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
300
cpp
google/quiche
qpack_instruction_encoder
quiche/quic/core/qpack/qpack_instruction_encoder.cc
quiche/quic/core/qpack/qpack_instruction_encoder_test.cc
#ifndef QUICHE_QUIC_CORE_QPACK_QPACK_INSTRUCTION_ENCODER_H_ #define QUICHE_QUIC_CORE_QPACK_QPACK_INSTRUCTION_ENCODER_H_ #include <cstdint> #include <string> #include "absl/strings/string_view.h" #include "quiche/quic/core/qpack/qpack_instructions.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { enum class HuffmanEncoding { kEnabled, kDisabled, }; class QUICHE_EXPORT QpackInstructionEncoder { public: explicit QpackInstructionEncoder(HuffmanEncoding huffman_encoding); QpackInstructionEncoder(const QpackInstructionEncoder&) = delete; QpackInstructionEncoder& operator=(const QpackInstructionEncoder&) = delete; void Encode(const QpackInstructionWithValues& instruction_with_values, std::string* output); private: enum class State { kOpcode, kStartField, kSbit, kVarintEncode, kStartString, kWriteString }; void DoOpcode(); void DoStartField(); void DoSBit(bool s_bit); void DoVarintEncode(uint64_t varint, uint64_t varint2, std::string* output); void DoStartString(absl::string_view name, absl::string_view value); void DoWriteString(absl::string_view name, absl::string_view value, std::string* output); const HuffmanEncoding huffman_encoding_; bool use_huffman_; size_t string_length_; uint8_t byte_; State state_; const QpackInstruction* instruction_; QpackInstructionFields::const_iterator field_; }; } #endif #include "quiche/quic/core/qpack/qpack_instruction_encoder.h" #include <limits> #include <string> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/http2/hpack/huffman/hpack_huffman_encoder.h" #include "quiche/http2/hpack/varint/hpack_varint_encoder.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { QpackInstructionEncoder::QpackInstructionEncoder( HuffmanEncoding huffman_encoding) : huffman_encoding_(huffman_encoding), use_huffman_(false), string_length_(0), byte_(0), state_(State::kOpcode), instruction_(nullptr) {} void QpackInstructionEncoder::Encode( const QpackInstructionWithValues& instruction_with_values, std::string* output) { QUICHE_DCHECK(instruction_with_values.instruction()); state_ = State::kOpcode; instruction_ = instruction_with_values.instruction(); field_ = instruction_->fields.begin(); QUICHE_DCHECK(field_ != instruction_->fields.end()); do { switch (state_) { case State::kOpcode: DoOpcode(); break; case State::kStartField: DoStartField(); break; case State::kSbit: DoSBit(instruction_with_values.s_bit()); break; case State::kVarintEncode: DoVarintEncode(instruction_with_values.varint(), instruction_with_values.varint2(), output); break; case State::kStartString: DoStartString(instruction_with_values.name(), instruction_with_values.value()); break; case State::kWriteString: DoWriteString(instruction_with_values.name(), instruction_with_values.value(), output); break; } } while (field_ != instruction_->fields.end()); QUICHE_DCHECK(state_ == State::kStartField); } void QpackInstructionEncoder::DoOpcode() { QUICHE_DCHECK_EQ(0u, byte_); byte_ = instruction_->opcode.value; state_ = State::kStartField; } void QpackInstructionEncoder::DoStartField() { switch (field_->type) { case QpackInstructionFieldType::kSbit: state_ = State::kSbit; return; case QpackInstructionFieldType::kVarint: case QpackInstructionFieldType::kVarint2: state_ = State::kVarintEncode; return; case QpackInstructionFieldType::kName: case QpackInstructionFieldType::kValue: state_ = State::kStartString; return; } } void QpackInstructionEncoder::DoSBit(bool s_bit) { QUICHE_DCHECK(field_->type == QpackInstructionFieldType::kSbit); if (s_bit) { QUICHE_DCHECK_EQ(0, byte_ & field_->param); byte_ |= field_->param; } ++field_; state_ = State::kStartField; } void QpackInstructionEncoder::DoVarintEncode(uint64_t varint, uint64_t varint2, std::string* output) { QUICHE_DCHECK(field_->type == QpackInstructionFieldType::kVarint || field_->type == QpackInstructionFieldType::kVarint2 || field_->type == QpackInstructionFieldType::kName || field_->type == QpackInstructionFieldType::kValue); uint64_t integer_to_encode; switch (field_->type) { case QpackInstructionFieldType::kVarint: integer_to_encode = varint; break; case QpackInstructionFieldType::kVarint2: integer_to_encode = varint2; break; default: integer_to_encode = string_length_; break; } http2::HpackVarintEncoder::Encode(byte_, field_->param, integer_to_encode, output); byte_ = 0; if (field_->type == QpackInstructionFieldType::kVarint || field_->type == QpackInstructionFieldType::kVarint2) { ++field_; state_ = State::kStartField; return; } state_ = State::kWriteString; } void QpackInstructionEncoder::DoStartString(absl::string_view name, absl::string_view value) { QUICHE_DCHECK(field_->type == QpackInstructionFieldType::kName || field_->type == QpackInstructionFieldType::kValue); absl::string_view string_to_write = (field_->type == QpackInstructionFieldType::kName) ? name : value; string_length_ = string_to_write.size(); if (huffman_encoding_ == HuffmanEncoding::kEnabled) { size_t encoded_size = http2::HuffmanSize(string_to_write); use_huffman_ = encoded_size < string_length_; if (use_huffman_) { QUICHE_DCHECK_EQ(0, byte_ & (1 << field_->param)); byte_ |= (1 << field_->param); string_length_ = encoded_size; } } state_ = State::kVarintEncode; } void QpackInstructionEncoder::DoWriteString(absl::string_view name, absl::string_view value, std::string* output) { QUICHE_DCHECK(field_->type == QpackInstructionFieldType::kName || field_->type == QpackInstructionFieldType::kValue); absl::string_view string_to_write = (field_->type == QpackInstructionFieldType::kName) ? name : value; if (use_huffman_) { http2::HuffmanEncodeFast(string_to_write, string_length_, output); } else { absl::StrAppend(output, string_to_write); } ++field_; state_ = State::kStartField; } }
#include "quiche/quic/core/qpack/qpack_instruction_encoder.h" #include <string> #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { class QpackInstructionWithValuesPeer { public: static QpackInstructionWithValues CreateQpackInstructionWithValues( const QpackInstruction* instruction) { QpackInstructionWithValues instruction_with_values; instruction_with_values.instruction_ = instruction; return instruction_with_values; } static void set_s_bit(QpackInstructionWithValues* instruction_with_values, bool s_bit) { instruction_with_values->s_bit_ = s_bit; } static void set_varint(QpackInstructionWithValues* instruction_with_values, uint64_t varint) { instruction_with_values->varint_ = varint; } static void set_varint2(QpackInstructionWithValues* instruction_with_values, uint64_t varint2) { instruction_with_values->varint2_ = varint2; } static void set_name(QpackInstructionWithValues* instruction_with_values, absl::string_view name) { instruction_with_values->name_ = name; } static void set_value(QpackInstructionWithValues* instruction_with_values, absl::string_view value) { instruction_with_values->value_ = value; } }; namespace { class QpackInstructionEncoderTest : public QuicTestWithParam<bool> { protected: QpackInstructionEncoderTest() : encoder_(HuffmanEncoding()), verified_position_(0) {} ~QpackInstructionEncoderTest() override = default; bool DisableHuffmanEncoding() { return GetParam(); } HuffmanEncoding HuffmanEncoding() { return DisableHuffmanEncoding() ? HuffmanEncoding::kDisabled : HuffmanEncoding::kEnabled; } void EncodeInstruction( const QpackInstructionWithValues& instruction_with_values) { encoder_.Encode(instruction_with_values, &output_); } bool EncodedSegmentMatches(absl::string_view hex_encoded_expected_substring) { auto recently_encoded = absl::string_view(output_).substr(verified_position_); std::string expected; EXPECT_TRUE( absl::HexStringToBytes(hex_encoded_expected_substring, &expected)); verified_position_ = output_.size(); return recently_encoded == expected; } private: QpackInstructionEncoder encoder_; std::string output_; std::string::size_type verified_position_; }; INSTANTIATE_TEST_SUITE_P(DisableHuffmanEncoding, QpackInstructionEncoderTest, testing::Values(false, true)); TEST_P(QpackInstructionEncoderTest, Varint) { const QpackInstruction instruction{QpackInstructionOpcode{0x00, 0x80}, {{QpackInstructionFieldType::kVarint, 7}}}; auto instruction_with_values = QpackInstructionWithValuesPeer::CreateQpackInstructionWithValues( &instruction); QpackInstructionWithValuesPeer::set_varint(&instruction_with_values, 5); EncodeInstruction(instruction_with_values); EXPECT_TRUE(EncodedSegmentMatches("05")); QpackInstructionWithValuesPeer::set_varint(&instruction_with_values, 127); EncodeInstruction(instruction_with_values); EXPECT_TRUE(EncodedSegmentMatches("7f00")); } TEST_P(QpackInstructionEncoderTest, SBitAndTwoVarint2) { const QpackInstruction instruction{ QpackInstructionOpcode{0x80, 0xc0}, {{QpackInstructionFieldType::kSbit, 0x20}, {QpackInstructionFieldType::kVarint, 5}, {QpackInstructionFieldType::kVarint2, 8}}}; auto instruction_with_values = QpackInstructionWithValuesPeer::CreateQpackInstructionWithValues( &instruction); QpackInstructionWithValuesPeer::set_s_bit(&instruction_with_values, true); QpackInstructionWithValuesPeer::set_varint(&instruction_with_values, 5); QpackInstructionWithValuesPeer::set_varint2(&instruction_with_values, 200); EncodeInstruction(instruction_with_values); EXPECT_TRUE(EncodedSegmentMatches("a5c8")); QpackInstructionWithValuesPeer::set_s_bit(&instruction_with_values, false); QpackInstructionWithValuesPeer::set_varint(&instruction_with_values, 31); QpackInstructionWithValuesPeer::set_varint2(&instruction_with_values, 356); EncodeInstruction(instruction_with_values); EXPECT_TRUE(EncodedSegmentMatches("9f00ff65")); } TEST_P(QpackInstructionEncoderTest, SBitAndVarintAndValue) { const QpackInstruction instruction{QpackInstructionOpcode{0xc0, 0xc0}, {{QpackInstructionFieldType::kSbit, 0x20}, {QpackInstructionFieldType::kVarint, 5}, {QpackInstructionFieldType::kValue, 7}}}; auto instruction_with_values = QpackInstructionWithValuesPeer::CreateQpackInstructionWithValues( &instruction); QpackInstructionWithValuesPeer::set_s_bit(&instruction_with_values, true); QpackInstructionWithValuesPeer::set_varint(&instruction_with_values, 100); QpackInstructionWithValuesPeer::set_value(&instruction_with_values, "foo"); EncodeInstruction(instruction_with_values); if (DisableHuffmanEncoding()) { EXPECT_TRUE(EncodedSegmentMatches("ff4503666f6f")); } else { EXPECT_TRUE(EncodedSegmentMatches("ff458294e7")); } QpackInstructionWithValuesPeer::set_s_bit(&instruction_with_values, false); QpackInstructionWithValuesPeer::set_varint(&instruction_with_values, 3); QpackInstructionWithValuesPeer::set_value(&instruction_with_values, "bar"); EncodeInstruction(instruction_with_values); EXPECT_TRUE(EncodedSegmentMatches("c303626172")); } TEST_P(QpackInstructionEncoderTest, Name) { const QpackInstruction instruction{QpackInstructionOpcode{0xe0, 0xe0}, {{QpackInstructionFieldType::kName, 4}}}; auto instruction_with_values = QpackInstructionWithValuesPeer::CreateQpackInstructionWithValues( &instruction); QpackInstructionWithValuesPeer::set_name(&instruction_with_values, ""); EncodeInstruction(instruction_with_values); EXPECT_TRUE(EncodedSegmentMatches("e0")); QpackInstructionWithValuesPeer::set_name(&instruction_with_values, "foo"); EncodeInstruction(instruction_with_values); if (DisableHuffmanEncoding()) { EXPECT_TRUE(EncodedSegmentMatches("e3666f6f")); } else { EXPECT_TRUE(EncodedSegmentMatches("f294e7")); } QpackInstructionWithValuesPeer::set_name(&instruction_with_values, "bar"); EncodeInstruction(instruction_with_values); EXPECT_TRUE(EncodedSegmentMatches("e3626172")); } TEST_P(QpackInstructionEncoderTest, Value) { const QpackInstruction instruction{QpackInstructionOpcode{0xf0, 0xf0}, {{QpackInstructionFieldType::kValue, 3}}}; auto instruction_with_values = QpackInstructionWithValuesPeer::CreateQpackInstructionWithValues( &instruction); QpackInstructionWithValuesPeer::set_value(&instruction_with_values, ""); EncodeInstruction(instruction_with_values); EXPECT_TRUE(EncodedSegmentMatches("f0")); QpackInstructionWithValuesPeer::set_value(&instruction_with_values, "foo"); EncodeInstruction(instruction_with_values); if (DisableHuffmanEncoding()) { EXPECT_TRUE(EncodedSegmentMatches("f3666f6f")); } else { EXPECT_TRUE(EncodedSegmentMatches("fa94e7")); } QpackInstructionWithValuesPeer::set_value(&instruction_with_values, "bar"); EncodeInstruction(instruction_with_values); EXPECT_TRUE(EncodedSegmentMatches("f3626172")); } TEST_P(QpackInstructionEncoderTest, SBitAndNameAndValue) { const QpackInstruction instruction{QpackInstructionOpcode{0xf0, 0xf0}, {{QpackInstructionFieldType::kSbit, 0x08}, {QpackInstructionFieldType::kName, 2}, {QpackInstructionFieldType::kValue, 7}}}; auto instruction_with_values = QpackInstructionWithValuesPeer::CreateQpackInstructionWithValues( &instruction); QpackInstructionWithValuesPeer::set_s_bit(&instruction_with_values, false); QpackInstructionWithValuesPeer::set_name(&instruction_with_values, ""); QpackInstructionWithValuesPeer::set_value(&instruction_with_values, ""); EncodeInstruction(instruction_with_values); EXPECT_TRUE(EncodedSegmentMatches("f000")); QpackInstructionWithValuesPeer::set_s_bit(&instruction_with_values, true); QpackInstructionWithValuesPeer::set_name(&instruction_with_values, "foo"); QpackInstructionWithValuesPeer::set_value(&instruction_with_values, "bar"); EncodeInstruction(instruction_with_values); if (DisableHuffmanEncoding()) { EXPECT_TRUE(EncodedSegmentMatches("fb00666f6f03626172")); } else { EXPECT_TRUE(EncodedSegmentMatches("fe94e703626172")); } } } } }
301
cpp
google/quiche
qpack_index_conversions
quiche/quic/core/qpack/qpack_index_conversions.cc
quiche/quic/core/qpack/qpack_index_conversions_test.cc
#ifndef QUICHE_QUIC_CORE_QPACK_QPACK_INDEX_CONVERSIONS_H_ #define QUICHE_QUIC_CORE_QPACK_QPACK_INDEX_CONVERSIONS_H_ #include <cstdint> #include "quiche/quic/platform/api/quic_export.h" namespace quic { QUICHE_EXPORT uint64_t QpackAbsoluteIndexToEncoderStreamRelativeIndex( uint64_t absolute_index, uint64_t inserted_entry_count); QUICHE_EXPORT uint64_t QpackAbsoluteIndexToRequestStreamRelativeIndex( uint64_t absolute_index, uint64_t base); QUICHE_EXPORT bool QpackEncoderStreamRelativeIndexToAbsoluteIndex( uint64_t relative_index, uint64_t inserted_entry_count, uint64_t* absolute_index); QUICHE_EXPORT bool QpackRequestStreamRelativeIndexToAbsoluteIndex( uint64_t relative_index, uint64_t base, uint64_t* absolute_index); QUICHE_EXPORT bool QpackPostBaseIndexToAbsoluteIndex(uint64_t post_base_index, uint64_t base, uint64_t* absolute_index); } #endif #include "quiche/quic/core/qpack/qpack_index_conversions.h" #include <limits> #include "quiche/quic/platform/api/quic_logging.h" namespace quic { uint64_t QpackAbsoluteIndexToEncoderStreamRelativeIndex( uint64_t absolute_index, uint64_t inserted_entry_count) { QUICHE_DCHECK_LT(absolute_index, inserted_entry_count); return inserted_entry_count - absolute_index - 1; } uint64_t QpackAbsoluteIndexToRequestStreamRelativeIndex(uint64_t absolute_index, uint64_t base) { QUICHE_DCHECK_LT(absolute_index, base); return base - absolute_index - 1; } bool QpackEncoderStreamRelativeIndexToAbsoluteIndex( uint64_t relative_index, uint64_t inserted_entry_count, uint64_t* absolute_index) { if (relative_index >= inserted_entry_count) { return false; } *absolute_index = inserted_entry_count - relative_index - 1; return true; } bool QpackRequestStreamRelativeIndexToAbsoluteIndex(uint64_t relative_index, uint64_t base, uint64_t* absolute_index) { if (relative_index >= base) { return false; } *absolute_index = base - relative_index - 1; return true; } bool QpackPostBaseIndexToAbsoluteIndex(uint64_t post_base_index, uint64_t base, uint64_t* absolute_index) { if (post_base_index >= std::numeric_limits<uint64_t>::max() - base) { return false; } *absolute_index = base + post_base_index; return true; } }
#include "quiche/quic/core/qpack/qpack_index_conversions.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { namespace { struct { uint64_t relative_index; uint64_t inserted_entry_count; uint64_t expected_absolute_index; } kEncoderStreamRelativeIndexTestData[] = {{0, 1, 0}, {0, 2, 1}, {1, 2, 0}, {0, 10, 9}, {5, 10, 4}, {9, 10, 0}}; TEST(QpackIndexConversions, EncoderStreamRelativeIndex) { for (const auto& test_data : kEncoderStreamRelativeIndexTestData) { uint64_t absolute_index = 42; EXPECT_TRUE(QpackEncoderStreamRelativeIndexToAbsoluteIndex( test_data.relative_index, test_data.inserted_entry_count, &absolute_index)); EXPECT_EQ(test_data.expected_absolute_index, absolute_index); EXPECT_EQ(test_data.relative_index, QpackAbsoluteIndexToEncoderStreamRelativeIndex( absolute_index, test_data.inserted_entry_count)); } } struct { uint64_t relative_index; uint64_t base; uint64_t expected_absolute_index; } kRequestStreamRelativeIndexTestData[] = {{0, 1, 0}, {0, 2, 1}, {1, 2, 0}, {0, 10, 9}, {5, 10, 4}, {9, 10, 0}}; TEST(QpackIndexConversions, RequestStreamRelativeIndex) { for (const auto& test_data : kRequestStreamRelativeIndexTestData) { uint64_t absolute_index = 42; EXPECT_TRUE(QpackRequestStreamRelativeIndexToAbsoluteIndex( test_data.relative_index, test_data.base, &absolute_index)); EXPECT_EQ(test_data.expected_absolute_index, absolute_index); EXPECT_EQ(test_data.relative_index, QpackAbsoluteIndexToRequestStreamRelativeIndex(absolute_index, test_data.base)); } } struct { uint64_t post_base_index; uint64_t base; uint64_t expected_absolute_index; } kPostBaseIndexTestData[] = {{0, 1, 1}, {1, 0, 1}, {2, 0, 2}, {1, 1, 2}, {0, 2, 2}, {1, 2, 3}}; TEST(QpackIndexConversions, PostBaseIndex) { for (const auto& test_data : kPostBaseIndexTestData) { uint64_t absolute_index = 42; EXPECT_TRUE(QpackPostBaseIndexToAbsoluteIndex( test_data.post_base_index, test_data.base, &absolute_index)); EXPECT_EQ(test_data.expected_absolute_index, absolute_index); } } TEST(QpackIndexConversions, EncoderStreamRelativeIndexUnderflow) { uint64_t absolute_index; EXPECT_FALSE(QpackEncoderStreamRelativeIndexToAbsoluteIndex( 10, 10, &absolute_index)); EXPECT_FALSE(QpackEncoderStreamRelativeIndexToAbsoluteIndex( 12, 10, &absolute_index)); } TEST(QpackIndexConversions, RequestStreamRelativeIndexUnderflow) { uint64_t absolute_index; EXPECT_FALSE(QpackRequestStreamRelativeIndexToAbsoluteIndex( 10, 10, &absolute_index)); EXPECT_FALSE(QpackRequestStreamRelativeIndexToAbsoluteIndex( 12, 10, &absolute_index)); } TEST(QpackIndexConversions, QpackPostBaseIndexToAbsoluteIndexOverflow) { uint64_t absolute_index; EXPECT_FALSE(QpackPostBaseIndexToAbsoluteIndex( 20, std::numeric_limits<uint64_t>::max() - 10, &absolute_index)); } } } }
302
cpp
google/quiche
qpack_encoder_stream_sender
quiche/quic/core/qpack/qpack_encoder_stream_sender.cc
quiche/quic/core/qpack/qpack_encoder_stream_sender_test.cc
#ifndef QUICHE_QUIC_CORE_QPACK_QPACK_ENCODER_STREAM_SENDER_H_ #define QUICHE_QUIC_CORE_QPACK_QPACK_ENCODER_STREAM_SENDER_H_ #include <cstdint> #include "absl/strings/string_view.h" #include "quiche/quic/core/qpack/qpack_instruction_encoder.h" #include "quiche/quic/core/qpack/qpack_stream_sender_delegate.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT QpackEncoderStreamSender { public: QpackEncoderStreamSender(HuffmanEncoding huffman_encoding); QpackEncoderStreamSender(const QpackEncoderStreamSender&) = delete; QpackEncoderStreamSender& operator=(const QpackEncoderStreamSender&) = delete; void SendInsertWithNameReference(bool is_static, uint64_t name_index, absl::string_view value); void SendInsertWithoutNameReference(absl::string_view name, absl::string_view value); void SendDuplicate(uint64_t index); void SendSetDynamicTableCapacity(uint64_t capacity); QuicByteCount BufferedByteCount() const { return buffer_.size(); } bool CanWrite() const; void Flush(); void set_qpack_stream_sender_delegate(QpackStreamSenderDelegate* delegate) { delegate_ = delegate; } private: QpackStreamSenderDelegate* delegate_; QpackInstructionEncoder instruction_encoder_; std::string buffer_; }; } #endif #include "quiche/quic/core/qpack/qpack_encoder_stream_sender.h" #include <cstddef> #include <limits> #include <string> #include "absl/strings/string_view.h" #include "quiche/quic/core/qpack/qpack_instructions.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { namespace { constexpr uint64_t kMaxBytesBufferedByStream = 64 * 1024; } QpackEncoderStreamSender::QpackEncoderStreamSender( HuffmanEncoding huffman_encoding) : delegate_(nullptr), instruction_encoder_(huffman_encoding) {} void QpackEncoderStreamSender::SendInsertWithNameReference( bool is_static, uint64_t name_index, absl::string_view value) { instruction_encoder_.Encode( QpackInstructionWithValues::InsertWithNameReference(is_static, name_index, value), &buffer_); } void QpackEncoderStreamSender::SendInsertWithoutNameReference( absl::string_view name, absl::string_view value) { instruction_encoder_.Encode( QpackInstructionWithValues::InsertWithoutNameReference(name, value), &buffer_); } void QpackEncoderStreamSender::SendDuplicate(uint64_t index) { instruction_encoder_.Encode(QpackInstructionWithValues::Duplicate(index), &buffer_); } void QpackEncoderStreamSender::SendSetDynamicTableCapacity(uint64_t capacity) { instruction_encoder_.Encode( QpackInstructionWithValues::SetDynamicTableCapacity(capacity), &buffer_); } bool QpackEncoderStreamSender::CanWrite() const { return delegate_ && delegate_->NumBytesBuffered() + buffer_.size() <= kMaxBytesBufferedByStream; } void QpackEncoderStreamSender::Flush() { if (buffer_.empty()) { return; } delegate_->WriteStreamData(buffer_); buffer_.clear(); } }
#include "quiche/quic/core/qpack/qpack_encoder_stream_sender.h" #include <string> #include "absl/strings/escaping.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/qpack/qpack_test_utils.h" using ::testing::Eq; using ::testing::StrictMock; namespace quic { namespace test { namespace { class QpackEncoderStreamSenderTest : public QuicTestWithParam<bool> { protected: QpackEncoderStreamSenderTest() : stream_(HuffmanEncoding()) { stream_.set_qpack_stream_sender_delegate(&delegate_); } ~QpackEncoderStreamSenderTest() override = default; bool DisableHuffmanEncoding() { return GetParam(); } HuffmanEncoding HuffmanEncoding() { return DisableHuffmanEncoding() ? HuffmanEncoding::kDisabled : HuffmanEncoding::kEnabled; } StrictMock<MockQpackStreamSenderDelegate> delegate_; QpackEncoderStreamSender stream_; }; INSTANTIATE_TEST_SUITE_P(DisableHuffmanEncoding, QpackEncoderStreamSenderTest, testing::Values(false, true)); TEST_P(QpackEncoderStreamSenderTest, InsertWithNameReference) { EXPECT_EQ(0u, stream_.BufferedByteCount()); std::string expected_encoded_data; ASSERT_TRUE(absl::HexStringToBytes("c500", &expected_encoded_data)); EXPECT_CALL(delegate_, WriteStreamData(Eq(expected_encoded_data))); stream_.SendInsertWithNameReference(true, 5, ""); EXPECT_EQ(expected_encoded_data.size(), stream_.BufferedByteCount()); stream_.Flush(); if (DisableHuffmanEncoding()) { ASSERT_TRUE(absl::HexStringToBytes("c203666f6f", &expected_encoded_data)); } else { ASSERT_TRUE(absl::HexStringToBytes("c28294e7", &expected_encoded_data)); } EXPECT_CALL(delegate_, WriteStreamData(Eq(expected_encoded_data))); stream_.SendInsertWithNameReference(true, 2, "foo"); EXPECT_EQ(expected_encoded_data.size(), stream_.BufferedByteCount()); stream_.Flush(); ASSERT_TRUE(absl::HexStringToBytes("bf4a03626172", &expected_encoded_data)); EXPECT_CALL(delegate_, WriteStreamData(Eq(expected_encoded_data))); stream_.SendInsertWithNameReference(false, 137, "bar"); EXPECT_EQ(expected_encoded_data.size(), stream_.BufferedByteCount()); stream_.Flush(); ASSERT_TRUE(absl::HexStringToBytes( "aa7f005a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a" "5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a" "5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a" "5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a", &expected_encoded_data)); EXPECT_CALL(delegate_, WriteStreamData(Eq(expected_encoded_data))); stream_.SendInsertWithNameReference(false, 42, std::string(127, 'Z')); EXPECT_EQ(expected_encoded_data.size(), stream_.BufferedByteCount()); stream_.Flush(); } TEST_P(QpackEncoderStreamSenderTest, InsertWithoutNameReference) { EXPECT_EQ(0u, stream_.BufferedByteCount()); std::string expected_encoded_data; ASSERT_TRUE(absl::HexStringToBytes("4000", &expected_encoded_data)); EXPECT_CALL(delegate_, WriteStreamData(Eq(expected_encoded_data))); stream_.SendInsertWithoutNameReference("", ""); EXPECT_EQ(expected_encoded_data.size(), stream_.BufferedByteCount()); stream_.Flush(); if (DisableHuffmanEncoding()) { ASSERT_TRUE( absl::HexStringToBytes("43666f6f03666f6f", &expected_encoded_data)); } else { ASSERT_TRUE(absl::HexStringToBytes("6294e78294e7", &expected_encoded_data)); } EXPECT_CALL(delegate_, WriteStreamData(Eq(expected_encoded_data))); stream_.SendInsertWithoutNameReference("foo", "foo"); EXPECT_EQ(expected_encoded_data.size(), stream_.BufferedByteCount()); stream_.Flush(); ASSERT_TRUE( absl::HexStringToBytes("4362617203626172", &expected_encoded_data)); EXPECT_CALL(delegate_, WriteStreamData(Eq(expected_encoded_data))); stream_.SendInsertWithoutNameReference("bar", "bar"); EXPECT_EQ(expected_encoded_data.size(), stream_.BufferedByteCount()); stream_.Flush(); ASSERT_TRUE(absl::HexStringToBytes( "5f005a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a7f" "005a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a" "5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a" "5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a" "5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a", &expected_encoded_data)); EXPECT_CALL(delegate_, WriteStreamData(Eq(expected_encoded_data))); stream_.SendInsertWithoutNameReference(std::string(31, 'Z'), std::string(127, 'Z')); EXPECT_EQ(expected_encoded_data.size(), stream_.BufferedByteCount()); stream_.Flush(); } TEST_P(QpackEncoderStreamSenderTest, Duplicate) { EXPECT_EQ(0u, stream_.BufferedByteCount()); std::string expected_encoded_data; ASSERT_TRUE(absl::HexStringToBytes("11", &expected_encoded_data)); EXPECT_CALL(delegate_, WriteStreamData(Eq(expected_encoded_data))); stream_.SendDuplicate(17); EXPECT_EQ(expected_encoded_data.size(), stream_.BufferedByteCount()); stream_.Flush(); ASSERT_TRUE(absl::HexStringToBytes("1fd503", &expected_encoded_data)); EXPECT_CALL(delegate_, WriteStreamData(Eq(expected_encoded_data))); stream_.SendDuplicate(500); EXPECT_EQ(expected_encoded_data.size(), stream_.BufferedByteCount()); stream_.Flush(); } TEST_P(QpackEncoderStreamSenderTest, SetDynamicTableCapacity) { EXPECT_EQ(0u, stream_.BufferedByteCount()); std::string expected_encoded_data; ASSERT_TRUE(absl::HexStringToBytes("31", &expected_encoded_data)); EXPECT_CALL(delegate_, WriteStreamData(Eq(expected_encoded_data))); stream_.SendSetDynamicTableCapacity(17); EXPECT_EQ(expected_encoded_data.size(), stream_.BufferedByteCount()); stream_.Flush(); EXPECT_EQ(0u, stream_.BufferedByteCount()); ASSERT_TRUE(absl::HexStringToBytes("3fd503", &expected_encoded_data)); EXPECT_CALL(delegate_, WriteStreamData(Eq(expected_encoded_data))); stream_.SendSetDynamicTableCapacity(500); EXPECT_EQ(expected_encoded_data.size(), stream_.BufferedByteCount()); stream_.Flush(); EXPECT_EQ(0u, stream_.BufferedByteCount()); } TEST_P(QpackEncoderStreamSenderTest, Coalesce) { stream_.SendInsertWithNameReference(true, 5, ""); stream_.SendInsertWithNameReference(true, 2, "foo"); stream_.SendInsertWithoutNameReference("foo", "foo"); stream_.SendDuplicate(17); std::string expected_encoded_data; if (DisableHuffmanEncoding()) { ASSERT_TRUE(absl::HexStringToBytes( "c500" "c203666f6f" "43666f6f03666f6f" "11", &expected_encoded_data)); } else { ASSERT_TRUE(absl::HexStringToBytes( "c500" "c28294e7" "6294e78294e7" "11", &expected_encoded_data)); } EXPECT_CALL(delegate_, WriteStreamData(Eq(expected_encoded_data))); EXPECT_EQ(expected_encoded_data.size(), stream_.BufferedByteCount()); stream_.Flush(); EXPECT_EQ(0u, stream_.BufferedByteCount()); } TEST_P(QpackEncoderStreamSenderTest, FlushEmpty) { EXPECT_EQ(0u, stream_.BufferedByteCount()); stream_.Flush(); EXPECT_EQ(0u, stream_.BufferedByteCount()); } } } }
303
cpp
google/quiche
qpack_decoder_stream_sender
quiche/quic/core/qpack/qpack_decoder_stream_sender.cc
quiche/quic/core/qpack/qpack_decoder_stream_sender_test.cc
#ifndef QUICHE_QUIC_CORE_QPACK_QPACK_DECODER_STREAM_SENDER_H_ #define QUICHE_QUIC_CORE_QPACK_QPACK_DECODER_STREAM_SENDER_H_ #include <cstdint> #include "quiche/quic/core/qpack/qpack_instruction_encoder.h" #include "quiche/quic/core/qpack/qpack_stream_sender_delegate.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT QpackDecoderStreamSender { public: QpackDecoderStreamSender(); QpackDecoderStreamSender(const QpackDecoderStreamSender&) = delete; QpackDecoderStreamSender& operator=(const QpackDecoderStreamSender&) = delete; void SendInsertCountIncrement(uint64_t increment); void SendHeaderAcknowledgement(QuicStreamId stream_id); void SendStreamCancellation(QuicStreamId stream_id); void Flush(); void set_qpack_stream_sender_delegate(QpackStreamSenderDelegate* delegate) { delegate_ = delegate; } private: QpackStreamSenderDelegate* delegate_; QpackInstructionEncoder instruction_encoder_; std::string buffer_; }; } #endif #include "quiche/quic/core/qpack/qpack_decoder_stream_sender.h" #include <cstddef> #include <limits> #include <string> #include <utility> #include "absl/strings/string_view.h" #include "quiche/quic/core/qpack/qpack_instructions.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { QpackDecoderStreamSender::QpackDecoderStreamSender() : delegate_(nullptr), instruction_encoder_(HuffmanEncoding::kEnabled) {} void QpackDecoderStreamSender::SendInsertCountIncrement(uint64_t increment) { instruction_encoder_.Encode( QpackInstructionWithValues::InsertCountIncrement(increment), &buffer_); } void QpackDecoderStreamSender::SendHeaderAcknowledgement( QuicStreamId stream_id) { instruction_encoder_.Encode( QpackInstructionWithValues::HeaderAcknowledgement(stream_id), &buffer_); } void QpackDecoderStreamSender::SendStreamCancellation(QuicStreamId stream_id) { instruction_encoder_.Encode( QpackInstructionWithValues::StreamCancellation(stream_id), &buffer_); } void QpackDecoderStreamSender::Flush() { if (buffer_.empty() || delegate_ == nullptr) { return; } if (GetQuicRestartFlag(quic_opport_bundle_qpack_decoder_data5)) { QUIC_RESTART_FLAG_COUNT_N(quic_opport_bundle_qpack_decoder_data5, 3, 4); std::string copy; std::swap(copy, buffer_); delegate_->WriteStreamData(copy); return; } delegate_->WriteStreamData(buffer_); buffer_.clear(); } }
#include "quiche/quic/core/qpack/qpack_decoder_stream_sender.h" #include <string> #include "absl/strings/escaping.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/qpack/qpack_test_utils.h" using ::testing::Eq; using ::testing::StrictMock; namespace quic { namespace test { namespace { class QpackDecoderStreamSenderTest : public QuicTest { protected: QpackDecoderStreamSenderTest() { stream_.set_qpack_stream_sender_delegate(&delegate_); } ~QpackDecoderStreamSenderTest() override = default; StrictMock<MockQpackStreamSenderDelegate> delegate_; QpackDecoderStreamSender stream_; }; TEST_F(QpackDecoderStreamSenderTest, InsertCountIncrement) { std::string stream_data; ASSERT_TRUE(absl::HexStringToBytes("00", &stream_data)); EXPECT_CALL(delegate_, WriteStreamData(Eq(stream_data))); stream_.SendInsertCountIncrement(0); stream_.Flush(); ASSERT_TRUE(absl::HexStringToBytes("0a", &stream_data)); EXPECT_CALL(delegate_, WriteStreamData(Eq(stream_data))); stream_.SendInsertCountIncrement(10); stream_.Flush(); ASSERT_TRUE(absl::HexStringToBytes("3f00", &stream_data)); EXPECT_CALL(delegate_, WriteStreamData(Eq(stream_data))); stream_.SendInsertCountIncrement(63); stream_.Flush(); ASSERT_TRUE(absl::HexStringToBytes("3f8901", &stream_data)); EXPECT_CALL(delegate_, WriteStreamData(Eq(stream_data))); stream_.SendInsertCountIncrement(200); stream_.Flush(); } TEST_F(QpackDecoderStreamSenderTest, HeaderAcknowledgement) { std::string stream_data; ASSERT_TRUE(absl::HexStringToBytes("80", &stream_data)); EXPECT_CALL(delegate_, WriteStreamData(Eq(stream_data))); stream_.SendHeaderAcknowledgement(0); stream_.Flush(); ASSERT_TRUE(absl::HexStringToBytes("a5", &stream_data)); EXPECT_CALL(delegate_, WriteStreamData(Eq(stream_data))); stream_.SendHeaderAcknowledgement(37); stream_.Flush(); ASSERT_TRUE(absl::HexStringToBytes("ff00", &stream_data)); EXPECT_CALL(delegate_, WriteStreamData(Eq(stream_data))); stream_.SendHeaderAcknowledgement(127); stream_.Flush(); ASSERT_TRUE(absl::HexStringToBytes("fff802", &stream_data)); EXPECT_CALL(delegate_, WriteStreamData(Eq(stream_data))); stream_.SendHeaderAcknowledgement(503); stream_.Flush(); } TEST_F(QpackDecoderStreamSenderTest, StreamCancellation) { std::string stream_data; ASSERT_TRUE(absl::HexStringToBytes("40", &stream_data)); EXPECT_CALL(delegate_, WriteStreamData(Eq(stream_data))); stream_.SendStreamCancellation(0); stream_.Flush(); ASSERT_TRUE(absl::HexStringToBytes("53", &stream_data)); EXPECT_CALL(delegate_, WriteStreamData(Eq(stream_data))); stream_.SendStreamCancellation(19); stream_.Flush(); ASSERT_TRUE(absl::HexStringToBytes("7f00", &stream_data)); EXPECT_CALL(delegate_, WriteStreamData(Eq(stream_data))); stream_.SendStreamCancellation(63); stream_.Flush(); ASSERT_TRUE(absl::HexStringToBytes("7f2f", &stream_data)); EXPECT_CALL(delegate_, WriteStreamData(Eq(stream_data))); stream_.SendStreamCancellation(110); stream_.Flush(); } TEST_F(QpackDecoderStreamSenderTest, Coalesce) { std::string stream_data; stream_.SendInsertCountIncrement(10); stream_.SendHeaderAcknowledgement(37); stream_.SendStreamCancellation(0); ASSERT_TRUE(absl::HexStringToBytes("0aa540", &stream_data)); EXPECT_CALL(delegate_, WriteStreamData(Eq(stream_data))); stream_.Flush(); stream_.SendInsertCountIncrement(63); stream_.SendStreamCancellation(110); ASSERT_TRUE(absl::HexStringToBytes("3f007f2f", &stream_data)); EXPECT_CALL(delegate_, WriteStreamData(Eq(stream_data))); stream_.Flush(); } } } }
304
cpp
google/quiche
qpack_static_table
quiche/quic/core/qpack/qpack_static_table.cc
quiche/quic/core/qpack/qpack_static_table_test.cc
#ifndef QUICHE_QUIC_CORE_QPACK_QPACK_STATIC_TABLE_H_ #define QUICHE_QUIC_CORE_QPACK_QPACK_STATIC_TABLE_H_ #include <vector> #include "quiche/quic/platform/api/quic_export.h" #include "quiche/spdy/core/hpack/hpack_constants.h" #include "quiche/spdy/core/hpack/hpack_static_table.h" namespace quic { using QpackStaticEntry = spdy::HpackStaticEntry; using QpackStaticTable = spdy::HpackStaticTable; QUICHE_EXPORT const std::vector<QpackStaticEntry>& QpackStaticTableVector(); QUICHE_EXPORT const QpackStaticTable& ObtainQpackStaticTable(); } #endif #include "quiche/quic/core/qpack/qpack_static_table.h" #include <vector> #include "absl/base/macros.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { #define STATIC_ENTRY(name, value) \ { name, ABSL_ARRAYSIZE(name) - 1, value, ABSL_ARRAYSIZE(value) - 1 } const std::vector<QpackStaticEntry>& QpackStaticTableVector() { static const auto* kQpackStaticTable = new std::vector<QpackStaticEntry>{ STATIC_ENTRY(":authority", ""), STATIC_ENTRY(":path", "/"), STATIC_ENTRY("age", "0"), STATIC_ENTRY("content-disposition", ""), STATIC_ENTRY("content-length", "0"), STATIC_ENTRY("cookie", ""), STATIC_ENTRY("date", ""), STATIC_ENTRY("etag", ""), STATIC_ENTRY("if-modified-since", ""), STATIC_ENTRY("if-none-match", ""), STATIC_ENTRY("last-modified", ""), STATIC_ENTRY("link", ""), STATIC_ENTRY("location", ""), STATIC_ENTRY("referer", ""), STATIC_ENTRY("set-cookie", ""), STATIC_ENTRY(":method", "CONNECT"), STATIC_ENTRY(":method", "DELETE"), STATIC_ENTRY(":method", "GET"), STATIC_ENTRY(":method", "HEAD"), STATIC_ENTRY(":method", "OPTIONS"), STATIC_ENTRY(":method", "POST"), STATIC_ENTRY(":method", "PUT"), STATIC_ENTRY(":scheme", "http"), STATIC_ENTRY(":scheme", "https"), STATIC_ENTRY(":status", "103"), STATIC_ENTRY(":status", "200"), STATIC_ENTRY(":status", "304"), STATIC_ENTRY(":status", "404"), STATIC_ENTRY(":status", "503"), STATIC_ENTRY("accept", "*/*"), STATIC_ENTRY("accept", "application/dns-message"), STATIC_ENTRY("accept-encoding", "gzip, deflate, br"), STATIC_ENTRY("accept-ranges", "bytes"), STATIC_ENTRY("access-control-allow-headers", "cache-control"), STATIC_ENTRY("access-control-allow-headers", "content-type"), STATIC_ENTRY("access-control-allow-origin", "*"), STATIC_ENTRY("cache-control", "max-age=0"), STATIC_ENTRY("cache-control", "max-age=2592000"), STATIC_ENTRY("cache-control", "max-age=604800"), STATIC_ENTRY("cache-control", "no-cache"), STATIC_ENTRY("cache-control", "no-store"), STATIC_ENTRY("cache-control", "public, max-age=31536000"), STATIC_ENTRY("content-encoding", "br"), STATIC_ENTRY("content-encoding", "gzip"), STATIC_ENTRY("content-type", "application/dns-message"), STATIC_ENTRY("content-type", "application/javascript"), STATIC_ENTRY("content-type", "application/json"), STATIC_ENTRY("content-type", "application/x-www-form-urlencoded"), STATIC_ENTRY("content-type", "image/gif"), STATIC_ENTRY("content-type", "image/jpeg"), STATIC_ENTRY("content-type", "image/png"), STATIC_ENTRY("content-type", "text/css"), STATIC_ENTRY("content-type", "text/html; charset=utf-8"), STATIC_ENTRY("content-type", "text/plain"), STATIC_ENTRY("content-type", "text/plain;charset=utf-8"), STATIC_ENTRY("range", "bytes=0-"), STATIC_ENTRY("strict-transport-security", "max-age=31536000"), STATIC_ENTRY("strict-transport-security", "max-age=31536000; includesubdomains"), STATIC_ENTRY("strict-transport-security", "max-age=31536000; includesubdomains; preload"), STATIC_ENTRY("vary", "accept-encoding"), STATIC_ENTRY("vary", "origin"), STATIC_ENTRY("x-content-type-options", "nosniff"), STATIC_ENTRY("x-xss-protection", "1; mode=block"), STATIC_ENTRY(":status", "100"), STATIC_ENTRY(":status", "204"), STATIC_ENTRY(":status", "206"), STATIC_ENTRY(":status", "302"), STATIC_ENTRY(":status", "400"), STATIC_ENTRY(":status", "403"), STATIC_ENTRY(":status", "421"), STATIC_ENTRY(":status", "425"), STATIC_ENTRY(":status", "500"), STATIC_ENTRY("accept-language", ""), STATIC_ENTRY("access-control-allow-credentials", "FALSE"), STATIC_ENTRY("access-control-allow-credentials", "TRUE"), STATIC_ENTRY("access-control-allow-headers", "*"), STATIC_ENTRY("access-control-allow-methods", "get"), STATIC_ENTRY("access-control-allow-methods", "get, post, options"), STATIC_ENTRY("access-control-allow-methods", "options"), STATIC_ENTRY("access-control-expose-headers", "content-length"), STATIC_ENTRY("access-control-request-headers", "content-type"), STATIC_ENTRY("access-control-request-method", "get"), STATIC_ENTRY("access-control-request-method", "post"), STATIC_ENTRY("alt-svc", "clear"), STATIC_ENTRY("authorization", ""), STATIC_ENTRY( "content-security-policy", "script-src 'none'; object-src 'none'; base-uri 'none'"), STATIC_ENTRY("early-data", "1"), STATIC_ENTRY("expect-ct", ""), STATIC_ENTRY("forwarded", ""), STATIC_ENTRY("if-range", ""), STATIC_ENTRY("origin", ""), STATIC_ENTRY("purpose", "prefetch"), STATIC_ENTRY("server", ""), STATIC_ENTRY("timing-allow-origin", "*"), STATIC_ENTRY("upgrade-insecure-requests", "1"), STATIC_ENTRY("user-agent", ""), STATIC_ENTRY("x-forwarded-for", ""), STATIC_ENTRY("x-frame-options", "deny"), STATIC_ENTRY("x-frame-options", "sameorigin"), }; return *kQpackStaticTable; } #undef STATIC_ENTRY const QpackStaticTable& ObtainQpackStaticTable() { static const QpackStaticTable* const shared_static_table = []() { auto* table = new QpackStaticTable(); table->Initialize(QpackStaticTableVector().data(), QpackStaticTableVector().size()); QUICHE_CHECK(table->IsInitialized()); return table; }(); return *shared_static_table; } }
#include "quiche/quic/core/qpack/qpack_static_table.h" #include <set> #include "absl/base/macros.h" #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { namespace { TEST(QpackStaticTableTest, Initialize) { QpackStaticTable table; EXPECT_FALSE(table.IsInitialized()); table.Initialize(QpackStaticTableVector().data(), QpackStaticTableVector().size()); EXPECT_TRUE(table.IsInitialized()); const auto& static_entries = table.GetStaticEntries(); EXPECT_EQ(QpackStaticTableVector().size(), static_entries.size()); const auto& static_index = table.GetStaticIndex(); EXPECT_EQ(QpackStaticTableVector().size(), static_index.size()); const auto& static_name_index = table.GetStaticNameIndex(); std::set<absl::string_view> names; for (const auto& entry : static_entries) { names.insert(entry.name()); } EXPECT_EQ(names.size(), static_name_index.size()); } TEST(QpackStaticTableTest, IsSingleton) { const QpackStaticTable* static_table_one = &ObtainQpackStaticTable(); const QpackStaticTable* static_table_two = &ObtainQpackStaticTable(); EXPECT_EQ(static_table_one, static_table_two); } } } }
305
cpp
google/quiche
http_decoder
quiche/quic/core/http/http_decoder.cc
quiche/quic/core/http/http_decoder_test.cc
#ifndef QUICHE_QUIC_CORE_HTTP_HTTP_DECODER_H_ #define QUICHE_QUIC_CORE_HTTP_HTTP_DECODER_H_ #include <cstdint> #include "absl/strings/string_view.h" #include "quiche/quic/core/http/http_frames.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { namespace test { class HttpDecoderPeer; } class QuicDataReader; class QUICHE_EXPORT HttpDecoder { public: class QUICHE_EXPORT Visitor { public: virtual ~Visitor() {} virtual void OnError(HttpDecoder* decoder) = 0; virtual bool OnMaxPushIdFrame() = 0; virtual bool OnGoAwayFrame(const GoAwayFrame& frame) = 0; virtual bool OnSettingsFrameStart(QuicByteCount header_length) = 0; virtual bool OnSettingsFrame(const SettingsFrame& frame) = 0; virtual bool OnDataFrameStart(QuicByteCount header_length, QuicByteCount payload_length) = 0; virtual bool OnDataFramePayload(absl::string_view payload) = 0; virtual bool OnDataFrameEnd() = 0; virtual bool OnHeadersFrameStart(QuicByteCount header_length, QuicByteCount payload_length) = 0; virtual bool OnHeadersFramePayload(absl::string_view payload) = 0; virtual bool OnHeadersFrameEnd() = 0; virtual bool OnPriorityUpdateFrameStart(QuicByteCount header_length) = 0; virtual bool OnPriorityUpdateFrame(const PriorityUpdateFrame& frame) = 0; virtual bool OnAcceptChFrameStart(QuicByteCount header_length) = 0; virtual bool OnAcceptChFrame(const AcceptChFrame& frame) = 0; virtual void OnWebTransportStreamFrameType( QuicByteCount header_length, WebTransportSessionId session_id) = 0; virtual bool OnMetadataFrameStart(QuicByteCount header_length, QuicByteCount payload_length) = 0; virtual bool OnMetadataFramePayload(absl::string_view payload) = 0; virtual bool OnMetadataFrameEnd() = 0; virtual bool OnUnknownFrameStart(uint64_t frame_type, QuicByteCount header_length, QuicByteCount payload_length) = 0; virtual bool OnUnknownFramePayload(absl::string_view payload) = 0; virtual bool OnUnknownFrameEnd() = 0; }; explicit HttpDecoder(Visitor* visitor); ~HttpDecoder(); QuicByteCount ProcessInput(const char* data, QuicByteCount len); static bool DecodeSettings(const char* data, QuicByteCount len, SettingsFrame* frame); QuicErrorCode error() const { return error_; } const std::string& error_detail() const { return error_detail_; } bool AtFrameBoundary() const { return state_ == STATE_READING_FRAME_TYPE; } void EnableWebTransportStreamParsing() { allow_web_transport_stream_ = true; } std::string DebugString() const; private: friend test::HttpDecoderPeer; enum HttpDecoderState { STATE_READING_FRAME_LENGTH, STATE_READING_FRAME_TYPE, STATE_BUFFER_OR_PARSE_PAYLOAD, STATE_READING_FRAME_PAYLOAD, STATE_FINISH_PARSING, STATE_PARSING_NO_LONGER_POSSIBLE, STATE_ERROR }; bool ReadFrameType(QuicDataReader* reader); bool ReadFrameLength(QuicDataReader* reader); bool IsFrameBuffered(); bool ReadFramePayload(QuicDataReader* reader); bool FinishParsing(); void ResetForNextFrame(); bool HandleUnknownFramePayload(QuicDataReader* reader); bool BufferOrParsePayload(QuicDataReader* reader); bool ParseEntirePayload(QuicDataReader* reader); void BufferFrameLength(QuicDataReader* reader); void BufferFrameType(QuicDataReader* reader); void RaiseError(QuicErrorCode error, std::string error_detail); bool ParseSettingsFrame(QuicDataReader* reader, SettingsFrame* frame); bool ParsePriorityUpdateFrame(QuicDataReader* reader, PriorityUpdateFrame* frame); bool ParseAcceptChFrame(QuicDataReader* reader, AcceptChFrame* frame); QuicByteCount MaxFrameLength(uint64_t frame_type); Visitor* const visitor_; bool allow_web_transport_stream_; HttpDecoderState state_; uint64_t current_frame_type_; QuicByteCount current_length_field_length_; QuicByteCount remaining_length_field_length_; QuicByteCount current_frame_length_; QuicByteCount remaining_frame_length_; QuicByteCount current_type_field_length_; QuicByteCount remaining_type_field_length_; QuicErrorCode error_; std::string error_detail_; std::string buffer_; std::array<char, sizeof(uint64_t)> length_buffer_; std::array<char, sizeof(uint64_t)> type_buffer_; }; } #endif #include "quiche/quic/core/http/http_decoder.h" #include <algorithm> #include <cstdint> #include <string> #include <utility> #include "absl/base/attributes.h" #include "absl/strings/string_view.h" #include "quiche/http2/http2_constants.h" #include "quiche/quic/core/http/http_frames.h" #include "quiche/quic/core/quic_data_reader.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { namespace { constexpr QuicByteCount kPayloadLengthLimit = 1024 * 1024; } HttpDecoder::HttpDecoder(Visitor* visitor) : visitor_(visitor), allow_web_transport_stream_(false), state_(STATE_READING_FRAME_TYPE), current_frame_type_(0), current_length_field_length_(0), remaining_length_field_length_(0), current_frame_length_(0), remaining_frame_length_(0), current_type_field_length_(0), remaining_type_field_length_(0), error_(QUIC_NO_ERROR), error_detail_("") { QUICHE_DCHECK(visitor_); } HttpDecoder::~HttpDecoder() {} bool HttpDecoder::DecodeSettings(const char* data, QuicByteCount len, SettingsFrame* frame) { QuicDataReader reader(data, len); uint64_t frame_type; if (!reader.ReadVarInt62(&frame_type)) { QUIC_DLOG(ERROR) << "Unable to read frame type."; return false; } if (frame_type != static_cast<uint64_t>(HttpFrameType::SETTINGS)) { QUIC_DLOG(ERROR) << "Invalid frame type " << frame_type; return false; } absl::string_view frame_contents; if (!reader.ReadStringPieceVarInt62(&frame_contents)) { QUIC_DLOG(ERROR) << "Failed to read SETTINGS frame contents"; return false; } QuicDataReader frame_reader(frame_contents); while (!frame_reader.IsDoneReading()) { uint64_t id; if (!frame_reader.ReadVarInt62(&id)) { QUIC_DLOG(ERROR) << "Unable to read setting identifier."; return false; } uint64_t content; if (!frame_reader.ReadVarInt62(&content)) { QUIC_DLOG(ERROR) << "Unable to read setting value."; return false; } auto result = frame->values.insert({id, content}); if (!result.second) { QUIC_DLOG(ERROR) << "Duplicate setting identifier."; return false; } } return true; } QuicByteCount HttpDecoder::ProcessInput(const char* data, QuicByteCount len) { QUICHE_DCHECK_EQ(QUIC_NO_ERROR, error_); QUICHE_DCHECK_NE(STATE_ERROR, state_); QuicDataReader reader(data, len); bool continue_processing = true; while (continue_processing && (reader.BytesRemaining() != 0 || state_ == STATE_BUFFER_OR_PARSE_PAYLOAD || state_ == STATE_FINISH_PARSING)) { QUICHE_DCHECK_EQ(QUIC_NO_ERROR, error_); QUICHE_DCHECK_NE(STATE_ERROR, state_); switch (state_) { case STATE_READING_FRAME_TYPE: continue_processing = ReadFrameType(&reader); break; case STATE_READING_FRAME_LENGTH: continue_processing = ReadFrameLength(&reader); break; case STATE_BUFFER_OR_PARSE_PAYLOAD: continue_processing = BufferOrParsePayload(&reader); break; case STATE_READING_FRAME_PAYLOAD: continue_processing = ReadFramePayload(&reader); break; case STATE_FINISH_PARSING: continue_processing = FinishParsing(); break; case STATE_PARSING_NO_LONGER_POSSIBLE: continue_processing = false; QUIC_BUG(HttpDecoder PARSING_NO_LONGER_POSSIBLE) << "HttpDecoder called after an indefinite-length frame has been " "received"; RaiseError(QUIC_INTERNAL_ERROR, "HttpDecoder called after an indefinite-length frame has " "been received"); break; case STATE_ERROR: break; default: QUIC_BUG(quic_bug_10411_1) << "Invalid state: " << state_; } } return len - reader.BytesRemaining(); } bool HttpDecoder::ReadFrameType(QuicDataReader* reader) { QUICHE_DCHECK_NE(0u, reader->BytesRemaining()); if (current_type_field_length_ == 0) { current_type_field_length_ = reader->PeekVarInt62Length(); QUICHE_DCHECK_NE(0u, current_type_field_length_); if (current_type_field_length_ > reader->BytesRemaining()) { remaining_type_field_length_ = current_type_field_length_; BufferFrameType(reader); return true; } bool success = reader->ReadVarInt62(&current_frame_type_); QUICHE_DCHECK(success); } else { BufferFrameType(reader); if (remaining_type_field_length_ != 0) { return true; } QuicDataReader type_reader(type_buffer_.data(), current_type_field_length_); bool success = type_reader.ReadVarInt62(&current_frame_type_); QUICHE_DCHECK(success); } if (current_frame_type_ == static_cast<uint64_t>(http2::Http2FrameType::PRIORITY) || current_frame_type_ == static_cast<uint64_t>(http2::Http2FrameType::PING) || current_frame_type_ == static_cast<uint64_t>(http2::Http2FrameType::WINDOW_UPDATE) || current_frame_type_ == static_cast<uint64_t>(http2::Http2FrameType::CONTINUATION)) { RaiseError(QUIC_HTTP_RECEIVE_SPDY_FRAME, absl::StrCat("HTTP/2 frame received in a HTTP/3 connection: ", current_frame_type_)); return false; } if (current_frame_type_ == static_cast<uint64_t>(HttpFrameType::CANCEL_PUSH)) { RaiseError(QUIC_HTTP_FRAME_ERROR, "CANCEL_PUSH frame received."); return false; } if (current_frame_type_ == static_cast<uint64_t>(HttpFrameType::PUSH_PROMISE)) { RaiseError(QUIC_HTTP_FRAME_ERROR, "PUSH_PROMISE frame received."); return false; } state_ = STATE_READING_FRAME_LENGTH; return true; } bool HttpDecoder::ReadFrameLength(QuicDataReader* reader) { QUICHE_DCHECK_NE(0u, reader->BytesRemaining()); if (current_length_field_length_ == 0) { current_length_field_length_ = reader->PeekVarInt62Length(); QUICHE_DCHECK_NE(0u, current_length_field_length_); if (current_length_field_length_ > reader->BytesRemaining()) { remaining_length_field_length_ = current_length_field_length_; BufferFrameLength(reader); return true; } bool success = reader->ReadVarInt62(&current_frame_length_); QUICHE_DCHECK(success); } else { BufferFrameLength(reader); if (remaining_length_field_length_ != 0) { return true; } QuicDataReader length_reader(length_buffer_.data(), current_length_field_length_); bool success = length_reader.ReadVarInt62(&current_frame_length_); QUICHE_DCHECK(success); } if (allow_web_transport_stream_ && current_frame_type_ == static_cast<uint64_t>(HttpFrameType::WEBTRANSPORT_STREAM)) { visitor_->OnWebTransportStreamFrameType( current_length_field_length_ + current_type_field_length_, current_frame_length_); state_ = STATE_PARSING_NO_LONGER_POSSIBLE; return false; } if (IsFrameBuffered() && current_frame_length_ > MaxFrameLength(current_frame_type_)) { RaiseError(QUIC_HTTP_FRAME_TOO_LARGE, "Frame is too large."); return false; } bool continue_processing = true; const QuicByteCount header_length = current_length_field_length_ + current_type_field_length_; switch (current_frame_type_) { case static_cast<uint64_t>(HttpFrameType::DATA): continue_processing = visitor_->OnDataFrameStart(header_length, current_frame_length_); break; case static_cast<uint64_t>(HttpFrameType::HEADERS): continue_processing = visitor_->OnHeadersFrameStart(header_length, current_frame_length_); break; case static_cast<uint64_t>(HttpFrameType::CANCEL_PUSH): QUICHE_NOTREACHED(); break; case static_cast<uint64_t>(HttpFrameType::SETTINGS): continue_processing = visitor_->OnSettingsFrameStart(header_length); break; case static_cast<uint64_t>(HttpFrameType::PUSH_PROMISE): QUICHE_NOTREACHED(); break; case static_cast<uint64_t>(HttpFrameType::GOAWAY): break; case static_cast<uint64_t>(HttpFrameType::MAX_PUSH_ID): break; case static_cast<uint64_t>(HttpFrameType::PRIORITY_UPDATE_REQUEST_STREAM): continue_processing = visitor_->OnPriorityUpdateFrameStart(header_length); break; case static_cast<uint64_t>(HttpFrameType::ACCEPT_CH): continue_processing = visitor_->OnAcceptChFrameStart(header_length); break; default: if (current_frame_type_ == static_cast<uint64_t>(HttpFrameType::METADATA)) { continue_processing = visitor_->OnMetadataFrameStart( header_length, current_frame_length_); break; } continue_processing = visitor_->OnUnknownFrameStart( current_frame_type_, header_length, current_frame_length_); break; } remaining_frame_length_ = current_frame_length_; if (IsFrameBuffered()) { state_ = STATE_BUFFER_OR_PARSE_PAYLOAD; return continue_processing; } state_ = (remaining_frame_length_ == 0) ? STATE_FINISH_PARSING : STATE_READING_FRAME_PAYLOAD; return continue_processing; } bool HttpDecoder::IsFrameBuffered() { switch (current_frame_type_) { case static_cast<uint64_t>(HttpFrameType::SETTINGS): return true; case static_cast<uint64_t>(HttpFrameType::GOAWAY): return true; case static_cast<uint64_t>(HttpFrameType::MAX_PUSH_ID): return true; case static_cast<uint64_t>(HttpFrameType::PRIORITY_UPDATE_REQUEST_STREAM): return true; case static_cast<uint64_t>(HttpFrameType::ACCEPT_CH): return true; } return false; } bool HttpDecoder::ReadFramePayload(QuicDataReader* reader) { QUICHE_DCHECK(!IsFrameBuffered()); QUICHE_DCHECK_NE(0u, reader->BytesRemaining()); QUICHE_DCHECK_NE(0u, remaining_frame_length_); bool continue_processing = true; switch (current_frame_type_) { case static_cast<uint64_t>(HttpFrameType::DATA): { QuicByteCount bytes_to_read = std::min<QuicByteCount>( remaining_frame_length_, reader->BytesRemaining()); absl::string_view payload; bool success = reader->ReadStringPiece(&payload, bytes_to_read); QUICHE_DCHECK(success); QUICHE_DCHECK(!payload.empty()); continue_processing = visitor_->OnDataFramePayload(payload); remaining_frame_length_ -= payload.length(); break; } case static_cast<uint64_t>(HttpFrameType::HEADERS): { QuicByteCount bytes_to_read = std::min<QuicByteCount>( remaining_frame_length_, reader->BytesRemaining()); absl::string_view payload; bool success = reader->ReadStringPiece(&payload, bytes_to_read); QUICHE_DCHECK(success); QUICHE_DCHECK(!payload.empty()); continue_processing = visitor_->OnHeadersFramePayload(payload); remaining_frame_length_ -= payload.length(); break; } case static_cast<uint64_t>(HttpFrameType::CANCEL_PUSH): { QUICHE_NOTREACHED(); break; } case static_cast<uint64_t>(HttpFrameType::SETTINGS): { QUICHE_NOTREACHED(); break; } case static_cast<uint64_t>(HttpFrameType::PUSH_PROMISE): { QUICHE_NOTREACHED(); break; } case static_cast<uint64_t>(HttpFrameType::GOAWAY): { QUICHE_NOTREACHED(); break; } case static_cast<uint64_t>(HttpFrameType::MAX_PUSH_ID): { QUICHE_NOTREACHED(); break; } case static_cast<uint64_t>(HttpFrameType::PRIORITY_UPDATE_REQUEST_STREAM): { QUICHE_NOTREACHED(); break; } case static_cast<uint64_t>(HttpFrameType::ACCEPT_CH): { QUICHE_NOTREACHED(); break; } default: { if (current_frame_type_ == static_cast<uint64_t>(HttpFrameType::METADATA)) { QuicByteCount bytes_to_read = std::min<QuicByteCount>( remaining_frame_length_, reader->BytesRemaining()); absl::string_view payload; bool success = reader->ReadStringPiece(&payload, bytes_to_read); QUICHE_DCHECK(success); QUICHE_DCHECK(!payload.empty()); continue_processing = visitor_->OnMetadataFramePayload(payload); remaining_frame_length_ -= payload.length(); break; } continue_processing = HandleUnknownFramePayload(reader); break; } } if (remaining_frame_length_ == 0) { state_ = STATE_FINISH_PARSING; } return continue_processing; } bool HttpDecoder::FinishParsing() { QUICHE_DCHECK(!IsFrameBuffered()); QUICHE_DCHECK_EQ(0u, remaining_frame_length_); bool continue_processing = true; switch (current_frame_type_) { case static_cast<uint64_t>(HttpFrameType::DATA): { continue_processing = visitor_->OnDataFrameEnd(); break; } case static_cast<uint64_t>(HttpFrameType::HEADERS): { continue_processing = visitor_->OnHeadersFrameEnd(); break; } case static_cast<uint64_t>(HttpFrameType::CANCEL_PUSH): { QUICHE_NOTREACHED(); break; } case static_cast<uint64_t>(HttpFrameType::SETTINGS): { QUICHE_NOTREACHED(); break; } case static_cast<uint64_t>(HttpFrameType::PUSH_PROMISE): { QUICHE_NOTREACHED(); break; } case static_cast<uint64_t>(HttpFrameType::GOAWAY): { QUICHE_NOTREACHED(); break; } case static_cast<uint64_t>(HttpFrameType::MAX_PUSH_ID): { QUICHE_NOTREACHED(); break; } case static_cast<uint64_t>(HttpFrameType::PRIORITY_UPDATE_REQUEST_STREAM): { QUICHE_NOTREACHED(); break; } case static_cast<uint64_t>(HttpFrameType::ACCEPT_CH): { QUICHE_NOTREACHED(); break; } default: if (current_frame_type_ == static_cast<uint64_t>(HttpFrameType::METADATA)) { continue_processing = visitor_->OnMetadataFrameEnd(); break; } continue_processing = visitor_->OnUnknownFrameEnd(); } ResetForNextFrame(); return continue_processing; } void HttpDecoder::ResetForNextFrame() { current_length_field_length_ = 0; current_type_field_length_ = 0; state_ = STATE_READING_FRAME_TYPE; } bool HttpDecoder::HandleUnknownFramePayload(QuicDataReader* reader) { QuicByteCount bytes_to_read = std::min<QuicByteCount>( remaining_frame_length_, reader->BytesRemaining()); absl::string_view payload; bool success = reader->ReadStringPiece(&payload, bytes_to_read); QUICHE_DCHECK(success); QUICHE_DCHECK(!payload.empty()); remaining_frame_length_ -= payload.length(); return visitor_->OnUnknownFramePayload(payload); } bool HttpDecoder::BufferOrParsePayload(QuicDataReader* reader) { QUICHE_DCHECK(IsFrameBuffered()); QUICHE_DCHECK_EQ(current_frame_length_, buffer_.size() + remaining_frame_length_); if (buffer_.empty() && reader->BytesRemaining() >= current_frame_length_) { remaining_frame_length_ = 0; QuicDataReader current_payload_reader(reader->PeekRemainingPayload().data(), current_frame_length_); bool continue_processing = ParseEntirePayload(&current_payload_reader); reader->Seek(current_frame_length_); ResetForNextFrame(); return continue_processing; } QuicByteCount bytes_to_read = std::min<QuicByteCount>( remaining_frame_length_, reader->BytesRemaining()); absl::StrAppend(&buffer_, reader->PeekRemainingPayload().substr( 0, bytes_to_read)); reader->Seek(bytes_to_read); remaining_frame_length_ -= bytes_to_read; QUICHE_DCHECK_EQ(current_frame_length_, buffer_.size() + remaining_frame_length_); if (remaining_frame_length_ > 0) { QUICHE_DCHECK(reader->IsDoneReading()); return false; } QuicDataReader buffer_reader(buffer_); bool continue_processing = ParseEntirePayload(&buffer_reader); buffer_.clear(); ResetForNextFrame(); return continue_processing; } bool HttpDecoder::ParseEntirePayload(QuicDataReader* reader) { QUICHE_DCHECK(IsFrameBuffered()); QUICHE_DCHECK_EQ(current_frame_length_, reader->BytesRemaining()); QUICHE_DCHECK_EQ(0u, remaining_frame_length_); switch (current_frame_type_) { case static_cast<uint64_t>(HttpFrameType::CANCEL_PUSH): { QUICHE_NOTREACHED(); return false; } case static_cast<uint64_t>(HttpFrameType::SETTINGS): { SettingsFrame frame; if (!ParseSettingsFrame(reader, &frame)) { return false; } return visitor_->OnSettingsFrame(frame); } case static_cast<uint64_t>(HttpFrameType::GOAWAY): { GoAwayFrame frame; if (!reader->ReadVarInt62(&frame.id)) { RaiseError(QUIC_HTTP_FRAME_ERROR, "Unable to read GOAWAY ID."); return false; } if (!reader->IsDoneReading()) { RaiseError(QUIC_HTTP_FRAME_ERROR, "Superfluous data in GOAWAY frame."); return false; } return visitor_->OnGoAwayFrame(frame); } case static_cast<uint64_t>(HttpFrameType::MAX_PUSH_ID): { uint64_t unused; if (!reader->ReadVarInt62(&unused)) { RaiseError(QUIC_HTTP_FRAME_ERROR, "Unable to read MAX_PUSH_ID push_id."); return false; } if (!reader->IsDoneReading()) { RaiseError(QUIC_HTTP_FRAME_ERROR, "Superfluous data in MAX_PUSH_ID frame."); return false; } return visitor_->OnMaxPushIdFrame(); } case static_cast<uint64_t>(HttpFrameType::PRIORITY_UPDATE_REQUEST_STREAM): { PriorityUpdateFrame frame; if (!ParsePriorityUpdateFrame(reader, &frame)) { return false; } return visitor_->OnPriorityUpdateFrame(frame); } case static_cast<uint64_t>(HttpFrameType::ACCEPT_CH): { AcceptChFrame frame; if (!ParseAcceptChFrame(reader, &frame)) { return false; } return visitor_->OnAcceptChFrame(frame); } default: QUICHE_NOTREACHED(); return false; } } void HttpDecoder::BufferFrameLength(QuicDataReader* reader) { QuicByteCount bytes_to_read = std::min<QuicByteCo
#include "quiche/quic/core/http/http_decoder.h" #include <memory> #include <string> #include <utility> #include "absl/base/macros.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/http/http_encoder.h" #include "quiche/quic/core/http/http_frames.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" using ::testing::_; using ::testing::AnyNumber; using ::testing::Eq; using ::testing::InSequence; using ::testing::Return; namespace quic { namespace test { class HttpDecoderPeer { public: static uint64_t current_frame_type(HttpDecoder* decoder) { return decoder->current_frame_type_; } }; namespace { class HttpDecoderTest : public QuicTest { public: HttpDecoderTest() : decoder_(&visitor_) { ON_CALL(visitor_, OnMaxPushIdFrame()).WillByDefault(Return(true)); ON_CALL(visitor_, OnGoAwayFrame(_)).WillByDefault(Return(true)); ON_CALL(visitor_, OnSettingsFrameStart(_)).WillByDefault(Return(true)); ON_CALL(visitor_, OnSettingsFrame(_)).WillByDefault(Return(true)); ON_CALL(visitor_, OnDataFrameStart(_, _)).WillByDefault(Return(true)); ON_CALL(visitor_, OnDataFramePayload(_)).WillByDefault(Return(true)); ON_CALL(visitor_, OnDataFrameEnd()).WillByDefault(Return(true)); ON_CALL(visitor_, OnHeadersFrameStart(_, _)).WillByDefault(Return(true)); ON_CALL(visitor_, OnHeadersFramePayload(_)).WillByDefault(Return(true)); ON_CALL(visitor_, OnHeadersFrameEnd()).WillByDefault(Return(true)); ON_CALL(visitor_, OnPriorityUpdateFrameStart(_)) .WillByDefault(Return(true)); ON_CALL(visitor_, OnPriorityUpdateFrame(_)).WillByDefault(Return(true)); ON_CALL(visitor_, OnAcceptChFrameStart(_)).WillByDefault(Return(true)); ON_CALL(visitor_, OnAcceptChFrame(_)).WillByDefault(Return(true)); ON_CALL(visitor_, OnMetadataFrameStart(_, _)).WillByDefault(Return(true)); ON_CALL(visitor_, OnMetadataFramePayload(_)).WillByDefault(Return(true)); ON_CALL(visitor_, OnMetadataFrameEnd()).WillByDefault(Return(true)); ON_CALL(visitor_, OnUnknownFrameStart(_, _, _)).WillByDefault(Return(true)); ON_CALL(visitor_, OnUnknownFramePayload(_)).WillByDefault(Return(true)); ON_CALL(visitor_, OnUnknownFrameEnd()).WillByDefault(Return(true)); } ~HttpDecoderTest() override = default; uint64_t current_frame_type() { return HttpDecoderPeer::current_frame_type(&decoder_); } QuicByteCount ProcessInput(absl::string_view input) { return decoder_.ProcessInput(input.data(), input.size()); } void ProcessInputCharByChar(absl::string_view input) { for (char c : input) { EXPECT_EQ(1u, decoder_.ProcessInput(&c, 1)); } } QuicByteCount ProcessInputWithGarbageAppended(absl::string_view input) { std::string input_with_garbage_appended = absl::StrCat(input, "blahblah"); QuicByteCount processed_bytes = ProcessInput(input_with_garbage_appended); QUICHE_DCHECK_LE(processed_bytes, input_with_garbage_appended.size()); EXPECT_LE(processed_bytes, input.size()); return processed_bytes; } testing::StrictMock<MockHttpDecoderVisitor> visitor_; HttpDecoder decoder_; }; TEST_F(HttpDecoderTest, InitialState) { EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); } TEST_F(HttpDecoderTest, UnknownFrame) { std::unique_ptr<char[]> input; const QuicByteCount payload_lengths[] = {0, 14, 100}; const uint64_t frame_types[] = { 0x21, 0x40, 0x5f, 0x7e, 0x9d, 0x6f, 0x14 }; for (auto payload_length : payload_lengths) { std::string data(payload_length, 'a'); for (auto frame_type : frame_types) { const QuicByteCount total_length = QuicDataWriter::GetVarInt62Len(frame_type) + QuicDataWriter::GetVarInt62Len(payload_length) + payload_length; input = std::make_unique<char[]>(total_length); QuicDataWriter writer(total_length, input.get()); writer.WriteVarInt62(frame_type); writer.WriteVarInt62(payload_length); const QuicByteCount header_length = writer.length(); if (payload_length > 0) { writer.WriteStringPiece(data); } EXPECT_CALL(visitor_, OnUnknownFrameStart(frame_type, header_length, payload_length)); if (payload_length > 0) { EXPECT_CALL(visitor_, OnUnknownFramePayload(Eq(data))); } EXPECT_CALL(visitor_, OnUnknownFrameEnd()); EXPECT_EQ(total_length, decoder_.ProcessInput(input.get(), total_length)); EXPECT_THAT(decoder_.error(), IsQuicNoError()); ASSERT_EQ("", decoder_.error_detail()); EXPECT_EQ(frame_type, current_frame_type()); } } } TEST_F(HttpDecoderTest, CancelPush) { InSequence s; std::string input; ASSERT_TRUE( absl::HexStringToBytes("03" "01" "01", &input)); EXPECT_CALL(visitor_, OnError(&decoder_)); EXPECT_EQ(1u, ProcessInput(input)); EXPECT_THAT(decoder_.error(), IsError(QUIC_HTTP_FRAME_ERROR)); EXPECT_EQ("CANCEL_PUSH frame received.", decoder_.error_detail()); } TEST_F(HttpDecoderTest, PushPromiseFrame) { InSequence s; std::string push_promise_bytes; ASSERT_TRUE( absl::HexStringToBytes("05" "08" "1f", &push_promise_bytes)); std::string input = absl::StrCat(push_promise_bytes, "Headers"); EXPECT_CALL(visitor_, OnError(&decoder_)); EXPECT_EQ(1u, ProcessInput(input)); EXPECT_THAT(decoder_.error(), IsError(QUIC_HTTP_FRAME_ERROR)); EXPECT_EQ("PUSH_PROMISE frame received.", decoder_.error_detail()); } TEST_F(HttpDecoderTest, MaxPushId) { InSequence s; std::string input; ASSERT_TRUE( absl::HexStringToBytes("0D" "01" "01", &input)); EXPECT_CALL(visitor_, OnMaxPushIdFrame()).WillOnce(Return(false)); EXPECT_EQ(input.size(), ProcessInputWithGarbageAppended(input)); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); EXPECT_CALL(visitor_, OnMaxPushIdFrame()); EXPECT_EQ(input.size(), ProcessInput(input)); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); EXPECT_CALL(visitor_, OnMaxPushIdFrame()); ProcessInputCharByChar(input); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); } TEST_F(HttpDecoderTest, SettingsFrame) { InSequence s; std::string input; ASSERT_TRUE(absl::HexStringToBytes( "04" "07" "01" "02" "06" "05" "4100" "04", &input)); SettingsFrame frame; frame.values[1] = 2; frame.values[6] = 5; frame.values[256] = 4; absl::string_view remaining_input(input); EXPECT_CALL(visitor_, OnSettingsFrameStart(2)).WillOnce(Return(false)); QuicByteCount processed_bytes = ProcessInputWithGarbageAppended(remaining_input); EXPECT_EQ(2u, processed_bytes); remaining_input = remaining_input.substr(processed_bytes); EXPECT_CALL(visitor_, OnSettingsFrame(frame)).WillOnce(Return(false)); processed_bytes = ProcessInputWithGarbageAppended(remaining_input); EXPECT_EQ(remaining_input.size(), processed_bytes); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); EXPECT_CALL(visitor_, OnSettingsFrameStart(2)); EXPECT_CALL(visitor_, OnSettingsFrame(frame)); EXPECT_EQ(input.size(), ProcessInput(input)); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); EXPECT_CALL(visitor_, OnSettingsFrameStart(2)); EXPECT_CALL(visitor_, OnSettingsFrame(frame)); ProcessInputCharByChar(input); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); } TEST_F(HttpDecoderTest, CorruptSettingsFrame) { const char* const kPayload = "\x42\x11" "\x80\x22\x33\x44" "\x58\x39" "\xf0\x22\x33\x44\x55\x66\x77\x88"; struct { size_t payload_length; const char* const error_message; } kTestData[] = { {1, "Unable to read setting identifier."}, {5, "Unable to read setting value."}, {7, "Unable to read setting identifier."}, {12, "Unable to read setting value."}, }; for (const auto& test_data : kTestData) { std::string input; input.push_back(4u); input.push_back(test_data.payload_length); const size_t header_length = input.size(); input.append(kPayload, test_data.payload_length); HttpDecoder decoder(&visitor_); EXPECT_CALL(visitor_, OnSettingsFrameStart(header_length)); EXPECT_CALL(visitor_, OnError(&decoder)); QuicByteCount processed_bytes = decoder.ProcessInput(input.data(), input.size()); EXPECT_EQ(input.size(), processed_bytes); EXPECT_THAT(decoder.error(), IsError(QUIC_HTTP_FRAME_ERROR)); EXPECT_EQ(test_data.error_message, decoder.error_detail()); } } TEST_F(HttpDecoderTest, DuplicateSettingsIdentifier) { std::string input; ASSERT_TRUE( absl::HexStringToBytes("04" "04" "01" "01" "01" "02", &input)); EXPECT_CALL(visitor_, OnSettingsFrameStart(2)); EXPECT_CALL(visitor_, OnError(&decoder_)); EXPECT_EQ(input.size(), ProcessInput(input)); EXPECT_THAT(decoder_.error(), IsError(QUIC_HTTP_DUPLICATE_SETTING_IDENTIFIER)); EXPECT_EQ("Duplicate setting identifier.", decoder_.error_detail()); } TEST_F(HttpDecoderTest, DataFrame) { InSequence s; std::string type_and_length_bytes; ASSERT_TRUE( absl::HexStringToBytes("00" "05", &type_and_length_bytes)); std::string input = absl::StrCat(type_and_length_bytes, "Data!"); EXPECT_CALL(visitor_, OnDataFrameStart(2, 5)).WillOnce(Return(false)); absl::string_view remaining_input(input); QuicByteCount processed_bytes = ProcessInputWithGarbageAppended(remaining_input); EXPECT_EQ(2u, processed_bytes); remaining_input = remaining_input.substr(processed_bytes); EXPECT_CALL(visitor_, OnDataFramePayload(absl::string_view("Data!"))) .WillOnce(Return(false)); processed_bytes = ProcessInputWithGarbageAppended(remaining_input); EXPECT_EQ(remaining_input.size(), processed_bytes); EXPECT_CALL(visitor_, OnDataFrameEnd()).WillOnce(Return(false)); EXPECT_EQ(0u, ProcessInputWithGarbageAppended("")); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); EXPECT_CALL(visitor_, OnDataFrameStart(2, 5)); EXPECT_CALL(visitor_, OnDataFramePayload(absl::string_view("Data!"))); EXPECT_CALL(visitor_, OnDataFrameEnd()); EXPECT_EQ(input.size(), ProcessInput(input)); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); EXPECT_CALL(visitor_, OnDataFrameStart(2, 5)); EXPECT_CALL(visitor_, OnDataFramePayload(absl::string_view("D"))); EXPECT_CALL(visitor_, OnDataFramePayload(absl::string_view("a"))); EXPECT_CALL(visitor_, OnDataFramePayload(absl::string_view("t"))); EXPECT_CALL(visitor_, OnDataFramePayload(absl::string_view("a"))); EXPECT_CALL(visitor_, OnDataFramePayload(absl::string_view("!"))); EXPECT_CALL(visitor_, OnDataFrameEnd()); ProcessInputCharByChar(input); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); } TEST_F(HttpDecoderTest, FrameHeaderPartialDelivery) { InSequence s; std::string input(2048, 'x'); quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader( input.length(), quiche::SimpleBufferAllocator::Get()); EXPECT_EQ(1u, decoder_.ProcessInput(header.data(), 1)); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); EXPECT_CALL(visitor_, OnDataFrameStart(3, input.length())); EXPECT_EQ(header.size() - 1, decoder_.ProcessInput(header.data() + 1, header.size() - 1)); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); EXPECT_CALL(visitor_, OnDataFramePayload(absl::string_view(input))); EXPECT_CALL(visitor_, OnDataFrameEnd()); EXPECT_EQ(2048u, decoder_.ProcessInput(input.data(), 2048)); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); } TEST_F(HttpDecoderTest, PartialDeliveryOfLargeFrameType) { const uint64_t frame_type = 0x1f * 0x222 + 0x21; const QuicByteCount payload_length = 0; const QuicByteCount header_length = QuicDataWriter::GetVarInt62Len(frame_type) + QuicDataWriter::GetVarInt62Len(payload_length); auto input = std::make_unique<char[]>(header_length); QuicDataWriter writer(header_length, input.get()); writer.WriteVarInt62(frame_type); writer.WriteVarInt62(payload_length); EXPECT_CALL(visitor_, OnUnknownFrameStart(frame_type, header_length, payload_length)); EXPECT_CALL(visitor_, OnUnknownFrameEnd()); auto raw_input = input.get(); for (uint64_t i = 0; i < header_length; ++i) { char c = raw_input[i]; EXPECT_EQ(1u, decoder_.ProcessInput(&c, 1)); } EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); EXPECT_EQ(frame_type, current_frame_type()); } TEST_F(HttpDecoderTest, GoAway) { InSequence s; std::string input; ASSERT_TRUE( absl::HexStringToBytes("07" "01" "01", &input)); EXPECT_CALL(visitor_, OnGoAwayFrame(GoAwayFrame({1}))) .WillOnce(Return(false)); EXPECT_EQ(input.size(), ProcessInputWithGarbageAppended(input)); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); EXPECT_CALL(visitor_, OnGoAwayFrame(GoAwayFrame({1}))); EXPECT_EQ(input.size(), ProcessInput(input)); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); EXPECT_CALL(visitor_, OnGoAwayFrame(GoAwayFrame({1}))); ProcessInputCharByChar(input); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); } TEST_F(HttpDecoderTest, HeadersFrame) { InSequence s; std::string type_and_length_bytes; ASSERT_TRUE( absl::HexStringToBytes("01" "07", &type_and_length_bytes)); std::string input = absl::StrCat(type_and_length_bytes, "Headers"); EXPECT_CALL(visitor_, OnHeadersFrameStart(2, 7)).WillOnce(Return(false)); absl::string_view remaining_input(input); QuicByteCount processed_bytes = ProcessInputWithGarbageAppended(remaining_input); EXPECT_EQ(2u, processed_bytes); remaining_input = remaining_input.substr(processed_bytes); EXPECT_CALL(visitor_, OnHeadersFramePayload(absl::string_view("Headers"))) .WillOnce(Return(false)); processed_bytes = ProcessInputWithGarbageAppended(remaining_input); EXPECT_EQ(remaining_input.size(), processed_bytes); EXPECT_CALL(visitor_, OnHeadersFrameEnd()).WillOnce(Return(false)); EXPECT_EQ(0u, ProcessInputWithGarbageAppended("")); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); EXPECT_CALL(visitor_, OnHeadersFrameStart(2, 7)); EXPECT_CALL(visitor_, OnHeadersFramePayload(absl::string_view("Headers"))); EXPECT_CALL(visitor_, OnHeadersFrameEnd()); EXPECT_EQ(input.size(), ProcessInput(input)); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); EXPECT_CALL(visitor_, OnHeadersFrameStart(2, 7)); EXPECT_CALL(visitor_, OnHeadersFramePayload(absl::string_view("H"))); EXPECT_CALL(visitor_, OnHeadersFramePayload(absl::string_view("e"))); EXPECT_CALL(visitor_, OnHeadersFramePayload(absl::string_view("a"))); EXPECT_CALL(visitor_, OnHeadersFramePayload(absl::string_view("d"))); EXPECT_CALL(visitor_, OnHeadersFramePayload(absl::string_view("e"))); EXPECT_CALL(visitor_, OnHeadersFramePayload(absl::string_view("r"))); EXPECT_CALL(visitor_, OnHeadersFramePayload(absl::string_view("s"))); EXPECT_CALL(visitor_, OnHeadersFrameEnd()); ProcessInputCharByChar(input); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); } TEST_F(HttpDecoderTest, MetadataFrame) { InSequence s; std::string type_and_length_bytes; ASSERT_TRUE( absl::HexStringToBytes("404d" "08", &type_and_length_bytes)); std::string input = absl::StrCat(type_and_length_bytes, "Metadata"); EXPECT_CALL(visitor_, OnMetadataFrameStart(3, 8)).WillOnce(Return(false)); absl::string_view remaining_input(input); QuicByteCount processed_bytes = ProcessInputWithGarbageAppended(remaining_input); EXPECT_EQ(3u, processed_bytes); remaining_input = remaining_input.substr(processed_bytes); EXPECT_CALL(visitor_, OnMetadataFramePayload(absl::string_view("Metadata"))) .WillOnce(Return(false)); processed_bytes = ProcessInputWithGarbageAppended(remaining_input); EXPECT_EQ(remaining_input.size(), processed_bytes); EXPECT_CALL(visitor_, OnMetadataFrameEnd()).WillOnce(Return(false)); EXPECT_EQ(0u, ProcessInputWithGarbageAppended("")); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); EXPECT_CALL(visitor_, OnMetadataFrameStart(3, 8)); EXPECT_CALL(visitor_, OnMetadataFramePayload(absl::string_view("Metadata"))); EXPECT_CALL(visitor_, OnMetadataFrameEnd()); EXPECT_EQ(input.size(), ProcessInput(input)); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); EXPECT_CALL(visitor_, OnMetadataFrameStart(3, 8)); EXPECT_CALL(visitor_, OnMetadataFramePayload(absl::string_view("M"))); EXPECT_CALL(visitor_, OnMetadataFramePayload(absl::string_view("e"))); EXPECT_CALL(visitor_, OnMetadataFramePayload(absl::string_view("t"))); EXPECT_CALL(visitor_, OnMetadataFramePayload(absl::string_view("a"))); EXPECT_CALL(visitor_, OnMetadataFramePayload(absl::string_view("d"))); EXPECT_CALL(visitor_, OnMetadataFramePayload(absl::string_view("a"))); EXPECT_CALL(visitor_, OnMetadataFramePayload(absl::string_view("t"))); EXPECT_CALL(visitor_, OnMetadataFramePayload(absl::string_view("a"))); EXPECT_CALL(visitor_, OnMetadataFrameEnd()); ProcessInputCharByChar(input); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); } TEST_F(HttpDecoderTest, EmptyDataFrame) { InSequence s; std::string input; ASSERT_TRUE( absl::HexStringToBytes("00" "00", &input)); EXPECT_CALL(visitor_, OnDataFrameStart(2, 0)).WillOnce(Return(false)); EXPECT_EQ(input.size(), ProcessInputWithGarbageAppended(input)); EXPECT_CALL(visitor_, OnDataFrameEnd()).WillOnce(Return(false)); EXPECT_EQ(0u, ProcessInputWithGarbageAppended("")); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); EXPECT_CALL(visitor_, OnDataFrameStart(2, 0)); EXPECT_CALL(visitor_, OnDataFrameEnd()); EXPECT_EQ(input.size(), ProcessInput(input)); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); EXPECT_CALL(visitor_, OnDataFrameStart(2, 0)); EXPECT_CALL(visitor_, OnDataFrameEnd()); ProcessInputCharByChar(input); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); } TEST_F(HttpDecoderTest, EmptyHeadersFrame) { InSequence s; std::string input; ASSERT_TRUE( absl::HexStringToBytes("01" "00", &input)); EXPECT_CALL(visitor_, OnHeadersFrameStart(2, 0)).WillOnce(Return(false)); EXPECT_EQ(input.size(), ProcessInputWithGarbageAppended(input)); EXPECT_CALL(visitor_, OnHeadersFrameEnd()).WillOnce(Return(false)); EXPECT_EQ(0u, ProcessInputWithGarbageAppended("")); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); EXPECT_CALL(visitor_, OnHeadersFrameStart(2, 0)); EXPECT_CALL(visitor_, OnHeadersFrameEnd()); EXPECT_EQ(input.size(), ProcessInput(input)); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); EXPECT_CALL(visitor_, OnHeadersFrameStart(2, 0)); EXPECT_CALL(visitor_, OnHeadersFrameEnd()); ProcessInputCharByChar(input); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); } TEST_F(HttpDecoderTest, GoawayWithOverlyLargePayload) { std::string input; ASSERT_TRUE(absl::HexStringToBytes( "07" "10", &input)); EXPECT_CALL(visitor_, OnError(&decoder_)); EXPECT_EQ(2u, ProcessInput(input)); EXPECT_THAT(decoder_.error(), IsError(QUIC_HTTP_FRAME_TOO_LARGE)); EXPECT_EQ("Frame is too large.", decoder_.error_detail()); } TEST_F(HttpDecoderTest, MaxPushIdWithOverlyLargePayload) { std::string input; ASSERT_TRUE( absl::HexStringToBytes("0d" "10", &input)); EXPECT_CALL(visitor_, OnError(&decoder_)); EXPECT_EQ(2u, ProcessInput(input)); EXPECT_THAT(decoder_.error(), IsError(QUIC_HTTP_FRAME_TOO_LARGE)); EXPECT_EQ("Frame is too large.", decoder_.error_detail()); } TEST_F(HttpDecoderTest, FrameWithOverlyLargePayload) { constexpr size_t max_input_length = sizeof(uint64_t) + sizeof(uint64_t) + sizeof(uint8_t); char input[max_input_length]; for (uint64_t frame_type = 0; frame_type < 1025; frame_type++) { ::testing::NiceMock<MockHttpDecoderVisitor> visitor; HttpDecoder decoder(&visitor); QuicDataWriter writer(max_input_length, input); ASSERT_TRUE(writer.WriteVarInt62(frame_type)); ASSERT_TRUE( writer.WriteVarInt62(quiche::kVarInt62MaxValue)); ASSERT_TRUE(writer.WriteUInt8(0x00)); EXPECT_NE(decoder.ProcessInput(input, writer.length()), 0u) << frame_type; } } TEST_F(HttpDecoderTest, MalformedSettingsFrame) { char input[30]; QuicDataWriter writer(30, input); writer.WriteUInt8(0x04); writer.WriteVarInt62(2048 * 1024); writer.WriteStringPiece("Malformed payload"); EXPECT_CALL(visitor_, OnError(&decoder_)); EXPECT_EQ(5u, decoder_.ProcessInput(input, ABSL_ARRAYSIZE(input))); EXPECT_THAT(decoder_.error(), IsError(QUIC_HTTP_FRAME_TOO_LARGE)); EXPECT_EQ("Frame is too large.", decoder_.error_detail()); } TEST_F(HttpDecoderTest, Http2Frame) { std::string input; ASSERT_TRUE(absl::HexStringToBytes( "06" "05" "15", &input)); EXPECT_CALL(visitor_, OnError(&decoder_)); EXPECT_EQ(1u, ProcessInput(input)); EXPECT_THAT(decoder_.error(), IsError(QUIC_HTTP_RECEIVE_SPDY_FRAME)); EXPECT_EQ("HTTP/2 frame received in a HTTP/3 connection: 6", decoder_.error_detail()); } TEST_F(HttpDecoderTest, HeadersPausedThenData) { InSequence s; std::string headers_type_and_length_bytes; ASSERT_TRUE( absl::HexStringToBytes("01" "07", &headers_type_and_length_bytes)); std::string headers = absl::StrCat(headers_type_and_length_bytes, "Headers"); std::string data_type_and_length_bytes; ASSERT_TRUE( absl::HexStringToBytes("00" "05", &data_type_and_length_bytes)); std::string data = absl::StrCat(data_type_and_length_bytes, "Data!"); std::string input = absl::StrCat(headers, data); EXPECT_CALL(visitor_, OnHeadersFrameStart(2, 7)); EXPECT_CALL(visitor_, OnHeadersFramePayload(absl::string_view("Headers"))); EXPECT_CALL(visitor_, OnHeadersFrameEnd()).WillOnce(Return(false)); absl::string_view remaining_input(input); QuicByteCount processed_bytes = ProcessInputWithGarbageAppended(remaining_input); EXPECT_EQ(9u, processed_bytes); remaining_input = remaining_input.substr(processed_bytes); EXPECT_CALL(visitor_, OnDataFrameStart(2, 5)); EXPECT_CALL(visitor_, OnDataFramePayload(absl::string_view("Data!"))); EXPECT_CALL(visitor_, OnDataFrameEnd()); processed_bytes = ProcessInput(remaining_input); EXPECT_EQ(remaining_input.size(), processed_bytes); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); } TEST_F(HttpDecoderTest, CorruptFrame) { InSequence s; struct { const char* const input; const char* const error_message; } kTestData[] = {{"\x0D" "\x01" "\x40", "Unable to read MAX_PUSH_ID push_id."}, {"\x0D" "\x04" "\x05" "foo", "Superfluous data in MAX_PUSH_ID frame."}, {"\x07" "\x01" "\x40", "Unable to read GOAWAY ID."}, {"\x07" "\x04" "\x05" "foo", "Superfluous data in GOAWAY frame."}, {"\x40\x89" "\x01" "\x40", "Unable to read ACCEPT_CH origin."}, {"\x40\x89" "\x01" "\x05", "Unable to read ACCEPT_CH origin."}, {"\x40\x89" "\x04" "\x05" "foo", "Unable to read ACCEPT_CH origin."}, {"\x40\x89" "\x04" "\x03" "foo", "Unable to read ACCEPT_CH value."}, {"\x40\x89" "\x05" "\x03" "foo" "\x40", "Unable to read ACCEPT_CH value."}, {"\x40\x89" "\x08" "\x03" "foo" "\x05" "bar", "Unable to read ACCEPT_CH value."}}; for (const auto& test_data : kTestData) { { HttpDecoder decoder(&visitor_); EXPECT_CALL(visitor_, OnAcceptChFrameStart(_)).Times(AnyNumber()); EXPECT_CALL(visitor_, OnError(&decoder)); absl::string_view input(test_data.input); decoder.ProcessInput(input.data(), input.size()); EXPECT_THAT(decoder.error(), IsError(QUIC_HTTP_FRAME_ERROR)); EXPECT_EQ(test_data.error_message, decoder.error_detail()); } { HttpDecoder decoder(&visitor_); EXPECT_CALL(visitor_, OnAcceptChFrameStart(_)).Times(AnyNumber()); EXPECT_CALL(visitor_, OnError(&decoder)); absl::string_view input(test_data.input); for (auto c : input) { decoder.ProcessInput(&c, 1); } EXPECT_THAT(decoder.error(), IsError(QUIC_HTTP_FRAME_ERROR)); EXPECT_EQ(test_data.error_message, decoder.error_detail()); } } } TEST_F(HttpDecoderTest, EmptySettingsFrame) { std::string input; ASSERT_TRUE( absl::HexStringToBytes("04" "00", &input)); EXPECT_CALL(visitor_, OnSettingsFrameStart(2)); SettingsFrame empty_frame; EXPECT_CALL(visitor_, OnSettingsFrame(empty_frame)); EXPECT_EQ(input.size(), ProcessInput(input)); EXPECT_THAT(decoder_.error(), IsQuicNoError()); EXPECT_EQ("", decoder_.error_detail()); } TEST_F(HttpDecoderTest, EmptyGoAwayFrame) { std::string input; ASSERT_TRUE( absl::HexStringToBytes("07" "00",
306
cpp
google/quiche
http_encoder
quiche/quic/core/http/http_encoder.cc
quiche/quic/core/http/http_encoder_test.cc
#ifndef QUICHE_QUIC_CORE_HTTP_HTTP_ENCODER_H_ #define QUICHE_QUIC_CORE_HTTP_HTTP_ENCODER_H_ #include <memory> #include "quiche/quic/core/http/http_frames.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/common/quiche_buffer_allocator.h" namespace quic { class QuicDataWriter; class QUICHE_EXPORT HttpEncoder { public: HttpEncoder() = delete; static QuicByteCount GetDataFrameHeaderLength(QuicByteCount payload_length); static quiche::QuicheBuffer SerializeDataFrameHeader( QuicByteCount payload_length, quiche::QuicheBufferAllocator* allocator); static std::string SerializeHeadersFrameHeader(QuicByteCount payload_length); static std::string SerializeSettingsFrame(const SettingsFrame& settings); static std::string SerializeGoAwayFrame(const GoAwayFrame& goaway); static std::string SerializePriorityUpdateFrame( const PriorityUpdateFrame& priority_update); static std::string SerializeAcceptChFrame(const AcceptChFrame& accept_ch); static std::string SerializeGreasingFrame(); static std::string SerializeWebTransportStreamFrameHeader( WebTransportSessionId session_id); static std::string SerializeMetadataFrameHeader(QuicByteCount payload_length); }; } #endif #include "quiche/quic/core/http/http_encoder.h" #include <algorithm> #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { namespace { bool WriteFrameHeader(QuicByteCount length, HttpFrameType type, QuicDataWriter* writer) { return writer->WriteVarInt62(static_cast<uint64_t>(type)) && writer->WriteVarInt62(length); } QuicByteCount GetTotalLength(QuicByteCount payload_length, HttpFrameType type) { return QuicDataWriter::GetVarInt62Len(payload_length) + QuicDataWriter::GetVarInt62Len(static_cast<uint64_t>(type)) + payload_length; } } QuicByteCount HttpEncoder::GetDataFrameHeaderLength( QuicByteCount payload_length) { QUICHE_DCHECK_NE(0u, payload_length); return QuicDataWriter::GetVarInt62Len(payload_length) + QuicDataWriter::GetVarInt62Len( static_cast<uint64_t>(HttpFrameType::DATA)); } quiche::QuicheBuffer HttpEncoder::SerializeDataFrameHeader( QuicByteCount payload_length, quiche::QuicheBufferAllocator* allocator) { QUICHE_DCHECK_NE(0u, payload_length); QuicByteCount header_length = GetDataFrameHeaderLength(payload_length); quiche::QuicheBuffer header(allocator, header_length); QuicDataWriter writer(header.size(), header.data()); if (WriteFrameHeader(payload_length, HttpFrameType::DATA, &writer)) { return header; } QUIC_DLOG(ERROR) << "Http encoder failed when attempting to serialize data frame header."; return quiche::QuicheBuffer(); } std::string HttpEncoder::SerializeHeadersFrameHeader( QuicByteCount payload_length) { QUICHE_DCHECK_NE(0u, payload_length); QuicByteCount header_length = QuicDataWriter::GetVarInt62Len(payload_length) + QuicDataWriter::GetVarInt62Len( static_cast<uint64_t>(HttpFrameType::HEADERS)); std::string frame; frame.resize(header_length); QuicDataWriter writer(header_length, frame.data()); if (WriteFrameHeader(payload_length, HttpFrameType::HEADERS, &writer)) { return frame; } QUIC_DLOG(ERROR) << "Http encoder failed when attempting to serialize headers " "frame header."; return {}; } std::string HttpEncoder::SerializeSettingsFrame(const SettingsFrame& settings) { QuicByteCount payload_length = 0; std::vector<std::pair<uint64_t, uint64_t>> ordered_settings{ settings.values.begin(), settings.values.end()}; std::sort(ordered_settings.begin(), ordered_settings.end()); for (const auto& p : ordered_settings) { payload_length += QuicDataWriter::GetVarInt62Len(p.first); payload_length += QuicDataWriter::GetVarInt62Len(p.second); } QuicByteCount total_length = GetTotalLength(payload_length, HttpFrameType::SETTINGS); std::string frame; frame.resize(total_length); QuicDataWriter writer(total_length, frame.data()); if (!WriteFrameHeader(payload_length, HttpFrameType::SETTINGS, &writer)) { QUIC_DLOG(ERROR) << "Http encoder failed when attempting to serialize " "settings frame header."; return {}; } for (const auto& p : ordered_settings) { if (!writer.WriteVarInt62(p.first) || !writer.WriteVarInt62(p.second)) { QUIC_DLOG(ERROR) << "Http encoder failed when attempting to serialize " "settings frame payload."; return {}; } } return frame; } std::string HttpEncoder::SerializeGoAwayFrame(const GoAwayFrame& goaway) { QuicByteCount payload_length = QuicDataWriter::GetVarInt62Len(goaway.id); QuicByteCount total_length = GetTotalLength(payload_length, HttpFrameType::GOAWAY); std::string frame; frame.resize(total_length); QuicDataWriter writer(total_length, frame.data()); if (WriteFrameHeader(payload_length, HttpFrameType::GOAWAY, &writer) && writer.WriteVarInt62(goaway.id)) { return frame; } QUIC_DLOG(ERROR) << "Http encoder failed when attempting to serialize goaway frame."; return {}; } std::string HttpEncoder::SerializePriorityUpdateFrame( const PriorityUpdateFrame& priority_update) { QuicByteCount payload_length = QuicDataWriter::GetVarInt62Len(priority_update.prioritized_element_id) + priority_update.priority_field_value.size(); QuicByteCount total_length = GetTotalLength( payload_length, HttpFrameType::PRIORITY_UPDATE_REQUEST_STREAM); std::string frame; frame.resize(total_length); QuicDataWriter writer(total_length, frame.data()); if (WriteFrameHeader(payload_length, HttpFrameType::PRIORITY_UPDATE_REQUEST_STREAM, &writer) && writer.WriteVarInt62(priority_update.prioritized_element_id) && writer.WriteBytes(priority_update.priority_field_value.data(), priority_update.priority_field_value.size())) { return frame; } QUIC_DLOG(ERROR) << "Http encoder failed when attempting to serialize " "PRIORITY_UPDATE frame."; return {}; } std::string HttpEncoder::SerializeAcceptChFrame( const AcceptChFrame& accept_ch) { QuicByteCount payload_length = 0; for (const auto& entry : accept_ch.entries) { payload_length += QuicDataWriter::GetVarInt62Len(entry.origin.size()); payload_length += entry.origin.size(); payload_length += QuicDataWriter::GetVarInt62Len(entry.value.size()); payload_length += entry.value.size(); } QuicByteCount total_length = GetTotalLength(payload_length, HttpFrameType::ACCEPT_CH); std::string frame; frame.resize(total_length); QuicDataWriter writer(total_length, frame.data()); if (!WriteFrameHeader(payload_length, HttpFrameType::ACCEPT_CH, &writer)) { QUIC_DLOG(ERROR) << "Http encoder failed to serialize ACCEPT_CH frame header."; return {}; } for (const auto& entry : accept_ch.entries) { if (!writer.WriteStringPieceVarInt62(entry.origin) || !writer.WriteStringPieceVarInt62(entry.value)) { QUIC_DLOG(ERROR) << "Http encoder failed to serialize ACCEPT_CH frame payload."; return {}; } } return frame; } std::string HttpEncoder::SerializeGreasingFrame() { uint64_t frame_type; QuicByteCount payload_length; std::string payload; if (!GetQuicFlag(quic_enable_http3_grease_randomness)) { frame_type = 0x40; payload_length = 1; payload = "a"; } else { uint32_t result; QuicRandom::GetInstance()->RandBytes(&result, sizeof(result)); frame_type = 0x1fULL * static_cast<uint64_t>(result) + 0x21ULL; payload_length = result % 4; if (payload_length > 0) { payload.resize(payload_length); QuicRandom::GetInstance()->RandBytes(payload.data(), payload_length); } } QuicByteCount total_length = QuicDataWriter::GetVarInt62Len(frame_type) + QuicDataWriter::GetVarInt62Len(payload_length) + payload_length; std::string frame; frame.resize(total_length); QuicDataWriter writer(total_length, frame.data()); bool success = writer.WriteVarInt62(frame_type) && writer.WriteVarInt62(payload_length); if (payload_length > 0) { success &= writer.WriteBytes(payload.data(), payload_length); } if (success) { return frame; } QUIC_DLOG(ERROR) << "Http encoder failed when attempting to serialize " "greasing frame."; return {}; } std::string HttpEncoder::SerializeWebTransportStreamFrameHeader( WebTransportSessionId session_id) { uint64_t stream_type = static_cast<uint64_t>(HttpFrameType::WEBTRANSPORT_STREAM); QuicByteCount header_length = QuicDataWriter::GetVarInt62Len(stream_type) + QuicDataWriter::GetVarInt62Len(session_id); std::string frame; frame.resize(header_length); QuicDataWriter writer(header_length, frame.data()); bool success = writer.WriteVarInt62(stream_type) && writer.WriteVarInt62(session_id); if (success && writer.remaining() == 0) { return frame; } QUIC_DLOG(ERROR) << "Http encoder failed when attempting to serialize " "WEBTRANSPORT_STREAM frame header."; return {}; } std::string HttpEncoder::SerializeMetadataFrameHeader( QuicByteCount payload_length) { QUICHE_DCHECK_NE(0u, payload_length); QuicByteCount header_length = QuicDataWriter::GetVarInt62Len(payload_length) + QuicDataWriter::GetVarInt62Len( static_cast<uint64_t>(HttpFrameType::METADATA)); std::string frame; frame.resize(header_length); QuicDataWriter writer(header_length, frame.data()); if (WriteFrameHeader(payload_length, HttpFrameType::METADATA, &writer)) { return frame; } QUIC_DLOG(ERROR) << "Http encoder failed when attempting to serialize METADATA " "frame header."; return {}; } }
#include "quiche/quic/core/http/http_encoder.h" #include <string> #include "absl/base/macros.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/simple_buffer_allocator.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace quic { namespace test { TEST(HttpEncoderTest, SerializeDataFrameHeader) { quiche::QuicheBuffer buffer = HttpEncoder::SerializeDataFrameHeader( 5, quiche::SimpleBufferAllocator::Get()); char output[] = {0x00, 0x05}; EXPECT_EQ(ABSL_ARRAYSIZE(output), buffer.size()); quiche::test::CompareCharArraysWithHexError( "DATA", buffer.data(), buffer.size(), output, ABSL_ARRAYSIZE(output)); } TEST(HttpEncoderTest, SerializeHeadersFrameHeader) { std::string header = HttpEncoder::SerializeHeadersFrameHeader( 7); char output[] = {0x01, 0x07}; quiche::test::CompareCharArraysWithHexError("HEADERS", header.data(), header.length(), output, ABSL_ARRAYSIZE(output)); } TEST(HttpEncoderTest, SerializeSettingsFrame) { SettingsFrame settings; settings.values[1] = 2; settings.values[6] = 5; settings.values[256] = 4; char output[] = {0x04, 0x07, 0x01, 0x02, 0x06, 0x05, 0x41, 0x00, 0x04}; std::string frame = HttpEncoder::SerializeSettingsFrame(settings); quiche::test::CompareCharArraysWithHexError( "SETTINGS", frame.data(), frame.length(), output, ABSL_ARRAYSIZE(output)); } TEST(HttpEncoderTest, SerializeGoAwayFrame) { GoAwayFrame goaway; goaway.id = 0x1; char output[] = {0x07, 0x1, 0x01}; std::string frame = HttpEncoder::SerializeGoAwayFrame(goaway); quiche::test::CompareCharArraysWithHexError( "GOAWAY", frame.data(), frame.length(), output, ABSL_ARRAYSIZE(output)); } TEST(HttpEncoderTest, SerializePriorityUpdateFrame) { PriorityUpdateFrame priority_update1; priority_update1.prioritized_element_id = 0x03; uint8_t output1[] = {0x80, 0x0f, 0x07, 0x00, 0x01, 0x03}; std::string frame1 = HttpEncoder::SerializePriorityUpdateFrame(priority_update1); quiche::test::CompareCharArraysWithHexError( "PRIORITY_UPDATE", frame1.data(), frame1.length(), reinterpret_cast<char*>(output1), ABSL_ARRAYSIZE(output1)); PriorityUpdateFrame priority_update2; priority_update2.prioritized_element_id = 0x05; priority_update2.priority_field_value = "foo"; uint8_t output2[] = {0x80, 0x0f, 0x07, 0x00, 0x04, 0x05, 0x66, 0x6f, 0x6f}; std::string frame2 = HttpEncoder::SerializePriorityUpdateFrame(priority_update2); quiche::test::CompareCharArraysWithHexError( "PRIORITY_UPDATE", frame2.data(), frame2.length(), reinterpret_cast<char*>(output2), ABSL_ARRAYSIZE(output2)); } TEST(HttpEncoderTest, SerializeAcceptChFrame) { AcceptChFrame accept_ch; uint8_t output1[] = {0x40, 0x89, 0x00}; std::string frame1 = HttpEncoder::SerializeAcceptChFrame(accept_ch); quiche::test::CompareCharArraysWithHexError( "ACCEPT_CH", frame1.data(), frame1.length(), reinterpret_cast<char*>(output1), ABSL_ARRAYSIZE(output1)); accept_ch.entries.push_back({"foo", "bar"}); uint8_t output2[] = {0x40, 0x89, 0x08, 0x03, 0x66, 0x6f, 0x6f, 0x03, 0x62, 0x61, 0x72}; std::string frame2 = HttpEncoder::SerializeAcceptChFrame(accept_ch); quiche::test::CompareCharArraysWithHexError( "ACCEPT_CH", frame2.data(), frame2.length(), reinterpret_cast<char*>(output2), ABSL_ARRAYSIZE(output2)); } TEST(HttpEncoderTest, SerializeWebTransportStreamFrameHeader) { WebTransportSessionId session_id = 0x17; char output[] = {0x40, 0x41, 0x17}; std::string frame = HttpEncoder::SerializeWebTransportStreamFrameHeader(session_id); quiche::test::CompareCharArraysWithHexError("WEBTRANSPORT_STREAM", frame.data(), frame.length(), output, sizeof(output)); } TEST(HttpEncoderTest, SerializeMetadataFrameHeader) { std::string frame = HttpEncoder::SerializeMetadataFrameHeader( 7); char output[] = {0x40, 0x4d, 0x07}; quiche::test::CompareCharArraysWithHexError( "METADATA", frame.data(), frame.length(), output, ABSL_ARRAYSIZE(output)); } } }
307
cpp
google/quiche
quic_spdy_client_stream
quiche/quic/core/http/quic_spdy_client_stream.cc
quiche/quic/core/http/quic_spdy_client_stream_test.cc
#ifndef QUICHE_QUIC_CORE_HTTP_QUIC_SPDY_CLIENT_STREAM_H_ #define QUICHE_QUIC_CORE_HTTP_QUIC_SPDY_CLIENT_STREAM_H_ #include <cstddef> #include <list> #include <string> #include "absl/strings/string_view.h" #include "quiche/quic/core/http/quic_spdy_stream.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/spdy/core/http2_header_block.h" #include "quiche/spdy/core/spdy_framer.h" namespace quic { class QuicSpdyClientSession; class QUICHE_EXPORT QuicSpdyClientStream : public QuicSpdyStream { public: QuicSpdyClientStream(QuicStreamId id, QuicSpdyClientSession* session, StreamType type); QuicSpdyClientStream(PendingStream* pending, QuicSpdyClientSession* spdy_session); QuicSpdyClientStream(const QuicSpdyClientStream&) = delete; QuicSpdyClientStream& operator=(const QuicSpdyClientStream&) = delete; ~QuicSpdyClientStream() override; void OnInitialHeadersComplete(bool fin, size_t frame_len, const QuicHeaderList& header_list) override; void OnTrailingHeadersComplete(bool fin, size_t frame_len, const QuicHeaderList& header_list) override; void OnBodyAvailable() override; void OnFinRead() override; size_t SendRequest(spdy::Http2HeaderBlock headers, absl::string_view body, bool fin); absl::string_view data() const { return data_; } const spdy::Http2HeaderBlock& response_headers() { return response_headers_; } const std::list<spdy::Http2HeaderBlock>& preliminary_headers() { return preliminary_headers_; } size_t header_bytes_read() const { return header_bytes_read_; } size_t header_bytes_written() const { return header_bytes_written_; } int response_code() const { return response_code_; } QuicTime::Delta time_to_response_headers_received() const { return time_to_response_headers_received_; } QuicTime::Delta time_to_response_complete() const { return time_to_response_complete_; } using QuicSpdyStream::SetPriority; protected: bool ValidateReceivedHeaders(const QuicHeaderList& header_list) override; virtual bool CopyAndValidateHeaders(const QuicHeaderList& header_list, int64_t& content_length, spdy::Http2HeaderBlock& headers); virtual bool ParseAndValidateStatusCode(); bool uses_capsules() const override { return QuicSpdyStream::uses_capsules() && !capsules_failed_; } private: spdy::Http2HeaderBlock response_headers_; int64_t content_length_; int response_code_; bool capsules_failed_ = false; std::string data_; size_t header_bytes_read_; size_t header_bytes_written_; QuicSpdyClientSession* session_; std::list<spdy::Http2HeaderBlock> preliminary_headers_; QuicTime::Delta time_to_response_headers_received_ = QuicTime::Delta::Infinite(); QuicTime::Delta time_to_response_complete_ = QuicTime::Delta::Infinite(); }; } #endif #include "quiche/quic/core/http/quic_spdy_client_stream.h" #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/http/quic_spdy_client_session.h" #include "quiche/quic/core/http/spdy_utils.h" #include "quiche/quic/core/http/web_transport_http3.h" #include "quiche/quic/core/quic_alarm.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/common/platform/api/quiche_flag_utils.h" #include "quiche/common/quiche_text_utils.h" #include "quiche/spdy/core/spdy_protocol.h" using spdy::Http2HeaderBlock; namespace quic { QuicSpdyClientStream::QuicSpdyClientStream(QuicStreamId id, QuicSpdyClientSession* session, StreamType type) : QuicSpdyStream(id, session, type), content_length_(-1), response_code_(0), header_bytes_read_(0), header_bytes_written_(0), session_(session) {} QuicSpdyClientStream::QuicSpdyClientStream(PendingStream* pending, QuicSpdyClientSession* session) : QuicSpdyStream(pending, session), content_length_(-1), response_code_(0), header_bytes_read_(0), header_bytes_written_(0), session_(session) {} QuicSpdyClientStream::~QuicSpdyClientStream() = default; bool QuicSpdyClientStream::CopyAndValidateHeaders( const QuicHeaderList& header_list, int64_t& content_length, spdy::Http2HeaderBlock& headers) { return SpdyUtils::CopyAndValidateHeaders(header_list, &content_length, &headers); } bool QuicSpdyClientStream::ParseAndValidateStatusCode() { if (!ParseHeaderStatusCode(response_headers_, &response_code_)) { QUIC_DLOG(ERROR) << "Received invalid response code: " << response_headers_[":status"].as_string() << " on stream " << id(); Reset(QUIC_BAD_APPLICATION_PAYLOAD); return false; } if (response_code_ == 101) { QUIC_DLOG(ERROR) << "Received forbidden 101 response code" << " on stream " << id(); Reset(QUIC_BAD_APPLICATION_PAYLOAD); return false; } if (response_code_ >= 100 && response_code_ < 200) { QUIC_DLOG(INFO) << "Received informational response code: " << response_headers_[":status"].as_string() << " on stream " << id(); set_headers_decompressed(false); preliminary_headers_.push_back(std::move(response_headers_)); } return true; } void QuicSpdyClientStream::OnInitialHeadersComplete( bool fin, size_t frame_len, const QuicHeaderList& header_list) { QuicSpdyStream::OnInitialHeadersComplete(fin, frame_len, header_list); time_to_response_headers_received_ = session()->GetClock()->ApproximateNow() - creation_time(); QUICHE_DCHECK(headers_decompressed()); header_bytes_read_ += frame_len; if (rst_sent()) { return; } if (!CopyAndValidateHeaders(header_list, content_length_, response_headers_)) { QUIC_DLOG(ERROR) << "Failed to parse header list: " << header_list.DebugString() << " on stream " << id(); Reset(QUIC_BAD_APPLICATION_PAYLOAD); return; } if (web_transport() != nullptr) { web_transport()->HeadersReceived(response_headers_); if (!web_transport()->ready()) { Reset(QUIC_STREAM_CANCELLED); return; } } if (!ParseAndValidateStatusCode()) { return; } if (uses_capsules() && (response_code_ < 200 || response_code_ >= 300)) { capsules_failed_ = true; } ConsumeHeaderList(); QUIC_DVLOG(1) << "headers complete for stream " << id(); } void QuicSpdyClientStream::OnTrailingHeadersComplete( bool fin, size_t frame_len, const QuicHeaderList& header_list) { QuicSpdyStream::OnTrailingHeadersComplete(fin, frame_len, header_list); MarkTrailersConsumed(); } void QuicSpdyClientStream::OnBodyAvailable() { while (HasBytesToRead()) { struct iovec iov; if (GetReadableRegions(&iov, 1) == 0) { break; } QUIC_DVLOG(1) << "Client processed " << iov.iov_len << " bytes for stream " << id(); data_.append(static_cast<char*>(iov.iov_base), iov.iov_len); if (content_length_ >= 0 && data_.size() > static_cast<uint64_t>(content_length_)) { QUIC_DLOG(ERROR) << "Invalid content length (" << content_length_ << ") with data of size " << data_.size(); Reset(QUIC_BAD_APPLICATION_PAYLOAD); return; } MarkConsumed(iov.iov_len); } if (sequencer()->IsClosed()) { OnFinRead(); } else { sequencer()->SetUnblocked(); } } size_t QuicSpdyClientStream::SendRequest(Http2HeaderBlock headers, absl::string_view body, bool fin) { QuicConnection::ScopedPacketFlusher flusher(session_->connection()); bool send_fin_with_headers = fin && body.empty(); size_t bytes_sent = body.size(); header_bytes_written_ = WriteHeaders(std::move(headers), send_fin_with_headers, nullptr); bytes_sent += header_bytes_written_; if (!body.empty()) { WriteOrBufferBody(body, fin); } return bytes_sent; } bool QuicSpdyClientStream::ValidateReceivedHeaders( const QuicHeaderList& header_list) { if (!QuicSpdyStream::ValidateReceivedHeaders(header_list)) { return false; } bool saw_status = false; for (const std::pair<std::string, std::string>& pair : header_list) { if (pair.first == ":status") { saw_status = true; } else if (absl::StrContains(pair.first, ":")) { set_invalid_request_details( absl::StrCat("Unexpected ':' in header ", pair.first, ".")); QUIC_DLOG(ERROR) << invalid_request_details(); return false; } } if (!saw_status) { set_invalid_request_details("Missing :status in response header."); QUIC_DLOG(ERROR) << invalid_request_details(); return false; } return saw_status; } void QuicSpdyClientStream::OnFinRead() { time_to_response_complete_ = session()->GetClock()->ApproximateNow() - creation_time(); QuicSpdyStream::OnFinRead(); } }
#include "quiche/quic/core/http/quic_spdy_client_stream.h" #include <memory> #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/http/quic_spdy_client_session.h" #include "quiche/quic/core/http/spdy_utils.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/crypto_test_utils.h" #include "quiche/quic/test_tools/quic_spdy_session_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/simple_buffer_allocator.h" using spdy::Http2HeaderBlock; using testing::_; using testing::ElementsAre; using testing::StrictMock; namespace quic { namespace test { namespace { class MockQuicSpdyClientSession : public QuicSpdyClientSession { public: explicit MockQuicSpdyClientSession( const ParsedQuicVersionVector& supported_versions, QuicConnection* connection) : QuicSpdyClientSession( DefaultQuicConfig(), supported_versions, connection, QuicServerId("example.com", 443, false), &crypto_config_), crypto_config_(crypto_test_utils::ProofVerifierForTesting()) {} MockQuicSpdyClientSession(const MockQuicSpdyClientSession&) = delete; MockQuicSpdyClientSession& operator=(const MockQuicSpdyClientSession&) = delete; ~MockQuicSpdyClientSession() override = default; MOCK_METHOD(bool, WriteControlFrame, (const QuicFrame& frame, TransmissionType type), (override)); using QuicSession::ActivateStream; private: QuicCryptoClientConfig crypto_config_; }; class QuicSpdyClientStreamTest : public QuicTestWithParam<ParsedQuicVersion> { public: class StreamVisitor; QuicSpdyClientStreamTest() : connection_(new StrictMock<MockQuicConnection>( &helper_, &alarm_factory_, Perspective::IS_CLIENT, SupportedVersions(GetParam()))), session_(connection_->supported_versions(), connection_), body_("hello world") { session_.Initialize(); connection_->AdvanceTime(QuicTime::Delta::FromSeconds(1)); connection_->SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(connection_->perspective())); headers_[":status"] = "200"; headers_["content-length"] = "11"; auto stream = std::make_unique<QuicSpdyClientStream>( GetNthClientInitiatedBidirectionalStreamId( connection_->transport_version(), 0), &session_, BIDIRECTIONAL); stream_ = stream.get(); session_.ActivateStream(std::move(stream)); stream_visitor_ = std::make_unique<StreamVisitor>(); stream_->set_visitor(stream_visitor_.get()); } class StreamVisitor : public QuicSpdyClientStream::Visitor { void OnClose(QuicSpdyStream* stream) override { QUIC_DVLOG(1) << "stream " << stream->id(); } }; MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; StrictMock<MockQuicConnection>* connection_; MockQuicSpdyClientSession session_; QuicSpdyClientStream* stream_; std::unique_ptr<StreamVisitor> stream_visitor_; Http2HeaderBlock headers_; std::string body_; }; INSTANTIATE_TEST_SUITE_P(Tests, QuicSpdyClientStreamTest, ::testing::ValuesIn(AllSupportedVersions()), ::testing::PrintToStringParamName()); TEST_P(QuicSpdyClientStreamTest, TestReceivingIllegalResponseStatusCode) { headers_[":status"] = "200 ok"; EXPECT_CALL(session_, WriteControlFrame(_, _)); EXPECT_CALL(*connection_, OnStreamReset(stream_->id(), QUIC_BAD_APPLICATION_PAYLOAD)); auto headers = AsHeaderList(headers_); stream_->OnStreamHeaderList(false, headers.uncompressed_header_bytes(), headers); EXPECT_THAT(stream_->stream_error(), IsStreamError(QUIC_BAD_APPLICATION_PAYLOAD)); EXPECT_EQ(stream_->ietf_application_error(), static_cast<uint64_t>(QuicHttp3ErrorCode::GENERAL_PROTOCOL_ERROR)); } TEST_P(QuicSpdyClientStreamTest, InvalidResponseHeader) { SetQuicReloadableFlag(quic_act_upon_invalid_header, true); auto headers = AsHeaderList(std::vector<std::pair<std::string, std::string>>{ {":status", "200"}, {":path", "/foo"}}); EXPECT_CALL(*connection_, OnStreamReset(stream_->id(), QUIC_BAD_APPLICATION_PAYLOAD)); stream_->OnStreamHeaderList(false, headers.uncompressed_header_bytes(), headers); EXPECT_THAT(stream_->stream_error(), IsStreamError(QUIC_BAD_APPLICATION_PAYLOAD)); EXPECT_EQ(stream_->ietf_application_error(), static_cast<uint64_t>(QuicHttp3ErrorCode::GENERAL_PROTOCOL_ERROR)); } TEST_P(QuicSpdyClientStreamTest, MissingStatusCode) { SetQuicReloadableFlag(quic_act_upon_invalid_header, true); auto headers = AsHeaderList( std::vector<std::pair<std::string, std::string>>{{"key", "value"}}); EXPECT_CALL(*connection_, OnStreamReset(stream_->id(), QUIC_BAD_APPLICATION_PAYLOAD)); stream_->OnStreamHeaderList(false, headers.uncompressed_header_bytes(), headers); EXPECT_THAT(stream_->stream_error(), IsStreamError(QUIC_BAD_APPLICATION_PAYLOAD)); EXPECT_EQ(stream_->ietf_application_error(), static_cast<uint64_t>(QuicHttp3ErrorCode::GENERAL_PROTOCOL_ERROR)); } TEST_P(QuicSpdyClientStreamTest, TestFraming) { auto headers = AsHeaderList(headers_); stream_->OnStreamHeaderList(false, headers.uncompressed_header_bytes(), headers); quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader( body_.length(), quiche::SimpleBufferAllocator::Get()); std::string data = VersionUsesHttp3(connection_->transport_version()) ? absl::StrCat(header.AsStringView(), body_) : body_; stream_->OnStreamFrame( QuicStreamFrame(stream_->id(), false, 0, data)); EXPECT_EQ("200", stream_->response_headers().find(":status")->second); EXPECT_EQ(200, stream_->response_code()); EXPECT_EQ(body_, stream_->data()); } TEST_P(QuicSpdyClientStreamTest, HostAllowedInResponseHeader) { SetQuicReloadableFlag(quic_act_upon_invalid_header, true); auto headers = AsHeaderList(std::vector<std::pair<std::string, std::string>>{ {":status", "200"}, {"host", "example.com"}}); EXPECT_CALL(*connection_, OnStreamReset(stream_->id(), _)).Times(0u); stream_->OnStreamHeaderList(false, headers.uncompressed_header_bytes(), headers); EXPECT_THAT(stream_->stream_error(), IsStreamError(QUIC_STREAM_NO_ERROR)); EXPECT_EQ(stream_->ietf_application_error(), static_cast<uint64_t>(QuicHttp3ErrorCode::HTTP3_NO_ERROR)); } TEST_P(QuicSpdyClientStreamTest, Test100ContinueBeforeSuccessful) { headers_[":status"] = "100"; auto headers = AsHeaderList(headers_); stream_->OnStreamHeaderList(false, headers.uncompressed_header_bytes(), headers); ASSERT_EQ(stream_->preliminary_headers().size(), 1); EXPECT_EQ("100", stream_->preliminary_headers().front().find(":status")->second); EXPECT_EQ(0u, stream_->response_headers().size()); EXPECT_EQ(100, stream_->response_code()); EXPECT_EQ("", stream_->data()); headers_[":status"] = "200"; headers = AsHeaderList(headers_); stream_->OnStreamHeaderList(false, headers.uncompressed_header_bytes(), headers); quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader( body_.length(), quiche::SimpleBufferAllocator::Get()); std::string data = VersionUsesHttp3(connection_->transport_version()) ? absl::StrCat(header.AsStringView(), body_) : body_; stream_->OnStreamFrame( QuicStreamFrame(stream_->id(), false, 0, data)); EXPECT_EQ("200", stream_->response_headers().find(":status")->second); EXPECT_EQ(200, stream_->response_code()); EXPECT_EQ(body_, stream_->data()); ASSERT_EQ(stream_->preliminary_headers().size(), 1); EXPECT_EQ("100", stream_->preliminary_headers().front().find(":status")->second); } TEST_P(QuicSpdyClientStreamTest, TestUnknownInformationalBeforeSuccessful) { headers_[":status"] = "199"; auto headers = AsHeaderList(headers_); stream_->OnStreamHeaderList(false, headers.uncompressed_header_bytes(), headers); ASSERT_EQ(stream_->preliminary_headers().size(), 1); EXPECT_EQ("199", stream_->preliminary_headers().front().find(":status")->second); EXPECT_EQ(0u, stream_->response_headers().size()); EXPECT_EQ(199, stream_->response_code()); EXPECT_EQ("", stream_->data()); headers_[":status"] = "200"; headers = AsHeaderList(headers_); stream_->OnStreamHeaderList(false, headers.uncompressed_header_bytes(), headers); quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader( body_.length(), quiche::SimpleBufferAllocator::Get()); std::string data = VersionUsesHttp3(connection_->transport_version()) ? absl::StrCat(header.AsStringView(), body_) : body_; stream_->OnStreamFrame( QuicStreamFrame(stream_->id(), false, 0, data)); EXPECT_EQ("200", stream_->response_headers().find(":status")->second); EXPECT_EQ(200, stream_->response_code()); EXPECT_EQ(body_, stream_->data()); ASSERT_EQ(stream_->preliminary_headers().size(), 1); EXPECT_EQ("199", stream_->preliminary_headers().front().find(":status")->second); } TEST_P(QuicSpdyClientStreamTest, TestMultipleInformationalBeforeSuccessful) { headers_[":status"] = "100"; auto headers = AsHeaderList(headers_); stream_->OnStreamHeaderList(false, headers.uncompressed_header_bytes(), headers); ASSERT_EQ(stream_->preliminary_headers().size(), 1); EXPECT_EQ("100", stream_->preliminary_headers().front().find(":status")->second); EXPECT_EQ(0u, stream_->response_headers().size()); EXPECT_EQ(100, stream_->response_code()); EXPECT_EQ("", stream_->data()); headers_[":status"] = "199"; headers = AsHeaderList(headers_); stream_->OnStreamHeaderList(false, headers.uncompressed_header_bytes(), headers); ASSERT_EQ(stream_->preliminary_headers().size(), 2); EXPECT_EQ("100", stream_->preliminary_headers().front().find(":status")->second); EXPECT_EQ("199", stream_->preliminary_headers().back().find(":status")->second); EXPECT_EQ(0u, stream_->response_headers().size()); EXPECT_EQ(199, stream_->response_code()); EXPECT_EQ("", stream_->data()); headers_[":status"] = "200"; headers = AsHeaderList(headers_); stream_->OnStreamHeaderList(false, headers.uncompressed_header_bytes(), headers); quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader( body_.length(), quiche::SimpleBufferAllocator::Get()); std::string data = VersionUsesHttp3(connection_->transport_version()) ? absl::StrCat(header.AsStringView(), body_) : body_; stream_->OnStreamFrame( QuicStreamFrame(stream_->id(), false, 0, data)); EXPECT_EQ("200", stream_->response_headers().find(":status")->second); EXPECT_EQ(200, stream_->response_code()); EXPECT_EQ(body_, stream_->data()); ASSERT_EQ(stream_->preliminary_headers().size(), 2); EXPECT_EQ("100", stream_->preliminary_headers().front().find(":status")->second); EXPECT_EQ("199", stream_->preliminary_headers().back().find(":status")->second); } TEST_P(QuicSpdyClientStreamTest, TestReceiving101) { headers_[":status"] = "101"; EXPECT_CALL(session_, WriteControlFrame(_, _)); EXPECT_CALL(*connection_, OnStreamReset(stream_->id(), QUIC_BAD_APPLICATION_PAYLOAD)); auto headers = AsHeaderList(headers_); stream_->OnStreamHeaderList(false, headers.uncompressed_header_bytes(), headers); EXPECT_THAT(stream_->stream_error(), IsStreamError(QUIC_BAD_APPLICATION_PAYLOAD)); } TEST_P(QuicSpdyClientStreamTest, TestFramingOnePacket) { auto headers = AsHeaderList(headers_); stream_->OnStreamHeaderList(false, headers.uncompressed_header_bytes(), headers); quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader( body_.length(), quiche::SimpleBufferAllocator::Get()); std::string data = VersionUsesHttp3(connection_->transport_version()) ? absl::StrCat(header.AsStringView(), body_) : body_; stream_->OnStreamFrame( QuicStreamFrame(stream_->id(), false, 0, data)); EXPECT_EQ("200", stream_->response_headers().find(":status")->second); EXPECT_EQ(200, stream_->response_code()); EXPECT_EQ(body_, stream_->data()); } TEST_P(QuicSpdyClientStreamTest, QUIC_TEST_DISABLED_IN_CHROME(TestFramingExtraData)) { std::string large_body = "hello world!!!!!!"; auto headers = AsHeaderList(headers_); stream_->OnStreamHeaderList(false, headers.uncompressed_header_bytes(), headers); EXPECT_THAT(stream_->stream_error(), IsQuicStreamNoError()); EXPECT_EQ("200", stream_->response_headers().find(":status")->second); EXPECT_EQ(200, stream_->response_code()); quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader( large_body.length(), quiche::SimpleBufferAllocator::Get()); std::string data = VersionUsesHttp3(connection_->transport_version()) ? absl::StrCat(header.AsStringView(), large_body) : large_body; EXPECT_CALL(session_, WriteControlFrame(_, _)); EXPECT_CALL(*connection_, OnStreamReset(stream_->id(), QUIC_BAD_APPLICATION_PAYLOAD)); stream_->OnStreamFrame( QuicStreamFrame(stream_->id(), false, 0, data)); EXPECT_NE(QUIC_STREAM_NO_ERROR, stream_->stream_error()); EXPECT_EQ(stream_->ietf_application_error(), static_cast<uint64_t>(QuicHttp3ErrorCode::GENERAL_PROTOCOL_ERROR)); } TEST_P(QuicSpdyClientStreamTest, ReceivingTrailers) { if (VersionUsesHttp3(connection_->transport_version())) { return; } auto headers = AsHeaderList(headers_); stream_->OnStreamHeaderList(false, headers.uncompressed_header_bytes(), headers); Http2HeaderBlock trailer_block; trailer_block["trailer key"] = "trailer value"; trailer_block[kFinalOffsetHeaderKey] = absl::StrCat(body_.size()); auto trailers = AsHeaderList(trailer_block); stream_->OnStreamHeaderList(true, trailers.uncompressed_header_bytes(), trailers); quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader( body_.length(), quiche::SimpleBufferAllocator::Get()); std::string data = VersionUsesHttp3(connection_->transport_version()) ? absl::StrCat(header.AsStringView(), body_) : body_; stream_->OnStreamFrame( QuicStreamFrame(stream_->id(), false, 0, data)); EXPECT_TRUE(stream_->reading_stopped()); } TEST_P(QuicSpdyClientStreamTest, Capsules) { if (!VersionUsesHttp3(connection_->transport_version())) { return; } SavingHttp3DatagramVisitor h3_datagram_visitor; stream_->RegisterHttp3DatagramVisitor(&h3_datagram_visitor); headers_.erase("content-length"); auto headers = AsHeaderList(headers_); stream_->OnStreamHeaderList(false, headers.uncompressed_header_bytes(), headers); std::string capsule_data = {0, 6, 1, 2, 3, 4, 5, 6, 0x17, 4, 1, 2, 3, 4}; quiche::QuicheBuffer data_frame_header = HttpEncoder::SerializeDataFrameHeader( capsule_data.length(), quiche::SimpleBufferAllocator::Get()); std::string stream_data = absl::StrCat(data_frame_header.AsStringView(), capsule_data); stream_->OnStreamFrame( QuicStreamFrame(stream_->id(), false, 0, stream_data)); std::string http_datagram_payload = {1, 2, 3, 4, 5, 6}; EXPECT_THAT(h3_datagram_visitor.received_h3_datagrams(), ElementsAre(SavingHttp3DatagramVisitor::SavedHttp3Datagram{ stream_->id(), http_datagram_payload})); uint64_t capsule_type = 0x17u; std::string unknown_capsule_payload = {1, 2, 3, 4}; EXPECT_THAT(h3_datagram_visitor.received_unknown_capsules(), ElementsAre(SavingHttp3DatagramVisitor::SavedUnknownCapsule{ stream_->id(), capsule_type, unknown_capsule_payload})); stream_->UnregisterHttp3DatagramVisitor(); } TEST_P(QuicSpdyClientStreamTest, CapsulesOnUnsuccessfulResponse) { if (!VersionUsesHttp3(connection_->transport_version())) { return; } SavingHttp3DatagramVisitor h3_datagram_visitor; stream_->RegisterHttp3DatagramVisitor(&h3_datagram_visitor); headers_[":status"] = "401"; headers_.erase("content-length"); auto headers = AsHeaderList(headers_); stream_->OnStreamHeaderList(false, headers.uncompressed_header_bytes(), headers); std::string capsule_data = {0, 6, 1, 2, 3, 4, 5, 6, 0x17, 4, 1, 2, 3, 4}; quiche::QuicheBuffer data_frame_header = HttpEncoder::SerializeDataFrameHeader( capsule_data.length(), quiche::SimpleBufferAllocator::Get()); std::string stream_data = absl::StrCat(data_frame_header.AsStringView(), capsule_data); stream_->OnStreamFrame( QuicStreamFrame(stream_->id(), false, 0, stream_data)); EXPECT_TRUE(h3_datagram_visitor.received_h3_datagrams().empty()); EXPECT_TRUE(h3_datagram_visitor.received_unknown_capsules().empty()); stream_->UnregisterHttp3DatagramVisitor(); } } } }
308
cpp
google/quiche
quic_spdy_session
quiche/quic/core/http/quic_spdy_session.cc
quiche/quic/core/http/quic_spdy_session_test.cc
#ifndef QUICHE_QUIC_CORE_HTTP_QUIC_SPDY_SESSION_H_ #define QUICHE_QUIC_CORE_HTTP_QUIC_SPDY_SESSION_H_ #include <cstddef> #include <cstdint> #include <list> #include <memory> #include <optional> #include <string> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/http/http_frames.h" #include "quiche/quic/core/http/quic_header_list.h" #include "quiche/quic/core/http/quic_headers_stream.h" #include "quiche/quic/core/http/quic_receive_control_stream.h" #include "quiche/quic/core/http/quic_send_control_stream.h" #include "quiche/quic/core/http/quic_spdy_stream.h" #include "quiche/quic/core/qpack/qpack_decoder.h" #include "quiche/quic/core/qpack/qpack_encoder.h" #include "quiche/quic/core/qpack/qpack_receive_stream.h" #include "quiche/quic/core/qpack/qpack_send_stream.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_stream_priority.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/spdy/core/http2_frame_decoder_adapter.h" #include "quiche/spdy/core/http2_header_block.h" namespace quic { namespace test { class QuicSpdySessionPeer; } class WebTransportHttp3UnidirectionalStream; QUICHE_EXPORT extern const size_t kMaxUnassociatedWebTransportStreams; class QUICHE_EXPORT Http3DebugVisitor { public: Http3DebugVisitor(); Http3DebugVisitor(const Http3DebugVisitor&) = delete; Http3DebugVisitor& operator=(const Http3DebugVisitor&) = delete; virtual ~Http3DebugVisitor(); virtual void OnControlStreamCreated(QuicStreamId ) = 0; virtual void OnQpackEncoderStreamCreated(QuicStreamId ) = 0; virtual void OnQpackDecoderStreamCreated(QuicStreamId ) = 0; virtual void OnPeerControlStreamCreated(QuicStreamId ) = 0; virtual void OnPeerQpackEncoderStreamCreated(QuicStreamId ) = 0; virtual void OnPeerQpackDecoderStreamCreated(QuicStreamId ) = 0; virtual void OnSettingsFrameReceivedViaAlps(const SettingsFrame& ) {} virtual void OnAcceptChFrameReceivedViaAlps(const AcceptChFrame& ) {} virtual void OnSettingsFrameReceived(const SettingsFrame& ) = 0; virtual void OnGoAwayFrameReceived(const GoAwayFrame& ) = 0; virtual void OnPriorityUpdateFrameReceived( const PriorityUpdateFrame& ) = 0; virtual void OnAcceptChFrameReceived(const AcceptChFrame& ) {} virtual void OnDataFrameReceived(QuicStreamId , QuicByteCount ) = 0; virtual void OnHeadersFrameReceived( QuicStreamId , QuicByteCount ) = 0; virtual void OnHeadersDecoded(QuicStreamId , QuicHeaderList ) = 0; virtual void OnUnknownFrameReceived(QuicStreamId , uint64_t , QuicByteCount ) = 0; virtual void OnSettingsFrameSent(const SettingsFrame& ) = 0; virtual void OnGoAwayFrameSent(QuicStreamId ) = 0; virtual void OnPriorityUpdateFrameSent( const PriorityUpdateFrame& ) = 0; virtual void OnDataFrameSent(QuicStreamId , QuicByteCount ) = 0; virtual void OnHeadersFrameSent( QuicStreamId , const spdy::Http2HeaderBlock& ) = 0; virtual void OnSettingsFrameResumed(const SettingsFrame& ) = 0; }; enum class HttpDatagramSupport : uint8_t { kNone, kDraft04, kRfc, kRfcAndDraft04, }; enum class WebTransportHttp3Version : uint8_t { kDraft02, kDraft07, }; using WebTransportHttp3VersionSet = BitMask<WebTransportHttp3Version, uint8_t>; inline constexpr WebTransportHttp3VersionSet kDefaultSupportedWebTransportVersions = WebTransportHttp3VersionSet({WebTransportHttp3Version::kDraft02, WebTransportHttp3Version::kDraft07}); QUICHE_EXPORT std::string HttpDatagramSupportToString( HttpDatagramSupport http_datagram_support); QUICHE_EXPORT std::ostream& operator<<( std::ostream& os, const HttpDatagramSupport& http_datagram_support); class QUICHE_EXPORT QuicSpdySession : public QuicSession, public QpackEncoder::DecoderStreamErrorDelegate, public QpackDecoder::EncoderStreamErrorDelegate { public: QuicSpdySession(QuicConnection* connection, QuicSession::Visitor* visitor, const QuicConfig& config, const ParsedQuicVersionVector& supported_versions); QuicSpdySession(const QuicSpdySession&) = delete; QuicSpdySession& operator=(const QuicSpdySession&) = delete; ~QuicSpdySession() override; void Initialize() override; void OnDecoderStreamError(QuicErrorCode error_code, absl::string_view error_message) override; void OnEncoderStreamError(QuicErrorCode error_code, absl::string_view error_message) override; virtual void OnStreamHeadersPriority( QuicStreamId stream_id, const spdy::SpdyStreamPrecedence& precedence); virtual void OnStreamHeaderList(QuicStreamId stream_id, bool fin, size_t frame_len, const QuicHeaderList& header_list); virtual void OnPriorityFrame(QuicStreamId stream_id, const spdy::SpdyStreamPrecedence& precedence); bool OnPriorityUpdateForRequestStream(QuicStreamId stream_id, HttpStreamPriority priority); virtual void OnAcceptChFrame(const AcceptChFrame& ) {} virtual void OnUnknownFrameStart(QuicStreamId , uint64_t , QuicByteCount , QuicByteCount ) {} virtual void OnUnknownFramePayload(QuicStreamId , absl::string_view ) {} size_t ProcessHeaderData(const struct iovec& iov); virtual size_t WriteHeadersOnHeadersStream( QuicStreamId id, spdy::Http2HeaderBlock headers, bool fin, const spdy::SpdyStreamPrecedence& precedence, quiche::QuicheReferenceCountedPointer<QuicAckListenerInterface> ack_listener); size_t WritePriority(QuicStreamId stream_id, QuicStreamId parent_stream_id, int weight, bool exclusive); void WriteHttp3PriorityUpdate(QuicStreamId stream_id, HttpStreamPriority priority); virtual void OnHttp3GoAway(uint64_t id); bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) override; void SendHttp3GoAway(QuicErrorCode error_code, const std::string& reason); QpackEncoder* qpack_encoder(); QpackDecoder* qpack_decoder(); QuicHeadersStream* headers_stream() { return headers_stream_; } const QuicHeadersStream* headers_stream() const { return headers_stream_; } virtual bool OnSettingsFrame(const SettingsFrame& frame); std::optional<std::string> OnSettingsFrameViaAlps(const SettingsFrame& frame); bool OnSetting(uint64_t id, uint64_t value); virtual bool ShouldReleaseHeadersStreamSequencerBuffer(); void CloseConnectionWithDetails(QuicErrorCode error, const std::string& details); void set_qpack_maximum_dynamic_table_capacity( uint64_t qpack_maximum_dynamic_table_capacity) { qpack_maximum_dynamic_table_capacity_ = qpack_maximum_dynamic_table_capacity; } uint64_t qpack_maximum_dynamic_table_capacity() const { return qpack_maximum_dynamic_table_capacity_; } void set_qpack_maximum_blocked_streams( uint64_t qpack_maximum_blocked_streams) { qpack_maximum_blocked_streams_ = qpack_maximum_blocked_streams; } void set_max_inbound_header_list_size(size_t max_inbound_header_list_size) { max_inbound_header_list_size_ = max_inbound_header_list_size; } void set_allow_extended_connect(bool allow_extended_connect); size_t max_outbound_header_list_size() const { return max_outbound_header_list_size_; } size_t max_inbound_header_list_size() const { return max_inbound_header_list_size_; } bool allow_extended_connect() const { return allow_extended_connect_; } bool HasActiveRequestStreams() const; void OnCompressedFrameSize(size_t frame_len); void OnHeaderList(const QuicHeaderList& header_list); void OnCanCreateNewOutgoingStream(bool unidirectional) override; int32_t destruction_indicator() const { return destruction_indicator_; } void set_debug_visitor(Http3DebugVisitor* debug_visitor) { debug_visitor_ = debug_visitor; } Http3DebugVisitor* debug_visitor() { return debug_visitor_; } bool goaway_received() const; bool goaway_sent() const; std::optional<uint64_t> last_received_http3_goaway_id() { return last_received_http3_goaway_id_; } static void LogHeaderCompressionRatioHistogram(bool using_qpack, bool is_sent, QuicByteCount compressed, QuicByteCount uncompressed); bool dynamic_table_entry_referenced() const { return (qpack_encoder_ && qpack_encoder_->dynamic_table_entry_referenced()) || (qpack_decoder_ && qpack_decoder_->dynamic_table_entry_referenced()); } void OnStreamCreated(QuicSpdyStream* stream); bool ResumeApplicationState(ApplicationState* cached_state) override; std::optional<std::string> OnAlpsData(const uint8_t* alps_data, size_t alps_length) override; virtual void OnAcceptChFrameReceivedViaAlps(const AcceptChFrame& ); HttpDatagramSupport http_datagram_support() const { return http_datagram_support_; } MessageStatus SendHttp3Datagram(QuicStreamId stream_id, absl::string_view payload); void SetMaxDatagramTimeInQueueForStreamId(QuicStreamId stream_id, QuicTime::Delta max_time_in_queue); void OnMessageReceived(absl::string_view message) override; bool SupportsWebTransport(); std::optional<WebTransportHttp3Version> SupportedWebTransportVersion(); bool SupportsH3Datagram() const; bool WillNegotiateWebTransport(); WebTransportHttp3* GetWebTransportSession(WebTransportSessionId id); bool ShouldBufferRequestsUntilSettings() { return version().UsesHttp3() && perspective() == Perspective::IS_SERVER && (ShouldNegotiateWebTransport() || LocalHttpDatagramSupport() == HttpDatagramSupport::kRfcAndDraft04 || force_buffer_requests_until_settings_); } bool ShouldProcessIncomingRequests(); void OnStreamWaitingForClientSettings(QuicStreamId id); void AssociateIncomingWebTransportStreamWithSession( WebTransportSessionId session_id, QuicStreamId stream_id); void ProcessBufferedWebTransportStreamsForSession(WebTransportHttp3* session); bool CanOpenOutgoingUnidirectionalWebTransportStream( WebTransportSessionId ) { return CanOpenNextOutgoingUnidirectionalStream(); } bool CanOpenOutgoingBidirectionalWebTransportStream( WebTransportSessionId ) { return CanOpenNextOutgoingBidirectionalStream(); } WebTransportHttp3UnidirectionalStream* CreateOutgoingUnidirectionalWebTransportStream(WebTransportHttp3* session); QuicSpdyStream* CreateOutgoingBidirectionalWebTransportStream( WebTransportHttp3* session); QuicSpdyStream* GetOrCreateSpdyDataStream(const QuicStreamId stream_id); QpackReceiveStream* GetQpackEncoderReceiveStream() const { return qpack_encoder_receive_stream_; } void OnConfigNegotiated() override; bool settings_received() const { return settings_received_; } protected: QuicSpdyStream* CreateIncomingStream(QuicStreamId id) override = 0; QuicSpdyStream* CreateIncomingStream(PendingStream* pending) override = 0; virtual QuicSpdyStream* CreateOutgoingBidirectionalStream() = 0; virtual QuicSpdyStream* CreateOutgoingUnidirectionalStream() = 0; virtual bool ShouldCreateIncomingStream(QuicStreamId id) = 0; virtual bool ShouldCreateOutgoingBidirectionalStream() = 0; virtual bool ShouldCreateOutgoingUnidirectionalStream() = 0; virtual WebTransportHttp3VersionSet LocallySupportedWebTransportVersions() const; bool ShouldNegotiateWebTransport() const; bool ShouldKeepConnectionAlive() const override; bool UsesPendingStreamForFrame(QuicFrameType type, QuicStreamId stream_id) const override; QuicStream* ProcessReadUnidirectionalPendingStream( PendingStream* pending) override; size_t WriteHeadersOnHeadersStreamImpl( QuicStreamId id, spdy::Http2HeaderBlock headers, bool fin, QuicStreamId parent_stream_id, int weight, bool exclusive, quiche::QuicheReferenceCountedPointer<QuicAckListenerInterface> ack_listener); void OnNewEncryptionKeyAvailable( EncryptionLevel level, std::unique_ptr<QuicEncrypter> encrypter) override; void UpdateHeaderEncoderTableSize(uint32_t value); bool IsConnected() { return connection()->connected(); } const QuicReceiveControlStream* receive_control_stream() const { return receive_control_stream_; } const SettingsFrame& settings() const { return settings_; } virtual void MaybeInitializeHttp3UnidirectionalStreams(); void BeforeConnectionCloseSent() override; void MaybeBundleOpportunistically() override; virtual void OnDatagramProcessed(std::optional<MessageStatus> status); virtual HttpDatagramSupport LocalHttpDatagramSupport(); void SendInitialData(); bool CheckStreamWriteBlocked(QuicStream* stream) const override; void DisableHuffmanEncoding() { huffman_encoding_ = HuffmanEncoding::kDisabled; } private: friend class test::QuicSpdySessionPeer; class SpdyFramerVisitor; class QUICHE_EXPORT DatagramObserver : public QuicDatagramQueue::Observer { public: explicit DatagramObserver(QuicSpdySession* session) : session_(session) {} void OnDatagramProcessed(std::optional<MessageStatus> status) override; private: QuicSpdySession* session_; }; struct QUICHE_EXPORT BufferedWebTransportStream { WebTransportSessionId session_id; QuicStreamId stream_id; }; void OnHeaders(spdy::SpdyStreamId stream_id, bool has_priority, const spdy::SpdyStreamPrecedence& precedence, bool fin); void OnPriority(spdy::SpdyStreamId stream_id, const spdy::SpdyStreamPrecedence& precedence); void CloseConnectionOnDuplicateHttp3UnidirectionalStreams( absl::string_view type); void FillSettingsFrame(); bool VerifySettingIsZeroOrOne(uint64_t id, uint64_t value); std::optional<WebTransportHttp3Version> NegotiatedWebTransportVersion() const { return (LocallySupportedWebTransportVersions() & peer_web_transport_versions_) .Max(); } bool ValidateWebTransportSettingsConsistency(); HuffmanEncoding huffman_encoding_ = HuffmanEncoding::kEnabled; std::unique_ptr<QpackEncoder> qpack_encoder_; std::unique_ptr<QpackDecoder> qpack_decoder_; QuicHeadersStream* headers_stream_; QuicSendControlStream* send_control_stream_; QuicReceiveControlStream* receive_control_stream_; QpackReceiveStream* qpack_encoder_receive_stream_; QpackReceiveStream* qpack_decoder_receive_stream_; QpackSendStream* qpack_encoder_send_stream_; QpackSendStream* qpack_decoder_send_stream_; SettingsFrame settings_; uint64_t qpack_maximum_dynamic_table_capacity_; uint64_t qpack_maximum_blocked_streams_; size_t max_inbound_header_list_size_; size_t max_outbound_header_list_size_; QuicStreamId stream_id_; size_t frame_len_; bool fin_; spdy::SpdyFramer spdy_framer_; http2::Http2DecoderAdapter h2_deframer_; std::unique_ptr<SpdyFramerVisitor> spdy_framer_visitor_; Http3DebugVisitor* debug_visitor_; absl::flat_hash_map<QuicStreamId, HttpStreamPriority> buffered_stream_priorities_; int32_t destruction_indicator_; std::optional<uint64_t> last_received_http3_goaway_id_; std::optional<uint64_t> last_sent_http3_goaway_id_; HttpDatagramSupport http_datagram_support_ = HttpDatagramSupport::kNone; WebTransportHttp3VersionSet peer_web_transport_versions_; bool settings_received_ = false; absl::flat_hash_set<QuicStreamId> streams_waiting_for_settings_; std::list<BufferedWebTransportStream> buffered_streams_; bool allow_extended_connect_; absl::flat_hash_map<WebTransportHttp3Version, QuicStreamCount> max_webtransport_sessions_; bool force_buffer_requests_until_settings_; }; } #endif #include "quiche/quic/core/http/quic_spdy_session.h" #include <algorithm> #include <cstdint> #include <limits> #include <memory> #include <optional> #include <ostream> #include <string> #include <utility> #include "absl/base/attributes.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/http/http_constants.h" #include "quiche/quic/core/http/http_decoder.h" #include "quiche/quic/core/http/http_frames.h" #include "quiche/quic/core/http/quic_headers_stream.h" #include "quiche/quic/core/http/quic_spdy_stream.h" #include "quiche/quic/core/http/web_transport_http3.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_exported_stats.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include
#include "quiche/quic/core/http/quic_spdy_session.h" #include <cstdint> #include <limits> #include <memory> #include <optional> #include <set> #include <string> #include <utility> #include "absl/base/macros.h" #include "absl/memory/memory.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/frames/quic_stream_frame.h" #include "quiche/quic/core/frames/quic_streams_blocked_frame.h" #include "quiche/quic/core/http/http_constants.h" #include "quiche/quic/core/http/http_encoder.h" #include "quiche/quic/core/http/quic_header_list.h" #include "quiche/quic/core/http/web_transport_http3.h" #include "quiche/quic/core/qpack/qpack_header_table.h" #include "quiche/quic/core/quic_config.h" #include "quiche/quic/core/quic_crypto_stream.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_stream.h" #include "quiche/quic/core/quic_stream_priority.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/qpack/qpack_encoder_peer.h" #include "quiche/quic/test_tools/qpack/qpack_test_utils.h" #include "quiche/quic/test_tools/quic_config_peer.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_flow_controller_peer.h" #include "quiche/quic/test_tools/quic_session_peer.h" #include "quiche/quic/test_tools/quic_spdy_session_peer.h" #include "quiche/quic/test_tools/quic_stream_peer.h" #include "quiche/quic/test_tools/quic_stream_send_buffer_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/platform/api/quiche_mem_slice.h" #include "quiche/common/quiche_endian.h" #include "quiche/common/test_tools/quiche_test_utils.h" #include "quiche/spdy/core/spdy_framer.h" using spdy::Http2HeaderBlock; using spdy::kV3HighestPriority; using spdy::Spdy3PriorityToHttp2Weight; using spdy::SpdyFramer; using spdy::SpdyPriority; using spdy::SpdyPriorityIR; using spdy::SpdySerializedFrame; using ::testing::_; using ::testing::AnyNumber; using ::testing::AtLeast; using ::testing::ElementsAre; using ::testing::InSequence; using ::testing::Invoke; using ::testing::Return; using ::testing::StrictMock; namespace quic { namespace test { namespace { bool VerifyAndClearStopSendingFrame(const QuicFrame& frame) { EXPECT_EQ(STOP_SENDING_FRAME, frame.type); return ClearControlFrame(frame); } class TestCryptoStream : public QuicCryptoStream, public QuicCryptoHandshaker { public: explicit TestCryptoStream(QuicSession* session) : QuicCryptoStream(session), QuicCryptoHandshaker(this, session), encryption_established_(false), one_rtt_keys_available_(false), params_(new QuicCryptoNegotiatedParameters) { params_->cipher_suite = 1; } void EstablishZeroRttEncryption() { encryption_established_ = true; session()->connection()->SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT)); } void OnHandshakeMessage(const CryptoHandshakeMessage& ) override { encryption_established_ = true; one_rtt_keys_available_ = true; QuicErrorCode error; std::string error_details; session()->config()->SetInitialStreamFlowControlWindowToSend( kInitialStreamFlowControlWindowForTest); session()->config()->SetInitialSessionFlowControlWindowToSend( kInitialSessionFlowControlWindowForTest); if (session()->version().UsesTls()) { if (session()->perspective() == Perspective::IS_CLIENT) { session()->config()->SetOriginalConnectionIdToSend( session()->connection()->connection_id()); session()->config()->SetInitialSourceConnectionIdToSend( session()->connection()->connection_id()); } else { session()->config()->SetInitialSourceConnectionIdToSend( session()->connection()->client_connection_id()); } TransportParameters transport_parameters; EXPECT_TRUE( session()->config()->FillTransportParameters(&transport_parameters)); error = session()->config()->ProcessTransportParameters( transport_parameters, false, &error_details); } else { CryptoHandshakeMessage msg; session()->config()->ToHandshakeMessage(&msg, transport_version()); error = session()->config()->ProcessPeerHello(msg, CLIENT, &error_details); } EXPECT_THAT(error, IsQuicNoError()); session()->OnNewEncryptionKeyAvailable( ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE)); session()->OnConfigNegotiated(); if (session()->connection()->version().handshake_protocol == PROTOCOL_TLS1_3) { session()->OnTlsHandshakeComplete(); } else { session()->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); } session()->DiscardOldEncryptionKey(ENCRYPTION_INITIAL); } ssl_early_data_reason_t EarlyDataReason() const override { return ssl_early_data_unknown; } bool encryption_established() const override { return encryption_established_; } bool one_rtt_keys_available() const override { return one_rtt_keys_available_; } HandshakeState GetHandshakeState() const override { return one_rtt_keys_available() ? HANDSHAKE_COMPLETE : HANDSHAKE_START; } void SetServerApplicationStateForResumption( std::unique_ptr<ApplicationState> ) override {} std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter() override { return nullptr; } std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override { return nullptr; } const QuicCryptoNegotiatedParameters& crypto_negotiated_params() const override { return *params_; } CryptoMessageParser* crypto_message_parser() override { return QuicCryptoHandshaker::crypto_message_parser(); } void OnPacketDecrypted(EncryptionLevel ) override {} void OnOneRttPacketAcknowledged() override {} void OnHandshakePacketSent() override {} void OnHandshakeDoneReceived() override {} void OnNewTokenReceived(absl::string_view ) override {} std::string GetAddressToken( const CachedNetworkParameters* ) const override { return ""; } bool ValidateAddressToken(absl::string_view ) const override { return true; } const CachedNetworkParameters* PreviousCachedNetworkParams() const override { return nullptr; } void SetPreviousCachedNetworkParams( CachedNetworkParameters ) override {} MOCK_METHOD(void, OnCanWrite, (), (override)); bool HasPendingCryptoRetransmission() const override { return false; } MOCK_METHOD(bool, HasPendingRetransmission, (), (const, override)); void OnConnectionClosed(const QuicConnectionCloseFrame& , ConnectionCloseSource ) override {} SSL* GetSsl() const override { return nullptr; } bool IsCryptoFrameExpectedForEncryptionLevel( EncryptionLevel level) const override { return level != ENCRYPTION_ZERO_RTT; } EncryptionLevel GetEncryptionLevelToSendCryptoDataOfSpace( PacketNumberSpace space) const override { switch (space) { case INITIAL_DATA: return ENCRYPTION_INITIAL; case HANDSHAKE_DATA: return ENCRYPTION_HANDSHAKE; case APPLICATION_DATA: return ENCRYPTION_FORWARD_SECURE; default: QUICHE_DCHECK(false); return NUM_ENCRYPTION_LEVELS; } } bool ExportKeyingMaterial(absl::string_view , absl::string_view , size_t , std::string* ) override { return false; } private: using QuicCryptoStream::session; bool encryption_established_; bool one_rtt_keys_available_; quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> params_; }; class TestHeadersStream : public QuicHeadersStream { public: explicit TestHeadersStream(QuicSpdySession* session) : QuicHeadersStream(session) {} MOCK_METHOD(void, OnCanWrite, (), (override)); }; class TestStream : public QuicSpdyStream { public: TestStream(QuicStreamId id, QuicSpdySession* session, StreamType type) : QuicSpdyStream(id, session, type) {} TestStream(PendingStream* pending, QuicSpdySession* session) : QuicSpdyStream(pending, session) {} using QuicStream::CloseWriteSide; void OnBodyAvailable() override {} MOCK_METHOD(void, OnCanWrite, (), (override)); MOCK_METHOD(bool, RetransmitStreamData, (QuicStreamOffset, QuicByteCount, bool, TransmissionType), (override)); MOCK_METHOD(bool, HasPendingRetransmission, (), (const, override)); protected: bool ValidateReceivedHeaders(const QuicHeaderList& ) override { return true; } }; class TestSession : public QuicSpdySession { public: explicit TestSession(QuicConnection* connection) : QuicSpdySession(connection, nullptr, DefaultQuicConfig(), CurrentSupportedVersions()), crypto_stream_(this), writev_consumes_all_data_(false) { this->connection()->SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE)); if (this->connection()->version().SupportsAntiAmplificationLimit()) { QuicConnectionPeer::SetAddressValidated(this->connection()); } } ~TestSession() override { DeleteConnection(); } TestCryptoStream* GetMutableCryptoStream() override { return &crypto_stream_; } const TestCryptoStream* GetCryptoStream() const override { return &crypto_stream_; } TestStream* CreateOutgoingBidirectionalStream() override { TestStream* stream = new TestStream(GetNextOutgoingBidirectionalStreamId(), this, BIDIRECTIONAL); ActivateStream(absl::WrapUnique(stream)); return stream; } TestStream* CreateOutgoingUnidirectionalStream() override { TestStream* stream = new TestStream(GetNextOutgoingUnidirectionalStreamId(), this, WRITE_UNIDIRECTIONAL); ActivateStream(absl::WrapUnique(stream)); return stream; } TestStream* CreateIncomingStream(QuicStreamId id) override { if (!VersionHasIetfQuicFrames(connection()->transport_version()) && stream_id_manager().num_open_incoming_streams() + 1 > max_open_incoming_bidirectional_streams()) { connection()->CloseConnection( QUIC_TOO_MANY_OPEN_STREAMS, "Too many streams!", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return nullptr; } else { TestStream* stream = new TestStream( id, this, DetermineStreamType(id, connection()->version(), perspective(), true, BIDIRECTIONAL)); ActivateStream(absl::WrapUnique(stream)); return stream; } } TestStream* CreateIncomingStream(PendingStream* pending) override { TestStream* stream = new TestStream(pending, this); ActivateStream(absl::WrapUnique(stream)); return stream; } bool ShouldCreateIncomingStream(QuicStreamId ) override { return true; } bool ShouldCreateOutgoingBidirectionalStream() override { return true; } bool ShouldCreateOutgoingUnidirectionalStream() override { return true; } bool IsClosedStream(QuicStreamId id) { return QuicSession::IsClosedStream(id); } QuicStream* GetOrCreateStream(QuicStreamId stream_id) { return QuicSpdySession::GetOrCreateStream(stream_id); } QuicConsumedData WritevData(QuicStreamId id, size_t write_length, QuicStreamOffset offset, StreamSendingState state, TransmissionType type, EncryptionLevel level) override { bool fin = state != NO_FIN; QuicConsumedData consumed(write_length, fin); if (!writev_consumes_all_data_) { consumed = QuicSession::WritevData(id, write_length, offset, state, type, level); } QuicSessionPeer::GetWriteBlockedStreams(this)->UpdateBytesForStream( id, consumed.bytes_consumed); return consumed; } void set_writev_consumes_all_data(bool val) { writev_consumes_all_data_ = val; } QuicConsumedData SendStreamData(QuicStream* stream) { if (!QuicUtils::IsCryptoStreamId(connection()->transport_version(), stream->id()) && connection()->encryption_level() != ENCRYPTION_FORWARD_SECURE) { this->connection()->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); } QuicStreamPeer::SendBuffer(stream).SaveStreamData("not empty"); QuicConsumedData consumed = WritevData(stream->id(), 9, 0, FIN, NOT_RETRANSMISSION, GetEncryptionLevelToSendApplicationData()); QuicStreamPeer::SendBuffer(stream).OnStreamDataConsumed( consumed.bytes_consumed); return consumed; } QuicConsumedData SendLargeFakeData(QuicStream* stream, int bytes) { QUICHE_DCHECK(writev_consumes_all_data_); return WritevData(stream->id(), bytes, 0, FIN, NOT_RETRANSMISSION, GetEncryptionLevelToSendApplicationData()); } WebTransportHttp3VersionSet LocallySupportedWebTransportVersions() const override { return locally_supported_web_transport_versions_; } void set_supports_webtransport(bool value) { locally_supported_web_transport_versions_ = value ? kDefaultSupportedWebTransportVersions : WebTransportHttp3VersionSet(); } void set_locally_supported_web_transport_versions( WebTransportHttp3VersionSet versions) { locally_supported_web_transport_versions_ = std::move(versions); } HttpDatagramSupport LocalHttpDatagramSupport() override { return local_http_datagram_support_; } void set_local_http_datagram_support(HttpDatagramSupport value) { local_http_datagram_support_ = value; } MOCK_METHOD(void, OnAcceptChFrame, (const AcceptChFrame&), (override)); using QuicSession::closed_streams; using QuicSession::pending_streams_size; using QuicSession::ShouldKeepConnectionAlive; using QuicSpdySession::settings; using QuicSpdySession::UsesPendingStreamForFrame; private: StrictMock<TestCryptoStream> crypto_stream_; bool writev_consumes_all_data_; WebTransportHttp3VersionSet locally_supported_web_transport_versions_; HttpDatagramSupport local_http_datagram_support_ = HttpDatagramSupport::kNone; }; class QuicSpdySessionTestBase : public QuicTestWithParam<ParsedQuicVersion> { public: bool ClearMaxStreamsControlFrame(const QuicFrame& frame) { if (frame.type == MAX_STREAMS_FRAME) { DeleteFrame(&const_cast<QuicFrame&>(frame)); return true; } return false; } protected: explicit QuicSpdySessionTestBase(Perspective perspective, bool allow_extended_connect) : connection_(new StrictMock<MockQuicConnection>( &helper_, &alarm_factory_, perspective, SupportedVersions(GetParam()))), allow_extended_connect_(allow_extended_connect) {} void Initialize() { session_.emplace(connection_); if (qpack_maximum_dynamic_table_capacity_.has_value()) { session_->set_qpack_maximum_dynamic_table_capacity( *qpack_maximum_dynamic_table_capacity_); } if (connection_->perspective() == Perspective::IS_SERVER && VersionUsesHttp3(transport_version())) { session_->set_allow_extended_connect(allow_extended_connect_); } session_->Initialize(); session_->config()->SetInitialStreamFlowControlWindowToSend( kInitialStreamFlowControlWindowForTest); session_->config()->SetInitialSessionFlowControlWindowToSend( kInitialSessionFlowControlWindowForTest); if (VersionUsesHttp3(transport_version())) { QuicConfigPeer::SetReceivedMaxUnidirectionalStreams( session_->config(), kHttp3StaticUnidirectionalStreamCount); } QuicConfigPeer::SetReceivedInitialSessionFlowControlWindow( session_->config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesUnidirectional( session_->config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesIncomingBidirectional( session_->config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesOutgoingBidirectional( session_->config(), kMinimumFlowControlSendWindow); session_->OnConfigNegotiated(); connection_->AdvanceTime(QuicTime::Delta::FromSeconds(1)); TestCryptoStream* crypto_stream = session_->GetMutableCryptoStream(); EXPECT_CALL(*crypto_stream, HasPendingRetransmission()) .Times(testing::AnyNumber()); writer_ = static_cast<MockPacketWriter*>( QuicConnectionPeer::GetWriter(session_->connection())); } void CheckClosedStreams() { QuicStreamId first_stream_id = QuicUtils::GetFirstBidirectionalStreamId( transport_version(), Perspective::IS_CLIENT); if (!QuicVersionUsesCryptoFrames(transport_version())) { first_stream_id = QuicUtils::GetCryptoStreamId(transport_version()); } for (QuicStreamId i = first_stream_id; i < 100; i++) { if (closed_streams_.find(i) == closed_streams_.end()) { EXPECT_FALSE(session_->IsClosedStream(i)) << " stream id: " << i; } else { EXPECT_TRUE(session_->IsClosedStream(i)) << " stream id: " << i; } } } void CloseStream(QuicStreamId id) { if (!VersionHasIetfQuicFrames(transport_version())) { EXPECT_CALL(*connection_, SendControlFrame(_)) .WillOnce(Invoke(&ClearControlFrame)); } else { EXPECT_CALL(*connection_, SendControlFrame(_)) .Times(2) .WillRepeatedly(Invoke(&ClearControlFrame)); } EXPECT_CALL(*connection_, OnStreamReset(id, _)); session_->set_writev_consumes_all_data(true); session_->ResetStream(id, QUIC_STREAM_CANCELLED); closed_streams_.insert(id); } ParsedQuicVersion version() const { return connection_->version(); } QuicTransportVersion transport_version() const { return connection_->transport_version(); } QuicStreamId GetNthClientInitiatedBidirectionalId(int n) { return GetNthClientInitiatedBidirectionalStreamId(transport_version(), n); } QuicStreamId GetNthServerInitiatedBidirectionalId(int n) { return GetNthServerInitiatedBidirectionalStreamId(transport_version(), n); } QuicStreamId IdDelta() { return QuicUtils::StreamIdDelta(transport_version()); } QuicStreamId StreamCountToId(QuicStreamCount stream_count, Perspective perspective, bool bidirectional) { QuicStreamId id = ((stream_count - 1) * QuicUtils::StreamIdDelta(transport_version())); if (!bidirectional) { id |= 0x2; } if (perspective == Perspective::IS_SERVER) { id |= 0x1; } return id; } void CompleteHandshake() { if (VersionHasIetfQuicFrames(transport_version())) { EXPECT_CALL(*writer_, WritePacket(_, _, _, _, _, _)) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 0))); } if (connection_->version().UsesTls() && connection_->perspective() == Perspective::IS_SERVER) { EXPECT_CALL(*connection_, SendControlFrame(_)) .WillOnce(Invoke(&ClearControlFrame)); } CryptoHandshakeMessage message; session_->GetMutableCryptoStream()->OnHandshakeMessage(message); testing::Mock::VerifyAndClearExpectations(writer_); testing::Mock::VerifyAndClearExpectations(connection_); } void ReceiveWebTransportSettings(WebTransportHttp3VersionSet versions = kDefaultSupportedWebTransportVersions) { SettingsFrame settings; settings.values[SETTINGS_H3_DATAGRAM] = 1; if (versions.IsSet(WebTransportHttp3Version::kDraft02)) { settings.values[SETTINGS_WEBTRANS_DRAFT00] = 1; } if (versions.IsSet(WebTransportHttp3Version::kDraft07)) { settings.values[SETTINGS_WEBTRANS_MAX_SESSIONS_DRAFT07] = 16; } settings.values[SETTINGS_ENABLE_CONNECT_PROTOCOL] = 1; std::string data = std::string(1, kControlStream) + HttpEncoder::SerializeSettingsFrame(settings); QuicStreamId control_stream_id = session_->perspective() == Perspective::IS_SERVER ? GetNthClientInitiatedUnidirectionalStreamId(transport_version(), 3) : GetNthServerInitiatedUnidirectionalStreamId(transport_version(), 3); QuicStreamFrame frame(control_stream_id, false, 0, data); session_->OnStreamFrame(frame); } void ReceiveWebTransportSession(WebTransportSessionId session_id) { QuicStreamFrame frame(session_id, false, 0, absl::string_view()); session_->OnStreamFrame(frame); QuicSpdyStream* stream = static_cast<QuicSpdyStream*>(session_->GetOrCreateStream(session_id)); QuicHeaderList headers; headers.OnHeaderBlockStart(); headers.OnHeader(":method", "CONNECT"); headers.OnHeader(":protocol", "webtransport"); stream->OnStreamHeaderList(true, 0, headers); WebTransportHttp3* web_transport = session_->GetWebTransportSession(session_id); ASSERT_TRUE(web_transport != nullptr); spdy::Http2HeaderBlock header_block; web_transport->HeadersReceived(header_block); } void ReceiveWebTransportUnidirectionalStream(WebTransportSessionId session_id, QuicStreamId stream_id) { char buffer[256]; QuicDataWriter data_writer(sizeof(buffer), buffer); ASSERT_TRUE(data_writer.WriteVarInt62(kWebTransportUnidirectionalStream)); ASSERT_TRUE(data_writer.WriteVarInt62(session_id)); ASSERT_TRUE(data_writer.WriteStringPiece("test data")); std::string data(buffer, data_writer.length()); QuicStreamFrame frame(stream_id, false, 0, data); session_->OnStreamFrame(frame); } void TestHttpDatagramSetting(HttpDatagramSupport local_support, HttpDatagramSupport remote_support, HttpDatagramSupport expected_support, bool expected_datagram_supported); MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; StrictMock<MockQuicConnection>* connection_; bool allow_extended_connect_; std::optional<TestSession> session_; std::set<QuicStreamId> closed_streams_; std::optional<uint64_t> qpack_maximum_dynamic_table_capacity_; MockPacketWriter* writer_; }; class QuicSpdySessionTestServer : public QuicSpdySessionTestBase { protected: QuicSpdySessionTestServer() : QuicSpdySessionTestBase(Perspective::IS_SERVER, true) {} }; INSTANTIATE_TEST_SUITE_P(Tests, QuicSpdySessionTestServer, ::testing::ValuesIn(AllSupportedVersions()), ::testing::PrintToStringParamName()); TEST_P(QuicSpdySessionTestServer, UsesPendingStreamsForFrame) { Initialize(); if (!VersionUsesHttp3(transport_version())) { return; } EXPECT_TRUE(session_->UsesPendingStreamForFrame( STREAM_FRAME, QuicUtils::GetFirstUnidirectionalStreamId( transport_version(), Perspective::IS_CLIENT))); EXPECT_TRUE(session_->UsesPendingStreamForFrame( RST_STREAM_FRAME, QuicUtils::GetFirstUnidirectionalStreamId( transport_version(), Perspective::IS_CLIENT))); EXPECT_FALSE(session_->UsesPendingStreamForFrame( RST_STREAM_FRAME, QuicUtils::GetFirstUnidirectionalStreamId( transport_version(), Perspective::IS_SERVER))); EXPECT_FALSE(session_->UsesPendingStreamForFrame( STOP_SENDING_FRAME, QuicUtils::GetFirstUnidirectionalStreamId( transport_version(), Perspective::IS_CLIENT))); EXPECT_FALSE(session_->UsesPendingStreamForFrame( RST_STREAM_FRAME, QuicUtils::GetFirstBidirectionalStreamId( transport_version(), Perspective::IS_CLIENT))); } TEST_P(QuicSpdySessionTestServer, PeerAddress) { Initialize(); EXPECT_EQ(QuicSocketAddress(QuicIpAddress::Loopback4(), kTestPort), session_->peer_address()); } TEST_P(QuicSpdySessionTestServer, SelfAddress) { Initialize(); EXPECT_TRUE(session_->self_address().IsInitialized()); } TEST_P(QuicSpdySessionTestServer, OneRttKeysAvailable) { Initialize(); EXPECT_FALSE(session_->OneRttKeysAvailable()); CompleteHandshake(); EXPECT_TRUE(session_->OneRttKeysAvailable()); } TEST_P(QuicSpdySessionTestServer, IsClosedStreamDefault) { Initialize(); QuicStreamId first_stream_id = QuicUtils::GetFirstBidirectionalStreamId( transport_version(), Perspective::IS_CLIENT); if (!QuicVersionUsesCryptoFrames(transport_version())) { first_stream_id = QuicUtils::GetCryptoStreamId(transport_version()); } for (QuicStreamId i = first_stream_id; i < 100; i++) { EXPECT_FALSE(session_->IsClosedStream(i)) << "stream id: " << i; } } TEST_P(QuicSpdySessionTestServer, AvailableStreams) { Initialize(); ASSERT_TRUE(session_->GetOrCreateStream( GetNthClientInitiatedBidirectionalId(2)) != nullptr); EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable( &*session_, GetNthClientInitiatedBidirectionalId(0))); EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable( &*session_, GetNthClientInitiatedBidirectionalId(1))); ASSERT_TRUE(session_->GetOrCreateStream( GetNthClientInitiatedBidirectionalId(1)) != nullptr); ASSERT_TRUE(session_->GetOrCreateStream( GetNthClientInitiatedBidirectionalId(0)) != nullptr); } TEST_P(QuicSpdySessionTestServer, IsClosedStreamLocallyCreated) { Initialize(); CompleteHandshake(); TestStream* stream2 = session_->CreateOutgoingBidirectionalStream(); EXPECT_EQ(GetNthServerInitiatedBidirectionalId(0), stream2->id()); QuicSpdyStream* stream4 = session_->CreateOutgoingBidirectionalStream(); EXPECT_EQ(GetNthServerInitiatedBidirectionalId(1), stream4->id()); CheckClosedStreams(); CloseStream(GetNthServerInitiatedBidirectionalId(0)); CheckClosedStreams(); CloseStream(GetNthServerInitiatedBidirectionalId(1)); CheckClosedStreams(); } TEST_P(QuicSpdySessionTestServer, IsClosedStreamPeerCreated) { Initialize(); CompleteHandshake(); QuicStreamId stream_id1 = GetNthClientInitiatedBidirectionalId(0); QuicStreamId stream_id2 = GetNthClientInitiatedBidirectionalId(1); session_->GetOrCreateStream(stream_id1); session_->GetOrCreateStream(stream_id2); CheckClosedStreams(); CloseStream(stream_id1); CheckClosedStreams(); CloseStream(stream_id2); QuicStream* stream3 = session_->GetOrCreateStream(stream_id2 + 4); CheckClosedStreams(); CloseStream(stream3->id()); CheckClosedStreams(); } TEST_P(QuicSpdySessionTestServer, MaximumAvailableOpenedStreams) { Initialize(); if (VersionHasIetfQuicFrames(transport_version())) { QuicStreamId stream_id = StreamCountToId( QuicSessionPeer::ietf_streamid_manager(&*session_) ->max_incoming_bidirectional_streams(), Perspective::IS_CLIENT, true); EXPECT_NE(nullptr, session_->GetOrCreateStream(stream_id)); stream_id = StreamCountToId(QuicSessionPeer::ietf_streamid_manager(&*session_) ->max_incoming_unidirectional_streams(), Perspective::IS_CLIENT, false); EXPECT_NE(nullptr, session_->GetOrCreateStream(stream_id)); EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(2); stream_id = StreamCountToId(QuicSessionPeer::ietf_streamid_manager(&*session_) ->max_incoming_bidirectional_streams() + 1, Perspective::IS_CLIENT, true); EXPECT_EQ(nullptr, session_->GetOrCreateStream(stream_id)); stream_id = StreamCountToId(QuicSessionPeer::ietf_streamid_manager(&*session_) ->max_incoming_unidirectional_streams() + 1, Perspective::IS_CLIENT, false); EXPECT_EQ(nullptr, session_->GetOrCreateStream(stream_id)); } else { QuicStreamId stream_id = GetNthClientInitiatedBidirectionalId(0); session_->GetOrCreateStream(stream_id); EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); EXPECT_NE( nullptr, session_->GetOrCreateStream( stream_id + IdDelta() * (session_->max_open_incoming_bidirectional_streams() - 1))); } } TEST_P(QuicSpdySessionTestServer, TooManyAvailableStreams) { Initialize(); QuicStreamId stream_id1 = GetNthClientInitiatedBidirectionalId(0); QuicStreamId stream_id2; EXPECT_NE(nullptr, session_->GetOrCreateStream(stream_id1)); stream_id2 = GetNthClientInitiatedBidirectionalId( 2 * session_->MaxAvailableBidirectionalStreams() + 4); if (VersionHasIetfQuicFrames(transport_version())) { EXPECT_CALL(*connection_, CloseConnection(QUIC_INVALID_STREAM_ID, _, _)); } else { EXPECT_CALL(*connection_, CloseConnection(QUIC_TOO_MANY_AVAILABLE_STREAMS, _, _)); } EXPECT_EQ(nullptr, session_->GetOrCreateStream(stream_id2)); } TEST_P(QuicSpdySessionTestServer, ManyAvailableStreams) { Initialize(); if (VersionHasIetfQuicFrames(transport_version())) { QuicSessionPeer::SetMaxOpenIncomingBidirectionalStreams(&*session_, 200); } else { QuicSessionPeer::SetMaxOpenIncomingStreams(&*session_, 200); } QuicStreamId stream_id = GetNthClientInitiatedBidirectionalId(0); session_->GetOrCreateStream(stream_id); EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); EXPECT_NE(nullptr, session_->GetOrCreateStream( GetNthClientInitiatedBidirectionalId(198))); } TEST_P(QuicSpdySessionTestServer, DebugDFatalIfMarkingClosedStreamWriteBlocked) { Initialize(); CompleteHandshake(); EXPECT_CALL(*writer_, WritePa
309
cpp
google/quiche
metadata_decoder
quiche/quic/core/http/metadata_decoder.cc
quiche/quic/core/http/metadata_decoder_test.cc
#ifndef QUICHE_QUIC_CORE_HTTP_METADATA_DECODER_H_ #define QUICHE_QUIC_CORE_HTTP_METADATA_DECODER_H_ #include <sys/types.h> #include <cstddef> #include <string> #include "absl/strings/string_view.h" #include "quiche/quic/core/http/quic_header_list.h" #include "quiche/quic/core/qpack/qpack_decoded_headers_accumulator.h" #include "quiche/quic/core/qpack/qpack_decoder.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_types.h" #include "quiche/common/platform/api/quiche_export.h" namespace quic { class QUICHE_EXPORT MetadataDecoder { public: MetadataDecoder(QuicStreamId id, size_t max_header_list_size, size_t frame_header_len, size_t payload_length); bool Decode(absl::string_view payload); bool EndHeaderBlock(); const std::string& error_message() { return decoder_.error_message(); } size_t frame_len() { return frame_len_; } const QuicHeaderList& headers() { return decoder_.headers(); } private: class MetadataHeadersDecoder : public QpackDecodedHeadersAccumulator::Visitor { public: void OnHeadersDecoded(QuicHeaderList headers, bool header_list_size_limit_exceeded) override; void OnHeaderDecodingError(QuicErrorCode error_code, absl::string_view error_message) override; QuicErrorCode error_code() { return error_code_; } const std::string& error_message() { return error_message_; } QuicHeaderList& headers() { return headers_; } bool header_list_size_limit_exceeded() { return header_list_size_limit_exceeded_; } private: QuicErrorCode error_code_ = QUIC_NO_ERROR; QuicHeaderList headers_; std::string error_message_; bool header_list_size_limit_exceeded_ = false; }; NoopEncoderStreamErrorDelegate delegate_; QpackDecoder qpack_decoder_; MetadataHeadersDecoder decoder_; QpackDecodedHeadersAccumulator accumulator_; const size_t frame_len_; size_t bytes_remaining_ = 0; }; } #endif #include "quiche/quic/core/http/metadata_decoder.h" #include <cstddef> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/http/quic_header_list.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" namespace quic { MetadataDecoder::MetadataDecoder(QuicStreamId id, size_t max_header_list_size, size_t frame_header_len, size_t payload_length) : qpack_decoder_(0, 0, &delegate_), accumulator_(id, &qpack_decoder_, &decoder_, max_header_list_size), frame_len_(frame_header_len + payload_length), bytes_remaining_(payload_length) {} bool MetadataDecoder::Decode(absl::string_view payload) { accumulator_.Decode(payload); bytes_remaining_ -= payload.length(); return decoder_.error_code() == QUIC_NO_ERROR; } bool MetadataDecoder::EndHeaderBlock() { QUIC_BUG_IF(METADATA bytes remaining, bytes_remaining_ != 0) << "More metadata remaining: " << bytes_remaining_; accumulator_.EndHeaderBlock(); return !decoder_.header_list_size_limit_exceeded(); } void MetadataDecoder::MetadataHeadersDecoder::OnHeadersDecoded( QuicHeaderList headers, bool header_list_size_limit_exceeded) { header_list_size_limit_exceeded_ = header_list_size_limit_exceeded; headers_ = std::move(headers); } void MetadataDecoder::MetadataHeadersDecoder::OnHeaderDecodingError( QuicErrorCode error_code, absl::string_view error_message) { error_code_ = error_code; error_message_ = absl::StrCat("Error decoding metadata: ", error_message); } }
#include "quiche/quic/core/http/metadata_decoder.h" #include <string> #include "absl/strings/escaping.h" #include "quiche/quic/core/qpack/qpack_encoder.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { namespace test { namespace { class MetadataDecoderTest : public QuicTest { protected: std::string EncodeHeaders(spdy::Http2HeaderBlock& headers) { quic::NoopDecoderStreamErrorDelegate delegate; quic::QpackEncoder encoder(&delegate, quic::HuffmanEncoding::kDisabled); return encoder.EncodeHeaderList(id_, headers, nullptr); } size_t max_header_list_size = 1 << 20; const QuicStreamId id_ = 1; }; TEST_F(MetadataDecoderTest, Initialize) { const size_t frame_header_len = 4; const size_t payload_len = 123; MetadataDecoder decoder(id_, max_header_list_size, frame_header_len, payload_len); EXPECT_EQ(frame_header_len + payload_len, decoder.frame_len()); EXPECT_EQ("", decoder.error_message()); EXPECT_TRUE(decoder.headers().empty()); } TEST_F(MetadataDecoderTest, Decode) { spdy::Http2HeaderBlock headers; headers["key1"] = "val1"; headers["key2"] = "val2"; headers["key3"] = "val3"; std::string data = EncodeHeaders(headers); const size_t frame_header_len = 4; MetadataDecoder decoder(id_, max_header_list_size, frame_header_len, data.length()); EXPECT_TRUE(decoder.Decode(data)); EXPECT_TRUE(decoder.EndHeaderBlock()); EXPECT_EQ(quic::test::AsHeaderList(headers), decoder.headers()); } TEST_F(MetadataDecoderTest, DecodeInvalidHeaders) { std::string data = "aaaaaaaaaa"; const size_t frame_header_len = 4; MetadataDecoder decoder(id_, max_header_list_size, frame_header_len, data.length()); EXPECT_FALSE(decoder.Decode(data)); EXPECT_EQ("Error decoding metadata: Error decoding Required Insert Count.", decoder.error_message()); } TEST_F(MetadataDecoderTest, TooLarge) { spdy::Http2HeaderBlock headers; for (int i = 0; i < 1024; ++i) { headers.AppendValueOrAddHeader(absl::StrCat(i), std::string(1024, 'a')); } std::string data = EncodeHeaders(headers); EXPECT_GT(data.length(), 1 << 20); const size_t frame_header_len = 4; MetadataDecoder decoder(id_, max_header_list_size, frame_header_len, data.length()); EXPECT_TRUE(decoder.Decode(data)); EXPECT_FALSE(decoder.EndHeaderBlock()); EXPECT_TRUE(decoder.error_message().empty()); } } } }
310
cpp
google/quiche
spdy_utils
quiche/quic/core/http/spdy_utils.cc
quiche/quic/core/http/spdy_utils_test.cc
#ifndef QUICHE_QUIC_CORE_HTTP_SPDY_UTILS_H_ #define QUICHE_QUIC_CORE_HTTP_SPDY_UTILS_H_ #include <cstddef> #include <cstdint> #include <optional> #include <string> #include "quiche/quic/core/http/http_constants.h" #include "quiche/quic/core/http/quic_header_list.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/spdy/core/http2_header_block.h" #include "quiche/spdy/core/spdy_alt_svc_wire_format.h" namespace quic { class QUICHE_EXPORT SpdyUtils { public: SpdyUtils() = delete; static bool ExtractContentLengthFromHeaders(int64_t* content_length, spdy::Http2HeaderBlock* headers); static bool CopyAndValidateHeaders(const QuicHeaderList& header_list, int64_t* content_length, spdy::Http2HeaderBlock* headers); static bool CopyAndValidateTrailers(const QuicHeaderList& header_list, bool expect_final_byte_offset, size_t* final_byte_offset, spdy::Http2HeaderBlock* trailers); static bool PopulateHeaderBlockFromUrl(const std::string url, spdy::Http2HeaderBlock* headers); static ParsedQuicVersion ExtractQuicVersionFromAltSvcEntry( const spdy::SpdyAltSvcWireFormat::AlternativeService& alternative_service_entry, const ParsedQuicVersionVector& supported_versions); }; } #endif #include "quiche/quic/core/http/spdy_utils.h" #include <memory> #include <optional> #include <string> #include <vector> #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/common/quiche_text_utils.h" #include "quiche/spdy/core/spdy_protocol.h" using spdy::Http2HeaderBlock; namespace quic { bool SpdyUtils::ExtractContentLengthFromHeaders(int64_t* content_length, Http2HeaderBlock* headers) { auto it = headers->find("content-length"); if (it == headers->end()) { return false; } else { absl::string_view content_length_header = it->second; std::vector<absl::string_view> values = absl::StrSplit(content_length_header, '\0'); for (const absl::string_view& value : values) { uint64_t new_value; if (!absl::SimpleAtoi(value, &new_value) || !quiche::QuicheTextUtils::IsAllDigits(value)) { QUIC_DLOG(ERROR) << "Content length was either unparseable or negative."; return false; } if (*content_length < 0) { *content_length = new_value; continue; } if (new_value != static_cast<uint64_t>(*content_length)) { QUIC_DLOG(ERROR) << "Parsed content length " << new_value << " is " << "inconsistent with previously detected content length " << *content_length; return false; } } return true; } } bool SpdyUtils::CopyAndValidateHeaders(const QuicHeaderList& header_list, int64_t* content_length, Http2HeaderBlock* headers) { for (const auto& p : header_list) { const std::string& name = p.first; if (name.empty()) { QUIC_DLOG(ERROR) << "Header name must not be empty."; return false; } if (quiche::QuicheTextUtils::ContainsUpperCase(name)) { QUIC_DLOG(ERROR) << "Malformed header: Header name " << name << " contains upper-case characters."; return false; } headers->AppendValueOrAddHeader(name, p.second); } if (headers->contains("content-length") && !ExtractContentLengthFromHeaders(content_length, headers)) { return false; } QUIC_DVLOG(1) << "Successfully parsed headers: " << headers->DebugString(); return true; } bool SpdyUtils::CopyAndValidateTrailers(const QuicHeaderList& header_list, bool expect_final_byte_offset, size_t* final_byte_offset, Http2HeaderBlock* trailers) { bool found_final_byte_offset = false; for (const auto& p : header_list) { const std::string& name = p.first; if (expect_final_byte_offset && !found_final_byte_offset && name == kFinalOffsetHeaderKey && absl::SimpleAtoi(p.second, final_byte_offset)) { found_final_byte_offset = true; continue; } if (name.empty() || name[0] == ':') { QUIC_DLOG(ERROR) << "Trailers must not be empty, and must not contain pseudo-" << "headers. Found: '" << name << "'"; return false; } if (quiche::QuicheTextUtils::ContainsUpperCase(name)) { QUIC_DLOG(ERROR) << "Malformed header: Header name " << name << " contains upper-case characters."; return false; } trailers->AppendValueOrAddHeader(name, p.second); } if (expect_final_byte_offset && !found_final_byte_offset) { QUIC_DLOG(ERROR) << "Required key '" << kFinalOffsetHeaderKey << "' not present"; return false; } QUIC_DVLOG(1) << "Successfully parsed Trailers: " << trailers->DebugString(); return true; } bool SpdyUtils::PopulateHeaderBlockFromUrl(const std::string url, Http2HeaderBlock* headers) { (*headers)[":method"] = "GET"; size_t pos = url.find(": if (pos == std::string::npos) { return false; } (*headers)[":scheme"] = url.substr(0, pos); size_t start = pos + 3; pos = url.find('/', start); if (pos == std::string::npos) { (*headers)[":authority"] = url.substr(start); (*headers)[":path"] = "/"; return true; } (*headers)[":authority"] = url.substr(start, pos - start); (*headers)[":path"] = url.substr(pos); return true; } ParsedQuicVersion SpdyUtils::ExtractQuicVersionFromAltSvcEntry( const spdy::SpdyAltSvcWireFormat::AlternativeService& alternative_service_entry, const ParsedQuicVersionVector& supported_versions) { for (const ParsedQuicVersion& version : supported_versions) { if (version.AlpnDeferToRFCv1()) { continue; } if (AlpnForVersion(version) == alternative_service_entry.protocol_id) { return version; } } return ParsedQuicVersion::Unsupported(); } }
#include "quiche/quic/core/http/spdy_utils.h" #include <memory> #include <string> #include "absl/base/macros.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_test.h" using spdy::Http2HeaderBlock; using testing::Pair; using testing::UnorderedElementsAre; namespace quic { namespace test { namespace { const bool kExpectFinalByteOffset = true; const bool kDoNotExpectFinalByteOffset = false; static std::unique_ptr<QuicHeaderList> FromList( const QuicHeaderList::ListType& src) { std::unique_ptr<QuicHeaderList> headers(new QuicHeaderList); headers->OnHeaderBlockStart(); for (const auto& p : src) { headers->OnHeader(p.first, p.second); } headers->OnHeaderBlockEnd(0, 0); return headers; } } using CopyAndValidateHeaders = QuicTest; TEST_F(CopyAndValidateHeaders, NormalUsage) { auto headers = FromList({ {"cookie", " part 1"}, {"cookie", "part 2 "}, {"cookie", "part3"}, {"passed-through", std::string("foo\0baz", 7)}, {"joined", "value 1"}, {"joined", "value 2"}, {"empty", ""}, {"empty-joined", ""}, {"empty-joined", "foo"}, {"empty-joined", ""}, {"empty-joined", ""}, {"cookie", " fin!"}}); int64_t content_length = -1; Http2HeaderBlock block; ASSERT_TRUE( SpdyUtils::CopyAndValidateHeaders(*headers, &content_length, &block)); EXPECT_THAT(block, UnorderedElementsAre( Pair("cookie", " part 1; part 2 ; part3; fin!"), Pair("passed-through", absl::string_view("foo\0baz", 7)), Pair("joined", absl::string_view("value 1\0value 2", 15)), Pair("empty", ""), Pair("empty-joined", absl::string_view("\0foo\0\0", 6)))); EXPECT_EQ(-1, content_length); } TEST_F(CopyAndValidateHeaders, EmptyName) { auto headers = FromList({{"foo", "foovalue"}, {"", "barvalue"}, {"baz", ""}}); int64_t content_length = -1; Http2HeaderBlock block; ASSERT_FALSE( SpdyUtils::CopyAndValidateHeaders(*headers, &content_length, &block)); } TEST_F(CopyAndValidateHeaders, UpperCaseName) { auto headers = FromList({{"foo", "foovalue"}, {"bar", "barvalue"}, {"bAz", ""}}); int64_t content_length = -1; Http2HeaderBlock block; ASSERT_FALSE( SpdyUtils::CopyAndValidateHeaders(*headers, &content_length, &block)); } TEST_F(CopyAndValidateHeaders, MultipleContentLengths) { auto headers = FromList({{"content-length", "9"}, {"foo", "foovalue"}, {"content-length", "9"}, {"bar", "barvalue"}, {"baz", ""}}); int64_t content_length = -1; Http2HeaderBlock block; ASSERT_TRUE( SpdyUtils::CopyAndValidateHeaders(*headers, &content_length, &block)); EXPECT_THAT(block, UnorderedElementsAre( Pair("foo", "foovalue"), Pair("bar", "barvalue"), Pair("content-length", absl::string_view("9\09", 3)), Pair("baz", ""))); EXPECT_EQ(9, content_length); } TEST_F(CopyAndValidateHeaders, InconsistentContentLengths) { auto headers = FromList({{"content-length", "9"}, {"foo", "foovalue"}, {"content-length", "8"}, {"bar", "barvalue"}, {"baz", ""}}); int64_t content_length = -1; Http2HeaderBlock block; ASSERT_FALSE( SpdyUtils::CopyAndValidateHeaders(*headers, &content_length, &block)); } TEST_F(CopyAndValidateHeaders, LargeContentLength) { auto headers = FromList({{"content-length", "9000000000"}, {"foo", "foovalue"}, {"bar", "barvalue"}, {"baz", ""}}); int64_t content_length = -1; Http2HeaderBlock block; ASSERT_TRUE( SpdyUtils::CopyAndValidateHeaders(*headers, &content_length, &block)); EXPECT_THAT(block, UnorderedElementsAre( Pair("foo", "foovalue"), Pair("bar", "barvalue"), Pair("content-length", absl::string_view("9000000000")), Pair("baz", ""))); EXPECT_EQ(9000000000, content_length); } TEST_F(CopyAndValidateHeaders, NonDigitContentLength) { auto headers = FromList({{"content-length", "+123"}, {"foo", "foovalue"}, {"bar", "barvalue"}, {"baz", ""}}); int64_t content_length = -1; Http2HeaderBlock block; EXPECT_FALSE( SpdyUtils::CopyAndValidateHeaders(*headers, &content_length, &block)); } TEST_F(CopyAndValidateHeaders, MultipleValues) { auto headers = FromList({{"foo", "foovalue"}, {"bar", "barvalue"}, {"baz", ""}, {"foo", "boo"}, {"baz", "buzz"}}); int64_t content_length = -1; Http2HeaderBlock block; ASSERT_TRUE( SpdyUtils::CopyAndValidateHeaders(*headers, &content_length, &block)); EXPECT_THAT(block, UnorderedElementsAre( Pair("foo", absl::string_view("foovalue\0boo", 12)), Pair("bar", "barvalue"), Pair("baz", absl::string_view("\0buzz", 5)))); EXPECT_EQ(-1, content_length); } TEST_F(CopyAndValidateHeaders, MoreThanTwoValues) { auto headers = FromList({{"set-cookie", "value1"}, {"set-cookie", "value2"}, {"set-cookie", "value3"}}); int64_t content_length = -1; Http2HeaderBlock block; ASSERT_TRUE( SpdyUtils::CopyAndValidateHeaders(*headers, &content_length, &block)); EXPECT_THAT(block, UnorderedElementsAre(Pair( "set-cookie", absl::string_view("value1\0value2\0value3", 20)))); EXPECT_EQ(-1, content_length); } TEST_F(CopyAndValidateHeaders, Cookie) { auto headers = FromList({{"foo", "foovalue"}, {"bar", "barvalue"}, {"cookie", "value1"}, {"baz", ""}}); int64_t content_length = -1; Http2HeaderBlock block; ASSERT_TRUE( SpdyUtils::CopyAndValidateHeaders(*headers, &content_length, &block)); EXPECT_THAT(block, UnorderedElementsAre( Pair("foo", "foovalue"), Pair("bar", "barvalue"), Pair("cookie", "value1"), Pair("baz", ""))); EXPECT_EQ(-1, content_length); } TEST_F(CopyAndValidateHeaders, MultipleCookies) { auto headers = FromList({{"foo", "foovalue"}, {"bar", "barvalue"}, {"cookie", "value1"}, {"baz", ""}, {"cookie", "value2"}}); int64_t content_length = -1; Http2HeaderBlock block; ASSERT_TRUE( SpdyUtils::CopyAndValidateHeaders(*headers, &content_length, &block)); EXPECT_THAT(block, UnorderedElementsAre( Pair("foo", "foovalue"), Pair("bar", "barvalue"), Pair("cookie", "value1; value2"), Pair("baz", ""))); EXPECT_EQ(-1, content_length); } using CopyAndValidateTrailers = QuicTest; TEST_F(CopyAndValidateTrailers, SimplestValidList) { auto trailers = FromList({{kFinalOffsetHeaderKey, "1234"}}); size_t final_byte_offset = 0; Http2HeaderBlock block; EXPECT_TRUE(SpdyUtils::CopyAndValidateTrailers( *trailers, kExpectFinalByteOffset, &final_byte_offset, &block)); EXPECT_EQ(1234u, final_byte_offset); } TEST_F(CopyAndValidateTrailers, EmptyTrailerListWithFinalByteOffsetExpected) { QuicHeaderList trailers; size_t final_byte_offset = 0; Http2HeaderBlock block; EXPECT_FALSE(SpdyUtils::CopyAndValidateTrailers( trailers, kExpectFinalByteOffset, &final_byte_offset, &block)); } TEST_F(CopyAndValidateTrailers, EmptyTrailerListWithFinalByteOffsetNotExpected) { QuicHeaderList trailers; size_t final_byte_offset = 0; Http2HeaderBlock block; EXPECT_TRUE(SpdyUtils::CopyAndValidateTrailers( trailers, kDoNotExpectFinalByteOffset, &final_byte_offset, &block)); EXPECT_TRUE(block.empty()); } TEST_F(CopyAndValidateTrailers, FinalByteOffsetExpectedButNotPresent) { auto trailers = FromList({{"key", "value"}}); size_t final_byte_offset = 0; Http2HeaderBlock block; EXPECT_FALSE(SpdyUtils::CopyAndValidateTrailers( *trailers, kExpectFinalByteOffset, &final_byte_offset, &block)); } TEST_F(CopyAndValidateTrailers, FinalByteOffsetNotExpectedButPresent) { auto trailers = FromList({{"key", "value"}, {kFinalOffsetHeaderKey, "1234"}}); size_t final_byte_offset = 0; Http2HeaderBlock block; EXPECT_FALSE(SpdyUtils::CopyAndValidateTrailers( *trailers, kDoNotExpectFinalByteOffset, &final_byte_offset, &block)); } TEST_F(CopyAndValidateTrailers, FinalByteOffsetNotExpectedAndNotPresent) { auto trailers = FromList({{"key", "value"}}); size_t final_byte_offset = 0; Http2HeaderBlock block; EXPECT_TRUE(SpdyUtils::CopyAndValidateTrailers( *trailers, kDoNotExpectFinalByteOffset, &final_byte_offset, &block)); EXPECT_THAT(block, UnorderedElementsAre(Pair("key", "value"))); } TEST_F(CopyAndValidateTrailers, EmptyName) { auto trailers = FromList({{"", "value"}, {kFinalOffsetHeaderKey, "1234"}}); size_t final_byte_offset = 0; Http2HeaderBlock block; EXPECT_FALSE(SpdyUtils::CopyAndValidateTrailers( *trailers, kExpectFinalByteOffset, &final_byte_offset, &block)); } TEST_F(CopyAndValidateTrailers, PseudoHeaderInTrailers) { auto trailers = FromList({{":pseudo_key", "value"}, {kFinalOffsetHeaderKey, "1234"}}); size_t final_byte_offset = 0; Http2HeaderBlock block; EXPECT_FALSE(SpdyUtils::CopyAndValidateTrailers( *trailers, kExpectFinalByteOffset, &final_byte_offset, &block)); } TEST_F(CopyAndValidateTrailers, DuplicateTrailers) { auto trailers = FromList({{"key", "value0"}, {"key", "value1"}, {"key", ""}, {"key", ""}, {"key", "value2"}, {"key", ""}, {kFinalOffsetHeaderKey, "1234"}, {"other_key", "value"}, {"key", "non_contiguous_duplicate"}}); size_t final_byte_offset = 0; Http2HeaderBlock block; EXPECT_TRUE(SpdyUtils::CopyAndValidateTrailers( *trailers, kExpectFinalByteOffset, &final_byte_offset, &block)); EXPECT_THAT( block, UnorderedElementsAre( Pair("key", absl::string_view( "value0\0value1\0\0\0value2\0\0non_contiguous_duplicate", 48)), Pair("other_key", "value"))); } TEST_F(CopyAndValidateTrailers, DuplicateCookies) { auto headers = FromList({{"cookie", " part 1"}, {"cookie", "part 2 "}, {"cookie", "part3"}, {"key", "value"}, {kFinalOffsetHeaderKey, "1234"}, {"cookie", " non_contiguous_cookie!"}}); size_t final_byte_offset = 0; Http2HeaderBlock block; EXPECT_TRUE(SpdyUtils::CopyAndValidateTrailers( *headers, kExpectFinalByteOffset, &final_byte_offset, &block)); EXPECT_THAT( block, UnorderedElementsAre( Pair("cookie", " part 1; part 2 ; part3; non_contiguous_cookie!"), Pair("key", "value"))); } using PopulateHeaderBlockFromUrl = QuicTest; TEST_F(PopulateHeaderBlockFromUrl, NormalUsage) { std::string url = "https: Http2HeaderBlock headers; EXPECT_TRUE(SpdyUtils::PopulateHeaderBlockFromUrl(url, &headers)); EXPECT_EQ("https", headers[":scheme"].as_string()); EXPECT_EQ("www.google.com", headers[":authority"].as_string()); EXPECT_EQ("/index.html", headers[":path"].as_string()); } TEST_F(PopulateHeaderBlockFromUrl, UrlWithNoPath) { std::string url = "https: Http2HeaderBlock headers; EXPECT_TRUE(SpdyUtils::PopulateHeaderBlockFromUrl(url, &headers)); EXPECT_EQ("https", headers[":scheme"].as_string()); EXPECT_EQ("www.google.com", headers[":authority"].as_string()); EXPECT_EQ("/", headers[":path"].as_string()); } TEST_F(PopulateHeaderBlockFromUrl, Failure) { Http2HeaderBlock headers; EXPECT_FALSE(SpdyUtils::PopulateHeaderBlockFromUrl("/", &headers)); EXPECT_FALSE(SpdyUtils::PopulateHeaderBlockFromUrl("/index.html", &headers)); EXPECT_FALSE( SpdyUtils::PopulateHeaderBlockFromUrl("www.google.com/", &headers)); } using ExtractQuicVersionFromAltSvcEntry = QuicTest; TEST_F(ExtractQuicVersionFromAltSvcEntry, SupportedVersion) { ParsedQuicVersionVector supported_versions = AllSupportedVersions(); spdy::SpdyAltSvcWireFormat::AlternativeService entry; for (const ParsedQuicVersion& version : supported_versions) { entry.protocol_id = AlpnForVersion(version); ParsedQuicVersion expected_version = version; if (entry.protocol_id == AlpnForVersion(ParsedQuicVersion::RFCv1()) && version != ParsedQuicVersion::RFCv1()) { expected_version = ParsedQuicVersion::RFCv1(); } EXPECT_EQ(expected_version, SpdyUtils::ExtractQuicVersionFromAltSvcEntry( entry, supported_versions)) << "version: " << version; } } TEST_F(ExtractQuicVersionFromAltSvcEntry, UnsupportedVersion) { spdy::SpdyAltSvcWireFormat::AlternativeService entry; entry.protocol_id = "quic"; EXPECT_EQ(ParsedQuicVersion::Unsupported(), SpdyUtils::ExtractQuicVersionFromAltSvcEntry( entry, AllSupportedVersions())); } } }
311
cpp
google/quiche
quic_receive_control_stream
quiche/quic/core/http/quic_receive_control_stream.cc
quiche/quic/core/http/quic_receive_control_stream_test.cc
#ifndef QUICHE_QUIC_CORE_HTTP_QUIC_RECEIVE_CONTROL_STREAM_H_ #define QUICHE_QUIC_CORE_HTTP_QUIC_RECEIVE_CONTROL_STREAM_H_ #include "quiche/quic/core/http/http_decoder.h" #include "quiche/quic/core/quic_stream.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QuicSpdySession; class QUICHE_EXPORT QuicReceiveControlStream : public QuicStream, public HttpDecoder::Visitor { public: explicit QuicReceiveControlStream(PendingStream* pending, QuicSpdySession* spdy_session); QuicReceiveControlStream(const QuicReceiveControlStream&) = delete; QuicReceiveControlStream& operator=(const QuicReceiveControlStream&) = delete; ~QuicReceiveControlStream() override; void OnStreamReset(const QuicRstStreamFrame& frame) override; void OnDataAvailable() override; void OnError(HttpDecoder* decoder) override; bool OnMaxPushIdFrame() override; bool OnGoAwayFrame(const GoAwayFrame& frame) override; bool OnSettingsFrameStart(QuicByteCount header_length) override; bool OnSettingsFrame(const SettingsFrame& frame) override; bool OnDataFrameStart(QuicByteCount header_length, QuicByteCount payload_length) override; bool OnDataFramePayload(absl::string_view payload) override; bool OnDataFrameEnd() override; bool OnHeadersFrameStart(QuicByteCount header_length, QuicByteCount payload_length) override; bool OnHeadersFramePayload(absl::string_view payload) override; bool OnHeadersFrameEnd() override; bool OnPriorityUpdateFrameStart(QuicByteCount header_length) override; bool OnPriorityUpdateFrame(const PriorityUpdateFrame& frame) override; bool OnAcceptChFrameStart(QuicByteCount header_length) override; bool OnAcceptChFrame(const AcceptChFrame& frame) override; void OnWebTransportStreamFrameType(QuicByteCount header_length, WebTransportSessionId session_id) override; bool OnMetadataFrameStart(QuicByteCount header_length, QuicByteCount payload_length) override; bool OnMetadataFramePayload(absl::string_view payload) override; bool OnMetadataFrameEnd() override; bool OnUnknownFrameStart(uint64_t frame_type, QuicByteCount header_length, QuicByteCount payload_length) override; bool OnUnknownFramePayload(absl::string_view payload) override; bool OnUnknownFrameEnd() override; QuicSpdySession* spdy_session() { return spdy_session_; } private: bool ValidateFrameType(HttpFrameType frame_type); bool settings_frame_received_; HttpDecoder decoder_; QuicSpdySession* const spdy_session_; }; } #endif #include "quiche/quic/core/http/quic_receive_control_stream.h" #include <optional> #include <utility> #include "absl/strings/numbers.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/http/http_constants.h" #include "quiche/quic/core/http/http_decoder.h" #include "quiche/quic/core/http/quic_spdy_session.h" #include "quiche/quic/core/quic_stream_priority.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/common/quiche_text_utils.h" namespace quic { QuicReceiveControlStream::QuicReceiveControlStream( PendingStream* pending, QuicSpdySession* spdy_session) : QuicStream(pending, spdy_session, true), settings_frame_received_(false), decoder_(this), spdy_session_(spdy_session) { sequencer()->set_level_triggered(true); } QuicReceiveControlStream::~QuicReceiveControlStream() {} void QuicReceiveControlStream::OnStreamReset( const QuicRstStreamFrame& ) { stream_delegate()->OnStreamError( QUIC_HTTP_CLOSED_CRITICAL_STREAM, "RESET_STREAM received for receive control stream"); } void QuicReceiveControlStream::OnDataAvailable() { iovec iov; while (!reading_stopped() && decoder_.error() == QUIC_NO_ERROR && sequencer()->GetReadableRegion(&iov)) { QUICHE_DCHECK(!sequencer()->IsClosed()); QuicByteCount processed_bytes = decoder_.ProcessInput( reinterpret_cast<const char*>(iov.iov_base), iov.iov_len); sequencer()->MarkConsumed(processed_bytes); if (!session()->connection()->connected()) { return; } QUICHE_DCHECK_EQ(iov.iov_len, processed_bytes); } } void QuicReceiveControlStream::OnError(HttpDecoder* decoder) { stream_delegate()->OnStreamError(decoder->error(), decoder->error_detail()); } bool QuicReceiveControlStream::OnMaxPushIdFrame() { return ValidateFrameType(HttpFrameType::MAX_PUSH_ID); } bool QuicReceiveControlStream::OnGoAwayFrame(const GoAwayFrame& frame) { if (spdy_session()->debug_visitor()) { spdy_session()->debug_visitor()->OnGoAwayFrameReceived(frame); } if (!ValidateFrameType(HttpFrameType::GOAWAY)) { return false; } spdy_session()->OnHttp3GoAway(frame.id); return true; } bool QuicReceiveControlStream::OnSettingsFrameStart( QuicByteCount ) { return ValidateFrameType(HttpFrameType::SETTINGS); } bool QuicReceiveControlStream::OnSettingsFrame(const SettingsFrame& frame) { QUIC_DVLOG(1) << "Control Stream " << id() << " received settings frame: " << frame; return spdy_session_->OnSettingsFrame(frame); } bool QuicReceiveControlStream::OnDataFrameStart(QuicByteCount , QuicByteCount ) { return ValidateFrameType(HttpFrameType::DATA); } bool QuicReceiveControlStream::OnDataFramePayload( absl::string_view ) { QUICHE_NOTREACHED(); return false; } bool QuicReceiveControlStream::OnDataFrameEnd() { QUICHE_NOTREACHED(); return false; } bool QuicReceiveControlStream::OnHeadersFrameStart( QuicByteCount , QuicByteCount ) { return ValidateFrameType(HttpFrameType::HEADERS); } bool QuicReceiveControlStream::OnHeadersFramePayload( absl::string_view ) { QUICHE_NOTREACHED(); return false; } bool QuicReceiveControlStream::OnHeadersFrameEnd() { QUICHE_NOTREACHED(); return false; } bool QuicReceiveControlStream::OnPriorityUpdateFrameStart( QuicByteCount ) { return ValidateFrameType(HttpFrameType::PRIORITY_UPDATE_REQUEST_STREAM); } bool QuicReceiveControlStream::OnPriorityUpdateFrame( const PriorityUpdateFrame& frame) { if (spdy_session()->debug_visitor()) { spdy_session()->debug_visitor()->OnPriorityUpdateFrameReceived(frame); } std::optional<HttpStreamPriority> priority = ParsePriorityFieldValue(frame.priority_field_value); if (!priority.has_value()) { stream_delegate()->OnStreamError(QUIC_INVALID_PRIORITY_UPDATE, "Invalid PRIORITY_UPDATE frame payload."); return false; } const QuicStreamId stream_id = frame.prioritized_element_id; return spdy_session_->OnPriorityUpdateForRequestStream(stream_id, *priority); } bool QuicReceiveControlStream::OnAcceptChFrameStart( QuicByteCount ) { return ValidateFrameType(HttpFrameType::ACCEPT_CH); } bool QuicReceiveControlStream::OnAcceptChFrame(const AcceptChFrame& frame) { QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, spdy_session()->perspective()); if (spdy_session()->debug_visitor()) { spdy_session()->debug_visitor()->OnAcceptChFrameReceived(frame); } spdy_session()->OnAcceptChFrame(frame); return true; } void QuicReceiveControlStream::OnWebTransportStreamFrameType( QuicByteCount , WebTransportSessionId ) { QUIC_BUG(WEBTRANSPORT_STREAM on Control Stream) << "Parsed WEBTRANSPORT_STREAM on a control stream."; } bool QuicReceiveControlStream::OnMetadataFrameStart( QuicByteCount , QuicByteCount ) { return ValidateFrameType(HttpFrameType::METADATA); } bool QuicReceiveControlStream::OnMetadataFramePayload( absl::string_view ) { return true; } bool QuicReceiveControlStream::OnMetadataFrameEnd() { return true; } bool QuicReceiveControlStream::OnUnknownFrameStart( uint64_t frame_type, QuicByteCount , QuicByteCount payload_length) { if (spdy_session()->debug_visitor()) { spdy_session()->debug_visitor()->OnUnknownFrameReceived(id(), frame_type, payload_length); } return ValidateFrameType(static_cast<HttpFrameType>(frame_type)); } bool QuicReceiveControlStream::OnUnknownFramePayload( absl::string_view ) { return true; } bool QuicReceiveControlStream::OnUnknownFrameEnd() { return true; } bool QuicReceiveControlStream::ValidateFrameType(HttpFrameType frame_type) { if (frame_type == HttpFrameType::DATA || frame_type == HttpFrameType::HEADERS || (spdy_session()->perspective() == Perspective::IS_CLIENT && frame_type == HttpFrameType::MAX_PUSH_ID) || (spdy_session()->perspective() == Perspective::IS_SERVER && frame_type == HttpFrameType::ACCEPT_CH)) { stream_delegate()->OnStreamError( QUIC_HTTP_FRAME_UNEXPECTED_ON_CONTROL_STREAM, absl::StrCat("Invalid frame type ", static_cast<int>(frame_type), " received on control stream.")); return false; } if (settings_frame_received_) { if (frame_type == HttpFrameType::SETTINGS) { stream_delegate()->OnStreamError( QUIC_HTTP_INVALID_FRAME_SEQUENCE_ON_CONTROL_STREAM, "SETTINGS frame can only be received once."); return false; } return true; } if (frame_type == HttpFrameType::SETTINGS) { settings_frame_received_ = true; return true; } stream_delegate()->OnStreamError( QUIC_HTTP_MISSING_SETTINGS_FRAME, absl::StrCat("First frame received on control stream is type ", static_cast<int>(frame_type), ", but it must be SETTINGS.")); return false; } }
#include "quiche/quic/core/http/quic_receive_control_stream.h" #include <ostream> #include <string> #include <vector> #include "absl/memory/memory.h" #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/http/http_constants.h" #include "quiche/quic/core/qpack/qpack_header_table.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/test_tools/qpack/qpack_encoder_peer.h" #include "quiche/quic/test_tools/quic_spdy_session_peer.h" #include "quiche/quic/test_tools/quic_stream_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/simple_buffer_allocator.h" namespace quic { class QpackEncoder; namespace test { namespace { using ::testing::_; using ::testing::AnyNumber; using ::testing::StrictMock; struct TestParams { TestParams(const ParsedQuicVersion& version, Perspective perspective) : version(version), perspective(perspective) { QUIC_LOG(INFO) << "TestParams: " << *this; } TestParams(const TestParams& other) : version(other.version), perspective(other.perspective) {} friend std::ostream& operator<<(std::ostream& os, const TestParams& tp) { os << "{ version: " << ParsedQuicVersionToString(tp.version) << ", perspective: " << (tp.perspective == Perspective::IS_CLIENT ? "client" : "server") << "}"; return os; } ParsedQuicVersion version; Perspective perspective; }; std::string PrintToString(const TestParams& tp) { return absl::StrCat( ParsedQuicVersionToString(tp.version), "_", (tp.perspective == Perspective::IS_CLIENT ? "client" : "server")); } std::vector<TestParams> GetTestParams() { std::vector<TestParams> params; ParsedQuicVersionVector all_supported_versions = AllSupportedVersions(); for (const auto& version : AllSupportedVersions()) { if (!VersionUsesHttp3(version.transport_version)) { continue; } for (Perspective p : {Perspective::IS_SERVER, Perspective::IS_CLIENT}) { params.emplace_back(version, p); } } return params; } class TestStream : public QuicSpdyStream { public: TestStream(QuicStreamId id, QuicSpdySession* session) : QuicSpdyStream(id, session, BIDIRECTIONAL) {} ~TestStream() override = default; void OnBodyAvailable() override {} }; class QuicReceiveControlStreamTest : public QuicTestWithParam<TestParams> { public: QuicReceiveControlStreamTest() : connection_(new StrictMock<MockQuicConnection>( &helper_, &alarm_factory_, perspective(), SupportedVersions(GetParam().version))), session_(connection_) { EXPECT_CALL(session_, OnCongestionWindowChange(_)).Times(AnyNumber()); session_.Initialize(); EXPECT_CALL( static_cast<const MockQuicCryptoStream&>(*session_.GetCryptoStream()), encryption_established()) .WillRepeatedly(testing::Return(true)); QuicStreamId id = perspective() == Perspective::IS_SERVER ? GetNthClientInitiatedUnidirectionalStreamId( session_.transport_version(), 3) : GetNthServerInitiatedUnidirectionalStreamId( session_.transport_version(), 3); char type[] = {kControlStream}; QuicStreamFrame data1(id, false, 0, absl::string_view(type, 1)); session_.OnStreamFrame(data1); receive_control_stream_ = QuicSpdySessionPeer::GetReceiveControlStream(&session_); stream_ = new TestStream(GetNthClientInitiatedBidirectionalStreamId( GetParam().version.transport_version, 0), &session_); session_.ActivateStream(absl::WrapUnique(stream_)); } Perspective perspective() const { return GetParam().perspective; } QuicStreamOffset NumBytesConsumed() { return QuicStreamPeer::sequencer(receive_control_stream_) ->NumBytesConsumed(); } MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; StrictMock<MockQuicConnection>* connection_; StrictMock<MockQuicSpdySession> session_; QuicReceiveControlStream* receive_control_stream_; TestStream* stream_; }; INSTANTIATE_TEST_SUITE_P(Tests, QuicReceiveControlStreamTest, ::testing::ValuesIn(GetTestParams()), ::testing::PrintToStringParamName()); TEST_P(QuicReceiveControlStreamTest, ResetControlStream) { EXPECT_TRUE(receive_control_stream_->is_static()); QuicRstStreamFrame rst_frame(kInvalidControlFrameId, receive_control_stream_->id(), QUIC_STREAM_CANCELLED, 1234); EXPECT_CALL(*connection_, CloseConnection(QUIC_HTTP_CLOSED_CRITICAL_STREAM, _, _)); receive_control_stream_->OnStreamReset(rst_frame); } TEST_P(QuicReceiveControlStreamTest, ReceiveSettings) { SettingsFrame settings; settings.values[10] = 2; settings.values[SETTINGS_MAX_FIELD_SECTION_SIZE] = 5; settings.values[SETTINGS_QPACK_BLOCKED_STREAMS] = 12; settings.values[SETTINGS_QPACK_MAX_TABLE_CAPACITY] = 37; std::string data = HttpEncoder::SerializeSettingsFrame(settings); QuicStreamFrame frame(receive_control_stream_->id(), false, 1, data); QpackEncoder* qpack_encoder = session_.qpack_encoder(); QpackEncoderHeaderTable* header_table = QpackEncoderPeer::header_table(qpack_encoder); EXPECT_EQ(std::numeric_limits<size_t>::max(), session_.max_outbound_header_list_size()); EXPECT_EQ(0u, QpackEncoderPeer::maximum_blocked_streams(qpack_encoder)); EXPECT_EQ(0u, header_table->maximum_dynamic_table_capacity()); receive_control_stream_->OnStreamFrame(frame); EXPECT_EQ(5u, session_.max_outbound_header_list_size()); EXPECT_EQ(12u, QpackEncoderPeer::maximum_blocked_streams(qpack_encoder)); EXPECT_EQ(37u, header_table->maximum_dynamic_table_capacity()); } TEST_P(QuicReceiveControlStreamTest, ReceiveSettingsTwice) { SettingsFrame settings; settings.values[0x21] = 100; settings.values[0x40] = 200; std::string settings_frame = HttpEncoder::SerializeSettingsFrame(settings); QuicStreamOffset offset = 1; EXPECT_EQ(offset, NumBytesConsumed()); receive_control_stream_->OnStreamFrame( QuicStreamFrame(receive_control_stream_->id(), false, offset, settings_frame)); offset += settings_frame.length(); EXPECT_EQ(offset, NumBytesConsumed()); EXPECT_CALL( *connection_, CloseConnection(QUIC_HTTP_INVALID_FRAME_SEQUENCE_ON_CONTROL_STREAM, "SETTINGS frame can only be received once.", _)) .WillOnce( Invoke(connection_, &MockQuicConnection::ReallyCloseConnection)); EXPECT_CALL(*connection_, SendConnectionClosePacket(_, _, _)); EXPECT_CALL(session_, OnConnectionClosed(_, _)); receive_control_stream_->OnStreamFrame( QuicStreamFrame(receive_control_stream_->id(), false, offset, settings_frame)); QuicByteCount settings_frame_header_length = 2; EXPECT_EQ(offset + settings_frame_header_length, NumBytesConsumed()); } TEST_P(QuicReceiveControlStreamTest, ReceiveSettingsFragments) { SettingsFrame settings; settings.values[10] = 2; settings.values[SETTINGS_MAX_FIELD_SECTION_SIZE] = 5; std::string data = HttpEncoder::SerializeSettingsFrame(settings); std::string data1 = data.substr(0, 1); std::string data2 = data.substr(1, data.length() - 1); QuicStreamFrame frame(receive_control_stream_->id(), false, 1, data1); QuicStreamFrame frame2(receive_control_stream_->id(), false, 2, data2); EXPECT_NE(5u, session_.max_outbound_header_list_size()); receive_control_stream_->OnStreamFrame(frame); receive_control_stream_->OnStreamFrame(frame2); EXPECT_EQ(5u, session_.max_outbound_header_list_size()); } TEST_P(QuicReceiveControlStreamTest, ReceiveWrongFrame) { quiche::QuicheBuffer data = HttpEncoder::SerializeDataFrameHeader( 2, quiche::SimpleBufferAllocator::Get()); QuicStreamFrame frame(receive_control_stream_->id(), false, 1, data.AsStringView()); EXPECT_CALL( *connection_, CloseConnection(QUIC_HTTP_FRAME_UNEXPECTED_ON_CONTROL_STREAM, _, _)); receive_control_stream_->OnStreamFrame(frame); } TEST_P(QuicReceiveControlStreamTest, ReceivePriorityUpdateFrameBeforeSettingsFrame) { std::string serialized_frame = HttpEncoder::SerializePriorityUpdateFrame({}); QuicStreamFrame data(receive_control_stream_->id(), false, 1, serialized_frame); EXPECT_CALL(*connection_, CloseConnection(QUIC_HTTP_MISSING_SETTINGS_FRAME, "First frame received on control stream is type " "984832, but it must be SETTINGS.", _)) .WillOnce( Invoke(connection_, &MockQuicConnection::ReallyCloseConnection)); EXPECT_CALL(*connection_, SendConnectionClosePacket(_, _, _)); EXPECT_CALL(session_, OnConnectionClosed(_, _)); receive_control_stream_->OnStreamFrame(data); } TEST_P(QuicReceiveControlStreamTest, ReceiveGoAwayFrame) { StrictMock<MockHttp3DebugVisitor> debug_visitor; session_.set_debug_visitor(&debug_visitor); QuicStreamOffset offset = 1; SettingsFrame settings; std::string settings_frame = HttpEncoder::SerializeSettingsFrame(settings); EXPECT_CALL(debug_visitor, OnSettingsFrameReceived(settings)); receive_control_stream_->OnStreamFrame( QuicStreamFrame(receive_control_stream_->id(), false, offset, settings_frame)); offset += settings_frame.length(); GoAwayFrame goaway{ 0}; std::string goaway_frame = HttpEncoder::SerializeGoAwayFrame(goaway); QuicStreamFrame frame(receive_control_stream_->id(), false, offset, goaway_frame); EXPECT_FALSE(session_.goaway_received()); EXPECT_CALL(debug_visitor, OnGoAwayFrameReceived(goaway)); receive_control_stream_->OnStreamFrame(frame); EXPECT_TRUE(session_.goaway_received()); } TEST_P(QuicReceiveControlStreamTest, PushPromiseOnControlStreamShouldClose) { std::string push_promise_frame; ASSERT_TRUE( absl::HexStringToBytes("05" "01" "00", &push_promise_frame)); QuicStreamFrame frame(receive_control_stream_->id(), false, 1, push_promise_frame); EXPECT_CALL(*connection_, CloseConnection(QUIC_HTTP_FRAME_ERROR, _, _)) .WillOnce( Invoke(connection_, &MockQuicConnection::ReallyCloseConnection)); EXPECT_CALL(*connection_, SendConnectionClosePacket(_, _, _)); EXPECT_CALL(session_, OnConnectionClosed(_, _)); receive_control_stream_->OnStreamFrame(frame); } TEST_P(QuicReceiveControlStreamTest, ConsumeUnknownFrame) { EXPECT_EQ(1u, NumBytesConsumed()); QuicStreamOffset offset = 1; std::string settings_frame = HttpEncoder::SerializeSettingsFrame({}); receive_control_stream_->OnStreamFrame( QuicStreamFrame(receive_control_stream_->id(), false, offset, settings_frame)); offset += settings_frame.length(); EXPECT_EQ(offset, NumBytesConsumed()); std::string unknown_frame; ASSERT_TRUE( absl::HexStringToBytes("21" "03" "666f6f", &unknown_frame)); receive_control_stream_->OnStreamFrame(QuicStreamFrame( receive_control_stream_->id(), false, offset, unknown_frame)); offset += unknown_frame.size(); EXPECT_EQ(offset, NumBytesConsumed()); } TEST_P(QuicReceiveControlStreamTest, ReceiveUnknownFrame) { StrictMock<MockHttp3DebugVisitor> debug_visitor; session_.set_debug_visitor(&debug_visitor); const QuicStreamId id = receive_control_stream_->id(); QuicStreamOffset offset = 1; SettingsFrame settings; std::string settings_frame = HttpEncoder::SerializeSettingsFrame(settings); EXPECT_CALL(debug_visitor, OnSettingsFrameReceived(settings)); receive_control_stream_->OnStreamFrame( QuicStreamFrame(id, false, offset, settings_frame)); offset += settings_frame.length(); std::string unknown_frame; ASSERT_TRUE( absl::HexStringToBytes("21" "03" "666f6f", &unknown_frame)); EXPECT_CALL(debug_visitor, OnUnknownFrameReceived(id, 0x21, 3)); receive_control_stream_->OnStreamFrame( QuicStreamFrame(id, false, offset, unknown_frame)); } TEST_P(QuicReceiveControlStreamTest, CancelPushFrameBeforeSettings) { std::string cancel_push_frame; ASSERT_TRUE( absl::HexStringToBytes("03" "01" "01", &cancel_push_frame)); EXPECT_CALL(*connection_, CloseConnection(QUIC_HTTP_FRAME_ERROR, "CANCEL_PUSH frame received.", _)) .WillOnce( Invoke(connection_, &MockQuicConnection::ReallyCloseConnection)); EXPECT_CALL(*connection_, SendConnectionClosePacket(_, _, _)); EXPECT_CALL(session_, OnConnectionClosed(_, _)); receive_control_stream_->OnStreamFrame( QuicStreamFrame(receive_control_stream_->id(), false, 1, cancel_push_frame)); } TEST_P(QuicReceiveControlStreamTest, AcceptChFrameBeforeSettings) { std::string accept_ch_frame; ASSERT_TRUE( absl::HexStringToBytes("4089" "00", &accept_ch_frame)); if (perspective() == Perspective::IS_SERVER) { EXPECT_CALL(*connection_, CloseConnection( QUIC_HTTP_FRAME_UNEXPECTED_ON_CONTROL_STREAM, "Invalid frame type 137 received on control stream.", _)) .WillOnce( Invoke(connection_, &MockQuicConnection::ReallyCloseConnection)); } else { EXPECT_CALL(*connection_, CloseConnection(QUIC_HTTP_MISSING_SETTINGS_FRAME, "First frame received on control stream is " "type 137, but it must be SETTINGS.", _)) .WillOnce( Invoke(connection_, &MockQuicConnection::ReallyCloseConnection)); } EXPECT_CALL(*connection_, SendConnectionClosePacket(_, _, _)); EXPECT_CALL(session_, OnConnectionClosed(_, _)); receive_control_stream_->OnStreamFrame( QuicStreamFrame(receive_control_stream_->id(), false, 1, accept_ch_frame)); } TEST_P(QuicReceiveControlStreamTest, ReceiveAcceptChFrame) { StrictMock<MockHttp3DebugVisitor> debug_visitor; session_.set_debug_visitor(&debug_visitor); const QuicStreamId id = receive_control_stream_->id(); QuicStreamOffset offset = 1; SettingsFrame settings; std::string settings_frame = HttpEncoder::SerializeSettingsFrame(settings); EXPECT_CALL(debug_visitor, OnSettingsFrameReceived(settings)); receive_control_stream_->OnStreamFrame( QuicStreamFrame(id, false, offset, settings_frame)); offset += settings_frame.length(); std::string accept_ch_frame; ASSERT_TRUE( absl::HexStringToBytes("4089" "00", &accept_ch_frame)); if (perspective() == Perspective::IS_CLIENT) { EXPECT_CALL(debug_visitor, OnAcceptChFrameReceived(_)); } else { EXPECT_CALL(*connection_, CloseConnection( QUIC_HTTP_FRAME_UNEXPECTED_ON_CONTROL_STREAM, "Invalid frame type 137 received on control stream.", _)) .WillOnce( Invoke(connection_, &MockQuicConnection::ReallyCloseConnection)); EXPECT_CALL(*connection_, SendConnectionClosePacket(_, _, _)); EXPECT_CALL(session_, OnConnectionClosed(_, _)); } receive_control_stream_->OnStreamFrame( QuicStreamFrame(id, false, offset, accept_ch_frame)); } TEST_P(QuicReceiveControlStreamTest, UnknownFrameBeforeSettings) { std::string unknown_frame; ASSERT_TRUE( absl::HexStringToBytes("21" "03" "666f6f", &unknown_frame)); EXPECT_CALL(*connection_, CloseConnection(QUIC_HTTP_MISSING_SETTINGS_FRAME, "First frame received on control stream is type " "33, but it must be SETTINGS.", _)) .WillOnce( Invoke(connection_, &MockQuicConnection::ReallyCloseConnection)); EXPECT_CALL(*connection_, SendConnectionClosePacket(_, _, _)); EXPECT_CALL(session_, OnConnectionClosed(_, _)); receive_control_stream_->OnStreamFrame( QuicStreamFrame(receive_control_stream_->id(), false, 1, unknown_frame)); } } } }
312
cpp
google/quiche
quic_spdy_server_stream_base
quiche/quic/core/http/quic_spdy_server_stream_base.cc
quiche/quic/core/http/quic_spdy_server_stream_base_test.cc
#ifndef QUICHE_QUIC_CORE_HTTP_QUIC_SPDY_SERVER_STREAM_BASE_H_ #define QUICHE_QUIC_CORE_HTTP_QUIC_SPDY_SERVER_STREAM_BASE_H_ #include "quiche/quic/core/http/quic_spdy_stream.h" namespace quic { class QUICHE_EXPORT QuicSpdyServerStreamBase : public QuicSpdyStream { public: QuicSpdyServerStreamBase(QuicStreamId id, QuicSpdySession* session, StreamType type); QuicSpdyServerStreamBase(PendingStream* pending, QuicSpdySession* session); QuicSpdyServerStreamBase(const QuicSpdyServerStreamBase&) = delete; QuicSpdyServerStreamBase& operator=(const QuicSpdyServerStreamBase&) = delete; void CloseWriteSide() override; void StopReading() override; protected: bool ValidateReceivedHeaders(const QuicHeaderList& header_list) override; }; } #endif #include "quiche/quic/core/http/quic_spdy_server_stream_base.h" #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/http/quic_spdy_session.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/common/quiche_text_utils.h" namespace quic { QuicSpdyServerStreamBase::QuicSpdyServerStreamBase(QuicStreamId id, QuicSpdySession* session, StreamType type) : QuicSpdyStream(id, session, type) {} QuicSpdyServerStreamBase::QuicSpdyServerStreamBase(PendingStream* pending, QuicSpdySession* session) : QuicSpdyStream(pending, session) {} void QuicSpdyServerStreamBase::CloseWriteSide() { if (!fin_received() && !rst_received() && sequencer()->ignore_read_data() && !rst_sent()) { QUICHE_DCHECK(fin_sent() || !session()->connection()->connected()); QUIC_DVLOG(1) << " Server: Send QUIC_STREAM_NO_ERROR on stream " << id(); MaybeSendStopSending(QUIC_STREAM_NO_ERROR); } QuicSpdyStream::CloseWriteSide(); } void QuicSpdyServerStreamBase::StopReading() { if (!fin_received() && !rst_received() && write_side_closed() && !rst_sent()) { QUICHE_DCHECK(fin_sent()); QUIC_DVLOG(1) << " Server: Send QUIC_STREAM_NO_ERROR on stream " << id(); MaybeSendStopSending(QUIC_STREAM_NO_ERROR); } QuicSpdyStream::StopReading(); } bool QuicSpdyServerStreamBase::ValidateReceivedHeaders( const QuicHeaderList& header_list) { if (!QuicSpdyStream::ValidateReceivedHeaders(header_list)) { return false; } bool saw_connect = false; bool saw_protocol = false; bool saw_path = false; bool saw_scheme = false; bool saw_method = false; bool saw_authority = false; bool is_extended_connect = false; for (const std::pair<std::string, std::string>& pair : header_list) { if (pair.first == ":method") { saw_method = true; if (pair.second == "CONNECT") { saw_connect = true; if (saw_protocol) { is_extended_connect = true; } } } else if (pair.first == ":protocol") { saw_protocol = true; if (saw_connect) { is_extended_connect = true; } } else if (pair.first == ":scheme") { saw_scheme = true; } else if (pair.first == ":path") { saw_path = true; } else if (pair.first == ":authority") { saw_authority = true; } else if (absl::StrContains(pair.first, ":")) { set_invalid_request_details( absl::StrCat("Unexpected ':' in header ", pair.first, ".")); QUIC_DLOG(ERROR) << invalid_request_details(); return false; } if (is_extended_connect) { if (!spdy_session()->allow_extended_connect()) { set_invalid_request_details( "Received extended-CONNECT request while it is disabled."); QUIC_DLOG(ERROR) << invalid_request_details(); return false; } } else if (saw_method && !saw_connect) { if (saw_protocol) { set_invalid_request_details( "Received non-CONNECT request with :protocol header."); QUIC_DLOG(ERROR) << "Receive non-CONNECT request with :protocol."; return false; } } } if (is_extended_connect) { if (saw_scheme && saw_path && saw_authority) { return true; } set_invalid_request_details( "Missing required pseudo headers for extended-CONNECT."); QUIC_DLOG(ERROR) << invalid_request_details(); return false; } if (saw_connect) { if (saw_path || saw_scheme) { set_invalid_request_details( "Received invalid CONNECT request with disallowed pseudo header."); QUIC_DLOG(ERROR) << invalid_request_details(); return false; } return true; } if (saw_method && saw_authority && saw_path && saw_scheme) { return true; } set_invalid_request_details("Missing required pseudo headers."); QUIC_DLOG(ERROR) << invalid_request_details(); return false; } }
#include "quiche/quic/core/http/quic_spdy_server_stream_base.h" #include <memory> #include <string> #include "absl/memory/memory.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/qpack/qpack_test_utils.h" #include "quiche/quic/test_tools/quic_spdy_session_peer.h" #include "quiche/quic/test_tools/quic_stream_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/spdy/core/http2_header_block.h" using testing::_; namespace quic { namespace test { namespace { class TestQuicSpdyServerStream : public QuicSpdyServerStreamBase { public: TestQuicSpdyServerStream(QuicStreamId id, QuicSpdySession* session, StreamType type) : QuicSpdyServerStreamBase(id, session, type) {} void OnBodyAvailable() override {} }; class QuicSpdyServerStreamBaseTest : public QuicTest { protected: QuicSpdyServerStreamBaseTest() : session_(new MockQuicConnection(&helper_, &alarm_factory_, Perspective::IS_SERVER)) { session_.Initialize(); session_.connection()->SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(session_.perspective())); stream_ = new TestQuicSpdyServerStream(GetNthClientInitiatedBidirectionalStreamId( session_.transport_version(), 0), &session_, BIDIRECTIONAL); session_.ActivateStream(absl::WrapUnique(stream_)); helper_.AdvanceTime(QuicTime::Delta::FromSeconds(1)); } QuicSpdyServerStreamBase* stream_ = nullptr; MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; MockQuicSpdySession session_; }; TEST_F(QuicSpdyServerStreamBaseTest, SendQuicRstStreamNoErrorWithEarlyResponse) { stream_->StopReading(); if (session_.version().UsesHttp3()) { EXPECT_CALL(session_, MaybeSendStopSendingFrame(_, QuicResetStreamError::FromInternal( QUIC_STREAM_NO_ERROR))) .Times(1); } else { EXPECT_CALL( session_, MaybeSendRstStreamFrame( _, QuicResetStreamError::FromInternal(QUIC_STREAM_NO_ERROR), _)) .Times(1); } QuicStreamPeer::SetFinSent(stream_); stream_->CloseWriteSide(); } TEST_F(QuicSpdyServerStreamBaseTest, DoNotSendQuicRstStreamNoErrorWithRstReceived) { EXPECT_FALSE(stream_->reading_stopped()); EXPECT_CALL(session_, MaybeSendRstStreamFrame( _, QuicResetStreamError::FromInternal( VersionHasIetfQuicFrames(session_.transport_version()) ? QUIC_STREAM_CANCELLED : QUIC_RST_ACKNOWLEDGEMENT), _)) .Times(1); QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream_->id(), QUIC_STREAM_CANCELLED, 1234); stream_->OnStreamReset(rst_frame); if (VersionHasIetfQuicFrames(session_.transport_version())) { QuicStopSendingFrame stop_sending(kInvalidControlFrameId, stream_->id(), QUIC_STREAM_CANCELLED); session_.OnStopSendingFrame(stop_sending); } EXPECT_TRUE(stream_->reading_stopped()); EXPECT_TRUE(stream_->write_side_closed()); } TEST_F(QuicSpdyServerStreamBaseTest, AllowExtendedConnect) { QuicHeaderList header_list; header_list.OnHeaderBlockStart(); header_list.OnHeader(":authority", "www.google.com:4433"); header_list.OnHeader(":method", "CONNECT"); header_list.OnHeader(":protocol", "webtransport"); header_list.OnHeader(":path", "/path"); header_list.OnHeader(":scheme", "http"); header_list.OnHeaderBlockEnd(128, 128); stream_->OnStreamHeaderList(false, 0, header_list); EXPECT_EQ(GetQuicReloadableFlag(quic_act_upon_invalid_header) && !session_.allow_extended_connect(), stream_->rst_sent()); } TEST_F(QuicSpdyServerStreamBaseTest, AllowExtendedConnectProtocolFirst) { QuicHeaderList header_list; header_list.OnHeaderBlockStart(); header_list.OnHeader(":protocol", "webtransport"); header_list.OnHeader(":authority", "www.google.com:4433"); header_list.OnHeader(":method", "CONNECT"); header_list.OnHeader(":path", "/path"); header_list.OnHeader(":scheme", "http"); header_list.OnHeaderBlockEnd(128, 128); stream_->OnStreamHeaderList(false, 0, header_list); EXPECT_EQ(GetQuicReloadableFlag(quic_act_upon_invalid_header) && !session_.allow_extended_connect(), stream_->rst_sent()); } TEST_F(QuicSpdyServerStreamBaseTest, InvalidExtendedConnect) { if (!session_.version().UsesHttp3()) { return; } SetQuicReloadableFlag(quic_act_upon_invalid_header, true); QuicHeaderList header_list; header_list.OnHeaderBlockStart(); header_list.OnHeader(":authority", "www.google.com:4433"); header_list.OnHeader(":method", "CONNECT"); header_list.OnHeader(":protocol", "webtransport"); header_list.OnHeader(":scheme", "http"); header_list.OnHeaderBlockEnd(128, 128); EXPECT_CALL( session_, MaybeSendRstStreamFrame( _, QuicResetStreamError::FromInternal(QUIC_BAD_APPLICATION_PAYLOAD), _)); stream_->OnStreamHeaderList(false, 0, header_list); EXPECT_TRUE(stream_->rst_sent()); } TEST_F(QuicSpdyServerStreamBaseTest, VanillaConnectAllowed) { QuicHeaderList header_list; header_list.OnHeaderBlockStart(); header_list.OnHeader(":authority", "www.google.com:4433"); header_list.OnHeader(":method", "CONNECT"); header_list.OnHeaderBlockEnd(128, 128); stream_->OnStreamHeaderList(false, 0, header_list); EXPECT_FALSE(stream_->rst_sent()); } TEST_F(QuicSpdyServerStreamBaseTest, InvalidVanillaConnect) { SetQuicReloadableFlag(quic_act_upon_invalid_header, true); QuicHeaderList header_list; header_list.OnHeaderBlockStart(); header_list.OnHeader(":authority", "www.google.com:4433"); header_list.OnHeader(":method", "CONNECT"); header_list.OnHeader(":scheme", "http"); header_list.OnHeaderBlockEnd(128, 128); EXPECT_CALL( session_, MaybeSendRstStreamFrame( _, QuicResetStreamError::FromInternal(QUIC_BAD_APPLICATION_PAYLOAD), _)); stream_->OnStreamHeaderList(false, 0, header_list); EXPECT_TRUE(stream_->rst_sent()); } TEST_F(QuicSpdyServerStreamBaseTest, InvalidNonConnectWithProtocol) { SetQuicReloadableFlag(quic_act_upon_invalid_header, true); QuicHeaderList header_list; header_list.OnHeaderBlockStart(); header_list.OnHeader(":authority", "www.google.com:4433"); header_list.OnHeader(":method", "GET"); header_list.OnHeader(":scheme", "http"); header_list.OnHeader(":path", "/path"); header_list.OnHeader(":protocol", "webtransport"); header_list.OnHeaderBlockEnd(128, 128); EXPECT_CALL( session_, MaybeSendRstStreamFrame( _, QuicResetStreamError::FromInternal(QUIC_BAD_APPLICATION_PAYLOAD), _)); stream_->OnStreamHeaderList(false, 0, header_list); EXPECT_TRUE(stream_->rst_sent()); } TEST_F(QuicSpdyServerStreamBaseTest, InvalidRequestWithoutScheme) { SetQuicReloadableFlag(quic_act_upon_invalid_header, true); QuicHeaderList header_list; header_list.OnHeaderBlockStart(); header_list.OnHeader(":authority", "www.google.com:4433"); header_list.OnHeader(":method", "GET"); header_list.OnHeader(":path", "/path"); header_list.OnHeaderBlockEnd(128, 128); EXPECT_CALL( session_, MaybeSendRstStreamFrame( _, QuicResetStreamError::FromInternal(QUIC_BAD_APPLICATION_PAYLOAD), _)); stream_->OnStreamHeaderList(false, 0, header_list); EXPECT_TRUE(stream_->rst_sent()); } TEST_F(QuicSpdyServerStreamBaseTest, InvalidRequestWithoutAuthority) { SetQuicReloadableFlag(quic_act_upon_invalid_header, true); QuicHeaderList header_list; header_list.OnHeaderBlockStart(); header_list.OnHeader(":scheme", "http"); header_list.OnHeader(":method", "GET"); header_list.OnHeader(":path", "/path"); header_list.OnHeaderBlockEnd(128, 128); EXPECT_CALL( session_, MaybeSendRstStreamFrame( _, QuicResetStreamError::FromInternal(QUIC_BAD_APPLICATION_PAYLOAD), _)); stream_->OnStreamHeaderList(false, 0, header_list); EXPECT_TRUE(stream_->rst_sent()); } TEST_F(QuicSpdyServerStreamBaseTest, InvalidRequestWithoutMethod) { SetQuicReloadableFlag(quic_act_upon_invalid_header, true); QuicHeaderList header_list; header_list.OnHeaderBlockStart(); header_list.OnHeader(":authority", "www.google.com:4433"); header_list.OnHeader(":scheme", "http"); header_list.OnHeader(":path", "/path"); header_list.OnHeaderBlockEnd(128, 128); EXPECT_CALL( session_, MaybeSendRstStreamFrame( _, QuicResetStreamError::FromInternal(QUIC_BAD_APPLICATION_PAYLOAD), _)); stream_->OnStreamHeaderList(false, 0, header_list); EXPECT_TRUE(stream_->rst_sent()); } TEST_F(QuicSpdyServerStreamBaseTest, InvalidRequestWithoutPath) { SetQuicReloadableFlag(quic_act_upon_invalid_header, true); QuicHeaderList header_list; header_list.OnHeaderBlockStart(); header_list.OnHeader(":authority", "www.google.com:4433"); header_list.OnHeader(":scheme", "http"); header_list.OnHeader(":method", "POST"); header_list.OnHeaderBlockEnd(128, 128); EXPECT_CALL( session_, MaybeSendRstStreamFrame( _, QuicResetStreamError::FromInternal(QUIC_BAD_APPLICATION_PAYLOAD), _)); stream_->OnStreamHeaderList(false, 0, header_list); EXPECT_TRUE(stream_->rst_sent()); } TEST_F(QuicSpdyServerStreamBaseTest, InvalidRequestHeader) { SetQuicReloadableFlag(quic_act_upon_invalid_header, true); QuicHeaderList header_list; header_list.OnHeaderBlockStart(); header_list.OnHeader(":authority", "www.google.com:4433"); header_list.OnHeader(":scheme", "http"); header_list.OnHeader(":method", "POST"); header_list.OnHeader("invalid:header", "value"); header_list.OnHeaderBlockEnd(128, 128); EXPECT_CALL( session_, MaybeSendRstStreamFrame( _, QuicResetStreamError::FromInternal(QUIC_BAD_APPLICATION_PAYLOAD), _)); stream_->OnStreamHeaderList(false, 0, header_list); EXPECT_TRUE(stream_->rst_sent()); } TEST_F(QuicSpdyServerStreamBaseTest, EmptyHeaders) { SetQuicReloadableFlag(quic_act_upon_invalid_header, true); spdy::Http2HeaderBlock empty_header; quic::test::NoopQpackStreamSenderDelegate encoder_stream_sender_delegate; NoopDecoderStreamErrorDelegate decoder_stream_error_delegate; auto qpack_encoder = std::make_unique<quic::QpackEncoder>( &decoder_stream_error_delegate, HuffmanEncoding::kEnabled); qpack_encoder->set_qpack_stream_sender_delegate( &encoder_stream_sender_delegate); std::string payload = qpack_encoder->EncodeHeaderList(stream_->id(), empty_header, nullptr); std::string headers_frame_header = quic::HttpEncoder::SerializeHeadersFrameHeader(payload.length()); EXPECT_CALL( session_, MaybeSendRstStreamFrame( _, QuicResetStreamError::FromInternal(QUIC_BAD_APPLICATION_PAYLOAD), _)); stream_->OnStreamFrame(QuicStreamFrame( stream_->id(), true, 0, absl::StrCat(headers_frame_header, payload))); EXPECT_TRUE(stream_->rst_sent()); } } } }
313
cpp
google/quiche
quic_spdy_stream
quiche/quic/core/http/quic_spdy_stream.cc
quiche/quic/core/http/quic_spdy_stream_test.cc
#ifndef QUICHE_QUIC_CORE_HTTP_QUIC_SPDY_STREAM_H_ #define QUICHE_QUIC_CORE_HTTP_QUIC_SPDY_STREAM_H_ #include <sys/types.h> #include <cstddef> #include <list> #include <memory> #include <optional> #include <string> #include "absl/base/attributes.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/core/http/http_decoder.h" #include "quiche/quic/core/http/http_encoder.h" #include "quiche/quic/core/http/metadata_decoder.h" #include "quiche/quic/core/http/quic_header_list.h" #include "quiche/quic/core/http/quic_spdy_stream_body_manager.h" #include "quiche/quic/core/http/web_transport_stream_adapter.h" #include "quiche/quic/core/qpack/qpack_decoded_headers_accumulator.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_stream.h" #include "quiche/quic/core/quic_stream_priority.h" #include "quiche/quic/core/quic_stream_sequencer.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/web_transport_interface.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/common/capsule.h" #include "quiche/common/platform/api/quiche_mem_slice.h" #include "quiche/spdy/core/http2_header_block.h" #include "quiche/spdy/core/spdy_framer.h" namespace quic { namespace test { class QuicSpdyStreamPeer; class QuicStreamPeer; } class QuicSpdySession; class WebTransportHttp3; class QUICHE_EXPORT QuicSpdyStream : public QuicStream, public quiche::CapsuleParser::Visitor, public QpackDecodedHeadersAccumulator::Visitor { public: class QUICHE_EXPORT Visitor { public: Visitor() {} Visitor(const Visitor&) = delete; Visitor& operator=(const Visitor&) = delete; virtual void OnClose(QuicSpdyStream* stream) = 0; protected: virtual ~Visitor() {} }; class QUICHE_EXPORT MetadataVisitor { public: virtual ~MetadataVisitor() = default; virtual void OnMetadataComplete(size_t frame_len, const QuicHeaderList& header_list) = 0; }; class QUICHE_EXPORT Http3DatagramVisitor { public: virtual ~Http3DatagramVisitor() {} virtual void OnHttp3Datagram(QuicStreamId stream_id, absl::string_view payload) = 0; virtual void OnUnknownCapsule(QuicStreamId stream_id, const quiche::UnknownCapsule& capsule) = 0; }; class QUICHE_EXPORT ConnectIpVisitor { public: virtual ~ConnectIpVisitor() {} virtual bool OnAddressAssignCapsule( const quiche::AddressAssignCapsule& capsule) = 0; virtual bool OnAddressRequestCapsule( const quiche::AddressRequestCapsule& capsule) = 0; virtual bool OnRouteAdvertisementCapsule( const quiche::RouteAdvertisementCapsule& capsule) = 0; virtual void OnHeadersWritten() = 0; }; QuicSpdyStream(QuicStreamId id, QuicSpdySession* spdy_session, StreamType type); QuicSpdyStream(PendingStream* pending, QuicSpdySession* spdy_session); QuicSpdyStream(const QuicSpdyStream&) = delete; QuicSpdyStream& operator=(const QuicSpdyStream&) = delete; ~QuicSpdyStream() override; void OnClose() override; void OnCanWrite() override; virtual void OnStreamHeadersPriority( const spdy::SpdyStreamPrecedence& precedence); virtual void OnStreamHeaderList(bool fin, size_t frame_len, const QuicHeaderList& header_list); void OnPriorityFrame(const spdy::SpdyStreamPrecedence& precedence); void OnStreamReset(const QuicRstStreamFrame& frame) override; void ResetWithError(QuicResetStreamError error) override; bool OnStopSending(QuicResetStreamError error) override; void OnDataAvailable() override; virtual void OnBodyAvailable() = 0; virtual size_t WriteHeaders( spdy::Http2HeaderBlock header_block, bool fin, quiche::QuicheReferenceCountedPointer<QuicAckListenerInterface> ack_listener); virtual void WriteOrBufferBody(absl::string_view data, bool fin); virtual size_t WriteTrailers( spdy::Http2HeaderBlock trailer_block, quiche::QuicheReferenceCountedPointer<QuicAckListenerInterface> ack_listener); bool OnStreamFrameAcked(QuicStreamOffset offset, QuicByteCount data_length, bool fin_acked, QuicTime::Delta ack_delay_time, QuicTime receive_timestamp, QuicByteCount* newly_acked_length) override; void OnStreamFrameRetransmitted(QuicStreamOffset offset, QuicByteCount data_length, bool fin_retransmitted) override; QuicConsumedData WritevBody(const struct iovec* iov, int count, bool fin); QuicConsumedData WriteBodySlices(absl::Span<quiche::QuicheMemSlice> slices, bool fin); void MarkTrailersConsumed(); void ConsumeHeaderList(); virtual size_t Readv(const struct iovec* iov, size_t iov_len); virtual int GetReadableRegions(iovec* iov, size_t iov_len) const; void MarkConsumed(size_t num_bytes); static bool ParseHeaderStatusCode(const spdy::Http2HeaderBlock& header, int* status_code); static bool ParseHeaderStatusCode(absl::string_view status_value, int* status_code); bool IsDoneReading() const; bool HasBytesToRead() const; QuicByteCount ReadableBytes() const; void set_visitor(Visitor* visitor) { visitor_ = visitor; } bool headers_decompressed() const { return headers_decompressed_; } uint64_t total_body_bytes_read() const; const QuicHeaderList& header_list() const { return header_list_; } bool trailers_decompressed() const { return trailers_decompressed_; } const spdy::Http2HeaderBlock& received_trailers() const { return received_trailers_; } bool FinishedReadingHeaders() const; bool FinishedReadingTrailers() const; bool IsSequencerClosed() { return sequencer()->IsClosed(); } void OnHeadersDecoded(QuicHeaderList headers, bool header_list_size_limit_exceeded) override; void OnHeaderDecodingError(QuicErrorCode error_code, absl::string_view error_message) override; QuicSpdySession* spdy_session() const { return spdy_session_; } void MaybeSendPriorityUpdateFrame() override; WebTransportHttp3* web_transport() { return web_transport_.get(); } WebTransportStream* web_transport_stream() { if (web_transport_data_ == nullptr) { return nullptr; } return &web_transport_data_->adapter; } void ConvertToWebTransportDataStream(WebTransportSessionId session_id); void OnCanWriteNewData() override; bool AssertNotWebTransportDataStream(absl::string_view operation); bool CanWriteNewBodyData(QuicByteCount write_size) const; bool OnCapsule(const quiche::Capsule& capsule) override; void OnCapsuleParseFailure(absl::string_view error_message) override; virtual MessageStatus SendHttp3Datagram(absl::string_view payload); void RegisterHttp3DatagramVisitor(Http3DatagramVisitor* visitor); void UnregisterHttp3DatagramVisitor(); void ReplaceHttp3DatagramVisitor(Http3DatagramVisitor* visitor); void RegisterConnectIpVisitor(ConnectIpVisitor* visitor); void UnregisterConnectIpVisitor(); void ReplaceConnectIpVisitor(ConnectIpVisitor* visitor); void SetMaxDatagramTimeInQueue(QuicTime::Delta max_time_in_queue); void OnDatagramReceived(QuicDataReader* reader); QuicByteCount GetMaxDatagramSize() const; void WriteCapsule(const quiche::Capsule& capsule, bool fin = false); void WriteGreaseCapsule(); const std::string& invalid_request_details() const { return invalid_request_details_; } void RegisterMetadataVisitor(MetadataVisitor* visitor); void UnregisterMetadataVisitor(); std::optional<QuicTime::Delta> header_decoding_delay() const { return header_decoding_delay_; } protected: virtual void OnHeadersTooLarge(); virtual void OnInitialHeadersComplete(bool fin, size_t frame_len, const QuicHeaderList& header_list); virtual void OnTrailingHeadersComplete(bool fin, size_t frame_len, const QuicHeaderList& header_list); virtual size_t WriteHeadersImpl( spdy::Http2HeaderBlock header_block, bool fin, quiche::QuicheReferenceCountedPointer<QuicAckListenerInterface> ack_listener); virtual bool CopyAndValidateTrailers(const QuicHeaderList& header_list, bool expect_final_byte_offset, size_t* final_byte_offset, spdy::Http2HeaderBlock* trailers); Visitor* visitor() { return visitor_; } void set_headers_decompressed(bool val) { headers_decompressed_ = val; } virtual bool uses_capsules() const { return capsule_parser_ != nullptr; } void set_ack_listener( quiche::QuicheReferenceCountedPointer<QuicAckListenerInterface> ack_listener) { ack_listener_ = std::move(ack_listener); } void OnWriteSideInDataRecvdState() override; virtual bool ValidateReceivedHeaders(const QuicHeaderList& header_list); virtual bool AreHeaderFieldValuesValid( const QuicHeaderList& header_list) const; virtual void OnInvalidHeaders(); void set_invalid_request_details(std::string invalid_request_details); virtual bool OnDataFrameStart(QuicByteCount header_length, QuicByteCount payload_length); void CloseReadSide() override; private: friend class test::QuicSpdyStreamPeer; friend class test::QuicStreamPeer; friend class QuicStreamUtils; class HttpDecoderVisitor; struct QUICHE_EXPORT WebTransportDataStream { WebTransportDataStream(QuicSpdyStream* stream, WebTransportSessionId session_id); WebTransportSessionId session_id; WebTransportStreamAdapter adapter; }; bool OnDataFramePayload(absl::string_view payload); bool OnDataFrameEnd(); bool OnHeadersFrameStart(QuicByteCount header_length, QuicByteCount payload_length); bool OnHeadersFramePayload(absl::string_view payload); bool OnHeadersFrameEnd(); void OnWebTransportStreamFrameType(QuicByteCount header_length, WebTransportSessionId session_id); bool OnMetadataFrameStart(QuicByteCount header_length, QuicByteCount payload_length); bool OnMetadataFramePayload(absl::string_view payload); bool OnMetadataFrameEnd(); bool OnUnknownFrameStart(uint64_t frame_type, QuicByteCount header_length, QuicByteCount payload_length); bool OnUnknownFramePayload(absl::string_view payload); bool OnUnknownFrameEnd(); QuicByteCount GetNumFrameHeadersInInterval(QuicStreamOffset offset, QuicByteCount data_length) const; void MaybeProcessSentWebTransportHeaders(spdy::Http2HeaderBlock& headers); void MaybeProcessReceivedWebTransportHeaders(); ABSL_MUST_USE_RESULT bool WriteDataFrameHeader(QuicByteCount data_length, bool force_write); void HandleBodyAvailable(); void HandleReceivedDatagram(absl::string_view payload); virtual bool NextHeaderIsTrailer() const { return headers_decompressed_; } QuicSpdySession* spdy_session_; bool on_body_available_called_because_sequencer_is_closed_; Visitor* visitor_; bool blocked_on_decoding_headers_; bool headers_decompressed_; bool header_list_size_limit_exceeded_; QuicHeaderList header_list_; QuicByteCount headers_payload_length_; bool trailers_decompressed_; bool trailers_consumed_; spdy::Http2HeaderBlock received_trailers_; std::unique_ptr<QpackDecodedHeadersAccumulator> qpack_decoded_headers_accumulator_; std::unique_ptr<HttpDecoderVisitor> http_decoder_visitor_; HttpDecoder decoder_; QuicSpdyStreamBodyManager body_manager_; std::unique_ptr<quiche::CapsuleParser> capsule_parser_; QuicStreamOffset sequencer_offset_; bool is_decoder_processing_input_; quiche::QuicheReferenceCountedPointer<QuicAckListenerInterface> ack_listener_; QuicIntervalSet<QuicStreamOffset> unacked_frame_headers_offsets_; QuicStreamPriority last_sent_priority_; std::unique_ptr<WebTransportHttp3> web_transport_; std::unique_ptr<WebTransportDataStream> web_transport_data_; Http3DatagramVisitor* datagram_visitor_ = nullptr; ConnectIpVisitor* connect_ip_visitor_ = nullptr; MetadataVisitor* metadata_visitor_ = nullptr; std::unique_ptr<MetadataDecoder> metadata_decoder_; std::string invalid_request_details_; QuicTime header_block_received_time_ = QuicTime::Zero(); std::optional<QuicTime::Delta> header_decoding_delay_; }; } #endif #include "quiche/quic/core/http/quic_spdy_stream.h" #include <limits> #include <memory> #include <optional> #include <string> #include <utility> #include "absl/base/macros.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/http2/adapter/header_validator.h" #include "quiche/http2/http2_constants.h" #include "quiche/quic/core/http/http_constants.h" #include "quiche/quic/core/http/http_decoder.h" #include "quiche/quic/core/http/http_frames.h" #include "quiche/quic/core/http/quic_spdy_session.h" #include "quiche/quic/core/http/spdy_utils.h" #include "quiche/quic/core/http/web_transport_http3.h" #include "quiche/quic/core/qpack/qpack_decoder.h" #include "quiche/quic/core/qpack/qpack_encoder.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_stream_priority.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/core/quic_write_blocked_list.h" #include "quiche/quic/core/web_transport_interface.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_testvalue.h" #include "quiche/common/capsule.h" #include "quiche/common/platform/api/quiche_flag_utils.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_mem_slice_storage.h" #include "quiche/common/quiche_text_utils.h" #include "quiche/spdy/core/spdy_protocol.h" using ::quiche::Capsule; using ::quiche::CapsuleType; using ::spdy::Http2HeaderBlock; namespace quic { class QuicSpdyStream::HttpDecoderVisitor : public HttpDecoder::Visitor { public: explicit HttpDecoderVisitor(QuicSpdyStream* stream) : stream_(stream) {} HttpDecoderVisitor(const HttpDecoderVisitor&) = delete; HttpDecoderVisitor& operator=(const HttpDecoderVisitor&) = delete; void OnError(HttpDecoder* decoder) override { stream_->OnUnrecoverableError(decoder->error(), decoder->error_detail()); } bool OnMaxPushIdFrame() override { CloseConnectionOnWrongFrame("Max Push Id"); return false; } bool OnGoAwayFrame(const GoAwayFrame& ) override { CloseConnectionOnWrongFrame("Goaway"); return false; } bool OnSettingsFrameStart(QuicByteCount ) override { CloseConnectionOnWrongFrame("Settings"); return false; } bool OnSettingsFrame(const SettingsFrame& ) override { CloseConnectionOnWrongFrame("Settings"); return false; } bool OnDataFrameStart(QuicByteCount header_length, QuicByteCount payload_length) override { return stream_->OnDataFrameStart(header_length, payload_length); } bool OnDataFramePayload(absl::string_view payload) override { QUICHE_DCHECK(!payload.empty()); return stream_->OnDataFramePayload(payload); } bool OnDataFrameEnd() override { return stream_->OnDataFrameEnd(); } bool OnHeadersFrameStart(QuicByteCount header_length, QuicByteCount payload_length) override { if (!VersionUsesHttp3(stream_->transport_version())) { CloseConnectionOnWrongFrame("Headers"); return false; } return stream_->OnHeadersFrameStart(header_length, payload_length); } bool OnHeadersFramePayload(absl::string_view payload) override { QUICHE_DCHECK(!payload.empty()); if (!VersionUsesHttp3(stream_->transport_version())) { CloseConnectionOnWrongFrame("Headers"); return false; } return stream_->OnHeadersFramePayload(payload); } bool OnHeadersFrameEnd() override { if (!VersionUsesHttp3(stream_->transport_version())) { CloseConnectionOnWrongFrame("Headers"); return false; } return stream_->OnHeadersFrameEnd(); } bool OnPriorityUpdateFrameStart(QuicByteCount ) override { CloseConnectionOnWrongFrame("Priority update"); return false; } bool OnPriorityUpdateFrame(const PriorityUpdateFrame& ) override { CloseConnectionOnWrongFrame("Priority update"); return false; } bool OnAcceptChFrameStart(QuicByteCount ) override { CloseConnectionOnWrongFrame("ACCEPT_CH"); return false; } bool OnAcceptChFrame(const AcceptChFrame& ) override { CloseConnectionOnWrongFrame("ACCEPT_CH"); return false; } void OnWebTransportStreamFrameType( QuicByteCount header_length, WebTransportSessionId session_id) override { stream_->OnWebTransportStreamFrameType(header_length, session_id); } bool OnMetadataFrameStart(QuicByteCount header_length, QuicByteCount payload_length) override { if (!VersionUsesHttp3(stream_->transport_version())) { CloseConnectionOnWrongFrame("Metadata"); return false; } return stream_->OnMetadataFrameStart(header_length, payload_length); } bool OnMetadataFramePayload(absl::string_view payload) override { QUICHE_DCHECK(!payload.empty()); if (!VersionUsesHttp3(stream_->transport_version())) { CloseConnectionOnWrongFrame("Metadata"); return false; } return stream_->OnMetadataFramePayload(payload); } bool OnMetadataFrameEnd() override { if (!VersionUsesHttp3(stream_->transport_version())) { CloseConnectionOnWrongFrame("Metadata"); return false; } return stream_->OnMetadataFrameEnd(); } bool OnUnknownFrameStart(uint64_t frame_type, QuicByteCount header_length, QuicByteCount payload_length) override { return stream_->OnUnknownFrameStart(frame_type, header_length, payload_length); } bool OnUnknownFramePayload(absl::string_view payload) override { return stream_->OnUnknownFramePayload(payload); } bool OnUnknownFrameEnd() override { return stream_->OnUnknownFrameEnd(); } private: void CloseConnectionOnWrongFrame(absl::string_view frame_type) { stream_->OnUnrecoverableError( QUIC_HTTP_FRAME_UNEXPECTED_ON_SPDY_STREAM, absl::StrCat(frame_type, " frame received on data stream")); } QuicSpdyStream* stream_; }; #define ENDPOINT \ (session()->perspective() == Perspective::IS_SERVER ? "Server: " \ : "Client:" \ " ") QuicSpdyStream::QuicSpdyStream(QuicStreamId id, QuicSpdySession* spdy_session, StreamType type) : QuicStream(id, spdy_session, false, type), spdy_session_(spdy_session), on_body_available_called_because_sequencer_is_closed_(false), visitor_(nullptr), blocked_on_decoding_headers_(false), headers_decompressed_(false), header_list_size_limit_exceeded_(false), headers_payload_length_(0), trailers_decompressed_(false), trailers_consumed_(false), http_decoder_visitor_(std::make_unique<HttpDecoderVisitor>(this)), decoder_(http_decoder_visitor_.get()), sequencer_offset_(0), is_decoder_processing_input_(false), ack_listener_(nullptr) { QUICHE_DCHECK_EQ(session()->connection(), spdy_session->connection()); QUICHE_DCHECK_EQ(transport_version(), spdy_session->transport_version()); QUICHE_DCHECK(!QuicUtils::IsCryptoStreamId(transport_version(), id)); QUICHE_DCHECK_EQ(0u, sequencer()->NumBytesConsumed()); if (!VersionUsesHttp3(transport_version())) { sequencer()->SetBlockedUntilFlush(); } if (VersionUsesHttp3(transport_version())) { sequencer()->set_level_triggered(true); } spdy_session_->OnStreamCreated(this); } QuicSpdyStream::QuicSpdyStream(PendingStream* pending, QuicSpdySession* spdy_session) : QuicStream(pending, spdy_session, false), spdy_session_(spdy_session), on_body_available_called_because_sequencer_is_closed_(false), visitor_(nullptr), blocked_on_decoding_headers_(false), headers_decompressed_(false), header_list_size_limit_exceeded_(false), headers_payload_length_(0), trailers_decompressed_(false), trailers_consumed_(false), http_decoder_visitor_(std::make_unique<HttpDecoderVisitor>(this)), decoder_(http_decoder_visitor_.get()), sequencer_offset_(sequencer()->NumBytesConsumed()), is_decoder_processing_input_(false), ack_listener_(nullptr) { QUICHE_DCHECK_EQ(session()->connection(), spdy_session->connection()); QUICHE_DCHECK_EQ(transport_version(), spdy_session->transport_version()); QUICHE_DCHECK(!QuicUtils::IsCryptoStreamId(transport_version(), id())); if (!VersionUsesHttp3(transport_version())) { sequencer()->SetBlockedUntilFlush(); } if (VersionUsesHttp3(transport_version())) { sequencer()->set_level_triggered(true); } spdy_session_->OnStreamCreated(this); } QuicSpdyStream::~QuicSpdyStream() {} size_t QuicSpdyStream::WriteHeaders( Http2HeaderBlock header_block, bool fin, quiche::QuicheReferenceCountedPointer<QuicAckListenerInterface> ack_listener) { if (!AssertNotWebTransportDataStream("writing headers")) {
#include "quiche/quic/core/http/quic_spdy_stream.h" #include <algorithm> #include <array> #include <cstring> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/memory/memory.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/http/http_constants.h" #include "quiche/quic/core/http/http_encoder.h" #include "quiche/quic/core/http/http_frames.h" #include "quiche/quic/core/http/quic_spdy_session.h" #include "quiche/quic/core/http/spdy_utils.h" #include "quiche/quic/core/http/web_transport_http3.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_stream_sequencer_buffer.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/core/quic_write_blocked_list.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/qpack/qpack_test_utils.h" #include "quiche/quic/test_tools/quic_config_peer.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_flow_controller_peer.h" #include "quiche/quic/test_tools/quic_session_peer.h" #include "quiche/quic/test_tools/quic_spdy_session_peer.h" #include "quiche/quic/test_tools/quic_spdy_stream_peer.h" #include "quiche/quic/test_tools/quic_stream_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/capsule.h" #include "quiche/common/quiche_ip_address.h" #include "quiche/common/quiche_mem_slice_storage.h" #include "quiche/common/simple_buffer_allocator.h" using quiche::Capsule; using quiche::IpAddressRange; using spdy::Http2HeaderBlock; using spdy::kV3HighestPriority; using spdy::kV3LowestPriority; using testing::_; using testing::AnyNumber; using testing::AtLeast; using testing::DoAll; using testing::ElementsAre; using testing::HasSubstr; using testing::Invoke; using testing::InvokeWithoutArgs; using testing::MatchesRegex; using testing::Optional; using testing::Pair; using testing::Return; using testing::SaveArg; using testing::StrictMock; namespace quic { namespace test { namespace { constexpr bool kShouldProcessData = true; constexpr absl::string_view kDataFramePayload = "some data"; class TestCryptoStream : public QuicCryptoStream, public QuicCryptoHandshaker { public: explicit TestCryptoStream(QuicSession* session) : QuicCryptoStream(session), QuicCryptoHandshaker(this, session), encryption_established_(false), one_rtt_keys_available_(false), params_(new QuicCryptoNegotiatedParameters) { params_->cipher_suite = 1; } void OnHandshakeMessage(const CryptoHandshakeMessage& ) override { encryption_established_ = true; one_rtt_keys_available_ = true; QuicErrorCode error; std::string error_details; session()->config()->SetInitialStreamFlowControlWindowToSend( kInitialStreamFlowControlWindowForTest); session()->config()->SetInitialSessionFlowControlWindowToSend( kInitialSessionFlowControlWindowForTest); if (session()->version().UsesTls()) { if (session()->perspective() == Perspective::IS_CLIENT) { session()->config()->SetOriginalConnectionIdToSend( session()->connection()->connection_id()); session()->config()->SetInitialSourceConnectionIdToSend( session()->connection()->connection_id()); } else { session()->config()->SetInitialSourceConnectionIdToSend( session()->connection()->client_connection_id()); } TransportParameters transport_parameters; EXPECT_TRUE( session()->config()->FillTransportParameters(&transport_parameters)); error = session()->config()->ProcessTransportParameters( transport_parameters, false, &error_details); } else { CryptoHandshakeMessage msg; session()->config()->ToHandshakeMessage(&msg, transport_version()); error = session()->config()->ProcessPeerHello(msg, CLIENT, &error_details); } EXPECT_THAT(error, IsQuicNoError()); session()->OnNewEncryptionKeyAvailable( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(session()->perspective())); session()->OnConfigNegotiated(); if (session()->version().UsesTls()) { session()->OnTlsHandshakeComplete(); } else { session()->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); } if (session()->version().UsesTls()) { EXPECT_CALL(*this, HasPendingRetransmission()); } session()->DiscardOldEncryptionKey(ENCRYPTION_INITIAL); } ssl_early_data_reason_t EarlyDataReason() const override { return ssl_early_data_unknown; } bool encryption_established() const override { return encryption_established_; } bool one_rtt_keys_available() const override { return one_rtt_keys_available_; } HandshakeState GetHandshakeState() const override { return one_rtt_keys_available() ? HANDSHAKE_COMPLETE : HANDSHAKE_START; } void SetServerApplicationStateForResumption( std::unique_ptr<ApplicationState> ) override {} std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter() override { return nullptr; } std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override { return nullptr; } const QuicCryptoNegotiatedParameters& crypto_negotiated_params() const override { return *params_; } CryptoMessageParser* crypto_message_parser() override { return QuicCryptoHandshaker::crypto_message_parser(); } void OnPacketDecrypted(EncryptionLevel ) override {} void OnOneRttPacketAcknowledged() override {} void OnHandshakePacketSent() override {} void OnConnectionClosed(const QuicConnectionCloseFrame& , ConnectionCloseSource ) override {} void OnHandshakeDoneReceived() override {} void OnNewTokenReceived(absl::string_view ) override {} std::string GetAddressToken( const CachedNetworkParameters* ) const override { return ""; } bool ValidateAddressToken(absl::string_view ) const override { return true; } const CachedNetworkParameters* PreviousCachedNetworkParams() const override { return nullptr; } void SetPreviousCachedNetworkParams( CachedNetworkParameters ) override {} MOCK_METHOD(void, OnCanWrite, (), (override)); bool HasPendingCryptoRetransmission() const override { return false; } MOCK_METHOD(bool, HasPendingRetransmission, (), (const, override)); bool ExportKeyingMaterial(absl::string_view , absl::string_view , size_t , std::string* ) override { return false; } SSL* GetSsl() const override { return nullptr; } bool IsCryptoFrameExpectedForEncryptionLevel( EncryptionLevel level) const override { return level != ENCRYPTION_ZERO_RTT; } EncryptionLevel GetEncryptionLevelToSendCryptoDataOfSpace( PacketNumberSpace space) const override { switch (space) { case INITIAL_DATA: return ENCRYPTION_INITIAL; case HANDSHAKE_DATA: return ENCRYPTION_HANDSHAKE; case APPLICATION_DATA: return ENCRYPTION_FORWARD_SECURE; default: QUICHE_DCHECK(false); return NUM_ENCRYPTION_LEVELS; } } private: using QuicCryptoStream::session; bool encryption_established_; bool one_rtt_keys_available_; quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> params_; }; class TestStream : public QuicSpdyStream { public: TestStream(QuicStreamId id, QuicSpdySession* session, bool should_process_data) : QuicSpdyStream(id, session, BIDIRECTIONAL), should_process_data_(should_process_data), headers_payload_length_(0) {} ~TestStream() override = default; using QuicSpdyStream::set_ack_listener; using QuicSpdyStream::ValidateReceivedHeaders; using QuicStream::CloseWriteSide; using QuicStream::sequencer; using QuicStream::WriteOrBufferData; void OnBodyAvailable() override { if (!should_process_data_) { return; } char buffer[2048]; struct iovec vec; vec.iov_base = buffer; vec.iov_len = ABSL_ARRAYSIZE(buffer); size_t bytes_read = Readv(&vec, 1); data_ += std::string(buffer, bytes_read); } MOCK_METHOD(void, WriteHeadersMock, (bool fin), ()); size_t WriteHeadersImpl( spdy::Http2HeaderBlock header_block, bool fin, quiche::QuicheReferenceCountedPointer<QuicAckListenerInterface> ) override { saved_headers_ = std::move(header_block); WriteHeadersMock(fin); if (VersionUsesHttp3(transport_version())) { return QuicSpdyStream::WriteHeadersImpl(saved_headers_.Clone(), fin, nullptr); } return 0; } const std::string& data() const { return data_; } const spdy::Http2HeaderBlock& saved_headers() const { return saved_headers_; } void OnStreamHeaderList(bool fin, size_t frame_len, const QuicHeaderList& header_list) override { headers_payload_length_ = frame_len; QuicSpdyStream::OnStreamHeaderList(fin, frame_len, header_list); } size_t headers_payload_length() const { return headers_payload_length_; } private: bool should_process_data_; spdy::Http2HeaderBlock saved_headers_; std::string data_; size_t headers_payload_length_; }; class TestSession : public MockQuicSpdySession { public: explicit TestSession(QuicConnection* connection) : MockQuicSpdySession(connection, false), crypto_stream_(this) {} TestCryptoStream* GetMutableCryptoStream() override { return &crypto_stream_; } const TestCryptoStream* GetCryptoStream() const override { return &crypto_stream_; } WebTransportHttp3VersionSet LocallySupportedWebTransportVersions() const override { return locally_supported_webtransport_versions_; } void EnableWebTransport(WebTransportHttp3VersionSet versions = kDefaultSupportedWebTransportVersions) { locally_supported_webtransport_versions_ = versions; } HttpDatagramSupport LocalHttpDatagramSupport() override { return local_http_datagram_support_; } void set_local_http_datagram_support(HttpDatagramSupport value) { local_http_datagram_support_ = value; } private: WebTransportHttp3VersionSet locally_supported_webtransport_versions_; HttpDatagramSupport local_http_datagram_support_ = HttpDatagramSupport::kNone; StrictMock<TestCryptoStream> crypto_stream_; }; class TestMockUpdateStreamSession : public MockQuicSpdySession { public: explicit TestMockUpdateStreamSession(QuicConnection* connection) : MockQuicSpdySession(connection) {} void UpdateStreamPriority(QuicStreamId id, const QuicStreamPriority& new_priority) override { EXPECT_EQ(id, expected_stream_->id()); EXPECT_EQ(expected_priority_, new_priority.http()); EXPECT_EQ(QuicStreamPriority(expected_priority_), expected_stream_->priority()); } void SetExpectedStream(QuicSpdyStream* stream) { expected_stream_ = stream; } void SetExpectedPriority(const HttpStreamPriority& priority) { expected_priority_ = priority; } private: QuicSpdyStream* expected_stream_; HttpStreamPriority expected_priority_; }; class QuicSpdyStreamTest : public QuicTestWithParam<ParsedQuicVersion> { protected: QuicSpdyStreamTest() { headers_[":host"] = "www.google.com"; headers_[":path"] = "/index.hml"; headers_[":scheme"] = "https"; headers_["cookie"] = "__utma=208381060.1228362404.1372200928.1372200928.1372200928.1; " "__utmc=160408618; " "GX=DQAAAOEAAACWJYdewdE9rIrW6qw3PtVi2-d729qaa-74KqOsM1NVQblK4VhX" "hoALMsy6HOdDad2Sz0flUByv7etmo3mLMidGrBoljqO9hSVA40SLqpG_iuKKSHX" "RW3Np4bq0F0SDGDNsW0DSmTS9ufMRrlpARJDS7qAI6M3bghqJp4eABKZiRqebHT" "pMU-RXvTI5D5oCF1vYxYofH_l1Kviuiy3oQ1kS1enqWgbhJ2t61_SNdv-1XJIS0" "O3YeHLmVCs62O6zp89QwakfAWK9d3IDQvVSJzCQsvxvNIvaZFa567MawWlXg0Rh" "1zFMi5vzcns38-8_Sns; " "GA=v*2%2Fmem*57968640*47239936%2Fmem*57968640*47114716%2Fno-nm-" "yj*15%2Fno-cc-yj*5%2Fpc-ch*133685%2Fpc-s-cr*133947%2Fpc-s-t*1339" "47%2Fno-nm-yj*4%2Fno-cc-yj*1%2Fceft-as*1%2Fceft-nqas*0%2Fad-ra-c" "v_p%2Fad-nr-cv_p-f*1%2Fad-v-cv_p*859%2Fad-ns-cv_p-f*1%2Ffn-v-ad%" "2Fpc-t*250%2Fpc-cm*461%2Fpc-s-cr*722%2Fpc-s-t*722%2Fau_p*4" "SICAID=AJKiYcHdKgxum7KMXG0ei2t1-W4OD1uW-ecNsCqC0wDuAXiDGIcT_HA2o1" "3Rs1UKCuBAF9g8rWNOFbxt8PSNSHFuIhOo2t6bJAVpCsMU5Laa6lewuTMYI8MzdQP" "ARHKyW-koxuhMZHUnGBJAM1gJODe0cATO_KGoX4pbbFxxJ5IicRxOrWK_5rU3cdy6" "edlR9FsEdH6iujMcHkbE5l18ehJDwTWmBKBzVD87naobhMMrF6VvnDGxQVGp9Ir_b" "Rgj3RWUoPumQVCxtSOBdX0GlJOEcDTNCzQIm9BSfetog_eP_TfYubKudt5eMsXmN6" "QnyXHeGeK2UINUzJ-D30AFcpqYgH9_1BvYSpi7fc7_ydBU8TaD8ZRxvtnzXqj0RfG" "tuHghmv3aD-uzSYJ75XDdzKdizZ86IG6Fbn1XFhYZM-fbHhm3mVEXnyRW4ZuNOLFk" "Fas6LMcVC6Q8QLlHYbXBpdNFuGbuZGUnav5C-2I_-46lL0NGg3GewxGKGHvHEfoyn" "EFFlEYHsBQ98rXImL8ySDycdLEFvBPdtctPmWCfTxwmoSMLHU2SCVDhbqMWU5b0yr" "JBCScs_ejbKaqBDoB7ZGxTvqlrB__2ZmnHHjCr8RgMRtKNtIeuZAo "; } ~QuicSpdyStreamTest() override = default; std::string EncodeQpackHeaders( std::vector<std::pair<absl::string_view, absl::string_view>> headers) { Http2HeaderBlock header_block; for (const auto& header_field : headers) { header_block.AppendValueOrAddHeader(header_field.first, header_field.second); } return EncodeQpackHeaders(header_block); } std::string EncodeQpackHeaders(const Http2HeaderBlock& header) { NoopQpackStreamSenderDelegate encoder_stream_sender_delegate; auto qpack_encoder = std::make_unique<QpackEncoder>( session_.get(), HuffmanEncoding::kEnabled); qpack_encoder->set_qpack_stream_sender_delegate( &encoder_stream_sender_delegate); return qpack_encoder->EncodeHeaderList( 0, header, nullptr); } void Initialize(bool stream_should_process_data) { InitializeWithPerspective(stream_should_process_data, Perspective::IS_SERVER); } void InitializeWithPerspective(bool stream_should_process_data, Perspective perspective) { connection_ = new StrictMock<MockQuicConnection>( &helper_, &alarm_factory_, perspective, SupportedVersions(GetParam())); session_ = std::make_unique<StrictMock<TestSession>>(connection_); EXPECT_CALL(*session_, OnCongestionWindowChange(_)).Times(AnyNumber()); session_->Initialize(); if (connection_->version().SupportsAntiAmplificationLimit()) { QuicConnectionPeer::SetAddressValidated(connection_); } connection_->AdvanceTime(QuicTime::Delta::FromSeconds(1)); ON_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillByDefault( Invoke(session_.get(), &MockQuicSpdySession::ConsumeData)); stream_ = new StrictMock<TestStream>(GetNthClientInitiatedBidirectionalId(0), session_.get(), stream_should_process_data); session_->ActivateStream(absl::WrapUnique(stream_)); stream2_ = new StrictMock<TestStream>(GetNthClientInitiatedBidirectionalId(1), session_.get(), stream_should_process_data); session_->ActivateStream(absl::WrapUnique(stream2_)); QuicConfigPeer::SetReceivedInitialSessionFlowControlWindow( session_->config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesUnidirectional( session_->config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesIncomingBidirectional( session_->config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesOutgoingBidirectional( session_->config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedMaxUnidirectionalStreams(session_->config(), 10); session_->OnConfigNegotiated(); if (UsesHttp3()) { int num_control_stream_writes = 3; auto send_control_stream = QuicSpdySessionPeer::GetSendControlStream(session_.get()); EXPECT_CALL(*session_, WritevData(send_control_stream->id(), _, _, _, _, _)) .Times(num_control_stream_writes); } TestCryptoStream* crypto_stream = session_->GetMutableCryptoStream(); EXPECT_CALL(*crypto_stream, HasPendingRetransmission()).Times(AnyNumber()); if (connection_->version().UsesTls() && session_->perspective() == Perspective::IS_SERVER) { EXPECT_CALL(*connection_, SendControlFrame(_)) .WillOnce(Invoke(&ClearControlFrame)); } CryptoHandshakeMessage message; session_->GetMutableCryptoStream()->OnHandshakeMessage(message); } QuicHeaderList ProcessHeaders(bool fin, const Http2HeaderBlock& headers) { QuicHeaderList h = AsHeaderList(headers); stream_->OnStreamHeaderList(fin, h.uncompressed_header_bytes(), h); return h; } QuicStreamId GetNthClientInitiatedBidirectionalId(int n) { return GetNthClientInitiatedBidirectionalStreamId( connection_->transport_version(), n); } bool UsesHttp3() const { return VersionUsesHttp3(GetParam().transport_version); } std::string HeadersFrame( std::vector<std::pair<absl::string_view, absl::string_view>> headers) { return HeadersFrame(EncodeQpackHeaders(headers)); } std::string HeadersFrame(const Http2HeaderBlock& headers) { return HeadersFrame(EncodeQpackHeaders(headers)); } std::string HeadersFrame(absl::string_view payload) { std::string headers_frame_header = HttpEncoder::SerializeHeadersFrameHeader(payload.length()); return absl::StrCat(headers_frame_header, payload); } std::string DataFrame(absl::string_view payload) { quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader( payload.length(), quiche::SimpleBufferAllocator::Get()); return absl::StrCat(header.AsStringView(), payload); } std::string UnknownFrame(uint64_t frame_type, absl::string_view payload) { std::string frame; const size_t length = QuicDataWriter::GetVarInt62Len(frame_type) + QuicDataWriter::GetVarInt62Len(payload.size()) + payload.size(); frame.resize(length); QuicDataWriter writer(length, const_cast<char*>(frame.data())); writer.WriteVarInt62(frame_type); writer.WriteStringPieceVarInt62(payload); QUICHE_DCHECK_EQ(length, writer.length()); return frame; } MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; MockQuicConnection* connection_; std::unique_ptr<TestSession> session_; TestStream* stream_; TestStream* stream2_; Http2HeaderBlock headers_; }; INSTANTIATE_TEST_SUITE_P(Tests, QuicSpdyStreamTest, ::testing::ValuesIn(AllSupportedVersions()), ::testing::PrintToStringParamName()); TEST_P(QuicSpdyStreamTest, ProcessHeaderList) { Initialize(kShouldProcessData); stream_->OnStreamHeadersPriority( spdy::SpdyStreamPrecedence(kV3HighestPriority)); ProcessHeaders(false, headers_); EXPECT_EQ("", stream_->data()); EXPECT_FALSE(stream_->header_list().empty()); EXPECT_FALSE(stream_->IsDoneReading()); } TEST_P(QuicSpdyStreamTest, ProcessTooLargeHeaderList) { Initialize(kShouldProcessData); if (!UsesHttp3()) { QuicHeaderList headers; stream_->OnStreamHeadersPriority( spdy::SpdyStreamPrecedence(kV3HighestPriority)); EXPECT_CALL( *session_, MaybeSendRstStreamFrame( stream_->id(), QuicResetStreamError::FromInternal(QUIC_HEADERS_TOO_LARGE), 0)); stream_->OnStreamHeaderList(false, 1 << 20, headers); EXPECT_THAT(stream_->stream_error(), IsStreamError(QUIC_HEADERS_TOO_LARGE)); return; } session_->set_max_inbound_header_list_size(40); std::string headers = HeadersFrame({std::make_pair("foo", "too long headers")}); QuicStreamFrame frame(stream_->id(), false, 0, headers); EXPECT_CALL(*session_, MaybeSendStopSendingFrame( stream_->id(), QuicResetStreamError::FromInternal( QUIC_HEADERS_TOO_LARGE))); EXPECT_CALL( *session_, MaybeSendRstStreamFrame( stream_->id(), QuicResetStreamError::FromInternal(QUIC_HEADERS_TOO_LARGE), 0)); if (!GetQuicRestartFlag(quic_opport_bundle_qpack_decoder_data5)) { auto qpack_decoder_stream = QuicSpdySessionPeer::GetQpackDecoderSendStream(session_.get()); EXPECT_CALL(*session_, WritevData(qpack_decoder_stream->id(), _, _, NO_FIN, _, _)) .Times(2); } stream_->OnStreamFrame(frame); EXPECT_THAT(stream_->stream_error(), IsStreamError(QUIC_HEADERS_TOO_LARGE)); } TEST_P(QuicSpdyStreamTest, QpackProcessLargeHeaderListDiscountOverhead) { if (!UsesHttp3()) { return; } SetQuicFlag(quic_header_size_limit_includes_overhead, false); Initialize(kShouldProcessData); session_->set_max_inbound_header_list_size(40); std::string headers = HeadersFrame({std::make_pair("foo", "too long headers")}); QuicStreamFrame frame(stream_->id(), false, 0, headers); stream_->OnStreamFrame(frame); EXPECT_THAT(stream_->stream_error(), IsStreamError(QUIC_STREAM_NO_ERROR)); } TEST_P(QuicSpdyStreamTest, ProcessHeaderListWithFin) { Initialize(kShouldProcessData); size_t total_bytes = 0; QuicHeaderList headers; for (auto p : headers_) { headers.OnHeader(p.first, p.second); total_bytes += p.first.size() + p.second.size(); } stream_->OnStreamHeadersPriority( spdy::SpdyStreamPrecedence(kV3HighestPriority)); stream_->OnStreamHeaderList(true, total_bytes, headers); EXPECT_EQ("", stream_->data()); EXPECT_FALSE(stream_->header_list().empty()); EXPECT_FALSE(stream_->IsDoneReading()); EXPECT_TRUE(stream_->HasReceivedFinalOffset()); } TEST_P(QuicSpdyStreamTest, ParseHeaderStatusCode) { Initialize(kShouldProcessData); int status_code = 0; headers_[":status"] = "404"; EXPECT_TRUE(stream_->ParseHeaderStatusCode(headers_, &status_code)); EXPECT_EQ(404, status_code); headers_[":status"] = "100"; EXPECT_TRUE(stream_->ParseHeaderStatusCode(headers_, &status_code)); EXPECT_EQ(100, status_code); headers_[":status"] = "599"; EXPECT_TRUE(stream_->ParseHeaderStatusCode(headers_, &status_code)); EXPECT_EQ(599, status_code); headers_[":status"] = "010"; EXPECT_FALSE(stream_->ParseHeaderStatusCode(headers_, &status_code)); headers_[":status"] = "600"; EXPECT_FALSE(stream_->ParseHeaderStatusCode(headers_, &status_code)); headers_[":status"] = "200 ok"; EXPECT_FALSE(stream_->ParseHeaderStatusCode(headers_, &status_code)); headers_[":status"] = "2000"; EXPECT_FALSE(stream_->ParseHeaderStatusCode(headers_, &status_code)); headers_[":status"] = "+200"; EXPECT_FALSE(stream_->ParseHeaderStatusCode(headers_, &status_code)); headers_[":status"] = "+20"; EXPECT_FALSE(stream_->ParseHeaderStatusCode(headers_, &status_code)); headers_[":status"] = "-10"; EXPECT_FALSE(stream_->ParseHeaderStatusCode(headers_, &status_code)); headers_[":status"] = "-100"; EXPECT_FALSE(stream_->ParseHeaderStatusCode(headers_, &status_code)); headers_[":status"] = " 200"; EXPECT_FALSE(stream_->ParseHeaderStatusCode(headers_, &status_code)); headers_[":status"] = "200 "; EXPECT_FALSE(stream_->ParseHeaderStatusCode(headers_, &status_code)); headers_[":status"] = " 200 "; EXPECT_FALSE(stream_->ParseHeaderStatusCode(headers_, &status_code)); headers_[":status"] = " "; EXPECT_FALSE(stream_->ParseHeaderStatusCode(headers_, &status_code)); } TEST_P(QuicSpdyStreamTest, MarkHeadersConsumed) { Initialize(kShouldProcessData); std::string body = "this is the body"; QuicHeaderList headers = ProcessHeaders(false, headers_); EXPECT_EQ(headers, stream_->header_list()); stream_->ConsumeHeaderList(); EXPECT_EQ(QuicHeaderList(), stream_->header_list()); } TEST_P(QuicSpdyStreamTest, ProcessWrongFramesOnSpdyStream) { if (!UsesHttp3()) { return; } Initialize(kShouldProcessData); testing::InSequence s; connection_->AdvanceTime(QuicTime::Delta::FromSeconds(1)); GoAwayFrame goaway; goaway.id = 0x1; std::string goaway_frame = HttpEncoder::SerializeGoAwayFrame(goaway); EXPECT_EQ("", stream_->data()); QuicHeaderList headers = ProcessHeaders(false, headers_); EXPECT_EQ(headers, stream_->header_list()); stream_->ConsumeHeaderList(); QuicStreamFrame frame(GetNthClientInitiatedBidirectionalId(0), false, 0, goaway_frame); EXPECT_CALL(*connection_, CloseConnection(QUIC_HTTP_FRAME_UNEXPECTED_ON_SPDY_STREAM, _, _)) .WillOnce( (Invoke([this](QuicErrorCode error, const std::string& error_details, ConnectionCloseBehavior connection_close_behavior) { connection_->ReallyCloseConnection(error, error_details, connection_close_behavior); }))); EXPECT_CALL(*connection_, SendConnectionClosePacket(_, _, _)); EXPECT_CALL(*session_, OnConnectionClosed(_, _)) .WillOnce(Invoke([this](const QuicConnectionCloseFrame& frame, ConnectionCloseSource source) { session_->ReallyOnConnectionClosed(frame, source); })); EXPECT_CALL(*session_, MaybeSendRstStreamFrame(_, _, _)).Times(2); stream_->OnStreamFrame(frame); } TEST_P(QuicSpdyStreamTest, Http3FrameError) { if (!UsesHttp3()) { return; } Initialize(kShouldProcessData); std::string invalid_http3_frame; ASSERT_TRUE(absl::HexStringToBytes("0500", &invalid_http3_frame)); QuicStreamFrame stream_frame(stream_->id(), false, 0, invalid_http3_frame); EXPECT_CALL(*connection_, CloseConnection(QUIC_HTTP_FRAME_ERROR, _, _)); stream_->OnStreamFrame(stream_frame); } TEST_P(QuicSpdyStreamTest, UnexpectedHttp3Frame) { if (!UsesHttp3()) { return; } Initialize(kShouldProcessData); std::string settings; ASSERT_TRUE(absl::HexStringToBytes("0400", &settings)); QuicStreamFrame stream_frame(stream_->id(), false, 0, settings); EXPECT_CALL(*connection_, CloseConnection(QUIC_HTTP_FRAME_UNEXPECTED_ON_SPDY_STREAM, _, _)); stream_->OnStreamFrame(stream_frame); } TEST_P(QuicSpdyStreamTest, ProcessHeadersAndBody) { Initialize(kShouldProcessData); std::string body = "this is the body"; std::string data = UsesHttp3() ? DataFrame(body) : body; EXPECT_EQ("", stream_->data()); QuicHeaderList headers = ProcessHeaders(false, headers_); EXPECT_EQ(headers, stream_->header_list()); stream_->ConsumeHeaderList(); QuicStreamFrame frame(GetNthClientInitiatedBidirectionalId(0), false, 0, absl::string_view(data)); stream_->OnStreamFrame(frame); EXPECT_EQ(QuicHeaderList(), stream_->header_list()); EXPECT_EQ(body, stream_->data()); } TEST_P(QuicSpdyStreamTest, ProcessHeadersAndBodyFragments) { std::string body = "this is the body"; std::string data = UsesHttp3() ? DataFrame(body) : body; for (size_t fragment_size = 1; fragment_size < data.size(); ++fragment_size) { Initialize(kShouldProcessData); QuicHeaderList headers = ProcessHeaders(false, headers_); ASSERT_EQ(headers, stream_->header_list()); stream_->ConsumeHeaderList(); for (size_t offset = 0; offset < data.size(); offset += fragment_size) { size_t remaining_data = data.size() - offset; absl::string_view fragment(data.data() + offset, std::min(fragment_size, remaining_data)); QuicStreamFrame frame(GetNthClientInitiatedBidirectionalId(0), false, offset, absl::string_view(fragment)); stream_->OnStreamFrame(frame); } ASSERT_EQ(body, stream_->data()) << "fragment_size: " << fragment_size; } } TEST_P(QuicSpdyStreamTest, ProcessHeadersAndBodyFragmentsSplit) { std::string body = "this is the body"; std::string data = UsesHttp3() ? DataFrame(body) : body; for (size_t split_point = 1; split_point < data.size() - 1; ++split_point) { Initialize(kShouldProcessData); QuicHeaderList headers = ProcessHeaders(false, headers_); ASSERT_EQ(headers, stream_->header_list()); stream_->ConsumeHeaderList(); absl::string_view fragment1(data.data(), split_point); QuicStreamFrame frame1(GetNthClientInitiatedBidirectionalId(0), false, 0, absl::string_view(fragment1)); stream_->OnStreamFrame(frame1); absl::string_view fragment2(data.data() + split_point, data.size() - split_point); QuicStreamFrame frame2(GetNthClientInitiatedBidirectionalId(0), false, split_point, absl::string_view(fragment2)); stream_->OnStreamFrame(frame2); ASSERT_EQ(body, stream_->data()) << "split_point: " << split_point; } } TEST_P(QuicSpdyStreamTest, ProcessHeadersAndBodyReadv) { Initialize(!kShouldProcessData); std::string body = "this is the body"; std::string data = UsesHttp3() ? DataFrame(body) : body; ProcessHeaders(false, headers_); QuicStreamFrame frame(GetNthClientInitiatedBidirectionalId(0), false, 0, absl::string_view(data)); stream_->OnStreamFrame(frame); stream_->ConsumeHeaderList(); char buffer[2048]; ASSERT_LT(data.length(), ABSL_ARRAYSIZE(buffer)); struct iovec vec; vec.iov_base = buffer; vec.iov_len = ABSL_ARRAYSIZE(buffer); size_t bytes_read = stream_->Readv(&vec, 1); QuicStreamPeer::CloseReadSide(stream_); EXPECT_EQ(body.length(), bytes_read); EXPECT_EQ(body, std::string(buffer, bytes_read)); } TEST_P(QuicSpdyStreamTest, ProcessHeadersAndLargeBodySmallReadv) { Initialize(kShouldProcessData); std::string body(12 * 1024, 'a'); std::string data = UsesHttp3() ? DataFrame(body) : body; ProcessHeaders(false, headers_); QuicStreamFrame frame(GetNthClientInitiatedBidirectionalId(0), false, 0, absl::string_view(data)); stream_->OnStreamFrame(frame); stream_->Con
314
cpp
google/quiche
quic_send_control_stream
quiche/quic/core/http/quic_send_control_stream.cc
quiche/quic/core/http/quic_send_control_stream_test.cc
#ifndef QUICHE_QUIC_CORE_HTTP_QUIC_SEND_CONTROL_STREAM_H_ #define QUICHE_QUIC_CORE_HTTP_QUIC_SEND_CONTROL_STREAM_H_ #include "quiche/quic/core/http/http_encoder.h" #include "quiche/quic/core/quic_stream.h" #include "quiche/quic/core/quic_stream_priority.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quic { class QuicSpdySession; class QUICHE_EXPORT QuicSendControlStream : public QuicStream { public: QuicSendControlStream(QuicStreamId id, QuicSpdySession* session, const SettingsFrame& settings); QuicSendControlStream(const QuicSendControlStream&) = delete; QuicSendControlStream& operator=(const QuicSendControlStream&) = delete; ~QuicSendControlStream() override = default; void OnStreamReset(const QuicRstStreamFrame& frame) override; bool OnStopSending(QuicResetStreamError code) override; void MaybeSendSettingsFrame(); void WritePriorityUpdate(QuicStreamId stream_id, HttpStreamPriority priority); void SendGoAway(QuicStreamId id); void OnDataAvailable() override { QUICHE_NOTREACHED(); } private: bool settings_sent_; const SettingsFrame settings_; QuicSpdySession* const spdy_session_; }; } #endif #include "quiche/quic/core/http/quic_send_control_stream.h" #include <cstdint> #include <memory> #include <string> #include "absl/base/macros.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/http/http_constants.h" #include "quiche/quic/core/http/quic_spdy_session.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { namespace { } QuicSendControlStream::QuicSendControlStream(QuicStreamId id, QuicSpdySession* spdy_session, const SettingsFrame& settings) : QuicStream(id, spdy_session, true, WRITE_UNIDIRECTIONAL), settings_sent_(false), settings_(settings), spdy_session_(spdy_session) {} void QuicSendControlStream::OnStreamReset(const QuicRstStreamFrame& ) { QUIC_BUG(quic_bug_10382_1) << "OnStreamReset() called for write unidirectional stream."; } bool QuicSendControlStream::OnStopSending(QuicResetStreamError ) { stream_delegate()->OnStreamError( QUIC_HTTP_CLOSED_CRITICAL_STREAM, "STOP_SENDING received for send control stream"); return false; } void QuicSendControlStream::MaybeSendSettingsFrame() { if (settings_sent_) { return; } QuicConnection::ScopedPacketFlusher flusher(session()->connection()); char data[sizeof(kControlStream)]; QuicDataWriter writer(ABSL_ARRAYSIZE(data), data); writer.WriteVarInt62(kControlStream); WriteOrBufferData(absl::string_view(writer.data(), writer.length()), false, nullptr); SettingsFrame settings = settings_; if (!GetQuicFlag(quic_enable_http3_grease_randomness)) { settings.values[0x40] = 20; } else { uint32_t result; QuicRandom::GetInstance()->RandBytes(&result, sizeof(result)); uint64_t setting_id = 0x1fULL * static_cast<uint64_t>(result) + 0x21ULL; QuicRandom::GetInstance()->RandBytes(&result, sizeof(result)); settings.values[setting_id] = result; } std::string settings_frame = HttpEncoder::SerializeSettingsFrame(settings); QUIC_DVLOG(1) << "Control stream " << id() << " is writing settings frame " << settings; if (spdy_session_->debug_visitor()) { spdy_session_->debug_visitor()->OnSettingsFrameSent(settings); } WriteOrBufferData(settings_frame, false, nullptr); settings_sent_ = true; WriteOrBufferData(HttpEncoder::SerializeGreasingFrame(), false, nullptr); } void QuicSendControlStream::WritePriorityUpdate(QuicStreamId stream_id, HttpStreamPriority priority) { QuicConnection::ScopedPacketFlusher flusher(session()->connection()); MaybeSendSettingsFrame(); const std::string priority_field_value = SerializePriorityFieldValue(priority); PriorityUpdateFrame priority_update_frame{stream_id, priority_field_value}; if (spdy_session_->debug_visitor()) { spdy_session_->debug_visitor()->OnPriorityUpdateFrameSent( priority_update_frame); } std::string frame = HttpEncoder::SerializePriorityUpdateFrame(priority_update_frame); QUIC_DVLOG(1) << "Control Stream " << id() << " is writing " << priority_update_frame; WriteOrBufferData(frame, false, nullptr); } void QuicSendControlStream::SendGoAway(QuicStreamId id) { QuicConnection::ScopedPacketFlusher flusher(session()->connection()); MaybeSendSettingsFrame(); GoAwayFrame frame; frame.id = id; if (spdy_session_->debug_visitor()) { spdy_session_->debug_visitor()->OnGoAwayFrameSent(id); } WriteOrBufferData(HttpEncoder::SerializeGoAwayFrame(frame), false, nullptr); } }
#include "quiche/quic/core/http/quic_send_control_stream.h" #include <memory> #include <optional> #include <ostream> #include <string> #include <utility> #include <vector> #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/test_tools/quic_config_peer.h" #include "quiche/quic/test_tools/quic_spdy_session_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace quic { namespace test { namespace { using ::testing::_; using ::testing::AnyNumber; using ::testing::Invoke; using ::testing::StrictMock; struct TestParams { TestParams(const ParsedQuicVersion& version, Perspective perspective) : version(version), perspective(perspective) { QUIC_LOG(INFO) << "TestParams: " << *this; } TestParams(const TestParams& other) : version(other.version), perspective(other.perspective) {} friend std::ostream& operator<<(std::ostream& os, const TestParams& tp) { os << "{ version: " << ParsedQuicVersionToString(tp.version) << ", perspective: " << (tp.perspective == Perspective::IS_CLIENT ? "client" : "server") << "}"; return os; } ParsedQuicVersion version; Perspective perspective; }; std::string PrintToString(const TestParams& tp) { return absl::StrCat( ParsedQuicVersionToString(tp.version), "_", (tp.perspective == Perspective::IS_CLIENT ? "client" : "server")); } std::vector<TestParams> GetTestParams() { std::vector<TestParams> params; ParsedQuicVersionVector all_supported_versions = AllSupportedVersions(); for (const auto& version : AllSupportedVersions()) { if (!VersionUsesHttp3(version.transport_version)) { continue; } for (Perspective p : {Perspective::IS_SERVER, Perspective::IS_CLIENT}) { params.emplace_back(version, p); } } return params; } class QuicSendControlStreamTest : public QuicTestWithParam<TestParams> { public: QuicSendControlStreamTest() : connection_(new StrictMock<MockQuicConnection>( &helper_, &alarm_factory_, perspective(), SupportedVersions(GetParam().version))), session_(connection_) { ON_CALL(session_, WritevData(_, _, _, _, _, _)) .WillByDefault(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); } void Initialize() { EXPECT_CALL(session_, OnCongestionWindowChange(_)).Times(AnyNumber()); session_.Initialize(); connection_->SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(connection_->perspective())); send_control_stream_ = QuicSpdySessionPeer::GetSendControlStream(&session_); QuicConfigPeer::SetReceivedInitialSessionFlowControlWindow( session_.config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesUnidirectional( session_.config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedMaxUnidirectionalStreams(session_.config(), 3); session_.OnConfigNegotiated(); } Perspective perspective() const { return GetParam().perspective; } MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; StrictMock<MockQuicConnection>* connection_; StrictMock<MockQuicSpdySession> session_; QuicSendControlStream* send_control_stream_; }; INSTANTIATE_TEST_SUITE_P(Tests, QuicSendControlStreamTest, ::testing::ValuesIn(GetTestParams()), ::testing::PrintToStringParamName()); TEST_P(QuicSendControlStreamTest, WriteSettings) { SetQuicFlag(quic_enable_http3_grease_randomness, false); session_.set_qpack_maximum_dynamic_table_capacity(255); session_.set_qpack_maximum_blocked_streams(16); session_.set_max_inbound_header_list_size(1024); Initialize(); testing::InSequence s; std::string expected_write_data; ASSERT_TRUE( absl::HexStringToBytes("00" "04" "0b" "01" "40ff" "06" "4400" "07" "10" "4040" "14" "4040" "01" "61", &expected_write_data)); if (perspective() == Perspective::IS_CLIENT && QuicSpdySessionPeer::LocalHttpDatagramSupport(&session_) != HttpDatagramSupport::kNone) { ASSERT_TRUE( absl::HexStringToBytes("00" "04" "0d" "01" "40ff" "06" "4400" "07" "10" "33" "01" "4040" "14" "4040" "01" "61", &expected_write_data)); } if (perspective() == Perspective::IS_SERVER && QuicSpdySessionPeer::LocalHttpDatagramSupport(&session_) == HttpDatagramSupport::kNone) { ASSERT_TRUE( absl::HexStringToBytes("00" "04" "0d" "01" "40ff" "06" "4400" "07" "10" "08" "01" "4040" "14" "4040" "01" "61", &expected_write_data)); } if (perspective() == Perspective::IS_SERVER && QuicSpdySessionPeer::LocalHttpDatagramSupport(&session_) != HttpDatagramSupport::kNone) { ASSERT_TRUE( absl::HexStringToBytes("00" "04" "0f" "01" "40ff" "06" "4400" "07" "10" "08" "01" "33" "01" "4040" "14" "4040" "01" "61", &expected_write_data)); } char buffer[1000] = {}; QuicDataWriter writer(sizeof(buffer), buffer); ASSERT_GE(sizeof(buffer), expected_write_data.size()); auto save_write_data = [&writer, this](QuicStreamId , size_t write_length, QuicStreamOffset offset, StreamSendingState , TransmissionType , std::optional<EncryptionLevel> ) { send_control_stream_->WriteStreamData(offset, write_length, &writer); return QuicConsumedData( write_length, false); }; EXPECT_CALL(session_, WritevData(send_control_stream_->id(), _, _, _, _, _)) .WillRepeatedly(Invoke(save_write_data)); send_control_stream_->MaybeSendSettingsFrame(); quiche::test::CompareCharArraysWithHexError( "settings", writer.data(), writer.length(), expected_write_data.data(), expected_write_data.length()); } TEST_P(QuicSendControlStreamTest, WriteSettingsOnlyOnce) { Initialize(); testing::InSequence s; EXPECT_CALL(session_, WritevData(send_control_stream_->id(), 1, _, _, _, _)); EXPECT_CALL(session_, WritevData(send_control_stream_->id(), _, _, _, _, _)) .Times(2); send_control_stream_->MaybeSendSettingsFrame(); send_control_stream_->MaybeSendSettingsFrame(); } TEST_P(QuicSendControlStreamTest, WritePriorityBeforeSettings) { Initialize(); testing::InSequence s; EXPECT_CALL(session_, WritevData(send_control_stream_->id(), _, _, _, _, _)) .Times(4); send_control_stream_->WritePriorityUpdate( 0, HttpStreamPriority{ 3, false}); EXPECT_TRUE(testing::Mock::VerifyAndClearExpectations(&session_)); EXPECT_CALL(session_, WritevData(send_control_stream_->id(), _, _, _, _, _)); send_control_stream_->WritePriorityUpdate( 0, HttpStreamPriority{ 3, false}); } TEST_P(QuicSendControlStreamTest, CloseControlStream) { Initialize(); EXPECT_CALL(*connection_, CloseConnection(QUIC_HTTP_CLOSED_CRITICAL_STREAM, _, _)); send_control_stream_->OnStopSending( QuicResetStreamError::FromInternal(QUIC_STREAM_CANCELLED)); } TEST_P(QuicSendControlStreamTest, ReceiveDataOnSendControlStream) { Initialize(); QuicStreamFrame frame(send_control_stream_->id(), false, 0, "test"); EXPECT_CALL( *connection_, CloseConnection(QUIC_DATA_RECEIVED_ON_WRITE_UNIDIRECTIONAL_STREAM, _, _)); send_control_stream_->OnStreamFrame(frame); } TEST_P(QuicSendControlStreamTest, SendGoAway) { Initialize(); StrictMock<MockHttp3DebugVisitor> debug_visitor; session_.set_debug_visitor(&debug_visitor); QuicStreamId stream_id = 4; EXPECT_CALL(session_, WritevData(send_control_stream_->id(), _, _, _, _, _)) .Times(AnyNumber()); EXPECT_CALL(debug_visitor, OnSettingsFrameSent(_)); EXPECT_CALL(debug_visitor, OnGoAwayFrameSent(stream_id)); send_control_stream_->SendGoAway(stream_id); } } } }
315
cpp
google/quiche
web_transport_http3
quiche/quic/core/http/web_transport_http3.cc
quiche/quic/core/http/web_transport_http3_test.cc
#ifndef QUICHE_QUIC_CORE_HTTP_WEB_TRANSPORT_HTTP3_H_ #define QUICHE_QUIC_CORE_HTTP_WEB_TRANSPORT_HTTP3_H_ #include <memory> #include <optional> #include "absl/base/attributes.h" #include "absl/container/flat_hash_set.h" #include "absl/time/time.h" #include "quiche/quic/core/http/quic_spdy_session.h" #include "quiche/quic/core/http/web_transport_stream_adapter.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_stream.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/web_transport_interface.h" #include "quiche/quic/core/web_transport_stats.h" #include "quiche/common/platform/api/quiche_mem_slice.h" #include "quiche/common/quiche_callbacks.h" #include "quiche/web_transport/web_transport.h" #include "quiche/spdy/core/http2_header_block.h" namespace quic { class QuicSpdySession; class QuicSpdyStream; enum class WebTransportHttp3RejectionReason { kNone, kNoStatusCode, kWrongStatusCode, kMissingDraftVersion, kUnsupportedDraftVersion, }; class QUICHE_EXPORT WebTransportHttp3 : public WebTransportSession, public QuicSpdyStream::Http3DatagramVisitor { public: WebTransportHttp3(QuicSpdySession* session, QuicSpdyStream* connect_stream, WebTransportSessionId id); void HeadersReceived(const spdy::Http2HeaderBlock& headers); void SetVisitor(std::unique_ptr<WebTransportVisitor> visitor) { visitor_ = std::move(visitor); } WebTransportSessionId id() { return id_; } bool ready() { return ready_; } void AssociateStream(QuicStreamId stream_id); void OnStreamClosed(QuicStreamId stream_id) { streams_.erase(stream_id); } void OnConnectStreamClosing(); size_t NumberOfAssociatedStreams() { return streams_.size(); } void CloseSession(WebTransportSessionError error_code, absl::string_view error_message) override; void OnCloseReceived(WebTransportSessionError error_code, absl::string_view error_message); void OnConnectStreamFinReceived(); void CloseSessionWithFinOnlyForTests(); WebTransportStream* AcceptIncomingBidirectionalStream() override; WebTransportStream* AcceptIncomingUnidirectionalStream() override; bool CanOpenNextOutgoingBidirectionalStream() override; bool CanOpenNextOutgoingUnidirectionalStream() override; WebTransportStream* OpenOutgoingBidirectionalStream() override; WebTransportStream* OpenOutgoingUnidirectionalStream() override; webtransport::Stream* GetStreamById(webtransport::StreamId id) override; webtransport::DatagramStatus SendOrQueueDatagram( absl::string_view datagram) override; QuicByteCount GetMaxDatagramSize() const override; void SetDatagramMaxTimeInQueue(absl::Duration max_time_in_queue) override; webtransport::DatagramStats GetDatagramStats() override { return WebTransportDatagramStatsForQuicSession(*session_); } webtransport::SessionStats GetSessionStats() override { return WebTransportStatsForQuicSession(*session_); } void NotifySessionDraining() override; void SetOnDraining(quiche::SingleUseCallback<void()> callback) override { drain_callback_ = std::move(callback); } void OnHttp3Datagram(QuicStreamId stream_id, absl::string_view payload) override; void OnUnknownCapsule(QuicStreamId , const quiche::UnknownCapsule& ) override {} bool close_received() const { return close_received_; } WebTransportHttp3RejectionReason rejection_reason() const { return rejection_reason_; } void OnGoAwayReceived(); void OnDrainSessionReceived(); private: void MaybeNotifyClose(); QuicSpdySession* const session_; QuicSpdyStream* const connect_stream_; const WebTransportSessionId id_; bool ready_ = false; std::unique_ptr<WebTransportVisitor> visitor_; absl::flat_hash_set<QuicStreamId> streams_; quiche::QuicheCircularDeque<QuicStreamId> incoming_bidirectional_streams_; quiche::QuicheCircularDeque<QuicStreamId> incoming_unidirectional_streams_; bool close_sent_ = false; bool close_received_ = false; bool close_notified_ = false; quiche::SingleUseCallback<void()> drain_callback_ = nullptr; WebTransportHttp3RejectionReason rejection_reason_ = WebTransportHttp3RejectionReason::kNone; bool drain_sent_ = false; WebTransportSessionError error_code_ = 0; std::string error_message_ = ""; }; class QUICHE_EXPORT WebTransportHttp3UnidirectionalStream : public QuicStream { public: WebTransportHttp3UnidirectionalStream(PendingStream* pending, QuicSpdySession* session); WebTransportHttp3UnidirectionalStream(QuicStreamId id, QuicSpdySession* session, WebTransportSessionId session_id); void WritePreamble(); void OnDataAvailable() override; void OnCanWriteNewData() override; void OnClose() override; void OnStreamReset(const QuicRstStreamFrame& frame) override; bool OnStopSending(QuicResetStreamError error) override; void OnWriteSideInDataRecvdState() override; WebTransportStream* interface() { return &adapter_; } void SetUnblocked() { sequencer()->SetUnblocked(); } private: QuicSpdySession* session_; WebTransportStreamAdapter adapter_; std::optional<WebTransportSessionId> session_id_; bool needs_to_send_preamble_; bool ReadSessionId(); void MaybeCloseIncompleteStream(); }; QUICHE_EXPORT std::optional<WebTransportStreamError> Http3ErrorToWebTransport( uint64_t http3_error_code); QUICHE_EXPORT WebTransportStreamError Http3ErrorToWebTransportOrDefault(uint64_t http3_error_code); QUICHE_EXPORT uint64_t WebTransportErrorToHttp3(WebTransportStreamError webtransport_error_code); } #endif #include "quiche/quic/core/http/web_transport_http3.h" #include <limits> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/core/http/quic_spdy_session.h" #include "quiche/quic/core/http/quic_spdy_stream.h" #include "quiche/quic/core/quic_data_reader.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_stream.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/common/capsule.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/web_transport/web_transport.h" #define ENDPOINT \ (session_->perspective() == Perspective::IS_SERVER ? "Server: " : "Client: ") namespace quic { namespace { class NoopWebTransportVisitor : public WebTransportVisitor { void OnSessionReady() override {} void OnSessionClosed(WebTransportSessionError , const std::string& ) override {} void OnIncomingBidirectionalStreamAvailable() override {} void OnIncomingUnidirectionalStreamAvailable() override {} void OnDatagramReceived(absl::string_view ) override {} void OnCanCreateNewOutgoingBidirectionalStream() override {} void OnCanCreateNewOutgoingUnidirectionalStream() override {} }; } WebTransportHttp3::WebTransportHttp3(QuicSpdySession* session, QuicSpdyStream* connect_stream, WebTransportSessionId id) : session_(session), connect_stream_(connect_stream), id_(id), visitor_(std::make_unique<NoopWebTransportVisitor>()) { QUICHE_DCHECK(session_->SupportsWebTransport()); QUICHE_DCHECK(IsValidWebTransportSessionId(id, session_->version())); QUICHE_DCHECK_EQ(connect_stream_->id(), id); connect_stream_->RegisterHttp3DatagramVisitor(this); } void WebTransportHttp3::AssociateStream(QuicStreamId stream_id) { streams_.insert(stream_id); ParsedQuicVersion version = session_->version(); if (QuicUtils::IsOutgoingStreamId(version, stream_id, session_->perspective())) { return; } if (QuicUtils::IsBidirectionalStreamId(stream_id, version)) { incoming_bidirectional_streams_.push_back(stream_id); visitor_->OnIncomingBidirectionalStreamAvailable(); } else { incoming_unidirectional_streams_.push_back(stream_id); visitor_->OnIncomingUnidirectionalStreamAvailable(); } } void WebTransportHttp3::OnConnectStreamClosing() { std::vector<QuicStreamId> streams(streams_.begin(), streams_.end()); streams_.clear(); for (QuicStreamId id : streams) { session_->ResetStream(id, QUIC_STREAM_WEBTRANSPORT_SESSION_GONE); } connect_stream_->UnregisterHttp3DatagramVisitor(); MaybeNotifyClose(); } void WebTransportHttp3::CloseSession(WebTransportSessionError error_code, absl::string_view error_message) { if (close_sent_) { QUIC_BUG(WebTransportHttp3 close sent twice) << "Calling WebTransportHttp3::CloseSession() more than once is not " "allowed."; return; } close_sent_ = true; if (close_received_) { QUIC_DLOG(INFO) << "Not sending CLOSE_WEBTRANSPORT_SESSION as we've " "already sent one from peer."; return; } error_code_ = error_code; error_message_ = std::string(error_message); QuicConnection::ScopedPacketFlusher flusher( connect_stream_->spdy_session()->connection()); connect_stream_->WriteCapsule( quiche::Capsule::CloseWebTransportSession(error_code, error_message), true); } void WebTransportHttp3::OnCloseReceived(WebTransportSessionError error_code, absl::string_view error_message) { if (close_received_) { QUIC_BUG(WebTransportHttp3 notified of close received twice) << "WebTransportHttp3::OnCloseReceived() may be only called once."; } close_received_ = true; if (close_sent_) { QUIC_DLOG(INFO) << "Ignoring received CLOSE_WEBTRANSPORT_SESSION as we've " "already sent our own."; return; } error_code_ = error_code; error_message_ = std::string(error_message); connect_stream_->WriteOrBufferBody("", true); MaybeNotifyClose(); } void WebTransportHttp3::OnConnectStreamFinReceived() { if (close_received_) { return; } close_received_ = true; if (close_sent_) { QUIC_DLOG(INFO) << "Ignoring received FIN as we've already sent our close."; return; } connect_stream_->WriteOrBufferBody("", true); MaybeNotifyClose(); } void WebTransportHttp3::CloseSessionWithFinOnlyForTests() { QUICHE_DCHECK(!close_sent_); close_sent_ = true; if (close_received_) { return; } connect_stream_->WriteOrBufferBody("", true); } void WebTransportHttp3::HeadersReceived(const spdy::Http2HeaderBlock& headers) { if (session_->perspective() == Perspective::IS_CLIENT) { int status_code; if (!QuicSpdyStream::ParseHeaderStatusCode(headers, &status_code)) { QUIC_DVLOG(1) << ENDPOINT << "Received WebTransport headers from server without " "a valid status code, rejecting."; rejection_reason_ = WebTransportHttp3RejectionReason::kNoStatusCode; return; } bool valid_status = status_code >= 200 && status_code <= 299; if (!valid_status) { QUIC_DVLOG(1) << ENDPOINT << "Received WebTransport headers from server with " "status code " << status_code << ", rejecting."; rejection_reason_ = WebTransportHttp3RejectionReason::kWrongStatusCode; return; } } QUIC_DVLOG(1) << ENDPOINT << "WebTransport session " << id_ << " ready."; ready_ = true; visitor_->OnSessionReady(); session_->ProcessBufferedWebTransportStreamsForSession(this); } WebTransportStream* WebTransportHttp3::AcceptIncomingBidirectionalStream() { while (!incoming_bidirectional_streams_.empty()) { QuicStreamId id = incoming_bidirectional_streams_.front(); incoming_bidirectional_streams_.pop_front(); QuicSpdyStream* stream = session_->GetOrCreateSpdyDataStream(id); if (stream == nullptr) { continue; } return stream->web_transport_stream(); } return nullptr; } WebTransportStream* WebTransportHttp3::AcceptIncomingUnidirectionalStream() { while (!incoming_unidirectional_streams_.empty()) { QuicStreamId id = incoming_unidirectional_streams_.front(); incoming_unidirectional_streams_.pop_front(); QuicStream* stream = session_->GetOrCreateStream(id); if (stream == nullptr) { continue; } return static_cast<WebTransportHttp3UnidirectionalStream*>(stream) ->interface(); } return nullptr; } bool WebTransportHttp3::CanOpenNextOutgoingBidirectionalStream() { return session_->CanOpenOutgoingBidirectionalWebTransportStream(id_); } bool WebTransportHttp3::CanOpenNextOutgoingUnidirectionalStream() { return session_->CanOpenOutgoingUnidirectionalWebTransportStream(id_); } WebTransportStream* WebTransportHttp3::OpenOutgoingBidirectionalStream() { QuicSpdyStream* stream = session_->CreateOutgoingBidirectionalWebTransportStream(this); if (stream == nullptr) { return nullptr; } return stream->web_transport_stream(); } WebTransportStream* WebTransportHttp3::OpenOutgoingUnidirectionalStream() { WebTransportHttp3UnidirectionalStream* stream = session_->CreateOutgoingUnidirectionalWebTransportStream(this); if (stream == nullptr) { return nullptr; } return stream->interface(); } webtransport::Stream* WebTransportHttp3::GetStreamById( webtransport::StreamId id) { if (!streams_.contains(id)) { return nullptr; } QuicStream* stream = session_->GetActiveStream(id); const bool bidi = QuicUtils::IsBidirectionalStreamId( id, ParsedQuicVersion::RFCv1()); if (bidi) { return static_cast<QuicSpdyStream*>(stream)->web_transport_stream(); } else { return static_cast<WebTransportHttp3UnidirectionalStream*>(stream) ->interface(); } } webtransport::DatagramStatus WebTransportHttp3::SendOrQueueDatagram( absl::string_view datagram) { return MessageStatusToWebTransportStatus( connect_stream_->SendHttp3Datagram(datagram)); } QuicByteCount WebTransportHttp3::GetMaxDatagramSize() const { return connect_stream_->GetMaxDatagramSize(); } void WebTransportHttp3::SetDatagramMaxTimeInQueue( absl::Duration max_time_in_queue) { connect_stream_->SetMaxDatagramTimeInQueue(QuicTimeDelta(max_time_in_queue)); } void WebTransportHttp3::NotifySessionDraining() { if (!drain_sent_) { connect_stream_->WriteCapsule( quiche::Capsule(quiche::DrainWebTransportSessionCapsule())); drain_sent_ = true; } } void WebTransportHttp3::OnHttp3Datagram(QuicStreamId stream_id, absl::string_view payload) { QUICHE_DCHECK_EQ(stream_id, connect_stream_->id()); visitor_->OnDatagramReceived(payload); } void WebTransportHttp3::MaybeNotifyClose() { if (close_notified_) { return; } close_notified_ = true; visitor_->OnSessionClosed(error_code_, error_message_); } void WebTransportHttp3::OnGoAwayReceived() { if (drain_callback_ != nullptr) { std::move(drain_callback_)(); drain_callback_ = nullptr; } } void WebTransportHttp3::OnDrainSessionReceived() { OnGoAwayReceived(); } WebTransportHttp3UnidirectionalStream::WebTransportHttp3UnidirectionalStream( PendingStream* pending, QuicSpdySession* session) : QuicStream(pending, session, false), session_(session), adapter_(session, this, sequencer(), std::nullopt), needs_to_send_preamble_(false) { sequencer()->set_level_triggered(true); } WebTransportHttp3UnidirectionalStream::WebTransportHttp3UnidirectionalStream( QuicStreamId id, QuicSpdySession* session, WebTransportSessionId session_id) : QuicStream(id, session, false, WRITE_UNIDIRECTIONAL), session_(session), adapter_(session, this, sequencer(), session_id), session_id_(session_id), needs_to_send_preamble_(true) {} void WebTransportHttp3UnidirectionalStream::WritePreamble() { if (!needs_to_send_preamble_ || !session_id_.has_value()) { QUIC_BUG(WebTransportHttp3UnidirectionalStream duplicate preamble) << ENDPOINT << "Sending preamble on stream ID " << id() << " at the wrong time."; OnUnrecoverableError(QUIC_INTERNAL_ERROR, "Attempting to send a WebTransport unidirectional " "stream preamble at the wrong time."); return; } QuicConnection::ScopedPacketFlusher flusher(session_->connection()); char buffer[sizeof(uint64_t) * 2]; QuicDataWriter writer(sizeof(buffer), buffer); bool success = true; success = success && writer.WriteVarInt62(kWebTransportUnidirectionalStream); success = success && writer.WriteVarInt62(*session_id_); QUICHE_DCHECK(success); WriteOrBufferData(absl::string_view(buffer, writer.length()), false, nullptr); QUIC_DVLOG(1) << ENDPOINT << "Sent stream type and session ID (" << *session_id_ << ") on WebTransport stream " << id(); needs_to_send_preamble_ = false; } bool WebTransportHttp3UnidirectionalStream::ReadSessionId() { iovec iov; if (!sequencer()->GetReadableRegion(&iov)) { return false; } QuicDataReader reader(static_cast<const char*>(iov.iov_base), iov.iov_len); WebTransportSessionId session_id; uint8_t session_id_length = reader.PeekVarInt62Length(); if (!reader.ReadVarInt62(&session_id)) { if (sequencer()->IsAllDataAvailable()) { QUIC_DLOG(WARNING) << ENDPOINT << "Failed to associate WebTransport stream " << id() << " with a session because the stream ended prematurely."; sequencer()->MarkConsumed(sequencer()->NumBytesBuffered()); } return false; } sequencer()->MarkConsumed(session_id_length); session_id_ = session_id; adapter_.SetSessionId(session_id); session_->AssociateIncomingWebTransportStreamWithSession(session_id, id()); return true; } void WebTransportHttp3UnidirectionalStream::OnDataAvailable() { if (!session_id_.has_value()) { if (!ReadSessionId()) { return; } } adapter_.OnDataAvailable(); } void WebTransportHttp3UnidirectionalStream::OnCanWriteNewData() { adapter_.OnCanWriteNewData(); } void WebTransportHttp3UnidirectionalStream::OnClose() { QuicStream::OnClose(); if (!session_id_.has_value()) { return; } WebTransportHttp3* session = session_->GetWebTransportSession(*session_id_); if (session == nullptr) { QUIC_DLOG(WARNING) << ENDPOINT << "WebTransport stream " << id() << " attempted to notify parent session " << *session_id_ << ", but the session could not be found."; return; } session->OnStreamClosed(id()); } void WebTransportHttp3UnidirectionalStream::OnStreamReset( const QuicRstStreamFrame& frame) { if (adapter_.visitor() != nullptr) { adapter_.visitor()->OnResetStreamReceived( Http3ErrorToWebTransportOrDefault(frame.ietf_error_code)); } QuicStream::OnStreamReset(frame); } bool WebTransportHttp3UnidirectionalStream::OnStopSending( QuicResetStreamError error) { if (adapter_.visitor() != nullptr) { adapter_.visitor()->OnStopSendingReceived( Http3ErrorToWebTransportOrDefault(error.ietf_application_code())); } return QuicStream::OnStopSending(error); } void WebTransportHttp3UnidirectionalStream::OnWriteSideInDataRecvdState() { if (adapter_.visitor() != nullptr) { adapter_.visitor()->OnWriteSideInDataRecvdState(); } QuicStream::OnWriteSideInDataRecvdState(); } namespace { constexpr uint64_t kWebTransportMappedErrorCodeFirst = 0x52e4a40fa8db; constexpr uint64_t kWebTransportMappedErrorCodeLast = 0x52e5ac983162; constexpr WebTransportStreamError kDefaultWebTransportError = 0; } std::optional<WebTransportStreamError> Http3ErrorToWebTransport( uint64_t http3_error_code) { if (http3_error_code < kWebTransportMappedErrorCodeFirst || http3_error_code > kWebTransportMappedErrorCodeLast) { return std::nullopt; } if ((http3_error_code - 0x21) % 0x1f == 0) { return std::nullopt; } uint64_t shifted = http3_error_code - kWebTransportMappedErrorCodeFirst; uint64_t result = shifted - shifted / 0x1f; QUICHE_DCHECK_LE(result, std::numeric_limits<webtransport::StreamErrorCode>::max()); return static_cast<WebTransportStreamError>(result); } WebTransportStreamError Http3ErrorToWebTransportOrDefault( uint64_t http3_error_code) { std::optional<WebTransportStreamError> result = Http3ErrorToWebTransport(http3_error_code); return result.has_value() ? *result : kDefaultWebTransportError; } uint64_t WebTransportErrorToHttp3( WebTransportStreamError webtransport_error_code) { return kWebTransportMappedErrorCodeFirst + webtransport_error_code + webtransport_error_code / 0x1e; } }
#include "quiche/quic/core/http/web_transport_http3.h" #include <cstdint> #include <limits> #include <optional> #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace { using ::testing::Optional; TEST(WebTransportHttp3Test, ErrorCodesToHttp3) { EXPECT_EQ(0x52e4a40fa8dbu, WebTransportErrorToHttp3(0x00)); EXPECT_EQ(0x52e4a40fa9e2u, WebTransportErrorToHttp3(0xff)); EXPECT_EQ(0x52e5ac983162u, WebTransportErrorToHttp3(0xffffffff)); EXPECT_EQ(0x52e4a40fa8f7u, WebTransportErrorToHttp3(0x1c)); EXPECT_EQ(0x52e4a40fa8f8u, WebTransportErrorToHttp3(0x1d)); EXPECT_EQ(0x52e4a40fa8fau, WebTransportErrorToHttp3(0x1e)); } TEST(WebTransportHttp3Test, ErrorCodesToWebTransport) { EXPECT_THAT(Http3ErrorToWebTransport(0x52e4a40fa8db), Optional(0x00)); EXPECT_THAT(Http3ErrorToWebTransport(0x52e4a40fa9e2), Optional(0xff)); EXPECT_THAT(Http3ErrorToWebTransport(0x52e5ac983162u), Optional(0xffffffff)); EXPECT_THAT(Http3ErrorToWebTransport(0x52e4a40fa8f7), Optional(0x1cu)); EXPECT_THAT(Http3ErrorToWebTransport(0x52e4a40fa8f8), Optional(0x1du)); EXPECT_THAT(Http3ErrorToWebTransport(0x52e4a40fa8f9), std::nullopt); EXPECT_THAT(Http3ErrorToWebTransport(0x52e4a40fa8fa), Optional(0x1eu)); EXPECT_EQ(Http3ErrorToWebTransport(0), std::nullopt); EXPECT_EQ(Http3ErrorToWebTransport(std::numeric_limits<uint64_t>::max()), std::nullopt); } TEST(WebTransportHttp3Test, ErrorCodeRoundTrip) { for (int error = 0; error <= 65536; error++) { uint64_t http_error = WebTransportErrorToHttp3(error); std::optional<WebTransportStreamError> mapped_back = quic::Http3ErrorToWebTransport(http_error); ASSERT_THAT(mapped_back, Optional(error)); } for (int64_t error = 0; error < std::numeric_limits<uint32_t>::max(); error += 65537) { uint64_t http_error = WebTransportErrorToHttp3(error); std::optional<WebTransportStreamError> mapped_back = quic::Http3ErrorToWebTransport(http_error); ASSERT_THAT(mapped_back, Optional(error)); } } } }
316
cpp
google/quiche
quic_spdy_stream_body_manager
quiche/quic/core/http/quic_spdy_stream_body_manager.cc
quiche/quic/core/http/quic_spdy_stream_body_manager_test.cc
#ifndef QUICHE_QUIC_CORE_HTTP_QUIC_SPDY_STREAM_BODY_MANAGER_H_ #define QUICHE_QUIC_CORE_HTTP_QUIC_SPDY_STREAM_BODY_MANAGER_H_ #include "absl/base/attributes.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/common/platform/api/quiche_iovec.h" #include "quiche/common/quiche_circular_deque.h" namespace quic { class QUICHE_EXPORT QuicSpdyStreamBodyManager { public: QuicSpdyStreamBodyManager(); ~QuicSpdyStreamBodyManager() = default; ABSL_MUST_USE_RESULT size_t OnNonBody(QuicByteCount length); void OnBody(absl::string_view body); ABSL_MUST_USE_RESULT size_t OnBodyConsumed(size_t num_bytes); int PeekBody(iovec* iov, size_t iov_len) const; ABSL_MUST_USE_RESULT size_t ReadBody(const struct iovec* iov, size_t iov_len, size_t* total_bytes_read); bool HasBytesToRead() const { return !fragments_.empty(); } size_t ReadableBytes() const; void Clear() { fragments_.clear(); } uint64_t total_body_bytes_received() const { return total_body_bytes_received_; } private: struct QUICHE_EXPORT Fragment { absl::string_view body; QuicByteCount trailing_non_body_byte_count; }; quiche::QuicheCircularDeque<Fragment> fragments_; QuicByteCount total_body_bytes_received_; }; } #endif #include "quiche/quic/core/http/quic_spdy_stream_body_manager.h" #include <algorithm> #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { QuicSpdyStreamBodyManager::QuicSpdyStreamBodyManager() : total_body_bytes_received_(0) {} size_t QuicSpdyStreamBodyManager::OnNonBody(QuicByteCount length) { QUICHE_DCHECK_NE(0u, length); if (fragments_.empty()) { return length; } fragments_.back().trailing_non_body_byte_count += length; return 0; } void QuicSpdyStreamBodyManager::OnBody(absl::string_view body) { QUICHE_DCHECK(!body.empty()); fragments_.push_back({body, 0}); total_body_bytes_received_ += body.length(); } size_t QuicSpdyStreamBodyManager::OnBodyConsumed(size_t num_bytes) { QuicByteCount bytes_to_consume = 0; size_t remaining_bytes = num_bytes; while (remaining_bytes > 0) { if (fragments_.empty()) { QUIC_BUG(quic_bug_10394_1) << "Not enough available body to consume."; return 0; } Fragment& fragment = fragments_.front(); const absl::string_view body = fragment.body; if (body.length() > remaining_bytes) { bytes_to_consume += remaining_bytes; fragment.body = body.substr(remaining_bytes); return bytes_to_consume; } remaining_bytes -= body.length(); bytes_to_consume += body.length() + fragment.trailing_non_body_byte_count; fragments_.pop_front(); } return bytes_to_consume; } int QuicSpdyStreamBodyManager::PeekBody(iovec* iov, size_t iov_len) const { QUICHE_DCHECK(iov); QUICHE_DCHECK_GT(iov_len, 0u); if (fragments_.empty()) { iov[0].iov_base = nullptr; iov[0].iov_len = 0; return 0; } size_t iov_filled = 0; while (iov_filled < fragments_.size() && iov_filled < iov_len) { absl::string_view body = fragments_[iov_filled].body; iov[iov_filled].iov_base = const_cast<char*>(body.data()); iov[iov_filled].iov_len = body.size(); iov_filled++; } return iov_filled; } size_t QuicSpdyStreamBodyManager::ReadableBytes() const { size_t count = 0; for (auto const& fragment : fragments_) { count += fragment.body.length(); } return count; } size_t QuicSpdyStreamBodyManager::ReadBody(const struct iovec* iov, size_t iov_len, size_t* total_bytes_read) { *total_bytes_read = 0; QuicByteCount bytes_to_consume = 0; size_t index = 0; char* dest = reinterpret_cast<char*>(iov[index].iov_base); size_t dest_remaining = iov[index].iov_len; while (!fragments_.empty()) { Fragment& fragment = fragments_.front(); const absl::string_view body = fragment.body; const size_t bytes_to_copy = std::min<size_t>(body.length(), dest_remaining); if (bytes_to_copy > 0) { memcpy(dest, body.data(), bytes_to_copy); } bytes_to_consume += bytes_to_copy; *total_bytes_read += bytes_to_copy; if (bytes_to_copy == body.length()) { bytes_to_consume += fragment.trailing_non_body_byte_count; fragments_.pop_front(); } else { fragment.body = body.substr(bytes_to_copy); } if (bytes_to_copy == dest_remaining) { ++index; if (index == iov_len) { break; } dest = reinterpret_cast<char*>(iov[index].iov_base); dest_remaining = iov[index].iov_len; } else { dest += bytes_to_copy; dest_remaining -= bytes_to_copy; } } return bytes_to_consume; } }
#include "quiche/quic/core/http/quic_spdy_stream_body_manager.h" #include <algorithm> #include <numeric> #include <string> #include <vector> #include "absl/base/macros.h" #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { namespace { class QuicSpdyStreamBodyManagerTest : public QuicTest { protected: QuicSpdyStreamBodyManager body_manager_; }; TEST_F(QuicSpdyStreamBodyManagerTest, HasBytesToRead) { EXPECT_FALSE(body_manager_.HasBytesToRead()); EXPECT_EQ(body_manager_.ReadableBytes(), 0u); EXPECT_EQ(0u, body_manager_.total_body_bytes_received()); const QuicByteCount header_length = 3; EXPECT_EQ(header_length, body_manager_.OnNonBody(header_length)); EXPECT_FALSE(body_manager_.HasBytesToRead()); EXPECT_EQ(body_manager_.ReadableBytes(), 0u); EXPECT_EQ(0u, body_manager_.total_body_bytes_received()); std::string body(1024, 'a'); body_manager_.OnBody(body); EXPECT_TRUE(body_manager_.HasBytesToRead()); EXPECT_EQ(body_manager_.ReadableBytes(), 1024u); EXPECT_EQ(1024u, body_manager_.total_body_bytes_received()); } TEST_F(QuicSpdyStreamBodyManagerTest, ConsumeMoreThanAvailable) { std::string body(1024, 'a'); body_manager_.OnBody(body); size_t bytes_to_consume = 0; EXPECT_QUIC_BUG(bytes_to_consume = body_manager_.OnBodyConsumed(2048), "Not enough available body to consume."); EXPECT_EQ(0u, bytes_to_consume); } TEST_F(QuicSpdyStreamBodyManagerTest, OnBodyConsumed) { struct { std::vector<QuicByteCount> frame_header_lengths; std::vector<const char*> frame_payloads; std::vector<QuicByteCount> body_bytes_to_read; std::vector<QuicByteCount> expected_return_values; } const kOnBodyConsumedTestData[] = { {{2}, {"foobar"}, {6}, {6}}, {{3, 5}, {"foobar", "baz"}, {9}, {14}}, {{2}, {"foobar"}, {4, 2}, {4, 2}}, {{3, 5}, {"foobar", "baz"}, {6, 3}, {11, 3}}, {{3, 5}, {"foobar", "baz"}, {5, 4}, {5, 9}}, {{3, 5}, {"foobar", "baz"}, {7, 2}, {12, 2}}, }; for (size_t test_case_index = 0; test_case_index < ABSL_ARRAYSIZE(kOnBodyConsumedTestData); ++test_case_index) { const std::vector<QuicByteCount>& frame_header_lengths = kOnBodyConsumedTestData[test_case_index].frame_header_lengths; const std::vector<const char*>& frame_payloads = kOnBodyConsumedTestData[test_case_index].frame_payloads; const std::vector<QuicByteCount>& body_bytes_to_read = kOnBodyConsumedTestData[test_case_index].body_bytes_to_read; const std::vector<QuicByteCount>& expected_return_values = kOnBodyConsumedTestData[test_case_index].expected_return_values; for (size_t frame_index = 0; frame_index < frame_header_lengths.size(); ++frame_index) { EXPECT_EQ(frame_index == 0 ? frame_header_lengths[frame_index] : 0u, body_manager_.OnNonBody(frame_header_lengths[frame_index])); body_manager_.OnBody(frame_payloads[frame_index]); } for (size_t call_index = 0; call_index < body_bytes_to_read.size(); ++call_index) { EXPECT_EQ(expected_return_values[call_index], body_manager_.OnBodyConsumed(body_bytes_to_read[call_index])); } EXPECT_FALSE(body_manager_.HasBytesToRead()); EXPECT_EQ(body_manager_.ReadableBytes(), 0u); } } TEST_F(QuicSpdyStreamBodyManagerTest, PeekBody) { struct { std::vector<QuicByteCount> frame_header_lengths; std::vector<const char*> frame_payloads; size_t iov_len; } const kPeekBodyTestData[] = { {{}, {}, 1}, {{3}, {"foobar"}, 1}, {{3}, {"foobar"}, 2}, {{3, 5}, {"foobar", "baz"}, 1}, {{3, 5}, {"foobar", "baz"}, 2}, {{3, 5}, {"foobar", "baz"}, 3}, }; for (size_t test_case_index = 0; test_case_index < ABSL_ARRAYSIZE(kPeekBodyTestData); ++test_case_index) { const std::vector<QuicByteCount>& frame_header_lengths = kPeekBodyTestData[test_case_index].frame_header_lengths; const std::vector<const char*>& frame_payloads = kPeekBodyTestData[test_case_index].frame_payloads; size_t iov_len = kPeekBodyTestData[test_case_index].iov_len; QuicSpdyStreamBodyManager body_manager; for (size_t frame_index = 0; frame_index < frame_header_lengths.size(); ++frame_index) { EXPECT_EQ(frame_index == 0 ? frame_header_lengths[frame_index] : 0u, body_manager.OnNonBody(frame_header_lengths[frame_index])); body_manager.OnBody(frame_payloads[frame_index]); } std::vector<iovec> iovecs; iovecs.resize(iov_len); size_t iovs_filled = std::min(frame_payloads.size(), iov_len); ASSERT_EQ(iovs_filled, static_cast<size_t>(body_manager.PeekBody(&iovecs[0], iov_len))); for (size_t iovec_index = 0; iovec_index < iovs_filled; ++iovec_index) { EXPECT_EQ(frame_payloads[iovec_index], absl::string_view( static_cast<const char*>(iovecs[iovec_index].iov_base), iovecs[iovec_index].iov_len)); } } } TEST_F(QuicSpdyStreamBodyManagerTest, ReadBody) { struct { std::vector<QuicByteCount> frame_header_lengths; std::vector<const char*> frame_payloads; std::vector<std::vector<QuicByteCount>> iov_lengths; std::vector<QuicByteCount> expected_total_bytes_read; std::vector<QuicByteCount> expected_return_values; } const kReadBodyTestData[] = { {{4}, {"foo"}, {{2}}, {2}, {2}}, {{4}, {"foo"}, {{3}}, {3}, {3}}, {{4}, {"foo"}, {{5}}, {3}, {3}}, {{4}, {"foobar"}, {{2, 3}}, {5}, {5}}, {{4}, {"foobar"}, {{2, 4}}, {6}, {6}}, {{4}, {"foobar"}, {{2, 6}}, {6}, {6}}, {{4}, {"foobar"}, {{2, 4, 4, 3}}, {6}, {6}}, {{4}, {"foobar"}, {{2, 7, 4, 3}}, {6}, {6}}, {{4}, {"foobarbaz"}, {{2, 1}, {3, 2}}, {3, 5}, {3, 5}}, {{4}, {"foobarbaz"}, {{2, 1}, {4, 2}}, {3, 6}, {3, 6}}, {{4}, {"foobarbaz"}, {{2, 1}, {4, 10}}, {3, 6}, {3, 6}}, {{4, 3}, {"foobar", "baz"}, {{8}}, {8}, {11}}, {{4, 3}, {"foobar", "baz"}, {{9}}, {9}, {12}}, {{4, 3}, {"foobar", "baz"}, {{10}}, {9}, {12}}, {{4, 3}, {"foobar", "baz"}, {{4, 3}}, {7}, {10}}, {{4, 3}, {"foobar", "baz"}, {{4, 5}}, {9}, {12}}, {{4, 3}, {"foobar", "baz"}, {{4, 6}}, {9}, {12}}, {{4, 3}, {"foobar", "baz"}, {{4, 6, 4, 3}}, {9}, {12}}, {{4, 3}, {"foobar", "baz"}, {{4, 7, 4, 3}}, {9}, {12}}, {{4, 3}, {"foobar", "baz"}, {{2, 4}, {2, 1}}, {6, 3}, {9, 3}}, {{4, 3, 6}, {"foobar", "bazquux", "qux"}, {{4, 3}, {2, 3}, {5, 3}}, {7, 5, 4}, {10, 5, 10}}, }; for (size_t test_case_index = 0; test_case_index < ABSL_ARRAYSIZE(kReadBodyTestData); ++test_case_index) { const std::vector<QuicByteCount>& frame_header_lengths = kReadBodyTestData[test_case_index].frame_header_lengths; const std::vector<const char*>& frame_payloads = kReadBodyTestData[test_case_index].frame_payloads; const std::vector<std::vector<QuicByteCount>>& iov_lengths = kReadBodyTestData[test_case_index].iov_lengths; const std::vector<QuicByteCount>& expected_total_bytes_read = kReadBodyTestData[test_case_index].expected_total_bytes_read; const std::vector<QuicByteCount>& expected_return_values = kReadBodyTestData[test_case_index].expected_return_values; QuicSpdyStreamBodyManager body_manager; std::string received_body; for (size_t frame_index = 0; frame_index < frame_header_lengths.size(); ++frame_index) { EXPECT_EQ(frame_index == 0 ? frame_header_lengths[frame_index] : 0u, body_manager.OnNonBody(frame_header_lengths[frame_index])); body_manager.OnBody(frame_payloads[frame_index]); received_body.append(frame_payloads[frame_index]); } std::string read_body; for (size_t call_index = 0; call_index < iov_lengths.size(); ++call_index) { size_t total_iov_length = std::accumulate(iov_lengths[call_index].begin(), iov_lengths[call_index].end(), static_cast<size_t>(0)); std::string buffer(total_iov_length, 'z'); std::vector<iovec> iovecs; size_t offset = 0; for (size_t iov_length : iov_lengths[call_index]) { QUICHE_CHECK(offset + iov_length <= buffer.size()); iovecs.push_back({&buffer[offset], iov_length}); offset += iov_length; } size_t total_bytes_read = expected_total_bytes_read[call_index] + 12; EXPECT_EQ( expected_return_values[call_index], body_manager.ReadBody(&iovecs[0], iovecs.size(), &total_bytes_read)); read_body.append(buffer.substr(0, total_bytes_read)); } EXPECT_EQ(received_body.substr(0, read_body.size()), read_body); EXPECT_EQ(read_body.size() < received_body.size(), body_manager.HasBytesToRead()); } } TEST_F(QuicSpdyStreamBodyManagerTest, Clear) { const QuicByteCount header_length = 3; EXPECT_EQ(header_length, body_manager_.OnNonBody(header_length)); std::string body("foo"); body_manager_.OnBody(body); EXPECT_TRUE(body_manager_.HasBytesToRead()); body_manager_.Clear(); EXPECT_FALSE(body_manager_.HasBytesToRead()); iovec iov; size_t total_bytes_read = 5; EXPECT_EQ(0, body_manager_.PeekBody(&iov, 1)); EXPECT_EQ(0u, body_manager_.ReadBody(&iov, 1, &total_bytes_read)); } } } }
317
cpp
google/quiche
quic_headers_stream
quiche/quic/core/http/quic_headers_stream.cc
quiche/quic/core/http/quic_headers_stream_test.cc
#ifndef QUICHE_QUIC_CORE_HTTP_QUIC_HEADERS_STREAM_H_ #define QUICHE_QUIC_CORE_HTTP_QUIC_HEADERS_STREAM_H_ #include <cstddef> #include <memory> #include "quiche/quic/core/http/quic_header_list.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_stream.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/spdy/core/spdy_framer.h" namespace quic { class QuicSpdySession; namespace test { class QuicHeadersStreamPeer; } class QUICHE_EXPORT QuicHeadersStream : public QuicStream { public: explicit QuicHeadersStream(QuicSpdySession* session); QuicHeadersStream(const QuicHeadersStream&) = delete; QuicHeadersStream& operator=(const QuicHeadersStream&) = delete; ~QuicHeadersStream() override; void OnDataAvailable() override; void MaybeReleaseSequencerBuffer(); bool OnStreamFrameAcked(QuicStreamOffset offset, QuicByteCount data_length, bool fin_acked, QuicTime::Delta ack_delay_time, QuicTime receive_timestamp, QuicByteCount* newly_acked_length) override; void OnStreamFrameRetransmitted(QuicStreamOffset offset, QuicByteCount data_length, bool fin_retransmitted) override; void OnStreamReset(const QuicRstStreamFrame& frame) override; private: friend class test::QuicHeadersStreamPeer; struct QUICHE_EXPORT CompressedHeaderInfo { CompressedHeaderInfo( QuicStreamOffset headers_stream_offset, QuicStreamOffset full_length, quiche::QuicheReferenceCountedPointer<QuicAckListenerInterface> ack_listener); CompressedHeaderInfo(const CompressedHeaderInfo& other); ~CompressedHeaderInfo(); QuicStreamOffset headers_stream_offset; QuicByteCount full_length; QuicByteCount unacked_length; quiche::QuicheReferenceCountedPointer<QuicAckListenerInterface> ack_listener; }; bool IsConnected(); void OnDataBuffered( QuicStreamOffset offset, QuicByteCount data_length, const quiche::QuicheReferenceCountedPointer<QuicAckListenerInterface>& ack_listener) override; QuicSpdySession* spdy_session_; quiche::QuicheCircularDeque<CompressedHeaderInfo> unacked_headers_; }; } #endif #include "quiche/quic/core/http/quic_headers_stream.h" #include <algorithm> #include <utility> #include "absl/base/macros.h" #include "quiche/quic/core/http/quic_spdy_session.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" namespace quic { QuicHeadersStream::CompressedHeaderInfo::CompressedHeaderInfo( QuicStreamOffset headers_stream_offset, QuicStreamOffset full_length, quiche::QuicheReferenceCountedPointer<QuicAckListenerInterface> ack_listener) : headers_stream_offset(headers_stream_offset), full_length(full_length), unacked_length(full_length), ack_listener(std::move(ack_listener)) {} QuicHeadersStream::CompressedHeaderInfo::CompressedHeaderInfo( const CompressedHeaderInfo& other) = default; QuicHeadersStream::CompressedHeaderInfo::~CompressedHeaderInfo() {} QuicHeadersStream::QuicHeadersStream(QuicSpdySession* session) : QuicStream(QuicUtils::GetHeadersStreamId(session->transport_version()), session, true, BIDIRECTIONAL), spdy_session_(session) { DisableConnectionFlowControlForThisStream(); } QuicHeadersStream::~QuicHeadersStream() {} void QuicHeadersStream::OnDataAvailable() { struct iovec iov; while (sequencer()->GetReadableRegion(&iov)) { if (spdy_session_->ProcessHeaderData(iov) != iov.iov_len) { return; } sequencer()->MarkConsumed(iov.iov_len); MaybeReleaseSequencerBuffer(); } } void QuicHeadersStream::MaybeReleaseSequencerBuffer() { if (spdy_session_->ShouldReleaseHeadersStreamSequencerBuffer()) { sequencer()->ReleaseBufferIfEmpty(); } } bool QuicHeadersStream::OnStreamFrameAcked(QuicStreamOffset offset, QuicByteCount data_length, bool fin_acked, QuicTime::Delta ack_delay_time, QuicTime receive_timestamp, QuicByteCount* newly_acked_length) { QuicIntervalSet<QuicStreamOffset> newly_acked(offset, offset + data_length); newly_acked.Difference(bytes_acked()); for (const auto& acked : newly_acked) { QuicStreamOffset acked_offset = acked.min(); QuicByteCount acked_length = acked.max() - acked.min(); for (CompressedHeaderInfo& header : unacked_headers_) { if (acked_offset < header.headers_stream_offset) { break; } if (acked_offset >= header.headers_stream_offset + header.full_length) { continue; } QuicByteCount header_offset = acked_offset - header.headers_stream_offset; QuicByteCount header_length = std::min(acked_length, header.full_length - header_offset); if (header.unacked_length < header_length) { QUIC_BUG(quic_bug_10416_1) << "Unsent stream data is acked. unacked_length: " << header.unacked_length << " acked_length: " << header_length; OnUnrecoverableError(QUIC_INTERNAL_ERROR, "Unsent stream data is acked"); return false; } if (header.ack_listener != nullptr && header_length > 0) { header.ack_listener->OnPacketAcked(header_length, ack_delay_time); } header.unacked_length -= header_length; acked_offset += header_length; acked_length -= header_length; } } while (!unacked_headers_.empty() && unacked_headers_.front().unacked_length == 0) { unacked_headers_.pop_front(); } return QuicStream::OnStreamFrameAcked(offset, data_length, fin_acked, ack_delay_time, receive_timestamp, newly_acked_length); } void QuicHeadersStream::OnStreamFrameRetransmitted(QuicStreamOffset offset, QuicByteCount data_length, bool ) { QuicStream::OnStreamFrameRetransmitted(offset, data_length, false); for (CompressedHeaderInfo& header : unacked_headers_) { if (offset < header.headers_stream_offset) { break; } if (offset >= header.headers_stream_offset + header.full_length) { continue; } QuicByteCount header_offset = offset - header.headers_stream_offset; QuicByteCount retransmitted_length = std::min(data_length, header.full_length - header_offset); if (header.ack_listener != nullptr && retransmitted_length > 0) { header.ack_listener->OnPacketRetransmitted(retransmitted_length); } offset += retransmitted_length; data_length -= retransmitted_length; } } void QuicHeadersStream::OnDataBuffered( QuicStreamOffset offset, QuicByteCount data_length, const quiche::QuicheReferenceCountedPointer<QuicAckListenerInterface>& ack_listener) { if (!unacked_headers_.empty() && (offset == unacked_headers_.back().headers_stream_offset + unacked_headers_.back().full_length) && ack_listener == unacked_headers_.back().ack_listener) { unacked_headers_.back().full_length += data_length; unacked_headers_.back().unacked_length += data_length; } else { unacked_headers_.push_back( CompressedHeaderInfo(offset, data_length, ack_listener)); } } void QuicHeadersStream::OnStreamReset(const QuicRstStreamFrame& ) { stream_delegate()->OnStreamError(QUIC_INVALID_STREAM_ID, "Attempt to reset headers stream"); } }
#include "quiche/quic/core/http/quic_headers_stream.h" #include <cstdint> #include <memory> #include <ostream> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/http/spdy_utils.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_spdy_session_peer.h" #include "quiche/quic/test_tools/quic_stream_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/quiche_endian.h" #include "quiche/spdy/core/http2_frame_decoder_adapter.h" #include "quiche/spdy/core/http2_header_block.h" #include "quiche/spdy/core/recording_headers_handler.h" #include "quiche/spdy/core/spdy_alt_svc_wire_format.h" #include "quiche/spdy/core/spdy_protocol.h" #include "quiche/spdy/test_tools/spdy_test_utils.h" using spdy::ERROR_CODE_PROTOCOL_ERROR; using spdy::Http2HeaderBlock; using spdy::RecordingHeadersHandler; using spdy::SETTINGS_ENABLE_PUSH; using spdy::SETTINGS_HEADER_TABLE_SIZE; using spdy::SETTINGS_INITIAL_WINDOW_SIZE; using spdy::SETTINGS_MAX_CONCURRENT_STREAMS; using spdy::SETTINGS_MAX_FRAME_SIZE; using spdy::Spdy3PriorityToHttp2Weight; using spdy::SpdyAltSvcWireFormat; using spdy::SpdyDataIR; using spdy::SpdyErrorCode; using spdy::SpdyFramer; using spdy::SpdyFramerVisitorInterface; using spdy::SpdyGoAwayIR; using spdy::SpdyHeadersHandlerInterface; using spdy::SpdyHeadersIR; using spdy::SpdyPingId; using spdy::SpdyPingIR; using spdy::SpdyPriority; using spdy::SpdyPriorityIR; using spdy::SpdyPushPromiseIR; using spdy::SpdyRstStreamIR; using spdy::SpdySerializedFrame; using spdy::SpdySettingsId; using spdy::SpdySettingsIR; using spdy::SpdyStreamId; using spdy::SpdyWindowUpdateIR; using testing::_; using testing::AnyNumber; using testing::AtLeast; using testing::InSequence; using testing::Invoke; using testing::Return; using testing::StrictMock; using testing::WithArgs; namespace quic { namespace test { namespace { class MockVisitor : public SpdyFramerVisitorInterface { public: MOCK_METHOD(void, OnError, (http2::Http2DecoderAdapter::SpdyFramerError error, std::string detailed_error), (override)); MOCK_METHOD(void, OnDataFrameHeader, (SpdyStreamId stream_id, size_t length, bool fin), (override)); MOCK_METHOD(void, OnStreamFrameData, (SpdyStreamId stream_id, const char*, size_t len), (override)); MOCK_METHOD(void, OnStreamEnd, (SpdyStreamId stream_id), (override)); MOCK_METHOD(void, OnStreamPadding, (SpdyStreamId stream_id, size_t len), (override)); MOCK_METHOD(SpdyHeadersHandlerInterface*, OnHeaderFrameStart, (SpdyStreamId stream_id), (override)); MOCK_METHOD(void, OnHeaderFrameEnd, (SpdyStreamId stream_id), (override)); MOCK_METHOD(void, OnRstStream, (SpdyStreamId stream_id, SpdyErrorCode error_code), (override)); MOCK_METHOD(void, OnSettings, (), (override)); MOCK_METHOD(void, OnSetting, (SpdySettingsId id, uint32_t value), (override)); MOCK_METHOD(void, OnSettingsAck, (), (override)); MOCK_METHOD(void, OnSettingsEnd, (), (override)); MOCK_METHOD(void, OnPing, (SpdyPingId unique_id, bool is_ack), (override)); MOCK_METHOD(void, OnGoAway, (SpdyStreamId last_accepted_stream_id, SpdyErrorCode error_code), (override)); MOCK_METHOD(void, OnHeaders, (SpdyStreamId stream_id, size_t payload_length, bool has_priority, int weight, SpdyStreamId parent_stream_id, bool exclusive, bool fin, bool end), (override)); MOCK_METHOD(void, OnWindowUpdate, (SpdyStreamId stream_id, int delta_window_size), (override)); MOCK_METHOD(void, OnPushPromise, (SpdyStreamId stream_id, SpdyStreamId promised_stream_id, bool end), (override)); MOCK_METHOD(void, OnContinuation, (SpdyStreamId stream_id, size_t payload_size, bool end), (override)); MOCK_METHOD( void, OnAltSvc, (SpdyStreamId stream_id, absl::string_view origin, const SpdyAltSvcWireFormat::AlternativeServiceVector& altsvc_vector), (override)); MOCK_METHOD(void, OnPriority, (SpdyStreamId stream_id, SpdyStreamId parent_stream_id, int weight, bool exclusive), (override)); MOCK_METHOD(void, OnPriorityUpdate, (SpdyStreamId prioritized_stream_id, absl::string_view priority_field_value), (override)); MOCK_METHOD(bool, OnUnknownFrame, (SpdyStreamId stream_id, uint8_t frame_type), (override)); MOCK_METHOD(void, OnUnknownFrameStart, (SpdyStreamId stream_id, size_t length, uint8_t type, uint8_t flags), (override)); MOCK_METHOD(void, OnUnknownFramePayload, (SpdyStreamId stream_id, absl::string_view payload), (override)); }; struct TestParams { TestParams(const ParsedQuicVersion& version, Perspective perspective) : version(version), perspective(perspective) { QUIC_LOG(INFO) << "TestParams: " << *this; } TestParams(const TestParams& other) : version(other.version), perspective(other.perspective) {} friend std::ostream& operator<<(std::ostream& os, const TestParams& tp) { os << "{ version: " << ParsedQuicVersionToString(tp.version) << ", perspective: " << (tp.perspective == Perspective::IS_CLIENT ? "client" : "server") << "}"; return os; } ParsedQuicVersion version; Perspective perspective; }; std::string PrintToString(const TestParams& tp) { return absl::StrCat( ParsedQuicVersionToString(tp.version), "_", (tp.perspective == Perspective::IS_CLIENT ? "client" : "server")); } std::vector<TestParams> GetTestParams() { std::vector<TestParams> params; ParsedQuicVersionVector all_supported_versions = AllSupportedVersions(); for (size_t i = 0; i < all_supported_versions.size(); ++i) { if (VersionUsesHttp3(all_supported_versions[i].transport_version)) { continue; } for (Perspective p : {Perspective::IS_SERVER, Perspective::IS_CLIENT}) { params.emplace_back(all_supported_versions[i], p); } } return params; } class QuicHeadersStreamTest : public QuicTestWithParam<TestParams> { public: QuicHeadersStreamTest() : connection_(new StrictMock<MockQuicConnection>( &helper_, &alarm_factory_, perspective(), GetVersion())), session_(connection_), body_("hello world"), stream_frame_( QuicUtils::GetHeadersStreamId(connection_->transport_version()), false, 0, ""), next_promised_stream_id_(2) { QuicSpdySessionPeer::SetMaxInboundHeaderListSize(&session_, 256 * 1024); EXPECT_CALL(session_, OnCongestionWindowChange(_)).Times(AnyNumber()); session_.Initialize(); connection_->SetEncrypter( quic::ENCRYPTION_FORWARD_SECURE, std::make_unique<quic::NullEncrypter>(connection_->perspective())); headers_stream_ = QuicSpdySessionPeer::GetHeadersStream(&session_); headers_[":status"] = "200 Ok"; headers_["content-length"] = "11"; framer_ = std::unique_ptr<SpdyFramer>( new SpdyFramer(SpdyFramer::ENABLE_COMPRESSION)); deframer_ = std::unique_ptr<http2::Http2DecoderAdapter>( new http2::Http2DecoderAdapter()); deframer_->set_visitor(&visitor_); EXPECT_EQ(transport_version(), session_.transport_version()); EXPECT_TRUE(headers_stream_ != nullptr); connection_->AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); client_id_1_ = GetNthClientInitiatedBidirectionalStreamId( connection_->transport_version(), 0); client_id_2_ = GetNthClientInitiatedBidirectionalStreamId( connection_->transport_version(), 1); client_id_3_ = GetNthClientInitiatedBidirectionalStreamId( connection_->transport_version(), 2); next_stream_id_ = QuicUtils::StreamIdDelta(connection_->transport_version()); } QuicStreamId GetNthClientInitiatedId(int n) { return GetNthClientInitiatedBidirectionalStreamId( connection_->transport_version(), n); } QuicConsumedData SaveIov(size_t write_length) { char* buf = new char[write_length]; QuicDataWriter writer(write_length, buf, quiche::NETWORK_BYTE_ORDER); headers_stream_->WriteStreamData(headers_stream_->stream_bytes_written(), write_length, &writer); saved_data_.append(buf, write_length); delete[] buf; return QuicConsumedData(write_length, false); } void SavePayload(const char* data, size_t len) { saved_payloads_.append(data, len); } bool SaveHeaderData(const char* data, int len) { saved_header_data_.append(data, len); return true; } void SaveHeaderDataStringPiece(absl::string_view data) { saved_header_data_.append(data.data(), data.length()); } void SavePromiseHeaderList(QuicStreamId , QuicStreamId , size_t size, const QuicHeaderList& header_list) { SaveToHandler(size, header_list); } void SaveHeaderList(QuicStreamId , bool , size_t size, const QuicHeaderList& header_list) { SaveToHandler(size, header_list); } void SaveToHandler(size_t size, const QuicHeaderList& header_list) { headers_handler_ = std::make_unique<RecordingHeadersHandler>(); headers_handler_->OnHeaderBlockStart(); for (const auto& p : header_list) { headers_handler_->OnHeader(p.first, p.second); } headers_handler_->OnHeaderBlockEnd(size, size); } void WriteAndExpectRequestHeaders(QuicStreamId stream_id, bool fin, SpdyPriority priority) { WriteHeadersAndCheckData(stream_id, fin, priority, true ); } void WriteAndExpectResponseHeaders(QuicStreamId stream_id, bool fin) { WriteHeadersAndCheckData(stream_id, fin, 0, false ); } void WriteHeadersAndCheckData(QuicStreamId stream_id, bool fin, SpdyPriority priority, bool is_request) { EXPECT_CALL(session_, WritevData(QuicUtils::GetHeadersStreamId( connection_->transport_version()), _, _, NO_FIN, _, _)) .WillOnce(WithArgs<1>(Invoke(this, &QuicHeadersStreamTest::SaveIov))); QuicSpdySessionPeer::WriteHeadersOnHeadersStream( &session_, stream_id, headers_.Clone(), fin, spdy::SpdyStreamPrecedence(priority), nullptr); if (is_request) { EXPECT_CALL( visitor_, OnHeaders(stream_id, saved_data_.length() - spdy::kFrameHeaderSize, kHasPriority, Spdy3PriorityToHttp2Weight(priority), 0, false, fin, kFrameComplete)); } else { EXPECT_CALL( visitor_, OnHeaders(stream_id, saved_data_.length() - spdy::kFrameHeaderSize, !kHasPriority, 0, 0, false, fin, kFrameComplete)); } headers_handler_ = std::make_unique<RecordingHeadersHandler>(); EXPECT_CALL(visitor_, OnHeaderFrameStart(stream_id)) .WillOnce(Return(headers_handler_.get())); EXPECT_CALL(visitor_, OnHeaderFrameEnd(stream_id)).Times(1); if (fin) { EXPECT_CALL(visitor_, OnStreamEnd(stream_id)); } deframer_->ProcessInput(saved_data_.data(), saved_data_.length()); EXPECT_FALSE(deframer_->HasError()) << http2::Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); CheckHeaders(); saved_data_.clear(); } void CheckHeaders() { ASSERT_TRUE(headers_handler_); EXPECT_EQ(headers_, headers_handler_->decoded_block()); headers_handler_.reset(); } Perspective perspective() const { return GetParam().perspective; } QuicTransportVersion transport_version() const { return GetParam().version.transport_version; } ParsedQuicVersionVector GetVersion() { ParsedQuicVersionVector versions; versions.push_back(GetParam().version); return versions; } void TearDownLocalConnectionState() { QuicConnectionPeer::TearDownLocalConnectionState(connection_); } QuicStreamId NextPromisedStreamId() { return next_promised_stream_id_ += next_stream_id_; } static constexpr bool kFrameComplete = true; static constexpr bool kHasPriority = true; MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; StrictMock<MockQuicConnection>* connection_; StrictMock<MockQuicSpdySession> session_; QuicHeadersStream* headers_stream_; Http2HeaderBlock headers_; std::unique_ptr<RecordingHeadersHandler> headers_handler_; std::string body_; std::string saved_data_; std::string saved_header_data_; std::string saved_payloads_; std::unique_ptr<SpdyFramer> framer_; std::unique_ptr<http2::Http2DecoderAdapter> deframer_; StrictMock<MockVisitor> visitor_; QuicStreamFrame stream_frame_; QuicStreamId next_promised_stream_id_; QuicStreamId client_id_1_; QuicStreamId client_id_2_; QuicStreamId client_id_3_; QuicStreamId next_stream_id_; }; INSTANTIATE_TEST_SUITE_P(Tests, QuicHeadersStreamTest, ::testing::ValuesIn(GetTestParams()), ::testing::PrintToStringParamName()); TEST_P(QuicHeadersStreamTest, StreamId) { EXPECT_EQ(QuicUtils::GetHeadersStreamId(connection_->transport_version()), headers_stream_->id()); } TEST_P(QuicHeadersStreamTest, WriteHeaders) { for (QuicStreamId stream_id = client_id_1_; stream_id < client_id_3_; stream_id += next_stream_id_) { for (bool fin : {false, true}) { if (perspective() == Perspective::IS_SERVER) { WriteAndExpectResponseHeaders(stream_id, fin); } else { for (SpdyPriority priority = 0; priority < 7; ++priority) { WriteAndExpectRequestHeaders(stream_id, fin, 0); } } } } } TEST_P(QuicHeadersStreamTest, ProcessRawData) { for (QuicStreamId stream_id = client_id_1_; stream_id < client_id_3_; stream_id += next_stream_id_) { for (bool fin : {false, true}) { for (SpdyPriority priority = 0; priority < 7; ++priority) { SpdySerializedFrame frame; if (perspective() == Perspective::IS_SERVER) { SpdyHeadersIR headers_frame(stream_id, headers_.Clone()); headers_frame.set_fin(fin); headers_frame.set_has_priority(true); headers_frame.set_weight(Spdy3PriorityToHttp2Weight(0)); frame = framer_->SerializeFrame(headers_frame); EXPECT_CALL(session_, OnStreamHeadersPriority( stream_id, spdy::SpdyStreamPrecedence(0))); } else { SpdyHeadersIR headers_frame(stream_id, headers_.Clone()); headers_frame.set_fin(fin); frame = framer_->SerializeFrame(headers_frame); } EXPECT_CALL(session_, OnStreamHeaderList(stream_id, fin, frame.size(), _)) .WillOnce(Invoke(this, &QuicHeadersStreamTest::SaveHeaderList)); stream_frame_.data_buffer = frame.data(); stream_frame_.data_length = frame.size(); headers_stream_->OnStreamFrame(stream_frame_); stream_frame_.offset += frame.size(); CheckHeaders(); } } } } TEST_P(QuicHeadersStreamTest, ProcessPushPromise) { for (QuicStreamId stream_id = client_id_1_; stream_id < client_id_3_; stream_id += next_stream_id_) { QuicStreamId promised_stream_id = NextPromisedStreamId(); SpdyPushPromiseIR push_promise(stream_id, promised_stream_id, headers_.Clone()); SpdySerializedFrame frame(framer_->SerializeFrame(push_promise)); if (perspective() == Perspective::IS_SERVER) { EXPECT_CALL(*connection_, CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA, "PUSH_PROMISE not supported.", _)) .WillRepeatedly(InvokeWithoutArgs( this, &QuicHeadersStreamTest::TearDownLocalConnectionState)); } else { EXPECT_CALL(session_, MaybeSendRstStreamFrame(promised_stream_id, _, _)); } stream_frame_.data_buffer = frame.data(); stream_frame_.data_length = frame.size(); headers_stream_->OnStreamFrame(stream_frame_); stream_frame_.offset += frame.size(); } } TEST_P(QuicHeadersStreamTest, ProcessPriorityFrame) { QuicStreamId parent_stream_id = 0; for (SpdyPriority priority = 0; priority < 7; ++priority) { for (QuicStreamId stream_id = client_id_1_; stream_id < client_id_3_; stream_id += next_stream_id_) { int weight = Spdy3PriorityToHttp2Weight(priority); SpdyPriorityIR priority_frame(stream_id, parent_stream_id, weight, true); SpdySerializedFrame frame(framer_->SerializeFrame(priority_frame)); parent_stream_id = stream_id; if (perspective() == Perspective::IS_CLIENT) { EXPECT_CALL(*connection_, CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA, "Server must not send PRIORITY frames.", _)) .WillRepeatedly(InvokeWithoutArgs( this, &QuicHeadersStreamTest::TearDownLocalConnectionState)); } else { EXPECT_CALL( session_, OnPriorityFrame(stream_id, spdy::SpdyStreamPrecedence(priority))) .Times(1); } stream_frame_.data_buffer = frame.data(); stream_frame_.data_length = frame.size(); headers_stream_->OnStreamFrame(stream_frame_); stream_frame_.offset += frame.size(); } } } TEST_P(QuicHeadersStreamTest, ProcessPushPromiseDisabledSetting) { if (perspective() != Perspective::IS_CLIENT) { return; } session_.OnConfigNegotiated(); SpdySettingsIR data; data.AddSetting(SETTINGS_ENABLE_PUSH, 0); SpdySerializedFrame frame(framer_->SerializeFrame(data)); stream_frame_.data_buffer = frame.data(); stream_frame_.data_length = frame.size(); EXPECT_CALL( *connection_, CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA, "Unsupported field of HTTP/2 SETTINGS frame: 2", _)); headers_stream_->OnStreamFrame(stream_frame_); } TEST_P(QuicHeadersStreamTest, ProcessLargeRawData) { headers_["key0"] = std::string(1 << 13, '.'); headers_["key1"] = std::string(1 << 13, '.'); headers_["key2"] = std::string(1 << 13, '.'); for (QuicStreamId stream_id = client_id_1_; stream_id < client_id_3_; stream_id += next_stream_id_) { for (bool fin : {false, true}) { for (SpdyPriority priority = 0; priority < 7; ++priority) { SpdySerializedFrame frame; if (perspective() == Perspective::IS_SERVER) { SpdyHeadersIR headers_frame(stream_id, headers_.Clone()); headers_frame.set_fin(fin); headers_frame.set_has_priority(true); headers_frame.set_weight(Spdy3PriorityToHttp2Weight(0)); frame = framer_->SerializeFrame(headers_frame); EXPECT_CALL(session_, OnStreamHeadersPriority( stream_id, spdy::SpdyStreamPrecedence(0))); } else { SpdyHeadersIR headers_frame(stream_id, headers_.Clone()); headers_frame.set_fin(fin); frame = framer_->SerializeFrame(headers_frame); } EXPECT_CALL(session_, OnStreamHeaderList(stream_id, fin, frame.size(), _)) .WillOnce(Invoke(this, &QuicHeadersStreamTest::SaveHeaderList)); stream_frame_.data_buffer = frame.data(); stream_frame_.data_length = frame.size(); headers_stream_->OnStreamFrame(stream_frame_); stream_frame_.offset += frame.size(); CheckHeaders(); } } } } TEST_P(QuicHeadersStreamTest, ProcessBadData) { const char kBadData[] = "blah blah blah"; EXPECT_CALL(*connection_, CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA, _, _)) .Times(::testing::AnyNumber()); stream_frame_.data_buffer = kBadData; stream_frame_.data_length = strlen(kBadData); headers_stream_->OnStreamFrame(stream_frame_); } TEST_P(QuicHeadersStreamTest, ProcessSpdyDataFrame) { SpdyDataIR data( 2, "ping"); SpdySerializedFrame frame(framer_->SerializeFrame(data)); EXPECT_CALL(*connection_, CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA, "SPDY DATA frame received.", _)) .WillOnce(InvokeWithoutArgs( this, &QuicHeadersStreamTest::TearDownLocalConnectionState)); stream_frame_.data_buffer = frame.data(); stream_frame_.data_length = frame.size(); headers_stream_->OnStreamFrame(stream_frame_); } TEST_P(QuicHeadersStreamTest, ProcessSpdyRstStreamFrame) { SpdyRstStreamIR data( 2, ERROR_CODE_PROTOCOL_ERROR); SpdySerializedFrame frame(framer_->SerializeFrame(data)); EXPECT_CALL(*connection_, CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA, "SPDY RST_STREAM frame received.", _)) .WillOnce(InvokeWithoutArgs( this, &QuicHeadersStreamTest::TearDownLocalConnectionState)); stream_frame_.data_buffer = frame.data(); stream_frame_.data_length = frame.size(); headers_stream_->OnStreamFrame(stream_frame_); } TEST_P(QuicHeadersStreamTest, RespectHttp2SettingsFrameSupportedFields) { const uint32_t kTestHeaderTableSize = 1000; SpdySettingsIR data; data.AddSetting(SETTINGS_HEADER_TABLE_SIZE, kTestHeaderTableSize); data.AddSetting(spdy::SETTINGS_MAX_HEADER_LIST_SIZE, 2000); SpdySerializedFrame frame(framer_->SerializeFrame(data)); stream_frame_.data_buffer = frame.data(); stream_frame_.data_length = frame.size(); headers_stream_->OnStreamFrame(stream_frame_); EXPECT_EQ(kTestHeaderTableSize, QuicSpdySessionPeer::GetSpdyFramer(&session_) ->header_encoder_table_size()); } TEST_P(QuicHeadersStreamTest, LimitEncoderDynamicTableSize) { const uint32_t kVeryLargeTableSizeLimit = 1024 * 1024 * 1024; SpdySettingsIR data; data.AddSetting(SETTINGS_HEADER_TABLE_SIZE, kVeryLargeTableSizeLimit); SpdySerializedFrame frame(framer_->SerializeFrame(data)); stream_frame_.data_buffer = frame.data(); stream_frame_.data_length = frame.size(); headers_stream_->OnStreamFrame(stream_frame_); EXPECT_EQ(16384u, QuicSpdySessionPeer::GetSpdyFramer(&session_) ->header_encoder_table_size()); } TEST_P(QuicHeadersStreamTest, RespectHttp2SettingsFrameUnsupportedFields) { SpdySettingsIR data; data.AddSetting(SETTINGS_MAX_CONCURRENT_STREAMS, 100); data.AddSetting(SETTINGS_INITIAL_WINDOW_SIZE, 100); data.AddSetting(SETTINGS_ENABLE_PUSH, 1); data.AddSetting(SETTINGS_MAX_FRAME_SIZE, 1250); SpdySerializedFrame frame(framer_->SerializeFrame(data)); EXPECT_CALL(*connection_, CloseConnection( QUIC_INVALID_HEADERS_STREAM_DATA, absl::StrCat("Unsupported field of HTTP/2 SETTINGS frame: ", SETTINGS_MAX_CONCURRENT_STREAMS), _)); EXPECT_CALL(*connection_, CloseConnection( QUIC_INVALID_HEADERS_STREAM_DATA, absl::StrCat("Unsupported field of HTTP/2 SETTINGS frame: ", SETTINGS_INITIAL_WINDOW_SIZE), _)); if (session_.perspective() == Perspective::IS_CLIENT) { EXPECT_CALL(*connection_, CloseConnection( QUIC_INVALID_HEADERS_STREAM_DATA, absl::StrCat("Unsupported field of HTTP/2 SETTINGS frame: ", SETTINGS_ENABLE_PUSH), _)); } EXPECT_CALL(*connection_, CloseConnection( QUIC_INVALID_HEADERS_STREAM_DATA, absl::StrCat("Unsupported field of HTTP/2 SETTINGS frame: ", SETTINGS_MAX_FRAME_SIZE), _)); stream_frame_.data_buffer = frame.data(); stream_frame_.data_length = frame.size(); headers_stream_->OnStreamFrame(stream_frame_); } TEST_P(QuicHeadersStreamTest, ProcessSpdyPingFrame) { SpdyPingIR data(1); SpdySerializedFrame frame(framer_->SerializeFrame(data)); EXPECT_CALL(*connection_, CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA, "SPDY PING frame received.", _)) .WillOnce(InvokeWithoutArgs( this, &QuicHeadersStreamTest::TearDownLocalConnectionState)); stream_frame_.data_buffer = frame.data(); stream_frame_.data_length = frame.size(); headers_stream_->OnStreamFrame(stream_frame_); } TEST_P(QuicHeadersStreamTest, ProcessSpdyGoAwayFrame) { SpdyGoAwayIR data( 1, ERROR_CODE_PROTOCOL_ERROR, "go away"); SpdySerializedFrame frame(framer_->SerializeFrame(data)); EXPECT_CALL(*connection_, CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA, "SPDY GOAWAY frame received.", _)) .WillOnce(InvokeWithoutArgs( this, &QuicHeadersStreamTest::TearDownLocalConnectionState)); stream_frame_.data_buffer = frame.data(); stream_frame_.data_length = frame.size(); headers_stream_->OnStreamFrame(stream_frame_); } TEST_P(QuicHeadersStreamTest, ProcessSpdyWindowUpdateFrame) { SpdyWindowUpdateIR data( 1, 1); SpdySerializedFrame frame(framer_->SerializeFrame(data)); EXPECT_CALL(*connection_, CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA, "SPDY WINDOW_UPDATE frame received.", _)) .WillOnce(InvokeWithoutArgs( this, &QuicHeadersStreamTest::TearDownLocalConnectionState)); stream_frame_.data_buffer = frame.data(); stream_frame_.data_length = frame.size(); headers_stream_->OnStreamFrame(stream_frame_); } TEST_P(QuicHeadersStreamTest, NoConnectionLevelFlowControl) { EXPECT_FALSE(QuicStreamPeer::StreamContributesToConnectionFlowControl( headers_stream_)); } TEST_P(QuicHeadersStreamTest, AckSentData) { EXPECT_CALL(session_, WritevData(QuicUtils::GetHeadersStreamId( connection_->transport_version()), _, _, NO_FIN, _, _)) .WillRepeatedly(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); InSequence s; quiche::QuicheReferenceCountedPointer<MockAckListener> ack_listener1( new MockAckListener()); quiche::QuicheReferenceCountedPointer<MockAckListener> ack_listener2( new MockAckListener()); quiche::QuicheReferenceCountedPointer<MockAckListener> ack_listener3( new MockAckListener()); headers_stream_->WriteOrBufferData("Header5", false, ack_listener1); headers_stream_->WriteOrBufferData("Header5", false, ack_listener1); headers_stream_->WriteOrBufferData("Header7", false, ack_listener2); headers_stream_->WriteOrBufferData("Header9", false, ack_listener3); headers_stream_->WriteOrBufferData("Header7", false, ack_listener2); headers_stream_->WriteOrBufferData("Header9", false, ack_listener3); EXPECT_CALL(*ack_listener3, OnPacketRetransmitted(7)).Times(1); EXPECT_CALL(*ack_listener2, OnPacketRetransmitted(7)).Times(1); headers_stream_->OnStreamFrameRetransmitted(21, 7, false); headers_stream_->OnStreamFrameRetransmitted(28, 7, false); QuicByteCount newly_acked_length = 0; EXPECT_CALL(*ack_listener3, OnPacketAcked(7, _)); EXPECT_CALL(*ack_listener2, OnPacketAcked(7, _)); EXPECT_TRUE(headers_stream_->OnStreamFrameAcked( 21, 7, false, QuicTime::Delta::Zero(), QuicTime::Zero(), &newly_acked_length)); EXPECT_EQ(7u, newly_acked_length); EXPECT_TRUE(headers_stream_->OnStreamFrameAcked( 28, 7, false, QuicTime::Delta::Zero(), QuicTime::Zero(), &newly_acked_length)); EXPECT_EQ(7u, newly_acked_length); EXPECT_CALL(*ack_listener3, OnPacketAcked(7, _)); EXPECT_TRUE(headers_stream_->OnStreamFrameAcked( 35, 7, false, QuicTime::Delta::Zero(), QuicTime::Zero(), &newly_acked_length)); EXPECT_EQ(7u, newly_acked_length); EXPECT_CALL(*ack_listener1, OnPacketAcked(7, _)); EXPECT_CALL(*ack_listener1, OnPacketAcked(7, _)); EXPECT_TRUE(headers_stream_->OnStreamFrameAcked( 0, 7, false, QuicTime::Delta::Zero(), QuicTime::Zero(), &newly_acked_length)); EXPECT_EQ(7u, newly_acked_length); EXPECT_TRUE(headers_stream_->OnStreamFrameAcked( 7, 7, false, QuicTime::Delta::Zero(), QuicTime::Zero(), &newly_acked_length)); EXPECT_EQ(7u, newly_acked_length); EXPECT_CALL(*ack_listener2, OnPacketAcked(7, _)); EXPECT_TRUE(headers_stream_->OnStreamFrameAcked( 14, 10, false, QuicTime::Delta::Zero(), QuicTime::Zero(), &newly_acked_length)); EXPECT_EQ(7u, newly_acked_length); } TEST_P(QuicHeadersStreamTest, FrameContainsMultipleHeaders) { EXPECT_CALL(session_, WritevData(QuicUtils::GetHeadersStreamId( connection_->transport_version()), _, _, NO_FIN, _, _)) .WillRepeatedly(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); InSequence s; quiche::QuicheReferenceCountedPointer<MockAckListener> ack_listener1( new MockAckListener()); quiche::QuicheReferenceCountedPointer<MockAckListener> ack_listener2( new MockAckListener()); quiche::QuicheReferenceCountedPointer<MockAckListener> ack_listener3( new MockAckListener()); headers_stream_->WriteOrBufferData("Header5", false, ack_listener1); headers_stream_->WriteOrBufferData("Header5", false, ack_listener1); headers_stream_->WriteOrBufferData("Header7", false, ack_listener2); headers_stream_->WriteOrBufferData("Header9", false, ack_listener3); headers_stream_->WriteOrBufferData("Header7", false, ack_listener2); headers_stream_->WriteOrBufferData("Header9", false, ack_listener3); EXPECT_CALL(*ack_listener1, OnPacketRetransmitted(14)); EXPECT_CALL(*ack_listener2, OnPacketRetransmitted(3)); headers_stream_->OnStreamFrameRetransmitted(0, 17, false); QuicByteCount newly_acked_length = 0; EXPECT_CALL(*ack_listener2, OnPacketAcked(4, _)); EXPECT_CALL(*ack_listener3, OnPacketAcked(7, _)); EXPECT_CALL(*ack_listener2, OnPacketAcked(2, _)); EXPECT_TRUE(headers_stream_->OnStreamFrameAcked( 17, 13, false, QuicTime::Delta::Zero(), QuicTime::Zero(), &newly_acked_length)); EXPECT_EQ(13u, newly_acked_length); EXPECT_CALL(*ack_listener2, OnPacketAcked(5, _)); EXPECT_CALL(*ack_listener3, OnPacketAcked(7, _)); EXPECT_TRUE(headers_stream_->OnStreamFrameAcked( 30, 12,
318
cpp
google/quiche
quic_header_list
quiche/quic/core/http/quic_header_list.cc
quiche/quic/core/http/quic_header_list_test.cc
#ifndef QUICHE_QUIC_CORE_HTTP_QUIC_HEADER_LIST_H_ #define QUICHE_QUIC_CORE_HTTP_QUIC_HEADER_LIST_H_ #include <algorithm> #include <functional> #include <string> #include <utility> #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/common/quiche_circular_deque.h" #include "quiche/spdy/core/spdy_headers_handler_interface.h" namespace quic { class QUICHE_EXPORT QuicHeaderList : public spdy::SpdyHeadersHandlerInterface { public: using ListType = quiche::QuicheCircularDeque<std::pair<std::string, std::string>>; using value_type = ListType::value_type; using const_iterator = ListType::const_iterator; QuicHeaderList(); QuicHeaderList(QuicHeaderList&& other); QuicHeaderList(const QuicHeaderList& other); QuicHeaderList& operator=(QuicHeaderList&& other); QuicHeaderList& operator=(const QuicHeaderList& other); ~QuicHeaderList() override; void OnHeaderBlockStart() override; void OnHeader(absl::string_view name, absl::string_view value) override; void OnHeaderBlockEnd(size_t uncompressed_header_bytes, size_t compressed_header_bytes) override; void Clear(); const_iterator begin() const { return header_list_.begin(); } const_iterator end() const { return header_list_.end(); } bool empty() const { return header_list_.empty(); } size_t uncompressed_header_bytes() const { return uncompressed_header_bytes_; } size_t compressed_header_bytes() const { return compressed_header_bytes_; } void set_max_header_list_size(size_t max_header_list_size) { max_header_list_size_ = max_header_list_size; } std::string DebugString() const; private: quiche::QuicheCircularDeque<std::pair<std::string, std::string>> header_list_; size_t max_header_list_size_; size_t current_header_list_size_; size_t uncompressed_header_bytes_; size_t compressed_header_bytes_; }; inline bool operator==(const QuicHeaderList& l1, const QuicHeaderList& l2) { auto pred = [](const std::pair<std::string, std::string>& p1, const std::pair<std::string, std::string>& p2) { return p1.first == p2.first && p1.second == p2.second; }; return std::equal(l1.begin(), l1.end(), l2.begin(), pred); } } #endif #include "quiche/quic/core/http/quic_header_list.h" #include <limits> #include <string> #include "absl/strings/string_view.h" #include "quiche/quic/core/qpack/qpack_header_table.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/platform/api/quic_flags.h" namespace quic { QuicHeaderList::QuicHeaderList() : max_header_list_size_(std::numeric_limits<size_t>::max()), current_header_list_size_(0), uncompressed_header_bytes_(0), compressed_header_bytes_(0) {} QuicHeaderList::QuicHeaderList(QuicHeaderList&& other) = default; QuicHeaderList::QuicHeaderList(const QuicHeaderList& other) = default; QuicHeaderList& QuicHeaderList::operator=(const QuicHeaderList& other) = default; QuicHeaderList& QuicHeaderList::operator=(QuicHeaderList&& other) = default; QuicHeaderList::~QuicHeaderList() {} void QuicHeaderList::OnHeaderBlockStart() { QUIC_BUG_IF(quic_bug_12518_1, current_header_list_size_ != 0) << "OnHeaderBlockStart called more than once!"; } void QuicHeaderList::OnHeader(absl::string_view name, absl::string_view value) { if (current_header_list_size_ < max_header_list_size_) { current_header_list_size_ += name.size(); current_header_list_size_ += value.size(); current_header_list_size_ += kQpackEntrySizeOverhead; header_list_.emplace_back(std::string(name), std::string(value)); } } void QuicHeaderList::OnHeaderBlockEnd(size_t uncompressed_header_bytes, size_t compressed_header_bytes) { uncompressed_header_bytes_ = uncompressed_header_bytes; compressed_header_bytes_ = compressed_header_bytes; if (current_header_list_size_ > max_header_list_size_) { Clear(); } } void QuicHeaderList::Clear() { header_list_.clear(); current_header_list_size_ = 0; uncompressed_header_bytes_ = 0; compressed_header_bytes_ = 0; } std::string QuicHeaderList::DebugString() const { std::string s = "{ "; for (const auto& p : *this) { s.append(p.first + "=" + p.second + ", "); } s.append("}"); return s; } }
#include "quiche/quic/core/http/quic_header_list.h" #include <string> #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" using ::testing::ElementsAre; using ::testing::Pair; namespace quic::test { class QuicHeaderListTest : public QuicTest {}; TEST_F(QuicHeaderListTest, OnHeader) { QuicHeaderList headers; headers.OnHeader("foo", "bar"); headers.OnHeader("april", "fools"); headers.OnHeader("beep", ""); EXPECT_THAT(headers, ElementsAre(Pair("foo", "bar"), Pair("april", "fools"), Pair("beep", ""))); } TEST_F(QuicHeaderListTest, DebugString) { QuicHeaderList headers; headers.OnHeader("foo", "bar"); headers.OnHeader("april", "fools"); headers.OnHeader("beep", ""); EXPECT_EQ("{ foo=bar, april=fools, beep=, }", headers.DebugString()); } TEST_F(QuicHeaderListTest, TooLarge) { const size_t kMaxHeaderListSize = 256; QuicHeaderList headers; headers.set_max_header_list_size(kMaxHeaderListSize); std::string key = "key"; std::string value(kMaxHeaderListSize, '1'); headers.OnHeader(key, value); headers.OnHeader(key + "2", value); EXPECT_LT(headers.DebugString().size(), 2 * value.size()); size_t total_bytes = 2 * (key.size() + value.size()) + 1; headers.OnHeaderBlockEnd(total_bytes, total_bytes); EXPECT_TRUE(headers.empty()); EXPECT_EQ("{ }", headers.DebugString()); } TEST_F(QuicHeaderListTest, NotTooLarge) { QuicHeaderList headers; headers.set_max_header_list_size(1 << 20); std::string key = "key"; std::string value(1 << 18, '1'); headers.OnHeader(key, value); size_t total_bytes = key.size() + value.size(); headers.OnHeaderBlockEnd(total_bytes, total_bytes); EXPECT_FALSE(headers.empty()); } TEST_F(QuicHeaderListTest, IsCopyableAndAssignable) { QuicHeaderList headers; headers.OnHeader("foo", "bar"); headers.OnHeader("april", "fools"); headers.OnHeader("beep", ""); QuicHeaderList headers2(headers); QuicHeaderList headers3 = headers; EXPECT_THAT(headers2, ElementsAre(Pair("foo", "bar"), Pair("april", "fools"), Pair("beep", ""))); EXPECT_THAT(headers3, ElementsAre(Pair("foo", "bar"), Pair("april", "fools"), Pair("beep", ""))); } }
319
cpp
google/quiche
quic_spdy_client_session
quiche/quic/core/http/quic_spdy_client_session.cc
quiche/quic/core/http/quic_spdy_client_session_test.cc
#ifndef QUICHE_QUIC_CORE_HTTP_QUIC_SPDY_CLIENT_SESSION_H_ #define QUICHE_QUIC_CORE_HTTP_QUIC_SPDY_CLIENT_SESSION_H_ #include <memory> #include <string> #include "quiche/quic/core/http/quic_spdy_client_session_base.h" #include "quiche/quic/core/http/quic_spdy_client_stream.h" #include "quiche/quic/core/quic_crypto_client_stream.h" #include "quiche/quic/core/quic_packets.h" namespace quic { class QuicConnection; class QuicServerId; class QUICHE_EXPORT QuicSpdyClientSession : public QuicSpdyClientSessionBase { public: QuicSpdyClientSession(const QuicConfig& config, const ParsedQuicVersionVector& supported_versions, QuicConnection* connection, const QuicServerId& server_id, QuicCryptoClientConfig* crypto_config); QuicSpdyClientSession(const QuicConfig& config, const ParsedQuicVersionVector& supported_versions, QuicConnection* connection, QuicSession::Visitor* visitor, const QuicServerId& server_id, QuicCryptoClientConfig* crypto_config); QuicSpdyClientSession(const QuicSpdyClientSession&) = delete; QuicSpdyClientSession& operator=(const QuicSpdyClientSession&) = delete; ~QuicSpdyClientSession() override; void Initialize() override; QuicSpdyClientStream* CreateOutgoingBidirectionalStream() override; QuicSpdyClientStream* CreateOutgoingUnidirectionalStream() override; QuicCryptoClientStreamBase* GetMutableCryptoStream() override; const QuicCryptoClientStreamBase* GetCryptoStream() const override; void OnProofValid(const QuicCryptoClientConfig::CachedState& cached) override; void OnProofVerifyDetailsAvailable( const ProofVerifyDetails& verify_details) override; virtual void CryptoConnect(); int GetNumSentClientHellos() const; bool ResumptionAttempted() const; bool IsResumption() const; bool EarlyDataAccepted() const; bool ReceivedInchoateReject() const; int GetNumReceivedServerConfigUpdates() const; using QuicSession::CanOpenNextOutgoingBidirectionalStream; void set_respect_goaway(bool respect_goaway) { respect_goaway_ = respect_goaway; } QuicSSLConfig GetSSLConfig() const override { return crypto_config_->ssl_config(); } protected: QuicSpdyStream* CreateIncomingStream(QuicStreamId id) override; QuicSpdyStream* CreateIncomingStream(PendingStream* pending) override; bool ShouldCreateOutgoingBidirectionalStream() override; bool ShouldCreateOutgoingUnidirectionalStream() override; bool ShouldCreateIncomingStream(QuicStreamId id) override; virtual std::unique_ptr<QuicCryptoClientStreamBase> CreateQuicCryptoStream(); virtual std::unique_ptr<QuicSpdyClientStream> CreateClientStream(); const QuicServerId& server_id() const { return server_id_; } QuicCryptoClientConfig* crypto_config() { return crypto_config_; } private: std::unique_ptr<QuicCryptoClientStreamBase> crypto_stream_; QuicServerId server_id_; QuicCryptoClientConfig* crypto_config_; bool respect_goaway_; }; } #endif #include "quiche/quic/core/http/quic_spdy_client_session.h" #include <memory> #include <string> #include <utility> #include "absl/memory/memory.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/http/quic_server_initiated_spdy_stream.h" #include "quiche/quic/core/http/quic_spdy_client_stream.h" #include "quiche/quic/core/http/spdy_utils.h" #include "quiche/quic/core/quic_server_id.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { QuicSpdyClientSession::QuicSpdyClientSession( const QuicConfig& config, const ParsedQuicVersionVector& supported_versions, QuicConnection* connection, const QuicServerId& server_id, QuicCryptoClientConfig* crypto_config) : QuicSpdyClientSession(config, supported_versions, connection, nullptr, server_id, crypto_config) {} QuicSpdyClientSession::QuicSpdyClientSession( const QuicConfig& config, const ParsedQuicVersionVector& supported_versions, QuicConnection* connection, QuicSession::Visitor* visitor, const QuicServerId& server_id, QuicCryptoClientConfig* crypto_config) : QuicSpdyClientSessionBase(connection, visitor, config, supported_versions), server_id_(server_id), crypto_config_(crypto_config), respect_goaway_(true) {} QuicSpdyClientSession::~QuicSpdyClientSession() = default; void QuicSpdyClientSession::Initialize() { crypto_stream_ = CreateQuicCryptoStream(); QuicSpdyClientSessionBase::Initialize(); } void QuicSpdyClientSession::OnProofValid( const QuicCryptoClientConfig::CachedState& ) {} void QuicSpdyClientSession::OnProofVerifyDetailsAvailable( const ProofVerifyDetails& ) {} bool QuicSpdyClientSession::ShouldCreateOutgoingBidirectionalStream() { if (!crypto_stream_->encryption_established()) { QUIC_DLOG(INFO) << "Encryption not active so no outgoing stream created."; QUIC_CODE_COUNT( quic_client_fails_to_create_stream_encryption_not_established); return false; } if (goaway_received() && respect_goaway_) { QUIC_DLOG(INFO) << "Failed to create a new outgoing stream. " << "Already received goaway."; QUIC_CODE_COUNT(quic_client_fails_to_create_stream_goaway_received); return false; } return CanOpenNextOutgoingBidirectionalStream(); } bool QuicSpdyClientSession::ShouldCreateOutgoingUnidirectionalStream() { QUIC_BUG(quic_bug_10396_1) << "Try to create outgoing unidirectional client data streams"; return false; } QuicSpdyClientStream* QuicSpdyClientSession::CreateOutgoingBidirectionalStream() { if (!ShouldCreateOutgoingBidirectionalStream()) { return nullptr; } std::unique_ptr<QuicSpdyClientStream> stream = CreateClientStream(); QuicSpdyClientStream* stream_ptr = stream.get(); ActivateStream(std::move(stream)); return stream_ptr; } QuicSpdyClientStream* QuicSpdyClientSession::CreateOutgoingUnidirectionalStream() { QUIC_BUG(quic_bug_10396_2) << "Try to create outgoing unidirectional client data streams"; return nullptr; } std::unique_ptr<QuicSpdyClientStream> QuicSpdyClientSession::CreateClientStream() { return std::make_unique<QuicSpdyClientStream>( GetNextOutgoingBidirectionalStreamId(), this, BIDIRECTIONAL); } QuicCryptoClientStreamBase* QuicSpdyClientSession::GetMutableCryptoStream() { return crypto_stream_.get(); } const QuicCryptoClientStreamBase* QuicSpdyClientSession::GetCryptoStream() const { return crypto_stream_.get(); } void QuicSpdyClientSession::CryptoConnect() { QUICHE_DCHECK(flow_controller()); crypto_stream_->CryptoConnect(); } int QuicSpdyClientSession::GetNumSentClientHellos() const { return crypto_stream_->num_sent_client_hellos(); } bool QuicSpdyClientSession::ResumptionAttempted() const { return crypto_stream_->ResumptionAttempted(); } bool QuicSpdyClientSession::IsResumption() const { return crypto_stream_->IsResumption(); } bool QuicSpdyClientSession::EarlyDataAccepted() const { return crypto_stream_->EarlyDataAccepted(); } bool QuicSpdyClientSession::ReceivedInchoateReject() const { return crypto_stream_->ReceivedInchoateReject(); } int QuicSpdyClientSession::GetNumReceivedServerConfigUpdates() const { return crypto_stream_->num_scup_messages_received(); } bool QuicSpdyClientSession::ShouldCreateIncomingStream(QuicStreamId id) { if (!connection()->connected()) { QUIC_BUG(quic_bug_10396_3) << "ShouldCreateIncomingStream called when disconnected"; return false; } if (goaway_received() && respect_goaway_) { QUIC_DLOG(INFO) << "Failed to create a new outgoing stream. " << "Already received goaway."; return false; } if (QuicUtils::IsClientInitiatedStreamId(transport_version(), id)) { QUIC_BUG(quic_bug_10396_4) << "ShouldCreateIncomingStream called with client initiated " "stream ID."; return false; } if (QuicUtils::IsClientInitiatedStreamId(transport_version(), id)) { QUIC_LOG(WARNING) << "Received invalid push stream id " << id; connection()->CloseConnection( QUIC_INVALID_STREAM_ID, "Server created non write unidirectional stream", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return false; } if (VersionHasIetfQuicFrames(transport_version()) && QuicUtils::IsBidirectionalStreamId(id, version()) && !WillNegotiateWebTransport()) { connection()->CloseConnection( QUIC_HTTP_SERVER_INITIATED_BIDIRECTIONAL_STREAM, "Server created bidirectional stream.", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return false; } return true; } QuicSpdyStream* QuicSpdyClientSession::CreateIncomingStream( PendingStream* pending) { QuicSpdyStream* stream = new QuicSpdyClientStream(pending, this); ActivateStream(absl::WrapUnique(stream)); return stream; } QuicSpdyStream* QuicSpdyClientSession::CreateIncomingStream(QuicStreamId id) { if (!ShouldCreateIncomingStream(id)) { return nullptr; } QuicSpdyStream* stream; if (version().UsesHttp3() && QuicUtils::IsBidirectionalStreamId(id, version())) { QUIC_BUG_IF(QuicServerInitiatedSpdyStream but no WebTransport support, !WillNegotiateWebTransport()) << "QuicServerInitiatedSpdyStream created but no WebTransport support"; stream = new QuicServerInitiatedSpdyStream(id, this, BIDIRECTIONAL); } else { stream = new QuicSpdyClientStream(id, this, READ_UNIDIRECTIONAL); } ActivateStream(absl::WrapUnique(stream)); return stream; } std::unique_ptr<QuicCryptoClientStreamBase> QuicSpdyClientSession::CreateQuicCryptoStream() { return std::make_unique<QuicCryptoClientStream>( server_id_, this, crypto_config_->proof_verifier()->CreateDefaultContext(), crypto_config_, this, version().UsesHttp3()); } }
#include "quiche/quic/core/http/quic_spdy_client_session.h" #include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/null_decrypter.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/http/http_constants.h" #include "quiche/quic/core/http/http_frames.h" #include "quiche/quic/core/http/quic_spdy_client_stream.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/core/tls_client_handshaker.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/crypto_test_utils.h" #include "quiche/quic/test_tools/mock_quic_spdy_client_stream.h" #include "quiche/quic/test_tools/quic_config_peer.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_framer_peer.h" #include "quiche/quic/test_tools/quic_packet_creator_peer.h" #include "quiche/quic/test_tools/quic_sent_packet_manager_peer.h" #include "quiche/quic/test_tools/quic_session_peer.h" #include "quiche/quic/test_tools/quic_spdy_session_peer.h" #include "quiche/quic/test_tools/quic_stream_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simple_session_cache.h" #include "quiche/spdy/core/http2_header_block.h" using spdy::Http2HeaderBlock; using ::testing::_; using ::testing::AnyNumber; using ::testing::AtLeast; using ::testing::AtMost; using ::testing::Invoke; using ::testing::StrictMock; using ::testing::Truly; namespace quic { namespace test { namespace { const char kServerHostname[] = "test.example.com"; const uint16_t kPort = 443; class TestQuicSpdyClientSession : public QuicSpdyClientSession { public: explicit TestQuicSpdyClientSession( const QuicConfig& config, const ParsedQuicVersionVector& supported_versions, QuicConnection* connection, const QuicServerId& server_id, QuicCryptoClientConfig* crypto_config) : QuicSpdyClientSession(config, supported_versions, connection, server_id, crypto_config) {} std::unique_ptr<QuicSpdyClientStream> CreateClientStream() override { return std::make_unique<MockQuicSpdyClientStream>( GetNextOutgoingBidirectionalStreamId(), this, BIDIRECTIONAL); } MockQuicSpdyClientStream* CreateIncomingStream(QuicStreamId id) override { if (!ShouldCreateIncomingStream(id)) { return nullptr; } MockQuicSpdyClientStream* stream = new MockQuicSpdyClientStream(id, this, READ_UNIDIRECTIONAL); ActivateStream(absl::WrapUnique(stream)); return stream; } }; class QuicSpdyClientSessionTest : public QuicTestWithParam<ParsedQuicVersion> { protected: QuicSpdyClientSessionTest() { auto client_cache = std::make_unique<test::SimpleSessionCache>(); client_session_cache_ = client_cache.get(); client_crypto_config_ = std::make_unique<QuicCryptoClientConfig>( crypto_test_utils::ProofVerifierForTesting(), std::move(client_cache)); server_crypto_config_ = crypto_test_utils::CryptoServerConfigForTesting(); Initialize(); connection_->AdvanceTime(QuicTime::Delta::FromSeconds(1)); } ~QuicSpdyClientSessionTest() override { session_.reset(nullptr); } void Initialize() { session_.reset(); connection_ = new ::testing::NiceMock<PacketSavingConnection>( &helper_, &alarm_factory_, Perspective::IS_CLIENT, SupportedVersions(GetParam())); session_ = std::make_unique<TestQuicSpdyClientSession>( DefaultQuicConfig(), SupportedVersions(GetParam()), connection_, QuicServerId(kServerHostname, kPort, false), client_crypto_config_.get()); session_->Initialize(); connection_->SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(connection_->perspective())); crypto_stream_ = static_cast<QuicCryptoClientStream*>( session_->GetMutableCryptoStream()); } bool ClearMaxStreamsControlFrame(const QuicFrame& frame) { if (frame.type == MAX_STREAMS_FRAME) { DeleteFrame(&const_cast<QuicFrame&>(frame)); return true; } return false; } public: bool ClearStreamsBlockedControlFrame(const QuicFrame& frame) { if (frame.type == STREAMS_BLOCKED_FRAME) { DeleteFrame(&const_cast<QuicFrame&>(frame)); return true; } return false; } protected: void CompleteCryptoHandshake() { CompleteCryptoHandshake(kDefaultMaxStreamsPerConnection); } void CompleteCryptoHandshake(uint32_t server_max_incoming_streams) { if (VersionHasIetfQuicFrames(connection_->transport_version())) { EXPECT_CALL(*connection_, SendControlFrame(_)) .Times(::testing::AnyNumber()) .WillRepeatedly(Invoke( this, &QuicSpdyClientSessionTest::ClearMaxStreamsControlFrame)); } session_->CryptoConnect(); QuicConfig config = DefaultQuicConfig(); if (VersionHasIetfQuicFrames(connection_->transport_version())) { config.SetMaxUnidirectionalStreamsToSend(server_max_incoming_streams); config.SetMaxBidirectionalStreamsToSend(server_max_incoming_streams); } else { config.SetMaxBidirectionalStreamsToSend(server_max_incoming_streams); } crypto_test_utils::HandshakeWithFakeServer( &config, server_crypto_config_.get(), &helper_, &alarm_factory_, connection_, crypto_stream_, AlpnForVersion(connection_->version())); } void CreateConnection() { connection_ = new ::testing::NiceMock<PacketSavingConnection>( &helper_, &alarm_factory_, Perspective::IS_CLIENT, SupportedVersions(GetParam())); connection_->AdvanceTime(QuicTime::Delta::FromSeconds(1)); session_ = std::make_unique<TestQuicSpdyClientSession>( DefaultQuicConfig(), SupportedVersions(GetParam()), connection_, QuicServerId(kServerHostname, kPort, false), client_crypto_config_.get()); session_->Initialize(); crypto_stream_ = static_cast<QuicCryptoClientStream*>( session_->GetMutableCryptoStream()); } void CompleteFirstConnection() { CompleteCryptoHandshake(); EXPECT_FALSE(session_->GetCryptoStream()->IsResumption()); if (session_->version().UsesHttp3()) { SettingsFrame settings; settings.values[SETTINGS_QPACK_MAX_TABLE_CAPACITY] = 2; settings.values[SETTINGS_MAX_FIELD_SECTION_SIZE] = 5; settings.values[256] = 4; session_->OnSettingsFrame(settings); } } QuicCryptoClientStream* crypto_stream_; std::unique_ptr<QuicCryptoServerConfig> server_crypto_config_; std::unique_ptr<QuicCryptoClientConfig> client_crypto_config_; MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; ::testing::NiceMock<PacketSavingConnection>* connection_; std::unique_ptr<TestQuicSpdyClientSession> session_; test::SimpleSessionCache* client_session_cache_; }; std::string ParamNameFormatter( const testing::TestParamInfo<QuicSpdyClientSessionTest::ParamType>& info) { return ParsedQuicVersionToString(info.param); } INSTANTIATE_TEST_SUITE_P(Tests, QuicSpdyClientSessionTest, ::testing::ValuesIn(AllSupportedVersions()), ParamNameFormatter); TEST_P(QuicSpdyClientSessionTest, GetSSLConfig) { EXPECT_EQ(session_->QuicSpdyClientSessionBase::GetSSLConfig(), QuicSSLConfig()); } TEST_P(QuicSpdyClientSessionTest, CryptoConnect) { CompleteCryptoHandshake(); } TEST_P(QuicSpdyClientSessionTest, NoEncryptionAfterInitialEncryption) { if (GetParam().handshake_protocol == PROTOCOL_TLS1_3) { return; } CompleteCryptoHandshake(); Initialize(); session_->CryptoConnect(); EXPECT_TRUE(session_->IsEncryptionEstablished()); QuicSpdyClientStream* stream = session_->CreateOutgoingBidirectionalStream(); ASSERT_TRUE(stream != nullptr); EXPECT_FALSE(QuicUtils::IsCryptoStreamId(connection_->transport_version(), stream->id())); CryptoHandshakeMessage rej; crypto_test_utils::FillInDummyReject(&rej); EXPECT_TRUE(session_->IsEncryptionEstablished()); crypto_test_utils::SendHandshakeMessageToStream( session_->GetMutableCryptoStream(), rej, Perspective::IS_CLIENT); EXPECT_FALSE(session_->IsEncryptionEstablished()); EXPECT_EQ(ENCRYPTION_INITIAL, QuicPacketCreatorPeer::GetEncryptionLevel( QuicConnectionPeer::GetPacketCreator(connection_))); EXPECT_TRUE(session_->CreateOutgoingBidirectionalStream() == nullptr); char data[] = "hello world"; QuicConsumedData consumed = session_->WritevData(stream->id(), ABSL_ARRAYSIZE(data), 0, NO_FIN, NOT_RETRANSMISSION, ENCRYPTION_INITIAL); EXPECT_EQ(0u, consumed.bytes_consumed); EXPECT_FALSE(consumed.fin_consumed); } TEST_P(QuicSpdyClientSessionTest, MaxNumStreamsWithNoFinOrRst) { uint32_t kServerMaxIncomingStreams = 1; CompleteCryptoHandshake(kServerMaxIncomingStreams); QuicSpdyClientStream* stream = session_->CreateOutgoingBidirectionalStream(); ASSERT_TRUE(stream); EXPECT_FALSE(session_->CreateOutgoingBidirectionalStream()); session_->ResetStream(stream->id(), QUIC_STREAM_CANCELLED); EXPECT_EQ(1u, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); stream = session_->CreateOutgoingBidirectionalStream(); EXPECT_FALSE(stream); } TEST_P(QuicSpdyClientSessionTest, MaxNumStreamsWithRst) { uint32_t kServerMaxIncomingStreams = 1; CompleteCryptoHandshake(kServerMaxIncomingStreams); QuicSpdyClientStream* stream = session_->CreateOutgoingBidirectionalStream(); ASSERT_NE(nullptr, stream); EXPECT_EQ(nullptr, session_->CreateOutgoingBidirectionalStream()); session_->ResetStream(stream->id(), QUIC_STREAM_CANCELLED); session_->OnRstStream(QuicRstStreamFrame(kInvalidControlFrameId, stream->id(), QUIC_RST_ACKNOWLEDGEMENT, 0)); EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); if (VersionHasIetfQuicFrames(GetParam().transport_version)) { QuicMaxStreamsFrame frame(0, 2, false); session_->OnMaxStreamsFrame(frame); } stream = session_->CreateOutgoingBidirectionalStream(); EXPECT_NE(nullptr, stream); if (VersionHasIetfQuicFrames(GetParam().transport_version)) { QuicStreamCount expected_stream_count = 2; EXPECT_EQ(expected_stream_count, QuicSessionPeer::ietf_bidirectional_stream_id_manager(&*session_) ->outgoing_stream_count()); } } TEST_P(QuicSpdyClientSessionTest, ResetAndTrailers) { uint32_t kServerMaxIncomingStreams = 1; CompleteCryptoHandshake(kServerMaxIncomingStreams); QuicSpdyClientStream* stream = session_->CreateOutgoingBidirectionalStream(); ASSERT_NE(nullptr, stream); if (VersionHasIetfQuicFrames(GetParam().transport_version)) { EXPECT_CALL(*connection_, SendControlFrame(_)) .WillOnce(Invoke( this, &QuicSpdyClientSessionTest::ClearStreamsBlockedControlFrame)); } EXPECT_EQ(nullptr, session_->CreateOutgoingBidirectionalStream()); QuicStreamId stream_id = stream->id(); EXPECT_CALL(*connection_, SendControlFrame(_)) .Times(AtLeast(1)) .WillRepeatedly(Invoke(&ClearControlFrame)); EXPECT_CALL(*connection_, OnStreamReset(_, _)).Times(1); session_->ResetStream(stream_id, QUIC_STREAM_PEER_GOING_AWAY); EXPECT_EQ(1u, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); stream = session_->CreateOutgoingBidirectionalStream(); EXPECT_EQ(nullptr, stream); QuicHeaderList trailers; trailers.OnHeaderBlockStart(); trailers.OnHeader(kFinalOffsetHeaderKey, "0"); trailers.OnHeaderBlockEnd(0, 0); session_->OnStreamHeaderList(stream_id, false, 0, trailers); EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); if (VersionHasIetfQuicFrames(GetParam().transport_version)) { QuicMaxStreamsFrame frame(0, 2, false); session_->OnMaxStreamsFrame(frame); } stream = session_->CreateOutgoingBidirectionalStream(); EXPECT_NE(nullptr, stream); if (VersionHasIetfQuicFrames(GetParam().transport_version)) { QuicStreamCount expected_stream_count = 2; EXPECT_EQ(expected_stream_count, QuicSessionPeer::ietf_bidirectional_stream_id_manager(&*session_) ->outgoing_stream_count()); } } TEST_P(QuicSpdyClientSessionTest, ReceivedMalformedTrailersAfterSendingRst) { CompleteCryptoHandshake(); QuicSpdyClientStream* stream = session_->CreateOutgoingBidirectionalStream(); ASSERT_NE(nullptr, stream); QuicStreamId stream_id = stream->id(); EXPECT_CALL(*connection_, SendControlFrame(_)) .Times(AtLeast(1)) .WillRepeatedly(Invoke(&ClearControlFrame)); EXPECT_CALL(*connection_, OnStreamReset(_, _)).Times(1); session_->ResetStream(stream_id, QUIC_STREAM_PEER_GOING_AWAY); QuicHeaderList trailers; trailers.OnHeaderBlockStart(); trailers.OnHeader(kFinalOffsetHeaderKey, "invalid non-numeric value"); trailers.OnHeaderBlockEnd(0, 0); EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(1); session_->OnStreamHeaderList(stream_id, false, 0, trailers); } TEST_P(QuicSpdyClientSessionTest, OnStreamHeaderListWithStaticStream) { CompleteCryptoHandshake(); QuicHeaderList trailers; trailers.OnHeaderBlockStart(); trailers.OnHeader(kFinalOffsetHeaderKey, "0"); trailers.OnHeaderBlockEnd(0, 0); QuicStreamId id; if (VersionUsesHttp3(connection_->transport_version())) { id = GetNthServerInitiatedUnidirectionalStreamId( connection_->transport_version(), 3); char type[] = {0x00}; QuicStreamFrame data1(id, false, 0, absl::string_view(type, 1)); session_->OnStreamFrame(data1); } else { id = QuicUtils::GetHeadersStreamId(connection_->transport_version()); } EXPECT_CALL(*connection_, CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA, "stream is static", _)) .Times(1); session_->OnStreamHeaderList(id, false, 0, trailers); } TEST_P(QuicSpdyClientSessionTest, GoAwayReceived) { if (VersionHasIetfQuicFrames(connection_->transport_version())) { return; } CompleteCryptoHandshake(); session_->connection()->OnGoAwayFrame(QuicGoAwayFrame( kInvalidControlFrameId, QUIC_PEER_GOING_AWAY, 1u, "Going away.")); EXPECT_EQ(nullptr, session_->CreateOutgoingBidirectionalStream()); } static bool CheckForDecryptionError(QuicFramer* framer) { return framer->error() == QUIC_DECRYPTION_FAILURE; } TEST_P(QuicSpdyClientSessionTest, InvalidPacketReceived) { QuicSocketAddress server_address(TestPeerIPAddress(), kTestPort); QuicSocketAddress client_address(TestPeerIPAddress(), kTestPort); EXPECT_CALL(*connection_, ProcessUdpPacket(server_address, client_address, _)) .WillRepeatedly(Invoke(static_cast<MockQuicConnection*>(connection_), &MockQuicConnection::ReallyProcessUdpPacket)); EXPECT_CALL(*connection_, OnCanWrite()).Times(AnyNumber()); EXPECT_CALL(*connection_, OnError(_)).Times(1); QuicReceivedPacket zero_length_packet(nullptr, 0, QuicTime::Zero(), false); EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); session_->ProcessUdpPacket(client_address, server_address, zero_length_packet); char buf[2] = {0x00, 0x01}; QuicConnectionId connection_id = session_->connection()->connection_id(); QuicReceivedPacket valid_packet(buf, 2, QuicTime::Zero(), false); EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); EXPECT_CALL(*connection_, OnError(_)).Times(AtMost(1)); session_->ProcessUdpPacket(client_address, server_address, valid_packet); QuicFramerPeer::SetLastSerializedServerConnectionId( QuicConnectionPeer::GetFramer(connection_), connection_id); ParsedQuicVersionVector versions = SupportedVersions(GetParam()); QuicConnectionId destination_connection_id = EmptyQuicConnectionId(); QuicConnectionId source_connection_id = connection_id; std::unique_ptr<QuicEncryptedPacket> packet(ConstructEncryptedPacket( destination_connection_id, source_connection_id, false, false, 100, "data", true, CONNECTION_ID_ABSENT, CONNECTION_ID_ABSENT, PACKET_4BYTE_PACKET_NUMBER, &versions, Perspective::IS_SERVER)); std::unique_ptr<QuicReceivedPacket> received( ConstructReceivedPacket(*packet, QuicTime::Zero())); *(const_cast<char*>(received->data() + received->length() - 1)) += 1; EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); EXPECT_CALL(*connection_, OnError(Truly(CheckForDecryptionError))).Times(1); session_->ProcessUdpPacket(client_address, server_address, *received); } TEST_P(QuicSpdyClientSessionTest, InvalidFramedPacketReceived) { const ParsedQuicVersion version = GetParam(); QuicSocketAddress server_address(TestPeerIPAddress(), kTestPort); QuicSocketAddress client_address(TestPeerIPAddress(), kTestPort); if (version.KnowsWhichDecrypterToUse()) { connection_->InstallDecrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE)); } else { connection_->SetAlternativeDecrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE), false); } EXPECT_CALL(*connection_, ProcessUdpPacket(server_address, client_address, _)) .WillRepeatedly(Invoke(static_cast<MockQuicConnection*>(connection_), &MockQuicConnection::ReallyProcessUdpPacket)); EXPECT_CALL(*connection_, OnError(_)).Times(1); QuicConnectionId destination_connection_id = session_->connection()->connection_id(); QuicConnectionId source_connection_id = destination_connection_id; QuicFramerPeer::SetLastSerializedServerConnectionId( QuicConnectionPeer::GetFramer(connection_), destination_connection_id); bool version_flag = true; QuicConnectionIdIncluded scid_included = CONNECTION_ID_PRESENT; std::unique_ptr<QuicEncryptedPacket> packet(ConstructMisFramedEncryptedPacket( destination_connection_id, source_connection_id, version_flag, false, 100, "data", CONNECTION_ID_ABSENT, scid_included, PACKET_4BYTE_PACKET_NUMBER, version, Perspective::IS_SERVER)); std::unique_ptr<QuicReceivedPacket> received( ConstructReceivedPacket(*packet, QuicTime::Zero())); EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(1); session_->ProcessUdpPacket(client_address, server_address, *received); } TEST_P(QuicSpdyClientSessionTest, TryToCreateServerInitiatedBidirectionalStream) { if (VersionHasIetfQuicFrames(connection_->transport_version())) { EXPECT_CALL( *connection_, CloseConnection(QUIC_HTTP_SERVER_INITIATED_BIDIRECTIONAL_STREAM, _, _)); } else { EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); } session_->GetOrCreateStream(GetNthServerInitiatedBidirectionalStreamId( connection_->transport_version(), 0)); } TEST_P(QuicSpdyClientSessionTest, OnSettingsFrame) { if (!VersionUsesHttp3(session_->transport_version())) { return; } CompleteCryptoHandshake(); SettingsFrame settings; settings.values[SETTINGS_QPACK_MAX_TABLE_CAPACITY] = 2; settings.values[SETTINGS_MAX_FIELD_SECTION_SIZE] = 5; settings.values[256] = 4; char application_state[] = { 0x04, 0x07, 0x01, 0x02, 0x06, 0x05, 0x40 + 0x01, 0x00, 0x04}; ApplicationState expected(std::begin(application_state), std::end(application_state)); session_->OnSettingsFrame(settings); EXPECT_EQ(expected, *client_session_cache_ ->Lookup(QuicServerId(kServerHostname, kPort, false), session_->GetClock()->WallNow(), nullptr) ->application_state); } TEST_P(QuicSpdyClientSessionTest, IetfZeroRttSetup) { if (session_->version().UsesQuicCrypto()) { return; } CompleteFirstConnection(); CreateConnection(); if (session_->version().UsesHttp3()) { EXPECT_EQ(0u, session_->flow_controller()->send_window_offset()); EXPECT_EQ(std::numeric_limits<size_t>::max(), session_->max_outbound_header_list_size()); } else { EXPECT_EQ(kMinimumFlowControlSendWindow, session_->flow_controller()->send_window_offset()); } session_->CryptoConnect(); EXPECT_TRUE(session_->IsEncryptionEstablished()); EXPECT_EQ(ENCRYPTION_ZERO_RTT, session_->connection()->encryption_level()); EXPECT_EQ(kInitialSessionFlowControlWindowForTest, session_->flow_controller()->send_window_offset()); if (session_->version().UsesHttp3()) { auto* id_manager = QuicSessionPeer::ietf_streamid_manager(session_.get()); EXPECT_EQ(kDefaultMaxStreamsPerConnection, id_manager->max_outgoing_bidirectional_streams()); EXPECT_EQ( kDefaultMaxStreamsPerConnection + kHttp3StaticUnidirectionalStreamCount, id_manager->max_outgoing_unidirectional_streams()); auto* control_stream = QuicSpdySessionPeer::GetSendControlStream(session_.get()); EXPECT_EQ(kInitialStreamFlowControlWindowForTest, QuicStreamPeer::SendWindowOffset(control_stream)); EXPECT_EQ(5u, session_->max_outbound_header_list_size()); } else { auto* id_manager = QuicSessionPeer::GetStreamIdManager(session_.get()); EXPECT_EQ(kDefaultMaxStreamsPerConnection, id_manager->max_open_outgoing_streams()); } QuicConfig config = DefaultQuicConfig(); config.SetInitialMaxStreamDataBytesUnidirectionalToSend( kInitialStreamFlowControlWindowForTest + 1); config.SetInitialSessionFlowControlWindowToSend( kInitialSessionFlowControlWindowForTest + 1); config.SetMaxBidirectionalStreamsToSend(kDefaultMaxStreamsPerConnection + 1); config.SetMaxUnidirectionalStreamsToSend(kDefaultMaxStreamsPerConnection + 1); crypto_test_utils::HandshakeWithFakeServer( &config, server_crypto_config_.get(), &helper_, &alarm_factory_, connection_, crypto_stream_, AlpnForVersion(connection_->version())); EXPECT_TRUE(session_->GetCryptoStream()->IsResumption()); EXPECT_EQ(kInitialSessionFlowControlWindowForTest + 1, session_->flow_controller()->send_window_offset()); if (session_->version().UsesHttp3()) { auto* id_manager = QuicSessionPeer::ietf_streamid_manager(session_.get()); auto* control_stream = QuicSpdySessionPeer::GetSendControlStream(session_.get()); EXPECT_EQ(kDefaultMaxStreamsPerConnection + 1, id_manager->max_outgoing_bidirectional_streams()); EXPECT_EQ(kDefaultMaxStreamsPerConnection + kHttp3StaticUnidirectionalStreamCount + 1, id_manager->max_outgoing_unidirectional_streams()); EXPECT_EQ(kInitialStreamFlowControlWindowForTest + 1, QuicStreamPeer::SendWindowOffset(control_stream)); } else { auto* id_manager = QuicSessionPeer::GetStreamIdManager(session_.get()); EXPECT_EQ(kDefaultMaxStreamsPerConnection + 1, id_manager->max_open_outgoing_streams()); } EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); if (session_->version().UsesHttp3()) { SettingsFrame settings; settings.values[SETTINGS_QPACK_MAX_TABLE_CAPACITY] = 2; settings.values[SETTINGS_MAX_FIELD_SECTION_SIZE] = 5; settings.values[256] = 4; session_->OnSettingsFrame(settings); } } TEST_P(QuicSpdyClientSessionTest, RetransmitDataOnZeroRttReject) { if (session_->version().UsesQuicCrypto()) { return; } CompleteFirstConnection(); CreateConnection(); ON_CALL(*connection_, OnCanWrite()) .WillByDefault( testing::Invoke(connection_, &MockQuicConnection::ReallyOnCanWrite)); EXPECT_CALL(*connection_, OnCanWrite()).Times(0); QuicConfig config = DefaultQuicConfig(); config.SetMaxUnidirectionalStreamsToSend(kDefaultMaxStreamsPerConnection); config.SetMaxBidirectionalStreamsToSend(kDefaultMaxStreamsPerConnection); SSL_CTX_set_early_data_enabled(server_crypto_config_->ssl_ctx(), false); EXPECT_CALL(*connection_, OnPacketSent(ENCRYPTION_INITIAL, NOT_RETRANSMISSION)); EXPECT_CALL(*connection_, OnPacketSent(ENCRYPTION_ZERO_RTT, NOT_RETRANSMISSION)) .Times(session_->version().UsesHttp3() ? 2 : 1); session_->CryptoConnect(); EXPECT_TRUE(session_->IsEncryptionEstablished()); EXPECT_EQ(ENCRYPTION_ZERO_RTT, session_->connection()->encryption_level()); QuicSpdyClientStream* stream = session_->CreateOutgoingBidirectionalStream(); ASSERT_TRUE(stream); stream->WriteOrBufferData("hello", true, nullptr); EXPECT_CALL(*connection_, OnPacketSent(ENCRYPTION_HANDSHAKE, NOT_RETRANSMISSION)); EXPECT_CALL(*connection_, OnPacketSent(ENCRYPTION_FORWARD_SECURE, LOSS_RETRANSMISSION)); crypto_test_utils::HandshakeWithFakeServer( &config, server_crypto_config_.get(), &helper_, &alarm_factory_, connection_, crypto_stream_, AlpnForVersion(connection_->version())); EXPECT_TRUE(session_->GetCryptoStream()->IsResumption()); } TEST_P(QuicSpdyClientSessionTest, ZeroRttRejectReducesStreamLimitTooMuch) { if (session_->version().UsesQuicCrypto()) { return; } CompleteFirstConnection(); CreateConnection(); QuicConfig config = DefaultQuicConfig(); config.SetMaxBidirectionalStreamsToSend(0); SSL_CTX_set_early_data_enabled(server_crypto_config_->ssl_ctx(), false); session_->CryptoConnect(); EXPECT_TRUE(session_->IsEncryptionEstablished()); QuicSpdyClientStream* stream = session_->CreateOutgoingBidirectionalStream(); ASSERT_TRUE(stream); if (session_->version().UsesHttp3()) { EXPECT_CALL( *connection_, CloseConnection( QUIC_ZERO_RTT_UNRETRANSMITTABLE, "Server rejected 0-RTT, aborting because new bidirectional initial " "stream limit 0 is less than current open streams: 1", _)) .WillOnce(testing::Invoke(connection_, &MockQuicConnection::ReallyCloseConnection)); } els
320
cpp
google/quiche
quic_server_session_base
quiche/quic/core/http/quic_server_session_base.cc
quiche/quic/core/http/quic_server_session_base_test.cc
#ifndef QUICHE_QUIC_CORE_HTTP_QUIC_SERVER_SESSION_BASE_H_ #define QUICHE_QUIC_CORE_HTTP_QUIC_SERVER_SESSION_BASE_H_ #include <cstdint> #include <memory> #include <set> #include <string> #include <vector> #include "quiche/quic/core/crypto/quic_compressed_certs_cache.h" #include "quiche/quic/core/http/quic_spdy_session.h" #include "quiche/quic/core/quic_crypto_server_stream_base.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QuicConfig; class QuicConnection; class QuicCryptoServerConfig; namespace test { class QuicServerSessionBasePeer; class QuicSimpleServerSessionPeer; } class QUICHE_EXPORT QuicServerSessionBase : public QuicSpdySession { public: QuicServerSessionBase(const QuicConfig& config, const ParsedQuicVersionVector& supported_versions, QuicConnection* connection, QuicSession::Visitor* visitor, QuicCryptoServerStreamBase::Helper* helper, const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache); QuicServerSessionBase(const QuicServerSessionBase&) = delete; QuicServerSessionBase& operator=(const QuicServerSessionBase&) = delete; void OnConnectionClosed(const QuicConnectionCloseFrame& frame, ConnectionCloseSource source) override; void OnCongestionWindowChange(QuicTime now) override; ~QuicServerSessionBase() override; void Initialize() override; const QuicCryptoServerStreamBase* crypto_stream() const { return crypto_stream_.get(); } void OnConfigNegotiated() override; void set_serving_region(const std::string& serving_region) { serving_region_ = serving_region; } const std::string& serving_region() const { return serving_region_; } QuicSSLConfig GetSSLConfig() const override; protected: QuicCryptoServerStreamBase* GetMutableCryptoStream() override; const QuicCryptoServerStreamBase* GetCryptoStream() const override; std::optional<CachedNetworkParameters> GenerateCachedNetworkParameters() const override; bool ShouldCreateOutgoingBidirectionalStream() override; bool ShouldCreateOutgoingUnidirectionalStream() override; bool ShouldCreateIncomingStream(QuicStreamId id) override; virtual std::unique_ptr<QuicCryptoServerStreamBase> CreateQuicCryptoServerStream( const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache) = 0; const QuicCryptoServerConfig* crypto_config() { return crypto_config_; } QuicCryptoServerStreamBase::Helper* stream_helper() { return helper_; } private: friend class test::QuicServerSessionBasePeer; friend class test::QuicSimpleServerSessionPeer; void SendSettingsToCryptoStream(); const QuicCryptoServerConfig* crypto_config_; QuicCompressedCertsCache* compressed_certs_cache_; std::unique_ptr<QuicCryptoServerStreamBase> crypto_stream_; QuicCryptoServerStreamBase::Helper* helper_; bool bandwidth_resumption_enabled_; QuicBandwidth bandwidth_estimate_sent_to_client_; std::string serving_region_; QuicTime last_scup_time_; QuicPacketNumber last_scup_packet_number_; int32_t BandwidthToCachedParameterBytesPerSecond( const QuicBandwidth& bandwidth) const; }; } #endif #include "quiche/quic/core/http/quic_server_session_base.h" #include <algorithm> #include <cstdlib> #include <limits> #include <memory> #include <optional> #include <string> #include <utility> #include "quiche/quic/core/proto/cached_network_parameters_proto.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_stream.h" #include "quiche/quic/core/quic_tag.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quic { QuicServerSessionBase::QuicServerSessionBase( const QuicConfig& config, const ParsedQuicVersionVector& supported_versions, QuicConnection* connection, Visitor* visitor, QuicCryptoServerStreamBase::Helper* helper, const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache) : QuicSpdySession(connection, visitor, config, supported_versions), crypto_config_(crypto_config), compressed_certs_cache_(compressed_certs_cache), helper_(helper), bandwidth_resumption_enabled_(false), bandwidth_estimate_sent_to_client_(QuicBandwidth::Zero()), last_scup_time_(QuicTime::Zero()) {} QuicServerSessionBase::~QuicServerSessionBase() {} void QuicServerSessionBase::Initialize() { crypto_stream_ = CreateQuicCryptoServerStream(crypto_config_, compressed_certs_cache_); QuicSpdySession::Initialize(); SendSettingsToCryptoStream(); } void QuicServerSessionBase::OnConfigNegotiated() { QuicSpdySession::OnConfigNegotiated(); const CachedNetworkParameters* cached_network_params = crypto_stream_->PreviousCachedNetworkParams(); if (version().UsesTls() && cached_network_params != nullptr) { if (cached_network_params->serving_region() == serving_region_) { QUIC_CODE_COUNT(quic_server_received_network_params_at_same_region); if (config()->HasReceivedConnectionOptions() && ContainsQuicTag(config()->ReceivedConnectionOptions(), kTRTT)) { QUIC_DLOG(INFO) << "Server: Setting initial rtt to " << cached_network_params->min_rtt_ms() << "ms which is received from a validated address token"; connection()->sent_packet_manager().SetInitialRtt( QuicTime::Delta::FromMilliseconds( cached_network_params->min_rtt_ms()), true); } } else { QUIC_CODE_COUNT(quic_server_received_network_params_at_different_region); } } if (!config()->HasReceivedConnectionOptions()) { return; } if (GetQuicReloadableFlag(quic_enable_disable_resumption) && version().UsesTls() && ContainsQuicTag(config()->ReceivedConnectionOptions(), kNRES) && crypto_stream_->ResumptionAttempted()) { QUIC_RELOADABLE_FLAG_COUNT(quic_enable_disable_resumption); const bool disabled = crypto_stream_->DisableResumption(); QUIC_BUG_IF(quic_failed_to_disable_resumption, !disabled) << "Failed to disable resumption"; } const bool last_bandwidth_resumption = ContainsQuicTag(config()->ReceivedConnectionOptions(), kBWRE); const bool max_bandwidth_resumption = ContainsQuicTag(config()->ReceivedConnectionOptions(), kBWMX); bandwidth_resumption_enabled_ = last_bandwidth_resumption || max_bandwidth_resumption; if (cached_network_params != nullptr && cached_network_params->serving_region() == serving_region_) { if (!version().UsesTls()) { connection()->OnReceiveConnectionState(*cached_network_params); } if (bandwidth_resumption_enabled_) { const uint64_t seconds_since_estimate = connection()->clock()->WallNow().ToUNIXSeconds() - cached_network_params->timestamp(); if (seconds_since_estimate <= kNumSecondsPerHour) { connection()->ResumeConnectionState(*cached_network_params, max_bandwidth_resumption); } } } } void QuicServerSessionBase::OnConnectionClosed( const QuicConnectionCloseFrame& frame, ConnectionCloseSource source) { QuicSession::OnConnectionClosed(frame, source); if (crypto_stream_ != nullptr) { crypto_stream_->CancelOutstandingCallbacks(); } } void QuicServerSessionBase::OnCongestionWindowChange(QuicTime now) { if (!bandwidth_resumption_enabled_) { return; } if (HasDataToWrite()) { return; } const QuicSentPacketManager& sent_packet_manager = connection()->sent_packet_manager(); int64_t srtt_ms = sent_packet_manager.GetRttStats()->smoothed_rtt().ToMilliseconds(); int64_t now_ms = (now - last_scup_time_).ToMilliseconds(); int64_t packets_since_last_scup = 0; const QuicPacketNumber largest_sent_packet = connection()->sent_packet_manager().GetLargestSentPacket(); if (largest_sent_packet.IsInitialized()) { packets_since_last_scup = last_scup_packet_number_.IsInitialized() ? largest_sent_packet - last_scup_packet_number_ : largest_sent_packet.ToUint64(); } if (now_ms < (kMinIntervalBetweenServerConfigUpdatesRTTs * srtt_ms) || now_ms < kMinIntervalBetweenServerConfigUpdatesMs || packets_since_last_scup < kMinPacketsBetweenServerConfigUpdates) { return; } const QuicSustainedBandwidthRecorder* bandwidth_recorder = sent_packet_manager.SustainedBandwidthRecorder(); if (bandwidth_recorder == nullptr || !bandwidth_recorder->HasEstimate()) { return; } QuicBandwidth new_bandwidth_estimate = bandwidth_recorder->BandwidthEstimate(); int64_t bandwidth_delta = std::abs(new_bandwidth_estimate.ToBitsPerSecond() - bandwidth_estimate_sent_to_client_.ToBitsPerSecond()); bool substantial_difference = bandwidth_delta > 0.5 * bandwidth_estimate_sent_to_client_.ToBitsPerSecond(); if (!substantial_difference) { return; } if (version().UsesTls()) { if (version().HasIetfQuicFrames() && MaybeSendAddressToken()) { bandwidth_estimate_sent_to_client_ = new_bandwidth_estimate; } } else { std::optional<CachedNetworkParameters> cached_network_params = GenerateCachedNetworkParameters(); if (cached_network_params.has_value()) { bandwidth_estimate_sent_to_client_ = new_bandwidth_estimate; QUIC_DVLOG(1) << "Server: sending new bandwidth estimate (KBytes/s): " << bandwidth_estimate_sent_to_client_.ToKBytesPerSecond(); QUICHE_DCHECK_EQ( BandwidthToCachedParameterBytesPerSecond( bandwidth_estimate_sent_to_client_), cached_network_params->bandwidth_estimate_bytes_per_second()); crypto_stream_->SendServerConfigUpdate(&*cached_network_params); connection()->OnSendConnectionState(*cached_network_params); } } last_scup_time_ = now; last_scup_packet_number_ = connection()->sent_packet_manager().GetLargestSentPacket(); } bool QuicServerSessionBase::ShouldCreateIncomingStream(QuicStreamId id) { if (!connection()->connected()) { QUIC_BUG(quic_bug_10393_2) << "ShouldCreateIncomingStream called when disconnected"; return false; } if (QuicUtils::IsServerInitiatedStreamId(transport_version(), id)) { QUIC_BUG(quic_bug_10393_3) << "ShouldCreateIncomingStream called with server initiated " "stream ID."; return false; } return true; } bool QuicServerSessionBase::ShouldCreateOutgoingBidirectionalStream() { if (!connection()->connected()) { QUIC_BUG(quic_bug_12513_2) << "ShouldCreateOutgoingBidirectionalStream called when disconnected"; return false; } if (!crypto_stream_->encryption_established()) { QUIC_BUG(quic_bug_10393_4) << "Encryption not established so no outgoing stream created."; return false; } return CanOpenNextOutgoingBidirectionalStream(); } bool QuicServerSessionBase::ShouldCreateOutgoingUnidirectionalStream() { if (!connection()->connected()) { QUIC_BUG(quic_bug_12513_3) << "ShouldCreateOutgoingUnidirectionalStream called when disconnected"; return false; } if (!crypto_stream_->encryption_established()) { QUIC_BUG(quic_bug_10393_5) << "Encryption not established so no outgoing stream created."; return false; } return CanOpenNextOutgoingUnidirectionalStream(); } QuicCryptoServerStreamBase* QuicServerSessionBase::GetMutableCryptoStream() { return crypto_stream_.get(); } const QuicCryptoServerStreamBase* QuicServerSessionBase::GetCryptoStream() const { return crypto_stream_.get(); } int32_t QuicServerSessionBase::BandwidthToCachedParameterBytesPerSecond( const QuicBandwidth& bandwidth) const { return static_cast<int32_t>(std::min<int64_t>( bandwidth.ToBytesPerSecond(), std::numeric_limits<int32_t>::max())); } void QuicServerSessionBase::SendSettingsToCryptoStream() { if (!version().UsesTls()) { return; } std::string settings_frame = HttpEncoder::SerializeSettingsFrame(settings()); std::unique_ptr<ApplicationState> serialized_settings = std::make_unique<ApplicationState>( settings_frame.data(), settings_frame.data() + settings_frame.length()); GetMutableCryptoStream()->SetServerApplicationStateForResumption( std::move(serialized_settings)); } QuicSSLConfig QuicServerSessionBase::GetSSLConfig() const { QUICHE_DCHECK(crypto_config_ && crypto_config_->proof_source()); QuicSSLConfig ssl_config = crypto_config_->ssl_config(); ssl_config.disable_ticket_support = GetQuicFlag(quic_disable_server_tls_resumption); if (!crypto_config_ || !crypto_config_->proof_source()) { return ssl_config; } absl::InlinedVector<uint16_t, 8> signature_algorithms = crypto_config_->proof_source()->SupportedTlsSignatureAlgorithms(); if (!signature_algorithms.empty()) { ssl_config.signing_algorithm_prefs = std::move(signature_algorithms); } return ssl_config; } std::optional<CachedNetworkParameters> QuicServerSessionBase::GenerateCachedNetworkParameters() const { const QuicSentPacketManager& sent_packet_manager = connection()->sent_packet_manager(); const QuicSustainedBandwidthRecorder* bandwidth_recorder = sent_packet_manager.SustainedBandwidthRecorder(); CachedNetworkParameters cached_network_params; cached_network_params.set_timestamp( connection()->clock()->WallNow().ToUNIXSeconds()); if (!sent_packet_manager.GetRttStats()->min_rtt().IsZero()) { cached_network_params.set_min_rtt_ms( sent_packet_manager.GetRttStats()->min_rtt().ToMilliseconds()); } if (bandwidth_recorder != nullptr && bandwidth_recorder->HasEstimate()) { const int32_t bw_estimate_bytes_per_second = BandwidthToCachedParameterBytesPerSecond( bandwidth_recorder->BandwidthEstimate()); const int32_t max_bw_estimate_bytes_per_second = BandwidthToCachedParameterBytesPerSecond( bandwidth_recorder->MaxBandwidthEstimate()); QUIC_BUG_IF(quic_bug_12513_1, max_bw_estimate_bytes_per_second < 0) << max_bw_estimate_bytes_per_second; QUIC_BUG_IF(quic_bug_10393_1, bw_estimate_bytes_per_second < 0) << bw_estimate_bytes_per_second; cached_network_params.set_bandwidth_estimate_bytes_per_second( bw_estimate_bytes_per_second); cached_network_params.set_max_bandwidth_estimate_bytes_per_second( max_bw_estimate_bytes_per_second); cached_network_params.set_max_bandwidth_timestamp_seconds( bandwidth_recorder->MaxBandwidthTimestamp()); cached_network_params.set_previous_connection_state( bandwidth_recorder->EstimateRecordedDuringSlowStart() ? CachedNetworkParameters::SLOW_START : CachedNetworkParameters::CONGESTION_AVOIDANCE); } if (!serving_region_.empty()) { cached_network_params.set_serving_region(serving_region_); } return cached_network_params; } }
#include "quiche/quic/core/http/quic_server_session_base.h" #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/memory/memory.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/crypto/quic_crypto_server_config.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/proto/cached_network_parameters_proto.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_crypto_server_stream.h" #include "quiche/quic/core/quic_crypto_server_stream_base.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/tls_server_handshaker.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/crypto_test_utils.h" #include "quiche/quic/test_tools/fake_proof_source.h" #include "quiche/quic/test_tools/mock_quic_session_visitor.h" #include "quiche/quic/test_tools/quic_config_peer.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_crypto_server_config_peer.h" #include "quiche/quic/test_tools/quic_sent_packet_manager_peer.h" #include "quiche/quic/test_tools/quic_server_session_base_peer.h" #include "quiche/quic/test_tools/quic_session_peer.h" #include "quiche/quic/test_tools/quic_spdy_session_peer.h" #include "quiche/quic/test_tools/quic_stream_id_manager_peer.h" #include "quiche/quic/test_tools/quic_stream_peer.h" #include "quiche/quic/test_tools/quic_sustained_bandwidth_recorder_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/tools/quic_memory_cache_backend.h" #include "quiche/quic/tools/quic_simple_server_stream.h" using testing::_; using testing::StrictMock; using testing::AtLeast; namespace quic { namespace test { namespace { const char* const kStreamData = "\1z"; class TestServerSession : public QuicServerSessionBase { public: TestServerSession(const QuicConfig& config, QuicConnection* connection, QuicSession::Visitor* visitor, QuicCryptoServerStreamBase::Helper* helper, const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache, QuicSimpleServerBackend* quic_simple_server_backend) : QuicServerSessionBase(config, CurrentSupportedVersions(), connection, visitor, helper, crypto_config, compressed_certs_cache), quic_simple_server_backend_(quic_simple_server_backend) { set_max_streams_accepted_per_loop(4u); } ~TestServerSession() override { DeleteConnection(); } MOCK_METHOD(bool, WriteControlFrame, (const QuicFrame& frame, TransmissionType type), (override)); using QuicServerSessionBase::pending_streams_size; protected: QuicSpdyStream* CreateIncomingStream(QuicStreamId id) override { if (!ShouldCreateIncomingStream(id)) { return nullptr; } QuicSpdyStream* stream = new QuicSimpleServerStream( id, this, BIDIRECTIONAL, quic_simple_server_backend_); ActivateStream(absl::WrapUnique(stream)); return stream; } QuicSpdyStream* CreateIncomingStream(PendingStream* pending) override { QuicSpdyStream* stream = new QuicSimpleServerStream(pending, this, quic_simple_server_backend_); ActivateStream(absl::WrapUnique(stream)); return stream; } QuicSpdyStream* CreateOutgoingBidirectionalStream() override { QUICHE_DCHECK(false); return nullptr; } QuicSpdyStream* CreateOutgoingUnidirectionalStream() override { if (!ShouldCreateOutgoingUnidirectionalStream()) { return nullptr; } QuicSpdyStream* stream = new QuicSimpleServerStream( GetNextOutgoingUnidirectionalStreamId(), this, WRITE_UNIDIRECTIONAL, quic_simple_server_backend_); ActivateStream(absl::WrapUnique(stream)); return stream; } std::unique_ptr<QuicCryptoServerStreamBase> CreateQuicCryptoServerStream( const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache) override { return CreateCryptoServerStream(crypto_config, compressed_certs_cache, this, stream_helper()); } QuicStream* ProcessBidirectionalPendingStream( PendingStream* pending) override { return CreateIncomingStream(pending); } private: QuicSimpleServerBackend* quic_simple_server_backend_; }; const size_t kMaxStreamsForTest = 10; class QuicServerSessionBaseTest : public QuicTestWithParam<ParsedQuicVersion> { protected: QuicServerSessionBaseTest() : QuicServerSessionBaseTest(crypto_test_utils::ProofSourceForTesting()) {} explicit QuicServerSessionBaseTest(std::unique_ptr<ProofSource> proof_source) : crypto_config_(QuicCryptoServerConfig::TESTING, QuicRandom::GetInstance(), std::move(proof_source), KeyExchangeSource::Default()), compressed_certs_cache_( QuicCompressedCertsCache::kQuicCompressedCertsCacheSize) { config_.SetMaxBidirectionalStreamsToSend(kMaxStreamsForTest); config_.SetMaxUnidirectionalStreamsToSend(kMaxStreamsForTest); QuicConfigPeer::SetReceivedMaxBidirectionalStreams(&config_, kMaxStreamsForTest); QuicConfigPeer::SetReceivedMaxUnidirectionalStreams(&config_, kMaxStreamsForTest); config_.SetInitialStreamFlowControlWindowToSend( kInitialStreamFlowControlWindowForTest); config_.SetInitialSessionFlowControlWindowToSend( kInitialSessionFlowControlWindowForTest); ParsedQuicVersionVector supported_versions = SupportedVersions(version()); connection_ = new StrictMock<MockQuicConnection>( &helper_, &alarm_factory_, Perspective::IS_SERVER, supported_versions); connection_->AdvanceTime(QuicTime::Delta::FromSeconds(1)); connection_->SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(connection_->perspective())); session_ = std::make_unique<TestServerSession>( config_, connection_, &owner_, &stream_helper_, &crypto_config_, &compressed_certs_cache_, &memory_cache_backend_); MockClock clock; handshake_message_ = crypto_config_.AddDefaultConfig( QuicRandom::GetInstance(), &clock, QuicCryptoServerConfig::ConfigOptions()); session_->Initialize(); QuicConfigPeer::SetReceivedInitialSessionFlowControlWindow( session_->config(), kMinimumFlowControlSendWindow); session_->OnConfigNegotiated(); if (version().SupportsAntiAmplificationLimit()) { QuicConnectionPeer::SetAddressValidated(connection_); } } QuicStreamId GetNthClientInitiatedBidirectionalId(int n) { return GetNthClientInitiatedBidirectionalStreamId(transport_version(), n); } QuicStreamId GetNthServerInitiatedUnidirectionalId(int n) { return quic::test::GetNthServerInitiatedUnidirectionalStreamId( transport_version(), n); } ParsedQuicVersion version() const { return GetParam(); } QuicTransportVersion transport_version() const { return version().transport_version; } void InjectStopSendingFrame(QuicStreamId stream_id) { if (!VersionHasIetfQuicFrames(transport_version())) { return; } QuicStopSendingFrame stop_sending(kInvalidControlFrameId, stream_id, QUIC_ERROR_PROCESSING_STREAM); EXPECT_CALL(owner_, OnStopSendingReceived(_)).Times(1); EXPECT_CALL(*session_, WriteControlFrame(_, _)); EXPECT_CALL(*connection_, OnStreamReset(stream_id, QUIC_ERROR_PROCESSING_STREAM)); session_->OnStopSendingFrame(stop_sending); } StrictMock<MockQuicSessionVisitor> owner_; StrictMock<MockQuicCryptoServerStreamHelper> stream_helper_; MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; StrictMock<MockQuicConnection>* connection_; QuicConfig config_; QuicCryptoServerConfig crypto_config_; QuicCompressedCertsCache compressed_certs_cache_; QuicMemoryCacheBackend memory_cache_backend_; std::unique_ptr<TestServerSession> session_; std::unique_ptr<CryptoHandshakeMessage> handshake_message_; }; MATCHER_P(EqualsProto, network_params, "") { CachedNetworkParameters reference(network_params); return (arg->bandwidth_estimate_bytes_per_second() == reference.bandwidth_estimate_bytes_per_second() && arg->bandwidth_estimate_bytes_per_second() == reference.bandwidth_estimate_bytes_per_second() && arg->max_bandwidth_estimate_bytes_per_second() == reference.max_bandwidth_estimate_bytes_per_second() && arg->max_bandwidth_timestamp_seconds() == reference.max_bandwidth_timestamp_seconds() && arg->min_rtt_ms() == reference.min_rtt_ms() && arg->previous_connection_state() == reference.previous_connection_state()); } INSTANTIATE_TEST_SUITE_P(Tests, QuicServerSessionBaseTest, ::testing::ValuesIn(AllSupportedVersions()), ::testing::PrintToStringParamName()); TEST_P(QuicServerSessionBaseTest, GetSSLConfig) { EXPECT_EQ(session_->QuicSpdySession::GetSSLConfig(), QuicSSLConfig()); } TEST_P(QuicServerSessionBaseTest, CloseStreamDueToReset) { QuicStreamFrame data1(GetNthClientInitiatedBidirectionalId(0), false, 0, kStreamData); session_->OnStreamFrame(data1); EXPECT_EQ(1u, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); QuicRstStreamFrame rst1(kInvalidControlFrameId, GetNthClientInitiatedBidirectionalId(0), QUIC_ERROR_PROCESSING_STREAM, 0); EXPECT_CALL(owner_, OnRstStreamReceived(_)).Times(1); if (!VersionHasIetfQuicFrames(transport_version())) { EXPECT_CALL(*session_, WriteControlFrame(_, _)); EXPECT_CALL(*connection_, OnStreamReset(GetNthClientInitiatedBidirectionalId(0), QUIC_RST_ACKNOWLEDGEMENT)); } session_->OnRstStream(rst1); InjectStopSendingFrame(GetNthClientInitiatedBidirectionalId(0)); EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); session_->OnStreamFrame(data1); EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); EXPECT_TRUE(connection_->connected()); } TEST_P(QuicServerSessionBaseTest, NeverOpenStreamDueToReset) { QuicRstStreamFrame rst1(kInvalidControlFrameId, GetNthClientInitiatedBidirectionalId(0), QUIC_ERROR_PROCESSING_STREAM, 0); EXPECT_CALL(owner_, OnRstStreamReceived(_)).Times(1); if (!VersionHasIetfQuicFrames(transport_version())) { EXPECT_CALL(*session_, WriteControlFrame(_, _)); EXPECT_CALL(*connection_, OnStreamReset(GetNthClientInitiatedBidirectionalId(0), QUIC_RST_ACKNOWLEDGEMENT)); } session_->OnRstStream(rst1); InjectStopSendingFrame(GetNthClientInitiatedBidirectionalId(0)); EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); QuicStreamFrame data1(GetNthClientInitiatedBidirectionalId(0), false, 0, kStreamData); session_->OnStreamFrame(data1); EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); EXPECT_TRUE(connection_->connected()); } TEST_P(QuicServerSessionBaseTest, AcceptClosedStream) { QuicStreamFrame frame1(GetNthClientInitiatedBidirectionalId(0), false, 0, kStreamData); QuicStreamFrame frame2(GetNthClientInitiatedBidirectionalId(1), false, 0, kStreamData); session_->OnStreamFrame(frame1); session_->OnStreamFrame(frame2); EXPECT_EQ(2u, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); QuicRstStreamFrame rst(kInvalidControlFrameId, GetNthClientInitiatedBidirectionalId(0), QUIC_ERROR_PROCESSING_STREAM, 0); EXPECT_CALL(owner_, OnRstStreamReceived(_)).Times(1); if (!VersionHasIetfQuicFrames(transport_version())) { EXPECT_CALL(*session_, WriteControlFrame(_, _)); EXPECT_CALL(*connection_, OnStreamReset(GetNthClientInitiatedBidirectionalId(0), QUIC_RST_ACKNOWLEDGEMENT)); } session_->OnRstStream(rst); InjectStopSendingFrame(GetNthClientInitiatedBidirectionalId(0)); QuicStreamFrame frame3(GetNthClientInitiatedBidirectionalId(0), false, 2, kStreamData); QuicStreamFrame frame4(GetNthClientInitiatedBidirectionalId(1), false, 2, kStreamData); session_->OnStreamFrame(frame3); session_->OnStreamFrame(frame4); EXPECT_EQ(1u, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); EXPECT_TRUE(connection_->connected()); } TEST_P(QuicServerSessionBaseTest, MaxOpenStreams) { connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); session_->OnConfigNegotiated(); if (!VersionHasIetfQuicFrames(transport_version())) { EXPECT_LT(kMaxStreamsMultiplier * kMaxStreamsForTest, kMaxStreamsForTest + kMaxStreamsMinimumIncrement); EXPECT_EQ(kMaxStreamsForTest + kMaxStreamsMinimumIncrement, session_->max_open_incoming_bidirectional_streams()); } EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); QuicStreamId stream_id = GetNthClientInitiatedBidirectionalId(0); for (size_t i = 0; i < kMaxStreamsForTest; ++i) { EXPECT_TRUE(QuicServerSessionBasePeer::GetOrCreateStream(session_.get(), stream_id)); stream_id += QuicUtils::StreamIdDelta(transport_version()); QuicAlarm* alarm = QuicSessionPeer::GetStreamCountResetAlarm(session_.get()); if (alarm->IsSet()) { alarm_factory_.FireAlarm(alarm); } } if (!VersionHasIetfQuicFrames(transport_version())) { for (size_t i = 0; i < kMaxStreamsMinimumIncrement; ++i) { EXPECT_TRUE(QuicServerSessionBasePeer::GetOrCreateStream(session_.get(), stream_id)); stream_id += QuicUtils::StreamIdDelta(transport_version()); } } stream_id += QuicUtils::StreamIdDelta(transport_version()); if (!VersionHasIetfQuicFrames(transport_version())) { EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); EXPECT_CALL(*session_, WriteControlFrame(_, _)); EXPECT_CALL(*connection_, OnStreamReset(stream_id, QUIC_REFUSED_STREAM)); } else { EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(1); } EXPECT_FALSE( QuicServerSessionBasePeer::GetOrCreateStream(session_.get(), stream_id)); } TEST_P(QuicServerSessionBaseTest, MaxAvailableBidirectionalStreams) { connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); session_->OnConfigNegotiated(); const size_t kAvailableStreamLimit = session_->MaxAvailableBidirectionalStreams(); EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); EXPECT_TRUE(QuicServerSessionBasePeer::GetOrCreateStream( session_.get(), GetNthClientInitiatedBidirectionalId(0))); QuicStreamId next_id = QuicUtils::StreamIdDelta(transport_version()); const int kLimitingStreamId = GetNthClientInitiatedBidirectionalId(kAvailableStreamLimit + 1); if (!VersionHasIetfQuicFrames(transport_version())) { EXPECT_TRUE(QuicServerSessionBasePeer::GetOrCreateStream( session_.get(), kLimitingStreamId)); EXPECT_CALL(*connection_, CloseConnection(QUIC_TOO_MANY_AVAILABLE_STREAMS, _, _)); } else { EXPECT_CALL(*connection_, CloseConnection(QUIC_INVALID_STREAM_ID, _, _)); } EXPECT_FALSE(QuicServerSessionBasePeer::GetOrCreateStream( session_.get(), kLimitingStreamId + 2 * next_id)); } TEST_P(QuicServerSessionBaseTest, GetEvenIncomingError) { const QuicErrorCode expected_error = VersionHasIetfQuicFrames(transport_version()) ? QUIC_HTTP_STREAM_WRONG_DIRECTION : QUIC_INVALID_STREAM_ID; EXPECT_CALL(*connection_, CloseConnection(expected_error, _, _)); EXPECT_EQ(nullptr, QuicServerSessionBasePeer::GetOrCreateStream( session_.get(), session_->next_outgoing_unidirectional_stream_id())); } TEST_P(QuicServerSessionBaseTest, GetStreamDisconnected) { if (version() != AllSupportedVersions()[0]) { return; } QuicConnectionPeer::TearDownLocalConnectionState(connection_); EXPECT_QUIC_BUG(QuicServerSessionBasePeer::GetOrCreateStream( session_.get(), GetNthClientInitiatedBidirectionalId(0)), "ShouldCreateIncomingStream called when disconnected"); } class MockQuicCryptoServerStream : public QuicCryptoServerStream { public: explicit MockQuicCryptoServerStream( const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache, QuicServerSessionBase* session, QuicCryptoServerStreamBase::Helper* helper) : QuicCryptoServerStream(crypto_config, compressed_certs_cache, session, helper) {} MockQuicCryptoServerStream(const MockQuicCryptoServerStream&) = delete; MockQuicCryptoServerStream& operator=(const MockQuicCryptoServerStream&) = delete; ~MockQuicCryptoServerStream() override {} MOCK_METHOD(void, SendServerConfigUpdate, (const CachedNetworkParameters*), (override)); }; class MockTlsServerHandshaker : public TlsServerHandshaker { public: explicit MockTlsServerHandshaker(QuicServerSessionBase* session, const QuicCryptoServerConfig* crypto_config) : TlsServerHandshaker(session, crypto_config) {} MockTlsServerHandshaker(const MockTlsServerHandshaker&) = delete; MockTlsServerHandshaker& operator=(const MockTlsServerHandshaker&) = delete; ~MockTlsServerHandshaker() override {} MOCK_METHOD(void, SendServerConfigUpdate, (const CachedNetworkParameters*), (override)); MOCK_METHOD(std::string, GetAddressToken, (const CachedNetworkParameters*), (const, override)); MOCK_METHOD(bool, encryption_established, (), (const, override)); }; TEST_P(QuicServerSessionBaseTest, BandwidthEstimates) { if (version().UsesTls() && !version().HasIetfQuicFrames()) { return; } QuicTagVector copt; copt.push_back(kBWRE); copt.push_back(kBWID); QuicConfigPeer::SetReceivedConnectionOptions(session_->config(), copt); connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); session_->OnConfigNegotiated(); EXPECT_TRUE( QuicServerSessionBasePeer::IsBandwidthResumptionEnabled(session_.get())); int32_t bandwidth_estimate_kbytes_per_second = 123; int32_t max_bandwidth_estimate_kbytes_per_second = 134; int32_t max_bandwidth_estimate_timestamp = 1122334455; const std::string serving_region = "not a real region"; session_->set_serving_region(serving_region); if (!VersionUsesHttp3(transport_version())) { session_->UnregisterStreamPriority( QuicUtils::GetHeadersStreamId(transport_version())); } QuicServerSessionBasePeer::SetCryptoStream(session_.get(), nullptr); MockQuicCryptoServerStream* quic_crypto_stream = nullptr; MockTlsServerHandshaker* tls_server_stream = nullptr; if (version().handshake_protocol == PROTOCOL_QUIC_CRYPTO) { quic_crypto_stream = new MockQuicCryptoServerStream( &crypto_config_, &compressed_certs_cache_, session_.get(), &stream_helper_); QuicServerSessionBasePeer::SetCryptoStream(session_.get(), quic_crypto_stream); } else { tls_server_stream = new MockTlsServerHandshaker(session_.get(), &crypto_config_); QuicServerSessionBasePeer::SetCryptoStream(session_.get(), tls_server_stream); } if (!VersionUsesHttp3(transport_version())) { session_->RegisterStreamPriority( QuicUtils::GetHeadersStreamId(transport_version()), true, QuicStreamPriority()); } QuicSentPacketManager* sent_packet_manager = QuicConnectionPeer::GetSentPacketManager(session_->connection()); QuicSustainedBandwidthRecorder& bandwidth_recorder = QuicSentPacketManagerPeer::GetBandwidthRecorder(sent_packet_manager); RttStats* rtt_stats = const_cast<RttStats*>(sent_packet_manager->GetRttStats()); rtt_stats->UpdateRtt(rtt_stats->initial_rtt(), QuicTime::Delta::Zero(), QuicTime::Zero()); QuicSustainedBandwidthRecorderPeer::SetBandwidthEstimate( &bandwidth_recorder, bandwidth_estimate_kbytes_per_second); QuicSustainedBandwidthRecorderPeer::SetMaxBandwidthEstimate( &bandwidth_recorder, max_bandwidth_estimate_kbytes_per_second, max_bandwidth_estimate_timestamp); if (!VersionUsesHttp3(transport_version())) { session_->MarkConnectionLevelWriteBlocked( QuicUtils::GetHeadersStreamId(transport_version())); } else { session_->MarkConnectionLevelWriteBlocked( QuicUtils::GetFirstUnidirectionalStreamId(transport_version(), Perspective::IS_SERVER)); } EXPECT_TRUE(session_->HasDataToWrite()); QuicTime now = QuicTime::Zero(); session_->OnCongestionWindowChange(now); bandwidth_estimate_kbytes_per_second = bandwidth_estimate_kbytes_per_second * 1.6; session_->OnCongestionWindowChange(now); int64_t srtt_ms = sent_packet_manager->GetRttStats()->smoothed_rtt().ToMilliseconds(); now = now + QuicTime::Delta::FromMilliseconds( kMinIntervalBetweenServerConfigUpdatesRTTs * srtt_ms); session_->OnCongestionWindowChange(now); session_->OnCanWrite(); EXPECT_FALSE(session_->HasDataToWrite()); session_->OnCongestionWindowChange(now); SerializedPacket packet( QuicPacketNumber(1) + kMinPacketsBetweenServerConfigUpdates, PACKET_4BYTE_PACKET_NUMBER, nullptr, 1000, false, false); sent_packet_manager->OnPacketSent(&packet, now, NOT_RETRANSMISSION, HAS_RETRANSMITTABLE_DATA, true, ECN_NOT_ECT); CachedNetworkParameters expected_network_params; expected_network_params.set_bandwidth_estimate_bytes_per_second( bandwidth_recorder.BandwidthEstimate().ToBytesPerSecond()); expected_network_params.set_max_bandwidth_estimate_bytes_per_second( bandwidth_recorder.MaxBandwidthEstimate().ToBytesPerSecond()); expected_network_params.set_max_bandwidth_timestamp_seconds( bandwidth_recorder.MaxBandwidthTimestamp()); expected_network_params.set_min_rtt_ms(session_->connection() ->sent_packet_manager() .GetRttStats() ->min_rtt() .ToMilliseconds()); expected_network_params.set_previous_connection_state( CachedNetworkParameters::CONGESTION_AVOIDANCE); expected_network_params.set_timestamp( session_->connection()->clock()->WallNow().ToUNIXSeconds()); expected_network_params.set_serving_region(serving_region); if (quic_crypto_stream) { EXPECT_CALL(*quic_crypto_stream, SendServerConfigUpdate(EqualsProto(expected_network_params))) .Times(1); } else { EXPECT_CALL(*tls_server_stream, GetAddressToken(EqualsProto(expected_network_params))) .WillOnce(testing::Return("Test address token")); } EXPECT_CALL(*connection_, OnSendConnectionState(_)).Times(1); session_->OnCongestionWindowChange(now); } TEST_P(QuicServerSessionBaseTest, BandwidthResumptionExperiment) { if (version().UsesTls()) { if (!version().HasIetfQuicFrames()) { return; } connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); } QuicTagVector copt; copt.push_back(kBWRE); QuicConfigPeer::SetReceivedConnectionOptions(session_->config(), copt); const std::string kTestServingRegion = "a serving region"; session_->set_serving_region(kTestServingRegion); connection_->AdvanceTime( QuicTime::Delta::FromSeconds(kNumSecondsPerHour + 1)); QuicCryptoServerStreamBase* crypto_stream = static_cast<QuicCryptoServerStreamBase*>( QuicSessionPeer::GetMutableCryptoStream(session_.get())); EXPECT_CALL(*connection_, ResumeConnectionState(_, _)).Times(0); session_->OnConfigNegotiated(); CachedNetworkParameters cached_network_params; cached_network_params.set_bandwidth_estimate_bytes_per_second(1); cached_network_params.set_serving_region("different serving region"); crypto_stream->SetPreviousCachedNetworkParams(cached_network_params); EXPECT_CALL(*connection_, ResumeConnectionState(_, _)).Times(0); session_->OnConfigNegotiated(); cached_network_params.set_serving_region(kTestServingRegion); cached_network_params.set_timestamp(0); crypto_stream->SetPreviousCachedNetworkParams(cached_network_params); EXPECT_CALL(*connection_, ResumeConnectionState(_, _)).Times(0); session_->OnConfigNegotiated(); cached_network_params.set_timestamp( connection_->clock()->WallNow().ToUNIXSeconds()); crypto_stream->SetPreviousCachedNetworkParams(cached_network_params); EXPECT_CALL(*connection_, ResumeConnectionState(_, _)).Times(1); session_->OnConfigNegotiated(); } TEST_P(QuicServerSessionBaseTest, BandwidthMaxEnablesResumption) { EXPECT_FALSE( QuicServerSessionBasePeer::IsBandwidthResumptionEnabled(session_.get())); QuicTagVector copt; copt.push_back(kBWMX); QuicConfigPeer::SetReceivedConnectionOptions(session_->config(), copt); connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); session_->OnConfigNegotiated(); EXPECT_TRUE( QuicServerSessionBasePeer::IsBan
321
cpp
google/quiche
bandwidth_sampler
quiche/quic/core/congestion_control/bandwidth_sampler.cc
quiche/quic/core/congestion_control/bandwidth_sampler_test.cc
#ifndef QUICHE_QUIC_CORE_CONGESTION_CONTROL_BANDWIDTH_SAMPLER_H_ #define QUICHE_QUIC_CORE_CONGESTION_CONTROL_BANDWIDTH_SAMPLER_H_ #include "quiche/quic/core/congestion_control/send_algorithm_interface.h" #include "quiche/quic/core/congestion_control/windowed_filter.h" #include "quiche/quic/core/packet_number_indexed_queue.h" #include "quiche/quic/core/quic_bandwidth.h" #include "quiche/quic/core/quic_packet_number.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_unacked_packet_map.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/common/quiche_circular_deque.h" namespace quic { namespace test { class BandwidthSamplerPeer; } struct QUICHE_EXPORT SendTimeState { SendTimeState() : is_valid(false), is_app_limited(false), total_bytes_sent(0), total_bytes_acked(0), total_bytes_lost(0), bytes_in_flight(0) {} SendTimeState(bool is_app_limited, QuicByteCount total_bytes_sent, QuicByteCount total_bytes_acked, QuicByteCount total_bytes_lost, QuicByteCount bytes_in_flight) : is_valid(true), is_app_limited(is_app_limited), total_bytes_sent(total_bytes_sent), total_bytes_acked(total_bytes_acked), total_bytes_lost(total_bytes_lost), bytes_in_flight(bytes_in_flight) {} SendTimeState(const SendTimeState& other) = default; SendTimeState& operator=(const SendTimeState& other) = default; friend QUICHE_EXPORT std::ostream& operator<<(std::ostream& os, const SendTimeState& s); bool is_valid; bool is_app_limited; QuicByteCount total_bytes_sent; QuicByteCount total_bytes_acked; QuicByteCount total_bytes_lost; QuicByteCount bytes_in_flight; }; struct QUICHE_EXPORT ExtraAckedEvent { QuicByteCount extra_acked = 0; QuicByteCount bytes_acked = 0; QuicTime::Delta time_delta = QuicTime::Delta::Zero(); QuicRoundTripCount round = 0; bool operator>=(const ExtraAckedEvent& other) const { return extra_acked >= other.extra_acked; } bool operator==(const ExtraAckedEvent& other) const { return extra_acked == other.extra_acked; } }; struct QUICHE_EXPORT BandwidthSample { QuicBandwidth bandwidth = QuicBandwidth::Zero(); QuicTime::Delta rtt = QuicTime::Delta::Zero(); QuicBandwidth send_rate = QuicBandwidth::Infinite(); SendTimeState state_at_send; }; class QUICHE_EXPORT MaxAckHeightTracker { public: explicit MaxAckHeightTracker(QuicRoundTripCount initial_filter_window) : max_ack_height_filter_(initial_filter_window, ExtraAckedEvent(), 0) {} QuicByteCount Get() const { return max_ack_height_filter_.GetBest().extra_acked; } QuicByteCount Update(QuicBandwidth bandwidth_estimate, bool is_new_max_bandwidth, QuicRoundTripCount round_trip_count, QuicPacketNumber last_sent_packet_number, QuicPacketNumber last_acked_packet_number, QuicTime ack_time, QuicByteCount bytes_acked); void SetFilterWindowLength(QuicRoundTripCount length) { max_ack_height_filter_.SetWindowLength(length); } void Reset(QuicByteCount new_height, QuicRoundTripCount new_time) { ExtraAckedEvent new_event; new_event.extra_acked = new_height; new_event.round = new_time; max_ack_height_filter_.Reset(new_event, new_time); } void SetAckAggregationBandwidthThreshold(double threshold) { ack_aggregation_bandwidth_threshold_ = threshold; } void SetStartNewAggregationEpochAfterFullRound(bool value) { start_new_aggregation_epoch_after_full_round_ = value; } void SetReduceExtraAckedOnBandwidthIncrease(bool value) { reduce_extra_acked_on_bandwidth_increase_ = value; } double ack_aggregation_bandwidth_threshold() const { return ack_aggregation_bandwidth_threshold_; } uint64_t num_ack_aggregation_epochs() const { return num_ack_aggregation_epochs_; } private: using MaxAckHeightFilter = WindowedFilter<ExtraAckedEvent, MaxFilter<ExtraAckedEvent>, QuicRoundTripCount, QuicRoundTripCount>; MaxAckHeightFilter max_ack_height_filter_; QuicTime aggregation_epoch_start_time_ = QuicTime::Zero(); QuicByteCount aggregation_epoch_bytes_ = 0; QuicPacketNumber last_sent_packet_number_before_epoch_; uint64_t num_ack_aggregation_epochs_ = 0; double ack_aggregation_bandwidth_threshold_ = GetQuicFlag(quic_ack_aggregation_bandwidth_threshold); bool start_new_aggregation_epoch_after_full_round_ = false; bool reduce_extra_acked_on_bandwidth_increase_ = false; }; class QUICHE_EXPORT BandwidthSamplerInterface { public: virtual ~BandwidthSamplerInterface() {} virtual void OnPacketSent( QuicTime sent_time, QuicPacketNumber packet_number, QuicByteCount bytes, QuicByteCount bytes_in_flight, HasRetransmittableData has_retransmittable_data) = 0; virtual void OnPacketNeutered(QuicPacketNumber packet_number) = 0; struct QUICHE_EXPORT CongestionEventSample { QuicBandwidth sample_max_bandwidth = QuicBandwidth::Zero(); bool sample_is_app_limited = false; QuicTime::Delta sample_rtt = QuicTime::Delta::Infinite(); QuicByteCount sample_max_inflight = 0; SendTimeState last_packet_send_state; QuicByteCount extra_acked = 0; }; virtual CongestionEventSample OnCongestionEvent( QuicTime ack_time, const AckedPacketVector& acked_packets, const LostPacketVector& lost_packets, QuicBandwidth max_bandwidth, QuicBandwidth est_bandwidth_upper_bound, QuicRoundTripCount round_trip_count) = 0; virtual void OnAppLimited() = 0; virtual void RemoveObsoletePackets(QuicPacketNumber least_unacked) = 0; virtual QuicByteCount total_bytes_sent() const = 0; virtual QuicByteCount total_bytes_acked() const = 0; virtual QuicByteCount total_bytes_lost() const = 0; virtual QuicByteCount total_bytes_neutered() const = 0; virtual bool is_app_limited() const = 0; virtual QuicPacketNumber end_of_app_limited_phase() const = 0; }; class QUICHE_EXPORT BandwidthSampler : public BandwidthSamplerInterface { public: BandwidthSampler(const QuicUnackedPacketMap* unacked_packet_map, QuicRoundTripCount max_height_tracker_window_length); BandwidthSampler(const BandwidthSampler& other); ~BandwidthSampler() override; void OnPacketSent(QuicTime sent_time, QuicPacketNumber packet_number, QuicByteCount bytes, QuicByteCount bytes_in_flight, HasRetransmittableData has_retransmittable_data) override; void OnPacketNeutered(QuicPacketNumber packet_number) override; CongestionEventSample OnCongestionEvent( QuicTime ack_time, const AckedPacketVector& acked_packets, const LostPacketVector& lost_packets, QuicBandwidth max_bandwidth, QuicBandwidth est_bandwidth_upper_bound, QuicRoundTripCount round_trip_count) override; QuicByteCount OnAckEventEnd(QuicBandwidth bandwidth_estimate, bool is_new_max_bandwidth, QuicRoundTripCount round_trip_count); void OnAppLimited() override; void RemoveObsoletePackets(QuicPacketNumber least_unacked) override; QuicByteCount total_bytes_sent() const override; QuicByteCount total_bytes_acked() const override; QuicByteCount total_bytes_lost() const override; QuicByteCount total_bytes_neutered() const override; bool is_app_limited() const override; QuicPacketNumber end_of_app_limited_phase() const override; QuicByteCount max_ack_height() const { return max_ack_height_tracker_.Get(); } uint64_t num_ack_aggregation_epochs() const { return max_ack_height_tracker_.num_ack_aggregation_epochs(); } void SetMaxAckHeightTrackerWindowLength(QuicRoundTripCount length) { max_ack_height_tracker_.SetFilterWindowLength(length); } void ResetMaxAckHeightTracker(QuicByteCount new_height, QuicRoundTripCount new_time) { max_ack_height_tracker_.Reset(new_height, new_time); } void SetStartNewAggregationEpochAfterFullRound(bool value) { max_ack_height_tracker_.SetStartNewAggregationEpochAfterFullRound(value); } void SetLimitMaxAckHeightTrackerBySendRate(bool value) { limit_max_ack_height_tracker_by_send_rate_ = value; } void SetReduceExtraAckedOnBandwidthIncrease(bool value) { max_ack_height_tracker_.SetReduceExtraAckedOnBandwidthIncrease(value); } struct QUICHE_EXPORT AckPoint { QuicTime ack_time = QuicTime::Zero(); QuicByteCount total_bytes_acked = 0; friend QUICHE_EXPORT std::ostream& operator<<(std::ostream& os, const AckPoint& ack_point) { return os << ack_point.ack_time << ":" << ack_point.total_bytes_acked; } }; class QUICHE_EXPORT RecentAckPoints { public: void Update(QuicTime ack_time, QuicByteCount total_bytes_acked) { QUICHE_DCHECK_GE(total_bytes_acked, ack_points_[1].total_bytes_acked); if (ack_time < ack_points_[1].ack_time) { ack_points_[1].ack_time = ack_time; } else if (ack_time > ack_points_[1].ack_time) { ack_points_[0] = ack_points_[1]; ack_points_[1].ack_time = ack_time; } ack_points_[1].total_bytes_acked = total_bytes_acked; } void Clear() { ack_points_[0] = ack_points_[1] = AckPoint(); } const AckPoint& MostRecentPoint() const { return ack_points_[1]; } const AckPoint& LessRecentPoint() const { if (ack_points_[0].total_bytes_acked != 0) { return ack_points_[0]; } return ack_points_[1]; } private: AckPoint ack_points_[2]; }; void EnableOverestimateAvoidance(); bool IsOverestimateAvoidanceEnabled() const { return overestimate_avoidance_; } private: friend class test::BandwidthSamplerPeer; class QUICHE_EXPORT ConnectionStateOnSentPacket { public: QuicTime sent_time() const { return sent_time_; } QuicByteCount size() const { return size_; } QuicByteCount total_bytes_sent_at_last_acked_packet() const { return total_bytes_sent_at_last_acked_packet_; } QuicTime last_acked_packet_sent_time() const { return last_acked_packet_sent_time_; } QuicTime last_acked_packet_ack_time() const { return last_acked_packet_ack_time_; } const SendTimeState& send_time_state() const { return send_time_state_; } ConnectionStateOnSentPacket(QuicTime sent_time, QuicByteCount size, QuicByteCount bytes_in_flight, const BandwidthSampler& sampler) : sent_time_(sent_time), size_(size), total_bytes_sent_at_last_acked_packet_( sampler.total_bytes_sent_at_last_acked_packet_), last_acked_packet_sent_time_(sampler.last_acked_packet_sent_time_), last_acked_packet_ack_time_(sampler.last_acked_packet_ack_time_), send_time_state_(sampler.is_app_limited_, sampler.total_bytes_sent_, sampler.total_bytes_acked_, sampler.total_bytes_lost_, bytes_in_flight) {} ConnectionStateOnSentPacket() : sent_time_(QuicTime::Zero()), size_(0), total_bytes_sent_at_last_acked_packet_(0), last_acked_packet_sent_time_(QuicTime::Zero()), last_acked_packet_ack_time_(QuicTime::Zero()) {} friend QUICHE_EXPORT std::ostream& operator<<( std::ostream& os, const ConnectionStateOnSentPacket& p) { os << "{sent_time:" << p.sent_time() << ", size:" << p.size() << ", total_bytes_sent_at_last_acked_packet:" << p.total_bytes_sent_at_last_acked_packet() << ", last_acked_packet_sent_time:" << p.last_acked_packet_sent_time() << ", last_acked_packet_ack_time:" << p.last_acked_packet_ack_time() << ", send_time_state:" << p.send_time_state() << "}"; return os; } private: QuicTime sent_time_; QuicByteCount size_; QuicByteCount total_bytes_sent_at_last_acked_packet_; QuicTime last_acked_packet_sent_time_; QuicTime last_acked_packet_ack_time_; SendTimeState send_time_state_; }; BandwidthSample OnPacketAcknowledged(QuicTime ack_time, QuicPacketNumber packet_number); SendTimeState OnPacketLost(QuicPacketNumber packet_number, QuicPacketLength bytes_lost); void SentPacketToSendTimeState(const ConnectionStateOnSentPacket& sent_packet, SendTimeState* send_time_state) const; bool ChooseA0Point(QuicByteCount total_bytes_acked, AckPoint* a0); QuicByteCount total_bytes_sent_; QuicByteCount total_bytes_acked_; QuicByteCount total_bytes_lost_; QuicByteCount total_bytes_neutered_; QuicByteCount total_bytes_sent_at_last_acked_packet_; QuicTime last_acked_packet_sent_time_; QuicTime last_acked_packet_ack_time_; QuicPacketNumber last_sent_packet_; QuicPacketNumber last_acked_packet_; bool is_app_limited_; QuicPacketNumber end_of_app_limited_phase_; PacketNumberIndexedQueue<ConnectionStateOnSentPacket> connection_state_map_; RecentAckPoints recent_ack_points_; quiche::QuicheCircularDeque<AckPoint> a0_candidates_; const QuicPacketCount max_tracked_packets_; const QuicUnackedPacketMap* unacked_packet_map_; BandwidthSample OnPacketAcknowledgedInner( QuicTime ack_time, QuicPacketNumber packet_number, const ConnectionStateOnSentPacket& sent_packet); MaxAckHeightTracker max_ack_height_tracker_; QuicByteCount total_bytes_acked_after_last_ack_event_; bool overestimate_avoidance_; bool limit_max_ack_height_tracker_by_send_rate_; }; } #endif #include "quiche/quic/core/congestion_control/bandwidth_sampler.h" #include <algorithm> #include <ostream> #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { std::ostream& operator<<(std::ostream& os, const SendTimeState& s) { os << "{valid:" << s.is_valid << ", app_limited:" << s.is_app_limited << ", total_sent:" << s.total_bytes_sent << ", total_acked:" << s.total_bytes_acked << ", total_lost:" << s.total_bytes_lost << ", inflight:" << s.bytes_in_flight << "}"; return os; } QuicByteCount MaxAckHeightTracker::Update( QuicBandwidth bandwidth_estimate, bool is_new_max_bandwidth, QuicRoundTripCount round_trip_count, QuicPacketNumber last_sent_packet_number, QuicPacketNumber last_acked_packet_number, QuicTime ack_time, QuicByteCount bytes_acked) { bool force_new_epoch = false; if (reduce_extra_acked_on_bandwidth_increase_ && is_new_max_bandwidth) { ExtraAckedEvent best = max_ack_height_filter_.GetBest(); ExtraAckedEvent second_best = max_ack_height_filter_.GetSecondBest(); ExtraAckedEvent third_best = max_ack_height_filter_.GetThirdBest(); max_ack_height_filter_.Clear(); QuicByteCount expected_bytes_acked = bandwidth_estimate * best.time_delta; if (expected_bytes_acked < best.bytes_acked) { best.extra_acked = best.bytes_acked - expected_bytes_acked; max_ack_height_filter_.Update(best, best.round); } expected_bytes_acked = bandwidth_estimate * second_best.time_delta; if (expected_bytes_acked < second_best.bytes_acked) { QUICHE_DCHECK_LE(best.round, second_best.round); second_best.extra_acked = second_best.bytes_acked - expected_bytes_acked; max_ack_height_filter_.Update(second_best, second_best.round); } expected_bytes_acked = bandwidth_estimate * third_best.time_delta; if (expected_bytes_acked < third_best.bytes_acked) { QUICHE_DCHECK_LE(second_best.round, third_best.round); third_best.extra_acked = third_best.bytes_acked - expected_bytes_acked; max_ack_height_filter_.Update(third_best, third_best.round); } } if (start_new_aggregation_epoch_after_full_round_ && last_sent_packet_number_before_epoch_.IsInitialized() && last_acked_packet_number.IsInitialized() && last_acked_packet_number > last_sent_packet_number_before_epoch_) { QUIC_DVLOG(3) << "Force starting a new aggregation epoch. " "last_sent_packet_number_before_epoch_:" << last_sent_packet_number_before_epoch_ << ", last_acked_packet_number:" << last_acked_packet_number; if (reduce_extra_acked_on_bandwidth_increase_) { QUIC_BUG(quic_bwsampler_46) << "A full round of aggregation should never " << "pass with startup_include_extra_acked(B204) enabled."; } force_new_epoch = true; } if (aggregation_epoch_start_time_ == QuicTime::Zero() || force_new_epoch) { aggregation_epoch_bytes_ = bytes_acked; aggregation_epoch_start_time_ = ack_time; last_sent_packet_number_before_epoch_ = last_sent_packet_number; ++num_ack_aggregation_epochs_; return 0; } QuicTime::Delta aggregation_delta = ack_time - aggregation_epoch_start_time_; QuicByteCount expected_bytes_acked = bandwidth_estimate * aggregation_delta; if (aggregation_epoch_bytes_ <= ack_aggregation_bandwidth_threshold_ * expected_bytes_acked) { QUIC_DVLOG(3) << "Starting a new aggregation epoch because " "aggregation_epoch_bytes_ " << aggregation_epoch_bytes_ << " is smaller than expected. " "ack_aggregation_bandwidth_threshold_:" << ack_aggregation_bandwidth_threshold_ << ", expected_bytes_acked:" << expected_bytes_acked << ", bandwidth_estimate:" << bandwidth_estimate << ", aggregation_duration:" << aggregation_delta << ", new_aggregation_epoch:" << ack_time << ", new_aggregation_bytes_acked:" << bytes_acked; aggregation_epoch_bytes_ = bytes_acked; aggregation_epoch_start_time_ = ack_time; last_sent_packet_number_before_epoch_ = last_sent_packet_number; ++num_ack_aggregation_epochs_; return 0; } aggregation_epoch_bytes_ += bytes_acked; QuicByteCount extra_bytes_acked = aggregation_epoch_bytes_ - expected_bytes_acked; QUIC_DVLOG(3) << "Updating MaxAckHeight. ack_time:" << ack_time << ", last sent packet:" << last_sent_packet_number << ", bandwidth_estimate:" << bandwidth_estimate << ", bytes_acked:" << bytes_acked << ", expected_bytes_acked:" << expected_bytes_acked << ", aggregation_epoch_bytes_:" << aggregation_epoch_bytes_ << ", extra_bytes_acked:" << extra_bytes_acked; ExtraAckedEvent new_event; new_event.extra_acked = extra_bytes_acked; new_event.bytes_acked = aggregation_epoch_bytes_; new_event.time_delta = aggregation_delta; max_ack_height_filter_.Update(new_event, round_trip_cou
#include "quiche/quic/core/congestion_control/bandwidth_sampler.h" #include <algorithm> #include <cstdint> #include <set> #include <string> #include "quiche/quic/core/quic_bandwidth.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_clock.h" namespace quic { namespace test { class BandwidthSamplerPeer { public: static size_t GetNumberOfTrackedPackets(const BandwidthSampler& sampler) { return sampler.connection_state_map_.number_of_present_entries(); } static QuicByteCount GetPacketSize(const BandwidthSampler& sampler, QuicPacketNumber packet_number) { return sampler.connection_state_map_.GetEntry(packet_number)->size(); } }; const QuicByteCount kRegularPacketSize = 1280; static_assert((kRegularPacketSize & 31) == 0, "kRegularPacketSize has to be five times divisible by 2"); struct TestParameters { bool overestimate_avoidance; }; std::string PrintToString(const TestParameters& p) { return p.overestimate_avoidance ? "enable_overestimate_avoidance" : "no_enable_overestimate_avoidance"; } class BandwidthSamplerTest : public QuicTestWithParam<TestParameters> { protected: BandwidthSamplerTest() : sampler_(nullptr, 0), sampler_app_limited_at_start_(sampler_.is_app_limited()), bytes_in_flight_(0), max_bandwidth_(QuicBandwidth::Zero()), est_bandwidth_upper_bound_(QuicBandwidth::Infinite()), round_trip_count_(0) { clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1)); if (GetParam().overestimate_avoidance) { sampler_.EnableOverestimateAvoidance(); } } MockClock clock_; BandwidthSampler sampler_; bool sampler_app_limited_at_start_; QuicByteCount bytes_in_flight_; QuicBandwidth max_bandwidth_; QuicBandwidth est_bandwidth_upper_bound_; QuicRoundTripCount round_trip_count_; QuicByteCount PacketsToBytes(QuicPacketCount packet_count) { return packet_count * kRegularPacketSize; } void SendPacketInner(uint64_t packet_number, QuicByteCount bytes, HasRetransmittableData has_retransmittable_data) { sampler_.OnPacketSent(clock_.Now(), QuicPacketNumber(packet_number), bytes, bytes_in_flight_, has_retransmittable_data); if (has_retransmittable_data == HAS_RETRANSMITTABLE_DATA) { bytes_in_flight_ += bytes; } } void SendPacket(uint64_t packet_number) { SendPacketInner(packet_number, kRegularPacketSize, HAS_RETRANSMITTABLE_DATA); } BandwidthSample AckPacketInner(uint64_t packet_number) { QuicByteCount size = BandwidthSamplerPeer::GetPacketSize( sampler_, QuicPacketNumber(packet_number)); bytes_in_flight_ -= size; BandwidthSampler::CongestionEventSample sample = sampler_.OnCongestionEvent( clock_.Now(), {MakeAckedPacket(packet_number)}, {}, max_bandwidth_, est_bandwidth_upper_bound_, round_trip_count_); max_bandwidth_ = std::max(max_bandwidth_, sample.sample_max_bandwidth); BandwidthSample bandwidth_sample; bandwidth_sample.bandwidth = sample.sample_max_bandwidth; bandwidth_sample.rtt = sample.sample_rtt; bandwidth_sample.state_at_send = sample.last_packet_send_state; EXPECT_TRUE(bandwidth_sample.state_at_send.is_valid); return bandwidth_sample; } AckedPacket MakeAckedPacket(uint64_t packet_number) const { QuicByteCount size = BandwidthSamplerPeer::GetPacketSize( sampler_, QuicPacketNumber(packet_number)); return AckedPacket(QuicPacketNumber(packet_number), size, clock_.Now()); } LostPacket MakeLostPacket(uint64_t packet_number) const { return LostPacket(QuicPacketNumber(packet_number), BandwidthSamplerPeer::GetPacketSize( sampler_, QuicPacketNumber(packet_number))); } QuicBandwidth AckPacket(uint64_t packet_number) { BandwidthSample sample = AckPacketInner(packet_number); return sample.bandwidth; } BandwidthSampler::CongestionEventSample OnCongestionEvent( std::set<uint64_t> acked_packet_numbers, std::set<uint64_t> lost_packet_numbers) { AckedPacketVector acked_packets; for (auto it = acked_packet_numbers.begin(); it != acked_packet_numbers.end(); ++it) { acked_packets.push_back(MakeAckedPacket(*it)); bytes_in_flight_ -= acked_packets.back().bytes_acked; } LostPacketVector lost_packets; for (auto it = lost_packet_numbers.begin(); it != lost_packet_numbers.end(); ++it) { lost_packets.push_back(MakeLostPacket(*it)); bytes_in_flight_ -= lost_packets.back().bytes_lost; } BandwidthSampler::CongestionEventSample sample = sampler_.OnCongestionEvent( clock_.Now(), acked_packets, lost_packets, max_bandwidth_, est_bandwidth_upper_bound_, round_trip_count_); max_bandwidth_ = std::max(max_bandwidth_, sample.sample_max_bandwidth); return sample; } SendTimeState LosePacket(uint64_t packet_number) { QuicByteCount size = BandwidthSamplerPeer::GetPacketSize( sampler_, QuicPacketNumber(packet_number)); bytes_in_flight_ -= size; LostPacket lost_packet(QuicPacketNumber(packet_number), size); BandwidthSampler::CongestionEventSample sample = sampler_.OnCongestionEvent( clock_.Now(), {}, {lost_packet}, max_bandwidth_, est_bandwidth_upper_bound_, round_trip_count_); EXPECT_TRUE(sample.last_packet_send_state.is_valid); EXPECT_EQ(sample.sample_max_bandwidth, QuicBandwidth::Zero()); EXPECT_EQ(sample.sample_rtt, QuicTime::Delta::Infinite()); return sample.last_packet_send_state; } void Send40PacketsAndAckFirst20(QuicTime::Delta time_between_packets) { for (int i = 1; i <= 20; i++) { SendPacket(i); clock_.AdvanceTime(time_between_packets); } for (int i = 1; i <= 20; i++) { AckPacket(i); SendPacket(i + 20); clock_.AdvanceTime(time_between_packets); } } }; INSTANTIATE_TEST_SUITE_P( BandwidthSamplerTests, BandwidthSamplerTest, testing::Values(TestParameters{false}, TestParameters{true}), testing::PrintToStringParamName()); TEST_P(BandwidthSamplerTest, SendAndWait) { QuicTime::Delta time_between_packets = QuicTime::Delta::FromMilliseconds(10); QuicBandwidth expected_bandwidth = QuicBandwidth::FromBytesPerSecond(kRegularPacketSize * 100); for (int i = 1; i < 20; i++) { SendPacket(i); clock_.AdvanceTime(time_between_packets); QuicBandwidth current_sample = AckPacket(i); EXPECT_EQ(expected_bandwidth, current_sample); } for (int i = 20; i < 25; i++) { time_between_packets = time_between_packets * 2; expected_bandwidth = expected_bandwidth * 0.5; SendPacket(i); clock_.AdvanceTime(time_between_packets); QuicBandwidth current_sample = AckPacket(i); EXPECT_EQ(expected_bandwidth, current_sample); } sampler_.RemoveObsoletePackets(QuicPacketNumber(25)); EXPECT_EQ(0u, BandwidthSamplerPeer::GetNumberOfTrackedPackets(sampler_)); EXPECT_EQ(0u, bytes_in_flight_); } TEST_P(BandwidthSamplerTest, SendTimeState) { QuicTime::Delta time_between_packets = QuicTime::Delta::FromMilliseconds(10); for (int i = 1; i <= 5; i++) { SendPacket(i); EXPECT_EQ(PacketsToBytes(i), sampler_.total_bytes_sent()); clock_.AdvanceTime(time_between_packets); } SendTimeState send_time_state = AckPacketInner(1).state_at_send; EXPECT_EQ(PacketsToBytes(1), send_time_state.total_bytes_sent); EXPECT_EQ(0u, send_time_state.total_bytes_acked); EXPECT_EQ(0u, send_time_state.total_bytes_lost); EXPECT_EQ(PacketsToBytes(1), sampler_.total_bytes_acked()); send_time_state = LosePacket(2); EXPECT_EQ(PacketsToBytes(2), send_time_state.total_bytes_sent); EXPECT_EQ(0u, send_time_state.total_bytes_acked); EXPECT_EQ(0u, send_time_state.total_bytes_lost); EXPECT_EQ(PacketsToBytes(1), sampler_.total_bytes_lost()); send_time_state = LosePacket(3); EXPECT_EQ(PacketsToBytes(3), send_time_state.total_bytes_sent); EXPECT_EQ(0u, send_time_state.total_bytes_acked); EXPECT_EQ(0u, send_time_state.total_bytes_lost); EXPECT_EQ(PacketsToBytes(2), sampler_.total_bytes_lost()); for (int i = 6; i <= 10; i++) { SendPacket(i); EXPECT_EQ(PacketsToBytes(i), sampler_.total_bytes_sent()); clock_.AdvanceTime(time_between_packets); } QuicPacketCount acked_packet_count = 1; EXPECT_EQ(PacketsToBytes(acked_packet_count), sampler_.total_bytes_acked()); for (int i = 4; i <= 10; i++) { send_time_state = AckPacketInner(i).state_at_send; ++acked_packet_count; EXPECT_EQ(PacketsToBytes(acked_packet_count), sampler_.total_bytes_acked()); EXPECT_EQ(PacketsToBytes(i), send_time_state.total_bytes_sent); if (i <= 5) { EXPECT_EQ(0u, send_time_state.total_bytes_acked); EXPECT_EQ(0u, send_time_state.total_bytes_lost); } else { EXPECT_EQ(PacketsToBytes(1), send_time_state.total_bytes_acked); EXPECT_EQ(PacketsToBytes(2), send_time_state.total_bytes_lost); } EXPECT_EQ(send_time_state.total_bytes_sent - send_time_state.total_bytes_acked - send_time_state.total_bytes_lost, send_time_state.bytes_in_flight); clock_.AdvanceTime(time_between_packets); } } TEST_P(BandwidthSamplerTest, SendPaced) { const QuicTime::Delta time_between_packets = QuicTime::Delta::FromMilliseconds(1); QuicBandwidth expected_bandwidth = QuicBandwidth::FromKBytesPerSecond(kRegularPacketSize); Send40PacketsAndAckFirst20(time_between_packets); QuicBandwidth last_bandwidth = QuicBandwidth::Zero(); for (int i = 21; i <= 40; i++) { last_bandwidth = AckPacket(i); EXPECT_EQ(expected_bandwidth, last_bandwidth) << "i is " << i; clock_.AdvanceTime(time_between_packets); } sampler_.RemoveObsoletePackets(QuicPacketNumber(41)); EXPECT_EQ(0u, BandwidthSamplerPeer::GetNumberOfTrackedPackets(sampler_)); EXPECT_EQ(0u, bytes_in_flight_); } TEST_P(BandwidthSamplerTest, SendWithLosses) { const QuicTime::Delta time_between_packets = QuicTime::Delta::FromMilliseconds(1); QuicBandwidth expected_bandwidth = QuicBandwidth::FromKBytesPerSecond(kRegularPacketSize) * 0.5; for (int i = 1; i <= 20; i++) { SendPacket(i); clock_.AdvanceTime(time_between_packets); } for (int i = 1; i <= 20; i++) { if (i % 2 == 0) { AckPacket(i); } else { LosePacket(i); } SendPacket(i + 20); clock_.AdvanceTime(time_between_packets); } QuicBandwidth last_bandwidth = QuicBandwidth::Zero(); for (int i = 21; i <= 40; i++) { if (i % 2 == 0) { last_bandwidth = AckPacket(i); EXPECT_EQ(expected_bandwidth, last_bandwidth); } else { LosePacket(i); } clock_.AdvanceTime(time_between_packets); } sampler_.RemoveObsoletePackets(QuicPacketNumber(41)); EXPECT_EQ(0u, BandwidthSamplerPeer::GetNumberOfTrackedPackets(sampler_)); EXPECT_EQ(0u, bytes_in_flight_); } TEST_P(BandwidthSamplerTest, NotCongestionControlled) { const QuicTime::Delta time_between_packets = QuicTime::Delta::FromMilliseconds(1); QuicBandwidth expected_bandwidth = QuicBandwidth::FromKBytesPerSecond(kRegularPacketSize) * 0.5; for (int i = 1; i <= 20; i++) { SendPacketInner( i, kRegularPacketSize, i % 2 == 0 ? HAS_RETRANSMITTABLE_DATA : NO_RETRANSMITTABLE_DATA); clock_.AdvanceTime(time_between_packets); } EXPECT_EQ(10u, BandwidthSamplerPeer::GetNumberOfTrackedPackets(sampler_)); for (int i = 1; i <= 20; i++) { if (i % 2 == 0) { AckPacket(i); } SendPacketInner( i + 20, kRegularPacketSize, i % 2 == 0 ? HAS_RETRANSMITTABLE_DATA : NO_RETRANSMITTABLE_DATA); clock_.AdvanceTime(time_between_packets); } QuicBandwidth last_bandwidth = QuicBandwidth::Zero(); for (int i = 21; i <= 40; i++) { if (i % 2 == 0) { last_bandwidth = AckPacket(i); EXPECT_EQ(expected_bandwidth, last_bandwidth); } clock_.AdvanceTime(time_between_packets); } sampler_.RemoveObsoletePackets(QuicPacketNumber(41)); EXPECT_EQ(0u, BandwidthSamplerPeer::GetNumberOfTrackedPackets(sampler_)); EXPECT_EQ(0u, bytes_in_flight_); } TEST_P(BandwidthSamplerTest, CompressedAck) { const QuicTime::Delta time_between_packets = QuicTime::Delta::FromMilliseconds(1); QuicBandwidth expected_bandwidth = QuicBandwidth::FromKBytesPerSecond(kRegularPacketSize); Send40PacketsAndAckFirst20(time_between_packets); clock_.AdvanceTime(time_between_packets * 15); QuicBandwidth last_bandwidth = QuicBandwidth::Zero(); QuicTime::Delta ridiculously_small_time_delta = QuicTime::Delta::FromMicroseconds(20); for (int i = 21; i <= 40; i++) { last_bandwidth = AckPacket(i); clock_.AdvanceTime(ridiculously_small_time_delta); } EXPECT_EQ(expected_bandwidth, last_bandwidth); sampler_.RemoveObsoletePackets(QuicPacketNumber(41)); EXPECT_EQ(0u, BandwidthSamplerPeer::GetNumberOfTrackedPackets(sampler_)); EXPECT_EQ(0u, bytes_in_flight_); } TEST_P(BandwidthSamplerTest, ReorderedAck) { const QuicTime::Delta time_between_packets = QuicTime::Delta::FromMilliseconds(1); QuicBandwidth expected_bandwidth = QuicBandwidth::FromKBytesPerSecond(kRegularPacketSize); Send40PacketsAndAckFirst20(time_between_packets); QuicBandwidth last_bandwidth = QuicBandwidth::Zero(); for (int i = 0; i < 20; i++) { last_bandwidth = AckPacket(40 - i); EXPECT_EQ(expected_bandwidth, last_bandwidth); SendPacket(41 + i); clock_.AdvanceTime(time_between_packets); } for (int i = 41; i <= 60; i++) { last_bandwidth = AckPacket(i); EXPECT_EQ(expected_bandwidth, last_bandwidth); clock_.AdvanceTime(time_between_packets); } sampler_.RemoveObsoletePackets(QuicPacketNumber(61)); EXPECT_EQ(0u, BandwidthSamplerPeer::GetNumberOfTrackedPackets(sampler_)); EXPECT_EQ(0u, bytes_in_flight_); } TEST_P(BandwidthSamplerTest, AppLimited) { const QuicTime::Delta time_between_packets = QuicTime::Delta::FromMilliseconds(1); QuicBandwidth expected_bandwidth = QuicBandwidth::FromKBytesPerSecond(kRegularPacketSize); for (int i = 1; i <= 20; i++) { SendPacket(i); clock_.AdvanceTime(time_between_packets); } for (int i = 1; i <= 20; i++) { BandwidthSample sample = AckPacketInner(i); EXPECT_EQ(sample.state_at_send.is_app_limited, sampler_app_limited_at_start_); SendPacket(i + 20); clock_.AdvanceTime(time_between_packets); } sampler_.OnAppLimited(); for (int i = 21; i <= 40; i++) { BandwidthSample sample = AckPacketInner(i); EXPECT_FALSE(sample.state_at_send.is_app_limited); EXPECT_EQ(expected_bandwidth, sample.bandwidth); clock_.AdvanceTime(time_between_packets); } clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1)); for (int i = 41; i <= 60; i++) { SendPacket(i); clock_.AdvanceTime(time_between_packets); } for (int i = 41; i <= 60; i++) { BandwidthSample sample = AckPacketInner(i); EXPECT_TRUE(sample.state_at_send.is_app_limited); EXPECT_LT(sample.bandwidth, 0.7f * expected_bandwidth); SendPacket(i + 20); clock_.AdvanceTime(time_between_packets); } for (int i = 61; i <= 80; i++) { BandwidthSample sample = AckPacketInner(i); EXPECT_FALSE(sample.state_at_send.is_app_limited); EXPECT_EQ(sample.bandwidth, expected_bandwidth); clock_.AdvanceTime(time_between_packets); } sampler_.RemoveObsoletePackets(QuicPacketNumber(81)); EXPECT_EQ(0u, BandwidthSamplerPeer::GetNumberOfTrackedPackets(sampler_)); EXPECT_EQ(0u, bytes_in_flight_); } TEST_P(BandwidthSamplerTest, FirstRoundTrip) { const QuicTime::Delta time_between_packets = QuicTime::Delta::FromMilliseconds(1); const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(800); const int num_packets = 10; const QuicByteCount num_bytes = kRegularPacketSize * num_packets; const QuicBandwidth real_bandwidth = QuicBandwidth::FromBytesAndTimeDelta(num_bytes, rtt); for (int i = 1; i <= 10; i++) { SendPacket(i); clock_.AdvanceTime(time_between_packets); } clock_.AdvanceTime(rtt - num_packets * time_between_packets); QuicBandwidth last_sample = QuicBandwidth::Zero(); for (int i = 1; i <= 10; i++) { QuicBandwidth sample = AckPacket(i); EXPECT_GT(sample, last_sample); last_sample = sample; clock_.AdvanceTime(time_between_packets); } EXPECT_LT(last_sample, real_bandwidth); EXPECT_GT(last_sample, 0.9f * real_bandwidth); } TEST_P(BandwidthSamplerTest, RemoveObsoletePackets) { SendPacket(1); SendPacket(2); SendPacket(3); SendPacket(4); SendPacket(5); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100)); EXPECT_EQ(5u, BandwidthSamplerPeer::GetNumberOfTrackedPackets(sampler_)); sampler_.RemoveObsoletePackets(QuicPacketNumber(4)); EXPECT_EQ(2u, BandwidthSamplerPeer::GetNumberOfTrackedPackets(sampler_)); LosePacket(4); sampler_.RemoveObsoletePackets(QuicPacketNumber(5)); EXPECT_EQ(1u, BandwidthSamplerPeer::GetNumberOfTrackedPackets(sampler_)); AckPacket(5); sampler_.RemoveObsoletePackets(QuicPacketNumber(6)); EXPECT_EQ(0u, BandwidthSamplerPeer::GetNumberOfTrackedPackets(sampler_)); } TEST_P(BandwidthSamplerTest, NeuterPacket) { SendPacket(1); EXPECT_EQ(0u, sampler_.total_bytes_neutered()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10)); sampler_.OnPacketNeutered(QuicPacketNumber(1)); EXPECT_LT(0u, sampler_.total_bytes_neutered()); EXPECT_EQ(0u, sampler_.total_bytes_acked()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10)); BandwidthSampler::CongestionEventSample sample = sampler_.OnCongestionEvent( clock_.Now(), {AckedPacket(QuicPacketNumber(1), kRegularPacketSize, clock_.Now())}, {}, max_bandwidth_, est_bandwidth_upper_bound_, round_trip_count_); EXPECT_EQ(0u, sampler_.total_bytes_acked()); EXPECT_EQ(QuicBandwidth::Zero(), sample.sample_max_bandwidth); EXPECT_FALSE(sample.sample_is_app_limited); EXPECT_EQ(QuicTime::Delta::Infinite(), sample.sample_rtt); EXPECT_EQ(0u, sample.sample_max_inflight); EXPECT_EQ(0u, sample.extra_acked); } TEST_P(BandwidthSamplerTest, CongestionEventSampleDefaultValues) { BandwidthSampler::CongestionEventSample sample; EXPECT_EQ(QuicBandwidth::Zero(), sample.sample_max_bandwidth); EXPECT_FALSE(sample.sample_is_app_limited); EXPECT_EQ(QuicTime::Delta::Infinite(), sample.sample_rtt); EXPECT_EQ(0u, sample.sample_max_inflight); EXPECT_EQ(0u, sample.extra_acked); } TEST_P(BandwidthSamplerTest, TwoAckedPacketsPerEvent) { QuicTime::Delta time_between_packets = QuicTime::Delta::FromMilliseconds(10); QuicBandwidth sending_rate = QuicBandwidth::FromBytesAndTimeDelta( kRegularPacketSize, time_between_packets); for (uint64_t i = 1; i < 21; i++) { SendPacket(i); clock_.AdvanceTime(time_between_packets); if (i % 2 != 0) { continue; } BandwidthSampler::CongestionEventSample sample = OnCongestionEvent({i - 1, i}, {}); EXPECT_EQ(sending_rate, sample.sample_max_bandwidth); EXPECT_EQ(time_between_packets, sample.sample_rtt); EXPECT_EQ(2 * kRegularPacketSize, sample.sample_max_inflight); EXPECT_TRUE(sample.last_packet_send_state.is_valid); EXPECT_EQ(2 * kRegularPacketSize, sample.last_packet_send_state.bytes_in_flight); EXPECT_EQ(i * kRegularPacketSize, sample.last_packet_send_state.total_bytes_sent); EXPECT_EQ((i - 2) * kRegularPacketSize, sample.last_packet_send_state.total_bytes_acked); EXPECT_EQ(0u, sample.last_packet_send_state.total_bytes_lost); sampler_.RemoveObsoletePackets(QuicPacketNumber(i - 2)); } } TEST_P(BandwidthSamplerTest, LoseEveryOtherPacket) { QuicTime::Delta time_between_packets = QuicTime::Delta::FromMilliseconds(10); QuicBandwidth sending_rate = QuicBandwidth::FromBytesAndTimeDelta( kRegularPacketSize, time_between_packets); for (uint64_t i = 1; i < 21; i++) { SendPacket(i); clock_.AdvanceTime(time_between_packets); if (i % 2 != 0) { continue; } BandwidthSampler::CongestionEventSample sample = OnCongestionEvent({i}, {i - 1}); EXPECT_EQ(sending_rate, sample.sample_max_bandwidth * 2); EXPECT_EQ(time_between_packets, sample.sample_rtt); EXPECT_EQ(kRegularPacketSize, sample.sample_max_inflight); EXPECT_TRUE(sample.last_packet_send_state.is_valid); EXPECT_EQ(2 * kRegularPacketSize, sample.last_packet_send_state.bytes_in_flight); EXPECT_EQ(i * kRegularPacketSize, sample.last_packet_send_state.total_bytes_sent); EXPECT_EQ((i - 2) * kRegularPacketSize / 2, sample.last_packet_send_state.total_bytes_acked); EXPECT_EQ((i - 2) * kRegularPacketSize / 2, sample.last_packet_send_state.total_bytes_lost); sampler_.RemoveObsoletePackets(QuicPacketNumber(i - 2)); } } TEST_P(BandwidthSamplerTest, AckHeightRespectBandwidthEstimateUpperBound) { QuicTime::Delta time_between_packets = QuicTime::Delta::FromMilliseconds(10); QuicBandwidth first_packet_sending_rate = QuicBandwidth::FromBytesAndTimeDelta(kRegularPacketSize, time_between_packets); SendPacket(1); clock_.AdvanceTime(time_between_packets); SendPacket(2); SendPacket(3); SendPacket(4); BandwidthSampler::CongestionEventSample sample = OnCongestionEvent({1}, {}); EXPECT_EQ(first_packet_sending_rate, sample.sample_max_bandwidth); EXPECT_EQ(first_packet_sending_rate, max_bandwidth_); round_trip_count_++; est_bandwidth_upper_bound_ = first_packet_sending_rate * 0.3; clock_.AdvanceTime(time_between_packets); sample = OnCongestionEvent({2, 3, 4}, {}); EXPECT_EQ(first_packet_sending_rate * 2, sample.sample_max_bandwidth); EXPECT_EQ(max_bandwidth_, sample.sample_max_bandwidth); EXPECT_LT(2 * kRegularPacketSize, sample.extra_acked); } class MaxAckHeightTrackerTest : public QuicTest { protected: MaxAckHeightTrackerTest() : tracker_(10) { tracker_.SetAckAggregationBandwidthThreshold(1.8); tracker_.SetStartNewAggregationEpochAfterFullRound(true); } void AggregationEpisode(QuicBandwidth aggregation_bandwidth, QuicTime::Delta aggregation_duration, QuicByteCount bytes_per_ack, bool expect_new_aggregation_epoch) { ASSERT_GE(aggregation_bandwidth, bandwidth_); const QuicTime start_time = now_; const QuicByteCount aggregation_bytes = aggregation_bandwidth * aggregation_duration; const int num_acks = aggregation_bytes / bytes_per_ack; ASSERT_EQ(aggregation_bytes, num_acks * bytes_per_ack) << "aggregation_bytes: " << aggregation_bytes << " [" << aggregation_bandwidth << " in " << aggregation_duration << "], bytes_per_ack: " << bytes_per_ack; const QuicTime::Delta time_between_acks = QuicTime::Delta::FromMicroseconds( aggregation_duration.ToMicroseconds() / num_acks); ASSERT_EQ(aggregation_duration, num_acks * time_between_acks) << "aggregation_bytes: " << aggregation_bytes << ", num_acks: " << num_acks << ", time_between_acks: " << time_between_acks; const QuicTime::Delta total_duration = QuicTime::Delta::FromMicroseconds( aggregation_bytes * 8 * 1000000 / bandwidth_.ToBitsPerSecond()); ASSERT_EQ(aggregation_bytes, total_duration * bandwidth_) << "total_duration: " << total_duration << ", bandwidth_: " << bandwidth_; QuicByteCount last_extra_acked = 0; for (QuicByteCount bytes = 0; bytes < aggregation_bytes; bytes += bytes_per_ack) { QuicByteCount extra_acked = tracker_.Update( bandwidth_, true, RoundTripCount(), last_sent_packet_number_, last_acked_packet_number_, now_, bytes_per_ack); QUIC_VLOG(1) << "T" << now_ << ": Update after " << bytes_per_ack << " bytes acked, " << extra_acked << " extra bytes acked"; if ((bytes == 0 && expect_new_aggregation_epoch) || (aggregation_bandwidth == bandwidth_)) { EXPECT_EQ(0u, extra_acked); } else { EXPECT_LT(last_extra_acked, extra_acked); } now_ = now_ + time_between_acks; last_extra_acked = extra_acked; } const QuicTime time_after_aggregation = now_; now_ = start_time + total_duration; QUIC_VLOG(1) << "Advanced time from " << time_after_aggregation << " to " << now_ << ". Aggregation time[" << (time_after_aggregation - start_time) << "], Quiet time[" << (now_ - time_after_aggregation) << "]."; } QuicRoundTripCount RoundTripCount() const { return (now_ - QuicTime::Zero()).ToMicroseconds() / rtt_.ToMicroseconds(); } MaxAckHeightTracker tracker_; QuicBandwidth bandwidth_ = QuicBandwidth::FromBytesPerSecond(10 * 1000); QuicTime now_ = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1); QuicTime::Delta rtt_ = QuicTime::Delta::FromMilliseconds(60); QuicPacketNumber last_sent_packet_number_; QuicPacketNumber last_acked_packet_number_; }; TEST_F(MaxAckHeightTrackerTest, VeryAggregatedLargeAck) { AggregationEpisode(bandwidth_ * 20, QuicTime::Delta::FromMilliseconds(6), 1200, true); AggregationEpisode(bandwidth_ * 20, QuicTime::Delta::FromMilliseconds(6), 1200, true); now_ = now_ - QuicTime::Delta::FromMilliseconds(1); if (tracker_.ack_aggregation_bandwidth_threshold() > 1.1) { AggregationEpisode(bandwidth_ * 20, QuicTime::Delta::FromMilliseconds(6), 1200, true); EXPECT_EQ(3u, tracker_.num_ack_aggregation_epochs()); } else { AggregationEpisode(bandwidth_ * 20, QuicTime::Delta::FromMilliseconds(6), 1200, false); EXPECT_EQ(2u, tracker_.num_ack_aggregation_epochs()); } } TEST_F(MaxAckHeightTrackerTest, VeryAggregatedSmallAcks) { AggregationEpisode(bandwidth_ * 20, QuicTime::Delta::FromMilliseconds(6), 300, true); AggregationEpisode(bandwidth_ * 20, QuicTime::Delta::FromMilliseconds(6), 300, true); now_ = now_ - QuicTime::Delta::FromMilliseconds(1); if (tracker_.ack_aggregation_bandwidth_threshold() > 1.1) { AggregationEpisode(bandwidth_ * 20, QuicTime::Delta::FromMilliseconds(6), 300, true); EXPECT_EQ(3u, tracker_.num_ack_aggregation_epochs()); } else { AggregationEpisode(bandwidth_ * 20, QuicTime::Delta::FromMilliseconds(6), 300, false); EXPECT_EQ(2u, tracker_.num_ack_aggregation_epochs()); } } TEST_F(MaxAckHeightTrackerTest, SomewhatAggregatedLargeAck) { AggregationEpisode(bandwidth_ * 2, QuicTime::Delta::FromMilliseconds(50), 1000, true); AggregationEpisode(bandwidth_ * 2, QuicTime::Delta::FromMilliseconds(50), 1000, true); now_ = now_ - QuicTime::Delta::FromMilliseconds(1); if (tracker_.ack_aggregation_bandwidth_threshold() > 1.1) { AggregationEpisode(bandwidth_ * 2, QuicTime::Delta::FromMilliseconds(50),
322
cpp
google/quiche
prr_sender
quiche/quic/core/congestion_control/prr_sender.cc
quiche/quic/core/congestion_control/prr_sender_test.cc
#ifndef QUICHE_QUIC_CORE_CONGESTION_CONTROL_PRR_SENDER_H_ #define QUICHE_QUIC_CORE_CONGESTION_CONTROL_PRR_SENDER_H_ #include "quiche/quic/core/quic_bandwidth.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT PrrSender { public: PrrSender(); void OnPacketLost(QuicByteCount prior_in_flight); void OnPacketSent(QuicByteCount sent_bytes); void OnPacketAcked(QuicByteCount acked_bytes); bool CanSend(QuicByteCount congestion_window, QuicByteCount bytes_in_flight, QuicByteCount slowstart_threshold) const; private: QuicByteCount bytes_sent_since_loss_; QuicByteCount bytes_delivered_since_loss_; size_t ack_count_since_loss_; QuicByteCount bytes_in_flight_before_loss_; }; } #endif #include "quiche/quic/core/congestion_control/prr_sender.h" #include "quiche/quic/core/quic_packets.h" namespace quic { PrrSender::PrrSender() : bytes_sent_since_loss_(0), bytes_delivered_since_loss_(0), ack_count_since_loss_(0), bytes_in_flight_before_loss_(0) {} void PrrSender::OnPacketSent(QuicByteCount sent_bytes) { bytes_sent_since_loss_ += sent_bytes; } void PrrSender::OnPacketLost(QuicByteCount prior_in_flight) { bytes_sent_since_loss_ = 0; bytes_in_flight_before_loss_ = prior_in_flight; bytes_delivered_since_loss_ = 0; ack_count_since_loss_ = 0; } void PrrSender::OnPacketAcked(QuicByteCount acked_bytes) { bytes_delivered_since_loss_ += acked_bytes; ++ack_count_since_loss_; } bool PrrSender::CanSend(QuicByteCount congestion_window, QuicByteCount bytes_in_flight, QuicByteCount slowstart_threshold) const { if (bytes_sent_since_loss_ == 0 || bytes_in_flight < kMaxSegmentSize) { return true; } if (congestion_window > bytes_in_flight) { if (bytes_delivered_since_loss_ + ack_count_since_loss_ * kMaxSegmentSize <= bytes_sent_since_loss_) { return false; } return true; } if (bytes_delivered_since_loss_ * slowstart_threshold > bytes_sent_since_loss_ * bytes_in_flight_before_loss_) { return true; } return false; } }
#include "quiche/quic/core/congestion_control/prr_sender.h" #include <algorithm> #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { namespace { const QuicByteCount kMaxSegmentSize = kDefaultTCPMSS; } class PrrSenderTest : public QuicTest {}; TEST_F(PrrSenderTest, SingleLossResultsInSendOnEveryOtherAck) { PrrSender prr; QuicPacketCount num_packets_in_flight = 50; QuicByteCount bytes_in_flight = num_packets_in_flight * kMaxSegmentSize; const QuicPacketCount ssthresh_after_loss = num_packets_in_flight / 2; const QuicByteCount congestion_window = ssthresh_after_loss * kMaxSegmentSize; prr.OnPacketLost(bytes_in_flight); prr.OnPacketAcked(kMaxSegmentSize); bytes_in_flight -= kMaxSegmentSize; EXPECT_TRUE(prr.CanSend(congestion_window, bytes_in_flight, ssthresh_after_loss * kMaxSegmentSize)); prr.OnPacketSent(kMaxSegmentSize); EXPECT_FALSE(prr.CanSend(congestion_window, bytes_in_flight, ssthresh_after_loss * kMaxSegmentSize)); for (uint64_t i = 0; i < ssthresh_after_loss - 1; ++i) { prr.OnPacketAcked(kMaxSegmentSize); bytes_in_flight -= kMaxSegmentSize; EXPECT_FALSE(prr.CanSend(congestion_window, bytes_in_flight, ssthresh_after_loss * kMaxSegmentSize)); prr.OnPacketAcked(kMaxSegmentSize); bytes_in_flight -= kMaxSegmentSize; EXPECT_TRUE(prr.CanSend(congestion_window, bytes_in_flight, ssthresh_after_loss * kMaxSegmentSize)); prr.OnPacketSent(kMaxSegmentSize); bytes_in_flight += kMaxSegmentSize; } EXPECT_EQ(congestion_window, bytes_in_flight); for (int i = 0; i < 10; ++i) { prr.OnPacketAcked(kMaxSegmentSize); bytes_in_flight -= kMaxSegmentSize; EXPECT_TRUE(prr.CanSend(congestion_window, bytes_in_flight, ssthresh_after_loss * kMaxSegmentSize)); prr.OnPacketSent(kMaxSegmentSize); bytes_in_flight += kMaxSegmentSize; EXPECT_EQ(congestion_window, bytes_in_flight); EXPECT_FALSE(prr.CanSend(congestion_window, bytes_in_flight, ssthresh_after_loss * kMaxSegmentSize)); } } TEST_F(PrrSenderTest, BurstLossResultsInSlowStart) { PrrSender prr; QuicByteCount bytes_in_flight = 20 * kMaxSegmentSize; const QuicPacketCount num_packets_lost = 13; const QuicPacketCount ssthresh_after_loss = 10; const QuicByteCount congestion_window = ssthresh_after_loss * kMaxSegmentSize; bytes_in_flight -= num_packets_lost * kMaxSegmentSize; prr.OnPacketLost(bytes_in_flight); for (int i = 0; i < 3; ++i) { prr.OnPacketAcked(kMaxSegmentSize); bytes_in_flight -= kMaxSegmentSize; for (int j = 0; j < 2; ++j) { EXPECT_TRUE(prr.CanSend(congestion_window, bytes_in_flight, ssthresh_after_loss * kMaxSegmentSize)); prr.OnPacketSent(kMaxSegmentSize); bytes_in_flight += kMaxSegmentSize; } EXPECT_FALSE(prr.CanSend(congestion_window, bytes_in_flight, ssthresh_after_loss * kMaxSegmentSize)); } for (int i = 0; i < 10; ++i) { prr.OnPacketAcked(kMaxSegmentSize); bytes_in_flight -= kMaxSegmentSize; EXPECT_TRUE(prr.CanSend(congestion_window, bytes_in_flight, ssthresh_after_loss * kMaxSegmentSize)); prr.OnPacketSent(kMaxSegmentSize); bytes_in_flight += kMaxSegmentSize; } } } }
323
cpp
google/quiche
pacing_sender
quiche/quic/core/congestion_control/pacing_sender.cc
quiche/quic/core/congestion_control/pacing_sender_test.cc
#ifndef QUICHE_QUIC_CORE_CONGESTION_CONTROL_PACING_SENDER_H_ #define QUICHE_QUIC_CORE_CONGESTION_CONTROL_PACING_SENDER_H_ #include <cstdint> #include <map> #include <memory> #include "quiche/quic/core/congestion_control/send_algorithm_interface.h" #include "quiche/quic/core/quic_bandwidth.h" #include "quiche/quic/core/quic_config.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { namespace test { class QuicSentPacketManagerPeer; } class QUICHE_EXPORT PacingSender { public: PacingSender(); PacingSender(const PacingSender&) = delete; PacingSender& operator=(const PacingSender&) = delete; ~PacingSender(); void set_sender(SendAlgorithmInterface* sender); void set_max_pacing_rate(QuicBandwidth max_pacing_rate) { max_pacing_rate_ = max_pacing_rate; } void set_remove_non_initial_burst() { remove_non_initial_burst_ = true; } QuicBandwidth max_pacing_rate() const { return max_pacing_rate_; } void OnCongestionEvent(bool rtt_updated, QuicByteCount bytes_in_flight, QuicTime event_time, const AckedPacketVector& acked_packets, const LostPacketVector& lost_packets, QuicPacketCount num_ect, QuicPacketCount num_ce); void OnPacketSent(QuicTime sent_time, QuicByteCount bytes_in_flight, QuicPacketNumber packet_number, QuicByteCount bytes, HasRetransmittableData has_retransmittable_data); void OnApplicationLimited(); void SetBurstTokens(uint32_t burst_tokens); QuicTime::Delta TimeUntilSend(QuicTime now, QuicByteCount bytes_in_flight) const; QuicBandwidth PacingRate(QuicByteCount bytes_in_flight) const; NextReleaseTimeResult GetNextReleaseTime() const { bool allow_burst = (burst_tokens_ > 0 || lumpy_tokens_ > 0); return {ideal_next_packet_send_time_, allow_burst}; } uint32_t initial_burst_size() const { return initial_burst_size_; } protected: uint32_t lumpy_tokens() const { return lumpy_tokens_; } private: friend class test::QuicSentPacketManagerPeer; SendAlgorithmInterface* sender_; QuicBandwidth max_pacing_rate_; uint32_t burst_tokens_; QuicTime ideal_next_packet_send_time_; uint32_t initial_burst_size_; uint32_t lumpy_tokens_; bool pacing_limited_; bool remove_non_initial_burst_ = GetQuicReloadableFlag(quic_pacing_remove_non_initial_burst); }; } #endif #include "quiche/quic/core/congestion_control/pacing_sender.h" #include <algorithm> #include "quiche/quic/core/quic_bandwidth.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { namespace { static const uint32_t kInitialUnpacedBurst = 10; } PacingSender::PacingSender() : sender_(nullptr), max_pacing_rate_(QuicBandwidth::Zero()), burst_tokens_(kInitialUnpacedBurst), ideal_next_packet_send_time_(QuicTime::Zero()), initial_burst_size_(kInitialUnpacedBurst), lumpy_tokens_(0), pacing_limited_(false) {} PacingSender::~PacingSender() {} void PacingSender::set_sender(SendAlgorithmInterface* sender) { QUICHE_DCHECK(sender != nullptr); sender_ = sender; } void PacingSender::OnCongestionEvent(bool rtt_updated, QuicByteCount bytes_in_flight, QuicTime event_time, const AckedPacketVector& acked_packets, const LostPacketVector& lost_packets, QuicPacketCount num_ect, QuicPacketCount num_ce) { QUICHE_DCHECK(sender_ != nullptr); if (!lost_packets.empty()) { burst_tokens_ = 0; } sender_->OnCongestionEvent(rtt_updated, bytes_in_flight, event_time, acked_packets, lost_packets, num_ect, num_ce); } void PacingSender::OnPacketSent( QuicTime sent_time, QuicByteCount bytes_in_flight, QuicPacketNumber packet_number, QuicByteCount bytes, HasRetransmittableData has_retransmittable_data) { QUICHE_DCHECK(sender_ != nullptr); QUIC_DVLOG(3) << "Packet " << packet_number << " with " << bytes << " bytes sent at " << sent_time << ". bytes_in_flight: " << bytes_in_flight; sender_->OnPacketSent(sent_time, bytes_in_flight, packet_number, bytes, has_retransmittable_data); if (has_retransmittable_data != HAS_RETRANSMITTABLE_DATA) { return; } if (remove_non_initial_burst_) { QUIC_RELOADABLE_FLAG_COUNT_N(quic_pacing_remove_non_initial_burst, 1, 2); } else { if (bytes_in_flight == 0 && !sender_->InRecovery()) { burst_tokens_ = std::min(initial_burst_size_, static_cast<uint32_t>(sender_->GetCongestionWindow() / kDefaultTCPMSS)); } } if (burst_tokens_ > 0) { --burst_tokens_; ideal_next_packet_send_time_ = QuicTime::Zero(); pacing_limited_ = false; return; } QuicTime::Delta delay = PacingRate(bytes_in_flight + bytes).TransferTime(bytes); if (!pacing_limited_ || lumpy_tokens_ == 0) { lumpy_tokens_ = std::max( 1u, std::min(static_cast<uint32_t>(GetQuicFlag(quic_lumpy_pacing_size)), static_cast<uint32_t>( (sender_->GetCongestionWindow() * GetQuicFlag(quic_lumpy_pacing_cwnd_fraction)) / kDefaultTCPMSS))); if (sender_->BandwidthEstimate() < QuicBandwidth::FromKBitsPerSecond( GetQuicFlag(quic_lumpy_pacing_min_bandwidth_kbps))) { lumpy_tokens_ = 1u; } if ((bytes_in_flight + bytes) >= sender_->GetCongestionWindow()) { lumpy_tokens_ = 1u; } } --lumpy_tokens_; if (pacing_limited_) { ideal_next_packet_send_time_ = ideal_next_packet_send_time_ + delay; } else { ideal_next_packet_send_time_ = std::max(ideal_next_packet_send_time_ + delay, sent_time + delay); } pacing_limited_ = sender_->CanSend(bytes_in_flight + bytes); } void PacingSender::OnApplicationLimited() { pacing_limited_ = false; } void PacingSender::SetBurstTokens(uint32_t burst_tokens) { initial_burst_size_ = burst_tokens; burst_tokens_ = std::min( initial_burst_size_, static_cast<uint32_t>(sender_->GetCongestionWindow() / kDefaultTCPMSS)); } QuicTime::Delta PacingSender::TimeUntilSend( QuicTime now, QuicByteCount bytes_in_flight) const { QUICHE_DCHECK(sender_ != nullptr); if (!sender_->CanSend(bytes_in_flight)) { return QuicTime::Delta::Infinite(); } if (remove_non_initial_burst_) { QUIC_RELOADABLE_FLAG_COUNT_N(quic_pacing_remove_non_initial_burst, 2, 2); if (burst_tokens_ > 0 || lumpy_tokens_ > 0) { QUIC_DVLOG(1) << "Can send packet now. burst_tokens:" << burst_tokens_ << ", lumpy_tokens:" << lumpy_tokens_; return QuicTime::Delta::Zero(); } } else { if (burst_tokens_ > 0 || bytes_in_flight == 0 || lumpy_tokens_ > 0) { QUIC_DVLOG(1) << "Sending packet now. burst_tokens:" << burst_tokens_ << ", bytes_in_flight:" << bytes_in_flight << ", lumpy_tokens:" << lumpy_tokens_; return QuicTime::Delta::Zero(); } } if (ideal_next_packet_send_time_ > now + kAlarmGranularity) { QUIC_DVLOG(1) << "Delaying packet: " << (ideal_next_packet_send_time_ - now).ToMicroseconds(); return ideal_next_packet_send_time_ - now; } QUIC_DVLOG(1) << "Can send packet now. ideal_next_packet_send_time: " << ideal_next_packet_send_time_ << ", now: " << now; return QuicTime::Delta::Zero(); } QuicBandwidth PacingSender::PacingRate(QuicByteCount bytes_in_flight) const { QUICHE_DCHECK(sender_ != nullptr); if (!max_pacing_rate_.IsZero()) { return QuicBandwidth::FromBitsPerSecond( std::min(max_pacing_rate_.ToBitsPerSecond(), sender_->PacingRate(bytes_in_flight).ToBitsPerSecond())); } return sender_->PacingRate(bytes_in_flight); } }
#include "quiche/quic/core/congestion_control/pacing_sender.h" #include <memory> #include <utility> #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_clock.h" #include "quiche/quic/test_tools/quic_test_utils.h" using testing::_; using testing::AtMost; using testing::Return; using testing::StrictMock; namespace quic { namespace test { const QuicByteCount kBytesInFlight = 1024; const int kInitialBurstPackets = 10; class TestPacingSender : public PacingSender { public: using PacingSender::lumpy_tokens; using PacingSender::PacingSender; QuicTime ideal_next_packet_send_time() const { return GetNextReleaseTime().release_time; } }; class PacingSenderTest : public QuicTest { protected: PacingSenderTest() : zero_time_(QuicTime::Delta::Zero()), infinite_time_(QuicTime::Delta::Infinite()), packet_number_(1), mock_sender_(new StrictMock<MockSendAlgorithm>()), pacing_sender_(new TestPacingSender) { pacing_sender_->set_sender(mock_sender_.get()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(9)); } ~PacingSenderTest() override {} void InitPacingRate(QuicPacketCount burst_size, QuicBandwidth bandwidth) { mock_sender_ = std::make_unique<StrictMock<MockSendAlgorithm>>(); pacing_sender_ = std::make_unique<TestPacingSender>(); pacing_sender_->set_sender(mock_sender_.get()); EXPECT_CALL(*mock_sender_, PacingRate(_)).WillRepeatedly(Return(bandwidth)); EXPECT_CALL(*mock_sender_, BandwidthEstimate()) .WillRepeatedly(Return(bandwidth)); if (burst_size == 0) { EXPECT_CALL(*mock_sender_, OnCongestionEvent(_, _, _, _, _, _, _)); LostPacketVector lost_packets; lost_packets.push_back( LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize)); AckedPacketVector empty; pacing_sender_->OnCongestionEvent(true, 1234, clock_.Now(), empty, lost_packets, 0, 0); } else if (burst_size != kInitialBurstPackets) { QUIC_LOG(FATAL) << "Unsupported burst_size " << burst_size << " specificied, only 0 and " << kInitialBurstPackets << " are supported."; } } void CheckPacketIsSentImmediately(HasRetransmittableData retransmittable_data, QuicByteCount prior_in_flight, bool in_recovery, QuicPacketCount cwnd) { for (int i = 0; i < 2; ++i) { EXPECT_CALL(*mock_sender_, CanSend(prior_in_flight)) .WillOnce(Return(true)); EXPECT_EQ(zero_time_, pacing_sender_->TimeUntilSend(clock_.Now(), prior_in_flight)) << "Next packet to send is " << packet_number_; } if (prior_in_flight == 0 && !GetQuicReloadableFlag(quic_pacing_remove_non_initial_burst)) { EXPECT_CALL(*mock_sender_, InRecovery()).WillOnce(Return(in_recovery)); } EXPECT_CALL(*mock_sender_, OnPacketSent(clock_.Now(), prior_in_flight, packet_number_, kMaxOutgoingPacketSize, retransmittable_data)); EXPECT_CALL(*mock_sender_, GetCongestionWindow()) .WillRepeatedly(Return(cwnd * kDefaultTCPMSS)); EXPECT_CALL(*mock_sender_, CanSend(prior_in_flight + kMaxOutgoingPacketSize)) .Times(AtMost(1)) .WillRepeatedly(Return((prior_in_flight + kMaxOutgoingPacketSize) < (cwnd * kDefaultTCPMSS))); pacing_sender_->OnPacketSent(clock_.Now(), prior_in_flight, packet_number_++, kMaxOutgoingPacketSize, retransmittable_data); } void CheckPacketIsSentImmediately() { CheckPacketIsSentImmediately(HAS_RETRANSMITTABLE_DATA, kBytesInFlight, false, 10); } void CheckPacketIsDelayed(QuicTime::Delta delay) { for (int i = 0; i < 2; ++i) { EXPECT_CALL(*mock_sender_, CanSend(kBytesInFlight)) .WillOnce(Return(true)); EXPECT_EQ(delay.ToMicroseconds(), pacing_sender_->TimeUntilSend(clock_.Now(), kBytesInFlight) .ToMicroseconds()); } } void UpdateRtt() { EXPECT_CALL(*mock_sender_, OnCongestionEvent(true, kBytesInFlight, _, _, _, _, _)); AckedPacketVector empty_acked; LostPacketVector empty_lost; pacing_sender_->OnCongestionEvent(true, kBytesInFlight, clock_.Now(), empty_acked, empty_lost, 0, 0); } void OnApplicationLimited() { pacing_sender_->OnApplicationLimited(); } const QuicTime::Delta zero_time_; const QuicTime::Delta infinite_time_; MockClock clock_; QuicPacketNumber packet_number_; std::unique_ptr<StrictMock<MockSendAlgorithm>> mock_sender_; std::unique_ptr<TestPacingSender> pacing_sender_; }; TEST_F(PacingSenderTest, NoSend) { for (int i = 0; i < 2; ++i) { EXPECT_CALL(*mock_sender_, CanSend(kBytesInFlight)).WillOnce(Return(false)); EXPECT_EQ(infinite_time_, pacing_sender_->TimeUntilSend(clock_.Now(), kBytesInFlight)); } } TEST_F(PacingSenderTest, SendNow) { for (int i = 0; i < 2; ++i) { EXPECT_CALL(*mock_sender_, CanSend(kBytesInFlight)).WillOnce(Return(true)); EXPECT_EQ(zero_time_, pacing_sender_->TimeUntilSend(clock_.Now(), kBytesInFlight)); } } TEST_F(PacingSenderTest, VariousSending) { InitPacingRate( 0, QuicBandwidth::FromBytesAndTimeDelta( kMaxOutgoingPacketSize, QuicTime::Delta::FromMilliseconds(1))); UpdateRtt(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(2)); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(4)); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(8)); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(8)); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); OnApplicationLimited(); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100)); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); CheckPacketIsSentImmediately(); } TEST_F(PacingSenderTest, InitialBurst) { InitPacingRate( 10, QuicBandwidth::FromBytesAndTimeDelta( kMaxOutgoingPacketSize, QuicTime::Delta::FromMilliseconds(1))); UpdateRtt(); for (int i = 0; i < kInitialBurstPackets; ++i) { CheckPacketIsSentImmediately(); } CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); if (GetQuicReloadableFlag(quic_pacing_remove_non_initial_burst)) { for (int i = 0; i < 6; ++i) { CheckPacketIsSentImmediately(); } CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(3)); return; } CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(HAS_RETRANSMITTABLE_DATA, 0, false, 10); for (int i = 0; i < kInitialBurstPackets - 1; ++i) { CheckPacketIsSentImmediately(); } CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); } TEST_F(PacingSenderTest, InitialBurstNoRttMeasurement) { InitPacingRate( 10, QuicBandwidth::FromBytesAndTimeDelta( kMaxOutgoingPacketSize, QuicTime::Delta::FromMilliseconds(1))); for (int i = 0; i < kInitialBurstPackets; ++i) { CheckPacketIsSentImmediately(); } CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); if (GetQuicReloadableFlag(quic_pacing_remove_non_initial_burst)) { for (int i = 0; i < 6; ++i) { CheckPacketIsSentImmediately(); } CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(3)); return; } CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(HAS_RETRANSMITTABLE_DATA, 0, false, 10); for (int i = 0; i < kInitialBurstPackets - 1; ++i) { CheckPacketIsSentImmediately(); } CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); } TEST_F(PacingSenderTest, FastSending) { InitPacingRate(10, QuicBandwidth::FromBytesAndTimeDelta( 2 * kMaxOutgoingPacketSize, QuicTime::Delta::FromMilliseconds(1))); UpdateRtt(); for (int i = 0; i < kInitialBurstPackets; ++i) { CheckPacketIsSentImmediately(); } CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMicroseconds(2000)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); if (GetQuicReloadableFlag(quic_pacing_remove_non_initial_burst)) { for (int i = 0; i < 10; ++i) { CheckPacketIsSentImmediately(); } CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); return; } CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(HAS_RETRANSMITTABLE_DATA, 0, false, 10); for (int i = 0; i < kInitialBurstPackets - 1; ++i) { CheckPacketIsSentImmediately(); } CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMicroseconds(2000)); } TEST_F(PacingSenderTest, NoBurstEnteringRecovery) { InitPacingRate( 0, QuicBandwidth::FromBytesAndTimeDelta( kMaxOutgoingPacketSize, QuicTime::Delta::FromMilliseconds(1))); CheckPacketIsSentImmediately(); LostPacketVector lost_packets; lost_packets.push_back( LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize)); AckedPacketVector empty_acked; EXPECT_CALL(*mock_sender_, OnCongestionEvent(true, kMaxOutgoingPacketSize, _, testing::IsEmpty(), _, _, _)); pacing_sender_->OnCongestionEvent(true, kMaxOutgoingPacketSize, clock_.Now(), empty_acked, lost_packets, 0, 0); CheckPacketIsSentImmediately(); EXPECT_CALL(*mock_sender_, CanSend(kMaxOutgoingPacketSize)) .WillOnce(Return(true)); EXPECT_EQ( QuicTime::Delta::FromMilliseconds(2), pacing_sender_->TimeUntilSend(clock_.Now(), kMaxOutgoingPacketSize)); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); } TEST_F(PacingSenderTest, NoBurstInRecovery) { InitPacingRate( 0, QuicBandwidth::FromBytesAndTimeDelta( kMaxOutgoingPacketSize, QuicTime::Delta::FromMilliseconds(1))); UpdateRtt(); CheckPacketIsSentImmediately(HAS_RETRANSMITTABLE_DATA, 0, true, 10); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); } TEST_F(PacingSenderTest, CwndLimited) { InitPacingRate( 0, QuicBandwidth::FromBytesAndTimeDelta( kMaxOutgoingPacketSize, QuicTime::Delta::FromMilliseconds(1))); UpdateRtt(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(2)); CheckPacketIsSentImmediately(HAS_RETRANSMITTABLE_DATA, 2 * kMaxOutgoingPacketSize, false, 2); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100)); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); } TEST_F(PacingSenderTest, LumpyPacingWithInitialBurstToken) { SetQuicFlag(quic_lumpy_pacing_size, 3); SetQuicFlag(quic_lumpy_pacing_cwnd_fraction, 0.5f); InitPacingRate( 10, QuicBandwidth::FromBytesAndTimeDelta( kMaxOutgoingPacketSize, QuicTime::Delta::FromMilliseconds(1))); UpdateRtt(); for (int i = 0; i < kInitialBurstPackets; ++i) { CheckPacketIsSentImmediately(); } CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(3)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3)); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(3)); OnApplicationLimited(); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100)); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(3)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3)); CheckPacketIsSentImmediately(); CheckPacketIsSentImmediately(HAS_RETRANSMITTABLE_DATA, 20 * kMaxOutgoingPacketSize, false, 20); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100)); CheckPacketIsSentImmediately(HAS_RETRANSMITTABLE_DATA, kBytesInFlight, false, 5); CheckPacketIsSentImmediately(); CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2)); } TEST_F(PacingSenderTest, NoLumpyPacingForLowBandwidthFlows) { SetQuicFlag(quic_lumpy_pacing_size, 3); SetQuicFlag(quic_lumpy_pacing_cwnd_fraction, 0.5f); QuicTime::Delta inter_packet_delay = QuicTime::Delta::FromMilliseconds(100); InitPacingRate(kInitialBurstPackets, QuicBandwidth::FromBytesAndTimeDelta(kMaxOutgoingPacketSize, inter_packet_delay)); UpdateRtt(); for (int i = 0; i < kInitialBurstPackets; ++i) { CheckPacketIsSentImmediately(); } CheckPacketIsSentImmediately(); for (int i = 0; i < 200; ++i) { CheckPacketIsDelayed(inter_packet_delay); } } TEST_F(PacingSenderTest, NoBurstsForLumpyPacingWithAckAggregation) { QuicTime::Delta inter_packet_delay = QuicTime::Delta::FromMilliseconds(1); InitPacingRate(kInitialBurstPackets, QuicBandwidth::FromBytesAndTimeDelta(kMaxOutgoingPacketSize, inter_packet_delay)); UpdateRtt(); for (int i = 0; i < kInitialBurstPackets; ++i) { CheckPacketIsSentImmediately(); } CheckPacketIsSentImmediately(HAS_RETRANSMITTABLE_DATA, 10 * kMaxOutgoingPacketSize, false, 10); EXPECT_EQ(0u, pacing_sender_->lumpy_tokens()); CheckPacketIsSentImmediately(HAS_RETRANSMITTABLE_DATA, 10 * kMaxOutgoingPacketSize, false, 10); EXPECT_EQ(0u, pacing_sender_->lumpy_tokens()); CheckPacketIsDelayed(2 * inter_packet_delay); } TEST_F(PacingSenderTest, IdealNextPacketSendTimeWithLumpyPacing) { SetQuicFlag(quic_lumpy_pacing_size, 3); SetQuicFlag(quic_lumpy_pacing_cwnd_fraction, 0.5f); QuicTime::Delta inter_packet_delay = QuicTime::Delta::FromMilliseconds(1); InitPacingRate(kInitialBurstPackets, QuicBandwidth::FromBytesAndTimeDelta(kMaxOutgoingPacketSize, inter_packet_delay)); for (int i = 0; i < kInitialBurstPackets; ++i) { CheckPacketIsSentImmediately(); } CheckPacketIsSentImmediately(); EXPECT_EQ(pacing_sender_->ideal_next_packet_send_time(), clock_.Now() + inter_packet_delay); EXPECT_EQ(pacing_sender_->lumpy_tokens(), 2u); CheckPacketIsSentImmediately(); EXPECT_EQ(pacing_sender_->ideal_next_packet_send_time(), clock_.Now() + 2 * inter_packet_delay); EXPECT_EQ(pacing_sender_->lumpy_tokens(), 1u); CheckPacketIsSentImmediately(); EXPECT_EQ(pacing_sender_->ideal_next_packet_send_time(), clock_.Now() + 3 * inter_packet_delay); EXPECT_EQ(pacing_sender_->lumpy_tokens(), 0u); CheckPacketIsDelayed(3 * inter_packet_delay); clock_.AdvanceTime(3 * inter_packet_delay); CheckPacketIsSentImmediately(); EXPECT_EQ(pacing_sender_->ideal_next_packet_send_time(), clock_.Now() + inter_packet_delay); EXPECT_EQ(pacing_sender_->lumpy_tokens(), 2u); CheckPacketIsSentImmediately(); EXPECT_EQ(pacing_sender_->ideal_next_packet_send_time(), clock_.Now() + 2 * inter_packet_delay); EXPECT_EQ(pacing_sender_->lumpy_tokens(), 1u); CheckPacketIsSentImmediately(); EXPECT_EQ(pacing_sender_->ideal_next_packet_send_time(), clock_.Now() + 3 * inter_packet_delay); EXPECT_EQ(pacing_sender_->lumpy_tokens(), 0u); CheckPacketIsDelayed(3 * inter_packet_delay); clock_.AdvanceTime(4.5 * inter_packet_delay); CheckPacketIsSentImmediately(); EXPECT_EQ(pacing_sender_->ideal_next_packet_send_time(), clock_.Now() - 0.5 * inter_packet_delay); EXPECT_EQ(pacing_sender_->lumpy_tokens(), 2u); CheckPacketIsSentImmediately(); EXPECT_EQ(pacing_sender_->ideal_next_packet_send_time(), clock_.Now() + 0.5 * inter_packet_delay); EXPECT_EQ(pacing_sender_->lumpy_tokens(), 1u); CheckPacketIsSentImmediately(); EXPECT_EQ(pacing_sender_->ideal_next_packet_send_time(), clock_.Now() + 1.5 * inter_packet_delay); EXPECT_EQ(pacing_sender_->lumpy_tokens(), 0u); CheckPacketIsDelayed(1.5 * inter_packet_delay); } } }
324
cpp
google/quiche
bbr_sender
quiche/quic/core/congestion_control/bbr_sender.cc
quiche/quic/core/congestion_control/bbr_sender_test.cc
#ifndef QUICHE_QUIC_CORE_CONGESTION_CONTROL_BBR_SENDER_H_ #define QUICHE_QUIC_CORE_CONGESTION_CONTROL_BBR_SENDER_H_ #include <cstdint> #include <ostream> #include <string> #include "quiche/quic/core/congestion_control/bandwidth_sampler.h" #include "quiche/quic/core/congestion_control/send_algorithm_interface.h" #include "quiche/quic/core/congestion_control/windowed_filter.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/quic_bandwidth.h" #include "quiche/quic/core/quic_packet_number.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_unacked_packet_map.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_flags.h" namespace quic { class RttStats; class QUICHE_EXPORT BbrSender : public SendAlgorithmInterface { public: enum Mode { STARTUP, DRAIN, PROBE_BW, PROBE_RTT, }; enum RecoveryState { NOT_IN_RECOVERY, CONSERVATION, GROWTH }; struct QUICHE_EXPORT DebugState { explicit DebugState(const BbrSender& sender); DebugState(const DebugState& state); Mode mode; QuicBandwidth max_bandwidth; QuicRoundTripCount round_trip_count; int gain_cycle_index; QuicByteCount congestion_window; bool is_at_full_bandwidth; QuicBandwidth bandwidth_at_last_round; QuicRoundTripCount rounds_without_bandwidth_gain; QuicTime::Delta min_rtt; QuicTime min_rtt_timestamp; RecoveryState recovery_state; QuicByteCount recovery_window; bool last_sample_is_app_limited; QuicPacketNumber end_of_app_limited_phase; }; BbrSender(QuicTime now, const RttStats* rtt_stats, const QuicUnackedPacketMap* unacked_packets, QuicPacketCount initial_tcp_congestion_window, QuicPacketCount max_tcp_congestion_window, QuicRandom* random, QuicConnectionStats* stats); BbrSender(const BbrSender&) = delete; BbrSender& operator=(const BbrSender&) = delete; ~BbrSender() override; bool InSlowStart() const override; bool InRecovery() const override; void SetFromConfig(const QuicConfig& config, Perspective perspective) override; void ApplyConnectionOptions(const QuicTagVector& connection_options) override; void AdjustNetworkParameters(const NetworkParams& params) override; void SetInitialCongestionWindowInPackets( QuicPacketCount congestion_window) override; void OnCongestionEvent(bool rtt_updated, QuicByteCount prior_in_flight, QuicTime event_time, const AckedPacketVector& acked_packets, const LostPacketVector& lost_packets, QuicPacketCount num_ect, QuicPacketCount num_ce) override; void OnPacketSent(QuicTime sent_time, QuicByteCount bytes_in_flight, QuicPacketNumber packet_number, QuicByteCount bytes, HasRetransmittableData is_retransmittable) override; void OnPacketNeutered(QuicPacketNumber packet_number) override; void OnRetransmissionTimeout(bool ) override {} void OnConnectionMigration() override {} bool CanSend(QuicByteCount bytes_in_flight) override; QuicBandwidth PacingRate(QuicByteCount bytes_in_flight) const override; QuicBandwidth BandwidthEstimate() const override; bool HasGoodBandwidthEstimateForResumption() const override { return has_non_app_limited_sample(); } QuicByteCount GetCongestionWindow() const override; QuicByteCount GetSlowStartThreshold() const override; CongestionControlType GetCongestionControlType() const override; std::string GetDebugState() const override; void OnApplicationLimited(QuicByteCount bytes_in_flight) override; void PopulateConnectionStats(QuicConnectionStats* stats) const override; bool EnableECT0() override { return false; } bool EnableECT1() override { return false; } QuicRoundTripCount num_startup_rtts() const { return num_startup_rtts_; } bool has_non_app_limited_sample() const { return has_non_app_limited_sample_; } void set_high_gain(float high_gain) { QUICHE_DCHECK_LT(1.0f, high_gain); high_gain_ = high_gain; if (mode_ == STARTUP) { pacing_gain_ = high_gain; } } void set_high_cwnd_gain(float high_cwnd_gain) { QUICHE_DCHECK_LT(1.0f, high_cwnd_gain); high_cwnd_gain_ = high_cwnd_gain; if (mode_ == STARTUP) { congestion_window_gain_ = high_cwnd_gain; } } void set_drain_gain(float drain_gain) { QUICHE_DCHECK_GT(1.0f, drain_gain); drain_gain_ = drain_gain; } QuicTime::Delta GetMinRtt() const; DebugState ExportDebugState() const; private: friend class Bbr2Sender; using MaxBandwidthFilter = WindowedFilter<QuicBandwidth, MaxFilter<QuicBandwidth>, QuicRoundTripCount, QuicRoundTripCount>; using MaxAckHeightFilter = WindowedFilter<QuicByteCount, MaxFilter<QuicByteCount>, QuicRoundTripCount, QuicRoundTripCount>; QuicByteCount GetTargetCongestionWindow(float gain) const; QuicByteCount ProbeRttCongestionWindow() const; bool MaybeUpdateMinRtt(QuicTime now, QuicTime::Delta sample_min_rtt); void EnterStartupMode(QuicTime now); void EnterProbeBandwidthMode(QuicTime now); bool UpdateRoundTripCounter(QuicPacketNumber last_acked_packet); void UpdateGainCyclePhase(QuicTime now, QuicByteCount prior_in_flight, bool has_losses); void CheckIfFullBandwidthReached(const SendTimeState& last_packet_send_state); void MaybeExitStartupOrDrain(QuicTime now); void MaybeEnterOrExitProbeRtt(QuicTime now, bool is_round_start, bool min_rtt_expired); void UpdateRecoveryState(QuicPacketNumber last_acked_packet, bool has_losses, bool is_round_start); QuicByteCount UpdateAckAggregationBytes(QuicTime ack_time, QuicByteCount newly_acked_bytes); void CalculatePacingRate(QuicByteCount bytes_lost); void CalculateCongestionWindow(QuicByteCount bytes_acked, QuicByteCount excess_acked); void CalculateRecoveryWindow(QuicByteCount bytes_acked, QuicByteCount bytes_lost); void OnExitStartup(QuicTime now); bool ShouldExitStartupDueToLoss( const SendTimeState& last_packet_send_state) const; const RttStats* rtt_stats_; const QuicUnackedPacketMap* unacked_packets_; QuicRandom* random_; QuicConnectionStats* stats_; Mode mode_; BandwidthSampler sampler_; QuicRoundTripCount round_trip_count_; QuicPacketNumber last_sent_packet_; QuicPacketNumber current_round_trip_end_; int64_t num_loss_events_in_round_; QuicByteCount bytes_lost_in_round_; MaxBandwidthFilter max_bandwidth_; QuicTime::Delta min_rtt_; QuicTime min_rtt_timestamp_; QuicByteCount congestion_window_; QuicByteCount initial_congestion_window_; QuicByteCount max_congestion_window_; QuicByteCount min_congestion_window_; float high_gain_; float high_cwnd_gain_; float drain_gain_; QuicBandwidth pacing_rate_; float pacing_gain_; float congestion_window_gain_; const float congestion_window_gain_constant_; QuicRoundTripCount num_startup_rtts_; int cycle_current_offset_; QuicTime last_cycle_start_; bool is_at_full_bandwidth_; QuicRoundTripCount rounds_without_bandwidth_gain_; QuicBandwidth bandwidth_at_last_round_; bool exiting_quiescence_; QuicTime exit_probe_rtt_at_; bool probe_rtt_round_passed_; bool last_sample_is_app_limited_; bool has_non_app_limited_sample_; RecoveryState recovery_state_; QuicPacketNumber end_recovery_at_; QuicByteCount recovery_window_; bool is_app_limited_recovery_; bool slower_startup_; bool rate_based_startup_; bool enable_ack_aggregation_during_startup_; bool expire_ack_aggregation_in_startup_; bool drain_to_target_; bool detect_overshooting_; QuicByteCount bytes_lost_while_detecting_overshooting_; uint8_t bytes_lost_multiplier_while_detecting_overshooting_; QuicByteCount cwnd_to_calculate_min_pacing_rate_; QuicByteCount max_congestion_window_with_network_parameters_adjusted_; }; QUICHE_EXPORT std::ostream& operator<<(std::ostream& os, const BbrSender::Mode& mode); QUICHE_EXPORT std::ostream& operator<<(std::ostream& os, const BbrSender::DebugState& state); } #endif #include "quiche/quic/core/congestion_control/bbr_sender.h" #include <algorithm> #include <ostream> #include <sstream> #include <string> #include "absl/base/attributes.h" #include "quiche/quic/core/congestion_control/rtt_stats.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_time_accumulator.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { namespace { const QuicByteCount kDefaultMinimumCongestionWindow = 4 * kMaxSegmentSize; const float kDefaultHighGain = 2.885f; const float kDerivedHighGain = 2.773f; const float kDerivedHighCWNDGain = 2.0f; const float kPacingGain[] = {1.25, 0.75, 1, 1, 1, 1, 1, 1}; const size_t kGainCycleLength = sizeof(kPacingGain) / sizeof(kPacingGain[0]); const QuicRoundTripCount kBandwidthWindowSize = kGainCycleLength + 2; const QuicTime::Delta kMinRttExpiry = QuicTime::Delta::FromSeconds(10); const QuicTime::Delta kProbeRttTime = QuicTime::Delta::FromMilliseconds(200); const float kStartupGrowthTarget = 1.25; const QuicRoundTripCount kRoundTripsWithoutGrowthBeforeExitingStartup = 3; } BbrSender::DebugState::DebugState(const BbrSender& sender) : mode(sender.mode_), max_bandwidth(sender.max_bandwidth_.GetBest()), round_trip_count(sender.round_trip_count_), gain_cycle_index(sender.cycle_current_offset_), congestion_window(sender.congestion_window_), is_at_full_bandwidth(sender.is_at_full_bandwidth_), bandwidth_at_last_round(sender.bandwidth_at_last_round_), rounds_without_bandwidth_gain(sender.rounds_without_bandwidth_gain_), min_rtt(sender.min_rtt_), min_rtt_timestamp(sender.min_rtt_timestamp_), recovery_state(sender.recovery_state_), recovery_window(sender.recovery_window_), last_sample_is_app_limited(sender.last_sample_is_app_limited_), end_of_app_limited_phase(sender.sampler_.end_of_app_limited_phase()) {} BbrSender::DebugState::DebugState(const DebugState& state) = default; BbrSender::BbrSender(QuicTime now, const RttStats* rtt_stats, const QuicUnackedPacketMap* unacked_packets, QuicPacketCount initial_tcp_congestion_window, QuicPacketCount max_tcp_congestion_window, QuicRandom* random, QuicConnectionStats* stats) : rtt_stats_(rtt_stats), unacked_packets_(unacked_packets), random_(random), stats_(stats), mode_(STARTUP), sampler_(unacked_packets, kBandwidthWindowSize), round_trip_count_(0), num_loss_events_in_round_(0), bytes_lost_in_round_(0), max_bandwidth_(kBandwidthWindowSize, QuicBandwidth::Zero(), 0), min_rtt_(QuicTime::Delta::Zero()), min_rtt_timestamp_(QuicTime::Zero()), congestion_window_(initial_tcp_congestion_window * kDefaultTCPMSS), initial_congestion_window_(initial_tcp_congestion_window * kDefaultTCPMSS), max_congestion_window_(max_tcp_congestion_window * kDefaultTCPMSS), min_congestion_window_(kDefaultMinimumCongestionWindow), high_gain_(kDefaultHighGain), high_cwnd_gain_(kDefaultHighGain), drain_gain_(1.f / kDefaultHighGain), pacing_rate_(QuicBandwidth::Zero()), pacing_gain_(1), congestion_window_gain_(1), congestion_window_gain_constant_( static_cast<float>(GetQuicFlag(quic_bbr_cwnd_gain))), num_startup_rtts_(kRoundTripsWithoutGrowthBeforeExitingStartup), cycle_current_offset_(0), last_cycle_start_(QuicTime::Zero()), is_at_full_bandwidth_(false), rounds_without_bandwidth_gain_(0), bandwidth_at_last_round_(QuicBandwidth::Zero()), exiting_quiescence_(false), exit_probe_rtt_at_(QuicTime::Zero()), probe_rtt_round_passed_(false), last_sample_is_app_limited_(false), has_non_app_limited_sample_(false), recovery_state_(NOT_IN_RECOVERY), recovery_window_(max_congestion_window_), slower_startup_(false), rate_based_startup_(false), enable_ack_aggregation_during_startup_(false), expire_ack_aggregation_in_startup_(false), drain_to_target_(false), detect_overshooting_(false), bytes_lost_while_detecting_overshooting_(0), bytes_lost_multiplier_while_detecting_overshooting_(2), cwnd_to_calculate_min_pacing_rate_(initial_congestion_window_), max_congestion_window_with_network_parameters_adjusted_( kMaxInitialCongestionWindow * kDefaultTCPMSS) { if (stats_) { stats_->slowstart_count = 0; stats_->slowstart_duration = QuicTimeAccumulator(); } EnterStartupMode(now); set_high_cwnd_gain(kDerivedHighCWNDGain); } BbrSender::~BbrSender() {} void BbrSender::SetInitialCongestionWindowInPackets( QuicPacketCount congestion_window) { if (mode_ == STARTUP) { initial_congestion_window_ = congestion_window * kDefaultTCPMSS; congestion_window_ = congestion_window * kDefaultTCPMSS; cwnd_to_calculate_min_pacing_rate_ = std::min( initial_congestion_window_, cwnd_to_calculate_min_pacing_rate_); } } bool BbrSender::InSlowStart() const { return mode_ == STARTUP; } void BbrSender::OnPacketSent(QuicTime sent_time, QuicByteCount bytes_in_flight, QuicPacketNumber packet_number, QuicByteCount bytes, HasRetransmittableData is_retransmittable) { if (stats_ && InSlowStart()) { ++stats_->slowstart_packets_sent; stats_->slowstart_bytes_sent += bytes; } last_sent_packet_ = packet_number; if (bytes_in_flight == 0 && sampler_.is_app_limited()) { exiting_quiescence_ = true; } sampler_.OnPacketSent(sent_time, packet_number, bytes, bytes_in_flight, is_retransmittable); } void BbrSender::OnPacketNeutered(QuicPacketNumber packet_number) { sampler_.OnPacketNeutered(packet_number); } bool BbrSender::CanSend(QuicByteCount bytes_in_flight) { return bytes_in_flight < GetCongestionWindow(); } QuicBandwidth BbrSender::PacingRate(QuicByteCount ) const { if (pacing_rate_.IsZero()) { return high_gain_ * QuicBandwidth::FromBytesAndTimeDelta( initial_congestion_window_, GetMinRtt()); } return pacing_rate_; } QuicBandwidth BbrSender::BandwidthEstimate() const { return max_bandwidth_.GetBest(); } QuicByteCount BbrSender::GetCongestionWindow() const { if (mode_ == PROBE_RTT) { return ProbeRttCongestionWindow(); } if (InRecovery()) { return std::min(congestion_window_, recovery_window_); } return congestion_window_; } QuicByteCount BbrSender::GetSlowStartThreshold() const { return 0; } bool BbrSender::InRecovery() const { return recovery_state_ != NOT_IN_RECOVERY; } void BbrSender::SetFromConfig(const QuicConfig& config, Perspective perspective) { if (config.HasClientRequestedIndependentOption(k1RTT, perspective)) { num_startup_rtts_ = 1; } if (config.HasClientRequestedIndependentOption(k2RTT, perspective)) { num_startup_rtts_ = 2; } if (config.HasClientRequestedIndependentOption(kBBR3, perspective)) { drain_to_target_ = true; } if (config.HasClientRequestedIndependentOption(kBWM3, perspective)) { bytes_lost_multiplier_while_detecting_overshooting_ = 3; } if (config.HasClientRequestedIndependentOption(kBWM4, perspective)) { bytes_lost_multiplier_while_detecting_overshooting_ = 4; } if (config.HasClientRequestedIndependentOption(kBBR4, perspective)) { sampler_.SetMaxAckHeightTrackerWindowLength(2 * kBandwidthWindowSize); } if (config.HasClientRequestedIndependentOption(kBBR5, perspective)) { sampler_.SetMaxAckHeightTrackerWindowLength(4 * kBandwidthWindowSize); } if (config.HasClientRequestedIndependentOption(kBBQ1, perspective)) { set_high_gain(kDerivedHighGain); set_high_cwnd_gain(kDerivedHighGain); set_drain_gain(1.0 / kDerivedHighCWNDGain); } if (config.HasClientRequestedIndependentOption(kBBQ3, perspective)) { enable_ack_aggregation_during_startup_ = true; } if (config.HasClientRequestedIndependentOption(kBBQ5, perspective)) { expire_ack_aggregation_in_startup_ = true; } if (config.HasClientRequestedIndependentOption(kMIN1, perspective)) { min_congestion_window_ = kMaxSegmentSize; } if (config.HasClientRequestedIndependentOption(kICW1, perspective)) { max_congestion_window_with_network_parameters_adjusted_ = 100 * kDefaultTCPMSS; } if (config.HasClientRequestedIndependentOption(kDTOS, perspective)) { detect_overshooting_ = true; cwnd_to_calculate_min_pacing_rate_ = std::min(initial_congestion_window_, 10 * kDefaultTCPMSS); } ApplyConnectionOptions(config.ClientRequestedIndependentOptions(perspective)); } void BbrSender::ApplyConnectionOptions( const QuicTagVector& connection_options) { if (ContainsQuicTag(connection_options, kBSAO)) { sampler_.EnableOverestimateAvoidance(); } if (ContainsQuicTag(connection_options, kBBRA)) { sampler_.SetStartNewAggregationEpochAfterFullRound(true); } if (ContainsQuicTag(connection_options, kBBRB)) { sampler_.SetLimitMaxAckHeightTrackerBySendRate(true); } } void BbrSender::AdjustNetworkParameters(const NetworkParams& params) { const QuicBandwidth& bandwidth = params.bandwidth; const QuicTime::Delta& rtt = params.rtt; if (!rtt.IsZero() && (min_rtt_ > rtt || min_rtt_.IsZero())) { min_rtt_ = rtt; } if (mode_ == STARTUP) { if (bandwidth.IsZero()) { return; } auto cwnd_bootstrapping_rtt = GetMinRtt(); if (params.max_initial_congestion_window > 0) { max_congestion_window_with_network_parameters_adjusted_ = params.max_initial_congestion_window * kDefaultTCPMSS; } const QuicByteCount new_cwnd = std::max( kMinInitialCongestionWindow * kDefaultTCPMSS, std::min(max_congestion_window_with_network_parameters_adjusted_, bandwidth * cwnd_bootstrapping_rtt)); stats_->cwnd_bootstrapping_rtt_us = cwnd_bootstrapping_rtt.ToMicroseconds(); if (!rtt_stats_->smoothed_rtt().IsZero()) { QUIC_CODE_COUNT(quic_smoothed_rtt_available); } else if (rtt_stats_->initial_rtt() != QuicTime::Delta::FromMilliseconds(kInitialRttMs)) { QUIC_CODE_COUNT(quic_client_initial_rtt_available); } else { QUIC_CODE_COUNT(quic_default_initial_rtt); } if (new_cwnd < congestion_window_ && !params.allow_cwnd_to_decrease) { return; } if (GetQuicReloadableFlag(quic_conservative_cwnd_and_pacing_gains)) { QUIC_RELOADABLE_FLAG_COUNT(quic_conservative_cwnd_and_pacing_gains); set_high_gain(kDerivedHighCWNDGain); set_high_cwnd_gain(kDerivedHighCWNDGain); } congestion_window_ = new_cwnd; QuicBandwidth new_pacing_rate = QuicBandwidth::FromBytesAndTimeDelta(congestion_window_, GetMinRtt()); pacing_rate_ = std::max(pacing_rate_, new_pacing_rate); detect_overshooting_ = true; } } void BbrSender::OnCongestionEvent(bool , QuicByteCount prior_in_flight, QuicTime event_time, const AckedPacketVector& acked_packets, const LostPacketVector& lost_packets, QuicPacketCount , QuicPacketCount ) { const QuicByteCount total_bytes_acked_before = sampler_.total_bytes_acked(); const QuicByteCount total_bytes_lost_before = sampler_.total_bytes_lost(); bool is_round_start = false; bool min_rtt_expired = false; QuicByteCount excess_acked = 0; QuicByteCount bytes_lost = 0; SendTimeState last_packet_send_state; if (!acked_packets.empty()) { QuicPacketNumber last_acked_packet = acked_packets.rbegin()->packet_number; is_round_start = UpdateRoundTripCounter(last_acked_packet); UpdateRecoveryState(last_acked_packet, !lost_packets.empty(), is_round_start); } BandwidthSamplerInterface::CongestionEventSample sample = sampler_.OnCongestionEvent(event_time, acked_packets, lost_packets, max_bandwidth_.GetBest(), QuicBandwidth::Infinite(), round_trip_count_); if (sample.last_packet_send_state.is_valid) { last_sample_is_app_limited_ = sample.last_packet_send_state.is_app_limited; has_non_app_limited_sample_ |= !last_sample_is_app_limited_; if (stats_) { stats_->has_non_app_limited_sample = has_non_app_limited_sample_; } } if (total_bytes_acked_before != sampler_.total_bytes_acked()) { QUIC_LOG_IF(WARNING, sample.sample_max_bandwidth.IsZero()) << sampler_.total_bytes_acked() - total_bytes_acked_before << " bytes from " << acked_packets.size() << " packets have been acked, but sample_max_bandwidth is zero."; if (!sample.sample_is_app_limited || sample.sample_max_bandwidth > max_bandwidth_.GetBest()) { max_bandwidth_.Update(sample.sample_max_bandwidth, round_trip_count_); } } if (!sample.sample_rtt.IsInfinite()) { min_rtt_expired = MaybeUpdateMinRtt(event_time, sample.sample_rtt); } bytes_lost = sampler_.total_bytes_lost() - total_bytes_lost_before; if (mode_ == STARTUP) { if (stats_) { stats_->slowstart_packets_lost += lost_packets.size(); stats_->slowstart_bytes_lost += bytes_lost; } } excess_acked = sample.extra_acked; last_packet_send_state = sample.last_packet_send_state; if (!lost_packets.empty()) { ++num_loss_events_in_round_; bytes_lost_in_round_ += bytes_lost; } if (mode_ == PROBE_BW) { UpdateGainCyclePhase(event_time, prior_in_flight, !lost_packets.empty()); } if (is_round_start && !is_at_full_bandwidth_) { CheckIfFullBandwidthReached(last_packet_send_state); } MaybeExitStartupOrDrain(event_time); MaybeEnterOrExitProbeRtt(event_time, is_round_start, min_rtt_expired); QuicByteCount bytes_acked = sampler_.total_bytes_acked() - total_bytes_acked_before; CalculatePacingRate(bytes_lost); CalculateCongestionWindow(bytes_acked, excess_acked); CalculateRecoveryWindow(bytes_acked, bytes_lost); sampler_.RemoveObsoletePackets(unacked_packets_->GetLeastUnacked()); if (is_round_start) { num_loss_events_in_round_ = 0; bytes_lost_in_round_ = 0; } } CongestionControlType BbrSender::GetCongestionControlType() const { return kBBR; } QuicTime::Delta BbrSender::GetMinRtt() const { if (!min_rtt_.IsZero()) { return min_rtt_; } return rtt_stats_->MinOrInitialRtt(); } QuicByteCount BbrSender::GetTargetCongestionWindow(float gain) const { QuicByteCount bdp = GetMinRtt() * BandwidthEstimate(); QuicByteCount congestion_window = gai
#include "quiche/quic/core/congestion_control/bbr_sender.h" #include <algorithm> #include <map> #include <memory> #include <string> #include <utility> #include "quiche/quic/core/congestion_control/rtt_stats.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/quic_bandwidth.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_clock.h" #include "quiche/quic/test_tools/quic_config_peer.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_sent_packet_manager_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/send_algorithm_test_result.pb.h" #include "quiche/quic/test_tools/send_algorithm_test_utils.h" #include "quiche/quic/test_tools/simulator/quic_endpoint.h" #include "quiche/quic/test_tools/simulator/simulator.h" #include "quiche/quic/test_tools/simulator/switch.h" #include "quiche/common/platform/api/quiche_command_line_flags.h" using testing::AllOf; using testing::Ge; using testing::Le; DEFINE_QUICHE_COMMAND_LINE_FLAG( std::string, quic_bbr_test_regression_mode, "", "One of a) 'record' to record test result (one file per test), or " "b) 'regress' to regress against recorded results, or " "c) <anything else> for non-regression mode."); namespace quic { namespace test { const uint32_t kInitialCongestionWindowPackets = 10; const uint32_t kDefaultWindowTCP = kInitialCongestionWindowPackets * kDefaultTCPMSS; const QuicBandwidth kTestLinkBandwidth = QuicBandwidth::FromKBitsPerSecond(4000); const QuicBandwidth kLocalLinkBandwidth = QuicBandwidth::FromKBitsPerSecond(10000); const QuicTime::Delta kTestPropagationDelay = QuicTime::Delta::FromMilliseconds(30); const QuicTime::Delta kLocalPropagationDelay = QuicTime::Delta::FromMilliseconds(2); const QuicTime::Delta kTestTransferTime = kTestLinkBandwidth.TransferTime(kMaxOutgoingPacketSize) + kLocalLinkBandwidth.TransferTime(kMaxOutgoingPacketSize); const QuicTime::Delta kTestRtt = (kTestPropagationDelay + kLocalPropagationDelay + kTestTransferTime) * 2; const QuicByteCount kTestBdp = kTestRtt * kTestLinkBandwidth; class BbrSenderTest : public QuicTest { protected: BbrSenderTest() : simulator_(&random_), bbr_sender_(&simulator_, "BBR sender", "Receiver", Perspective::IS_CLIENT, TestConnectionId(42)), competing_sender_(&simulator_, "Competing sender", "Competing receiver", Perspective::IS_CLIENT, TestConnectionId(43)), receiver_(&simulator_, "Receiver", "BBR sender", Perspective::IS_SERVER, TestConnectionId(42)), competing_receiver_(&simulator_, "Competing receiver", "Competing sender", Perspective::IS_SERVER, TestConnectionId(43)), receiver_multiplexer_("Receiver multiplexer", {&receiver_, &competing_receiver_}) { rtt_stats_ = bbr_sender_.connection()->sent_packet_manager().GetRttStats(); const int kTestMaxPacketSize = 1350; bbr_sender_.connection()->SetMaxPacketLength(kTestMaxPacketSize); sender_ = SetupBbrSender(&bbr_sender_); SetConnectionOption(kBBRA); clock_ = simulator_.GetClock(); } void SetUp() override { if (quiche::GetQuicheCommandLineFlag(FLAGS_quic_bbr_test_regression_mode) == "regress") { SendAlgorithmTestResult expected; ASSERT_TRUE(LoadSendAlgorithmTestResult(&expected)); random_seed_ = expected.random_seed(); } else { random_seed_ = QuicRandom::GetInstance()->RandUint64(); } random_.set_seed(random_seed_); QUIC_LOG(INFO) << "BbrSenderTest simulator set up. Seed: " << random_seed_; } ~BbrSenderTest() { const std::string regression_mode = quiche::GetQuicheCommandLineFlag(FLAGS_quic_bbr_test_regression_mode); const QuicTime::Delta simulated_duration = clock_->Now() - QuicTime::Zero(); if (regression_mode == "record") { RecordSendAlgorithmTestResult(random_seed_, simulated_duration.ToMicroseconds()); } else if (regression_mode == "regress") { CompareSendAlgorithmTestResult(simulated_duration.ToMicroseconds()); } } uint64_t random_seed_; SimpleRandom random_; simulator::Simulator simulator_; simulator::QuicEndpoint bbr_sender_; simulator::QuicEndpoint competing_sender_; simulator::QuicEndpoint receiver_; simulator::QuicEndpoint competing_receiver_; simulator::QuicEndpointMultiplexer receiver_multiplexer_; std::unique_ptr<simulator::Switch> switch_; std::unique_ptr<simulator::SymmetricLink> bbr_sender_link_; std::unique_ptr<simulator::SymmetricLink> competing_sender_link_; std::unique_ptr<simulator::SymmetricLink> receiver_link_; const QuicClock* clock_; const RttStats* rtt_stats_; BbrSender* sender_; BbrSender* SetupBbrSender(simulator::QuicEndpoint* endpoint) { const RttStats* rtt_stats = endpoint->connection()->sent_packet_manager().GetRttStats(); BbrSender* sender = new BbrSender( endpoint->connection()->clock()->Now(), rtt_stats, QuicSentPacketManagerPeer::GetUnackedPacketMap( QuicConnectionPeer::GetSentPacketManager(endpoint->connection())), kInitialCongestionWindowPackets, GetQuicFlag(quic_max_congestion_window), &random_, QuicConnectionPeer::GetStats(endpoint->connection())); QuicConnectionPeer::SetSendAlgorithm(endpoint->connection(), sender); endpoint->RecordTrace(); return sender; } void CreateDefaultSetup() { switch_ = std::make_unique<simulator::Switch>(&simulator_, "Switch", 8, 2 * kTestBdp); bbr_sender_link_ = std::make_unique<simulator::SymmetricLink>( &bbr_sender_, switch_->port(1), kLocalLinkBandwidth, kLocalPropagationDelay); receiver_link_ = std::make_unique<simulator::SymmetricLink>( &receiver_, switch_->port(2), kTestLinkBandwidth, kTestPropagationDelay); } void CreateSmallBufferSetup() { switch_ = std::make_unique<simulator::Switch>(&simulator_, "Switch", 8, 0.5 * kTestBdp); bbr_sender_link_ = std::make_unique<simulator::SymmetricLink>( &bbr_sender_, switch_->port(1), kLocalLinkBandwidth, kLocalPropagationDelay); receiver_link_ = std::make_unique<simulator::SymmetricLink>( &receiver_, switch_->port(2), kTestLinkBandwidth, kTestPropagationDelay); } void CreateCompetitionSetup() { switch_ = std::make_unique<simulator::Switch>(&simulator_, "Switch", 8, 2 * kTestBdp); const QuicTime::Delta small_offset = QuicTime::Delta::FromMicroseconds(3); bbr_sender_link_ = std::make_unique<simulator::SymmetricLink>( &bbr_sender_, switch_->port(1), kLocalLinkBandwidth, kLocalPropagationDelay); competing_sender_link_ = std::make_unique<simulator::SymmetricLink>( &competing_sender_, switch_->port(3), kLocalLinkBandwidth, kLocalPropagationDelay + small_offset); receiver_link_ = std::make_unique<simulator::SymmetricLink>( &receiver_multiplexer_, switch_->port(2), kTestLinkBandwidth, kTestPropagationDelay); } void CreateBbrVsBbrSetup() { SetupBbrSender(&competing_sender_); CreateCompetitionSetup(); } void EnableAggregation(QuicByteCount aggregation_bytes, QuicTime::Delta aggregation_timeout) { switch_->port_queue(1)->EnableAggregation(aggregation_bytes, aggregation_timeout); } void DoSimpleTransfer(QuicByteCount transfer_size, QuicTime::Delta deadline) { bbr_sender_.AddBytesToTransfer(transfer_size); bool simulator_result = simulator_.RunUntilOrTimeout( [this]() { return bbr_sender_.bytes_to_transfer() == 0; }, deadline); EXPECT_TRUE(simulator_result) << "Simple transfer failed. Bytes remaining: " << bbr_sender_.bytes_to_transfer(); QUIC_LOG(INFO) << "Simple transfer state: " << sender_->ExportDebugState(); } void DriveOutOfStartup() { ASSERT_FALSE(sender_->ExportDebugState().is_at_full_bandwidth); DoSimpleTransfer(1024 * 1024, QuicTime::Delta::FromSeconds(15)); EXPECT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); EXPECT_APPROX_EQ(kTestLinkBandwidth, sender_->ExportDebugState().max_bandwidth, 0.02f); } void SendBursts(size_t number_of_bursts, QuicByteCount bytes, QuicTime::Delta wait_time) { ASSERT_EQ(0u, bbr_sender_.bytes_to_transfer()); for (size_t i = 0; i < number_of_bursts; i++) { bbr_sender_.AddBytesToTransfer(bytes); simulator_.RunFor(wait_time); ASSERT_TRUE(bbr_sender_.connection()->connected()); ASSERT_TRUE(receiver_.connection()->connected()); } simulator_.RunFor(wait_time + kTestRtt); ASSERT_EQ(0u, bbr_sender_.bytes_to_transfer()); } void SetConnectionOption(QuicTag option) { QuicConfig config; QuicTagVector options; options.push_back(option); QuicConfigPeer::SetReceivedConnectionOptions(&config, options); sender_->SetFromConfig(config, Perspective::IS_SERVER); } }; TEST_F(BbrSenderTest, SetInitialCongestionWindow) { EXPECT_NE(3u * kDefaultTCPMSS, sender_->GetCongestionWindow()); sender_->SetInitialCongestionWindowInPackets(3); EXPECT_EQ(3u * kDefaultTCPMSS, sender_->GetCongestionWindow()); } TEST_F(BbrSenderTest, SimpleTransfer) { CreateDefaultSetup(); EXPECT_EQ(kDefaultWindowTCP, sender_->GetCongestionWindow()); EXPECT_TRUE(sender_->CanSend(0)); EXPECT_EQ(kDefaultWindowTCP, sender_->GetCongestionWindow()); EXPECT_TRUE(sender_->InSlowStart()); QuicBandwidth expected_pacing_rate = QuicBandwidth::FromBytesAndTimeDelta( 2.885 * kDefaultWindowTCP, rtt_stats_->initial_rtt()); EXPECT_APPROX_EQ(expected_pacing_rate.ToBitsPerSecond(), sender_->PacingRate(0).ToBitsPerSecond(), 0.01f); ASSERT_GE(kTestBdp, kDefaultWindowTCP + kDefaultTCPMSS); DoSimpleTransfer(12 * 1024 * 1024, QuicTime::Delta::FromSeconds(30)); EXPECT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); EXPECT_EQ(0u, bbr_sender_.connection()->GetStats().packets_lost); EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited); EXPECT_APPROX_EQ(kTestRtt, rtt_stats_->smoothed_rtt(), 0.2f); } TEST_F(BbrSenderTest, SimpleTransferBBRB) { SetConnectionOption(kBBRB); CreateDefaultSetup(); EXPECT_EQ(kDefaultWindowTCP, sender_->GetCongestionWindow()); EXPECT_TRUE(sender_->CanSend(0)); EXPECT_EQ(kDefaultWindowTCP, sender_->GetCongestionWindow()); EXPECT_TRUE(sender_->InSlowStart()); QuicBandwidth expected_pacing_rate = QuicBandwidth::FromBytesAndTimeDelta( 2.885 * kDefaultWindowTCP, rtt_stats_->initial_rtt()); EXPECT_APPROX_EQ(expected_pacing_rate.ToBitsPerSecond(), sender_->PacingRate(0).ToBitsPerSecond(), 0.01f); ASSERT_GE(kTestBdp, kDefaultWindowTCP + kDefaultTCPMSS); DoSimpleTransfer(12 * 1024 * 1024, QuicTime::Delta::FromSeconds(30)); EXPECT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); EXPECT_EQ(0u, bbr_sender_.connection()->GetStats().packets_lost); EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited); EXPECT_APPROX_EQ(kTestRtt, rtt_stats_->smoothed_rtt(), 0.2f); } TEST_F(BbrSenderTest, SimpleTransferSmallBuffer) { CreateSmallBufferSetup(); DoSimpleTransfer(12 * 1024 * 1024, QuicTime::Delta::FromSeconds(30)); EXPECT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); EXPECT_APPROX_EQ(kTestLinkBandwidth, sender_->ExportDebugState().max_bandwidth, 0.01f); EXPECT_GE(bbr_sender_.connection()->GetStats().packets_lost, 0u); EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited); EXPECT_APPROX_EQ(kTestRtt, sender_->GetMinRtt(), 0.2f); } TEST_F(BbrSenderTest, RemoveBytesLostInRecovery) { CreateDefaultSetup(); DriveOutOfStartup(); receiver_.DropNextIncomingPacket(); ASSERT_TRUE( simulator_.RunUntilOrTimeout([this]() { return sender_->InRecovery(); }, QuicTime::Delta::FromSeconds(30))); QuicUnackedPacketMap* unacked_packets = QuicSentPacketManagerPeer::GetUnackedPacketMap( QuicConnectionPeer::GetSentPacketManager(bbr_sender_.connection())); QuicPacketNumber largest_sent = bbr_sender_.connection()->sent_packet_manager().GetLargestSentPacket(); QuicPacketNumber least_inflight = bbr_sender_.connection()->sent_packet_manager().GetLeastUnacked(); while (!unacked_packets->GetTransmissionInfo(least_inflight).in_flight) { ASSERT_LE(least_inflight, largest_sent); least_inflight++; } QuicPacketLength least_inflight_packet_size = unacked_packets->GetTransmissionInfo(least_inflight).bytes_sent; QuicByteCount prior_recovery_window = sender_->ExportDebugState().recovery_window; QuicByteCount prior_inflight = unacked_packets->bytes_in_flight(); QUIC_LOG(INFO) << "Recovery window:" << prior_recovery_window << ", least_inflight_packet_size:" << least_inflight_packet_size << ", bytes_in_flight:" << prior_inflight; ASSERT_GT(prior_recovery_window, least_inflight_packet_size); unacked_packets->RemoveFromInFlight(least_inflight); LostPacketVector lost_packets; lost_packets.emplace_back(least_inflight, least_inflight_packet_size); sender_->OnCongestionEvent(false, prior_inflight, clock_->Now(), {}, lost_packets, 0, 0); EXPECT_EQ(sender_->ExportDebugState().recovery_window, prior_inflight - least_inflight_packet_size); EXPECT_LT(sender_->ExportDebugState().recovery_window, prior_recovery_window); } TEST_F(BbrSenderTest, SimpleTransfer2RTTAggregationBytes) { SetConnectionOption(kBSAO); CreateDefaultSetup(); EnableAggregation(10 * 1024, 2 * kTestRtt); DoSimpleTransfer(12 * 1024 * 1024, QuicTime::Delta::FromSeconds(35)); EXPECT_TRUE(sender_->ExportDebugState().mode == BbrSender::PROBE_BW || sender_->ExportDebugState().mode == BbrSender::PROBE_RTT); EXPECT_APPROX_EQ(kTestLinkBandwidth, sender_->ExportDebugState().max_bandwidth, 0.01f); EXPECT_GE(kTestRtt * 4, rtt_stats_->smoothed_rtt()); EXPECT_APPROX_EQ(kTestRtt, rtt_stats_->min_rtt(), 0.5f); } TEST_F(BbrSenderTest, SimpleTransferAckDecimation) { SetConnectionOption(kBSAO); SetQuicFlag(quic_bbr_cwnd_gain, 1.0); sender_ = new BbrSender( bbr_sender_.connection()->clock()->Now(), rtt_stats_, QuicSentPacketManagerPeer::GetUnackedPacketMap( QuicConnectionPeer::GetSentPacketManager(bbr_sender_.connection())), kInitialCongestionWindowPackets, GetQuicFlag(quic_max_congestion_window), &random_, QuicConnectionPeer::GetStats(bbr_sender_.connection())); QuicConnectionPeer::SetSendAlgorithm(bbr_sender_.connection(), sender_); CreateDefaultSetup(); DoSimpleTransfer(12 * 1024 * 1024, QuicTime::Delta::FromSeconds(35)); EXPECT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); EXPECT_APPROX_EQ(kTestLinkBandwidth, sender_->ExportDebugState().max_bandwidth, 0.01f); EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited); EXPECT_GE(kTestRtt * 2, rtt_stats_->smoothed_rtt()); EXPECT_APPROX_EQ(kTestRtt, rtt_stats_->min_rtt(), 0.1f); } TEST_F(BbrSenderTest, QUIC_TEST_DISABLED_IN_CHROME( SimpleTransfer2RTTAggregationBytes20RTTWindow)) { SetConnectionOption(kBSAO); CreateDefaultSetup(); SetConnectionOption(kBBR4); EnableAggregation(10 * 1024, 2 * kTestRtt); DoSimpleTransfer(12 * 1024 * 1024, QuicTime::Delta::FromSeconds(35)); EXPECT_TRUE(sender_->ExportDebugState().mode == BbrSender::PROBE_BW || sender_->ExportDebugState().mode == BbrSender::PROBE_RTT); EXPECT_APPROX_EQ(kTestLinkBandwidth, sender_->ExportDebugState().max_bandwidth, 0.01f); EXPECT_GE(kTestRtt * 4, rtt_stats_->smoothed_rtt()); EXPECT_APPROX_EQ(kTestRtt, rtt_stats_->min_rtt(), 0.25f); } TEST_F(BbrSenderTest, SimpleTransfer2RTTAggregationBytes40RTTWindow) { SetConnectionOption(kBSAO); CreateDefaultSetup(); SetConnectionOption(kBBR5); EnableAggregation(10 * 1024, 2 * kTestRtt); DoSimpleTransfer(12 * 1024 * 1024, QuicTime::Delta::FromSeconds(35)); EXPECT_TRUE(sender_->ExportDebugState().mode == BbrSender::PROBE_BW || sender_->ExportDebugState().mode == BbrSender::PROBE_RTT); EXPECT_APPROX_EQ(kTestLinkBandwidth, sender_->ExportDebugState().max_bandwidth, 0.01f); EXPECT_GE(kTestRtt * 4, rtt_stats_->smoothed_rtt()); EXPECT_APPROX_EQ(kTestRtt, rtt_stats_->min_rtt(), 0.25f); } TEST_F(BbrSenderTest, PacketLossOnSmallBufferStartup) { CreateSmallBufferSetup(); DriveOutOfStartup(); float loss_rate = static_cast<float>(bbr_sender_.connection()->GetStats().packets_lost) / bbr_sender_.connection()->GetStats().packets_sent; EXPECT_LE(loss_rate, 0.31); } TEST_F(BbrSenderTest, PacketLossOnSmallBufferStartupDerivedCWNDGain) { CreateSmallBufferSetup(); SetConnectionOption(kBBQ2); DriveOutOfStartup(); float loss_rate = static_cast<float>(bbr_sender_.connection()->GetStats().packets_lost) / bbr_sender_.connection()->GetStats().packets_sent; EXPECT_LE(loss_rate, 0.1); } TEST_F(BbrSenderTest, RecoveryStates) { const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(10); bool simulator_result; CreateSmallBufferSetup(); bbr_sender_.AddBytesToTransfer(100 * 1024 * 1024); ASSERT_EQ(BbrSender::NOT_IN_RECOVERY, sender_->ExportDebugState().recovery_state); simulator_result = simulator_.RunUntilOrTimeout( [this]() { return sender_->ExportDebugState().recovery_state != BbrSender::NOT_IN_RECOVERY; }, timeout); ASSERT_TRUE(simulator_result); ASSERT_EQ(BbrSender::CONSERVATION, sender_->ExportDebugState().recovery_state); simulator_result = simulator_.RunUntilOrTimeout( [this]() { return sender_->ExportDebugState().recovery_state != BbrSender::CONSERVATION; }, timeout); ASSERT_TRUE(simulator_result); ASSERT_EQ(BbrSender::GROWTH, sender_->ExportDebugState().recovery_state); simulator_result = simulator_.RunUntilOrTimeout( [this]() { return sender_->ExportDebugState().recovery_state != BbrSender::GROWTH; }, timeout); ASSERT_EQ(BbrSender::NOT_IN_RECOVERY, sender_->ExportDebugState().recovery_state); ASSERT_TRUE(simulator_result); } TEST_F(BbrSenderTest, ApplicationLimitedBursts) { CreateDefaultSetup(); EXPECT_FALSE(sender_->HasGoodBandwidthEstimateForResumption()); DriveOutOfStartup(); EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited); EXPECT_TRUE(sender_->HasGoodBandwidthEstimateForResumption()); SendBursts(20, 512, QuicTime::Delta::FromSeconds(3)); EXPECT_TRUE(sender_->ExportDebugState().last_sample_is_app_limited); EXPECT_TRUE(sender_->HasGoodBandwidthEstimateForResumption()); EXPECT_APPROX_EQ(kTestLinkBandwidth, sender_->ExportDebugState().max_bandwidth, 0.01f); } TEST_F(BbrSenderTest, ApplicationLimitedBurstsWithoutPrior) { CreateDefaultSetup(); SendBursts(40, 512, QuicTime::Delta::FromSeconds(3)); EXPECT_TRUE(sender_->ExportDebugState().last_sample_is_app_limited); DriveOutOfStartup(); EXPECT_APPROX_EQ(kTestLinkBandwidth, sender_->ExportDebugState().max_bandwidth, 0.01f); EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited); } TEST_F(BbrSenderTest, Drain) { CreateDefaultSetup(); const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(10); const simulator::Queue* queue = switch_->port_queue(2); bool simulator_result; bbr_sender_.AddBytesToTransfer(100 * 1024 * 1024); ASSERT_EQ(BbrSender::STARTUP, sender_->ExportDebugState().mode); simulator_result = simulator_.RunUntilOrTimeout( [this]() { return sender_->ExportDebugState().mode != BbrSender::STARTUP; }, timeout); ASSERT_TRUE(simulator_result); ASSERT_EQ(BbrSender::DRAIN, sender_->ExportDebugState().mode); EXPECT_APPROX_EQ(sender_->BandwidthEstimate() * (1 / 2.885f), sender_->PacingRate(0), 0.01f); EXPECT_GE(queue->bytes_queued(), 0.8 * kTestBdp); const QuicTime::Delta queueing_delay = kTestLinkBandwidth.TransferTime(queue->bytes_queued()); EXPECT_APPROX_EQ(kTestRtt + queueing_delay, rtt_stats_->latest_rtt(), 0.1f); simulator_result = simulator_.RunUntilOrTimeout( [this]() { return sender_->ExportDebugState().mode != BbrSender::DRAIN; }, timeout); ASSERT_TRUE(simulator_result); ASSERT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); EXPECT_LE(queue->bytes_queued(), kTestBdp); const QuicRoundTripCount start_round_trip = sender_->ExportDebugState().round_trip_count; simulator_result = simulator_.RunUntilOrTimeout( [this, start_round_trip]() { QuicRoundTripCount rounds_passed = sender_->ExportDebugState().round_trip_count - start_round_trip; return rounds_passed >= 4 && sender_->ExportDebugState().gain_cycle_index == 7; }, timeout); ASSERT_TRUE(simulator_result); EXPECT_APPROX_EQ(kTestRtt, rtt_stats_->smoothed_rtt(), 0.1f); } TEST_F(BbrSenderTest, DISABLED_ShallowDrain) { CreateDefaultSetup(); const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(10); const simulator::Queue* queue = switch_->port_queue(2); bool simulator_result; bbr_sender_.AddBytesToTransfer(100 * 1024 * 1024); ASSERT_EQ(BbrSender::STARTUP, sender_->ExportDebugState().mode); simulator_result = simulator_.RunUntilOrTimeout( [this]() { return sender_->ExportDebugState().mode != BbrSender::STARTUP; }, timeout); ASSERT_TRUE(simulator_result); ASSERT_EQ(BbrSender::DRAIN, sender_->ExportDebugState().mode); EXPECT_EQ(0.75 * sender_->BandwidthEstimate(), sender_->PacingRate(0)); EXPECT_GE(queue->bytes_queued(), 1.5 * kTestBdp); const QuicTime::Delta queueing_delay = kTestLinkBandwidth.TransferTime(queue->bytes_queued()); EXPECT_APPROX_EQ(kTestRtt + queueing_delay, rtt_stats_->latest_rtt(), 0.1f); simulator_result = simulator_.RunUntilOrTimeout( [this]() { return sender_->ExportDebugState().mode != BbrSender::DRAIN; }, timeout); ASSERT_TRUE(simulator_result); ASSERT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); EXPECT_LE(queue->bytes_queued(), kTestBdp); const QuicRoundTripCount start_round_trip = sender_->ExportDebugState().round_trip_count; simulator_result = simulator_.RunUntilOrTimeout( [this, start_round_trip]() { QuicRoundTripCount rounds_passed = sender_->ExportDebugState().round_trip_count - start_round_trip; return rounds_passed >= 4 && sender_->ExportDebugState().gain_cycle_index == 7; }, timeout); ASSERT_TRUE(simulator_result); EXPECT_APPROX_EQ(kTestRtt, rtt_stats_->smoothed_rtt(), 0.1f); } TEST_F(BbrSenderTest, ProbeRtt) { CreateDefaultSetup(); DriveOutOfStartup(); bbr_sender_.AddBytesToTransfer(100 * 1024 * 1024); const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(12); bool simulator_result = simulator_.RunUntilOrTimeout( [this]() { return sender_->ExportDebugState().mode == BbrSender::PROBE_RTT; }, timeout); ASSERT_TRUE(simulator_result); ASSERT_EQ(BbrSender::PROBE_RTT, sender_->ExportDebugState().mode); const QuicTime probe_rtt_start = clock_->Now(); const QuicTime::Delta time_to_exit_probe_rtt = kTestRtt + QuicTime::Delta::FromMilliseconds(200); simulator_.RunFor(1.5 * time_to_exit_probe_rtt); EXPECT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode); EXPECT_GE(sender_->ExportDebugState().min_rtt_timestamp, probe_rtt_start); } TEST_F(BbrSenderTest, QUIC_TEST_DISABLED_IN_CHROME(InFlightAwareGainCycling)) { CreateDefaultSetup(); DriveOutOfStartup(); const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5); while (!(sender_->ExportDebugState().gain_cycle_index >= 4 && bbr_sender_.bytes_to_transfer() == 0)) { bbr_sender_.AddBytesToTransfer(kTestLinkBandwidth.ToBytesPerSecond()); ASSERT_TRUE(simulator_.RunUntilOrTimeout( [this]() { return bbr_sender_.bytes_to_transfer() == 0; }, timeout)); } QuicBandwidth target_bandwidth = 0.1f * kTestLinkBandwidth; QuicTime::Delta burst
325
cpp
google/quiche
hybrid_slow_start
quiche/quic/core/congestion_control/hybrid_slow_start.cc
quiche/quic/core/congestion_control/hybrid_slow_start_test.cc
#ifndef QUICHE_QUIC_CORE_CONGESTION_CONTROL_HYBRID_SLOW_START_H_ #define QUICHE_QUIC_CORE_CONGESTION_CONTROL_HYBRID_SLOW_START_H_ #include <cstdint> #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT HybridSlowStart { public: HybridSlowStart(); HybridSlowStart(const HybridSlowStart&) = delete; HybridSlowStart& operator=(const HybridSlowStart&) = delete; void OnPacketAcked(QuicPacketNumber acked_packet_number); void OnPacketSent(QuicPacketNumber packet_number); bool ShouldExitSlowStart(QuicTime::Delta rtt, QuicTime::Delta min_rtt, QuicPacketCount congestion_window); void Restart(); bool IsEndOfRound(QuicPacketNumber ack) const; void StartReceiveRound(QuicPacketNumber last_sent); bool started() const { return started_; } private: enum HystartState { NOT_FOUND, DELAY, }; bool started_; HystartState hystart_found_; QuicPacketNumber last_sent_packet_number_; QuicPacketNumber end_packet_number_; uint32_t rtt_sample_count_; QuicTime::Delta current_min_rtt_; }; } #endif #include "quiche/quic/core/congestion_control/hybrid_slow_start.h" #include <algorithm> #include "quiche/quic/platform/api/quic_logging.h" namespace quic { const int64_t kHybridStartLowWindow = 16; const uint32_t kHybridStartMinSamples = 8; const int kHybridStartDelayFactorExp = 3; const int64_t kHybridStartDelayMinThresholdUs = 4000; const int64_t kHybridStartDelayMaxThresholdUs = 16000; HybridSlowStart::HybridSlowStart() : started_(false), hystart_found_(NOT_FOUND), rtt_sample_count_(0), current_min_rtt_(QuicTime::Delta::Zero()) {} void HybridSlowStart::OnPacketAcked(QuicPacketNumber acked_packet_number) { if (IsEndOfRound(acked_packet_number)) { started_ = false; } } void HybridSlowStart::OnPacketSent(QuicPacketNumber packet_number) { last_sent_packet_number_ = packet_number; } void HybridSlowStart::Restart() { started_ = false; hystart_found_ = NOT_FOUND; } void HybridSlowStart::StartReceiveRound(QuicPacketNumber last_sent) { QUIC_DVLOG(1) << "Reset hybrid slow start @" << last_sent; end_packet_number_ = last_sent; current_min_rtt_ = QuicTime::Delta::Zero(); rtt_sample_count_ = 0; started_ = true; } bool HybridSlowStart::IsEndOfRound(QuicPacketNumber ack) const { return !end_packet_number_.IsInitialized() || end_packet_number_ <= ack; } bool HybridSlowStart::ShouldExitSlowStart(QuicTime::Delta latest_rtt, QuicTime::Delta min_rtt, QuicPacketCount congestion_window) { if (!started_) { StartReceiveRound(last_sent_packet_number_); } if (hystart_found_ != NOT_FOUND) { return true; } rtt_sample_count_++; if (rtt_sample_count_ <= kHybridStartMinSamples) { if (current_min_rtt_.IsZero() || current_min_rtt_ > latest_rtt) { current_min_rtt_ = latest_rtt; } } if (rtt_sample_count_ == kHybridStartMinSamples) { int64_t min_rtt_increase_threshold_us = min_rtt.ToMicroseconds() >> kHybridStartDelayFactorExp; min_rtt_increase_threshold_us = std::min(min_rtt_increase_threshold_us, kHybridStartDelayMaxThresholdUs); QuicTime::Delta min_rtt_increase_threshold = QuicTime::Delta::FromMicroseconds(std::max( min_rtt_increase_threshold_us, kHybridStartDelayMinThresholdUs)); if (current_min_rtt_ > min_rtt + min_rtt_increase_threshold) { hystart_found_ = DELAY; } } return congestion_window >= kHybridStartLowWindow && hystart_found_ != NOT_FOUND; } }
#include "quiche/quic/core/congestion_control/hybrid_slow_start.h" #include <memory> #include <utility> #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { class HybridSlowStartTest : public QuicTest { protected: HybridSlowStartTest() : one_ms_(QuicTime::Delta::FromMilliseconds(1)), rtt_(QuicTime::Delta::FromMilliseconds(60)) {} void SetUp() override { slow_start_ = std::make_unique<HybridSlowStart>(); } const QuicTime::Delta one_ms_; const QuicTime::Delta rtt_; std::unique_ptr<HybridSlowStart> slow_start_; }; TEST_F(HybridSlowStartTest, Simple) { QuicPacketNumber packet_number(1); QuicPacketNumber end_packet_number(3); slow_start_->StartReceiveRound(end_packet_number); EXPECT_FALSE(slow_start_->IsEndOfRound(packet_number++)); EXPECT_FALSE(slow_start_->IsEndOfRound(packet_number)); EXPECT_FALSE(slow_start_->IsEndOfRound(packet_number++)); EXPECT_TRUE(slow_start_->IsEndOfRound(packet_number++)); EXPECT_TRUE(slow_start_->IsEndOfRound(packet_number++)); end_packet_number = QuicPacketNumber(20); slow_start_->StartReceiveRound(end_packet_number); while (packet_number < end_packet_number) { EXPECT_FALSE(slow_start_->IsEndOfRound(packet_number++)); } EXPECT_TRUE(slow_start_->IsEndOfRound(packet_number++)); } TEST_F(HybridSlowStartTest, Delay) { const int kHybridStartMinSamples = 8; QuicPacketNumber end_packet_number(1); slow_start_->StartReceiveRound(end_packet_number++); for (int n = 0; n < kHybridStartMinSamples; ++n) { EXPECT_FALSE(slow_start_->ShouldExitSlowStart( rtt_ + QuicTime::Delta::FromMilliseconds(n), rtt_, 100)); } slow_start_->StartReceiveRound(end_packet_number++); for (int n = 1; n < kHybridStartMinSamples; ++n) { EXPECT_FALSE(slow_start_->ShouldExitSlowStart( rtt_ + QuicTime::Delta::FromMilliseconds(n + 10), rtt_, 100)); } EXPECT_TRUE(slow_start_->ShouldExitSlowStart( rtt_ + QuicTime::Delta::FromMilliseconds(10), rtt_, 100)); } } }
326
cpp
google/quiche
cubic_bytes
quiche/quic/core/congestion_control/cubic_bytes.cc
quiche/quic/core/congestion_control/cubic_bytes_test.cc
#ifndef QUICHE_QUIC_CORE_CONGESTION_CONTROL_CUBIC_BYTES_H_ #define QUICHE_QUIC_CORE_CONGESTION_CONTROL_CUBIC_BYTES_H_ #include <cstdint> #include "quiche/quic/core/quic_bandwidth.h" #include "quiche/quic/core/quic_clock.h" #include "quiche/quic/core/quic_connection_stats.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { namespace test { class CubicBytesTest; } class QUICHE_EXPORT CubicBytes { public: explicit CubicBytes(const QuicClock* clock); CubicBytes(const CubicBytes&) = delete; CubicBytes& operator=(const CubicBytes&) = delete; void SetNumConnections(int num_connections); void ResetCubicState(); QuicByteCount CongestionWindowAfterPacketLoss(QuicPacketCount current); QuicByteCount CongestionWindowAfterAck(QuicByteCount acked_bytes, QuicByteCount current, QuicTime::Delta delay_min, QuicTime event_time); void OnApplicationLimited(); private: friend class test::CubicBytesTest; static const QuicTime::Delta MaxCubicTimeInterval() { return QuicTime::Delta::FromMilliseconds(30); } float Alpha() const; float Beta() const; float BetaLastMax() const; QuicByteCount last_max_congestion_window() const { return last_max_congestion_window_; } const QuicClock* clock_; int num_connections_; QuicTime epoch_; QuicByteCount last_max_congestion_window_; QuicByteCount acked_bytes_count_; QuicByteCount estimated_tcp_congestion_window_; QuicByteCount origin_point_congestion_window_; uint32_t time_to_origin_point_; QuicByteCount last_target_congestion_window_; }; } #endif #include "quiche/quic/core/congestion_control/cubic_bytes.h" #include <algorithm> #include <cmath> #include <cstdint> #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { namespace { const int kCubeScale = 40; const int kCubeCongestionWindowScale = 410; const uint64_t kCubeFactor = (UINT64_C(1) << kCubeScale) / kCubeCongestionWindowScale / kDefaultTCPMSS; const float kDefaultCubicBackoffFactor = 0.7f; const float kBetaLastMax = 0.85f; } CubicBytes::CubicBytes(const QuicClock* clock) : clock_(clock), num_connections_(kDefaultNumConnections), epoch_(QuicTime::Zero()) { ResetCubicState(); } void CubicBytes::SetNumConnections(int num_connections) { num_connections_ = num_connections; } float CubicBytes::Alpha() const { const float beta = Beta(); return 3 * num_connections_ * num_connections_ * (1 - beta) / (1 + beta); } float CubicBytes::Beta() const { return (num_connections_ - 1 + kDefaultCubicBackoffFactor) / num_connections_; } float CubicBytes::BetaLastMax() const { return (num_connections_ - 1 + kBetaLastMax) / num_connections_; } void CubicBytes::ResetCubicState() { epoch_ = QuicTime::Zero(); last_max_congestion_window_ = 0; acked_bytes_count_ = 0; estimated_tcp_congestion_window_ = 0; origin_point_congestion_window_ = 0; time_to_origin_point_ = 0; last_target_congestion_window_ = 0; } void CubicBytes::OnApplicationLimited() { epoch_ = QuicTime::Zero(); } QuicByteCount CubicBytes::CongestionWindowAfterPacketLoss( QuicByteCount current_congestion_window) { if (current_congestion_window + kDefaultTCPMSS < last_max_congestion_window_) { last_max_congestion_window_ = static_cast<int>(BetaLastMax() * current_congestion_window); } else { last_max_congestion_window_ = current_congestion_window; } epoch_ = QuicTime::Zero(); return static_cast<int>(current_congestion_window * Beta()); } QuicByteCount CubicBytes::CongestionWindowAfterAck( QuicByteCount acked_bytes, QuicByteCount current_congestion_window, QuicTime::Delta delay_min, QuicTime event_time) { acked_bytes_count_ += acked_bytes; if (!epoch_.IsInitialized()) { QUIC_DVLOG(1) << "Start of epoch"; epoch_ = event_time; acked_bytes_count_ = acked_bytes; estimated_tcp_congestion_window_ = current_congestion_window; if (last_max_congestion_window_ <= current_congestion_window) { time_to_origin_point_ = 0; origin_point_congestion_window_ = current_congestion_window; } else { time_to_origin_point_ = static_cast<uint32_t>( cbrt(kCubeFactor * (last_max_congestion_window_ - current_congestion_window))); origin_point_congestion_window_ = last_max_congestion_window_; } } int64_t elapsed_time = ((event_time + delay_min - epoch_).ToMicroseconds() << 10) / kNumMicrosPerSecond; uint64_t offset = std::abs(time_to_origin_point_ - elapsed_time); QuicByteCount delta_congestion_window = (kCubeCongestionWindowScale * offset * offset * offset * kDefaultTCPMSS) >> kCubeScale; const bool add_delta = elapsed_time > time_to_origin_point_; QUICHE_DCHECK(add_delta || (origin_point_congestion_window_ > delta_congestion_window)); QuicByteCount target_congestion_window = add_delta ? origin_point_congestion_window_ + delta_congestion_window : origin_point_congestion_window_ - delta_congestion_window; target_congestion_window = std::min(target_congestion_window, current_congestion_window + acked_bytes_count_ / 2); QUICHE_DCHECK_LT(0u, estimated_tcp_congestion_window_); estimated_tcp_congestion_window_ += acked_bytes_count_ * (Alpha() * kDefaultTCPMSS) / estimated_tcp_congestion_window_; acked_bytes_count_ = 0; last_target_congestion_window_ = target_congestion_window; if (target_congestion_window < estimated_tcp_congestion_window_) { target_congestion_window = estimated_tcp_congestion_window_; } QUIC_DVLOG(1) << "Final target congestion_window: " << target_congestion_window; return target_congestion_window; } }
#include "quiche/quic/core/congestion_control/cubic_bytes.h" #include <cmath> #include <cstdint> #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_clock.h" namespace quic { namespace test { namespace { const float kBeta = 0.7f; const float kBetaLastMax = 0.85f; const uint32_t kNumConnections = 2; const float kNConnectionBeta = (kNumConnections - 1 + kBeta) / kNumConnections; const float kNConnectionBetaLastMax = (kNumConnections - 1 + kBetaLastMax) / kNumConnections; const float kNConnectionAlpha = 3 * kNumConnections * kNumConnections * (1 - kNConnectionBeta) / (1 + kNConnectionBeta); } class CubicBytesTest : public QuicTest { protected: CubicBytesTest() : one_ms_(QuicTime::Delta::FromMilliseconds(1)), hundred_ms_(QuicTime::Delta::FromMilliseconds(100)), cubic_(&clock_) {} QuicByteCount RenoCwndInBytes(QuicByteCount current_cwnd) { QuicByteCount reno_estimated_cwnd = current_cwnd + kDefaultTCPMSS * (kNConnectionAlpha * kDefaultTCPMSS) / current_cwnd; return reno_estimated_cwnd; } QuicByteCount ConservativeCwndInBytes(QuicByteCount current_cwnd) { QuicByteCount conservative_cwnd = current_cwnd + kDefaultTCPMSS / 2; return conservative_cwnd; } QuicByteCount CubicConvexCwndInBytes(QuicByteCount initial_cwnd, QuicTime::Delta rtt, QuicTime::Delta elapsed_time) { const int64_t offset = ((elapsed_time + rtt).ToMicroseconds() << 10) / 1000000; const QuicByteCount delta_congestion_window = ((410 * offset * offset * offset) * kDefaultTCPMSS >> 40); const QuicByteCount cubic_cwnd = initial_cwnd + delta_congestion_window; return cubic_cwnd; } QuicByteCount LastMaxCongestionWindow() { return cubic_.last_max_congestion_window(); } QuicTime::Delta MaxCubicTimeInterval() { return cubic_.MaxCubicTimeInterval(); } const QuicTime::Delta one_ms_; const QuicTime::Delta hundred_ms_; MockClock clock_; CubicBytes cubic_; }; TEST_F(CubicBytesTest, AboveOriginWithTighterBounds) { const QuicTime::Delta rtt_min = hundred_ms_; int64_t rtt_min_ms = rtt_min.ToMilliseconds(); float rtt_min_s = rtt_min_ms / 1000.0; QuicByteCount current_cwnd = 10 * kDefaultTCPMSS; const QuicByteCount initial_cwnd = current_cwnd; clock_.AdvanceTime(one_ms_); const QuicTime initial_time = clock_.ApproximateNow(); const QuicByteCount expected_first_cwnd = RenoCwndInBytes(current_cwnd); current_cwnd = cubic_.CongestionWindowAfterAck(kDefaultTCPMSS, current_cwnd, rtt_min, initial_time); ASSERT_EQ(expected_first_cwnd, current_cwnd); const int max_reno_rtts = std::sqrt(kNConnectionAlpha / (.4 * rtt_min_s * rtt_min_s * rtt_min_s)) - 2; for (int i = 0; i < max_reno_rtts; ++i) { const uint64_t num_acks_this_epoch = current_cwnd / kDefaultTCPMSS / kNConnectionAlpha; const QuicByteCount initial_cwnd_this_epoch = current_cwnd; for (QuicPacketCount n = 0; n < num_acks_this_epoch; ++n) { const QuicByteCount expected_next_cwnd = RenoCwndInBytes(current_cwnd); current_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()); ASSERT_EQ(expected_next_cwnd, current_cwnd); } const QuicByteCount cwnd_change_this_epoch = current_cwnd - initial_cwnd_this_epoch; ASSERT_NEAR(kDefaultTCPMSS, cwnd_change_this_epoch, kDefaultTCPMSS / 2); clock_.AdvanceTime(hundred_ms_); } for (int i = 0; i < 54; ++i) { const uint64_t max_acks_this_epoch = current_cwnd / kDefaultTCPMSS; const QuicTime::Delta interval = QuicTime::Delta::FromMicroseconds( hundred_ms_.ToMicroseconds() / max_acks_this_epoch); for (QuicPacketCount n = 0; n < max_acks_this_epoch; ++n) { clock_.AdvanceTime(interval); current_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()); const QuicByteCount expected_cwnd = CubicConvexCwndInBytes( initial_cwnd, rtt_min, (clock_.ApproximateNow() - initial_time)); ASSERT_EQ(expected_cwnd, current_cwnd); } } const QuicByteCount expected_cwnd = CubicConvexCwndInBytes( initial_cwnd, rtt_min, (clock_.ApproximateNow() - initial_time)); current_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()); ASSERT_EQ(expected_cwnd, current_cwnd); } TEST_F(CubicBytesTest, DISABLED_AboveOrigin) { const QuicTime::Delta rtt_min = hundred_ms_; QuicByteCount current_cwnd = 10 * kDefaultTCPMSS; QuicPacketCount expected_cwnd = RenoCwndInBytes(current_cwnd); clock_.AdvanceTime(one_ms_); ASSERT_EQ(expected_cwnd, cubic_.CongestionWindowAfterAck(kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow())); current_cwnd = expected_cwnd; const QuicPacketCount initial_cwnd = expected_cwnd; for (int i = 0; i < 48; ++i) { for (QuicPacketCount n = 1; n < current_cwnd / kDefaultTCPMSS / kNConnectionAlpha; ++n) { ASSERT_NEAR( current_cwnd, cubic_.CongestionWindowAfterAck(kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()), kDefaultTCPMSS); } clock_.AdvanceTime(hundred_ms_); current_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()); expected_cwnd += kDefaultTCPMSS; ASSERT_NEAR(expected_cwnd, current_cwnd, kDefaultTCPMSS); } for (int i = 0; i < 52; ++i) { for (QuicPacketCount n = 1; n < current_cwnd / kDefaultTCPMSS; ++n) { ASSERT_NEAR( current_cwnd, cubic_.CongestionWindowAfterAck(kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()), kDefaultTCPMSS); } clock_.AdvanceTime(hundred_ms_); current_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()); } float elapsed_time_s = 10.0f + 0.1f; expected_cwnd = initial_cwnd / kDefaultTCPMSS + (elapsed_time_s * elapsed_time_s * elapsed_time_s * 410) / 1024; EXPECT_EQ(expected_cwnd, current_cwnd / kDefaultTCPMSS); } TEST_F(CubicBytesTest, AboveOriginFineGrainedCubing) { QuicByteCount current_cwnd = 1000 * kDefaultTCPMSS; const QuicByteCount initial_cwnd = current_cwnd; const QuicTime::Delta rtt_min = hundred_ms_; clock_.AdvanceTime(one_ms_); QuicTime initial_time = clock_.ApproximateNow(); current_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(600)); current_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()); for (int i = 0; i < 100; ++i) { clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10)); const QuicByteCount expected_cwnd = CubicConvexCwndInBytes( initial_cwnd, rtt_min, (clock_.ApproximateNow() - initial_time)); const QuicByteCount next_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()); ASSERT_EQ(expected_cwnd, next_cwnd); ASSERT_GT(next_cwnd, current_cwnd); const QuicByteCount cwnd_delta = next_cwnd - current_cwnd; ASSERT_GT(kDefaultTCPMSS * .1, cwnd_delta); current_cwnd = next_cwnd; } } TEST_F(CubicBytesTest, PerAckUpdates) { QuicPacketCount initial_cwnd_packets = 150; QuicByteCount current_cwnd = initial_cwnd_packets * kDefaultTCPMSS; const QuicTime::Delta rtt_min = 350 * one_ms_; clock_.AdvanceTime(one_ms_); QuicByteCount reno_cwnd = RenoCwndInBytes(current_cwnd); current_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()); const QuicByteCount initial_cwnd = current_cwnd; const QuicPacketCount max_acks = initial_cwnd_packets / kNConnectionAlpha; const QuicTime::Delta interval = QuicTime::Delta::FromMicroseconds( MaxCubicTimeInterval().ToMicroseconds() / (max_acks + 1)); clock_.AdvanceTime(interval); reno_cwnd = RenoCwndInBytes(reno_cwnd); ASSERT_EQ(current_cwnd, cubic_.CongestionWindowAfterAck(kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow())); for (QuicPacketCount i = 1; i < max_acks; ++i) { clock_.AdvanceTime(interval); const QuicByteCount next_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()); reno_cwnd = RenoCwndInBytes(reno_cwnd); ASSERT_LT(current_cwnd, next_cwnd); ASSERT_EQ(reno_cwnd, next_cwnd); current_cwnd = next_cwnd; } const QuicByteCount minimum_expected_increase = kDefaultTCPMSS * .9; EXPECT_LT(minimum_expected_increase + initial_cwnd, current_cwnd); } TEST_F(CubicBytesTest, LossEvents) { const QuicTime::Delta rtt_min = hundred_ms_; QuicByteCount current_cwnd = 422 * kDefaultTCPMSS; QuicPacketCount expected_cwnd = RenoCwndInBytes(current_cwnd); clock_.AdvanceTime(one_ms_); EXPECT_EQ(expected_cwnd, cubic_.CongestionWindowAfterAck(kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow())); QuicByteCount pre_loss_cwnd = current_cwnd; ASSERT_EQ(0u, LastMaxCongestionWindow()); expected_cwnd = static_cast<QuicByteCount>(current_cwnd * kNConnectionBeta); EXPECT_EQ(expected_cwnd, cubic_.CongestionWindowAfterPacketLoss(current_cwnd)); ASSERT_EQ(pre_loss_cwnd, LastMaxCongestionWindow()); current_cwnd = expected_cwnd; pre_loss_cwnd = current_cwnd; expected_cwnd = static_cast<QuicByteCount>(current_cwnd * kNConnectionBeta); ASSERT_EQ(expected_cwnd, cubic_.CongestionWindowAfterPacketLoss(current_cwnd)); current_cwnd = expected_cwnd; EXPECT_GT(pre_loss_cwnd, LastMaxCongestionWindow()); QuicByteCount expected_last_max = static_cast<QuicByteCount>(pre_loss_cwnd * kNConnectionBetaLastMax); EXPECT_EQ(expected_last_max, LastMaxCongestionWindow()); EXPECT_LT(expected_cwnd, LastMaxCongestionWindow()); current_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()); EXPECT_GT(LastMaxCongestionWindow(), current_cwnd); current_cwnd = LastMaxCongestionWindow() - 1; pre_loss_cwnd = current_cwnd; expected_cwnd = static_cast<QuicByteCount>(current_cwnd * kNConnectionBeta); EXPECT_EQ(expected_cwnd, cubic_.CongestionWindowAfterPacketLoss(current_cwnd)); expected_last_max = pre_loss_cwnd; ASSERT_EQ(expected_last_max, LastMaxCongestionWindow()); } TEST_F(CubicBytesTest, BelowOrigin) { const QuicTime::Delta rtt_min = hundred_ms_; QuicByteCount current_cwnd = 422 * kDefaultTCPMSS; QuicPacketCount expected_cwnd = RenoCwndInBytes(current_cwnd); clock_.AdvanceTime(one_ms_); EXPECT_EQ(expected_cwnd, cubic_.CongestionWindowAfterAck(kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow())); expected_cwnd = static_cast<QuicPacketCount>(current_cwnd * kNConnectionBeta); EXPECT_EQ(expected_cwnd, cubic_.CongestionWindowAfterPacketLoss(current_cwnd)); current_cwnd = expected_cwnd; current_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()); for (int i = 0; i < 40; ++i) { clock_.AdvanceTime(hundred_ms_); current_cwnd = cubic_.CongestionWindowAfterAck( kDefaultTCPMSS, current_cwnd, rtt_min, clock_.ApproximateNow()); } expected_cwnd = 553632; EXPECT_EQ(expected_cwnd, current_cwnd); } } }
327
cpp
google/quiche
rtt_stats
quiche/quic/core/congestion_control/rtt_stats.cc
quiche/quic/core/congestion_control/rtt_stats_test.cc
#ifndef QUICHE_QUIC_CORE_CONGESTION_CONTROL_RTT_STATS_H_ #define QUICHE_QUIC_CORE_CONGESTION_CONTROL_RTT_STATS_H_ #include <algorithm> #include <cstdint> #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { namespace test { class RttStatsPeer; } class QUICHE_EXPORT RttStats { public: struct QUICHE_EXPORT StandardDeviationCalculator { StandardDeviationCalculator() {} void OnNewRttSample(QuicTime::Delta rtt_sample, QuicTime::Delta smoothed_rtt); QuicTime::Delta CalculateStandardDeviation() const; bool has_valid_standard_deviation = false; private: double m2 = 0; }; RttStats(); RttStats(const RttStats&) = delete; RttStats& operator=(const RttStats&) = delete; bool UpdateRtt(QuicTime::Delta send_delta, QuicTime::Delta ack_delay, QuicTime now); void ExpireSmoothedMetrics(); void OnConnectionMigration(); QuicTime::Delta smoothed_rtt() const { return smoothed_rtt_; } QuicTime::Delta previous_srtt() const { return previous_srtt_; } QuicTime::Delta initial_rtt() const { return initial_rtt_; } QuicTime::Delta SmoothedOrInitialRtt() const { return smoothed_rtt_.IsZero() ? initial_rtt_ : smoothed_rtt_; } QuicTime::Delta MinOrInitialRtt() const { return min_rtt_.IsZero() ? initial_rtt_ : min_rtt_; } void set_initial_rtt(QuicTime::Delta initial_rtt) { if (initial_rtt.ToMicroseconds() <= 0) { QUIC_BUG(quic_bug_10453_1) << "Attempt to set initial rtt to <= 0."; return; } initial_rtt_ = initial_rtt; } QuicTime::Delta latest_rtt() const { return latest_rtt_; } QuicTime::Delta min_rtt() const { return min_rtt_; } QuicTime::Delta mean_deviation() const { return mean_deviation_; } QuicTime::Delta GetStandardOrMeanDeviation() const; QuicTime last_update_time() const { return last_update_time_; } void EnableStandardDeviationCalculation() { calculate_standard_deviation_ = true; } void CloneFrom(const RttStats& stats); private: friend class test::RttStatsPeer; QuicTime::Delta latest_rtt_; QuicTime::Delta min_rtt_; QuicTime::Delta smoothed_rtt_; QuicTime::Delta previous_srtt_; QuicTime::Delta mean_deviation_; StandardDeviationCalculator standard_deviation_calculator_; bool calculate_standard_deviation_; QuicTime::Delta initial_rtt_; QuicTime last_update_time_; }; } #endif #include "quiche/quic/core/congestion_control/rtt_stats.h" #include <algorithm> #include <cstdlib> #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { namespace { const float kAlpha = 0.125f; const float kOneMinusAlpha = (1 - kAlpha); const float kBeta = 0.25f; const float kOneMinusBeta = (1 - kBeta); } RttStats::RttStats() : latest_rtt_(QuicTime::Delta::Zero()), min_rtt_(QuicTime::Delta::Zero()), smoothed_rtt_(QuicTime::Delta::Zero()), previous_srtt_(QuicTime::Delta::Zero()), mean_deviation_(QuicTime::Delta::Zero()), calculate_standard_deviation_(false), initial_rtt_(QuicTime::Delta::FromMilliseconds(kInitialRttMs)), last_update_time_(QuicTime::Zero()) {} void RttStats::ExpireSmoothedMetrics() { mean_deviation_ = std::max( mean_deviation_, QuicTime::Delta::FromMicroseconds(std::abs( (smoothed_rtt_ - latest_rtt_).ToMicroseconds()))); smoothed_rtt_ = std::max(smoothed_rtt_, latest_rtt_); } bool RttStats::UpdateRtt(QuicTime::Delta send_delta, QuicTime::Delta ack_delay, QuicTime now) { if (send_delta.IsInfinite() || send_delta <= QuicTime::Delta::Zero()) { QUIC_LOG_FIRST_N(WARNING, 3) << "Ignoring measured send_delta, because it's is " << "either infinite, zero, or negative. send_delta = " << send_delta.ToMicroseconds(); return false; } last_update_time_ = now; if (min_rtt_.IsZero() || min_rtt_ > send_delta) { min_rtt_ = send_delta; } QuicTime::Delta rtt_sample(send_delta); previous_srtt_ = smoothed_rtt_; if (rtt_sample > ack_delay) { if (rtt_sample - min_rtt_ >= ack_delay) { rtt_sample = rtt_sample - ack_delay; } else { QUIC_CODE_COUNT(quic_ack_delay_makes_rtt_sample_smaller_than_min_rtt); } } else { QUIC_CODE_COUNT(quic_ack_delay_greater_than_rtt_sample); } latest_rtt_ = rtt_sample; if (calculate_standard_deviation_) { standard_deviation_calculator_.OnNewRttSample(rtt_sample, smoothed_rtt_); } if (smoothed_rtt_.IsZero()) { smoothed_rtt_ = rtt_sample; mean_deviation_ = QuicTime::Delta::FromMicroseconds(rtt_sample.ToMicroseconds() / 2); } else { mean_deviation_ = QuicTime::Delta::FromMicroseconds(static_cast<int64_t>( kOneMinusBeta * mean_deviation_.ToMicroseconds() + kBeta * std::abs((smoothed_rtt_ - rtt_sample).ToMicroseconds()))); smoothed_rtt_ = kOneMinusAlpha * smoothed_rtt_ + kAlpha * rtt_sample; QUIC_DVLOG(1) << " smoothed_rtt(us):" << smoothed_rtt_.ToMicroseconds() << " mean_deviation(us):" << mean_deviation_.ToMicroseconds(); } return true; } void RttStats::OnConnectionMigration() { latest_rtt_ = QuicTime::Delta::Zero(); min_rtt_ = QuicTime::Delta::Zero(); smoothed_rtt_ = QuicTime::Delta::Zero(); mean_deviation_ = QuicTime::Delta::Zero(); initial_rtt_ = QuicTime::Delta::FromMilliseconds(kInitialRttMs); } QuicTime::Delta RttStats::GetStandardOrMeanDeviation() const { QUICHE_DCHECK(calculate_standard_deviation_); if (!standard_deviation_calculator_.has_valid_standard_deviation) { return mean_deviation_; } return standard_deviation_calculator_.CalculateStandardDeviation(); } void RttStats::StandardDeviationCalculator::OnNewRttSample( QuicTime::Delta rtt_sample, QuicTime::Delta smoothed_rtt) { double new_value = rtt_sample.ToMicroseconds(); if (smoothed_rtt.IsZero()) { return; } has_valid_standard_deviation = true; const double delta = new_value - smoothed_rtt.ToMicroseconds(); m2 = kOneMinusBeta * m2 + kBeta * pow(delta, 2); } QuicTime::Delta RttStats::StandardDeviationCalculator::CalculateStandardDeviation() const { QUICHE_DCHECK(has_valid_standard_deviation); return QuicTime::Delta::FromMicroseconds(sqrt(m2)); } void RttStats::CloneFrom(const RttStats& stats) { latest_rtt_ = stats.latest_rtt_; min_rtt_ = stats.min_rtt_; smoothed_rtt_ = stats.smoothed_rtt_; previous_srtt_ = stats.previous_srtt_; mean_deviation_ = stats.mean_deviation_; standard_deviation_calculator_ = stats.standard_deviation_calculator_; calculate_standard_deviation_ = stats.calculate_standard_deviation_; initial_rtt_ = stats.initial_rtt_; last_update_time_ = stats.last_update_time_; } }
#include "quiche/quic/core/congestion_control/rtt_stats.h" #include <cmath> #include <vector> #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" using testing::Message; namespace quic { namespace test { class RttStatsTest : public QuicTest { protected: RttStats rtt_stats_; }; TEST_F(RttStatsTest, DefaultsBeforeUpdate) { EXPECT_LT(QuicTime::Delta::Zero(), rtt_stats_.initial_rtt()); EXPECT_EQ(QuicTime::Delta::Zero(), rtt_stats_.min_rtt()); EXPECT_EQ(QuicTime::Delta::Zero(), rtt_stats_.smoothed_rtt()); } TEST_F(RttStatsTest, SmoothedRtt) { rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(300), QuicTime::Delta::FromMilliseconds(100), QuicTime::Zero()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(300), rtt_stats_.latest_rtt()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(300), rtt_stats_.smoothed_rtt()); rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(400), QuicTime::Delta::FromMilliseconds(100), QuicTime::Zero()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(300), rtt_stats_.latest_rtt()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(300), rtt_stats_.smoothed_rtt()); rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(350), QuicTime::Delta::FromMilliseconds(50), QuicTime::Zero()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(300), rtt_stats_.latest_rtt()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(300), rtt_stats_.smoothed_rtt()); rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(200), QuicTime::Delta::FromMilliseconds(300), QuicTime::Zero()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.latest_rtt()); EXPECT_EQ(QuicTime::Delta::FromMicroseconds(287500), rtt_stats_.smoothed_rtt()); } TEST_F(RttStatsTest, SmoothedRttStability) { for (size_t time = 3; time < 20000; time++) { RttStats stats; for (size_t i = 0; i < 100; i++) { stats.UpdateRtt(QuicTime::Delta::FromMicroseconds(time), QuicTime::Delta::FromMilliseconds(0), QuicTime::Zero()); int64_t time_delta_us = stats.smoothed_rtt().ToMicroseconds() - time; ASSERT_LE(std::abs(time_delta_us), 1); } } } TEST_F(RttStatsTest, PreviousSmoothedRtt) { rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(200), QuicTime::Delta::FromMilliseconds(0), QuicTime::Zero()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.latest_rtt()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.smoothed_rtt()); EXPECT_EQ(QuicTime::Delta::Zero(), rtt_stats_.previous_srtt()); rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(100), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(100), rtt_stats_.latest_rtt()); EXPECT_EQ(QuicTime::Delta::FromMicroseconds(187500).ToMicroseconds(), rtt_stats_.smoothed_rtt().ToMicroseconds()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.previous_srtt()); } TEST_F(RttStatsTest, MinRtt) { rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(200), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.min_rtt()); rtt_stats_.UpdateRtt( QuicTime::Delta::FromMilliseconds(10), QuicTime::Delta::Zero(), QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(10)); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.min_rtt()); rtt_stats_.UpdateRtt( QuicTime::Delta::FromMilliseconds(50), QuicTime::Delta::Zero(), QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(20)); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.min_rtt()); rtt_stats_.UpdateRtt( QuicTime::Delta::FromMilliseconds(50), QuicTime::Delta::Zero(), QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(30)); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.min_rtt()); rtt_stats_.UpdateRtt( QuicTime::Delta::FromMilliseconds(50), QuicTime::Delta::Zero(), QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(40)); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.min_rtt()); rtt_stats_.UpdateRtt( QuicTime::Delta::FromMilliseconds(7), QuicTime::Delta::FromMilliseconds(2), QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(50)); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(7), rtt_stats_.min_rtt()); } TEST_F(RttStatsTest, ExpireSmoothedMetrics) { QuicTime::Delta initial_rtt = QuicTime::Delta::FromMilliseconds(10); rtt_stats_.UpdateRtt(initial_rtt, QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_EQ(initial_rtt, rtt_stats_.min_rtt()); EXPECT_EQ(initial_rtt, rtt_stats_.smoothed_rtt()); EXPECT_EQ(0.5 * initial_rtt, rtt_stats_.mean_deviation()); QuicTime::Delta doubled_rtt = 2 * initial_rtt; rtt_stats_.UpdateRtt(doubled_rtt, QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_EQ(1.125 * initial_rtt, rtt_stats_.smoothed_rtt()); rtt_stats_.ExpireSmoothedMetrics(); EXPECT_EQ(doubled_rtt, rtt_stats_.smoothed_rtt()); EXPECT_EQ(0.875 * initial_rtt, rtt_stats_.mean_deviation()); QuicTime::Delta half_rtt = 0.5 * initial_rtt; rtt_stats_.UpdateRtt(half_rtt, QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_GT(doubled_rtt, rtt_stats_.smoothed_rtt()); EXPECT_LT(initial_rtt, rtt_stats_.mean_deviation()); } TEST_F(RttStatsTest, UpdateRttWithBadSendDeltas) { QuicTime::Delta initial_rtt = QuicTime::Delta::FromMilliseconds(10); rtt_stats_.UpdateRtt(initial_rtt, QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_EQ(initial_rtt, rtt_stats_.min_rtt()); EXPECT_EQ(initial_rtt, rtt_stats_.smoothed_rtt()); std::vector<QuicTime::Delta> bad_send_deltas; bad_send_deltas.push_back(QuicTime::Delta::Zero()); bad_send_deltas.push_back(QuicTime::Delta::Infinite()); bad_send_deltas.push_back(QuicTime::Delta::FromMicroseconds(-1000)); for (QuicTime::Delta bad_send_delta : bad_send_deltas) { SCOPED_TRACE(Message() << "bad_send_delta = " << bad_send_delta.ToMicroseconds()); EXPECT_FALSE(rtt_stats_.UpdateRtt(bad_send_delta, QuicTime::Delta::Zero(), QuicTime::Zero())); EXPECT_EQ(initial_rtt, rtt_stats_.min_rtt()); EXPECT_EQ(initial_rtt, rtt_stats_.smoothed_rtt()); } } TEST_F(RttStatsTest, ResetAfterConnectionMigrations) { rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(200), QuicTime::Delta::FromMilliseconds(0), QuicTime::Zero()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.latest_rtt()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.smoothed_rtt()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.min_rtt()); rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(300), QuicTime::Delta::FromMilliseconds(100), QuicTime::Zero()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.latest_rtt()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.smoothed_rtt()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.min_rtt()); rtt_stats_.OnConnectionMigration(); EXPECT_EQ(QuicTime::Delta::Zero(), rtt_stats_.latest_rtt()); EXPECT_EQ(QuicTime::Delta::Zero(), rtt_stats_.smoothed_rtt()); EXPECT_EQ(QuicTime::Delta::Zero(), rtt_stats_.min_rtt()); } TEST_F(RttStatsTest, StandardDeviationCalculatorTest1) { rtt_stats_.EnableStandardDeviationCalculation(); rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(10), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_EQ(rtt_stats_.mean_deviation(), rtt_stats_.GetStandardOrMeanDeviation()); rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(10), QuicTime::Delta::Zero(), QuicTime::Zero()); rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(10), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_EQ(QuicTime::Delta::Zero(), rtt_stats_.GetStandardOrMeanDeviation()); } TEST_F(RttStatsTest, StandardDeviationCalculatorTest2) { rtt_stats_.EnableStandardDeviationCalculation(); rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(10), QuicTime::Delta::Zero(), QuicTime::Zero()); rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(10), QuicTime::Delta::Zero(), QuicTime::Zero()); rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(10), QuicTime::Delta::Zero(), QuicTime::Zero()); rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(9), QuicTime::Delta::Zero(), QuicTime::Zero()); rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(11), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_LT(QuicTime::Delta::FromMicroseconds(500), rtt_stats_.GetStandardOrMeanDeviation()); EXPECT_GT(QuicTime::Delta::FromMilliseconds(1), rtt_stats_.GetStandardOrMeanDeviation()); } TEST_F(RttStatsTest, StandardDeviationCalculatorTest3) { rtt_stats_.EnableStandardDeviationCalculation(); rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(50), QuicTime::Delta::Zero(), QuicTime::Zero()); rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(100), QuicTime::Delta::Zero(), QuicTime::Zero()); rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(100), QuicTime::Delta::Zero(), QuicTime::Zero()); rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(50), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_APPROX_EQ(rtt_stats_.mean_deviation(), rtt_stats_.GetStandardOrMeanDeviation(), 0.25f); } } }
328
cpp
google/quiche
general_loss_algorithm
quiche/quic/core/congestion_control/general_loss_algorithm.cc
quiche/quic/core/congestion_control/general_loss_algorithm_test.cc
#ifndef QUICHE_QUIC_CORE_CONGESTION_CONTROL_GENERAL_LOSS_ALGORITHM_H_ #define QUICHE_QUIC_CORE_CONGESTION_CONTROL_GENERAL_LOSS_ALGORITHM_H_ #include <algorithm> #include <map> #include "quiche/quic/core/congestion_control/loss_detection_interface.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_unacked_packet_map.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT GeneralLossAlgorithm : public LossDetectionInterface { public: GeneralLossAlgorithm() = default; GeneralLossAlgorithm(const GeneralLossAlgorithm&) = delete; GeneralLossAlgorithm& operator=(const GeneralLossAlgorithm&) = delete; ~GeneralLossAlgorithm() override {} void SetFromConfig(const QuicConfig& , Perspective ) override {} DetectionStats DetectLosses(const QuicUnackedPacketMap& unacked_packets, QuicTime time, const RttStats& rtt_stats, QuicPacketNumber largest_newly_acked, const AckedPacketVector& packets_acked, LostPacketVector* packets_lost) override; QuicTime GetLossTimeout() const override; void SpuriousLossDetected(const QuicUnackedPacketMap& unacked_packets, const RttStats& rtt_stats, QuicTime ack_receive_time, QuicPacketNumber packet_number, QuicPacketNumber previous_largest_acked) override; void OnConfigNegotiated() override { QUICHE_DCHECK(false) << "Unexpected call to GeneralLossAlgorithm::OnConfigNegotiated"; } void OnMinRttAvailable() override { QUICHE_DCHECK(false) << "Unexpected call to GeneralLossAlgorithm::OnMinRttAvailable"; } void OnUserAgentIdKnown() override { QUICHE_DCHECK(false) << "Unexpected call to GeneralLossAlgorithm::OnUserAgentIdKnown"; } void OnConnectionClosed() override { QUICHE_DCHECK(false) << "Unexpected call to GeneralLossAlgorithm::OnConnectionClosed"; } void OnReorderingDetected() override { QUICHE_DCHECK(false) << "Unexpected call to GeneralLossAlgorithm::OnReorderingDetected"; } void Initialize(PacketNumberSpace packet_number_space, LossDetectionInterface* parent); void Reset(); QuicPacketCount reordering_threshold() const { return reordering_threshold_; } int reordering_shift() const { return reordering_shift_; } void set_reordering_shift(int reordering_shift) { reordering_shift_ = reordering_shift; } void set_reordering_threshold(QuicPacketCount reordering_threshold) { reordering_threshold_ = reordering_threshold; } bool use_adaptive_reordering_threshold() const { return use_adaptive_reordering_threshold_; } void set_use_adaptive_reordering_threshold(bool value) { use_adaptive_reordering_threshold_ = value; } bool use_adaptive_time_threshold() const { return use_adaptive_time_threshold_; } void enable_adaptive_time_threshold() { use_adaptive_time_threshold_ = true; } bool use_packet_threshold_for_runt_packets() const { return use_packet_threshold_for_runt_packets_; } void disable_packet_threshold_for_runt_packets() { use_packet_threshold_for_runt_packets_ = false; } private: LossDetectionInterface* parent_ = nullptr; QuicTime loss_detection_timeout_ = QuicTime::Zero(); int reordering_shift_ = kDefaultLossDelayShift; QuicPacketCount reordering_threshold_ = kDefaultPacketReorderingThreshold; bool use_adaptive_reordering_threshold_ = true; bool use_adaptive_time_threshold_ = false; bool use_packet_threshold_for_runt_packets_ = true; QuicPacketNumber least_in_flight_{1}; PacketNumberSpace packet_number_space_ = NUM_PACKET_NUMBER_SPACES; }; } #endif #include "quiche/quic/core/congestion_control/general_loss_algorithm.h" #include <algorithm> #include "quiche/quic/core/congestion_control/rtt_stats.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" namespace quic { namespace { float DetectionResponseTime(QuicTime::Delta rtt, QuicTime send_time, QuicTime detection_time) { if (detection_time <= send_time || rtt.IsZero()) { return 1.0; } float send_to_detection_us = (detection_time - send_time).ToMicroseconds(); return send_to_detection_us / rtt.ToMicroseconds(); } QuicTime::Delta GetMaxRtt(const RttStats& rtt_stats) { return std::max(kAlarmGranularity, std::max(rtt_stats.previous_srtt(), rtt_stats.latest_rtt())); } } LossDetectionInterface::DetectionStats GeneralLossAlgorithm::DetectLosses( const QuicUnackedPacketMap& unacked_packets, QuicTime time, const RttStats& rtt_stats, QuicPacketNumber largest_newly_acked, const AckedPacketVector& packets_acked, LostPacketVector* packets_lost) { DetectionStats detection_stats; loss_detection_timeout_ = QuicTime::Zero(); if (!packets_acked.empty() && least_in_flight_.IsInitialized() && packets_acked.front().packet_number == least_in_flight_) { if (packets_acked.back().packet_number == largest_newly_acked && least_in_flight_ + packets_acked.size() - 1 == largest_newly_acked) { least_in_flight_ = largest_newly_acked + 1; return detection_stats; } for (const auto& acked : packets_acked) { if (acked.packet_number != least_in_flight_) { break; } ++least_in_flight_; } } const QuicTime::Delta max_rtt = GetMaxRtt(rtt_stats); QuicPacketNumber packet_number = unacked_packets.GetLeastUnacked(); auto it = unacked_packets.begin(); if (least_in_flight_.IsInitialized() && least_in_flight_ >= packet_number) { if (least_in_flight_ > unacked_packets.largest_sent_packet() + 1) { QUIC_BUG(quic_bug_10430_1) << "least_in_flight: " << least_in_flight_ << " is greater than largest_sent_packet + 1: " << unacked_packets.largest_sent_packet() + 1; } else { it += (least_in_flight_ - packet_number); packet_number = least_in_flight_; } } least_in_flight_.Clear(); QUICHE_DCHECK_EQ(packet_number_space_, unacked_packets.GetPacketNumberSpace(largest_newly_acked)); for (; it != unacked_packets.end() && packet_number <= largest_newly_acked; ++it, ++packet_number) { if (unacked_packets.GetPacketNumberSpace(it->encryption_level) != packet_number_space_) { continue; } if (!it->in_flight) { continue; } if (parent_ != nullptr && largest_newly_acked != packet_number) { parent_->OnReorderingDetected(); } if (largest_newly_acked - packet_number > detection_stats.sent_packets_max_sequence_reordering) { detection_stats.sent_packets_max_sequence_reordering = largest_newly_acked - packet_number; } const bool skip_packet_threshold_detection = !use_packet_threshold_for_runt_packets_ && it->bytes_sent > unacked_packets.GetTransmissionInfo(largest_newly_acked).bytes_sent; if (!skip_packet_threshold_detection && largest_newly_acked - packet_number >= reordering_threshold_) { packets_lost->push_back(LostPacket(packet_number, it->bytes_sent)); detection_stats.total_loss_detection_response_time += DetectionResponseTime(max_rtt, it->sent_time, time); continue; } const QuicTime::Delta loss_delay = max_rtt + (max_rtt >> reordering_shift_); QuicTime when_lost = it->sent_time + loss_delay; if (time < when_lost) { if (time >= it->sent_time + max_rtt + (max_rtt >> (reordering_shift_ + 1))) { ++detection_stats.sent_packets_num_borderline_time_reorderings; } loss_detection_timeout_ = when_lost; if (!least_in_flight_.IsInitialized()) { least_in_flight_ = packet_number; } break; } packets_lost->push_back(LostPacket(packet_number, it->bytes_sent)); detection_stats.total_loss_detection_response_time += DetectionResponseTime(max_rtt, it->sent_time, time); } if (!least_in_flight_.IsInitialized()) { least_in_flight_ = largest_newly_acked + 1; } return detection_stats; } QuicTime GeneralLossAlgorithm::GetLossTimeout() const { return loss_detection_timeout_; } void GeneralLossAlgorithm::SpuriousLossDetected( const QuicUnackedPacketMap& unacked_packets, const RttStats& rtt_stats, QuicTime ack_receive_time, QuicPacketNumber packet_number, QuicPacketNumber previous_largest_acked) { if (use_adaptive_time_threshold_ && reordering_shift_ > 0) { QuicTime::Delta time_needed = ack_receive_time - unacked_packets.GetTransmissionInfo(packet_number).sent_time; QuicTime::Delta max_rtt = std::max(rtt_stats.previous_srtt(), rtt_stats.latest_rtt()); while (max_rtt + (max_rtt >> reordering_shift_) < time_needed && reordering_shift_ > 0) { --reordering_shift_; } } if (use_adaptive_reordering_threshold_) { QUICHE_DCHECK_LT(packet_number, previous_largest_acked); reordering_threshold_ = std::max( reordering_threshold_, previous_largest_acked - packet_number + 1); } } void GeneralLossAlgorithm::Initialize(PacketNumberSpace packet_number_space, LossDetectionInterface* parent) { parent_ = parent; if (packet_number_space_ < NUM_PACKET_NUMBER_SPACES) { QUIC_BUG(quic_bug_10430_2) << "Cannot switch packet_number_space"; return; } packet_number_space_ = packet_number_space; } void GeneralLossAlgorithm::Reset() { loss_detection_timeout_ = QuicTime::Zero(); least_in_flight_.Clear(); } }
#include "quiche/quic/core/congestion_control/general_loss_algorithm.h" #include <algorithm> #include <cstdint> #include <optional> #include <vector> #include "quiche/quic/core/congestion_control/rtt_stats.h" #include "quiche/quic/core/quic_unacked_packet_map.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_clock.h" namespace quic { namespace test { namespace { const uint32_t kDefaultLength = 1000; class GeneralLossAlgorithmTest : public QuicTest { protected: GeneralLossAlgorithmTest() : unacked_packets_(Perspective::IS_CLIENT) { rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(100), QuicTime::Delta::Zero(), clock_.Now()); EXPECT_LT(0, rtt_stats_.smoothed_rtt().ToMicroseconds()); loss_algorithm_.Initialize(HANDSHAKE_DATA, nullptr); } ~GeneralLossAlgorithmTest() override {} void SendDataPacket(uint64_t packet_number, QuicPacketLength encrypted_length) { QuicStreamFrame frame; frame.stream_id = QuicUtils::GetFirstBidirectionalStreamId( CurrentSupportedVersions()[0].transport_version, Perspective::IS_CLIENT); SerializedPacket packet(QuicPacketNumber(packet_number), PACKET_1BYTE_PACKET_NUMBER, nullptr, encrypted_length, false, false); packet.retransmittable_frames.push_back(QuicFrame(frame)); unacked_packets_.AddSentPacket(&packet, NOT_RETRANSMISSION, clock_.Now(), true, true, ECN_NOT_ECT); } void SendDataPacket(uint64_t packet_number) { SendDataPacket(packet_number, kDefaultLength); } void SendAckPacket(uint64_t packet_number) { SerializedPacket packet(QuicPacketNumber(packet_number), PACKET_1BYTE_PACKET_NUMBER, nullptr, kDefaultLength, true, false); unacked_packets_.AddSentPacket(&packet, NOT_RETRANSMISSION, clock_.Now(), false, true, ECN_NOT_ECT); } void VerifyLosses(uint64_t largest_newly_acked, const AckedPacketVector& packets_acked, const std::vector<uint64_t>& losses_expected) { return VerifyLosses(largest_newly_acked, packets_acked, losses_expected, std::nullopt, std::nullopt); } void VerifyLosses( uint64_t largest_newly_acked, const AckedPacketVector& packets_acked, const std::vector<uint64_t>& losses_expected, std::optional<QuicPacketCount> max_sequence_reordering_expected, std::optional<QuicPacketCount> num_borderline_time_reorderings_expected) { unacked_packets_.MaybeUpdateLargestAckedOfPacketNumberSpace( APPLICATION_DATA, QuicPacketNumber(largest_newly_acked)); LostPacketVector lost_packets; LossDetectionInterface::DetectionStats stats = loss_algorithm_.DetectLosses( unacked_packets_, clock_.Now(), rtt_stats_, QuicPacketNumber(largest_newly_acked), packets_acked, &lost_packets); if (max_sequence_reordering_expected.has_value()) { EXPECT_EQ(stats.sent_packets_max_sequence_reordering, max_sequence_reordering_expected.value()); } if (num_borderline_time_reorderings_expected.has_value()) { EXPECT_EQ(stats.sent_packets_num_borderline_time_reorderings, num_borderline_time_reorderings_expected.value()); } ASSERT_EQ(losses_expected.size(), lost_packets.size()); for (size_t i = 0; i < losses_expected.size(); ++i) { EXPECT_EQ(lost_packets[i].packet_number, QuicPacketNumber(losses_expected[i])); } } QuicUnackedPacketMap unacked_packets_; GeneralLossAlgorithm loss_algorithm_; RttStats rtt_stats_; MockClock clock_; }; TEST_F(GeneralLossAlgorithmTest, NackRetransmit1Packet) { const size_t kNumSentPackets = 5; for (size_t i = 1; i <= kNumSentPackets; ++i) { SendDataPacket(i); } AckedPacketVector packets_acked; unacked_packets_.RemoveFromInFlight(QuicPacketNumber(2)); packets_acked.push_back(AckedPacket( QuicPacketNumber(2), kMaxOutgoingPacketSize, QuicTime::Zero())); VerifyLosses(2, packets_acked, std::vector<uint64_t>{}, 1, 0); packets_acked.clear(); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(3)); packets_acked.push_back(AckedPacket( QuicPacketNumber(3), kMaxOutgoingPacketSize, QuicTime::Zero())); VerifyLosses(3, packets_acked, std::vector<uint64_t>{}, 2, 0); packets_acked.clear(); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(4)); packets_acked.push_back(AckedPacket( QuicPacketNumber(4), kMaxOutgoingPacketSize, QuicTime::Zero())); VerifyLosses(4, packets_acked, {1}, 3, 0); EXPECT_EQ(QuicTime::Zero(), loss_algorithm_.GetLossTimeout()); } TEST_F(GeneralLossAlgorithmTest, NackRetransmit1PacketWith1StretchAck) { const size_t kNumSentPackets = 10; for (size_t i = 1; i <= kNumSentPackets; ++i) { SendDataPacket(i); } AckedPacketVector packets_acked; unacked_packets_.RemoveFromInFlight(QuicPacketNumber(2)); packets_acked.push_back(AckedPacket( QuicPacketNumber(2), kMaxOutgoingPacketSize, QuicTime::Zero())); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(3)); packets_acked.push_back(AckedPacket( QuicPacketNumber(3), kMaxOutgoingPacketSize, QuicTime::Zero())); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(4)); packets_acked.push_back(AckedPacket( QuicPacketNumber(4), kMaxOutgoingPacketSize, QuicTime::Zero())); VerifyLosses(4, packets_acked, {1}); EXPECT_EQ(QuicTime::Zero(), loss_algorithm_.GetLossTimeout()); } TEST_F(GeneralLossAlgorithmTest, NackRetransmit1PacketSingleAck) { const size_t kNumSentPackets = 10; for (size_t i = 1; i <= kNumSentPackets; ++i) { SendDataPacket(i); } AckedPacketVector packets_acked; unacked_packets_.RemoveFromInFlight(QuicPacketNumber(4)); packets_acked.push_back(AckedPacket( QuicPacketNumber(4), kMaxOutgoingPacketSize, QuicTime::Zero())); VerifyLosses(4, packets_acked, {1}); EXPECT_EQ(clock_.Now() + 1.25 * rtt_stats_.smoothed_rtt(), loss_algorithm_.GetLossTimeout()); } TEST_F(GeneralLossAlgorithmTest, EarlyRetransmit1Packet) { const size_t kNumSentPackets = 2; for (size_t i = 1; i <= kNumSentPackets; ++i) { SendDataPacket(i); } AckedPacketVector packets_acked; unacked_packets_.RemoveFromInFlight(QuicPacketNumber(2)); packets_acked.push_back(AckedPacket( QuicPacketNumber(2), kMaxOutgoingPacketSize, QuicTime::Zero())); VerifyLosses(2, packets_acked, std::vector<uint64_t>{}); packets_acked.clear(); EXPECT_EQ(clock_.Now() + 1.25 * rtt_stats_.smoothed_rtt(), loss_algorithm_.GetLossTimeout()); clock_.AdvanceTime(1.13 * rtt_stats_.latest_rtt()); VerifyLosses(2, packets_acked, {}, 1, 1); clock_.AdvanceTime(0.13 * rtt_stats_.latest_rtt()); VerifyLosses(2, packets_acked, {1}); EXPECT_EQ(QuicTime::Zero(), loss_algorithm_.GetLossTimeout()); } TEST_F(GeneralLossAlgorithmTest, EarlyRetransmitAllPackets) { const size_t kNumSentPackets = 5; for (size_t i = 1; i <= kNumSentPackets; ++i) { SendDataPacket(i); if (i == 3) { clock_.AdvanceTime(0.25 * rtt_stats_.smoothed_rtt()); } } AckedPacketVector packets_acked; unacked_packets_.RemoveFromInFlight(QuicPacketNumber(kNumSentPackets)); packets_acked.push_back(AckedPacket(QuicPacketNumber(kNumSentPackets), kMaxOutgoingPacketSize, QuicTime::Zero())); VerifyLosses(kNumSentPackets, packets_acked, {1, 2}); packets_acked.clear(); EXPECT_EQ(clock_.Now() + rtt_stats_.smoothed_rtt(), loss_algorithm_.GetLossTimeout()); clock_.AdvanceTime(rtt_stats_.smoothed_rtt()); VerifyLosses(kNumSentPackets, packets_acked, {3}); EXPECT_EQ(clock_.Now() + 0.25 * rtt_stats_.smoothed_rtt(), loss_algorithm_.GetLossTimeout()); clock_.AdvanceTime(0.25 * rtt_stats_.smoothed_rtt()); VerifyLosses(kNumSentPackets, packets_acked, {4}); EXPECT_EQ(QuicTime::Zero(), loss_algorithm_.GetLossTimeout()); } TEST_F(GeneralLossAlgorithmTest, DontEarlyRetransmitNeuteredPacket) { const size_t kNumSentPackets = 2; for (size_t i = 1; i <= kNumSentPackets; ++i) { SendDataPacket(i); } AckedPacketVector packets_acked; unacked_packets_.RemoveRetransmittability(QuicPacketNumber(1)); clock_.AdvanceTime(rtt_stats_.smoothed_rtt()); unacked_packets_.MaybeUpdateLargestAckedOfPacketNumberSpace( APPLICATION_DATA, QuicPacketNumber(2)); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(2)); packets_acked.push_back(AckedPacket( QuicPacketNumber(2), kMaxOutgoingPacketSize, QuicTime::Zero())); VerifyLosses(2, packets_acked, std::vector<uint64_t>{}); EXPECT_EQ(clock_.Now() + 0.25 * rtt_stats_.smoothed_rtt(), loss_algorithm_.GetLossTimeout()); } TEST_F(GeneralLossAlgorithmTest, EarlyRetransmitWithLargerUnackablePackets) { SendDataPacket(1); SendDataPacket(2); SendAckPacket(3); AckedPacketVector packets_acked; clock_.AdvanceTime(rtt_stats_.smoothed_rtt()); unacked_packets_.MaybeUpdateLargestAckedOfPacketNumberSpace( APPLICATION_DATA, QuicPacketNumber(2)); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(2)); packets_acked.push_back(AckedPacket( QuicPacketNumber(2), kMaxOutgoingPacketSize, QuicTime::Zero())); VerifyLosses(2, packets_acked, std::vector<uint64_t>{}); packets_acked.clear(); EXPECT_EQ(clock_.Now() + 0.25 * rtt_stats_.smoothed_rtt(), loss_algorithm_.GetLossTimeout()); clock_.AdvanceTime(0.25 * rtt_stats_.latest_rtt()); VerifyLosses(2, packets_acked, {1}); EXPECT_EQ(QuicTime::Zero(), loss_algorithm_.GetLossTimeout()); } TEST_F(GeneralLossAlgorithmTest, AlwaysLosePacketSent1RTTEarlier) { SendDataPacket(1); clock_.AdvanceTime(rtt_stats_.smoothed_rtt() + QuicTime::Delta::FromMilliseconds(1)); SendDataPacket(2); SendDataPacket(3); AckedPacketVector packets_acked; clock_.AdvanceTime(rtt_stats_.smoothed_rtt()); unacked_packets_.MaybeUpdateLargestAckedOfPacketNumberSpace( APPLICATION_DATA, QuicPacketNumber(2)); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(2)); packets_acked.push_back(AckedPacket( QuicPacketNumber(2), kMaxOutgoingPacketSize, QuicTime::Zero())); VerifyLosses(2, packets_acked, {1}); } TEST_F(GeneralLossAlgorithmTest, IncreaseTimeThresholdUponSpuriousLoss) { loss_algorithm_.enable_adaptive_time_threshold(); loss_algorithm_.set_reordering_shift(kDefaultLossDelayShift); EXPECT_EQ(kDefaultLossDelayShift, loss_algorithm_.reordering_shift()); EXPECT_TRUE(loss_algorithm_.use_adaptive_time_threshold()); const size_t kNumSentPackets = 10; for (size_t i = 1; i <= kNumSentPackets; ++i) { SendDataPacket(i); clock_.AdvanceTime(0.1 * rtt_stats_.smoothed_rtt()); } EXPECT_EQ(QuicTime::Zero() + rtt_stats_.smoothed_rtt(), clock_.Now()); AckedPacketVector packets_acked; EXPECT_EQ(QuicTime::Zero(), loss_algorithm_.GetLossTimeout()); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(2)); packets_acked.push_back(AckedPacket( QuicPacketNumber(2), kMaxOutgoingPacketSize, QuicTime::Zero())); VerifyLosses(2, packets_acked, std::vector<uint64_t>{}); packets_acked.clear(); EXPECT_EQ(rtt_stats_.smoothed_rtt() * (1.0f / 4), loss_algorithm_.GetLossTimeout() - clock_.Now()); VerifyLosses(2, packets_acked, std::vector<uint64_t>{}); clock_.AdvanceTime(rtt_stats_.smoothed_rtt() * (1.0f / 4)); VerifyLosses(2, packets_acked, {1}); EXPECT_EQ(QuicTime::Zero(), loss_algorithm_.GetLossTimeout()); SendDataPacket(11); SendDataPacket(12); clock_.AdvanceTime(rtt_stats_.smoothed_rtt() * (1.0f / 4)); loss_algorithm_.SpuriousLossDetected(unacked_packets_, rtt_stats_, clock_.Now(), QuicPacketNumber(1), QuicPacketNumber(2)); EXPECT_EQ(1, loss_algorithm_.reordering_shift()); } TEST_F(GeneralLossAlgorithmTest, IncreaseReorderingThresholdUponSpuriousLoss) { loss_algorithm_.set_use_adaptive_reordering_threshold(true); for (size_t i = 1; i <= 4; ++i) { SendDataPacket(i); } AckedPacketVector packets_acked; unacked_packets_.RemoveFromInFlight(QuicPacketNumber(4)); packets_acked.push_back(AckedPacket( QuicPacketNumber(4), kMaxOutgoingPacketSize, QuicTime::Zero())); VerifyLosses(4, packets_acked, std::vector<uint64_t>{1}); packets_acked.clear(); SendDataPacket(5); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(1)); packets_acked.push_back(AckedPacket( QuicPacketNumber(1), kMaxOutgoingPacketSize, QuicTime::Zero())); loss_algorithm_.SpuriousLossDetected(unacked_packets_, rtt_stats_, clock_.Now(), QuicPacketNumber(1), QuicPacketNumber(4)); VerifyLosses(4, packets_acked, std::vector<uint64_t>{}); packets_acked.clear(); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(5)); packets_acked.push_back(AckedPacket( QuicPacketNumber(5), kMaxOutgoingPacketSize, QuicTime::Zero())); VerifyLosses(5, packets_acked, std::vector<uint64_t>{}); packets_acked.clear(); SendDataPacket(6); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(6)); packets_acked.push_back(AckedPacket( QuicPacketNumber(6), kMaxOutgoingPacketSize, QuicTime::Zero())); VerifyLosses(6, packets_acked, std::vector<uint64_t>{2}); packets_acked.clear(); SendDataPacket(7); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(2)); packets_acked.push_back(AckedPacket( QuicPacketNumber(2), kMaxOutgoingPacketSize, QuicTime::Zero())); loss_algorithm_.SpuriousLossDetected(unacked_packets_, rtt_stats_, clock_.Now(), QuicPacketNumber(2), QuicPacketNumber(6)); VerifyLosses(6, packets_acked, std::vector<uint64_t>{}); packets_acked.clear(); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(7)); packets_acked.push_back(AckedPacket( QuicPacketNumber(7), kMaxOutgoingPacketSize, QuicTime::Zero())); VerifyLosses(7, packets_acked, std::vector<uint64_t>{}); packets_acked.clear(); } TEST_F(GeneralLossAlgorithmTest, DefaultIetfLossDetection) { loss_algorithm_.set_reordering_shift(kDefaultIetfLossDelayShift); for (size_t i = 1; i <= 6; ++i) { SendDataPacket(i); } AckedPacketVector packets_acked; unacked_packets_.RemoveFromInFlight(QuicPacketNumber(2)); packets_acked.push_back(AckedPacket( QuicPacketNumber(2), kMaxOutgoingPacketSize, QuicTime::Zero())); VerifyLosses(2, packets_acked, std::vector<uint64_t>{}); packets_acked.clear(); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(3)); packets_acked.push_back(AckedPacket( QuicPacketNumber(3), kMaxOutgoingPacketSize, QuicTime::Zero())); VerifyLosses(3, packets_acked, std::vector<uint64_t>{}); packets_acked.clear(); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(4)); packets_acked.push_back(AckedPacket( QuicPacketNumber(4), kMaxOutgoingPacketSize, QuicTime::Zero())); VerifyLosses(4, packets_acked, {1}); EXPECT_EQ(QuicTime::Zero(), loss_algorithm_.GetLossTimeout()); packets_acked.clear(); SendDataPacket(7); unacked_packets_.RemoveFromInFlight(QuicPacketNumber(6)); packets_acked.push_back(AckedPacket( QuicPacketNumber(6), kMaxOutgoingPacketSize, QuicTime::Zero())); VerifyLosses(6, packets_acked, std::vector<uint64_t>{}); packets_acked.clear(); EXPECT_EQ(clock_.Now() + rtt_stats_.smoothed_rtt() + (rtt_stats_.smoothed_rtt() >> 3), loss_algorithm_.GetLossTimeout()); clock_.AdvanceTime(rtt_stats_.smoothed_rtt() + (rtt_stats_.smoothed_rtt() >> 3)); VerifyLosses(6, packets_acked, {5}); EXPECT_EQ(QuicTime::Zero(), loss_algorithm_.GetLossTimeout()); } TEST_F(GeneralLossAlgorithmTest, IetfLossDetectionWithOneFourthRttDelay) { loss_algorithm_.set_reordering_shift(2); SendDataPacket(1); SendDataPacket(2); AckedPacketVector packets_acked; unacked_packets_.RemoveFromInFlight(QuicPacketNumber(2)); packets_acked.push_back(AckedPacket( QuicPacketNumber(2), kMaxOutgoingPacketSize, QuicTime::Zero())); VerifyLosses(2, packets_acked, std::vector<uint64_t>{}); packets_acked.clear(); EXPECT_EQ(clock_.Now() + rtt_stats_.smoothed_rtt() + (rtt_stats_.smoothed_rtt() >> 2), loss_algorithm_.GetLossTimeout()); clock_.AdvanceTime(rtt_stats_.smoothed_rtt() + (rtt_stats_.smoothed_rtt() >> 2)); VerifyLosses(2, packets_acked, {1}); EXPECT_EQ(QuicTime::Zero(), loss_algorithm_.GetLossTimeout()); } TEST_F(GeneralLossAlgorithmTest, NoPacketThresholdForRuntPackets) { loss_algorithm_.disable_packet_threshold_for_runt_packets(); for (size_t i = 1; i <= 6; ++i) { SendDataPacket(i); } SendDataPacket(7, kDefaultLength / 2); AckedPacketVector packets_acked; unacked_packets_.RemoveFromInFlight(QuicPacketNumber(7)); packets_acked.push_back(AckedPacket( QuicPacketNumber(7), kMaxOutgoingPacketSize, QuicTime::Zero())); VerifyLosses(7, packets_acked, std::vector<uint64_t>{}); EXPECT_EQ(clock_.Now() + rtt_stats_.smoothed_rtt() + (rtt_stats_.smoothed_rtt() >> 2), loss_algorithm_.GetLossTimeout()); clock_.AdvanceTime(rtt_stats_.smoothed_rtt() + (rtt_stats_.smoothed_rtt() >> 2)); VerifyLosses(7, packets_acked, {1, 2, 3, 4, 5, 6}); EXPECT_EQ(QuicTime::Zero(), loss_algorithm_.GetLossTimeout()); } } } }
329
cpp
google/quiche
uber_loss_algorithm
quiche/quic/core/congestion_control/uber_loss_algorithm.cc
quiche/quic/core/congestion_control/uber_loss_algorithm_test.cc
#ifndef QUICHE_QUIC_CORE_CONGESTION_CONTROL_UBER_LOSS_ALGORITHM_H_ #define QUICHE_QUIC_CORE_CONGESTION_CONTROL_UBER_LOSS_ALGORITHM_H_ #include <optional> #include "quiche/quic/core/congestion_control/general_loss_algorithm.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_flags.h" namespace quic { namespace test { class QuicSentPacketManagerPeer; } struct QUICHE_EXPORT LossDetectionParameters { std::optional<int> reordering_shift; std::optional<QuicPacketCount> reordering_threshold; }; class QUICHE_EXPORT LossDetectionTunerInterface { public: virtual ~LossDetectionTunerInterface() {} virtual bool Start(LossDetectionParameters* params) = 0; virtual void Finish(const LossDetectionParameters& params) = 0; }; class QUICHE_EXPORT UberLossAlgorithm : public LossDetectionInterface { public: UberLossAlgorithm(); UberLossAlgorithm(const UberLossAlgorithm&) = delete; UberLossAlgorithm& operator=(const UberLossAlgorithm&) = delete; ~UberLossAlgorithm() override {} void SetFromConfig(const QuicConfig& config, Perspective perspective) override; DetectionStats DetectLosses(const QuicUnackedPacketMap& unacked_packets, QuicTime time, const RttStats& rtt_stats, QuicPacketNumber largest_newly_acked, const AckedPacketVector& packets_acked, LostPacketVector* packets_lost) override; QuicTime GetLossTimeout() const override; void SpuriousLossDetected(const QuicUnackedPacketMap& unacked_packets, const RttStats& rtt_stats, QuicTime ack_receive_time, QuicPacketNumber packet_number, QuicPacketNumber previous_largest_acked) override; void SetLossDetectionTuner( std::unique_ptr<LossDetectionTunerInterface> tuner); void OnConfigNegotiated() override; void OnMinRttAvailable() override; void OnUserAgentIdKnown() override; void OnConnectionClosed() override; void OnReorderingDetected() override; void SetReorderingShift(int reordering_shift); void SetReorderingThreshold(QuicPacketCount reordering_threshold); void EnableAdaptiveReorderingThreshold(); void DisableAdaptiveReorderingThreshold(); void EnableAdaptiveTimeThreshold(); QuicPacketCount GetPacketReorderingThreshold() const; int GetPacketReorderingShift() const; void DisablePacketThresholdForRuntPackets(); void ResetLossDetection(PacketNumberSpace space); bool use_adaptive_reordering_threshold() const { return general_loss_algorithms_[APPLICATION_DATA] .use_adaptive_reordering_threshold(); } bool use_adaptive_time_threshold() const { return general_loss_algorithms_[APPLICATION_DATA] .use_adaptive_time_threshold(); } private: friend class test::QuicSentPacketManagerPeer; void MaybeStartTuning(); GeneralLossAlgorithm general_loss_algorithms_[NUM_PACKET_NUMBER_SPACES]; std::unique_ptr<LossDetectionTunerInterface> tuner_; LossDetectionParameters tuned_parameters_; bool tuner_started_ = false; bool min_rtt_available_ = false; bool user_agent_known_ = false; bool tuning_configured_ = false; bool reorder_happened_ = false; }; } #endif #include "quiche/quic/core/congestion_control/uber_loss_algorithm.h" #include <algorithm> #include <memory> #include <utility> #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" namespace quic { UberLossAlgorithm::UberLossAlgorithm() { for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) { general_loss_algorithms_[i].Initialize(static_cast<PacketNumberSpace>(i), this); } } void UberLossAlgorithm::SetFromConfig(const QuicConfig& config, Perspective perspective) { if (config.HasClientRequestedIndependentOption(kELDT, perspective) && tuner_ != nullptr) { tuning_configured_ = true; MaybeStartTuning(); } } LossDetectionInterface::DetectionStats UberLossAlgorithm::DetectLosses( const QuicUnackedPacketMap& unacked_packets, QuicTime time, const RttStats& rtt_stats, QuicPacketNumber , const AckedPacketVector& packets_acked, LostPacketVector* packets_lost) { DetectionStats overall_stats; for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) { const QuicPacketNumber largest_acked = unacked_packets.GetLargestAckedOfPacketNumberSpace( static_cast<PacketNumberSpace>(i)); if (!largest_acked.IsInitialized() || unacked_packets.GetLeastUnacked() > largest_acked) { continue; } DetectionStats stats = general_loss_algorithms_[i].DetectLosses( unacked_packets, time, rtt_stats, largest_acked, packets_acked, packets_lost); overall_stats.sent_packets_max_sequence_reordering = std::max(overall_stats.sent_packets_max_sequence_reordering, stats.sent_packets_max_sequence_reordering); overall_stats.sent_packets_num_borderline_time_reorderings += stats.sent_packets_num_borderline_time_reorderings; overall_stats.total_loss_detection_response_time += stats.total_loss_detection_response_time; } return overall_stats; } QuicTime UberLossAlgorithm::GetLossTimeout() const { QuicTime loss_timeout = QuicTime::Zero(); for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) { const QuicTime timeout = general_loss_algorithms_[i].GetLossTimeout(); if (!loss_timeout.IsInitialized()) { loss_timeout = timeout; continue; } if (timeout.IsInitialized()) { loss_timeout = std::min(loss_timeout, timeout); } } return loss_timeout; } void UberLossAlgorithm::SpuriousLossDetected( const QuicUnackedPacketMap& unacked_packets, const RttStats& rtt_stats, QuicTime ack_receive_time, QuicPacketNumber packet_number, QuicPacketNumber previous_largest_acked) { general_loss_algorithms_[unacked_packets.GetPacketNumberSpace(packet_number)] .SpuriousLossDetected(unacked_packets, rtt_stats, ack_receive_time, packet_number, previous_largest_acked); } void UberLossAlgorithm::SetLossDetectionTuner( std::unique_ptr<LossDetectionTunerInterface> tuner) { if (tuner_ != nullptr) { QUIC_BUG(quic_bug_10469_1) << "LossDetectionTuner can only be set once when session begins."; return; } tuner_ = std::move(tuner); } void UberLossAlgorithm::MaybeStartTuning() { if (tuner_started_ || !tuning_configured_ || !min_rtt_available_ || !user_agent_known_ || !reorder_happened_) { return; } tuner_started_ = tuner_->Start(&tuned_parameters_); if (!tuner_started_) { return; } if (tuned_parameters_.reordering_shift.has_value() && tuned_parameters_.reordering_threshold.has_value()) { QUIC_DLOG(INFO) << "Setting reordering shift to " << *tuned_parameters_.reordering_shift << ", and reordering threshold to " << *tuned_parameters_.reordering_threshold; SetReorderingShift(*tuned_parameters_.reordering_shift); SetReorderingThreshold(*tuned_parameters_.reordering_threshold); } else { QUIC_BUG(quic_bug_10469_2) << "Tuner started but some parameters are missing"; } } void UberLossAlgorithm::OnConfigNegotiated() {} void UberLossAlgorithm::OnMinRttAvailable() { min_rtt_available_ = true; MaybeStartTuning(); } void UberLossAlgorithm::OnUserAgentIdKnown() { user_agent_known_ = true; MaybeStartTuning(); } void UberLossAlgorithm::OnConnectionClosed() { if (tuner_ != nullptr && tuner_started_) { tuner_->Finish(tuned_parameters_); } } void UberLossAlgorithm::OnReorderingDetected() { const bool tuner_started_before = tuner_started_; const bool reorder_happened_before = reorder_happened_; reorder_happened_ = true; MaybeStartTuning(); if (!tuner_started_before && tuner_started_) { if (reorder_happened_before) { QUIC_CODE_COUNT(quic_loss_tuner_started_after_first_reorder); } else { QUIC_CODE_COUNT(quic_loss_tuner_started_on_first_reorder); } } } void UberLossAlgorithm::SetReorderingShift(int reordering_shift) { for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) { general_loss_algorithms_[i].set_reordering_shift(reordering_shift); } } void UberLossAlgorithm::SetReorderingThreshold( QuicPacketCount reordering_threshold) { for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) { general_loss_algorithms_[i].set_reordering_threshold(reordering_threshold); } } void UberLossAlgorithm::EnableAdaptiveReorderingThreshold() { for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) { general_loss_algorithms_[i].set_use_adaptive_reordering_threshold(true); } } void UberLossAlgorithm::DisableAdaptiveReorderingThreshold() { for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) { general_loss_algorithms_[i].set_use_adaptive_reordering_threshold(false); } } void UberLossAlgorithm::EnableAdaptiveTimeThreshold() { for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) { general_loss_algorithms_[i].enable_adaptive_time_threshold(); } } QuicPacketCount UberLossAlgorithm::GetPacketReorderingThreshold() const { return general_loss_algorithms_[APPLICATION_DATA].reordering_threshold(); } int UberLossAlgorithm::GetPacketReorderingShift() const { return general_loss_algorithms_[APPLICATION_DATA].reordering_shift(); } void UberLossAlgorithm::DisablePacketThresholdForRuntPackets() { for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) { general_loss_algorithms_[i].disable_packet_threshold_for_runt_packets(); } } void UberLossAlgorithm::ResetLossDetection(PacketNumberSpace space) { if (space >= NUM_PACKET_NUMBER_SPACES) { QUIC_BUG(quic_bug_10469_3) << "Invalid packet number space: " << space; return; } general_loss_algorithms_[space].Reset(); } }
#include "quiche/quic/core/congestion_control/uber_loss_algorithm.h" #include <memory> #include <optional> #include <utility> #include <vector> #include "quiche/quic/core/congestion_control/rtt_stats.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_clock.h" #include "quiche/quic/test_tools/quic_unacked_packet_map_peer.h" namespace quic { namespace test { namespace { const uint32_t kDefaultLength = 1000; class UberLossAlgorithmTest : public QuicTest { protected: UberLossAlgorithmTest() { unacked_packets_ = std::make_unique<QuicUnackedPacketMap>(Perspective::IS_CLIENT); rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(100), QuicTime::Delta::Zero(), clock_.Now()); EXPECT_LT(0, rtt_stats_.smoothed_rtt().ToMicroseconds()); } void SendPacket(uint64_t packet_number, EncryptionLevel encryption_level) { QuicStreamFrame frame; QuicTransportVersion version = CurrentSupportedVersions()[0].transport_version; frame.stream_id = QuicUtils::GetFirstBidirectionalStreamId( version, Perspective::IS_CLIENT); if (encryption_level == ENCRYPTION_INITIAL) { if (QuicVersionUsesCryptoFrames(version)) { frame.stream_id = QuicUtils::GetFirstBidirectionalStreamId( version, Perspective::IS_CLIENT); } else { frame.stream_id = QuicUtils::GetCryptoStreamId(version); } } SerializedPacket packet(QuicPacketNumber(packet_number), PACKET_1BYTE_PACKET_NUMBER, nullptr, kDefaultLength, false, false); packet.encryption_level = encryption_level; packet.retransmittable_frames.push_back(QuicFrame(frame)); unacked_packets_->AddSentPacket(&packet, NOT_RETRANSMISSION, clock_.Now(), true, true, ECN_NOT_ECT); } void AckPackets(const std::vector<uint64_t>& packets_acked) { packets_acked_.clear(); for (uint64_t acked : packets_acked) { unacked_packets_->RemoveFromInFlight(QuicPacketNumber(acked)); packets_acked_.push_back(AckedPacket( QuicPacketNumber(acked), kMaxOutgoingPacketSize, QuicTime::Zero())); } } void VerifyLosses(uint64_t largest_newly_acked, const AckedPacketVector& packets_acked, const std::vector<uint64_t>& losses_expected) { return VerifyLosses(largest_newly_acked, packets_acked, losses_expected, std::nullopt); } void VerifyLosses( uint64_t largest_newly_acked, const AckedPacketVector& packets_acked, const std::vector<uint64_t>& losses_expected, std::optional<QuicPacketCount> max_sequence_reordering_expected) { LostPacketVector lost_packets; LossDetectionInterface::DetectionStats stats = loss_algorithm_.DetectLosses( *unacked_packets_, clock_.Now(), rtt_stats_, QuicPacketNumber(largest_newly_acked), packets_acked, &lost_packets); if (max_sequence_reordering_expected.has_value()) { EXPECT_EQ(stats.sent_packets_max_sequence_reordering, max_sequence_reordering_expected.value()); } ASSERT_EQ(losses_expected.size(), lost_packets.size()); for (size_t i = 0; i < losses_expected.size(); ++i) { EXPECT_EQ(lost_packets[i].packet_number, QuicPacketNumber(losses_expected[i])); } } MockClock clock_; std::unique_ptr<QuicUnackedPacketMap> unacked_packets_; RttStats rtt_stats_; UberLossAlgorithm loss_algorithm_; AckedPacketVector packets_acked_; }; TEST_F(UberLossAlgorithmTest, ScenarioA) { SendPacket(1, ENCRYPTION_INITIAL); SendPacket(2, ENCRYPTION_ZERO_RTT); SendPacket(3, ENCRYPTION_ZERO_RTT); unacked_packets_->RemoveFromInFlight(QuicPacketNumber(1)); SendPacket(4, ENCRYPTION_INITIAL); AckPackets({1, 4}); unacked_packets_->MaybeUpdateLargestAckedOfPacketNumberSpace( HANDSHAKE_DATA, QuicPacketNumber(4)); VerifyLosses(4, packets_acked_, std::vector<uint64_t>{}, 0); EXPECT_EQ(QuicTime::Zero(), loss_algorithm_.GetLossTimeout()); } TEST_F(UberLossAlgorithmTest, ScenarioB) { SendPacket(3, ENCRYPTION_ZERO_RTT); SendPacket(4, ENCRYPTION_ZERO_RTT); SendPacket(5, ENCRYPTION_FORWARD_SECURE); SendPacket(6, ENCRYPTION_FORWARD_SECURE); AckPackets({4}); unacked_packets_->MaybeUpdateLargestAckedOfPacketNumberSpace( APPLICATION_DATA, QuicPacketNumber(4)); VerifyLosses(4, packets_acked_, std::vector<uint64_t>{}, 1); EXPECT_EQ(clock_.Now() + 1.25 * rtt_stats_.smoothed_rtt(), loss_algorithm_.GetLossTimeout()); AckPackets({6}); unacked_packets_->MaybeUpdateLargestAckedOfPacketNumberSpace( APPLICATION_DATA, QuicPacketNumber(6)); VerifyLosses(6, packets_acked_, std::vector<uint64_t>{3}, 3); EXPECT_EQ(clock_.Now() + 1.25 * rtt_stats_.smoothed_rtt(), loss_algorithm_.GetLossTimeout()); packets_acked_.clear(); clock_.AdvanceTime(1.25 * rtt_stats_.latest_rtt()); VerifyLosses(6, packets_acked_, {5}, 1); } TEST_F(UberLossAlgorithmTest, ScenarioC) { QuicUnackedPacketMapPeer::SetPerspective(unacked_packets_.get(), Perspective::IS_SERVER); SendPacket(1, ENCRYPTION_ZERO_RTT); SendPacket(2, ENCRYPTION_FORWARD_SECURE); SendPacket(3, ENCRYPTION_FORWARD_SECURE); SendPacket(4, ENCRYPTION_FORWARD_SECURE); unacked_packets_->RemoveFromInFlight(QuicPacketNumber(1)); SendPacket(5, ENCRYPTION_ZERO_RTT); AckPackets({4, 5}); unacked_packets_->MaybeUpdateLargestAckedOfPacketNumberSpace( APPLICATION_DATA, QuicPacketNumber(4)); unacked_packets_->MaybeUpdateLargestAckedOfPacketNumberSpace( HANDSHAKE_DATA, QuicPacketNumber(5)); VerifyLosses(5, packets_acked_, std::vector<uint64_t>{}, 2); EXPECT_EQ(clock_.Now() + 1.25 * rtt_stats_.smoothed_rtt(), loss_algorithm_.GetLossTimeout()); packets_acked_.clear(); clock_.AdvanceTime(1.25 * rtt_stats_.latest_rtt()); VerifyLosses(5, packets_acked_, std::vector<uint64_t>{2, 3}, 2); } TEST_F(UberLossAlgorithmTest, PacketInLimbo) { QuicUnackedPacketMapPeer::SetPerspective(unacked_packets_.get(), Perspective::IS_SERVER); SendPacket(1, ENCRYPTION_ZERO_RTT); SendPacket(2, ENCRYPTION_FORWARD_SECURE); SendPacket(3, ENCRYPTION_FORWARD_SECURE); SendPacket(4, ENCRYPTION_ZERO_RTT); SendPacket(5, ENCRYPTION_FORWARD_SECURE); AckPackets({1, 3, 4}); unacked_packets_->MaybeUpdateLargestAckedOfPacketNumberSpace( APPLICATION_DATA, QuicPacketNumber(3)); unacked_packets_->MaybeUpdateLargestAckedOfPacketNumberSpace( HANDSHAKE_DATA, QuicPacketNumber(4)); VerifyLosses(4, packets_acked_, std::vector<uint64_t>{}); SendPacket(6, ENCRYPTION_FORWARD_SECURE); AckPackets({5, 6}); unacked_packets_->MaybeUpdateLargestAckedOfPacketNumberSpace( APPLICATION_DATA, QuicPacketNumber(6)); VerifyLosses(6, packets_acked_, std::vector<uint64_t>{2}); } class TestLossTuner : public LossDetectionTunerInterface { public: TestLossTuner(bool forced_start_result, LossDetectionParameters forced_parameters) : forced_start_result_(forced_start_result), forced_parameters_(std::move(forced_parameters)) {} ~TestLossTuner() override = default; bool Start(LossDetectionParameters* params) override { start_called_ = true; *params = forced_parameters_; return forced_start_result_; } void Finish(const LossDetectionParameters& ) override {} bool start_called() const { return start_called_; } private: bool forced_start_result_; LossDetectionParameters forced_parameters_; bool start_called_ = false; }; TEST_F(UberLossAlgorithmTest, LossDetectionTuning_SetFromConfigFirst) { const int old_reordering_shift = loss_algorithm_.GetPacketReorderingShift(); const QuicPacketCount old_reordering_threshold = loss_algorithm_.GetPacketReorderingThreshold(); loss_algorithm_.OnUserAgentIdKnown(); TestLossTuner* test_tuner = new TestLossTuner( true, LossDetectionParameters{ old_reordering_shift + 1, old_reordering_threshold * 2}); loss_algorithm_.SetLossDetectionTuner( std::unique_ptr<LossDetectionTunerInterface>(test_tuner)); QuicConfig config; QuicTagVector connection_options; connection_options.push_back(kELDT); config.SetInitialReceivedConnectionOptions(connection_options); loss_algorithm_.SetFromConfig(config, Perspective::IS_SERVER); EXPECT_FALSE(test_tuner->start_called()); EXPECT_EQ(old_reordering_shift, loss_algorithm_.GetPacketReorderingShift()); EXPECT_EQ(old_reordering_threshold, loss_algorithm_.GetPacketReorderingThreshold()); loss_algorithm_.OnMinRttAvailable(); EXPECT_FALSE(test_tuner->start_called()); loss_algorithm_.OnReorderingDetected(); EXPECT_TRUE(test_tuner->start_called()); EXPECT_NE(old_reordering_shift, loss_algorithm_.GetPacketReorderingShift()); EXPECT_NE(old_reordering_threshold, loss_algorithm_.GetPacketReorderingThreshold()); } TEST_F(UberLossAlgorithmTest, LossDetectionTuning_OnMinRttAvailableFirst) { const int old_reordering_shift = loss_algorithm_.GetPacketReorderingShift(); const QuicPacketCount old_reordering_threshold = loss_algorithm_.GetPacketReorderingThreshold(); loss_algorithm_.OnUserAgentIdKnown(); TestLossTuner* test_tuner = new TestLossTuner( true, LossDetectionParameters{ old_reordering_shift + 1, old_reordering_threshold * 2}); loss_algorithm_.SetLossDetectionTuner( std::unique_ptr<LossDetectionTunerInterface>(test_tuner)); loss_algorithm_.OnMinRttAvailable(); EXPECT_FALSE(test_tuner->start_called()); EXPECT_EQ(old_reordering_shift, loss_algorithm_.GetPacketReorderingShift()); EXPECT_EQ(old_reordering_threshold, loss_algorithm_.GetPacketReorderingThreshold()); loss_algorithm_.OnReorderingDetected(); EXPECT_FALSE(test_tuner->start_called()); QuicConfig config; QuicTagVector connection_options; connection_options.push_back(kELDT); config.SetInitialReceivedConnectionOptions(connection_options); loss_algorithm_.SetFromConfig(config, Perspective::IS_SERVER); EXPECT_TRUE(test_tuner->start_called()); EXPECT_NE(old_reordering_shift, loss_algorithm_.GetPacketReorderingShift()); EXPECT_NE(old_reordering_threshold, loss_algorithm_.GetPacketReorderingThreshold()); } TEST_F(UberLossAlgorithmTest, LossDetectionTuning_StartFailed) { const int old_reordering_shift = loss_algorithm_.GetPacketReorderingShift(); const QuicPacketCount old_reordering_threshold = loss_algorithm_.GetPacketReorderingThreshold(); loss_algorithm_.OnUserAgentIdKnown(); TestLossTuner* test_tuner = new TestLossTuner( false, LossDetectionParameters{ old_reordering_shift + 1, old_reordering_threshold * 2}); loss_algorithm_.SetLossDetectionTuner( std::unique_ptr<LossDetectionTunerInterface>(test_tuner)); QuicConfig config; QuicTagVector connection_options; connection_options.push_back(kELDT); config.SetInitialReceivedConnectionOptions(connection_options); loss_algorithm_.SetFromConfig(config, Perspective::IS_SERVER); EXPECT_FALSE(test_tuner->start_called()); EXPECT_EQ(old_reordering_shift, loss_algorithm_.GetPacketReorderingShift()); EXPECT_EQ(old_reordering_threshold, loss_algorithm_.GetPacketReorderingThreshold()); loss_algorithm_.OnReorderingDetected(); EXPECT_FALSE(test_tuner->start_called()); loss_algorithm_.OnMinRttAvailable(); EXPECT_TRUE(test_tuner->start_called()); EXPECT_EQ(old_reordering_shift, loss_algorithm_.GetPacketReorderingShift()); EXPECT_EQ(old_reordering_threshold, loss_algorithm_.GetPacketReorderingThreshold()); } } } }
330
cpp
google/quiche
tcp_cubic_sender_bytes
quiche/quic/core/congestion_control/tcp_cubic_sender_bytes.cc
quiche/quic/core/congestion_control/tcp_cubic_sender_bytes_test.cc
#ifndef QUICHE_QUIC_CORE_CONGESTION_CONTROL_TCP_CUBIC_SENDER_BYTES_H_ #define QUICHE_QUIC_CORE_CONGESTION_CONTROL_TCP_CUBIC_SENDER_BYTES_H_ #include <cstdint> #include <string> #include "quiche/quic/core/congestion_control/cubic_bytes.h" #include "quiche/quic/core/congestion_control/hybrid_slow_start.h" #include "quiche/quic/core/congestion_control/prr_sender.h" #include "quiche/quic/core/congestion_control/send_algorithm_interface.h" #include "quiche/quic/core/quic_bandwidth.h" #include "quiche/quic/core/quic_connection_stats.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class RttStats; inline constexpr QuicPacketCount kMaxResumptionCongestionWindow = 200; namespace test { class TcpCubicSenderBytesPeer; } class QUICHE_EXPORT TcpCubicSenderBytes : public SendAlgorithmInterface { public: TcpCubicSenderBytes(const QuicClock* clock, const RttStats* rtt_stats, bool reno, QuicPacketCount initial_tcp_congestion_window, QuicPacketCount max_congestion_window, QuicConnectionStats* stats); TcpCubicSenderBytes(const TcpCubicSenderBytes&) = delete; TcpCubicSenderBytes& operator=(const TcpCubicSenderBytes&) = delete; ~TcpCubicSenderBytes() override; void SetFromConfig(const QuicConfig& config, Perspective perspective) override; void ApplyConnectionOptions( const QuicTagVector& ) override {} void AdjustNetworkParameters(const NetworkParams& params) override; void SetNumEmulatedConnections(int num_connections); void SetInitialCongestionWindowInPackets( QuicPacketCount congestion_window) override; void OnConnectionMigration() override; void OnCongestionEvent(bool rtt_updated, QuicByteCount prior_in_flight, QuicTime event_time, const AckedPacketVector& acked_packets, const LostPacketVector& lost_packets, QuicPacketCount num_ect, QuicPacketCount num_ce) override; void OnPacketSent(QuicTime sent_time, QuicByteCount bytes_in_flight, QuicPacketNumber packet_number, QuicByteCount bytes, HasRetransmittableData is_retransmittable) override; void OnPacketNeutered(QuicPacketNumber ) override {} void OnRetransmissionTimeout(bool packets_retransmitted) override; bool CanSend(QuicByteCount bytes_in_flight) override; QuicBandwidth PacingRate(QuicByteCount bytes_in_flight) const override; QuicBandwidth BandwidthEstimate() const override; bool HasGoodBandwidthEstimateForResumption() const override { return false; } QuicByteCount GetCongestionWindow() const override; QuicByteCount GetSlowStartThreshold() const override; CongestionControlType GetCongestionControlType() const override; bool InSlowStart() const override; bool InRecovery() const override; std::string GetDebugState() const override; void OnApplicationLimited(QuicByteCount bytes_in_flight) override; void PopulateConnectionStats(QuicConnectionStats* ) const override {} bool EnableECT0() override { return false; } bool EnableECT1() override { return false; } QuicByteCount min_congestion_window() const { return min_congestion_window_; } protected: float RenoBeta() const; bool IsCwndLimited(QuicByteCount bytes_in_flight) const; void OnPacketAcked(QuicPacketNumber acked_packet_number, QuicByteCount acked_bytes, QuicByteCount prior_in_flight, QuicTime event_time); void SetCongestionWindowFromBandwidthAndRtt(QuicBandwidth bandwidth, QuicTime::Delta rtt); void SetMinCongestionWindowInPackets(QuicPacketCount congestion_window); void ExitSlowstart(); void OnPacketLost(QuicPacketNumber packet_number, QuicByteCount lost_bytes, QuicByteCount prior_in_flight); void MaybeIncreaseCwnd(QuicPacketNumber acked_packet_number, QuicByteCount acked_bytes, QuicByteCount prior_in_flight, QuicTime event_time); void HandleRetransmissionTimeout(); private: friend class test::TcpCubicSenderBytesPeer; HybridSlowStart hybrid_slow_start_; PrrSender prr_; const RttStats* rtt_stats_; QuicConnectionStats* stats_; const bool reno_; uint32_t num_connections_; QuicPacketNumber largest_sent_packet_number_; QuicPacketNumber largest_acked_packet_number_; QuicPacketNumber largest_sent_at_last_cutback_; bool min4_mode_; bool last_cutback_exited_slowstart_; bool slow_start_large_reduction_; bool no_prr_; CubicBytes cubic_; uint64_t num_acked_packets_; QuicByteCount congestion_window_; QuicByteCount min_congestion_window_; QuicByteCount max_congestion_window_; QuicByteCount slowstart_threshold_; const QuicByteCount initial_tcp_congestion_window_; const QuicByteCount initial_max_tcp_congestion_window_; QuicByteCount min_slow_start_exit_window_; }; } #endif #include "quiche/quic/core/congestion_control/tcp_cubic_sender_bytes.h" #include <algorithm> #include <cstdint> #include <string> #include "quiche/quic/core/congestion_control/prr_sender.h" #include "quiche/quic/core/congestion_control/rtt_stats.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { namespace { const QuicByteCount kMaxBurstBytes = 3 * kDefaultTCPMSS; const float kRenoBeta = 0.7f; const QuicByteCount kDefaultMinimumCongestionWindow = 2 * kDefaultTCPMSS; } TcpCubicSenderBytes::TcpCubicSenderBytes( const QuicClock* clock, const RttStats* rtt_stats, bool reno, QuicPacketCount initial_tcp_congestion_window, QuicPacketCount max_congestion_window, QuicConnectionStats* stats) : rtt_stats_(rtt_stats), stats_(stats), reno_(reno), num_connections_(kDefaultNumConnections), min4_mode_(false), last_cutback_exited_slowstart_(false), slow_start_large_reduction_(false), no_prr_(false), cubic_(clock), num_acked_packets_(0), congestion_window_(initial_tcp_congestion_window * kDefaultTCPMSS), min_congestion_window_(kDefaultMinimumCongestionWindow), max_congestion_window_(max_congestion_window * kDefaultTCPMSS), slowstart_threshold_(max_congestion_window * kDefaultTCPMSS), initial_tcp_congestion_window_(initial_tcp_congestion_window * kDefaultTCPMSS), initial_max_tcp_congestion_window_(max_congestion_window * kDefaultTCPMSS), min_slow_start_exit_window_(min_congestion_window_) {} TcpCubicSenderBytes::~TcpCubicSenderBytes() {} void TcpCubicSenderBytes::SetFromConfig(const QuicConfig& config, Perspective perspective) { if (perspective == Perspective::IS_SERVER && config.HasReceivedConnectionOptions()) { if (ContainsQuicTag(config.ReceivedConnectionOptions(), kMIN4)) { min4_mode_ = true; SetMinCongestionWindowInPackets(1); } if (ContainsQuicTag(config.ReceivedConnectionOptions(), kSSLR)) { slow_start_large_reduction_ = true; } if (ContainsQuicTag(config.ReceivedConnectionOptions(), kNPRR)) { no_prr_ = true; } } } void TcpCubicSenderBytes::AdjustNetworkParameters(const NetworkParams& params) { if (params.bandwidth.IsZero() || params.rtt.IsZero()) { return; } SetCongestionWindowFromBandwidthAndRtt(params.bandwidth, params.rtt); } float TcpCubicSenderBytes::RenoBeta() const { return (num_connections_ - 1 + kRenoBeta) / num_connections_; } void TcpCubicSenderBytes::OnCongestionEvent( bool rtt_updated, QuicByteCount prior_in_flight, QuicTime event_time, const AckedPacketVector& acked_packets, const LostPacketVector& lost_packets, QuicPacketCount , QuicPacketCount ) { if (rtt_updated && InSlowStart() && hybrid_slow_start_.ShouldExitSlowStart( rtt_stats_->latest_rtt(), rtt_stats_->min_rtt(), GetCongestionWindow() / kDefaultTCPMSS)) { ExitSlowstart(); } for (const LostPacket& lost_packet : lost_packets) { OnPacketLost(lost_packet.packet_number, lost_packet.bytes_lost, prior_in_flight); } for (const AckedPacket& acked_packet : acked_packets) { OnPacketAcked(acked_packet.packet_number, acked_packet.bytes_acked, prior_in_flight, event_time); } } void TcpCubicSenderBytes::OnPacketAcked(QuicPacketNumber acked_packet_number, QuicByteCount acked_bytes, QuicByteCount prior_in_flight, QuicTime event_time) { largest_acked_packet_number_.UpdateMax(acked_packet_number); if (InRecovery()) { if (!no_prr_) { prr_.OnPacketAcked(acked_bytes); } return; } MaybeIncreaseCwnd(acked_packet_number, acked_bytes, prior_in_flight, event_time); if (InSlowStart()) { hybrid_slow_start_.OnPacketAcked(acked_packet_number); } } void TcpCubicSenderBytes::OnPacketSent( QuicTime , QuicByteCount , QuicPacketNumber packet_number, QuicByteCount bytes, HasRetransmittableData is_retransmittable) { if (InSlowStart()) { ++(stats_->slowstart_packets_sent); } if (is_retransmittable != HAS_RETRANSMITTABLE_DATA) { return; } if (InRecovery()) { prr_.OnPacketSent(bytes); } QUICHE_DCHECK(!largest_sent_packet_number_.IsInitialized() || largest_sent_packet_number_ < packet_number); largest_sent_packet_number_ = packet_number; hybrid_slow_start_.OnPacketSent(packet_number); } bool TcpCubicSenderBytes::CanSend(QuicByteCount bytes_in_flight) { if (!no_prr_ && InRecovery()) { return prr_.CanSend(GetCongestionWindow(), bytes_in_flight, GetSlowStartThreshold()); } if (GetCongestionWindow() > bytes_in_flight) { return true; } if (min4_mode_ && bytes_in_flight < 4 * kDefaultTCPMSS) { return true; } return false; } QuicBandwidth TcpCubicSenderBytes::PacingRate( QuicByteCount ) const { QuicTime::Delta srtt = rtt_stats_->SmoothedOrInitialRtt(); const QuicBandwidth bandwidth = QuicBandwidth::FromBytesAndTimeDelta(GetCongestionWindow(), srtt); return bandwidth * (InSlowStart() ? 2 : (no_prr_ && InRecovery() ? 1 : 1.25)); } QuicBandwidth TcpCubicSenderBytes::BandwidthEstimate() const { QuicTime::Delta srtt = rtt_stats_->smoothed_rtt(); if (srtt.IsZero()) { return QuicBandwidth::Zero(); } return QuicBandwidth::FromBytesAndTimeDelta(GetCongestionWindow(), srtt); } bool TcpCubicSenderBytes::InSlowStart() const { return GetCongestionWindow() < GetSlowStartThreshold(); } bool TcpCubicSenderBytes::IsCwndLimited(QuicByteCount bytes_in_flight) const { const QuicByteCount congestion_window = GetCongestionWindow(); if (bytes_in_flight >= congestion_window) { return true; } const QuicByteCount available_bytes = congestion_window - bytes_in_flight; const bool slow_start_limited = InSlowStart() && bytes_in_flight > congestion_window / 2; return slow_start_limited || available_bytes <= kMaxBurstBytes; } bool TcpCubicSenderBytes::InRecovery() const { return largest_acked_packet_number_.IsInitialized() && largest_sent_at_last_cutback_.IsInitialized() && largest_acked_packet_number_ <= largest_sent_at_last_cutback_; } void TcpCubicSenderBytes::OnRetransmissionTimeout(bool packets_retransmitted) { largest_sent_at_last_cutback_.Clear(); if (!packets_retransmitted) { return; } hybrid_slow_start_.Restart(); HandleRetransmissionTimeout(); } std::string TcpCubicSenderBytes::GetDebugState() const { return ""; } void TcpCubicSenderBytes::OnApplicationLimited( QuicByteCount ) {} void TcpCubicSenderBytes::SetCongestionWindowFromBandwidthAndRtt( QuicBandwidth bandwidth, QuicTime::Delta rtt) { QuicByteCount new_congestion_window = bandwidth.ToBytesPerPeriod(rtt); congestion_window_ = std::max(min_congestion_window_, std::min(new_congestion_window, kMaxResumptionCongestionWindow * kDefaultTCPMSS)); } void TcpCubicSenderBytes::SetInitialCongestionWindowInPackets( QuicPacketCount congestion_window) { congestion_window_ = congestion_window * kDefaultTCPMSS; } void TcpCubicSenderBytes::SetMinCongestionWindowInPackets( QuicPacketCount congestion_window) { min_congestion_window_ = congestion_window * kDefaultTCPMSS; } void TcpCubicSenderBytes::SetNumEmulatedConnections(int num_connections) { num_connections_ = std::max(1, num_connections); cubic_.SetNumConnections(num_connections_); } void TcpCubicSenderBytes::ExitSlowstart() { slowstart_threshold_ = congestion_window_; } void TcpCubicSenderBytes::OnPacketLost(QuicPacketNumber packet_number, QuicByteCount lost_bytes, QuicByteCount prior_in_flight) { if (largest_sent_at_last_cutback_.IsInitialized() && packet_number <= largest_sent_at_last_cutback_) { if (last_cutback_exited_slowstart_) { ++stats_->slowstart_packets_lost; stats_->slowstart_bytes_lost += lost_bytes; if (slow_start_large_reduction_) { congestion_window_ = std::max(congestion_window_ - lost_bytes, min_slow_start_exit_window_); slowstart_threshold_ = congestion_window_; } } QUIC_DVLOG(1) << "Ignoring loss for largest_missing:" << packet_number << " because it was sent prior to the last CWND cutback."; return; } ++stats_->tcp_loss_events; last_cutback_exited_slowstart_ = InSlowStart(); if (InSlowStart()) { ++stats_->slowstart_packets_lost; } if (!no_prr_) { prr_.OnPacketLost(prior_in_flight); } if (slow_start_large_reduction_ && InSlowStart()) { QUICHE_DCHECK_LT(kDefaultTCPMSS, congestion_window_); if (congestion_window_ >= 2 * initial_tcp_congestion_window_) { min_slow_start_exit_window_ = congestion_window_ / 2; } congestion_window_ = congestion_window_ - kDefaultTCPMSS; } else if (reno_) { congestion_window_ = congestion_window_ * RenoBeta(); } else { congestion_window_ = cubic_.CongestionWindowAfterPacketLoss(congestion_window_); } if (congestion_window_ < min_congestion_window_) { congestion_window_ = min_congestion_window_; } slowstart_threshold_ = congestion_window_; largest_sent_at_last_cutback_ = largest_sent_packet_number_; num_acked_packets_ = 0; QUIC_DVLOG(1) << "Incoming loss; congestion window: " << congestion_window_ << " slowstart threshold: " << slowstart_threshold_; } QuicByteCount TcpCubicSenderBytes::GetCongestionWindow() const { return congestion_window_; } QuicByteCount TcpCubicSenderBytes::GetSlowStartThreshold() const { return slowstart_threshold_; } void TcpCubicSenderBytes::MaybeIncreaseCwnd( QuicPacketNumber , QuicByteCount acked_bytes, QuicByteCount prior_in_flight, QuicTime event_time) { QUIC_BUG_IF(quic_bug_10439_1, InRecovery()) << "Never increase the CWND during recovery."; if (!IsCwndLimited(prior_in_flight)) { cubic_.OnApplicationLimited(); return; } if (congestion_window_ >= max_congestion_window_) { return; } if (InSlowStart()) { congestion_window_ += kDefaultTCPMSS; QUIC_DVLOG(1) << "Slow start; congestion window: " << congestion_window_ << " slowstart threshold: " << slowstart_threshold_; return; } if (reno_) { ++num_acked_packets_; if (num_acked_packets_ * num_connections_ >= congestion_window_ / kDefaultTCPMSS) { congestion_window_ += kDefaultTCPMSS; num_acked_packets_ = 0; } QUIC_DVLOG(1) << "Reno; congestion window: " << congestion_window_ << " slowstart threshold: " << slowstart_threshold_ << " congestion window count: " << num_acked_packets_; } else { congestion_window_ = std::min( max_congestion_window_, cubic_.CongestionWindowAfterAck(acked_bytes, congestion_window_, rtt_stats_->min_rtt(), event_time)); QUIC_DVLOG(1) << "Cubic; congestion window: " << congestion_window_ << " slowstart threshold: " << slowstart_threshold_; } } void TcpCubicSenderBytes::HandleRetransmissionTimeout() { cubic_.ResetCubicState(); slowstart_threshold_ = congestion_window_ / 2; congestion_window_ = min_congestion_window_; } void TcpCubicSenderBytes::OnConnectionMigration() { hybrid_slow_start_.Restart(); prr_ = PrrSender(); largest_sent_packet_number_.Clear(); largest_acked_packet_number_.Clear(); largest_sent_at_last_cutback_.Clear(); last_cutback_exited_slowstart_ = false; cubic_.ResetCubicState(); num_acked_packets_ = 0; congestion_window_ = initial_tcp_congestion_window_; max_congestion_window_ = initial_max_tcp_congestion_window_; slowstart_threshold_ = initial_max_tcp_congestion_window_; } CongestionControlType TcpCubicSenderBytes::GetCongestionControlType() const { return reno_ ? kRenoBytes : kCubicBytes; } }
#include "quiche/quic/core/congestion_control/tcp_cubic_sender_bytes.h" #include <algorithm> #include <cstdint> #include <memory> #include <utility> #include "quiche/quic/core/congestion_control/rtt_stats.h" #include "quiche/quic/core/congestion_control/send_algorithm_interface.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_clock.h" #include "quiche/quic/test_tools/quic_config_peer.h" namespace quic { namespace test { const uint32_t kInitialCongestionWindowPackets = 10; const uint32_t kMaxCongestionWindowPackets = 200; const uint32_t kDefaultWindowTCP = kInitialCongestionWindowPackets * kDefaultTCPMSS; const float kRenoBeta = 0.7f; class TcpCubicSenderBytesPeer : public TcpCubicSenderBytes { public: TcpCubicSenderBytesPeer(const QuicClock* clock, bool reno) : TcpCubicSenderBytes(clock, &rtt_stats_, reno, kInitialCongestionWindowPackets, kMaxCongestionWindowPackets, &stats_) {} const HybridSlowStart& hybrid_slow_start() const { return hybrid_slow_start_; } float GetRenoBeta() const { return RenoBeta(); } RttStats rtt_stats_; QuicConnectionStats stats_; }; class TcpCubicSenderBytesTest : public QuicTest { protected: TcpCubicSenderBytesTest() : one_ms_(QuicTime::Delta::FromMilliseconds(1)), sender_(new TcpCubicSenderBytesPeer(&clock_, true)), packet_number_(1), acked_packet_number_(0), bytes_in_flight_(0) {} int SendAvailableSendWindow() { return SendAvailableSendWindow(kDefaultTCPMSS); } int SendAvailableSendWindow(QuicPacketLength ) { int packets_sent = 0; bool can_send = sender_->CanSend(bytes_in_flight_); while (can_send) { sender_->OnPacketSent(clock_.Now(), bytes_in_flight_, QuicPacketNumber(packet_number_++), kDefaultTCPMSS, HAS_RETRANSMITTABLE_DATA); ++packets_sent; bytes_in_flight_ += kDefaultTCPMSS; can_send = sender_->CanSend(bytes_in_flight_); } return packets_sent; } void AckNPackets(int n) { sender_->rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(60), QuicTime::Delta::Zero(), clock_.Now()); AckedPacketVector acked_packets; LostPacketVector lost_packets; for (int i = 0; i < n; ++i) { ++acked_packet_number_; acked_packets.push_back( AckedPacket(QuicPacketNumber(acked_packet_number_), kDefaultTCPMSS, QuicTime::Zero())); } sender_->OnCongestionEvent(true, bytes_in_flight_, clock_.Now(), acked_packets, lost_packets, 0, 0); bytes_in_flight_ -= n * kDefaultTCPMSS; clock_.AdvanceTime(one_ms_); } void LoseNPackets(int n) { LoseNPackets(n, kDefaultTCPMSS); } void LoseNPackets(int n, QuicPacketLength packet_length) { AckedPacketVector acked_packets; LostPacketVector lost_packets; for (int i = 0; i < n; ++i) { ++acked_packet_number_; lost_packets.push_back( LostPacket(QuicPacketNumber(acked_packet_number_), packet_length)); } sender_->OnCongestionEvent(false, bytes_in_flight_, clock_.Now(), acked_packets, lost_packets, 0, 0); bytes_in_flight_ -= n * packet_length; } void LosePacket(uint64_t packet_number) { AckedPacketVector acked_packets; LostPacketVector lost_packets; lost_packets.push_back( LostPacket(QuicPacketNumber(packet_number), kDefaultTCPMSS)); sender_->OnCongestionEvent(false, bytes_in_flight_, clock_.Now(), acked_packets, lost_packets, 0, 0); bytes_in_flight_ -= kDefaultTCPMSS; } const QuicTime::Delta one_ms_; MockClock clock_; std::unique_ptr<TcpCubicSenderBytesPeer> sender_; uint64_t packet_number_; uint64_t acked_packet_number_; QuicByteCount bytes_in_flight_; }; TEST_F(TcpCubicSenderBytesTest, SimpleSender) { EXPECT_EQ(kDefaultWindowTCP, sender_->GetCongestionWindow()); EXPECT_TRUE(sender_->CanSend(0)); EXPECT_TRUE(sender_->CanSend(0)); EXPECT_EQ(kDefaultWindowTCP, sender_->GetCongestionWindow()); SendAvailableSendWindow(); EXPECT_FALSE(sender_->CanSend(sender_->GetCongestionWindow())); } TEST_F(TcpCubicSenderBytesTest, ApplicationLimitedSlowStart) { const int kNumberOfAcks = 5; EXPECT_TRUE(sender_->CanSend(0)); EXPECT_TRUE(sender_->CanSend(0)); SendAvailableSendWindow(); for (int i = 0; i < kNumberOfAcks; ++i) { AckNPackets(2); } QuicByteCount bytes_to_send = sender_->GetCongestionWindow(); EXPECT_EQ(kDefaultWindowTCP + kDefaultTCPMSS * 2 * 2, bytes_to_send); } TEST_F(TcpCubicSenderBytesTest, ExponentialSlowStart) { const int kNumberOfAcks = 20; EXPECT_TRUE(sender_->CanSend(0)); EXPECT_EQ(QuicBandwidth::Zero(), sender_->BandwidthEstimate()); EXPECT_TRUE(sender_->CanSend(0)); for (int i = 0; i < kNumberOfAcks; ++i) { SendAvailableSendWindow(); AckNPackets(2); } const QuicByteCount cwnd = sender_->GetCongestionWindow(); EXPECT_EQ(kDefaultWindowTCP + kDefaultTCPMSS * 2 * kNumberOfAcks, cwnd); EXPECT_EQ(QuicBandwidth::FromBytesAndTimeDelta( cwnd, sender_->rtt_stats_.smoothed_rtt()), sender_->BandwidthEstimate()); } TEST_F(TcpCubicSenderBytesTest, SlowStartPacketLoss) { sender_->SetNumEmulatedConnections(1); const int kNumberOfAcks = 10; for (int i = 0; i < kNumberOfAcks; ++i) { SendAvailableSendWindow(); AckNPackets(2); } SendAvailableSendWindow(); QuicByteCount expected_send_window = kDefaultWindowTCP + (kDefaultTCPMSS * 2 * kNumberOfAcks); EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); LoseNPackets(1); size_t packets_in_recovery_window = expected_send_window / kDefaultTCPMSS; expected_send_window *= kRenoBeta; EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); size_t number_of_packets_in_window = expected_send_window / kDefaultTCPMSS; QUIC_DLOG(INFO) << "number_packets: " << number_of_packets_in_window; AckNPackets(packets_in_recovery_window); SendAvailableSendWindow(); EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); AckNPackets(number_of_packets_in_window - 2); SendAvailableSendWindow(); EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); AckNPackets(1); expected_send_window += kDefaultTCPMSS; EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); EXPECT_TRUE(sender_->hybrid_slow_start().started()); sender_->OnRetransmissionTimeout(true); EXPECT_FALSE(sender_->hybrid_slow_start().started()); } TEST_F(TcpCubicSenderBytesTest, SlowStartPacketLossWithLargeReduction) { QuicConfig config; QuicTagVector options; options.push_back(kSSLR); QuicConfigPeer::SetReceivedConnectionOptions(&config, options); sender_->SetFromConfig(config, Perspective::IS_SERVER); sender_->SetNumEmulatedConnections(1); const int kNumberOfAcks = (kDefaultWindowTCP / (2 * kDefaultTCPMSS)) - 1; for (int i = 0; i < kNumberOfAcks; ++i) { SendAvailableSendWindow(); AckNPackets(2); } SendAvailableSendWindow(); QuicByteCount expected_send_window = kDefaultWindowTCP + (kDefaultTCPMSS * 2 * kNumberOfAcks); EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); LoseNPackets(1); expected_send_window -= kDefaultTCPMSS; EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); LoseNPackets(5); expected_send_window -= 5 * kDefaultTCPMSS; EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); LoseNPackets(10); expected_send_window -= 10 * kDefaultTCPMSS; EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); size_t packets_in_recovery_window = expected_send_window / kDefaultTCPMSS; size_t number_of_packets_in_window = expected_send_window / kDefaultTCPMSS; QUIC_DLOG(INFO) << "number_packets: " << number_of_packets_in_window; AckNPackets(packets_in_recovery_window); SendAvailableSendWindow(); EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); AckNPackets(number_of_packets_in_window - 1); SendAvailableSendWindow(); EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); AckNPackets(1); expected_send_window += kDefaultTCPMSS; EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); EXPECT_TRUE(sender_->hybrid_slow_start().started()); sender_->OnRetransmissionTimeout(true); EXPECT_FALSE(sender_->hybrid_slow_start().started()); } TEST_F(TcpCubicSenderBytesTest, SlowStartHalfPacketLossWithLargeReduction) { QuicConfig config; QuicTagVector options; options.push_back(kSSLR); QuicConfigPeer::SetReceivedConnectionOptions(&config, options); sender_->SetFromConfig(config, Perspective::IS_SERVER); sender_->SetNumEmulatedConnections(1); const int kNumberOfAcks = 10; for (int i = 0; i < kNumberOfAcks; ++i) { SendAvailableSendWindow(kDefaultTCPMSS / 2); AckNPackets(2); } SendAvailableSendWindow(kDefaultTCPMSS / 2); QuicByteCount expected_send_window = kDefaultWindowTCP + (kDefaultTCPMSS * 2 * kNumberOfAcks); EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); LoseNPackets(1); expected_send_window -= kDefaultTCPMSS; EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); LoseNPackets(10, kDefaultTCPMSS / 2); expected_send_window -= 5 * kDefaultTCPMSS; EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); } TEST_F(TcpCubicSenderBytesTest, SlowStartPacketLossWithMaxHalfReduction) { QuicConfig config; QuicTagVector options; options.push_back(kSSLR); QuicConfigPeer::SetReceivedConnectionOptions(&config, options); sender_->SetFromConfig(config, Perspective::IS_SERVER); sender_->SetNumEmulatedConnections(1); const int kNumberOfAcks = kInitialCongestionWindowPackets / 2; for (int i = 0; i < kNumberOfAcks; ++i) { SendAvailableSendWindow(); AckNPackets(2); } SendAvailableSendWindow(); QuicByteCount expected_send_window = kDefaultWindowTCP + (kDefaultTCPMSS * 2 * kNumberOfAcks); EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); LoseNPackets(1); expected_send_window -= kDefaultTCPMSS; EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); LoseNPackets(kNumberOfAcks * 2); expected_send_window -= (kNumberOfAcks * 2 - 1) * kDefaultTCPMSS; EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); LoseNPackets(5); EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); } TEST_F(TcpCubicSenderBytesTest, NoPRRWhenLessThanOnePacketInFlight) { SendAvailableSendWindow(); LoseNPackets(kInitialCongestionWindowPackets - 1); AckNPackets(1); EXPECT_EQ(2, SendAvailableSendWindow()); EXPECT_TRUE(sender_->CanSend(0)); } TEST_F(TcpCubicSenderBytesTest, SlowStartPacketLossPRR) { sender_->SetNumEmulatedConnections(1); const int kNumberOfAcks = 5; for (int i = 0; i < kNumberOfAcks; ++i) { SendAvailableSendWindow(); AckNPackets(2); } SendAvailableSendWindow(); QuicByteCount expected_send_window = kDefaultWindowTCP + (kDefaultTCPMSS * 2 * kNumberOfAcks); EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); LoseNPackets(1); size_t send_window_before_loss = expected_send_window; expected_send_window *= kRenoBeta; EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); size_t remaining_packets_in_recovery = send_window_before_loss / kDefaultTCPMSS - 2; for (size_t i = 0; i < remaining_packets_in_recovery; ++i) { AckNPackets(1); SendAvailableSendWindow(); EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); } size_t number_of_packets_in_window = expected_send_window / kDefaultTCPMSS; for (size_t i = 0; i < number_of_packets_in_window; ++i) { AckNPackets(1); EXPECT_EQ(1, SendAvailableSendWindow()); EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); } AckNPackets(1); expected_send_window += kDefaultTCPMSS; EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); } TEST_F(TcpCubicSenderBytesTest, SlowStartBurstPacketLossPRR) { sender_->SetNumEmulatedConnections(1); const int kNumberOfAcks = 10; for (int i = 0; i < kNumberOfAcks; ++i) { SendAvailableSendWindow(); AckNPackets(2); } SendAvailableSendWindow(); QuicByteCount expected_send_window = kDefaultWindowTCP + (kDefaultTCPMSS * 2 * kNumberOfAcks); EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); size_t send_window_after_loss = kRenoBeta * expected_send_window; size_t num_packets_to_lose = (expected_send_window - send_window_after_loss) / kDefaultTCPMSS + 1; LoseNPackets(num_packets_to_lose); EXPECT_TRUE(sender_->CanSend(bytes_in_flight_)); AckNPackets(1); expected_send_window *= kRenoBeta; EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); EXPECT_EQ(2, SendAvailableSendWindow()); LoseNPackets(1); AckNPackets(1); EXPECT_EQ(2, SendAvailableSendWindow()); LoseNPackets(1); AckNPackets(1); EXPECT_EQ(2, SendAvailableSendWindow()); for (int i = 0; i < kNumberOfAcks; ++i) { AckNPackets(1); EXPECT_EQ(1, SendAvailableSendWindow()); } } TEST_F(TcpCubicSenderBytesTest, RTOCongestionWindow) { EXPECT_EQ(kDefaultWindowTCP, sender_->GetCongestionWindow()); sender_->OnRetransmissionTimeout(true); EXPECT_EQ(2 * kDefaultTCPMSS, sender_->GetCongestionWindow()); EXPECT_EQ(5u * kDefaultTCPMSS, sender_->GetSlowStartThreshold()); } TEST_F(TcpCubicSenderBytesTest, RTOCongestionWindowNoRetransmission) { EXPECT_EQ(kDefaultWindowTCP, sender_->GetCongestionWindow()); sender_->OnRetransmissionTimeout(false); EXPECT_EQ(kDefaultWindowTCP, sender_->GetCongestionWindow()); } TEST_F(TcpCubicSenderBytesTest, TcpCubicResetEpochOnQuiescence) { const int kMaxCongestionWindow = 50; const QuicByteCount kMaxCongestionWindowBytes = kMaxCongestionWindow * kDefaultTCPMSS; int num_sent = SendAvailableSendWindow(); QuicByteCount saved_cwnd = sender_->GetCongestionWindow(); LoseNPackets(1); EXPECT_GT(saved_cwnd, sender_->GetCongestionWindow()); for (int i = 1; i < num_sent; ++i) { AckNPackets(1); } EXPECT_EQ(0u, bytes_in_flight_); saved_cwnd = sender_->GetCongestionWindow(); num_sent = SendAvailableSendWindow(); for (int i = 0; i < num_sent; ++i) { AckNPackets(1); } EXPECT_LT(saved_cwnd, sender_->GetCongestionWindow()); EXPECT_GT(kMaxCongestionWindowBytes, sender_->GetCongestionWindow()); EXPECT_EQ(0u, bytes_in_flight_); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100000)); saved_cwnd = sender_->GetCongestionWindow(); SendAvailableSendWindow(); AckNPackets(1); EXPECT_NEAR(saved_cwnd, sender_->GetCongestionWindow(), kDefaultTCPMSS); EXPECT_GT(kMaxCongestionWindowBytes, sender_->GetCongestionWindow()); } TEST_F(TcpCubicSenderBytesTest, MultipleLossesInOneWindow) { SendAvailableSendWindow(); const QuicByteCount initial_window = sender_->GetCongestionWindow(); LosePacket(acked_packet_number_ + 1); const QuicByteCount post_loss_window = sender_->GetCongestionWindow(); EXPECT_GT(initial_window, post_loss_window); LosePacket(acked_packet_number_ + 3); EXPECT_EQ(post_loss_window, sender_->GetCongestionWindow()); LosePacket(packet_number_ - 1); EXPECT_EQ(post_loss_window, sender_->GetCongestionWindow()); LosePacket(packet_number_); EXPECT_GT(post_loss_window, sender_->GetCongestionWindow()); } TEST_F(TcpCubicSenderBytesTest, ConfigureMaxInitialWindow) { QuicConfig config; QuicTagVector options; options.push_back(kIW10); QuicConfigPeer::SetReceivedConnectionOptions(&config, options); sender_->SetFromConfig(config, Perspective::IS_SERVER); EXPECT_EQ(10u * kDefaultTCPMSS, sender_->GetCongestionWindow()); } TEST_F(TcpCubicSenderBytesTest, SetInitialCongestionWindow) { EXPECT_NE(3u * kDefaultTCPMSS, sender_->GetCongestionWindow()); sender_->SetInitialCongestionWindowInPackets(3); EXPECT_EQ(3u * kDefaultTCPMSS, sender_->GetCongestionWindow()); } TEST_F(TcpCubicSenderBytesTest, 2ConnectionCongestionAvoidanceAtEndOfRecovery) { sender_->SetNumEmulatedConnections(2); const int kNumberOfAcks = 5; for (int i = 0; i < kNumberOfAcks; ++i) { SendAvailableSendWindow(); AckNPackets(2); } SendAvailableSendWindow(); QuicByteCount expected_send_window = kDefaultWindowTCP + (kDefaultTCPMSS * 2 * kNumberOfAcks); EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); LoseNPackets(1); expected_send_window = expected_send_window * sender_->GetRenoBeta(); EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); for (int i = 0; i < 10; ++i) { SendAvailableSendWindow(); EXPECT_TRUE(sender_->InRecovery()); AckNPackets(2); EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); } EXPECT_FALSE(sender_->InRecovery()); size_t packets_in_send_window = expected_send_window / kDefaultTCPMSS; SendAvailableSendWindow(); AckNPackets(packets_in_send_window / 2 - 2); EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); SendAvailableSendWindow(); AckNPackets(2); expected_send_window += kDefaultTCPMSS; packets_in_send_window += 1; EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); SendAvailableSendWindow(); AckNPackets(packets_in_send_window / 2 - 1); EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); SendAvailableSendWindow(); AckNPackets(2); expected_send_window += kDefaultTCPMSS; EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); } TEST_F(TcpCubicSenderBytesTest, 1ConnectionCongestionAvoidanceAtEndOfRecovery) { sender_->SetNumEmulatedConnections(1); const int kNumberOfAcks = 5; for (int i = 0; i < kNumberOfAcks; ++i) { SendAvailableSendWindow(); AckNPackets(2); } SendAvailableSendWindow(); QuicByteCount expected_send_window = kDefaultWindowTCP + (kDefaultTCPMSS * 2 * kNumberOfAcks); EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); LoseNPackets(1); expected_send_window *= kRenoBeta; EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); for (int i = 0; i < 10; ++i) { SendAvailableSendWindow(); EXPECT_TRUE(sender_->InRecovery()); AckNPackets(2); EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); } EXPECT_FALSE(sender_->InRecovery()); for (uint64_t i = 0; i < expected_send_window / kDefaultTCPMSS - 2; i += 2) { SendAvailableSendWindow(); AckNPackets(2); EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); } SendAvailableSendWindow(); AckNPackets(2); expected_send_window += kDefaultTCPMSS; EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); } TEST_F(TcpCubicSenderBytesTest, BandwidthResumption) { const QuicPacketCount kNumberOfPackets = 123; const QuicBandwidth kBandwidthEstimate = QuicBandwidth::FromBytesPerSecond(kNumberOfPackets * kDefaultTCPMSS); const QuicTime::Delta kRttEstimate = QuicTime::Delta::FromSeconds(1); SendAlgorithmInterface::NetworkParams network_param; network_param.bandwidth = kBandwidthEstimate; network_param.rtt = kRttEstimate; sender_->AdjustNetworkParameters(network_param); EXPECT_EQ(kNumberOfPackets * kDefaultTCPMSS, sender_->GetCongestionWindow()); SendAlgorithmInterface::NetworkParams network_param_no_bandwidth; network_param_no_bandwidth.bandwidth = QuicBandwidth::Zero(); network_param_no_bandwidth.rtt = kRttEstimate; sender_->AdjustNetworkParameters(network_param_no_bandwidth); EXPECT_EQ(kNumberOfPackets * kDefaultTCPMSS, sender_->GetCongestionWindow()); const QuicBandwidth kUnreasonableBandwidth = QuicBandwidth::FromBytesPerSecond((kMaxResumptionCongestionWindow + 1) * kDefaultTCPMSS); SendAlgorithmInterface::NetworkParams network_param_large_bandwidth; network_param_large_bandwidth.bandwidth = kUnreasonableBandwidth; network_param_large_bandwidth.rtt = QuicTime::Delta::FromSeconds(1); sender_->AdjustNetworkParameters(network_param_large_bandwidth); EXPECT_EQ(kMaxResumptionCongestionWindow * kDefaultTCPMSS, sender_->GetCongestionWindow()); } TEST_F(TcpCubicSenderBytesTest, PaceBelowCWND) { QuicConfig config; QuicTagVector options; options.push_back(kMIN4); QuicConfigPeer::SetReceivedConnectionOptions(&config, options); sender_->SetFromConfig(config, Perspective::IS_SERVER); sender_->OnRetransmissionTimeout(true); EXPECT_EQ(kDefaultTCPMSS, sender_->GetCongestionWindow()); EXPECT_TRUE(sender_->CanSend(kDefaultTCPMSS)); EXPECT_TRUE(sender_->CanSend(2 * kDefaultTCPMSS)); EXPECT_TRUE(sender_->CanSend(3 * kDefaultTCPMSS)); EXPECT_FALSE(sender_->CanSend(4 * kDefaultTCPMSS)); } TEST_F(TcpCubicSenderBytesTest, NoPRR) { QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(100); sender_->rtt_stats_.UpdateRtt(rtt, QuicTime::Delta::Zero(), QuicTime::Zero()); sender_->SetNumEmulatedConnections(1); QuicTagVector options; options.push_back(kNPRR); QuicConfig config; QuicConfigPeer::SetReceivedConnectionOptions(&config, options); sender_->SetFromConfig(config, Perspective::IS_SERVER); SendAvailableSendWindow(); LoseNPackets(9); AckNPackets(1); EXPECT_EQ(kRenoBeta * kDefaultWindowTCP, sender_->GetCongestionWindow()); const QuicPacketCount window_in_packets = kRenoBeta * kDefaultWindowTCP / kDefaultTCPMSS; const QuicBandwidth expected_pacing_rate = QuicBandwidth::FromBytesAndTimeDelta(kRenoBeta * kDefaultWindowTCP, sender_->rtt_stats_.smoothed_rtt()); EXPECT_EQ(expected_pacing_rate, sender_->PacingRate(0)); EXPECT_EQ(window_in_packets, static_cast<uint64_t>(SendAvailableSendWindow())); EXPECT_EQ(expected_pacing_rate, sender_->PacingRate(kRenoBeta * kDefaultWindowTCP)); } TEST_F(TcpCubicSenderBytesTest, ResetAfterConnectionMigration) { sender_->SetNumEmulatedConnections(1); const int kNumberOfAcks = 10; for (int i = 0; i < kNumberOfAcks; ++i) { SendAvailableSendWindow(); AckNPackets(2); } SendAvailableSendWindow(); QuicByteCount expected_send_window = kDefaultWindowTCP + (kDefaultTCPMSS * 2 * kNumberOfAcks); EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); LoseNPackets(1); expected_send_window *= kRenoBeta; EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); EXPECT_EQ(expected_send_window, sender_->GetSlowStartThreshold()); sender_->OnConnectionMigration(); EXPECT_EQ(kDefaultWindowTCP, sender_->GetCongestionWindow()); EXPECT_EQ(kMaxCongestionWindowPackets * kDefaultTCPMSS, sender_->GetSlowStartThreshold()); EXPECT_FALSE(sender_->hybrid_slow_start().started()); } TEST_F(TcpCubicSenderBytesTest, DefaultMaxCwnd) { RttStats rtt_stats; QuicConnectionStats stats; std::unique_ptr<SendAlgorithmInterface> sender(SendAlgorithmInterface::Create( &clock_, &rtt_stats, nullptr, kCubicBytes, QuicRandom::GetInstance(), &stats, kInitialCongestionWindow, nullptr)); AckedPacketVector acked_packets; LostPacketVector missing_packets; QuicPacketCount max_congestion_window = GetQuicFlag(quic_max_congestion_window); for (uint64_t i = 1; i < max_congestion_window; ++i) { acked_packets.clear(); acked_packets.push_back( AckedPacket(QuicPacketNumber(i), 1350, QuicTime::Zero())); sender->OnCongestionEvent(true, sender->GetCongestionWindow(), clock_.Now(), acked_packets, missing_packets, 0, 0); } EXPECT_EQ(max_congestion_window, sender->GetCongestionWindow() / kDefaultTCPMSS); } TEST_F(TcpCubicSenderBytesTest, LimitCwndIncreaseInCongestionAvoidance) { sender_ = std::make_unique<TcpCubicSenderBytesPeer>(&clock_, false); int num_sent = SendAvailableSendWindow(); QuicByteCount saved_cwnd = sender_->GetCongestionWindow(); LoseNPackets(1); EXPECT_GT(saved_cwnd, sender_->GetCongestionWindow()); for (int i = 1; i < num_sent; ++i) { AckNPackets(1); } EXPECT_EQ(0u, bytes_in_flight_); saved_cwnd = sender_->GetCongestionWindow(); num_sent = SendAvailableSendWindow(); while (sender_->GetCongestionWindow() == saved_cwnd) { AckNPackets(1); SendAvailableSendWindow(); } EXPECT_GE(bytes_in_flight_, sender_->GetCongestionWindow()); saved_cwnd = sender_->GetCongestionWindow(); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(2000)); AckNPackets(2); EXPECT_EQ(saved_cwnd + kDefaultTCPMSS, sender_->GetCongestionWindow()); } } }
331
cpp
google/quiche
aes_256_gcm_decrypter
quiche/quic/core/crypto/aes_256_gcm_decrypter.cc
quiche/quic/core/crypto/aes_256_gcm_decrypter_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_AES_256_GCM_DECRYPTER_H_ #define QUICHE_QUIC_CORE_CRYPTO_AES_256_GCM_DECRYPTER_H_ #include <cstdint> #include "quiche/quic/core/crypto/aes_base_decrypter.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT Aes256GcmDecrypter : public AesBaseDecrypter { public: enum { kAuthTagSize = 16, }; Aes256GcmDecrypter(); Aes256GcmDecrypter(const Aes256GcmDecrypter&) = delete; Aes256GcmDecrypter& operator=(const Aes256GcmDecrypter&) = delete; ~Aes256GcmDecrypter() override; uint32_t cipher_id() const override; }; } #endif #include "quiche/quic/core/crypto/aes_256_gcm_decrypter.h" #include "openssl/aead.h" #include "openssl/tls1.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" namespace quic { namespace { const size_t kKeySize = 32; const size_t kNonceSize = 12; } Aes256GcmDecrypter::Aes256GcmDecrypter() : AesBaseDecrypter(EVP_aead_aes_256_gcm, kKeySize, kAuthTagSize, kNonceSize, true) { static_assert(kKeySize <= kMaxKeySize, "key size too big"); static_assert(kNonceSize <= kMaxNonceSize, "nonce size too big"); } Aes256GcmDecrypter::~Aes256GcmDecrypter() {} uint32_t Aes256GcmDecrypter::cipher_id() const { return TLS1_CK_AES_256_GCM_SHA384; } }
#include "quiche/quic/core/crypto/aes_256_gcm_decrypter.h" #include <memory> #include <string> #include "absl/base/macros.h" #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace { struct TestGroupInfo { size_t key_len; size_t iv_len; size_t pt_len; size_t aad_len; size_t tag_len; }; struct TestVector { const char* key; const char* iv; const char* ct; const char* aad; const char* tag; const char* pt; }; const TestGroupInfo test_group_info[] = { {256, 96, 0, 0, 128}, {256, 96, 0, 128, 128}, {256, 96, 128, 0, 128}, {256, 96, 408, 160, 128}, {256, 96, 408, 720, 128}, {256, 96, 104, 0, 128}, }; const TestVector test_group_0[] = { {"f5a2b27c74355872eb3ef6c5feafaa740e6ae990d9d48c3bd9bb8235e589f010", "58d2240f580a31c1d24948e9", "", "", "15e051a5e4a5f5da6cea92e2ebee5bac", ""}, { "e5a8123f2e2e007d4e379ba114a2fb66e6613f57c72d4e4f024964053028a831", "51e43385bf533e168427e1ad", "", "", "38fe845c66e66bdd884c2aecafd280e6", nullptr }, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_1[] = { {"6dfdafd6703c285c01f14fd10a6012862b2af950d4733abb403b2e745b26945d", "3749d0b3d5bacb71be06ade6", "", "c0d249871992e70302ae008193d1e89f", "4aa4cc69f84ee6ac16d9bfb4e05de500", ""}, { "2c392a5eb1a9c705371beda3a901c7c61dca4d93b4291de1dd0dd15ec11ffc45", "0723fb84a08f4ea09841f32a", "", "140be561b6171eab942c486a94d33d43", "aa0e1c9b57975bfc91aa137231977d2c", nullptr }, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_2[] = { {"4c8ebfe1444ec1b2d503c6986659af2c94fafe945f72c1e8486a5acfedb8a0f8", "473360e0ad24889959858995", "d2c78110ac7e8f107c0df0570bd7c90c", "", "c26a379b6d98ef2852ead8ce83a833a7", "7789b41cb3ee548814ca0b388c10b343"}, {"3934f363fd9f771352c4c7a060682ed03c2864223a1573b3af997e2ababd60ab", "efe2656d878c586e41c539c4", "e0de64302ac2d04048d65a87d2ad09fe", "", "33cbd8d2fb8a3a03e30c1eb1b53c1d99", "697aff2d6b77e5ed6232770e400c1ead"}, { "c997768e2d14e3d38259667a6649079de77beb4543589771e5068e6cd7cd0b14", "835090aed9552dbdd45277e2", "9f6607d68e22ccf21928db0986be126e", "", "f32617f67c574fd9f44ef76ff880ab9f", nullptr }, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_3[] = { { "e9d381a9c413bee66175d5586a189836e5c20f5583535ab4d3f3e612dc21700e", "23e81571da1c7821c681c7ca", "a25f3f580306cd5065d22a6b7e9660110af7204bb77d370f7f34bee547feeff7b32a59" "6fce29c9040e68b1589aad48da881990", "6f39c9ae7b8e8a58a95f0dd8ea6a9087cbccdfd6", "5b6dcd70eefb0892fab1539298b92a4b", nullptr }, {"6450d4501b1e6cfbe172c4c8570363e96b496591b842661c28c2f6c908379cad", "7e4262035e0bf3d60e91668a", "5a99b336fd3cfd82f10fb08f7045012415f0d9a06bb92dcf59c6f0dbe62d433671aacb8a1" "c52ce7bbf6aea372bf51e2ba79406", "f1c522f026e4c5d43851da516a1b78768ab18171", "fe93b01636f7bb0458041f213e98de65", "17449e236ef5858f6d891412495ead4607bfae2a2d735182a2a0242f9d52fc5345ef912db" "e16f3bb4576fe3bcafe336dee6085"}, {"90f2e71ccb1148979cb742efc8f921de95457d898c84ce28edeed701650d3a26", "aba58ad60047ba553f6e4c98", "3fc77a5fe9203d091c7916587c9763cf2e4d0d53ca20b078b851716f1dab4873fe342b7b3" "01402f015d00263bf3f77c58a99d6", "2abe465df6e5be47f05b92c9a93d76ae3611fac5", "9cb3d04637048bc0bddef803ffbb56cf", "1d21639640e11638a2769e3fab78778f84be3f4a8ce28dfd99cb2e75171e05ea8e94e30aa" "78b54bb402b39d613616a8ed951dc"}, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_4[] = { { "e36aca93414b13f5313e76a7244588ee116551d1f34c32859166f2eb0ac1a9b7", "e9e701b1ccef6bddd03391d8", "5b059ac6733b6de0e8cf5b88b7301c02c993426f71bb12abf692e9deeacfac1ff1644c" "87d4df130028f515f0feda636309a24d", "6a08fe6e55a08f283cec4c4b37676e770f402af6102f548ad473ec6236da764f7076ff" "d41bbd9611b439362d899682b7b0f839fc5a68d9df54afd1e2b3c4e7d072454ee27111" "d52193d28b9c4f925d2a8b451675af39191a2cba", "43c7c9c93cc265fc8e192000e0417b5b", nullptr }, {"5f72046245d3f4a0877e50a86554bfd57d1c5e073d1ed3b5451f6d0fc2a8507a", "ea6f5b391e44b751b26bce6f", "0e6e0b2114c40769c15958d965a14dcf50b680e0185a4409d77d894ca15b1e698dd83b353" "6b18c05d8cd0873d1edce8150ecb5", "9b3a68c941d42744673fb60fea49075eae77322e7e70e34502c115b6495ebfc796d629080" "7653c6b53cd84281bd0311656d0013f44619d2748177e99e8f8347c989a7b59f9d8dcf00f" "31db0684a4a83e037e8777bae55f799b0d", "fdaaff86ceb937502cd9012d03585800", "b0a881b751cc1eb0c912a4cf9bd971983707dbd2411725664503455c55db25cdb19bc669c" "2654a3a8011de6bf7eff3f9f07834"}, {"ab639bae205547607506522bd3cdca7861369e2b42ef175ff135f6ba435d5a8e", "5fbb63eb44bd59fee458d8f6", "9a34c62bed0972285503a32812877187a54dedbd55d2317fed89282bf1af4ba0b6bb9f9e1" "6dd86da3b441deb7841262bc6bd63", "1ef2b1768b805587935ffaf754a11bd2a305076d6374f1f5098b1284444b78f55408a786d" "a37e1b7f1401c330d3585ef56f3e4d35eaaac92e1381d636477dc4f4beaf559735e902d6b" "e58723257d4ac1ed9bd213de387f35f3c4", "e0299e079bff46fd12e36d1c60e41434", "e5a3ce804a8516cdd12122c091256b789076576040dbf3c55e8be3c016025896b8a72532b" "fd51196cc82efca47aa0fd8e2e0dc"}, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_5[] = { { "8b37c4b8cf634704920059866ad96c49e9da502c63fca4a3a7a4dcec74cb0610", "cb59344d2b06c4ae57cd0ea4", "66ab935c93555e786b775637a3", "", "d8733acbb564d8afaa99d7ca2e2f92a9", nullptr }, {"a71dac1377a3bf5d7fb1b5e36bee70d2e01de2a84a1c1009ba7448f7f26131dc", "c5b60dda3f333b1146e9da7c", "43af49ec1ae3738a20755034d6", "", "6f80b6ef2d8830a55eb63680a8dff9e0", "5b87141335f2becac1a559e05f"}, {"dc1f64681014be221b00793bbcf5a5bc675b968eb7a3a3d5aa5978ef4fa45ecc", "056ae9a1a69e38af603924fe", "33013a48d9ea0df2911d583271", "", "5b8f9cc22303e979cd1524187e9f70fe", "2a7e05612191c8bce2f529dca9"}, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector* const test_group_array[] = { test_group_0, test_group_1, test_group_2, test_group_3, test_group_4, test_group_5, }; } namespace quic { namespace test { QuicData* DecryptWithNonce(Aes256GcmDecrypter* decrypter, absl::string_view nonce, absl::string_view associated_data, absl::string_view ciphertext) { decrypter->SetIV(nonce); std::unique_ptr<char[]> output(new char[ciphertext.length()]); size_t output_length = 0; const bool success = decrypter->DecryptPacket(0, associated_data, ciphertext, output.get(), &output_length, ciphertext.length()); if (!success) { return nullptr; } return new QuicData(output.release(), output_length, true); } class Aes256GcmDecrypterTest : public QuicTest {}; TEST_F(Aes256GcmDecrypterTest, Decrypt) { for (size_t i = 0; i < ABSL_ARRAYSIZE(test_group_array); i++) { SCOPED_TRACE(i); const TestVector* test_vectors = test_group_array[i]; const TestGroupInfo& test_info = test_group_info[i]; for (size_t j = 0; test_vectors[j].key != nullptr; j++) { bool has_pt = test_vectors[j].pt; std::string key; std::string iv; std::string ct; std::string aad; std::string tag; std::string pt; ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].key, &key)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].iv, &iv)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].ct, &ct)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].aad, &aad)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].tag, &tag)); if (has_pt) { ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].pt, &pt)); } EXPECT_EQ(test_info.key_len, key.length() * 8); EXPECT_EQ(test_info.iv_len, iv.length() * 8); EXPECT_EQ(test_info.pt_len, ct.length() * 8); EXPECT_EQ(test_info.aad_len, aad.length() * 8); EXPECT_EQ(test_info.tag_len, tag.length() * 8); if (has_pt) { EXPECT_EQ(test_info.pt_len, pt.length() * 8); } std::string ciphertext = ct + tag; Aes256GcmDecrypter decrypter; ASSERT_TRUE(decrypter.SetKey(key)); std::unique_ptr<QuicData> decrypted(DecryptWithNonce( &decrypter, iv, aad.length() ? aad : absl::string_view(), ciphertext)); if (!decrypted) { EXPECT_FALSE(has_pt); continue; } EXPECT_TRUE(has_pt); ASSERT_EQ(pt.length(), decrypted->length()); quiche::test::CompareCharArraysWithHexError( "plaintext", decrypted->data(), pt.length(), pt.data(), pt.length()); } } } TEST_F(Aes256GcmDecrypterTest, GenerateHeaderProtectionMask) { Aes256GcmDecrypter decrypter; std::string key; std::string sample; std::string expected_mask; ASSERT_TRUE(absl::HexStringToBytes( "ed23ecbf54d426def5c52c3dcfc84434e62e57781d3125bb21ed91b7d3e07788", &key)); ASSERT_TRUE( absl::HexStringToBytes("4d190c474be2b8babafb49ec4e38e810", &sample)); ASSERT_TRUE(absl::HexStringToBytes("db9ed4e6ccd033af2eae01407199c56e", &expected_mask)); QuicDataReader sample_reader(sample.data(), sample.size()); ASSERT_TRUE(decrypter.SetHeaderProtectionKey(key)); std::string mask = decrypter.GenerateHeaderProtectionMask(&sample_reader); quiche::test::CompareCharArraysWithHexError( "header protection mask", mask.data(), mask.size(), expected_mask.data(), expected_mask.size()); } } }
332
cpp
google/quiche
chacha20_poly1305_tls_decrypter
quiche/quic/core/crypto/chacha20_poly1305_tls_decrypter.cc
quiche/quic/core/crypto/chacha20_poly1305_tls_decrypter_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_CHACHA20_POLY1305_TLS_DECRYPTER_H_ #define QUICHE_QUIC_CORE_CRYPTO_CHACHA20_POLY1305_TLS_DECRYPTER_H_ #include <cstdint> #include "quiche/quic/core/crypto/chacha_base_decrypter.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT ChaCha20Poly1305TlsDecrypter : public ChaChaBaseDecrypter { public: enum { kAuthTagSize = 16, }; ChaCha20Poly1305TlsDecrypter(); ChaCha20Poly1305TlsDecrypter(const ChaCha20Poly1305TlsDecrypter&) = delete; ChaCha20Poly1305TlsDecrypter& operator=(const ChaCha20Poly1305TlsDecrypter&) = delete; ~ChaCha20Poly1305TlsDecrypter() override; uint32_t cipher_id() const override; QuicPacketCount GetIntegrityLimit() const override; }; } #endif #include "quiche/quic/core/crypto/chacha20_poly1305_tls_decrypter.h" #include "openssl/aead.h" #include "openssl/tls1.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" namespace quic { namespace { const size_t kKeySize = 32; const size_t kNonceSize = 12; } ChaCha20Poly1305TlsDecrypter::ChaCha20Poly1305TlsDecrypter() : ChaChaBaseDecrypter(EVP_aead_chacha20_poly1305, kKeySize, kAuthTagSize, kNonceSize, true) { static_assert(kKeySize <= kMaxKeySize, "key size too big"); static_assert(kNonceSize <= kMaxNonceSize, "nonce size too big"); } ChaCha20Poly1305TlsDecrypter::~ChaCha20Poly1305TlsDecrypter() {} uint32_t ChaCha20Poly1305TlsDecrypter::cipher_id() const { return TLS1_CK_CHACHA20_POLY1305_SHA256; } QuicPacketCount ChaCha20Poly1305TlsDecrypter::GetIntegrityLimit() const { static_assert(kMaxIncomingPacketSize < 16384, "This key limit requires limits on decryption payload sizes"); return 68719476736U; } }
#include "quiche/quic/core/crypto/chacha20_poly1305_tls_decrypter.h" #include <memory> #include <string> #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace { struct TestVector { const char* key; const char* iv; const char* fixed; const char* aad; const char* ct; const char* pt; }; const TestVector test_vectors[] = { {"808182838485868788898a8b8c8d8e8f" "909192939495969798999a9b9c9d9e9f", "4041424344454647", "07000000", "50515253c0c1c2c3c4c5c6c7", "d31a8d34648e60db7b86afbc53ef7ec2" "a4aded51296e08fea9e2b5a736ee62d6" "3dbea45e8ca9671282fafb69da92728b" "1a71de0a9e060b2905d6a5b67ecd3b36" "92ddbd7f2d778b8c9803aee328091b58" "fab324e4fad675945585808b4831d7bc" "3ff4def08e4b7a9de576d26586cec64b" "6116" "1ae10b594f09e26a7e902ecbd0600691", "4c616469657320616e642047656e746c" "656d656e206f662074686520636c6173" "73206f66202739393a20496620492063" "6f756c64206f6666657220796f75206f" "6e6c79206f6e652074697020666f7220" "746865206675747572652c2073756e73" "637265656e20776f756c642062652069" "742e"}, {"808182838485868788898a8b8c8d8e8f" "909192939495969798999a9b9c9d9e9f", "4041424344454647", "07000000", "50515253c0c1c2c3c4c5c6c7", "d31a8d34648e60db7b86afbc53ef7ec2" "a4aded51296e08fea9e2b5a736ee62d6" "3dbea45e8ca9671282fafb69da92728b" "1a71de0a9e060b2905d6a5b67ecd3b36" "92ddbd7f2d778b8c9803aee328091b58" "fab324e4fad675945585808b4831d7bc" "3ff4def08e4b7a9de576d26586cec64b" "6116" "1ae10b594f09e26a7e902eccd0600691", nullptr}, {"808182838485868788898a8b8c8d8e8f" "909192939495969798999a9b9c9d9e9f", "4041424344454647", "07000000", "60515253c0c1c2c3c4c5c6c7", "d31a8d34648e60db7b86afbc53ef7ec2" "a4aded51296e08fea9e2b5a736ee62d6" "3dbea45e8ca9671282fafb69da92728b" "1a71de0a9e060b2905d6a5b67ecd3b36" "92ddbd7f2d778b8c9803aee328091b58" "fab324e4fad675945585808b4831d7bc" "3ff4def08e4b7a9de576d26586cec64b" "6116" "1ae10b594f09e26a7e902ecbd0600691", nullptr}, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; } namespace quic { namespace test { QuicData* DecryptWithNonce(ChaCha20Poly1305TlsDecrypter* decrypter, absl::string_view nonce, absl::string_view associated_data, absl::string_view ciphertext) { decrypter->SetIV(nonce); std::unique_ptr<char[]> output(new char[ciphertext.length()]); size_t output_length = 0; const bool success = decrypter->DecryptPacket(0, associated_data, ciphertext, output.get(), &output_length, ciphertext.length()); if (!success) { return nullptr; } return new QuicData(output.release(), output_length, true); } class ChaCha20Poly1305TlsDecrypterTest : public QuicTest {}; TEST_F(ChaCha20Poly1305TlsDecrypterTest, Decrypt) { for (size_t i = 0; test_vectors[i].key != nullptr; i++) { bool has_pt = test_vectors[i].pt; std::string key; std::string iv; std::string fixed; std::string aad; std::string ct; std::string pt; ASSERT_TRUE(absl::HexStringToBytes(test_vectors[i].key, &key)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[i].iv, &iv)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[i].fixed, &fixed)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[i].aad, &aad)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[i].ct, &ct)); if (has_pt) { ASSERT_TRUE(absl::HexStringToBytes(test_vectors[i].pt, &pt)); } ChaCha20Poly1305TlsDecrypter decrypter; ASSERT_TRUE(decrypter.SetKey(key)); std::unique_ptr<QuicData> decrypted(DecryptWithNonce( &decrypter, fixed + iv, absl::string_view(aad.length() ? aad.data() : nullptr, aad.length()), ct)); if (!decrypted) { EXPECT_FALSE(has_pt); continue; } EXPECT_TRUE(has_pt); EXPECT_EQ(16u, ct.size() - decrypted->length()); ASSERT_EQ(pt.length(), decrypted->length()); quiche::test::CompareCharArraysWithHexError( "plaintext", decrypted->data(), pt.length(), pt.data(), pt.length()); } } TEST_F(ChaCha20Poly1305TlsDecrypterTest, GenerateHeaderProtectionMask) { ChaCha20Poly1305TlsDecrypter decrypter; std::string key; std::string sample; std::string expected_mask; ASSERT_TRUE(absl::HexStringToBytes( "6a067f432787bd6034dd3f08f07fc9703a27e58c70e2d88d948b7f6489923cc7", &key)); ASSERT_TRUE( absl::HexStringToBytes("1210d91cceb45c716b023f492c29e612", &sample)); ASSERT_TRUE(absl::HexStringToBytes("1cc2cd98dc", &expected_mask)); QuicDataReader sample_reader(sample.data(), sample.size()); ASSERT_TRUE(decrypter.SetHeaderProtectionKey(key)); std::string mask = decrypter.GenerateHeaderProtectionMask(&sample_reader); quiche::test::CompareCharArraysWithHexError( "header protection mask", mask.data(), mask.size(), expected_mask.data(), expected_mask.size()); } } }
333
cpp
google/quiche
curve25519_key_exchange
quiche/quic/core/crypto/curve25519_key_exchange.cc
quiche/quic/core/crypto/curve25519_key_exchange_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_CURVE25519_KEY_EXCHANGE_H_ #define QUICHE_QUIC_CORE_CRYPTO_CURVE25519_KEY_EXCHANGE_H_ #include <cstdint> #include <string> #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/key_exchange.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT Curve25519KeyExchange : public SynchronousKeyExchange { public: ~Curve25519KeyExchange() override; static std::unique_ptr<Curve25519KeyExchange> New(QuicRandom* rand); static std::unique_ptr<Curve25519KeyExchange> New( absl::string_view private_key); static std::string NewPrivateKey(QuicRandom* rand); bool CalculateSharedKeySync(absl::string_view peer_public_value, std::string* shared_key) const override; absl::string_view public_value() const override; QuicTag type() const override { return kC255; } private: Curve25519KeyExchange(); uint8_t private_key_[32]; uint8_t public_key_[32]; }; } #endif #include "quiche/quic/core/crypto/curve25519_key_exchange.h" #include <cstdint> #include <cstring> #include <memory> #include <string> #include "absl/memory/memory.h" #include "absl/strings/string_view.h" #include "openssl/curve25519.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" namespace quic { Curve25519KeyExchange::Curve25519KeyExchange() {} Curve25519KeyExchange::~Curve25519KeyExchange() {} std::unique_ptr<Curve25519KeyExchange> Curve25519KeyExchange::New( QuicRandom* rand) { std::unique_ptr<Curve25519KeyExchange> result = New(Curve25519KeyExchange::NewPrivateKey(rand)); QUIC_BUG_IF(quic_bug_12891_1, result == nullptr); return result; } std::unique_ptr<Curve25519KeyExchange> Curve25519KeyExchange::New( absl::string_view private_key) { static_assert( sizeof(Curve25519KeyExchange::private_key_) == X25519_PRIVATE_KEY_LEN, "header out of sync"); static_assert( sizeof(Curve25519KeyExchange::public_key_) == X25519_PUBLIC_VALUE_LEN, "header out of sync"); if (private_key.size() != X25519_PRIVATE_KEY_LEN) { return nullptr; } auto ka = absl::WrapUnique(new Curve25519KeyExchange); memcpy(ka->private_key_, private_key.data(), X25519_PRIVATE_KEY_LEN); X25519_public_from_private(ka->public_key_, ka->private_key_); return ka; } std::string Curve25519KeyExchange::NewPrivateKey(QuicRandom* rand) { uint8_t private_key[X25519_PRIVATE_KEY_LEN]; rand->RandBytes(private_key, sizeof(private_key)); return std::string(reinterpret_cast<char*>(private_key), sizeof(private_key)); } bool Curve25519KeyExchange::CalculateSharedKeySync( absl::string_view peer_public_value, std::string* shared_key) const { if (peer_public_value.size() != X25519_PUBLIC_VALUE_LEN) { return false; } uint8_t result[X25519_PUBLIC_VALUE_LEN]; if (!X25519(result, private_key_, reinterpret_cast<const uint8_t*>(peer_public_value.data()))) { return false; } shared_key->assign(reinterpret_cast<char*>(result), sizeof(result)); return true; } absl::string_view Curve25519KeyExchange::public_value() const { return absl::string_view(reinterpret_cast<const char*>(public_key_), sizeof(public_key_)); } }
#include "quiche/quic/core/crypto/curve25519_key_exchange.h" #include <memory> #include <string> #include <utility> #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { class Curve25519KeyExchangeTest : public QuicTest { public: class TestCallbackResult { public: void set_ok(bool ok) { ok_ = ok; } bool ok() { return ok_; } private: bool ok_ = false; }; class TestCallback : public AsynchronousKeyExchange::Callback { public: TestCallback(TestCallbackResult* result) : result_(result) {} virtual ~TestCallback() = default; void Run(bool ok) { result_->set_ok(ok); } private: TestCallbackResult* result_; }; }; TEST_F(Curve25519KeyExchangeTest, SharedKey) { QuicRandom* const rand = QuicRandom::GetInstance(); for (int i = 0; i < 5; i++) { const std::string alice_key(Curve25519KeyExchange::NewPrivateKey(rand)); const std::string bob_key(Curve25519KeyExchange::NewPrivateKey(rand)); std::unique_ptr<Curve25519KeyExchange> alice( Curve25519KeyExchange::New(alice_key)); std::unique_ptr<Curve25519KeyExchange> bob( Curve25519KeyExchange::New(bob_key)); const absl::string_view alice_public(alice->public_value()); const absl::string_view bob_public(bob->public_value()); std::string alice_shared, bob_shared; ASSERT_TRUE(alice->CalculateSharedKeySync(bob_public, &alice_shared)); ASSERT_TRUE(bob->CalculateSharedKeySync(alice_public, &bob_shared)); ASSERT_EQ(alice_shared, bob_shared); } } TEST_F(Curve25519KeyExchangeTest, SharedKeyAsync) { QuicRandom* const rand = QuicRandom::GetInstance(); for (int i = 0; i < 5; i++) { const std::string alice_key(Curve25519KeyExchange::NewPrivateKey(rand)); const std::string bob_key(Curve25519KeyExchange::NewPrivateKey(rand)); std::unique_ptr<Curve25519KeyExchange> alice( Curve25519KeyExchange::New(alice_key)); std::unique_ptr<Curve25519KeyExchange> bob( Curve25519KeyExchange::New(bob_key)); const absl::string_view alice_public(alice->public_value()); const absl::string_view bob_public(bob->public_value()); std::string alice_shared, bob_shared; TestCallbackResult alice_result; ASSERT_FALSE(alice_result.ok()); alice->CalculateSharedKeyAsync( bob_public, &alice_shared, std::make_unique<TestCallback>(&alice_result)); ASSERT_TRUE(alice_result.ok()); TestCallbackResult bob_result; ASSERT_FALSE(bob_result.ok()); bob->CalculateSharedKeyAsync(alice_public, &bob_shared, std::make_unique<TestCallback>(&bob_result)); ASSERT_TRUE(bob_result.ok()); ASSERT_EQ(alice_shared, bob_shared); ASSERT_NE(0u, alice_shared.length()); ASSERT_NE(0u, bob_shared.length()); } } } }
334
cpp
google/quiche
quic_hkdf
quiche/quic/core/crypto/quic_hkdf.cc
quiche/quic/core/crypto/quic_hkdf_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_QUIC_HKDF_H_ #define QUICHE_QUIC_CORE_CRYPTO_QUIC_HKDF_H_ #include <cstdint> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT QuicHKDF { public: QuicHKDF(absl::string_view secret, absl::string_view salt, absl::string_view info, size_t key_bytes_to_generate, size_t iv_bytes_to_generate, size_t subkey_secret_bytes_to_generate); QuicHKDF(absl::string_view secret, absl::string_view salt, absl::string_view info, size_t client_key_bytes_to_generate, size_t server_key_bytes_to_generate, size_t client_iv_bytes_to_generate, size_t server_iv_bytes_to_generate, size_t subkey_secret_bytes_to_generate); ~QuicHKDF(); absl::string_view client_write_key() const { return client_write_key_; } absl::string_view client_write_iv() const { return client_write_iv_; } absl::string_view server_write_key() const { return server_write_key_; } absl::string_view server_write_iv() const { return server_write_iv_; } absl::string_view subkey_secret() const { return subkey_secret_; } absl::string_view client_hp_key() const { return client_hp_key_; } absl::string_view server_hp_key() const { return server_hp_key_; } private: std::vector<uint8_t> output_; absl::string_view client_write_key_; absl::string_view server_write_key_; absl::string_view client_write_iv_; absl::string_view server_write_iv_; absl::string_view subkey_secret_; absl::string_view client_hp_key_; absl::string_view server_hp_key_; }; } #endif #include "quiche/quic/core/crypto/quic_hkdf.h" #include <memory> #include "absl/strings/string_view.h" #include "openssl/digest.h" #include "openssl/hkdf.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { const size_t kSHA256HashLength = 32; const size_t kMaxKeyMaterialSize = kSHA256HashLength * 256; QuicHKDF::QuicHKDF(absl::string_view secret, absl::string_view salt, absl::string_view info, size_t key_bytes_to_generate, size_t iv_bytes_to_generate, size_t subkey_secret_bytes_to_generate) : QuicHKDF(secret, salt, info, key_bytes_to_generate, key_bytes_to_generate, iv_bytes_to_generate, iv_bytes_to_generate, subkey_secret_bytes_to_generate) {} QuicHKDF::QuicHKDF(absl::string_view secret, absl::string_view salt, absl::string_view info, size_t client_key_bytes_to_generate, size_t server_key_bytes_to_generate, size_t client_iv_bytes_to_generate, size_t server_iv_bytes_to_generate, size_t subkey_secret_bytes_to_generate) { const size_t material_length = 2 * client_key_bytes_to_generate + client_iv_bytes_to_generate + 2 * server_key_bytes_to_generate + server_iv_bytes_to_generate + subkey_secret_bytes_to_generate; QUICHE_DCHECK_LT(material_length, kMaxKeyMaterialSize); output_.resize(material_length); if (output_.empty()) { return; } ::HKDF(&output_[0], output_.size(), ::EVP_sha256(), reinterpret_cast<const uint8_t*>(secret.data()), secret.size(), reinterpret_cast<const uint8_t*>(salt.data()), salt.size(), reinterpret_cast<const uint8_t*>(info.data()), info.size()); size_t j = 0; if (client_key_bytes_to_generate) { client_write_key_ = absl::string_view(reinterpret_cast<char*>(&output_[j]), client_key_bytes_to_generate); j += client_key_bytes_to_generate; } if (server_key_bytes_to_generate) { server_write_key_ = absl::string_view(reinterpret_cast<char*>(&output_[j]), server_key_bytes_to_generate); j += server_key_bytes_to_generate; } if (client_iv_bytes_to_generate) { client_write_iv_ = absl::string_view(reinterpret_cast<char*>(&output_[j]), client_iv_bytes_to_generate); j += client_iv_bytes_to_generate; } if (server_iv_bytes_to_generate) { server_write_iv_ = absl::string_view(reinterpret_cast<char*>(&output_[j]), server_iv_bytes_to_generate); j += server_iv_bytes_to_generate; } if (subkey_secret_bytes_to_generate) { subkey_secret_ = absl::string_view(reinterpret_cast<char*>(&output_[j]), subkey_secret_bytes_to_generate); j += subkey_secret_bytes_to_generate; } if (client_key_bytes_to_generate) { client_hp_key_ = absl::string_view(reinterpret_cast<char*>(&output_[j]), client_key_bytes_to_generate); j += client_key_bytes_to_generate; } if (server_key_bytes_to_generate) { server_hp_key_ = absl::string_view(reinterpret_cast<char*>(&output_[j]), server_key_bytes_to_generate); j += server_key_bytes_to_generate; } } QuicHKDF::~QuicHKDF() {} }
#include "quiche/quic/core/crypto/quic_hkdf.h" #include <string> #include "absl/base/macros.h" #include "absl/strings/escaping.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { namespace { struct HKDFInput { const char* key_hex; const char* salt_hex; const char* info_hex; const char* output_hex; }; static const HKDFInput kHKDFInputs[] = { { "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", "000102030405060708090a0b0c", "f0f1f2f3f4f5f6f7f8f9", "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf340072" "08d5" "b887185865", }, { "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122" "2324" "25262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f4041424344454647" "4849" "4a4b4c4d4e4f", "606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182" "8384" "85868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7" "a8a9" "aaabacadaeaf", "b0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2" "d3d4" "d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7" "f8f9" "fafbfcfdfeff", "b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c59045a" "99ca" "c7827271cb41c65e590e09da3275600c2f09b8367793a9aca3db71cc30c58179ec3e87" "c14c" "01d5c1f3434f1d87", }, { "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", "", "", "8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d2013" "95fa" "a4b61a96c8", }, }; class QuicHKDFTest : public QuicTest {}; TEST_F(QuicHKDFTest, HKDF) { for (size_t i = 0; i < ABSL_ARRAYSIZE(kHKDFInputs); i++) { const HKDFInput& test(kHKDFInputs[i]); SCOPED_TRACE(i); std::string key; std::string salt; std::string info; std::string expected; ASSERT_TRUE(absl::HexStringToBytes(test.key_hex, &key)); ASSERT_TRUE(absl::HexStringToBytes(test.salt_hex, &salt)); ASSERT_TRUE(absl::HexStringToBytes(test.info_hex, &info)); ASSERT_TRUE(absl::HexStringToBytes(test.output_hex, &expected)); QuicHKDF hkdf(key, salt, info, expected.size(), 0, 0); ASSERT_EQ(expected.size(), hkdf.client_write_key().size()); EXPECT_EQ(0, memcmp(expected.data(), hkdf.client_write_key().data(), expected.size())); } } } } }
335
cpp
google/quiche
aes_128_gcm_12_encrypter
quiche/quic/core/crypto/aes_128_gcm_12_encrypter.cc
quiche/quic/core/crypto/aes_128_gcm_12_encrypter_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_AES_128_GCM_12_ENCRYPTER_H_ #define QUICHE_QUIC_CORE_CRYPTO_AES_128_GCM_12_ENCRYPTER_H_ #include "quiche/quic/core/crypto/aes_base_encrypter.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT Aes128Gcm12Encrypter : public AesBaseEncrypter { public: enum { kAuthTagSize = 12, }; Aes128Gcm12Encrypter(); Aes128Gcm12Encrypter(const Aes128Gcm12Encrypter&) = delete; Aes128Gcm12Encrypter& operator=(const Aes128Gcm12Encrypter&) = delete; ~Aes128Gcm12Encrypter() override; }; } #endif #include "quiche/quic/core/crypto/aes_128_gcm_12_encrypter.h" #include "openssl/evp.h" namespace quic { namespace { const size_t kKeySize = 16; const size_t kNonceSize = 12; } Aes128Gcm12Encrypter::Aes128Gcm12Encrypter() : AesBaseEncrypter(EVP_aead_aes_128_gcm, kKeySize, kAuthTagSize, kNonceSize, false) { static_assert(kKeySize <= kMaxKeySize, "key size too big"); static_assert(kNonceSize <= kMaxNonceSize, "nonce size too big"); } Aes128Gcm12Encrypter::~Aes128Gcm12Encrypter() {} }
#include "quiche/quic/core/crypto/aes_128_gcm_12_encrypter.h" #include <memory> #include <string> #include "absl/base/macros.h" #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace { struct TestGroupInfo { size_t key_len; size_t iv_len; size_t pt_len; size_t aad_len; size_t tag_len; }; struct TestVector { const char* key; const char* iv; const char* pt; const char* aad; const char* ct; const char* tag; }; const TestGroupInfo test_group_info[] = { {128, 96, 0, 0, 128}, {128, 96, 0, 128, 128}, {128, 96, 128, 0, 128}, {128, 96, 408, 160, 128}, {128, 96, 408, 720, 128}, {128, 96, 104, 0, 128}, }; const TestVector test_group_0[] = { {"11754cd72aec309bf52f7687212e8957", "3c819d9a9bed087615030b65", "", "", "", "250327c674aaf477aef2675748cf6971"}, {"ca47248ac0b6f8372a97ac43508308ed", "ffd2b598feabc9019262d2be", "", "", "", "60d20404af527d248d893ae495707d1a"}, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_1[] = { {"77be63708971c4e240d1cb79e8d77feb", "e0e00f19fed7ba0136a797f3", "", "7a43ec1d9c0a5a78a0b16533a6213cab", "", "209fcc8d3675ed938e9c7166709dd946"}, {"7680c5d3ca6154758e510f4d25b98820", "f8f105f9c3df4965780321f8", "", "c94c410194c765e3dcc7964379758ed3", "", "94dca8edfcf90bb74b153c8d48a17930"}, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_2[] = { {"7fddb57453c241d03efbed3ac44e371c", "ee283a3fc75575e33efd4887", "d5de42b461646c255c87bd2962d3b9a2", "", "2ccda4a5415cb91e135c2a0f78c9b2fd", "b36d1df9b9d5e596f83e8b7f52971cb3"}, {"ab72c77b97cb5fe9a382d9fe81ffdbed", "54cc7dc2c37ec006bcc6d1da", "007c5e5b3e59df24a7c355584fc1518d", "", "0e1bde206a07a9c2c1b65300f8c64997", "2b4401346697138c7a4891ee59867d0c"}, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_3[] = { {"fe47fcce5fc32665d2ae399e4eec72ba", "5adb9609dbaeb58cbd6e7275", "7c0e88c88899a779228465074797cd4c2e1498d259b54390b85e3eef1c02df60e743f1" "b840382c4bccaf3bafb4ca8429bea063", "88319d6e1d3ffa5f987199166c8a9b56c2aeba5a", "98f4826f05a265e6dd2be82db241c0fbbbf9ffb1c173aa83964b7cf539304373636525" "3ddbc5db8778371495da76d269e5db3e", "291ef1982e4defedaa2249f898556b47"}, {"ec0c2ba17aa95cd6afffe949da9cc3a8", "296bce5b50b7d66096d627ef", "b85b3753535b825cbe5f632c0b843c741351f18aa484281aebec2f45bb9eea2d79d987" "b764b9611f6c0f8641843d5d58f3a242", "f8d00f05d22bf68599bcdeb131292ad6e2df5d14", "a7443d31c26bdf2a1c945e29ee4bd344a99cfaf3aa71f8b3f191f83c2adfc7a0716299" "5506fde6309ffc19e716eddf1a828c5a", "890147971946b627c40016da1ecf3e77"}, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_4[] = { {"2c1f21cf0f6fb3661943155c3e3d8492", "23cb5ff362e22426984d1907", "42f758836986954db44bf37c6ef5e4ac0adaf38f27252a1b82d02ea949c8a1a2dbc0d6" "8b5615ba7c1220ff6510e259f06655d8", "5d3624879d35e46849953e45a32a624d6a6c536ed9857c613b572b0333e701557a713e" "3f010ecdf9a6bd6c9e3e44b065208645aff4aabee611b391528514170084ccf587177f" "4488f33cfb5e979e42b6e1cfc0a60238982a7aec", "81824f0e0d523db30d3da369fdc0d60894c7a0a20646dd015073ad2732bd989b14a222" "b6ad57af43e1895df9dca2a5344a62cc", "57a3ee28136e94c74838997ae9823f3a"}, {"d9f7d2411091f947b4d6f1e2d1f0fb2e", "e1934f5db57cc983e6b180e7", "73ed042327f70fe9c572a61545eda8b2a0c6e1d6c291ef19248e973aee6c312012f490" "c2c6f6166f4a59431e182663fcaea05a", "0a8a18a7150e940c3d87b38e73baee9a5c049ee21795663e264b694a949822b639092d" "0e67015e86363583fcf0ca645af9f43375f05fdb4ce84f411dcbca73c2220dea03a201" "15d2e51398344b16bee1ed7c499b353d6c597af8", "aaadbd5c92e9151ce3db7210b8714126b73e43436d242677afa50384f2149b831f1d57" "3c7891c2a91fbc48db29967ec9542b23", "21b51ca862cb637cdd03b99a0f93b134"}, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_5[] = { {"fe9bb47deb3a61e423c2231841cfd1fb", "4d328eb776f500a2f7fb47aa", "f1cc3818e421876bb6b8bbd6c9", "", "b88c5c1977b35b517b0aeae967", "43fd4727fe5cdb4b5b42818dea7ef8c9"}, {"6703df3701a7f54911ca72e24dca046a", "12823ab601c350ea4bc2488c", "793cd125b0b84a043e3ac67717", "", "b2051c80014f42f08735a7b0cd", "38e6bcd29962e5f2c13626b85a877101"}, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector* const test_group_array[] = { test_group_0, test_group_1, test_group_2, test_group_3, test_group_4, test_group_5, }; } namespace quic { namespace test { QuicData* EncryptWithNonce(Aes128Gcm12Encrypter* encrypter, absl::string_view nonce, absl::string_view associated_data, absl::string_view plaintext) { size_t ciphertext_size = encrypter->GetCiphertextSize(plaintext.length()); std::unique_ptr<char[]> ciphertext(new char[ciphertext_size]); if (!encrypter->Encrypt(nonce, associated_data, plaintext, reinterpret_cast<unsigned char*>(ciphertext.get()))) { return nullptr; } return new QuicData(ciphertext.release(), ciphertext_size, true); } class Aes128Gcm12EncrypterTest : public QuicTest {}; TEST_F(Aes128Gcm12EncrypterTest, Encrypt) { for (size_t i = 0; i < ABSL_ARRAYSIZE(test_group_array); i++) { SCOPED_TRACE(i); const TestVector* test_vectors = test_group_array[i]; const TestGroupInfo& test_info = test_group_info[i]; for (size_t j = 0; test_vectors[j].key != nullptr; j++) { std::string key; std::string iv; std::string pt; std::string aad; std::string ct; std::string tag; ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].key, &key)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].iv, &iv)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].pt, &pt)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].aad, &aad)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].ct, &ct)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].tag, &tag)); EXPECT_EQ(test_info.key_len, key.length() * 8); EXPECT_EQ(test_info.iv_len, iv.length() * 8); EXPECT_EQ(test_info.pt_len, pt.length() * 8); EXPECT_EQ(test_info.aad_len, aad.length() * 8); EXPECT_EQ(test_info.pt_len, ct.length() * 8); EXPECT_EQ(test_info.tag_len, tag.length() * 8); Aes128Gcm12Encrypter encrypter; ASSERT_TRUE(encrypter.SetKey(key)); std::unique_ptr<QuicData> encrypted( EncryptWithNonce(&encrypter, iv, aad.length() ? aad : absl::string_view(), pt)); ASSERT_TRUE(encrypted.get()); ASSERT_LE(static_cast<size_t>(Aes128Gcm12Encrypter::kAuthTagSize), tag.length()); tag.resize(Aes128Gcm12Encrypter::kAuthTagSize); ASSERT_EQ(ct.length() + tag.length(), encrypted->length()); quiche::test::CompareCharArraysWithHexError( "ciphertext", encrypted->data(), ct.length(), ct.data(), ct.length()); quiche::test::CompareCharArraysWithHexError( "authentication tag", encrypted->data() + ct.length(), tag.length(), tag.data(), tag.length()); } } } TEST_F(Aes128Gcm12EncrypterTest, GetMaxPlaintextSize) { Aes128Gcm12Encrypter encrypter; EXPECT_EQ(1000u, encrypter.GetMaxPlaintextSize(1012)); EXPECT_EQ(100u, encrypter.GetMaxPlaintextSize(112)); EXPECT_EQ(10u, encrypter.GetMaxPlaintextSize(22)); EXPECT_EQ(0u, encrypter.GetMaxPlaintextSize(11)); } TEST_F(Aes128Gcm12EncrypterTest, GetCiphertextSize) { Aes128Gcm12Encrypter encrypter; EXPECT_EQ(1012u, encrypter.GetCiphertextSize(1000)); EXPECT_EQ(112u, encrypter.GetCiphertextSize(100)); EXPECT_EQ(22u, encrypter.GetCiphertextSize(10)); } } }
336
cpp
google/quiche
null_encrypter
quiche/quic/core/crypto/null_encrypter.cc
quiche/quic/core/crypto/null_encrypter_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_NULL_ENCRYPTER_H_ #define QUICHE_QUIC_CORE_CRYPTO_NULL_ENCRYPTER_H_ #include <cstddef> #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/quic_encrypter.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT NullEncrypter : public QuicEncrypter { public: explicit NullEncrypter(Perspective perspective); NullEncrypter(const NullEncrypter&) = delete; NullEncrypter& operator=(const NullEncrypter&) = delete; ~NullEncrypter() override {} bool SetKey(absl::string_view key) override; bool SetNoncePrefix(absl::string_view nonce_prefix) override; bool SetIV(absl::string_view iv) override; bool SetHeaderProtectionKey(absl::string_view key) override; bool EncryptPacket(uint64_t packet_number, absl::string_view associated_data, absl::string_view plaintext, char* output, size_t* output_length, size_t max_output_length) override; std::string GenerateHeaderProtectionMask(absl::string_view sample) override; size_t GetKeySize() const override; size_t GetNoncePrefixSize() const override; size_t GetIVSize() const override; size_t GetMaxPlaintextSize(size_t ciphertext_size) const override; size_t GetCiphertextSize(size_t plaintext_size) const override; QuicPacketCount GetConfidentialityLimit() const override; absl::string_view GetKey() const override; absl::string_view GetNoncePrefix() const override; private: size_t GetHashLength() const; Perspective perspective_; }; } #endif #include "quiche/quic/core/crypto/null_encrypter.h" #include <algorithm> #include <limits> #include <string> #include "absl/numeric/int128.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/core/quic_utils.h" namespace quic { const size_t kHashSizeShort = 12; NullEncrypter::NullEncrypter(Perspective perspective) : perspective_(perspective) {} bool NullEncrypter::SetKey(absl::string_view key) { return key.empty(); } bool NullEncrypter::SetNoncePrefix(absl::string_view nonce_prefix) { return nonce_prefix.empty(); } bool NullEncrypter::SetIV(absl::string_view iv) { return iv.empty(); } bool NullEncrypter::SetHeaderProtectionKey(absl::string_view key) { return key.empty(); } bool NullEncrypter::EncryptPacket(uint64_t , absl::string_view associated_data, absl::string_view plaintext, char* output, size_t* output_length, size_t max_output_length) { const size_t len = plaintext.size() + GetHashLength(); if (max_output_length < len) { return false; } absl::uint128 hash; if (perspective_ == Perspective::IS_SERVER) { hash = QuicUtils::FNV1a_128_Hash_Three(associated_data, plaintext, "Server"); } else { hash = QuicUtils::FNV1a_128_Hash_Three(associated_data, plaintext, "Client"); } memmove(output + GetHashLength(), plaintext.data(), plaintext.length()); QuicUtils::SerializeUint128Short(hash, reinterpret_cast<unsigned char*>(output)); *output_length = len; return true; } std::string NullEncrypter::GenerateHeaderProtectionMask( absl::string_view ) { return std::string(5, 0); } size_t NullEncrypter::GetKeySize() const { return 0; } size_t NullEncrypter::GetNoncePrefixSize() const { return 0; } size_t NullEncrypter::GetIVSize() const { return 0; } size_t NullEncrypter::GetMaxPlaintextSize(size_t ciphertext_size) const { return ciphertext_size - std::min(ciphertext_size, GetHashLength()); } size_t NullEncrypter::GetCiphertextSize(size_t plaintext_size) const { return plaintext_size + GetHashLength(); } QuicPacketCount NullEncrypter::GetConfidentialityLimit() const { return std::numeric_limits<QuicPacketCount>::max(); } absl::string_view NullEncrypter::GetKey() const { return absl::string_view(); } absl::string_view NullEncrypter::GetNoncePrefix() const { return absl::string_view(); } size_t NullEncrypter::GetHashLength() const { return kHashSizeShort; } }
#include "quiche/quic/core/crypto/null_encrypter.h" #include "absl/base/macros.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace quic { namespace test { class NullEncrypterTest : public QuicTestWithParam<bool> {}; TEST_F(NullEncrypterTest, EncryptClient) { unsigned char expected[] = { 0x97, 0xdc, 0x27, 0x2f, 0x18, 0xa8, 0x56, 0x73, 0xdf, 0x8d, 0x1d, 0xd0, 'g', 'o', 'o', 'd', 'b', 'y', 'e', '!', }; char encrypted[256]; size_t encrypted_len = 0; NullEncrypter encrypter(Perspective::IS_CLIENT); ASSERT_TRUE(encrypter.EncryptPacket(0, "hello world!", "goodbye!", encrypted, &encrypted_len, 256)); quiche::test::CompareCharArraysWithHexError( "encrypted data", encrypted, encrypted_len, reinterpret_cast<const char*>(expected), ABSL_ARRAYSIZE(expected)); } TEST_F(NullEncrypterTest, EncryptServer) { unsigned char expected[] = { 0x63, 0x5e, 0x08, 0x03, 0x32, 0x80, 0x8f, 0x73, 0xdf, 0x8d, 0x1d, 0x1a, 'g', 'o', 'o', 'd', 'b', 'y', 'e', '!', }; char encrypted[256]; size_t encrypted_len = 0; NullEncrypter encrypter(Perspective::IS_SERVER); ASSERT_TRUE(encrypter.EncryptPacket(0, "hello world!", "goodbye!", encrypted, &encrypted_len, 256)); quiche::test::CompareCharArraysWithHexError( "encrypted data", encrypted, encrypted_len, reinterpret_cast<const char*>(expected), ABSL_ARRAYSIZE(expected)); } TEST_F(NullEncrypterTest, GetMaxPlaintextSize) { NullEncrypter encrypter(Perspective::IS_CLIENT); EXPECT_EQ(1000u, encrypter.GetMaxPlaintextSize(1012)); EXPECT_EQ(100u, encrypter.GetMaxPlaintextSize(112)); EXPECT_EQ(10u, encrypter.GetMaxPlaintextSize(22)); EXPECT_EQ(0u, encrypter.GetMaxPlaintextSize(11)); } TEST_F(NullEncrypterTest, GetCiphertextSize) { NullEncrypter encrypter(Perspective::IS_CLIENT); EXPECT_EQ(1012u, encrypter.GetCiphertextSize(1000)); EXPECT_EQ(112u, encrypter.GetCiphertextSize(100)); EXPECT_EQ(22u, encrypter.GetCiphertextSize(10)); } } }
337
cpp
google/quiche
quic_client_session_cache
quiche/quic/core/crypto/quic_client_session_cache.cc
quiche/quic/core/crypto/quic_client_session_cache_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_QUIC_CLIENT_SESSION_CACHE_H_ #define QUICHE_QUIC_CORE_CRYPTO_QUIC_CLIENT_SESSION_CACHE_H_ #include <memory> #include "quiche/quic/core/crypto/quic_crypto_client_config.h" #include "quiche/quic/core/quic_lru_cache.h" #include "quiche/quic/core/quic_server_id.h" namespace quic { namespace test { class QuicClientSessionCachePeer; } class QUICHE_EXPORT QuicClientSessionCache : public SessionCache { public: QuicClientSessionCache(); explicit QuicClientSessionCache(size_t max_entries); ~QuicClientSessionCache() override; void Insert(const QuicServerId& server_id, bssl::UniquePtr<SSL_SESSION> session, const TransportParameters& params, const ApplicationState* application_state) override; std::unique_ptr<QuicResumptionState> Lookup(const QuicServerId& server_id, QuicWallTime now, const SSL_CTX* ctx) override; void ClearEarlyData(const QuicServerId& server_id) override; void OnNewTokenReceived(const QuicServerId& server_id, absl::string_view token) override; void RemoveExpiredEntries(QuicWallTime now) override; void Clear() override; size_t size() const { return cache_.Size(); } private: friend class test::QuicClientSessionCachePeer; struct QUICHE_EXPORT Entry { Entry(); Entry(Entry&&); ~Entry(); void PushSession(bssl::UniquePtr<SSL_SESSION> session); bssl::UniquePtr<SSL_SESSION> PopSession(); SSL_SESSION* PeekSession(); bssl::UniquePtr<SSL_SESSION> sessions[2]; std::unique_ptr<TransportParameters> params; std::unique_ptr<ApplicationState> application_state; std::string token; }; void CreateAndInsertEntry(const QuicServerId& server_id, bssl::UniquePtr<SSL_SESSION> session, const TransportParameters& params, const ApplicationState* application_state); QuicLRUCache<QuicServerId, Entry, QuicServerIdHash> cache_; }; } #endif #include "quiche/quic/core/crypto/quic_client_session_cache.h" #include <memory> #include <string> #include <utility> #include "quiche/quic/core/quic_clock.h" namespace quic { namespace { const size_t kDefaultMaxEntries = 1024; bool IsValid(SSL_SESSION* session, uint64_t now) { if (!session) return false; return !(now + 1 < SSL_SESSION_get_time(session) || now >= SSL_SESSION_get_time(session) + SSL_SESSION_get_timeout(session)); } bool DoApplicationStatesMatch(const ApplicationState* state, ApplicationState* other) { if ((state && !other) || (!state && other)) return false; if ((!state && !other) || *state == *other) return true; return false; } } QuicClientSessionCache::QuicClientSessionCache() : QuicClientSessionCache(kDefaultMaxEntries) {} QuicClientSessionCache::QuicClientSessionCache(size_t max_entries) : cache_(max_entries) {} QuicClientSessionCache::~QuicClientSessionCache() { Clear(); } void QuicClientSessionCache::Insert(const QuicServerId& server_id, bssl::UniquePtr<SSL_SESSION> session, const TransportParameters& params, const ApplicationState* application_state) { QUICHE_DCHECK(session) << "TLS session is not inserted into client cache."; auto iter = cache_.Lookup(server_id); if (iter == cache_.end()) { CreateAndInsertEntry(server_id, std::move(session), params, application_state); return; } QUICHE_DCHECK(iter->second->params); if (params == *iter->second->params && DoApplicationStatesMatch(application_state, iter->second->application_state.get())) { iter->second->PushSession(std::move(session)); return; } cache_.Erase(iter); CreateAndInsertEntry(server_id, std::move(session), params, application_state); } std::unique_ptr<QuicResumptionState> QuicClientSessionCache::Lookup( const QuicServerId& server_id, QuicWallTime now, const SSL_CTX* ) { auto iter = cache_.Lookup(server_id); if (iter == cache_.end()) return nullptr; if (!IsValid(iter->second->PeekSession(), now.ToUNIXSeconds())) { QUIC_DLOG(INFO) << "TLS Session expired for host:" << server_id.host(); cache_.Erase(iter); return nullptr; } auto state = std::make_unique<QuicResumptionState>(); state->tls_session = iter->second->PopSession(); if (iter->second->params != nullptr) { state->transport_params = std::make_unique<TransportParameters>(*iter->second->params); } if (iter->second->application_state != nullptr) { state->application_state = std::make_unique<ApplicationState>(*iter->second->application_state); } if (!iter->second->token.empty()) { state->token = iter->second->token; iter->second->token.clear(); } return state; } void QuicClientSessionCache::ClearEarlyData(const QuicServerId& server_id) { auto iter = cache_.Lookup(server_id); if (iter == cache_.end()) return; for (auto& session : iter->second->sessions) { if (session) { QUIC_DLOG(INFO) << "Clear early data for for host: " << server_id.host(); session.reset(SSL_SESSION_copy_without_early_data(session.get())); } } } void QuicClientSessionCache::OnNewTokenReceived(const QuicServerId& server_id, absl::string_view token) { if (token.empty()) { return; } auto iter = cache_.Lookup(server_id); if (iter == cache_.end()) { return; } iter->second->token = std::string(token); } void QuicClientSessionCache::RemoveExpiredEntries(QuicWallTime now) { auto iter = cache_.begin(); while (iter != cache_.end()) { if (!IsValid(iter->second->PeekSession(), now.ToUNIXSeconds())) { iter = cache_.Erase(iter); } else { ++iter; } } } void QuicClientSessionCache::Clear() { cache_.Clear(); } void QuicClientSessionCache::CreateAndInsertEntry( const QuicServerId& server_id, bssl::UniquePtr<SSL_SESSION> session, const TransportParameters& params, const ApplicationState* application_state) { auto entry = std::make_unique<Entry>(); entry->PushSession(std::move(session)); entry->params = std::make_unique<TransportParameters>(params); if (application_state) { entry->application_state = std::make_unique<ApplicationState>(*application_state); } cache_.Insert(server_id, std::move(entry)); } QuicClientSessionCache::Entry::Entry() = default; QuicClientSessionCache::Entry::Entry(Entry&&) = default; QuicClientSessionCache::Entry::~Entry() = default; void QuicClientSessionCache::Entry::PushSession( bssl::UniquePtr<SSL_SESSION> session) { if (sessions[0] != nullptr) { sessions[1] = std::move(sessions[0]); } sessions[0] = std::move(session); } bssl::UniquePtr<SSL_SESSION> QuicClientSessionCache::Entry::PopSession() { if (sessions[0] == nullptr) return nullptr; bssl::UniquePtr<SSL_SESSION> session = std::move(sessions[0]); sessions[0] = std::move(sessions[1]); sessions[1] = nullptr; return session; } SSL_SESSION* QuicClientSessionCache::Entry::PeekSession() { return sessions[0].get(); } }
#include "quiche/quic/core/crypto/quic_client_session_cache.h" #include <memory> #include <string> #include <utility> #include <vector> #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_clock.h" #include "quiche/common/quiche_text_utils.h" namespace quic { namespace test { namespace { const QuicTime::Delta kTimeout = QuicTime::Delta::FromSeconds(1000); const QuicVersionLabel kFakeVersionLabel = 0x01234567; const QuicVersionLabel kFakeVersionLabel2 = 0x89ABCDEF; const uint64_t kFakeIdleTimeoutMilliseconds = 12012; const uint8_t kFakeStatelessResetTokenData[16] = { 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F}; const uint64_t kFakeMaxPacketSize = 9001; const uint64_t kFakeInitialMaxData = 101; const bool kFakeDisableMigration = true; const auto kCustomParameter1 = static_cast<TransportParameters::TransportParameterId>(0xffcd); const char* kCustomParameter1Value = "foo"; const auto kCustomParameter2 = static_cast<TransportParameters::TransportParameterId>(0xff34); const char* kCustomParameter2Value = "bar"; std::vector<uint8_t> CreateFakeStatelessResetToken() { return std::vector<uint8_t>( kFakeStatelessResetTokenData, kFakeStatelessResetTokenData + sizeof(kFakeStatelessResetTokenData)); } TransportParameters::LegacyVersionInformation CreateFakeLegacyVersionInformation() { TransportParameters::LegacyVersionInformation legacy_version_information; legacy_version_information.version = kFakeVersionLabel; legacy_version_information.supported_versions.push_back(kFakeVersionLabel); legacy_version_information.supported_versions.push_back(kFakeVersionLabel2); return legacy_version_information; } TransportParameters::VersionInformation CreateFakeVersionInformation() { TransportParameters::VersionInformation version_information; version_information.chosen_version = kFakeVersionLabel; version_information.other_versions.push_back(kFakeVersionLabel); return version_information; } std::unique_ptr<TransportParameters> MakeFakeTransportParams() { auto params = std::make_unique<TransportParameters>(); params->perspective = Perspective::IS_CLIENT; params->legacy_version_information = CreateFakeLegacyVersionInformation(); params->version_information = CreateFakeVersionInformation(); params->max_idle_timeout_ms.set_value(kFakeIdleTimeoutMilliseconds); params->stateless_reset_token = CreateFakeStatelessResetToken(); params->max_udp_payload_size.set_value(kFakeMaxPacketSize); params->initial_max_data.set_value(kFakeInitialMaxData); params->disable_active_migration = kFakeDisableMigration; params->custom_parameters[kCustomParameter1] = kCustomParameter1Value; params->custom_parameters[kCustomParameter2] = kCustomParameter2Value; return params; } static const char kCachedSession[] = "30820ad7020101020203040402130104206594ce84e61a866b56163c4ba09079aebf1d4f" "6cbcbd38dc9d7066a38a76c9cf0420ec9062063582a4cc0a44f9ff93256a195153ba6032" "0cf3c9189990932d838adaa10602046196f7b9a205020302a300a382039f3082039b3082" "0183a00302010202021001300d06092a864886f70d010105050030623111300f06035504" "030c08426f677573204941310b300906035504080c024d41310b30090603550406130255" "533121301f06092a864886f70d0109011612626f67757340626f6775732d69612e636f6d" "3110300e060355040a0c07426f6775734941301e170d3231303132383136323030315a17" "0d3331303132363136323030315a3069311d301b06035504030c14746573745f6563632e" "6578616d706c652e636f6d310b300906035504080c024d41310b30090603550406130255" "53311e301c06092a864886f70d010901160f626f67757340626f6775732e636f6d310e30" "0c060355040a0c05426f6775733059301306072a8648ce3d020106082a8648ce3d030107" "034200041ba5e2b6f24e64990b9f24ae6d23473d8c77fbcfb7f554f36559529a69a57170" "a10a81b7fe4a36ebf37b0a8c5e467a8443d8b8c002892aa5c1194bd843f42c9aa31f301d" "301b0603551d11041430128210746573742e6578616d706c652e636f6d300d06092a8648" "86f70d0101050500038202010019921d54ac06948763d609215f64f5d6540e3da886c6c9" "61bc737a437719b4621416ef1229f39282d7d3234e1a5d57535473066233bd246eec8e96" "1e0633cf4fe014c800e62599981820ec33d92e74ded0fa2953db1d81e19cb6890b6305b6" "3ede8d3e9fcf3c09f3f57283acf08aa57be4ee9a68d00bb3e2ded5920c619b5d83e5194a" "adb77ae5d61ed3e0a5670f0ae61cc3197329f0e71e3364dcab0405e9e4a6646adef8f022" "6415ec16c8046307b1769029fe780bd576114dde2fa9b4a32aa70bc436549a24ee4907a9" "045f6457ce8dfd8d62cc65315afe798ae1a948eefd70b035d415e73569c48fb20085de1a" "87de039e6b0b9a5fcb4069df27f3a7a1409e72d1ac739c72f29ef786134207e61c79855f" "c22e3ee5f6ad59a7b1ff0f18d79776f1c95efaebbebe381664132a58a1e7ff689945b7e0" "88634b0872feeefbf6be020884b994c6a7ff435f2b3f609077ff97cb509cfa17ff479b34" "e633e4b5bc46b20c5f27c80a2e2943f795a928acd5a3fc43c3af8425ad600c048b41d87e" "6361bc72fc4e5e44680a3d325674ba6ffa760d2fc7d9e4847a8e0dd9d35a543324e18b94" "2d42af6391ed1dd54a39e3f4a4c6b32486eb4ba72815dbd89c56fc053743a0b0483ce676" "15defce6800c629b99d0cbc56da162487f475b7c246099eaf1e6d10a022b2f49c6af1da3" "e8ed66096f267c4a76976b9572db7456ef90278330a4020400aa81b60481b3494e534543" "55524500f3439e548c21d2ad6e5634cc1cc0045730819702010102020304040213010400" "0420ec9062063582a4cc0a44f9ff93256a195153ba60320cf3c9189990932d838adaa106" "02046196f7b9a205020302a300a4020400b20302011db5060404130800cdb807020500ff" "ffffffb9050203093a80ba0404026833bb030101ffbc23042100d27d985bfce04833f02d" "38366b219f4def42bc4ba1b01844d1778db11731487dbd020400be020400b20302011db3" "8205da308205d6308203bea00302010202021000300d06092a864886f70d010105050030" "62310b3009060355040613025553310b300906035504080c024d413110300e060355040a" "0c07426f67757343413111300f06035504030c08426f6775732043413121301f06092a86" "4886f70d0109011612626f67757340626f6775732d63612e636f6d3020170d3231303132" "383136313935385a180f32303730303531313136313935385a30623111300f0603550403" "0c08426f677573204941310b300906035504080c024d41310b3009060355040613025553" "3121301f06092a864886f70d0109011612626f67757340626f6775732d69612e636f6d31" "10300e060355040a0c07426f677573494130820222300d06092a864886f70d0101010500" "0382020f003082020a028202010096c03a0ffc61bcedcd5ec9bf6f848b8a066b43f08377" "3af518a6a0044f22e666e24d2ae741954e344302c4be04612185bd53bcd848eb322bf900" "724eb0848047d647033ffbddb00f01d1de7c1cdb684f83c9bf5fd18ff60afad5a53b0d7d" "2c2a50abc38df019cd7f50194d05bc4597a1ef8570ea04069a2c36d74496af126573ca18" "8e470009b56250fadf2a04e837ee3837b36b1f08b7a0cfe2533d05f26484ce4e30203d01" "517fffd3da63d0341079ddce16e9ab4dbf9d4049e5cc52326031e645dd682fe6220d9e0e" "95451f5a82f3e1720dc13e8499466426a0bdbea9f6a76b3c9228dd3c79ab4dcc4c145ef0" "e78d1ee8bfd4650692d7e28a54bed809d8f7b37fe24c586be59cc46638531cb291c8c156" "8f08d67e768e51563e95a639c1f138b275ffad6a6a2a042ba9e26ad63c2ce63b600013f0" "a6f0703ee51c4f457f7bab0391c2fc4c5bb3213742c9cf9941bff68cc2e1cc96139d35ed" "1885244ddde0bf658416c486701841b81f7b17503d08c59a4db08a2a80755e007aa3b6c7" "eadcaa9e07c8325f3689f100de23970b12c9d9f6d0a8fb35ba0fd75c64410318db4a13ac" "3972ad16cdf6408af37013c7bcd7c42f20d6d04c3e39436c7531e8dafa219dd04b784ef0" "3c70ee5a4782b33cafa925aa3deca62a14aed704f179b932efabc2b0c5c15a8a99bfc9e6" "189dce7da50ea303594b6af9c933dd54b6e9d17c472d0203010001a38193308190300f06" "03551d130101ff040530030101ff301d0603551d0e041604141a98e80029a80992b7e5e0" "068ab9b3486cd839d6301f0603551d23041830168014780beeefe2fa419c48a438bdb30b" "e37ef0b7a94e300b0603551d0f0404030202a430130603551d25040c300a06082b060105" "05070301301b0603551d11041430128207426f67757343418207426f6775734941300d06" "092a864886f70d010105050003820201009e822ed8064b1aabaddf1340010ea147f68c06" "5a5a599ea305349f1b0e545a00817d6e55c7bf85560fab429ca72186c4d520b52f5cc121" "abd068b06f3111494431d2522efa54642f907059e7db80b73bb5ecf621377195b8700bba" "df798cece8c67a9571548d0e6592e81ae5d934877cb170aef18d3b97f635600fe0890d98" "f88b33fe3d1fd34c1c915beae4e5c0b133f476c40b21d220f16ce9cdd9e8f97a36a31723" "68875f052c9271648d9cb54687c6fdc3ea96f2908003bc5e5e79de00a21da7b8429f8b08" "af4c4d34641e386d72eabf5f01f106363f2ffd18969bf0bb9a4d17627c6427ff772c4308" "83c276feef5fc6dba9582c22fdbe9df7e8dfca375695f028ed588df54f3c86462dbf4c07" "91d80ca738988a1419c86bb4dd8d738b746921f01f39422e5ffd488b6f00195b996e6392" "3a820a32cd78b5989f339c0fcf4f269103964a30a16347d0ffdc8df1f3653ddc1515fa09" "22c7aef1af1fbcb23e93ae7622ab1ee11fcfa98319bad4c37c091cad46bd0337b3cc78b5" "5b9f1ea7994acc1f89c49a0b4cb540d2137e266fd43e56a9b5b778217b6f77df530e1eaf" "b3417262b5ddb86d3c6c5ac51e3f326c650dcc2434473973b7182c66220d1f3871bde7ee" "47d3f359d3d4c5bdd61baa684c03db4c75f9d6690c9e6e3abe6eaf5fa2c33c4daf26b373" "d85a1e8a7d671ac4a0a97b14e36e81280de4593bbb12da7695b5060404130800cdb60301" "0100b70402020403b807020500ffffffffb9050203093a80ba0404026833bb030101ffbd" "020400be020400"; class QuicClientSessionCacheTest : public QuicTest { public: QuicClientSessionCacheTest() : ssl_ctx_(SSL_CTX_new(TLS_method())) { clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1)); } protected: bssl::UniquePtr<SSL_SESSION> NewSSLSession() { std::string cached_session; EXPECT_TRUE(absl::HexStringToBytes(kCachedSession, &cached_session)); SSL_SESSION* session = SSL_SESSION_from_bytes( reinterpret_cast<const uint8_t*>(cached_session.data()), cached_session.size(), ssl_ctx_.get()); QUICHE_DCHECK(session); return bssl::UniquePtr<SSL_SESSION>(session); } bssl::UniquePtr<SSL_SESSION> MakeTestSession( QuicTime::Delta timeout = kTimeout) { bssl::UniquePtr<SSL_SESSION> session = NewSSLSession(); SSL_SESSION_set_time(session.get(), clock_.WallNow().ToUNIXSeconds()); SSL_SESSION_set_timeout(session.get(), timeout.ToSeconds()); return session; } bssl::UniquePtr<SSL_CTX> ssl_ctx_; MockClock clock_; }; TEST_F(QuicClientSessionCacheTest, SingleSession) { QuicClientSessionCache cache; auto params = MakeFakeTransportParams(); auto session = MakeTestSession(); QuicServerId id1("a.com", 443); auto params2 = MakeFakeTransportParams(); auto session2 = MakeTestSession(); SSL_SESSION* unowned2 = session2.get(); QuicServerId id2("b.com", 443); EXPECT_EQ(nullptr, cache.Lookup(id1, clock_.WallNow(), ssl_ctx_.get())); EXPECT_EQ(nullptr, cache.Lookup(id2, clock_.WallNow(), ssl_ctx_.get())); EXPECT_EQ(0u, cache.size()); cache.Insert(id1, std::move(session), *params, nullptr); EXPECT_EQ(1u, cache.size()); EXPECT_EQ( *params, *(cache.Lookup(id1, clock_.WallNow(), ssl_ctx_.get())->transport_params)); EXPECT_EQ(nullptr, cache.Lookup(id2, clock_.WallNow(), ssl_ctx_.get())); EXPECT_EQ(1u, cache.size()); EXPECT_EQ(nullptr, cache.Lookup(id1, clock_.WallNow(), ssl_ctx_.get())); EXPECT_EQ(0u, cache.size()); auto session3 = MakeTestSession(); SSL_SESSION* unowned3 = session3.get(); QuicServerId id3("c.com", 443); cache.Insert(id3, std::move(session3), *params, nullptr); cache.Insert(id2, std::move(session2), *params2, nullptr); EXPECT_EQ(2u, cache.size()); EXPECT_EQ( unowned2, cache.Lookup(id2, clock_.WallNow(), ssl_ctx_.get())->tls_session.get()); EXPECT_EQ( unowned3, cache.Lookup(id3, clock_.WallNow(), ssl_ctx_.get())->tls_session.get()); EXPECT_EQ(nullptr, cache.Lookup(id1, clock_.WallNow(), ssl_ctx_.get())); EXPECT_EQ(nullptr, cache.Lookup(id2, clock_.WallNow(), ssl_ctx_.get())); EXPECT_EQ(nullptr, cache.Lookup(id3, clock_.WallNow(), ssl_ctx_.get())); EXPECT_EQ(0u, cache.size()); } TEST_F(QuicClientSessionCacheTest, MultipleSessions) { QuicClientSessionCache cache; auto params = MakeFakeTransportParams(); auto session = MakeTestSession(); QuicServerId id1("a.com", 443); auto session2 = MakeTestSession(); SSL_SESSION* unowned2 = session2.get(); auto session3 = MakeTestSession(); SSL_SESSION* unowned3 = session3.get(); cache.Insert(id1, std::move(session), *params, nullptr); cache.Insert(id1, std::move(session2), *params, nullptr); cache.Insert(id1, std::move(session3), *params, nullptr); EXPECT_EQ( unowned3, cache.Lookup(id1, clock_.WallNow(), ssl_ctx_.get())->tls_session.get()); EXPECT_EQ( unowned2, cache.Lookup(id1, clock_.WallNow(), ssl_ctx_.get())->tls_session.get()); EXPECT_EQ(nullptr, cache.Lookup(id1, clock_.WallNow(), ssl_ctx_.get())); } TEST_F(QuicClientSessionCacheTest, DifferentTransportParams) { QuicClientSessionCache cache; auto params = MakeFakeTransportParams(); auto session = MakeTestSession(); QuicServerId id1("a.com", 443); auto session2 = MakeTestSession(); auto session3 = MakeTestSession(); SSL_SESSION* unowned3 = session3.get(); cache.Insert(id1, std::move(session), *params, nullptr); cache.Insert(id1, std::move(session2), *params, nullptr); params->perspective = Perspective::IS_SERVER; cache.Insert(id1, std::move(session3), *params, nullptr); auto resumption_state = cache.Lookup(id1, clock_.WallNow(), ssl_ctx_.get()); EXPECT_EQ(unowned3, resumption_state->tls_session.get()); EXPECT_EQ(*params.get(), *resumption_state->transport_params); EXPECT_EQ(nullptr, cache.Lookup(id1, clock_.WallNow(), ssl_ctx_.get())); } TEST_F(QuicClientSessionCacheTest, DifferentApplicationState) { QuicClientSessionCache cache; auto params = MakeFakeTransportParams(); auto session = MakeTestSession(); QuicServerId id1("a.com", 443); auto session2 = MakeTestSession(); auto session3 = MakeTestSession(); SSL_SESSION* unowned3 = session3.get(); ApplicationState state; state.push_back('a'); cache.Insert(id1, std::move(session), *params, &state); cache.Insert(id1, std::move(session2), *params, &state); cache.Insert(id1, std::move(session3), *params, nullptr); auto resumption_state = cache.Lookup(id1, clock_.WallNow(), ssl_ctx_.get()); EXPECT_EQ(unowned3, resumption_state->tls_session.get()); EXPECT_EQ(nullptr, resumption_state->application_state); EXPECT_EQ(nullptr, cache.Lookup(id1, clock_.WallNow(), ssl_ctx_.get())); } TEST_F(QuicClientSessionCacheTest, BothStatesDifferent) { QuicClientSessionCache cache; auto params = MakeFakeTransportParams(); auto session = MakeTestSession(); QuicServerId id1("a.com", 443); auto session2 = MakeTestSession(); auto session3 = MakeTestSession(); SSL_SESSION* unowned3 = session3.get(); ApplicationState state; state.push_back('a'); cache.Insert(id1, std::move(session), *params, &state); cache.Insert(id1, std::move(session2), *params, &state); params->perspective = Perspective::IS_SERVER; cache.Insert(id1, std::move(session3), *params, nullptr); auto resumption_state = cache.Lookup(id1, clock_.WallNow(), ssl_ctx_.get()); EXPECT_EQ(unowned3, resumption_state->tls_session.get()); EXPECT_EQ(*params.get(), *resumption_state->transport_params); EXPECT_EQ(nullptr, resumption_state->application_state); EXPECT_EQ(nullptr, cache.Lookup(id1, clock_.WallNow(), ssl_ctx_.get())); } TEST_F(QuicClientSessionCacheTest, SizeLimit) { QuicClientSessionCache cache(2); auto params = MakeFakeTransportParams(); auto session = MakeTestSession(); QuicServerId id1("a.com", 443); auto session2 = MakeTestSession(); SSL_SESSION* unowned2 = session2.get(); QuicServerId id2("b.com", 443); auto session3 = MakeTestSession(); SSL_SESSION* unowned3 = session3.get(); QuicServerId id3("c.com", 443); cache.Insert(id1, std::move(session), *params, nullptr); cache.Insert(id2, std::move(session2), *params, nullptr); cache.Insert(id3, std::move(session3), *params, nullptr); EXPECT_EQ(2u, cache.size()); EXPECT_EQ( unowned2, cache.Lookup(id2, clock_.WallNow(), ssl_ctx_.get())->tls_session.get()); EXPECT_EQ( unowned3, cache.Lookup(id3, clock_.WallNow(), ssl_ctx_.get())->tls_session.get()); EXPECT_EQ(nullptr, cache.Lookup(id1, clock_.WallNow(), ssl_ctx_.get())); } TEST_F(QuicClientSessionCacheTest, ClearEarlyData) { QuicClientSessionCache cache; SSL_CTX_set_early_data_enabled(ssl_ctx_.get(), 1); auto params = MakeFakeTransportParams(); auto session = MakeTestSession(); QuicServerId id1("a.com", 443); auto session2 = MakeTestSession(); EXPECT_TRUE(SSL_SESSION_early_data_capable(session.get())); EXPECT_TRUE(SSL_SESSION_early_data_capable(session2.get())); cache.Insert(id1, std::move(session), *params, nullptr); cache.Insert(id1, std::move(session2), *params, nullptr); cache.ClearEarlyData(id1); auto resumption_state = cache.Lookup(id1, clock_.WallNow(), ssl_ctx_.get()); EXPECT_FALSE( SSL_SESSION_early_data_capable(resumption_state->tls_session.get())); resumption_state = cache.Lookup(id1, clock_.WallNow(), ssl_ctx_.get()); EXPECT_FALSE( SSL_SESSION_early_data_capable(resumption_state->tls_session.get())); EXPECT_EQ(nullptr, cache.Lookup(id1, clock_.WallNow(), ssl_ctx_.get())); } TEST_F(QuicClientSessionCacheTest, Expiration) { QuicClientSessionCache cache; auto params = MakeFakeTransportParams(); auto session = MakeTestSession(); QuicServerId id1("a.com", 443); auto session2 = MakeTestSession(3 * kTimeout); SSL_SESSION* unowned2 = session2.get(); QuicServerId id2("b.com", 443); cache.Insert(id1, std::move(session), *params, nullptr); cache.Insert(id2, std::move(session2), *params, nullptr); EXPECT_EQ(2u, cache.size()); clock_.AdvanceTime(kTimeout * 2); EXPECT_EQ(2u, cache.size()); EXPECT_EQ(nullptr, cache.Lookup(id1, clock_.WallNow(), ssl_ctx_.get())); EXPECT_EQ(1u, cache.size()); EXPECT_EQ( unowned2, cache.Lookup(id2, clock_.WallNow(), ssl_ctx_.get())->tls_session.get()); EXPECT_EQ(1u, cache.size()); } TEST_F(QuicClientSessionCacheTest, RemoveExpiredEntriesAndClear) { QuicClientSessionCache cache; auto params = MakeFakeTransportParams(); auto session = MakeTestSession(); quic::QuicServerId id1("a.com", 443); auto session2 = MakeTestSession(3 * kTimeout); quic::QuicServerId id2("b.com", 443); cache.Insert(id1, std::move(session), *params, nullptr); cache.Insert(id2, std::move(session2), *params, nullptr); EXPECT_EQ(2u, cache.size()); clock_.AdvanceTime(kTimeout * 2); EXPECT_EQ(2u, cache.size()); cache.RemoveExpiredEntries(clock_.WallNow()); EXPECT_EQ(nullptr, cache.Lookup(id1, clock_.WallNow(), ssl_ctx_.get())); EXPECT_EQ(1u, cache.size()); cache.Clear(); EXPECT_EQ(0u, cache.size()); } } } }
338
cpp
google/quiche
crypto_framer
quiche/quic/core/crypto/crypto_framer.cc
quiche/quic/core/crypto/crypto_framer_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_CRYPTO_FRAMER_H_ #define QUICHE_QUIC_CORE_CRYPTO_CRYPTO_FRAMER_H_ #include <cstddef> #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/crypto_handshake_message.h" #include "quiche/quic/core/crypto/crypto_message_parser.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class CryptoFramer; class QuicData; class QuicDataWriter; class QUICHE_EXPORT CryptoFramerVisitorInterface { public: virtual ~CryptoFramerVisitorInterface() {} virtual void OnError(CryptoFramer* framer) = 0; virtual void OnHandshakeMessage(const CryptoHandshakeMessage& message) = 0; }; class QUICHE_EXPORT CryptoFramer : public CryptoMessageParser { public: CryptoFramer(); ~CryptoFramer() override; static std::unique_ptr<CryptoHandshakeMessage> ParseMessage( absl::string_view in); void set_visitor(CryptoFramerVisitorInterface* visitor) { visitor_ = visitor; } QuicErrorCode error() const override; const std::string& error_detail() const override; bool ProcessInput(absl::string_view input, EncryptionLevel level) override; bool ProcessInput(absl::string_view input); size_t InputBytesRemaining() const override; bool HasTag(QuicTag tag) const; void ForceHandshake(); static std::unique_ptr<QuicData> ConstructHandshakeMessage( const CryptoHandshakeMessage& message); void set_process_truncated_messages(bool process_truncated_messages) { process_truncated_messages_ = process_truncated_messages; } private: void Clear(); QuicErrorCode Process(absl::string_view input); static bool WritePadTag(QuicDataWriter* writer, size_t pad_length, uint32_t* end_offset); enum CryptoFramerState { STATE_READING_TAG, STATE_READING_NUM_ENTRIES, STATE_READING_TAGS_AND_LENGTHS, STATE_READING_VALUES }; CryptoFramerVisitorInterface* visitor_; QuicErrorCode error_; std::string buffer_; CryptoFramerState state_; CryptoHandshakeMessage message_; std::string error_detail_; uint16_t num_entries_; std::vector<std::pair<QuicTag, size_t>> tags_and_lengths_; size_t values_len_; bool process_truncated_messages_; }; } #endif #include "quiche/quic/core/crypto/crypto_framer.h" #include <memory> #include <string> #include <utility> #include "absl/base/attributes.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/quic_data_reader.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/common/quiche_endian.h" namespace quic { namespace { const size_t kQuicTagSize = sizeof(QuicTag); const size_t kCryptoEndOffsetSize = sizeof(uint32_t); const size_t kNumEntriesSize = sizeof(uint16_t); class OneShotVisitor : public CryptoFramerVisitorInterface { public: OneShotVisitor() : error_(false) {} void OnError(CryptoFramer* ) override { error_ = true; } void OnHandshakeMessage(const CryptoHandshakeMessage& message) override { out_ = std::make_unique<CryptoHandshakeMessage>(message); } bool error() const { return error_; } std::unique_ptr<CryptoHandshakeMessage> release() { return std::move(out_); } private: std::unique_ptr<CryptoHandshakeMessage> out_; bool error_; }; } CryptoFramer::CryptoFramer() : visitor_(nullptr), error_detail_(""), num_entries_(0), values_len_(0), process_truncated_messages_(false) { Clear(); } CryptoFramer::~CryptoFramer() {} std::unique_ptr<CryptoHandshakeMessage> CryptoFramer::ParseMessage( absl::string_view in) { OneShotVisitor visitor; CryptoFramer framer; framer.set_visitor(&visitor); if (!framer.ProcessInput(in) || visitor.error() || framer.InputBytesRemaining()) { return nullptr; } return visitor.release(); } QuicErrorCode CryptoFramer::error() const { return error_; } const std::string& CryptoFramer::error_detail() const { return error_detail_; } bool CryptoFramer::ProcessInput(absl::string_view input, EncryptionLevel ) { return ProcessInput(input); } bool CryptoFramer::ProcessInput(absl::string_view input) { QUICHE_DCHECK_EQ(QUIC_NO_ERROR, error_); if (error_ != QUIC_NO_ERROR) { return false; } error_ = Process(input); if (error_ != QUIC_NO_ERROR) { QUICHE_DCHECK(!error_detail_.empty()); visitor_->OnError(this); return false; } return true; } size_t CryptoFramer::InputBytesRemaining() const { return buffer_.length(); } bool CryptoFramer::HasTag(QuicTag tag) const { if (state_ != STATE_READING_VALUES) { return false; } for (const auto& it : tags_and_lengths_) { if (it.first == tag) { return true; } } return false; } void CryptoFramer::ForceHandshake() { QuicDataReader reader(buffer_.data(), buffer_.length(), quiche::HOST_BYTE_ORDER); for (const std::pair<QuicTag, size_t>& item : tags_and_lengths_) { absl::string_view value; if (reader.BytesRemaining() < item.second) { break; } reader.ReadStringPiece(&value, item.second); message_.SetStringPiece(item.first, value); } visitor_->OnHandshakeMessage(message_); } std::unique_ptr<QuicData> CryptoFramer::ConstructHandshakeMessage( const CryptoHandshakeMessage& message) { size_t num_entries = message.tag_value_map().size(); size_t pad_length = 0; bool need_pad_tag = false; bool need_pad_value = false; size_t len = message.size(); if (len < message.minimum_size()) { need_pad_tag = true; need_pad_value = true; num_entries++; size_t delta = message.minimum_size() - len; const size_t overhead = kQuicTagSize + kCryptoEndOffsetSize; if (delta > overhead) { pad_length = delta - overhead; } len += overhead + pad_length; } if (num_entries > kMaxEntries) { return nullptr; } std::unique_ptr<char[]> buffer(new char[len]); QuicDataWriter writer(len, buffer.get(), quiche::HOST_BYTE_ORDER); if (!writer.WriteTag(message.tag())) { QUICHE_DCHECK(false) << "Failed to write message tag."; return nullptr; } if (!writer.WriteUInt16(static_cast<uint16_t>(num_entries))) { QUICHE_DCHECK(false) << "Failed to write size."; return nullptr; } if (!writer.WriteUInt16(0)) { QUICHE_DCHECK(false) << "Failed to write padding."; return nullptr; } uint32_t end_offset = 0; for (auto it = message.tag_value_map().begin(); it != message.tag_value_map().end(); ++it) { if (it->first == kPAD && need_pad_tag) { QUICHE_DCHECK(false) << "Message needed padding but already contained a PAD tag"; return nullptr; } if (it->first > kPAD && need_pad_tag) { need_pad_tag = false; if (!WritePadTag(&writer, pad_length, &end_offset)) { return nullptr; } } if (!writer.WriteTag(it->first)) { QUICHE_DCHECK(false) << "Failed to write tag."; return nullptr; } end_offset += it->second.length(); if (!writer.WriteUInt32(end_offset)) { QUICHE_DCHECK(false) << "Failed to write end offset."; return nullptr; } } if (need_pad_tag) { if (!WritePadTag(&writer, pad_length, &end_offset)) { return nullptr; } } for (auto it = message.tag_value_map().begin(); it != message.tag_value_map().end(); ++it) { if (it->first > kPAD && need_pad_value) { need_pad_value = false; if (!writer.WriteRepeatedByte('-', pad_length)) { QUICHE_DCHECK(false) << "Failed to write padding."; return nullptr; } } if (!writer.WriteBytes(it->second.data(), it->second.length())) { QUICHE_DCHECK(false) << "Failed to write value."; return nullptr; } } if (need_pad_value) { if (!writer.WriteRepeatedByte('-', pad_length)) { QUICHE_DCHECK(false) << "Failed to write padding."; return nullptr; } } return std::make_unique<QuicData>(buffer.release(), len, true); } void CryptoFramer::Clear() { message_.Clear(); tags_and_lengths_.clear(); error_ = QUIC_NO_ERROR; error_detail_ = ""; state_ = STATE_READING_TAG; } QuicErrorCode CryptoFramer::Process(absl::string_view input) { buffer_.append(input.data(), input.length()); QuicDataReader reader(buffer_.data(), buffer_.length(), quiche::HOST_BYTE_ORDER); switch (state_) { case STATE_READING_TAG: if (reader.BytesRemaining() < kQuicTagSize) { break; } QuicTag message_tag; reader.ReadTag(&message_tag); message_.set_tag(message_tag); state_ = STATE_READING_NUM_ENTRIES; ABSL_FALLTHROUGH_INTENDED; case STATE_READING_NUM_ENTRIES: if (reader.BytesRemaining() < kNumEntriesSize + sizeof(uint16_t)) { break; } reader.ReadUInt16(&num_entries_); if (num_entries_ > kMaxEntries) { error_detail_ = absl::StrCat(num_entries_, " entries"); return QUIC_CRYPTO_TOO_MANY_ENTRIES; } uint16_t padding; reader.ReadUInt16(&padding); tags_and_lengths_.reserve(num_entries_); state_ = STATE_READING_TAGS_AND_LENGTHS; values_len_ = 0; ABSL_FALLTHROUGH_INTENDED; case STATE_READING_TAGS_AND_LENGTHS: { if (reader.BytesRemaining() < num_entries_ * (kQuicTagSize + kCryptoEndOffsetSize)) { break; } uint32_t last_end_offset = 0; for (unsigned i = 0; i < num_entries_; ++i) { QuicTag tag; reader.ReadTag(&tag); if (i > 0 && tag <= tags_and_lengths_[i - 1].first) { if (tag == tags_and_lengths_[i - 1].first) { error_detail_ = absl::StrCat("Duplicate tag:", tag); return QUIC_CRYPTO_DUPLICATE_TAG; } error_detail_ = absl::StrCat("Tag ", tag, " out of order"); return QUIC_CRYPTO_TAGS_OUT_OF_ORDER; } uint32_t end_offset; reader.ReadUInt32(&end_offset); if (end_offset < last_end_offset) { error_detail_ = absl::StrCat("End offset: ", end_offset, " vs ", last_end_offset); return QUIC_CRYPTO_TAGS_OUT_OF_ORDER; } tags_and_lengths_.push_back(std::make_pair( tag, static_cast<size_t>(end_offset - last_end_offset))); last_end_offset = end_offset; } values_len_ = last_end_offset; state_ = STATE_READING_VALUES; ABSL_FALLTHROUGH_INTENDED; } case STATE_READING_VALUES: if (reader.BytesRemaining() < values_len_) { if (!process_truncated_messages_) { break; } QUIC_LOG(ERROR) << "Trunacted message. Missing " << values_len_ - reader.BytesRemaining() << " bytes."; } for (const std::pair<QuicTag, size_t>& item : tags_and_lengths_) { absl::string_view value; if (!reader.ReadStringPiece(&value, item.second)) { QUICHE_DCHECK(process_truncated_messages_); message_.SetStringPiece(item.first, ""); continue; } message_.SetStringPiece(item.first, value); } visitor_->OnHandshakeMessage(message_); Clear(); state_ = STATE_READING_TAG; break; } buffer_ = std::string(reader.PeekRemainingPayload()); return QUIC_NO_ERROR; } bool CryptoFramer::WritePadTag(QuicDataWriter* writer, size_t pad_length, uint32_t* end_offset) { if (!writer->WriteTag(kPAD)) { QUICHE_DCHECK(false) << "Failed to write tag."; return false; } *end_offset += pad_length; if (!writer->WriteUInt32(*end_offset)) { QUICHE_DCHECK(false) << "Failed to write end offset."; return false; } return true; } }
#include "quiche/quic/core/crypto/crypto_framer.h" #include <map> #include <memory> #include <vector> #include "absl/base/macros.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/crypto_handshake.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/crypto_test_utils.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace quic { namespace test { namespace { char* AsChars(unsigned char* data) { return reinterpret_cast<char*>(data); } class TestCryptoVisitor : public CryptoFramerVisitorInterface { public: TestCryptoVisitor() : error_count_(0) {} void OnError(CryptoFramer* framer) override { QUIC_DLOG(ERROR) << "CryptoFramer Error: " << framer->error(); ++error_count_; } void OnHandshakeMessage(const CryptoHandshakeMessage& message) override { messages_.push_back(message); } int error_count_; std::vector<CryptoHandshakeMessage> messages_; }; TEST(CryptoFramerTest, ConstructHandshakeMessage) { CryptoHandshakeMessage message; message.set_tag(0xFFAA7733); message.SetStringPiece(0x12345678, "abcdef"); message.SetStringPiece(0x12345679, "ghijk"); message.SetStringPiece(0x1234567A, "lmnopqr"); unsigned char packet[] = { 0x33, 0x77, 0xAA, 0xFF, 0x03, 0x00, 0x00, 0x00, 0x78, 0x56, 0x34, 0x12, 0x06, 0x00, 0x00, 0x00, 0x79, 0x56, 0x34, 0x12, 0x0b, 0x00, 0x00, 0x00, 0x7A, 0x56, 0x34, 0x12, 0x12, 0x00, 0x00, 0x00, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r'}; CryptoFramer framer; std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet), ABSL_ARRAYSIZE(packet)); } TEST(CryptoFramerTest, ConstructHandshakeMessageWithTwoKeys) { CryptoHandshakeMessage message; message.set_tag(0xFFAA7733); message.SetStringPiece(0x12345678, "abcdef"); message.SetStringPiece(0x12345679, "ghijk"); unsigned char packet[] = { 0x33, 0x77, 0xAA, 0xFF, 0x02, 0x00, 0x00, 0x00, 0x78, 0x56, 0x34, 0x12, 0x06, 0x00, 0x00, 0x00, 0x79, 0x56, 0x34, 0x12, 0x0b, 0x00, 0x00, 0x00, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'}; CryptoFramer framer; std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet), ABSL_ARRAYSIZE(packet)); } TEST(CryptoFramerTest, ConstructHandshakeMessageZeroLength) { CryptoHandshakeMessage message; message.set_tag(0xFFAA7733); message.SetStringPiece(0x12345678, ""); unsigned char packet[] = { 0x33, 0x77, 0xAA, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x78, 0x56, 0x34, 0x12, 0x00, 0x00, 0x00, 0x00}; CryptoFramer framer; std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet), ABSL_ARRAYSIZE(packet)); } TEST(CryptoFramerTest, ConstructHandshakeMessageTooManyEntries) { CryptoHandshakeMessage message; message.set_tag(0xFFAA7733); for (uint32_t key = 1; key <= kMaxEntries + 1; ++key) { message.SetStringPiece(key, "abcdef"); } CryptoFramer framer; std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message); EXPECT_TRUE(data == nullptr); } TEST(CryptoFramerTest, ConstructHandshakeMessageMinimumSize) { CryptoHandshakeMessage message; message.set_tag(0xFFAA7733); message.SetStringPiece(0x01020304, "test"); message.set_minimum_size(64); unsigned char packet[] = { 0x33, 0x77, 0xAA, 0xFF, 0x02, 0x00, 0x00, 0x00, 'P', 'A', 'D', 0, 0x24, 0x00, 0x00, 0x00, 0x04, 0x03, 0x02, 0x01, 0x28, 0x00, 0x00, 0x00, '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', 't', 'e', 's', 't'}; CryptoFramer framer; std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet), ABSL_ARRAYSIZE(packet)); } TEST(CryptoFramerTest, ConstructHandshakeMessageMinimumSizePadLast) { CryptoHandshakeMessage message; message.set_tag(0xFFAA7733); message.SetStringPiece(1, ""); message.set_minimum_size(64); unsigned char packet[] = { 0x33, 0x77, 0xAA, 0xFF, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 'P', 'A', 'D', 0, 0x28, 0x00, 0x00, 0x00, '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-'}; CryptoFramer framer; std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet), ABSL_ARRAYSIZE(packet)); } TEST(CryptoFramerTest, ProcessInput) { test::TestCryptoVisitor visitor; CryptoFramer framer; framer.set_visitor(&visitor); unsigned char input[] = { 0x33, 0x77, 0xAA, 0xFF, 0x02, 0x00, 0x00, 0x00, 0x78, 0x56, 0x34, 0x12, 0x06, 0x00, 0x00, 0x00, 0x79, 0x56, 0x34, 0x12, 0x0b, 0x00, 0x00, 0x00, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'}; EXPECT_TRUE(framer.ProcessInput( absl::string_view(AsChars(input), ABSL_ARRAYSIZE(input)))); EXPECT_EQ(0u, framer.InputBytesRemaining()); EXPECT_EQ(0, visitor.error_count_); ASSERT_EQ(1u, visitor.messages_.size()); const CryptoHandshakeMessage& message = visitor.messages_[0]; EXPECT_EQ(0xFFAA7733, message.tag()); EXPECT_EQ(2u, message.tag_value_map().size()); EXPECT_EQ("abcdef", crypto_test_utils::GetValueForTag(message, 0x12345678)); EXPECT_EQ("ghijk", crypto_test_utils::GetValueForTag(message, 0x12345679)); } TEST(CryptoFramerTest, ProcessInputWithThreeKeys) { test::TestCryptoVisitor visitor; CryptoFramer framer; framer.set_visitor(&visitor); unsigned char input[] = { 0x33, 0x77, 0xAA, 0xFF, 0x03, 0x00, 0x00, 0x00, 0x78, 0x56, 0x34, 0x12, 0x06, 0x00, 0x00, 0x00, 0x79, 0x56, 0x34, 0x12, 0x0b, 0x00, 0x00, 0x00, 0x7A, 0x56, 0x34, 0x12, 0x12, 0x00, 0x00, 0x00, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r'}; EXPECT_TRUE(framer.ProcessInput( absl::string_view(AsChars(input), ABSL_ARRAYSIZE(input)))); EXPECT_EQ(0u, framer.InputBytesRemaining()); EXPECT_EQ(0, visitor.error_count_); ASSERT_EQ(1u, visitor.messages_.size()); const CryptoHandshakeMessage& message = visitor.messages_[0]; EXPECT_EQ(0xFFAA7733, message.tag()); EXPECT_EQ(3u, message.tag_value_map().size()); EXPECT_EQ("abcdef", crypto_test_utils::GetValueForTag(message, 0x12345678)); EXPECT_EQ("ghijk", crypto_test_utils::GetValueForTag(message, 0x12345679)); EXPECT_EQ("lmnopqr", crypto_test_utils::GetValueForTag(message, 0x1234567A)); } TEST(CryptoFramerTest, ProcessInputIncrementally) { test::TestCryptoVisitor visitor; CryptoFramer framer; framer.set_visitor(&visitor); unsigned char input[] = { 0x33, 0x77, 0xAA, 0xFF, 0x02, 0x00, 0x00, 0x00, 0x78, 0x56, 0x34, 0x12, 0x06, 0x00, 0x00, 0x00, 0x79, 0x56, 0x34, 0x12, 0x0b, 0x00, 0x00, 0x00, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'}; for (size_t i = 0; i < ABSL_ARRAYSIZE(input); i++) { EXPECT_TRUE(framer.ProcessInput(absl::string_view(AsChars(input) + i, 1))); } EXPECT_EQ(0u, framer.InputBytesRemaining()); ASSERT_EQ(1u, visitor.messages_.size()); const CryptoHandshakeMessage& message = visitor.messages_[0]; EXPECT_EQ(0xFFAA7733, message.tag()); EXPECT_EQ(2u, message.tag_value_map().size()); EXPECT_EQ("abcdef", crypto_test_utils::GetValueForTag(message, 0x12345678)); EXPECT_EQ("ghijk", crypto_test_utils::GetValueForTag(message, 0x12345679)); } TEST(CryptoFramerTest, ProcessInputTagsOutOfOrder) { test::TestCryptoVisitor visitor; CryptoFramer framer; framer.set_visitor(&visitor); unsigned char input[] = { 0x33, 0x77, 0xAA, 0xFF, 0x02, 0x00, 0x00, 0x00, 0x78, 0x56, 0x34, 0x13, 0x01, 0x00, 0x00, 0x00, 0x79, 0x56, 0x34, 0x12, 0x02, 0x00, 0x00, 0x00}; EXPECT_FALSE(framer.ProcessInput( absl::string_view(AsChars(input), ABSL_ARRAYSIZE(input)))); EXPECT_THAT(framer.error(), IsError(QUIC_CRYPTO_TAGS_OUT_OF_ORDER)); EXPECT_EQ(1, visitor.error_count_); } TEST(CryptoFramerTest, ProcessEndOffsetsOutOfOrder) { test::TestCryptoVisitor visitor; CryptoFramer framer; framer.set_visitor(&visitor); unsigned char input[] = { 0x33, 0x77, 0xAA, 0xFF, 0x02, 0x00, 0x00, 0x00, 0x79, 0x56, 0x34, 0x12, 0x01, 0x00, 0x00, 0x00, 0x78, 0x56, 0x34, 0x13, 0x00, 0x00, 0x00, 0x00}; EXPECT_FALSE(framer.ProcessInput( absl::string_view(AsChars(input), ABSL_ARRAYSIZE(input)))); EXPECT_THAT(framer.error(), IsError(QUIC_CRYPTO_TAGS_OUT_OF_ORDER)); EXPECT_EQ(1, visitor.error_count_); } TEST(CryptoFramerTest, ProcessInputTooManyEntries) { test::TestCryptoVisitor visitor; CryptoFramer framer; framer.set_visitor(&visitor); unsigned char input[] = { 0x33, 0x77, 0xAA, 0xFF, 0xA0, 0x00, 0x00, 0x00}; EXPECT_FALSE(framer.ProcessInput( absl::string_view(AsChars(input), ABSL_ARRAYSIZE(input)))); EXPECT_THAT(framer.error(), IsError(QUIC_CRYPTO_TOO_MANY_ENTRIES)); EXPECT_EQ(1, visitor.error_count_); } TEST(CryptoFramerTest, ProcessInputZeroLength) { test::TestCryptoVisitor visitor; CryptoFramer framer; framer.set_visitor(&visitor); unsigned char input[] = { 0x33, 0x77, 0xAA, 0xFF, 0x02, 0x00, 0x00, 0x00, 0x78, 0x56, 0x34, 0x12, 0x00, 0x00, 0x00, 0x00, 0x79, 0x56, 0x34, 0x12, 0x05, 0x00, 0x00, 0x00}; EXPECT_TRUE(framer.ProcessInput( absl::string_view(AsChars(input), ABSL_ARRAYSIZE(input)))); EXPECT_EQ(0, visitor.error_count_); } } } }
339
cpp
google/quiche
chacha20_poly1305_encrypter
quiche/quic/core/crypto/chacha20_poly1305_encrypter.cc
quiche/quic/core/crypto/chacha20_poly1305_encrypter_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_CHACHA20_POLY1305_ENCRYPTER_H_ #define QUICHE_QUIC_CORE_CRYPTO_CHACHA20_POLY1305_ENCRYPTER_H_ #include "quiche/quic/core/crypto/chacha_base_encrypter.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT ChaCha20Poly1305Encrypter : public ChaChaBaseEncrypter { public: enum { kAuthTagSize = 12, }; ChaCha20Poly1305Encrypter(); ChaCha20Poly1305Encrypter(const ChaCha20Poly1305Encrypter&) = delete; ChaCha20Poly1305Encrypter& operator=(const ChaCha20Poly1305Encrypter&) = delete; ~ChaCha20Poly1305Encrypter() override; QuicPacketCount GetConfidentialityLimit() const override; }; } #endif #include "quiche/quic/core/crypto/chacha20_poly1305_encrypter.h" #include <limits> #include "openssl/evp.h" namespace quic { namespace { const size_t kKeySize = 32; const size_t kNonceSize = 12; } ChaCha20Poly1305Encrypter::ChaCha20Poly1305Encrypter() : ChaChaBaseEncrypter(EVP_aead_chacha20_poly1305, kKeySize, kAuthTagSize, kNonceSize, false) { static_assert(kKeySize <= kMaxKeySize, "key size too big"); static_assert(kNonceSize <= kMaxNonceSize, "nonce size too big"); } ChaCha20Poly1305Encrypter::~ChaCha20Poly1305Encrypter() {} QuicPacketCount ChaCha20Poly1305Encrypter::GetConfidentialityLimit() const { return std::numeric_limits<QuicPacketCount>::max(); } }
#include "quiche/quic/core/crypto/chacha20_poly1305_encrypter.h" #include <memory> #include <string> #include "absl/base/macros.h" #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/chacha20_poly1305_decrypter.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace { struct TestVector { const char* key; const char* pt; const char* iv; const char* fixed; const char* aad; const char* ct; }; const TestVector test_vectors[] = { { "808182838485868788898a8b8c8d8e8f" "909192939495969798999a9b9c9d9e9f", "4c616469657320616e642047656e746c" "656d656e206f662074686520636c6173" "73206f66202739393a20496620492063" "6f756c64206f6666657220796f75206f" "6e6c79206f6e652074697020666f7220" "746865206675747572652c2073756e73" "637265656e20776f756c642062652069" "742e", "4041424344454647", "07000000", "50515253c0c1c2c3c4c5c6c7", "d31a8d34648e60db7b86afbc53ef7ec2" "a4aded51296e08fea9e2b5a736ee62d6" "3dbea45e8ca9671282fafb69da92728b" "1a71de0a9e060b2905d6a5b67ecd3b36" "92ddbd7f2d778b8c9803aee328091b58" "fab324e4fad675945585808b4831d7bc" "3ff4def08e4b7a9de576d26586cec64b" "6116" "1ae10b594f09e26a7e902ecb", }, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; } namespace quic { namespace test { QuicData* EncryptWithNonce(ChaCha20Poly1305Encrypter* encrypter, absl::string_view nonce, absl::string_view associated_data, absl::string_view plaintext) { size_t ciphertext_size = encrypter->GetCiphertextSize(plaintext.length()); std::unique_ptr<char[]> ciphertext(new char[ciphertext_size]); if (!encrypter->Encrypt(nonce, associated_data, plaintext, reinterpret_cast<unsigned char*>(ciphertext.get()))) { return nullptr; } return new QuicData(ciphertext.release(), ciphertext_size, true); } class ChaCha20Poly1305EncrypterTest : public QuicTest {}; TEST_F(ChaCha20Poly1305EncrypterTest, EncryptThenDecrypt) { ChaCha20Poly1305Encrypter encrypter; ChaCha20Poly1305Decrypter decrypter; std::string key; ASSERT_TRUE(absl::HexStringToBytes(test_vectors[0].key, &key)); ASSERT_TRUE(encrypter.SetKey(key)); ASSERT_TRUE(decrypter.SetKey(key)); ASSERT_TRUE(encrypter.SetNoncePrefix("abcd")); ASSERT_TRUE(decrypter.SetNoncePrefix("abcd")); uint64_t packet_number = UINT64_C(0x123456789ABC); std::string associated_data = "associated_data"; std::string plaintext = "plaintext"; char encrypted[1024]; size_t len; ASSERT_TRUE(encrypter.EncryptPacket(packet_number, associated_data, plaintext, encrypted, &len, ABSL_ARRAYSIZE(encrypted))); absl::string_view ciphertext(encrypted, len); char decrypted[1024]; ASSERT_TRUE(decrypter.DecryptPacket(packet_number, associated_data, ciphertext, decrypted, &len, ABSL_ARRAYSIZE(decrypted))); } TEST_F(ChaCha20Poly1305EncrypterTest, Encrypt) { for (size_t i = 0; test_vectors[i].key != nullptr; i++) { std::string key; std::string pt; std::string iv; std::string fixed; std::string aad; std::string ct; ASSERT_TRUE(absl::HexStringToBytes(test_vectors[i].key, &key)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[i].pt, &pt)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[i].iv, &iv)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[i].fixed, &fixed)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[i].aad, &aad)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[i].ct, &ct)); ChaCha20Poly1305Encrypter encrypter; ASSERT_TRUE(encrypter.SetKey(key)); std::unique_ptr<QuicData> encrypted(EncryptWithNonce( &encrypter, fixed + iv, absl::string_view(aad.length() ? aad.data() : nullptr, aad.length()), pt)); ASSERT_TRUE(encrypted.get()); EXPECT_EQ(12u, ct.size() - pt.size()); EXPECT_EQ(12u, encrypted->length() - pt.size()); quiche::test::CompareCharArraysWithHexError("ciphertext", encrypted->data(), encrypted->length(), ct.data(), ct.length()); } } TEST_F(ChaCha20Poly1305EncrypterTest, GetMaxPlaintextSize) { ChaCha20Poly1305Encrypter encrypter; EXPECT_EQ(1000u, encrypter.GetMaxPlaintextSize(1012)); EXPECT_EQ(100u, encrypter.GetMaxPlaintextSize(112)); EXPECT_EQ(10u, encrypter.GetMaxPlaintextSize(22)); } TEST_F(ChaCha20Poly1305EncrypterTest, GetCiphertextSize) { ChaCha20Poly1305Encrypter encrypter; EXPECT_EQ(1012u, encrypter.GetCiphertextSize(1000)); EXPECT_EQ(112u, encrypter.GetCiphertextSize(100)); EXPECT_EQ(22u, encrypter.GetCiphertextSize(10)); } } }
340
cpp
google/quiche
chacha20_poly1305_decrypter
quiche/quic/core/crypto/chacha20_poly1305_decrypter.cc
quiche/quic/core/crypto/chacha20_poly1305_decrypter_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_CHACHA20_POLY1305_DECRYPTER_H_ #define QUICHE_QUIC_CORE_CRYPTO_CHACHA20_POLY1305_DECRYPTER_H_ #include <cstdint> #include "quiche/quic/core/crypto/chacha_base_decrypter.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT ChaCha20Poly1305Decrypter : public ChaChaBaseDecrypter { public: enum { kAuthTagSize = 12, }; ChaCha20Poly1305Decrypter(); ChaCha20Poly1305Decrypter(const ChaCha20Poly1305Decrypter&) = delete; ChaCha20Poly1305Decrypter& operator=(const ChaCha20Poly1305Decrypter&) = delete; ~ChaCha20Poly1305Decrypter() override; uint32_t cipher_id() const override; QuicPacketCount GetIntegrityLimit() const override; }; } #endif #include "quiche/quic/core/crypto/chacha20_poly1305_decrypter.h" #include "openssl/aead.h" #include "openssl/tls1.h" namespace quic { namespace { const size_t kKeySize = 32; const size_t kNonceSize = 12; } ChaCha20Poly1305Decrypter::ChaCha20Poly1305Decrypter() : ChaChaBaseDecrypter(EVP_aead_chacha20_poly1305, kKeySize, kAuthTagSize, kNonceSize, false) { static_assert(kKeySize <= kMaxKeySize, "key size too big"); static_assert(kNonceSize <= kMaxNonceSize, "nonce size too big"); } ChaCha20Poly1305Decrypter::~ChaCha20Poly1305Decrypter() {} uint32_t ChaCha20Poly1305Decrypter::cipher_id() const { return TLS1_CK_CHACHA20_POLY1305_SHA256; } QuicPacketCount ChaCha20Poly1305Decrypter::GetIntegrityLimit() const { static_assert(kMaxIncomingPacketSize < 16384, "This key limit requires limits on decryption payload sizes"); return 68719476736U; } }
#include "quiche/quic/core/crypto/chacha20_poly1305_decrypter.h" #include <memory> #include <string> #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace { struct TestVector { const char* key; const char* iv; const char* fixed; const char* aad; const char* ct; const char* pt; }; const TestVector test_vectors[] = { {"808182838485868788898a8b8c8d8e8f" "909192939495969798999a9b9c9d9e9f", "4041424344454647", "07000000", "50515253c0c1c2c3c4c5c6c7", "d31a8d34648e60db7b86afbc53ef7ec2" "a4aded51296e08fea9e2b5a736ee62d6" "3dbea45e8ca9671282fafb69da92728b" "1a71de0a9e060b2905d6a5b67ecd3b36" "92ddbd7f2d778b8c9803aee328091b58" "fab324e4fad675945585808b4831d7bc" "3ff4def08e4b7a9de576d26586cec64b" "6116" "1ae10b594f09e26a7e902ecb", "4c616469657320616e642047656e746c" "656d656e206f662074686520636c6173" "73206f66202739393a20496620492063" "6f756c64206f6666657220796f75206f" "6e6c79206f6e652074697020666f7220" "746865206675747572652c2073756e73" "637265656e20776f756c642062652069" "742e"}, {"808182838485868788898a8b8c8d8e8f" "909192939495969798999a9b9c9d9e9f", "4041424344454647", "07000000", "50515253c0c1c2c3c4c5c6c7", "d31a8d34648e60db7b86afbc53ef7ec2" "a4aded51296e08fea9e2b5a736ee62d6" "3dbea45e8ca9671282fafb69da92728b" "1a71de0a9e060b2905d6a5b67ecd3b36" "92ddbd7f2d778b8c9803aee328091b58" "fab324e4fad675945585808b4831d7bc" "3ff4def08e4b7a9de576d26586cec64b" "6116" "1ae10b594f09e26a7e902ecc", nullptr}, {"808182838485868788898a8b8c8d8e8f" "909192939495969798999a9b9c9d9e9f", "4041424344454647", "07000000", "60515253c0c1c2c3c4c5c6c7", "d31a8d34648e60db7b86afbc53ef7ec2" "a4aded51296e08fea9e2b5a736ee62d6" "3dbea45e8ca9671282fafb69da92728b" "1a71de0a9e060b2905d6a5b67ecd3b36" "92ddbd7f2d778b8c9803aee328091b58" "fab324e4fad675945585808b4831d7bc" "3ff4def08e4b7a9de576d26586cec64b" "6116" "1ae10b594f09e26a7e902ecb", nullptr}, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; } namespace quic { namespace test { QuicData* DecryptWithNonce(ChaCha20Poly1305Decrypter* decrypter, absl::string_view nonce, absl::string_view associated_data, absl::string_view ciphertext) { uint64_t packet_number; absl::string_view nonce_prefix(nonce.data(), nonce.size() - sizeof(packet_number)); decrypter->SetNoncePrefix(nonce_prefix); memcpy(&packet_number, nonce.data() + nonce_prefix.size(), sizeof(packet_number)); std::unique_ptr<char[]> output(new char[ciphertext.length()]); size_t output_length = 0; const bool success = decrypter->DecryptPacket( packet_number, associated_data, ciphertext, output.get(), &output_length, ciphertext.length()); if (!success) { return nullptr; } return new QuicData(output.release(), output_length, true); } class ChaCha20Poly1305DecrypterTest : public QuicTest {}; TEST_F(ChaCha20Poly1305DecrypterTest, Decrypt) { for (size_t i = 0; test_vectors[i].key != nullptr; i++) { bool has_pt = test_vectors[i].pt; std::string key; std::string iv; std::string fixed; std::string aad; std::string ct; std::string pt; ASSERT_TRUE(absl::HexStringToBytes(test_vectors[i].key, &key)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[i].iv, &iv)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[i].fixed, &fixed)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[i].aad, &aad)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[i].ct, &ct)); if (has_pt) { ASSERT_TRUE(absl::HexStringToBytes(test_vectors[i].pt, &pt)); } ChaCha20Poly1305Decrypter decrypter; ASSERT_TRUE(decrypter.SetKey(key)); std::unique_ptr<QuicData> decrypted(DecryptWithNonce( &decrypter, fixed + iv, absl::string_view(aad.length() ? aad.data() : nullptr, aad.length()), ct)); if (!decrypted) { EXPECT_FALSE(has_pt); continue; } EXPECT_TRUE(has_pt); EXPECT_EQ(12u, ct.size() - decrypted->length()); ASSERT_EQ(pt.length(), decrypted->length()); quiche::test::CompareCharArraysWithHexError( "plaintext", decrypted->data(), pt.length(), pt.data(), pt.length()); } } } }
341
cpp
google/quiche
channel_id
quiche/quic/core/crypto/channel_id.cc
quiche/quic/core/crypto/channel_id_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_CHANNEL_ID_H_ #define QUICHE_QUIC_CORE_CRYPTO_CHANNEL_ID_H_ #include <memory> #include <string> #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT ChannelIDVerifier { public: ChannelIDVerifier() = delete; static const char kContextStr[]; static const char kClientToServerStr[]; static bool Verify(absl::string_view key, absl::string_view signed_data, absl::string_view signature); static bool VerifyRaw(absl::string_view key, absl::string_view signed_data, absl::string_view signature, bool is_channel_id_signature); }; } #endif #include "quiche/quic/core/crypto/channel_id.h" #include <cstdint> #include "absl/strings/string_view.h" #include "openssl/bn.h" #include "openssl/ec.h" #include "openssl/ecdsa.h" #include "openssl/nid.h" #include "openssl/sha.h" namespace quic { const char ChannelIDVerifier::kContextStr[] = "QUIC ChannelID"; const char ChannelIDVerifier::kClientToServerStr[] = "client -> server"; bool ChannelIDVerifier::Verify(absl::string_view key, absl::string_view signed_data, absl::string_view signature) { return VerifyRaw(key, signed_data, signature, true); } bool ChannelIDVerifier::VerifyRaw(absl::string_view key, absl::string_view signed_data, absl::string_view signature, bool is_channel_id_signature) { if (key.size() != 32 * 2 || signature.size() != 32 * 2) { return false; } bssl::UniquePtr<EC_GROUP> p256( EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1)); if (p256.get() == nullptr) { return false; } bssl::UniquePtr<BIGNUM> x(BN_new()), y(BN_new()), r(BN_new()), s(BN_new()); ECDSA_SIG sig; sig.r = r.get(); sig.s = s.get(); const uint8_t* key_bytes = reinterpret_cast<const uint8_t*>(key.data()); const uint8_t* signature_bytes = reinterpret_cast<const uint8_t*>(signature.data()); if (BN_bin2bn(key_bytes + 0, 32, x.get()) == nullptr || BN_bin2bn(key_bytes + 32, 32, y.get()) == nullptr || BN_bin2bn(signature_bytes + 0, 32, sig.r) == nullptr || BN_bin2bn(signature_bytes + 32, 32, sig.s) == nullptr) { return false; } bssl::UniquePtr<EC_POINT> point(EC_POINT_new(p256.get())); if (point.get() == nullptr || !EC_POINT_set_affine_coordinates_GFp(p256.get(), point.get(), x.get(), y.get(), nullptr)) { return false; } bssl::UniquePtr<EC_KEY> ecdsa_key(EC_KEY_new()); if (ecdsa_key.get() == nullptr || !EC_KEY_set_group(ecdsa_key.get(), p256.get()) || !EC_KEY_set_public_key(ecdsa_key.get(), point.get())) { return false; } SHA256_CTX sha256; SHA256_Init(&sha256); if (is_channel_id_signature) { SHA256_Update(&sha256, kContextStr, strlen(kContextStr) + 1); SHA256_Update(&sha256, kClientToServerStr, strlen(kClientToServerStr) + 1); } SHA256_Update(&sha256, signed_data.data(), signed_data.size()); unsigned char digest[SHA256_DIGEST_LENGTH]; SHA256_Final(digest, &sha256); return ECDSA_do_verify(digest, sizeof(digest), &sig, ecdsa_key.get()) == 1; } }
#include "quiche/quic/core/crypto/channel_id.h" #include <memory> #include <string> #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/crypto_test_utils.h" namespace quic { namespace test { namespace { struct TestVector { const char* msg; const char* qx; const char* qy; const char* r; const char* s; bool result; }; const TestVector test_vector[] = { { "e4796db5f785f207aa30d311693b3702821dff1168fd2e04c0836825aefd850d" "9aa60326d88cde1a23c7745351392ca2288d632c264f197d05cd424a30336c19" "fd09bb229654f0222fcb881a4b35c290a093ac159ce13409111ff0358411133c" "24f5b8e2090d6db6558afc36f06ca1f6ef779785adba68db27a409859fc4c4a0", "87f8f2b218f49845f6f10eec3877136269f5c1a54736dbdf69f89940cad41555", "e15f369036f49842fac7a86c8a2b0557609776814448b8f5e84aa9f4395205e9", "d19ff48b324915576416097d2544f7cbdf8768b1454ad20e0baac50e211f23b0", "a3e81e59311cdfff2d4784949f7a2cb50ba6c3a91fa54710568e61aca3e847c6", false }, { "069a6e6b93dfee6df6ef6997cd80dd2182c36653cef10c655d524585655462d6" "83877f95ecc6d6c81623d8fac4e900ed0019964094e7de91f1481989ae187300" "4565789cbf5dc56c62aedc63f62f3b894c9c6f7788c8ecaadc9bd0e81ad91b2b" "3569ea12260e93924fdddd3972af5273198f5efda0746219475017557616170e", "5cf02a00d205bdfee2016f7421807fc38ae69e6b7ccd064ee689fc1a94a9f7d2", "ec530ce3cc5c9d1af463f264d685afe2b4db4b5828d7e61b748930f3ce622a85", "dc23d130c6117fb5751201455e99f36f59aba1a6a21cf2d0e7481a97451d6693", "d6ce7708c18dbf35d4f8aa7240922dc6823f2e7058cbc1484fcad1599db5018c", false }, { "df04a346cf4d0e331a6db78cca2d456d31b0a000aa51441defdb97bbeb20b94d" "8d746429a393ba88840d661615e07def615a342abedfa4ce912e562af7149598" "96858af817317a840dcff85a057bb91a3c2bf90105500362754a6dd321cdd861" "28cfc5f04667b57aa78c112411e42da304f1012d48cd6a7052d7de44ebcc01de", "2ddfd145767883ffbb0ac003ab4a44346d08fa2570b3120dcce94562422244cb", "5f70c7d11ac2b7a435ccfbbae02c3df1ea6b532cc0e9db74f93fffca7c6f9a64", "9913111cff6f20c5bf453a99cd2c2019a4e749a49724a08774d14e4c113edda8", "9467cd4cd21ecb56b0cab0a9a453b43386845459127a952421f5c6382866c5cc", false }, { "e1130af6a38ccb412a9c8d13e15dbfc9e69a16385af3c3f1e5da954fd5e7c45f" "d75e2b8c36699228e92840c0562fbf3772f07e17f1add56588dd45f7450e1217" "ad239922dd9c32695dc71ff2424ca0dec1321aa47064a044b7fe3c2b97d03ce4" "70a592304c5ef21eed9f93da56bb232d1eeb0035f9bf0dfafdcc4606272b20a3", "e424dc61d4bb3cb7ef4344a7f8957a0c5134e16f7a67c074f82e6e12f49abf3c", "970eed7aa2bc48651545949de1dddaf0127e5965ac85d1243d6f60e7dfaee927", "bf96b99aa49c705c910be33142017c642ff540c76349b9dab72f981fd9347f4f", "17c55095819089c2e03b9cd415abdf12444e323075d98f31920b9e0f57ec871c", true }, { "73c5f6a67456ae48209b5f85d1e7de7758bf235300c6ae2bdceb1dcb27a7730f" "b68c950b7fcada0ecc4661d3578230f225a875e69aaa17f1e71c6be5c831f226" "63bac63d0c7a9635edb0043ff8c6f26470f02a7bc56556f1437f06dfa27b487a" "6c4290d8bad38d4879b334e341ba092dde4e4ae694a9c09302e2dbf443581c08", "e0fc6a6f50e1c57475673ee54e3a57f9a49f3328e743bf52f335e3eeaa3d2864", "7f59d689c91e463607d9194d99faf316e25432870816dde63f5d4b373f12f22a", "1d75830cd36f4c9aa181b2c4221e87f176b7f05b7c87824e82e396c88315c407", "cb2acb01dac96efc53a32d4a0d85d0c2e48955214783ecf50a4f0414a319c05a", true }, { "666036d9b4a2426ed6585a4e0fd931a8761451d29ab04bd7dc6d0c5b9e38e6c2" "b263ff6cb837bd04399de3d757c6c7005f6d7a987063cf6d7e8cb38a4bf0d74a" "282572bd01d0f41e3fd066e3021575f0fa04f27b700d5b7ddddf50965993c3f9" "c7118ed78888da7cb221849b3260592b8e632d7c51e935a0ceae15207bedd548", "a849bef575cac3c6920fbce675c3b787136209f855de19ffe2e8d29b31a5ad86", "bf5fe4f7858f9b805bd8dcc05ad5e7fb889de2f822f3d8b41694e6c55c16b471", "25acc3aa9d9e84c7abf08f73fa4195acc506491d6fc37cb9074528a7db87b9d6", "9b21d5b5259ed3f2ef07dfec6cc90d3a37855d1ce122a85ba6a333f307d31537", false }, { "7e80436bce57339ce8da1b5660149a20240b146d108deef3ec5da4ae256f8f89" "4edcbbc57b34ce37089c0daa17f0c46cd82b5a1599314fd79d2fd2f446bd5a25" "b8e32fcf05b76d644573a6df4ad1dfea707b479d97237a346f1ec632ea5660ef" "b57e8717a8628d7f82af50a4e84b11f21bdff6839196a880ae20b2a0918d58cd", "3dfb6f40f2471b29b77fdccba72d37c21bba019efa40c1c8f91ec405d7dcc5df", "f22f953f1e395a52ead7f3ae3fc47451b438117b1e04d613bc8555b7d6e6d1bb", "548886278e5ec26bed811dbb72db1e154b6f17be70deb1b210107decb1ec2a5a", "e93bfebd2f14f3d827ca32b464be6e69187f5edbd52def4f96599c37d58eee75", false }, { "1669bfb657fdc62c3ddd63269787fc1c969f1850fb04c933dda063ef74a56ce1" "3e3a649700820f0061efabf849a85d474326c8a541d99830eea8131eaea584f2" "2d88c353965dabcdc4bf6b55949fd529507dfb803ab6b480cd73ca0ba00ca19c" "438849e2cea262a1c57d8f81cd257fb58e19dec7904da97d8386e87b84948169", "69b7667056e1e11d6caf6e45643f8b21e7a4bebda463c7fdbc13bc98efbd0214", "d3f9b12eb46c7c6fda0da3fc85bc1fd831557f9abc902a3be3cb3e8be7d1aa2f", "288f7a1cd391842cce21f00e6f15471c04dc182fe4b14d92dc18910879799790", "247b3c4e89a3bcadfea73c7bfd361def43715fa382b8c3edf4ae15d6e55e9979", false }, { "3fe60dd9ad6caccf5a6f583b3ae65953563446c4510b70da115ffaa0ba04c076" "115c7043ab8733403cd69c7d14c212c655c07b43a7c71b9a4cffe22c2684788e" "c6870dc2013f269172c822256f9e7cc674791bf2d8486c0f5684283e1649576e" "fc982ede17c7b74b214754d70402fb4bb45ad086cf2cf76b3d63f7fce39ac970", "bf02cbcf6d8cc26e91766d8af0b164fc5968535e84c158eb3bc4e2d79c3cc682", "069ba6cb06b49d60812066afa16ecf7b51352f2c03bd93ec220822b1f3dfba03", "f5acb06c59c2b4927fb852faa07faf4b1852bbb5d06840935e849c4d293d1bad", "049dab79c89cc02f1484c437f523e080a75f134917fda752f2d5ca397addfe5d", false }, { "983a71b9994d95e876d84d28946a041f8f0a3f544cfcc055496580f1dfd4e312" "a2ad418fe69dbc61db230cc0c0ed97e360abab7d6ff4b81ee970a7e97466acfd" "9644f828ffec538abc383d0e92326d1c88c55e1f46a668a039beaa1be631a891" "29938c00a81a3ae46d4aecbf9707f764dbaccea3ef7665e4c4307fa0b0a3075c", "224a4d65b958f6d6afb2904863efd2a734b31798884801fcab5a590f4d6da9de", "178d51fddada62806f097aa615d33b8f2404e6b1479f5fd4859d595734d6d2b9", "87b93ee2fecfda54deb8dff8e426f3c72c8864991f8ec2b3205bb3b416de93d2", "4044a24df85be0cc76f21a4430b75b8e77b932a87f51e4eccbc45c263ebf8f66", false }, { "4a8c071ac4fd0d52faa407b0fe5dab759f7394a5832127f2a3498f34aac28733" "9e043b4ffa79528faf199dc917f7b066ad65505dab0e11e6948515052ce20cfd" "b892ffb8aa9bf3f1aa5be30a5bbe85823bddf70b39fd7ebd4a93a2f75472c1d4" "f606247a9821f1a8c45a6cb80545de2e0c6c0174e2392088c754e9c8443eb5af", "43691c7795a57ead8c5c68536fe934538d46f12889680a9cb6d055a066228369", "f8790110b3c3b281aa1eae037d4f1234aff587d903d93ba3af225c27ddc9ccac", "8acd62e8c262fa50dd9840480969f4ef70f218ebf8ef9584f199031132c6b1ce", "cfca7ed3d4347fb2a29e526b43c348ae1ce6c60d44f3191b6d8ea3a2d9c92154", false }, { "0a3a12c3084c865daf1d302c78215d39bfe0b8bf28272b3c0b74beb4b7409db0" "718239de700785581514321c6440a4bbaea4c76fa47401e151e68cb6c29017f0" "bce4631290af5ea5e2bf3ed742ae110b04ade83a5dbd7358f29a85938e23d87a" "c8233072b79c94670ff0959f9c7f4517862ff829452096c78f5f2e9a7e4e9216", "9157dbfcf8cf385f5bb1568ad5c6e2a8652ba6dfc63bc1753edf5268cb7eb596", "972570f4313d47fc96f7c02d5594d77d46f91e949808825b3d31f029e8296405", "dfaea6f297fa320b707866125c2a7d5d515b51a503bee817de9faa343cc48eeb", "8f780ad713f9c3e5a4f7fa4c519833dfefc6a7432389b1e4af463961f09764f2", false }, { "785d07a3c54f63dca11f5d1a5f496ee2c2f9288e55007e666c78b007d95cc285" "81dce51f490b30fa73dc9e2d45d075d7e3a95fb8a9e1465ad191904124160b7c" "60fa720ef4ef1c5d2998f40570ae2a870ef3e894c2bc617d8a1dc85c3c557749" "28c38789b4e661349d3f84d2441a3b856a76949b9f1f80bc161648a1cad5588e", "072b10c081a4c1713a294f248aef850e297991aca47fa96a7470abe3b8acfdda", "9581145cca04a0fb94cedce752c8f0370861916d2a94e7c647c5373ce6a4c8f5", "09f5483eccec80f9d104815a1be9cc1a8e5b12b6eb482a65c6907b7480cf4f19", "a4f90e560c5e4eb8696cb276e5165b6a9d486345dedfb094a76e8442d026378d", false }, { "76f987ec5448dd72219bd30bf6b66b0775c80b394851a43ff1f537f140a6e722" "9ef8cd72ad58b1d2d20298539d6347dd5598812bc65323aceaf05228f738b5ad" "3e8d9fe4100fd767c2f098c77cb99c2992843ba3eed91d32444f3b6db6cd212d" "d4e5609548f4bb62812a920f6e2bf1581be1ebeebdd06ec4e971862cc42055ca", "09308ea5bfad6e5adf408634b3d5ce9240d35442f7fe116452aaec0d25be8c24", "f40c93e023ef494b1c3079b2d10ef67f3170740495ce2cc57f8ee4b0618b8ee5", "5cc8aa7c35743ec0c23dde88dabd5e4fcd0192d2116f6926fef788cddb754e73", "9c9c045ebaa1b828c32f82ace0d18daebf5e156eb7cbfdc1eff4399a8a900ae7", false }, { "60cd64b2cd2be6c33859b94875120361a24085f3765cb8b2bf11e026fa9d8855" "dbe435acf7882e84f3c7857f96e2baab4d9afe4588e4a82e17a78827bfdb5ddb" "d1c211fbc2e6d884cddd7cb9d90d5bf4a7311b83f352508033812c776a0e00c0" "03c7e0d628e50736c7512df0acfa9f2320bd102229f46495ae6d0857cc452a84", "2d98ea01f754d34bbc3003df5050200abf445ec728556d7ed7d5c54c55552b6d", "9b52672742d637a32add056dfd6d8792f2a33c2e69dafabea09b960bc61e230a", "06108e525f845d0155bf60193222b3219c98e3d49424c2fb2a0987f825c17959", "62b5cdd591e5b507e560167ba8f6f7cda74673eb315680cb89ccbc4eec477dce", true }, {nullptr, nullptr, nullptr, nullptr, nullptr, false}}; bool IsHexDigit(char ch) { return ('0' <= ch && ch <= '9') || ('a' <= ch && ch <= 'f'); } int HexDigitToInt(char ch) { if ('0' <= ch && ch <= '9') { return ch - '0'; } return ch - 'a' + 10; } bool DecodeHexString(const char* in, char* out, size_t* out_len, size_t max_len) { if (!in) { *out_len = static_cast<size_t>(-1); return true; } *out_len = 0; while (*in != '\0') { if (!IsHexDigit(*in) || !IsHexDigit(*(in + 1))) { return false; } if (*out_len >= max_len) { return false; } out[*out_len] = HexDigitToInt(*in) * 16 + HexDigitToInt(*(in + 1)); (*out_len)++; in += 2; } return true; } } class ChannelIDTest : public QuicTest {}; TEST_F(ChannelIDTest, VerifyKnownAnswerTest) { char msg[1024]; size_t msg_len; char key[64]; size_t qx_len; size_t qy_len; char signature[64]; size_t r_len; size_t s_len; for (size_t i = 0; test_vector[i].msg != nullptr; i++) { SCOPED_TRACE(i); ASSERT_TRUE( DecodeHexString(test_vector[i].msg, msg, &msg_len, sizeof(msg))); ASSERT_TRUE(DecodeHexString(test_vector[i].qx, key, &qx_len, sizeof(key))); ASSERT_TRUE(DecodeHexString(test_vector[i].qy, key + qx_len, &qy_len, sizeof(key) - qx_len)); ASSERT_TRUE(DecodeHexString(test_vector[i].r, signature, &r_len, sizeof(signature))); ASSERT_TRUE(DecodeHexString(test_vector[i].s, signature + r_len, &s_len, sizeof(signature) - r_len)); EXPECT_EQ(sizeof(key) / 2, qx_len); EXPECT_EQ(sizeof(key) / 2, qy_len); EXPECT_EQ(sizeof(signature) / 2, r_len); EXPECT_EQ(sizeof(signature) / 2, s_len); EXPECT_EQ(test_vector[i].result, ChannelIDVerifier::VerifyRaw( absl::string_view(key, sizeof(key)), absl::string_view(msg, msg_len), absl::string_view(signature, sizeof(signature)), false)); } } } }
342
cpp
google/quiche
certificate_util
quiche/quic/core/crypto/certificate_util.cc
quiche/quic/core/crypto/certificate_util_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_CERTIFICATE_UTIL_H_ #define QUICHE_QUIC_CORE_CRYPTO_CERTIFICATE_UTIL_H_ #include <string> #include "absl/strings/string_view.h" #include "openssl/evp.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { struct QUICHE_EXPORT CertificateTimestamp { uint16_t year; uint8_t month; uint8_t day; uint8_t hour; uint8_t minute; uint8_t second; }; struct QUICHE_EXPORT CertificateOptions { absl::string_view subject; uint64_t serial_number; CertificateTimestamp validity_start; CertificateTimestamp validity_end; }; QUICHE_EXPORT bssl::UniquePtr<EVP_PKEY> MakeKeyPairForSelfSignedCertificate(); QUICHE_EXPORT std::string CreateSelfSignedCertificate( EVP_PKEY& key, const CertificateOptions& options); } #endif #include "quiche/quic/core/crypto/certificate_util.h" #include <string> #include <vector> #include "absl/strings/str_format.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "openssl/bn.h" #include "openssl/bytestring.h" #include "openssl/digest.h" #include "openssl/ec_key.h" #include "openssl/mem.h" #include "openssl/pkcs7.h" #include "openssl/pool.h" #include "openssl/rsa.h" #include "openssl/stack.h" #include "quiche/quic/core/crypto/boring_utils.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { namespace { bool AddEcdsa256SignatureAlgorithm(CBB* cbb) { static const uint8_t kEcdsaWithSha256[] = {0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02}; CBB sequence, oid; if (!CBB_add_asn1(cbb, &sequence, CBS_ASN1_SEQUENCE) || !CBB_add_asn1(&sequence, &oid, CBS_ASN1_OBJECT)) { return false; } if (!CBB_add_bytes(&oid, kEcdsaWithSha256, sizeof(kEcdsaWithSha256))) { return false; } return CBB_flush(cbb); } bool AddName(CBB* cbb, absl::string_view name) { static const uint8_t kCommonName[] = {0x55, 0x04, 0x03}; static const uint8_t kCountryName[] = {0x55, 0x04, 0x06}; static const uint8_t kOrganizationName[] = {0x55, 0x04, 0x0a}; static const uint8_t kOrganizationalUnitName[] = {0x55, 0x04, 0x0b}; std::vector<std::string> attributes = absl::StrSplit(name, ',', absl::SkipEmpty()); if (attributes.empty()) { QUIC_LOG(ERROR) << "Missing DN or wrong format"; return false; } CBB rdns; if (!CBB_add_asn1(cbb, &rdns, CBS_ASN1_SEQUENCE)) { return false; } for (const std::string& attribute : attributes) { std::vector<std::string> parts = absl::StrSplit(absl::StripAsciiWhitespace(attribute), '='); if (parts.size() != 2) { QUIC_LOG(ERROR) << "Wrong DN format at " + attribute; return false; } const std::string& type_string = parts[0]; const std::string& value_string = parts[1]; absl::Span<const uint8_t> type_bytes; if (type_string == "CN") { type_bytes = kCommonName; } else if (type_string == "C") { type_bytes = kCountryName; } else if (type_string == "O") { type_bytes = kOrganizationName; } else if (type_string == "OU") { type_bytes = kOrganizationalUnitName; } else { QUIC_LOG(ERROR) << "Unrecognized type " + type_string; return false; } CBB rdn, attr, type, value; if (!CBB_add_asn1(&rdns, &rdn, CBS_ASN1_SET) || !CBB_add_asn1(&rdn, &attr, CBS_ASN1_SEQUENCE) || !CBB_add_asn1(&attr, &type, CBS_ASN1_OBJECT) || !CBB_add_bytes(&type, type_bytes.data(), type_bytes.size()) || !CBB_add_asn1(&attr, &value, type_string == "C" ? CBS_ASN1_PRINTABLESTRING : CBS_ASN1_UTF8STRING) || !AddStringToCbb(&value, value_string) || !CBB_flush(&rdns)) { return false; } } if (!CBB_flush(cbb)) { return false; } return true; } bool CBBAddTime(CBB* cbb, const CertificateTimestamp& timestamp) { CBB child; std::string formatted_time; const bool is_utc_time = (1950 <= timestamp.year && timestamp.year < 2050); if (is_utc_time) { uint16_t year = timestamp.year - 1900; if (year >= 100) { year -= 100; } formatted_time = absl::StrFormat("%02d", year); if (!CBB_add_asn1(cbb, &child, CBS_ASN1_UTCTIME)) { return false; } } else { formatted_time = absl::StrFormat("%04d", timestamp.year); if (!CBB_add_asn1(cbb, &child, CBS_ASN1_GENERALIZEDTIME)) { return false; } } absl::StrAppendFormat(&formatted_time, "%02d%02d%02d%02d%02dZ", timestamp.month, timestamp.day, timestamp.hour, timestamp.minute, timestamp.second); static const size_t kGeneralizedTimeLength = 15; static const size_t kUTCTimeLength = 13; QUICHE_DCHECK_EQ(formatted_time.size(), is_utc_time ? kUTCTimeLength : kGeneralizedTimeLength); return AddStringToCbb(&child, formatted_time) && CBB_flush(cbb); } bool CBBAddExtension(CBB* extensions, absl::Span<const uint8_t> oid, bool critical, absl::Span<const uint8_t> contents) { CBB extension, cbb_oid, cbb_contents; if (!CBB_add_asn1(extensions, &extension, CBS_ASN1_SEQUENCE) || !CBB_add_asn1(&extension, &cbb_oid, CBS_ASN1_OBJECT) || !CBB_add_bytes(&cbb_oid, oid.data(), oid.size()) || (critical && !CBB_add_asn1_bool(&extension, 1)) || !CBB_add_asn1(&extension, &cbb_contents, CBS_ASN1_OCTETSTRING) || !CBB_add_bytes(&cbb_contents, contents.data(), contents.size()) || !CBB_flush(extensions)) { return false; } return true; } bool IsEcdsa256Key(const EVP_PKEY& evp_key) { if (EVP_PKEY_id(&evp_key) != EVP_PKEY_EC) { return false; } const EC_KEY* key = EVP_PKEY_get0_EC_KEY(&evp_key); if (key == nullptr) { return false; } const EC_GROUP* group = EC_KEY_get0_group(key); if (group == nullptr) { return false; } return EC_GROUP_get_curve_name(group) == NID_X9_62_prime256v1; } } bssl::UniquePtr<EVP_PKEY> MakeKeyPairForSelfSignedCertificate() { bssl::UniquePtr<EVP_PKEY_CTX> context( EVP_PKEY_CTX_new_id(EVP_PKEY_EC, nullptr)); if (!context) { return nullptr; } if (EVP_PKEY_keygen_init(context.get()) != 1) { return nullptr; } if (EVP_PKEY_CTX_set_ec_paramgen_curve_nid(context.get(), NID_X9_62_prime256v1) != 1) { return nullptr; } EVP_PKEY* raw_key = nullptr; if (EVP_PKEY_keygen(context.get(), &raw_key) != 1) { return nullptr; } return bssl::UniquePtr<EVP_PKEY>(raw_key); } std::string CreateSelfSignedCertificate(EVP_PKEY& key, const CertificateOptions& options) { std::string error; if (!IsEcdsa256Key(key)) { QUIC_LOG(ERROR) << "CreateSelfSignedCert only accepts ECDSA P-256 keys"; return error; } bssl::ScopedCBB cbb; CBB tbs_cert, version, validity; uint8_t* tbs_cert_bytes; size_t tbs_cert_len; if (!CBB_init(cbb.get(), 64) || !CBB_add_asn1(cbb.get(), &tbs_cert, CBS_ASN1_SEQUENCE) || !CBB_add_asn1(&tbs_cert, &version, CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) || !CBB_add_asn1_uint64(&version, 2) || !CBB_add_asn1_uint64(&tbs_cert, options.serial_number) || !AddEcdsa256SignatureAlgorithm(&tbs_cert) || !AddName(&tbs_cert, options.subject) || !CBB_add_asn1(&tbs_cert, &validity, CBS_ASN1_SEQUENCE) || !CBBAddTime(&validity, options.validity_start) || !CBBAddTime(&validity, options.validity_end) || !AddName(&tbs_cert, options.subject) || !EVP_marshal_public_key(&tbs_cert, &key)) { return error; } CBB outer_extensions, extensions; if (!CBB_add_asn1(&tbs_cert, &outer_extensions, 3 | CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED) || !CBB_add_asn1(&outer_extensions, &extensions, CBS_ASN1_SEQUENCE)) { return error; } constexpr uint8_t kKeyUsageOid[] = {0x55, 0x1d, 0x0f}; constexpr uint8_t kKeyUsageContent[] = { 0x3, 0x2, 0x0, 0x80, }; CBBAddExtension(&extensions, kKeyUsageOid, true, kKeyUsageContent); if (!CBB_finish(cbb.get(), &tbs_cert_bytes, &tbs_cert_len)) { return error; } bssl::UniquePtr<uint8_t> delete_tbs_cert_bytes(tbs_cert_bytes); CBB cert, signature; bssl::ScopedEVP_MD_CTX ctx; uint8_t* sig_out; size_t sig_len; uint8_t* cert_bytes; size_t cert_len; if (!CBB_init(cbb.get(), tbs_cert_len) || !CBB_add_asn1(cbb.get(), &cert, CBS_ASN1_SEQUENCE) || !CBB_add_bytes(&cert, tbs_cert_bytes, tbs_cert_len) || !AddEcdsa256SignatureAlgorithm(&cert) || !CBB_add_asn1(&cert, &signature, CBS_ASN1_BITSTRING) || !CBB_add_u8(&signature, 0 ) || !EVP_DigestSignInit(ctx.get(), nullptr, EVP_sha256(), nullptr, &key) || !EVP_DigestSign(ctx.get(), nullptr, &sig_len, tbs_cert_bytes, tbs_cert_len) || !CBB_reserve(&signature, &sig_out, sig_len) || !EVP_DigestSign(ctx.get(), sig_out, &sig_len, tbs_cert_bytes, tbs_cert_len) || !CBB_did_write(&signature, sig_len) || !CBB_finish(cbb.get(), &cert_bytes, &cert_len)) { return error; } bssl::UniquePtr<uint8_t> delete_cert_bytes(cert_bytes); return std::string(reinterpret_cast<char*>(cert_bytes), cert_len); } }
#include "quiche/quic/core/crypto/certificate_util.h" #include <memory> #include <optional> #include <string> #include <utility> #include "openssl/ssl.h" #include "quiche/quic/core/crypto/certificate_view.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/platform/api/quic_test_output.h" namespace quic { namespace test { namespace { TEST(CertificateUtilTest, CreateSelfSignedCertificate) { bssl::UniquePtr<EVP_PKEY> key = MakeKeyPairForSelfSignedCertificate(); ASSERT_NE(key, nullptr); CertificatePrivateKey cert_key(std::move(key)); CertificateOptions options; options.subject = "CN=subject"; options.serial_number = 0x12345678; options.validity_start = {2020, 1, 1, 0, 0, 0}; options.validity_end = {2049, 12, 31, 0, 0, 0}; std::string der_cert = CreateSelfSignedCertificate(*cert_key.private_key(), options); ASSERT_FALSE(der_cert.empty()); QuicSaveTestOutput("CertificateUtilTest_CreateSelfSignedCert.crt", der_cert); std::unique_ptr<CertificateView> cert_view = CertificateView::ParseSingleCertificate(der_cert); ASSERT_NE(cert_view, nullptr); EXPECT_EQ(cert_view->public_key_type(), PublicKeyType::kP256); std::optional<std::string> subject = cert_view->GetHumanReadableSubject(); ASSERT_TRUE(subject.has_value()); EXPECT_EQ(*subject, options.subject); EXPECT_TRUE( cert_key.ValidForSignatureAlgorithm(SSL_SIGN_ECDSA_SECP256R1_SHA256)); EXPECT_TRUE(cert_key.MatchesPublicKey(*cert_view)); } } } }
343
cpp
google/quiche
crypto_secret_boxer
quiche/quic/core/crypto/crypto_secret_boxer.cc
quiche/quic/core/crypto/crypto_secret_boxer_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_CRYPTO_SECRET_BOXER_H_ #define QUICHE_QUIC_CORE_CRYPTO_CRYPTO_SECRET_BOXER_H_ #include <cstddef> #include <memory> #include <string> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_mutex.h" namespace quic { class QUICHE_EXPORT CryptoSecretBoxer { public: CryptoSecretBoxer(); CryptoSecretBoxer(const CryptoSecretBoxer&) = delete; CryptoSecretBoxer& operator=(const CryptoSecretBoxer&) = delete; ~CryptoSecretBoxer(); static size_t GetKeySize(); bool SetKeys(const std::vector<std::string>& keys); std::string Box(QuicRandom* rand, absl::string_view plaintext) const; bool Unbox(absl::string_view ciphertext, std::string* out_storage, absl::string_view* out) const; private: struct State; mutable QuicMutex lock_; std::unique_ptr<State> state_ QUIC_GUARDED_BY(lock_); }; } #endif #include "quiche/quic/core/crypto/crypto_secret_boxer.h" #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "openssl/aead.h" #include "openssl/err.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { static const size_t kSIVNonceSize = 12; static const size_t kBoxKeySize = 32; struct CryptoSecretBoxer::State { std::vector<bssl::UniquePtr<EVP_AEAD_CTX>> ctxs; }; CryptoSecretBoxer::CryptoSecretBoxer() {} CryptoSecretBoxer::~CryptoSecretBoxer() {} size_t CryptoSecretBoxer::GetKeySize() { return kBoxKeySize; } static const EVP_AEAD* (*const kAEAD)() = EVP_aead_aes_256_gcm_siv; bool CryptoSecretBoxer::SetKeys(const std::vector<std::string>& keys) { if (keys.empty()) { QUIC_LOG(DFATAL) << "No keys supplied!"; return false; } const EVP_AEAD* const aead = kAEAD(); std::unique_ptr<State> new_state(new State); for (const std::string& key : keys) { QUICHE_DCHECK_EQ(kBoxKeySize, key.size()); bssl::UniquePtr<EVP_AEAD_CTX> ctx( EVP_AEAD_CTX_new(aead, reinterpret_cast<const uint8_t*>(key.data()), key.size(), EVP_AEAD_DEFAULT_TAG_LENGTH)); if (!ctx) { ERR_clear_error(); QUIC_LOG(DFATAL) << "EVP_AEAD_CTX_init failed"; return false; } new_state->ctxs.push_back(std::move(ctx)); } QuicWriterMutexLock l(&lock_); state_ = std::move(new_state); return true; } std::string CryptoSecretBoxer::Box(QuicRandom* rand, absl::string_view plaintext) const { size_t out_len = kSIVNonceSize + plaintext.size() + EVP_AEAD_max_overhead(kAEAD()); std::string ret; ret.resize(out_len); uint8_t* out = reinterpret_cast<uint8_t*>(const_cast<char*>(ret.data())); rand->RandBytes(out, kSIVNonceSize); const uint8_t* const nonce = out; out += kSIVNonceSize; out_len -= kSIVNonceSize; size_t bytes_written; { QuicReaderMutexLock l(&lock_); if (!EVP_AEAD_CTX_seal(state_->ctxs[0].get(), out, &bytes_written, out_len, nonce, kSIVNonceSize, reinterpret_cast<const uint8_t*>(plaintext.data()), plaintext.size(), nullptr, 0)) { ERR_clear_error(); QUIC_LOG(DFATAL) << "EVP_AEAD_CTX_seal failed"; return ""; } } QUICHE_DCHECK_EQ(out_len, bytes_written); return ret; } bool CryptoSecretBoxer::Unbox(absl::string_view in_ciphertext, std::string* out_storage, absl::string_view* out) const { if (in_ciphertext.size() < kSIVNonceSize) { return false; } const uint8_t* const nonce = reinterpret_cast<const uint8_t*>(in_ciphertext.data()); const uint8_t* const ciphertext = nonce + kSIVNonceSize; const size_t ciphertext_len = in_ciphertext.size() - kSIVNonceSize; out_storage->resize(ciphertext_len); bool ok = false; { QuicReaderMutexLock l(&lock_); for (const bssl::UniquePtr<EVP_AEAD_CTX>& ctx : state_->ctxs) { size_t bytes_written; if (EVP_AEAD_CTX_open(ctx.get(), reinterpret_cast<uint8_t*>( const_cast<char*>(out_storage->data())), &bytes_written, ciphertext_len, nonce, kSIVNonceSize, ciphertext, ciphertext_len, nullptr, 0)) { ok = true; *out = absl::string_view(out_storage->data(), bytes_written); break; } ERR_clear_error(); } } return ok; } }
#include "quiche/quic/core/crypto/crypto_secret_boxer.h" #include <string> #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { class CryptoSecretBoxerTest : public QuicTest {}; TEST_F(CryptoSecretBoxerTest, BoxAndUnbox) { absl::string_view message("hello world"); CryptoSecretBoxer boxer; boxer.SetKeys({std::string(CryptoSecretBoxer::GetKeySize(), 0x11)}); const std::string box = boxer.Box(QuicRandom::GetInstance(), message); std::string storage; absl::string_view result; EXPECT_TRUE(boxer.Unbox(box, &storage, &result)); EXPECT_EQ(result, message); EXPECT_FALSE(boxer.Unbox(std::string(1, 'X') + box, &storage, &result)); EXPECT_FALSE( boxer.Unbox(box.substr(1, std::string::npos), &storage, &result)); EXPECT_FALSE(boxer.Unbox(std::string(), &storage, &result)); EXPECT_FALSE(boxer.Unbox( std::string(1, box[0] ^ 0x80) + box.substr(1, std::string::npos), &storage, &result)); } static bool CanDecode(const CryptoSecretBoxer& decoder, const CryptoSecretBoxer& encoder) { absl::string_view message("hello world"); const std::string boxed = encoder.Box(QuicRandom::GetInstance(), message); std::string storage; absl::string_view result; bool ok = decoder.Unbox(boxed, &storage, &result); if (ok) { EXPECT_EQ(result, message); } return ok; } TEST_F(CryptoSecretBoxerTest, MultipleKeys) { std::string key_11(CryptoSecretBoxer::GetKeySize(), 0x11); std::string key_12(CryptoSecretBoxer::GetKeySize(), 0x12); CryptoSecretBoxer boxer_11, boxer_12, boxer; EXPECT_TRUE(boxer_11.SetKeys({key_11})); EXPECT_TRUE(boxer_12.SetKeys({key_12})); EXPECT_TRUE(boxer.SetKeys({key_12, key_11})); EXPECT_FALSE(CanDecode(boxer_11, boxer_12)); EXPECT_FALSE(CanDecode(boxer_12, boxer_11)); EXPECT_TRUE(CanDecode(boxer_12, boxer)); EXPECT_FALSE(CanDecode(boxer_11, boxer)); EXPECT_TRUE(CanDecode(boxer, boxer_11)); EXPECT_TRUE(CanDecode(boxer, boxer_12)); EXPECT_TRUE(boxer.SetKeys({key_12})); EXPECT_FALSE(CanDecode(boxer, boxer_11)); } } }
344
cpp
google/quiche
client_proof_source
quiche/quic/core/crypto/client_proof_source.cc
quiche/quic/core/crypto/client_proof_source_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_CLIENT_PROOF_SOURCE_H_ #define QUICHE_QUIC_CORE_CRYPTO_CLIENT_PROOF_SOURCE_H_ #include <memory> #include "absl/container/flat_hash_map.h" #include "quiche/quic/core/crypto/certificate_view.h" #include "quiche/quic/core/crypto/proof_source.h" namespace quic { class QUICHE_EXPORT ClientProofSource { public: using Chain = ProofSource::Chain; virtual ~ClientProofSource() {} struct QUICHE_EXPORT CertAndKey { CertAndKey(quiche::QuicheReferenceCountedPointer<Chain> chain, CertificatePrivateKey private_key) : chain(std::move(chain)), private_key(std::move(private_key)) {} quiche::QuicheReferenceCountedPointer<Chain> chain; CertificatePrivateKey private_key; }; virtual std::shared_ptr<const CertAndKey> GetCertAndKey( absl::string_view server_hostname) const = 0; }; class QUICHE_EXPORT DefaultClientProofSource : public ClientProofSource { public: ~DefaultClientProofSource() override {} bool AddCertAndKey(std::vector<std::string> server_hostnames, quiche::QuicheReferenceCountedPointer<Chain> chain, CertificatePrivateKey private_key); std::shared_ptr<const CertAndKey> GetCertAndKey( absl::string_view hostname) const override; private: std::shared_ptr<const CertAndKey> LookupExact( absl::string_view map_key) const; absl::flat_hash_map<std::string, std::shared_ptr<CertAndKey>> cert_and_keys_; }; } #endif #include "quiche/quic/core/crypto/client_proof_source.h" #include <memory> #include <string> #include <utility> #include <vector> #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" namespace quic { bool DefaultClientProofSource::AddCertAndKey( std::vector<std::string> server_hostnames, quiche::QuicheReferenceCountedPointer<Chain> chain, CertificatePrivateKey private_key) { if (!ValidateCertAndKey(chain, private_key)) { return false; } auto cert_and_key = std::make_shared<CertAndKey>(std::move(chain), std::move(private_key)); for (const std::string& domain : server_hostnames) { cert_and_keys_[domain] = cert_and_key; } return true; } std::shared_ptr<const ClientProofSource::CertAndKey> DefaultClientProofSource::GetCertAndKey(absl::string_view hostname) const { if (std::shared_ptr<const CertAndKey> result = LookupExact(hostname); result || hostname == "*") { return result; } if (hostname.size() > 1 && !absl::StartsWith(hostname, "*.")) { auto dot_pos = hostname.find('.'); if (dot_pos != std::string::npos) { std::string wildcard = absl::StrCat("*", hostname.substr(dot_pos)); std::shared_ptr<const CertAndKey> result = LookupExact(wildcard); if (result != nullptr) { return result; } } } return LookupExact("*"); } std::shared_ptr<const ClientProofSource::CertAndKey> DefaultClientProofSource::LookupExact(absl::string_view map_key) const { const auto it = cert_and_keys_.find(map_key); QUIC_DVLOG(1) << "LookupExact(" << map_key << ") found:" << (it != cert_and_keys_.end()); if (it != cert_and_keys_.end()) { return it->second; } return nullptr; } }
#include "quiche/quic/core/crypto/client_proof_source.h" #include <string> #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/test_certificates.h" namespace quic { namespace test { quiche::QuicheReferenceCountedPointer<ClientProofSource::Chain> TestCertChain() { return quiche::QuicheReferenceCountedPointer<ClientProofSource::Chain>( new ClientProofSource::Chain({std::string(kTestCertificate)})); } CertificatePrivateKey TestPrivateKey() { CBS private_key_cbs; CBS_init(&private_key_cbs, reinterpret_cast<const uint8_t*>(kTestCertificatePrivateKey.data()), kTestCertificatePrivateKey.size()); return CertificatePrivateKey( bssl::UniquePtr<EVP_PKEY>(EVP_parse_private_key(&private_key_cbs))); } const ClientProofSource::CertAndKey* TestCertAndKey() { static const ClientProofSource::CertAndKey cert_and_key(TestCertChain(), TestPrivateKey()); return &cert_and_key; } quiche::QuicheReferenceCountedPointer<ClientProofSource::Chain> NullCertChain() { return quiche::QuicheReferenceCountedPointer<ClientProofSource::Chain>(); } quiche::QuicheReferenceCountedPointer<ClientProofSource::Chain> EmptyCertChain() { return quiche::QuicheReferenceCountedPointer<ClientProofSource::Chain>( new ClientProofSource::Chain(std::vector<std::string>())); } quiche::QuicheReferenceCountedPointer<ClientProofSource::Chain> BadCertChain() { return quiche::QuicheReferenceCountedPointer<ClientProofSource::Chain>( new ClientProofSource::Chain({"This is the content of a bad cert."})); } CertificatePrivateKey EmptyPrivateKey() { return CertificatePrivateKey(bssl::UniquePtr<EVP_PKEY>(EVP_PKEY_new())); } #define VERIFY_CERT_AND_KEY_MATCHES(lhs, rhs) \ do { \ SCOPED_TRACE(testing::Message()); \ VerifyCertAndKeyMatches(lhs.get(), rhs); \ } while (0) void VerifyCertAndKeyMatches(const ClientProofSource::CertAndKey* lhs, const ClientProofSource::CertAndKey* rhs) { if (lhs == rhs) { return; } if (lhs == nullptr) { ADD_FAILURE() << "lhs is nullptr, but rhs is not"; return; } if (rhs == nullptr) { ADD_FAILURE() << "rhs is nullptr, but lhs is not"; return; } if (1 != EVP_PKEY_cmp(lhs->private_key.private_key(), rhs->private_key.private_key())) { ADD_FAILURE() << "Private keys mismatch"; return; } const ClientProofSource::Chain* lhs_chain = lhs->chain.get(); const ClientProofSource::Chain* rhs_chain = rhs->chain.get(); if (lhs_chain == rhs_chain) { return; } if (lhs_chain == nullptr) { ADD_FAILURE() << "lhs->chain is nullptr, but rhs->chain is not"; return; } if (rhs_chain == nullptr) { ADD_FAILURE() << "rhs->chain is nullptr, but lhs->chain is not"; return; } if (lhs_chain->certs.size() != rhs_chain->certs.size()) { ADD_FAILURE() << "Cert chain length differ. lhs:" << lhs_chain->certs.size() << ", rhs:" << rhs_chain->certs.size(); return; } for (size_t i = 0; i < lhs_chain->certs.size(); ++i) { if (lhs_chain->certs[i] != rhs_chain->certs[i]) { ADD_FAILURE() << "The " << i << "-th certs differ."; return; } } } TEST(DefaultClientProofSource, FullDomain) { DefaultClientProofSource proof_source; ASSERT_TRUE(proof_source.AddCertAndKey({"www.google.com"}, TestCertChain(), TestPrivateKey())); VERIFY_CERT_AND_KEY_MATCHES(proof_source.GetCertAndKey("www.google.com"), TestCertAndKey()); EXPECT_EQ(proof_source.GetCertAndKey("*.google.com"), nullptr); EXPECT_EQ(proof_source.GetCertAndKey("*"), nullptr); } TEST(DefaultClientProofSource, WildcardDomain) { DefaultClientProofSource proof_source; ASSERT_TRUE(proof_source.AddCertAndKey({"*.google.com"}, TestCertChain(), TestPrivateKey())); VERIFY_CERT_AND_KEY_MATCHES(proof_source.GetCertAndKey("www.google.com"), TestCertAndKey()); VERIFY_CERT_AND_KEY_MATCHES(proof_source.GetCertAndKey("*.google.com"), TestCertAndKey()); EXPECT_EQ(proof_source.GetCertAndKey("*"), nullptr); } TEST(DefaultClientProofSource, DefaultDomain) { DefaultClientProofSource proof_source; ASSERT_TRUE( proof_source.AddCertAndKey({"*"}, TestCertChain(), TestPrivateKey())); VERIFY_CERT_AND_KEY_MATCHES(proof_source.GetCertAndKey("www.google.com"), TestCertAndKey()); VERIFY_CERT_AND_KEY_MATCHES(proof_source.GetCertAndKey("*.google.com"), TestCertAndKey()); VERIFY_CERT_AND_KEY_MATCHES(proof_source.GetCertAndKey("*"), TestCertAndKey()); } TEST(DefaultClientProofSource, FullAndWildcard) { DefaultClientProofSource proof_source; ASSERT_TRUE(proof_source.AddCertAndKey({"www.google.com", "*.google.com"}, TestCertChain(), TestPrivateKey())); VERIFY_CERT_AND_KEY_MATCHES(proof_source.GetCertAndKey("www.google.com"), TestCertAndKey()); VERIFY_CERT_AND_KEY_MATCHES(proof_source.GetCertAndKey("foo.google.com"), TestCertAndKey()); EXPECT_EQ(proof_source.GetCertAndKey("www.example.com"), nullptr); EXPECT_EQ(proof_source.GetCertAndKey("*"), nullptr); } TEST(DefaultClientProofSource, FullWildcardAndDefault) { DefaultClientProofSource proof_source; ASSERT_TRUE( proof_source.AddCertAndKey({"www.google.com", "*.google.com", "*"}, TestCertChain(), TestPrivateKey())); VERIFY_CERT_AND_KEY_MATCHES(proof_source.GetCertAndKey("www.google.com"), TestCertAndKey()); VERIFY_CERT_AND_KEY_MATCHES(proof_source.GetCertAndKey("foo.google.com"), TestCertAndKey()); VERIFY_CERT_AND_KEY_MATCHES(proof_source.GetCertAndKey("www.example.com"), TestCertAndKey()); VERIFY_CERT_AND_KEY_MATCHES(proof_source.GetCertAndKey("*.google.com"), TestCertAndKey()); VERIFY_CERT_AND_KEY_MATCHES(proof_source.GetCertAndKey("*"), TestCertAndKey()); } TEST(DefaultClientProofSource, EmptyCerts) { DefaultClientProofSource proof_source; EXPECT_QUIC_BUG(ASSERT_FALSE(proof_source.AddCertAndKey( {"*"}, NullCertChain(), TestPrivateKey())), "Certificate chain is empty"); EXPECT_QUIC_BUG(ASSERT_FALSE(proof_source.AddCertAndKey( {"*"}, EmptyCertChain(), TestPrivateKey())), "Certificate chain is empty"); EXPECT_EQ(proof_source.GetCertAndKey("*"), nullptr); } TEST(DefaultClientProofSource, BadCerts) { DefaultClientProofSource proof_source; EXPECT_QUIC_BUG(ASSERT_FALSE(proof_source.AddCertAndKey({"*"}, BadCertChain(), TestPrivateKey())), "Unabled to parse leaf certificate"); EXPECT_EQ(proof_source.GetCertAndKey("*"), nullptr); } TEST(DefaultClientProofSource, KeyMismatch) { DefaultClientProofSource proof_source; EXPECT_QUIC_BUG(ASSERT_FALSE(proof_source.AddCertAndKey( {"www.google.com"}, TestCertChain(), EmptyPrivateKey())), "Private key does not match the leaf certificate"); EXPECT_EQ(proof_source.GetCertAndKey("*"), nullptr); } } }
345
cpp
google/quiche
web_transport_fingerprint_proof_verifier
quiche/quic/core/crypto/web_transport_fingerprint_proof_verifier.cc
quiche/quic/core/crypto/web_transport_fingerprint_proof_verifier_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_WEB_TRANSPORT_FINGERPRINT_PROOF_VERIFIER_H_ #define QUICHE_QUIC_CORE_CRYPTO_WEB_TRANSPORT_FINGERPRINT_PROOF_VERIFIER_H_ #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/certificate_view.h" #include "quiche/quic/core/crypto/proof_verifier.h" #include "quiche/quic/core/quic_clock.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { struct QUICHE_EXPORT CertificateFingerprint { static constexpr char kSha256[] = "sha-256"; std::string algorithm; std::string fingerprint; }; struct QUICHE_EXPORT WebTransportHash { static constexpr char kSha256[] = "sha-256"; std::string algorithm; std::string value; }; class QUICHE_EXPORT WebTransportFingerprintProofVerifier : public ProofVerifier { public: enum class Status { kValidCertificate = 0, kUnknownFingerprint = 1, kCertificateParseFailure = 2, kExpiryTooLong = 3, kExpired = 4, kInternalError = 5, kDisallowedKeyAlgorithm = 6, kMaxValue = kDisallowedKeyAlgorithm, }; class QUICHE_EXPORT Details : public ProofVerifyDetails { public: explicit Details(Status status) : status_(status) {} Status status() const { return status_; } ProofVerifyDetails* Clone() const override; private: const Status status_; }; WebTransportFingerprintProofVerifier(const QuicClock* clock, int max_validity_days); bool AddFingerprint(CertificateFingerprint fingerprint); bool AddFingerprint(WebTransportHash hash); QuicAsyncStatus VerifyProof( const std::string& hostname, const uint16_t port, const std::string& server_config, QuicTransportVersion transport_version, absl::string_view chlo_hash, const std::vector<std::string>& certs, const std::string& cert_sct, const std::string& signature, const ProofVerifyContext* context, std::string* error_details, std::unique_ptr<ProofVerifyDetails>* details, std::unique_ptr<ProofVerifierCallback> callback) override; QuicAsyncStatus VerifyCertChain( const std::string& hostname, const uint16_t port, const std::vector<std::string>& certs, const std::string& ocsp_response, const std::string& cert_sct, const ProofVerifyContext* context, std::string* error_details, std::unique_ptr<ProofVerifyDetails>* details, uint8_t* out_alert, std::unique_ptr<ProofVerifierCallback> callback) override; std::unique_ptr<ProofVerifyContext> CreateDefaultContext() override; protected: virtual bool IsKeyTypeAllowedByPolicy(const CertificateView& certificate); private: bool HasKnownFingerprint(absl::string_view der_certificate); bool HasValidExpiry(const CertificateView& certificate); bool IsWithinValidityPeriod(const CertificateView& certificate); const QuicClock* clock_; const int max_validity_days_; const QuicTime::Delta max_validity_; std::vector<WebTransportHash> hashes_; }; } #endif #include "quiche/quic/core/crypto/web_transport_fingerprint_proof_verifier.h" #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/strings/escaping.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_replace.h" #include "absl/strings/string_view.h" #include "openssl/sha.h" #include "quiche/quic/core/crypto/certificate_view.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/common/quiche_text_utils.h" namespace quic { namespace { constexpr size_t kFingerprintLength = SHA256_DIGEST_LENGTH * 3 - 1; bool IsNormalizedHexDigit(char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); } void NormalizeFingerprint(CertificateFingerprint& fingerprint) { fingerprint.fingerprint = quiche::QuicheTextUtils::ToLower(fingerprint.fingerprint); } } constexpr char CertificateFingerprint::kSha256[]; constexpr char WebTransportHash::kSha256[]; ProofVerifyDetails* WebTransportFingerprintProofVerifier::Details::Clone() const { return new Details(*this); } WebTransportFingerprintProofVerifier::WebTransportFingerprintProofVerifier( const QuicClock* clock, int max_validity_days) : clock_(clock), max_validity_days_(max_validity_days), max_validity_( QuicTime::Delta::FromSeconds(max_validity_days * 86400 + 1)) {} bool WebTransportFingerprintProofVerifier::AddFingerprint( CertificateFingerprint fingerprint) { NormalizeFingerprint(fingerprint); if (!absl::EqualsIgnoreCase(fingerprint.algorithm, CertificateFingerprint::kSha256)) { QUIC_DLOG(WARNING) << "Algorithms other than SHA-256 are not supported"; return false; } if (fingerprint.fingerprint.size() != kFingerprintLength) { QUIC_DLOG(WARNING) << "Invalid fingerprint length"; return false; } for (size_t i = 0; i < fingerprint.fingerprint.size(); i++) { char current = fingerprint.fingerprint[i]; if (i % 3 == 2) { if (current != ':') { QUIC_DLOG(WARNING) << "Missing colon separator between the bytes of the hash"; return false; } } else { if (!IsNormalizedHexDigit(current)) { QUIC_DLOG(WARNING) << "Fingerprint must be in hexadecimal"; return false; } } } std::string normalized = absl::StrReplaceAll(fingerprint.fingerprint, {{":", ""}}); std::string normalized_bytes; if (!absl::HexStringToBytes(normalized, &normalized_bytes)) { QUIC_DLOG(WARNING) << "Fingerprint hexadecimal is invalid"; return false; } hashes_.push_back( WebTransportHash{fingerprint.algorithm, std::move(normalized_bytes)}); return true; } bool WebTransportFingerprintProofVerifier::AddFingerprint( WebTransportHash hash) { if (hash.algorithm != CertificateFingerprint::kSha256) { QUIC_DLOG(WARNING) << "Algorithms other than SHA-256 are not supported"; return false; } if (hash.value.size() != SHA256_DIGEST_LENGTH) { QUIC_DLOG(WARNING) << "Invalid fingerprint length"; return false; } hashes_.push_back(std::move(hash)); return true; } QuicAsyncStatus WebTransportFingerprintProofVerifier::VerifyProof( const std::string& , const uint16_t , const std::string& , QuicTransportVersion , absl::string_view , const std::vector<std::string>& , const std::string& , const std::string& , const ProofVerifyContext* , std::string* error_details, std::unique_ptr<ProofVerifyDetails>* details, std::unique_ptr<ProofVerifierCallback> ) { *error_details = "QUIC crypto certificate verification is not supported in " "WebTransportFingerprintProofVerifier"; QUIC_BUG(quic_bug_10879_1) << *error_details; *details = std::make_unique<Details>(Status::kInternalError); return QUIC_FAILURE; } QuicAsyncStatus WebTransportFingerprintProofVerifier::VerifyCertChain( const std::string& , const uint16_t , const std::vector<std::string>& certs, const std::string& , const std::string& , const ProofVerifyContext* , std::string* error_details, std::unique_ptr<ProofVerifyDetails>* details, uint8_t* , std::unique_ptr<ProofVerifierCallback> ) { if (certs.empty()) { *details = std::make_unique<Details>(Status::kInternalError); *error_details = "No certificates provided"; return QUIC_FAILURE; } if (!HasKnownFingerprint(certs[0])) { *details = std::make_unique<Details>(Status::kUnknownFingerprint); *error_details = "Certificate does not match any fingerprint"; return QUIC_FAILURE; } std::unique_ptr<CertificateView> view = CertificateView::ParseSingleCertificate(certs[0]); if (view == nullptr) { *details = std::make_unique<Details>(Status::kCertificateParseFailure); *error_details = "Failed to parse the certificate"; return QUIC_FAILURE; } if (!HasValidExpiry(*view)) { *details = std::make_unique<Details>(Status::kExpiryTooLong); *error_details = absl::StrCat("Certificate expiry exceeds the configured limit of ", max_validity_days_, " days"); return QUIC_FAILURE; } if (!IsWithinValidityPeriod(*view)) { *details = std::make_unique<Details>(Status::kExpired); *error_details = "Certificate has expired or has validity listed in the future"; return QUIC_FAILURE; } if (!IsKeyTypeAllowedByPolicy(*view)) { *details = std::make_unique<Details>(Status::kDisallowedKeyAlgorithm); *error_details = absl::StrCat("Certificate uses a disallowed public key type (", PublicKeyTypeToString(view->public_key_type()), ")"); return QUIC_FAILURE; } *details = std::make_unique<Details>(Status::kValidCertificate); return QUIC_SUCCESS; } std::unique_ptr<ProofVerifyContext> WebTransportFingerprintProofVerifier::CreateDefaultContext() { return nullptr; } bool WebTransportFingerprintProofVerifier::HasKnownFingerprint( absl::string_view der_certificate) { const std::string hash = RawSha256(der_certificate); for (const WebTransportHash& reference : hashes_) { if (reference.algorithm != WebTransportHash::kSha256) { QUIC_BUG(quic_bug_10879_2) << "Unexpected non-SHA-256 hash"; continue; } if (hash == reference.value) { return true; } } return false; } bool WebTransportFingerprintProofVerifier::HasValidExpiry( const CertificateView& certificate) { if (!certificate.validity_start().IsBefore(certificate.validity_end())) { return false; } const QuicTime::Delta duration_seconds = certificate.validity_end() - certificate.validity_start(); return duration_seconds <= max_validity_; } bool WebTransportFingerprintProofVerifier::IsWithinValidityPeriod( const CertificateView& certificate) { QuicWallTime now = clock_->WallNow(); return now.IsAfter(certificate.validity_start()) && now.IsBefore(certificate.validity_end()); } bool WebTransportFingerprintProofVerifier::IsKeyTypeAllowedByPolicy( const CertificateView& certificate) { switch (certificate.public_key_type()) { case PublicKeyType::kP256: case PublicKeyType::kP384: case PublicKeyType::kEd25519: return true; case PublicKeyType::kRsa: return true; default: return false; } } }
#include "quiche/quic/core/crypto/web_transport_fingerprint_proof_verifier.h" #include <memory> #include <string> #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_clock.h" #include "quiche/quic/test_tools/test_certificates.h" namespace quic { namespace test { namespace { using ::testing::HasSubstr; constexpr QuicTime::Delta kValidTime = QuicTime::Delta::FromSeconds(1580560556); struct VerifyResult { QuicAsyncStatus status; WebTransportFingerprintProofVerifier::Status detailed_status; std::string error; }; class WebTransportFingerprintProofVerifierTest : public QuicTest { public: WebTransportFingerprintProofVerifierTest() { clock_.AdvanceTime(kValidTime); verifier_ = std::make_unique<WebTransportFingerprintProofVerifier>( &clock_, 365); AddTestCertificate(); } protected: VerifyResult Verify(absl::string_view certificate) { VerifyResult result; std::unique_ptr<ProofVerifyDetails> details; uint8_t tls_alert; result.status = verifier_->VerifyCertChain( "", 0, std::vector<std::string>{std::string(certificate)}, "", "", nullptr, &result.error, &details, &tls_alert, nullptr); result.detailed_status = static_cast<WebTransportFingerprintProofVerifier::Details*>( details.get()) ->status(); return result; } void AddTestCertificate() { EXPECT_TRUE(verifier_->AddFingerprint(WebTransportHash{ WebTransportHash::kSha256, RawSha256(kTestCertificate)})); } MockClock clock_; std::unique_ptr<WebTransportFingerprintProofVerifier> verifier_; }; TEST_F(WebTransportFingerprintProofVerifierTest, Sha256Fingerprint) { EXPECT_EQ(absl::BytesToHexString(RawSha256(kTestCertificate)), "f2e5465e2bf7ecd6f63066a5a37511734aa0eb7c4701" "0e86d6758ed4f4fa1b0f"); } TEST_F(WebTransportFingerprintProofVerifierTest, SimpleFingerprint) { VerifyResult result = Verify(kTestCertificate); EXPECT_EQ(result.status, QUIC_SUCCESS); EXPECT_EQ(result.detailed_status, WebTransportFingerprintProofVerifier::Status::kValidCertificate); result = Verify(kWildcardCertificate); EXPECT_EQ(result.status, QUIC_FAILURE); EXPECT_EQ(result.detailed_status, WebTransportFingerprintProofVerifier::Status::kUnknownFingerprint); result = Verify("Some random text"); EXPECT_EQ(result.status, QUIC_FAILURE); } TEST_F(WebTransportFingerprintProofVerifierTest, Validity) { constexpr QuicTime::Delta kStartTime = QuicTime::Delta::FromSeconds(1580324400); clock_.Reset(); clock_.AdvanceTime(kStartTime); VerifyResult result = Verify(kTestCertificate); EXPECT_EQ(result.status, QUIC_FAILURE); EXPECT_EQ(result.detailed_status, WebTransportFingerprintProofVerifier::Status::kExpired); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(86400)); result = Verify(kTestCertificate); EXPECT_EQ(result.status, QUIC_SUCCESS); EXPECT_EQ(result.detailed_status, WebTransportFingerprintProofVerifier::Status::kValidCertificate); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(4 * 86400)); result = Verify(kTestCertificate); EXPECT_EQ(result.status, QUIC_FAILURE); EXPECT_EQ(result.detailed_status, WebTransportFingerprintProofVerifier::Status::kExpired); } TEST_F(WebTransportFingerprintProofVerifierTest, MaxValidity) { verifier_ = std::make_unique<WebTransportFingerprintProofVerifier>( &clock_, 2); AddTestCertificate(); VerifyResult result = Verify(kTestCertificate); EXPECT_EQ(result.status, QUIC_FAILURE); EXPECT_EQ(result.detailed_status, WebTransportFingerprintProofVerifier::Status::kExpiryTooLong); EXPECT_THAT(result.error, HasSubstr("limit of 2 days")); verifier_ = std::make_unique<WebTransportFingerprintProofVerifier>( &clock_, 4); AddTestCertificate(); result = Verify(kTestCertificate); EXPECT_EQ(result.status, QUIC_SUCCESS); EXPECT_EQ(result.detailed_status, WebTransportFingerprintProofVerifier::Status::kValidCertificate); } TEST_F(WebTransportFingerprintProofVerifierTest, InvalidCertificate) { constexpr absl::string_view kInvalidCertificate = "Hello, world!"; ASSERT_TRUE(verifier_->AddFingerprint(WebTransportHash{ WebTransportHash::kSha256, RawSha256(kInvalidCertificate)})); VerifyResult result = Verify(kInvalidCertificate); EXPECT_EQ(result.status, QUIC_FAILURE); EXPECT_EQ( result.detailed_status, WebTransportFingerprintProofVerifier::Status::kCertificateParseFailure); } TEST_F(WebTransportFingerprintProofVerifierTest, AddCertificate) { verifier_ = std::make_unique<WebTransportFingerprintProofVerifier>( &clock_, 365); EXPECT_TRUE(verifier_->AddFingerprint(CertificateFingerprint{ CertificateFingerprint::kSha256, "F2:E5:46:5E:2B:F7:EC:D6:F6:30:66:A5:A3:75:11:73:4A:A0:EB:" "7C:47:01:0E:86:D6:75:8E:D4:F4:FA:1B:0F"})); EXPECT_EQ(Verify(kTestCertificate).detailed_status, WebTransportFingerprintProofVerifier::Status::kValidCertificate); EXPECT_FALSE(verifier_->AddFingerprint(CertificateFingerprint{ "sha-1", "00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00"})); EXPECT_FALSE(verifier_->AddFingerprint( CertificateFingerprint{CertificateFingerprint::kSha256, "00:00:00:00"})); EXPECT_FALSE(verifier_->AddFingerprint(CertificateFingerprint{ CertificateFingerprint::kSha256, "00.00.00.00.00.00.00.00.00.00.00.00.00.00.00.00.00.00.00." "00.00.00.00.00.00.00.00.00.00.00.00.00"})); EXPECT_FALSE(verifier_->AddFingerprint(CertificateFingerprint{ CertificateFingerprint::kSha256, "zz:zz:zz:zz:zz:zz:zz:zz:zz:zz:zz:zz:zz:zz:zz:zz:zz:zz:zz:" "zz:zz:zz:zz:zz:zz:zz:zz:zz:zz:zz:zz:zz"})); } } } }
346
cpp
google/quiche
null_decrypter
quiche/quic/core/crypto/null_decrypter.cc
quiche/quic/core/crypto/null_decrypter_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_NULL_DECRYPTER_H_ #define QUICHE_QUIC_CORE_CRYPTO_NULL_DECRYPTER_H_ #include <cstddef> #include <cstdint> #include "absl/numeric/int128.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/quic_decrypter.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QuicDataReader; class QUICHE_EXPORT NullDecrypter : public QuicDecrypter { public: explicit NullDecrypter(Perspective perspective); NullDecrypter(const NullDecrypter&) = delete; NullDecrypter& operator=(const NullDecrypter&) = delete; ~NullDecrypter() override {} bool SetKey(absl::string_view key) override; bool SetNoncePrefix(absl::string_view nonce_prefix) override; bool SetIV(absl::string_view iv) override; bool SetHeaderProtectionKey(absl::string_view key) override; bool SetPreliminaryKey(absl::string_view key) override; bool SetDiversificationNonce(const DiversificationNonce& nonce) override; bool DecryptPacket(uint64_t packet_number, absl::string_view associated_data, absl::string_view ciphertext, char* output, size_t* output_length, size_t max_output_length) override; std::string GenerateHeaderProtectionMask( QuicDataReader* sample_reader) override; size_t GetKeySize() const override; size_t GetNoncePrefixSize() const override; size_t GetIVSize() const override; absl::string_view GetKey() const override; absl::string_view GetNoncePrefix() const override; uint32_t cipher_id() const override; QuicPacketCount GetIntegrityLimit() const override; private: bool ReadHash(QuicDataReader* reader, absl::uint128* hash); absl::uint128 ComputeHash(absl::string_view data1, absl::string_view data2) const; Perspective perspective_; }; } #endif #include "quiche/quic/core/crypto/null_decrypter.h" #include <cstdint> #include <limits> #include <string> #include "absl/numeric/int128.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_data_reader.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/common/quiche_endian.h" namespace quic { NullDecrypter::NullDecrypter(Perspective perspective) : perspective_(perspective) {} bool NullDecrypter::SetKey(absl::string_view key) { return key.empty(); } bool NullDecrypter::SetNoncePrefix(absl::string_view nonce_prefix) { return nonce_prefix.empty(); } bool NullDecrypter::SetIV(absl::string_view iv) { return iv.empty(); } bool NullDecrypter::SetHeaderProtectionKey(absl::string_view key) { return key.empty(); } bool NullDecrypter::SetPreliminaryKey(absl::string_view ) { QUIC_BUG(quic_bug_10652_1) << "Should not be called"; return false; } bool NullDecrypter::SetDiversificationNonce( const DiversificationNonce& ) { QUIC_BUG(quic_bug_10652_2) << "Should not be called"; return true; } bool NullDecrypter::DecryptPacket(uint64_t , absl::string_view associated_data, absl::string_view ciphertext, char* output, size_t* output_length, size_t max_output_length) { QuicDataReader reader(ciphertext.data(), ciphertext.length(), quiche::HOST_BYTE_ORDER); absl::uint128 hash; if (!ReadHash(&reader, &hash)) { return false; } absl::string_view plaintext = reader.ReadRemainingPayload(); if (plaintext.length() > max_output_length) { QUIC_BUG(quic_bug_10652_3) << "Output buffer must be larger than the plaintext."; return false; } if (hash != ComputeHash(associated_data, plaintext)) { return false; } memcpy(output, plaintext.data(), plaintext.length()); *output_length = plaintext.length(); return true; } std::string NullDecrypter::GenerateHeaderProtectionMask( QuicDataReader* ) { return std::string(5, 0); } size_t NullDecrypter::GetKeySize() const { return 0; } size_t NullDecrypter::GetNoncePrefixSize() const { return 0; } size_t NullDecrypter::GetIVSize() const { return 0; } absl::string_view NullDecrypter::GetKey() const { return absl::string_view(); } absl::string_view NullDecrypter::GetNoncePrefix() const { return absl::string_view(); } uint32_t NullDecrypter::cipher_id() const { return 0; } QuicPacketCount NullDecrypter::GetIntegrityLimit() const { return std::numeric_limits<QuicPacketCount>::max(); } bool NullDecrypter::ReadHash(QuicDataReader* reader, absl::uint128* hash) { uint64_t lo; uint32_t hi; if (!reader->ReadUInt64(&lo) || !reader->ReadUInt32(&hi)) { return false; } *hash = absl::MakeUint128(hi, lo); return true; } absl::uint128 NullDecrypter::ComputeHash(const absl::string_view data1, const absl::string_view data2) const { absl::uint128 correct_hash; if (perspective_ == Perspective::IS_CLIENT) { correct_hash = QuicUtils::FNV1a_128_Hash_Three(data1, data2, "Server"); } else { correct_hash = QuicUtils::FNV1a_128_Hash_Three(data1, data2, "Client"); } absl::uint128 mask = absl::MakeUint128(UINT64_C(0x0), UINT64_C(0xffffffff)); mask <<= 96; correct_hash &= ~mask; return correct_hash; } }
#include "quiche/quic/core/crypto/null_decrypter.h" #include "absl/base/macros.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { namespace test { class NullDecrypterTest : public QuicTestWithParam<bool> {}; TEST_F(NullDecrypterTest, DecryptClient) { unsigned char expected[] = { 0x97, 0xdc, 0x27, 0x2f, 0x18, 0xa8, 0x56, 0x73, 0xdf, 0x8d, 0x1d, 0xd0, 'g', 'o', 'o', 'd', 'b', 'y', 'e', '!', }; const char* data = reinterpret_cast<const char*>(expected); size_t len = ABSL_ARRAYSIZE(expected); NullDecrypter decrypter(Perspective::IS_SERVER); char buffer[256]; size_t length = 0; ASSERT_TRUE(decrypter.DecryptPacket( 0, "hello world!", absl::string_view(data, len), buffer, &length, 256)); EXPECT_LT(0u, length); EXPECT_EQ("goodbye!", absl::string_view(buffer, length)); } TEST_F(NullDecrypterTest, DecryptServer) { unsigned char expected[] = { 0x63, 0x5e, 0x08, 0x03, 0x32, 0x80, 0x8f, 0x73, 0xdf, 0x8d, 0x1d, 0x1a, 'g', 'o', 'o', 'd', 'b', 'y', 'e', '!', }; const char* data = reinterpret_cast<const char*>(expected); size_t len = ABSL_ARRAYSIZE(expected); NullDecrypter decrypter(Perspective::IS_CLIENT); char buffer[256]; size_t length = 0; ASSERT_TRUE(decrypter.DecryptPacket( 0, "hello world!", absl::string_view(data, len), buffer, &length, 256)); EXPECT_LT(0u, length); EXPECT_EQ("goodbye!", absl::string_view(buffer, length)); } TEST_F(NullDecrypterTest, BadHash) { unsigned char expected[] = { 0x46, 0x11, 0xea, 0x5f, 0xcf, 0x1d, 0x66, 0x5b, 0xba, 0xf0, 0xbc, 0xfd, 'g', 'o', 'o', 'd', 'b', 'y', 'e', '!', }; const char* data = reinterpret_cast<const char*>(expected); size_t len = ABSL_ARRAYSIZE(expected); NullDecrypter decrypter(Perspective::IS_CLIENT); char buffer[256]; size_t length = 0; ASSERT_FALSE(decrypter.DecryptPacket( 0, "hello world!", absl::string_view(data, len), buffer, &length, 256)); } TEST_F(NullDecrypterTest, ShortInput) { unsigned char expected[] = { 0x46, 0x11, 0xea, 0x5f, 0xcf, 0x1d, 0x66, 0x5b, 0xba, 0xf0, 0xbc, }; const char* data = reinterpret_cast<const char*>(expected); size_t len = ABSL_ARRAYSIZE(expected); NullDecrypter decrypter(Perspective::IS_CLIENT); char buffer[256]; size_t length = 0; ASSERT_FALSE(decrypter.DecryptPacket( 0, "hello world!", absl::string_view(data, len), buffer, &length, 256)); } } }
347
cpp
google/quiche
transport_parameters
quiche/quic/core/crypto/transport_parameters.cc
quiche/quic/core/crypto/transport_parameters_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_TRANSPORT_PARAMETERS_H_ #define QUICHE_QUIC_CORE_CRYPTO_TRANSPORT_PARAMETERS_H_ #include <memory> #include <optional> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_data_reader.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/core/quic_tag.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_socket_address.h" namespace quic { struct QUICHE_EXPORT TransportParameters { enum TransportParameterId : uint64_t; using ParameterMap = absl::flat_hash_map<TransportParameterId, std::string>; class QUICHE_EXPORT IntegerParameter { public: IntegerParameter() = delete; IntegerParameter& operator=(const IntegerParameter&) = delete; void set_value(uint64_t value); uint64_t value() const; bool IsValid() const; bool Write(QuicDataWriter* writer) const; bool Read(QuicDataReader* reader, std::string* error_details); friend QUICHE_EXPORT std::ostream& operator<<( std::ostream& os, const IntegerParameter& param); private: friend struct TransportParameters; explicit IntegerParameter(TransportParameterId param_id); IntegerParameter(TransportParameterId param_id, uint64_t default_value, uint64_t min_value, uint64_t max_value); IntegerParameter(const IntegerParameter& other) = default; IntegerParameter(IntegerParameter&& other) = default; std::string ToString(bool for_use_in_list) const; TransportParameterId param_id_; uint64_t value_; const uint64_t default_value_; const uint64_t min_value_; const uint64_t max_value_; bool has_been_read_; }; struct QUICHE_EXPORT PreferredAddress { PreferredAddress(); PreferredAddress(const PreferredAddress& other) = default; PreferredAddress(PreferredAddress&& other) = default; ~PreferredAddress(); bool operator==(const PreferredAddress& rhs) const; bool operator!=(const PreferredAddress& rhs) const; QuicSocketAddress ipv4_socket_address; QuicSocketAddress ipv6_socket_address; QuicConnectionId connection_id; std::vector<uint8_t> stateless_reset_token; std::string ToString() const; friend QUICHE_EXPORT std::ostream& operator<<( std::ostream& os, const TransportParameters& params); }; struct QUICHE_EXPORT LegacyVersionInformation { LegacyVersionInformation(); LegacyVersionInformation(const LegacyVersionInformation& other) = default; LegacyVersionInformation& operator=(const LegacyVersionInformation& other) = default; LegacyVersionInformation& operator=(LegacyVersionInformation&& other) = default; LegacyVersionInformation(LegacyVersionInformation&& other) = default; ~LegacyVersionInformation() = default; bool operator==(const LegacyVersionInformation& rhs) const; bool operator!=(const LegacyVersionInformation& rhs) const; QuicVersionLabel version; QuicVersionLabelVector supported_versions; std::string ToString() const; friend QUICHE_EXPORT std::ostream& operator<<( std::ostream& os, const LegacyVersionInformation& legacy_version_information); }; struct QUICHE_EXPORT VersionInformation { VersionInformation(); VersionInformation(const VersionInformation& other) = default; VersionInformation& operator=(const VersionInformation& other) = default; VersionInformation& operator=(VersionInformation&& other) = default; VersionInformation(VersionInformation&& other) = default; ~VersionInformation() = default; bool operator==(const VersionInformation& rhs) const; bool operator!=(const VersionInformation& rhs) const; QuicVersionLabel chosen_version; QuicVersionLabelVector other_versions; std::string ToString() const; friend QUICHE_EXPORT std::ostream& operator<<( std::ostream& os, const VersionInformation& version_information); }; TransportParameters(); TransportParameters(const TransportParameters& other); ~TransportParameters(); bool operator==(const TransportParameters& rhs) const; bool operator!=(const TransportParameters& rhs) const; Perspective perspective; std::optional<LegacyVersionInformation> legacy_version_information; std::optional<VersionInformation> version_information; std::optional<QuicConnectionId> original_destination_connection_id; IntegerParameter max_idle_timeout_ms; std::vector<uint8_t> stateless_reset_token; IntegerParameter max_udp_payload_size; IntegerParameter initial_max_data; IntegerParameter initial_max_stream_data_bidi_local; IntegerParameter initial_max_stream_data_bidi_remote; IntegerParameter initial_max_stream_data_uni; IntegerParameter initial_max_streams_bidi; IntegerParameter initial_max_streams_uni; IntegerParameter ack_delay_exponent; IntegerParameter max_ack_delay; IntegerParameter min_ack_delay_us; bool disable_active_migration; std::unique_ptr<PreferredAddress> preferred_address; IntegerParameter active_connection_id_limit; std::optional<QuicConnectionId> initial_source_connection_id; std::optional<QuicConnectionId> retry_source_connection_id; IntegerParameter max_datagram_frame_size; IntegerParameter initial_round_trip_time_us; std::optional<std::string> google_handshake_message; std::optional<QuicTagVector> google_connection_options; bool AreValid(std::string* error_details) const; ParameterMap custom_parameters; std::string ToString() const; friend QUICHE_EXPORT std::ostream& operator<<( std::ostream& os, const TransportParameters& params); }; QUICHE_EXPORT bool SerializeTransportParameters(const TransportParameters& in, std::vector<uint8_t>* out); QUICHE_EXPORT bool ParseTransportParameters(ParsedQuicVersion version, Perspective perspective, const uint8_t* in, size_t in_len, TransportParameters* out, std::string* error_details); QUICHE_EXPORT bool SerializeTransportParametersForTicket( const TransportParameters& in, const std::vector<uint8_t>& application_data, std::vector<uint8_t>* out); QUICHE_EXPORT void DegreaseTransportParameters(TransportParameters& parameters); } #endif #include "quiche/quic/core/crypto/transport_parameters.h" #include <algorithm> #include <cstdint> #include <cstring> #include <forward_list> #include <memory> #include <ostream> #include <string> #include <utility> #include <vector> #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "openssl/digest.h" #include "openssl/sha.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_data_reader.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_ip_address.h" namespace quic { enum TransportParameters::TransportParameterId : uint64_t { kOriginalDestinationConnectionId = 0, kMaxIdleTimeout = 1, kStatelessResetToken = 2, kMaxPacketSize = 3, kInitialMaxData = 4, kInitialMaxStreamDataBidiLocal = 5, kInitialMaxStreamDataBidiRemote = 6, kInitialMaxStreamDataUni = 7, kInitialMaxStreamsBidi = 8, kInitialMaxStreamsUni = 9, kAckDelayExponent = 0xa, kMaxAckDelay = 0xb, kDisableActiveMigration = 0xc, kPreferredAddress = 0xd, kActiveConnectionIdLimit = 0xe, kInitialSourceConnectionId = 0xf, kRetrySourceConnectionId = 0x10, kMaxDatagramFrameSize = 0x20, kGoogleHandshakeMessage = 0x26ab, kInitialRoundTripTime = 0x3127, kGoogleConnectionOptions = 0x3128, kGoogleQuicVersion = 0x4752, kMinAckDelay = 0xDE1A, kVersionInformation = 0xFF73DB, }; namespace { constexpr QuicVersionLabel kReservedVersionMask = 0x0f0f0f0f; constexpr QuicVersionLabel kReservedVersionBits = 0x0a0a0a0a; constexpr uint64_t kMinMaxPacketSizeTransportParam = 1200; constexpr uint64_t kMaxAckDelayExponentTransportParam = 20; constexpr uint64_t kDefaultAckDelayExponentTransportParam = 3; constexpr uint64_t kMaxMaxAckDelayTransportParam = 16383; constexpr uint64_t kDefaultMaxAckDelayTransportParam = 25; constexpr uint64_t kMinActiveConnectionIdLimitTransportParam = 2; constexpr uint64_t kDefaultActiveConnectionIdLimitTransportParam = 2; std::string TransportParameterIdToString( TransportParameters::TransportParameterId param_id) { switch (param_id) { case TransportParameters::kOriginalDestinationConnectionId: return "original_destination_connection_id"; case TransportParameters::kMaxIdleTimeout: return "max_idle_timeout"; case TransportParameters::kStatelessResetToken: return "stateless_reset_token"; case TransportParameters::kMaxPacketSize: return "max_udp_payload_size"; case TransportParameters::kInitialMaxData: return "initial_max_data"; case TransportParameters::kInitialMaxStreamDataBidiLocal: return "initial_max_stream_data_bidi_local"; case TransportParameters::kInitialMaxStreamDataBidiRemote: return "initial_max_stream_data_bidi_remote"; case TransportParameters::kInitialMaxStreamDataUni: return "initial_max_stream_data_uni"; case TransportParameters::kInitialMaxStreamsBidi: return "initial_max_streams_bidi"; case TransportParameters::kInitialMaxStreamsUni: return "initial_max_streams_uni"; case TransportParameters::kAckDelayExponent: return "ack_delay_exponent"; case TransportParameters::kMaxAckDelay: return "max_ack_delay"; case TransportParameters::kDisableActiveMigration: return "disable_active_migration"; case TransportParameters::kPreferredAddress: return "preferred_address"; case TransportParameters::kActiveConnectionIdLimit: return "active_connection_id_limit"; case TransportParameters::kInitialSourceConnectionId: return "initial_source_connection_id"; case TransportParameters::kRetrySourceConnectionId: return "retry_source_connection_id"; case TransportParameters::kMaxDatagramFrameSize: return "max_datagram_frame_size"; case TransportParameters::kGoogleHandshakeMessage: return "google_handshake_message"; case TransportParameters::kInitialRoundTripTime: return "initial_round_trip_time"; case TransportParameters::kGoogleConnectionOptions: return "google_connection_options"; case TransportParameters::kGoogleQuicVersion: return "google-version"; case TransportParameters::kMinAckDelay: return "min_ack_delay_us"; case TransportParameters::kVersionInformation: return "version_information"; } return absl::StrCat("Unknown(", param_id, ")"); } bool TransportParameterIdIsKnown( TransportParameters::TransportParameterId param_id) { switch (param_id) { case TransportParameters::kOriginalDestinationConnectionId: case TransportParameters::kMaxIdleTimeout: case TransportParameters::kStatelessResetToken: case TransportParameters::kMaxPacketSize: case TransportParameters::kInitialMaxData: case TransportParameters::kInitialMaxStreamDataBidiLocal: case TransportParameters::kInitialMaxStreamDataBidiRemote: case TransportParameters::kInitialMaxStreamDataUni: case TransportParameters::kInitialMaxStreamsBidi: case TransportParameters::kInitialMaxStreamsUni: case TransportParameters::kAckDelayExponent: case TransportParameters::kMaxAckDelay: case TransportParameters::kDisableActiveMigration: case TransportParameters::kPreferredAddress: case TransportParameters::kActiveConnectionIdLimit: case TransportParameters::kInitialSourceConnectionId: case TransportParameters::kRetrySourceConnectionId: case TransportParameters::kMaxDatagramFrameSize: case TransportParameters::kGoogleHandshakeMessage: case TransportParameters::kInitialRoundTripTime: case TransportParameters::kGoogleConnectionOptions: case TransportParameters::kGoogleQuicVersion: case TransportParameters::kMinAckDelay: case TransportParameters::kVersionInformation: return true; } return false; } } TransportParameters::IntegerParameter::IntegerParameter( TransportParameters::TransportParameterId param_id, uint64_t default_value, uint64_t min_value, uint64_t max_value) : param_id_(param_id), value_(default_value), default_value_(default_value), min_value_(min_value), max_value_(max_value), has_been_read_(false) { QUICHE_DCHECK_LE(min_value, default_value); QUICHE_DCHECK_LE(default_value, max_value); QUICHE_DCHECK_LE(max_value, quiche::kVarInt62MaxValue); } TransportParameters::IntegerParameter::IntegerParameter( TransportParameters::TransportParameterId param_id) : TransportParameters::IntegerParameter::IntegerParameter( param_id, 0, 0, quiche::kVarInt62MaxValue) {} void TransportParameters::IntegerParameter::set_value(uint64_t value) { value_ = value; } uint64_t TransportParameters::IntegerParameter::value() const { return value_; } bool TransportParameters::IntegerParameter::IsValid() const { return min_value_ <= value_ && value_ <= max_value_; } bool TransportParameters::IntegerParameter::Write( QuicDataWriter* writer) const { QUICHE_DCHECK(IsValid()); if (value_ == default_value_) { return true; } if (!writer->WriteVarInt62(param_id_)) { QUIC_BUG(quic_bug_10743_1) << "Failed to write param_id for " << *this; return false; } const quiche::QuicheVariableLengthIntegerLength value_length = QuicDataWriter::GetVarInt62Len(value_); if (!writer->WriteVarInt62(value_length)) { QUIC_BUG(quic_bug_10743_2) << "Failed to write value_length for " << *this; return false; } if (!writer->WriteVarInt62WithForcedLength(value_, value_length)) { QUIC_BUG(quic_bug_10743_3) << "Failed to write value for " << *this; return false; } return true; } bool TransportParameters::IntegerParameter::Read(QuicDataReader* reader, std::string* error_details) { if (has_been_read_) { *error_details = "Received a second " + TransportParameterIdToString(param_id_); return false; } has_been_read_ = true; if (!reader->ReadVarInt62(&value_)) { *error_details = "Failed to parse value for " + TransportParameterIdToString(param_id_); return false; } if (!reader->IsDoneReading()) { *error_details = absl::StrCat("Received unexpected ", reader->BytesRemaining(), " bytes after parsing ", this->ToString(false)); return false; } return true; } std::string TransportParameters::IntegerParameter::ToString( bool for_use_in_list) const { if (for_use_in_list && value_ == default_value_) { return ""; } std::string rv = for_use_in_list ? " " : ""; absl::StrAppend(&rv, TransportParameterIdToString(param_id_), " ", value_); if (!IsValid()) { rv += " (Invalid)"; } return rv; } std::ostream& operator<<(std::ostream& os, const TransportParameters::IntegerParameter& param) { os << param.ToString(false); return os; } TransportParameters::PreferredAddress::PreferredAddress() : ipv4_socket_address(QuicIpAddress::Any4(), 0), ipv6_socket_address(QuicIpAddress::Any6(), 0), connection_id(EmptyQuicConnectionId()), stateless_reset_token(kStatelessResetTokenLength, 0) {} TransportParameters::PreferredAddress::~PreferredAddress() {} bool TransportParameters::PreferredAddress::operator==( const PreferredAddress& rhs) const { return ipv4_socket_address == rhs.ipv4_socket_address && ipv6_socket_address == rhs.ipv6_socket_address && connection_id == rhs.connection_id && stateless_reset_token == rhs.stateless_reset_token; } bool TransportParameters::PreferredAddress::operator!=( const PreferredAddress& rhs) const { return !(*this == rhs); } std::ostream& operator<<( std::ostream& os, const TransportParameters::PreferredAddress& preferred_address) { os << preferred_address.ToString(); return os; } std::string TransportParameters::PreferredAddress::ToString() const { return "[" + ipv4_socket_address.ToString() + " " + ipv6_socket_address.ToString() + " connection_id " + connection_id.ToString() + " stateless_reset_token " + absl::BytesToHexString(absl::string_view( reinterpret_cast<const char*>(stateless_reset_token.data()), stateless_reset_token.size())) + "]"; } TransportParameters::LegacyVersionInformation::LegacyVersionInformation() : version(0) {} bool TransportParameters::LegacyVersionInformation::operator==( const LegacyVersionInformation& rhs) const { return version == rhs.version && supported_versions == rhs.supported_versions; } bool TransportParameters::LegacyVersionInformation::operator!=( const LegacyVersionInformation& rhs) const { return !(*this == rhs); } std::string TransportParameters::LegacyVersionInformation::ToString() const { std::string rv = absl::StrCat("legacy[version ", QuicVersionLabelToString(version)); if (!supported_versions.empty()) { absl::StrAppend(&rv, " supported_versions " + QuicVersionLabelVectorToString(supported_versions)); } absl::StrAppend(&rv, "]"); return rv; } std::ostream& operator<<(std::ostream& os, const TransportParameters::LegacyVersionInformation& legacy_version_information) { os << legacy_version_information.ToString(); return os; } TransportParameters::VersionInformation::VersionInformation() : chosen_version(0) {} bool TransportParameters::VersionInformation::operator==( const VersionInformation& rhs) const { return chosen_version == rhs.chosen_version && other_versions == rhs.other_versions; } bool TransportParameters::VersionInformation::operator!=( const VersionInformation& rhs) const { return !(*this == rhs); } std::string TransportParameters::VersionInformation::ToString() const { std::string rv = absl::StrCat("[chosen_version ", QuicVersionLabelToString(chosen_version)); if (!other_versions.empty()) { absl::StrAppend(&rv, " other_versions " + QuicVersionLabelVectorToString(other_versions)); } absl::StrAppend(&rv, "]"); return rv; } std::ostream& operator<<( std::ostream& os, const TransportParameters::VersionInformation& version_information) { os << version_information.ToString(); return os; } std::ostream& operator<<(std::ostream& os, const TransportParameters& params) { os << params.ToString(); return os; } std::string TransportParameters::ToString() const { std::string rv = "["; if (perspective == Perspective::IS_SERVER) { rv += "Server"; } else { rv += "Client"; } if (legacy_version_information.has_value()) { rv += " " + legacy_version_information->ToString(); } if (version_information.has_value()) { rv += " " + version_information->ToString(); } if (original_destination_connection_id.has_value()) { rv += " " + TransportParameterIdToString(kOriginalDestinationConnectionId) + " " + original_destination_connection_id->ToString(); } rv += max_idle_timeout_ms.ToString(true); if (!stateless_reset_token.empty()) { rv += " " + TransportParameterIdToString(kStatelessResetToken) + " " + absl::BytesToHexString(absl::string_view( reinterpret_cast<const char*>(stateless_reset_token.data()), stateless_reset_token.size())); } rv += max_udp_payload_size.ToString(true); rv += initial_max_data.ToString(true); rv += initial_max_stream_data_bidi_local.ToString(true); rv += initial_max_stream_data_bidi_remote.ToString(true); rv += initial_max_stream_data_uni.ToString(true); rv += initial_max_streams_bidi.ToString(true); rv += initial_max_streams_uni.ToString(true); rv += ack_delay_exponent.ToString(true); rv += max_ack_delay.ToString(true); rv += min_ack_delay_us.ToString(true); if (disable_active_migration) { rv += " " + TransportParameterIdToString(kDisableActiveMigration); } if (preferred_address) { rv += " " + TransportParameterIdToString(kPreferredAddress) + " " + preferred_address->ToString(); } rv += active_connection_id_limit.ToString(true); if (initial_source_connection_id.has_value()) { rv += " " + TransportParameterIdToString(kInitialSourceConnectionId) + " " + initial_source_connection_id->ToString(); } if (retry_source_connection_id.has_value()) { rv += " " + TransportParameterIdToString(kRetrySourceConnectionId) + " " + retry_source_connection_id->ToString(); } rv += max_datagram_frame_size.ToString(true); if (google_handshake_message.has_value()) { absl::StrAppend(&rv, " ", TransportParameterIdToString(kGoogleHandshakeMessage), " length: ", google_handshake_message->length()); } rv += initial_round_trip_time_us.ToString(true); if (google_connection_options.has_value()) { rv += " " + TransportParameterIdToString(kGoogleConnectionOptions) + " "; bool first = true; for (const QuicTag& connection_option : *google_connection_options) { if (first) { first = false; } else { rv += ","; } rv += QuicTagToString(connection_option); } } for (const auto& kv : custom_parameters) { absl::StrAppend(&rv, " 0x", absl::Hex(static_cast<uint32_t>(kv.first)), "="); static constexpr size_t kMaxPrintableLength = 32; if (kv.second.length() <= kMaxPrintableLength) { rv += absl::BytesToHexString(kv.second); } else { absl::string_view truncated(kv.second.data(), kMaxPrintableLength); rv += absl::StrCat(absl::BytesToHexString(truncated), "...(length ", kv.second.length(), ")"); } } rv += "]"; return rv; } TransportParameters::TransportParameters() : max_idle_timeout_ms(kMaxIdleTimeout), max_udp_payload_size(kMaxPacketSize, kDefaultMaxPacketSizeTransportParam, kMinMaxPacketSizeTransportParam, quiche::kVarInt62MaxValue), initial_max_data(kInitialMaxData), initial_max_stream_data_bidi_local(kInitialMaxStreamDataBidiLocal), initial_max_stream_data_bidi_remote(kInitialMaxStreamDataBidiRemote), initial_max_stream_data_uni(kInitialMaxStreamDataUni), initial_max_streams_bidi(kInitialMaxStreamsBidi), initial_max_streams_uni(kInitialMaxStreamsUni), ack_delay_exponent(kAckDelayExponent, kDefaultAckDelayExponentTransportParam, 0, kMaxAckDelayExponentTransportParam), max_ack_delay(kMaxAckDelay, kDefaultMaxAckDelayTransportParam, 0, kMaxMaxAckDelayTransportParam), min_ack_delay_us(kMinAckDelay, 0, 0, kMaxMaxAckDelayTransportParam * kNumMicrosPerMilli), disable_active_migration(false),
#include "quiche/quic/core/crypto/transport_parameters.h" #include <cstring> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_tag.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { namespace test { namespace { const QuicVersionLabel kFakeVersionLabel = 0x01234567; const QuicVersionLabel kFakeVersionLabel2 = 0x89ABCDEF; const uint64_t kFakeIdleTimeoutMilliseconds = 12012; const uint64_t kFakeInitialMaxData = 101; const uint64_t kFakeInitialMaxStreamDataBidiLocal = 2001; const uint64_t kFakeInitialMaxStreamDataBidiRemote = 2002; const uint64_t kFakeInitialMaxStreamDataUni = 3000; const uint64_t kFakeInitialMaxStreamsBidi = 21; const uint64_t kFakeInitialMaxStreamsUni = 22; const bool kFakeDisableMigration = true; const uint64_t kFakeInitialRoundTripTime = 53; const uint8_t kFakePreferredStatelessResetTokenData[16] = { 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F}; const auto kCustomParameter1 = static_cast<TransportParameters::TransportParameterId>(0xffcd); const char* kCustomParameter1Value = "foo"; const auto kCustomParameter2 = static_cast<TransportParameters::TransportParameterId>(0xff34); const char* kCustomParameter2Value = "bar"; const char kFakeGoogleHandshakeMessage[] = "01000106030392655f5230270d4964a4f99b15bbad220736d972aea97bf9ac494ead62e6"; QuicConnectionId CreateFakeOriginalDestinationConnectionId() { return TestConnectionId(0x1337); } QuicConnectionId CreateFakeInitialSourceConnectionId() { return TestConnectionId(0x2345); } QuicConnectionId CreateFakeRetrySourceConnectionId() { return TestConnectionId(0x9876); } QuicConnectionId CreateFakePreferredConnectionId() { return TestConnectionId(0xBEEF); } std::vector<uint8_t> CreateFakePreferredStatelessResetToken() { return std::vector<uint8_t>( kFakePreferredStatelessResetTokenData, kFakePreferredStatelessResetTokenData + sizeof(kFakePreferredStatelessResetTokenData)); } QuicSocketAddress CreateFakeV4SocketAddress() { QuicIpAddress ipv4_address; if (!ipv4_address.FromString("65.66.67.68")) { QUIC_LOG(FATAL) << "Failed to create IPv4 address"; return QuicSocketAddress(); } return QuicSocketAddress(ipv4_address, 0x4884); } QuicSocketAddress CreateFakeV6SocketAddress() { QuicIpAddress ipv6_address; if (!ipv6_address.FromString("6061:6263:6465:6667:6869:6A6B:6C6D:6E6F")) { QUIC_LOG(FATAL) << "Failed to create IPv6 address"; return QuicSocketAddress(); } return QuicSocketAddress(ipv6_address, 0x6336); } std::unique_ptr<TransportParameters::PreferredAddress> CreateFakePreferredAddress() { TransportParameters::PreferredAddress preferred_address; preferred_address.ipv4_socket_address = CreateFakeV4SocketAddress(); preferred_address.ipv6_socket_address = CreateFakeV6SocketAddress(); preferred_address.connection_id = CreateFakePreferredConnectionId(); preferred_address.stateless_reset_token = CreateFakePreferredStatelessResetToken(); return std::make_unique<TransportParameters::PreferredAddress>( preferred_address); } TransportParameters::LegacyVersionInformation CreateFakeLegacyVersionInformationClient() { TransportParameters::LegacyVersionInformation legacy_version_information; legacy_version_information.version = kFakeVersionLabel; return legacy_version_information; } TransportParameters::LegacyVersionInformation CreateFakeLegacyVersionInformationServer() { TransportParameters::LegacyVersionInformation legacy_version_information = CreateFakeLegacyVersionInformationClient(); legacy_version_information.supported_versions.push_back(kFakeVersionLabel); legacy_version_information.supported_versions.push_back(kFakeVersionLabel2); return legacy_version_information; } TransportParameters::VersionInformation CreateFakeVersionInformation() { TransportParameters::VersionInformation version_information; version_information.chosen_version = kFakeVersionLabel; version_information.other_versions.push_back(kFakeVersionLabel); version_information.other_versions.push_back(kFakeVersionLabel2); return version_information; } QuicTagVector CreateFakeGoogleConnectionOptions() { return {kALPN, MakeQuicTag('E', 'F', 'G', 0x00), MakeQuicTag('H', 'I', 'J', 0xff)}; } void RemoveGreaseParameters(TransportParameters* params) { std::vector<TransportParameters::TransportParameterId> grease_params; for (const auto& kv : params->custom_parameters) { if (kv.first % 31 == 27) { grease_params.push_back(kv.first); } } EXPECT_EQ(grease_params.size(), 1u); for (TransportParameters::TransportParameterId param_id : grease_params) { params->custom_parameters.erase(param_id); } if (params->version_information.has_value()) { QuicVersionLabelVector& other_versions = params->version_information.value().other_versions; for (auto it = other_versions.begin(); it != other_versions.end();) { if ((*it & 0x0f0f0f0f) == 0x0a0a0a0a) { it = other_versions.erase(it); } else { ++it; } } } } } class TransportParametersTest : public QuicTestWithParam<ParsedQuicVersion> { protected: TransportParametersTest() : version_(GetParam()) {} ParsedQuicVersion version_; }; INSTANTIATE_TEST_SUITE_P(TransportParametersTests, TransportParametersTest, ::testing::ValuesIn(AllSupportedVersionsWithTls()), ::testing::PrintToStringParamName()); TEST_P(TransportParametersTest, Comparator) { TransportParameters orig_params; TransportParameters new_params; orig_params.perspective = Perspective::IS_CLIENT; new_params.perspective = Perspective::IS_SERVER; EXPECT_NE(orig_params, new_params); EXPECT_FALSE(orig_params == new_params); EXPECT_TRUE(orig_params != new_params); new_params.perspective = Perspective::IS_CLIENT; orig_params.legacy_version_information = CreateFakeLegacyVersionInformationClient(); new_params.legacy_version_information = CreateFakeLegacyVersionInformationClient(); orig_params.version_information = CreateFakeVersionInformation(); new_params.version_information = CreateFakeVersionInformation(); orig_params.disable_active_migration = true; new_params.disable_active_migration = true; EXPECT_EQ(orig_params, new_params); EXPECT_TRUE(orig_params == new_params); EXPECT_FALSE(orig_params != new_params); orig_params.legacy_version_information.value().supported_versions.push_back( kFakeVersionLabel); new_params.legacy_version_information.value().supported_versions.push_back( kFakeVersionLabel2); EXPECT_NE(orig_params, new_params); EXPECT_FALSE(orig_params == new_params); EXPECT_TRUE(orig_params != new_params); new_params.legacy_version_information.value().supported_versions.pop_back(); new_params.legacy_version_information.value().supported_versions.push_back( kFakeVersionLabel); orig_params.stateless_reset_token = CreateStatelessResetTokenForTest(); new_params.stateless_reset_token = CreateStatelessResetTokenForTest(); EXPECT_EQ(orig_params, new_params); EXPECT_TRUE(orig_params == new_params); EXPECT_FALSE(orig_params != new_params); orig_params.max_udp_payload_size.set_value(kMaxPacketSizeForTest); new_params.max_udp_payload_size.set_value(kMaxPacketSizeForTest + 1); EXPECT_NE(orig_params, new_params); EXPECT_FALSE(orig_params == new_params); EXPECT_TRUE(orig_params != new_params); new_params.max_udp_payload_size.set_value(kMaxPacketSizeForTest); EXPECT_EQ(orig_params, new_params); EXPECT_TRUE(orig_params == new_params); EXPECT_FALSE(orig_params != new_params); orig_params.preferred_address = CreateFakePreferredAddress(); EXPECT_NE(orig_params, new_params); EXPECT_FALSE(orig_params == new_params); EXPECT_TRUE(orig_params != new_params); new_params.preferred_address = CreateFakePreferredAddress(); EXPECT_EQ(orig_params, new_params); EXPECT_TRUE(orig_params == new_params); EXPECT_FALSE(orig_params != new_params); orig_params.custom_parameters[kCustomParameter1] = kCustomParameter1Value; orig_params.custom_parameters[kCustomParameter2] = kCustomParameter2Value; new_params.custom_parameters[kCustomParameter2] = kCustomParameter2Value; new_params.custom_parameters[kCustomParameter1] = kCustomParameter1Value; EXPECT_EQ(orig_params, new_params); EXPECT_TRUE(orig_params == new_params); EXPECT_FALSE(orig_params != new_params); orig_params.initial_source_connection_id = CreateFakeInitialSourceConnectionId(); new_params.initial_source_connection_id = std::nullopt; EXPECT_NE(orig_params, new_params); EXPECT_FALSE(orig_params == new_params); EXPECT_TRUE(orig_params != new_params); new_params.initial_source_connection_id = TestConnectionId(0xbadbad); EXPECT_NE(orig_params, new_params); EXPECT_FALSE(orig_params == new_params); EXPECT_TRUE(orig_params != new_params); new_params.initial_source_connection_id = CreateFakeInitialSourceConnectionId(); EXPECT_EQ(orig_params, new_params); EXPECT_TRUE(orig_params == new_params); EXPECT_FALSE(orig_params != new_params); } TEST_P(TransportParametersTest, CopyConstructor) { TransportParameters orig_params; orig_params.perspective = Perspective::IS_CLIENT; orig_params.legacy_version_information = CreateFakeLegacyVersionInformationClient(); orig_params.version_information = CreateFakeVersionInformation(); orig_params.original_destination_connection_id = CreateFakeOriginalDestinationConnectionId(); orig_params.max_idle_timeout_ms.set_value(kFakeIdleTimeoutMilliseconds); orig_params.stateless_reset_token = CreateStatelessResetTokenForTest(); orig_params.max_udp_payload_size.set_value(kMaxPacketSizeForTest); orig_params.initial_max_data.set_value(kFakeInitialMaxData); orig_params.initial_max_stream_data_bidi_local.set_value( kFakeInitialMaxStreamDataBidiLocal); orig_params.initial_max_stream_data_bidi_remote.set_value( kFakeInitialMaxStreamDataBidiRemote); orig_params.initial_max_stream_data_uni.set_value( kFakeInitialMaxStreamDataUni); orig_params.initial_max_streams_bidi.set_value(kFakeInitialMaxStreamsBidi); orig_params.initial_max_streams_uni.set_value(kFakeInitialMaxStreamsUni); orig_params.ack_delay_exponent.set_value(kAckDelayExponentForTest); orig_params.max_ack_delay.set_value(kMaxAckDelayForTest); orig_params.min_ack_delay_us.set_value(kMinAckDelayUsForTest); orig_params.disable_active_migration = kFakeDisableMigration; orig_params.preferred_address = CreateFakePreferredAddress(); orig_params.active_connection_id_limit.set_value( kActiveConnectionIdLimitForTest); orig_params.initial_source_connection_id = CreateFakeInitialSourceConnectionId(); orig_params.retry_source_connection_id = CreateFakeRetrySourceConnectionId(); orig_params.initial_round_trip_time_us.set_value(kFakeInitialRoundTripTime); std::string google_handshake_message; ASSERT_TRUE(absl::HexStringToBytes(kFakeGoogleHandshakeMessage, &google_handshake_message)); orig_params.google_handshake_message = std::move(google_handshake_message); orig_params.google_connection_options = CreateFakeGoogleConnectionOptions(); orig_params.custom_parameters[kCustomParameter1] = kCustomParameter1Value; orig_params.custom_parameters[kCustomParameter2] = kCustomParameter2Value; TransportParameters new_params(orig_params); EXPECT_EQ(new_params, orig_params); } TEST_P(TransportParametersTest, RoundTripClient) { TransportParameters orig_params; orig_params.perspective = Perspective::IS_CLIENT; orig_params.legacy_version_information = CreateFakeLegacyVersionInformationClient(); orig_params.version_information = CreateFakeVersionInformation(); orig_params.max_idle_timeout_ms.set_value(kFakeIdleTimeoutMilliseconds); orig_params.max_udp_payload_size.set_value(kMaxPacketSizeForTest); orig_params.initial_max_data.set_value(kFakeInitialMaxData); orig_params.initial_max_stream_data_bidi_local.set_value( kFakeInitialMaxStreamDataBidiLocal); orig_params.initial_max_stream_data_bidi_remote.set_value( kFakeInitialMaxStreamDataBidiRemote); orig_params.initial_max_stream_data_uni.set_value( kFakeInitialMaxStreamDataUni); orig_params.initial_max_streams_bidi.set_value(kFakeInitialMaxStreamsBidi); orig_params.initial_max_streams_uni.set_value(kFakeInitialMaxStreamsUni); orig_params.ack_delay_exponent.set_value(kAckDelayExponentForTest); orig_params.max_ack_delay.set_value(kMaxAckDelayForTest); orig_params.min_ack_delay_us.set_value(kMinAckDelayUsForTest); orig_params.disable_active_migration = kFakeDisableMigration; orig_params.active_connection_id_limit.set_value( kActiveConnectionIdLimitForTest); orig_params.initial_source_connection_id = CreateFakeInitialSourceConnectionId(); orig_params.initial_round_trip_time_us.set_value(kFakeInitialRoundTripTime); std::string google_handshake_message; ASSERT_TRUE(absl::HexStringToBytes(kFakeGoogleHandshakeMessage, &google_handshake_message)); orig_params.google_handshake_message = std::move(google_handshake_message); orig_params.google_connection_options = CreateFakeGoogleConnectionOptions(); orig_params.custom_parameters[kCustomParameter1] = kCustomParameter1Value; orig_params.custom_parameters[kCustomParameter2] = kCustomParameter2Value; std::vector<uint8_t> serialized; ASSERT_TRUE(SerializeTransportParameters(orig_params, &serialized)); TransportParameters new_params; std::string error_details; ASSERT_TRUE(ParseTransportParameters(version_, Perspective::IS_CLIENT, serialized.data(), serialized.size(), &new_params, &error_details)) << error_details; EXPECT_TRUE(error_details.empty()); RemoveGreaseParameters(&new_params); EXPECT_EQ(new_params, orig_params); } TEST_P(TransportParametersTest, RoundTripServer) { TransportParameters orig_params; orig_params.perspective = Perspective::IS_SERVER; orig_params.legacy_version_information = CreateFakeLegacyVersionInformationServer(); orig_params.version_information = CreateFakeVersionInformation(); orig_params.original_destination_connection_id = CreateFakeOriginalDestinationConnectionId(); orig_params.max_idle_timeout_ms.set_value(kFakeIdleTimeoutMilliseconds); orig_params.stateless_reset_token = CreateStatelessResetTokenForTest(); orig_params.max_udp_payload_size.set_value(kMaxPacketSizeForTest); orig_params.initial_max_data.set_value(kFakeInitialMaxData); orig_params.initial_max_stream_data_bidi_local.set_value( kFakeInitialMaxStreamDataBidiLocal); orig_params.initial_max_stream_data_bidi_remote.set_value( kFakeInitialMaxStreamDataBidiRemote); orig_params.initial_max_stream_data_uni.set_value( kFakeInitialMaxStreamDataUni); orig_params.initial_max_streams_bidi.set_value(kFakeInitialMaxStreamsBidi); orig_params.initial_max_streams_uni.set_value(kFakeInitialMaxStreamsUni); orig_params.ack_delay_exponent.set_value(kAckDelayExponentForTest); orig_params.max_ack_delay.set_value(kMaxAckDelayForTest); orig_params.min_ack_delay_us.set_value(kMinAckDelayUsForTest); orig_params.disable_active_migration = kFakeDisableMigration; orig_params.preferred_address = CreateFakePreferredAddress(); orig_params.active_connection_id_limit.set_value( kActiveConnectionIdLimitForTest); orig_params.initial_source_connection_id = CreateFakeInitialSourceConnectionId(); orig_params.retry_source_connection_id = CreateFakeRetrySourceConnectionId(); orig_params.google_connection_options = CreateFakeGoogleConnectionOptions(); std::vector<uint8_t> serialized; ASSERT_TRUE(SerializeTransportParameters(orig_params, &serialized)); TransportParameters new_params; std::string error_details; ASSERT_TRUE(ParseTransportParameters(version_, Perspective::IS_SERVER, serialized.data(), serialized.size(), &new_params, &error_details)) << error_details; EXPECT_TRUE(error_details.empty()); RemoveGreaseParameters(&new_params); EXPECT_EQ(new_params, orig_params); } TEST_P(TransportParametersTest, AreValid) { { TransportParameters params; std::string error_details; params.perspective = Perspective::IS_CLIENT; EXPECT_TRUE(params.AreValid(&error_details)); EXPECT_TRUE(error_details.empty()); } { TransportParameters params; std::string error_details; params.perspective = Perspective::IS_CLIENT; EXPECT_TRUE(params.AreValid(&error_details)); EXPECT_TRUE(error_details.empty()); params.max_idle_timeout_ms.set_value(kFakeIdleTimeoutMilliseconds); EXPECT_TRUE(params.AreValid(&error_details)); EXPECT_TRUE(error_details.empty()); params.max_idle_timeout_ms.set_value(601000); EXPECT_TRUE(params.AreValid(&error_details)); EXPECT_TRUE(error_details.empty()); } { TransportParameters params; std::string error_details; params.perspective = Perspective::IS_CLIENT; EXPECT_TRUE(params.AreValid(&error_details)); EXPECT_TRUE(error_details.empty()); params.max_udp_payload_size.set_value(1200); EXPECT_TRUE(params.AreValid(&error_details)); EXPECT_TRUE(error_details.empty()); params.max_udp_payload_size.set_value(65535); EXPECT_TRUE(params.AreValid(&error_details)); EXPECT_TRUE(error_details.empty()); params.max_udp_payload_size.set_value(9999999); EXPECT_TRUE(params.AreValid(&error_details)); EXPECT_TRUE(error_details.empty()); params.max_udp_payload_size.set_value(0); error_details = ""; EXPECT_FALSE(params.AreValid(&error_details)); EXPECT_EQ(error_details, "Invalid transport parameters [Client max_udp_payload_size 0 " "(Invalid)]"); params.max_udp_payload_size.set_value(1199); error_details = ""; EXPECT_FALSE(params.AreValid(&error_details)); EXPECT_EQ(error_details, "Invalid transport parameters [Client max_udp_payload_size 1199 " "(Invalid)]"); } { TransportParameters params; std::string error_details; params.perspective = Perspective::IS_CLIENT; EXPECT_TRUE(params.AreValid(&error_details)); EXPECT_TRUE(error_details.empty()); params.ack_delay_exponent.set_value(0); EXPECT_TRUE(params.AreValid(&error_details)); EXPECT_TRUE(error_details.empty()); params.ack_delay_exponent.set_value(20); EXPECT_TRUE(params.AreValid(&error_details)); EXPECT_TRUE(error_details.empty()); params.ack_delay_exponent.set_value(21); EXPECT_FALSE(params.AreValid(&error_details)); EXPECT_EQ(error_details, "Invalid transport parameters [Client ack_delay_exponent 21 " "(Invalid)]"); } { TransportParameters params; std::string error_details; params.perspective = Perspective::IS_CLIENT; EXPECT_TRUE(params.AreValid(&error_details)); EXPECT_TRUE(error_details.empty()); params.active_connection_id_limit.set_value(2); EXPECT_TRUE(params.AreValid(&error_details)); EXPECT_TRUE(error_details.empty()); params.active_connection_id_limit.set_value(999999); EXPECT_TRUE(params.AreValid(&error_details)); EXPECT_TRUE(error_details.empty()); params.active_connection_id_limit.set_value(1); EXPECT_FALSE(params.AreValid(&error_details)); EXPECT_EQ(error_details, "Invalid transport parameters [Client active_connection_id_limit" " 1 (Invalid)]"); params.active_connection_id_limit.set_value(0); EXPECT_FALSE(params.AreValid(&error_details)); EXPECT_EQ(error_details, "Invalid transport parameters [Client active_connection_id_limit" " 0 (Invalid)]"); } } TEST_P(TransportParametersTest, NoClientParamsWithStatelessResetToken) { TransportParameters orig_params; orig_params.perspective = Perspective::IS_CLIENT; orig_params.legacy_version_information = CreateFakeLegacyVersionInformationClient(); orig_params.max_idle_timeout_ms.set_value(kFakeIdleTimeoutMilliseconds); orig_params.stateless_reset_token = CreateStatelessResetTokenForTest(); orig_params.max_udp_payload_size.set_value(kMaxPacketSizeForTest); std::vector<uint8_t> out; EXPECT_QUIC_BUG( EXPECT_FALSE(SerializeTransportParameters(orig_params, &out)), "Not serializing invalid transport parameters: Client cannot send " "stateless reset token"); } TEST_P(TransportParametersTest, ParseClientParams) { const uint8_t kClientParams[] = { 0x01, 0x02, 0x6e, 0xec, 0x03, 0x02, 0x63, 0x29, 0x04, 0x02, 0x40, 0x65, 0x05, 0x02, 0x47, 0xD1, 0x06, 0x02, 0x47, 0xD2, 0x07, 0x02, 0x4B, 0xB8, 0x08, 0x01, 0x15, 0x09, 0x01, 0x16, 0x0a, 0x01, 0x0a, 0x0b, 0x01, 0x33, 0x80, 0x00, 0xde, 0x1a, 0x02, 0x43, 0xe8, 0x0c, 0x00, 0x0e, 0x01, 0x34, 0x0f, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x23, 0x45, 0x66, 0xab, 0x24, 0x01, 0x00, 0x01, 0x06, 0x03, 0x03, 0x92, 0x65, 0x5f, 0x52, 0x30, 0x27, 0x0d, 0x49, 0x64, 0xa4, 0xf9, 0x9b, 0x15, 0xbb, 0xad, 0x22, 0x07, 0x36, 0xd9, 0x72, 0xae, 0xa9, 0x7b, 0xf9, 0xac, 0x49, 0x4e, 0xad, 0x62, 0xe6, 0x71, 0x27, 0x01, 0x35, 0x71, 0x28, 0x0c, 'A', 'L', 'P', 'N', 'E', 'F', 'G', 0x00, 'H', 'I', 'J', 0xff, 0x80, 0x00, 0x47, 0x52, 0x04, 0x01, 0x23, 0x45, 0x67, 0x80, 0xFF, 0x73, 0xDB, 0x0C, 0x01, 0x23, 0x45, 0x67, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, }; const uint8_t* client_params = reinterpret_cast<const uint8_t*>(kClientParams); size_t client_params_length = ABSL_ARRAYSIZE(kClientParams); TransportParameters new_params; std::string error_details; ASSERT_TRUE(ParseTransportParameters(version_, Perspective::IS_CLIENT, client_params, client_params_length, &new_params, &error_details)) << error_details; EXPECT_TRUE(error_details.empty()); EXPECT_EQ(Perspective::IS_CLIENT, new_params.perspective); ASSERT_TRUE(new_params.legacy_version_information.has_value()); EXPECT_EQ(kFakeVersionLabel, new_params.legacy_version_information.value().version); EXPECT_TRUE( new_params.legacy_version_information.value().supported_versions.empty()); ASSERT_TRUE(new_params.version_information.has_value()); EXPECT_EQ(new_params.version_information.value(), CreateFakeVersionInformation()); EXPECT_FALSE(new_params.original_destination_connection_id.has_value()); EXPECT_EQ(kFakeIdleTimeoutMilliseconds, new_params.max_idle_timeout_ms.value()); EXPECT_TRUE(new_params.stateless_reset_token.empty()); EXPECT_EQ(kMaxPacketSizeForTest, new_params.max_udp_payload_size.value()); EXPECT_EQ(kFakeInitialMaxData, new_params.initial_max_data.value()); EXPECT_EQ(kFakeInitialMaxStreamDataBidiLocal, new_params.initial_max_stream_data_bidi_local.value()); EXPECT_EQ(kFakeInitialMaxStreamDataBidiRemote, new_params.initial_max_stream_data_bidi_remote.value()); EXPECT_EQ(kFakeInitialMaxStreamDataUni, new_params.initial_max_stream_data_uni.value()); EXPECT_EQ(kFakeInitialMaxStreamsBidi, new_params.initial_max_streams_bidi.value()); EXPECT_EQ(kFakeInitialMaxStreamsUni, new_params.initial_max_streams_uni.value()); EXPECT_EQ(kAckDelayExponentForTest, new_params.ack_delay_exponent.value()); EXPECT_EQ(kMaxAckDelayForTest, new_params.max_ack_delay.value()); EXPECT_EQ(kMinAckDelayUsForTest, new_params.min_ack_delay_us.value()); EXPECT_EQ(kFakeDisableMigration, new_params.disable_active_migration); EXPECT_EQ(kActiveConnectionIdLimitForTest, new_params.active_connection_id_limit.value()); ASSERT_TRUE(new_params.initial_source_connection_id.has_value()); EXPECT_EQ(CreateFakeInitialSourceConnectionId(), new_params.initial_source_connection_id.value()); EXPECT_FALSE(new_params.retry_source_connection_id.has_value()); EXPECT_EQ(kFakeInitialRoundTripTime, new_params.initial_round_trip_time_us.value()); ASSERT_TRUE(new_params.google_connection_options.has_value()); EXPECT_EQ(CreateFakeGoogleConnectionOptions(), new_params.google_connection_options.value()); std::string expected_google_handshake_message; ASSERT_TRUE(absl::HexStringToBytes(kFakeGoogleHandshakeMessage, &expected_google_handshake_message)); EXPECT_EQ(expected_google_handshake_message, new_params.google_handshake_message); } TEST_P(TransportParametersTest, ParseClientParamsFailsWithFullStatelessResetToken) { const uint8_t kClientParamsWithFullToken[] = { 0x01, 0x02, 0x6e, 0xec, 0x02, 0x10, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F, 0x03, 0x02, 0x63, 0x29, 0x04, 0x02, 0x40, 0x65, }; const uint8_t* client_params = reinterpret_cast<const uint8_t*>(kClientParamsWithFullToken); size_t client_params_length = ABSL_ARRAYSIZE(kClientParamsWithFullToken); TransportParameters out_params; std::string error_details; EXPECT_FALSE(ParseTransportParameters(version_, Perspective::IS_CLIENT, client_params, client_params_length, &out_params, &error_details)); EXPECT_EQ(error_details, "Client cannot send stateless reset token"); } TEST_P(TransportParametersTest, ParseClientParamsFailsWithEmptyStatelessResetToken) { const uint8_t kClientParamsWithEmptyToken[] = { 0x01, 0x02, 0x6e, 0xec, 0x02, 0x00, 0x03, 0x02, 0x63, 0x29, 0x04, 0x02, 0x40, 0x65, }; const uint8_t* client_params = reinterpret_cast<const uint8_t*>(kClientParamsWithEmptyToken); size_t client_params_length = ABSL_ARRAYSIZE(kClientParamsWithEmptyToken); TransportParameters out_params; std::string error_details; EXPECT_FALSE(ParseTransportParameters(version_, Perspective::IS_CLIENT, client_params, client_params_length, &out_params, &error_details)); EXPECT_EQ(error_details, "Received stateless_reset_token of invalid length 0"); } TEST_P(TransportParametersTest, ParseClientParametersRepeated) { const uint8_t kClientParamsRepeated[] = { 0x01, 0x02, 0x6e, 0xec, 0x03, 0x02, 0x63, 0x29, 0x01, 0x02, 0x6e, 0xec, }; const uint8_t* client_params = reinterpret_cast<const uint8_t*>(kClientParamsRepeated); size_t client_params_length = ABSL_ARRAYSIZE(kClientParamsRepeated); TransportParameters out_params; std::string error_details; EXPECT_FALSE(ParseTransportParameters(version_, Perspective::IS_CLIENT, client_params, client_params_length, &out_params, &error_details)); EXPECT_EQ(error_details, "Received a second max_idle_timeout"); } TEST_P(TransportParametersTest, ParseServerParams) { const uint8_t kServerParams[] = { 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0x37, 0x01, 0x02, 0x6e, 0xec, 0x02, 0x10, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F, 0x03, 0x02, 0x63, 0x29, 0x04, 0x02, 0x40, 0x65, 0x05, 0x02, 0x47, 0xD1, 0x06, 0x02, 0x47, 0xD2, 0x07, 0x02, 0x4B, 0xB8, 0x08, 0x01, 0x15, 0x09, 0x01, 0x16, 0x0a, 0x01, 0x0a, 0x0b, 0x01, 0x33, 0x80, 0x00, 0xde, 0x1a, 0x02, 0x43, 0xe8, 0x0c, 0x00, 0x0d, 0x31,
348
cpp
google/quiche
aes_128_gcm_encrypter
quiche/quic/core/crypto/aes_128_gcm_encrypter.cc
quiche/quic/core/crypto/aes_128_gcm_encrypter_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_AES_128_GCM_ENCRYPTER_H_ #define QUICHE_QUIC_CORE_CRYPTO_AES_128_GCM_ENCRYPTER_H_ #include "quiche/quic/core/crypto/aes_base_encrypter.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT Aes128GcmEncrypter : public AesBaseEncrypter { public: enum { kAuthTagSize = 16, }; Aes128GcmEncrypter(); Aes128GcmEncrypter(const Aes128GcmEncrypter&) = delete; Aes128GcmEncrypter& operator=(const Aes128GcmEncrypter&) = delete; ~Aes128GcmEncrypter() override; }; } #endif #include "quiche/quic/core/crypto/aes_128_gcm_encrypter.h" #include "openssl/evp.h" namespace quic { namespace { const size_t kKeySize = 16; const size_t kNonceSize = 12; } Aes128GcmEncrypter::Aes128GcmEncrypter() : AesBaseEncrypter(EVP_aead_aes_128_gcm, kKeySize, kAuthTagSize, kNonceSize, true) { static_assert(kKeySize <= kMaxKeySize, "key size too big"); static_assert(kNonceSize <= kMaxNonceSize, "nonce size too big"); } Aes128GcmEncrypter::~Aes128GcmEncrypter() {} }
#include "quiche/quic/core/crypto/aes_128_gcm_encrypter.h" #include <memory> #include <string> #include <vector> #include "absl/base/macros.h" #include "absl/strings/escaping.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace { struct TestGroupInfo { size_t key_len; size_t iv_len; size_t pt_len; size_t aad_len; size_t tag_len; }; struct TestVector { const char* key; const char* iv; const char* pt; const char* aad; const char* ct; const char* tag; }; const TestGroupInfo test_group_info[] = { {128, 96, 0, 0, 128}, {128, 96, 0, 128, 128}, {128, 96, 128, 0, 128}, {128, 96, 408, 160, 128}, {128, 96, 408, 720, 128}, {128, 96, 104, 0, 128}, }; const TestVector test_group_0[] = { {"11754cd72aec309bf52f7687212e8957", "3c819d9a9bed087615030b65", "", "", "", "250327c674aaf477aef2675748cf6971"}, {"ca47248ac0b6f8372a97ac43508308ed", "ffd2b598feabc9019262d2be", "", "", "", "60d20404af527d248d893ae495707d1a"}, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_1[] = { {"77be63708971c4e240d1cb79e8d77feb", "e0e00f19fed7ba0136a797f3", "", "7a43ec1d9c0a5a78a0b16533a6213cab", "", "209fcc8d3675ed938e9c7166709dd946"}, {"7680c5d3ca6154758e510f4d25b98820", "f8f105f9c3df4965780321f8", "", "c94c410194c765e3dcc7964379758ed3", "", "94dca8edfcf90bb74b153c8d48a17930"}, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_2[] = { {"7fddb57453c241d03efbed3ac44e371c", "ee283a3fc75575e33efd4887", "d5de42b461646c255c87bd2962d3b9a2", "", "2ccda4a5415cb91e135c2a0f78c9b2fd", "b36d1df9b9d5e596f83e8b7f52971cb3"}, {"ab72c77b97cb5fe9a382d9fe81ffdbed", "54cc7dc2c37ec006bcc6d1da", "007c5e5b3e59df24a7c355584fc1518d", "", "0e1bde206a07a9c2c1b65300f8c64997", "2b4401346697138c7a4891ee59867d0c"}, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_3[] = { {"fe47fcce5fc32665d2ae399e4eec72ba", "5adb9609dbaeb58cbd6e7275", "7c0e88c88899a779228465074797cd4c2e1498d259b54390b85e3eef1c02df60e743f1" "b840382c4bccaf3bafb4ca8429bea063", "88319d6e1d3ffa5f987199166c8a9b56c2aeba5a", "98f4826f05a265e6dd2be82db241c0fbbbf9ffb1c173aa83964b7cf539304373636525" "3ddbc5db8778371495da76d269e5db3e", "291ef1982e4defedaa2249f898556b47"}, {"ec0c2ba17aa95cd6afffe949da9cc3a8", "296bce5b50b7d66096d627ef", "b85b3753535b825cbe5f632c0b843c741351f18aa484281aebec2f45bb9eea2d79d987" "b764b9611f6c0f8641843d5d58f3a242", "f8d00f05d22bf68599bcdeb131292ad6e2df5d14", "a7443d31c26bdf2a1c945e29ee4bd344a99cfaf3aa71f8b3f191f83c2adfc7a0716299" "5506fde6309ffc19e716eddf1a828c5a", "890147971946b627c40016da1ecf3e77"}, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_4[] = { {"2c1f21cf0f6fb3661943155c3e3d8492", "23cb5ff362e22426984d1907", "42f758836986954db44bf37c6ef5e4ac0adaf38f27252a1b82d02ea949c8a1a2dbc0d6" "8b5615ba7c1220ff6510e259f06655d8", "5d3624879d35e46849953e45a32a624d6a6c536ed9857c613b572b0333e701557a713e" "3f010ecdf9a6bd6c9e3e44b065208645aff4aabee611b391528514170084ccf587177f" "4488f33cfb5e979e42b6e1cfc0a60238982a7aec", "81824f0e0d523db30d3da369fdc0d60894c7a0a20646dd015073ad2732bd989b14a222" "b6ad57af43e1895df9dca2a5344a62cc", "57a3ee28136e94c74838997ae9823f3a"}, {"d9f7d2411091f947b4d6f1e2d1f0fb2e", "e1934f5db57cc983e6b180e7", "73ed042327f70fe9c572a61545eda8b2a0c6e1d6c291ef19248e973aee6c312012f490" "c2c6f6166f4a59431e182663fcaea05a", "0a8a18a7150e940c3d87b38e73baee9a5c049ee21795663e264b694a949822b639092d" "0e67015e86363583fcf0ca645af9f43375f05fdb4ce84f411dcbca73c2220dea03a201" "15d2e51398344b16bee1ed7c499b353d6c597af8", "aaadbd5c92e9151ce3db7210b8714126b73e43436d242677afa50384f2149b831f1d57" "3c7891c2a91fbc48db29967ec9542b23", "21b51ca862cb637cdd03b99a0f93b134"}, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_5[] = { {"fe9bb47deb3a61e423c2231841cfd1fb", "4d328eb776f500a2f7fb47aa", "f1cc3818e421876bb6b8bbd6c9", "", "b88c5c1977b35b517b0aeae967", "43fd4727fe5cdb4b5b42818dea7ef8c9"}, {"6703df3701a7f54911ca72e24dca046a", "12823ab601c350ea4bc2488c", "793cd125b0b84a043e3ac67717", "", "b2051c80014f42f08735a7b0cd", "38e6bcd29962e5f2c13626b85a877101"}, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector* const test_group_array[] = { test_group_0, test_group_1, test_group_2, test_group_3, test_group_4, test_group_5, }; } namespace quic { namespace test { QuicData* EncryptWithNonce(Aes128GcmEncrypter* encrypter, absl::string_view nonce, absl::string_view associated_data, absl::string_view plaintext) { size_t ciphertext_size = encrypter->GetCiphertextSize(plaintext.length()); std::unique_ptr<char[]> ciphertext(new char[ciphertext_size]); if (!encrypter->Encrypt(nonce, associated_data, plaintext, reinterpret_cast<unsigned char*>(ciphertext.get()))) { return nullptr; } return new QuicData(ciphertext.release(), ciphertext_size, true); } class Aes128GcmEncrypterTest : public QuicTest {}; TEST_F(Aes128GcmEncrypterTest, Encrypt) { for (size_t i = 0; i < ABSL_ARRAYSIZE(test_group_array); i++) { SCOPED_TRACE(i); const TestVector* test_vectors = test_group_array[i]; const TestGroupInfo& test_info = test_group_info[i]; for (size_t j = 0; test_vectors[j].key != nullptr; j++) { std::string key; std::string iv; std::string pt; std::string aad; std::string ct; std::string tag; ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].key, &key)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].iv, &iv)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].pt, &pt)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].aad, &aad)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].ct, &ct)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].tag, &tag)); EXPECT_EQ(test_info.key_len, key.length() * 8); EXPECT_EQ(test_info.iv_len, iv.length() * 8); EXPECT_EQ(test_info.pt_len, pt.length() * 8); EXPECT_EQ(test_info.aad_len, aad.length() * 8); EXPECT_EQ(test_info.pt_len, ct.length() * 8); EXPECT_EQ(test_info.tag_len, tag.length() * 8); Aes128GcmEncrypter encrypter; ASSERT_TRUE(encrypter.SetKey(key)); std::unique_ptr<QuicData> encrypted( EncryptWithNonce(&encrypter, iv, aad.length() ? aad : absl::string_view(), pt)); ASSERT_TRUE(encrypted.get()); ASSERT_EQ(ct.length() + tag.length(), encrypted->length()); quiche::test::CompareCharArraysWithHexError( "ciphertext", encrypted->data(), ct.length(), ct.data(), ct.length()); quiche::test::CompareCharArraysWithHexError( "authentication tag", encrypted->data() + ct.length(), tag.length(), tag.data(), tag.length()); } } } TEST_F(Aes128GcmEncrypterTest, EncryptPacket) { std::string key; std::string iv; std::string aad; std::string pt; std::string ct; ASSERT_TRUE(absl::HexStringToBytes("d95a145250826c25a77b6a84fd4d34fc", &key)); ASSERT_TRUE(absl::HexStringToBytes("50c4431ebb18283448e276e2", &iv)); ASSERT_TRUE( absl::HexStringToBytes("875d49f64a70c9cbe713278f44ff000005", &aad)); ASSERT_TRUE(absl::HexStringToBytes("aa0003a250bd000000000001", &pt)); ASSERT_TRUE(absl::HexStringToBytes( "7dd4708b989ee7d38a013e3656e9b37beefd05808fe1ab41e3b4f2c0", &ct)); uint64_t packet_num = 0x13278f44; std::vector<char> out(ct.size()); size_t out_size; Aes128GcmEncrypter encrypter; ASSERT_TRUE(encrypter.SetKey(key)); ASSERT_TRUE(encrypter.SetIV(iv)); ASSERT_TRUE(encrypter.EncryptPacket(packet_num, aad, pt, out.data(), &out_size, out.size())); EXPECT_EQ(out_size, out.size()); quiche::test::CompareCharArraysWithHexError("ciphertext", out.data(), out.size(), ct.data(), ct.size()); } TEST_F(Aes128GcmEncrypterTest, GetMaxPlaintextSize) { Aes128GcmEncrypter encrypter; EXPECT_EQ(1000u, encrypter.GetMaxPlaintextSize(1016)); EXPECT_EQ(100u, encrypter.GetMaxPlaintextSize(116)); EXPECT_EQ(10u, encrypter.GetMaxPlaintextSize(26)); } TEST_F(Aes128GcmEncrypterTest, GetCiphertextSize) { Aes128GcmEncrypter encrypter; EXPECT_EQ(1016u, encrypter.GetCiphertextSize(1000)); EXPECT_EQ(116u, encrypter.GetCiphertextSize(100)); EXPECT_EQ(26u, encrypter.GetCiphertextSize(10)); } TEST_F(Aes128GcmEncrypterTest, GenerateHeaderProtectionMask) { Aes128GcmEncrypter encrypter; std::string key; std::string sample; std::string expected_mask; ASSERT_TRUE(absl::HexStringToBytes("d9132370cb18476ab833649cf080d970", &key)); ASSERT_TRUE( absl::HexStringToBytes("d1d7998068517adb769b48b924a32c47", &sample)); ASSERT_TRUE(absl::HexStringToBytes("b132c37d6164da4ea4dc9b763aceec27", &expected_mask)); ASSERT_TRUE(encrypter.SetHeaderProtectionKey(key)); std::string mask = encrypter.GenerateHeaderProtectionMask(sample); quiche::test::CompareCharArraysWithHexError( "header protection mask", mask.data(), mask.size(), expected_mask.data(), expected_mask.size()); } } }
349
cpp
google/quiche
p256_key_exchange
quiche/quic/core/crypto/p256_key_exchange.cc
quiche/quic/core/crypto/p256_key_exchange_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_P256_KEY_EXCHANGE_H_ #define QUICHE_QUIC_CORE_CRYPTO_P256_KEY_EXCHANGE_H_ #include <cstdint> #include <string> #include "absl/strings/string_view.h" #include "openssl/base.h" #include "quiche/quic/core/crypto/key_exchange.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT P256KeyExchange : public SynchronousKeyExchange { public: ~P256KeyExchange() override; static std::unique_ptr<P256KeyExchange> New(); static std::unique_ptr<P256KeyExchange> New(absl::string_view private_key); static std::string NewPrivateKey(); bool CalculateSharedKeySync(absl::string_view peer_public_value, std::string* shared_key) const override; absl::string_view public_value() const override; QuicTag type() const override { return kP256; } private: enum { kP256FieldBytes = 32, kUncompressedP256PointBytes = 1 + 2 * kP256FieldBytes, kUncompressedECPointForm = 0x04, }; P256KeyExchange(bssl::UniquePtr<EC_KEY> private_key, const uint8_t* public_key); P256KeyExchange(const P256KeyExchange&) = delete; P256KeyExchange& operator=(const P256KeyExchange&) = delete; bssl::UniquePtr<EC_KEY> private_key_; uint8_t public_key_[kUncompressedP256PointBytes]; }; } #endif #include "quiche/quic/core/crypto/p256_key_exchange.h" #include <cstdint> #include <cstring> #include <memory> #include <string> #include <utility> #include "absl/memory/memory.h" #include "absl/strings/string_view.h" #include "openssl/ec.h" #include "openssl/ecdh.h" #include "openssl/err.h" #include "openssl/evp.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { P256KeyExchange::P256KeyExchange(bssl::UniquePtr<EC_KEY> private_key, const uint8_t* public_key) : private_key_(std::move(private_key)) { memcpy(public_key_, public_key, sizeof(public_key_)); } P256KeyExchange::~P256KeyExchange() {} std::unique_ptr<P256KeyExchange> P256KeyExchange::New() { return New(P256KeyExchange::NewPrivateKey()); } std::unique_ptr<P256KeyExchange> P256KeyExchange::New(absl::string_view key) { if (key.empty()) { QUIC_DLOG(INFO) << "Private key is empty"; return nullptr; } const uint8_t* keyp = reinterpret_cast<const uint8_t*>(key.data()); bssl::UniquePtr<EC_KEY> private_key( d2i_ECPrivateKey(nullptr, &keyp, key.size())); if (!private_key.get() || !EC_KEY_check_key(private_key.get())) { QUIC_DLOG(INFO) << "Private key is invalid."; return nullptr; } uint8_t public_key[kUncompressedP256PointBytes]; if (EC_POINT_point2oct(EC_KEY_get0_group(private_key.get()), EC_KEY_get0_public_key(private_key.get()), POINT_CONVERSION_UNCOMPRESSED, public_key, sizeof(public_key), nullptr) != sizeof(public_key)) { QUIC_DLOG(INFO) << "Can't get public key."; return nullptr; } return absl::WrapUnique( new P256KeyExchange(std::move(private_key), public_key)); } std::string P256KeyExchange::NewPrivateKey() { bssl::UniquePtr<EC_KEY> key(EC_KEY_new_by_curve_name(NID_X9_62_prime256v1)); if (!key.get() || !EC_KEY_generate_key(key.get())) { QUIC_DLOG(INFO) << "Can't generate a new private key."; return std::string(); } int key_len = i2d_ECPrivateKey(key.get(), nullptr); if (key_len <= 0) { QUIC_DLOG(INFO) << "Can't convert private key to string"; return std::string(); } std::unique_ptr<uint8_t[]> private_key(new uint8_t[key_len]); uint8_t* keyp = private_key.get(); if (!i2d_ECPrivateKey(key.get(), &keyp)) { QUIC_DLOG(INFO) << "Can't convert private key to string."; return std::string(); } return std::string(reinterpret_cast<char*>(private_key.get()), key_len); } bool P256KeyExchange::CalculateSharedKeySync( absl::string_view peer_public_value, std::string* shared_key) const { if (peer_public_value.size() != kUncompressedP256PointBytes) { QUIC_DLOG(INFO) << "Peer public value is invalid"; return false; } bssl::UniquePtr<EC_POINT> point( EC_POINT_new(EC_KEY_get0_group(private_key_.get()))); if (!point.get() || !EC_POINT_oct2point( EC_KEY_get0_group(private_key_.get()), point.get(), reinterpret_cast<const uint8_t*>( peer_public_value.data()), peer_public_value.size(), nullptr)) { QUIC_DLOG(INFO) << "Can't convert peer public value to curve point."; return false; } uint8_t result[kP256FieldBytes]; if (ECDH_compute_key(result, sizeof(result), point.get(), private_key_.get(), nullptr) != sizeof(result)) { QUIC_DLOG(INFO) << "Can't compute ECDH shared key."; return false; } shared_key->assign(reinterpret_cast<char*>(result), sizeof(result)); return true; } absl::string_view P256KeyExchange::public_value() const { return absl::string_view(reinterpret_cast<const char*>(public_key_), sizeof(public_key_)); } }
#include "quiche/quic/core/crypto/p256_key_exchange.h" #include <memory> #include <string> #include <utility> #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { class P256KeyExchangeTest : public QuicTest { public: class TestCallbackResult { public: void set_ok(bool ok) { ok_ = ok; } bool ok() { return ok_; } private: bool ok_ = false; }; class TestCallback : public AsynchronousKeyExchange::Callback { public: TestCallback(TestCallbackResult* result) : result_(result) {} virtual ~TestCallback() = default; void Run(bool ok) { result_->set_ok(ok); } private: TestCallbackResult* result_; }; }; TEST_F(P256KeyExchangeTest, SharedKey) { for (int i = 0; i < 5; i++) { std::string alice_private(P256KeyExchange::NewPrivateKey()); std::string bob_private(P256KeyExchange::NewPrivateKey()); ASSERT_FALSE(alice_private.empty()); ASSERT_FALSE(bob_private.empty()); ASSERT_NE(alice_private, bob_private); std::unique_ptr<P256KeyExchange> alice(P256KeyExchange::New(alice_private)); std::unique_ptr<P256KeyExchange> bob(P256KeyExchange::New(bob_private)); ASSERT_TRUE(alice != nullptr); ASSERT_TRUE(bob != nullptr); const absl::string_view alice_public(alice->public_value()); const absl::string_view bob_public(bob->public_value()); std::string alice_shared, bob_shared; ASSERT_TRUE(alice->CalculateSharedKeySync(bob_public, &alice_shared)); ASSERT_TRUE(bob->CalculateSharedKeySync(alice_public, &bob_shared)); ASSERT_EQ(alice_shared, bob_shared); } } TEST_F(P256KeyExchangeTest, AsyncSharedKey) { for (int i = 0; i < 5; i++) { std::string alice_private(P256KeyExchange::NewPrivateKey()); std::string bob_private(P256KeyExchange::NewPrivateKey()); ASSERT_FALSE(alice_private.empty()); ASSERT_FALSE(bob_private.empty()); ASSERT_NE(alice_private, bob_private); std::unique_ptr<P256KeyExchange> alice(P256KeyExchange::New(alice_private)); std::unique_ptr<P256KeyExchange> bob(P256KeyExchange::New(bob_private)); ASSERT_TRUE(alice != nullptr); ASSERT_TRUE(bob != nullptr); const absl::string_view alice_public(alice->public_value()); const absl::string_view bob_public(bob->public_value()); std::string alice_shared, bob_shared; TestCallbackResult alice_result; ASSERT_FALSE(alice_result.ok()); alice->CalculateSharedKeyAsync( bob_public, &alice_shared, std::make_unique<TestCallback>(&alice_result)); ASSERT_TRUE(alice_result.ok()); TestCallbackResult bob_result; ASSERT_FALSE(bob_result.ok()); bob->CalculateSharedKeyAsync(alice_public, &bob_shared, std::make_unique<TestCallback>(&bob_result)); ASSERT_TRUE(bob_result.ok()); ASSERT_EQ(alice_shared, bob_shared); ASSERT_NE(0u, alice_shared.length()); ASSERT_NE(0u, bob_shared.length()); } } } }
350
cpp
google/quiche
aes_128_gcm_decrypter
quiche/quic/core/crypto/aes_128_gcm_decrypter.cc
quiche/quic/core/crypto/aes_128_gcm_decrypter_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_AES_128_GCM_DECRYPTER_H_ #define QUICHE_QUIC_CORE_CRYPTO_AES_128_GCM_DECRYPTER_H_ #include <cstdint> #include "quiche/quic/core/crypto/aes_base_decrypter.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT Aes128GcmDecrypter : public AesBaseDecrypter { public: enum { kAuthTagSize = 16, }; Aes128GcmDecrypter(); Aes128GcmDecrypter(const Aes128GcmDecrypter&) = delete; Aes128GcmDecrypter& operator=(const Aes128GcmDecrypter&) = delete; ~Aes128GcmDecrypter() override; uint32_t cipher_id() const override; }; } #endif #include "quiche/quic/core/crypto/aes_128_gcm_decrypter.h" #include "openssl/aead.h" #include "openssl/tls1.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" namespace quic { namespace { const size_t kKeySize = 16; const size_t kNonceSize = 12; } Aes128GcmDecrypter::Aes128GcmDecrypter() : AesBaseDecrypter(EVP_aead_aes_128_gcm, kKeySize, kAuthTagSize, kNonceSize, true) { static_assert(kKeySize <= kMaxKeySize, "key size too big"); static_assert(kNonceSize <= kMaxNonceSize, "nonce size too big"); } Aes128GcmDecrypter::~Aes128GcmDecrypter() {} uint32_t Aes128GcmDecrypter::cipher_id() const { return TLS1_CK_AES_128_GCM_SHA256; } }
#include "quiche/quic/core/crypto/aes_128_gcm_decrypter.h" #include <memory> #include <string> #include "absl/base/macros.h" #include "absl/strings/escaping.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace { struct TestGroupInfo { size_t key_len; size_t iv_len; size_t pt_len; size_t aad_len; size_t tag_len; }; struct TestVector { const char* key; const char* iv; const char* ct; const char* aad; const char* tag; const char* pt; }; const TestGroupInfo test_group_info[] = { {128, 96, 0, 0, 128}, {128, 96, 0, 128, 128}, {128, 96, 128, 0, 128}, {128, 96, 408, 160, 128}, {128, 96, 408, 720, 128}, {128, 96, 104, 0, 128}, }; const TestVector test_group_0[] = { {"cf063a34d4a9a76c2c86787d3f96db71", "113b9785971864c83b01c787", "", "", "72ac8493e3a5228b5d130a69d2510e42", ""}, { "a49a5e26a2f8cb63d05546c2a62f5343", "907763b19b9b4ab6bd4f0281", "", "", "a2be08210d8c470a8df6e8fbd79ec5cf", nullptr }, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_1[] = { { "d1f6af919cde85661208bdce0c27cb22", "898c6929b435017bf031c3c5", "", "7c5faa40e636bbc91107e68010c92b9f", "ae45f11777540a2caeb128be8092468a", nullptr }, {"2370e320d4344208e0ff5683f243b213", "04dbb82f044d30831c441228", "", "d43a8e5089eea0d026c03a85178b27da", "2a049c049d25aa95969b451d93c31c6e", ""}, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_2[] = { {"e98b72a9881a84ca6b76e0f43e68647a", "8b23299fde174053f3d652ba", "5a3c1cf1985dbb8bed818036fdd5ab42", "", "23c7ab0f952b7091cd324835043b5eb5", "28286a321293253c3e0aa2704a278032"}, {"33240636cd3236165f1a553b773e728e", "17c4d61493ecdc8f31700b12", "47bb7e23f7bdfe05a8091ac90e4f8b2e", "", "b723c70e931d9785f40fd4ab1d612dc9", "95695a5b12f2870b9cc5fdc8f218a97d"}, { "5164df856f1e9cac04a79b808dc5be39", "e76925d5355e0584ce871b2b", "0216c899c88d6e32c958c7e553daa5bc", "", "a145319896329c96df291f64efbe0e3a", nullptr }, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_3[] = { {"af57f42c60c0fc5a09adb81ab86ca1c3", "a2dc01871f37025dc0fc9a79", "b9a535864f48ea7b6b1367914978f9bfa087d854bb0e269bed8d279d2eea1210e48947" "338b22f9bad09093276a331e9c79c7f4", "41dc38988945fcb44faf2ef72d0061289ef8efd8", "4f71e72bde0018f555c5adcce062e005", "3803a0727eeb0ade441e0ec107161ded2d425ec0d102f21f51bf2cf9947c7ec4aa7279" "5b2f69b041596e8817d0a3c16f8fadeb"}, {"ebc753e5422b377d3cb64b58ffa41b61", "2e1821efaced9acf1f241c9b", "069567190554e9ab2b50a4e1fbf9c147340a5025fdbd201929834eaf6532325899ccb9" "f401823e04b05817243d2142a3589878", "b9673412fd4f88ba0e920f46dd6438ff791d8eef", "534d9234d2351cf30e565de47baece0b", "39077edb35e9c5a4b1e4c2a6b9bb1fce77f00f5023af40333d6d699014c2bcf4209c18" "353a18017f5b36bfc00b1f6dcb7ed485"}, { "52bdbbf9cf477f187ec010589cb39d58", "d3be36d3393134951d324b31", "700188da144fa692cf46e4a8499510a53d90903c967f7f13e8a1bd8151a74adc4fe63e" "32b992760b3a5f99e9a47838867000a9", "93c4fc6a4135f54d640b0c976bf755a06a292c33", "8ca4e38aa3dfa6b1d0297021ccf3ea5f", nullptr }, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_4[] = { {"da2bb7d581493d692380c77105590201", "44aa3e7856ca279d2eb020c6", "9290d430c9e89c37f0446dbd620c9a6b34b1274aeb6f911f75867efcf95b6feda69f1a" "f4ee16c761b3c9aeac3da03aa9889c88", "4cd171b23bddb3a53cdf959d5c1710b481eb3785a90eb20a2345ee00d0bb7868c367ab" "12e6f4dd1dee72af4eee1d197777d1d6499cc541f34edbf45cda6ef90b3c024f9272d7" "2ec1909fb8fba7db88a4d6f7d3d925980f9f9f72", "9e3ac938d3eb0cadd6f5c9e35d22ba38", "9bbf4c1a2742f6ac80cb4e8a052e4a8f4f07c43602361355b717381edf9fabd4cb7e3a" "d65dbd1378b196ac270588dd0621f642"}, {"d74e4958717a9d5c0e235b76a926cae8", "0b7471141e0c70b1995fd7b1", "e701c57d2330bf066f9ff8cf3ca4343cafe4894651cd199bdaaa681ba486b4a65c5a22" "b0f1420be29ea547d42c713bc6af66aa", "4a42b7aae8c245c6f1598a395316e4b8484dbd6e64648d5e302021b1d3fa0a38f46e22" "bd9c8080b863dc0016482538a8562a4bd0ba84edbe2697c76fd039527ac179ec5506cf" "34a6039312774cedebf4961f3978b14a26509f96", "e192c23cb036f0b31592989119eed55d", "840d9fb95e32559fb3602e48590280a172ca36d9b49ab69510f5bd552bfab7a306f85f" "f0a34bc305b88b804c60b90add594a17"}, { "1986310c725ac94ecfe6422e75fc3ee7", "93ec4214fa8e6dc4e3afc775", "b178ec72f85a311ac4168f42a4b2c23113fbea4b85f4b9dabb74e143eb1b8b0a361e02" "43edfd365b90d5b325950df0ada058f9", "e80b88e62c49c958b5e0b8b54f532d9ff6aa84c8a40132e93e55b59fc24e8decf28463" "139f155d1e8ce4ee76aaeefcd245baa0fc519f83a5fb9ad9aa40c4b21126013f576c42" "72c2cb136c8fd091cc4539877a5d1e72d607f960", "8b347853f11d75e81e8a95010be81f17", nullptr }, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_5[] = { {"387218b246c1a8257748b56980e50c94", "dd7e014198672be39f95b69d", "cdba9e73eaf3d38eceb2b04a8d", "", "ecf90f4a47c9c626d6fb2c765d201556", "48f5b426baca03064554cc2b30"}, {"294de463721e359863887c820524b3d4", "3338b35c9d57a5d28190e8c9", "2f46634e74b8e4c89812ac83b9", "", "dabd506764e68b82a7e720aa18da0abe", "46a2e55c8e264df211bd112685"}, {"28ead7fd2179e0d12aa6d5d88c58c2dc", "5055347f18b4d5add0ae5c41", "142d8210c3fb84774cdbd0447a", "", "5fd321d9cdb01952dc85f034736c2a7d", "3b95b981086ee73cc4d0cc1422"}, { "7d7b6c988137b8d470c57bf674a09c87", "9edf2aa970d016ac962e1fd8", "a85b66c3cb5eab91d5bdc8bc0e", "", "dc054efc01f3afd21d9c2484819f569a", nullptr }, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector* const test_group_array[] = { test_group_0, test_group_1, test_group_2, test_group_3, test_group_4, test_group_5, }; } namespace quic { namespace test { QuicData* DecryptWithNonce(Aes128GcmDecrypter* decrypter, absl::string_view nonce, absl::string_view associated_data, absl::string_view ciphertext) { decrypter->SetIV(nonce); std::unique_ptr<char[]> output(new char[ciphertext.length()]); size_t output_length = 0; const bool success = decrypter->DecryptPacket(0, associated_data, ciphertext, output.get(), &output_length, ciphertext.length()); if (!success) { return nullptr; } return new QuicData(output.release(), output_length, true); } class Aes128GcmDecrypterTest : public QuicTest {}; TEST_F(Aes128GcmDecrypterTest, Decrypt) { for (size_t i = 0; i < ABSL_ARRAYSIZE(test_group_array); i++) { SCOPED_TRACE(i); const TestVector* test_vectors = test_group_array[i]; const TestGroupInfo& test_info = test_group_info[i]; for (size_t j = 0; test_vectors[j].key != nullptr; j++) { bool has_pt = test_vectors[j].pt; std::string key; std::string iv; std::string ct; std::string aad; std::string tag; std::string pt; ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].key, &key)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].iv, &iv)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].ct, &ct)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].aad, &aad)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].tag, &tag)); if (has_pt) { ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].pt, &pt)); } EXPECT_EQ(test_info.key_len, key.length() * 8); EXPECT_EQ(test_info.iv_len, iv.length() * 8); EXPECT_EQ(test_info.pt_len, ct.length() * 8); EXPECT_EQ(test_info.aad_len, aad.length() * 8); EXPECT_EQ(test_info.tag_len, tag.length() * 8); if (has_pt) { EXPECT_EQ(test_info.pt_len, pt.length() * 8); } std::string ciphertext = ct + tag; Aes128GcmDecrypter decrypter; ASSERT_TRUE(decrypter.SetKey(key)); std::unique_ptr<QuicData> decrypted(DecryptWithNonce( &decrypter, iv, aad.length() ? aad : absl::string_view(), ciphertext)); if (!decrypted) { EXPECT_FALSE(has_pt); continue; } EXPECT_TRUE(has_pt); ASSERT_EQ(pt.length(), decrypted->length()); quiche::test::CompareCharArraysWithHexError( "plaintext", decrypted->data(), pt.length(), pt.data(), pt.length()); } } } TEST_F(Aes128GcmDecrypterTest, GenerateHeaderProtectionMask) { Aes128GcmDecrypter decrypter; std::string key; std::string sample; std::string expected_mask; ASSERT_TRUE(absl::HexStringToBytes("d9132370cb18476ab833649cf080d970", &key)); ASSERT_TRUE( absl::HexStringToBytes("d1d7998068517adb769b48b924a32c47", &sample)); ASSERT_TRUE(absl::HexStringToBytes("b132c37d6164da4ea4dc9b763aceec27", &expected_mask)); QuicDataReader sample_reader(sample.data(), sample.size()); ASSERT_TRUE(decrypter.SetHeaderProtectionKey(key)); std::string mask = decrypter.GenerateHeaderProtectionMask(&sample_reader); quiche::test::CompareCharArraysWithHexError( "header protection mask", mask.data(), mask.size(), expected_mask.data(), expected_mask.size()); } } }
351
cpp
google/quiche
aes_256_gcm_encrypter
quiche/quic/core/crypto/aes_256_gcm_encrypter.cc
quiche/quic/core/crypto/aes_256_gcm_encrypter_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_AES_256_GCM_ENCRYPTER_H_ #define QUICHE_QUIC_CORE_CRYPTO_AES_256_GCM_ENCRYPTER_H_ #include "quiche/quic/core/crypto/aes_base_encrypter.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT Aes256GcmEncrypter : public AesBaseEncrypter { public: enum { kAuthTagSize = 16, }; Aes256GcmEncrypter(); Aes256GcmEncrypter(const Aes256GcmEncrypter&) = delete; Aes256GcmEncrypter& operator=(const Aes256GcmEncrypter&) = delete; ~Aes256GcmEncrypter() override; }; } #endif #include "quiche/quic/core/crypto/aes_256_gcm_encrypter.h" #include "openssl/evp.h" namespace quic { namespace { const size_t kKeySize = 32; const size_t kNonceSize = 12; } Aes256GcmEncrypter::Aes256GcmEncrypter() : AesBaseEncrypter(EVP_aead_aes_256_gcm, kKeySize, kAuthTagSize, kNonceSize, true) { static_assert(kKeySize <= kMaxKeySize, "key size too big"); static_assert(kNonceSize <= kMaxNonceSize, "nonce size too big"); } Aes256GcmEncrypter::~Aes256GcmEncrypter() {} }
#include "quiche/quic/core/crypto/aes_256_gcm_encrypter.h" #include <memory> #include <string> #include "absl/base/macros.h" #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace { struct TestGroupInfo { size_t key_len; size_t iv_len; size_t pt_len; size_t aad_len; size_t tag_len; }; struct TestVector { const char* key; const char* iv; const char* pt; const char* aad; const char* ct; const char* tag; }; const TestGroupInfo test_group_info[] = { {256, 96, 0, 0, 128}, {256, 96, 0, 128, 128}, {256, 96, 128, 0, 128}, {256, 96, 408, 160, 128}, {256, 96, 408, 720, 128}, {256, 96, 104, 0, 128}, }; const TestVector test_group_0[] = { {"b52c505a37d78eda5dd34f20c22540ea1b58963cf8e5bf8ffa85f9f2492505b4", "516c33929df5a3284ff463d7", "", "", "", "bdc1ac884d332457a1d2664f168c76f0"}, {"5fe0861cdc2690ce69b3658c7f26f8458eec1c9243c5ba0845305d897e96ca0f", "770ac1a5a3d476d5d96944a1", "", "", "", "196d691e1047093ca4b3d2ef4baba216"}, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_1[] = { {"78dc4e0aaf52d935c3c01eea57428f00ca1fd475f5da86a49c8dd73d68c8e223", "d79cf22d504cc793c3fb6c8a", "", "b96baa8c1c75a671bfb2d08d06be5f36", "", "3e5d486aa2e30b22e040b85723a06e76"}, {"4457ff33683cca6ca493878bdc00373893a9763412eef8cddb54f91318e0da88", "699d1f29d7b8c55300bb1fd2", "", "6749daeea367d0e9809e2dc2f309e6e3", "", "d60c74d2517fde4a74e0cd4709ed43a9"}, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_2[] = { {"31bdadd96698c204aa9ce1448ea94ae1fb4a9a0b3c9d773b51bb1822666b8f22", "0d18e06c7c725ac9e362e1ce", "2db5168e932556f8089a0622981d017d", "", "fa4362189661d163fcd6a56d8bf0405a", "d636ac1bbedd5cc3ee727dc2ab4a9489"}, {"460fc864972261c2560e1eb88761ff1c992b982497bd2ac36c04071cbb8e5d99", "8a4a16b9e210eb68bcb6f58d", "99e4e926ffe927f691893fb79a96b067", "", "133fc15751621b5f325c7ff71ce08324", "ec4e87e0cf74a13618d0b68636ba9fa7"}, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_3[] = { {"24501ad384e473963d476edcfe08205237acfd49b5b8f33857f8114e863fec7f", "9ff18563b978ec281b3f2794", "27f348f9cdc0c5bd5e66b1ccb63ad920ff2219d14e8d631b3872265cf117ee86757accb15" "8bd9abb3868fdc0d0b074b5f01b2c", "adb5ec720ccf9898500028bf34afccbcaca126ef", "eb7cb754c824e8d96f7c6d9b76c7d26fb874ffbf1d65c6f64a698d839b0b06145dae82057" "ad55994cf59ad7f67c0fa5e85fab8", "bc95c532fecc594c36d1550286a7a3f0"}, {"fb43f5ab4a1738a30c1e053d484a94254125d55dccee1ad67c368bc1a985d235", "9fbb5f8252db0bca21f1c230", "34b797bb82250e23c5e796db2c37e488b3b99d1b981cea5e5b0c61a0b39adb6bd6ef1f507" "22e2e4f81115cfcf53f842e2a6c08", "98f8ae1735c39f732e2cbee1156dabeb854ec7a2", "871cd53d95a8b806bd4821e6c4456204d27fd704ba3d07ce25872dc604ea5c5ea13322186" "b7489db4fa060c1fd4159692612c8", "07b48e4a32fac47e115d7ac7445d8330"}, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_4[] = { {"148579a3cbca86d5520d66c0ec71ca5f7e41ba78e56dc6eebd566fed547fe691", "b08a5ea1927499c6ecbfd4e0", "9d0b15fdf1bd595f91f8b3abc0f7dec927dfd4799935a1795d9ce00c9b879434420fe42c2" "75a7cd7b39d638fb81ca52b49dc41", "e4f963f015ffbb99ee3349bbaf7e8e8e6c2a71c230a48f9d59860a29091d2747e01a5ca57" "2347e247d25f56ba7ae8e05cde2be3c97931292c02370208ecd097ef692687fecf2f419d3" "200162a6480a57dad408a0dfeb492e2c5d", "2097e372950a5e9383c675e89eea1c314f999159f5611344b298cda45e62843716f215f82" "ee663919c64002a5c198d7878fd3f", "adbecdb0d5c2224d804d2886ff9a5760"}, {"e49af19182faef0ebeeba9f2d3be044e77b1212358366e4ef59e008aebcd9788", "e7f37d79a6a487a5a703edbb", "461cd0caf7427a3d44408d825ed719237272ecd503b9094d1f62c97d63ed83a0b50bdc804" "ffdd7991da7a5b6dcf48d4bcd2cbc", "19a9a1cfc647346781bef51ed9070d05f99a0e0192a223c5cd2522dbdf97d9739dd39fb17" "8ade3339e68774b058aa03e9a20a9a205bc05f32381df4d63396ef691fefd5a71b49a2ad8" "2d5ea428778ca47ee1398792762413cff4", "32ca3588e3e56eb4c8301b009d8b84b8a900b2b88ca3c21944205e9dd7311757b51394ae9" "0d8bb3807b471677614f4198af909", "3e403d035c71d88f1be1a256c89ba6ad"}, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_5[] = { {"82c4f12eeec3b2d3d157b0f992d292b237478d2cecc1d5f161389b97f999057a", "7b40b20f5f397177990ef2d1", "982a296ee1cd7086afad976945", "", "ec8e05a0471d6b43a59ca5335f", "113ddeafc62373cac2f5951bb9165249"}, {"db4340af2f835a6c6d7ea0ca9d83ca81ba02c29b7410f221cb6071114e393240", "40e438357dd80a85cac3349e", "8ddb3397bd42853193cb0f80c9", "", "b694118c85c41abf69e229cb0f", "c07f1b8aafbd152f697eb67f2a85fe45"}, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector* const test_group_array[] = { test_group_0, test_group_1, test_group_2, test_group_3, test_group_4, test_group_5, }; } namespace quic { namespace test { QuicData* EncryptWithNonce(Aes256GcmEncrypter* encrypter, absl::string_view nonce, absl::string_view associated_data, absl::string_view plaintext) { size_t ciphertext_size = encrypter->GetCiphertextSize(plaintext.length()); std::unique_ptr<char[]> ciphertext(new char[ciphertext_size]); if (!encrypter->Encrypt(nonce, associated_data, plaintext, reinterpret_cast<unsigned char*>(ciphertext.get()))) { return nullptr; } return new QuicData(ciphertext.release(), ciphertext_size, true); } class Aes256GcmEncrypterTest : public QuicTest {}; TEST_F(Aes256GcmEncrypterTest, Encrypt) { for (size_t i = 0; i < ABSL_ARRAYSIZE(test_group_array); i++) { SCOPED_TRACE(i); const TestVector* test_vectors = test_group_array[i]; const TestGroupInfo& test_info = test_group_info[i]; for (size_t j = 0; test_vectors[j].key != nullptr; j++) { std::string key; std::string iv; std::string pt; std::string aad; std::string ct; std::string tag; ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].key, &key)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].iv, &iv)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].pt, &pt)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].aad, &aad)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].ct, &ct)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].tag, &tag)); EXPECT_EQ(test_info.key_len, key.length() * 8); EXPECT_EQ(test_info.iv_len, iv.length() * 8); EXPECT_EQ(test_info.pt_len, pt.length() * 8); EXPECT_EQ(test_info.aad_len, aad.length() * 8); EXPECT_EQ(test_info.pt_len, ct.length() * 8); EXPECT_EQ(test_info.tag_len, tag.length() * 8); Aes256GcmEncrypter encrypter; ASSERT_TRUE(encrypter.SetKey(key)); std::unique_ptr<QuicData> encrypted( EncryptWithNonce(&encrypter, iv, aad.length() ? aad : absl::string_view(), pt)); ASSERT_TRUE(encrypted.get()); ASSERT_EQ(ct.length() + tag.length(), encrypted->length()); quiche::test::CompareCharArraysWithHexError( "ciphertext", encrypted->data(), ct.length(), ct.data(), ct.length()); quiche::test::CompareCharArraysWithHexError( "authentication tag", encrypted->data() + ct.length(), tag.length(), tag.data(), tag.length()); } } } TEST_F(Aes256GcmEncrypterTest, GetMaxPlaintextSize) { Aes256GcmEncrypter encrypter; EXPECT_EQ(1000u, encrypter.GetMaxPlaintextSize(1016)); EXPECT_EQ(100u, encrypter.GetMaxPlaintextSize(116)); EXPECT_EQ(10u, encrypter.GetMaxPlaintextSize(26)); } TEST_F(Aes256GcmEncrypterTest, GetCiphertextSize) { Aes256GcmEncrypter encrypter; EXPECT_EQ(1016u, encrypter.GetCiphertextSize(1000)); EXPECT_EQ(116u, encrypter.GetCiphertextSize(100)); EXPECT_EQ(26u, encrypter.GetCiphertextSize(10)); } TEST_F(Aes256GcmEncrypterTest, GenerateHeaderProtectionMask) { Aes256GcmEncrypter encrypter; std::string key; std::string sample; std::string expected_mask; ASSERT_TRUE(absl::HexStringToBytes( "ed23ecbf54d426def5c52c3dcfc84434e62e57781d3125bb21ed91b7d3e07788", &key)); ASSERT_TRUE( absl::HexStringToBytes("4d190c474be2b8babafb49ec4e38e810", &sample)); ASSERT_TRUE(absl::HexStringToBytes("db9ed4e6ccd033af2eae01407199c56e", &expected_mask)); ASSERT_TRUE(encrypter.SetHeaderProtectionKey(key)); std::string mask = encrypter.GenerateHeaderProtectionMask(sample); quiche::test::CompareCharArraysWithHexError( "header protection mask", mask.data(), mask.size(), expected_mask.data(), expected_mask.size()); } } }
352
cpp
google/quiche
quic_crypto_server_config
quiche/quic/core/crypto/quic_crypto_server_config.cc
quiche/quic/core/crypto/quic_crypto_server_config_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_QUIC_CRYPTO_SERVER_CONFIG_H_ #define QUICHE_QUIC_CORE_CRYPTO_QUIC_CRYPTO_SERVER_CONFIG_H_ #include <cstddef> #include <cstdint> #include <map> #include <memory> #include <string> #include <vector> #include "absl/strings/string_view.h" #include "openssl/base.h" #include "quiche/quic/core/crypto/crypto_handshake.h" #include "quiche/quic/core/crypto/crypto_handshake_message.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/crypto/crypto_secret_boxer.h" #include "quiche/quic/core/crypto/key_exchange.h" #include "quiche/quic/core/crypto/proof_source.h" #include "quiche/quic/core/crypto/quic_compressed_certs_cache.h" #include "quiche/quic/core/crypto/quic_crypto_proof.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/proto/cached_network_parameters_proto.h" #include "quiche/quic/core/proto/source_address_token_proto.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_mutex.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/common/platform/api/quiche_reference_counted.h" namespace quic { class CryptoHandshakeMessage; class ProofSource; class QuicClock; class QuicServerConfigProtobuf; struct QuicSignedServerConfig; struct QUICHE_EXPORT ClientHelloInfo { ClientHelloInfo(const QuicIpAddress& in_client_ip, QuicWallTime in_now); ClientHelloInfo(const ClientHelloInfo& other); ~ClientHelloInfo(); const QuicIpAddress client_ip; const QuicWallTime now; bool valid_source_address_token; absl::string_view sni; absl::string_view client_nonce; absl::string_view server_nonce; absl::string_view user_agent_id; SourceAddressTokens source_address_tokens; std::vector<uint32_t> reject_reasons; static_assert(sizeof(QuicTag) == sizeof(uint32_t), "header out of sync"); }; namespace test { class QuicCryptoServerConfigPeer; } class QUICHE_EXPORT PrimaryConfigChangedCallback { public: PrimaryConfigChangedCallback(); PrimaryConfigChangedCallback(const PrimaryConfigChangedCallback&) = delete; PrimaryConfigChangedCallback& operator=(const PrimaryConfigChangedCallback&) = delete; virtual ~PrimaryConfigChangedCallback(); virtual void Run(const std::string& scid) = 0; }; class QUICHE_EXPORT ValidateClientHelloResultCallback { public: struct QUICHE_EXPORT Result : public quiche::QuicheReferenceCounted { Result(const CryptoHandshakeMessage& in_client_hello, QuicIpAddress in_client_ip, QuicWallTime in_now); CryptoHandshakeMessage client_hello; ClientHelloInfo info; QuicErrorCode error_code; std::string error_details; CachedNetworkParameters cached_network_params; protected: ~Result() override; }; ValidateClientHelloResultCallback(); ValidateClientHelloResultCallback(const ValidateClientHelloResultCallback&) = delete; ValidateClientHelloResultCallback& operator=( const ValidateClientHelloResultCallback&) = delete; virtual ~ValidateClientHelloResultCallback(); virtual void Run(quiche::QuicheReferenceCountedPointer<Result> result, std::unique_ptr<ProofSource::Details> details) = 0; }; class QUICHE_EXPORT ProcessClientHelloResultCallback { public: ProcessClientHelloResultCallback(); ProcessClientHelloResultCallback(const ProcessClientHelloResultCallback&) = delete; ProcessClientHelloResultCallback& operator=( const ProcessClientHelloResultCallback&) = delete; virtual ~ProcessClientHelloResultCallback(); virtual void Run(QuicErrorCode error, const std::string& error_details, std::unique_ptr<CryptoHandshakeMessage> message, std::unique_ptr<DiversificationNonce> diversification_nonce, std::unique_ptr<ProofSource::Details> details) = 0; }; class QUICHE_EXPORT BuildServerConfigUpdateMessageResultCallback { public: BuildServerConfigUpdateMessageResultCallback() = default; virtual ~BuildServerConfigUpdateMessageResultCallback() {} BuildServerConfigUpdateMessageResultCallback( const BuildServerConfigUpdateMessageResultCallback&) = delete; BuildServerConfigUpdateMessageResultCallback& operator=( const BuildServerConfigUpdateMessageResultCallback&) = delete; virtual void Run(bool ok, const CryptoHandshakeMessage& message) = 0; }; class QUICHE_EXPORT RejectionObserver { public: RejectionObserver() = default; virtual ~RejectionObserver() {} RejectionObserver(const RejectionObserver&) = delete; RejectionObserver& operator=(const RejectionObserver&) = delete; virtual void OnRejectionBuilt(const std::vector<uint32_t>& reasons, CryptoHandshakeMessage* out) const = 0; }; class QUICHE_EXPORT KeyExchangeSource { public: virtual ~KeyExchangeSource() = default; static std::unique_ptr<KeyExchangeSource> Default(); virtual std::unique_ptr<AsynchronousKeyExchange> Create( std::string server_config_id, bool is_fallback, QuicTag type, absl::string_view private_key) = 0; }; class QUICHE_EXPORT QuicCryptoServerConfig { public: struct QUICHE_EXPORT ConfigOptions { ConfigOptions(); ConfigOptions(const ConfigOptions& other); ~ConfigOptions(); QuicWallTime expiry_time; bool channel_id_enabled; std::string id; std::string orbit; bool p256; }; QuicCryptoServerConfig( absl::string_view source_address_token_secret, QuicRandom* server_nonce_entropy, std::unique_ptr<ProofSource> proof_source, std::unique_ptr<KeyExchangeSource> key_exchange_source); QuicCryptoServerConfig(const QuicCryptoServerConfig&) = delete; QuicCryptoServerConfig& operator=(const QuicCryptoServerConfig&) = delete; ~QuicCryptoServerConfig(); static const char TESTING[]; static QuicServerConfigProtobuf GenerateConfig(QuicRandom* rand, const QuicClock* clock, const ConfigOptions& options); std::unique_ptr<CryptoHandshakeMessage> AddConfig( const QuicServerConfigProtobuf& protobuf, QuicWallTime now); std::unique_ptr<CryptoHandshakeMessage> AddDefaultConfig( QuicRandom* rand, const QuicClock* clock, const ConfigOptions& options); bool SetConfigs(const std::vector<QuicServerConfigProtobuf>& protobufs, const QuicServerConfigProtobuf* fallback_protobuf, QuicWallTime now); void SetSourceAddressTokenKeys(const std::vector<std::string>& keys); std::vector<std::string> GetConfigIds() const; void ValidateClientHello( const CryptoHandshakeMessage& client_hello, const QuicSocketAddress& client_address, const QuicSocketAddress& server_address, QuicTransportVersion version, const QuicClock* clock, quiche::QuicheReferenceCountedPointer<QuicSignedServerConfig> signed_config, std::unique_ptr<ValidateClientHelloResultCallback> done_cb) const; void ProcessClientHello( quiche::QuicheReferenceCountedPointer< ValidateClientHelloResultCallback::Result> validate_chlo_result, bool reject_only, QuicConnectionId connection_id, const QuicSocketAddress& server_address, const QuicSocketAddress& client_address, ParsedQuicVersion version, const ParsedQuicVersionVector& supported_versions, const QuicClock* clock, QuicRandom* rand, QuicCompressedCertsCache* compressed_certs_cache, quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> params, quiche::QuicheReferenceCountedPointer<QuicSignedServerConfig> signed_config, QuicByteCount total_framing_overhead, QuicByteCount chlo_packet_size, std::shared_ptr<ProcessClientHelloResultCallback> done_cb) const; void BuildServerConfigUpdateMessage( QuicTransportVersion version, absl::string_view chlo_hash, const SourceAddressTokens& previous_source_address_tokens, const QuicSocketAddress& server_address, const QuicSocketAddress& client_address, const QuicClock* clock, QuicRandom* rand, QuicCompressedCertsCache* compressed_certs_cache, const QuicCryptoNegotiatedParameters& params, const CachedNetworkParameters* cached_network_params, std::unique_ptr<BuildServerConfigUpdateMessageResultCallback> cb) const; void set_replay_protection(bool on); void set_chlo_multiplier(size_t multiplier); void set_validate_chlo_size(bool new_value) { validate_chlo_size_ = new_value; } bool validate_chlo_size() const { return validate_chlo_size_; } void set_validate_source_address_token(bool new_value) { validate_source_address_token_ = new_value; } void set_source_address_token_future_secs(uint32_t future_secs); void set_source_address_token_lifetime_secs(uint32_t lifetime_secs); void set_enable_serving_sct(bool enable_serving_sct); void AcquirePrimaryConfigChangedCb( std::unique_ptr<PrimaryConfigChangedCallback> cb); int NumberOfConfigs() const; std::string NewSourceAddressToken( const CryptoSecretBoxer& crypto_secret_boxer, const SourceAddressTokens& previous_tokens, const QuicIpAddress& ip, QuicRandom* rand, QuicWallTime now, const CachedNetworkParameters* cached_network_params) const; HandshakeFailureReason ParseSourceAddressToken( const CryptoSecretBoxer& crypto_secret_boxer, absl::string_view token, SourceAddressTokens& tokens) const; HandshakeFailureReason ValidateSourceAddressTokens( const SourceAddressTokens& tokens, const QuicIpAddress& ip, QuicWallTime now, CachedNetworkParameters* cached_network_params) const; void set_rejection_observer(RejectionObserver* rejection_observer) { rejection_observer_ = rejection_observer; } ProofSource* proof_source() const; SSL_CTX* ssl_ctx() const; const std::vector<uint16_t>& preferred_groups() const { return preferred_groups_; } void set_preferred_groups(const std::vector<uint16_t>& preferred_groups) { preferred_groups_ = preferred_groups; } const std::string& pre_shared_key() const { return pre_shared_key_; } void set_pre_shared_key(absl::string_view psk) { pre_shared_key_ = std::string(psk); } bool pad_rej() const { return pad_rej_; } void set_pad_rej(bool new_value) { pad_rej_ = new_value; } bool pad_shlo() const { return pad_shlo_; } void set_pad_shlo(bool new_value) { pad_shlo_ = new_value; } const CryptoSecretBoxer& source_address_token_boxer() const { return source_address_token_boxer_; } const QuicSSLConfig& ssl_config() const { return ssl_config_; } private: friend class test::QuicCryptoServerConfigPeer; friend struct QuicSignedServerConfig; class QUICHE_EXPORT Config : public QuicCryptoConfig, public quiche::QuicheReferenceCounted { public: Config(); Config(const Config&) = delete; Config& operator=(const Config&) = delete; std::string serialized; std::string id; unsigned char orbit[kOrbitSize]; std::vector<std::unique_ptr<AsynchronousKeyExchange>> key_exchanges; bool channel_id_enabled; bool is_primary; QuicWallTime primary_time; QuicWallTime expiry_time; uint64_t priority; const CryptoSecretBoxer* source_address_token_boxer; std::unique_ptr<CryptoSecretBoxer> source_address_token_boxer_storage; private: ~Config() override; }; using ConfigMap = std::map<ServerConfigID, quiche::QuicheReferenceCountedPointer<Config>>; quiche::QuicheReferenceCountedPointer<Config> GetConfigWithScid( absl::string_view requested_scid) const QUIC_SHARED_LOCKS_REQUIRED(configs_lock_); struct QUICHE_EXPORT Configs { quiche::QuicheReferenceCountedPointer<Config> requested; quiche::QuicheReferenceCountedPointer<Config> primary; quiche::QuicheReferenceCountedPointer<Config> fallback; }; bool GetCurrentConfigs( const QuicWallTime& now, absl::string_view requested_scid, quiche::QuicheReferenceCountedPointer<Config> old_primary_config, Configs* configs) const; static bool ConfigPrimaryTimeLessThan( const quiche::QuicheReferenceCountedPointer<Config>& a, const quiche::QuicheReferenceCountedPointer<Config>& b); void SelectNewPrimaryConfig(QuicWallTime now) const QUIC_EXCLUSIVE_LOCKS_REQUIRED(configs_lock_); void EvaluateClientHello( const QuicSocketAddress& server_address, const QuicSocketAddress& client_address, QuicTransportVersion version, const Configs& configs, quiche::QuicheReferenceCountedPointer< ValidateClientHelloResultCallback::Result> client_hello_state, std::unique_ptr<ValidateClientHelloResultCallback> done_cb) const; class QUICHE_EXPORT ProcessClientHelloContext { public: ProcessClientHelloContext( quiche::QuicheReferenceCountedPointer< ValidateClientHelloResultCallback::Result> validate_chlo_result, bool reject_only, QuicConnectionId connection_id, const QuicSocketAddress& server_address, const QuicSocketAddress& client_address, ParsedQuicVersion version, const ParsedQuicVersionVector& supported_versions, const QuicClock* clock, QuicRandom* rand, QuicCompressedCertsCache* compressed_certs_cache, quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> params, quiche::QuicheReferenceCountedPointer<QuicSignedServerConfig> signed_config, QuicByteCount total_framing_overhead, QuicByteCount chlo_packet_size, std::shared_ptr<ProcessClientHelloResultCallback> done_cb) : validate_chlo_result_(validate_chlo_result), reject_only_(reject_only), connection_id_(connection_id), server_address_(server_address), client_address_(client_address), version_(version), supported_versions_(supported_versions), clock_(clock), rand_(rand), compressed_certs_cache_(compressed_certs_cache), params_(params), signed_config_(signed_config), total_framing_overhead_(total_framing_overhead), chlo_packet_size_(chlo_packet_size), done_cb_(std::move(done_cb)) {} ~ProcessClientHelloContext(); void Fail(QuicErrorCode error, const std::string& error_details); void Succeed(std::unique_ptr<CryptoHandshakeMessage> message, std::unique_ptr<DiversificationNonce> diversification_nonce, std::unique_ptr<ProofSource::Details> proof_source_details); quiche::QuicheReferenceCountedPointer< ValidateClientHelloResultCallback::Result> validate_chlo_result() const { return validate_chlo_result_; } bool reject_only() const { return reject_only_; } QuicConnectionId connection_id() const { return connection_id_; } QuicSocketAddress server_address() const { return server_address_; } QuicSocketAddress client_address() const { return client_address_; } ParsedQuicVersion version() const { return version_; } ParsedQuicVersionVector supported_versions() const { return supported_versions_; } const QuicClock* clock() const { return clock_; } QuicRandom* rand() const { return rand_; } QuicCompressedCertsCache* compressed_certs_cache() const { return compressed_certs_cache_; } quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> params() const { return params_; } quiche::QuicheReferenceCountedPointer<QuicSignedServerConfig> signed_config() const { return signed_config_; } QuicByteCount total_framing_overhead() const { return total_framing_overhead_; } QuicByteCount chlo_packet_size() const { return chlo_packet_size_; } const CryptoHandshakeMessage& client_hello() const { return validate_chlo_result()->client_hello; } const ClientHelloInfo& info() const { return validate_chlo_result()->info; } QuicTransportVersion transport_version() const { return version().transport_version; } private: const quiche::QuicheReferenceCountedPointer< ValidateClientHelloResultCallback::Result> validate_chlo_result_; const bool reject_only_; const QuicConnectionId connection_id_; const QuicSocketAddress server_address_; const QuicSocketAddress client_address_; const ParsedQuicVersion version_; const ParsedQuicVersionVector supported_versions_; const QuicClock* const clock_; QuicRandom* const rand_; QuicCompressedCertsCache* const compressed_certs_cache_; const quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> params_; const quiche::QuicheReferenceCountedPointer<QuicSignedServerConfig> signed_config_; const QuicByteCount total_framing_overhead_; const QuicByteCount chlo_packet_size_; std::shared_ptr<ProcessClientHelloResultCallback> done_cb_; }; class ProcessClientHelloCallback; friend class ProcessClientHelloCallback; void ProcessClientHelloAfterGetProof( bool found_error, std::unique_ptr<ProofSource::Details> proof_source_details, std::unique_ptr<ProcessClientHelloContext> context, const Configs& configs) const; class ProcessClientHelloAfterGetProofCallback; friend class ProcessClientHelloAfterGetProofCallback; void ProcessClientHelloAfterCalculateSharedKeys( bool found_error, std::unique_ptr<ProofSource::Details> proof_source_details, QuicTag key_exchange_type, std::unique_ptr<CryptoHandshakeMessage> out, absl::string_view public_value, std::unique_ptr<ProcessClientHelloContext> context, const Configs& configs) const; void SendRejectWithFallbackConfig( std::unique_ptr<ProcessClientHelloContext> context, quiche::QuicheReferenceCountedPointer<Config> fallback_config) const; class SendRejectWithFallbackConfigCallback; friend class SendRejectWithFallbackConfigCallback;
#include "quiche/quic/core/crypto/quic_crypto_server_config.h" #include <stdarg.h> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/cert_compressor.h" #include "quiche/quic/core/crypto/chacha20_poly1305_encrypter.h" #include "quiche/quic/core/crypto/crypto_handshake_message.h" #include "quiche/quic/core/crypto/crypto_secret_boxer.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/proto/crypto_server_config_proto.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/crypto_test_utils.h" #include "quiche/quic/test_tools/mock_clock.h" #include "quiche/quic/test_tools/quic_crypto_server_config_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { namespace test { using ::testing::Not; MATCHER_P(SerializedProtoEquals, message, "") { std::string expected_serialized, actual_serialized; message.SerializeToString(&expected_serialized); arg.SerializeToString(&actual_serialized); return expected_serialized == actual_serialized; } class QuicCryptoServerConfigTest : public QuicTest {}; TEST_F(QuicCryptoServerConfigTest, ServerConfig) { QuicRandom* rand = QuicRandom::GetInstance(); QuicCryptoServerConfig server(QuicCryptoServerConfig::TESTING, rand, crypto_test_utils::ProofSourceForTesting(), KeyExchangeSource::Default()); MockClock clock; std::unique_ptr<CryptoHandshakeMessage> message(server.AddDefaultConfig( rand, &clock, QuicCryptoServerConfig::ConfigOptions())); QuicTagVector aead; ASSERT_THAT(message->GetTaglist(kAEAD, &aead), IsQuicNoError()); EXPECT_THAT(aead, ::testing::Contains(kAESG)); EXPECT_LE(1u, aead.size()); } TEST_F(QuicCryptoServerConfigTest, CompressCerts) { QuicCompressedCertsCache compressed_certs_cache( QuicCompressedCertsCache::kQuicCompressedCertsCacheSize); QuicRandom* rand = QuicRandom::GetInstance(); QuicCryptoServerConfig server(QuicCryptoServerConfig::TESTING, rand, crypto_test_utils::ProofSourceForTesting(), KeyExchangeSource::Default()); QuicCryptoServerConfigPeer peer(&server); std::vector<std::string> certs = {"testcert"}; quiche::QuicheReferenceCountedPointer<ProofSource::Chain> chain( new ProofSource::Chain(certs)); std::string compressed = QuicCryptoServerConfigPeer::CompressChain( &compressed_certs_cache, chain, ""); EXPECT_EQ(compressed_certs_cache.Size(), 1u); } TEST_F(QuicCryptoServerConfigTest, CompressSameCertsTwice) { QuicCompressedCertsCache compressed_certs_cache( QuicCompressedCertsCache::kQuicCompressedCertsCacheSize); QuicRandom* rand = QuicRandom::GetInstance(); QuicCryptoServerConfig server(QuicCryptoServerConfig::TESTING, rand, crypto_test_utils::ProofSourceForTesting(), KeyExchangeSource::Default()); QuicCryptoServerConfigPeer peer(&server); std::vector<std::string> certs = {"testcert"}; quiche::QuicheReferenceCountedPointer<ProofSource::Chain> chain( new ProofSource::Chain(certs)); std::string cached_certs = ""; std::string compressed = QuicCryptoServerConfigPeer::CompressChain( &compressed_certs_cache, chain, cached_certs); EXPECT_EQ(compressed_certs_cache.Size(), 1u); std::string compressed2 = QuicCryptoServerConfigPeer::CompressChain( &compressed_certs_cache, chain, cached_certs); EXPECT_EQ(compressed, compressed2); EXPECT_EQ(compressed_certs_cache.Size(), 1u); } TEST_F(QuicCryptoServerConfigTest, CompressDifferentCerts) { QuicCompressedCertsCache compressed_certs_cache( QuicCompressedCertsCache::kQuicCompressedCertsCacheSize); QuicRandom* rand = QuicRandom::GetInstance(); QuicCryptoServerConfig server(QuicCryptoServerConfig::TESTING, rand, crypto_test_utils::ProofSourceForTesting(), KeyExchangeSource::Default()); QuicCryptoServerConfigPeer peer(&server); std::vector<std::string> certs = {"testcert"}; quiche::QuicheReferenceCountedPointer<ProofSource::Chain> chain( new ProofSource::Chain(certs)); std::string cached_certs = ""; std::string compressed = QuicCryptoServerConfigPeer::CompressChain( &compressed_certs_cache, chain, cached_certs); EXPECT_EQ(compressed_certs_cache.Size(), 1u); quiche::QuicheReferenceCountedPointer<ProofSource::Chain> chain2( new ProofSource::Chain(certs)); std::string compressed2 = QuicCryptoServerConfigPeer::CompressChain( &compressed_certs_cache, chain2, cached_certs); EXPECT_EQ(compressed_certs_cache.Size(), 2u); } class SourceAddressTokenTest : public QuicTest { public: SourceAddressTokenTest() : ip4_(QuicIpAddress::Loopback4()), ip4_dual_(ip4_.DualStacked()), ip6_(QuicIpAddress::Loopback6()), original_time_(QuicWallTime::Zero()), rand_(QuicRandom::GetInstance()), server_(QuicCryptoServerConfig::TESTING, rand_, crypto_test_utils::ProofSourceForTesting(), KeyExchangeSource::Default()), peer_(&server_) { clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1000000)); original_time_ = clock_.WallNow(); primary_config_ = server_.AddDefaultConfig( rand_, &clock_, QuicCryptoServerConfig::ConfigOptions()); } std::string NewSourceAddressToken(std::string config_id, const QuicIpAddress& ip) { return NewSourceAddressToken(config_id, ip, nullptr); } std::string NewSourceAddressToken( std::string config_id, const QuicIpAddress& ip, const SourceAddressTokens& previous_tokens) { return peer_.NewSourceAddressToken(config_id, previous_tokens, ip, rand_, clock_.WallNow(), nullptr); } std::string NewSourceAddressToken( std::string config_id, const QuicIpAddress& ip, CachedNetworkParameters* cached_network_params) { SourceAddressTokens previous_tokens; return peer_.NewSourceAddressToken(config_id, previous_tokens, ip, rand_, clock_.WallNow(), cached_network_params); } HandshakeFailureReason ValidateSourceAddressTokens(std::string config_id, absl::string_view srct, const QuicIpAddress& ip) { return ValidateSourceAddressTokens(config_id, srct, ip, nullptr); } HandshakeFailureReason ValidateSourceAddressTokens( std::string config_id, absl::string_view srct, const QuicIpAddress& ip, CachedNetworkParameters* cached_network_params) { return peer_.ValidateSourceAddressTokens( config_id, srct, ip, clock_.WallNow(), cached_network_params); } const std::string kPrimary = "<primary>"; const std::string kOverride = "Config with custom source address token key"; QuicIpAddress ip4_; QuicIpAddress ip4_dual_; QuicIpAddress ip6_; MockClock clock_; QuicWallTime original_time_; QuicRandom* rand_ = QuicRandom::GetInstance(); QuicCryptoServerConfig server_; QuicCryptoServerConfigPeer peer_; std::unique_ptr<CryptoHandshakeMessage> primary_config_; std::unique_ptr<QuicServerConfigProtobuf> override_config_protobuf_; }; TEST_F(SourceAddressTokenTest, SourceAddressToken) { const std::string token4 = NewSourceAddressToken(kPrimary, ip4_); const std::string token4d = NewSourceAddressToken(kPrimary, ip4_dual_); const std::string token6 = NewSourceAddressToken(kPrimary, ip6_); EXPECT_EQ(HANDSHAKE_OK, ValidateSourceAddressTokens(kPrimary, token4, ip4_)); ASSERT_EQ(HANDSHAKE_OK, ValidateSourceAddressTokens(kPrimary, token4, ip4_dual_)); ASSERT_EQ(SOURCE_ADDRESS_TOKEN_DIFFERENT_IP_ADDRESS_FAILURE, ValidateSourceAddressTokens(kPrimary, token4, ip6_)); ASSERT_EQ(HANDSHAKE_OK, ValidateSourceAddressTokens(kPrimary, token4d, ip4_)); ASSERT_EQ(HANDSHAKE_OK, ValidateSourceAddressTokens(kPrimary, token4d, ip4_dual_)); ASSERT_EQ(SOURCE_ADDRESS_TOKEN_DIFFERENT_IP_ADDRESS_FAILURE, ValidateSourceAddressTokens(kPrimary, token4d, ip6_)); ASSERT_EQ(HANDSHAKE_OK, ValidateSourceAddressTokens(kPrimary, token6, ip6_)); } TEST_F(SourceAddressTokenTest, SourceAddressTokenExpiration) { const std::string token = NewSourceAddressToken(kPrimary, ip4_); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(-3600 * 2)); ASSERT_EQ(SOURCE_ADDRESS_TOKEN_CLOCK_SKEW_FAILURE, ValidateSourceAddressTokens(kPrimary, token, ip4_)); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(86400 * 7)); ASSERT_EQ(SOURCE_ADDRESS_TOKEN_EXPIRED_FAILURE, ValidateSourceAddressTokens(kPrimary, token, ip4_)); } TEST_F(SourceAddressTokenTest, SourceAddressTokenWithNetworkParams) { CachedNetworkParameters cached_network_params_input; cached_network_params_input.set_bandwidth_estimate_bytes_per_second(1234); const std::string token4_with_cached_network_params = NewSourceAddressToken(kPrimary, ip4_, &cached_network_params_input); CachedNetworkParameters cached_network_params_output; EXPECT_THAT(cached_network_params_output, Not(SerializedProtoEquals(cached_network_params_input))); ValidateSourceAddressTokens(kPrimary, token4_with_cached_network_params, ip4_, &cached_network_params_output); EXPECT_THAT(cached_network_params_output, SerializedProtoEquals(cached_network_params_input)); } TEST_F(SourceAddressTokenTest, SourceAddressTokenMultipleAddresses) { QuicWallTime now = clock_.WallNow(); SourceAddressToken previous_token; previous_token.set_ip(ip6_.DualStacked().ToPackedString()); previous_token.set_timestamp(now.ToUNIXSeconds()); SourceAddressTokens previous_tokens; (*previous_tokens.add_tokens()) = previous_token; const std::string token4or6 = NewSourceAddressToken(kPrimary, ip4_, previous_tokens); EXPECT_EQ(HANDSHAKE_OK, ValidateSourceAddressTokens(kPrimary, token4or6, ip4_)); ASSERT_EQ(HANDSHAKE_OK, ValidateSourceAddressTokens(kPrimary, token4or6, ip6_)); } class CryptoServerConfigsTest : public QuicTest { public: CryptoServerConfigsTest() : rand_(QuicRandom::GetInstance()), config_(QuicCryptoServerConfig::TESTING, rand_, crypto_test_utils::ProofSourceForTesting(), KeyExchangeSource::Default()), test_peer_(&config_) {} void SetUp() override { clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1000)); } struct ServerConfigIDWithTimeAndPriority { ServerConfigID server_config_id; int primary_time; int priority; }; void SetConfigs(std::vector<ServerConfigIDWithTimeAndPriority> configs) { const char kOrbit[] = "12345678"; bool has_invalid = false; std::vector<QuicServerConfigProtobuf> protobufs; for (const auto& config : configs) { const ServerConfigID& server_config_id = config.server_config_id; const int primary_time = config.primary_time; const int priority = config.priority; QuicCryptoServerConfig::ConfigOptions options; options.id = server_config_id; options.orbit = kOrbit; QuicServerConfigProtobuf protobuf = QuicCryptoServerConfig::GenerateConfig(rand_, &clock_, options); protobuf.set_primary_time(primary_time); protobuf.set_priority(priority); if (absl::StartsWith(std::string(server_config_id), "INVALID")) { protobuf.clear_key(); has_invalid = true; } protobufs.push_back(std::move(protobuf)); } ASSERT_EQ(!has_invalid && !configs.empty(), config_.SetConfigs(protobufs, nullptr, clock_.WallNow())); } protected: QuicRandom* const rand_; MockClock clock_; QuicCryptoServerConfig config_; QuicCryptoServerConfigPeer test_peer_; }; TEST_F(CryptoServerConfigsTest, NoConfigs) { test_peer_.CheckConfigs(std::vector<std::pair<std::string, bool>>()); } TEST_F(CryptoServerConfigsTest, MakePrimaryFirst) { SetConfigs({{"a", 1100, 1}, {"b", 900, 1}}); test_peer_.CheckConfigs({{"a", false}, {"b", true}}); } TEST_F(CryptoServerConfigsTest, MakePrimarySecond) { SetConfigs({{"a", 900, 1}, {"b", 1100, 1}}); test_peer_.CheckConfigs({{"a", true}, {"b", false}}); } TEST_F(CryptoServerConfigsTest, Delete) { SetConfigs({{"a", 800, 1}, {"b", 900, 1}, {"c", 1100, 1}}); test_peer_.CheckConfigs({{"a", false}, {"b", true}, {"c", false}}); SetConfigs({{"b", 900, 1}, {"c", 1100, 1}}); test_peer_.CheckConfigs({{"b", true}, {"c", false}}); } TEST_F(CryptoServerConfigsTest, DeletePrimary) { SetConfigs({{"a", 800, 1}, {"b", 900, 1}, {"c", 1100, 1}}); test_peer_.CheckConfigs({{"a", false}, {"b", true}, {"c", false}}); SetConfigs({{"a", 800, 1}, {"c", 1100, 1}}); test_peer_.CheckConfigs({{"a", true}, {"c", false}}); } TEST_F(CryptoServerConfigsTest, FailIfDeletingAllConfigs) { SetConfigs({{"a", 800, 1}, {"b", 900, 1}}); test_peer_.CheckConfigs({{"a", false}, {"b", true}}); SetConfigs(std::vector<ServerConfigIDWithTimeAndPriority>()); test_peer_.CheckConfigs({{"a", false}, {"b", true}}); } TEST_F(CryptoServerConfigsTest, ChangePrimaryTime) { SetConfigs({{"a", 400, 1}, {"b", 800, 1}, {"c", 1200, 1}}); test_peer_.SelectNewPrimaryConfig(500); test_peer_.CheckConfigs({{"a", true}, {"b", false}, {"c", false}}); SetConfigs({{"a", 1200, 1}, {"b", 800, 1}, {"c", 400, 1}}); test_peer_.SelectNewPrimaryConfig(500); test_peer_.CheckConfigs({{"a", false}, {"b", false}, {"c", true}}); } TEST_F(CryptoServerConfigsTest, AllConfigsInThePast) { SetConfigs({{"a", 400, 1}, {"b", 800, 1}, {"c", 1200, 1}}); test_peer_.SelectNewPrimaryConfig(1500); test_peer_.CheckConfigs({{"a", false}, {"b", false}, {"c", true}}); } TEST_F(CryptoServerConfigsTest, AllConfigsInTheFuture) { SetConfigs({{"a", 400, 1}, {"b", 800, 1}, {"c", 1200, 1}}); test_peer_.SelectNewPrimaryConfig(100); test_peer_.CheckConfigs({{"a", true}, {"b", false}, {"c", false}}); } TEST_F(CryptoServerConfigsTest, SortByPriority) { SetConfigs({{"a", 900, 1}, {"b", 900, 2}, {"c", 900, 3}}); test_peer_.CheckConfigs({{"a", true}, {"b", false}, {"c", false}}); test_peer_.SelectNewPrimaryConfig(800); test_peer_.CheckConfigs({{"a", true}, {"b", false}, {"c", false}}); test_peer_.SelectNewPrimaryConfig(1000); test_peer_.CheckConfigs({{"a", true}, {"b", false}, {"c", false}}); SetConfigs({{"a", 900, 2}, {"b", 900, 1}, {"c", 900, 0}}); test_peer_.CheckConfigs({{"a", false}, {"b", false}, {"c", true}}); test_peer_.SelectNewPrimaryConfig(800); test_peer_.CheckConfigs({{"a", false}, {"b", false}, {"c", true}}); test_peer_.SelectNewPrimaryConfig(1000); test_peer_.CheckConfigs({{"a", false}, {"b", false}, {"c", true}}); } TEST_F(CryptoServerConfigsTest, AdvancePrimary) { SetConfigs({{"a", 900, 1}, {"b", 1100, 1}}); test_peer_.SelectNewPrimaryConfig(1000); test_peer_.CheckConfigs({{"a", true}, {"b", false}}); test_peer_.SelectNewPrimaryConfig(1101); test_peer_.CheckConfigs({{"a", false}, {"b", true}}); } class ValidateCallback : public ValidateClientHelloResultCallback { public: void Run(quiche::QuicheReferenceCountedPointer<Result> , std::unique_ptr<ProofSource::Details> ) override {} }; TEST_F(CryptoServerConfigsTest, AdvancePrimaryViaValidate) { SetConfigs({{"a", 900, 1}, {"b", 1100, 1}}); test_peer_.SelectNewPrimaryConfig(1000); test_peer_.CheckConfigs({{"a", true}, {"b", false}}); CryptoHandshakeMessage client_hello; QuicSocketAddress client_address; QuicSocketAddress server_address; QuicTransportVersion transport_version = QUIC_VERSION_UNSUPPORTED; for (const ParsedQuicVersion& version : AllSupportedVersions()) { if (version.handshake_protocol == PROTOCOL_QUIC_CRYPTO) { transport_version = version.transport_version; break; } } ASSERT_NE(transport_version, QUIC_VERSION_UNSUPPORTED); MockClock clock; quiche::QuicheReferenceCountedPointer<QuicSignedServerConfig> signed_config( new QuicSignedServerConfig); std::unique_ptr<ValidateClientHelloResultCallback> done_cb( new ValidateCallback); clock.AdvanceTime(QuicTime::Delta::FromSeconds(1100)); config_.ValidateClientHello(client_hello, client_address, server_address, transport_version, &clock, signed_config, std::move(done_cb)); test_peer_.CheckConfigs({{"a", false}, {"b", true}}); } TEST_F(CryptoServerConfigsTest, InvalidConfigs) { SetConfigs({{"a", 800, 1}, {"b", 900, 1}, {"c", 1100, 1}}); test_peer_.CheckConfigs({{"a", false}, {"b", true}, {"c", false}}); SetConfigs({{"a", 800, 1}, {"c", 1100, 1}, {"INVALID1", 1000, 1}}); test_peer_.CheckConfigs({{"a", false}, {"b", true}, {"c", false}}); } } }
353
cpp
google/quiche
certificate_view
quiche/quic/core/crypto/certificate_view.cc
quiche/quic/core/crypto/certificate_view_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_CERTIFICATE_VIEW_H_ #define QUICHE_QUIC_CORE_CRYPTO_CERTIFICATE_VIEW_H_ #include <istream> #include <memory> #include <optional> #include <vector> #include "absl/strings/string_view.h" #include "openssl/base.h" #include "openssl/bytestring.h" #include "openssl/evp.h" #include "quiche/quic/core/crypto/boring_utils.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/quic/platform/api/quic_ip_address.h" namespace quic { struct QUICHE_EXPORT PemReadResult { enum Status { kOk, kEof, kError }; Status status; std::string contents; std::string type; }; QUICHE_EXPORT PemReadResult ReadNextPemMessage(std::istream* input); enum class PublicKeyType { kRsa, kP256, kP384, kEd25519, kUnknown, }; QUICHE_EXPORT std::string PublicKeyTypeToString(PublicKeyType type); QUICHE_EXPORT PublicKeyType PublicKeyTypeFromSignatureAlgorithm(uint16_t signature_algorithm); QUICHE_EXPORT QuicSignatureAlgorithmVector SupportedSignatureAlgorithmsForQuic(); class QUICHE_EXPORT CertificateView { public: static std::unique_ptr<CertificateView> ParseSingleCertificate( absl::string_view certificate); static std::vector<std::string> LoadPemFromStream(std::istream* input); QuicWallTime validity_start() const { return validity_start_; } QuicWallTime validity_end() const { return validity_end_; } const EVP_PKEY* public_key() const { return public_key_.get(); } const std::vector<absl::string_view>& subject_alt_name_domains() const { return subject_alt_name_domains_; } const std::vector<QuicIpAddress>& subject_alt_name_ips() const { return subject_alt_name_ips_; } std::optional<std::string> GetHumanReadableSubject() const; bool VerifySignature(absl::string_view data, absl::string_view signature, uint16_t signature_algorithm) const; PublicKeyType public_key_type() const; private: CertificateView() = default; QuicWallTime validity_start_ = QuicWallTime::Zero(); QuicWallTime validity_end_ = QuicWallTime::Zero(); absl::string_view subject_der_; bssl::UniquePtr<EVP_PKEY> public_key_; std::vector<absl::string_view> subject_alt_name_domains_; std::vector<QuicIpAddress> subject_alt_name_ips_; bool ParseExtensions(CBS extensions); bool ValidatePublicKeyParameters(); }; class QUICHE_EXPORT CertificatePrivateKey { public: explicit CertificatePrivateKey(bssl::UniquePtr<EVP_PKEY> private_key) : private_key_(std::move(private_key)) {} static std::unique_ptr<CertificatePrivateKey> LoadFromDer( absl::string_view private_key); static std::unique_ptr<CertificatePrivateKey> LoadPemFromStream( std::istream* input); std::string Sign(absl::string_view input, uint16_t signature_algorithm) const; bool MatchesPublicKey(const CertificateView& view) const; bool ValidForSignatureAlgorithm(uint16_t signature_algorithm) const; EVP_PKEY* private_key() const { return private_key_.get(); } private: CertificatePrivateKey() = default; bssl::UniquePtr<EVP_PKEY> private_key_; }; QUICHE_EXPORT std::optional<std::string> X509NameAttributeToString(CBS input); QUICHE_EXPORT std::optional<quic::QuicWallTime> ParseDerTime( unsigned tag, absl::string_view payload); } #endif #include "quiche/quic/core/crypto/certificate_view.h" #include <algorithm> #include <cstdint> #include <istream> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/strings/escaping.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "openssl/base.h" #include "openssl/bytestring.h" #include "openssl/digest.h" #include "openssl/ec.h" #include "openssl/ec_key.h" #include "openssl/evp.h" #include "openssl/nid.h" #include "openssl/rsa.h" #include "openssl/ssl.h" #include "quiche/quic/core/crypto/boring_utils.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/common/platform/api/quiche_time_utils.h" #include "quiche/common/quiche_data_reader.h" #include "quiche/common/quiche_text_utils.h" namespace quic { namespace { using ::quiche::QuicheTextUtils; constexpr uint8_t kX509Version[] = {0x02, 0x01, 0x02}; constexpr uint8_t kSubjectAltNameOid[] = {0x55, 0x1d, 0x11}; PublicKeyType PublicKeyTypeFromKey(EVP_PKEY* public_key) { switch (EVP_PKEY_id(public_key)) { case EVP_PKEY_RSA: return PublicKeyType::kRsa; case EVP_PKEY_EC: { const EC_KEY* key = EVP_PKEY_get0_EC_KEY(public_key); if (key == nullptr) { return PublicKeyType::kUnknown; } const EC_GROUP* group = EC_KEY_get0_group(key); if (group == nullptr) { return PublicKeyType::kUnknown; } const int curve_nid = EC_GROUP_get_curve_name(group); switch (curve_nid) { case NID_X9_62_prime256v1: return PublicKeyType::kP256; case NID_secp384r1: return PublicKeyType::kP384; default: return PublicKeyType::kUnknown; } } case EVP_PKEY_ED25519: return PublicKeyType::kEd25519; default: return PublicKeyType::kUnknown; } } } PublicKeyType PublicKeyTypeFromSignatureAlgorithm( uint16_t signature_algorithm) { switch (signature_algorithm) { case SSL_SIGN_RSA_PSS_RSAE_SHA256: return PublicKeyType::kRsa; case SSL_SIGN_ECDSA_SECP256R1_SHA256: return PublicKeyType::kP256; case SSL_SIGN_ECDSA_SECP384R1_SHA384: return PublicKeyType::kP384; case SSL_SIGN_ED25519: return PublicKeyType::kEd25519; default: return PublicKeyType::kUnknown; } } QUICHE_EXPORT QuicSignatureAlgorithmVector SupportedSignatureAlgorithmsForQuic() { return QuicSignatureAlgorithmVector{ SSL_SIGN_ED25519, SSL_SIGN_ECDSA_SECP256R1_SHA256, SSL_SIGN_ECDSA_SECP384R1_SHA384, SSL_SIGN_RSA_PSS_RSAE_SHA256}; } namespace { std::string AttributeNameToString(const CBS& oid_cbs) { absl::string_view oid = CbsToStringPiece(oid_cbs); if (oid.length() == 3 && absl::StartsWith(oid, "\x55\x04")) { switch (oid[2]) { case '\x3': return "CN"; case '\x7': return "L"; case '\x8': return "ST"; case '\xa': return "O"; case '\xb': return "OU"; case '\x6': return "C"; } } bssl::UniquePtr<char> oid_representation(CBS_asn1_oid_to_text(&oid_cbs)); if (oid_representation == nullptr) { return absl::StrCat("(", absl::BytesToHexString(oid), ")"); } return std::string(oid_representation.get()); } } std::optional<std::string> X509NameAttributeToString(CBS input) { CBS name, value; unsigned value_tag; if (!CBS_get_asn1(&input, &name, CBS_ASN1_OBJECT) || !CBS_get_any_asn1(&input, &value, &value_tag) || CBS_len(&input) != 0) { return std::nullopt; } return absl::StrCat(AttributeNameToString(name), "=", absl::CHexEscape(CbsToStringPiece(value))); } namespace { template <unsigned inner_tag, char separator, std::optional<std::string> (*parser)(CBS)> std::optional<std::string> ParseAndJoin(CBS input) { std::vector<std::string> pieces; while (CBS_len(&input) != 0) { CBS attribute; if (!CBS_get_asn1(&input, &attribute, inner_tag)) { return std::nullopt; } std::optional<std::string> formatted = parser(attribute); if (!formatted.has_value()) { return std::nullopt; } pieces.push_back(*formatted); } return absl::StrJoin(pieces, std::string({separator})); } std::optional<std::string> RelativeDistinguishedNameToString(CBS input) { return ParseAndJoin<CBS_ASN1_SEQUENCE, '+', X509NameAttributeToString>(input); } std::optional<std::string> DistinguishedNameToString(CBS input) { return ParseAndJoin<CBS_ASN1_SET, ',', RelativeDistinguishedNameToString>( input); } } std::string PublicKeyTypeToString(PublicKeyType type) { switch (type) { case PublicKeyType::kRsa: return "RSA"; case PublicKeyType::kP256: return "ECDSA P-256"; case PublicKeyType::kP384: return "ECDSA P-384"; case PublicKeyType::kEd25519: return "Ed25519"; case PublicKeyType::kUnknown: return "unknown"; } return ""; } std::optional<quic::QuicWallTime> ParseDerTime(unsigned tag, absl::string_view payload) { if (tag != CBS_ASN1_GENERALIZEDTIME && tag != CBS_ASN1_UTCTIME) { QUIC_DLOG(WARNING) << "Invalid tag supplied for a DER timestamp"; return std::nullopt; } const size_t year_length = tag == CBS_ASN1_GENERALIZEDTIME ? 4 : 2; uint64_t year, month, day, hour, minute, second; quiche::QuicheDataReader reader(payload); if (!reader.ReadDecimal64(year_length, &year) || !reader.ReadDecimal64(2, &month) || !reader.ReadDecimal64(2, &day) || !reader.ReadDecimal64(2, &hour) || !reader.ReadDecimal64(2, &minute) || !reader.ReadDecimal64(2, &second) || reader.ReadRemainingPayload() != "Z") { QUIC_DLOG(WARNING) << "Failed to parse the DER timestamp"; return std::nullopt; } if (tag == CBS_ASN1_UTCTIME) { QUICHE_DCHECK_LE(year, 100u); year += (year >= 50) ? 1900 : 2000; } const std::optional<int64_t> unix_time = quiche::QuicheUtcDateTimeToUnixSeconds(year, month, day, hour, minute, second); if (!unix_time.has_value() || *unix_time < 0) { return std::nullopt; } return QuicWallTime::FromUNIXSeconds(*unix_time); } PemReadResult ReadNextPemMessage(std::istream* input) { constexpr absl::string_view kPemBegin = "-----BEGIN "; constexpr absl::string_view kPemEnd = "-----END "; constexpr absl::string_view kPemDashes = "-----"; std::string line_buffer, encoded_message_contents, expected_end; bool pending_message = false; PemReadResult result; while (std::getline(*input, line_buffer)) { absl::string_view line(line_buffer); QuicheTextUtils::RemoveLeadingAndTrailingWhitespace(&line); if (!pending_message && absl::StartsWith(line, kPemBegin) && absl::EndsWith(line, kPemDashes)) { result.type = std::string( line.substr(kPemBegin.size(), line.size() - kPemDashes.size() - kPemBegin.size())); expected_end = absl::StrCat(kPemEnd, result.type, kPemDashes); pending_message = true; continue; } if (pending_message && line == expected_end) { std::optional<std::string> data = QuicheTextUtils::Base64Decode(encoded_message_contents); if (data.has_value()) { result.status = PemReadResult::kOk; result.contents = *data; } else { result.status = PemReadResult::kError; } return result; } if (pending_message) { encoded_message_contents.append(std::string(line)); } } bool eof_reached = input->eof() && !pending_message; return PemReadResult{ (eof_reached ? PemReadResult::kEof : PemReadResult::kError), "", ""}; } std::unique_ptr<CertificateView> CertificateView::ParseSingleCertificate( absl::string_view certificate) { std::unique_ptr<CertificateView> result(new CertificateView()); CBS top = StringPieceToCbs(certificate); CBS top_certificate, tbs_certificate, signature_algorithm, signature; if (!CBS_get_asn1(&top, &top_certificate, CBS_ASN1_SEQUENCE) || CBS_len(&top) != 0) { return nullptr; } if ( !CBS_get_asn1(&top_certificate, &tbs_certificate, CBS_ASN1_SEQUENCE) || !CBS_get_asn1(&top_certificate, &signature_algorithm, CBS_ASN1_SEQUENCE) || !CBS_get_asn1(&top_certificate, &signature, CBS_ASN1_BITSTRING) || CBS_len(&top_certificate) != 0) { return nullptr; } int has_version, has_extensions; CBS version, serial, signature_algorithm_inner, issuer, validity, subject, spki, issuer_id, subject_id, extensions_outer; if ( !CBS_get_optional_asn1( &tbs_certificate, &version, &has_version, CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0) || !CBS_get_asn1(&tbs_certificate, &serial, CBS_ASN1_INTEGER) || !CBS_get_asn1(&tbs_certificate, &signature_algorithm_inner, CBS_ASN1_SEQUENCE) || !CBS_get_asn1(&tbs_certificate, &issuer, CBS_ASN1_SEQUENCE) || !CBS_get_asn1(&tbs_certificate, &validity, CBS_ASN1_SEQUENCE) || !CBS_get_asn1(&tbs_certificate, &subject, CBS_ASN1_SEQUENCE) || !CBS_get_asn1_element(&tbs_certificate, &spki, CBS_ASN1_SEQUENCE) || !CBS_get_optional_asn1(&tbs_certificate, &issuer_id, nullptr, CBS_ASN1_CONTEXT_SPECIFIC | 1) || !CBS_get_optional_asn1(&tbs_certificate, &subject_id, nullptr, CBS_ASN1_CONTEXT_SPECIFIC | 2) || !CBS_get_optional_asn1( &tbs_certificate, &extensions_outer, &has_extensions, CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 3) || CBS_len(&tbs_certificate) != 0) { return nullptr; } result->subject_der_ = CbsToStringPiece(subject); unsigned not_before_tag, not_after_tag; CBS not_before, not_after; if (!CBS_get_any_asn1(&validity, &not_before, &not_before_tag) || !CBS_get_any_asn1(&validity, &not_after, &not_after_tag) || CBS_len(&validity) != 0) { QUIC_DLOG(WARNING) << "Failed to extract the validity dates"; return nullptr; } std::optional<QuicWallTime> not_before_parsed = ParseDerTime(not_before_tag, CbsToStringPiece(not_before)); std::optional<QuicWallTime> not_after_parsed = ParseDerTime(not_after_tag, CbsToStringPiece(not_after)); if (!not_before_parsed.has_value() || !not_after_parsed.has_value()) { QUIC_DLOG(WARNING) << "Failed to parse validity dates"; return nullptr; } result->validity_start_ = *not_before_parsed; result->validity_end_ = *not_after_parsed; result->public_key_.reset(EVP_parse_public_key(&spki)); if (result->public_key_ == nullptr) { QUIC_DLOG(WARNING) << "Failed to parse the public key"; return nullptr; } if (!result->ValidatePublicKeyParameters()) { QUIC_DLOG(WARNING) << "Public key has invalid parameters"; return nullptr; } if (!has_version || !CBS_mem_equal(&version, kX509Version, sizeof(kX509Version))) { QUIC_DLOG(WARNING) << "Bad X.509 version"; return nullptr; } if (!has_extensions) { return nullptr; } CBS extensions; if (!CBS_get_asn1(&extensions_outer, &extensions, CBS_ASN1_SEQUENCE) || CBS_len(&extensions_outer) != 0) { QUIC_DLOG(WARNING) << "Failed to extract the extension sequence"; return nullptr; } if (!result->ParseExtensions(extensions)) { QUIC_DLOG(WARNING) << "Failed to parse extensions"; return nullptr; } return result; } bool CertificateView::ParseExtensions(CBS extensions) { while (CBS_len(&extensions) != 0) { CBS extension, oid, critical, payload; if ( !CBS_get_asn1(&extensions, &extension, CBS_ASN1_SEQUENCE) || !CBS_get_asn1(&extension, &oid, CBS_ASN1_OBJECT) || !CBS_get_optional_asn1(&extension, &critical, nullptr, CBS_ASN1_BOOLEAN) || !CBS_get_asn1(&extension, &payload, CBS_ASN1_OCTETSTRING) || CBS_len(&extension) != 0) { QUIC_DLOG(WARNING) << "Bad extension entry"; return false; } if (CBS_mem_equal(&oid, kSubjectAltNameOid, sizeof(kSubjectAltNameOid))) { CBS alt_names; if (!CBS_get_asn1(&payload, &alt_names, CBS_ASN1_SEQUENCE) || CBS_len(&payload) != 0) { QUIC_DLOG(WARNING) << "Failed to parse subjectAltName"; return false; } while (CBS_len(&alt_names) != 0) { CBS alt_name_cbs; unsigned int alt_name_tag; if (!CBS_get_any_asn1(&alt_names, &alt_name_cbs, &alt_name_tag)) { QUIC_DLOG(WARNING) << "Failed to parse subjectAltName"; return false; } absl::string_view alt_name = CbsToStringPiece(alt_name_cbs); QuicIpAddress ip_address; switch (alt_name_tag) { case CBS_ASN1_CONTEXT_SPECIFIC | 2: subject_alt_name_domains_.push_back(alt_name); break; case CBS_ASN1_CONTEXT_SPECIFIC | 7: if (!ip_address.FromPackedString(alt_name.data(), alt_name.size())) { QUIC_DLOG(WARNING) << "Failed to parse subjectAltName IP address"; return false; } subject_alt_name_ips_.push_back(ip_address); break; default: QUIC_DLOG(INFO) << "Unknown subjectAltName tag " << alt_name_tag; continue; } } } } return true; } std::vector<std::string> CertificateView::LoadPemFromStream( std::istream* input) { std::vector<std::string> result; for (;;) { PemReadResult read_result = ReadNextPemMessage(input); if (read_result.status == PemReadResult::kEof) { return result; } if (read_result.status != PemReadResult::kOk) { return std::vector<std::string>(); } if (read_result.type != "CERTIFICATE") { continue; } result.emplace_back(std::move(read_result.contents)); } } PublicKeyType CertificateView::public_key_type() const { return PublicKeyTypeFromKey(public_key_.get()); } bool CertificateView::ValidatePublicKeyParameters() { PublicKeyType key_type = PublicKeyTypeFromKey(public_key_.get()); switch (key_type) { case PublicKeyType::kRsa: return EVP_PKEY_bits(public_key_.get()) >= 2048; case PublicKeyType::kP256: case PublicKeyType::kP384: case PublicKeyType::kEd25519: return true; default: return false; } } bool CertificateView::VerifySignature(absl::string_view data, absl::string_view signature, uint16_t signature_algorithm) const { if (PublicKeyTypeFromSignatureAlgorithm(signature_algorithm) != PublicKeyTypeFromKey(public_key_.get())) { QUIC_BUG(quic_bug_10640_1) << "Mismatch between the requested signature algorithm and the " "type of the public key."; return false; } bssl::ScopedEVP_MD_CTX md_ctx; EVP_PKEY_CTX* pctx; if (!EVP_DigestVerifyInit( md_ctx.get(), &pctx, SSL_get_signature_algorithm_digest(signature_algorithm), nullptr, public_key_.get())) { return false; } if (SSL_is_signature_algorithm_rsa_pss(signature_algorithm)) { if (!EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) || !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1)) { return false; } } return EVP_DigestVerify( md_ctx.get(), reinterpret_cast<const uint8_t*>(signature.data()), signature.size(), reinterpret_cast<const uint8_t*>(data.data()), data.size()); } std::optional<std::string> CertificateView::GetHumanReadableSubject() const { CBS input = StringPieceToCbs(subject_der_); return DistinguishedNameToString(input); } std::unique_ptr<CertificatePrivateKey> CertificatePrivateKey::LoadFromDer( absl::string_view private_key) { std::unique_ptr<CertificatePrivateKey> result(new CertificatePrivateKey()); CBS private_key_cbs = StringPieceToCbs(private_key); result->private_key_.reset(EVP_parse_private_key(&private_key_cbs)); if (result->private_key_ == nullptr || CBS_len(&private_key_cbs) != 0) { return nullptr; } return result; } std::unique_ptr<CertificatePrivateKey> CertificatePrivateKey::LoadPemFromStream( std::istream* input) { skip: PemReadResult result = ReadNextPemMessage(input); if (result.status != PemReadResult::kOk) { return nullptr; } if (result.type == "PRIVATE KEY") { return LoadFromDer(result.contents); } if (result.type == "RSA PRIVATE KEY") { CBS private_key_cbs = StringPieceToCbs(result.contents); bssl::UniquePtr<RSA> rsa(RSA_parse_private_key(&private_key_cbs)); if (rsa == nullptr || CBS_len(&private_key_cbs) != 0) { return nullptr; } std::unique_ptr<CertificatePrivateKey> key(new CertificatePrivateKey()); key->private_key_.reset(EVP_PKEY_new()); EVP_PKEY_assign_RSA(key->private_key_.get(), rsa.release()); return key; } if (result.type == "EC PARAMETERS") { goto skip; } if (result.type == "EC PRIVATE KEY") { CBS private_key_cbs = StringPieceToCbs(result.contents); bssl::UniquePtr<EC_KEY> ec_key( EC_KEY_parse_private_key(&private_key_cbs, nullptr)); if (ec_key == nullptr || CBS_len(&private_key_cbs) != 0) { return nullptr; } std::unique_ptr<CertificatePrivateKey> key(new CertificatePrivateKey()); key->private_key_.reset(EVP_PKEY_new()); EVP_PKEY_assign_EC_KEY(key->private_key_.get(), ec_key.release()); return key; } return nullptr; } std::string CertificatePrivateKey::Sign(absl::string_view input, uint16_t signature_algorithm) const { if (!ValidForSignatureAlgorithm(signature_algorithm)) { QUIC_BUG(quic_bug_10640_2) << "Mismatch between the requested signature algorithm and the " "type of the private key."; return ""; } bssl::ScopedEVP_MD_CTX md_ctx; EVP_PKEY_CTX* pctx; if (!EVP_DigestSignInit( md_ctx.get(), &pctx, SSL_get_signature_algorithm_digest(signature_algorithm), nullptr, private_key_.get())) { return ""; } if (SSL_is_signature_algorithm_rsa_pss(signature_algorithm)) { if (!EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) || !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1)) { return ""; } } std::string output; size_t output_size; if (!EVP_DigestSign(md_ctx.get(), nullptr, &output_size, reinterpret_cast<const uint8_t*>(input.data()), input.size())) { return ""; } output.resize(output_size); if (!EVP_DigestSign( md_ctx.get(), reinterpret_cast<uint8_t*>(&output[0]), &output_size, reinterpret_cast<const uint8_t*>(input.data()), input.size())) { return ""; } output.resize(output_size); return output; } bool CertificatePrivateKey::MatchesPublicKey( const CertificateView& view) const { return EVP_PKEY_cmp(view.public_key(), private_key_.get()) == 1; } bool CertificatePrivateKey::ValidForSignatureAlgorithm( uint16_t signature_algorithm) const { return PublicKeyTypeFromSignatureAlgorithm(signature_algorithm) == PublicKeyTypeFromKey(private_key_.get()); } }
#include "quiche/quic/core/crypto/certificate_view.h" #include <limits> #include <memory> #include <sstream> #include <string> #include <vector> #include "absl/algorithm/container.h" #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "openssl/base.h" #include "openssl/bytestring.h" #include "openssl/evp.h" #include "openssl/ssl.h" #include "quiche/quic/core/crypto/boring_utils.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/test_certificates.h" #include "quiche/common/platform/api/quiche_time_utils.h" namespace quic { namespace test { namespace { using ::testing::ElementsAre; using ::testing::HasSubstr; using ::testing::Optional; TEST(CertificateViewTest, PemParser) { std::stringstream stream(kTestCertificatePem); PemReadResult result = ReadNextPemMessage(&stream); EXPECT_EQ(result.status, PemReadResult::kOk); EXPECT_EQ(result.type, "CERTIFICATE"); EXPECT_EQ(result.contents, kTestCertificate); result = ReadNextPemMessage(&stream); EXPECT_EQ(result.status, PemReadResult::kEof); } TEST(CertificateViewTest, Parse) { std::unique_ptr<CertificateView> view = CertificateView::ParseSingleCertificate(kTestCertificate); ASSERT_TRUE(view != nullptr); EXPECT_THAT(view->subject_alt_name_domains(), ElementsAre(absl::string_view("www.example.org"), absl::string_view("mail.example.org"), absl::string_view("mail.example.com"))); EXPECT_THAT(view->subject_alt_name_ips(), ElementsAre(QuicIpAddress::Loopback4())); EXPECT_EQ(EVP_PKEY_id(view->public_key()), EVP_PKEY_RSA); const QuicWallTime validity_start = QuicWallTime::FromUNIXSeconds( *quiche::QuicheUtcDateTimeToUnixSeconds(2020, 1, 30, 18, 13, 59)); EXPECT_EQ(view->validity_start(), validity_start); const QuicWallTime validity_end = QuicWallTime::FromUNIXSeconds( *quiche::QuicheUtcDateTimeToUnixSeconds(2020, 2, 2, 18, 13, 59)); EXPECT_EQ(view->validity_end(), validity_end); EXPECT_EQ(view->public_key_type(), PublicKeyType::kRsa); EXPECT_EQ(PublicKeyTypeToString(view->public_key_type()), "RSA"); EXPECT_EQ("C=US,ST=California,L=Mountain View,O=QUIC Server,CN=127.0.0.1", view->GetHumanReadableSubject()); } TEST(CertificateViewTest, ParseCertWithUnknownSanType) { std::stringstream stream(kTestCertWithUnknownSanTypePem); PemReadResult result = ReadNextPemMessage(&stream); EXPECT_EQ(result.status, PemReadResult::kOk); EXPECT_EQ(result.type, "CERTIFICATE"); std::unique_ptr<CertificateView> view = CertificateView::ParseSingleCertificate(result.contents); EXPECT_TRUE(view != nullptr); } TEST(CertificateViewTest, PemSingleCertificate) { std::stringstream pem_stream(kTestCertificatePem); std::vector<std::string> chain = CertificateView::LoadPemFromStream(&pem_stream); EXPECT_THAT(chain, ElementsAre(kTestCertificate)); } TEST(CertificateViewTest, PemMultipleCertificates) { std::stringstream pem_stream(kTestCertificateChainPem); std::vector<std::string> chain = CertificateView::LoadPemFromStream(&pem_stream); EXPECT_THAT(chain, ElementsAre(kTestCertificate, HasSubstr("QUIC Server Root CA"))); } TEST(CertificateViewTest, PemNoCertificates) { std::stringstream pem_stream("one\ntwo\nthree\n"); std::vector<std::string> chain = CertificateView::LoadPemFromStream(&pem_stream); EXPECT_TRUE(chain.empty()); } TEST(CertificateViewTest, SignAndVerify) { std::unique_ptr<CertificatePrivateKey> key = CertificatePrivateKey::LoadFromDer(kTestCertificatePrivateKey); ASSERT_TRUE(key != nullptr); std::string data = "A really important message"; std::string signature = key->Sign(data, SSL_SIGN_RSA_PSS_RSAE_SHA256); ASSERT_FALSE(signature.empty()); std::unique_ptr<CertificateView> view = CertificateView::ParseSingleCertificate(kTestCertificate); ASSERT_TRUE(view != nullptr); EXPECT_TRUE(key->MatchesPublicKey(*view)); EXPECT_TRUE( view->VerifySignature(data, signature, SSL_SIGN_RSA_PSS_RSAE_SHA256)); EXPECT_FALSE(view->VerifySignature("An unimportant message", signature, SSL_SIGN_RSA_PSS_RSAE_SHA256)); EXPECT_FALSE(view->VerifySignature(data, "Not a signature", SSL_SIGN_RSA_PSS_RSAE_SHA256)); } TEST(CertificateViewTest, PrivateKeyPem) { std::unique_ptr<CertificateView> view = CertificateView::ParseSingleCertificate(kTestCertificate); ASSERT_TRUE(view != nullptr); std::stringstream pem_stream(kTestCertificatePrivateKeyPem); std::unique_ptr<CertificatePrivateKey> pem_key = CertificatePrivateKey::LoadPemFromStream(&pem_stream); ASSERT_TRUE(pem_key != nullptr); EXPECT_TRUE(pem_key->MatchesPublicKey(*view)); std::stringstream legacy_stream(kTestCertificatePrivateKeyLegacyPem); std::unique_ptr<CertificatePrivateKey> legacy_key = CertificatePrivateKey::LoadPemFromStream(&legacy_stream); ASSERT_TRUE(legacy_key != nullptr); EXPECT_TRUE(legacy_key->MatchesPublicKey(*view)); } TEST(CertificateViewTest, PrivateKeyEcdsaPem) { std::stringstream pem_stream(kTestEcPrivateKeyLegacyPem); std::unique_ptr<CertificatePrivateKey> key = CertificatePrivateKey::LoadPemFromStream(&pem_stream); ASSERT_TRUE(key != nullptr); EXPECT_TRUE(key->ValidForSignatureAlgorithm(SSL_SIGN_ECDSA_SECP256R1_SHA256)); } TEST(CertificateViewTest, DerTime) { EXPECT_THAT(ParseDerTime(CBS_ASN1_GENERALIZEDTIME, "19700101000024Z"), Optional(QuicWallTime::FromUNIXSeconds(24))); EXPECT_THAT(ParseDerTime(CBS_ASN1_GENERALIZEDTIME, "19710101000024Z"), Optional(QuicWallTime::FromUNIXSeconds(365 * 86400 + 24))); EXPECT_THAT(ParseDerTime(CBS_ASN1_UTCTIME, "700101000024Z"), Optional(QuicWallTime::FromUNIXSeconds(24))); EXPECT_TRUE(ParseDerTime(CBS_ASN1_UTCTIME, "200101000024Z").has_value()); EXPECT_EQ(ParseDerTime(CBS_ASN1_GENERALIZEDTIME, ""), std::nullopt); EXPECT_EQ(ParseDerTime(CBS_ASN1_GENERALIZEDTIME, "19700101000024.001Z"), std::nullopt); EXPECT_EQ(ParseDerTime(CBS_ASN1_GENERALIZEDTIME, "19700101000024Q"), std::nullopt); EXPECT_EQ(ParseDerTime(CBS_ASN1_GENERALIZEDTIME, "19700101000024-0500"), std::nullopt); EXPECT_EQ(ParseDerTime(CBS_ASN1_GENERALIZEDTIME, "700101000024ZZ"), std::nullopt); EXPECT_EQ(ParseDerTime(CBS_ASN1_GENERALIZEDTIME, "19700101000024.00Z"), std::nullopt); EXPECT_EQ(ParseDerTime(CBS_ASN1_GENERALIZEDTIME, "19700101000024.Z"), std::nullopt); EXPECT_EQ(ParseDerTime(CBS_ASN1_GENERALIZEDTIME, "197O0101000024Z"), std::nullopt); EXPECT_EQ(ParseDerTime(CBS_ASN1_GENERALIZEDTIME, "19700101000024.0O1Z"), std::nullopt); EXPECT_EQ(ParseDerTime(CBS_ASN1_GENERALIZEDTIME, "-9700101000024Z"), std::nullopt); EXPECT_EQ(ParseDerTime(CBS_ASN1_GENERALIZEDTIME, "1970-101000024Z"), std::nullopt); EXPECT_TRUE(ParseDerTime(CBS_ASN1_UTCTIME, "490101000024Z").has_value()); EXPECT_FALSE(ParseDerTime(CBS_ASN1_UTCTIME, "500101000024Z").has_value()); EXPECT_THAT(ParseDerTime(CBS_ASN1_GENERALIZEDTIME, "19700101230000Z"), Optional(QuicWallTime::FromUNIXSeconds(23 * 3600))); EXPECT_EQ(ParseDerTime(CBS_ASN1_GENERALIZEDTIME, "19700101240000Z"), std::nullopt); } TEST(CertificateViewTest, NameAttribute) { std::string unknown_oid; ASSERT_TRUE(absl::HexStringToBytes("060b2a864886f712040186ee1b0c0454657374", &unknown_oid)); EXPECT_EQ("1.2.840.113554.4.1.112411=Test", X509NameAttributeToString(StringPieceToCbs(unknown_oid))); std::string non_printable; ASSERT_TRUE( absl::HexStringToBytes("06035504030c0742656c6c3a2007", &non_printable)); EXPECT_EQ(R"(CN=Bell: \x07)", X509NameAttributeToString(StringPieceToCbs(non_printable))); std::string invalid_oid; ASSERT_TRUE(absl::HexStringToBytes("060255800c0454657374", &invalid_oid)); EXPECT_EQ("(5580)=Test", X509NameAttributeToString(StringPieceToCbs(invalid_oid))); } TEST(CertificateViewTest, SupportedSignatureAlgorithmsForQuicIsUpToDate) { QuicSignatureAlgorithmVector supported = SupportedSignatureAlgorithmsForQuic(); for (int i = 0; i < std::numeric_limits<uint16_t>::max(); i++) { uint16_t sigalg = static_cast<uint16_t>(i); PublicKeyType key_type = PublicKeyTypeFromSignatureAlgorithm(sigalg); if (absl::c_find(supported, sigalg) == supported.end()) { EXPECT_EQ(key_type, PublicKeyType::kUnknown); } else { EXPECT_NE(key_type, PublicKeyType::kUnknown); } } } } } }
354
cpp
google/quiche
cert_compressor
quiche/quic/core/crypto/cert_compressor.cc
quiche/quic/core/crypto/cert_compressor_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_CERT_COMPRESSOR_H_ #define QUICHE_QUIC_CORE_CRYPTO_CERT_COMPRESSOR_H_ #include <string> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT CertCompressor { public: CertCompressor() = delete; static std::string CompressChain(const std::vector<std::string>& certs, absl::string_view client_cached_cert_hashes); static bool DecompressChain(absl::string_view in, const std::vector<std::string>& cached_certs, std::vector<std::string>* out_certs); }; } #endif #include "quiche/quic/core/crypto/cert_compressor.h" #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "zlib.h" namespace quic { namespace { static const unsigned char kCommonCertSubstrings[] = { 0x04, 0x02, 0x30, 0x00, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x25, 0x04, 0x16, 0x30, 0x14, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x02, 0x30, 0x5f, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x86, 0xf8, 0x42, 0x04, 0x01, 0x06, 0x06, 0x0b, 0x60, 0x86, 0x48, 0x01, 0x86, 0xfd, 0x6d, 0x01, 0x07, 0x17, 0x01, 0x30, 0x33, 0x20, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x64, 0x65, 0x64, 0x20, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x53, 0x20, 0x4c, 0x69, 0x6d, 0x69, 0x74, 0x65, 0x64, 0x31, 0x34, 0x20, 0x53, 0x53, 0x4c, 0x20, 0x43, 0x41, 0x30, 0x1e, 0x17, 0x0d, 0x31, 0x32, 0x20, 0x53, 0x65, 0x63, 0x75, 0x72, 0x65, 0x20, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x43, 0x41, 0x30, 0x2d, 0x61, 0x69, 0x61, 0x2e, 0x76, 0x65, 0x72, 0x69, 0x73, 0x69, 0x67, 0x6e, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x45, 0x2d, 0x63, 0x72, 0x6c, 0x2e, 0x76, 0x65, 0x72, 0x69, 0x73, 0x69, 0x67, 0x6e, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x45, 0x2e, 0x63, 0x65, 0x72, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x03, 0x82, 0x01, 0x01, 0x00, 0x4a, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x2f, 0x63, 0x70, 0x73, 0x20, 0x28, 0x63, 0x29, 0x30, 0x30, 0x09, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04, 0x02, 0x30, 0x00, 0x30, 0x1d, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x03, 0x82, 0x01, 0x01, 0x00, 0x7b, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 0x00, 0xd2, 0x6f, 0x64, 0x6f, 0x63, 0x61, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x43, 0x2e, 0x63, 0x72, 0x6c, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0xb4, 0x2e, 0x67, 0x6c, 0x6f, 0x62, 0x61, 0x6c, 0x73, 0x69, 0x67, 0x6e, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x72, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x04, 0x04, 0x03, 0x02, 0x01, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x30, 0x81, 0xca, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x10, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x07, 0x41, 0x72, 0x69, 0x7a, 0x6f, 0x6e, 0x61, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x07, 0x13, 0x0a, 0x53, 0x63, 0x6f, 0x74, 0x74, 0x73, 0x64, 0x61, 0x6c, 0x65, 0x31, 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x11, 0x47, 0x6f, 0x44, 0x61, 0x64, 0x64, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2c, 0x20, 0x49, 0x6e, 0x63, 0x2e, 0x31, 0x33, 0x30, 0x31, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x13, 0x2a, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x63, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x73, 0x2e, 0x67, 0x6f, 0x64, 0x61, 0x64, 0x64, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x72, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x31, 0x30, 0x30, 0x2e, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x27, 0x47, 0x6f, 0x20, 0x44, 0x61, 0x64, 0x64, 0x79, 0x20, 0x53, 0x65, 0x63, 0x75, 0x72, 0x65, 0x20, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x31, 0x11, 0x30, 0x0f, 0x06, 0x03, 0x55, 0x04, 0x05, 0x13, 0x08, 0x30, 0x37, 0x39, 0x36, 0x39, 0x32, 0x38, 0x37, 0x30, 0x1e, 0x17, 0x0d, 0x31, 0x31, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x01, 0x01, 0xff, 0x04, 0x04, 0x03, 0x02, 0x05, 0xa0, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x01, 0x01, 0xff, 0x04, 0x02, 0x30, 0x00, 0x30, 0x1d, 0x30, 0x0f, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x01, 0x01, 0xff, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0x00, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x25, 0x04, 0x16, 0x30, 0x14, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x02, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x01, 0x01, 0xff, 0x04, 0x04, 0x03, 0x02, 0x05, 0xa0, 0x30, 0x33, 0x06, 0x03, 0x55, 0x1d, 0x1f, 0x04, 0x2c, 0x30, 0x2a, 0x30, 0x28, 0xa0, 0x26, 0xa0, 0x24, 0x86, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x63, 0x72, 0x6c, 0x2e, 0x67, 0x6f, 0x64, 0x61, 0x64, 0x64, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x64, 0x73, 0x31, 0x2d, 0x32, 0x30, 0x2a, 0x30, 0x28, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x02, 0x01, 0x16, 0x1c, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x76, 0x65, 0x72, 0x69, 0x73, 0x69, 0x67, 0x6e, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x70, 0x73, 0x30, 0x34, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x5a, 0x17, 0x0d, 0x31, 0x33, 0x30, 0x35, 0x30, 0x39, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x30, 0x02, 0x86, 0x2d, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x73, 0x30, 0x39, 0x30, 0x37, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x02, 0x30, 0x44, 0x06, 0x03, 0x55, 0x1d, 0x20, 0x04, 0x3d, 0x30, 0x3b, 0x30, 0x39, 0x06, 0x0b, 0x60, 0x86, 0x48, 0x01, 0x86, 0xf8, 0x45, 0x01, 0x07, 0x17, 0x06, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x47, 0x42, 0x31, 0x1b, 0x53, 0x31, 0x17, 0x30, 0x15, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x0e, 0x56, 0x65, 0x72, 0x69, 0x53, 0x69, 0x67, 0x6e, 0x2c, 0x20, 0x49, 0x6e, 0x63, 0x2e, 0x31, 0x1f, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x13, 0x16, 0x56, 0x65, 0x72, 0x69, 0x53, 0x69, 0x67, 0x6e, 0x20, 0x54, 0x72, 0x75, 0x73, 0x74, 0x20, 0x4e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x31, 0x3b, 0x30, 0x39, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x13, 0x32, 0x54, 0x65, 0x72, 0x6d, 0x73, 0x20, 0x6f, 0x66, 0x20, 0x75, 0x73, 0x65, 0x20, 0x61, 0x74, 0x20, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x76, 0x65, 0x72, 0x69, 0x73, 0x69, 0x67, 0x6e, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x72, 0x70, 0x61, 0x20, 0x28, 0x63, 0x29, 0x30, 0x31, 0x10, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x04, 0x07, 0x13, 0x07, 0x53, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x13, 0x0a, 0x47, 0x31, 0x13, 0x30, 0x11, 0x06, 0x0b, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x3c, 0x02, 0x01, 0x03, 0x13, 0x02, 0x55, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03, 0x55, 0x04, 0x03, 0x14, 0x31, 0x19, 0x30, 0x17, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x31, 0x1d, 0x30, 0x1b, 0x06, 0x03, 0x55, 0x04, 0x0f, 0x13, 0x14, 0x50, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x20, 0x4f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x31, 0x12, 0x31, 0x21, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x13, 0x18, 0x44, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x20, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, 0x20, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x65, 0x64, 0x31, 0x14, 0x31, 0x31, 0x30, 0x2f, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x13, 0x28, 0x53, 0x65, 0x65, 0x20, 0x77, 0x77, 0x77, 0x2e, 0x72, 0x3a, 0x2f, 0x2f, 0x73, 0x65, 0x63, 0x75, 0x72, 0x65, 0x2e, 0x67, 0x47, 0x6c, 0x6f, 0x62, 0x61, 0x6c, 0x53, 0x69, 0x67, 0x6e, 0x31, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x43, 0x41, 0x2e, 0x63, 0x72, 0x6c, 0x56, 0x65, 0x72, 0x69, 0x53, 0x69, 0x67, 0x6e, 0x20, 0x43, 0x6c, 0x61, 0x73, 0x73, 0x20, 0x33, 0x20, 0x45, 0x63, 0x72, 0x6c, 0x2e, 0x67, 0x65, 0x6f, 0x74, 0x72, 0x75, 0x73, 0x74, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x72, 0x6c, 0x73, 0x2f, 0x73, 0x64, 0x31, 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x45, 0x56, 0x49, 0x6e, 0x74, 0x6c, 0x2d, 0x63, 0x63, 0x72, 0x74, 0x2e, 0x67, 0x77, 0x77, 0x77, 0x2e, 0x67, 0x69, 0x63, 0x65, 0x72, 0x74, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x31, 0x6f, 0x63, 0x73, 0x70, 0x2e, 0x76, 0x65, 0x72, 0x69, 0x73, 0x69, 0x67, 0x6e, 0x2e, 0x63, 0x6f, 0x6d, 0x30, 0x39, 0x72, 0x61, 0x70, 0x69, 0x64, 0x73, 0x73, 0x6c, 0x2e, 0x63, 0x6f, 0x73, 0x2e, 0x67, 0x6f, 0x64, 0x61, 0x64, 0x64, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x72, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x2f, 0x30, 0x81, 0x80, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x01, 0x01, 0x04, 0x74, 0x30, 0x72, 0x30, 0x24, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x30, 0x01, 0x86, 0x18, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6f, 0x63, 0x73, 0x70, 0x2e, 0x67, 0x6f, 0x64, 0x61, 0x64, 0x64, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x30, 0x4a, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x30, 0x02, 0x86, 0x3e, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x63, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x73, 0x2e, 0x67, 0x6f, 0x64, 0x61, 0x64, 0x64, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x72, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x2f, 0x67, 0x64, 0x5f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6d, 0x65, 0x64, 0x69, 0x61, 0x74, 0x65, 0x2e, 0x63, 0x72, 0x74, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0xfd, 0xac, 0x61, 0x32, 0x93, 0x6c, 0x45, 0xd6, 0xe2, 0xee, 0x85, 0x5f, 0x9a, 0xba, 0xe7, 0x76, 0x99, 0x68, 0xcc, 0xe7, 0x30, 0x27, 0x86, 0x29, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x63, 0x86, 0x30, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x73, }; struct CertEntry { public: enum Type { COMPRESSED = 1, CACHED = 2, }; Type type; uint64_t hash; uint64_t set_hash; uint32_t index; }; std::vector<CertEntry> MatchCerts(const std::vector<std::string>& certs, absl::string_view client_cached_cert_hashes) { std::vector<CertEntry> entries; entries.reserve(certs.size()); const bool cached_valid = client_cached_cert_hashes.size() % sizeof(uint64_t) == 0 && !client_cached_cert_hashes.empty(); for (auto i = certs.begin(); i != certs.end(); ++i) { CertEntry entry; if (cached_valid) { bool cached = false; uint64_t hash = QuicUtils::FNV1a_64_Hash(*i); for (size_t j = 0; j < client_cached_cert_hashes.size(); j += sizeof(uint64_t)) { uint64_t cached_hash; memcpy(&cached_hash, client_cached_cert_hashes.data() + j, sizeof(uint64_t)); if (hash != cached_hash) { continue; } entry.type = CertEntry::CACHED; entry.hash = hash; entries.push_back(entry); cached = true; break; } if (cached) { continue; } } entry.type = CertEntry::COMPRESSED; entries.push_back(entry); } return entries; } size_t CertEntriesSize(const std::vector<CertEntry>& entries) { size_t entries_size = 0; for (auto i = entries.begin(); i != entries.end(); ++i) { entries_size++; switch (i->type) { case CertEntry::COMPRESSED: break; case CertEntry::CACHED: entries_size += sizeof(uint64_t); break; } } entries_size++; return entries_size; } void SerializeCertEntries(uint8_t* out, const std::vector<CertEntry>& entries) { for (auto i = entries.begin(); i != entries.end(); ++i) { *out++ = static_cast<uint8_t>(i->type); switch (i->type) { case CertEntry::COMPRESSED: break; case CertEntry::CACHED: memcpy(out, &i->hash, sizeof(i->hash)); out += sizeof(uint64_t); break; } } *out++ = 0; } std::string ZlibDictForEntries(const std::vector<CertEntry>& entries, const std::vector<std::string>& certs) { std::string zlib_dict; size_t zlib_dict_size = 0; for (size_t i = certs.size() - 1; i < certs.size(); i--) { if (entries[i].type != CertEntry::COMPRESSED) { zlib_dict_size += certs[i].size(); } } zlib_dict_size += sizeof(kCommonCertSubstrings); zlib_dict.reserve(zlib_dict_size); for (size_t i = certs.size() - 1; i < certs.size(); i--) { if (entries[i].type != CertEntry::COMPRESSED) { zlib_dict += certs[i]; } } zlib_dict += std::string(reinterpret_cast<const char*>(kCommonCertSubstrings), sizeof(kCommonCertSubstrings)); QUICHE_DCHECK_EQ(zlib_dict.size(), zlib_dict_size); return zlib_dict; } std::vector<uint64_t> HashCerts(const std::vector<std::string>& certs) { std::vector<uint64_t> ret; ret.reserve(certs.size()); for (auto i = certs.begin(); i != certs.end(); ++i) { ret.push_back(QuicUtils::FNV1a_64_Hash(*i)); } return ret; } bool ParseEntries(absl::string_view* in_out, const std::vector<std::string>& cached_certs, std::vector<CertEntry>* out_entries, std::vector<std::string>* out_certs) { absl::string_view in = *in_out; std::vector<uint64_t> cached_hashes; out_entries->clear(); out_certs->clear(); for (;;) { if (in.empty()) { return false; } CertEntry entry; const uint8_t type_byte = in[0]; in.remove_prefix(1); if (type_byte == 0) { break; } entry.type = static_cast<CertEntry::Type>(type_byte); switch (entry.type) { case CertEntry::COMPRESSED: out_certs->push_back(std::string()); break; case CertEntry::CACHED: { if (in.size() < sizeof(uint64_t)) { return false; } memcpy(&entry.hash, in.data(), sizeof(uint64_t)); in.remove_prefix(sizeof(uint64_t)); if (cached_hashes.size() != cached_certs.size()) { cached_hashes = HashCerts(cached_certs); } bool found = false; for (size_t i = 0; i < cached_hashes.size(); i++) { if (cached_hashes[i] == entry.hash) { out_certs->push_back(cached_certs[i]); found = true; break; } } if (!found) { return false; } break; } default: return false; } out_entries->push_back(entry); } *in_out = in; return true; } class ScopedZLib { public: enum Type { INFLATE, DEFLATE, }; explicit ScopedZLib(Type type) : z_(nullptr), type_(type) {} void reset(z_stream* z) { Clear(); z_ = z; } ~ScopedZLib() { Clear(); } private: void Clear() { if (!z_) { return; } if (type_ == DEFLATE) { deflateEnd(z_); } else { inflateEnd(z_); } z_ = nullptr; } z_stream* z_; const Type type_; }; } std::string CertCompressor::CompressChain( const std::vector<std::string>& certs, absl::string_view client_cached_cert_hashes) { const std::vector<CertEntry> entries = MatchCerts(certs, client_cached_cert_hashes); QUICHE_DCHECK_EQ(entries.size(), certs.size()); size_t uncompressed_size = 0; for (size_t i = 0; i < entries.size(); i++) { if (entries[i].type == CertEntry::COMPRESSED) { uncompressed_size += 4 + certs[i].size(); } } size_t compressed_size = 0; z_stream z; ScopedZLib scoped_z(ScopedZLib::DEFLATE); if (uncompressed_size > 0) { memset(&z, 0, sizeof(z)); int rv = deflateInit(&z, Z_DEFAULT_COMPRESSION); QUICHE_DCHECK_EQ(Z_OK, rv); if (rv != Z_OK) { return ""; } scoped_z.reset(&z); std::string zlib_dict = ZlibDictForEntries(entries, certs); rv = deflateSetDictionary( &z, reinterpret_cast<const uint8_t*>(&zlib_dict[0]), zlib_dict.size()); QUICHE_DCHECK_EQ(Z_OK, rv); if (rv != Z_OK) { return ""; } compressed_size = deflateBound(&z, uncompressed_size); } const size_t entries_size = CertEntriesSize(entries); std::string result; result.resize(entries_size + (uncompressed_size > 0 ? 4 : 0) + compressed_size); uint8_t* j = reinterpret_cast<uint8_t*>(&result[0]); SerializeCertEntries(j, entries); j += entries_size; if (uncompressed_size == 0) { return result; } uint32_t uncompressed_size_32 = uncompressed_size; memcpy(j, &uncompressed_size_32, sizeof(uint32_t)); j += sizeof(uint32_t); int rv; z.next_out = j; z.avail_out = compressed_size; for (size_t i = 0; i < certs.size(); i++) { if (entries[i].type != CertEntry::COMPRESSED) { continue; } uint32_t length32 = certs[i].size(); z.next_in = reinterpret_cast<uint8_t*>(&length32); z.avail_in = sizeof(length32); rv = deflate(&z, Z_NO_FLUSH); QUICHE_DCHECK_EQ(Z_OK, rv); QUICHE_DCHECK_EQ(0u, z.avail_in); if (rv != Z_OK || z.avail_in) { return ""; } z.next_in = const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(certs[i].data())); z.avail_in = certs[i].size(); rv = deflate(&z, Z_NO_FLUSH); QUICHE_DCHECK_EQ(Z_OK, rv); QUICHE_DCHECK_EQ(0u, z.avail_in); if (rv != Z_OK || z.avail_in) { return ""; } } z.avail_in = 0; rv = deflate(&z, Z_FINISH); QUICHE_DCHECK_EQ(Z_STREAM_END, rv); if (rv != Z_STREAM_END) { return ""; } result.resize(result.size() - z.avail_out); return result; } bool CertCompressor::DecompressChain( absl::string_view in, const std::vector<std::string>& cached_certs, std::vector<std::string>* out_certs) { std::vector<CertEntry> entries; if (!ParseEntries(&in, cached_certs, &entries, out_certs)) { return false; } QUICHE_DCHECK_EQ(entries.size(), out_certs->size()); std::unique_ptr<uint8_t[]> uncompressed_data; absl::string_view uncompressed; if (!in.empty()) { if (in.size() < sizeof(uint32_t)) { return false; } uint32_t uncompressed_size; memcpy(&uncompressed_size, in.data(), sizeof(uncompressed_size)); in.remove_prefix(sizeof(uint32_t)); if (uncompressed_size > 128 * 1024) { return false; } uncompressed_data = std::make_unique<uint8_t[]>(uncompressed_size); z_stream z; ScopedZLib scoped_z(ScopedZLib::INFLATE); memset(&z, 0, sizeof(z)); z.next_out = uncompressed_data.get(); z.avail_out = uncompressed_size; z.next_in = const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(in.data())); z.avail_in = in.size(); if (Z_OK != inflateInit(&z)) { return false; } scoped_z.reset(&z); int rv = inflate(&z, Z_FINISH); if (rv == Z_NEED_DICT) { std::string zlib_dict = ZlibDictForEntries(entries, *out_certs); const uint8_t* dict = reinterpret_cast<const uint8_t*>(zlib_dict.data()); if (Z_OK != inflateSetDictionary(&z, dict, zlib_dict.size())) { return false; } rv = inflate(&z, Z_FINISH); } if (Z_STREAM_END != rv || z.avail_out > 0 || z.avail_in > 0) { return false; } uncompressed = absl::string_view( reinterpret_cast<char*>(uncompressed_data.get()), uncompressed_size); } for (size_t i = 0; i < entries.size(); i++) { switch (entries[i].type) { case CertEntry::COMPRESSED: if (uncompressed.size() < sizeof(uint32_t)) { return false; } uint32_t cert_len; memcpy(&cert_len, uncompressed.data(), sizeof(cert_len)); uncompressed.remove_prefix(sizeof(uint32_t)); if (uncompressed.size() < cert_len) { return false; } (*out_certs)[i] = std::string(uncompressed.substr(0, cert_len)); uncompressed.remove_prefix(cert_len); break; case CertEntry::CACHED: break; } } if (!uncompressed.empty()) { return false; } return true; } }
#include "quiche/quic/core/crypto/cert_compressor.h" #include <memory> #include <string> #include <vector> #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/crypto_test_utils.h" namespace quic { namespace test { class CertCompressorTest : public QuicTest {}; TEST_F(CertCompressorTest, EmptyChain) { std::vector<std::string> chain; const std::string compressed = CertCompressor::CompressChain(chain, absl::string_view()); EXPECT_EQ("00", absl::BytesToHexString(compressed)); std::vector<std::string> chain2, cached_certs; ASSERT_TRUE( CertCompressor::DecompressChain(compressed, cached_certs, &chain2)); EXPECT_EQ(chain.size(), chain2.size()); } TEST_F(CertCompressorTest, Compressed) { std::vector<std::string> chain; chain.push_back("testcert"); const std::string compressed = CertCompressor::CompressChain(chain, absl::string_view()); ASSERT_GE(compressed.size(), 2u); EXPECT_EQ("0100", absl::BytesToHexString(compressed.substr(0, 2))); std::vector<std::string> chain2, cached_certs; ASSERT_TRUE( CertCompressor::DecompressChain(compressed, cached_certs, &chain2)); EXPECT_EQ(chain.size(), chain2.size()); EXPECT_EQ(chain[0], chain2[0]); } TEST_F(CertCompressorTest, Common) { std::vector<std::string> chain; chain.push_back("testcert"); static const uint64_t set_hash = 42; const std::string compressed = CertCompressor::CompressChain( chain, absl::string_view(reinterpret_cast<const char*>(&set_hash), sizeof(set_hash))); ASSERT_GE(compressed.size(), 2u); EXPECT_EQ("0100", absl::BytesToHexString(compressed.substr(0, 2))); std::vector<std::string> chain2, cached_certs; ASSERT_TRUE( CertCompressor::DecompressChain(compressed, cached_certs, &chain2)); EXPECT_EQ(chain.size(), chain2.size()); EXPECT_EQ(chain[0], chain2[0]); } TEST_F(CertCompressorTest, Cached) { std::vector<std::string> chain; chain.push_back("testcert"); uint64_t hash = QuicUtils::FNV1a_64_Hash(chain[0]); absl::string_view hash_bytes(reinterpret_cast<char*>(&hash), sizeof(hash)); const std::string compressed = CertCompressor::CompressChain(chain, hash_bytes); EXPECT_EQ("02" + absl::BytesToHexString(hash_bytes) + "00" , absl::BytesToHexString(compressed)); std::vector<std::string> cached_certs, chain2; cached_certs.push_back(chain[0]); ASSERT_TRUE( CertCompressor::DecompressChain(compressed, cached_certs, &chain2)); EXPECT_EQ(chain.size(), chain2.size()); EXPECT_EQ(chain[0], chain2[0]); } TEST_F(CertCompressorTest, BadInputs) { std::vector<std::string> cached_certs, chain; EXPECT_FALSE(CertCompressor::DecompressChain( absl::BytesToHexString("04") , cached_certs, &chain)); EXPECT_FALSE(CertCompressor::DecompressChain( absl::BytesToHexString("01") , cached_certs, &chain)); EXPECT_FALSE(CertCompressor::DecompressChain( absl::BytesToHexString("0200") , cached_certs, &chain)); EXPECT_FALSE(CertCompressor::DecompressChain( absl::BytesToHexString("0300") , cached_certs, &chain)); EXPECT_FALSE( CertCompressor::DecompressChain(absl::BytesToHexString("03" "0000000000000000" "00000000"), cached_certs, &chain)); EXPECT_FALSE( CertCompressor::DecompressChain(absl::BytesToHexString("03" "a200000000000000" "00000000"), cached_certs, &chain)); } } }
355
cpp
google/quiche
crypto_handshake_message
quiche/quic/core/crypto/crypto_handshake_message.cc
quiche/quic/core/crypto/crypto_handshake_message_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_CRYPTO_HANDSHAKE_MESSAGE_H_ #define QUICHE_QUIC_CORE_CRYPTO_CRYPTO_HANDSHAKE_MESSAGE_H_ #include <cstddef> #include <cstdint> #include <memory> #include <string> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT CryptoHandshakeMessage { public: CryptoHandshakeMessage(); CryptoHandshakeMessage(const CryptoHandshakeMessage& other); CryptoHandshakeMessage(CryptoHandshakeMessage&& other); ~CryptoHandshakeMessage(); CryptoHandshakeMessage& operator=(const CryptoHandshakeMessage& other); CryptoHandshakeMessage& operator=(CryptoHandshakeMessage&& other); bool operator==(const CryptoHandshakeMessage& rhs) const; bool operator!=(const CryptoHandshakeMessage& rhs) const; void Clear(); const QuicData& GetSerialized() const; void MarkDirty(); template <class T> void SetValue(QuicTag tag, const T& v) { tag_value_map_[tag] = std::string(reinterpret_cast<const char*>(&v), sizeof(v)); } template <class T> void SetVector(QuicTag tag, const std::vector<T>& v) { if (v.empty()) { tag_value_map_[tag] = std::string(); } else { tag_value_map_[tag] = std::string(reinterpret_cast<const char*>(&v[0]), v.size() * sizeof(T)); } } void SetVersion(QuicTag tag, ParsedQuicVersion version); void SetVersionVector(QuicTag tag, ParsedQuicVersionVector versions); QuicTag tag() const { return tag_; } void set_tag(QuicTag tag) { tag_ = tag; } const QuicTagValueMap& tag_value_map() const { return tag_value_map_; } void SetStringPiece(QuicTag tag, absl::string_view value); void Erase(QuicTag tag); QuicErrorCode GetTaglist(QuicTag tag, QuicTagVector* out_tags) const; QuicErrorCode GetVersionLabelList(QuicTag tag, QuicVersionLabelVector* out) const; QuicErrorCode GetVersionLabel(QuicTag tag, QuicVersionLabel* out) const; bool GetStringPiece(QuicTag tag, absl::string_view* out) const; bool HasStringPiece(QuicTag tag) const; QuicErrorCode GetNthValue24(QuicTag tag, unsigned index, absl::string_view* out) const; QuicErrorCode GetUint32(QuicTag tag, uint32_t* out) const; QuicErrorCode GetUint64(QuicTag tag, uint64_t* out) const; QuicErrorCode GetStatelessResetToken(QuicTag tag, StatelessResetToken* out) const; size_t size() const; void set_minimum_size(size_t min_bytes); size_t minimum_size() const; std::string DebugString() const; private: QuicErrorCode GetPOD(QuicTag tag, void* out, size_t len) const; std::string DebugStringInternal(size_t indent) const; QuicTag tag_; QuicTagValueMap tag_value_map_; size_t minimum_size_; mutable std::unique_ptr<QuicData> serialized_; }; } #endif #include "quiche/quic/core/crypto/crypto_handshake_message.h" #include <memory> #include <string> #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/crypto_framer.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/crypto/crypto_utils.h" #include "quiche/quic/core/quic_socket_address_coder.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/common/quiche_endian.h" namespace quic { CryptoHandshakeMessage::CryptoHandshakeMessage() : tag_(0), minimum_size_(0) {} CryptoHandshakeMessage::CryptoHandshakeMessage( const CryptoHandshakeMessage& other) : tag_(other.tag_), tag_value_map_(other.tag_value_map_), minimum_size_(other.minimum_size_) { } CryptoHandshakeMessage::CryptoHandshakeMessage(CryptoHandshakeMessage&& other) = default; CryptoHandshakeMessage::~CryptoHandshakeMessage() {} CryptoHandshakeMessage& CryptoHandshakeMessage::operator=( const CryptoHandshakeMessage& other) { tag_ = other.tag_; tag_value_map_ = other.tag_value_map_; serialized_.reset(); minimum_size_ = other.minimum_size_; return *this; } CryptoHandshakeMessage& CryptoHandshakeMessage::operator=( CryptoHandshakeMessage&& other) = default; bool CryptoHandshakeMessage::operator==( const CryptoHandshakeMessage& rhs) const { return tag_ == rhs.tag_ && tag_value_map_ == rhs.tag_value_map_ && minimum_size_ == rhs.minimum_size_; } bool CryptoHandshakeMessage::operator!=( const CryptoHandshakeMessage& rhs) const { return !(*this == rhs); } void CryptoHandshakeMessage::Clear() { tag_ = 0; tag_value_map_.clear(); minimum_size_ = 0; serialized_.reset(); } const QuicData& CryptoHandshakeMessage::GetSerialized() const { if (!serialized_) { serialized_ = CryptoFramer::ConstructHandshakeMessage(*this); } return *serialized_; } void CryptoHandshakeMessage::MarkDirty() { serialized_.reset(); } void CryptoHandshakeMessage::SetVersionVector( QuicTag tag, ParsedQuicVersionVector versions) { QuicVersionLabelVector version_labels; for (const ParsedQuicVersion& version : versions) { version_labels.push_back( quiche::QuicheEndian::HostToNet32(CreateQuicVersionLabel(version))); } SetVector(tag, version_labels); } void CryptoHandshakeMessage::SetVersion(QuicTag tag, ParsedQuicVersion version) { SetValue(tag, quiche::QuicheEndian::HostToNet32(CreateQuicVersionLabel(version))); } void CryptoHandshakeMessage::SetStringPiece(QuicTag tag, absl::string_view value) { tag_value_map_[tag] = std::string(value); } void CryptoHandshakeMessage::Erase(QuicTag tag) { tag_value_map_.erase(tag); } QuicErrorCode CryptoHandshakeMessage::GetTaglist( QuicTag tag, QuicTagVector* out_tags) const { auto it = tag_value_map_.find(tag); QuicErrorCode ret = QUIC_NO_ERROR; if (it == tag_value_map_.end()) { ret = QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND; } else if (it->second.size() % sizeof(QuicTag) != 0) { ret = QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER; } if (ret != QUIC_NO_ERROR) { out_tags->clear(); return ret; } size_t num_tags = it->second.size() / sizeof(QuicTag); out_tags->resize(num_tags); for (size_t i = 0; i < num_tags; ++i) { memcpy(&(*out_tags)[i], it->second.data() + i * sizeof(tag), sizeof(tag)); } return ret; } QuicErrorCode CryptoHandshakeMessage::GetVersionLabelList( QuicTag tag, QuicVersionLabelVector* out) const { QuicErrorCode error = GetTaglist(tag, out); if (error != QUIC_NO_ERROR) { return error; } for (size_t i = 0; i < out->size(); ++i) { (*out)[i] = quiche::QuicheEndian::HostToNet32((*out)[i]); } return QUIC_NO_ERROR; } QuicErrorCode CryptoHandshakeMessage::GetVersionLabel( QuicTag tag, QuicVersionLabel* out) const { QuicErrorCode error = GetUint32(tag, out); if (error != QUIC_NO_ERROR) { return error; } *out = quiche::QuicheEndian::HostToNet32(*out); return QUIC_NO_ERROR; } bool CryptoHandshakeMessage::GetStringPiece(QuicTag tag, absl::string_view* out) const { auto it = tag_value_map_.find(tag); if (it == tag_value_map_.end()) { return false; } *out = it->second; return true; } bool CryptoHandshakeMessage::HasStringPiece(QuicTag tag) const { return tag_value_map_.find(tag) != tag_value_map_.end(); } QuicErrorCode CryptoHandshakeMessage::GetNthValue24( QuicTag tag, unsigned index, absl::string_view* out) const { absl::string_view value; if (!GetStringPiece(tag, &value)) { return QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND; } for (unsigned i = 0;; i++) { if (value.empty()) { return QUIC_CRYPTO_MESSAGE_INDEX_NOT_FOUND; } if (value.size() < 3) { return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER; } const unsigned char* data = reinterpret_cast<const unsigned char*>(value.data()); size_t size = static_cast<size_t>(data[0]) | (static_cast<size_t>(data[1]) << 8) | (static_cast<size_t>(data[2]) << 16); value.remove_prefix(3); if (value.size() < size) { return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER; } if (i == index) { *out = absl::string_view(value.data(), size); return QUIC_NO_ERROR; } value.remove_prefix(size); } } QuicErrorCode CryptoHandshakeMessage::GetUint32(QuicTag tag, uint32_t* out) const { return GetPOD(tag, out, sizeof(uint32_t)); } QuicErrorCode CryptoHandshakeMessage::GetUint64(QuicTag tag, uint64_t* out) const { return GetPOD(tag, out, sizeof(uint64_t)); } QuicErrorCode CryptoHandshakeMessage::GetStatelessResetToken( QuicTag tag, StatelessResetToken* out) const { return GetPOD(tag, out, kStatelessResetTokenLength); } size_t CryptoHandshakeMessage::size() const { size_t ret = sizeof(QuicTag) + sizeof(uint16_t) + sizeof(uint16_t) ; ret += (sizeof(QuicTag) + sizeof(uint32_t) ) * tag_value_map_.size(); for (auto i = tag_value_map_.begin(); i != tag_value_map_.end(); ++i) { ret += i->second.size(); } return ret; } void CryptoHandshakeMessage::set_minimum_size(size_t min_bytes) { if (min_bytes == minimum_size_) { return; } serialized_.reset(); minimum_size_ = min_bytes; } size_t CryptoHandshakeMessage::minimum_size() const { return minimum_size_; } std::string CryptoHandshakeMessage::DebugString() const { return DebugStringInternal(0); } QuicErrorCode CryptoHandshakeMessage::GetPOD(QuicTag tag, void* out, size_t len) const { auto it = tag_value_map_.find(tag); QuicErrorCode ret = QUIC_NO_ERROR; if (it == tag_value_map_.end()) { ret = QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND; } else if (it->second.size() != len) { ret = QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER; } if (ret != QUIC_NO_ERROR) { memset(out, 0, len); return ret; } memcpy(out, it->second.data(), len); return ret; } std::string CryptoHandshakeMessage::DebugStringInternal(size_t indent) const { std::string ret = std::string(2 * indent, ' ') + QuicTagToString(tag_) + "<\n"; ++indent; for (auto it = tag_value_map_.begin(); it != tag_value_map_.end(); ++it) { ret += std::string(2 * indent, ' ') + QuicTagToString(it->first) + ": "; bool done = false; switch (it->first) { case kICSL: case kCFCW: case kSFCW: case kIRTT: case kMIUS: case kMIBS: case kTCID: case kMAD: if (it->second.size() == 4) { uint32_t value; memcpy(&value, it->second.data(), sizeof(value)); absl::StrAppend(&ret, value); done = true; } break; case kKEXS: case kAEAD: case kCOPT: case kPDMD: case kVER: if (it->second.size() % sizeof(QuicTag) == 0) { for (size_t j = 0; j < it->second.size(); j += sizeof(QuicTag)) { QuicTag tag; memcpy(&tag, it->second.data() + j, sizeof(tag)); if (j > 0) { ret += ","; } ret += "'" + QuicTagToString(tag) + "'"; } done = true; } break; case kRREJ: if (it->second.size() % sizeof(uint32_t) == 0) { for (size_t j = 0; j < it->second.size(); j += sizeof(uint32_t)) { uint32_t value; memcpy(&value, it->second.data() + j, sizeof(value)); if (j > 0) { ret += ","; } ret += CryptoUtils::HandshakeFailureReasonToString( static_cast<HandshakeFailureReason>(value)); } done = true; } break; case kCADR: if (!it->second.empty()) { QuicSocketAddressCoder decoder; if (decoder.Decode(it->second.data(), it->second.size())) { ret += QuicSocketAddress(decoder.ip(), decoder.port()).ToString(); done = true; } } break; case kSCFG: if (!it->second.empty()) { std::unique_ptr<CryptoHandshakeMessage> msg( CryptoFramer::ParseMessage(it->second)); if (msg) { ret += "\n"; ret += msg->DebugStringInternal(indent + 1); done = true; } } break; case kPAD: ret += absl::StrFormat("(%d bytes of padding)", it->second.size()); done = true; break; case kSNI: case kUAID: ret += "\"" + it->second + "\""; done = true; break; } if (!done) { ret += "0x" + absl::BytesToHexString(it->second); } ret += "\n"; } --indent; ret += std::string(2 * indent, ' ') + ">"; return ret; } }
#include "quiche/quic/core/crypto/crypto_handshake_message.h" #include <utility> #include <vector> #include "quiche/quic/core/crypto/crypto_handshake.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/common/quiche_endian.h" namespace quic { namespace test { namespace { TEST(CryptoHandshakeMessageTest, DebugString) { const char* str = "SHLO<\n>"; CryptoHandshakeMessage message; message.set_tag(kSHLO); EXPECT_EQ(str, message.DebugString()); CryptoHandshakeMessage message2(message); EXPECT_EQ(str, message2.DebugString()); CryptoHandshakeMessage message3(std::move(message)); EXPECT_EQ(str, message3.DebugString()); CryptoHandshakeMessage message4 = message3; EXPECT_EQ(str, message4.DebugString()); CryptoHandshakeMessage message5 = std::move(message3); EXPECT_EQ(str, message5.DebugString()); } TEST(CryptoHandshakeMessageTest, DebugStringWithUintVector) { const char* str = "REJ <\n RREJ: " "SOURCE_ADDRESS_TOKEN_DIFFERENT_IP_ADDRESS_FAILURE," "CLIENT_NONCE_NOT_UNIQUE_FAILURE\n>"; CryptoHandshakeMessage message; message.set_tag(kREJ); std::vector<uint32_t> reasons = { SOURCE_ADDRESS_TOKEN_DIFFERENT_IP_ADDRESS_FAILURE, CLIENT_NONCE_NOT_UNIQUE_FAILURE}; message.SetVector(kRREJ, reasons); EXPECT_EQ(str, message.DebugString()); CryptoHandshakeMessage message2(message); EXPECT_EQ(str, message2.DebugString()); CryptoHandshakeMessage message3(std::move(message)); EXPECT_EQ(str, message3.DebugString()); CryptoHandshakeMessage message4 = message3; EXPECT_EQ(str, message4.DebugString()); CryptoHandshakeMessage message5 = std::move(message3); EXPECT_EQ(str, message5.DebugString()); } TEST(CryptoHandshakeMessageTest, DebugStringWithTagVector) { const char* str = "CHLO<\n COPT: 'TBBR','PAD ','BYTE'\n>"; CryptoHandshakeMessage message; message.set_tag(kCHLO); message.SetVector(kCOPT, QuicTagVector{kTBBR, kPAD, kBYTE}); EXPECT_EQ(str, message.DebugString()); CryptoHandshakeMessage message2(message); EXPECT_EQ(str, message2.DebugString()); CryptoHandshakeMessage message3(std::move(message)); EXPECT_EQ(str, message3.DebugString()); CryptoHandshakeMessage message4 = message3; EXPECT_EQ(str, message4.DebugString()); CryptoHandshakeMessage message5 = std::move(message3); EXPECT_EQ(str, message5.DebugString()); } TEST(CryptoHandshakeMessageTest, HasStringPiece) { CryptoHandshakeMessage message; EXPECT_FALSE(message.HasStringPiece(kALPN)); message.SetStringPiece(kALPN, "foo"); EXPECT_TRUE(message.HasStringPiece(kALPN)); } } } }
356
cpp
google/quiche
aes_128_gcm_12_decrypter
quiche/quic/core/crypto/aes_128_gcm_12_decrypter.cc
quiche/quic/core/crypto/aes_128_gcm_12_decrypter_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_AES_128_GCM_12_DECRYPTER_H_ #define QUICHE_QUIC_CORE_CRYPTO_AES_128_GCM_12_DECRYPTER_H_ #include <cstdint> #include "quiche/quic/core/crypto/aes_base_decrypter.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT Aes128Gcm12Decrypter : public AesBaseDecrypter { public: enum { kAuthTagSize = 12, }; Aes128Gcm12Decrypter(); Aes128Gcm12Decrypter(const Aes128Gcm12Decrypter&) = delete; Aes128Gcm12Decrypter& operator=(const Aes128Gcm12Decrypter&) = delete; ~Aes128Gcm12Decrypter() override; uint32_t cipher_id() const override; }; } #endif #include "quiche/quic/core/crypto/aes_128_gcm_12_decrypter.h" #include "openssl/aead.h" #include "openssl/tls1.h" namespace quic { namespace { const size_t kKeySize = 16; const size_t kNonceSize = 12; } Aes128Gcm12Decrypter::Aes128Gcm12Decrypter() : AesBaseDecrypter(EVP_aead_aes_128_gcm, kKeySize, kAuthTagSize, kNonceSize, false) { static_assert(kKeySize <= kMaxKeySize, "key size too big"); static_assert(kNonceSize <= kMaxNonceSize, "nonce size too big"); } Aes128Gcm12Decrypter::~Aes128Gcm12Decrypter() {} uint32_t Aes128Gcm12Decrypter::cipher_id() const { return TLS1_CK_AES_128_GCM_SHA256; } }
#include "quiche/quic/core/crypto/aes_128_gcm_12_decrypter.h" #include <memory> #include <string> #include "absl/base/macros.h" #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace { struct TestGroupInfo { size_t key_len; size_t iv_len; size_t pt_len; size_t aad_len; size_t tag_len; }; struct TestVector { const char* key; const char* iv; const char* ct; const char* aad; const char* tag; const char* pt; }; const TestGroupInfo test_group_info[] = { {128, 96, 0, 0, 128}, {128, 96, 0, 128, 128}, {128, 96, 128, 0, 128}, {128, 96, 408, 160, 128}, {128, 96, 408, 720, 128}, {128, 96, 104, 0, 128}, }; const TestVector test_group_0[] = { {"cf063a34d4a9a76c2c86787d3f96db71", "113b9785971864c83b01c787", "", "", "72ac8493e3a5228b5d130a69d2510e42", ""}, { "a49a5e26a2f8cb63d05546c2a62f5343", "907763b19b9b4ab6bd4f0281", "", "", "a2be08210d8c470a8df6e8fbd79ec5cf", nullptr }, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_1[] = { { "d1f6af919cde85661208bdce0c27cb22", "898c6929b435017bf031c3c5", "", "7c5faa40e636bbc91107e68010c92b9f", "ae45f11777540a2caeb128be8092468a", nullptr }, {"2370e320d4344208e0ff5683f243b213", "04dbb82f044d30831c441228", "", "d43a8e5089eea0d026c03a85178b27da", "2a049c049d25aa95969b451d93c31c6e", ""}, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_2[] = { {"e98b72a9881a84ca6b76e0f43e68647a", "8b23299fde174053f3d652ba", "5a3c1cf1985dbb8bed818036fdd5ab42", "", "23c7ab0f952b7091cd324835043b5eb5", "28286a321293253c3e0aa2704a278032"}, {"33240636cd3236165f1a553b773e728e", "17c4d61493ecdc8f31700b12", "47bb7e23f7bdfe05a8091ac90e4f8b2e", "", "b723c70e931d9785f40fd4ab1d612dc9", "95695a5b12f2870b9cc5fdc8f218a97d"}, { "5164df856f1e9cac04a79b808dc5be39", "e76925d5355e0584ce871b2b", "0216c899c88d6e32c958c7e553daa5bc", "", "a145319896329c96df291f64efbe0e3a", nullptr }, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_3[] = { {"af57f42c60c0fc5a09adb81ab86ca1c3", "a2dc01871f37025dc0fc9a79", "b9a535864f48ea7b6b1367914978f9bfa087d854bb0e269bed8d279d2eea1210e48947" "338b22f9bad09093276a331e9c79c7f4", "41dc38988945fcb44faf2ef72d0061289ef8efd8", "4f71e72bde0018f555c5adcce062e005", "3803a0727eeb0ade441e0ec107161ded2d425ec0d102f21f51bf2cf9947c7ec4aa7279" "5b2f69b041596e8817d0a3c16f8fadeb"}, {"ebc753e5422b377d3cb64b58ffa41b61", "2e1821efaced9acf1f241c9b", "069567190554e9ab2b50a4e1fbf9c147340a5025fdbd201929834eaf6532325899ccb9" "f401823e04b05817243d2142a3589878", "b9673412fd4f88ba0e920f46dd6438ff791d8eef", "534d9234d2351cf30e565de47baece0b", "39077edb35e9c5a4b1e4c2a6b9bb1fce77f00f5023af40333d6d699014c2bcf4209c18" "353a18017f5b36bfc00b1f6dcb7ed485"}, { "52bdbbf9cf477f187ec010589cb39d58", "d3be36d3393134951d324b31", "700188da144fa692cf46e4a8499510a53d90903c967f7f13e8a1bd8151a74adc4fe63e" "32b992760b3a5f99e9a47838867000a9", "93c4fc6a4135f54d640b0c976bf755a06a292c33", "8ca4e38aa3dfa6b1d0297021ccf3ea5f", nullptr }, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_4[] = { {"da2bb7d581493d692380c77105590201", "44aa3e7856ca279d2eb020c6", "9290d430c9e89c37f0446dbd620c9a6b34b1274aeb6f911f75867efcf95b6feda69f1a" "f4ee16c761b3c9aeac3da03aa9889c88", "4cd171b23bddb3a53cdf959d5c1710b481eb3785a90eb20a2345ee00d0bb7868c367ab" "12e6f4dd1dee72af4eee1d197777d1d6499cc541f34edbf45cda6ef90b3c024f9272d7" "2ec1909fb8fba7db88a4d6f7d3d925980f9f9f72", "9e3ac938d3eb0cadd6f5c9e35d22ba38", "9bbf4c1a2742f6ac80cb4e8a052e4a8f4f07c43602361355b717381edf9fabd4cb7e3a" "d65dbd1378b196ac270588dd0621f642"}, {"d74e4958717a9d5c0e235b76a926cae8", "0b7471141e0c70b1995fd7b1", "e701c57d2330bf066f9ff8cf3ca4343cafe4894651cd199bdaaa681ba486b4a65c5a22" "b0f1420be29ea547d42c713bc6af66aa", "4a42b7aae8c245c6f1598a395316e4b8484dbd6e64648d5e302021b1d3fa0a38f46e22" "bd9c8080b863dc0016482538a8562a4bd0ba84edbe2697c76fd039527ac179ec5506cf" "34a6039312774cedebf4961f3978b14a26509f96", "e192c23cb036f0b31592989119eed55d", "840d9fb95e32559fb3602e48590280a172ca36d9b49ab69510f5bd552bfab7a306f85f" "f0a34bc305b88b804c60b90add594a17"}, { "1986310c725ac94ecfe6422e75fc3ee7", "93ec4214fa8e6dc4e3afc775", "b178ec72f85a311ac4168f42a4b2c23113fbea4b85f4b9dabb74e143eb1b8b0a361e02" "43edfd365b90d5b325950df0ada058f9", "e80b88e62c49c958b5e0b8b54f532d9ff6aa84c8a40132e93e55b59fc24e8decf28463" "139f155d1e8ce4ee76aaeefcd245baa0fc519f83a5fb9ad9aa40c4b21126013f576c42" "72c2cb136c8fd091cc4539877a5d1e72d607f960", "8b347853f11d75e81e8a95010be81f17", nullptr }, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector test_group_5[] = { {"387218b246c1a8257748b56980e50c94", "dd7e014198672be39f95b69d", "cdba9e73eaf3d38eceb2b04a8d", "", "ecf90f4a47c9c626d6fb2c765d201556", "48f5b426baca03064554cc2b30"}, {"294de463721e359863887c820524b3d4", "3338b35c9d57a5d28190e8c9", "2f46634e74b8e4c89812ac83b9", "", "dabd506764e68b82a7e720aa18da0abe", "46a2e55c8e264df211bd112685"}, {"28ead7fd2179e0d12aa6d5d88c58c2dc", "5055347f18b4d5add0ae5c41", "142d8210c3fb84774cdbd0447a", "", "5fd321d9cdb01952dc85f034736c2a7d", "3b95b981086ee73cc4d0cc1422"}, { "7d7b6c988137b8d470c57bf674a09c87", "9edf2aa970d016ac962e1fd8", "a85b66c3cb5eab91d5bdc8bc0e", "", "dc054efc01f3afd21d9c2484819f569a", nullptr }, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; const TestVector* const test_group_array[] = { test_group_0, test_group_1, test_group_2, test_group_3, test_group_4, test_group_5, }; } namespace quic { namespace test { QuicData* DecryptWithNonce(Aes128Gcm12Decrypter* decrypter, absl::string_view nonce, absl::string_view associated_data, absl::string_view ciphertext) { uint64_t packet_number; absl::string_view nonce_prefix(nonce.data(), nonce.size() - sizeof(packet_number)); decrypter->SetNoncePrefix(nonce_prefix); memcpy(&packet_number, nonce.data() + nonce_prefix.size(), sizeof(packet_number)); std::unique_ptr<char[]> output(new char[ciphertext.length()]); size_t output_length = 0; const bool success = decrypter->DecryptPacket( packet_number, associated_data, ciphertext, output.get(), &output_length, ciphertext.length()); if (!success) { return nullptr; } return new QuicData(output.release(), output_length, true); } class Aes128Gcm12DecrypterTest : public QuicTest {}; TEST_F(Aes128Gcm12DecrypterTest, Decrypt) { for (size_t i = 0; i < ABSL_ARRAYSIZE(test_group_array); i++) { SCOPED_TRACE(i); const TestVector* test_vectors = test_group_array[i]; const TestGroupInfo& test_info = test_group_info[i]; for (size_t j = 0; test_vectors[j].key != nullptr; j++) { bool has_pt = test_vectors[j].pt; std::string key; std::string iv; std::string ct; std::string aad; std::string tag; std::string pt; ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].key, &key)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].iv, &iv)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].ct, &ct)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].aad, &aad)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].tag, &tag)); if (has_pt) { ASSERT_TRUE(absl::HexStringToBytes(test_vectors[j].pt, &pt)); } EXPECT_EQ(test_info.key_len, key.length() * 8); EXPECT_EQ(test_info.iv_len, iv.length() * 8); EXPECT_EQ(test_info.pt_len, ct.length() * 8); EXPECT_EQ(test_info.aad_len, aad.length() * 8); EXPECT_EQ(test_info.tag_len, tag.length() * 8); if (has_pt) { EXPECT_EQ(test_info.pt_len, pt.length() * 8); } ASSERT_LE(static_cast<size_t>(Aes128Gcm12Decrypter::kAuthTagSize), tag.length()); tag.resize(Aes128Gcm12Decrypter::kAuthTagSize); std::string ciphertext = ct + tag; Aes128Gcm12Decrypter decrypter; ASSERT_TRUE(decrypter.SetKey(key)); std::unique_ptr<QuicData> decrypted(DecryptWithNonce( &decrypter, iv, aad.length() ? aad : absl::string_view(), ciphertext)); if (!decrypted) { EXPECT_FALSE(has_pt); continue; } EXPECT_TRUE(has_pt); ASSERT_EQ(pt.length(), decrypted->length()); quiche::test::CompareCharArraysWithHexError( "plaintext", decrypted->data(), pt.length(), pt.data(), pt.length()); } } } } }
357
cpp
google/quiche
proof_source_x509
quiche/quic/core/crypto/proof_source_x509.cc
quiche/quic/core/crypto/proof_source_x509_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_PROOF_SOURCE_X509_H_ #define QUICHE_QUIC_CORE_CRYPTO_PROOF_SOURCE_X509_H_ #include <forward_list> #include <memory> #include "absl/base/attributes.h" #include "absl/container/node_hash_map.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/certificate_view.h" #include "quiche/quic/core/crypto/proof_source.h" #include "quiche/quic/core/crypto/quic_crypto_proof.h" namespace quic { class QUICHE_EXPORT ProofSourceX509 : public ProofSource { public: static std::unique_ptr<ProofSourceX509> Create( quiche::QuicheReferenceCountedPointer<Chain> default_chain, CertificatePrivateKey default_key); void GetProof(const QuicSocketAddress& server_address, const QuicSocketAddress& client_address, const std::string& hostname, const std::string& server_config, QuicTransportVersion transport_version, absl::string_view chlo_hash, std::unique_ptr<Callback> callback) override; quiche::QuicheReferenceCountedPointer<Chain> GetCertChain( const QuicSocketAddress& server_address, const QuicSocketAddress& client_address, const std::string& hostname, bool* cert_matched_sni) override; void ComputeTlsSignature( const QuicSocketAddress& server_address, const QuicSocketAddress& client_address, const std::string& hostname, uint16_t signature_algorithm, absl::string_view in, std::unique_ptr<SignatureCallback> callback) override; QuicSignatureAlgorithmVector SupportedTlsSignatureAlgorithms() const override; TicketCrypter* GetTicketCrypter() override; ABSL_MUST_USE_RESULT bool AddCertificateChain( quiche::QuicheReferenceCountedPointer<Chain> chain, CertificatePrivateKey key); protected: ProofSourceX509(quiche::QuicheReferenceCountedPointer<Chain> default_chain, CertificatePrivateKey default_key); bool valid() const { return default_certificate_ != nullptr; } virtual void MaybeAddSctsForHostname(absl::string_view , std::string& ) {} private: struct QUICHE_EXPORT Certificate { quiche::QuicheReferenceCountedPointer<Chain> chain; CertificatePrivateKey key; }; Certificate* GetCertificate(const std::string& hostname, bool* cert_matched_sni) const; std::forward_list<Certificate> certificates_; Certificate* default_certificate_ = nullptr; absl::node_hash_map<std::string, Certificate*> certificate_map_; }; } #endif #include "quiche/quic/core/crypto/proof_source_x509.h" #include <memory> #include <optional> #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "openssl/ssl.h" #include "quiche/quic/core/crypto/certificate_view.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/crypto/crypto_utils.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/common/quiche_endian.h" namespace quic { ProofSourceX509::ProofSourceX509( quiche::QuicheReferenceCountedPointer<Chain> default_chain, CertificatePrivateKey default_key) { if (!AddCertificateChain(default_chain, std::move(default_key))) { return; } default_certificate_ = &certificates_.front(); } std::unique_ptr<ProofSourceX509> ProofSourceX509::Create( quiche::QuicheReferenceCountedPointer<Chain> default_chain, CertificatePrivateKey default_key) { std::unique_ptr<ProofSourceX509> result( new ProofSourceX509(default_chain, std::move(default_key))); if (!result->valid()) { return nullptr; } return result; } void ProofSourceX509::GetProof( const QuicSocketAddress& , const QuicSocketAddress& , const std::string& hostname, const std::string& server_config, QuicTransportVersion , absl::string_view chlo_hash, std::unique_ptr<ProofSource::Callback> callback) { QuicCryptoProof proof; if (!valid()) { QUIC_BUG(ProofSourceX509::GetProof called in invalid state) << "ProofSourceX509::GetProof called while the object is not valid"; callback->Run(false, nullptr, proof, nullptr); return; } std::optional<std::string> payload = CryptoUtils::GenerateProofPayloadToBeSigned(chlo_hash, server_config); if (!payload.has_value()) { callback->Run(false, nullptr, proof, nullptr); return; } Certificate* certificate = GetCertificate(hostname, &proof.cert_matched_sni); proof.signature = certificate->key.Sign(*payload, SSL_SIGN_RSA_PSS_RSAE_SHA256); MaybeAddSctsForHostname(hostname, proof.leaf_cert_scts); callback->Run(!proof.signature.empty(), certificate->chain, proof, nullptr); } quiche::QuicheReferenceCountedPointer<ProofSource::Chain> ProofSourceX509::GetCertChain(const QuicSocketAddress& , const QuicSocketAddress& , const std::string& hostname, bool* cert_matched_sni) { if (!valid()) { QUIC_BUG(ProofSourceX509::GetCertChain called in invalid state) << "ProofSourceX509::GetCertChain called while the object is not " "valid"; return nullptr; } return GetCertificate(hostname, cert_matched_sni)->chain; } void ProofSourceX509::ComputeTlsSignature( const QuicSocketAddress& , const QuicSocketAddress& , const std::string& hostname, uint16_t signature_algorithm, absl::string_view in, std::unique_ptr<ProofSource::SignatureCallback> callback) { if (!valid()) { QUIC_BUG(ProofSourceX509::ComputeTlsSignature called in invalid state) << "ProofSourceX509::ComputeTlsSignature called while the object is " "not valid"; callback->Run(false, "", nullptr); return; } bool cert_matched_sni; std::string signature = GetCertificate(hostname, &cert_matched_sni) ->key.Sign(in, signature_algorithm); callback->Run(!signature.empty(), signature, nullptr); } QuicSignatureAlgorithmVector ProofSourceX509::SupportedTlsSignatureAlgorithms() const { return SupportedSignatureAlgorithmsForQuic(); } ProofSource::TicketCrypter* ProofSourceX509::GetTicketCrypter() { return nullptr; } bool ProofSourceX509::AddCertificateChain( quiche::QuicheReferenceCountedPointer<Chain> chain, CertificatePrivateKey key) { if (chain->certs.empty()) { QUIC_BUG(quic_bug_10644_1) << "Empty certificate chain supplied."; return false; } std::unique_ptr<CertificateView> leaf = CertificateView::ParseSingleCertificate(chain->certs[0]); if (leaf == nullptr) { QUIC_BUG(quic_bug_10644_2) << "Unable to parse X.509 leaf certificate in the supplied chain."; return false; } if (!key.MatchesPublicKey(*leaf)) { QUIC_BUG(quic_bug_10644_3) << "Private key does not match the leaf certificate."; return false; } certificates_.push_front(Certificate{ chain, std::move(key), }); Certificate* certificate = &certificates_.front(); for (absl::string_view host : leaf->subject_alt_name_domains()) { certificate_map_[std::string(host)] = certificate; } return true; } ProofSourceX509::Certificate* ProofSourceX509::GetCertificate( const std::string& hostname, bool* cert_matched_sni) const { QUICHE_DCHECK(valid()); auto it = certificate_map_.find(hostname); if (it != certificate_map_.end()) { *cert_matched_sni = true; return it->second; } auto dot_pos = hostname.find('.'); if (dot_pos != std::string::npos) { std::string wildcard = absl::StrCat("*", hostname.substr(dot_pos)); it = certificate_map_.find(wildcard); if (it != certificate_map_.end()) { *cert_matched_sni = true; return it->second; } } *cert_matched_sni = false; return default_certificate_; } }
#include "quiche/quic/core/crypto/proof_source_x509.h" #include <memory> #include <string> #include <utility> #include "absl/strings/string_view.h" #include "openssl/ssl.h" #include "quiche/quic/core/crypto/certificate_view.h" #include "quiche/quic/core/crypto/proof_source.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/test_certificates.h" #include "quiche/common/platform/api/quiche_reference_counted.h" namespace quic { namespace test { namespace { quiche::QuicheReferenceCountedPointer<ProofSource::Chain> MakeChain( absl::string_view cert) { return quiche::QuicheReferenceCountedPointer<ProofSource::Chain>( new ProofSource::Chain(std::vector<std::string>{std::string(cert)})); } class ProofSourceX509Test : public QuicTest { public: ProofSourceX509Test() : test_chain_(MakeChain(kTestCertificate)), wildcard_chain_(MakeChain(kWildcardCertificate)), test_key_( CertificatePrivateKey::LoadFromDer(kTestCertificatePrivateKey)), wildcard_key_(CertificatePrivateKey::LoadFromDer( kWildcardCertificatePrivateKey)) { QUICHE_CHECK(test_key_ != nullptr); QUICHE_CHECK(wildcard_key_ != nullptr); } protected: quiche::QuicheReferenceCountedPointer<ProofSource::Chain> test_chain_, wildcard_chain_; std::unique_ptr<CertificatePrivateKey> test_key_, wildcard_key_; }; TEST_F(ProofSourceX509Test, AddCertificates) { std::unique_ptr<ProofSourceX509> proof_source = ProofSourceX509::Create(test_chain_, std::move(*test_key_)); ASSERT_TRUE(proof_source != nullptr); EXPECT_TRUE(proof_source->AddCertificateChain(wildcard_chain_, std::move(*wildcard_key_))); } TEST_F(ProofSourceX509Test, AddCertificateKeyMismatch) { std::unique_ptr<ProofSourceX509> proof_source = ProofSourceX509::Create(test_chain_, std::move(*test_key_)); ASSERT_TRUE(proof_source != nullptr); test_key_ = CertificatePrivateKey::LoadFromDer(kTestCertificatePrivateKey); EXPECT_QUIC_BUG((void)proof_source->AddCertificateChain( wildcard_chain_, std::move(*test_key_)), "Private key does not match"); } TEST_F(ProofSourceX509Test, CertificateSelection) { std::unique_ptr<ProofSourceX509> proof_source = ProofSourceX509::Create(test_chain_, std::move(*test_key_)); ASSERT_TRUE(proof_source != nullptr); ASSERT_TRUE(proof_source->AddCertificateChain(wildcard_chain_, std::move(*wildcard_key_))); bool cert_matched_sni; EXPECT_EQ(proof_source ->GetCertChain(QuicSocketAddress(), QuicSocketAddress(), "unknown.test", &cert_matched_sni) ->certs[0], kTestCertificate); EXPECT_FALSE(cert_matched_sni); EXPECT_EQ(proof_source ->GetCertChain(QuicSocketAddress(), QuicSocketAddress(), "mail.example.org", &cert_matched_sni) ->certs[0], kTestCertificate); EXPECT_TRUE(cert_matched_sni); EXPECT_EQ(proof_source ->GetCertChain(QuicSocketAddress(), QuicSocketAddress(), "www.foo.test", &cert_matched_sni) ->certs[0], kWildcardCertificate); EXPECT_TRUE(cert_matched_sni); EXPECT_EQ(proof_source ->GetCertChain(QuicSocketAddress(), QuicSocketAddress(), "www.wildcard.test", &cert_matched_sni) ->certs[0], kWildcardCertificate); EXPECT_TRUE(cert_matched_sni); EXPECT_EQ(proof_source ->GetCertChain(QuicSocketAddress(), QuicSocketAddress(), "etc.wildcard.test", &cert_matched_sni) ->certs[0], kWildcardCertificate); EXPECT_TRUE(cert_matched_sni); EXPECT_EQ(proof_source ->GetCertChain(QuicSocketAddress(), QuicSocketAddress(), "wildcard.test", &cert_matched_sni) ->certs[0], kTestCertificate); EXPECT_FALSE(cert_matched_sni); } TEST_F(ProofSourceX509Test, TlsSignature) { class Callback : public ProofSource::SignatureCallback { public: void Run(bool ok, std::string signature, std::unique_ptr<ProofSource::Details> ) override { ASSERT_TRUE(ok); std::unique_ptr<CertificateView> view = CertificateView::ParseSingleCertificate(kTestCertificate); EXPECT_TRUE(view->VerifySignature("Test data", signature, SSL_SIGN_RSA_PSS_RSAE_SHA256)); } }; std::unique_ptr<ProofSourceX509> proof_source = ProofSourceX509::Create(test_chain_, std::move(*test_key_)); ASSERT_TRUE(proof_source != nullptr); proof_source->ComputeTlsSignature(QuicSocketAddress(), QuicSocketAddress(), "example.com", SSL_SIGN_RSA_PSS_RSAE_SHA256, "Test data", std::make_unique<Callback>()); } } } }
358
cpp
google/quiche
quic_crypto_client_config
quiche/quic/core/crypto/quic_crypto_client_config.cc
quiche/quic/core/crypto/quic_crypto_client_config_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_QUIC_CRYPTO_CLIENT_CONFIG_H_ #define QUICHE_QUIC_CORE_CRYPTO_QUIC_CRYPTO_CLIENT_CONFIG_H_ #include <cstdint> #include <map> #include <memory> #include <string> #include <vector> #include "absl/strings/string_view.h" #include "openssl/base.h" #include "openssl/ssl.h" #include "quiche/quic/core/crypto/client_proof_source.h" #include "quiche/quic/core/crypto/crypto_handshake.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/crypto/transport_parameters.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_server_id.h" #include "quiche/quic/platform/api/quic_export.h" #include "quiche/common/platform/api/quiche_reference_counted.h" namespace quic { class CryptoHandshakeMessage; class ProofVerifier; class ProofVerifyDetails; struct QUICHE_EXPORT QuicResumptionState { bssl::UniquePtr<SSL_SESSION> tls_session; std::unique_ptr<TransportParameters> transport_params = nullptr; std::unique_ptr<ApplicationState> application_state = nullptr; std::string token; }; class QUICHE_EXPORT SessionCache { public: virtual ~SessionCache() {} virtual void Insert(const QuicServerId& server_id, bssl::UniquePtr<SSL_SESSION> session, const TransportParameters& params, const ApplicationState* application_state) = 0; virtual std::unique_ptr<QuicResumptionState> Lookup( const QuicServerId& server_id, QuicWallTime now, const SSL_CTX* ctx) = 0; virtual void ClearEarlyData(const QuicServerId& server_id) = 0; virtual void OnNewTokenReceived(const QuicServerId& server_id, absl::string_view token) = 0; virtual void RemoveExpiredEntries(QuicWallTime now) = 0; virtual void Clear() = 0; }; class QUICHE_EXPORT QuicCryptoClientConfig : public QuicCryptoConfig { public: class QUICHE_EXPORT CachedState { public: enum ServerConfigState { SERVER_CONFIG_EMPTY = 0, SERVER_CONFIG_INVALID = 1, SERVER_CONFIG_CORRUPTED = 2, SERVER_CONFIG_EXPIRED = 3, SERVER_CONFIG_INVALID_EXPIRY = 4, SERVER_CONFIG_VALID = 5, SERVER_CONFIG_COUNT }; CachedState(); CachedState(const CachedState&) = delete; CachedState& operator=(const CachedState&) = delete; ~CachedState(); bool IsComplete(QuicWallTime now) const; bool IsEmpty() const; const CryptoHandshakeMessage* GetServerConfig() const; ServerConfigState SetServerConfig(absl::string_view server_config, QuicWallTime now, QuicWallTime expiry_time, std::string* error_details); void InvalidateServerConfig(); void SetProof(const std::vector<std::string>& certs, absl::string_view cert_sct, absl::string_view chlo_hash, absl::string_view signature); void Clear(); void ClearProof(); void SetProofValid(); void SetProofInvalid(); const std::string& server_config() const; const std::string& source_address_token() const; const std::vector<std::string>& certs() const; const std::string& cert_sct() const; const std::string& chlo_hash() const; const std::string& signature() const; bool proof_valid() const; uint64_t generation_counter() const; const ProofVerifyDetails* proof_verify_details() const; void set_source_address_token(absl::string_view token); void set_cert_sct(absl::string_view cert_sct); void SetProofVerifyDetails(ProofVerifyDetails* details); void InitializeFrom(const CachedState& other); bool Initialize(absl::string_view server_config, absl::string_view source_address_token, const std::vector<std::string>& certs, const std::string& cert_sct, absl::string_view chlo_hash, absl::string_view signature, QuicWallTime now, QuicWallTime expiration_time); private: std::string server_config_; std::string source_address_token_; std::vector<std::string> certs_; std::string cert_sct_; std::string chlo_hash_; std::string server_config_sig_; bool server_config_valid_; QuicWallTime expiration_time_; uint64_t generation_counter_; std::unique_ptr<ProofVerifyDetails> proof_verify_details_; mutable std::unique_ptr<CryptoHandshakeMessage> scfg_; }; class QUICHE_EXPORT ServerIdFilter { public: virtual ~ServerIdFilter() {} virtual bool Matches(const QuicServerId& server_id) const = 0; }; explicit QuicCryptoClientConfig( std::unique_ptr<ProofVerifier> proof_verifier); QuicCryptoClientConfig(std::unique_ptr<ProofVerifier> proof_verifier, std::shared_ptr<SessionCache> session_cache); QuicCryptoClientConfig(const QuicCryptoClientConfig&) = delete; QuicCryptoClientConfig& operator=(const QuicCryptoClientConfig&) = delete; ~QuicCryptoClientConfig(); CachedState* LookupOrCreate(const QuicServerId& server_id); void ClearCachedStates(const ServerIdFilter& filter); void FillInchoateClientHello( const QuicServerId& server_id, const ParsedQuicVersion preferred_version, const CachedState* cached, QuicRandom* rand, bool demand_x509_proof, quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> out_params, CryptoHandshakeMessage* out) const; QuicErrorCode FillClientHello( const QuicServerId& server_id, QuicConnectionId connection_id, const ParsedQuicVersion preferred_version, const ParsedQuicVersion actual_version, const CachedState* cached, QuicWallTime now, QuicRandom* rand, quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> out_params, CryptoHandshakeMessage* out, std::string* error_details) const; QuicErrorCode ProcessRejection( const CryptoHandshakeMessage& rej, QuicWallTime now, QuicTransportVersion version, absl::string_view chlo_hash, CachedState* cached, quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> out_params, std::string* error_details); QuicErrorCode ProcessServerHello( const CryptoHandshakeMessage& server_hello, QuicConnectionId connection_id, ParsedQuicVersion version, const ParsedQuicVersionVector& negotiated_versions, CachedState* cached, quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> out_params, std::string* error_details); QuicErrorCode ProcessServerConfigUpdate( const CryptoHandshakeMessage& server_config_update, QuicWallTime now, const QuicTransportVersion version, absl::string_view chlo_hash, CachedState* cached, quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> out_params, std::string* error_details); ProofVerifier* proof_verifier() const; SessionCache* session_cache() const; void set_session_cache(std::shared_ptr<SessionCache> session_cache); ClientProofSource* proof_source() const; void set_proof_source(std::unique_ptr<ClientProofSource> proof_source); SSL_CTX* ssl_ctx() const; void InitializeFrom(const QuicServerId& server_id, const QuicServerId& canonical_server_id, QuicCryptoClientConfig* canonical_crypto_config); void AddCanonicalSuffix(const std::string& suffix); const std::vector<uint16_t>& preferred_groups() const { return preferred_groups_; } void set_preferred_groups(const std::vector<uint16_t>& preferred_groups) { preferred_groups_ = preferred_groups; } void set_user_agent_id(const std::string& user_agent_id) { user_agent_id_ = user_agent_id; } const std::string& user_agent_id() const { return user_agent_id_; } void set_tls_signature_algorithms(std::string signature_algorithms) { tls_signature_algorithms_ = std::move(signature_algorithms); } const std::optional<std::string>& tls_signature_algorithms() const { return tls_signature_algorithms_; } void set_alpn(const std::string& alpn) { alpn_ = alpn; } void set_pre_shared_key(absl::string_view psk) { pre_shared_key_ = std::string(psk); } const std::string& pre_shared_key() const { return pre_shared_key_; } bool pad_inchoate_hello() const { return pad_inchoate_hello_; } void set_pad_inchoate_hello(bool new_value) { pad_inchoate_hello_ = new_value; } bool pad_full_hello() const { return pad_full_hello_; } void set_pad_full_hello(bool new_value) { pad_full_hello_ = new_value; } #if BORINGSSL_API_VERSION >= 27 bool alps_use_new_codepoint() const { return alps_use_new_codepoint_; } void set_alps_use_new_codepoint(bool new_value) { alps_use_new_codepoint_ = new_value; } #endif const QuicSSLConfig& ssl_config() const { return ssl_config_; } QuicSSLConfig& ssl_config() { return ssl_config_; } private: void SetDefaults(); QuicErrorCode CacheNewServerConfig( const CryptoHandshakeMessage& message, QuicWallTime now, QuicTransportVersion version, absl::string_view chlo_hash, const std::vector<std::string>& cached_certs, CachedState* cached, std::string* error_details); bool PopulateFromCanonicalConfig(const QuicServerId& server_id, CachedState* cached); std::map<QuicServerId, std::unique_ptr<CachedState>> cached_states_; std::map<QuicServerId, QuicServerId> canonical_server_map_; std::vector<std::string> canonical_suffixes_; std::unique_ptr<ProofVerifier> proof_verifier_; std::shared_ptr<SessionCache> session_cache_; std::unique_ptr<ClientProofSource> proof_source_; bssl::UniquePtr<SSL_CTX> ssl_ctx_; std::vector<uint16_t> preferred_groups_; std::string user_agent_id_; std::string alpn_; std::string pre_shared_key_; std::optional<std::string> tls_signature_algorithms_; bool pad_inchoate_hello_ = true; bool pad_full_hello_ = true; #if BORINGSSL_API_VERSION >= 27 bool alps_use_new_codepoint_ = false; #endif QuicSSLConfig ssl_config_; }; } #endif #include "quiche/quic/core/crypto/quic_crypto_client_config.h" #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/memory/memory.h" #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "openssl/ssl.h" #include "quiche/quic/core/crypto/cert_compressor.h" #include "quiche/quic/core/crypto/chacha20_poly1305_encrypter.h" #include "quiche/quic/core/crypto/crypto_framer.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/crypto/crypto_utils.h" #include "quiche/quic/core/crypto/curve25519_key_exchange.h" #include "quiche/quic/core/crypto/key_exchange.h" #include "quiche/quic/core/crypto/p256_key_exchange.h" #include "quiche/quic/core/crypto/proof_verifier.h" #include "quiche/quic/core/crypto/quic_encrypter.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/crypto/tls_client_connection.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_client_stats.h" #include "quiche/quic/platform/api/quic_hostname_utils.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { namespace { void RecordInchoateClientHelloReason( QuicCryptoClientConfig::CachedState::ServerConfigState state) { QUIC_CLIENT_HISTOGRAM_ENUM( "QuicInchoateClientHelloReason", state, QuicCryptoClientConfig::CachedState::SERVER_CONFIG_COUNT, ""); } void RecordDiskCacheServerConfigState( QuicCryptoClientConfig::CachedState::ServerConfigState state) { QUIC_CLIENT_HISTOGRAM_ENUM( "QuicServerInfo.DiskCacheState", state, QuicCryptoClientConfig::CachedState::SERVER_CONFIG_COUNT, ""); } } QuicCryptoClientConfig::QuicCryptoClientConfig( std::unique_ptr<ProofVerifier> proof_verifier) : QuicCryptoClientConfig(std::move(proof_verifier), nullptr) {} QuicCryptoClientConfig::QuicCryptoClientConfig( std::unique_ptr<ProofVerifier> proof_verifier, std::shared_ptr<SessionCache> session_cache) : proof_verifier_(std::move(proof_verifier)), session_cache_(std::move(session_cache)), ssl_ctx_(TlsClientConnection::CreateSslCtx( !GetQuicFlag(quic_disable_client_tls_zero_rtt))) { QUICHE_DCHECK(proof_verifier_.get()); SetDefaults(); } QuicCryptoClientConfig::~QuicCryptoClientConfig() {} QuicCryptoClientConfig::CachedState::CachedState() : server_config_valid_(false), expiration_time_(QuicWallTime::Zero()), generation_counter_(0) {} QuicCryptoClientConfig::CachedState::~CachedState() {} bool QuicCryptoClientConfig::CachedState::IsComplete(QuicWallTime now) const { if (server_config_.empty()) { RecordInchoateClientHelloReason(SERVER_CONFIG_EMPTY); return false; } if (!server_config_valid_) { RecordInchoateClientHelloReason(SERVER_CONFIG_INVALID); return false; } const CryptoHandshakeMessage* scfg = GetServerConfig(); if (!scfg) { RecordInchoateClientHelloReason(SERVER_CONFIG_CORRUPTED); QUICHE_DCHECK(false); return false; } if (now.IsBefore(expiration_time_)) { return true; } QUIC_CLIENT_HISTOGRAM_TIMES( "QuicClientHelloServerConfig.InvalidDuration", QuicTime::Delta::FromSeconds(now.ToUNIXSeconds() - expiration_time_.ToUNIXSeconds()), QuicTime::Delta::FromSeconds(60), QuicTime::Delta::FromSeconds(20 * 24 * 3600), 50, ""); RecordInchoateClientHelloReason(SERVER_CONFIG_EXPIRED); return false; } bool QuicCryptoClientConfig::CachedState::IsEmpty() const { return server_config_.empty(); } const CryptoHandshakeMessage* QuicCryptoClientConfig::CachedState::GetServerConfig() const { if (server_config_.empty()) { return nullptr; } if (!scfg_) { scfg_ = CryptoFramer::ParseMessage(server_config_); QUICHE_DCHECK(scfg_.get()); } return scfg_.get(); } QuicCryptoClientConfig::CachedState::ServerConfigState QuicCryptoClientConfig::CachedState::SetServerConfig( absl::string_view server_config, QuicWallTime now, QuicWallTime expiry_time, std::string* error_details) { const bool matches_existing = server_config == server_config_; std::unique_ptr<CryptoHandshakeMessage> new_scfg_storage; const CryptoHandshakeMessage* new_scfg; if (!matches_existing) { new_scfg_storage = CryptoFramer::ParseMessage(server_config); new_scfg = new_scfg_storage.get(); } else { new_scfg = GetServerConfig(); } if (!new_scfg) { *error_details = "SCFG invalid"; return SERVER_CONFIG_INVALID; } if (expiry_time.IsZero()) { uint64_t expiry_seconds; if (new_scfg->GetUint64(kEXPY, &expiry_seconds) != QUIC_NO_ERROR) { *error_details = "SCFG missing EXPY"; return SERVER_CONFIG_INVALID_EXPIRY; } expiration_time_ = QuicWallTime::FromUNIXSeconds(expiry_seconds); } else { expiration_time_ = expiry_time; } if (now.IsAfter(expiration_time_)) { *error_details = "SCFG has expired"; return SERVER_CONFIG_EXPIRED; } if (!matches_existing) { server_config_ = std::string(server_config); SetProofInvalid(); scfg_ = std::move(new_scfg_storage); } return SERVER_CONFIG_VALID; } void QuicCryptoClientConfig::CachedState::InvalidateServerConfig() { server_config_.clear(); scfg_.reset(); SetProofInvalid(); } void QuicCryptoClientConfig::CachedState::SetProof( const std::vector<std::string>& certs, absl::string_view cert_sct, absl::string_view chlo_hash, absl::string_view signature) { bool has_changed = signature != server_config_sig_ || chlo_hash != chlo_hash_ || certs_.size() != certs.size(); if (!has_changed) { for (size_t i = 0; i < certs_.size(); i++) { if (certs_[i] != certs[i]) { has_changed = true; break; } } } if (!has_changed) { return; } SetProofInvalid(); certs_ = certs; cert_sct_ = std::string(cert_sct); chlo_hash_ = std::string(chlo_hash); server_config_sig_ = std::string(signature); } void QuicCryptoClientConfig::CachedState::Clear() { server_config_.clear(); source_address_token_.clear(); certs_.clear(); cert_sct_.clear(); chlo_hash_.clear(); server_config_sig_.clear(); server_config_valid_ = false; proof_verify_details_.reset(); scfg_.reset(); ++generation_counter_; } void QuicCryptoClientConfig::CachedState::ClearProof() { SetProofInvalid(); certs_.clear(); cert_sct_.clear(); chlo_hash_.clear(); server_config_sig_.clear(); } void QuicCryptoClientConfig::CachedState::SetProofValid() { server_config_valid_ = true; } void QuicCryptoClientConfig::CachedState::SetProofInvalid() { server_config_valid_ = false; ++generation_counter_; } bool QuicCryptoClientConfig::CachedState::Initialize( absl::string_view server_config, absl::string_view source_address_token, const std::vector<std::string>& certs, const std::string& cert_sct, absl::string_view chlo_hash, absl::string_view signature, QuicWallTime now, QuicWallTime expiration_time) { QUICHE_DCHECK(server_config_.empty()); if (server_config.empty()) { RecordDiskCacheServerConfigState(SERVER_CONFIG_EMPTY); return false; } std::string error_details; ServerConfigState state = SetServerConfig(server_config, now, expiration_time, &error_details); RecordDiskCacheServerConfigState(state); if (state != SERVER_CONFIG_VALID) { QUIC_DVLOG(1) << "SetServerConfig failed with " << error_details; return false; } chlo_hash_.assign(chlo_hash.data(), chlo_hash.size()); server_config_sig_.assign(signature.data(), signature.size()); source_address_token_.assign(source_address_token.data(), source_address_token.size()); certs_ = certs; cert_sct_ = cert_sct; return true; } const std::string& QuicCryptoClientConfig::CachedState::server_config() const { return server_config_; } const std::string& QuicCryptoClientConfig::CachedState::source_address_token() const { return source_address_token_; } const std::vector<std::string>& QuicCryptoClientConfig::CachedState::certs() const { return certs_; } const std::string& QuicCryptoClientConfig::CachedState::cert_sct() const { return cert_sct_; } const std::string& QuicCryptoClientConfig::CachedState::chlo_hash() const { return chlo_hash_; } const std::string& QuicCryptoClientConfig::CachedState::signature() const { return server_config_sig_; } bool QuicCryptoClientConfig::CachedState::proof_valid() const { return server_config_valid_; } uint64_t QuicCryptoClientConfig::CachedState::generation_counter() const { return generation_counter_; } const ProofVerifyDetails* QuicCryptoClientConfig::CachedState::proof_verify_details() const { return proof_verify_details_.get(); } void QuicCryptoClientConfig::CachedState::set_source_address_token( absl::string_view token) { source_address_token_ = std::string(token); } void QuicCryptoClientConfig::CachedState::set_cert_sct( absl::string_view cert_sct) { cert_sct_ = std::string(cert_sct); } void QuicCryptoClientConfig::CachedState::SetProofVerifyDetails( ProofVerifyDetails* details) { proof_verify_details_.reset(details); } void QuicCryptoClientConfig::CachedState::InitializeFrom( const QuicCryptoClientConfig::CachedSt
#include "quiche/quic/core/crypto/quic_crypto_client_config.h" #include <string> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/proof_verifier.h" #include "quiche/quic/core/quic_server_id.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/crypto_test_utils.h" #include "quiche/quic/test_tools/mock_random.h" #include "quiche/quic/test_tools/quic_test_utils.h" using testing::StartsWith; namespace quic { namespace test { namespace { class TestProofVerifyDetails : public ProofVerifyDetails { ~TestProofVerifyDetails() override {} ProofVerifyDetails* Clone() const override { return new TestProofVerifyDetails; } }; class OneServerIdFilter : public QuicCryptoClientConfig::ServerIdFilter { public: explicit OneServerIdFilter(const QuicServerId* server_id) : server_id_(*server_id) {} bool Matches(const QuicServerId& server_id) const override { return server_id == server_id_; } private: const QuicServerId server_id_; }; class AllServerIdsFilter : public QuicCryptoClientConfig::ServerIdFilter { public: bool Matches(const QuicServerId& ) const override { return true; } }; } class QuicCryptoClientConfigTest : public QuicTest {}; TEST_F(QuicCryptoClientConfigTest, CachedState_IsEmpty) { QuicCryptoClientConfig::CachedState state; EXPECT_TRUE(state.IsEmpty()); } TEST_F(QuicCryptoClientConfigTest, CachedState_IsComplete) { QuicCryptoClientConfig::CachedState state; EXPECT_FALSE(state.IsComplete(QuicWallTime::FromUNIXSeconds(0))); } TEST_F(QuicCryptoClientConfigTest, CachedState_GenerationCounter) { QuicCryptoClientConfig::CachedState state; EXPECT_EQ(0u, state.generation_counter()); state.SetProofInvalid(); EXPECT_EQ(1u, state.generation_counter()); } TEST_F(QuicCryptoClientConfigTest, CachedState_SetProofVerifyDetails) { QuicCryptoClientConfig::CachedState state; EXPECT_TRUE(state.proof_verify_details() == nullptr); ProofVerifyDetails* details = new TestProofVerifyDetails; state.SetProofVerifyDetails(details); EXPECT_EQ(details, state.proof_verify_details()); } TEST_F(QuicCryptoClientConfigTest, CachedState_InitializeFrom) { QuicCryptoClientConfig::CachedState state; QuicCryptoClientConfig::CachedState other; state.set_source_address_token("TOKEN"); other.InitializeFrom(state); EXPECT_EQ(state.server_config(), other.server_config()); EXPECT_EQ(state.source_address_token(), other.source_address_token()); EXPECT_EQ(state.certs(), other.certs()); EXPECT_EQ(1u, other.generation_counter()); } TEST_F(QuicCryptoClientConfigTest, InchoateChlo) { QuicCryptoClientConfig::CachedState state; QuicCryptoClientConfig config(crypto_test_utils::ProofVerifierForTesting()); config.set_user_agent_id("quic-tester"); config.set_alpn("hq"); quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> params( new QuicCryptoNegotiatedParameters); CryptoHandshakeMessage msg; QuicServerId server_id("www.google.com", 443, false); MockRandom rand; config.FillInchoateClientHello(server_id, QuicVersionMax(), &state, &rand, true, params, &msg); QuicVersionLabel cver; EXPECT_THAT(msg.GetVersionLabel(kVER, &cver), IsQuicNoError()); EXPECT_EQ(CreateQuicVersionLabel(QuicVersionMax()), cver); absl::string_view proof_nonce; EXPECT_TRUE(msg.GetStringPiece(kNONP, &proof_nonce)); EXPECT_EQ(std::string(32, 'r'), proof_nonce); absl::string_view user_agent_id; EXPECT_TRUE(msg.GetStringPiece(kUAID, &user_agent_id)); EXPECT_EQ("quic-tester", user_agent_id); absl::string_view alpn; EXPECT_TRUE(msg.GetStringPiece(kALPN, &alpn)); EXPECT_EQ("hq", alpn); EXPECT_EQ(msg.minimum_size(), 1u); } TEST_F(QuicCryptoClientConfigTest, InchoateChloIsNotPadded) { QuicCryptoClientConfig::CachedState state; QuicCryptoClientConfig config(crypto_test_utils::ProofVerifierForTesting()); config.set_pad_inchoate_hello(false); config.set_user_agent_id("quic-tester"); config.set_alpn("hq"); quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> params( new QuicCryptoNegotiatedParameters); CryptoHandshakeMessage msg; QuicServerId server_id("www.google.com", 443, false); MockRandom rand; config.FillInchoateClientHello(server_id, QuicVersionMax(), &state, &rand, true, params, &msg); EXPECT_EQ(msg.minimum_size(), 1u); } TEST_F(QuicCryptoClientConfigTest, PreferAesGcm) { QuicCryptoClientConfig config(crypto_test_utils::ProofVerifierForTesting()); if (EVP_has_aes_hardware() == 1) { EXPECT_EQ(kAESG, config.aead[0]); } else { EXPECT_EQ(kCC20, config.aead[0]); } } TEST_F(QuicCryptoClientConfigTest, InchoateChloSecure) { QuicCryptoClientConfig::CachedState state; QuicCryptoClientConfig config(crypto_test_utils::ProofVerifierForTesting()); quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> params( new QuicCryptoNegotiatedParameters); CryptoHandshakeMessage msg; QuicServerId server_id("www.google.com", 443, false); MockRandom rand; config.FillInchoateClientHello(server_id, QuicVersionMax(), &state, &rand, true, params, &msg); QuicTag pdmd; EXPECT_THAT(msg.GetUint32(kPDMD, &pdmd), IsQuicNoError()); EXPECT_EQ(kX509, pdmd); absl::string_view scid; EXPECT_FALSE(msg.GetStringPiece(kSCID, &scid)); } TEST_F(QuicCryptoClientConfigTest, InchoateChloSecureWithSCIDNoEXPY) { QuicCryptoClientConfig::CachedState state; CryptoHandshakeMessage scfg; scfg.set_tag(kSCFG); scfg.SetStringPiece(kSCID, "12345678"); std::string details; QuicWallTime now = QuicWallTime::FromUNIXSeconds(1); QuicWallTime expiry = QuicWallTime::FromUNIXSeconds(2); state.SetServerConfig(scfg.GetSerialized().AsStringPiece(), now, expiry, &details); EXPECT_FALSE(state.IsEmpty()); QuicCryptoClientConfig config(crypto_test_utils::ProofVerifierForTesting()); quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> params( new QuicCryptoNegotiatedParameters); CryptoHandshakeMessage msg; QuicServerId server_id("www.google.com", 443, false); MockRandom rand; config.FillInchoateClientHello(server_id, QuicVersionMax(), &state, &rand, true, params, &msg); absl::string_view scid; EXPECT_TRUE(msg.GetStringPiece(kSCID, &scid)); EXPECT_EQ("12345678", scid); } TEST_F(QuicCryptoClientConfigTest, InchoateChloSecureWithSCID) { QuicCryptoClientConfig::CachedState state; CryptoHandshakeMessage scfg; scfg.set_tag(kSCFG); uint64_t future = 1; scfg.SetValue(kEXPY, future); scfg.SetStringPiece(kSCID, "12345678"); std::string details; state.SetServerConfig(scfg.GetSerialized().AsStringPiece(), QuicWallTime::FromUNIXSeconds(1), QuicWallTime::FromUNIXSeconds(0), &details); EXPECT_FALSE(state.IsEmpty()); QuicCryptoClientConfig config(crypto_test_utils::ProofVerifierForTesting()); quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> params( new QuicCryptoNegotiatedParameters); CryptoHandshakeMessage msg; QuicServerId server_id("www.google.com", 443, false); MockRandom rand; config.FillInchoateClientHello(server_id, QuicVersionMax(), &state, &rand, true, params, &msg); absl::string_view scid; EXPECT_TRUE(msg.GetStringPiece(kSCID, &scid)); EXPECT_EQ("12345678", scid); } TEST_F(QuicCryptoClientConfigTest, FillClientHello) { QuicCryptoClientConfig::CachedState state; QuicCryptoClientConfig config(crypto_test_utils::ProofVerifierForTesting()); quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> params( new QuicCryptoNegotiatedParameters); QuicConnectionId kConnectionId = TestConnectionId(1234); std::string error_details; MockRandom rand; CryptoHandshakeMessage chlo; QuicServerId server_id("www.google.com", 443, false); config.FillClientHello(server_id, kConnectionId, QuicVersionMax(), QuicVersionMax(), &state, QuicWallTime::Zero(), &rand, params, &chlo, &error_details); QuicVersionLabel cver; EXPECT_THAT(chlo.GetVersionLabel(kVER, &cver), IsQuicNoError()); EXPECT_EQ(CreateQuicVersionLabel(QuicVersionMax()), cver); } TEST_F(QuicCryptoClientConfigTest, FillClientHelloNoPadding) { QuicCryptoClientConfig::CachedState state; QuicCryptoClientConfig config(crypto_test_utils::ProofVerifierForTesting()); config.set_pad_full_hello(false); quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> params( new QuicCryptoNegotiatedParameters); QuicConnectionId kConnectionId = TestConnectionId(1234); std::string error_details; MockRandom rand; CryptoHandshakeMessage chlo; QuicServerId server_id("www.google.com", 443, false); config.FillClientHello(server_id, kConnectionId, QuicVersionMax(), QuicVersionMax(), &state, QuicWallTime::Zero(), &rand, params, &chlo, &error_details); QuicVersionLabel cver; EXPECT_THAT(chlo.GetVersionLabel(kVER, &cver), IsQuicNoError()); EXPECT_EQ(CreateQuicVersionLabel(QuicVersionMax()), cver); EXPECT_EQ(chlo.minimum_size(), 1u); } TEST_F(QuicCryptoClientConfigTest, ProcessServerDowngradeAttack) { ParsedQuicVersionVector supported_versions = AllSupportedVersions(); if (supported_versions.size() == 1) { return; } ParsedQuicVersionVector supported_version_vector; for (size_t i = supported_versions.size(); i > 0; --i) { supported_version_vector.push_back(supported_versions[i - 1]); } CryptoHandshakeMessage msg; msg.set_tag(kSHLO); msg.SetVersionVector(kVER, supported_version_vector); QuicCryptoClientConfig::CachedState cached; quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> out_params(new QuicCryptoNegotiatedParameters); std::string error; QuicCryptoClientConfig config(crypto_test_utils::ProofVerifierForTesting()); EXPECT_THAT(config.ProcessServerHello( msg, EmptyQuicConnectionId(), supported_versions.front(), supported_versions, &cached, out_params, &error), IsError(QUIC_VERSION_NEGOTIATION_MISMATCH)); EXPECT_THAT(error, StartsWith("Downgrade attack detected: ServerVersions")); } TEST_F(QuicCryptoClientConfigTest, InitializeFrom) { QuicCryptoClientConfig config(crypto_test_utils::ProofVerifierForTesting()); QuicServerId canonical_server_id("www.google.com", 443, false); QuicCryptoClientConfig::CachedState* state = config.LookupOrCreate(canonical_server_id); state->set_source_address_token("TOKEN"); state->SetProofValid(); QuicServerId other_server_id("mail.google.com", 443, false); config.InitializeFrom(other_server_id, canonical_server_id, &config); QuicCryptoClientConfig::CachedState* other = config.LookupOrCreate(other_server_id); EXPECT_EQ(state->server_config(), other->server_config()); EXPECT_EQ(state->source_address_token(), other->source_address_token()); EXPECT_EQ(state->certs(), other->certs()); EXPECT_EQ(1u, other->generation_counter()); } TEST_F(QuicCryptoClientConfigTest, Canonical) { QuicCryptoClientConfig config(crypto_test_utils::ProofVerifierForTesting()); config.AddCanonicalSuffix(".google.com"); QuicServerId canonical_id1("www.google.com", 443, false); QuicServerId canonical_id2("mail.google.com", 443, false); QuicCryptoClientConfig::CachedState* state = config.LookupOrCreate(canonical_id1); state->set_source_address_token("TOKEN"); state->SetProofValid(); QuicCryptoClientConfig::CachedState* other = config.LookupOrCreate(canonical_id2); EXPECT_TRUE(state->IsEmpty()); EXPECT_EQ(state->server_config(), other->server_config()); EXPECT_EQ(state->source_address_token(), other->source_address_token()); EXPECT_EQ(state->certs(), other->certs()); EXPECT_EQ(1u, other->generation_counter()); QuicServerId different_id("mail.google.org", 443, false); EXPECT_TRUE(config.LookupOrCreate(different_id)->IsEmpty()); } TEST_F(QuicCryptoClientConfigTest, CanonicalNotUsedIfNotValid) { QuicCryptoClientConfig config(crypto_test_utils::ProofVerifierForTesting()); config.AddCanonicalSuffix(".google.com"); QuicServerId canonical_id1("www.google.com", 443, false); QuicServerId canonical_id2("mail.google.com", 443, false); QuicCryptoClientConfig::CachedState* state = config.LookupOrCreate(canonical_id1); state->set_source_address_token("TOKEN"); EXPECT_TRUE(config.LookupOrCreate(canonical_id2)->IsEmpty()); } TEST_F(QuicCryptoClientConfigTest, ClearCachedStates) { QuicCryptoClientConfig config(crypto_test_utils::ProofVerifierForTesting()); struct TestCase { TestCase(const std::string& host, QuicCryptoClientConfig* config) : server_id(host, 443, false), state(config->LookupOrCreate(server_id)) { CryptoHandshakeMessage scfg; scfg.set_tag(kSCFG); uint64_t future = 1; scfg.SetValue(kEXPY, future); scfg.SetStringPiece(kSCID, "12345678"); std::string details; state->SetServerConfig(scfg.GetSerialized().AsStringPiece(), QuicWallTime::FromUNIXSeconds(0), QuicWallTime::FromUNIXSeconds(future), &details); std::vector<std::string> certs(1); certs[0] = "Hello Cert for " + host; state->SetProof(certs, "cert_sct", "chlo_hash", "signature"); state->set_source_address_token("TOKEN"); state->SetProofValid(); EXPECT_EQ(2u, state->generation_counter()); } QuicServerId server_id; QuicCryptoClientConfig::CachedState* state; } test_cases[] = {TestCase("www.google.com", &config), TestCase("www.example.com", &config)}; for (const TestCase& test_case : test_cases) { QuicCryptoClientConfig::CachedState* other = config.LookupOrCreate(test_case.server_id); EXPECT_EQ(test_case.state, other); EXPECT_EQ(2u, other->generation_counter()); } OneServerIdFilter google_com_filter(&test_cases[0].server_id); config.ClearCachedStates(google_com_filter); QuicCryptoClientConfig::CachedState* cleared_cache = config.LookupOrCreate(test_cases[0].server_id); EXPECT_EQ(test_cases[0].state, cleared_cache); EXPECT_FALSE(cleared_cache->proof_valid()); EXPECT_TRUE(cleared_cache->server_config().empty()); EXPECT_TRUE(cleared_cache->certs().empty()); EXPECT_TRUE(cleared_cache->cert_sct().empty()); EXPECT_TRUE(cleared_cache->signature().empty()); EXPECT_EQ(3u, cleared_cache->generation_counter()); QuicCryptoClientConfig::CachedState* existing_cache = config.LookupOrCreate(test_cases[1].server_id); EXPECT_EQ(test_cases[1].state, existing_cache); EXPECT_TRUE(existing_cache->proof_valid()); EXPECT_FALSE(existing_cache->server_config().empty()); EXPECT_FALSE(existing_cache->certs().empty()); EXPECT_FALSE(existing_cache->cert_sct().empty()); EXPECT_FALSE(existing_cache->signature().empty()); EXPECT_EQ(2u, existing_cache->generation_counter()); AllServerIdsFilter all_server_ids; config.ClearCachedStates(all_server_ids); cleared_cache = config.LookupOrCreate(test_cases[1].server_id); EXPECT_EQ(test_cases[1].state, cleared_cache); EXPECT_FALSE(cleared_cache->proof_valid()); EXPECT_TRUE(cleared_cache->server_config().empty()); EXPECT_TRUE(cleared_cache->certs().empty()); EXPECT_TRUE(cleared_cache->cert_sct().empty()); EXPECT_TRUE(cleared_cache->signature().empty()); EXPECT_EQ(3u, cleared_cache->generation_counter()); } TEST_F(QuicCryptoClientConfigTest, ProcessReject) { CryptoHandshakeMessage rej; crypto_test_utils::FillInDummyReject(&rej); QuicCryptoClientConfig::CachedState cached; quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> out_params(new QuicCryptoNegotiatedParameters); std::string error; QuicCryptoClientConfig config(crypto_test_utils::ProofVerifierForTesting()); EXPECT_THAT( config.ProcessRejection( rej, QuicWallTime::FromUNIXSeconds(0), AllSupportedVersionsWithQuicCrypto().front().transport_version, "", &cached, out_params, &error), IsQuicNoError()); } TEST_F(QuicCryptoClientConfigTest, ProcessRejectWithLongTTL) { CryptoHandshakeMessage rej; crypto_test_utils::FillInDummyReject(&rej); QuicTime::Delta one_week = QuicTime::Delta::FromSeconds(kNumSecondsPerWeek); int64_t long_ttl = 3 * one_week.ToSeconds(); rej.SetValue(kSTTL, long_ttl); QuicCryptoClientConfig::CachedState cached; quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> out_params(new QuicCryptoNegotiatedParameters); std::string error; QuicCryptoClientConfig config(crypto_test_utils::ProofVerifierForTesting()); EXPECT_THAT( config.ProcessRejection( rej, QuicWallTime::FromUNIXSeconds(0), AllSupportedVersionsWithQuicCrypto().front().transport_version, "", &cached, out_params, &error), IsQuicNoError()); cached.SetProofValid(); EXPECT_FALSE(cached.IsComplete(QuicWallTime::FromUNIXSeconds(long_ttl))); EXPECT_FALSE( cached.IsComplete(QuicWallTime::FromUNIXSeconds(one_week.ToSeconds()))); EXPECT_TRUE(cached.IsComplete( QuicWallTime::FromUNIXSeconds(one_week.ToSeconds() - 1))); } TEST_F(QuicCryptoClientConfigTest, ServerNonceinSHLO) { CryptoHandshakeMessage msg; msg.set_tag(kSHLO); ParsedQuicVersionVector supported_versions; ParsedQuicVersion version = AllSupportedVersions().front(); supported_versions.push_back(version); msg.SetVersionVector(kVER, supported_versions); QuicCryptoClientConfig config(crypto_test_utils::ProofVerifierForTesting()); QuicCryptoClientConfig::CachedState cached; quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> out_params(new QuicCryptoNegotiatedParameters); std::string error_details; EXPECT_THAT(config.ProcessServerHello(msg, EmptyQuicConnectionId(), version, supported_versions, &cached, out_params, &error_details), IsError(QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER)); EXPECT_EQ("server hello missing server nonce", error_details); } TEST_F(QuicCryptoClientConfigTest, MultipleCanonicalEntries) { QuicCryptoClientConfig config(crypto_test_utils::ProofVerifierForTesting()); config.AddCanonicalSuffix(".google.com"); QuicServerId canonical_server_id1("www.google.com", 443, false); QuicCryptoClientConfig::CachedState* state1 = config.LookupOrCreate(canonical_server_id1); CryptoHandshakeMessage scfg; scfg.set_tag(kSCFG); scfg.SetStringPiece(kSCID, "12345678"); std::string details; QuicWallTime now = QuicWallTime::FromUNIXSeconds(1); QuicWallTime expiry = QuicWallTime::FromUNIXSeconds(2); state1->SetServerConfig(scfg.GetSerialized().AsStringPiece(), now, expiry, &details); state1->set_source_address_token("TOKEN"); state1->SetProofValid(); EXPECT_FALSE(state1->IsEmpty()); QuicServerId canonical_server_id2("mail.google.com", 443, false); QuicCryptoClientConfig::CachedState* state2 = config.LookupOrCreate(canonical_server_id2); EXPECT_FALSE(state2->IsEmpty()); const CryptoHandshakeMessage* const scfg2 = state2->GetServerConfig(); ASSERT_TRUE(scfg2); EXPECT_EQ(kSCFG, scfg2->tag()); config.AddCanonicalSuffix(".example.com"); QuicServerId canonical_server_id3("www.example.com", 443, false); QuicCryptoClientConfig::CachedState* state3 = config.LookupOrCreate(canonical_server_id3); EXPECT_TRUE(state3->IsEmpty()); const CryptoHandshakeMessage* const scfg3 = state3->GetServerConfig(); EXPECT_FALSE(scfg3); } } }
359
cpp
google/quiche
chacha20_poly1305_tls_encrypter
quiche/quic/core/crypto/chacha20_poly1305_tls_encrypter.cc
quiche/quic/core/crypto/chacha20_poly1305_tls_encrypter_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_CHACHA20_POLY1305_TLS_ENCRYPTER_H_ #define QUICHE_QUIC_CORE_CRYPTO_CHACHA20_POLY1305_TLS_ENCRYPTER_H_ #include "quiche/quic/core/crypto/chacha_base_encrypter.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT ChaCha20Poly1305TlsEncrypter : public ChaChaBaseEncrypter { public: enum { kAuthTagSize = 16, }; ChaCha20Poly1305TlsEncrypter(); ChaCha20Poly1305TlsEncrypter(const ChaCha20Poly1305TlsEncrypter&) = delete; ChaCha20Poly1305TlsEncrypter& operator=(const ChaCha20Poly1305TlsEncrypter&) = delete; ~ChaCha20Poly1305TlsEncrypter() override; QuicPacketCount GetConfidentialityLimit() const override; }; } #endif #include "quiche/quic/core/crypto/chacha20_poly1305_tls_encrypter.h" #include <limits> #include "openssl/evp.h" namespace quic { namespace { const size_t kKeySize = 32; const size_t kNonceSize = 12; } ChaCha20Poly1305TlsEncrypter::ChaCha20Poly1305TlsEncrypter() : ChaChaBaseEncrypter(EVP_aead_chacha20_poly1305, kKeySize, kAuthTagSize, kNonceSize, true) { static_assert(kKeySize <= kMaxKeySize, "key size too big"); static_assert(kNonceSize <= kMaxNonceSize, "nonce size too big"); } ChaCha20Poly1305TlsEncrypter::~ChaCha20Poly1305TlsEncrypter() {} QuicPacketCount ChaCha20Poly1305TlsEncrypter::GetConfidentialityLimit() const { return std::numeric_limits<QuicPacketCount>::max(); } }
#include "quiche/quic/core/crypto/chacha20_poly1305_tls_encrypter.h" #include <memory> #include <string> #include "absl/base/macros.h" #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/chacha20_poly1305_tls_decrypter.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace { struct TestVector { const char* key; const char* pt; const char* iv; const char* fixed; const char* aad; const char* ct; }; const TestVector test_vectors[] = { { "808182838485868788898a8b8c8d8e8f" "909192939495969798999a9b9c9d9e9f", "4c616469657320616e642047656e746c" "656d656e206f662074686520636c6173" "73206f66202739393a20496620492063" "6f756c64206f6666657220796f75206f" "6e6c79206f6e652074697020666f7220" "746865206675747572652c2073756e73" "637265656e20776f756c642062652069" "742e", "4041424344454647", "07000000", "50515253c0c1c2c3c4c5c6c7", "d31a8d34648e60db7b86afbc53ef7ec2" "a4aded51296e08fea9e2b5a736ee62d6" "3dbea45e8ca9671282fafb69da92728b" "1a71de0a9e060b2905d6a5b67ecd3b36" "92ddbd7f2d778b8c9803aee328091b58" "fab324e4fad675945585808b4831d7bc" "3ff4def08e4b7a9de576d26586cec64b" "6116" "1ae10b594f09e26a7e902ecbd0600691", }, {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}}; } namespace quic { namespace test { QuicData* EncryptWithNonce(ChaCha20Poly1305TlsEncrypter* encrypter, absl::string_view nonce, absl::string_view associated_data, absl::string_view plaintext) { size_t ciphertext_size = encrypter->GetCiphertextSize(plaintext.length()); std::unique_ptr<char[]> ciphertext(new char[ciphertext_size]); if (!encrypter->Encrypt(nonce, associated_data, plaintext, reinterpret_cast<unsigned char*>(ciphertext.get()))) { return nullptr; } return new QuicData(ciphertext.release(), ciphertext_size, true); } class ChaCha20Poly1305TlsEncrypterTest : public QuicTest {}; TEST_F(ChaCha20Poly1305TlsEncrypterTest, EncryptThenDecrypt) { ChaCha20Poly1305TlsEncrypter encrypter; ChaCha20Poly1305TlsDecrypter decrypter; std::string key; ASSERT_TRUE(absl::HexStringToBytes(test_vectors[0].key, &key)); ASSERT_TRUE(encrypter.SetKey(key)); ASSERT_TRUE(decrypter.SetKey(key)); ASSERT_TRUE(encrypter.SetIV("abcdefghijkl")); ASSERT_TRUE(decrypter.SetIV("abcdefghijkl")); uint64_t packet_number = UINT64_C(0x123456789ABC); std::string associated_data = "associated_data"; std::string plaintext = "plaintext"; char encrypted[1024]; size_t len; ASSERT_TRUE(encrypter.EncryptPacket(packet_number, associated_data, plaintext, encrypted, &len, ABSL_ARRAYSIZE(encrypted))); absl::string_view ciphertext(encrypted, len); char decrypted[1024]; ASSERT_TRUE(decrypter.DecryptPacket(packet_number, associated_data, ciphertext, decrypted, &len, ABSL_ARRAYSIZE(decrypted))); } TEST_F(ChaCha20Poly1305TlsEncrypterTest, Encrypt) { for (size_t i = 0; test_vectors[i].key != nullptr; i++) { std::string key; std::string pt; std::string iv; std::string fixed; std::string aad; std::string ct; ASSERT_TRUE(absl::HexStringToBytes(test_vectors[i].key, &key)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[i].pt, &pt)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[i].iv, &iv)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[i].fixed, &fixed)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[i].aad, &aad)); ASSERT_TRUE(absl::HexStringToBytes(test_vectors[i].ct, &ct)); ChaCha20Poly1305TlsEncrypter encrypter; ASSERT_TRUE(encrypter.SetKey(key)); std::unique_ptr<QuicData> encrypted(EncryptWithNonce( &encrypter, fixed + iv, absl::string_view(aad.length() ? aad.data() : nullptr, aad.length()), pt)); ASSERT_TRUE(encrypted.get()); EXPECT_EQ(16u, ct.size() - pt.size()); EXPECT_EQ(16u, encrypted->length() - pt.size()); quiche::test::CompareCharArraysWithHexError("ciphertext", encrypted->data(), encrypted->length(), ct.data(), ct.length()); } } TEST_F(ChaCha20Poly1305TlsEncrypterTest, GetMaxPlaintextSize) { ChaCha20Poly1305TlsEncrypter encrypter; EXPECT_EQ(1000u, encrypter.GetMaxPlaintextSize(1016)); EXPECT_EQ(100u, encrypter.GetMaxPlaintextSize(116)); EXPECT_EQ(10u, encrypter.GetMaxPlaintextSize(26)); } TEST_F(ChaCha20Poly1305TlsEncrypterTest, GetCiphertextSize) { ChaCha20Poly1305TlsEncrypter encrypter; EXPECT_EQ(1016u, encrypter.GetCiphertextSize(1000)); EXPECT_EQ(116u, encrypter.GetCiphertextSize(100)); EXPECT_EQ(26u, encrypter.GetCiphertextSize(10)); } TEST_F(ChaCha20Poly1305TlsEncrypterTest, GenerateHeaderProtectionMask) { ChaCha20Poly1305TlsEncrypter encrypter; std::string key; std::string sample; std::string expected_mask; ASSERT_TRUE(absl::HexStringToBytes( "6a067f432787bd6034dd3f08f07fc9703a27e58c70e2d88d948b7f6489923cc7", &key)); ASSERT_TRUE( absl::HexStringToBytes("1210d91cceb45c716b023f492c29e612", &sample)); ASSERT_TRUE(absl::HexStringToBytes("1cc2cd98dc", &expected_mask)); ASSERT_TRUE(encrypter.SetHeaderProtectionKey(key)); std::string mask = encrypter.GenerateHeaderProtectionMask(sample); quiche::test::CompareCharArraysWithHexError( "header protection mask", mask.data(), mask.size(), expected_mask.data(), expected_mask.size()); } } }
360
cpp
google/quiche
quic_compressed_certs_cache
quiche/quic/core/crypto/quic_compressed_certs_cache.cc
quiche/quic/core/crypto/quic_compressed_certs_cache_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_QUIC_COMPRESSED_CERTS_CACHE_H_ #define QUICHE_QUIC_CORE_CRYPTO_QUIC_COMPRESSED_CERTS_CACHE_H_ #include <string> #include <vector> #include "quiche/quic/core/crypto/proof_source.h" #include "quiche/quic/core/quic_lru_cache.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT QuicCompressedCertsCache { public: explicit QuicCompressedCertsCache(int64_t max_num_certs); ~QuicCompressedCertsCache(); const std::string* GetCompressedCert( const quiche::QuicheReferenceCountedPointer<ProofSource::Chain>& chain, const std::string& client_cached_cert_hashes); void Insert( const quiche::QuicheReferenceCountedPointer<ProofSource::Chain>& chain, const std::string& client_cached_cert_hashes, const std::string& compressed_cert); size_t MaxSize(); size_t Size(); static const size_t kQuicCompressedCertsCacheSize; private: struct QUICHE_EXPORT UncompressedCerts { UncompressedCerts(); UncompressedCerts( const quiche::QuicheReferenceCountedPointer<ProofSource::Chain>& chain, const std::string* client_cached_cert_hashes); ~UncompressedCerts(); const quiche::QuicheReferenceCountedPointer<ProofSource::Chain> chain; const std::string* client_cached_cert_hashes; }; class QUICHE_EXPORT CachedCerts { public: CachedCerts(); CachedCerts(const UncompressedCerts& uncompressed_certs, const std::string& compressed_cert); CachedCerts(const CachedCerts& other); ~CachedCerts(); bool MatchesUncompressedCerts( const UncompressedCerts& uncompressed_certs) const; const std::string* compressed_cert() const; private: quiche::QuicheReferenceCountedPointer<ProofSource::Chain> chain_; const std::string client_cached_cert_hashes_; const std::string compressed_cert_; }; uint64_t ComputeUncompressedCertsHash( const UncompressedCerts& uncompressed_certs); QuicLRUCache<uint64_t, CachedCerts> certs_cache_; }; } #endif #include "quiche/quic/core/crypto/quic_compressed_certs_cache.h" #include <memory> #include <string> #include <utility> namespace quic { namespace { inline void hash_combine(uint64_t* seed, const uint64_t& val) { (*seed) ^= val + 0x9e3779b9 + ((*seed) << 6) + ((*seed) >> 2); } } const size_t QuicCompressedCertsCache::kQuicCompressedCertsCacheSize = 225; QuicCompressedCertsCache::UncompressedCerts::UncompressedCerts() : chain(nullptr), client_cached_cert_hashes(nullptr) {} QuicCompressedCertsCache::UncompressedCerts::UncompressedCerts( const quiche::QuicheReferenceCountedPointer<ProofSource::Chain>& chain, const std::string* client_cached_cert_hashes) : chain(chain), client_cached_cert_hashes(client_cached_cert_hashes) {} QuicCompressedCertsCache::UncompressedCerts::~UncompressedCerts() {} QuicCompressedCertsCache::CachedCerts::CachedCerts() {} QuicCompressedCertsCache::CachedCerts::CachedCerts( const UncompressedCerts& uncompressed_certs, const std::string& compressed_cert) : chain_(uncompressed_certs.chain), client_cached_cert_hashes_(*uncompressed_certs.client_cached_cert_hashes), compressed_cert_(compressed_cert) {} QuicCompressedCertsCache::CachedCerts::CachedCerts(const CachedCerts& other) = default; QuicCompressedCertsCache::CachedCerts::~CachedCerts() {} bool QuicCompressedCertsCache::CachedCerts::MatchesUncompressedCerts( const UncompressedCerts& uncompressed_certs) const { return (client_cached_cert_hashes_ == *uncompressed_certs.client_cached_cert_hashes && chain_ == uncompressed_certs.chain); } const std::string* QuicCompressedCertsCache::CachedCerts::compressed_cert() const { return &compressed_cert_; } QuicCompressedCertsCache::QuicCompressedCertsCache(int64_t max_num_certs) : certs_cache_(max_num_certs) {} QuicCompressedCertsCache::~QuicCompressedCertsCache() { certs_cache_.Clear(); } const std::string* QuicCompressedCertsCache::GetCompressedCert( const quiche::QuicheReferenceCountedPointer<ProofSource::Chain>& chain, const std::string& client_cached_cert_hashes) { UncompressedCerts uncompressed_certs(chain, &client_cached_cert_hashes); uint64_t key = ComputeUncompressedCertsHash(uncompressed_certs); CachedCerts* cached_value = nullptr; auto iter = certs_cache_.Lookup(key); if (iter != certs_cache_.end()) { cached_value = iter->second.get(); } if (cached_value != nullptr && cached_value->MatchesUncompressedCerts(uncompressed_certs)) { return cached_value->compressed_cert(); } return nullptr; } void QuicCompressedCertsCache::Insert( const quiche::QuicheReferenceCountedPointer<ProofSource::Chain>& chain, const std::string& client_cached_cert_hashes, const std::string& compressed_cert) { UncompressedCerts uncompressed_certs(chain, &client_cached_cert_hashes); uint64_t key = ComputeUncompressedCertsHash(uncompressed_certs); std::unique_ptr<CachedCerts> cached_certs( new CachedCerts(uncompressed_certs, compressed_cert)); certs_cache_.Insert(key, std::move(cached_certs)); } size_t QuicCompressedCertsCache::MaxSize() { return certs_cache_.MaxSize(); } size_t QuicCompressedCertsCache::Size() { return certs_cache_.Size(); } uint64_t QuicCompressedCertsCache::ComputeUncompressedCertsHash( const UncompressedCerts& uncompressed_certs) { uint64_t hash = std::hash<std::string>()(*uncompressed_certs.client_cached_cert_hashes); hash_combine(&hash, reinterpret_cast<uint64_t>(uncompressed_certs.chain.get())); return hash; } }
#include "quiche/quic/core/crypto/quic_compressed_certs_cache.h" #include <string> #include <vector> #include "absl/strings/str_cat.h" #include "quiche/quic/core/crypto/cert_compressor.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/crypto_test_utils.h" namespace quic { namespace test { namespace { class QuicCompressedCertsCacheTest : public QuicTest { public: QuicCompressedCertsCacheTest() : certs_cache_(QuicCompressedCertsCache::kQuicCompressedCertsCacheSize) {} protected: QuicCompressedCertsCache certs_cache_; }; TEST_F(QuicCompressedCertsCacheTest, CacheHit) { std::vector<std::string> certs = {"leaf cert", "intermediate cert", "root cert"}; quiche::QuicheReferenceCountedPointer<ProofSource::Chain> chain( new ProofSource::Chain(certs)); std::string cached_certs = "cached certs"; std::string compressed = "compressed cert"; certs_cache_.Insert(chain, cached_certs, compressed); const std::string* cached_value = certs_cache_.GetCompressedCert(chain, cached_certs); ASSERT_NE(nullptr, cached_value); EXPECT_EQ(*cached_value, compressed); } TEST_F(QuicCompressedCertsCacheTest, CacheMiss) { std::vector<std::string> certs = {"leaf cert", "intermediate cert", "root cert"}; quiche::QuicheReferenceCountedPointer<ProofSource::Chain> chain( new ProofSource::Chain(certs)); std::string cached_certs = "cached certs"; std::string compressed = "compressed cert"; certs_cache_.Insert(chain, cached_certs, compressed); EXPECT_EQ(nullptr, certs_cache_.GetCompressedCert(chain, "mismatched cached certs")); quiche::QuicheReferenceCountedPointer<ProofSource::Chain> chain2( new ProofSource::Chain(certs)); EXPECT_EQ(nullptr, certs_cache_.GetCompressedCert(chain2, cached_certs)); } TEST_F(QuicCompressedCertsCacheTest, CacheMissDueToEviction) { std::vector<std::string> certs = {"leaf cert", "intermediate cert", "root cert"}; quiche::QuicheReferenceCountedPointer<ProofSource::Chain> chain( new ProofSource::Chain(certs)); std::string cached_certs = "cached certs"; std::string compressed = "compressed cert"; certs_cache_.Insert(chain, cached_certs, compressed); for (unsigned int i = 0; i < QuicCompressedCertsCache::kQuicCompressedCertsCacheSize; i++) { EXPECT_EQ(certs_cache_.Size(), i + 1); certs_cache_.Insert(chain, absl::StrCat(i), absl::StrCat(i)); } EXPECT_EQ(certs_cache_.MaxSize(), certs_cache_.Size()); EXPECT_EQ(nullptr, certs_cache_.GetCompressedCert(chain, cached_certs)); } } } }
361
cpp
google/quiche
crypto_utils
quiche/quic/core/crypto/crypto_utils.cc
quiche/quic/core/crypto/crypto_utils_test.cc
#ifndef QUICHE_QUIC_CORE_CRYPTO_CRYPTO_UTILS_H_ #define QUICHE_QUIC_CORE_CRYPTO_CRYPTO_UTILS_H_ #include <cstddef> #include <cstdint> #include <string> #include "absl/strings/string_view.h" #include "openssl/evp.h" #include "openssl/ssl.h" #include "quiche/quic/core/crypto/crypto_handshake.h" #include "quiche/quic/core/crypto/crypto_handshake_message.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/crypto/quic_crypter.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_export.h" namespace quic { class QUICHE_EXPORT CryptoUtils { public: CryptoUtils() = delete; class QUICHE_EXPORT Diversification { public: enum Mode { NEVER, PENDING, NOW, }; Diversification(const Diversification& diversification) = default; static Diversification Never() { return Diversification(NEVER, nullptr); } static Diversification Pending() { return Diversification(PENDING, nullptr); } static Diversification Now(DiversificationNonce* nonce) { return Diversification(NOW, nonce); } Mode mode() const { return mode_; } DiversificationNonce* nonce() const { QUICHE_DCHECK_EQ(mode_, NOW); return nonce_; } private: Diversification(Mode mode, DiversificationNonce* nonce) : mode_(mode), nonce_(nonce) {} Mode mode_; DiversificationNonce* nonce_; }; static void InitializeCrypterSecrets(const EVP_MD* prf, const std::vector<uint8_t>& pp_secret, const ParsedQuicVersion& version, QuicCrypter* crypter); static void SetKeyAndIV(const EVP_MD* prf, absl::Span<const uint8_t> pp_secret, const ParsedQuicVersion& version, QuicCrypter* crypter); static std::vector<uint8_t> GenerateHeaderProtectionKey( const EVP_MD* prf, absl::Span<const uint8_t> pp_secret, const ParsedQuicVersion& version, size_t out_len); static std::vector<uint8_t> GenerateNextKeyPhaseSecret( const EVP_MD* prf, const ParsedQuicVersion& version, const std::vector<uint8_t>& current_secret); static void CreateInitialObfuscators(Perspective perspective, ParsedQuicVersion version, QuicConnectionId connection_id, CrypterPair* crypters); static bool ValidateRetryIntegrityTag(ParsedQuicVersion version, QuicConnectionId original_connection_id, absl::string_view retry_without_tag, absl::string_view integrity_tag); static void GenerateNonce(QuicWallTime now, QuicRandom* random_generator, absl::string_view orbit, std::string* nonce); static bool DeriveKeys(const ParsedQuicVersion& version, absl::string_view premaster_secret, QuicTag aead, absl::string_view client_nonce, absl::string_view server_nonce, absl::string_view pre_shared_key, const std::string& hkdf_input, Perspective perspective, Diversification diversification, CrypterPair* crypters, std::string* subkey_secret); static uint64_t ComputeLeafCertHash(absl::string_view cert); static QuicErrorCode ValidateServerHello( const CryptoHandshakeMessage& server_hello, const ParsedQuicVersionVector& negotiated_versions, std::string* error_details); static QuicErrorCode ValidateServerHelloVersions( const QuicVersionLabelVector& server_versions, const ParsedQuicVersionVector& negotiated_versions, std::string* error_details); static QuicErrorCode ValidateClientHello( const CryptoHandshakeMessage& client_hello, ParsedQuicVersion version, const ParsedQuicVersionVector& supported_versions, std::string* error_details); static QuicErrorCode ValidateClientHelloVersion( QuicVersionLabel client_version, ParsedQuicVersion connection_version, const ParsedQuicVersionVector& supported_versions, std::string* error_details); static bool ValidateChosenVersion( const QuicVersionLabel& version_information_chosen_version, const ParsedQuicVersion& session_version, std::string* error_details); static bool ValidateServerVersions( const QuicVersionLabelVector& version_information_other_versions, const ParsedQuicVersion& session_version, const ParsedQuicVersionVector& client_original_supported_versions, std::string* error_details); static const char* HandshakeFailureReasonToString( HandshakeFailureReason reason); static std::string EarlyDataReasonToString(ssl_early_data_reason_t reason); static std::string HashHandshakeMessage(const CryptoHandshakeMessage& message, Perspective perspective); static bool GetSSLCapabilities(const SSL* ssl, bssl::UniquePtr<uint8_t>* capabilities, size_t* capabilities_len); static std::optional<std::string> GenerateProofPayloadToBeSigned( absl::string_view chlo_hash, absl::string_view server_config); }; } #endif #include "quiche/quic/core/crypto/crypto_utils.h" #include <algorithm> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "openssl/bytestring.h" #include "openssl/hkdf.h" #include "openssl/mem.h" #include "openssl/sha.h" #include "quiche/quic/core/crypto/aes_128_gcm_12_decrypter.h" #include "quiche/quic/core/crypto/aes_128_gcm_12_encrypter.h" #include "quiche/quic/core/crypto/aes_128_gcm_decrypter.h" #include "quiche/quic/core/crypto/aes_128_gcm_encrypter.h" #include "quiche/quic/core/crypto/crypto_handshake.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/crypto/null_decrypter.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/crypto/quic_decrypter.h" #include "quiche/quic/core/crypto/quic_encrypter.h" #include "quiche/quic/core/crypto/quic_hkdf.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/common/quiche_endian.h" namespace quic { namespace { std::vector<uint8_t> HkdfExpandLabel(const EVP_MD* prf, absl::Span<const uint8_t> secret, const std::string& label, size_t out_len) { bssl::ScopedCBB quic_hkdf_label; CBB inner_label; const char label_prefix[] = "tls13 "; static const size_t max_quic_hkdf_label_length = 20; if (!CBB_init(quic_hkdf_label.get(), max_quic_hkdf_label_length) || !CBB_add_u16(quic_hkdf_label.get(), out_len) || !CBB_add_u8_length_prefixed(quic_hkdf_label.get(), &inner_label) || !CBB_add_bytes(&inner_label, reinterpret_cast<const uint8_t*>(label_prefix), ABSL_ARRAYSIZE(label_prefix) - 1) || !CBB_add_bytes(&inner_label, reinterpret_cast<const uint8_t*>(label.data()), label.size()) || !CBB_add_u8(quic_hkdf_label.get(), 0) || !CBB_flush(quic_hkdf_label.get())) { QUIC_LOG(ERROR) << "Building HKDF label failed"; return std::vector<uint8_t>(); } std::vector<uint8_t> out; out.resize(out_len); if (!HKDF_expand(out.data(), out_len, prf, secret.data(), secret.size(), CBB_data(quic_hkdf_label.get()), CBB_len(quic_hkdf_label.get()))) { QUIC_LOG(ERROR) << "Running HKDF-Expand-Label failed"; return std::vector<uint8_t>(); } return out; } } const std::string getLabelForVersion(const ParsedQuicVersion& version, const absl::string_view& predicate) { static_assert(SupportedVersions().size() == 4u, "Supported versions out of sync with HKDF labels"); if (version == ParsedQuicVersion::RFCv2()) { return absl::StrCat("quicv2 ", predicate); } else { return absl::StrCat("quic ", predicate); } } void CryptoUtils::InitializeCrypterSecrets( const EVP_MD* prf, const std::vector<uint8_t>& pp_secret, const ParsedQuicVersion& version, QuicCrypter* crypter) { SetKeyAndIV(prf, pp_secret, version, crypter); std::vector<uint8_t> header_protection_key = GenerateHeaderProtectionKey( prf, pp_secret, version, crypter->GetKeySize()); crypter->SetHeaderProtectionKey( absl::string_view(reinterpret_cast<char*>(header_protection_key.data()), header_protection_key.size())); } void CryptoUtils::SetKeyAndIV(const EVP_MD* prf, absl::Span<const uint8_t> pp_secret, const ParsedQuicVersion& version, QuicCrypter* crypter) { std::vector<uint8_t> key = HkdfExpandLabel(prf, pp_secret, getLabelForVersion(version, "key"), crypter->GetKeySize()); std::vector<uint8_t> iv = HkdfExpandLabel( prf, pp_secret, getLabelForVersion(version, "iv"), crypter->GetIVSize()); crypter->SetKey( absl::string_view(reinterpret_cast<char*>(key.data()), key.size())); crypter->SetIV( absl::string_view(reinterpret_cast<char*>(iv.data()), iv.size())); } std::vector<uint8_t> CryptoUtils::GenerateHeaderProtectionKey( const EVP_MD* prf, absl::Span<const uint8_t> pp_secret, const ParsedQuicVersion& version, size_t out_len) { return HkdfExpandLabel(prf, pp_secret, getLabelForVersion(version, "hp"), out_len); } std::vector<uint8_t> CryptoUtils::GenerateNextKeyPhaseSecret( const EVP_MD* prf, const ParsedQuicVersion& version, const std::vector<uint8_t>& current_secret) { return HkdfExpandLabel(prf, current_secret, getLabelForVersion(version, "ku"), current_secret.size()); } namespace { const uint8_t kDraft29InitialSalt[] = {0xaf, 0xbf, 0xec, 0x28, 0x99, 0x93, 0xd2, 0x4c, 0x9e, 0x97, 0x86, 0xf1, 0x9c, 0x61, 0x11, 0xe0, 0x43, 0x90, 0xa8, 0x99}; const uint8_t kRFCv1InitialSalt[] = {0x38, 0x76, 0x2c, 0xf7, 0xf5, 0x59, 0x34, 0xb3, 0x4d, 0x17, 0x9a, 0xe6, 0xa4, 0xc8, 0x0c, 0xad, 0xcc, 0xbb, 0x7f, 0x0a}; const uint8_t kRFCv2InitialSalt[] = { 0x0d, 0xed, 0xe3, 0xde, 0xf7, 0x00, 0xa6, 0xdb, 0x81, 0x93, 0x81, 0xbe, 0x6e, 0x26, 0x9d, 0xcb, 0xf9, 0xbd, 0x2e, 0xd9, }; const uint8_t kReservedForNegotiationSalt[] = { 0xf9, 0x64, 0xbf, 0x45, 0x3a, 0x1f, 0x1b, 0x80, 0xa5, 0xf8, 0x82, 0x03, 0x77, 0xd4, 0xaf, 0xca, 0x58, 0x0e, 0xe7, 0x43}; const uint8_t* InitialSaltForVersion(const ParsedQuicVersion& version, size_t* out_len) { static_assert(SupportedVersions().size() == 4u, "Supported versions out of sync with initial encryption salts"); if (version == ParsedQuicVersion::RFCv2()) { *out_len = ABSL_ARRAYSIZE(kRFCv2InitialSalt); return kRFCv2InitialSalt; } else if (version == ParsedQuicVersion::RFCv1()) { *out_len = ABSL_ARRAYSIZE(kRFCv1InitialSalt); return kRFCv1InitialSalt; } else if (version == ParsedQuicVersion::Draft29()) { *out_len = ABSL_ARRAYSIZE(kDraft29InitialSalt); return kDraft29InitialSalt; } else if (version == ParsedQuicVersion::ReservedForNegotiation()) { *out_len = ABSL_ARRAYSIZE(kReservedForNegotiationSalt); return kReservedForNegotiationSalt; } QUIC_BUG(quic_bug_10699_1) << "No initial obfuscation salt for version " << version; *out_len = ABSL_ARRAYSIZE(kReservedForNegotiationSalt); return kReservedForNegotiationSalt; } const char kPreSharedKeyLabel[] = "QUIC PSK"; const uint8_t kDraft29RetryIntegrityKey[] = {0xcc, 0xce, 0x18, 0x7e, 0xd0, 0x9a, 0x09, 0xd0, 0x57, 0x28, 0x15, 0x5a, 0x6c, 0xb9, 0x6b, 0xe1}; const uint8_t kDraft29RetryIntegrityNonce[] = { 0xe5, 0x49, 0x30, 0xf9, 0x7f, 0x21, 0x36, 0xf0, 0x53, 0x0a, 0x8c, 0x1c}; const uint8_t kRFCv1RetryIntegrityKey[] = {0xbe, 0x0c, 0x69, 0x0b, 0x9f, 0x66, 0x57, 0x5a, 0x1d, 0x76, 0x6b, 0x54, 0xe3, 0x68, 0xc8, 0x4e}; const uint8_t kRFCv1RetryIntegrityNonce[] = { 0x46, 0x15, 0x99, 0xd3, 0x5d, 0x63, 0x2b, 0xf2, 0x23, 0x98, 0x25, 0xbb}; const uint8_t kRFCv2RetryIntegrityKey[] = {0x8f, 0xb4, 0xb0, 0x1b, 0x56, 0xac, 0x48, 0xe2, 0x60, 0xfb, 0xcb, 0xce, 0xad, 0x7c, 0xcc, 0x92}; const uint8_t kRFCv2RetryIntegrityNonce[] = { 0xd8, 0x69, 0x69, 0xbc, 0x2d, 0x7c, 0x6d, 0x99, 0x90, 0xef, 0xb0, 0x4a}; const uint8_t kReservedForNegotiationRetryIntegrityKey[] = { 0xf2, 0xcd, 0x8f, 0xe0, 0x36, 0xd0, 0x25, 0x35, 0x03, 0xe6, 0x7c, 0x7b, 0xd2, 0x44, 0xca, 0xd9}; const uint8_t kReservedForNegotiationRetryIntegrityNonce[] = { 0x35, 0x9f, 0x16, 0xd1, 0xed, 0x80, 0x90, 0x8e, 0xec, 0x85, 0xc4, 0xd6}; bool RetryIntegrityKeysForVersion(const ParsedQuicVersion& version, absl::string_view* key, absl::string_view* nonce) { static_assert(SupportedVersions().size() == 4u, "Supported versions out of sync with retry integrity keys"); if (!version.UsesTls()) { QUIC_BUG(quic_bug_10699_2) << "Attempted to get retry integrity keys for invalid version " << version; return false; } else if (version == ParsedQuicVersion::RFCv2()) { *key = absl::string_view( reinterpret_cast<const char*>(kRFCv2RetryIntegrityKey), ABSL_ARRAYSIZE(kRFCv2RetryIntegrityKey)); *nonce = absl::string_view( reinterpret_cast<const char*>(kRFCv2RetryIntegrityNonce), ABSL_ARRAYSIZE(kRFCv2RetryIntegrityNonce)); return true; } else if (version == ParsedQuicVersion::RFCv1()) { *key = absl::string_view( reinterpret_cast<const char*>(kRFCv1RetryIntegrityKey), ABSL_ARRAYSIZE(kRFCv1RetryIntegrityKey)); *nonce = absl::string_view( reinterpret_cast<const char*>(kRFCv1RetryIntegrityNonce), ABSL_ARRAYSIZE(kRFCv1RetryIntegrityNonce)); return true; } else if (version == ParsedQuicVersion::Draft29()) { *key = absl::string_view( reinterpret_cast<const char*>(kDraft29RetryIntegrityKey), ABSL_ARRAYSIZE(kDraft29RetryIntegrityKey)); *nonce = absl::string_view( reinterpret_cast<const char*>(kDraft29RetryIntegrityNonce), ABSL_ARRAYSIZE(kDraft29RetryIntegrityNonce)); return true; } else if (version == ParsedQuicVersion::ReservedForNegotiation()) { *key = absl::string_view( reinterpret_cast<const char*>(kReservedForNegotiationRetryIntegrityKey), ABSL_ARRAYSIZE(kReservedForNegotiationRetryIntegrityKey)); *nonce = absl::string_view( reinterpret_cast<const char*>( kReservedForNegotiationRetryIntegrityNonce), ABSL_ARRAYSIZE(kReservedForNegotiationRetryIntegrityNonce)); return true; } QUIC_BUG(quic_bug_10699_3) << "Attempted to get retry integrity keys for version " << version; return false; } } void CryptoUtils::CreateInitialObfuscators(Perspective perspective, ParsedQuicVersion version, QuicConnectionId connection_id, CrypterPair* crypters) { QUIC_DLOG(INFO) << "Creating " << (perspective == Perspective::IS_CLIENT ? "client" : "server") << " crypters for version " << version << " with CID " << connection_id; if (!version.UsesInitialObfuscators()) { crypters->encrypter = std::make_unique<NullEncrypter>(perspective); crypters->decrypter = std::make_unique<NullDecrypter>(perspective); return; } QUIC_BUG_IF(quic_bug_12871_1, !QuicUtils::IsConnectionIdValidForVersion( connection_id, version.transport_version)) << "CreateTlsInitialCrypters: attempted to use connection ID " << connection_id << " which is invalid with version " << version; const EVP_MD* hash = EVP_sha256(); size_t salt_len; const uint8_t* salt = InitialSaltForVersion(version, &salt_len); std::vector<uint8_t> handshake_secret; handshake_secret.resize(EVP_MAX_MD_SIZE); size_t handshake_secret_len; const bool hkdf_extract_success = HKDF_extract(handshake_secret.data(), &handshake_secret_len, hash, reinterpret_cast<const uint8_t*>(connection_id.data()), connection_id.length(), salt, salt_len); QUIC_BUG_IF(quic_bug_12871_2, !hkdf_extract_success) << "HKDF_extract failed when creating initial crypters"; handshake_secret.resize(handshake_secret_len); const std::string client_label = "client in"; const std::string server_label = "server in"; std::string encryption_label, decryption_label; if (perspective == Perspective::IS_CLIENT) { encryption_label = client_label; decryption_label = server_label; } else { encryption_label = server_label; decryption_label = client_label; } std::vector<uint8_t> encryption_secret = HkdfExpandLabel( hash, handshake_secret, encryption_label, EVP_MD_size(hash)); crypters->encrypter = std::make_unique<Aes128GcmEncrypter>(); InitializeCrypterSecrets(hash, encryption_secret, version, crypters->encrypter.get()); std::vector<uint8_t> decryption_secret = HkdfExpandLabel( hash, handshake_secret, decryption_label, EVP_MD_size(hash)); crypters->decrypter = std::make_unique<Aes128GcmDecrypter>(); InitializeCrypterSecrets(hash, decryption_secret, version, crypters->decrypter.get()); } bool CryptoUtils::ValidateRetryIntegrityTag( ParsedQuicVersion version, QuicConnectionId original_connection_id, absl::string_view retry_without_tag, absl::string_view integrity_tag) { unsigned char computed_integrity_tag[kRetryIntegrityTagLength]; if (integrity_tag.length() != ABSL_ARRAYSIZE(computed_integrity_tag)) { QUIC_BUG(quic_bug_10699_4) << "Invalid retry integrity tag length " << integrity_tag.length(); return false; } char retry_pseudo_packet[kMaxIncomingPacketSize + 256]; QuicDataWriter writer(ABSL_ARRAYSIZE(retry_pseudo_packet), retry_pseudo_packet); if (!writer.WriteLengthPrefixedConnectionId(original_connection_id)) { QUIC_BUG(quic_bug_10699_5) << "Failed to write original connection ID in retry pseudo packet"; return false; } if (!writer.WriteStringPiece(retry_without_tag)) { QUIC_BUG(quic_bug_10699_6) << "Failed to write retry without tag in retry pseudo packet"; return false; } absl::string_view key; absl::string_view nonce; if (!RetryIntegrityKeysForVersion(version, &key, &nonce)) { return false; } Aes128GcmEncrypter crypter; crypter.SetKey(key); absl::string_view associated_data(writer.data(), writer.length()); absl::string_view plaintext; if (!crypter.Encrypt(nonce, associated_data, plaintext, computed_integrity_tag)) { QUIC_BUG(quic_bug_10699_7) << "Failed to compute retry integrity tag"; return false; } if (CRYPTO_memcmp(computed_integrity_tag, integrity_tag.data(), ABSL_ARRAYSIZE(computed_integrity_tag)) != 0) { QUIC_DLOG(ERROR) << "Failed to validate retry integrity tag"; return false; } return true; } void CryptoUtils::GenerateNonce(QuicWallTime now, QuicRandom* random_generator, absl::string_view orbit, std::string* nonce) { nonce->reserve(kNonceSize); nonce->resize(kNonceSize); uint32_t gmt_unix_time = static_cast<uint32_t>(now.ToUNIXSeconds()); (*nonce)[0] = static_cast<char>(gmt_unix_time >> 24); (*nonce)[1] = static_cast<char>(gmt_unix_time >> 16); (*nonce)[2] = static_cast<char>(gmt_unix_time >> 8); (*nonce)[3] = static_cast<char>(gmt_unix_time); size_t bytes_written = 4; if (orbit.size() == 8) { memcpy(&(*nonce)[bytes_written], orbit.data(), orbit.size()); bytes_written += orbit.size(); } random_generator->RandBytes(&(*nonce)[bytes_written], kNonceSize - bytes_written); } bool CryptoUtils::DeriveKeys( const ParsedQuicVersion& version, absl::string_view premaster_secret, QuicTag aead, absl::string_view client_nonce, absl::string_view server_nonce, absl::string_view pre_shared_key, const std::string& hkdf_input, Perspective perspective, Diversification diversification, CrypterPair* crypters, std::string* subkey_secret) { std::unique_ptr<char[]> psk_premaster_secret; if (!pre_shared_key.empty()) { const absl::string_view label(kPreSharedKeyLabel); const size_t psk_premaster_secret_size = label.size() + 1 + pre_shared_key.size() + 8 + premaster_secret.size() + 8; psk_premaster_secret = std::make_unique<char[]>(psk_premaster_secret_size); QuicDataWriter writer(psk_premaster_secret_size, psk_premaster_secret.get(), quiche::HOST_BYTE_ORDER); if (!writer.WriteStringPiece(label) || !writer.WriteUInt8(0) || !writer.WriteStringPiece(pre_shared_key) || !writer.WriteUInt64(pre_shared_key.size()) || !writer.WriteStringPiece(premaster_secret) || !writer.WriteUInt64(premaster_secret.size()) || writer.remaining() != 0) { return false; } premaster_secret = absl::string_view(psk_premaster_secret.get(), psk_premaster_secret_size); } crypters->encrypter = QuicEncrypter::Create(version, aead); crypters->decrypter = QuicDecrypter::Create(version, aead); size_t key_bytes = crypters->encrypter->GetKeySize(); size_t nonce_prefix_bytes = crypters->encrypter->GetNoncePrefixSize(); if (version.UsesInitialObfuscators()) { nonce_prefix_bytes = crypters->encrypter->GetIVSize(); } size_t subkey_secret_bytes = subkey_secret == nullptr ? 0 : premaster_secret.length(); absl::string_view nonce = client_nonce; std::string nonce_storage; if (!server_nonce.empty()) { nonce_storage = std::string(client_nonce) + std::string(server_nonce); nonce = nonce_storage; } QuicHKDF hkdf(premaster_secret, nonce, hkdf_input, key_bytes, nonce_prefix_bytes, subkey_secret_bytes);
#include "quiche/quic/core/crypto/crypto_utils.h" #include <memory> #include <string> #include "absl/base/macros.h" #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace quic { namespace test { namespace { class CryptoUtilsTest : public QuicTest {}; TEST_F(CryptoUtilsTest, HandshakeFailureReasonToString) { EXPECT_STREQ("HANDSHAKE_OK", CryptoUtils::HandshakeFailureReasonToString(HANDSHAKE_OK)); EXPECT_STREQ("CLIENT_NONCE_UNKNOWN_FAILURE", CryptoUtils::HandshakeFailureReasonToString( CLIENT_NONCE_UNKNOWN_FAILURE)); EXPECT_STREQ("CLIENT_NONCE_INVALID_FAILURE", CryptoUtils::HandshakeFailureReasonToString( CLIENT_NONCE_INVALID_FAILURE)); EXPECT_STREQ("CLIENT_NONCE_NOT_UNIQUE_FAILURE", CryptoUtils::HandshakeFailureReasonToString( CLIENT_NONCE_NOT_UNIQUE_FAILURE)); EXPECT_STREQ("CLIENT_NONCE_INVALID_ORBIT_FAILURE", CryptoUtils::HandshakeFailureReasonToString( CLIENT_NONCE_INVALID_ORBIT_FAILURE)); EXPECT_STREQ("CLIENT_NONCE_INVALID_TIME_FAILURE", CryptoUtils::HandshakeFailureReasonToString( CLIENT_NONCE_INVALID_TIME_FAILURE)); EXPECT_STREQ("CLIENT_NONCE_STRIKE_REGISTER_TIMEOUT", CryptoUtils::HandshakeFailureReasonToString( CLIENT_NONCE_STRIKE_REGISTER_TIMEOUT)); EXPECT_STREQ("CLIENT_NONCE_STRIKE_REGISTER_FAILURE", CryptoUtils::HandshakeFailureReasonToString( CLIENT_NONCE_STRIKE_REGISTER_FAILURE)); EXPECT_STREQ("SERVER_NONCE_DECRYPTION_FAILURE", CryptoUtils::HandshakeFailureReasonToString( SERVER_NONCE_DECRYPTION_FAILURE)); EXPECT_STREQ("SERVER_NONCE_INVALID_FAILURE", CryptoUtils::HandshakeFailureReasonToString( SERVER_NONCE_INVALID_FAILURE)); EXPECT_STREQ("SERVER_NONCE_NOT_UNIQUE_FAILURE", CryptoUtils::HandshakeFailureReasonToString( SERVER_NONCE_NOT_UNIQUE_FAILURE)); EXPECT_STREQ("SERVER_NONCE_INVALID_TIME_FAILURE", CryptoUtils::HandshakeFailureReasonToString( SERVER_NONCE_INVALID_TIME_FAILURE)); EXPECT_STREQ("SERVER_NONCE_REQUIRED_FAILURE", CryptoUtils::HandshakeFailureReasonToString( SERVER_NONCE_REQUIRED_FAILURE)); EXPECT_STREQ("SERVER_CONFIG_INCHOATE_HELLO_FAILURE", CryptoUtils::HandshakeFailureReasonToString( SERVER_CONFIG_INCHOATE_HELLO_FAILURE)); EXPECT_STREQ("SERVER_CONFIG_UNKNOWN_CONFIG_FAILURE", CryptoUtils::HandshakeFailureReasonToString( SERVER_CONFIG_UNKNOWN_CONFIG_FAILURE)); EXPECT_STREQ("SOURCE_ADDRESS_TOKEN_INVALID_FAILURE", CryptoUtils::HandshakeFailureReasonToString( SOURCE_ADDRESS_TOKEN_INVALID_FAILURE)); EXPECT_STREQ("SOURCE_ADDRESS_TOKEN_DECRYPTION_FAILURE", CryptoUtils::HandshakeFailureReasonToString( SOURCE_ADDRESS_TOKEN_DECRYPTION_FAILURE)); EXPECT_STREQ("SOURCE_ADDRESS_TOKEN_PARSE_FAILURE", CryptoUtils::HandshakeFailureReasonToString( SOURCE_ADDRESS_TOKEN_PARSE_FAILURE)); EXPECT_STREQ("SOURCE_ADDRESS_TOKEN_DIFFERENT_IP_ADDRESS_FAILURE", CryptoUtils::HandshakeFailureReasonToString( SOURCE_ADDRESS_TOKEN_DIFFERENT_IP_ADDRESS_FAILURE)); EXPECT_STREQ("SOURCE_ADDRESS_TOKEN_CLOCK_SKEW_FAILURE", CryptoUtils::HandshakeFailureReasonToString( SOURCE_ADDRESS_TOKEN_CLOCK_SKEW_FAILURE)); EXPECT_STREQ("SOURCE_ADDRESS_TOKEN_EXPIRED_FAILURE", CryptoUtils::HandshakeFailureReasonToString( SOURCE_ADDRESS_TOKEN_EXPIRED_FAILURE)); EXPECT_STREQ("INVALID_EXPECTED_LEAF_CERTIFICATE", CryptoUtils::HandshakeFailureReasonToString( INVALID_EXPECTED_LEAF_CERTIFICATE)); EXPECT_STREQ("MAX_FAILURE_REASON", CryptoUtils::HandshakeFailureReasonToString(MAX_FAILURE_REASON)); EXPECT_STREQ( "INVALID_HANDSHAKE_FAILURE_REASON", CryptoUtils::HandshakeFailureReasonToString( static_cast<HandshakeFailureReason>(MAX_FAILURE_REASON + 1))); } TEST_F(CryptoUtilsTest, AuthTagLengths) { for (const auto& version : AllSupportedVersions()) { for (QuicTag algo : {kAESG, kCC20}) { SCOPED_TRACE(version); std::unique_ptr<QuicEncrypter> encrypter( QuicEncrypter::Create(version, algo)); size_t auth_tag_size = 12; if (version.UsesInitialObfuscators()) { auth_tag_size = 16; } EXPECT_EQ(encrypter->GetCiphertextSize(0), auth_tag_size); } } } TEST_F(CryptoUtilsTest, ValidateChosenVersion) { for (const ParsedQuicVersion& v1 : AllSupportedVersions()) { for (const ParsedQuicVersion& v2 : AllSupportedVersions()) { std::string error_details; bool success = CryptoUtils::ValidateChosenVersion( CreateQuicVersionLabel(v1), v2, &error_details); EXPECT_EQ(success, v1 == v2); EXPECT_EQ(success, error_details.empty()); } } } TEST_F(CryptoUtilsTest, ValidateServerVersionsNoVersionNegotiation) { QuicVersionLabelVector version_information_other_versions; ParsedQuicVersionVector client_original_supported_versions; for (const ParsedQuicVersion& version : AllSupportedVersions()) { std::string error_details; EXPECT_TRUE(CryptoUtils::ValidateServerVersions( version_information_other_versions, version, client_original_supported_versions, &error_details)); EXPECT_TRUE(error_details.empty()); } } TEST_F(CryptoUtilsTest, ValidateServerVersionsWithVersionNegotiation) { for (const ParsedQuicVersion& version : AllSupportedVersions()) { QuicVersionLabelVector version_information_other_versions{ CreateQuicVersionLabel(version)}; ParsedQuicVersionVector client_original_supported_versions{ ParsedQuicVersion::ReservedForNegotiation(), version}; std::string error_details; EXPECT_TRUE(CryptoUtils::ValidateServerVersions( version_information_other_versions, version, client_original_supported_versions, &error_details)); EXPECT_TRUE(error_details.empty()); } } TEST_F(CryptoUtilsTest, ValidateServerVersionsWithDowngrade) { if (AllSupportedVersions().size() <= 1) { return; } ParsedQuicVersion client_version = AllSupportedVersions().front(); ParsedQuicVersion server_version = AllSupportedVersions().back(); ASSERT_NE(client_version, server_version); QuicVersionLabelVector version_information_other_versions{ CreateQuicVersionLabel(client_version)}; ParsedQuicVersionVector client_original_supported_versions{ ParsedQuicVersion::ReservedForNegotiation(), server_version}; std::string error_details; EXPECT_FALSE(CryptoUtils::ValidateServerVersions( version_information_other_versions, server_version, client_original_supported_versions, &error_details)); EXPECT_FALSE(error_details.empty()); } TEST_F(CryptoUtilsTest, ValidateCryptoLabels) { EXPECT_EQ(AllSupportedVersionsWithTls().size(), 3u); const char draft_29_key[] = { 0x14, static_cast<char>(0x9d), 0x0b, 0x16, 0x62, static_cast<char>(0xab), static_cast<char>(0x87), 0x1f, static_cast<char>(0xbe), 0x63, static_cast<char>(0xc4), static_cast<char>(0x9b), 0x5e, 0x65, 0x5a, 0x5d}; const char v1_key[] = { static_cast<char>(0xcf), 0x3a, 0x53, 0x31, 0x65, 0x3c, 0x36, 0x4c, static_cast<char>(0x88), static_cast<char>(0xf0), static_cast<char>(0xf3), 0x79, static_cast<char>(0xb6), 0x06, 0x7e, 0x37}; const char v2_08_key[] = { static_cast<char>(0x82), static_cast<char>(0xdb), static_cast<char>(0x63), static_cast<char>(0x78), static_cast<char>(0x61), static_cast<char>(0xd5), static_cast<char>(0x5e), 0x1d, static_cast<char>(0x01), static_cast<char>(0x1f), 0x19, static_cast<char>(0xea), 0x71, static_cast<char>(0xd5), static_cast<char>(0xd2), static_cast<char>(0xa7)}; const char connection_id[] = {static_cast<char>(0x83), static_cast<char>(0x94), static_cast<char>(0xc8), static_cast<char>(0xf0), 0x3e, 0x51, 0x57, 0x08}; const QuicConnectionId cid(connection_id, sizeof(connection_id)); const char* key_str; size_t key_size; for (const ParsedQuicVersion& version : AllSupportedVersionsWithTls()) { if (version == ParsedQuicVersion::Draft29()) { key_str = draft_29_key; key_size = sizeof(draft_29_key); } else if (version == ParsedQuicVersion::RFCv1()) { key_str = v1_key; key_size = sizeof(v1_key); } else { key_str = v2_08_key; key_size = sizeof(v2_08_key); } const absl::string_view expected_key{key_str, key_size}; CrypterPair crypters; CryptoUtils::CreateInitialObfuscators(Perspective::IS_SERVER, version, cid, &crypters); EXPECT_EQ(crypters.encrypter->GetKey(), expected_key); } } } } }
362
cpp
google/quiche
quic_gso_batch_writer
quiche/quic/core/batch_writer/quic_gso_batch_writer.cc
quiche/quic/core/batch_writer/quic_gso_batch_writer_test.cc
#ifndef QUICHE_QUIC_CORE_BATCH_WRITER_QUIC_GSO_BATCH_WRITER_H_ #define QUICHE_QUIC_CORE_BATCH_WRITER_QUIC_GSO_BATCH_WRITER_H_ #include <cstddef> #include "quiche/quic/core/batch_writer/quic_batch_writer_base.h" #include "quiche/quic/core/quic_linux_socket_utils.h" namespace quic { class QUICHE_EXPORT QuicGsoBatchWriter : public QuicUdpBatchWriter { public: explicit QuicGsoBatchWriter(int fd); QuicGsoBatchWriter(int fd, clockid_t clockid_for_release_time); bool SupportsReleaseTime() const final { return supports_release_time_; } bool SupportsEcn() const override { return GetQuicRestartFlag(quic_support_ect1); } CanBatchResult CanBatch(const char* buffer, size_t buf_len, const QuicIpAddress& self_address, const QuicSocketAddress& peer_address, const PerPacketOptions* options, const QuicPacketWriterParams& params, uint64_t release_time) const override; FlushImplResult FlushImpl() override; protected: struct QUICHE_EXPORT ReleaseTimeForceEnabler {}; QuicGsoBatchWriter(std::unique_ptr<QuicBatchWriterBuffer> batch_buffer, int fd, clockid_t clockid_for_release_time, ReleaseTimeForceEnabler enabler); ReleaseTime GetReleaseTime( const QuicPacketWriterParams& params) const override; virtual uint64_t NowInNanosForReleaseTime() const; static size_t MaxSegments(size_t gso_size) { return gso_size <= 2 ? 16 : 45; } static const int kCmsgSpace = kCmsgSpaceForIp + kCmsgSpaceForSegmentSize + kCmsgSpaceForTxTime + kCmsgSpaceForTOS; static void BuildCmsg(QuicMsgHdr* hdr, const QuicIpAddress& self_address, uint16_t gso_size, uint64_t release_time, QuicEcnCodepoint ecn_codepoint); template <size_t CmsgSpace, typename CmsgBuilderT> FlushImplResult InternalFlushImpl(CmsgBuilderT cmsg_builder) { QUICHE_DCHECK(!IsWriteBlocked()); QUICHE_DCHECK(!buffered_writes().empty()); FlushImplResult result = {WriteResult(WRITE_STATUS_OK, 0), 0, 0}; WriteResult& write_result = result.write_result; size_t total_bytes = batch_buffer().SizeInUse(); const BufferedWrite& first = buffered_writes().front(); char cbuf[CmsgSpace]; iovec iov{const_cast<char*>(first.buffer), total_bytes}; QuicMsgHdr hdr(&iov, 1, cbuf, sizeof(cbuf)); hdr.SetPeerAddress(first.peer_address); uint16_t gso_size = buffered_writes().size() > 1 ? first.buf_len : 0; cmsg_builder(&hdr, first.self_address, gso_size, first.release_time, first.params.ecn_codepoint); write_result = QuicLinuxSocketUtils::WritePacket(fd(), hdr); QUIC_DVLOG(1) << "Write GSO packet result: " << write_result << ", fd: " << fd() << ", self_address: " << first.self_address.ToString() << ", peer_address: " << first.peer_address.ToString() << ", num_segments: " << buffered_writes().size() << ", total_bytes: " << total_bytes << ", gso_size: " << gso_size << ", release_time: " << first.release_time; if (write_result.status != WRITE_STATUS_OK) { return result; } result.num_packets_sent = buffered_writes().size(); write_result.bytes_written = total_bytes; result.bytes_written = total_bytes; batch_buffer().PopBufferedWrite(buffered_writes().size()); QUIC_BUG_IF(quic_bug_12544_1, !buffered_writes().empty()) << "All packets should have been written on a successful return"; return result; } private: static std::unique_ptr<QuicBatchWriterBuffer> CreateBatchWriterBuffer(); const clockid_t clockid_for_release_time_; const bool supports_release_time_; }; } #endif #include "quiche/quic/core/batch_writer/quic_gso_batch_writer.h" #include <time.h> #include <ctime> #include <memory> #include <utility> #include "quiche/quic/core/quic_linux_socket_utils.h" #include "quiche/quic/platform/api/quic_server_stats.h" namespace quic { std::unique_ptr<QuicBatchWriterBuffer> QuicGsoBatchWriter::CreateBatchWriterBuffer() { return std::make_unique<QuicBatchWriterBuffer>(); } QuicGsoBatchWriter::QuicGsoBatchWriter(int fd) : QuicGsoBatchWriter(fd, CLOCK_MONOTONIC) {} QuicGsoBatchWriter::QuicGsoBatchWriter(int fd, clockid_t clockid_for_release_time) : QuicUdpBatchWriter(CreateBatchWriterBuffer(), fd), clockid_for_release_time_(clockid_for_release_time), supports_release_time_( GetQuicRestartFlag(quic_support_release_time_for_gso) && QuicLinuxSocketUtils::EnableReleaseTime(fd, clockid_for_release_time)) { if (supports_release_time_) { QUIC_RESTART_FLAG_COUNT(quic_support_release_time_for_gso); } } QuicGsoBatchWriter::QuicGsoBatchWriter( std::unique_ptr<QuicBatchWriterBuffer> batch_buffer, int fd, clockid_t clockid_for_release_time, ReleaseTimeForceEnabler ) : QuicUdpBatchWriter(std::move(batch_buffer), fd), clockid_for_release_time_(clockid_for_release_time), supports_release_time_(true) { QUIC_DLOG(INFO) << "Release time forcefully enabled."; } QuicGsoBatchWriter::CanBatchResult QuicGsoBatchWriter::CanBatch( const char* , size_t buf_len, const QuicIpAddress& self_address, const QuicSocketAddress& peer_address, const PerPacketOptions* , const QuicPacketWriterParams& params, uint64_t release_time) const { if (buffered_writes().empty()) { return CanBatchResult(true, false); } const BufferedWrite& first = buffered_writes().front(); const BufferedWrite& last = buffered_writes().back(); const bool can_burst = !SupportsReleaseTime() || params.release_time_delay.IsZero() || params.allow_burst; size_t max_segments = MaxSegments(first.buf_len); bool can_batch = buffered_writes().size() < max_segments && last.self_address == self_address && last.peer_address == peer_address && batch_buffer().SizeInUse() + buf_len <= kMaxGsoPacketSize && first.buf_len == last.buf_len && first.buf_len >= buf_len && first.params.ecn_codepoint == params.ecn_codepoint && (can_burst || first.release_time == release_time); bool must_flush = (!can_batch) || (last.buf_len != buf_len) || (buffered_writes().size() + 1 == max_segments); return CanBatchResult(can_batch, must_flush); } QuicGsoBatchWriter::ReleaseTime QuicGsoBatchWriter::GetReleaseTime( const QuicPacketWriterParams& params) const { QUICHE_DCHECK(SupportsReleaseTime()); const uint64_t now = NowInNanosForReleaseTime(); const uint64_t ideal_release_time = now + params.release_time_delay.ToMicroseconds() * 1000; if ((params.release_time_delay.IsZero() || params.allow_burst) && !buffered_writes().empty() && (buffered_writes().back().release_time >= now)) { const uint64_t actual_release_time = buffered_writes().back().release_time; const int64_t offset_ns = actual_release_time - ideal_release_time; ReleaseTime result{actual_release_time, QuicTime::Delta::FromMicroseconds(offset_ns / 1000)}; QUIC_DVLOG(1) << "ideal_release_time:" << ideal_release_time << ", actual_release_time:" << actual_release_time << ", offset:" << result.release_time_offset; return result; } return {ideal_release_time, QuicTime::Delta::Zero()}; } uint64_t QuicGsoBatchWriter::NowInNanosForReleaseTime() const { struct timespec ts; if (clock_gettime(clockid_for_release_time_, &ts) != 0) { return 0; } return ts.tv_sec * (1000ULL * 1000 * 1000) + ts.tv_nsec; } void QuicGsoBatchWriter::BuildCmsg(QuicMsgHdr* hdr, const QuicIpAddress& self_address, uint16_t gso_size, uint64_t release_time, QuicEcnCodepoint ecn_codepoint) { hdr->SetIpInNextCmsg(self_address); if (gso_size > 0) { *hdr->GetNextCmsgData<uint16_t>(SOL_UDP, UDP_SEGMENT) = gso_size; } if (release_time != 0) { *hdr->GetNextCmsgData<uint64_t>(SOL_SOCKET, SO_TXTIME) = release_time; } if (ecn_codepoint != ECN_NOT_ECT && GetQuicRestartFlag(quic_support_ect1)) { QUIC_RESTART_FLAG_COUNT_N(quic_support_ect1, 8, 9); if (self_address.IsIPv4()) { *hdr->GetNextCmsgData<int>(IPPROTO_IP, IP_TOS) = static_cast<int>(ecn_codepoint); } else { *hdr->GetNextCmsgData<int>(IPPROTO_IPV6, IPV6_TCLASS) = static_cast<int>(ecn_codepoint); } } } QuicGsoBatchWriter::FlushImplResult QuicGsoBatchWriter::FlushImpl() { return InternalFlushImpl<kCmsgSpace>(BuildCmsg); } }
#include "quiche/quic/core/batch_writer/quic_gso_batch_writer.h" #include <sys/socket.h> #include <cstdint> #include <limits> #include <memory> #include <utility> #include <vector> #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_mock_syscall_wrapper.h" using testing::_; using testing::Invoke; using testing::StrictMock; namespace quic { namespace test { namespace { size_t PacketLength(const msghdr* msg) { size_t length = 0; for (size_t i = 0; i < msg->msg_iovlen; ++i) { length += msg->msg_iov[i].iov_len; } return length; } uint64_t MillisToNanos(uint64_t milliseconds) { return milliseconds * 1000000; } class QUICHE_EXPORT TestQuicGsoBatchWriter : public QuicGsoBatchWriter { public: using QuicGsoBatchWriter::batch_buffer; using QuicGsoBatchWriter::buffered_writes; using QuicGsoBatchWriter::CanBatch; using QuicGsoBatchWriter::CanBatchResult; using QuicGsoBatchWriter::GetReleaseTime; using QuicGsoBatchWriter::MaxSegments; using QuicGsoBatchWriter::QuicGsoBatchWriter; using QuicGsoBatchWriter::ReleaseTime; static std::unique_ptr<TestQuicGsoBatchWriter> NewInstanceWithReleaseTimeSupport() { return std::unique_ptr<TestQuicGsoBatchWriter>(new TestQuicGsoBatchWriter( std::make_unique<QuicBatchWriterBuffer>(), -1, CLOCK_MONOTONIC, ReleaseTimeForceEnabler())); } uint64_t NowInNanosForReleaseTime() const override { return MillisToNanos(forced_release_time_ms_); } void ForceReleaseTimeMs(uint64_t forced_release_time_ms) { forced_release_time_ms_ = forced_release_time_ms; } private: uint64_t forced_release_time_ms_ = 1; }; struct QUICHE_EXPORT TestBufferedWrite : public BufferedWrite { using BufferedWrite::BufferedWrite; TestBufferedWrite(const TestBufferedWrite& other) : BufferedWrite(other.buffer, other.buf_len, other.self_address, other.peer_address, other.options ? other.options->Clone() : std::unique_ptr<PerPacketOptions>(), QuicPacketWriterParams(), other.release_time) {} }; static char unused_packet_buffer[kMaxOutgoingPacketSize]; struct QUICHE_EXPORT BatchCriteriaTestData { BatchCriteriaTestData(size_t buf_len, const QuicIpAddress& self_address, const QuicSocketAddress& peer_address, uint64_t release_time, bool can_batch, bool must_flush) : buffered_write(unused_packet_buffer, buf_len, self_address, peer_address, std::unique_ptr<PerPacketOptions>(), QuicPacketWriterParams(), release_time), can_batch(can_batch), must_flush(must_flush) {} TestBufferedWrite buffered_write; bool can_batch; bool must_flush; }; std::vector<BatchCriteriaTestData> BatchCriteriaTestData_SizeDecrease() { const QuicIpAddress self_addr; const QuicSocketAddress peer_addr; std::vector<BatchCriteriaTestData> test_data_table = { {1350, self_addr, peer_addr, 0, true, false}, {1350, self_addr, peer_addr, 0, true, false}, {1350, self_addr, peer_addr, 0, true, false}, {39, self_addr, peer_addr, 0, true, true}, {39, self_addr, peer_addr, 0, false, true}, {1350, self_addr, peer_addr, 0, false, true}, }; return test_data_table; } std::vector<BatchCriteriaTestData> BatchCriteriaTestData_SizeIncrease() { const QuicIpAddress self_addr; const QuicSocketAddress peer_addr; std::vector<BatchCriteriaTestData> test_data_table = { {1350, self_addr, peer_addr, 0, true, false}, {1350, self_addr, peer_addr, 0, true, false}, {1350, self_addr, peer_addr, 0, true, false}, {1351, self_addr, peer_addr, 0, false, true}, }; return test_data_table; } std::vector<BatchCriteriaTestData> BatchCriteriaTestData_AddressChange() { const QuicIpAddress self_addr1 = QuicIpAddress::Loopback4(); const QuicIpAddress self_addr2 = QuicIpAddress::Loopback6(); const QuicSocketAddress peer_addr1(self_addr1, 666); const QuicSocketAddress peer_addr2(self_addr1, 777); const QuicSocketAddress peer_addr3(self_addr2, 666); const QuicSocketAddress peer_addr4(self_addr2, 777); std::vector<BatchCriteriaTestData> test_data_table = { {1350, self_addr1, peer_addr1, 0, true, false}, {1350, self_addr1, peer_addr1, 0, true, false}, {1350, self_addr1, peer_addr1, 0, true, false}, {1350, self_addr2, peer_addr1, 0, false, true}, {1350, self_addr1, peer_addr2, 0, false, true}, {1350, self_addr1, peer_addr3, 0, false, true}, {1350, self_addr1, peer_addr4, 0, false, true}, {1350, self_addr1, peer_addr4, 0, false, true}, }; return test_data_table; } std::vector<BatchCriteriaTestData> BatchCriteriaTestData_ReleaseTime1() { const QuicIpAddress self_addr; const QuicSocketAddress peer_addr; std::vector<BatchCriteriaTestData> test_data_table = { {1350, self_addr, peer_addr, 5, true, false}, {1350, self_addr, peer_addr, 5, true, false}, {1350, self_addr, peer_addr, 5, true, false}, {1350, self_addr, peer_addr, 9, false, true}, }; return test_data_table; } std::vector<BatchCriteriaTestData> BatchCriteriaTestData_ReleaseTime2() { const QuicIpAddress self_addr; const QuicSocketAddress peer_addr; std::vector<BatchCriteriaTestData> test_data_table = { {1350, self_addr, peer_addr, 0, true, false}, {1350, self_addr, peer_addr, 0, true, false}, {1350, self_addr, peer_addr, 0, true, false}, {1350, self_addr, peer_addr, 9, false, true}, }; return test_data_table; } std::vector<BatchCriteriaTestData> BatchCriteriaTestData_MaxSegments( size_t gso_size) { const QuicIpAddress self_addr; const QuicSocketAddress peer_addr; std::vector<BatchCriteriaTestData> test_data_table; size_t max_segments = TestQuicGsoBatchWriter::MaxSegments(gso_size); for (size_t i = 0; i < max_segments; ++i) { bool is_last_in_batch = (i + 1 == max_segments); test_data_table.push_back({gso_size, self_addr, peer_addr, 0, true, is_last_in_batch}); } test_data_table.push_back( {gso_size, self_addr, peer_addr, 0, false, true}); return test_data_table; } class QuicGsoBatchWriterTest : public QuicTest { protected: WriteResult WritePacket(QuicGsoBatchWriter* writer, size_t packet_size) { return writer->WritePacket(&packet_buffer_[0], packet_size, self_address_, peer_address_, nullptr, QuicPacketWriterParams()); } WriteResult WritePacketWithParams(QuicGsoBatchWriter* writer, QuicPacketWriterParams& params) { return writer->WritePacket(&packet_buffer_[0], 1350, self_address_, peer_address_, nullptr, params); } QuicIpAddress self_address_ = QuicIpAddress::Any4(); QuicSocketAddress peer_address_{QuicIpAddress::Any4(), 443}; char packet_buffer_[1500]; StrictMock<MockQuicSyscallWrapper> mock_syscalls_; ScopedGlobalSyscallWrapperOverride syscall_override_{&mock_syscalls_}; }; TEST_F(QuicGsoBatchWriterTest, BatchCriteria) { std::unique_ptr<TestQuicGsoBatchWriter> writer; std::vector<std::vector<BatchCriteriaTestData>> test_data_tables; test_data_tables.emplace_back(BatchCriteriaTestData_SizeDecrease()); test_data_tables.emplace_back(BatchCriteriaTestData_SizeIncrease()); test_data_tables.emplace_back(BatchCriteriaTestData_AddressChange()); test_data_tables.emplace_back(BatchCriteriaTestData_ReleaseTime1()); test_data_tables.emplace_back(BatchCriteriaTestData_ReleaseTime2()); test_data_tables.emplace_back(BatchCriteriaTestData_MaxSegments(1)); test_data_tables.emplace_back(BatchCriteriaTestData_MaxSegments(2)); test_data_tables.emplace_back(BatchCriteriaTestData_MaxSegments(1350)); for (size_t i = 0; i < test_data_tables.size(); ++i) { writer = TestQuicGsoBatchWriter::NewInstanceWithReleaseTimeSupport(); const auto& test_data_table = test_data_tables[i]; for (size_t j = 0; j < test_data_table.size(); ++j) { const BatchCriteriaTestData& test_data = test_data_table[j]; SCOPED_TRACE(testing::Message() << "i=" << i << ", j=" << j); QuicPacketWriterParams params; params.release_time_delay = QuicTime::Delta::FromMicroseconds( test_data.buffered_write.release_time); TestQuicGsoBatchWriter::CanBatchResult result = writer->CanBatch( test_data.buffered_write.buffer, test_data.buffered_write.buf_len, test_data.buffered_write.self_address, test_data.buffered_write.peer_address, nullptr, params, test_data.buffered_write.release_time); ASSERT_EQ(test_data.can_batch, result.can_batch); ASSERT_EQ(test_data.must_flush, result.must_flush); if (result.can_batch) { ASSERT_TRUE(writer->batch_buffer() .PushBufferedWrite( test_data.buffered_write.buffer, test_data.buffered_write.buf_len, test_data.buffered_write.self_address, test_data.buffered_write.peer_address, nullptr, params, test_data.buffered_write.release_time) .succeeded); } } } } TEST_F(QuicGsoBatchWriterTest, WriteSuccess) { TestQuicGsoBatchWriter writer(-1); ASSERT_EQ(WriteResult(WRITE_STATUS_OK, 0), WritePacket(&writer, 1000)); EXPECT_CALL(mock_syscalls_, Sendmsg(_, _, _)) .WillOnce(Invoke([](int , const msghdr* msg, int ) { EXPECT_EQ(1100u, PacketLength(msg)); return 1100; })); ASSERT_EQ(WriteResult(WRITE_STATUS_OK, 1100), WritePacket(&writer, 100)); ASSERT_EQ(0u, writer.batch_buffer().SizeInUse()); ASSERT_EQ(0u, writer.buffered_writes().size()); } TEST_F(QuicGsoBatchWriterTest, WriteBlockDataNotBuffered) { TestQuicGsoBatchWriter writer(-1); ASSERT_EQ(WriteResult(WRITE_STATUS_OK, 0), WritePacket(&writer, 100)); ASSERT_EQ(WriteResult(WRITE_STATUS_OK, 0), WritePacket(&writer, 100)); EXPECT_CALL(mock_syscalls_, Sendmsg(_, _, _)) .WillOnce(Invoke([](int , const msghdr* msg, int ) { EXPECT_EQ(200u, PacketLength(msg)); errno = EWOULDBLOCK; return -1; })); ASSERT_EQ(WriteResult(WRITE_STATUS_BLOCKED, EWOULDBLOCK), WritePacket(&writer, 150)); ASSERT_EQ(200u, writer.batch_buffer().SizeInUse()); ASSERT_EQ(2u, writer.buffered_writes().size()); } TEST_F(QuicGsoBatchWriterTest, WriteBlockDataBuffered) { TestQuicGsoBatchWriter writer(-1); ASSERT_EQ(WriteResult(WRITE_STATUS_OK, 0), WritePacket(&writer, 100)); ASSERT_EQ(WriteResult(WRITE_STATUS_OK, 0), WritePacket(&writer, 100)); EXPECT_CALL(mock_syscalls_, Sendmsg(_, _, _)) .WillOnce(Invoke([](int , const msghdr* msg, int ) { EXPECT_EQ(250u, PacketLength(msg)); errno = EWOULDBLOCK; return -1; })); ASSERT_EQ(WriteResult(WRITE_STATUS_BLOCKED_DATA_BUFFERED, EWOULDBLOCK), WritePacket(&writer, 50)); EXPECT_TRUE(writer.IsWriteBlocked()); ASSERT_EQ(250u, writer.batch_buffer().SizeInUse()); ASSERT_EQ(3u, writer.buffered_writes().size()); } TEST_F(QuicGsoBatchWriterTest, WriteErrorWithoutDataBuffered) { TestQuicGsoBatchWriter writer(-1); ASSERT_EQ(WriteResult(WRITE_STATUS_OK, 0), WritePacket(&writer, 100)); ASSERT_EQ(WriteResult(WRITE_STATUS_OK, 0), WritePacket(&writer, 100)); EXPECT_CALL(mock_syscalls_, Sendmsg(_, _, _)) .WillOnce(Invoke([](int , const msghdr* msg, int ) { EXPECT_EQ(200u, PacketLength(msg)); errno = EPERM; return -1; })); WriteResult error_result = WritePacket(&writer, 150); ASSERT_EQ(WriteResult(WRITE_STATUS_ERROR, EPERM), error_result); ASSERT_EQ(3u, error_result.dropped_packets); ASSERT_EQ(0u, writer.batch_buffer().SizeInUse()); ASSERT_EQ(0u, writer.buffered_writes().size()); } TEST_F(QuicGsoBatchWriterTest, WriteErrorAfterDataBuffered) { TestQuicGsoBatchWriter writer(-1); ASSERT_EQ(WriteResult(WRITE_STATUS_OK, 0), WritePacket(&writer, 100)); ASSERT_EQ(WriteResult(WRITE_STATUS_OK, 0), WritePacket(&writer, 100)); EXPECT_CALL(mock_syscalls_, Sendmsg(_, _, _)) .WillOnce(Invoke([](int , const msghdr* msg, int ) { EXPECT_EQ(250u, PacketLength(msg)); errno = EPERM; return -1; })); WriteResult error_result = WritePacket(&writer, 50); ASSERT_EQ(WriteResult(WRITE_STATUS_ERROR, EPERM), error_result); ASSERT_EQ(3u, error_result.dropped_packets); ASSERT_EQ(0u, writer.batch_buffer().SizeInUse()); ASSERT_EQ(0u, writer.buffered_writes().size()); } TEST_F(QuicGsoBatchWriterTest, FlushError) { TestQuicGsoBatchWriter writer(-1); ASSERT_EQ(WriteResult(WRITE_STATUS_OK, 0), WritePacket(&writer, 100)); ASSERT_EQ(WriteResult(WRITE_STATUS_OK, 0), WritePacket(&writer, 100)); EXPECT_CALL(mock_syscalls_, Sendmsg(_, _, _)) .WillOnce(Invoke([](int , const msghdr* msg, int ) { EXPECT_EQ(200u, PacketLength(msg)); errno = EINVAL; return -1; })); WriteResult error_result = writer.Flush(); ASSERT_EQ(WriteResult(WRITE_STATUS_ERROR, EINVAL), error_result); ASSERT_EQ(2u, error_result.dropped_packets); ASSERT_EQ(0u, writer.batch_buffer().SizeInUse()); ASSERT_EQ(0u, writer.buffered_writes().size()); } TEST_F(QuicGsoBatchWriterTest, ReleaseTime) { const WriteResult write_buffered(WRITE_STATUS_OK, 0); auto writer = TestQuicGsoBatchWriter::NewInstanceWithReleaseTimeSupport(); QuicPacketWriterParams params; EXPECT_TRUE(params.release_time_delay.IsZero()); EXPECT_FALSE(params.allow_burst); EXPECT_EQ(MillisToNanos(1), writer->GetReleaseTime(params).actual_release_time); WriteResult result = WritePacketWithParams(writer.get(), params); ASSERT_EQ(write_buffered, result); EXPECT_EQ(MillisToNanos(1), writer->buffered_writes().back().release_time); EXPECT_EQ(result.send_time_offset, QuicTime::Delta::Zero()); params.release_time_delay = QuicTime::Delta::FromMilliseconds(3); params.allow_burst = true; result = WritePacketWithParams(writer.get(), params); ASSERT_EQ(write_buffered, result); EXPECT_EQ(MillisToNanos(1), writer->buffered_writes().back().release_time); EXPECT_EQ(result.send_time_offset, QuicTime::Delta::FromMilliseconds(-3)); EXPECT_CALL(mock_syscalls_, Sendmsg(_, _, _)) .WillOnce(Invoke([](int , const msghdr* msg, int ) { EXPECT_EQ(2700u, PacketLength(msg)); errno = 0; return 0; })); params.release_time_delay = QuicTime::Delta::FromMilliseconds(5); params.allow_burst = false; result = WritePacketWithParams(writer.get(), params); ASSERT_EQ(WriteResult(WRITE_STATUS_OK, 2700), result); EXPECT_EQ(MillisToNanos(6), writer->buffered_writes().back().release_time); EXPECT_EQ(result.send_time_offset, QuicTime::Delta::Zero()); params.allow_burst = true; result = WritePacketWithParams(writer.get(), params); ASSERT_EQ(write_buffered, result); EXPECT_EQ(MillisToNanos(6), writer->buffered_writes().back().release_time); EXPECT_EQ(result.send_time_offset, QuicTime::Delta::Zero()); EXPECT_CALL(mock_syscalls_, Sendmsg(_, _, _)) .WillOnce(Invoke([](int , const msghdr* msg, int ) { EXPECT_EQ(3000u, PacketLength(msg)); errno = 0; return 0; })); params.allow_burst = true; EXPECT_EQ(MillisToNanos(6), writer->GetReleaseTime(params).actual_release_time); ASSERT_EQ(WriteResult(WRITE_STATUS_OK, 3000), writer->WritePacket(&packet_buffer_[0], 300, self_address_, peer_address_, nullptr, params)); EXPECT_TRUE(writer->buffered_writes().empty()); writer->ForceReleaseTimeMs(2); params.release_time_delay = QuicTime::Delta::FromMilliseconds(4); result = WritePacketWithParams(writer.get(), params); ASSERT_EQ(write_buffered, result); EXPECT_EQ(MillisToNanos(6), writer->buffered_writes().back().release_time); EXPECT_EQ(result.send_time_offset, QuicTime::Delta::Zero()); } TEST_F(QuicGsoBatchWriterTest, EcnCodepoint) { const WriteResult write_buffered(WRITE_STATUS_OK, 0); auto writer = TestQuicGsoBatchWriter::NewInstanceWithReleaseTimeSupport(); QuicPacketWriterParams params; EXPECT_TRUE(params.release_time_delay.IsZero()); EXPECT_FALSE(params.allow_burst); params.ecn_codepoint = ECN_ECT0; WriteResult result = WritePacketWithParams(writer.get(), params); ASSERT_EQ(write_buffered, result); EXPECT_EQ(MillisToNanos(1), writer->buffered_writes().back().release_time); EXPECT_EQ(result.send_time_offset, QuicTime::Delta::Zero()); params.allow_burst = true; result = WritePacketWithParams(writer.get(), params); ASSERT_EQ(write_buffered, result); params.ecn_codepoint = ECN_ECT1; EXPECT_CALL(mock_syscalls_, Sendmsg(_, _, _)) .WillOnce(Invoke([](int , const msghdr* msg, int ) { const int kEct0 = 0x02; EXPECT_EQ(2700u, PacketLength(msg)); msghdr mutable_msg; memcpy(&mutable_msg, msg, sizeof(*msg)); for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&mutable_msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&mutable_msg, cmsg)) { if (cmsg->cmsg_level == IPPROTO_IP && cmsg->cmsg_type == IP_TOS) { EXPECT_EQ(*reinterpret_cast<int*> CMSG_DATA(cmsg), kEct0); break; } } errno = 0; return 0; })); result = WritePacketWithParams(writer.get(), params); ASSERT_EQ(WriteResult(WRITE_STATUS_OK, 2700), result); } TEST_F(QuicGsoBatchWriterTest, EcnCodepointIPv6) { const WriteResult write_buffered(WRITE_STATUS_OK, 0); self_address_ = QuicIpAddress::Any6(); peer_address_ = QuicSocketAddress(QuicIpAddress::Any6(), 443); auto writer = TestQuicGsoBatchWriter::NewInstanceWithReleaseTimeSupport(); QuicPacketWriterParams params; EXPECT_TRUE(params.release_time_delay.IsZero()); EXPECT_FALSE(params.allow_burst); params.ecn_codepoint = ECN_ECT0; WriteResult result = WritePacketWithParams(writer.get(), params); ASSERT_EQ(write_buffered, result); EXPECT_EQ(MillisToNanos(1), writer->buffered_writes().back().release_time); EXPECT_EQ(result.send_time_offset, QuicTime::Delta::Zero()); params.allow_burst = true; result = WritePacketWithParams(writer.get(), params); ASSERT_EQ(write_buffered, result); params.ecn_codepoint = ECN_ECT1; EXPECT_CALL(mock_syscalls_, Sendmsg(_, _, _)) .WillOnce(Invoke([](int , const msghdr* msg, int ) { const int kEct0 = 0x02; EXPECT_EQ(2700u, PacketLength(msg)); msghdr mutable_msg; memcpy(&mutable_msg, msg, sizeof(*msg)); for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&mutable_msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&mutable_msg, cmsg)) { if (cmsg->cmsg_level == IPPROTO_IPV6 && cmsg->cmsg_type == IPV6_TCLASS) { EXPECT_EQ(*reinterpret_cast<int*> CMSG_DATA(cmsg), kEct0); break; } } errno = 0; return 0; })); result = WritePacketWithParams(writer.get(), params); ASSERT_EQ(WriteResult(WRITE_STATUS_OK, 2700), result); } } } }
363
cpp
google/quiche
quic_batch_writer_buffer
quiche/quic/core/batch_writer/quic_batch_writer_buffer.cc
quiche/quic/core/batch_writer/quic_batch_writer_buffer_test.cc
#ifndef QUICHE_QUIC_CORE_BATCH_WRITER_QUIC_BATCH_WRITER_BUFFER_H_ #define QUICHE_QUIC_CORE_BATCH_WRITER_QUIC_BATCH_WRITER_BUFFER_H_ #include "absl/base/optimization.h" #include "quiche/quic/core/quic_linux_socket_utils.h" #include "quiche/quic/core/quic_packet_writer.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/common/quiche_circular_deque.h" namespace quic { class QUICHE_EXPORT QuicBatchWriterBuffer { public: QuicBatchWriterBuffer(); void Clear(); char* GetNextWriteLocation() const; struct QUICHE_EXPORT PushResult { bool succeeded; bool buffer_copied; uint32_t batch_id = 0; }; PushResult PushBufferedWrite(const char* buffer, size_t buf_len, const QuicIpAddress& self_address, const QuicSocketAddress& peer_address, const PerPacketOptions* options, const QuicPacketWriterParams& params, uint64_t release_time); void UndoLastPush(); struct QUICHE_EXPORT PopResult { int32_t num_buffers_popped; bool moved_remaining_buffers; }; PopResult PopBufferedWrite(int32_t num_buffered_writes); const quiche::QuicheCircularDeque<BufferedWrite>& buffered_writes() const { return buffered_writes_; } bool IsExternalBuffer(const char* buffer, size_t buf_len) const { return (buffer + buf_len) <= buffer_ || buffer >= buffer_end(); } bool IsInternalBuffer(const char* buffer, size_t buf_len) const { return buffer >= buffer_ && (buffer + buf_len) <= buffer_end(); } size_t SizeInUse() const; static const size_t kBufferSize = 64 * 1024; std::string DebugString() const; protected: bool Invariants() const; const char* buffer_end() const { return buffer_ + sizeof(buffer_); } ABSL_CACHELINE_ALIGNED char buffer_[kBufferSize]; quiche::QuicheCircularDeque<BufferedWrite> buffered_writes_; uint32_t batch_id_ = 0; }; } #endif #include "quiche/quic/core/batch_writer/quic_batch_writer_buffer.h" #include <algorithm> #include <sstream> #include <string> namespace quic { QuicBatchWriterBuffer::QuicBatchWriterBuffer() { memset(buffer_, 0, sizeof(buffer_)); } void QuicBatchWriterBuffer::Clear() { buffered_writes_.clear(); } std::string QuicBatchWriterBuffer::DebugString() const { std::ostringstream os; os << "{ buffer: " << static_cast<const void*>(buffer_) << " buffer_end: " << static_cast<const void*>(buffer_end()) << " buffered_writes_.size(): " << buffered_writes_.size() << " next_write_loc: " << static_cast<const void*>(GetNextWriteLocation()) << " SizeInUse: " << SizeInUse() << " }"; return os.str(); } bool QuicBatchWriterBuffer::Invariants() const { const char* next_buffer = buffer_; for (auto iter = buffered_writes_.begin(); iter != buffered_writes_.end(); ++iter) { if ((iter->buffer != next_buffer) || (iter->buffer + iter->buf_len > buffer_end())) { return false; } next_buffer += iter->buf_len; } return static_cast<size_t>(next_buffer - buffer_) == SizeInUse(); } char* QuicBatchWriterBuffer::GetNextWriteLocation() const { const char* next_loc = buffered_writes_.empty() ? buffer_ : buffered_writes_.back().buffer + buffered_writes_.back().buf_len; if (static_cast<size_t>(buffer_end() - next_loc) < kMaxOutgoingPacketSize) { return nullptr; } return const_cast<char*>(next_loc); } QuicBatchWriterBuffer::PushResult QuicBatchWriterBuffer::PushBufferedWrite( const char* buffer, size_t buf_len, const QuicIpAddress& self_address, const QuicSocketAddress& peer_address, const PerPacketOptions* options, const QuicPacketWriterParams& params, uint64_t release_time) { QUICHE_DCHECK(Invariants()); QUICHE_DCHECK_LE(buf_len, kMaxOutgoingPacketSize); PushResult result = {false, false}; char* next_write_location = GetNextWriteLocation(); if (next_write_location == nullptr) { return result; } if (buffer != next_write_location) { if (IsExternalBuffer(buffer, buf_len)) { memcpy(next_write_location, buffer, buf_len); } else if (IsInternalBuffer(buffer, buf_len)) { memmove(next_write_location, buffer, buf_len); } else { QUIC_BUG(quic_bug_10831_1) << "Buffer[" << static_cast<const void*>(buffer) << ", " << static_cast<const void*>(buffer + buf_len) << ") overlaps with internal buffer[" << static_cast<const void*>(buffer_) << ", " << static_cast<const void*>(buffer_end()) << ")"; return result; } result.buffer_copied = true; } else { } if (buffered_writes_.empty()) { ++batch_id_; if (batch_id_ == 0) { ++batch_id_; } } buffered_writes_.emplace_back( next_write_location, buf_len, self_address, peer_address, options ? options->Clone() : std::unique_ptr<PerPacketOptions>(), params, release_time); QUICHE_DCHECK(Invariants()); result.succeeded = true; result.batch_id = batch_id_; return result; } void QuicBatchWriterBuffer::UndoLastPush() { if (!buffered_writes_.empty()) { buffered_writes_.pop_back(); } } QuicBatchWriterBuffer::PopResult QuicBatchWriterBuffer::PopBufferedWrite( int32_t num_buffered_writes) { QUICHE_DCHECK(Invariants()); QUICHE_DCHECK_GE(num_buffered_writes, 0); QUICHE_DCHECK_LE(static_cast<size_t>(num_buffered_writes), buffered_writes_.size()); PopResult result = {0, false}; result.num_buffers_popped = std::max<int32_t>(num_buffered_writes, 0); result.num_buffers_popped = std::min<int32_t>(result.num_buffers_popped, buffered_writes_.size()); buffered_writes_.pop_front_n(result.num_buffers_popped); if (!buffered_writes_.empty()) { result.moved_remaining_buffers = true; const char* buffer_before_move = buffered_writes_.front().buffer; size_t buffer_len_to_move = buffered_writes_.back().buffer + buffered_writes_.back().buf_len - buffer_before_move; memmove(buffer_, buffer_before_move, buffer_len_to_move); size_t distance_to_move = buffer_before_move - buffer_; for (BufferedWrite& buffered_write : buffered_writes_) { buffered_write.buffer -= distance_to_move; } QUICHE_DCHECK_EQ(buffer_, buffered_writes_.front().buffer); } QUICHE_DCHECK(Invariants()); return result; } size_t QuicBatchWriterBuffer::SizeInUse() const { if (buffered_writes_.empty()) { return 0; } return buffered_writes_.back().buffer + buffered_writes_.back().buf_len - buffer_; } }
#include "quiche/quic/core/batch_writer/quic_batch_writer_buffer.h" #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { namespace { class QUICHE_EXPORT TestQuicBatchWriterBuffer : public QuicBatchWriterBuffer { public: using QuicBatchWriterBuffer::buffer_; using QuicBatchWriterBuffer::buffered_writes_; }; static const size_t kBatchBufferSize = QuicBatchWriterBuffer::kBufferSize; class QuicBatchWriterBufferTest : public QuicTest { public: QuicBatchWriterBufferTest() { SwitchToNewBuffer(); } void SwitchToNewBuffer() { batch_buffer_ = std::make_unique<TestQuicBatchWriterBuffer>(); } char* FillPacketBuffer(char c) { return FillPacketBuffer(c, packet_buffer_, kMaxOutgoingPacketSize); } char* FillPacketBuffer(char c, char* packet_buffer) { return FillPacketBuffer(c, packet_buffer, kMaxOutgoingPacketSize); } char* FillPacketBuffer(char c, char* packet_buffer, size_t buf_len) { memset(packet_buffer, c, buf_len); return packet_buffer; } void CheckBufferedWriteContent(int buffered_write_index, char buffer_content, size_t buf_len, const QuicIpAddress& self_addr, const QuicSocketAddress& peer_addr, const PerPacketOptions* , const QuicPacketWriterParams& params) { const BufferedWrite& buffered_write = batch_buffer_->buffered_writes()[buffered_write_index]; EXPECT_EQ(buf_len, buffered_write.buf_len); for (size_t i = 0; i < buf_len; ++i) { EXPECT_EQ(buffer_content, buffered_write.buffer[i]); if (buffer_content != buffered_write.buffer[i]) { break; } } EXPECT_EQ(self_addr, buffered_write.self_address); EXPECT_EQ(peer_addr, buffered_write.peer_address); EXPECT_EQ(params.release_time_delay, buffered_write.params.release_time_delay); } protected: std::unique_ptr<TestQuicBatchWriterBuffer> batch_buffer_; QuicIpAddress self_addr_; QuicSocketAddress peer_addr_; uint64_t release_time_ = 0; char packet_buffer_[kMaxOutgoingPacketSize]; }; class BufferSizeSequence { public: explicit BufferSizeSequence( std::vector<std::pair<std::vector<size_t>, size_t>> stages) : stages_(std::move(stages)), total_buf_len_(0), stage_index_(0), sequence_index_(0) {} size_t Next() { const std::vector<size_t>& seq = stages_[stage_index_].first; size_t buf_len = seq[sequence_index_++ % seq.size()]; total_buf_len_ += buf_len; if (stages_[stage_index_].second <= total_buf_len_) { stage_index_ = std::min(stage_index_ + 1, stages_.size() - 1); } return buf_len; } private: const std::vector<std::pair<std::vector<size_t>, size_t>> stages_; size_t total_buf_len_; size_t stage_index_; size_t sequence_index_; }; TEST_F(QuicBatchWriterBufferTest, InPlacePushes) { std::vector<BufferSizeSequence> buffer_size_sequences = { BufferSizeSequence({{{1350}, kBatchBufferSize - 3000}, {{1}, 1000000}}), BufferSizeSequence({{{1, 39, 97, 150, 1350, 1350, 1350, 1350}, 1000000}}), }; for (auto& buffer_size_sequence : buffer_size_sequences) { SwitchToNewBuffer(); int64_t num_push_failures = 0; while (batch_buffer_->SizeInUse() < kBatchBufferSize) { size_t buf_len = buffer_size_sequence.Next(); const bool has_enough_space = (kBatchBufferSize - batch_buffer_->SizeInUse() >= kMaxOutgoingPacketSize); char* buffer = batch_buffer_->GetNextWriteLocation(); if (has_enough_space) { EXPECT_EQ(batch_buffer_->buffer_ + batch_buffer_->SizeInUse(), buffer); } else { EXPECT_EQ(nullptr, buffer); } SCOPED_TRACE(testing::Message() << "Before Push: buf_len=" << buf_len << ", has_enough_space=" << has_enough_space << ", batch_buffer=" << batch_buffer_->DebugString()); auto push_result = batch_buffer_->PushBufferedWrite( buffer, buf_len, self_addr_, peer_addr_, nullptr, QuicPacketWriterParams(), release_time_); if (!push_result.succeeded) { ++num_push_failures; } EXPECT_EQ(has_enough_space, push_result.succeeded); EXPECT_FALSE(push_result.buffer_copied); if (!has_enough_space) { break; } } EXPECT_EQ(1, num_push_failures); } } TEST_F(QuicBatchWriterBufferTest, MixedPushes) { char* buffer = batch_buffer_->GetNextWriteLocation(); QuicPacketWriterParams params; auto push_result = batch_buffer_->PushBufferedWrite( FillPacketBuffer('A', buffer), kDefaultMaxPacketSize, self_addr_, peer_addr_, nullptr, params, release_time_); EXPECT_TRUE(push_result.succeeded); EXPECT_FALSE(push_result.buffer_copied); CheckBufferedWriteContent(0, 'A', kDefaultMaxPacketSize, self_addr_, peer_addr_, nullptr, params); push_result = batch_buffer_->PushBufferedWrite( FillPacketBuffer('B'), kDefaultMaxPacketSize, self_addr_, peer_addr_, nullptr, params, release_time_); EXPECT_TRUE(push_result.succeeded); EXPECT_TRUE(push_result.buffer_copied); CheckBufferedWriteContent(1, 'B', kDefaultMaxPacketSize, self_addr_, peer_addr_, nullptr, params); buffer = batch_buffer_->GetNextWriteLocation(); push_result = batch_buffer_->PushBufferedWrite( FillPacketBuffer('C', buffer), kDefaultMaxPacketSize, self_addr_, peer_addr_, nullptr, params, release_time_); EXPECT_TRUE(push_result.succeeded); EXPECT_FALSE(push_result.buffer_copied); CheckBufferedWriteContent(2, 'C', kDefaultMaxPacketSize, self_addr_, peer_addr_, nullptr, params); push_result = batch_buffer_->PushBufferedWrite( FillPacketBuffer('D'), kDefaultMaxPacketSize, self_addr_, peer_addr_, nullptr, params, release_time_); EXPECT_TRUE(push_result.succeeded); EXPECT_TRUE(push_result.buffer_copied); CheckBufferedWriteContent(3, 'D', kDefaultMaxPacketSize, self_addr_, peer_addr_, nullptr, params); } TEST_F(QuicBatchWriterBufferTest, PopAll) { const int kNumBufferedWrites = 10; QuicPacketWriterParams params; for (int i = 0; i < kNumBufferedWrites; ++i) { EXPECT_TRUE(batch_buffer_ ->PushBufferedWrite(packet_buffer_, kDefaultMaxPacketSize, self_addr_, peer_addr_, nullptr, params, release_time_) .succeeded); } EXPECT_EQ(kNumBufferedWrites, static_cast<int>(batch_buffer_->buffered_writes().size())); auto pop_result = batch_buffer_->PopBufferedWrite(kNumBufferedWrites); EXPECT_EQ(0u, batch_buffer_->buffered_writes().size()); EXPECT_EQ(kNumBufferedWrites, pop_result.num_buffers_popped); EXPECT_FALSE(pop_result.moved_remaining_buffers); } TEST_F(QuicBatchWriterBufferTest, PopPartial) { const int kNumBufferedWrites = 10; QuicPacketWriterParams params; for (int i = 0; i < kNumBufferedWrites; ++i) { EXPECT_TRUE(batch_buffer_ ->PushBufferedWrite( FillPacketBuffer('A' + i), kDefaultMaxPacketSize - i, self_addr_, peer_addr_, nullptr, params, release_time_) .succeeded); } for (size_t i = 0; i < kNumBufferedWrites && !batch_buffer_->buffered_writes().empty(); ++i) { const size_t size_before_pop = batch_buffer_->buffered_writes().size(); const size_t expect_size_after_pop = size_before_pop < i ? 0 : size_before_pop - i; batch_buffer_->PopBufferedWrite(i); ASSERT_EQ(expect_size_after_pop, batch_buffer_->buffered_writes().size()); const char first_write_content = 'A' + kNumBufferedWrites - expect_size_after_pop; const size_t first_write_len = kDefaultMaxPacketSize - kNumBufferedWrites + expect_size_after_pop; for (size_t j = 0; j < expect_size_after_pop; ++j) { CheckBufferedWriteContent(j, first_write_content + j, first_write_len - j, self_addr_, peer_addr_, nullptr, params); } } } TEST_F(QuicBatchWriterBufferTest, InPlacePushWithPops) { char* buffer = batch_buffer_->GetNextWriteLocation(); const size_t first_packet_len = 2; QuicPacketWriterParams params; auto push_result = batch_buffer_->PushBufferedWrite( FillPacketBuffer('A', buffer, first_packet_len), first_packet_len, self_addr_, peer_addr_, nullptr, params, release_time_); EXPECT_TRUE(push_result.succeeded); EXPECT_FALSE(push_result.buffer_copied); CheckBufferedWriteContent(0, 'A', first_packet_len, self_addr_, peer_addr_, nullptr, params); buffer = batch_buffer_->GetNextWriteLocation(); const size_t second_packet_len = 1350; auto pop_result = batch_buffer_->PopBufferedWrite(1); EXPECT_EQ(1, pop_result.num_buffers_popped); EXPECT_FALSE(pop_result.moved_remaining_buffers); push_result = batch_buffer_->PushBufferedWrite( FillPacketBuffer('B', buffer, second_packet_len), second_packet_len, self_addr_, peer_addr_, nullptr, params, release_time_); EXPECT_TRUE(push_result.succeeded); EXPECT_TRUE(push_result.buffer_copied); CheckBufferedWriteContent(0, 'B', second_packet_len, self_addr_, peer_addr_, nullptr, params); } TEST_F(QuicBatchWriterBufferTest, BatchID) { const int kNumBufferedWrites = 10; QuicPacketWriterParams params; auto first_push_result = batch_buffer_->PushBufferedWrite( packet_buffer_, kDefaultMaxPacketSize, self_addr_, peer_addr_, nullptr, params, release_time_); ASSERT_TRUE(first_push_result.succeeded); ASSERT_NE(first_push_result.batch_id, 0); for (int i = 1; i < kNumBufferedWrites; ++i) { EXPECT_EQ(batch_buffer_ ->PushBufferedWrite(packet_buffer_, kDefaultMaxPacketSize, self_addr_, peer_addr_, nullptr, params, release_time_) .batch_id, first_push_result.batch_id); } batch_buffer_->PopBufferedWrite(kNumBufferedWrites); EXPECT_TRUE(batch_buffer_->buffered_writes().empty()); EXPECT_NE( batch_buffer_ ->PushBufferedWrite(packet_buffer_, kDefaultMaxPacketSize, self_addr_, peer_addr_, nullptr, params, release_time_) .batch_id, first_push_result.batch_id); } } } }
364
cpp
google/quiche
quic_sendmmsg_batch_writer
quiche/quic/core/batch_writer/quic_sendmmsg_batch_writer.cc
quiche/quic/core/batch_writer/quic_sendmmsg_batch_writer_test.cc
#ifndef QUICHE_QUIC_CORE_BATCH_WRITER_QUIC_SENDMMSG_BATCH_WRITER_H_ #define QUICHE_QUIC_CORE_BATCH_WRITER_QUIC_SENDMMSG_BATCH_WRITER_H_ #include "quiche/quic/core/batch_writer/quic_batch_writer_base.h" #include "quiche/quic/core/quic_linux_socket_utils.h" namespace quic { class QUICHE_EXPORT QuicSendmmsgBatchWriter : public QuicUdpBatchWriter { public: QuicSendmmsgBatchWriter(std::unique_ptr<QuicBatchWriterBuffer> batch_buffer, int fd); CanBatchResult CanBatch(const char* buffer, size_t buf_len, const QuicIpAddress& self_address, const QuicSocketAddress& peer_address, const PerPacketOptions* options, const QuicPacketWriterParams& params, uint64_t release_time) const override; FlushImplResult FlushImpl() override; protected: using CmsgBuilder = QuicMMsgHdr::ControlBufferInitializer; FlushImplResult InternalFlushImpl(size_t cmsg_space, const CmsgBuilder& cmsg_builder); }; } #endif #include "quiche/quic/core/batch_writer/quic_sendmmsg_batch_writer.h" #include <memory> #include <utility> namespace quic { QuicSendmmsgBatchWriter::QuicSendmmsgBatchWriter( std::unique_ptr<QuicBatchWriterBuffer> batch_buffer, int fd) : QuicUdpBatchWriter(std::move(batch_buffer), fd) {} QuicSendmmsgBatchWriter::CanBatchResult QuicSendmmsgBatchWriter::CanBatch( const char* , size_t , const QuicIpAddress& , const QuicSocketAddress& , const PerPacketOptions* , const QuicPacketWriterParams& , uint64_t ) const { return CanBatchResult(true, false); } QuicSendmmsgBatchWriter::FlushImplResult QuicSendmmsgBatchWriter::FlushImpl() { return InternalFlushImpl( kCmsgSpaceForIp, [](QuicMMsgHdr* mhdr, int i, const BufferedWrite& buffered_write) { mhdr->SetIpInNextCmsg(i, buffered_write.self_address); }); } QuicSendmmsgBatchWriter::FlushImplResult QuicSendmmsgBatchWriter::InternalFlushImpl(size_t cmsg_space, const CmsgBuilder& cmsg_builder) { QUICHE_DCHECK(!IsWriteBlocked()); QUICHE_DCHECK(!buffered_writes().empty()); FlushImplResult result = {WriteResult(WRITE_STATUS_OK, 0), 0, 0}; WriteResult& write_result = result.write_result; auto first = buffered_writes().cbegin(); const auto last = buffered_writes().cend(); while (first != last) { QuicMMsgHdr mhdr(first, last, cmsg_space, cmsg_builder); int num_packets_sent; write_result = QuicLinuxSocketUtils::WriteMultiplePackets( fd(), &mhdr, &num_packets_sent); QUIC_DVLOG(1) << "WriteMultiplePackets sent " << num_packets_sent << " out of " << mhdr.num_msgs() << " packets. WriteResult=" << write_result; if (write_result.status != WRITE_STATUS_OK) { QUICHE_DCHECK_EQ(0, num_packets_sent); break; } else if (num_packets_sent == 0) { QUIC_BUG(quic_bug_10825_1) << "WriteMultiplePackets returned OK, but no packets were sent."; write_result = WriteResult(WRITE_STATUS_ERROR, EIO); break; } first += num_packets_sent; result.num_packets_sent += num_packets_sent; result.bytes_written += write_result.bytes_written; } batch_buffer().PopBufferedWrite(result.num_packets_sent); if (write_result.status != WRITE_STATUS_OK) { return result; } QUIC_BUG_IF(quic_bug_12537_1, !buffered_writes().empty()) << "All packets should have been written on a successful return"; write_result.bytes_written = result.bytes_written; return result; } }
#include "quiche/quic/core/batch_writer/quic_sendmmsg_batch_writer.h" namespace quic { namespace test { namespace { } } }
365
cpp
google/quiche
event_loop_connecting_client_socket
quiche/quic/core/io/event_loop_connecting_client_socket.cc
quiche/quic/core/io/event_loop_connecting_client_socket_test.cc
#ifndef QUICHE_QUIC_CORE_IO_EVENT_LOOP_CONNECTING_CLIENT_SOCKET_H_ #define QUICHE_QUIC_CORE_IO_EVENT_LOOP_CONNECTING_CLIENT_SOCKET_H_ #include <optional> #include <string> #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "absl/types/variant.h" #include "quiche/quic/core/connecting_client_socket.h" #include "quiche/quic/core/io/quic_event_loop.h" #include "quiche/quic/core/io/socket.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/quiche_buffer_allocator.h" namespace quic { class EventLoopConnectingClientSocket : public ConnectingClientSocket, public QuicSocketEventListener { public: EventLoopConnectingClientSocket( socket_api::SocketProtocol protocol, const quic::QuicSocketAddress& peer_address, QuicByteCount receive_buffer_size, QuicByteCount send_buffer_size, QuicEventLoop* event_loop, quiche::QuicheBufferAllocator* buffer_allocator, AsyncVisitor* async_visitor); ~EventLoopConnectingClientSocket() override; absl::Status ConnectBlocking() override; void ConnectAsync() override; void Disconnect() override; absl::StatusOr<QuicSocketAddress> GetLocalAddress() override; absl::StatusOr<quiche::QuicheMemSlice> ReceiveBlocking( QuicByteCount max_size) override; void ReceiveAsync(QuicByteCount max_size) override; absl::Status SendBlocking(std::string data) override; absl::Status SendBlocking(quiche::QuicheMemSlice data) override; void SendAsync(std::string data) override; void SendAsync(quiche::QuicheMemSlice data) override; void OnSocketEvent(QuicEventLoop* event_loop, SocketFd fd, QuicSocketEventMask events) override; private: enum class ConnectStatus { kNotConnected, kConnecting, kConnected, }; absl::Status Open(); void Close(); absl::Status DoInitialConnect(); absl::Status GetConnectResult(); void FinishOrRearmAsyncConnect(absl::Status status); absl::StatusOr<quiche::QuicheMemSlice> ReceiveInternal(); void FinishOrRearmAsyncReceive(absl::StatusOr<quiche::QuicheMemSlice> buffer); absl::StatusOr<bool> OneBytePeek(); absl::Status SendBlockingInternal(); absl::Status SendInternal(); void FinishOrRearmAsyncSend(absl::Status status); const socket_api::SocketProtocol protocol_; const QuicSocketAddress peer_address_; const QuicByteCount receive_buffer_size_; const QuicByteCount send_buffer_size_; QuicEventLoop* const event_loop_; quiche::QuicheBufferAllocator* buffer_allocator_; AsyncVisitor* const async_visitor_; SocketFd descriptor_ = kInvalidSocketFd; ConnectStatus connect_status_ = ConnectStatus::kNotConnected; std::optional<QuicByteCount> receive_max_size_; absl::variant<absl::monostate, std::string, quiche::QuicheMemSlice> send_data_; absl::string_view send_remaining_; }; } #endif #include "quiche/quic/core/io/event_loop_connecting_client_socket.h" #include <limits> #include <string> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "absl/types/variant.h" #include "quiche/quic/core/io/quic_event_loop.h" #include "quiche/quic/core/io/socket.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_mem_slice.h" namespace quic { EventLoopConnectingClientSocket::EventLoopConnectingClientSocket( socket_api::SocketProtocol protocol, const quic::QuicSocketAddress& peer_address, QuicByteCount receive_buffer_size, QuicByteCount send_buffer_size, QuicEventLoop* event_loop, quiche::QuicheBufferAllocator* buffer_allocator, AsyncVisitor* async_visitor) : protocol_(protocol), peer_address_(peer_address), receive_buffer_size_(receive_buffer_size), send_buffer_size_(send_buffer_size), event_loop_(event_loop), buffer_allocator_(buffer_allocator), async_visitor_(async_visitor) { QUICHE_DCHECK(event_loop_); QUICHE_DCHECK(buffer_allocator_); } EventLoopConnectingClientSocket::~EventLoopConnectingClientSocket() { QUICHE_DCHECK(connect_status_ != ConnectStatus::kConnecting); QUICHE_DCHECK(!receive_max_size_.has_value()); QUICHE_DCHECK(absl::holds_alternative<absl::monostate>(send_data_)); if (descriptor_ != kInvalidSocketFd) { QUICHE_BUG(quic_event_loop_connecting_socket_invalid_destruction) << "Must call Disconnect() on connected socket before destruction."; Close(); } QUICHE_DCHECK(connect_status_ == ConnectStatus::kNotConnected); QUICHE_DCHECK(send_remaining_.empty()); } absl::Status EventLoopConnectingClientSocket::ConnectBlocking() { QUICHE_DCHECK_EQ(descriptor_, kInvalidSocketFd); QUICHE_DCHECK(connect_status_ == ConnectStatus::kNotConnected); QUICHE_DCHECK(!receive_max_size_.has_value()); QUICHE_DCHECK(absl::holds_alternative<absl::monostate>(send_data_)); absl::Status status = Open(); if (!status.ok()) { return status; } status = socket_api::SetSocketBlocking(descriptor_, true); if (!status.ok()) { QUICHE_LOG_FIRST_N(WARNING, 100) << "Failed to set socket to address: " << peer_address_.ToString() << " as blocking for connect with error: " << status; Close(); return status; } status = DoInitialConnect(); if (absl::IsUnavailable(status)) { QUICHE_LOG_FIRST_N(ERROR, 100) << "Non-blocking connect to should-be blocking socket to address:" << peer_address_.ToString() << "."; Close(); connect_status_ = ConnectStatus::kNotConnected; return status; } else if (!status.ok()) { QUICHE_DCHECK_EQ(descriptor_, kInvalidSocketFd); QUICHE_DCHECK(connect_status_ == ConnectStatus::kNotConnected); return status; } status = socket_api::SetSocketBlocking(descriptor_, false); if (!status.ok()) { QUICHE_LOG_FIRST_N(WARNING, 100) << "Failed to return socket to address: " << peer_address_.ToString() << " to non-blocking after connect with error: " << status; Close(); connect_status_ = ConnectStatus::kNotConnected; } QUICHE_DCHECK(connect_status_ != ConnectStatus::kConnecting); return status; } void EventLoopConnectingClientSocket::ConnectAsync() { QUICHE_DCHECK(async_visitor_); QUICHE_DCHECK_EQ(descriptor_, kInvalidSocketFd); QUICHE_DCHECK(connect_status_ == ConnectStatus::kNotConnected); QUICHE_DCHECK(!receive_max_size_.has_value()); QUICHE_DCHECK(absl::holds_alternative<absl::monostate>(send_data_)); absl::Status status = Open(); if (!status.ok()) { async_visitor_->ConnectComplete(status); return; } FinishOrRearmAsyncConnect(DoInitialConnect()); } void EventLoopConnectingClientSocket::Disconnect() { QUICHE_DCHECK_NE(descriptor_, kInvalidSocketFd); QUICHE_DCHECK(connect_status_ != ConnectStatus::kNotConnected); Close(); QUICHE_DCHECK_EQ(descriptor_, kInvalidSocketFd); bool require_connect_callback = connect_status_ == ConnectStatus::kConnecting; connect_status_ = ConnectStatus::kNotConnected; bool require_receive_callback = receive_max_size_.has_value(); receive_max_size_.reset(); bool require_send_callback = !absl::holds_alternative<absl::monostate>(send_data_); send_data_ = absl::monostate(); send_remaining_ = ""; if (require_connect_callback) { QUICHE_DCHECK(async_visitor_); async_visitor_->ConnectComplete(absl::CancelledError()); } if (require_receive_callback) { QUICHE_DCHECK(async_visitor_); async_visitor_->ReceiveComplete(absl::CancelledError()); } if (require_send_callback) { QUICHE_DCHECK(async_visitor_); async_visitor_->SendComplete(absl::CancelledError()); } } absl::StatusOr<QuicSocketAddress> EventLoopConnectingClientSocket::GetLocalAddress() { QUICHE_DCHECK_NE(descriptor_, kInvalidSocketFd); QUICHE_DCHECK(connect_status_ == ConnectStatus::kConnected); return socket_api::GetSocketAddress(descriptor_); } absl::StatusOr<quiche::QuicheMemSlice> EventLoopConnectingClientSocket::ReceiveBlocking(QuicByteCount max_size) { QUICHE_DCHECK_GT(max_size, 0u); QUICHE_DCHECK_NE(descriptor_, kInvalidSocketFd); QUICHE_DCHECK(connect_status_ == ConnectStatus::kConnected); QUICHE_DCHECK(!receive_max_size_.has_value()); absl::Status status = socket_api::SetSocketBlocking(descriptor_, true); if (!status.ok()) { QUICHE_LOG_FIRST_N(WARNING, 100) << "Failed to set socket to address: " << peer_address_.ToString() << " as blocking for receive with error: " << status; return status; } receive_max_size_ = max_size; absl::StatusOr<quiche::QuicheMemSlice> buffer = ReceiveInternal(); if (!buffer.ok() && absl::IsUnavailable(buffer.status())) { QUICHE_LOG_FIRST_N(ERROR, 100) << "Non-blocking receive from should-be blocking socket to address:" << peer_address_.ToString() << "."; receive_max_size_.reset(); } else { QUICHE_DCHECK(!receive_max_size_.has_value()); } absl::Status set_non_blocking_status = socket_api::SetSocketBlocking(descriptor_, false); if (!set_non_blocking_status.ok()) { QUICHE_LOG_FIRST_N(WARNING, 100) << "Failed to return socket to address: " << peer_address_.ToString() << " to non-blocking after receive with error: " << set_non_blocking_status; return set_non_blocking_status; } return buffer; } void EventLoopConnectingClientSocket::ReceiveAsync(QuicByteCount max_size) { QUICHE_DCHECK(async_visitor_); QUICHE_DCHECK_GT(max_size, 0u); QUICHE_DCHECK_NE(descriptor_, kInvalidSocketFd); QUICHE_DCHECK(connect_status_ == ConnectStatus::kConnected); QUICHE_DCHECK(!receive_max_size_.has_value()); receive_max_size_ = max_size; FinishOrRearmAsyncReceive(ReceiveInternal()); } absl::Status EventLoopConnectingClientSocket::SendBlocking(std::string data) { QUICHE_DCHECK(!data.empty()); QUICHE_DCHECK(absl::holds_alternative<absl::monostate>(send_data_)); send_data_ = std::move(data); return SendBlockingInternal(); } absl::Status EventLoopConnectingClientSocket::SendBlocking( quiche::QuicheMemSlice data) { QUICHE_DCHECK(!data.empty()); QUICHE_DCHECK(absl::holds_alternative<absl::monostate>(send_data_)); send_data_ = std::move(data); return SendBlockingInternal(); } void EventLoopConnectingClientSocket::SendAsync(std::string data) { QUICHE_DCHECK(!data.empty()); QUICHE_DCHECK(absl::holds_alternative<absl::monostate>(send_data_)); send_data_ = std::move(data); send_remaining_ = absl::get<std::string>(send_data_); FinishOrRearmAsyncSend(SendInternal()); } void EventLoopConnectingClientSocket::SendAsync(quiche::QuicheMemSlice data) { QUICHE_DCHECK(!data.empty()); QUICHE_DCHECK(absl::holds_alternative<absl::monostate>(send_data_)); send_data_ = std::move(data); send_remaining_ = absl::get<quiche::QuicheMemSlice>(send_data_).AsStringView(); FinishOrRearmAsyncSend(SendInternal()); } void EventLoopConnectingClientSocket::OnSocketEvent( QuicEventLoop* event_loop, SocketFd fd, QuicSocketEventMask events) { QUICHE_DCHECK_EQ(event_loop, event_loop_); QUICHE_DCHECK_EQ(fd, descriptor_); if (connect_status_ == ConnectStatus::kConnecting && (events & (kSocketEventWritable | kSocketEventError))) { FinishOrRearmAsyncConnect(GetConnectResult()); return; } if (receive_max_size_.has_value() && (events & (kSocketEventReadable | kSocketEventError))) { FinishOrRearmAsyncReceive(ReceiveInternal()); } if (!send_remaining_.empty() && (events & (kSocketEventWritable | kSocketEventError))) { FinishOrRearmAsyncSend(SendInternal()); } } absl::Status EventLoopConnectingClientSocket::Open() { QUICHE_DCHECK_EQ(descriptor_, kInvalidSocketFd); QUICHE_DCHECK(connect_status_ == ConnectStatus::kNotConnected); QUICHE_DCHECK(!receive_max_size_.has_value()); QUICHE_DCHECK(absl::holds_alternative<absl::monostate>(send_data_)); QUICHE_DCHECK(send_remaining_.empty()); absl::StatusOr<SocketFd> descriptor = socket_api::CreateSocket(peer_address_.host().address_family(), protocol_, false); if (!descriptor.ok()) { QUICHE_DVLOG(1) << "Failed to open socket for connection to address: " << peer_address_.ToString() << " with error: " << descriptor.status(); return descriptor.status(); } QUICHE_DCHECK_NE(*descriptor, kInvalidSocketFd); descriptor_ = *descriptor; if (async_visitor_) { bool registered; if (event_loop_->SupportsEdgeTriggered()) { registered = event_loop_->RegisterSocket( descriptor_, kSocketEventReadable | kSocketEventWritable | kSocketEventError, this); } else { registered = event_loop_->RegisterSocket(descriptor_, 0, this); } QUICHE_DCHECK(registered); } if (receive_buffer_size_ != 0) { absl::Status status = socket_api::SetReceiveBufferSize(descriptor_, receive_buffer_size_); if (!status.ok()) { QUICHE_LOG_FIRST_N(WARNING, 100) << "Failed to set receive buffer size to: " << receive_buffer_size_ << " for socket to address: " << peer_address_.ToString() << " with error: " << status; Close(); return status; } } if (send_buffer_size_ != 0) { absl::Status status = socket_api::SetSendBufferSize(descriptor_, send_buffer_size_); if (!status.ok()) { QUICHE_LOG_FIRST_N(WARNING, 100) << "Failed to set send buffer size to: " << send_buffer_size_ << " for socket to address: " << peer_address_.ToString() << " with error: " << status; Close(); return status; } } return absl::OkStatus(); } void EventLoopConnectingClientSocket::Close() { QUICHE_DCHECK_NE(descriptor_, kInvalidSocketFd); bool unregistered = event_loop_->UnregisterSocket(descriptor_); QUICHE_DCHECK_EQ(unregistered, !!async_visitor_); absl::Status status = socket_api::Close(descriptor_); if (!status.ok()) { QUICHE_LOG_FIRST_N(WARNING, 100) << "Could not close socket to address: " << peer_address_.ToString() << " with error: " << status; } descriptor_ = kInvalidSocketFd; } absl::Status EventLoopConnectingClientSocket::DoInitialConnect() { QUICHE_DCHECK_NE(descriptor_, kInvalidSocketFd); QUICHE_DCHECK(connect_status_ == ConnectStatus::kNotConnected); QUICHE_DCHECK(!receive_max_size_.has_value()); QUICHE_DCHECK(absl::holds_alternative<absl::monostate>(send_data_)); absl::Status connect_result = socket_api::Connect(descriptor_, peer_address_); if (connect_result.ok()) { connect_status_ = ConnectStatus::kConnected; } else if (absl::IsUnavailable(connect_result)) { connect_status_ = ConnectStatus::kConnecting; } else { QUICHE_DVLOG(1) << "Synchronously failed to connect socket to address: " << peer_address_.ToString() << " with error: " << connect_result; Close(); connect_status_ = ConnectStatus::kNotConnected; } return connect_result; } absl::Status EventLoopConnectingClientSocket::GetConnectResult() { QUICHE_DCHECK_NE(descriptor_, kInvalidSocketFd); QUICHE_DCHECK(connect_status_ == ConnectStatus::kConnecting); QUICHE_DCHECK(!receive_max_size_.has_value()); QUICHE_DCHECK(absl::holds_alternative<absl::monostate>(send_data_)); absl::Status error = socket_api::GetSocketError(descriptor_); if (!error.ok()) { QUICHE_DVLOG(1) << "Asynchronously failed to connect socket to address: " << peer_address_.ToString() << " with error: " << error; Close(); connect_status_ = ConnectStatus::kNotConnected; return error; } absl::StatusOr<bool> peek_data = OneBytePeek(); if (peek_data.ok() || absl::IsUnavailable(peek_data.status())) { connect_status_ = ConnectStatus::kConnected; } else { error = peek_data.status(); QUICHE_LOG_FIRST_N(WARNING, 100) << "Socket to address: " << peer_address_.ToString() << " signalled writable after connect and no connect error found, " "but socket does not appear connected with error: " << error; Close(); connect_status_ = ConnectStatus::kNotConnected; } return error; } void EventLoopConnectingClientSocket::FinishOrRearmAsyncConnect( absl::Status status) { if (absl::IsUnavailable(status)) { if (!event_loop_->SupportsEdgeTriggered()) { bool result = event_loop_->RearmSocket( descriptor_, kSocketEventWritable | kSocketEventError); QUICHE_DCHECK(result); } QUICHE_DCHECK(connect_status_ == ConnectStatus::kConnecting); } else { QUICHE_DCHECK(connect_status_ != ConnectStatus::kConnecting); async_visitor_->ConnectComplete(status); } } absl::StatusOr<quiche::QuicheMemSlice> EventLoopConnectingClientSocket::ReceiveInternal() { QUICHE_DCHECK_NE(descriptor_, kInvalidSocketFd); QUICHE_DCHECK(connect_status_ == ConnectStatus::kConnected); QUICHE_CHECK(receive_max_size_.has_value()); QUICHE_DCHECK_GE(*receive_max_size_, 1u); QUICHE_DCHECK_LE(*receive_max_size_, std::numeric_limits<size_t>::max()); if (*receive_max_size_ > 1) { absl::StatusOr<bool> peek_data = OneBytePeek(); if (!peek_data.ok()) { if (!absl::IsUnavailable(peek_data.status())) { receive_max_size_.reset(); } return peek_data.status(); } else if (!*peek_data) { receive_max_size_.reset(); return quiche::QuicheMemSlice(); } } quiche::QuicheBuffer buffer(buffer_allocator_, *receive_max_size_); absl::StatusOr<absl::Span<char>> received = socket_api::Receive( descriptor_, absl::MakeSpan(buffer.data(), buffer.size())); if (received.ok()) { QUICHE_DCHECK_LE(received->size(), buffer.size()); QUICHE_DCHECK_EQ(received->data(), buffer.data()); receive_max_size_.reset(); return quiche::QuicheMemSlice( quiche::QuicheBuffer(buffer.Release(), received->size())); } else { if (!absl::IsUnavailable(received.status())) { QUICHE_DVLOG(1) << "Failed to receive from socket to address: " << peer_address_.ToString() << " with error: " << received.status(); receive_max_size_.reset(); } return received.status(); } } void EventLoopConnectingClientSocket::FinishOrRearmAsyncReceive( absl::StatusOr<quiche::QuicheMemSlice> buffer) { QUICHE_DCHECK(async_visitor_); QUICHE_DCHECK(connect_status_ == ConnectStatus::kConnected); if (!buffer.ok() && absl::IsUnavailable(buffer.status())) { if (!event_loop_->SupportsEdgeTriggered()) { bool result = event_loop_->RearmSocket( descriptor_, kSocketEventReadable | kSocketEventError); QUICHE_DCHECK(result); } QUICHE_DCHECK(receive_max_size_.has_value()); } else { QUICHE_DCHECK(!receive_max_size_.has_value()); async_visitor_->ReceiveComplete(std::move(buffer)); } } absl::StatusOr<bool> EventLoopConnectingClientSocket::OneBytePeek() { QUICHE_DCHECK_NE(descriptor_, kInvalidSocketFd); char peek_buffer; absl::StatusOr<absl::Span<char>> peek_received = socket_api::Receive( descriptor_, absl::MakeSpan(&peek_buffer, 1), true); if (!peek_received.ok()) { return peek_received.status(); } else { return !peek_received->empty(); } } absl::Status EventLoopConnectingClientSocket::SendBlockingInternal() { QUICHE_DCHECK_NE(descriptor_, kInvalidSocketFd); QUICHE_DCHECK(connect_status_ == ConnectStatus::kConnected); QUICHE_DCHECK(!absl::holds_alternative<absl::monostate>(send_data_)); QUICHE_DCHECK(send_remaining_.empty()); absl::Status status = socket_api::SetSocketBlocking(descriptor_, true); if (!status.ok()) { QUICHE_LOG_FIRST_N(WARNING, 100) << "Failed to set socket to address: " << peer_address_.ToString() << " as blocking for send with error: " << status; send_data_ = absl::monostate(); return status; } if (absl::holds_alternative<std::string>(send_data_)) { send_remaining_ = absl::get<std::string>(send_data_); } else { send_remaining_ = absl::get<quiche::QuicheMemSlice>(send_data_).AsStringView(); } status = SendInternal(); if (absl::IsUnavailable(status)) { QUICHE_LOG_FIRST_N(ERROR, 100) << "Non-blocking send for should-be blocking socket to address:" << peer_address_.ToString(); send_data_ = absl::monostate(); send_remaining_ = ""; } else { QUICHE_DCHECK(absl::holds_alternative<absl::monostate>(send_data_)); QUICHE_DCHECK(send_remaining_.empty()); } absl::Status set_non_blocking_status = socket_api::SetSocketBlocking(descriptor_, false); if (!set_non_blocking_status.ok()) { QUICHE_LOG_FIRST_N(WARNING, 100) << "Failed to return socket to address: " << peer_address_.ToString() << " to non-blocking after send with error: " << set_non_blocking_status; return set_non_blocking_status; } return status; } absl::Status EventLoopConnectingClientSocket::SendInternal() { QUICHE_DCHECK_NE(descriptor_, kInvalidSocketFd); QUICHE_DCHECK(connect_status_ == ConnectStatus::kConnected); QUICHE_DCHECK(!absl::holds_alternative<absl::monostate>(send_data_)); QUICHE_DCHECK(!send_remaining_.empty()); while (!send_remaining_.empty()) { absl::StatusOr<absl::string_view> remainder = socket_api::Send(descriptor_, send_remaining_); if (remainder.ok()) { QUICHE_DCHECK(remainder->empty() || (remainder->data() >= send_remaining_.data() && remainder->data() < send_remaining_.data() + send_remaining_.size())); QUICHE_DCHECK(remainder->empty() || (remainder->data() + remainder->size() == send_remaining_.data() + send_remaining_.size())); send_remaining_ = *remainder; } else { if (!absl::IsUnavailable(remainder.status())) { QUICHE_DVLOG(1) << "Failed to send to socket to address: " << peer_address_.ToString() << " with error: " << remainder.status(); send_data_ = absl::monostate(); send_remaining_ = ""; } return remainder.status(); } } send_data_ = absl::monostate(); return absl::OkStatus(); } void EventLoopConnectingClientSocket::FinishOrRearmAsyncSend( absl::Status status) { QUICHE_DCHECK(async_visitor_); QUICHE_DCHECK(connect_status_ == ConnectStatus::kConnected); if (absl::IsUnavailable(status)) { if (!event_loop_->SupportsEdgeTriggered()) { bool result = event_loop_->RearmSocket( descriptor_, kSocketEventWritable | kSocketEventError); QUICHE_DCHECK(result); } QUICHE_DCHECK(!absl::holds_alternative<absl::monostate>(send_data_)); QUICHE_DCHECK(!send_remaining_.empty()); } else { QUICHE_DCHECK(absl::holds_alternative<absl::monostate>(send_data_)); QUICHE_DCHECK(send_remaining_.empty()); async_visitor_->SendComplete(status); } } }
#include "quiche/quic/core/io/event_loop_connecting_client_socket.h" #include <memory> #include <optional> #include <string> #include <tuple> #include <utility> #include "absl/functional/bind_front.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/types/span.h" #include "quiche/quic/core/connecting_client_socket.h" #include "quiche/quic/core/io/event_loop_socket_factory.h" #include "quiche/quic/core/io/quic_default_event_loop.h" #include "quiche/quic/core/io/quic_event_loop.h" #include "quiche/quic/core/io/socket.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/test_tools/mock_clock.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_mem_slice.h" #include "quiche/common/platform/api/quiche_mutex.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/platform/api/quiche_test_loopback.h" #include "quiche/common/platform/api/quiche_thread.h" #include "quiche/common/quiche_callbacks.h" #include "quiche/common/simple_buffer_allocator.h" namespace quic::test { namespace { using ::testing::Combine; using ::testing::Values; using ::testing::ValuesIn; class TestServerSocketRunner : public quiche::QuicheThread { public: using SocketBehavior = quiche::MultiUseCallback<void( SocketFd connected_socket, socket_api::SocketProtocol protocol)>; TestServerSocketRunner(SocketFd server_socket_descriptor, SocketBehavior behavior) : QuicheThread("TestServerSocketRunner"), server_socket_descriptor_(server_socket_descriptor), behavior_(std::move(behavior)) {} ~TestServerSocketRunner() override { WaitForCompletion(); } void WaitForCompletion() { completion_notification_.WaitForNotification(); } protected: SocketFd server_socket_descriptor() const { return server_socket_descriptor_; } const SocketBehavior& behavior() const { return behavior_; } quiche::QuicheNotification& completion_notification() { return completion_notification_; } private: const SocketFd server_socket_descriptor_; const SocketBehavior behavior_; quiche::QuicheNotification completion_notification_; }; class TestTcpServerSocketRunner : public TestServerSocketRunner { public: TestTcpServerSocketRunner(SocketFd server_socket_descriptor, SocketBehavior behavior) : TestServerSocketRunner(server_socket_descriptor, std::move(behavior)) { Start(); } ~TestTcpServerSocketRunner() override { Join(); } protected: void Run() override { AcceptSocket(); behavior()(connection_socket_descriptor_, socket_api::SocketProtocol::kTcp); CloseSocket(); completion_notification().Notify(); } private: void AcceptSocket() { absl::StatusOr<socket_api::AcceptResult> connection_socket = socket_api::Accept(server_socket_descriptor(), true); QUICHE_CHECK(connection_socket.ok()); connection_socket_descriptor_ = connection_socket.value().fd; } void CloseSocket() { QUICHE_CHECK(socket_api::Close(connection_socket_descriptor_).ok()); QUICHE_CHECK(socket_api::Close(server_socket_descriptor()).ok()); } SocketFd connection_socket_descriptor_ = kInvalidSocketFd; }; class TestUdpServerSocketRunner : public TestServerSocketRunner { public: TestUdpServerSocketRunner(SocketFd server_socket_descriptor, SocketBehavior behavior, QuicSocketAddress client_socket_address) : TestServerSocketRunner(server_socket_descriptor, std::move(behavior)), client_socket_address_(std::move(client_socket_address)) { Start(); } ~TestUdpServerSocketRunner() override { Join(); } protected: void Run() override { ConnectSocket(); behavior()(server_socket_descriptor(), socket_api::SocketProtocol::kUdp); DisconnectSocket(); completion_notification().Notify(); } private: void ConnectSocket() { QUICHE_CHECK( socket_api::Connect(server_socket_descriptor(), client_socket_address_) .ok()); } void DisconnectSocket() { QUICHE_CHECK(socket_api::Close(server_socket_descriptor()).ok()); } QuicSocketAddress client_socket_address_; }; class EventLoopConnectingClientSocketTest : public quiche::test::QuicheTestWithParam< std::tuple<socket_api::SocketProtocol, QuicEventLoopFactory*>>, public ConnectingClientSocket::AsyncVisitor { public: void SetUp() override { QuicEventLoopFactory* event_loop_factory; std::tie(protocol_, event_loop_factory) = GetParam(); event_loop_ = event_loop_factory->Create(&clock_); socket_factory_ = std::make_unique<EventLoopSocketFactory>( event_loop_.get(), quiche::SimpleBufferAllocator::Get()); QUICHE_CHECK(CreateListeningServerSocket()); } void TearDown() override { if (server_socket_descriptor_ != kInvalidSocketFd) { QUICHE_CHECK(socket_api::Close(server_socket_descriptor_).ok()); } } void ConnectComplete(absl::Status status) override { QUICHE_CHECK(!connect_result_.has_value()); connect_result_ = std::move(status); } void ReceiveComplete(absl::StatusOr<quiche::QuicheMemSlice> data) override { QUICHE_CHECK(!receive_result_.has_value()); receive_result_ = std::move(data); } void SendComplete(absl::Status status) override { QUICHE_CHECK(!send_result_.has_value()); send_result_ = std::move(status); } protected: std::unique_ptr<ConnectingClientSocket> CreateSocket( const quic::QuicSocketAddress& peer_address, ConnectingClientSocket::AsyncVisitor* async_visitor) { switch (protocol_) { case socket_api::SocketProtocol::kUdp: return socket_factory_->CreateConnectingUdpClientSocket( peer_address, 0, 0, async_visitor); case socket_api::SocketProtocol::kTcp: return socket_factory_->CreateTcpClientSocket( peer_address, 0, 0, async_visitor); default: QUICHE_NOTREACHED(); return nullptr; } } std::unique_ptr<ConnectingClientSocket> CreateSocketToEncourageDelayedSend( const quic::QuicSocketAddress& peer_address, ConnectingClientSocket::AsyncVisitor* async_visitor) { switch (protocol_) { case socket_api::SocketProtocol::kUdp: return socket_factory_->CreateConnectingUdpClientSocket( peer_address, 0, 0, async_visitor); case socket_api::SocketProtocol::kTcp: return socket_factory_->CreateTcpClientSocket( peer_address, 0, 4, async_visitor); default: QUICHE_NOTREACHED(); return nullptr; } } bool CreateListeningServerSocket() { absl::StatusOr<SocketFd> socket = socket_api::CreateSocket( quiche::TestLoopback().address_family(), protocol_, true); QUICHE_CHECK(socket.ok()); if (protocol_ == socket_api::SocketProtocol::kTcp) { static const QuicByteCount kReceiveBufferSize = 2; absl::Status result = socket_api::SetReceiveBufferSize(socket.value(), kReceiveBufferSize); QUICHE_CHECK(result.ok()); } QuicSocketAddress bind_address(quiche::TestLoopback(), 0); absl::Status result = socket_api::Bind(socket.value(), bind_address); QUICHE_CHECK(result.ok()); absl::StatusOr<QuicSocketAddress> socket_address = socket_api::GetSocketAddress(socket.value()); QUICHE_CHECK(socket_address.ok()); if (protocol_ == socket_api::SocketProtocol::kTcp) { result = socket_api::Listen(socket.value(), 1); QUICHE_CHECK(result.ok()); } server_socket_descriptor_ = socket.value(); server_socket_address_ = std::move(socket_address).value(); return true; } std::unique_ptr<TestServerSocketRunner> CreateServerSocketRunner( TestServerSocketRunner::SocketBehavior behavior, ConnectingClientSocket* client_socket) { std::unique_ptr<TestServerSocketRunner> runner; switch (protocol_) { case socket_api::SocketProtocol::kUdp: { absl::StatusOr<QuicSocketAddress> client_socket_address = client_socket->GetLocalAddress(); QUICHE_CHECK(client_socket_address.ok()); runner = std::make_unique<TestUdpServerSocketRunner>( server_socket_descriptor_, std::move(behavior), std::move(client_socket_address).value()); break; } case socket_api::SocketProtocol::kTcp: runner = std::make_unique<TestTcpServerSocketRunner>( server_socket_descriptor_, std::move(behavior)); break; default: QUICHE_NOTREACHED(); } server_socket_descriptor_ = kInvalidSocketFd; return runner; } socket_api::SocketProtocol protocol_; SocketFd server_socket_descriptor_ = kInvalidSocketFd; QuicSocketAddress server_socket_address_; MockClock clock_; std::unique_ptr<QuicEventLoop> event_loop_; std::unique_ptr<EventLoopSocketFactory> socket_factory_; std::optional<absl::Status> connect_result_; std::optional<absl::StatusOr<quiche::QuicheMemSlice>> receive_result_; std::optional<absl::Status> send_result_; }; std::string GetTestParamName( ::testing::TestParamInfo< std::tuple<socket_api::SocketProtocol, QuicEventLoopFactory*>> info) { auto [protocol, event_loop_factory] = info.param; return EscapeTestParamName(absl::StrCat(socket_api::GetProtocolName(protocol), "_", event_loop_factory->GetName())); } INSTANTIATE_TEST_SUITE_P(EventLoopConnectingClientSocketTests, EventLoopConnectingClientSocketTest, Combine(Values(socket_api::SocketProtocol::kUdp, socket_api::SocketProtocol::kTcp), ValuesIn(GetAllSupportedEventLoops())), &GetTestParamName); TEST_P(EventLoopConnectingClientSocketTest, ConnectBlocking) { std::unique_ptr<ConnectingClientSocket> socket = CreateSocket(server_socket_address_, nullptr); EXPECT_TRUE(socket->ConnectBlocking().ok()); socket->Disconnect(); } TEST_P(EventLoopConnectingClientSocketTest, ConnectAsync) { std::unique_ptr<ConnectingClientSocket> socket = CreateSocket(server_socket_address_, this); socket->ConnectAsync(); if (!connect_result_.has_value()) { event_loop_->RunEventLoopOnce(QuicTime::Delta::FromSeconds(1)); ASSERT_TRUE(connect_result_.has_value()); } EXPECT_TRUE(connect_result_.value().ok()); connect_result_.reset(); socket->Disconnect(); EXPECT_FALSE(connect_result_.has_value()); } TEST_P(EventLoopConnectingClientSocketTest, ErrorBeforeConnectAsync) { std::unique_ptr<ConnectingClientSocket> socket = CreateSocket(server_socket_address_, this); EXPECT_TRUE(socket_api::Close(server_socket_descriptor_).ok()); server_socket_descriptor_ = kInvalidSocketFd; socket->ConnectAsync(); if (!connect_result_.has_value()) { event_loop_->RunEventLoopOnce(QuicTime::Delta::FromSeconds(1)); ASSERT_TRUE(connect_result_.has_value()); } switch (protocol_) { case socket_api::SocketProtocol::kTcp: EXPECT_FALSE(connect_result_.value().ok()); break; case socket_api::SocketProtocol::kUdp: EXPECT_TRUE(connect_result_.value().ok()); socket->Disconnect(); break; default: FAIL(); } } TEST_P(EventLoopConnectingClientSocketTest, ErrorDuringConnectAsync) { std::unique_ptr<ConnectingClientSocket> socket = CreateSocket(server_socket_address_, this); socket->ConnectAsync(); if (connect_result_.has_value()) { EXPECT_TRUE(connect_result_.value().ok()); socket->Disconnect(); return; } EXPECT_TRUE(socket_api::Close(server_socket_descriptor_).ok()); server_socket_descriptor_ = kInvalidSocketFd; EXPECT_FALSE(connect_result_.has_value()); event_loop_->RunEventLoopOnce(QuicTime::Delta::FromSeconds(1)); ASSERT_TRUE(connect_result_.has_value()); switch (protocol_) { case socket_api::SocketProtocol::kTcp: EXPECT_FALSE(connect_result_.value().ok()); break; case socket_api::SocketProtocol::kUdp: EXPECT_TRUE(connect_result_.value().ok()); break; default: FAIL(); } } TEST_P(EventLoopConnectingClientSocketTest, Disconnect) { std::unique_ptr<ConnectingClientSocket> socket = CreateSocket(server_socket_address_, nullptr); ASSERT_TRUE(socket->ConnectBlocking().ok()); socket->Disconnect(); } TEST_P(EventLoopConnectingClientSocketTest, DisconnectCancelsConnectAsync) { std::unique_ptr<ConnectingClientSocket> socket = CreateSocket(server_socket_address_, this); socket->ConnectAsync(); bool expect_canceled = true; if (connect_result_.has_value()) { EXPECT_TRUE(connect_result_.value().ok()); expect_canceled = false; } socket->Disconnect(); if (expect_canceled) { ASSERT_TRUE(connect_result_.has_value()); EXPECT_TRUE(absl::IsCancelled(connect_result_.value())); } } TEST_P(EventLoopConnectingClientSocketTest, ConnectAndReconnect) { std::unique_ptr<ConnectingClientSocket> socket = CreateSocket(server_socket_address_, nullptr); ASSERT_TRUE(socket->ConnectBlocking().ok()); socket->Disconnect(); EXPECT_TRUE(socket->ConnectBlocking().ok()); socket->Disconnect(); } TEST_P(EventLoopConnectingClientSocketTest, GetLocalAddress) { std::unique_ptr<ConnectingClientSocket> socket = CreateSocket(server_socket_address_, nullptr); ASSERT_TRUE(socket->ConnectBlocking().ok()); absl::StatusOr<QuicSocketAddress> address = socket->GetLocalAddress(); ASSERT_TRUE(address.ok()); EXPECT_TRUE(address.value().IsInitialized()); socket->Disconnect(); } void SendDataOnSocket(absl::string_view data, SocketFd connected_socket, socket_api::SocketProtocol protocol) { QUICHE_CHECK(!data.empty()); do { absl::StatusOr<absl::string_view> remainder = socket_api::Send(connected_socket, data); if (!remainder.ok()) { return; } data = remainder.value(); } while (protocol == socket_api::SocketProtocol::kTcp && !data.empty()); QUICHE_CHECK(data.empty()); } TEST_P(EventLoopConnectingClientSocketTest, ReceiveBlocking) { std::unique_ptr<ConnectingClientSocket> socket = CreateSocket(server_socket_address_, nullptr); ASSERT_TRUE(socket->ConnectBlocking().ok()); std::string expected = {1, 2, 3, 4, 5, 6, 7, 8}; std::unique_ptr<TestServerSocketRunner> runner = CreateServerSocketRunner( absl::bind_front(&SendDataOnSocket, expected), socket.get()); std::string received; absl::StatusOr<quiche::QuicheMemSlice> data; do { data = socket->ReceiveBlocking(100); ASSERT_TRUE(data.ok()); received.append(data.value().data(), data.value().length()); } while (protocol_ == socket_api::SocketProtocol::kTcp && !data.value().empty()); EXPECT_EQ(received, expected); socket->Disconnect(); } TEST_P(EventLoopConnectingClientSocketTest, ReceiveAsync) { std::unique_ptr<ConnectingClientSocket> socket = CreateSocket(server_socket_address_, this); ASSERT_TRUE(socket->ConnectBlocking().ok()); socket->ReceiveAsync(100); EXPECT_FALSE(receive_result_.has_value()); std::string expected = {1, 2, 3, 4, 5, 6, 7, 8}; std::unique_ptr<TestServerSocketRunner> runner = CreateServerSocketRunner( absl::bind_front(&SendDataOnSocket, expected), socket.get()); EXPECT_FALSE(receive_result_.has_value()); for (int i = 0; i < 5 && !receive_result_.has_value(); ++i) { event_loop_->RunEventLoopOnce(QuicTime::Delta::FromSeconds(1)); } ASSERT_TRUE(receive_result_.has_value()); ASSERT_TRUE(receive_result_.value().ok()); EXPECT_FALSE(receive_result_.value().value().empty()); std::string received(receive_result_.value().value().data(), receive_result_.value().value().length()); if (protocol_ == socket_api::SocketProtocol::kTcp) { absl::StatusOr<quiche::QuicheMemSlice> data; do { data = socket->ReceiveBlocking(100); ASSERT_TRUE(data.ok()); received.append(data.value().data(), data.value().length()); } while (!data.value().empty()); } EXPECT_EQ(received, expected); receive_result_.reset(); socket->Disconnect(); EXPECT_FALSE(receive_result_.has_value()); } TEST_P(EventLoopConnectingClientSocketTest, DisconnectCancelsReceiveAsync) { std::unique_ptr<ConnectingClientSocket> socket = CreateSocket(server_socket_address_, this); ASSERT_TRUE(socket->ConnectBlocking().ok()); socket->ReceiveAsync(100); EXPECT_FALSE(receive_result_.has_value()); socket->Disconnect(); ASSERT_TRUE(receive_result_.has_value()); ASSERT_FALSE(receive_result_.value().ok()); EXPECT_TRUE(absl::IsCancelled(receive_result_.value().status())); } void ReceiveDataFromSocket(std::string* out_received, SocketFd connected_socket, socket_api::SocketProtocol protocol) { out_received->clear(); std::string buffer(100, 0); absl::StatusOr<absl::Span<char>> received; do { received = socket_api::Receive(connected_socket, absl::MakeSpan(buffer)); QUICHE_CHECK(received.ok()); out_received->insert(out_received->end(), received.value().begin(), received.value().end()); } while (protocol == socket_api::SocketProtocol::kTcp && !received.value().empty()); QUICHE_CHECK(!out_received->empty()); } TEST_P(EventLoopConnectingClientSocketTest, SendBlocking) { std::unique_ptr<ConnectingClientSocket> socket = CreateSocket(server_socket_address_, nullptr); ASSERT_TRUE(socket->ConnectBlocking().ok()); std::string sent; std::unique_ptr<TestServerSocketRunner> runner = CreateServerSocketRunner( absl::bind_front(&ReceiveDataFromSocket, &sent), socket.get()); std::string expected = {1, 2, 3, 4, 5, 6, 7, 8}; EXPECT_TRUE(socket->SendBlocking(expected).ok()); socket->Disconnect(); runner->WaitForCompletion(); EXPECT_EQ(sent, expected); } TEST_P(EventLoopConnectingClientSocketTest, SendAsync) { std::unique_ptr<ConnectingClientSocket> socket = CreateSocketToEncourageDelayedSend(server_socket_address_, this); ASSERT_TRUE(socket->ConnectBlocking().ok()); std::string data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; std::string expected; std::unique_ptr<TestServerSocketRunner> runner; std::string sent; switch (protocol_) { case socket_api::SocketProtocol::kTcp: do { expected.insert(expected.end(), data.begin(), data.end()); send_result_.reset(); socket->SendAsync(data); ASSERT_TRUE(!send_result_.has_value() || send_result_.value().ok()); } while (send_result_.has_value()); runner = CreateServerSocketRunner( absl::bind_front(&ReceiveDataFromSocket, &sent), socket.get()); EXPECT_FALSE(send_result_.has_value()); for (int i = 0; i < 5 && !send_result_.has_value(); ++i) { event_loop_->RunEventLoopOnce(QuicTime::Delta::FromSeconds(1)); } break; case socket_api::SocketProtocol::kUdp: runner = CreateServerSocketRunner( absl::bind_front(&ReceiveDataFromSocket, &sent), socket.get()); socket->SendAsync(data); expected = data; break; default: FAIL(); } ASSERT_TRUE(send_result_.has_value()); EXPECT_TRUE(send_result_.value().ok()); send_result_.reset(); socket->Disconnect(); EXPECT_FALSE(send_result_.has_value()); runner->WaitForCompletion(); EXPECT_EQ(sent, expected); } TEST_P(EventLoopConnectingClientSocketTest, DisconnectCancelsSendAsync) { if (protocol_ == socket_api::SocketProtocol::kUdp) { return; } std::unique_ptr<ConnectingClientSocket> socket = CreateSocketToEncourageDelayedSend(server_socket_address_, this); ASSERT_TRUE(socket->ConnectBlocking().ok()); std::string data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; do { send_result_.reset(); socket->SendAsync(data); ASSERT_TRUE(!send_result_.has_value() || send_result_.value().ok()); } while (send_result_.has_value()); socket->Disconnect(); ASSERT_TRUE(send_result_.has_value()); EXPECT_TRUE(absl::IsCancelled(send_result_.value())); } } }
366
cpp
google/quiche
socket
quiche/quic/core/io/socket.cc
quiche/quic/core/io/socket_test.cc
#ifndef QUICHE_QUIC_CORE_IO_SOCKET_H_ #define QUICHE_QUIC_CORE_IO_SOCKET_H_ #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_ip_address_family.h" #include "quiche/quic/platform/api/quic_socket_address.h" #if defined(_WIN32) #include <winsock2.h> #else #include <sys/socket.h> #endif namespace quic { #if defined(_WIN32) using SocketFd = SOCKET; inline constexpr SocketFd kInvalidSocketFd = INVALID_SOCKET; inline constexpr int kSocketErrorMsgSize = WSAEMSGSIZE; #else using SocketFd = int; inline constexpr SocketFd kInvalidSocketFd = -1; inline constexpr int kSocketErrorMsgSize = EMSGSIZE; #endif namespace socket_api { enum class SocketProtocol { kUdp, kTcp, kRawIp, }; inline absl::string_view GetProtocolName(SocketProtocol protocol) { switch (protocol) { case SocketProtocol::kUdp: return "UDP"; case SocketProtocol::kTcp: return "TCP"; case SocketProtocol::kRawIp: return "RAW_IP"; } return "unknown"; } struct AcceptResult { SocketFd fd; QuicSocketAddress peer_address; }; absl::StatusOr<SocketFd> CreateSocket(IpAddressFamily address_family, SocketProtocol protocol, bool blocking = false); absl::Status SetSocketBlocking(SocketFd fd, bool blocking); absl::Status SetReceiveBufferSize(SocketFd fd, QuicByteCount size); absl::Status SetSendBufferSize(SocketFd fd, QuicByteCount size); absl::Status SetIpHeaderIncluded(SocketFd fd, IpAddressFamily address_family, bool ip_header_included); absl::Status Connect(SocketFd fd, const QuicSocketAddress& peer_address); absl::Status GetSocketError(SocketFd fd); absl::Status Bind(SocketFd fd, const QuicSocketAddress& address); absl::StatusOr<QuicSocketAddress> GetSocketAddress(SocketFd fd); absl::Status Listen(SocketFd fd, int backlog); absl::StatusOr<AcceptResult> Accept(SocketFd fd, bool blocking = false); absl::StatusOr<absl::Span<char>> Receive(SocketFd fd, absl::Span<char> buffer, bool peek = false); absl::StatusOr<absl::string_view> Send(SocketFd fd, absl::string_view buffer); absl::StatusOr<absl::string_view> SendTo(SocketFd fd, const QuicSocketAddress& peer_address, absl::string_view buffer); absl::Status Close(SocketFd fd); } } #endif #include "quiche/quic/core/io/socket.h" #include <cerrno> #include <climits> #include <cstddef> #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/core/io/socket_internal.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/common/platform/api/quiche_logging.h" #if defined(_WIN32) #include "quiche/quic/core/io/socket_win.inc" #else #include "quiche/quic/core/io/socket_posix.inc" #endif namespace quic::socket_api { namespace { absl::StatusOr<AcceptResult> AcceptInternal(SocketFd fd) { QUICHE_DCHECK_NE(fd, kInvalidSocketFd); sockaddr_storage peer_addr; PlatformSocklen peer_addr_len = sizeof(peer_addr); SocketFd connection_socket = SyscallAccept( fd, reinterpret_cast<struct sockaddr*>(&peer_addr), &peer_addr_len); if (connection_socket == kInvalidSocketFd) { absl::Status status = LastSocketOperationError("::accept()"); QUICHE_DVLOG(1) << "Failed to accept connection from socket " << fd << " with error: " << status; return status; } absl::StatusOr<QuicSocketAddress> peer_address = ValidateAndConvertAddress(peer_addr, peer_addr_len); if (peer_address.ok()) { return AcceptResult{connection_socket, *peer_address}; } else { return peer_address.status(); } } absl::Status SetSockOptInt(SocketFd fd, int level, int option, int value) { QUICHE_DCHECK_NE(fd, kInvalidSocketFd); int result = SyscallSetsockopt(fd, level, option, &value, sizeof(value)); if (result >= 0) { return absl::OkStatus(); } else { absl::Status status = LastSocketOperationError("::setsockopt()"); QUICHE_DVLOG(1) << "Failed to set socket " << fd << " option " << option << " to " << value << " with error: " << status; return status; } } } absl::Status SetReceiveBufferSize(SocketFd fd, QuicByteCount size) { QUICHE_DCHECK_NE(fd, kInvalidSocketFd); QUICHE_DCHECK_LE(size, QuicByteCount{INT_MAX}); return SetSockOptInt(fd, SOL_SOCKET, SO_RCVBUF, static_cast<int>(size)); } absl::Status SetSendBufferSize(SocketFd fd, QuicByteCount size) { QUICHE_DCHECK_NE(fd, kInvalidSocketFd); QUICHE_DCHECK_LE(size, QuicByteCount{INT_MAX}); return SetSockOptInt(fd, SOL_SOCKET, SO_SNDBUF, static_cast<int>(size)); } absl::Status Connect(SocketFd fd, const QuicSocketAddress& peer_address) { QUICHE_DCHECK_NE(fd, kInvalidSocketFd); QUICHE_DCHECK(peer_address.IsInitialized()); sockaddr_storage addr = peer_address.generic_address(); PlatformSocklen addrlen = GetAddrlen(peer_address.host().address_family()); int connect_result = SyscallConnect(fd, reinterpret_cast<sockaddr*>(&addr), addrlen); if (connect_result >= 0) { return absl::OkStatus(); } else { absl::Status status = LastSocketOperationError("::connect()", {EINPROGRESS}); QUICHE_DVLOG(1) << "Failed to connect socket " << fd << " to address: " << peer_address.ToString() << " with error: " << status; return status; } } absl::Status GetSocketError(SocketFd fd) { QUICHE_DCHECK_NE(fd, kInvalidSocketFd); int socket_error = 0; PlatformSocklen len = sizeof(socket_error); int sockopt_result = SyscallGetsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &len); if (sockopt_result >= 0) { if (socket_error == 0) { return absl::OkStatus(); } else { return ToStatus(socket_error, "SO_ERROR"); } } else { absl::Status status = LastSocketOperationError("::getsockopt()"); QUICHE_LOG_FIRST_N(ERROR, 100) << "Failed to get socket error information from socket " << fd << " with error: " << status; return status; } } absl::Status Bind(SocketFd fd, const QuicSocketAddress& address) { QUICHE_DCHECK_NE(fd, kInvalidSocketFd); QUICHE_DCHECK(address.IsInitialized()); sockaddr_storage addr = address.generic_address(); PlatformSocklen addr_len = GetAddrlen(address.host().address_family()); int result = SyscallBind(fd, reinterpret_cast<sockaddr*>(&addr), addr_len); if (result >= 0) { return absl::OkStatus(); } else { absl::Status status = LastSocketOperationError("::bind()"); QUICHE_DVLOG(1) << "Failed to bind socket " << fd << " to address: " << address.ToString() << " with error: " << status; return status; } } absl::StatusOr<QuicSocketAddress> GetSocketAddress(SocketFd fd) { QUICHE_DCHECK_NE(fd, kInvalidSocketFd); sockaddr_storage addr; PlatformSocklen addr_len = sizeof(addr); int result = SyscallGetsockname(fd, reinterpret_cast<sockaddr*>(&addr), &addr_len); if (result >= 0) { return ValidateAndConvertAddress(addr, addr_len); } else { absl::Status status = LastSocketOperationError("::getsockname()"); QUICHE_DVLOG(1) << "Failed to get socket " << fd << " name with error: " << status; return status; } } absl::Status Listen(SocketFd fd, int backlog) { QUICHE_DCHECK_NE(fd, kInvalidSocketFd); QUICHE_DCHECK_GT(backlog, 0); int result = SyscallListen(fd, backlog); if (result >= 0) { return absl::OkStatus(); } else { absl::Status status = LastSocketOperationError("::listen()"); QUICHE_DVLOG(1) << "Failed to mark socket: " << fd << " to listen with error :" << status; return status; } } absl::StatusOr<AcceptResult> Accept(SocketFd fd, bool blocking) { QUICHE_DCHECK_NE(fd, kInvalidSocketFd); #if defined(HAS_ACCEPT4) if (!blocking) { return AcceptWithFlags(fd, SOCK_NONBLOCK); } #endif absl::StatusOr<AcceptResult> accept_result = AcceptInternal(fd); if (!accept_result.ok() || blocking) { return accept_result; } #if !defined(__linux__) || !defined(SOCK_NONBLOCK) absl::Status set_non_blocking_result = SetSocketBlocking(accept_result->fd, false); if (!set_non_blocking_result.ok()) { QUICHE_LOG_FIRST_N(ERROR, 100) << "Failed to set socket " << fd << " as non-blocking on acceptance."; if (!Close(accept_result->fd).ok()) { QUICHE_LOG_FIRST_N(ERROR, 100) << "Failed to close socket " << accept_result->fd << " after error setting non-blocking on acceptance."; } return set_non_blocking_result; } #endif return accept_result; } absl::StatusOr<absl::Span<char>> Receive(SocketFd fd, absl::Span<char> buffer, bool peek) { QUICHE_DCHECK_NE(fd, kInvalidSocketFd); QUICHE_DCHECK(!buffer.empty()); PlatformSsizeT num_read = SyscallRecv(fd, buffer.data(), buffer.size(), peek ? MSG_PEEK : 0); if (num_read > 0 && static_cast<size_t>(num_read) > buffer.size()) { QUICHE_LOG_FIRST_N(WARNING, 100) << "Received more bytes (" << num_read << ") from socket " << fd << " than buffer size (" << buffer.size() << ")."; return absl::OutOfRangeError( "::recv(): Received more bytes than buffer size."); } else if (num_read >= 0) { return buffer.subspan(0, num_read); } else { absl::Status status = LastSocketOperationError("::recv()"); QUICHE_DVLOG(1) << "Failed to receive from socket: " << fd << " with error: " << status; return status; } } absl::StatusOr<absl::string_view> Send(SocketFd fd, absl::string_view buffer) { QUICHE_DCHECK_NE(fd, kInvalidSocketFd); QUICHE_DCHECK(!buffer.empty()); PlatformSsizeT num_sent = SyscallSend(fd, buffer.data(), buffer.size(), 0); if (num_sent > 0 && static_cast<size_t>(num_sent) > buffer.size()) { QUICHE_LOG_FIRST_N(WARNING, 100) << "Sent more bytes (" << num_sent << ") to socket " << fd << " than buffer size (" << buffer.size() << ")."; return absl::OutOfRangeError("::send(): Sent more bytes than buffer size."); } else if (num_sent >= 0) { return buffer.substr(num_sent); } else { absl::Status status = LastSocketOperationError("::send()"); QUICHE_DVLOG(1) << "Failed to send to socket: " << fd << " with error: " << status; return status; } } absl::StatusOr<absl::string_view> SendTo(SocketFd fd, const QuicSocketAddress& peer_address, absl::string_view buffer) { QUICHE_DCHECK_NE(fd, kInvalidSocketFd); QUICHE_DCHECK(peer_address.IsInitialized()); QUICHE_DCHECK(!buffer.empty()); sockaddr_storage addr = peer_address.generic_address(); PlatformSocklen addrlen = GetAddrlen(peer_address.host().address_family()); PlatformSsizeT num_sent = SyscallSendTo(fd, buffer.data(), buffer.size(), 0, reinterpret_cast<sockaddr*>(&addr), addrlen); if (num_sent > 0 && static_cast<size_t>(num_sent) > buffer.size()) { QUICHE_LOG_FIRST_N(WARNING, 100) << "Sent more bytes (" << num_sent << ") to socket " << fd << " to address: " << peer_address.ToString() << " than buffer size (" << buffer.size() << ")."; return absl::OutOfRangeError( "::sendto(): Sent more bytes than buffer size."); } else if (num_sent >= 0) { return buffer.substr(num_sent); } else { absl::Status status = LastSocketOperationError("::sendto()"); QUICHE_DVLOG(1) << "Failed to send to socket: " << fd << " to address: " << peer_address.ToString() << " with error: " << status; return status; } } }
#include "quiche/quic/core/io/socket.h" #include <string> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/platform/api/quic_ip_address.h" #include "quiche/quic/platform/api/quic_ip_address_family.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/test_tools/test_ip_packets.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/platform/api/quiche_test_loopback.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace quic::test { namespace { using quiche::test::QuicheTest; using quiche::test::StatusIs; using testing::Lt; using testing::SizeIs; SocketFd CreateTestSocket(socket_api::SocketProtocol protocol, bool blocking = true) { absl::StatusOr<SocketFd> socket = socket_api::CreateSocket( quiche::TestLoopback().address_family(), protocol, blocking); if (socket.ok()) { return socket.value(); } else { QUICHE_CHECK(false); return kInvalidSocketFd; } } SocketFd CreateTestRawSocket( bool blocking = true, IpAddressFamily address_family = IpAddressFamily::IP_UNSPEC) { absl::StatusOr<SocketFd> socket; switch (address_family) { case IpAddressFamily::IP_V4: socket = socket_api::CreateSocket( quiche::TestLoopback4().address_family(), socket_api::SocketProtocol::kRawIp, blocking); break; case IpAddressFamily::IP_V6: socket = socket_api::CreateSocket( quiche::TestLoopback6().address_family(), socket_api::SocketProtocol::kRawIp, blocking); break; case IpAddressFamily::IP_UNSPEC: socket = socket_api::CreateSocket(quiche::TestLoopback().address_family(), socket_api::SocketProtocol::kRawIp, blocking); break; } if (socket.ok()) { return socket.value(); } else { QUICHE_CHECK(absl::IsPermissionDenied(socket.status()) || absl::IsNotFound(socket.status())); return kInvalidSocketFd; } } TEST(SocketTest, CreateAndCloseSocket) { QuicIpAddress localhost_address = quiche::TestLoopback(); absl::StatusOr<SocketFd> created_socket = socket_api::CreateSocket( localhost_address.address_family(), socket_api::SocketProtocol::kUdp); QUICHE_EXPECT_OK(created_socket.status()); QUICHE_EXPECT_OK(socket_api::Close(created_socket.value())); } TEST(SocketTest, CreateAndCloseRawSocket) { QuicIpAddress localhost_address = quiche::TestLoopback(); absl::StatusOr<SocketFd> created_socket = socket_api::CreateSocket( localhost_address.address_family(), socket_api::SocketProtocol::kRawIp); if (!created_socket.ok()) { EXPECT_THAT(created_socket.status(), StatusIs(absl::StatusCode::kPermissionDenied)); return; } QUICHE_EXPECT_OK(socket_api::Close(created_socket.value())); } TEST(SocketTest, SetSocketBlocking) { SocketFd socket = CreateTestSocket(socket_api::SocketProtocol::kUdp, true); QUICHE_EXPECT_OK(socket_api::SetSocketBlocking(socket, false)); QUICHE_EXPECT_OK(socket_api::Close(socket)); } TEST(SocketTest, SetReceiveBufferSize) { SocketFd socket = CreateTestSocket(socket_api::SocketProtocol::kUdp, true); QUICHE_EXPECT_OK(socket_api::SetReceiveBufferSize(socket, 100)); QUICHE_EXPECT_OK(socket_api::Close(socket)); } TEST(SocketTest, SetSendBufferSize) { SocketFd socket = CreateTestSocket(socket_api::SocketProtocol::kUdp, true); QUICHE_EXPECT_OK(socket_api::SetSendBufferSize(socket, 100)); QUICHE_EXPECT_OK(socket_api::Close(socket)); } TEST(SocketTest, SetIpHeaderIncludedForRaw) { SocketFd socket = CreateTestRawSocket(true, IpAddressFamily::IP_V4); if (socket == kInvalidSocketFd) { GTEST_SKIP(); } QUICHE_EXPECT_OK(socket_api::SetIpHeaderIncluded( socket, IpAddressFamily::IP_V4, true)); QUICHE_EXPECT_OK(socket_api::Close(socket)); } TEST(SocketTest, SetIpHeaderIncludedForRawV6) { SocketFd socket = CreateTestRawSocket(true, IpAddressFamily::IP_V6); if (socket == kInvalidSocketFd) { GTEST_SKIP(); } QUICHE_EXPECT_OK(socket_api::SetIpHeaderIncluded( socket, IpAddressFamily::IP_V6, true)); QUICHE_EXPECT_OK(socket_api::Close(socket)); } TEST(SocketTest, SetIpHeaderIncludedForUdp) { SocketFd socket = CreateTestSocket(socket_api::SocketProtocol::kUdp, true); EXPECT_THAT(socket_api::SetIpHeaderIncluded(socket, IpAddressFamily::IP_V4, true), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(socket_api::SetIpHeaderIncluded(socket, IpAddressFamily::IP_V6, true), StatusIs(absl::StatusCode::kInvalidArgument)); QUICHE_EXPECT_OK(socket_api::Close(socket)); } TEST(SocketTest, Connect) { SocketFd socket = CreateTestSocket(socket_api::SocketProtocol::kUdp); QUICHE_EXPECT_OK(socket_api::Connect( socket, QuicSocketAddress(quiche::TestLoopback(), 0))); QUICHE_EXPECT_OK(socket_api::Close(socket)); } TEST(SocketTest, GetSocketError) { SocketFd socket = CreateTestSocket(socket_api::SocketProtocol::kUdp, true); absl::Status error = socket_api::GetSocketError(socket); QUICHE_EXPECT_OK(error); QUICHE_EXPECT_OK(socket_api::Close(socket)); } TEST(SocketTest, Bind) { SocketFd socket = CreateTestSocket(socket_api::SocketProtocol::kUdp); QUICHE_EXPECT_OK(socket_api::Bind( socket, QuicSocketAddress(quiche::TestLoopback(), 0))); QUICHE_EXPECT_OK(socket_api::Close(socket)); } TEST(SocketTest, GetSocketAddress) { SocketFd socket = CreateTestSocket(socket_api::SocketProtocol::kUdp); QUICHE_ASSERT_OK(socket_api::Bind( socket, QuicSocketAddress(quiche::TestLoopback(), 0))); absl::StatusOr<QuicSocketAddress> address = socket_api::GetSocketAddress(socket); QUICHE_EXPECT_OK(address); EXPECT_TRUE(address.value().IsInitialized()); EXPECT_EQ(address.value().host(), quiche::TestLoopback()); QUICHE_EXPECT_OK(socket_api::Close(socket)); } TEST(SocketTest, Listen) { SocketFd socket = CreateTestSocket(socket_api::SocketProtocol::kTcp); QUICHE_ASSERT_OK(socket_api::Bind( socket, QuicSocketAddress(quiche::TestLoopback(), 0))); QUICHE_EXPECT_OK(socket_api::Listen(socket, 5)); QUICHE_EXPECT_OK(socket_api::Close(socket)); } TEST(SocketTest, Accept) { SocketFd socket = CreateTestSocket(socket_api::SocketProtocol::kTcp, false); QUICHE_ASSERT_OK(socket_api::Bind( socket, QuicSocketAddress(quiche::TestLoopback(), 0))); QUICHE_ASSERT_OK(socket_api::Listen(socket, 5)); absl::StatusOr<socket_api::AcceptResult> result = socket_api::Accept(socket); EXPECT_THAT(result, StatusIs(absl::StatusCode::kUnavailable)); QUICHE_EXPECT_OK(socket_api::Close(socket)); } TEST(SocketTest, Receive) { SocketFd socket = CreateTestSocket(socket_api::SocketProtocol::kUdp, false); QUICHE_ASSERT_OK(socket_api::Bind( socket, QuicSocketAddress(quiche::TestLoopback(), 0))); std::string buffer(100, 0); absl::StatusOr<absl::Span<char>> result = socket_api::Receive(socket, absl::MakeSpan(buffer)); EXPECT_THAT(result, StatusIs(absl::StatusCode::kUnavailable)); QUICHE_EXPECT_OK(socket_api::Close(socket)); } TEST(SocketTest, Peek) { SocketFd socket = CreateTestSocket(socket_api::SocketProtocol::kUdp, false); QUICHE_ASSERT_OK(socket_api::Bind( socket, QuicSocketAddress(quiche::TestLoopback(), 0))); std::string buffer(100, 0); absl::StatusOr<absl::Span<char>> result = socket_api::Receive(socket, absl::MakeSpan(buffer), true); EXPECT_THAT(result, StatusIs(absl::StatusCode::kUnavailable)); QUICHE_EXPECT_OK(socket_api::Close(socket)); } TEST(SocketTest, Send) { SocketFd socket = CreateTestSocket(socket_api::SocketProtocol::kUdp); QUICHE_ASSERT_OK(socket_api::Connect( socket, QuicSocketAddress(quiche::TestLoopback(), 0))); char buffer[] = {12, 34, 56, 78}; absl::StatusOr<absl::string_view> result = socket_api::Send(socket, absl::string_view(buffer, sizeof(buffer))); QUICHE_ASSERT_OK(result.status()); EXPECT_THAT(result.value(), SizeIs(Lt(4))); QUICHE_EXPECT_OK(socket_api::Close(socket)); } TEST(SocketTest, SendTo) { SocketFd socket = CreateTestSocket(socket_api::SocketProtocol::kUdp); char buffer[] = {12, 34, 56, 78}; absl::StatusOr<absl::string_view> result = socket_api::SendTo( socket, QuicSocketAddress(quiche::TestLoopback(), 57290), absl::string_view(buffer, sizeof(buffer))); QUICHE_ASSERT_OK(result.status()); EXPECT_THAT(result.value(), SizeIs(Lt(4))); QUICHE_EXPECT_OK(socket_api::Close(socket)); } TEST(SocketTest, SendToWithConnection) { SocketFd socket = CreateTestSocket(socket_api::SocketProtocol::kUdp); QUICHE_ASSERT_OK(socket_api::Connect( socket, QuicSocketAddress(quiche::TestLoopback(), 0))); char buffer[] = {12, 34, 56, 78}; absl::StatusOr<absl::string_view> result = socket_api::SendTo( socket, QuicSocketAddress(quiche::TestLoopback(), 50495), absl::string_view(buffer, sizeof(buffer))); QUICHE_ASSERT_OK(result.status()); EXPECT_THAT(result.value(), SizeIs(Lt(4))); QUICHE_EXPECT_OK(socket_api::Close(socket)); } TEST(SocketTest, SendToForRaw) { SocketFd socket = CreateTestRawSocket(true); if (socket == kInvalidSocketFd) { GTEST_SKIP(); } QuicIpAddress localhost_address = quiche::TestLoopback(); QUICHE_EXPECT_OK(socket_api::SetIpHeaderIncluded( socket, localhost_address.address_family(), false)); QuicSocketAddress client_address(localhost_address, 53368); QuicSocketAddress server_address(localhost_address, 56362); std::string packet = CreateUdpPacket(client_address, server_address, "foo"); absl::StatusOr<absl::string_view> result = socket_api::SendTo( socket, QuicSocketAddress(localhost_address, 56362), packet); QUICHE_ASSERT_OK(result.status()); EXPECT_THAT(result.value(), SizeIs(Lt(packet.size()))); QUICHE_EXPECT_OK(socket_api::Close(socket)); } TEST(SocketTest, SendToForRawWithIpHeader) { SocketFd socket = CreateTestRawSocket(true); if (socket == kInvalidSocketFd) { GTEST_SKIP(); } QuicIpAddress localhost_address = quiche::TestLoopback(); QUICHE_EXPECT_OK(socket_api::SetIpHeaderIncluded( socket, localhost_address.address_family(), true)); QuicSocketAddress client_address(localhost_address, 53368); QuicSocketAddress server_address(localhost_address, 56362); std::string packet = CreateIpPacket(client_address.host(), server_address.host(), CreateUdpPacket(client_address, server_address, "foo")); absl::StatusOr<absl::string_view> result = socket_api::SendTo( socket, QuicSocketAddress(localhost_address, 56362), packet); QUICHE_ASSERT_OK(result.status()); EXPECT_THAT(result.value(), SizeIs(Lt(packet.size()))); QUICHE_EXPECT_OK(socket_api::Close(socket)); } } }
367
cpp
google/quiche
quic_poll_event_loop
quiche/quic/core/io/quic_poll_event_loop.cc
quiche/quic/core/io/quic_poll_event_loop_test.cc
#ifndef QUICHE_QUIC_CORE_IO_QUIC_POLL_EVENT_LOOP_H_ #define QUICHE_QUIC_CORE_IO_QUIC_POLL_EVENT_LOOP_H_ #if defined(_WIN32) #include <winsock2.h> #else #include <poll.h> #endif #include <memory> #include "absl/container/btree_map.h" #include "absl/types/span.h" #include "quiche/quic/core/io/quic_event_loop.h" #include "quiche/quic/core/io/socket.h" #include "quiche/quic/core/quic_alarm.h" #include "quiche/quic/core/quic_alarm_factory.h" #include "quiche/quic/core/quic_clock.h" #include "quiche/common/quiche_linked_hash_map.h" namespace quic { class QuicPollEventLoop : public QuicEventLoop { public: QuicPollEventLoop(QuicClock* clock); bool SupportsEdgeTriggered() const override { return false; } ABSL_MUST_USE_RESULT bool RegisterSocket( SocketFd fd, QuicSocketEventMask events, QuicSocketEventListener* listener) override; ABSL_MUST_USE_RESULT bool UnregisterSocket(SocketFd fd) override; ABSL_MUST_USE_RESULT bool RearmSocket(SocketFd fd, QuicSocketEventMask events) override; ABSL_MUST_USE_RESULT bool ArtificiallyNotifyEvent( SocketFd fd, QuicSocketEventMask events) override; void RunEventLoopOnce(QuicTime::Delta default_timeout) override; std::unique_ptr<QuicAlarmFactory> CreateAlarmFactory() override; const QuicClock* GetClock() override { return clock_; } protected: virtual int PollSyscall(pollfd* fds, size_t nfds, int timeout); private: friend class QuicPollEventLoopPeer; struct Registration { QuicSocketEventMask events = 0; QuicSocketEventListener* listener; QuicSocketEventMask artificially_notify_at_next_iteration = 0; }; class Alarm : public QuicAlarm { public: Alarm(QuicPollEventLoop* loop, QuicArenaScopedPtr<QuicAlarm::Delegate> delegate); void SetImpl() override; void CancelImpl() override; void DoFire() { current_schedule_handle_.reset(); Fire(); } private: QuicPollEventLoop* loop_; std::shared_ptr<Alarm*> current_schedule_handle_; }; class AlarmFactory : public QuicAlarmFactory { public: AlarmFactory(QuicPollEventLoop* loop) : loop_(loop) {} QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override; QuicArenaScopedPtr<QuicAlarm> CreateAlarm( QuicArenaScopedPtr<QuicAlarm::Delegate> delegate, QuicConnectionArena* arena) override; private: QuicPollEventLoop* loop_; }; struct ReadyListEntry { SocketFd fd; std::weak_ptr<Registration> registration; QuicSocketEventMask events; }; using RegistrationMap = quiche::QuicheLinkedHashMap<SocketFd, std::shared_ptr<Registration>>; using AlarmList = absl::btree_multimap<QuicTime, std::weak_ptr<Alarm*>>; QuicTime::Delta ComputePollTimeout(QuicTime now, QuicTime::Delta default_timeout) const; void ProcessIoEvents(QuicTime start_time, QuicTime::Delta timeout); void ProcessAlarmsUpTo(QuicTime time); void DispatchIoEvent(std::vector<ReadyListEntry>& ready_list, SocketFd fd, short mask); void RunReadyCallbacks(std::vector<ReadyListEntry>& ready_list); int PollWithRetries(absl::Span<pollfd> fds, QuicTime start_time, QuicTime::Delta timeout); const QuicClock* clock_; RegistrationMap registrations_; AlarmList alarms_; bool has_artificial_events_pending_ = false; }; class QuicPollEventLoopFactory : public QuicEventLoopFactory { public: static QuicPollEventLoopFactory* Get() { static QuicPollEventLoopFactory* factory = new QuicPollEventLoopFactory(); return factory; } std::unique_ptr<QuicEventLoop> Create(QuicClock* clock) override { return std::make_unique<QuicPollEventLoop>(clock); } std::string GetName() const override { return "poll(2)"; } }; } #endif #include "quiche/quic/core/io/quic_poll_event_loop.h" #include <algorithm> #include <cerrno> #include <cmath> #include <memory> #include <utility> #include <vector> #include "absl/types/span.h" #include "quiche/quic/core/io/quic_event_loop.h" #include "quiche/quic/core/quic_alarm.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" namespace quic { namespace { using PollMask = decltype(::pollfd().events); PollMask GetPollMask(QuicSocketEventMask event_mask) { return ((event_mask & kSocketEventReadable) ? POLLIN : 0) | ((event_mask & kSocketEventWritable) ? POLLOUT : 0) | ((event_mask & kSocketEventError) ? POLLERR : 0); } QuicSocketEventMask GetEventMask(PollMask poll_mask) { return ((poll_mask & POLLIN) ? kSocketEventReadable : 0) | ((poll_mask & POLLOUT) ? kSocketEventWritable : 0) | ((poll_mask & POLLERR) ? kSocketEventError : 0); } } QuicPollEventLoop::QuicPollEventLoop(QuicClock* clock) : clock_(clock) {} bool QuicPollEventLoop::RegisterSocket(SocketFd fd, QuicSocketEventMask events, QuicSocketEventListener* listener) { auto [it, success] = registrations_.insert({fd, std::make_shared<Registration>()}); if (!success) { return false; } Registration& registration = *it->second; registration.events = events; registration.listener = listener; return true; } bool QuicPollEventLoop::UnregisterSocket(SocketFd fd) { return registrations_.erase(fd); } bool QuicPollEventLoop::RearmSocket(SocketFd fd, QuicSocketEventMask events) { auto it = registrations_.find(fd); if (it == registrations_.end()) { return false; } it->second->events |= events; return true; } bool QuicPollEventLoop::ArtificiallyNotifyEvent(SocketFd fd, QuicSocketEventMask events) { auto it = registrations_.find(fd); if (it == registrations_.end()) { return false; } has_artificial_events_pending_ = true; it->second->artificially_notify_at_next_iteration |= events; return true; } void QuicPollEventLoop::RunEventLoopOnce(QuicTime::Delta default_timeout) { const QuicTime start_time = clock_->Now(); ProcessAlarmsUpTo(start_time); QuicTime::Delta timeout = ComputePollTimeout(start_time, default_timeout); ProcessIoEvents(start_time, timeout); const QuicTime end_time = clock_->Now(); ProcessAlarmsUpTo(end_time); } QuicTime::Delta QuicPollEventLoop::ComputePollTimeout( QuicTime now, QuicTime::Delta default_timeout) const { default_timeout = std::max(default_timeout, QuicTime::Delta::Zero()); if (has_artificial_events_pending_) { return QuicTime::Delta::Zero(); } if (alarms_.empty()) { return default_timeout; } QuicTime end_time = std::min(now + default_timeout, alarms_.begin()->first); if (end_time < now) { return QuicTime::Delta::Zero(); } return end_time - now; } int QuicPollEventLoop::PollWithRetries(absl::Span<pollfd> fds, QuicTime start_time, QuicTime::Delta timeout) { const QuicTime timeout_at = start_time + timeout; int poll_result; for (;;) { float timeout_ms = std::ceil(timeout.ToMicroseconds() / 1000.f); poll_result = PollSyscall(fds.data(), fds.size(), static_cast<int>(timeout_ms)); bool done = poll_result > 0 || (poll_result < 0 && errno != EINTR); if (done) { break; } QuicTime now = clock_->Now(); if (now >= timeout_at) { break; } timeout = timeout_at - now; } return poll_result; } void QuicPollEventLoop::ProcessIoEvents(QuicTime start_time, QuicTime::Delta timeout) { const size_t registration_count = registrations_.size(); auto pollfds = std::make_unique<pollfd[]>(registration_count); size_t i = 0; for (auto& [fd, registration] : registrations_) { QUICHE_CHECK_LT( i, registration_count); pollfds[i].fd = fd; pollfds[i].events = GetPollMask(registration->events); pollfds[i].revents = 0; ++i; } int poll_result = PollWithRetries(absl::Span<pollfd>(pollfds.get(), registration_count), start_time, timeout); if (poll_result == 0 && !has_artificial_events_pending_) { return; } std::vector<ReadyListEntry> ready_list; ready_list.reserve(registration_count); for (i = 0; i < registration_count; i++) { DispatchIoEvent(ready_list, pollfds[i].fd, pollfds[i].revents); } has_artificial_events_pending_ = false; RunReadyCallbacks(ready_list); } void QuicPollEventLoop::DispatchIoEvent(std::vector<ReadyListEntry>& ready_list, SocketFd fd, PollMask mask) { auto it = registrations_.find(fd); if (it == registrations_.end()) { QUIC_BUG(poll returned an unregistered fd) << fd; return; } Registration& registration = *it->second; mask |= GetPollMask(registration.artificially_notify_at_next_iteration); mask &= GetPollMask(registration.events | registration.artificially_notify_at_next_iteration); registration.artificially_notify_at_next_iteration = QuicSocketEventMask(); if (!mask) { return; } ready_list.push_back(ReadyListEntry{fd, it->second, GetEventMask(mask)}); registration.events &= ~GetEventMask(mask); } void QuicPollEventLoop::RunReadyCallbacks( std::vector<ReadyListEntry>& ready_list) { for (ReadyListEntry& entry : ready_list) { std::shared_ptr<Registration> registration = entry.registration.lock(); if (!registration) { continue; } registration->listener->OnSocketEvent(this, entry.fd, entry.events); } ready_list.clear(); } void QuicPollEventLoop::ProcessAlarmsUpTo(QuicTime time) { std::vector<std::weak_ptr<Alarm*>> alarms_to_call; while (!alarms_.empty() && alarms_.begin()->first <= time) { auto& [deadline, schedule_handle_weak] = *alarms_.begin(); alarms_to_call.push_back(std::move(schedule_handle_weak)); alarms_.erase(alarms_.begin()); } for (std::weak_ptr<Alarm*>& schedule_handle_weak : alarms_to_call) { std::shared_ptr<Alarm*> schedule_handle = schedule_handle_weak.lock(); if (!schedule_handle) { continue; } (*schedule_handle)->DoFire(); } while (!alarms_.empty()) { if (alarms_.begin()->second.expired()) { alarms_.erase(alarms_.begin()); } else { break; } } } QuicAlarm* QuicPollEventLoop::AlarmFactory::CreateAlarm( QuicAlarm::Delegate* delegate) { return new Alarm(loop_, QuicArenaScopedPtr<QuicAlarm::Delegate>(delegate)); } QuicArenaScopedPtr<QuicAlarm> QuicPollEventLoop::AlarmFactory::CreateAlarm( QuicArenaScopedPtr<QuicAlarm::Delegate> delegate, QuicConnectionArena* arena) { if (arena != nullptr) { return arena->New<Alarm>(loop_, std::move(delegate)); } return QuicArenaScopedPtr<QuicAlarm>(new Alarm(loop_, std::move(delegate))); } QuicPollEventLoop::Alarm::Alarm( QuicPollEventLoop* loop, QuicArenaScopedPtr<QuicAlarm::Delegate> delegate) : QuicAlarm(std::move(delegate)), loop_(loop) {} void QuicPollEventLoop::Alarm::SetImpl() { current_schedule_handle_ = std::make_shared<Alarm*>(this); loop_->alarms_.insert({deadline(), current_schedule_handle_}); } void QuicPollEventLoop::Alarm::CancelImpl() { current_schedule_handle_.reset(); } std::unique_ptr<QuicAlarmFactory> QuicPollEventLoop::CreateAlarmFactory() { return std::make_unique<AlarmFactory>(this); } int QuicPollEventLoop::PollSyscall(pollfd* fds, size_t nfds, int timeout) { #if defined(_WIN32) return WSAPoll(fds, nfds, timeout); #else return ::poll(fds, nfds, timeout); #endif } }
#include "quiche/quic/core/io/quic_poll_event_loop.h" #include <fcntl.h> #include <unistd.h> #include <cerrno> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/memory/memory.h" #include "quiche/quic/core/io/quic_event_loop.h" #include "quiche/quic/core/quic_alarm.h" #include "quiche/quic/core/quic_alarm_factory.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_clock.h" namespace quic { class QuicPollEventLoopPeer { public: static QuicTime::Delta ComputePollTimeout(const QuicPollEventLoop& loop, QuicTime now, QuicTime::Delta default_timeout) { return loop.ComputePollTimeout(now, default_timeout); } }; } namespace quic::test { namespace { using testing::_; using testing::AtMost; using testing::ElementsAre; constexpr QuicSocketEventMask kAllEvents = kSocketEventReadable | kSocketEventWritable | kSocketEventError; constexpr QuicTime::Delta kDefaultTimeout = QuicTime::Delta::FromSeconds(100); class MockQuicSocketEventListener : public QuicSocketEventListener { public: MOCK_METHOD(void, OnSocketEvent, (QuicEventLoop* , SocketFd , QuicSocketEventMask ), (override)); }; class MockDelegate : public QuicAlarm::Delegate { public: QuicConnectionContext* GetConnectionContext() override { return nullptr; } MOCK_METHOD(void, OnAlarm, (), (override)); }; class QuicPollEventLoopForTest : public QuicPollEventLoop { public: QuicPollEventLoopForTest(MockClock* clock) : QuicPollEventLoop(clock), clock_(clock) {} int PollSyscall(pollfd* fds, nfds_t nfds, int timeout) override { timeouts_.push_back(timeout); if (eintr_after_ != QuicTime::Delta::Infinite()) { errno = EINTR; clock_->AdvanceTime(eintr_after_); eintr_after_ = QuicTime::Delta::Infinite(); return -1; } if (poll_return_after_ != QuicTime::Delta::Infinite()) { clock_->AdvanceTime(poll_return_after_); poll_return_after_ = QuicTime::Delta::Infinite(); } else { clock_->AdvanceTime(QuicTime::Delta::FromMilliseconds(timeout)); } return QuicPollEventLoop::PollSyscall(fds, nfds, timeout); } void TriggerEintrAfter(QuicTime::Delta time) { eintr_after_ = time; } void ReturnFromPollAfter(QuicTime::Delta time) { poll_return_after_ = time; } const std::vector<int>& timeouts() const { return timeouts_; } private: MockClock* clock_; QuicTime::Delta eintr_after_ = QuicTime::Delta::Infinite(); QuicTime::Delta poll_return_after_ = QuicTime::Delta::Infinite(); std::vector<int> timeouts_; }; class QuicPollEventLoopTest : public QuicTest { public: QuicPollEventLoopTest() : loop_(&clock_), factory_(loop_.CreateAlarmFactory()) { int fds[2]; int result = ::pipe(fds); QUICHE_CHECK(result >= 0) << "Failed to create a pipe, errno: " << errno; read_fd_ = fds[0]; write_fd_ = fds[1]; QUICHE_CHECK(::fcntl(read_fd_, F_SETFL, ::fcntl(read_fd_, F_GETFL) | O_NONBLOCK) == 0) << "Failed to mark pipe FD non-blocking, errno: " << errno; QUICHE_CHECK(::fcntl(write_fd_, F_SETFL, ::fcntl(write_fd_, F_GETFL) | O_NONBLOCK) == 0) << "Failed to mark pipe FD non-blocking, errno: " << errno; clock_.AdvanceTime(10 * kDefaultTimeout); } ~QuicPollEventLoopTest() { close(read_fd_); close(write_fd_); } QuicTime::Delta ComputePollTimeout() { return QuicPollEventLoopPeer::ComputePollTimeout(loop_, clock_.Now(), kDefaultTimeout); } std::pair<std::unique_ptr<QuicAlarm>, MockDelegate*> CreateAlarm() { auto delegate = std::make_unique<testing::StrictMock<MockDelegate>>(); MockDelegate* delegate_unowned = delegate.get(); auto alarm = absl::WrapUnique(factory_->CreateAlarm(delegate.release())); return std::make_pair(std::move(alarm), delegate_unowned); } protected: MockClock clock_; QuicPollEventLoopForTest loop_; std::unique_ptr<QuicAlarmFactory> factory_; int read_fd_; int write_fd_; }; TEST_F(QuicPollEventLoopTest, NothingHappens) { testing::StrictMock<MockQuicSocketEventListener> listener; ASSERT_TRUE(loop_.RegisterSocket(read_fd_, kAllEvents, &listener)); ASSERT_TRUE(loop_.RegisterSocket(write_fd_, kAllEvents, &listener)); EXPECT_FALSE(loop_.RegisterSocket(write_fd_, kAllEvents, &listener)); EXPECT_EQ(ComputePollTimeout(), kDefaultTimeout); EXPECT_CALL(listener, OnSocketEvent(_, write_fd_, kSocketEventWritable)); loop_.RunEventLoopOnce(QuicTime::Delta::FromMilliseconds(4)); loop_.RunEventLoopOnce(QuicTime::Delta::FromMilliseconds(5)); EXPECT_THAT(loop_.timeouts(), ElementsAre(4, 5)); } TEST_F(QuicPollEventLoopTest, RearmWriter) { testing::StrictMock<MockQuicSocketEventListener> listener; ASSERT_TRUE(loop_.RegisterSocket(write_fd_, kAllEvents, &listener)); EXPECT_CALL(listener, OnSocketEvent(_, write_fd_, kSocketEventWritable)) .Times(2); loop_.RunEventLoopOnce(QuicTime::Delta::FromMilliseconds(1)); ASSERT_TRUE(loop_.RearmSocket(write_fd_, kSocketEventWritable)); loop_.RunEventLoopOnce(QuicTime::Delta::FromMilliseconds(1)); } TEST_F(QuicPollEventLoopTest, Readable) { testing::StrictMock<MockQuicSocketEventListener> listener; ASSERT_TRUE(loop_.RegisterSocket(read_fd_, kAllEvents, &listener)); ASSERT_EQ(4, write(write_fd_, "test", 4)); EXPECT_CALL(listener, OnSocketEvent(_, read_fd_, kSocketEventReadable)); loop_.RunEventLoopOnce(QuicTime::Delta::FromMilliseconds(1)); loop_.RunEventLoopOnce(QuicTime::Delta::FromMilliseconds(1)); } TEST_F(QuicPollEventLoopTest, RearmReader) { testing::StrictMock<MockQuicSocketEventListener> listener; ASSERT_TRUE(loop_.RegisterSocket(read_fd_, kAllEvents, &listener)); ASSERT_EQ(4, write(write_fd_, "test", 4)); EXPECT_CALL(listener, OnSocketEvent(_, read_fd_, kSocketEventReadable)); loop_.RunEventLoopOnce(QuicTime::Delta::FromMilliseconds(1)); loop_.RunEventLoopOnce(QuicTime::Delta::FromMilliseconds(1)); } TEST_F(QuicPollEventLoopTest, WriterUnblocked) { testing::StrictMock<MockQuicSocketEventListener> listener; ASSERT_TRUE(loop_.RegisterSocket(write_fd_, kAllEvents, &listener)); EXPECT_CALL(listener, OnSocketEvent(_, write_fd_, kSocketEventWritable)); loop_.RunEventLoopOnce(QuicTime::Delta::FromMilliseconds(1)); loop_.RunEventLoopOnce(QuicTime::Delta::FromMilliseconds(1)); int io_result; std::string data(2048, 'a'); do { io_result = write(write_fd_, data.data(), data.size()); } while (io_result > 0); ASSERT_EQ(errno, EAGAIN); ASSERT_TRUE(loop_.RearmSocket(write_fd_, kSocketEventWritable)); loop_.RunEventLoopOnce(QuicTime::Delta::FromMilliseconds(1)); EXPECT_CALL(listener, OnSocketEvent(_, write_fd_, kSocketEventWritable)); do { io_result = read(read_fd_, data.data(), data.size()); } while (io_result > 0); ASSERT_EQ(errno, EAGAIN); loop_.RunEventLoopOnce(QuicTime::Delta::FromMilliseconds(1)); } TEST_F(QuicPollEventLoopTest, ArtificialEvent) { testing::StrictMock<MockQuicSocketEventListener> listener; ASSERT_TRUE(loop_.RegisterSocket(read_fd_, kAllEvents, &listener)); ASSERT_TRUE(loop_.RegisterSocket(write_fd_, kAllEvents, &listener)); EXPECT_EQ(ComputePollTimeout(), kDefaultTimeout); ASSERT_TRUE(loop_.ArtificiallyNotifyEvent(read_fd_, kSocketEventReadable)); EXPECT_EQ(ComputePollTimeout(), QuicTime::Delta::Zero()); { testing::InSequence s; EXPECT_CALL(listener, OnSocketEvent(_, read_fd_, kSocketEventReadable)); EXPECT_CALL(listener, OnSocketEvent(_, write_fd_, kSocketEventWritable)); } loop_.RunEventLoopOnce(QuicTime::Delta::FromMilliseconds(1)); EXPECT_EQ(ComputePollTimeout(), kDefaultTimeout); } TEST_F(QuicPollEventLoopTest, Unregister) { testing::StrictMock<MockQuicSocketEventListener> listener; ASSERT_TRUE(loop_.RegisterSocket(write_fd_, kAllEvents, &listener)); ASSERT_TRUE(loop_.UnregisterSocket(write_fd_)); loop_.RunEventLoopOnce(QuicTime::Delta::FromMilliseconds(1)); EXPECT_FALSE(loop_.UnregisterSocket(write_fd_)); EXPECT_FALSE(loop_.RearmSocket(write_fd_, kSocketEventWritable)); EXPECT_FALSE(loop_.ArtificiallyNotifyEvent(write_fd_, kSocketEventWritable)); } TEST_F(QuicPollEventLoopTest, UnregisterInsideEventHandler) { testing::StrictMock<MockQuicSocketEventListener> listener; ASSERT_TRUE(loop_.RegisterSocket(read_fd_, kAllEvents, &listener)); ASSERT_TRUE(loop_.RegisterSocket(write_fd_, kAllEvents, &listener)); EXPECT_CALL(listener, OnSocketEvent(_, read_fd_, kSocketEventReadable)) .WillOnce([this]() { ASSERT_TRUE(loop_.UnregisterSocket(write_fd_)); }); EXPECT_CALL(listener, OnSocketEvent(_, write_fd_, kSocketEventWritable)) .Times(0); ASSERT_TRUE(loop_.ArtificiallyNotifyEvent(read_fd_, kSocketEventReadable)); loop_.RunEventLoopOnce(QuicTime::Delta::FromMilliseconds(1)); } TEST_F(QuicPollEventLoopTest, EintrHandler) { testing::StrictMock<MockQuicSocketEventListener> listener; ASSERT_TRUE(loop_.RegisterSocket(read_fd_, kAllEvents, &listener)); loop_.TriggerEintrAfter(QuicTime::Delta::FromMilliseconds(25)); loop_.RunEventLoopOnce(QuicTime::Delta::FromMilliseconds(100)); EXPECT_THAT(loop_.timeouts(), ElementsAre(100, 75)); } TEST_F(QuicPollEventLoopTest, PollReturnsEarly) { testing::StrictMock<MockQuicSocketEventListener> listener; ASSERT_TRUE(loop_.RegisterSocket(read_fd_, kAllEvents, &listener)); loop_.ReturnFromPollAfter(QuicTime::Delta::FromMilliseconds(25)); loop_.RunEventLoopOnce(QuicTime::Delta::FromMilliseconds(100)); EXPECT_THAT(loop_.timeouts(), ElementsAre(100, 75)); } TEST_F(QuicPollEventLoopTest, AlarmInFuture) { EXPECT_EQ(ComputePollTimeout(), kDefaultTimeout); constexpr auto kAlarmTimeout = QuicTime::Delta::FromMilliseconds(5); auto [alarm, delegate] = CreateAlarm(); EXPECT_EQ(ComputePollTimeout(), kDefaultTimeout); alarm->Set(clock_.Now() + kAlarmTimeout); EXPECT_EQ(ComputePollTimeout(), kAlarmTimeout); EXPECT_CALL(*delegate, OnAlarm()); loop_.RunEventLoopOnce(QuicTime::Delta::FromMilliseconds(100)); EXPECT_EQ(ComputePollTimeout(), kDefaultTimeout); } TEST_F(QuicPollEventLoopTest, AlarmsInPast) { EXPECT_EQ(ComputePollTimeout(), kDefaultTimeout); constexpr auto kAlarmTimeout = QuicTime::Delta::FromMilliseconds(5); auto [alarm1, delegate1] = CreateAlarm(); auto [alarm2, delegate2] = CreateAlarm(); alarm1->Set(clock_.Now() - 2 * kAlarmTimeout); alarm2->Set(clock_.Now() - kAlarmTimeout); { testing::InSequence s; EXPECT_CALL(*delegate1, OnAlarm()); EXPECT_CALL(*delegate2, OnAlarm()); } loop_.RunEventLoopOnce(QuicTime::Delta::FromMilliseconds(100)); } TEST_F(QuicPollEventLoopTest, AlarmCancelled) { EXPECT_EQ(ComputePollTimeout(), kDefaultTimeout); constexpr auto kAlarmTimeout = QuicTime::Delta::FromMilliseconds(5); auto [alarm, delegate] = CreateAlarm(); EXPECT_EQ(ComputePollTimeout(), kDefaultTimeout); alarm->Set(clock_.Now() + kAlarmTimeout); alarm->Cancel(); alarm->Set(clock_.Now() + 2 * kAlarmTimeout); EXPECT_EQ(ComputePollTimeout(), kAlarmTimeout); EXPECT_CALL(*delegate, OnAlarm()); loop_.RunEventLoopOnce(QuicTime::Delta::FromMilliseconds(100)); EXPECT_THAT(loop_.timeouts(), ElementsAre(10)); EXPECT_EQ(ComputePollTimeout(), kDefaultTimeout); } TEST_F(QuicPollEventLoopTest, AlarmCancelsAnotherAlarm) { EXPECT_EQ(ComputePollTimeout(), kDefaultTimeout); constexpr auto kAlarmTimeout = QuicTime::Delta::FromMilliseconds(5); auto [alarm1_ptr, delegate1] = CreateAlarm(); auto [alarm2_ptr, delegate2] = CreateAlarm(); QuicAlarm& alarm1 = *alarm1_ptr; QuicAlarm& alarm2 = *alarm2_ptr; alarm1.Set(clock_.Now() - kAlarmTimeout); alarm2.Set(clock_.Now() - kAlarmTimeout); int alarms_called = 0; EXPECT_CALL(*delegate1, OnAlarm()).Times(AtMost(1)).WillOnce([&]() { alarm2.Cancel(); ++alarms_called; }); EXPECT_CALL(*delegate2, OnAlarm()).Times(AtMost(1)).WillOnce([&]() { alarm1.Cancel(); ++alarms_called; }); loop_.RunEventLoopOnce(QuicTime::Delta::FromMilliseconds(100)); EXPECT_EQ(alarms_called, 1); EXPECT_EQ(ComputePollTimeout(), kDefaultTimeout); } } }
368
cpp
google/quiche
moqt_framer
quiche/quic/moqt/moqt_framer.cc
quiche/quic/moqt/moqt_framer_test.cc
#ifndef QUICHE_QUIC_MOQT_MOQT_FRAMER_H_ #define QUICHE_QUIC_MOQT_MOQT_FRAMER_H_ #include "absl/strings/string_view.h" #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/quiche_buffer_allocator.h" namespace moqt { class QUICHE_EXPORT MoqtFramer { public: MoqtFramer(quiche::QuicheBufferAllocator* allocator, bool using_webtrans) : allocator_(allocator), using_webtrans_(using_webtrans) {} quiche::QuicheBuffer SerializeObjectHeader(const MoqtObject& message, bool is_first_in_stream); quiche::QuicheBuffer SerializeObjectDatagram(const MoqtObject& message, absl::string_view payload); quiche::QuicheBuffer SerializeClientSetup(const MoqtClientSetup& message); quiche::QuicheBuffer SerializeServerSetup(const MoqtServerSetup& message); quiche::QuicheBuffer SerializeSubscribe(const MoqtSubscribe& message); quiche::QuicheBuffer SerializeSubscribeOk(const MoqtSubscribeOk& message); quiche::QuicheBuffer SerializeSubscribeError( const MoqtSubscribeError& message); quiche::QuicheBuffer SerializeUnsubscribe(const MoqtUnsubscribe& message); quiche::QuicheBuffer SerializeSubscribeDone(const MoqtSubscribeDone& message); quiche::QuicheBuffer SerializeSubscribeUpdate( const MoqtSubscribeUpdate& message); quiche::QuicheBuffer SerializeAnnounce(const MoqtAnnounce& message); quiche::QuicheBuffer SerializeAnnounceOk(const MoqtAnnounceOk& message); quiche::QuicheBuffer SerializeAnnounceError(const MoqtAnnounceError& message); quiche::QuicheBuffer SerializeAnnounceCancel( const MoqtAnnounceCancel& message); quiche::QuicheBuffer SerializeTrackStatusRequest( const MoqtTrackStatusRequest& message); quiche::QuicheBuffer SerializeUnannounce(const MoqtUnannounce& message); quiche::QuicheBuffer SerializeTrackStatus(const MoqtTrackStatus& message); quiche::QuicheBuffer SerializeGoAway(const MoqtGoAway& message); private: quiche::QuicheBufferAllocator* allocator_; bool using_webtrans_; }; } #endif #include "quiche/quic/moqt/moqt_framer.h" #include <cstddef> #include <cstdint> #include <cstdlib> #include <optional> #include <type_traits> #include <utility> #include "absl/container/inlined_vector.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/quiche_buffer_allocator.h" #include "quiche/common/quiche_data_writer.h" #include "quiche/common/simple_buffer_allocator.h" #include "quiche/common/wire_serialization.h" namespace moqt { namespace { using ::quiche::QuicheBuffer; using ::quiche::WireBytes; using ::quiche::WireOptional; using ::quiche::WireSpan; using ::quiche::WireStringWithVarInt62Length; using ::quiche::WireUint8; using ::quiche::WireVarInt62; struct StringParameter { template <typename Enum> StringParameter(Enum type, absl::string_view data) : type(static_cast<uint64_t>(type)), data(data) { static_assert(std::is_enum_v<Enum>); } uint64_t type; absl::string_view data; }; class WireStringParameter { public: using DataType = StringParameter; explicit WireStringParameter(const StringParameter& parameter) : parameter_(parameter) {} size_t GetLengthOnWire() { return quiche::ComputeLengthOnWire( WireVarInt62(parameter_.type), WireStringWithVarInt62Length(parameter_.data)); } absl::Status SerializeIntoWriter(quiche::QuicheDataWriter& writer) { return quiche::SerializeIntoWriter( writer, WireVarInt62(parameter_.type), WireStringWithVarInt62Length(parameter_.data)); } private: const StringParameter& parameter_; }; struct IntParameter { template <typename Enum, typename Param> IntParameter(Enum type, Param value) : type(static_cast<uint64_t>(type)), value(static_cast<uint64_t>(value)) { static_assert(std::is_enum_v<Enum>); static_assert(std::is_enum_v<Param> || std::is_unsigned_v<Param>); } uint64_t type; uint64_t value; }; class WireIntParameter { public: using DataType = IntParameter; explicit WireIntParameter(const IntParameter& parameter) : parameter_(parameter) {} size_t GetLengthOnWire() { return quiche::ComputeLengthOnWire( WireVarInt62(parameter_.type), WireVarInt62(NeededVarIntLen(parameter_.value)), WireVarInt62(parameter_.value)); } absl::Status SerializeIntoWriter(quiche::QuicheDataWriter& writer) { return quiche::SerializeIntoWriter( writer, WireVarInt62(parameter_.type), WireVarInt62(NeededVarIntLen(parameter_.value)), WireVarInt62(parameter_.value)); } private: size_t NeededVarIntLen(const uint64_t value) { return static_cast<size_t>(quic::QuicDataWriter::GetVarInt62Len(value)); } const IntParameter& parameter_; }; template <typename... Ts> QuicheBuffer Serialize(Ts... data) { absl::StatusOr<QuicheBuffer> buffer = quiche::SerializeIntoBuffer( quiche::SimpleBufferAllocator::Get(), data...); if (!buffer.ok()) { QUICHE_BUG(moqt_failed_serialization) << "Failed to serialize MoQT frame: " << buffer.status(); return QuicheBuffer(); } return *std::move(buffer); } } quiche::QuicheBuffer MoqtFramer::SerializeObjectHeader( const MoqtObject& message, bool is_first_in_stream) { if (!message.payload_length.has_value() && !(message.forwarding_preference == MoqtForwardingPreference::kObject || message.forwarding_preference == MoqtForwardingPreference::kDatagram)) { QUIC_BUG(quic_bug_serialize_object_input_01) << "Track or Group forwarding preference requires knowing the object " "length in advance"; return quiche::QuicheBuffer(); } if (message.object_status != MoqtObjectStatus::kNormal && message.payload_length.has_value() && *message.payload_length > 0) { QUIC_BUG(quic_bug_serialize_object_input_03) << "Object status must be kNormal if payload is non-empty"; return quiche::QuicheBuffer(); } if (!is_first_in_stream) { switch (message.forwarding_preference) { case MoqtForwardingPreference::kTrack: return (*message.payload_length == 0) ? Serialize(WireVarInt62(message.group_id), WireVarInt62(message.object_id), WireVarInt62(*message.payload_length), WireVarInt62(message.object_status)) : Serialize(WireVarInt62(message.group_id), WireVarInt62(message.object_id), WireVarInt62(*message.payload_length)); case MoqtForwardingPreference::kGroup: return (*message.payload_length == 0) ? Serialize(WireVarInt62(message.object_id), WireVarInt62(*message.payload_length), WireVarInt62(static_cast<uint64_t>( message.object_status))) : Serialize(WireVarInt62(message.object_id), WireVarInt62(*message.payload_length)); default: QUIC_BUG(quic_bug_serialize_object_input_02) << "Object or Datagram forwarding_preference must be first in " "stream"; return quiche::QuicheBuffer(); } } MoqtMessageType message_type = GetMessageTypeForForwardingPreference(message.forwarding_preference); switch (message.forwarding_preference) { case MoqtForwardingPreference::kTrack: return (*message.payload_length == 0) ? Serialize(WireVarInt62(message_type), WireVarInt62(message.subscribe_id), WireVarInt62(message.track_alias), WireVarInt62(message.object_send_order), WireVarInt62(message.group_id), WireVarInt62(message.object_id), WireVarInt62(*message.payload_length), WireVarInt62(message.object_status)) : Serialize(WireVarInt62(message_type), WireVarInt62(message.subscribe_id), WireVarInt62(message.track_alias), WireVarInt62(message.object_send_order), WireVarInt62(message.group_id), WireVarInt62(message.object_id), WireVarInt62(*message.payload_length)); case MoqtForwardingPreference::kGroup: return (*message.payload_length == 0) ? Serialize(WireVarInt62(message_type), WireVarInt62(message.subscribe_id), WireVarInt62(message.track_alias), WireVarInt62(message.group_id), WireVarInt62(message.object_send_order), WireVarInt62(message.object_id), WireVarInt62(*message.payload_length), WireVarInt62(message.object_status)) : Serialize(WireVarInt62(message_type), WireVarInt62(message.subscribe_id), WireVarInt62(message.track_alias), WireVarInt62(message.group_id), WireVarInt62(message.object_send_order), WireVarInt62(message.object_id), WireVarInt62(*message.payload_length)); case MoqtForwardingPreference::kObject: case MoqtForwardingPreference::kDatagram: return Serialize( WireVarInt62(message_type), WireVarInt62(message.subscribe_id), WireVarInt62(message.track_alias), WireVarInt62(message.group_id), WireVarInt62(message.object_id), WireVarInt62(message.object_send_order), WireVarInt62(message.object_status)); } } quiche::QuicheBuffer MoqtFramer::SerializeObjectDatagram( const MoqtObject& message, absl::string_view payload) { if (message.object_status != MoqtObjectStatus::kNormal && !payload.empty()) { QUIC_BUG(quic_bug_serialize_object_datagram_01) << "Object status must be kNormal if payload is non-empty"; return quiche::QuicheBuffer(); } return Serialize( WireVarInt62(MoqtMessageType::kObjectDatagram), WireVarInt62(message.subscribe_id), WireVarInt62(message.track_alias), WireVarInt62(message.group_id), WireVarInt62(message.object_id), WireVarInt62(message.object_send_order), WireVarInt62(static_cast<uint64_t>(message.object_status)), WireBytes(payload)); } quiche::QuicheBuffer MoqtFramer::SerializeClientSetup( const MoqtClientSetup& message) { absl::InlinedVector<IntParameter, 1> int_parameters; absl::InlinedVector<StringParameter, 1> string_parameters; if (message.role.has_value()) { int_parameters.push_back( IntParameter(MoqtSetupParameter::kRole, *message.role)); } if (!using_webtrans_ && message.path.has_value()) { string_parameters.push_back( StringParameter(MoqtSetupParameter::kPath, *message.path)); } return Serialize( WireVarInt62(MoqtMessageType::kClientSetup), WireVarInt62(message.supported_versions.size()), WireSpan<WireVarInt62, MoqtVersion>(message.supported_versions), WireVarInt62(string_parameters.size() + int_parameters.size()), WireSpan<WireIntParameter>(int_parameters), WireSpan<WireStringParameter>(string_parameters)); } quiche::QuicheBuffer MoqtFramer::SerializeServerSetup( const MoqtServerSetup& message) { absl::InlinedVector<IntParameter, 1> int_parameters; if (message.role.has_value()) { int_parameters.push_back( IntParameter(MoqtSetupParameter::kRole, *message.role)); } return Serialize(WireVarInt62(MoqtMessageType::kServerSetup), WireVarInt62(message.selected_version), WireVarInt62(int_parameters.size()), WireSpan<WireIntParameter>(int_parameters)); } quiche::QuicheBuffer MoqtFramer::SerializeSubscribe( const MoqtSubscribe& message) { MoqtFilterType filter_type = GetFilterType(message); if (filter_type == MoqtFilterType::kNone) { QUICHE_BUG(MoqtFramer_invalid_subscribe) << "Invalid object range"; return quiche::QuicheBuffer(); } absl::InlinedVector<StringParameter, 1> string_params; if (message.authorization_info.has_value()) { string_params.push_back( StringParameter(MoqtTrackRequestParameter::kAuthorizationInfo, *message.authorization_info)); } switch (filter_type) { case MoqtFilterType::kLatestGroup: case MoqtFilterType::kLatestObject: return Serialize( WireVarInt62(MoqtMessageType::kSubscribe), WireVarInt62(message.subscribe_id), WireVarInt62(message.track_alias), WireStringWithVarInt62Length(message.track_namespace), WireStringWithVarInt62Length(message.track_name), WireVarInt62(filter_type), WireVarInt62(string_params.size()), WireSpan<WireStringParameter>(string_params)); case MoqtFilterType::kAbsoluteStart: return Serialize( WireVarInt62(MoqtMessageType::kSubscribe), WireVarInt62(message.subscribe_id), WireVarInt62(message.track_alias), WireStringWithVarInt62Length(message.track_namespace), WireStringWithVarInt62Length(message.track_name), WireVarInt62(filter_type), WireVarInt62(*message.start_group), WireVarInt62(*message.start_object), WireVarInt62(string_params.size()), WireSpan<WireStringParameter>(string_params)); case MoqtFilterType::kAbsoluteRange: return Serialize( WireVarInt62(MoqtMessageType::kSubscribe), WireVarInt62(message.subscribe_id), WireVarInt62(message.track_alias), WireStringWithVarInt62Length(message.track_namespace), WireStringWithVarInt62Length(message.track_name), WireVarInt62(filter_type), WireVarInt62(*message.start_group), WireVarInt62(*message.start_object), WireVarInt62(*message.end_group), WireVarInt62(message.end_object.has_value() ? *message.end_object + 1 : 0), WireVarInt62(string_params.size()), WireSpan<WireStringParameter>(string_params)); default: QUICHE_BUG(MoqtFramer_end_group_missing) << "Subscribe framing error."; return quiche::QuicheBuffer(); } } quiche::QuicheBuffer MoqtFramer::SerializeSubscribeOk( const MoqtSubscribeOk& message) { if (message.largest_id.has_value()) { return Serialize(WireVarInt62(MoqtMessageType::kSubscribeOk), WireVarInt62(message.subscribe_id), WireVarInt62(message.expires.ToMilliseconds()), WireUint8(1), WireVarInt62(message.largest_id->group), WireVarInt62(message.largest_id->object)); } return Serialize(WireVarInt62(MoqtMessageType::kSubscribeOk), WireVarInt62(message.subscribe_id), WireVarInt62(message.expires.ToMilliseconds()), WireUint8(0)); } quiche::QuicheBuffer MoqtFramer::SerializeSubscribeError( const MoqtSubscribeError& message) { return Serialize(WireVarInt62(MoqtMessageType::kSubscribeError), WireVarInt62(message.subscribe_id), WireVarInt62(message.error_code), WireStringWithVarInt62Length(message.reason_phrase), WireVarInt62(message.track_alias)); } quiche::QuicheBuffer MoqtFramer::SerializeUnsubscribe( const MoqtUnsubscribe& message) { return Serialize(WireVarInt62(MoqtMessageType::kUnsubscribe), WireVarInt62(message.subscribe_id)); } quiche::QuicheBuffer MoqtFramer::SerializeSubscribeDone( const MoqtSubscribeDone& message) { if (message.final_id.has_value()) { return Serialize(WireVarInt62(MoqtMessageType::kSubscribeDone), WireVarInt62(message.subscribe_id), WireVarInt62(message.status_code), WireStringWithVarInt62Length(message.reason_phrase), WireUint8(1), WireVarInt62(message.final_id->group), WireVarInt62(message.final_id->object)); } return Serialize( WireVarInt62(MoqtMessageType::kSubscribeDone), WireVarInt62(message.subscribe_id), WireVarInt62(message.status_code), WireStringWithVarInt62Length(message.reason_phrase), WireUint8(0)); } quiche::QuicheBuffer MoqtFramer::SerializeSubscribeUpdate( const MoqtSubscribeUpdate& message) { uint64_t end_group = message.end_group.has_value() ? *message.end_group + 1 : 0; uint64_t end_object = message.end_object.has_value() ? *message.end_object + 1 : 0; if (end_group == 0 && end_object != 0) { QUICHE_BUG(MoqtFramer_invalid_subscribe_update) << "Invalid object range"; return quiche::QuicheBuffer(); } absl::InlinedVector<StringParameter, 1> string_params; if (message.authorization_info.has_value()) { string_params.push_back( StringParameter(MoqtTrackRequestParameter::kAuthorizationInfo, *message.authorization_info)); } return Serialize( WireVarInt62(MoqtMessageType::kSubscribeUpdate), WireVarInt62(message.subscribe_id), WireVarInt62(message.start_group), WireVarInt62(message.start_object), WireVarInt62(end_group), WireVarInt62(end_object), WireSpan<WireStringParameter>(string_params)); } quiche::QuicheBuffer MoqtFramer::SerializeAnnounce( const MoqtAnnounce& message) { absl::InlinedVector<StringParameter, 1> string_params; if (message.authorization_info.has_value()) { string_params.push_back( StringParameter(MoqtTrackRequestParameter::kAuthorizationInfo, *message.authorization_info)); } return Serialize( WireVarInt62(static_cast<uint64_t>(MoqtMessageType::kAnnounce)), WireStringWithVarInt62Length(message.track_namespace), WireVarInt62(string_params.size()), WireSpan<WireStringParameter>(string_params)); } quiche::QuicheBuffer MoqtFramer::SerializeAnnounceOk( const MoqtAnnounceOk& message) { return Serialize(WireVarInt62(MoqtMessageType::kAnnounceOk), WireStringWithVarInt62Length(message.track_namespace)); } quiche::QuicheBuffer MoqtFramer::SerializeAnnounceError( const MoqtAnnounceError& message) { return Serialize(WireVarInt62(MoqtMessageType::kAnnounceError), WireStringWithVarInt62Length(message.track_namespace), WireVarInt62(message.error_code), WireStringWithVarInt62Length(message.reason_phrase)); } quiche::QuicheBuffer MoqtFramer::SerializeAnnounceCancel( const MoqtAnnounceCancel& message) { return Serialize(WireVarInt62(MoqtMessageType::kAnnounceCancel), WireStringWithVarInt62Length(message.track_namespace)); } quiche::QuicheBuffer MoqtFramer::SerializeTrackStatusRequest( const MoqtTrackStatusRequest& message) { return Serialize(WireVarInt62(MoqtMessageType::kTrackStatusRequest), WireStringWithVarInt62Length(message.track_namespace), WireStringWithVarInt62Length(message.track_name)); } quiche::QuicheBuffer MoqtFramer::SerializeUnannounce( const MoqtUnannounce& message) { return Serialize(WireVarInt62(MoqtMessageType::kUnannounce), WireStringWithVarInt62Length(message.track_namespace)); } quiche::QuicheBuffer MoqtFramer::SerializeTrackStatus( const MoqtTrackStatus& message) { return Serialize(WireVarInt62(MoqtMessageType::kTrackStatus), WireStringWithVarInt62Length(message.track_namespace), WireStringWithVarInt62Length(message.track_name), WireVarInt62(message.status_code), WireVarInt62(message.last_group), WireVarInt62(message.last_object)); } quiche::QuicheBuffer MoqtFramer::SerializeGoAway(const MoqtGoAway& message) { return Serialize(WireVarInt62(MoqtMessageType::kGoAway), WireStringWithVarInt62Length(message.new_session_uri)); } }
#include "quiche/quic/moqt/moqt_framer.h" #include <cerrno> #include <cstddef> #include <cstdint> #include <memory> #include <optional> #include <string> #include <vector> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/quic/moqt/test_tools/moqt_test_message.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/common/quiche_buffer_allocator.h" #include "quiche/common/simple_buffer_allocator.h" namespace moqt::test { struct MoqtFramerTestParams { MoqtFramerTestParams(MoqtMessageType message_type, bool uses_web_transport) : message_type(message_type), uses_web_transport(uses_web_transport) {} MoqtMessageType message_type; bool uses_web_transport; }; std::vector<MoqtFramerTestParams> GetMoqtFramerTestParams() { std::vector<MoqtFramerTestParams> params; std::vector<MoqtMessageType> message_types = { MoqtMessageType::kObjectStream, MoqtMessageType::kSubscribe, MoqtMessageType::kSubscribeOk, MoqtMessageType::kSubscribeError, MoqtMessageType::kUnsubscribe, MoqtMessageType::kSubscribeDone, MoqtMessageType::kAnnounceCancel, MoqtMessageType::kTrackStatusRequest, MoqtMessageType::kTrackStatus, MoqtMessageType::kAnnounce, MoqtMessageType::kAnnounceOk, MoqtMessageType::kAnnounceError, MoqtMessageType::kUnannounce, MoqtMessageType::kGoAway, MoqtMessageType::kClientSetup, MoqtMessageType::kServerSetup, MoqtMessageType::kStreamHeaderTrack, MoqtMessageType::kStreamHeaderGroup, }; std::vector<bool> uses_web_transport_bool = { false, true, }; for (const MoqtMessageType message_type : message_types) { if (message_type == MoqtMessageType::kClientSetup) { for (const bool uses_web_transport : uses_web_transport_bool) { params.push_back( MoqtFramerTestParams(message_type, uses_web_transport)); } } else { params.push_back(MoqtFramerTestParams(message_type, true)); } } return params; } std::string ParamNameFormatter( const testing::TestParamInfo<MoqtFramerTestParams>& info) { return MoqtMessageTypeToString(info.param.message_type) + "_" + (info.param.uses_web_transport ? "WebTransport" : "QUIC"); } quiche::QuicheBuffer SerializeObject(MoqtFramer& framer, const MoqtObject& message, absl::string_view payload, bool is_first_in_stream) { MoqtObject adjusted_message = message; adjusted_message.payload_length = payload.size(); quiche::QuicheBuffer header = framer.SerializeObjectHeader(adjusted_message, is_first_in_stream); if (header.empty()) { return quiche::QuicheBuffer(); } return quiche::QuicheBuffer::Copy( quiche::SimpleBufferAllocator::Get(), absl::StrCat(header.AsStringView(), payload)); } class MoqtFramerTest : public quic::test::QuicTestWithParam<MoqtFramerTestParams> { public: MoqtFramerTest() : message_type_(GetParam().message_type), webtrans_(GetParam().uses_web_transport), buffer_allocator_(quiche::SimpleBufferAllocator::Get()), framer_(buffer_allocator_, GetParam().uses_web_transport) {} std::unique_ptr<TestMessageBase> MakeMessage(MoqtMessageType message_type) { return CreateTestMessage(message_type, webtrans_); } quiche::QuicheBuffer SerializeMessage( TestMessageBase::MessageStructuredData& structured_data) { switch (message_type_) { case MoqtMessageType::kObjectStream: case MoqtMessageType::kStreamHeaderTrack: case MoqtMessageType::kStreamHeaderGroup: { MoqtObject data = std::get<MoqtObject>(structured_data); return SerializeObject(framer_, data, "foo", true); } case MoqtMessageType::kSubscribe: { auto data = std::get<MoqtSubscribe>(structured_data); return framer_.SerializeSubscribe(data); } case MoqtMessageType::kSubscribeOk: { auto data = std::get<MoqtSubscribeOk>(structured_data); return framer_.SerializeSubscribeOk(data); } case MoqtMessageType::kSubscribeError: { auto data = std::get<MoqtSubscribeError>(structured_data); return framer_.SerializeSubscribeError(data); } case MoqtMessageType::kUnsubscribe: { auto data = std::get<MoqtUnsubscribe>(structured_data); return framer_.SerializeUnsubscribe(data); } case MoqtMessageType::kSubscribeDone: { auto data = std::get<MoqtSubscribeDone>(structured_data); return framer_.SerializeSubscribeDone(data); } case MoqtMessageType::kAnnounce: { auto data = std::get<MoqtAnnounce>(structured_data); return framer_.SerializeAnnounce(data); } case moqt::MoqtMessageType::kAnnounceOk: { auto data = std::get<MoqtAnnounceOk>(structured_data); return framer_.SerializeAnnounceOk(data); } case moqt::MoqtMessageType::kAnnounceError: { auto data = std::get<MoqtAnnounceError>(structured_data); return framer_.SerializeAnnounceError(data); } case moqt::MoqtMessageType::kAnnounceCancel: { auto data = std::get<MoqtAnnounceCancel>(structured_data); return framer_.SerializeAnnounceCancel(data); } case moqt::MoqtMessageType::kTrackStatusRequest: { auto data = std::get<MoqtTrackStatusRequest>(structured_data); return framer_.SerializeTrackStatusRequest(data); } case MoqtMessageType::kUnannounce: { auto data = std::get<MoqtUnannounce>(structured_data); return framer_.SerializeUnannounce(data); } case moqt::MoqtMessageType::kTrackStatus: { auto data = std::get<MoqtTrackStatus>(structured_data); return framer_.SerializeTrackStatus(data); } case moqt::MoqtMessageType::kGoAway: { auto data = std::get<MoqtGoAway>(structured_data); return framer_.SerializeGoAway(data); } case MoqtMessageType::kClientSetup: { auto data = std::get<MoqtClientSetup>(structured_data); return framer_.SerializeClientSetup(data); } case MoqtMessageType::kServerSetup: { auto data = std::get<MoqtServerSetup>(structured_data); return framer_.SerializeServerSetup(data); } default: return quiche::QuicheBuffer(); } } MoqtMessageType message_type_; bool webtrans_; quiche::SimpleBufferAllocator* buffer_allocator_; MoqtFramer framer_; }; INSTANTIATE_TEST_SUITE_P(MoqtFramerTests, MoqtFramerTest, testing::ValuesIn(GetMoqtFramerTestParams()), ParamNameFormatter); TEST_P(MoqtFramerTest, OneMessage) { auto message = MakeMessage(message_type_); auto structured_data = message->structured_data(); auto buffer = SerializeMessage(structured_data); EXPECT_EQ(buffer.size(), message->total_message_size()); EXPECT_EQ(buffer.AsStringView(), message->PacketSample()); } class MoqtFramerSimpleTest : public quic::test::QuicTest { public: MoqtFramerSimpleTest() : buffer_allocator_(quiche::SimpleBufferAllocator::Get()), framer_(buffer_allocator_, true) {} quiche::SimpleBufferAllocator* buffer_allocator_; MoqtFramer framer_; const uint8_t* BufferAtOffset(quiche::QuicheBuffer& buffer, size_t offset) { const char* data = buffer.data(); return reinterpret_cast<const uint8_t*>(data + offset); } }; TEST_F(MoqtFramerSimpleTest, GroupMiddler) { auto header = std::make_unique<StreamHeaderGroupMessage>(); auto buffer1 = SerializeObject( framer_, std::get<MoqtObject>(header->structured_data()), "foo", true); EXPECT_EQ(buffer1.size(), header->total_message_size()); EXPECT_EQ(buffer1.AsStringView(), header->PacketSample()); auto middler = std::make_unique<StreamMiddlerGroupMessage>(); auto buffer2 = SerializeObject( framer_, std::get<MoqtObject>(middler->structured_data()), "bar", false); EXPECT_EQ(buffer2.size(), middler->total_message_size()); EXPECT_EQ(buffer2.AsStringView(), middler->PacketSample()); } TEST_F(MoqtFramerSimpleTest, TrackMiddler) { auto header = std::make_unique<StreamHeaderTrackMessage>(); auto buffer1 = SerializeObject( framer_, std::get<MoqtObject>(header->structured_data()), "foo", true); EXPECT_EQ(buffer1.size(), header->total_message_size()); EXPECT_EQ(buffer1.AsStringView(), header->PacketSample()); auto middler = std::make_unique<StreamMiddlerTrackMessage>(); auto buffer2 = SerializeObject( framer_, std::get<MoqtObject>(middler->structured_data()), "bar", false); EXPECT_EQ(buffer2.size(), middler->total_message_size()); EXPECT_EQ(buffer2.AsStringView(), middler->PacketSample()); } TEST_F(MoqtFramerSimpleTest, BadObjectInput) { MoqtObject object = { 3, 4, 5, 6, 7, MoqtObjectStatus::kNormal, MoqtForwardingPreference::kObject, std::nullopt, }; quiche::QuicheBuffer buffer; object.forwarding_preference = MoqtForwardingPreference::kDatagram; EXPECT_QUIC_BUG(buffer = framer_.SerializeObjectHeader(object, false), "must be first"); EXPECT_TRUE(buffer.empty()); object.forwarding_preference = MoqtForwardingPreference::kGroup; EXPECT_QUIC_BUG(buffer = framer_.SerializeObjectHeader(object, false), "requires knowing the object length"); EXPECT_TRUE(buffer.empty()); object.payload_length = 5; object.object_status = MoqtObjectStatus::kEndOfGroup; EXPECT_QUIC_BUG(buffer = framer_.SerializeObjectHeader(object, false), "Object status must be kNormal if payload is non-empty"); EXPECT_TRUE(buffer.empty()); } TEST_F(MoqtFramerSimpleTest, Datagram) { auto datagram = std::make_unique<ObjectDatagramMessage>(); MoqtObject object = { 3, 4, 5, 6, 7, MoqtObjectStatus::kNormal, MoqtForwardingPreference::kObject, std::nullopt, }; std::string payload = "foo"; quiche::QuicheBuffer buffer; buffer = framer_.SerializeObjectDatagram(object, payload); EXPECT_EQ(buffer.size(), datagram->total_message_size()); EXPECT_EQ(buffer.AsStringView(), datagram->PacketSample()); } TEST_F(MoqtFramerSimpleTest, AllSubscribeInputs) { for (std::optional<uint64_t> start_group : {std::optional<uint64_t>(), std::optional<uint64_t>(4)}) { for (std::optional<uint64_t> start_object : {std::optional<uint64_t>(), std::optional<uint64_t>(0)}) { for (std::optional<uint64_t> end_group : {std::optional<uint64_t>(), std::optional<uint64_t>(7)}) { for (std::optional<uint64_t> end_object : {std::optional<uint64_t>(), std::optional<uint64_t>(3)}) { MoqtSubscribe subscribe = { 3, 4, "foo", "abcd", start_group, start_object, end_group, end_object, "bar", }; quiche::QuicheBuffer buffer; MoqtFilterType expected_filter_type = MoqtFilterType::kNone; if (!start_group.has_value() && !start_object.has_value() && !end_group.has_value() && !end_object.has_value()) { expected_filter_type = MoqtFilterType::kLatestObject; } else if (!start_group.has_value() && start_object.has_value() && *start_object == 0 && !end_group.has_value() && !end_object.has_value()) { expected_filter_type = MoqtFilterType::kLatestGroup; } else if (start_group.has_value() && start_object.has_value() && !end_group.has_value() && !end_object.has_value()) { expected_filter_type = MoqtFilterType::kAbsoluteStart; } else if (start_group.has_value() && start_object.has_value() && end_group.has_value()) { expected_filter_type = MoqtFilterType::kAbsoluteRange; } if (expected_filter_type == MoqtFilterType::kNone) { EXPECT_QUIC_BUG(buffer = framer_.SerializeSubscribe(subscribe), "Invalid object range"); EXPECT_EQ(buffer.size(), 0); continue; } buffer = framer_.SerializeSubscribe(subscribe); const uint8_t* read = BufferAtOffset(buffer, 12); EXPECT_EQ(static_cast<MoqtFilterType>(*read), expected_filter_type); EXPECT_GT(buffer.size(), 0); if (expected_filter_type == MoqtFilterType::kAbsoluteRange && end_object.has_value()) { const uint8_t* object_id = read + 4; EXPECT_EQ(*object_id, *end_object + 1); } } } } } } TEST_F(MoqtFramerSimpleTest, SubscribeEndBeforeStart) { MoqtSubscribe subscribe = { 3, 4, "foo", "abcd", std::optional<uint64_t>(4), std::optional<uint64_t>(3), std::optional<uint64_t>(3), std::nullopt, "bar", }; quiche::QuicheBuffer buffer; EXPECT_QUIC_BUG(buffer = framer_.SerializeSubscribe(subscribe), "Invalid object range"); EXPECT_EQ(buffer.size(), 0); subscribe.end_group = 4; subscribe.end_object = 1; EXPECT_QUIC_BUG(buffer = framer_.SerializeSubscribe(subscribe), "Invalid object range"); EXPECT_EQ(buffer.size(), 0); } TEST_F(MoqtFramerSimpleTest, SubscribeLatestGroupNonzeroObject) { MoqtSubscribe subscribe = { 3, 4, "foo", "abcd", std::nullopt, std::optional<uint64_t>(3), std::nullopt, std::nullopt, "bar", }; quiche::QuicheBuffer buffer; EXPECT_QUIC_BUG(buffer = framer_.SerializeSubscribe(subscribe), "Invalid object range"); EXPECT_EQ(buffer.size(), 0); } TEST_F(MoqtFramerSimpleTest, SubscribeUpdateEndGroupOnly) { MoqtSubscribeUpdate subscribe_update = { 3, 4, 3, 4, std::nullopt, "bar", }; quiche::QuicheBuffer buffer; buffer = framer_.SerializeSubscribeUpdate(subscribe_update); EXPECT_GT(buffer.size(), 0); const uint8_t* end_group = BufferAtOffset(buffer, 4); EXPECT_EQ(*end_group, 5); const uint8_t* end_object = end_group + 1; EXPECT_EQ(*end_object, 0); } TEST_F(MoqtFramerSimpleTest, SubscribeUpdateIncrementsEnd) { MoqtSubscribeUpdate subscribe_update = { 3, 4, 3, 4, 6, "bar", }; quiche::QuicheBuffer buffer; buffer = framer_.SerializeSubscribeUpdate(subscribe_update); EXPECT_GT(buffer.size(), 0); const uint8_t* end_group = BufferAtOffset(buffer, 4); EXPECT_EQ(*end_group, 5); const uint8_t* end_object = end_group + 1; EXPECT_EQ(*end_object, 7); } TEST_F(MoqtFramerSimpleTest, SubscribeUpdateInvalidRange) { MoqtSubscribeUpdate subscribe_update = { 3, 4, 3, std::nullopt, 6, "bar", }; quiche::QuicheBuffer buffer; EXPECT_QUIC_BUG(buffer = framer_.SerializeSubscribeUpdate(subscribe_update), "Invalid object range"); EXPECT_EQ(buffer.size(), 0); } }
369
cpp
google/quiche
moqt_track
quiche/quic/moqt/moqt_track.cc
quiche/quic/moqt/moqt_track_test.cc
#ifndef QUICHE_QUIC_MOQT_MOQT_SUBSCRIPTION_H_ #define QUICHE_QUIC_MOQT_MOQT_SUBSCRIPTION_H_ #include <cstdint> #include <optional> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/quic/moqt/moqt_subscribe_windows.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/common/quiche_callbacks.h" namespace moqt { class LocalTrack { public: class Visitor { public: virtual ~Visitor() = default; using PublishPastObjectsCallback = quiche::SingleUseCallback<void()>; virtual absl::StatusOr<PublishPastObjectsCallback> OnSubscribeForPast( const SubscribeWindow& window) = 0; }; LocalTrack(const FullTrackName& full_track_name, MoqtForwardingPreference forwarding_preference, Visitor* visitor) : full_track_name_(full_track_name), forwarding_preference_(forwarding_preference), windows_(forwarding_preference), visitor_(visitor) {} LocalTrack(const FullTrackName& full_track_name, MoqtForwardingPreference forwarding_preference, Visitor* visitor, FullSequence next_sequence) : full_track_name_(full_track_name), forwarding_preference_(forwarding_preference), windows_(forwarding_preference), next_sequence_(next_sequence), visitor_(visitor) {} const FullTrackName& full_track_name() const { return full_track_name_; } std::optional<uint64_t> track_alias() const { return track_alias_; } void set_track_alias(uint64_t track_alias) { track_alias_ = track_alias; } Visitor* visitor() { return visitor_; } std::vector<SubscribeWindow*> ShouldSend(FullSequence sequence) { return windows_.SequenceIsSubscribed(sequence); } void AddWindow(uint64_t subscribe_id, uint64_t start_group, uint64_t start_object); void AddWindow(uint64_t subscribe_id, uint64_t start_group, uint64_t start_object, uint64_t end_group); void AddWindow(uint64_t subscribe_id, uint64_t start_group, uint64_t start_object, uint64_t end_group, uint64_t end_object); void DeleteWindow(uint64_t subscribe_id) { windows_.RemoveWindow(subscribe_id); } const FullSequence& next_sequence() const { return next_sequence_; } void SentSequence(FullSequence sequence, MoqtObjectStatus status); bool HasSubscriber() const { return !windows_.IsEmpty(); } SubscribeWindow* GetWindow(uint64_t subscribe_id) { return windows_.GetWindow(subscribe_id); } MoqtForwardingPreference forwarding_preference() const { return forwarding_preference_; } void set_announce_cancel() { announce_canceled_ = true; } bool canceled() const { return announce_canceled_; } private: const FullTrackName full_track_name_; MoqtForwardingPreference forwarding_preference_; std::optional<uint64_t> track_alias_; MoqtSubscribeWindows windows_; FullSequence next_sequence_ = {0, 0}; absl::flat_hash_map<uint64_t, uint64_t> max_object_ids_; Visitor* visitor_; bool announce_canceled_ = false; }; class RemoteTrack { public: class Visitor { public: virtual ~Visitor() = default; virtual void OnReply( const FullTrackName& full_track_name, std::optional<absl::string_view> error_reason_phrase) = 0; virtual void OnObjectFragment( const FullTrackName& full_track_name, uint64_t group_sequence, uint64_t object_sequence, uint64_t object_send_order, MoqtObjectStatus object_status, MoqtForwardingPreference forwarding_preference, absl::string_view object, bool end_of_message) = 0; }; RemoteTrack(const FullTrackName& full_track_name, uint64_t track_alias, Visitor* visitor) : full_track_name_(full_track_name), track_alias_(track_alias), visitor_(visitor) {} const FullTrackName& full_track_name() { return full_track_name_; } uint64_t track_alias() const { return track_alias_; } Visitor* visitor() { return visitor_; } bool CheckForwardingPreference(MoqtForwardingPreference preference); private: const FullTrackName full_track_name_; const uint64_t track_alias_; Visitor* visitor_; std::optional<MoqtForwardingPreference> forwarding_preference_; }; } #endif #include "quiche/quic/moqt/moqt_track.h" #include <cstdint> #include "quiche/quic/moqt/moqt_messages.h" namespace moqt { void LocalTrack::AddWindow(uint64_t subscribe_id, uint64_t start_group, uint64_t start_object) { QUIC_BUG_IF(quic_bug_subscribe_to_canceled_track, announce_canceled_) << "Canceled track got subscription"; windows_.AddWindow(subscribe_id, next_sequence_, start_group, start_object); } void LocalTrack::AddWindow(uint64_t subscribe_id, uint64_t start_group, uint64_t start_object, uint64_t end_group) { QUIC_BUG_IF(quic_bug_subscribe_to_canceled_track, announce_canceled_) << "Canceled track got subscription"; auto it = max_object_ids_.find(end_group); if (end_group >= next_sequence_.group) { windows_.AddWindow(subscribe_id, next_sequence_, start_group, start_object, end_group, UINT64_MAX); return; } windows_.AddWindow(subscribe_id, next_sequence_, start_group, start_object, end_group, it->second); } void LocalTrack::AddWindow(uint64_t subscribe_id, uint64_t start_group, uint64_t start_object, uint64_t end_group, uint64_t end_object) { QUIC_BUG_IF(quic_bug_subscribe_to_canceled_track, announce_canceled_) << "Canceled track got subscription"; windows_.AddWindow(subscribe_id, next_sequence_, start_group, start_object, end_group, end_object); } void LocalTrack::SentSequence(FullSequence sequence, MoqtObjectStatus status) { QUICHE_DCHECK(max_object_ids_.find(sequence.group) == max_object_ids_.end() || max_object_ids_[sequence.group] < sequence.object); switch (status) { case MoqtObjectStatus::kNormal: case MoqtObjectStatus::kObjectDoesNotExist: if (next_sequence_ <= sequence) { next_sequence_ = sequence.next(); } break; case MoqtObjectStatus::kGroupDoesNotExist: max_object_ids_[sequence.group] = 0; break; case MoqtObjectStatus::kEndOfGroup: max_object_ids_[sequence.group] = sequence.object; if (next_sequence_ <= sequence) { next_sequence_ = FullSequence(sequence.group + 1, 0); } break; case MoqtObjectStatus::kEndOfTrack: max_object_ids_[sequence.group] = sequence.object; break; default: QUICHE_DCHECK(false); return; } } bool RemoteTrack::CheckForwardingPreference( MoqtForwardingPreference preference) { if (forwarding_preference_.has_value()) { return forwarding_preference_.value() == preference; } forwarding_preference_ = preference; return true; } }
#include "quiche/quic/moqt/moqt_track.h" #include <optional> #include "absl/strings/string_view.h" #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/quic/moqt/moqt_subscribe_windows.h" #include "quiche/quic/moqt/tools/moqt_mock_visitor.h" #include "quiche/quic/platform/api/quic_test.h" namespace moqt { namespace test { class LocalTrackTest : public quic::test::QuicTest { public: LocalTrackTest() : track_(FullTrackName("foo", "bar"), MoqtForwardingPreference::kTrack, &visitor_, FullSequence(4, 1)) {} LocalTrack track_; MockLocalTrackVisitor visitor_; }; TEST_F(LocalTrackTest, Queries) { EXPECT_EQ(track_.full_track_name(), FullTrackName("foo", "bar")); EXPECT_EQ(track_.track_alias(), std::nullopt); EXPECT_EQ(track_.visitor(), &visitor_); EXPECT_EQ(track_.next_sequence(), FullSequence(4, 1)); track_.SentSequence(FullSequence(4, 0), MoqtObjectStatus::kNormal); EXPECT_EQ(track_.next_sequence(), FullSequence(4, 1)); track_.SentSequence(FullSequence(4, 1), MoqtObjectStatus::kNormal); EXPECT_EQ(track_.next_sequence(), FullSequence(4, 2)); track_.SentSequence(FullSequence(4, 2), MoqtObjectStatus::kEndOfGroup); EXPECT_EQ(track_.next_sequence(), FullSequence(5, 0)); EXPECT_FALSE(track_.HasSubscriber()); EXPECT_EQ(track_.forwarding_preference(), MoqtForwardingPreference::kTrack); } TEST_F(LocalTrackTest, SetTrackAlias) { EXPECT_EQ(track_.track_alias(), std::nullopt); track_.set_track_alias(6); EXPECT_EQ(track_.track_alias(), 6); } TEST_F(LocalTrackTest, AddGetDeleteWindow) { track_.AddWindow(0, 4, 1); EXPECT_EQ(track_.GetWindow(0)->subscribe_id(), 0); EXPECT_EQ(track_.GetWindow(1), nullptr); track_.DeleteWindow(0); EXPECT_EQ(track_.GetWindow(0), nullptr); } TEST_F(LocalTrackTest, GroupSubscriptionUsesMaxObjectId) { track_.SentSequence(FullSequence(0, 0), MoqtObjectStatus::kEndOfGroup); track_.SentSequence(FullSequence(1, 0), MoqtObjectStatus::kNormal); track_.SentSequence(FullSequence(1, 1), MoqtObjectStatus::kEndOfGroup); track_.SentSequence(FullSequence(2, 0), MoqtObjectStatus::kGroupDoesNotExist); track_.SentSequence(FullSequence(3, 0), MoqtObjectStatus::kNormal); track_.SentSequence(FullSequence(3, 1), MoqtObjectStatus::kNormal); track_.SentSequence(FullSequence(3, 2), MoqtObjectStatus::kNormal); track_.SentSequence(FullSequence(3, 3), MoqtObjectStatus::kEndOfGroup); track_.SentSequence(FullSequence(4, 0), MoqtObjectStatus::kNormal); track_.SentSequence(FullSequence(4, 1), MoqtObjectStatus::kNormal); track_.SentSequence(FullSequence(4, 2), MoqtObjectStatus::kNormal); track_.SentSequence(FullSequence(4, 3), MoqtObjectStatus::kNormal); track_.SentSequence(FullSequence(4, 4), MoqtObjectStatus::kNormal); EXPECT_EQ(track_.next_sequence(), FullSequence(4, 5)); track_.AddWindow(0, 1, 1, 3); SubscribeWindow* window = track_.GetWindow(0); EXPECT_TRUE(window->InWindow(FullSequence(3, 3))); EXPECT_FALSE(window->InWindow(FullSequence(3, 4))); track_.AddWindow(1, 1, 1, 2); window = track_.GetWindow(1); EXPECT_TRUE(window->InWindow(FullSequence(1, 1))); track_.AddWindow(2, 1, 1, 4); window = track_.GetWindow(2); EXPECT_TRUE(window->InWindow(FullSequence(4, 9))); EXPECT_FALSE(window->InWindow(FullSequence(5, 0))); } TEST_F(LocalTrackTest, ShouldSend) { track_.AddWindow(0, 4, 1); EXPECT_TRUE(track_.HasSubscriber()); EXPECT_TRUE(track_.ShouldSend(FullSequence(3, 12)).empty()); EXPECT_TRUE(track_.ShouldSend(FullSequence(4, 0)).empty()); EXPECT_EQ(track_.ShouldSend(FullSequence(4, 1)).size(), 1); EXPECT_EQ(track_.ShouldSend(FullSequence(12, 0)).size(), 1); } class RemoteTrackTest : public quic::test::QuicTest { public: RemoteTrackTest() : track_(FullTrackName("foo", "bar"), 5, &visitor_) {} RemoteTrack track_; MockRemoteTrackVisitor visitor_; }; TEST_F(RemoteTrackTest, Queries) { EXPECT_EQ(track_.full_track_name(), FullTrackName("foo", "bar")); EXPECT_EQ(track_.track_alias(), 5); EXPECT_EQ(track_.visitor(), &visitor_); } TEST_F(RemoteTrackTest, UpdateForwardingPreference) { EXPECT_TRUE( track_.CheckForwardingPreference(MoqtForwardingPreference::kObject)); EXPECT_TRUE( track_.CheckForwardingPreference(MoqtForwardingPreference::kObject)); EXPECT_FALSE( track_.CheckForwardingPreference(MoqtForwardingPreference::kDatagram)); } } }
370
cpp
google/quiche
moqt_parser
quiche/quic/moqt/moqt_parser.cc
quiche/quic/moqt/moqt_parser_test.cc
#ifndef QUICHE_QUIC_MOQT_MOQT_PARSER_H_ #define QUICHE_QUIC_MOQT_MOQT_PARSER_H_ #include <cstddef> #include <cstdint> #include <optional> #include <string> #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_data_reader.h" #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/common/platform/api/quiche_export.h" namespace moqt { class QUICHE_EXPORT MoqtParserVisitor { public: virtual ~MoqtParserVisitor() = default; virtual void OnObjectMessage(const MoqtObject& message, absl::string_view payload, bool end_of_message) = 0; virtual void OnClientSetupMessage(const MoqtClientSetup& message) = 0; virtual void OnServerSetupMessage(const MoqtServerSetup& message) = 0; virtual void OnSubscribeMessage(const MoqtSubscribe& message) = 0; virtual void OnSubscribeOkMessage(const MoqtSubscribeOk& message) = 0; virtual void OnSubscribeErrorMessage(const MoqtSubscribeError& message) = 0; virtual void OnUnsubscribeMessage(const MoqtUnsubscribe& message) = 0; virtual void OnSubscribeDoneMessage(const MoqtSubscribeDone& message) = 0; virtual void OnSubscribeUpdateMessage(const MoqtSubscribeUpdate& message) = 0; virtual void OnAnnounceMessage(const MoqtAnnounce& message) = 0; virtual void OnAnnounceOkMessage(const MoqtAnnounceOk& message) = 0; virtual void OnAnnounceErrorMessage(const MoqtAnnounceError& message) = 0; virtual void OnAnnounceCancelMessage(const MoqtAnnounceCancel& message) = 0; virtual void OnTrackStatusRequestMessage( const MoqtTrackStatusRequest& message) = 0; virtual void OnUnannounceMessage(const MoqtUnannounce& message) = 0; virtual void OnTrackStatusMessage(const MoqtTrackStatus& message) = 0; virtual void OnGoAwayMessage(const MoqtGoAway& message) = 0; virtual void OnParsingError(MoqtError code, absl::string_view reason) = 0; }; class QUICHE_EXPORT MoqtParser { public: MoqtParser(bool uses_web_transport, MoqtParserVisitor& visitor) : visitor_(visitor), uses_web_transport_(uses_web_transport) {} ~MoqtParser() = default; void ProcessData(absl::string_view data, bool fin); static absl::string_view ProcessDatagram(absl::string_view data, MoqtObject& object_metadata); private: size_t ProcessMessage(absl::string_view data, bool fin); size_t ProcessObject(quic::QuicDataReader& reader, MoqtMessageType type, bool fin); size_t ProcessClientSetup(quic::QuicDataReader& reader); size_t ProcessServerSetup(quic::QuicDataReader& reader); size_t ProcessSubscribe(quic::QuicDataReader& reader); size_t ProcessSubscribeOk(quic::QuicDataReader& reader); size_t ProcessSubscribeError(quic::QuicDataReader& reader); size_t ProcessUnsubscribe(quic::QuicDataReader& reader); size_t ProcessSubscribeDone(quic::QuicDataReader& reader); size_t ProcessSubscribeUpdate(quic::QuicDataReader& reader); size_t ProcessAnnounce(quic::QuicDataReader& reader); size_t ProcessAnnounceOk(quic::QuicDataReader& reader); size_t ProcessAnnounceError(quic::QuicDataReader& reader); size_t ProcessAnnounceCancel(quic::QuicDataReader& reader); size_t ProcessTrackStatusRequest(quic::QuicDataReader& reader); size_t ProcessUnannounce(quic::QuicDataReader& reader); size_t ProcessTrackStatus(quic::QuicDataReader& reader); size_t ProcessGoAway(quic::QuicDataReader& reader); static size_t ParseObjectHeader(quic::QuicDataReader& reader, MoqtObject& object, MoqtMessageType type); void ParseError(absl::string_view reason); void ParseError(MoqtError error, absl::string_view reason); bool ReadVarIntPieceVarInt62(quic::QuicDataReader& reader, uint64_t& result); bool ReadParameter(quic::QuicDataReader& reader, uint64_t& type, absl::string_view& value); bool StringViewToVarInt(absl::string_view& sv, uint64_t& vi); bool ObjectStreamInitialized() const { return object_metadata_.has_value(); } bool ObjectPayloadInProgress() const { return (object_metadata_.has_value() && object_metadata_->object_status == MoqtObjectStatus::kNormal && (object_metadata_->forwarding_preference == MoqtForwardingPreference::kObject || object_metadata_->forwarding_preference == MoqtForwardingPreference::kDatagram || payload_length_remaining_ > 0)); } MoqtParserVisitor& visitor_; bool uses_web_transport_; bool no_more_data_ = false; bool parsing_error_ = false; std::string buffered_message_; std::optional<MoqtObject> object_metadata_ = std::nullopt; size_t payload_length_remaining_ = 0; bool processing_ = false; }; } #endif #include "quiche/quic/moqt/moqt_parser.h" #include <cstddef> #include <cstdint> #include <cstring> #include <optional> #include <string> #include "absl/cleanup/cleanup.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_data_reader.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/common/platform/api/quiche_logging.h" namespace moqt { void MoqtParser::ProcessData(absl::string_view data, bool fin) { if (no_more_data_) { ParseError("Data after end of stream"); } if (processing_) { return; } processing_ = true; auto on_return = absl::MakeCleanup([&] { processing_ = false; }); if (fin) { no_more_data_ = true; if (ObjectPayloadInProgress() && payload_length_remaining_ > data.length()) { ParseError("End of stream before complete OBJECT PAYLOAD"); return; } if (!buffered_message_.empty() && data.empty()) { ParseError("End of stream before complete message"); return; } } std::optional<quic::QuicDataReader> reader = std::nullopt; size_t original_buffer_size = buffered_message_.size(); if (ObjectPayloadInProgress()) { QUICHE_DCHECK(buffered_message_.empty()); if (!object_metadata_->payload_length.has_value()) { visitor_.OnObjectMessage(*object_metadata_, data, fin); if (fin) { object_metadata_.reset(); } return; } if (data.length() < payload_length_remaining_) { visitor_.OnObjectMessage(*object_metadata_, data, false); payload_length_remaining_ -= data.length(); return; } reader.emplace(data); visitor_.OnObjectMessage(*object_metadata_, data.substr(0, payload_length_remaining_), true); reader->Seek(payload_length_remaining_); payload_length_remaining_ = 0; } else if (!buffered_message_.empty()) { absl::StrAppend(&buffered_message_, data); reader.emplace(buffered_message_); } else { reader.emplace(data); } size_t total_processed = 0; while (!reader->IsDoneReading()) { size_t message_len = ProcessMessage(reader->PeekRemainingPayload(), fin); if (message_len == 0) { if (reader->BytesRemaining() > kMaxMessageHeaderSize) { ParseError(MoqtError::kInternalError, "Cannot parse non-OBJECT messages > 2KB"); return; } if (fin) { ParseError("FIN after incomplete message"); return; } if (buffered_message_.empty()) { absl::StrAppend(&buffered_message_, reader->PeekRemainingPayload()); } break; } total_processed += message_len; reader->Seek(message_len); } if (original_buffer_size > 0) { buffered_message_.erase(0, total_processed); } } absl::string_view MoqtParser::ProcessDatagram(absl::string_view data, MoqtObject& object_metadata) { uint64_t value; quic::QuicDataReader reader(data); if (!reader.ReadVarInt62(&value)) { return absl::string_view(); } if (static_cast<MoqtMessageType>(value) != MoqtMessageType::kObjectDatagram) { return absl::string_view(); } size_t processed_data = ParseObjectHeader(reader, object_metadata, MoqtMessageType::kObjectDatagram); if (processed_data == 0) { return absl::string_view(); } return reader.PeekRemainingPayload(); } size_t MoqtParser::ProcessMessage(absl::string_view data, bool fin) { uint64_t value; quic::QuicDataReader reader(data); if (ObjectStreamInitialized() && !ObjectPayloadInProgress()) { return ProcessObject(reader, GetMessageTypeForForwardingPreference( object_metadata_->forwarding_preference), fin); } if (!reader.ReadVarInt62(&value)) { return 0; } auto type = static_cast<MoqtMessageType>(value); switch (type) { case MoqtMessageType::kObjectDatagram: ParseError("Received OBJECT_DATAGRAM on stream"); return 0; case MoqtMessageType::kObjectStream: case MoqtMessageType::kStreamHeaderTrack: case MoqtMessageType::kStreamHeaderGroup: return ProcessObject(reader, type, fin); case MoqtMessageType::kClientSetup: return ProcessClientSetup(reader); case MoqtMessageType::kServerSetup: return ProcessServerSetup(reader); case MoqtMessageType::kSubscribe: return ProcessSubscribe(reader); case MoqtMessageType::kSubscribeOk: return ProcessSubscribeOk(reader); case MoqtMessageType::kSubscribeError: return ProcessSubscribeError(reader); case MoqtMessageType::kUnsubscribe: return ProcessUnsubscribe(reader); case MoqtMessageType::kSubscribeDone: return ProcessSubscribeDone(reader); case MoqtMessageType::kSubscribeUpdate: return ProcessSubscribeUpdate(reader); case MoqtMessageType::kAnnounce: return ProcessAnnounce(reader); case MoqtMessageType::kAnnounceOk: return ProcessAnnounceOk(reader); case MoqtMessageType::kAnnounceError: return ProcessAnnounceError(reader); case MoqtMessageType::kAnnounceCancel: return ProcessAnnounceCancel(reader); case MoqtMessageType::kTrackStatusRequest: return ProcessTrackStatusRequest(reader); case MoqtMessageType::kUnannounce: return ProcessUnannounce(reader); case MoqtMessageType::kTrackStatus: return ProcessTrackStatus(reader); case MoqtMessageType::kGoAway: return ProcessGoAway(reader); default: ParseError("Unknown message type"); return 0; } } size_t MoqtParser::ProcessObject(quic::QuicDataReader& reader, MoqtMessageType type, bool fin) { size_t processed_data = 0; QUICHE_DCHECK(!ObjectPayloadInProgress()); if (!ObjectStreamInitialized()) { object_metadata_ = MoqtObject(); processed_data = ParseObjectHeader(reader, object_metadata_.value(), type); if (processed_data == 0) { object_metadata_.reset(); return 0; } } QUICHE_DCHECK(payload_length_remaining_ == 0); switch (type) { case MoqtMessageType::kStreamHeaderTrack: if (!reader.ReadVarInt62(&object_metadata_->group_id)) { return processed_data; } [[fallthrough]]; case MoqtMessageType::kStreamHeaderGroup: { uint64_t length; if (!reader.ReadVarInt62(&object_metadata_->object_id) || !reader.ReadVarInt62(&length)) { return processed_data; } object_metadata_->payload_length = length; uint64_t status = 0; if (length == 0 && !reader.ReadVarInt62(&status)) { return processed_data; } object_metadata_->object_status = IntegerToObjectStatus(status); break; } default: break; } if (object_metadata_->object_status == MoqtObjectStatus::kInvalidObjectStatus) { ParseError("Invalid object status"); return processed_data; } if (object_metadata_->object_status != MoqtObjectStatus::kNormal) { if ((type == MoqtMessageType::kObjectStream || type == MoqtMessageType::kObjectDatagram) && reader.BytesRemaining() > 0) { ParseError("Object with non-normal status has payload"); return processed_data; } visitor_.OnObjectMessage(*object_metadata_, "", true); return processed_data; } bool has_length = object_metadata_->payload_length.has_value(); bool received_complete_message = false; size_t payload_to_draw = reader.BytesRemaining(); if (fin && has_length && *object_metadata_->payload_length > reader.BytesRemaining()) { ParseError("Received FIN mid-payload"); return processed_data; } received_complete_message = fin || (has_length && *object_metadata_->payload_length <= reader.BytesRemaining()); if (received_complete_message && has_length && *object_metadata_->payload_length < reader.BytesRemaining()) { payload_to_draw = *object_metadata_->payload_length; } visitor_.OnObjectMessage( *object_metadata_, reader.PeekRemainingPayload().substr(0, payload_to_draw), received_complete_message); reader.Seek(payload_to_draw); payload_length_remaining_ = has_length ? *object_metadata_->payload_length - payload_to_draw : 0; return reader.PreviouslyReadPayload().length(); } size_t MoqtParser::ProcessClientSetup(quic::QuicDataReader& reader) { MoqtClientSetup setup; uint64_t number_of_supported_versions; if (!reader.ReadVarInt62(&number_of_supported_versions)) { return 0; } uint64_t version; for (uint64_t i = 0; i < number_of_supported_versions; ++i) { if (!reader.ReadVarInt62(&version)) { return 0; } setup.supported_versions.push_back(static_cast<MoqtVersion>(version)); } uint64_t num_params; if (!reader.ReadVarInt62(&num_params)) { return 0; } for (uint64_t i = 0; i < num_params; ++i) { uint64_t type; absl::string_view value; if (!ReadParameter(reader, type, value)) { return 0; } auto key = static_cast<MoqtSetupParameter>(type); switch (key) { case MoqtSetupParameter::kRole: if (setup.role.has_value()) { ParseError("ROLE parameter appears twice in SETUP"); return 0; } uint64_t index; if (!StringViewToVarInt(value, index)) { return 0; } if (index > static_cast<uint64_t>(MoqtRole::kRoleMax)) { ParseError("Invalid ROLE parameter"); return 0; } setup.role = static_cast<MoqtRole>(index); break; case MoqtSetupParameter::kPath: if (uses_web_transport_) { ParseError( "WebTransport connection is using PATH parameter in SETUP"); return 0; } if (setup.path.has_value()) { ParseError("PATH parameter appears twice in CLIENT_SETUP"); return 0; } setup.path = value; break; default: break; } } if (!setup.role.has_value()) { ParseError("ROLE parameter missing from CLIENT_SETUP message"); return 0; } if (!uses_web_transport_ && !setup.path.has_value()) { ParseError("PATH SETUP parameter missing from Client message over QUIC"); return 0; } visitor_.OnClientSetupMessage(setup); return reader.PreviouslyReadPayload().length(); } size_t MoqtParser::ProcessServerSetup(quic::QuicDataReader& reader) { MoqtServerSetup setup; uint64_t version; if (!reader.ReadVarInt62(&version)) { return 0; } setup.selected_version = static_cast<MoqtVersion>(version); uint64_t num_params; if (!reader.ReadVarInt62(&num_params)) { return 0; } for (uint64_t i = 0; i < num_params; ++i) { uint64_t type; absl::string_view value; if (!ReadParameter(reader, type, value)) { return 0; } auto key = static_cast<MoqtSetupParameter>(type); switch (key) { case MoqtSetupParameter::kRole: if (setup.role.has_value()) { ParseError("ROLE parameter appears twice in SETUP"); return 0; } uint64_t index; if (!StringViewToVarInt(value, index)) { return 0; } if (index > static_cast<uint64_t>(MoqtRole::kRoleMax)) { ParseError("Invalid ROLE parameter"); return 0; } setup.role = static_cast<MoqtRole>(index); break; case MoqtSetupParameter::kPath: ParseError("PATH parameter in SERVER_SETUP"); return 0; default: break; } } if (!setup.role.has_value()) { ParseError("ROLE parameter missing from SERVER_SETUP message"); return 0; } visitor_.OnServerSetupMessage(setup); return reader.PreviouslyReadPayload().length(); } size_t MoqtParser::ProcessSubscribe(quic::QuicDataReader& reader) { MoqtSubscribe subscribe_request; uint64_t filter, group, object; if (!reader.ReadVarInt62(&subscribe_request.subscribe_id) || !reader.ReadVarInt62(&subscribe_request.track_alias) || !reader.ReadStringVarInt62(subscribe_request.track_namespace) || !reader.ReadStringVarInt62(subscribe_request.track_name) || !reader.ReadVarInt62(&filter)) { return 0; } MoqtFilterType filter_type = static_cast<MoqtFilterType>(filter); switch (filter_type) { case MoqtFilterType::kLatestGroup: subscribe_request.start_object = 0; break; case MoqtFilterType::kLatestObject: break; case MoqtFilterType::kAbsoluteStart: case MoqtFilterType::kAbsoluteRange: if (!reader.ReadVarInt62(&group) || !reader.ReadVarInt62(&object)) { return 0; } subscribe_request.start_group = group; subscribe_request.start_object = object; if (filter_type == MoqtFilterType::kAbsoluteStart) { break; } if (!reader.ReadVarInt62(&group) || !reader.ReadVarInt62(&object)) { return 0; } subscribe_request.end_group = group; if (subscribe_request.end_group < subscribe_request.start_group) { ParseError("End group is less than start group"); return 0; } if (object == 0) { subscribe_request.end_object = std::nullopt; } else { subscribe_request.end_object = object - 1; if (subscribe_request.start_group == subscribe_request.end_group && subscribe_request.end_object < subscribe_request.start_object) { ParseError("End object comes before start object"); return 0; } } break; default: ParseError("Invalid filter type"); return 0; } uint64_t num_params; if (!reader.ReadVarInt62(&num_params)) { return 0; } for (uint64_t i = 0; i < num_params; ++i) { uint64_t type; absl::string_view value; if (!ReadParameter(reader, type, value)) { return 0; } auto key = static_cast<MoqtTrackRequestParameter>(type); switch (key) { case MoqtTrackRequestParameter::kAuthorizationInfo: if (subscribe_request.authorization_info.has_value()) { ParseError( "AUTHORIZATION_INFO parameter appears twice in " "SUBSCRIBE"); return 0; } subscribe_request.authorization_info = value; break; default: break; } } visitor_.OnSubscribeMessage(subscribe_request); return reader.PreviouslyReadPayload().length(); } size_t MoqtParser::ProcessSubscribeOk(quic::QuicDataReader& reader) { MoqtSubscribeOk subscribe_ok; uint64_t milliseconds; uint8_t content_exists; if (!reader.ReadVarInt62(&subscribe_ok.subscribe_id) || !reader.ReadVarInt62(&milliseconds) || !reader.ReadUInt8(&content_exists)) { return 0; } if (content_exists > 1) { ParseError("SUBSCRIBE_OK ContentExists has invalid value"); return 0; } subscribe_ok.expires = quic::QuicTimeDelta::FromMilliseconds(milliseconds); if (content_exists) { subscribe_ok.largest_id = FullSequence(); if (!reader.ReadVarInt62(&subscribe_ok.largest_id->group) || !reader.ReadVarInt62(&subscribe_ok.largest_id->object)) { return 0; } } visitor_.OnSubscribeOkMessage(subscribe_ok); return reader.PreviouslyReadPayload().length(); } size_t MoqtParser::ProcessSubscribeError(quic::QuicDataReader& reader) { MoqtSubscribeError subscribe_error; uint64_t error_code; if (!reader.ReadVarInt62(&subscribe_error.subscribe_id) || !reader.ReadVarInt62(&error_code) || !reader.ReadStringVarInt62(subscribe_error.reason_phrase) || !reader.ReadVarInt62(&subscribe_error.track_alias)) { return 0; } subscribe_error.error_code = static_cast<SubscribeErrorCode>(error_code); visitor_.OnSubscribeErrorMessage(subscribe_error); return reader.PreviouslyReadPayload().length(); } size_t MoqtParser::ProcessUnsubscribe(quic::QuicDataReader& reader) { MoqtUnsubscribe unsubscribe; if (!reader.ReadVarInt62(&unsubscribe.subscribe_id)) { return 0; } visitor_.OnUnsubscribeMessage(unsubscribe); return reader.PreviouslyReadPayload().length(); } size_t MoqtParser::ProcessSubscribeDone(quic::QuicDataReader& reader) { MoqtSubscribeDone subscribe_done; uint8_t content_exists; uint64_t value; if (!reader.ReadVarInt62(&subscribe_done.subscribe_id) || !reader.ReadVarInt62(&value) || !reader.ReadStringVarInt62(subscribe_done.reason_phrase) || !reader.ReadUInt8(&content_exists)) { return 0; } subscribe_done.status_code = static_cast<SubscribeDoneCode>(value); if (content_exists > 1) { ParseError("SUBSCRIBE_DONE ContentExists has invalid value"); return 0; } if (content_exists == 1) { subscribe_done.final_id = FullSequence(); if (!reader.ReadVarInt62(&subscribe_done.final_id->group) || !reader.ReadVarInt62(&subscribe_done.final_id->object)) { return 0; } } visitor_.OnSubscribeDoneMessage(subscribe_done); return reader.PreviouslyReadPayload().length(); } size_t MoqtParser::ProcessSubscribeUpdate(quic::QuicDataReader& reader) { MoqtSubscribeUpdate subscribe_update; uint64_t end_group, end_object, num_params; if (!reader.ReadVarInt62(&subscribe_update.subscribe_id) || !reader.ReadVarInt62(&subscribe_update.start_group) || !reader.ReadVarInt62(&subscribe_update.start_object) || !reader.ReadVarInt62(&end_group) || !reader.ReadVarInt62(&end_object) || !reader.ReadVarInt62(&num_params)) { return 0; } if (end_group == 0) { if (end_object > 0) { ParseError("SUBSCRIBE_UPDATE has end_object but no end_group"); return 0; } } else { subscribe_update.end_group = end_group - 1; if (subscribe_update.end_group < subscribe_update.start_group) { ParseError("End group is less than start group"); return 0; } } if (end_object > 0) { subscribe_update.end_object = end_object - 1; if (subscribe_update.end_object.has_value() && subscribe_update.start_group == *subscribe_update.end_group && *subscribe_update.end_object < subscribe_update.start_object) { ParseError("End object comes before start object"); return 0; } } else { subscribe_update.end_object = std::nullopt; } for (uint64_t i = 0; i < num_params; ++i) { uint64_t type; absl::string_view value; if (!ReadParameter(reader, type, value)) { return 0; } auto key = static_cast<MoqtTrackRequestParameter>(type); switch (key) { case MoqtTrackRequestParameter::kAuthorizationInfo: if (subscribe_update.authorization_info.has_value()) { ParseError( "AUTHORIZATION_INFO parameter appears twice in " "SUBSCRIBE_UPDATE"); return 0; } subscribe_update.authorization_info = value; break; default: break; } } visitor_.OnSubscribeUpdateMessage(subscribe_update); return reader.PreviouslyReadPayload().length(); } size_t MoqtParser::ProcessAnnounce(quic::QuicDataReader& reader) { MoqtAnnounce announce; if (!reader.ReadStringVarInt62(announce.track_namespace)) { return 0; } uint64_t num_params; if (!reader.ReadVarInt62(&num_params)) { return 0; } for (uint64_t i = 0; i < num_params; ++i) { uint64_t type; absl::string_view value; if (!ReadParameter(reader, type, value)) { return 0; } auto key = static_cast<MoqtTrackRequestParameter>(type); switch (key) { case MoqtTrackRequestParameter::kAuthorizationInfo: if (announce.authorization_info.has_value()) { ParseError("AUTHORIZATION_INFO parameter appears twice in ANNOUNCE"); return 0; } announce.authorization_info = value; break; default: break; } } visitor_.OnAnnounceMessage(announce); return reader.PreviouslyReadPayload().length(); } size_t MoqtParser::ProcessAnnounceOk(quic::QuicDataReader& reader) { MoqtAnnounceOk announce_ok; if (!reader.ReadStringVarInt62(announce_ok.track_namespace)) { return 0; } visitor_.OnAnnounceOkMessage(announce_ok); return reader.PreviouslyReadPayload().length(); } size_t MoqtParser::ProcessAnnounceError(quic::QuicDataReader& reader) { MoqtAnnounceError announce_error; if (!reader.ReadStringVarInt62(announce_error.track_namespace)) { return 0; } uint64_t error_code; if (!reader.ReadVarInt62(&error_code)) { return 0; } announce_error.error_code = static_cast<MoqtAnnounceErrorCode>(error_code); if (!reader.ReadStringVarInt62(announce_error.reason_phrase)) { return 0; } visitor_.OnAnnounceErrorMessage(announce_error); return reader.PreviouslyReadPayload().length(); } size_t MoqtParser::ProcessAnnounceCancel(quic::QuicDataReader& reader) { MoqtAnnounceCancel announce_cancel; if (!reader.ReadStringVarInt62(announce_cancel.track_namespace)) { return 0; } visitor_.OnAnnounceCancelMessage(announce_cancel); return reader.PreviouslyReadPayload().length(); } size_t MoqtParser::ProcessTrackStatusRequest(quic::QuicDataReader& reader) { MoqtTrackStatusRequest track_status_request; if (!reader.ReadStringVarInt62(track_status_request.track_namespace)) { return 0; } if (!reader.ReadStringVarInt62(track_status_request.track_name)) { return 0; } visitor_.OnTrackStatusRequestMessage(track_status_request); return reader.PreviouslyReadPayload().length(); } size_t MoqtParser::ProcessUnannounce(quic::QuicDataReader& reader) { MoqtUnannounce unannounce; if (!reader.ReadStringVarInt62(unannounce.track_namespace)) { return 0; } visitor_.OnUnannounceMessage(unannounce); return reader.PreviouslyReadPayload().length(); } size_t MoqtParser::ProcessTrackStatus(quic::QuicDataReader& reader) { MoqtTrackStatus track_status; uint64_t value; if (!reader.ReadStringVarInt62(track_status.track_namespace) || !reader.ReadStringVarInt62(track_status.track_name) || !reader.ReadVarInt62(&value) || !reader.ReadVarInt62(&track_status.last_group) || !reader.ReadVarInt62(&track_status.last_object)) { return 0; } track_status.status_code = static_cast<MoqtTrackStatusCode>(value); visitor_.OnTrackStatusMessage(track_status); return reader.PreviouslyReadPayload().length(); } size_t MoqtParser::ProcessGoAway(quic::QuicDataReader& reader) { MoqtGoAway goaway; if (!reader.ReadStringVarInt62(goaway.n
#include "quiche/quic/moqt/moqt_parser.h" #include <cstddef> #include <cstdint> #include <cstring> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/quic/moqt/test_tools/moqt_test_message.h" #include "quiche/quic/platform/api/quic_test.h" namespace moqt::test { namespace { inline bool IsObjectMessage(MoqtMessageType type) { return (type == MoqtMessageType::kObjectStream || type == MoqtMessageType::kObjectDatagram || type == MoqtMessageType::kStreamHeaderTrack || type == MoqtMessageType::kStreamHeaderGroup); } inline bool IsObjectWithoutPayloadLength(MoqtMessageType type) { return (type == MoqtMessageType::kObjectStream || type == MoqtMessageType::kObjectDatagram); } std::vector<MoqtMessageType> message_types = { MoqtMessageType::kObjectStream, MoqtMessageType::kSubscribe, MoqtMessageType::kSubscribeOk, MoqtMessageType::kSubscribeError, MoqtMessageType::kSubscribeUpdate, MoqtMessageType::kUnsubscribe, MoqtMessageType::kSubscribeDone, MoqtMessageType::kAnnounceCancel, MoqtMessageType::kTrackStatusRequest, MoqtMessageType::kTrackStatus, MoqtMessageType::kAnnounce, MoqtMessageType::kAnnounceOk, MoqtMessageType::kAnnounceError, MoqtMessageType::kUnannounce, MoqtMessageType::kClientSetup, MoqtMessageType::kServerSetup, MoqtMessageType::kStreamHeaderTrack, MoqtMessageType::kStreamHeaderGroup, MoqtMessageType::kGoAway, }; } struct MoqtParserTestParams { MoqtParserTestParams(MoqtMessageType message_type, bool uses_web_transport) : message_type(message_type), uses_web_transport(uses_web_transport) {} MoqtMessageType message_type; bool uses_web_transport; }; std::vector<MoqtParserTestParams> GetMoqtParserTestParams() { std::vector<MoqtParserTestParams> params; std::vector<bool> uses_web_transport_bool = { false, true, }; for (const MoqtMessageType message_type : message_types) { if (message_type == MoqtMessageType::kClientSetup) { for (const bool uses_web_transport : uses_web_transport_bool) { params.push_back( MoqtParserTestParams(message_type, uses_web_transport)); } } else { params.push_back(MoqtParserTestParams(message_type, true)); } } return params; } std::string ParamNameFormatter( const testing::TestParamInfo<MoqtParserTestParams>& info) { return MoqtMessageTypeToString(info.param.message_type) + "_" + (info.param.uses_web_transport ? "WebTransport" : "QUIC"); } class MoqtParserTestVisitor : public MoqtParserVisitor { public: ~MoqtParserTestVisitor() = default; void OnObjectMessage(const MoqtObject& message, absl::string_view payload, bool end_of_message) override { MoqtObject object = message; object_payload_ = payload; end_of_message_ = end_of_message; messages_received_++; last_message_ = TestMessageBase::MessageStructuredData(object); } template <typename Message> void OnControlMessage(const Message& message) { end_of_message_ = true; ++messages_received_; last_message_ = TestMessageBase::MessageStructuredData(message); } void OnClientSetupMessage(const MoqtClientSetup& message) override { OnControlMessage(message); } void OnServerSetupMessage(const MoqtServerSetup& message) override { OnControlMessage(message); } void OnSubscribeMessage(const MoqtSubscribe& message) override { OnControlMessage(message); } void OnSubscribeOkMessage(const MoqtSubscribeOk& message) override { OnControlMessage(message); } void OnSubscribeErrorMessage(const MoqtSubscribeError& message) override { OnControlMessage(message); } void OnSubscribeUpdateMessage(const MoqtSubscribeUpdate& message) override { OnControlMessage(message); } void OnUnsubscribeMessage(const MoqtUnsubscribe& message) override { OnControlMessage(message); } void OnSubscribeDoneMessage(const MoqtSubscribeDone& message) override { OnControlMessage(message); } void OnAnnounceMessage(const MoqtAnnounce& message) override { OnControlMessage(message); } void OnAnnounceOkMessage(const MoqtAnnounceOk& message) override { OnControlMessage(message); } void OnAnnounceErrorMessage(const MoqtAnnounceError& message) override { OnControlMessage(message); } void OnAnnounceCancelMessage(const MoqtAnnounceCancel& message) override { OnControlMessage(message); } void OnTrackStatusRequestMessage( const MoqtTrackStatusRequest& message) override { OnControlMessage(message); } void OnUnannounceMessage(const MoqtUnannounce& message) override { OnControlMessage(message); } void OnTrackStatusMessage(const MoqtTrackStatus& message) override { OnControlMessage(message); } void OnGoAwayMessage(const MoqtGoAway& message) override { OnControlMessage(message); } void OnParsingError(MoqtError code, absl::string_view reason) override { QUIC_LOG(INFO) << "Parsing error: " << reason; parsing_error_ = reason; parsing_error_code_ = code; } std::optional<absl::string_view> object_payload_; bool end_of_message_ = false; std::optional<absl::string_view> parsing_error_; MoqtError parsing_error_code_; uint64_t messages_received_ = 0; std::optional<TestMessageBase::MessageStructuredData> last_message_; }; class MoqtParserTest : public quic::test::QuicTestWithParam<MoqtParserTestParams> { public: MoqtParserTest() : message_type_(GetParam().message_type), webtrans_(GetParam().uses_web_transport), parser_(GetParam().uses_web_transport, visitor_) {} std::unique_ptr<TestMessageBase> MakeMessage(MoqtMessageType message_type) { return CreateTestMessage(message_type, webtrans_); } MoqtParserTestVisitor visitor_; MoqtMessageType message_type_; bool webtrans_; MoqtParser parser_; }; INSTANTIATE_TEST_SUITE_P(MoqtParserTests, MoqtParserTest, testing::ValuesIn(GetMoqtParserTestParams()), ParamNameFormatter); TEST_P(MoqtParserTest, OneMessage) { std::unique_ptr<TestMessageBase> message = MakeMessage(message_type_); parser_.ProcessData(message->PacketSample(), true); EXPECT_EQ(visitor_.messages_received_, 1); EXPECT_TRUE(message->EqualFieldValues(*visitor_.last_message_)); EXPECT_TRUE(visitor_.end_of_message_); if (IsObjectMessage(message_type_)) { EXPECT_TRUE(visitor_.object_payload_.has_value()); EXPECT_EQ(*(visitor_.object_payload_), "foo"); } } TEST_P(MoqtParserTest, OneMessageWithLongVarints) { std::unique_ptr<TestMessageBase> message = MakeMessage(message_type_); message->ExpandVarints(); parser_.ProcessData(message->PacketSample(), true); EXPECT_EQ(visitor_.messages_received_, 1); EXPECT_TRUE(message->EqualFieldValues(*visitor_.last_message_)); EXPECT_TRUE(visitor_.end_of_message_); if (IsObjectMessage(message_type_)) { EXPECT_EQ(visitor_.object_payload_, "foo"); } EXPECT_FALSE(visitor_.parsing_error_.has_value()); } TEST_P(MoqtParserTest, TwoPartMessage) { std::unique_ptr<TestMessageBase> message = MakeMessage(message_type_); size_t first_data_size = message->total_message_size() / 2; if (message_type_ == MoqtMessageType::kStreamHeaderTrack) { ++first_data_size; } parser_.ProcessData(message->PacketSample().substr(0, first_data_size), false); EXPECT_EQ(visitor_.messages_received_, 0); parser_.ProcessData( message->PacketSample().substr( first_data_size, message->total_message_size() - first_data_size), true); EXPECT_EQ(visitor_.messages_received_, 1); EXPECT_TRUE(message->EqualFieldValues(*visitor_.last_message_)); if (IsObjectMessage(message_type_)) { EXPECT_EQ(visitor_.object_payload_, "foo"); } EXPECT_TRUE(visitor_.end_of_message_); EXPECT_FALSE(visitor_.parsing_error_.has_value()); } TEST_P(MoqtParserTest, OneByteAtATime) { std::unique_ptr<TestMessageBase> message = MakeMessage(message_type_); size_t kObjectPayloadSize = 3; for (size_t i = 0; i < message->total_message_size(); ++i) { if (!IsObjectMessage(message_type_)) { EXPECT_EQ(visitor_.messages_received_, 0); } EXPECT_FALSE(visitor_.end_of_message_); parser_.ProcessData(message->PacketSample().substr(i, 1), false); } EXPECT_EQ(visitor_.messages_received_, (IsObjectMessage(message_type_) ? (kObjectPayloadSize + 1) : 1)); if (IsObjectWithoutPayloadLength(message_type_)) { EXPECT_FALSE(visitor_.end_of_message_); parser_.ProcessData(absl::string_view(), true); EXPECT_EQ(visitor_.messages_received_, kObjectPayloadSize + 2); } EXPECT_TRUE(message->EqualFieldValues(*visitor_.last_message_)); EXPECT_TRUE(visitor_.end_of_message_); EXPECT_FALSE(visitor_.parsing_error_.has_value()); } TEST_P(MoqtParserTest, OneByteAtATimeLongerVarints) { std::unique_ptr<TestMessageBase> message = MakeMessage(message_type_); message->ExpandVarints(); size_t kObjectPayloadSize = 3; for (size_t i = 0; i < message->total_message_size(); ++i) { if (!IsObjectMessage(message_type_)) { EXPECT_EQ(visitor_.messages_received_, 0); } EXPECT_FALSE(visitor_.end_of_message_); parser_.ProcessData(message->PacketSample().substr(i, 1), false); } EXPECT_EQ(visitor_.messages_received_, (IsObjectMessage(message_type_) ? (kObjectPayloadSize + 1) : 1)); if (IsObjectWithoutPayloadLength(message_type_)) { EXPECT_FALSE(visitor_.end_of_message_); parser_.ProcessData(absl::string_view(), true); EXPECT_EQ(visitor_.messages_received_, kObjectPayloadSize + 2); } EXPECT_TRUE(message->EqualFieldValues(*visitor_.last_message_)); EXPECT_TRUE(visitor_.end_of_message_); EXPECT_FALSE(visitor_.parsing_error_.has_value()); } TEST_P(MoqtParserTest, EarlyFin) { std::unique_ptr<TestMessageBase> message = MakeMessage(message_type_); size_t first_data_size = message->total_message_size() / 2; if (message_type_ == MoqtMessageType::kStreamHeaderTrack) { ++first_data_size; } parser_.ProcessData(message->PacketSample().substr(0, first_data_size), true); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "FIN after incomplete message"); } TEST_P(MoqtParserTest, SeparateEarlyFin) { std::unique_ptr<TestMessageBase> message = MakeMessage(message_type_); size_t first_data_size = message->total_message_size() / 2; if (message_type_ == MoqtMessageType::kStreamHeaderTrack) { ++first_data_size; } parser_.ProcessData(message->PacketSample().substr(0, first_data_size), false); parser_.ProcessData(absl::string_view(), true); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "End of stream before complete message"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } class MoqtMessageSpecificTest : public quic::test::QuicTest { public: MoqtMessageSpecificTest() {} MoqtParserTestVisitor visitor_; static constexpr bool kWebTrans = true; static constexpr bool kRawQuic = false; }; TEST_F(MoqtMessageSpecificTest, ObjectStreamSeparateFin) { MoqtParser parser(kRawQuic, visitor_); auto message = std::make_unique<ObjectStreamMessage>(); parser.ProcessData(message->PacketSample(), false); EXPECT_EQ(visitor_.messages_received_, 1); EXPECT_TRUE(message->EqualFieldValues(*visitor_.last_message_)); EXPECT_TRUE(visitor_.object_payload_.has_value()); EXPECT_EQ(*(visitor_.object_payload_), "foo"); EXPECT_FALSE(visitor_.end_of_message_); parser.ProcessData(absl::string_view(), true); EXPECT_EQ(visitor_.messages_received_, 2); EXPECT_TRUE(message->EqualFieldValues(*visitor_.last_message_)); EXPECT_TRUE(visitor_.object_payload_.has_value()); EXPECT_EQ(*(visitor_.object_payload_), ""); EXPECT_TRUE(visitor_.end_of_message_); EXPECT_FALSE(visitor_.parsing_error_.has_value()); } TEST_F(MoqtMessageSpecificTest, ThreePartObject) { MoqtParser parser(kRawQuic, visitor_); auto message = std::make_unique<ObjectStreamMessage>(); parser.ProcessData(message->PacketSample(), false); EXPECT_EQ(visitor_.messages_received_, 1); EXPECT_TRUE(message->EqualFieldValues(*visitor_.last_message_)); EXPECT_FALSE(visitor_.end_of_message_); EXPECT_TRUE(visitor_.object_payload_.has_value()); EXPECT_EQ(*(visitor_.object_payload_), "foo"); parser.ProcessData("bar", false); EXPECT_EQ(visitor_.messages_received_, 2); EXPECT_TRUE(message->EqualFieldValues(*visitor_.last_message_)); EXPECT_FALSE(visitor_.end_of_message_); EXPECT_TRUE(visitor_.object_payload_.has_value()); EXPECT_EQ(*(visitor_.object_payload_), "bar"); parser.ProcessData("deadbeef", true); EXPECT_EQ(visitor_.messages_received_, 3); EXPECT_TRUE(message->EqualFieldValues(*visitor_.last_message_)); EXPECT_TRUE(visitor_.end_of_message_); EXPECT_TRUE(visitor_.object_payload_.has_value()); EXPECT_EQ(*(visitor_.object_payload_), "deadbeef"); EXPECT_FALSE(visitor_.parsing_error_.has_value()); } TEST_F(MoqtMessageSpecificTest, ThreePartObjectFirstIncomplete) { MoqtParser parser(kRawQuic, visitor_); auto message = std::make_unique<ObjectStreamMessage>(); parser.ProcessData(message->PacketSample().substr(0, 4), false); EXPECT_EQ(visitor_.messages_received_, 0); message->set_wire_image_size(100); parser.ProcessData( message->PacketSample().substr(4, message->total_message_size() - 4), false); EXPECT_EQ(visitor_.messages_received_, 1); EXPECT_TRUE(message->EqualFieldValues(*visitor_.last_message_)); EXPECT_FALSE(visitor_.end_of_message_); EXPECT_TRUE(visitor_.object_payload_.has_value()); EXPECT_EQ(visitor_.object_payload_->length(), 93); parser.ProcessData("bar", true); EXPECT_EQ(visitor_.messages_received_, 2); EXPECT_TRUE(message->EqualFieldValues(*visitor_.last_message_)); EXPECT_TRUE(visitor_.end_of_message_); EXPECT_TRUE(visitor_.object_payload_.has_value()); EXPECT_EQ(*(visitor_.object_payload_), "bar"); EXPECT_FALSE(visitor_.parsing_error_.has_value()); } TEST_F(MoqtMessageSpecificTest, StreamHeaderGroupFollowOn) { MoqtParser parser(kRawQuic, visitor_); auto message1 = std::make_unique<StreamHeaderGroupMessage>(); parser.ProcessData(message1->PacketSample(), false); EXPECT_EQ(visitor_.messages_received_, 1); EXPECT_TRUE(message1->EqualFieldValues(*visitor_.last_message_)); EXPECT_TRUE(visitor_.end_of_message_); EXPECT_TRUE(visitor_.object_payload_.has_value()); EXPECT_EQ(*(visitor_.object_payload_), "foo"); EXPECT_FALSE(visitor_.parsing_error_.has_value()); auto message2 = std::make_unique<StreamMiddlerGroupMessage>(); parser.ProcessData(message2->PacketSample(), false); EXPECT_EQ(visitor_.messages_received_, 2); EXPECT_TRUE(message2->EqualFieldValues(*visitor_.last_message_)); EXPECT_TRUE(visitor_.end_of_message_); EXPECT_TRUE(visitor_.object_payload_.has_value()); EXPECT_EQ(*(visitor_.object_payload_), "bar"); EXPECT_FALSE(visitor_.parsing_error_.has_value()); } TEST_F(MoqtMessageSpecificTest, StreamHeaderTrackFollowOn) { MoqtParser parser(kRawQuic, visitor_); auto message1 = std::make_unique<StreamHeaderTrackMessage>(); parser.ProcessData(message1->PacketSample(), false); EXPECT_EQ(visitor_.messages_received_, 1); EXPECT_TRUE(message1->EqualFieldValues(*visitor_.last_message_)); EXPECT_TRUE(visitor_.end_of_message_); EXPECT_TRUE(visitor_.object_payload_.has_value()); EXPECT_EQ(*(visitor_.object_payload_), "foo"); EXPECT_FALSE(visitor_.parsing_error_.has_value()); auto message2 = std::make_unique<StreamMiddlerTrackMessage>(); parser.ProcessData(message2->PacketSample(), false); EXPECT_EQ(visitor_.messages_received_, 2); EXPECT_TRUE(message2->EqualFieldValues(*visitor_.last_message_)); EXPECT_TRUE(visitor_.end_of_message_); EXPECT_TRUE(visitor_.object_payload_.has_value()); EXPECT_EQ(*(visitor_.object_payload_), "bar"); EXPECT_FALSE(visitor_.parsing_error_.has_value()); } TEST_F(MoqtMessageSpecificTest, ClientSetupRoleIsInvalid) { MoqtParser parser(kRawQuic, visitor_); char setup[] = { 0x40, 0x40, 0x02, 0x01, 0x02, 0x03, 0x00, 0x01, 0x04, 0x01, 0x03, 0x66, 0x6f, 0x6f }; parser.ProcessData(absl::string_view(setup, sizeof(setup)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "Invalid ROLE parameter"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, ServerSetupRoleIsInvalid) { MoqtParser parser(kRawQuic, visitor_); char setup[] = { 0x40, 0x41, 0x01, 0x01, 0x00, 0x01, 0x04, 0x01, 0x03, 0x66, 0x6f, 0x6f }; parser.ProcessData(absl::string_view(setup, sizeof(setup)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "Invalid ROLE parameter"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, SetupRoleAppearsTwice) { MoqtParser parser(kRawQuic, visitor_); char setup[] = { 0x40, 0x40, 0x02, 0x01, 0x02, 0x03, 0x00, 0x01, 0x03, 0x00, 0x01, 0x03, 0x01, 0x03, 0x66, 0x6f, 0x6f }; parser.ProcessData(absl::string_view(setup, sizeof(setup)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "ROLE parameter appears twice in SETUP"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, ClientSetupRoleIsMissing) { MoqtParser parser(kRawQuic, visitor_); char setup[] = { 0x40, 0x40, 0x02, 0x01, 0x02, 0x01, 0x01, 0x03, 0x66, 0x6f, 0x6f, }; parser.ProcessData(absl::string_view(setup, sizeof(setup)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "ROLE parameter missing from CLIENT_SETUP message"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, ServerSetupRoleIsMissing) { MoqtParser parser(kRawQuic, visitor_); char setup[] = { 0x40, 0x41, 0x01, 0x00, }; parser.ProcessData(absl::string_view(setup, sizeof(setup)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "ROLE parameter missing from SERVER_SETUP message"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, SetupRoleVarintLengthIsWrong) { MoqtParser parser(kRawQuic, visitor_); char setup[] = { 0x40, 0x40, 0x02, 0x01, 0x02, 0x02, 0x00, 0x02, 0x03, 0x01, 0x03, 0x66, 0x6f, 0x6f }; parser.ProcessData(absl::string_view(setup, sizeof(setup)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "Parameter length does not match varint encoding"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kParameterLengthMismatch); } TEST_F(MoqtMessageSpecificTest, SetupPathFromServer) { MoqtParser parser(kRawQuic, visitor_); char setup[] = { 0x40, 0x41, 0x01, 0x01, 0x01, 0x03, 0x66, 0x6f, 0x6f, }; parser.ProcessData(absl::string_view(setup, sizeof(setup)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "PATH parameter in SERVER_SETUP"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, SetupPathAppearsTwice) { MoqtParser parser(kRawQuic, visitor_); char setup[] = { 0x40, 0x40, 0x02, 0x01, 0x02, 0x03, 0x00, 0x01, 0x03, 0x01, 0x03, 0x66, 0x6f, 0x6f, 0x01, 0x03, 0x66, 0x6f, 0x6f, }; parser.ProcessData(absl::string_view(setup, sizeof(setup)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "PATH parameter appears twice in CLIENT_SETUP"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, SetupPathOverWebtrans) { MoqtParser parser(kWebTrans, visitor_); char setup[] = { 0x40, 0x40, 0x02, 0x01, 0x02, 0x02, 0x00, 0x01, 0x03, 0x01, 0x03, 0x66, 0x6f, 0x6f, }; parser.ProcessData(absl::string_view(setup, sizeof(setup)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "WebTransport connection is using PATH parameter in SETUP"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, SetupPathMissing) { MoqtParser parser(kRawQuic, visitor_); char setup[] = { 0x40, 0x40, 0x02, 0x01, 0x02, 0x01, 0x00, 0x01, 0x03, }; parser.ProcessData(absl::string_view(setup, sizeof(setup)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "PATH SETUP parameter missing from Client message over QUIC"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, SubscribeAuthorizationInfoTwice) { MoqtParser parser(kWebTrans, visitor_); char subscribe[] = { 0x03, 0x01, 0x02, 0x03, 0x66, 0x6f, 0x6f, 0x04, 0x61, 0x62, 0x63, 0x64, 0x02, 0x02, 0x02, 0x03, 0x62, 0x61, 0x72, 0x02, 0x03, 0x62, 0x61, 0x72, }; parser.ProcessData(absl::string_view(subscribe, sizeof(subscribe)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "AUTHORIZATION_INFO parameter appears twice in SUBSCRIBE"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, SubscribeUpdateAuthorizationInfoTwice) { MoqtParser parser(kWebTrans, visitor_); char subscribe_update[] = { 0x02, 0x02, 0x03, 0x01, 0x05, 0x06, 0x02, 0x02, 0x03, 0x62, 0x61, 0x72, 0x02, 0x03, 0x62, 0x61, 0x72, }; parser.ProcessData( absl::string_view(subscribe_update, sizeof(subscribe_update)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "AUTHORIZATION_INFO parameter appears twice in SUBSCRIBE_UPDATE"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, AnnounceAuthorizationInfoTwice) { MoqtParser parser(kWebTrans, visitor_); char announce[] = { 0x06, 0x03, 0x66, 0x6f, 0x6f, 0x02, 0x02, 0x03, 0x62, 0x61, 0x72, 0x02, 0x03, 0x62, 0x61, 0x72, }; parser.ProcessData(absl::string_view(announce, sizeof(announce)), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "AUTHORIZATION_INFO parameter appears twice in ANNOUNCE"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, FinMidPayload) { MoqtParser parser(kRawQuic, visitor_); auto message = std::make_unique<StreamHeaderGroupMessage>(); parser.ProcessData( message->PacketSample().substr(0, message->total_message_size() - 1), true); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "Received FIN mid-payload"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, PartialPayloadThenFin) { MoqtParser parser(kRawQuic, visitor_); auto message = std::make_unique<StreamHeaderTrackMessage>(); parser.ProcessData( message->PacketSample().substr(0, message->total_message_size() - 1), false); parser.ProcessData(absl::string_view(), true); EXPECT_EQ(visitor_.messages_received_, 1); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "End of stream before complete OBJECT PAYLOAD"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, DataAfterFin) { MoqtParser parser(kRawQuic, visitor_); parser.ProcessData(absl::string_view(), true); parser.ProcessData("foo", false); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "Data after end of stream"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, NonNormalObjectHasPayload) { MoqtParser parser(kRawQuic, visitor_); char object_stream[] = { 0x00, 0x03, 0x04, 0x05, 0x06, 0x07, 0x02, 0x66, 0x6f, 0x6f, }; parser.ProcessData(absl::string_view(object_stream, sizeof(object_stream)), false); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "Object with non-normal status has payload"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, InvalidObjectStatus) { MoqtParser parser(kRawQuic, visitor_); char object_stream[] = { 0x00, 0x03, 0x04, 0x05, 0x06, 0x07, 0x06, 0x66, 0x6f, 0x6f, }; parser.ProcessData(absl::string_view(object_stream, sizeof(object_stream)), false); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "Invalid object status"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kProtocolViolation); } TEST_F(MoqtMessageSpecificTest, Setup2KB) { MoqtParser parser(kRawQuic, visitor_); char big_message[2 * kMaxMessageHeaderSize]; quic::QuicDataWriter writer(sizeof(big_message), big_message); writer.WriteVarInt62(static_cast<uint64_t>(MoqtMessageType::kServerSetup)); writer.WriteVarInt62(0x1); writer.WriteVarInt62(0x1); writer.WriteVarInt62(0xbeef); writer.WriteVarInt62(kMaxMessageHeaderSize); writer.WriteRepeatedByte(0x04, kMaxMessageHeaderSize); parser.ProcessData(absl::string_view(big_message, writer.length() - 1), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "Cannot parse non-OBJECT messages > 2KB"); EXPECT_EQ(visitor_.parsing_error_code_, MoqtError::kInternalError); } TEST_F(MoqtMessageSpecificTest, UnknownMessageType) { MoqtParser parser(kRawQuic, visitor_); char message[4]; quic::QuicDataWriter writer(sizeof(message), message); writer.WriteVarInt62(0xbeef); parser.ProcessData(absl::string_view(message, writer.length()), false); EXPECT_EQ(visitor_.messages_received_, 0); EXPECT_TRUE(visitor_.parsing_error_.has_value()); EXPECT_EQ(*visitor_.parsing_error_, "Unknown message type"); } TEST_F(MoqtMessageSpecificTest, LatestGroup) { MoqtParser parser(kRawQuic, visitor_); char subscribe[] = { 0x03, 0x01, 0x02, 0x03, 0x66, 0x6f, 0x6f, 0x04, 0x61, 0x62, 0x63, 0x64, 0x01, 0x01, 0x02, 0x03, 0x62, 0x61, 0x72, }; parser.ProcessData(absl::string_view(subscribe, sizeof(subscribe)), false); EXPECT_EQ(visitor_.messages_received_, 1); EXPECT_TRUE(visitor_.last_message_.has_value()); MoqtSubscribe message = std::get<MoqtSubscribe>(visitor_.last_message_.value()); EXPECT_FALSE(message.start_group.has_value()); EXPECT_EQ(message.start_object, 0); EXPECT_FALSE(message.end_group.has_value()); EXPECT_FALSE(message.end_object.has_value()); } TEST_F(MoqtMessageSpecificTest, LatestObject) { MoqtParser parser(kRawQuic, visitor_); char subscribe[] = { 0x03, 0x01, 0x02, 0x03, 0x66, 0x6f, 0x6f, 0x04, 0x61, 0x62, 0x63, 0x64, 0x02, 0x01, 0x02, 0x03, 0x62, 0x61, 0x72, }; parser.ProcessData(absl::string_view(subscribe, sizeof(subscribe)), false); EXPECT_EQ(visitor_.messages_received_, 1); EXPECT_FALSE(visitor_.parsing_error_.has_value()); MoqtSubscribe message = std::get<MoqtSubscribe>(visitor_.last_message_.value()); EXPECT_FALSE(message.start_group.has_value()); EXPECT_FALSE(message.start_object.has_value()); EXPECT_FALSE(message.end_group.has_value()); EXPECT_FALSE(message.end_object.has_value()); } TEST_F(MoqtMessageSpec
371
cpp
google/quiche
moqt_session
quiche/quic/moqt/moqt_session.cc
quiche/quic/moqt/moqt_session_test.cc
#ifndef QUICHE_QUIC_MOQT_MOQT_SESSION_H_ #define QUICHE_QUIC_MOQT_MOQT_SESSION_H_ #include <cstdint> #include <optional> #include <string> #include <utility> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/moqt/moqt_framer.h" #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/quic/moqt/moqt_parser.h" #include "quiche/quic/moqt/moqt_track.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/simple_buffer_allocator.h" #include "quiche/web_transport/web_transport.h" namespace moqt { namespace test { class MoqtSessionPeer; } using MoqtSessionEstablishedCallback = quiche::SingleUseCallback<void()>; using MoqtSessionTerminatedCallback = quiche::SingleUseCallback<void(absl::string_view error_message)>; using MoqtSessionDeletedCallback = quiche::SingleUseCallback<void()>; using MoqtOutgoingAnnounceCallback = quiche::SingleUseCallback<void( absl::string_view track_namespace, std::optional<MoqtAnnounceErrorReason> error)>; using MoqtIncomingAnnounceCallback = quiche::MultiUseCallback<std::optional<MoqtAnnounceErrorReason>( absl::string_view track_namespace)>; inline std::optional<MoqtAnnounceErrorReason> DefaultIncomingAnnounceCallback( absl::string_view ) { return std::optional(MoqtAnnounceErrorReason{ MoqtAnnounceErrorCode::kAnnounceNotSupported, "This endpoint does not accept incoming ANNOUNCE messages"}); }; struct MoqtSessionCallbacks { MoqtSessionEstablishedCallback session_established_callback = +[] {}; MoqtSessionTerminatedCallback session_terminated_callback = +[](absl::string_view) {}; MoqtSessionDeletedCallback session_deleted_callback = +[] {}; MoqtIncomingAnnounceCallback incoming_announce_callback = DefaultIncomingAnnounceCallback; }; class QUICHE_EXPORT MoqtSession : public webtransport::SessionVisitor { public: MoqtSession(webtransport::Session* session, MoqtSessionParameters parameters, MoqtSessionCallbacks callbacks = MoqtSessionCallbacks()) : session_(session), parameters_(parameters), callbacks_(std::move(callbacks)), framer_(quiche::SimpleBufferAllocator::Get(), parameters.using_webtrans) {} ~MoqtSession() { std::move(callbacks_.session_deleted_callback)(); } void OnSessionReady() override; void OnSessionClosed(webtransport::SessionErrorCode, const std::string&) override; void OnIncomingBidirectionalStreamAvailable() override; void OnIncomingUnidirectionalStreamAvailable() override; void OnDatagramReceived(absl::string_view datagram) override; void OnCanCreateNewOutgoingBidirectionalStream() override {} void OnCanCreateNewOutgoingUnidirectionalStream() override {} void Error(MoqtError code, absl::string_view error); quic::Perspective perspective() const { return parameters_.perspective; } void AddLocalTrack(const FullTrackName& full_track_name, MoqtForwardingPreference forwarding_preference, LocalTrack::Visitor* visitor); void Announce(absl::string_view track_namespace, MoqtOutgoingAnnounceCallback announce_callback); bool HasSubscribers(const FullTrackName& full_track_name) const; void CancelAnnounce(absl::string_view track_namespace); bool SubscribeAbsolute(absl::string_view track_namespace, absl::string_view name, uint64_t start_group, uint64_t start_object, RemoteTrack::Visitor* visitor, absl::string_view auth_info = ""); bool SubscribeAbsolute(absl::string_view track_namespace, absl::string_view name, uint64_t start_group, uint64_t start_object, uint64_t end_group, RemoteTrack::Visitor* visitor, absl::string_view auth_info = ""); bool SubscribeAbsolute(absl::string_view track_namespace, absl::string_view name, uint64_t start_group, uint64_t start_object, uint64_t end_group, uint64_t end_object, RemoteTrack::Visitor* visitor, absl::string_view auth_info = ""); bool SubscribeCurrentObject(absl::string_view track_namespace, absl::string_view name, RemoteTrack::Visitor* visitor, absl::string_view auth_info = ""); bool SubscribeCurrentGroup(absl::string_view track_namespace, absl::string_view name, RemoteTrack::Visitor* visitor, absl::string_view auth_info = ""); bool PublishObject(const FullTrackName& full_track_name, uint64_t group_id, uint64_t object_id, uint64_t object_send_order, MoqtObjectStatus status, absl::string_view payload); void CloseObjectStream(const FullTrackName& full_track_name, uint64_t group_id); MoqtSessionCallbacks& callbacks() { return callbacks_; } private: friend class test::MoqtSessionPeer; class QUICHE_EXPORT Stream : public webtransport::StreamVisitor, public MoqtParserVisitor { public: Stream(MoqtSession* session, webtransport::Stream* stream) : session_(session), stream_(stream), parser_(session->parameters_.using_webtrans, *this) {} Stream(MoqtSession* session, webtransport::Stream* stream, bool is_control_stream) : session_(session), stream_(stream), parser_(session->parameters_.using_webtrans, *this), is_control_stream_(is_control_stream) {} void OnCanRead() override; void OnCanWrite() override; void OnResetStreamReceived(webtransport::StreamErrorCode error) override; void OnStopSendingReceived(webtransport::StreamErrorCode error) override; void OnWriteSideInDataRecvdState() override {} void OnObjectMessage(const MoqtObject& message, absl::string_view payload, bool end_of_message) override; void OnClientSetupMessage(const MoqtClientSetup& message) override; void OnServerSetupMessage(const MoqtServerSetup& message) override; void OnSubscribeMessage(const MoqtSubscribe& message) override; void OnSubscribeOkMessage(const MoqtSubscribeOk& message) override; void OnSubscribeErrorMessage(const MoqtSubscribeError& message) override; void OnUnsubscribeMessage(const MoqtUnsubscribe& message) override; void OnSubscribeDoneMessage(const MoqtSubscribeDone& ) override { } void OnSubscribeUpdateMessage(const MoqtSubscribeUpdate& message) override; void OnAnnounceMessage(const MoqtAnnounce& message) override; void OnAnnounceOkMessage(const MoqtAnnounceOk& message) override; void OnAnnounceErrorMessage(const MoqtAnnounceError& message) override; void OnAnnounceCancelMessage(const MoqtAnnounceCancel& message) override; void OnTrackStatusRequestMessage( const MoqtTrackStatusRequest& message) override {}; void OnUnannounceMessage(const MoqtUnannounce& ) override {} void OnTrackStatusMessage(const MoqtTrackStatus& message) override {} void OnGoAwayMessage(const MoqtGoAway& ) override {} void OnParsingError(MoqtError error_code, absl::string_view reason) override; quic::Perspective perspective() const { return session_->parameters_.perspective; } webtransport::Stream* stream() const { return stream_; } void SendOrBufferMessage(quiche::QuicheBuffer message, bool fin = false); private: friend class test::MoqtSessionPeer; void SendSubscribeError(const MoqtSubscribe& message, SubscribeErrorCode error_code, absl::string_view reason_phrase, uint64_t track_alias); bool CheckIfIsControlStream(); MoqtSession* session_; webtransport::Stream* stream_; MoqtParser parser_; std::optional<bool> is_control_stream_; std::string partial_object_; }; bool SubscribeIsDone(uint64_t subscribe_id, SubscribeDoneCode code, absl::string_view reason_phrase); Stream* GetControlStream(); void SendControlMessage(quiche::QuicheBuffer message); bool Subscribe(MoqtSubscribe& message, RemoteTrack::Visitor* visitor); std::optional<webtransport::StreamId> OpenUnidirectionalStream(); std::pair<FullTrackName, RemoteTrack::Visitor*> TrackPropertiesFromAlias( const MoqtObject& message); webtransport::Session* session_; MoqtSessionParameters parameters_; MoqtSessionCallbacks callbacks_; MoqtFramer framer_; std::optional<webtransport::StreamId> control_stream_; std::string error_; absl::flat_hash_map<uint64_t, RemoteTrack> remote_tracks_; absl::flat_hash_map<FullTrackName, uint64_t> remote_track_aliases_; uint64_t next_remote_track_alias_ = 0; absl::flat_hash_map<FullTrackName, LocalTrack> local_tracks_; absl::flat_hash_map<uint64_t, FullTrackName> local_track_by_subscribe_id_; absl::flat_hash_set<uint64_t> used_track_aliases_; uint64_t next_local_track_alias_ = 0; struct ActiveSubscribe { MoqtSubscribe message; RemoteTrack::Visitor* visitor; std::optional<MoqtForwardingPreference> forwarding_preference; bool received_object = false; }; absl::flat_hash_map<uint64_t, ActiveSubscribe> active_subscribes_; uint64_t next_subscribe_id_ = 0; absl::flat_hash_map<std::string, MoqtOutgoingAnnounceCallback> pending_outgoing_announces_; MoqtRole peer_role_ = MoqtRole::kPubSub; }; } #endif #include "quiche/quic/moqt/moqt_session.h" #include <algorithm> #include <array> #include <cstdint> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/algorithm/container.h" #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 "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/quic/moqt/moqt_parser.h" #include "quiche/quic/moqt/moqt_subscribe_windows.h" #include "quiche/quic/moqt/moqt_track.h" #include "quiche/quic/platform/api/quic_bug_tracker.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_stream.h" #include "quiche/web_transport/web_transport.h" #define ENDPOINT \ (perspective() == Perspective::IS_SERVER ? "MoQT Server: " : "MoQT Client: ") namespace moqt { using ::quic::Perspective; MoqtSession::Stream* MoqtSession::GetControlStream() { if (!control_stream_.has_value()) { return nullptr; } webtransport::Stream* raw_stream = session_->GetStreamById(*control_stream_); if (raw_stream == nullptr) { return nullptr; } return static_cast<Stream*>(raw_stream->visitor()); } void MoqtSession::SendControlMessage(quiche::QuicheBuffer message) { Stream* control_stream = GetControlStream(); if (control_stream == nullptr) { QUICHE_LOG(DFATAL) << "Trying to send a message on the control stream " "while it does not exist"; return; } control_stream->SendOrBufferMessage(std::move(message)); } void MoqtSession::OnSessionReady() { QUICHE_DLOG(INFO) << ENDPOINT << "Underlying session ready"; if (parameters_.perspective == Perspective::IS_SERVER) { return; } webtransport::Stream* control_stream = session_->OpenOutgoingBidirectionalStream(); if (control_stream == nullptr) { Error(MoqtError::kInternalError, "Unable to open a control stream"); return; } control_stream->SetVisitor(std::make_unique<Stream>( this, control_stream, true)); control_stream_ = control_stream->GetStreamId(); MoqtClientSetup setup = MoqtClientSetup{ .supported_versions = std::vector<MoqtVersion>{parameters_.version}, .role = MoqtRole::kPubSub, }; if (!parameters_.using_webtrans) { setup.path = parameters_.path; } SendControlMessage(framer_.SerializeClientSetup(setup)); QUIC_DLOG(INFO) << ENDPOINT << "Send the SETUP message"; } void MoqtSession::OnSessionClosed(webtransport::SessionErrorCode, const std::string& error_message) { if (!error_.empty()) { return; } QUICHE_DLOG(INFO) << ENDPOINT << "Underlying session closed with message: " << error_message; error_ = error_message; std::move(callbacks_.session_terminated_callback)(error_message); } void MoqtSession::OnIncomingBidirectionalStreamAvailable() { while (webtransport::Stream* stream = session_->AcceptIncomingBidirectionalStream()) { if (control_stream_.has_value()) { Error(MoqtError::kProtocolViolation, "Bidirectional stream already open"); return; } stream->SetVisitor(std::make_unique<Stream>(this, stream)); stream->visitor()->OnCanRead(); } } void MoqtSession::OnIncomingUnidirectionalStreamAvailable() { while (webtransport::Stream* stream = session_->AcceptIncomingUnidirectionalStream()) { stream->SetVisitor(std::make_unique<Stream>(this, stream)); stream->visitor()->OnCanRead(); } } void MoqtSession::OnDatagramReceived(absl::string_view datagram) { MoqtObject message; absl::string_view payload = MoqtParser::ProcessDatagram(datagram, message); if (payload.empty()) { Error(MoqtError::kProtocolViolation, "Malformed datagram"); return; } QUICHE_DLOG(INFO) << ENDPOINT << "Received OBJECT message in datagram for subscribe_id " << message.subscribe_id << " for track alias " << message.track_alias << " with sequence " << message.group_id << ":" << message.object_id << " send_order " << message.object_send_order << " length " << payload.size(); auto [full_track_name, visitor] = TrackPropertiesFromAlias(message); if (visitor != nullptr) { visitor->OnObjectFragment(full_track_name, message.group_id, message.object_id, message.object_send_order, message.object_status, message.forwarding_preference, payload, true); } } void MoqtSession::Error(MoqtError code, absl::string_view error) { if (!error_.empty()) { return; } QUICHE_DLOG(INFO) << ENDPOINT << "MOQT session closed with code: " << static_cast<int>(code) << " and message: " << error; error_ = std::string(error); session_->CloseSession(static_cast<uint64_t>(code), error); std::move(callbacks_.session_terminated_callback)(error); } void MoqtSession::AddLocalTrack(const FullTrackName& full_track_name, MoqtForwardingPreference forwarding_preference, LocalTrack::Visitor* visitor) { local_tracks_.try_emplace(full_track_name, full_track_name, forwarding_preference, visitor); } void MoqtSession::Announce(absl::string_view track_namespace, MoqtOutgoingAnnounceCallback announce_callback) { if (peer_role_ == MoqtRole::kPublisher) { std::move(announce_callback)( track_namespace, MoqtAnnounceErrorReason{MoqtAnnounceErrorCode::kInternalError, "ANNOUNCE cannot be sent to Publisher"}); return; } if (pending_outgoing_announces_.contains(track_namespace)) { std::move(announce_callback)( track_namespace, MoqtAnnounceErrorReason{ MoqtAnnounceErrorCode::kInternalError, "ANNOUNCE message already outstanding for namespace"}); return; } MoqtAnnounce message; message.track_namespace = track_namespace; SendControlMessage(framer_.SerializeAnnounce(message)); QUIC_DLOG(INFO) << ENDPOINT << "Sent ANNOUNCE message for " << message.track_namespace; pending_outgoing_announces_[track_namespace] = std::move(announce_callback); } bool MoqtSession::HasSubscribers(const FullTrackName& full_track_name) const { auto it = local_tracks_.find(full_track_name); return (it != local_tracks_.end() && it->second.HasSubscriber()); } void MoqtSession::CancelAnnounce(absl::string_view track_namespace) { for (auto it = local_tracks_.begin(); it != local_tracks_.end(); ++it) { if (it->first.track_namespace == track_namespace) { it->second.set_announce_cancel(); } } absl::erase_if(local_tracks_, [&](const auto& it) { return it.first.track_namespace == track_namespace && !it.second.HasSubscriber(); }); } bool MoqtSession::SubscribeAbsolute(absl::string_view track_namespace, absl::string_view name, uint64_t start_group, uint64_t start_object, RemoteTrack::Visitor* visitor, absl::string_view auth_info) { MoqtSubscribe message; message.track_namespace = track_namespace; message.track_name = name; message.start_group = start_group; message.start_object = start_object; message.end_group = std::nullopt; message.end_object = std::nullopt; if (!auth_info.empty()) { message.authorization_info = std::move(auth_info); } return Subscribe(message, visitor); } bool MoqtSession::SubscribeAbsolute(absl::string_view track_namespace, absl::string_view name, uint64_t start_group, uint64_t start_object, uint64_t end_group, RemoteTrack::Visitor* visitor, absl::string_view auth_info) { if (end_group < start_group) { QUIC_DLOG(ERROR) << "Subscription end is before beginning"; return false; } MoqtSubscribe message; message.track_namespace = track_namespace; message.track_name = name; message.start_group = start_group; message.start_object = start_object; message.end_group = end_group; message.end_object = std::nullopt; if (!auth_info.empty()) { message.authorization_info = std::move(auth_info); } return Subscribe(message, visitor); } bool MoqtSession::SubscribeAbsolute(absl::string_view track_namespace, absl::string_view name, uint64_t start_group, uint64_t start_object, uint64_t end_group, uint64_t end_object, RemoteTrack::Visitor* visitor, absl::string_view auth_info) { if (end_group < start_group) { QUIC_DLOG(ERROR) << "Subscription end is before beginning"; return false; } if (end_group == start_group && end_object < start_object) { QUIC_DLOG(ERROR) << "Subscription end is before beginning"; return false; } MoqtSubscribe message; message.track_namespace = track_namespace; message.track_name = name; message.start_group = start_group; message.start_object = start_object; message.end_group = end_group; message.end_object = end_object; if (!auth_info.empty()) { message.authorization_info = std::move(auth_info); } return Subscribe(message, visitor); } bool MoqtSession::SubscribeCurrentObject(absl::string_view track_namespace, absl::string_view name, RemoteTrack::Visitor* visitor, absl::string_view auth_info) { MoqtSubscribe message; message.track_namespace = track_namespace; message.track_name = name; message.start_group = std::nullopt; message.start_object = std::nullopt; message.end_group = std::nullopt; message.end_object = std::nullopt; if (!auth_info.empty()) { message.authorization_info = std::move(auth_info); } return Subscribe(message, visitor); } bool MoqtSession::SubscribeCurrentGroup(absl::string_view track_namespace, absl::string_view name, RemoteTrack::Visitor* visitor, absl::string_view auth_info) { MoqtSubscribe message; message.track_namespace = track_namespace; message.track_name = name; message.start_group = std::nullopt; message.start_object = 0; message.end_group = std::nullopt; message.end_object = std::nullopt; if (!auth_info.empty()) { message.authorization_info = std::move(auth_info); } return Subscribe(message, visitor); } bool MoqtSession::SubscribeIsDone(uint64_t subscribe_id, SubscribeDoneCode code, absl::string_view reason_phrase) { auto name_it = local_track_by_subscribe_id_.find(subscribe_id); if (name_it == local_track_by_subscribe_id_.end()) { return false; } auto track_it = local_tracks_.find(name_it->second); if (track_it == local_tracks_.end()) { return false; } LocalTrack& track = track_it->second; MoqtSubscribeDone subscribe_done; subscribe_done.subscribe_id = subscribe_id; subscribe_done.status_code = code; subscribe_done.reason_phrase = reason_phrase; SubscribeWindow* window = track.GetWindow(subscribe_id); if (window == nullptr) { return false; } subscribe_done.final_id = window->largest_delivered(); SendControlMessage(framer_.SerializeSubscribeDone(subscribe_done)); QUIC_DLOG(INFO) << ENDPOINT << "Sent SUBSCRIBE_DONE message for " << subscribe_id; track.DeleteWindow(subscribe_id); local_track_by_subscribe_id_.erase(name_it); if (track.canceled() && !track.HasSubscriber()) { local_tracks_.erase(track_it); } return true; } bool MoqtSession::Subscribe(MoqtSubscribe& message, RemoteTrack::Visitor* visitor) { if (peer_role_ == MoqtRole::kSubscriber) { QUIC_DLOG(INFO) << ENDPOINT << "Tried to send SUBSCRIBE to subscriber peer"; return false; } message.subscribe_id = next_subscribe_id_++; FullTrackName ftn(std::string(message.track_namespace), std::string(message.track_name)); auto it = remote_track_aliases_.find(ftn); if (it != remote_track_aliases_.end()) { message.track_alias = it->second; if (message.track_alias >= next_remote_track_alias_) { next_remote_track_alias_ = message.track_alias + 1; } } else { message.track_alias = next_remote_track_alias_++; } SendControlMessage(framer_.SerializeSubscribe(message)); QUIC_DLOG(INFO) << ENDPOINT << "Sent SUBSCRIBE message for " << message.track_namespace << ":" << message.track_name; active_subscribes_.try_emplace(message.subscribe_id, message, visitor); return true; } std::optional<webtransport::StreamId> MoqtSession::OpenUnidirectionalStream() { if (!session_->CanOpenNextOutgoingUnidirectionalStream()) { return std::nullopt; } webtransport::Stream* new_stream = session_->OpenOutgoingUnidirectionalStream(); if (new_stream == nullptr) { return std::nullopt; } new_stream->SetVisitor(std::make_unique<Stream>(this, new_stream, false)); return new_stream->GetStreamId(); } std::pair<FullTrackName, RemoteTrack::Visitor*> MoqtSession::TrackPropertiesFromAlias(const MoqtObject& message) { auto it = remote_tracks_.find(message.track_alias); RemoteTrack::Visitor* visitor = nullptr; if (it == remote_tracks_.end()) { auto subscribe_it = active_subscribes_.find(message.subscribe_id); if (subscribe_it == active_subscribes_.end()) { return std::pair<FullTrackName, RemoteTrack::Visitor*>( {{"", ""}, nullptr}); } ActiveSubscribe& subscribe = subscribe_it->second; visitor = subscribe.visitor; subscribe.received_object = true; if (subscribe.forwarding_preference.has_value()) { if (message.forwarding_preference != *subscribe.forwarding_preference) { Error(MoqtError::kProtocolViolation, "Forwarding preference changes mid-track"); return std::pair<FullTrackName, RemoteTrack::Visitor*>( {{"", ""}, nullptr}); } } else { subscribe.forwarding_preference = message.forwarding_preference; } return std::pair<FullTrackName, RemoteTrack::Visitor*>( {{subscribe.message.track_namespace, subscribe.message.track_name}, subscribe.visitor}); } RemoteTrack& track = it->second; if (!track.CheckForwardingPreference(message.forwarding_preference)) { Error(MoqtError::kProtocolViolation, "Forwarding preference changes mid-track"); return std::pair<FullTrackName, RemoteTrack::Visitor*>({{"", ""}, nullptr}); } return std::pair<FullTrackName, RemoteTrack::Visitor*>( {{track.full_track_name().track_namespace, track.full_track_name().track_name}, track.visitor()}); } bool MoqtSession::PublishObject(const FullTrackName& full_track_name, uint64_t group_id, uint64_t object_id, uint64_t object_send_order, MoqtObjectStatus status, absl::string_view payload) { auto track_it = local_tracks_.find(full_track_name); if (track_it == local_tracks_.end()) { QUICHE_DLOG(ERROR) << ENDPOINT << "Sending OBJECT for nonexistent track"; return false; } QUIC_BUG_IF(moqt_publish_abnormal_with_payload, status != MoqtObjectStatus::kNormal && !payload.empty()); LocalTrack& track = track_it->second; bool end_of_stream = false; MoqtForwardingPreference forwarding_preference = track.forwarding_preference(); switch (forwarding_preference) { case MoqtForwardingPreference::kTrack: end_of_stream = (status == MoqtObjectStatus::kEndOfTrack); break; case MoqtForwardingPreference::kObject: case MoqtForwardingPreference::kDatagram: end_of_stream = true; break; case MoqtForwardingPreference::kGroup: end_of_stream = (status == MoqtObjectStatus::kEndOfGroup || status == MoqtObjectStatus::kGroupDoesNotExist || status == MoqtObjectStatus::kEndOfTrack); break; } FullSequence sequence{group_id, object_id}; track.SentSequence(sequence, status); std::vector<SubscribeWindow*> subscriptions = track.ShouldSend({group_id, object_id}); if (subscriptions.empty()) { return true; } MoqtObject object; QUICHE_DCHECK(track.track_alias().has_value()); object.track_alias = *track.track_alias(); object.group_id = group_id; object.object_id = object_id; object.object_send_order = object_send_order; object.object_status = status; object.forwarding_preference = forwarding_preference; object.payload_length = payload.size(); int failures = 0; quiche::StreamWriteOptions write_options; write_options.set_send_fin(end_of_stream); absl::flat_hash_set<uint64_t> subscribes_to_close; for (auto subscription : subscriptions) { if (subscription->OnObjectSent(sequence, status)) { subscribes_to_close.insert(subscription->subscribe_id()); } if (forwarding_preference == MoqtForwardingPreference::kDatagram) { object.subscribe_id = subscription->subscribe_id(); quiche::QuicheBuffer datagram = framer_.SerializeObjectDatagram(object, payload); session_->SendOrQueueDatagram(datagram.AsStringView()); continue; } bool new_stream = false; std::optional<webtransport::StreamId> stream_id = subscription->GetStreamForSequence(sequence); if (!stream_id.has_value()) { new_stream = true; stream_id = Ope
#include "quiche/quic/moqt/moqt_session.h" #include <cstdint> #include <cstring> #include <memory> #include <optional> #include <string> #include <utility> #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/core/quic_data_reader.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/quic/moqt/moqt_parser.h" #include "quiche/quic/moqt/moqt_track.h" #include "quiche/quic/moqt/tools/moqt_mock_visitor.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/common/quiche_stream.h" #include "quiche/web_transport/test_tools/mock_web_transport.h" #include "quiche/web_transport/web_transport.h" namespace moqt { namespace test { namespace { using ::testing::_; using ::testing::AnyNumber; using ::testing::Return; using ::testing::StrictMock; constexpr webtransport::StreamId kControlStreamId = 4; constexpr webtransport::StreamId kIncomingUniStreamId = 15; constexpr webtransport::StreamId kOutgoingUniStreamId = 14; constexpr MoqtSessionParameters default_parameters = { MoqtVersion::kDraft04, quic::Perspective::IS_CLIENT, true, std::string(), false, }; static std::optional<MoqtMessageType> ExtractMessageType( const absl::string_view message) { quic::QuicDataReader reader(message); uint64_t value; if (!reader.ReadVarInt62(&value)) { return std::nullopt; } return static_cast<MoqtMessageType>(value); } } class MoqtSessionPeer { public: static std::unique_ptr<MoqtParserVisitor> CreateControlStream( MoqtSession* session, webtransport::test::MockStream* stream) { auto new_stream = std::make_unique<MoqtSession::Stream>( session, stream, true); session->control_stream_ = kControlStreamId; EXPECT_CALL(*stream, visitor()) .Times(AnyNumber()) .WillRepeatedly(Return(new_stream.get())); return new_stream; } static std::unique_ptr<MoqtParserVisitor> CreateUniStream( MoqtSession* session, webtransport::Stream* stream) { auto new_stream = std::make_unique<MoqtSession::Stream>( session, stream, false); return new_stream; } static MoqtParserVisitor* FetchParserVisitorFromWebtransportStreamVisitor( MoqtSession* session, webtransport::StreamVisitor* visitor) { return (MoqtSession::Stream*)visitor; } static void CreateRemoteTrack(MoqtSession* session, const FullTrackName& name, RemoteTrack::Visitor* visitor, uint64_t track_alias) { session->remote_tracks_.try_emplace(track_alias, name, track_alias, visitor); session->remote_track_aliases_.try_emplace(name, track_alias); } static void AddActiveSubscribe(MoqtSession* session, uint64_t subscribe_id, MoqtSubscribe& subscribe, RemoteTrack::Visitor* visitor) { session->active_subscribes_[subscribe_id] = {subscribe, visitor}; } static LocalTrack* local_track(MoqtSession* session, FullTrackName& name) { auto it = session->local_tracks_.find(name); if (it == session->local_tracks_.end()) { return nullptr; } return &it->second; } static void AddSubscription(MoqtSession* session, FullTrackName& name, uint64_t subscribe_id, uint64_t track_alias, uint64_t start_group, uint64_t start_object) { LocalTrack* track = local_track(session, name); track->set_track_alias(track_alias); track->AddWindow(subscribe_id, start_group, start_object); session->used_track_aliases_.emplace(track_alias); session->local_track_by_subscribe_id_.emplace(subscribe_id, track->full_track_name()); } static FullSequence next_sequence(MoqtSession* session, FullTrackName& name) { auto it = session->local_tracks_.find(name); EXPECT_NE(it, session->local_tracks_.end()); LocalTrack& track = it->second; return track.next_sequence(); } static void set_peer_role(MoqtSession* session, MoqtRole role) { session->peer_role_ = role; } static RemoteTrack& remote_track(MoqtSession* session, uint64_t track_alias) { return session->remote_tracks_.find(track_alias)->second; } }; class MoqtSessionTest : public quic::test::QuicTest { public: MoqtSessionTest() : session_(&mock_session_, default_parameters, session_callbacks_.AsSessionCallbacks()) {} ~MoqtSessionTest() { EXPECT_CALL(session_callbacks_.session_deleted_callback, Call()); } MockSessionCallbacks session_callbacks_; StrictMock<webtransport::test::MockSession> mock_session_; MoqtSession session_; }; TEST_F(MoqtSessionTest, Queries) { EXPECT_EQ(session_.perspective(), quic::Perspective::IS_CLIENT); } TEST_F(MoqtSessionTest, OnSessionReady) { StrictMock<webtransport::test::MockStream> mock_stream; EXPECT_CALL(mock_session_, OpenOutgoingBidirectionalStream()) .WillOnce(Return(&mock_stream)); std::unique_ptr<webtransport::StreamVisitor> visitor; EXPECT_CALL(mock_stream, SetVisitor(_)) .WillOnce([&](std::unique_ptr<webtransport::StreamVisitor> new_visitor) { visitor = std::move(new_visitor); }); EXPECT_CALL(mock_stream, GetStreamId()) .WillOnce(Return(webtransport::StreamId(4))); EXPECT_CALL(mock_session_, GetStreamById(4)).WillOnce(Return(&mock_stream)); bool correct_message = false; EXPECT_CALL(mock_stream, visitor()).WillOnce([&] { return visitor.get(); }); EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kClientSetup); return absl::OkStatus(); }); session_.OnSessionReady(); EXPECT_TRUE(correct_message); MoqtParserVisitor* stream_input = MoqtSessionPeer::FetchParserVisitorFromWebtransportStreamVisitor( &session_, visitor.get()); MoqtServerSetup setup = { MoqtVersion::kDraft04, MoqtRole::kPubSub, }; EXPECT_CALL(session_callbacks_.session_established_callback, Call()).Times(1); stream_input->OnServerSetupMessage(setup); } TEST_F(MoqtSessionTest, OnClientSetup) { MoqtSessionParameters server_parameters = { MoqtVersion::kDraft04, quic::Perspective::IS_SERVER, true, "", false, }; MoqtSession server_session(&mock_session_, server_parameters, session_callbacks_.AsSessionCallbacks()); StrictMock<webtransport::test::MockStream> mock_stream; std::unique_ptr<MoqtParserVisitor> stream_input = MoqtSessionPeer::CreateControlStream(&server_session, &mock_stream); MoqtClientSetup setup = { {MoqtVersion::kDraft04}, MoqtRole::kPubSub, std::nullopt, }; bool correct_message = false; EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kServerSetup); return absl::OkStatus(); }); EXPECT_CALL(mock_stream, GetStreamId()).WillOnce(Return(0)); EXPECT_CALL(session_callbacks_.session_established_callback, Call()).Times(1); stream_input->OnClientSetupMessage(setup); } TEST_F(MoqtSessionTest, OnSessionClosed) { bool reported_error = false; EXPECT_CALL(session_callbacks_.session_terminated_callback, Call(_)) .WillOnce([&](absl::string_view error_message) { reported_error = true; EXPECT_EQ(error_message, "foo"); }); session_.OnSessionClosed(webtransport::SessionErrorCode(1), "foo"); EXPECT_TRUE(reported_error); } TEST_F(MoqtSessionTest, OnIncomingBidirectionalStream) { ::testing::InSequence seq; StrictMock<webtransport::test::MockStream> mock_stream; StrictMock<webtransport::test::MockStreamVisitor> mock_stream_visitor; EXPECT_CALL(mock_session_, AcceptIncomingBidirectionalStream()) .WillOnce(Return(&mock_stream)); EXPECT_CALL(mock_stream, SetVisitor(_)).Times(1); EXPECT_CALL(mock_stream, visitor()).WillOnce(Return(&mock_stream_visitor)); EXPECT_CALL(mock_stream_visitor, OnCanRead()).Times(1); EXPECT_CALL(mock_session_, AcceptIncomingBidirectionalStream()) .WillOnce(Return(nullptr)); session_.OnIncomingBidirectionalStreamAvailable(); } TEST_F(MoqtSessionTest, OnIncomingUnidirectionalStream) { ::testing::InSequence seq; StrictMock<webtransport::test::MockStream> mock_stream; StrictMock<webtransport::test::MockStreamVisitor> mock_stream_visitor; EXPECT_CALL(mock_session_, AcceptIncomingUnidirectionalStream()) .WillOnce(Return(&mock_stream)); EXPECT_CALL(mock_stream, SetVisitor(_)).Times(1); EXPECT_CALL(mock_stream, visitor()).WillOnce(Return(&mock_stream_visitor)); EXPECT_CALL(mock_stream_visitor, OnCanRead()).Times(1); EXPECT_CALL(mock_session_, AcceptIncomingUnidirectionalStream()) .WillOnce(Return(nullptr)); session_.OnIncomingUnidirectionalStreamAvailable(); } TEST_F(MoqtSessionTest, Error) { bool reported_error = false; EXPECT_CALL( mock_session_, CloseSession(static_cast<uint64_t>(MoqtError::kParameterLengthMismatch), "foo")) .Times(1); EXPECT_CALL(session_callbacks_.session_terminated_callback, Call(_)) .WillOnce([&](absl::string_view error_message) { reported_error = (error_message == "foo"); }); session_.Error(MoqtError::kParameterLengthMismatch, "foo"); EXPECT_TRUE(reported_error); } TEST_F(MoqtSessionTest, AddLocalTrack) { MoqtSubscribe request = { 1, 2, "foo", "bar", 0, 0, std::nullopt, std::nullopt, std::nullopt, }; StrictMock<webtransport::test::MockStream> mock_stream; std::unique_ptr<MoqtParserVisitor> stream_input = MoqtSessionPeer::CreateControlStream(&session_, &mock_stream); bool correct_message = false; EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kSubscribeError); return absl::OkStatus(); }); stream_input->OnSubscribeMessage(request); EXPECT_TRUE(correct_message); MockLocalTrackVisitor local_track_visitor; session_.AddLocalTrack(FullTrackName("foo", "bar"), MoqtForwardingPreference::kObject, &local_track_visitor); correct_message = true; EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kSubscribeOk); return absl::OkStatus(); }); stream_input->OnSubscribeMessage(request); EXPECT_TRUE(correct_message); } TEST_F(MoqtSessionTest, AnnounceWithOk) { testing::MockFunction<void( absl::string_view track_namespace, std::optional<MoqtAnnounceErrorReason> error_message)> announce_resolved_callback; StrictMock<webtransport::test::MockStream> mock_stream; std::unique_ptr<MoqtParserVisitor> stream_input = MoqtSessionPeer::CreateControlStream(&session_, &mock_stream); EXPECT_CALL(mock_session_, GetStreamById(_)).WillOnce(Return(&mock_stream)); bool correct_message = true; EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kAnnounce); return absl::OkStatus(); }); session_.Announce("foo", announce_resolved_callback.AsStdFunction()); EXPECT_TRUE(correct_message); MoqtAnnounceOk ok = { "foo", }; correct_message = false; EXPECT_CALL(announce_resolved_callback, Call(_, _)) .WillOnce([&](absl::string_view track_namespace, std::optional<MoqtAnnounceErrorReason> error) { correct_message = true; EXPECT_EQ(track_namespace, "foo"); EXPECT_FALSE(error.has_value()); }); stream_input->OnAnnounceOkMessage(ok); EXPECT_TRUE(correct_message); } TEST_F(MoqtSessionTest, AnnounceWithError) { testing::MockFunction<void( absl::string_view track_namespace, std::optional<MoqtAnnounceErrorReason> error_message)> announce_resolved_callback; StrictMock<webtransport::test::MockStream> mock_stream; std::unique_ptr<MoqtParserVisitor> stream_input = MoqtSessionPeer::CreateControlStream(&session_, &mock_stream); EXPECT_CALL(mock_session_, GetStreamById(_)).WillOnce(Return(&mock_stream)); bool correct_message = true; EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kAnnounce); return absl::OkStatus(); }); session_.Announce("foo", announce_resolved_callback.AsStdFunction()); EXPECT_TRUE(correct_message); MoqtAnnounceError error = { "foo", MoqtAnnounceErrorCode::kInternalError, "Test error", }; correct_message = false; EXPECT_CALL(announce_resolved_callback, Call(_, _)) .WillOnce([&](absl::string_view track_namespace, std::optional<MoqtAnnounceErrorReason> error) { correct_message = true; EXPECT_EQ(track_namespace, "foo"); ASSERT_TRUE(error.has_value()); EXPECT_EQ(error->error_code, MoqtAnnounceErrorCode::kInternalError); EXPECT_EQ(error->reason_phrase, "Test error"); }); stream_input->OnAnnounceErrorMessage(error); EXPECT_TRUE(correct_message); } TEST_F(MoqtSessionTest, HasSubscribers) { MockLocalTrackVisitor local_track_visitor; FullTrackName ftn("foo", "bar"); EXPECT_FALSE(session_.HasSubscribers(ftn)); session_.AddLocalTrack(ftn, MoqtForwardingPreference::kGroup, &local_track_visitor); EXPECT_FALSE(session_.HasSubscribers(ftn)); MoqtSubscribe request = { 1, 2, "foo", "bar", 0, 0, std::nullopt, std::nullopt, std::nullopt, }; StrictMock<webtransport::test::MockStream> mock_stream; std::unique_ptr<MoqtParserVisitor> stream_input = MoqtSessionPeer::CreateControlStream(&session_, &mock_stream); bool correct_message = true; EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kSubscribeOk); return absl::OkStatus(); }); stream_input->OnSubscribeMessage(request); EXPECT_TRUE(correct_message); EXPECT_TRUE(session_.HasSubscribers(ftn)); } TEST_F(MoqtSessionTest, SubscribeForPast) { MockLocalTrackVisitor local_track_visitor; FullTrackName ftn("foo", "bar"); session_.AddLocalTrack(ftn, MoqtForwardingPreference::kObject, &local_track_visitor); session_.PublishObject(ftn, 2, 0, 0, MoqtObjectStatus::kNormal, "foo"); MoqtSubscribe request = { 1, 2, "foo", "bar", 0, 0, std::nullopt, std::nullopt, std::nullopt, }; StrictMock<webtransport::test::MockStream> mock_stream; std::unique_ptr<MoqtParserVisitor> stream_input = MoqtSessionPeer::CreateControlStream(&session_, &mock_stream); bool correct_message = true; EXPECT_CALL(local_track_visitor, OnSubscribeForPast(_)).WillOnce(Return([] { })); EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kSubscribeOk); return absl::OkStatus(); }); stream_input->OnSubscribeMessage(request); EXPECT_TRUE(correct_message); } TEST_F(MoqtSessionTest, SubscribeWithOk) { StrictMock<webtransport::test::MockStream> mock_stream; std::unique_ptr<MoqtParserVisitor> stream_input = MoqtSessionPeer::CreateControlStream(&session_, &mock_stream); MockRemoteTrackVisitor remote_track_visitor; EXPECT_CALL(mock_session_, GetStreamById(_)).WillOnce(Return(&mock_stream)); bool correct_message = true; EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kSubscribe); return absl::OkStatus(); }); session_.SubscribeCurrentGroup("foo", "bar", &remote_track_visitor, ""); MoqtSubscribeOk ok = { 0, quic::QuicTimeDelta::FromMilliseconds(0), }; correct_message = false; EXPECT_CALL(remote_track_visitor, OnReply(_, _)) .WillOnce([&](const FullTrackName& ftn, std::optional<absl::string_view> error_message) { correct_message = true; EXPECT_EQ(ftn, FullTrackName("foo", "bar")); EXPECT_FALSE(error_message.has_value()); }); stream_input->OnSubscribeOkMessage(ok); EXPECT_TRUE(correct_message); } TEST_F(MoqtSessionTest, SubscribeWithError) { StrictMock<webtransport::test::MockStream> mock_stream; std::unique_ptr<MoqtParserVisitor> stream_input = MoqtSessionPeer::CreateControlStream(&session_, &mock_stream); MockRemoteTrackVisitor remote_track_visitor; EXPECT_CALL(mock_session_, GetStreamById(_)).WillOnce(Return(&mock_stream)); bool correct_message = true; EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kSubscribe); return absl::OkStatus(); }); session_.SubscribeCurrentGroup("foo", "bar", &remote_track_visitor, ""); MoqtSubscribeError error = { 0, SubscribeErrorCode::kInvalidRange, "deadbeef", 2, }; correct_message = false; EXPECT_CALL(remote_track_visitor, OnReply(_, _)) .WillOnce([&](const FullTrackName& ftn, std::optional<absl::string_view> error_message) { correct_message = true; EXPECT_EQ(ftn, FullTrackName("foo", "bar")); EXPECT_EQ(*error_message, "deadbeef"); }); stream_input->OnSubscribeErrorMessage(error); EXPECT_TRUE(correct_message); } TEST_F(MoqtSessionTest, ReplyToAnnounce) { StrictMock<webtransport::test::MockStream> mock_stream; std::unique_ptr<MoqtParserVisitor> stream_input = MoqtSessionPeer::CreateControlStream(&session_, &mock_stream); MoqtAnnounce announce = { "foo", }; bool correct_message = false; EXPECT_CALL(session_callbacks_.incoming_announce_callback, Call("foo")) .WillOnce(Return(std::nullopt)); EXPECT_CALL(mock_stream, Writev(_, _)) .WillOnce([&](absl::Span<const absl::string_view> data, const quiche::StreamWriteOptions& options) { correct_message = true; EXPECT_EQ(*ExtractMessageType(data[0]), MoqtMessageType::kAnnounceOk); return absl::OkStatus(); }); stream_input->OnAnnounceMessage(announce); EXPECT_TRUE(correct_message); } TEST_F(MoqtSessionTest, IncomingObject) { MockRemoteTrackVisitor visitor_; FullTrackName ftn("foo", "bar"); std::string payload = "deadbeef"; MoqtSessionPeer::CreateRemoteTrack(&session_, ftn, &visitor_, 2); MoqtObject object = { 1, 2, 0, 0, 0, MoqtObjectStatus::kNormal, MoqtForwardingPreference::kGroup, 8, }; StrictMock<webtransport::test::MockStream> mock_stream; std::unique_ptr<MoqtParserVisitor> object_stream = MoqtSessionPeer::CreateUniStream(&session_, &mock_stream); EXPECT_CALL(visitor_, OnObjectFragment(_, _, _, _, _, _, _, _)).Times(1); EXPECT_CALL(mock_stream, GetStreamId()) .WillRepeatedly(Return(kIncomingUniStreamId)); object_stream->OnObjectMessage(object, payload, true); } TEST_F(MoqtSessionTest, IncomingPartialObject) { MockRemoteTrackVisitor visitor_; FullTrackName ftn("foo", "bar"); std::string payload = "deadbeef"; MoqtSessionPeer::CreateRemoteTrack(&session_, ftn, &visitor_, 2); MoqtObject object = { 1, 2, 0, 0, 0, MoqtObjectStatus::kNormal, MoqtForwardingPreference::kGroup, 16, }; StrictMock<webtransport::test::MockStream> mock_stream; std::unique_ptr<MoqtParserVisitor> object_stream = MoqtSessionPeer::CreateUniStream(&session_, &mock_stream); EXPECT_CALL(visitor_, OnObjectFragment(_, _, _, _, _, _, _, _)).Times(1); EXPECT_CALL(mock_stream, GetStreamId()) .WillRepeatedly(Return(kIncomingUniStreamId)); object_stream->OnObjectMessage(object, payload, false); object_stream->OnObjectMessage(object, payload, true); } TEST_F(MoqtSessionTest, IncomingPartialObjectNoBuffer) { MoqtSessionParameters parameters = { MoqtVersion::kDraft04, quic::Perspective::IS_CLIENT, true, "", true, }; MoqtSession session(&mock_session_, parameters, session_callbacks_.AsSessionCallbacks()); MockRemoteTrackVisitor visitor_; FullTrackName ftn("foo", "bar"); std::string payload = "deadbeef"; MoqtSessionPeer::CreateRemoteTrack(&session, ftn, &visitor_, 2); MoqtObject object = { 1, 2, 0, 0, 0, MoqtObjectStatus::kNormal, MoqtForwardingPreference::kGroup, 16, }; StrictMock<webtransport::test::MockStream> mock_stream; std::unique_ptr<MoqtParserVisitor> object_stream = MoqtSessionPeer::CreateUniStream(&session, &mock_stream); EXPECT_CALL(visitor_, OnObjectFragment(_, _, _, _, _, _, _, _)).Times(2); EXPECT_CALL(mock_stream, GetStreamId()) .WillRepeatedly(Return(kIncomingUniStreamId)); object_stream->OnObjectMessage(object, payload, false); object_stream->OnObjectMessage(object, payload, true); } TEST_F(MoqtSessionTest, ObjectBeforeSubscribeOk) { MockRemoteTrackVisitor visitor_; FullTrackName ftn("foo", "bar"); std::string payload = "deadbeef"; MoqtSubscribe subscribe = { 1, 2, ftn.track_namespace, ftn.track_name, 0, 0, std::nullopt, std::nullopt, }; MoqtSessionPeer::AddActiveSubscribe(&session_, 1, subscribe, &visitor_); MoqtObject object = { 1, 2, 0, 0, 0, MoqtObjectStatus::kNormal, MoqtForwardingPreference::kGroup, 8, }; StrictMock<webtransport::test::MockStream> mock_stream; std::unique_ptr<MoqtParserVisitor> object_stream = MoqtSessionPeer::CreateUniStream(&session_, &mock_stream); EXPECT_CALL(visitor_, OnObjectFragment(_, _, _, _, _, _, _, _)) .WillOnce([&](const FullTrackName& full_track_name, uint64_t group_sequence, uint64_t object_sequence, uint64_t object_send_order, MoqtObjectStatus status, MoqtForwardingPreference forwarding_preference, absl::string_view payload, bool end_of_message) { EXPECT_EQ(full_track_name, ftn); EXPECT_EQ(group_sequence, object.group_id); EXPECT_EQ(object_sequence, object.object_id); }); EXPECT_CALL(mock_stream, GetStreamId()) .WillRepeatedly(Return(kIncomingUniStreamId)); object_stream->OnObjectMessage(object, payload, true); MoqtSubscribeOk ok = { 1, quic::QuicTimeDelta::FromMilliseconds(0), std::nullopt, }; StrictMock<webtransport::test::MockStream> mock_control_stream; std::unique_ptr<MoqtParserVisitor> control_stream = MoqtSessionPeer::CreateControlStream(&session_, &mock_control_stream); EXPECT_CALL(visitor_, OnReply(_, _)).Times(1); control_stream->OnSubscribeOkMessage(ok); } TEST_F(MoqtSessionTest, ObjectBeforeSubscribeError) { MockRemoteTrackVisitor visitor; FullTrackName ftn("foo", "bar"); std::string payload = "deadbeef"; MoqtSubscribe subscribe = { 1, 2, ftn.track_namespace, ftn.track_name, 0, 0, std::nullopt, std::nullopt, }; MoqtSessionPeer::AddActiveSubscribe(&session_, 1, subscribe, &visitor); MoqtObject object = { 1, 2, 0, 0, 0, MoqtObjectStatus::kNormal, MoqtForwardingPreference::kGroup, 8, }; StrictMock<webtransport::test::MockStream> mock_stream; std::unique_ptr<MoqtParserVisitor> object_stream = MoqtSessionPeer::CreateUniStream(&session_, &mock_stream); EXPECT_CALL(visitor, OnObjectFragment(_, _, _, _, _, _, _, _)) .WillOnce([&](const FullTrackName& full_track_name, uint64_t group_sequence, uint64_t object_sequence, uint64_t object_send_order, MoqtObjectStatus status, MoqtForwardingPreference forwarding_preference, absl::string_view payload, bool end_of_message) { EXPECT_EQ(full_track_name, ftn); EXPECT_EQ(group_sequence, object.group_id); EXPECT_EQ(object_sequence, object.object_id); }); EXPECT_CALL(mock_stream, GetStreamId()) .WillRepeatedly(Return(kIncomingUniStreamId)); object_stream->OnObjectMessage(object, payload, true); MoqtSubscribeError subscribe_error = { 1, SubscribeErrorCode::kRetryTrackAlias, "foo", 3, }; StrictMock<webtransport::test::MockStream> mock_control_stream; std::unique_ptr<MoqtParserVisitor> control_stream = MoqtSessionPeer::CreateControlStream(&session_, &mock_control_stream); EXPECT_CALL(mock_session_, CloseSession(static_cast<uint64_t>(MoqtError::kProtocolViolation), "Received SUBSCRIBE_ERROR after object")) .Times(1); control_stream->OnSubscribeErrorMessage(subscribe_error); } TEST_F(MoqtSessionTest, TwoEarlyObjectsDifferentForwarding) { MockRemoteTrackVisitor visitor; FullTrackName ftn("foo", "bar"); std::string payload = "deadbeef"; MoqtSubscribe subscribe = { 1, 2, ftn.track_namespace, ftn.track_name, 0, 0, std::nullopt, std::nullopt, }; MoqtSessionPeer::AddActiveSubscribe(&session_, 1, subscribe, &visitor); MoqtObject object = { 1, 2, 0, 0, 0, MoqtObjectStatus::kNormal, MoqtForwardingPreference::kGroup, 8, }; StrictMock<webtransport::test::MockStream> mock_stream; std::unique_ptr<MoqtParserVisitor> object_stream = MoqtSessionPeer::CreateUniStream(&session_, &mock_stream); EXPECT_CALL(visitor, OnObjectFragment(_, _, _, _, _, _, _, _)) .WillOnce([&](const FullTrackName& full_track_name, uint64_t group_sequence, uint64_t object_sequence, uint64_t object_send_order, MoqtObjectStatus status, MoqtForwardingPreference forwarding_preference, absl::string_view payload, bool end_of_message) { EXPECT_EQ(full_track_name, ftn); EXPECT_EQ(group_sequence, object.group_id); EXPECT_EQ(object_sequence, object.object_id); }); EXPECT_CALL(mock_stream, GetStreamId()) .WillRepeatedly(Return(kIncomingUniStreamId)); object_stream->OnObjectMessage(object, payload, true); object.forwarding_preference = MoqtForwardingPreference::kObject; ++object.object_id; EXPECT_CALL(mock_session_, CloseSession(static_cast<uint64_t>(MoqtError::kProtocolViolation), "Forwarding preference changes mid-track")) .Times(1); object_stream->OnObjectMessage(object, payload, true); } TEST_F(MoqtSessionTest, EarlyObjectForwardingDoesNotMatchTrack) { MockRemoteTrackVisitor visitor; FullTrackName ftn("foo", "bar"); std::string payload = "deadbeef"; MoqtSubscribe subscribe = { 1, 2, ftn.track_namespace, ftn.track_name, 0, 0, std::nullopt, std::nullopt, }; MoqtSessionPeer::AddActiveSubscribe(&session_, 1, subscribe, &visitor); MoqtObject object = { 1, 2, 0, 0, 0, MoqtObjectStatus::kNormal, MoqtForwardingPreference::kGroup,
372
cpp
google/quiche
moqt_subscribe_windows
quiche/quic/moqt/moqt_subscribe_windows.cc
quiche/quic/moqt/moqt_subscribe_windows_test.cc
#ifndef QUICHE_QUIC_MOQT_SUBSCRIBE_WINDOWS_H #define QUICHE_QUIC_MOQT_SUBSCRIBE_WINDOWS_H #include <cstdint> #include <optional> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/node_hash_map.h" #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/web_transport/web_transport.h" namespace moqt { class QUICHE_EXPORT SubscribeWindow { public: SubscribeWindow(uint64_t subscribe_id, MoqtForwardingPreference forwarding_preference, FullSequence next_object, uint64_t start_group, uint64_t start_object) : SubscribeWindow(subscribe_id, forwarding_preference, next_object, FullSequence(start_group, start_object), std::nullopt) { } SubscribeWindow(uint64_t subscribe_id, MoqtForwardingPreference forwarding_preference, FullSequence next_object, uint64_t start_group, uint64_t start_object, uint64_t end_group, uint64_t end_object) : SubscribeWindow(subscribe_id, forwarding_preference, next_object, FullSequence(start_group, start_object), FullSequence(end_group, end_object)) {} SubscribeWindow(uint64_t subscribe_id, MoqtForwardingPreference forwarding_preference, FullSequence next_object, FullSequence start, std::optional<FullSequence> end) : subscribe_id_(subscribe_id), start_(start), end_(end), original_next_object_(next_object), forwarding_preference_(forwarding_preference) { next_to_backfill_ = (start < next_object) ? start : std::optional<FullSequence>(); } uint64_t subscribe_id() const { return subscribe_id_; } bool InWindow(const FullSequence& seq) const; std::optional<webtransport::StreamId> GetStreamForSequence( FullSequence sequence) const; void AddStream(uint64_t group_id, uint64_t object_id, webtransport::StreamId stream_id); void RemoveStream(uint64_t group_id, uint64_t object_id); bool HasEnd() const { return end_.has_value(); } MoqtForwardingPreference forwarding_preference() const { return forwarding_preference_; } bool OnObjectSent(FullSequence sequence, MoqtObjectStatus status); std::optional<FullSequence>& largest_delivered() { return largest_delivered_; } bool UpdateStartEnd(FullSequence start, std::optional<FullSequence> end); private: FullSequence SequenceToIndex(FullSequence sequence) const; const uint64_t subscribe_id_; FullSequence start_; std::optional<FullSequence> end_; std::optional<FullSequence> largest_delivered_; std::optional<FullSequence> next_to_backfill_; const FullSequence original_next_object_; absl::flat_hash_map<FullSequence, webtransport::StreamId> send_streams_; const MoqtForwardingPreference forwarding_preference_; }; class QUICHE_EXPORT MoqtSubscribeWindows { public: MoqtSubscribeWindows(MoqtForwardingPreference forwarding_preference) : forwarding_preference_(forwarding_preference) {} std::vector<SubscribeWindow*> SequenceIsSubscribed(FullSequence sequence); void AddWindow(uint64_t subscribe_id, FullSequence next_object, uint64_t start_group, uint64_t start_object) { windows_.emplace(subscribe_id, SubscribeWindow(subscribe_id, forwarding_preference_, next_object, start_group, start_object)); } void AddWindow(uint64_t subscribe_id, FullSequence next_object, uint64_t start_group, uint64_t start_object, uint64_t end_group, uint64_t end_object) { windows_.emplace( subscribe_id, SubscribeWindow(subscribe_id, forwarding_preference_, next_object, start_group, start_object, end_group, end_object)); } void RemoveWindow(uint64_t subscribe_id) { windows_.erase(subscribe_id); } bool IsEmpty() const { return windows_.empty(); } SubscribeWindow* GetWindow(uint64_t subscribe_id) { auto it = windows_.find(subscribe_id); if (it == windows_.end()) { return nullptr; } return &it->second; } private: absl::node_hash_map<uint64_t, SubscribeWindow> windows_; const MoqtForwardingPreference forwarding_preference_; }; } #endif #include "quiche/quic/moqt/moqt_subscribe_windows.h" #include <cstdint> #include <optional> #include <vector> #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/web_transport/web_transport.h" namespace moqt { bool SubscribeWindow::InWindow(const FullSequence& seq) const { if (seq < start_) { return false; } return (!end_.has_value() || seq <= *end_); } std::optional<webtransport::StreamId> SubscribeWindow::GetStreamForSequence( FullSequence sequence) const { FullSequence index = SequenceToIndex(sequence); auto stream_it = send_streams_.find(index); if (stream_it == send_streams_.end()) { return std::nullopt; } return stream_it->second; } void SubscribeWindow::AddStream(uint64_t group_id, uint64_t object_id, webtransport::StreamId stream_id) { if (!InWindow(FullSequence(group_id, object_id))) { return; } FullSequence index = SequenceToIndex(FullSequence(group_id, object_id)); if (forwarding_preference_ == MoqtForwardingPreference::kDatagram) { QUIC_BUG(quic_bug_moqt_draft_03_01) << "Adding a stream for datagram"; return; } auto stream_it = send_streams_.find(index); if (stream_it != send_streams_.end()) { QUIC_BUG(quic_bug_moqt_draft_03_02) << "Stream already added"; return; } send_streams_[index] = stream_id; } void SubscribeWindow::RemoveStream(uint64_t group_id, uint64_t object_id) { FullSequence index = SequenceToIndex(FullSequence(group_id, object_id)); send_streams_.erase(index); } bool SubscribeWindow::OnObjectSent(FullSequence sequence, MoqtObjectStatus status) { if (!largest_delivered_.has_value() || *largest_delivered_ < sequence) { largest_delivered_ = sequence; } if (sequence < original_next_object_ && next_to_backfill_.has_value() && *next_to_backfill_ <= sequence) { switch (status) { case MoqtObjectStatus::kNormal: case MoqtObjectStatus::kObjectDoesNotExist: next_to_backfill_ = sequence.next(); break; case MoqtObjectStatus::kEndOfGroup: next_to_backfill_ = FullSequence(sequence.group + 1, 0); break; default: next_to_backfill_ = std::nullopt; break; } if (next_to_backfill_ == original_next_object_ || *next_to_backfill_ == end_) { next_to_backfill_ = std::nullopt; } } return (!next_to_backfill_.has_value() && end_.has_value() && *end_ <= sequence); } bool SubscribeWindow::UpdateStartEnd(FullSequence start, std::optional<FullSequence> end) { if (!InWindow(start)) { return false; } if (end_.has_value() && (!end.has_value() || *end_ < *end)) { return false; } start_ = start; end_ = end; return true; } FullSequence SubscribeWindow::SequenceToIndex(FullSequence sequence) const { switch (forwarding_preference_) { case MoqtForwardingPreference::kTrack: return FullSequence(0, 0); case MoqtForwardingPreference::kGroup: return FullSequence(sequence.group, 0); case MoqtForwardingPreference::kObject: return sequence; case MoqtForwardingPreference::kDatagram: QUIC_BUG(quic_bug_moqt_draft_03_01) << "No stream for datagram"; return FullSequence(0, 0); } } std::vector<SubscribeWindow*> MoqtSubscribeWindows::SequenceIsSubscribed( FullSequence sequence) { std::vector<SubscribeWindow*> retval; for (auto& [subscribe_id, window] : windows_) { if (window.InWindow(sequence)) { retval.push_back(&(window)); } } return retval; } }
#include "quiche/quic/moqt/moqt_subscribe_windows.h" #include <cstdint> #include <optional> #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/common/platform/api/quiche_export.h" namespace moqt { namespace test { class QUICHE_EXPORT SubscribeWindowTest : public quic::test::QuicTest { public: SubscribeWindowTest() {} const uint64_t subscribe_id_ = 2; const FullSequence right_edge_{4, 5}; const FullSequence start_{4, 0}; const FullSequence end_{5, 5}; }; TEST_F(SubscribeWindowTest, Queries) { SubscribeWindow window(subscribe_id_, MoqtForwardingPreference::kObject, right_edge_, start_, end_); EXPECT_EQ(window.subscribe_id(), 2); EXPECT_TRUE(window.InWindow(FullSequence(4, 0))); EXPECT_TRUE(window.InWindow(FullSequence(5, 5))); EXPECT_FALSE(window.InWindow(FullSequence(5, 6))); EXPECT_FALSE(window.InWindow(FullSequence(6, 0))); EXPECT_FALSE(window.InWindow(FullSequence(3, 12))); } TEST_F(SubscribeWindowTest, AddQueryRemoveStreamIdTrack) { SubscribeWindow window(subscribe_id_, MoqtForwardingPreference::kTrack, right_edge_, start_, end_); window.AddStream(4, 0, 2); EXPECT_QUIC_BUG(window.AddStream(5, 2, 6), "Stream already added"); EXPECT_EQ(*window.GetStreamForSequence(FullSequence(5, 2)), 2); window.RemoveStream(7, 2); EXPECT_FALSE(window.GetStreamForSequence(FullSequence(4, 0)).has_value()); } TEST_F(SubscribeWindowTest, AddQueryRemoveStreamIdGroup) { SubscribeWindow window(subscribe_id_, MoqtForwardingPreference::kGroup, right_edge_, start_, end_); window.AddStream(4, 0, 2); EXPECT_FALSE(window.GetStreamForSequence(FullSequence(5, 0)).has_value()); window.AddStream(5, 2, 6); EXPECT_QUIC_BUG(window.AddStream(5, 3, 6), "Stream already added"); EXPECT_EQ(*window.GetStreamForSequence(FullSequence(4, 1)), 2); EXPECT_EQ(*window.GetStreamForSequence(FullSequence(5, 0)), 6); window.RemoveStream(5, 1); EXPECT_FALSE(window.GetStreamForSequence(FullSequence(5, 2)).has_value()); } TEST_F(SubscribeWindowTest, AddQueryRemoveStreamIdObject) { SubscribeWindow window(subscribe_id_, MoqtForwardingPreference::kObject, right_edge_, start_, end_); window.AddStream(4, 0, 2); window.AddStream(4, 1, 6); window.AddStream(4, 2, 10); EXPECT_QUIC_BUG(window.AddStream(4, 2, 14), "Stream already added"); EXPECT_EQ(*window.GetStreamForSequence(FullSequence(4, 0)), 2); EXPECT_EQ(*window.GetStreamForSequence(FullSequence(4, 2)), 10); EXPECT_FALSE(window.GetStreamForSequence(FullSequence(4, 4)).has_value()); EXPECT_FALSE(window.GetStreamForSequence(FullSequence(5, 0)).has_value()); window.RemoveStream(4, 2); EXPECT_FALSE(window.GetStreamForSequence(FullSequence(4, 2)).has_value()); } TEST_F(SubscribeWindowTest, AddQueryRemoveStreamIdDatagram) { SubscribeWindow window(subscribe_id_, MoqtForwardingPreference::kDatagram, right_edge_, start_, end_); EXPECT_QUIC_BUG(window.AddStream(4, 0, 2), "Adding a stream for datagram"); } TEST_F(SubscribeWindowTest, OnObjectSent) { SubscribeWindow window(subscribe_id_, MoqtForwardingPreference::kObject, right_edge_, start_, end_); EXPECT_FALSE(window.largest_delivered().has_value()); EXPECT_FALSE( window.OnObjectSent(FullSequence(4, 1), MoqtObjectStatus::kNormal)); EXPECT_TRUE(window.largest_delivered().has_value()); EXPECT_EQ(window.largest_delivered().value(), FullSequence(4, 1)); EXPECT_FALSE( window.OnObjectSent(FullSequence(4, 2), MoqtObjectStatus::kNormal)); EXPECT_EQ(window.largest_delivered().value(), FullSequence(4, 2)); EXPECT_FALSE( window.OnObjectSent(FullSequence(4, 0), MoqtObjectStatus::kNormal)); EXPECT_EQ(window.largest_delivered().value(), FullSequence(4, 2)); } TEST_F(SubscribeWindowTest, AllObjectsUnpublishedAtStart) { SubscribeWindow window(subscribe_id_, MoqtForwardingPreference::kObject, FullSequence(0, 0), FullSequence(0, 0), FullSequence(0, 1)); EXPECT_FALSE( window.OnObjectSent(FullSequence(0, 0), MoqtObjectStatus::kNormal)); EXPECT_TRUE( window.OnObjectSent(FullSequence(0, 1), MoqtObjectStatus::kNormal)); } TEST_F(SubscribeWindowTest, AllObjectsPublishedAtStart) { SubscribeWindow window(subscribe_id_, MoqtForwardingPreference::kObject, FullSequence(4, 0), FullSequence(0, 0), FullSequence(0, 1)); EXPECT_FALSE( window.OnObjectSent(FullSequence(0, 0), MoqtObjectStatus::kNormal)); EXPECT_TRUE( window.OnObjectSent(FullSequence(0, 1), MoqtObjectStatus::kNormal)); } TEST_F(SubscribeWindowTest, SomeObjectsUnpublishedAtStart) { SubscribeWindow window(subscribe_id_, MoqtForwardingPreference::kObject, FullSequence(0, 1), FullSequence(0, 0), FullSequence(0, 1)); EXPECT_FALSE( window.OnObjectSent(FullSequence(0, 0), MoqtObjectStatus::kNormal)); EXPECT_TRUE( window.OnObjectSent(FullSequence(0, 1), MoqtObjectStatus::kNormal)); } TEST_F(SubscribeWindowTest, UpdateStartEnd) { SubscribeWindow window(subscribe_id_, MoqtForwardingPreference::kObject, right_edge_, start_, end_); EXPECT_TRUE(window.UpdateStartEnd(start_.next(), FullSequence(end_.group, end_.object - 1))); EXPECT_FALSE(window.InWindow(FullSequence(start_.group, start_.object))); EXPECT_FALSE(window.InWindow(FullSequence(end_.group, end_.object))); EXPECT_FALSE( window.UpdateStartEnd(start_, FullSequence(end_.group, end_.object - 1))); EXPECT_FALSE(window.UpdateStartEnd(start_.next(), end_)); } TEST_F(SubscribeWindowTest, UpdateStartEndOpenEnded) { SubscribeWindow window(subscribe_id_, MoqtForwardingPreference::kObject, right_edge_, start_, std::nullopt); EXPECT_TRUE(window.UpdateStartEnd(start_, end_)); EXPECT_FALSE(window.InWindow(end_.next())); EXPECT_FALSE(window.UpdateStartEnd(start_, std::nullopt)); } class QUICHE_EXPORT MoqtSubscribeWindowsTest : public quic::test::QuicTest { public: MoqtSubscribeWindowsTest() : windows_(MoqtForwardingPreference::kObject) {} MoqtSubscribeWindows windows_; }; TEST_F(MoqtSubscribeWindowsTest, IsEmpty) { EXPECT_TRUE(windows_.IsEmpty()); windows_.AddWindow(0, FullSequence(2, 1), 1, 3); EXPECT_FALSE(windows_.IsEmpty()); } TEST_F(MoqtSubscribeWindowsTest, IsSubscribed) { EXPECT_TRUE(windows_.IsEmpty()); windows_.AddWindow(0, FullSequence(0, 0), 1, 0, 3, 9); windows_.AddWindow(1, FullSequence(0, 0), 2, 4, 4, 3); windows_.AddWindow(2, FullSequence(0, 0), 10, 0); EXPECT_FALSE(windows_.IsEmpty()); EXPECT_TRUE(windows_.SequenceIsSubscribed(FullSequence(0, 8)).empty()); auto hits = windows_.SequenceIsSubscribed(FullSequence(1, 0)); EXPECT_EQ(hits.size(), 1); EXPECT_EQ(hits[0]->subscribe_id(), 0); EXPECT_TRUE(windows_.SequenceIsSubscribed(FullSequence(4, 4)).empty()); EXPECT_TRUE(windows_.SequenceIsSubscribed(FullSequence(8, 3)).empty()); hits = windows_.SequenceIsSubscribed(FullSequence(100, 7)); EXPECT_EQ(hits.size(), 1); EXPECT_EQ(hits[0]->subscribe_id(), 2); hits = windows_.SequenceIsSubscribed(FullSequence(3, 0)); EXPECT_EQ(hits.size(), 2); EXPECT_EQ(hits[0]->subscribe_id() + hits[1]->subscribe_id(), 1); } TEST_F(MoqtSubscribeWindowsTest, AddGetRemoveWindow) { windows_.AddWindow(0, FullSequence(2, 5), 1, 0, 3, 9); SubscribeWindow* window = windows_.GetWindow(0); EXPECT_EQ(window->subscribe_id(), 0); EXPECT_EQ(windows_.GetWindow(1), nullptr); windows_.RemoveWindow(0); EXPECT_EQ(windows_.GetWindow(0), nullptr); } } }
373
cpp
google/quiche
moqt_outgoing_queue
quiche/quic/moqt/moqt_outgoing_queue.cc
quiche/quic/moqt/moqt_outgoing_queue_test.cc
#ifndef QUICHE_QUIC_MOQT_TOOLS_MOQT_OUTGOING_QUEUE_H_ #define QUICHE_QUIC_MOQT_TOOLS_MOQT_OUTGOING_QUEUE_H_ #include <cstddef> #include <cstdint> #include <optional> #include <utility> #include <vector> #include "absl/container/inlined_vector.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/quic/moqt/moqt_session.h" #include "quiche/quic/moqt/moqt_subscribe_windows.h" #include "quiche/quic/moqt/moqt_track.h" #include "quiche/common/platform/api/quiche_mem_slice.h" namespace moqt { class MoqtOutgoingQueue : public LocalTrack::Visitor { public: explicit MoqtOutgoingQueue(MoqtSession* session, FullTrackName track) : session_(session), track_(std::move(track)) {} MoqtOutgoingQueue(const MoqtOutgoingQueue&) = delete; MoqtOutgoingQueue(MoqtOutgoingQueue&&) = default; MoqtOutgoingQueue& operator=(const MoqtOutgoingQueue&) = delete; MoqtOutgoingQueue& operator=(MoqtOutgoingQueue&&) = default; void AddObject(quiche::QuicheMemSlice payload, bool key); absl::StatusOr<PublishPastObjectsCallback> OnSubscribeForPast( const SubscribeWindow& window) override; protected: virtual void CloseStreamForGroup(uint64_t group_id); virtual void PublishObject(uint64_t group_id, uint64_t object_id, absl::string_view payload); private: static constexpr size_t kMaxQueuedGroups = 3; using Object = quiche::QuicheMemSlice; using Group = std::vector<Object>; uint64_t first_group_in_queue() { return current_group_id_ - queue_.size() + 1; } MoqtSession* session_; FullTrackName track_; absl::InlinedVector<Group, kMaxQueuedGroups> queue_; uint64_t current_group_id_ = -1; }; } #endif #include "quiche/quic/moqt/moqt_outgoing_queue.h" #include <cstddef> #include <cstdint> #include <optional> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/quic/moqt/moqt_subscribe_windows.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_mem_slice.h" namespace moqt { void MoqtOutgoingQueue::AddObject(quiche::QuicheMemSlice payload, bool key) { if (queue_.empty() && !key) { QUICHE_BUG(MoqtOutgoingQueue_AddObject_first_object_not_key) << "The first object ever added to the queue must have the \"key\" " "flag."; return; } if (key) { if (!queue_.empty()) { CloseStreamForGroup(current_group_id_); } if (queue_.size() == kMaxQueuedGroups) { queue_.erase(queue_.begin()); } queue_.emplace_back(); ++current_group_id_; } absl::string_view payload_view = payload.AsStringView(); uint64_t object_id = queue_.back().size(); queue_.back().push_back(std::move(payload)); PublishObject(current_group_id_, object_id, payload_view); } absl::StatusOr<MoqtOutgoingQueue::PublishPastObjectsCallback> MoqtOutgoingQueue::OnSubscribeForPast(const SubscribeWindow& window) { QUICHE_BUG_IF( MoqtOutgoingQueue_requires_kGroup, window.forwarding_preference() != MoqtForwardingPreference::kGroup) << "MoqtOutgoingQueue currently only supports kGroup."; return [this, &window]() { for (size_t i = 0; i < queue_.size(); ++i) { const uint64_t group_id = first_group_in_queue() + i; const Group& group = queue_[i]; const bool is_last_group = ((i == queue_.size() - 1) || !window.InWindow(FullSequence{group_id + 1, 0})); for (size_t j = 0; j < group.size(); ++j) { const FullSequence sequence{group_id, j}; if (!window.InWindow(sequence)) { continue; } const bool is_last_object = (j == group.size() - 1); PublishObject(group_id, j, group[j].AsStringView()); if (!is_last_group && is_last_object) { CloseStreamForGroup(group_id); } } } }; } void MoqtOutgoingQueue::CloseStreamForGroup(uint64_t group_id) { session_->PublishObject(track_, group_id, queue_[group_id].size(), group_id, MoqtObjectStatus::kEndOfGroup, ""); session_->CloseObjectStream(track_, group_id); } void MoqtOutgoingQueue::PublishObject(uint64_t group_id, uint64_t object_id, absl::string_view payload) { session_->PublishObject(track_, group_id, object_id, group_id, MoqtObjectStatus::kNormal, payload); } }
#include "quiche/quic/moqt/moqt_outgoing_queue.h" #include <cstdint> #include <utility> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "quiche/quic/moqt/moqt_messages.h" #include "quiche/quic/moqt/moqt_subscribe_windows.h" #include "quiche/quic/test_tools/quic_test_utils.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 moqt { namespace { using ::quic::test::MemSliceFromString; class TestMoqtOutgoingQueue : public MoqtOutgoingQueue { public: TestMoqtOutgoingQueue() : MoqtOutgoingQueue(nullptr, FullTrackName{"test", "track"}) {} void CallSubscribeForPast(const SubscribeWindow& window) { absl::StatusOr<PublishPastObjectsCallback> callback = OnSubscribeForPast(window); QUICHE_CHECK_OK(callback.status()); (*std::move(callback))(); } MOCK_METHOD(void, CloseStreamForGroup, (uint64_t group_id), (override)); MOCK_METHOD(void, PublishObject, (uint64_t group_id, uint64_t object_id, absl::string_view payload), (override)); }; TEST(MoqtOutgoingQueue, FirstObjectNotKeyframe) { TestMoqtOutgoingQueue queue; EXPECT_QUICHE_BUG(queue.AddObject(MemSliceFromString("a"), false), "The first object"); } TEST(MoqtOutgoingQueue, SingleGroup) { TestMoqtOutgoingQueue queue; { testing::InSequence seq; EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, PublishObject(0, 2, "c")); } queue.AddObject(MemSliceFromString("a"), true); queue.AddObject(MemSliceFromString("b"), false); queue.AddObject(MemSliceFromString("c"), false); } TEST(MoqtOutgoingQueue, SingleGroupPastSubscribeFromZero) { TestMoqtOutgoingQueue queue; { testing::InSequence seq; EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, PublishObject(0, 2, "c")); EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, PublishObject(0, 2, "c")); } queue.AddObject(MemSliceFromString("a"), true); queue.AddObject(MemSliceFromString("b"), false); queue.AddObject(MemSliceFromString("c"), false); queue.CallSubscribeForPast(SubscribeWindow( 0, MoqtForwardingPreference::kGroup, FullSequence(0, 3), 0, 0)); } TEST(MoqtOutgoingQueue, SingleGroupPastSubscribeFromMidGroup) { TestMoqtOutgoingQueue queue; { testing::InSequence seq; EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, PublishObject(0, 2, "c")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, PublishObject(0, 2, "c")); } queue.AddObject(MemSliceFromString("a"), true); queue.AddObject(MemSliceFromString("b"), false); queue.AddObject(MemSliceFromString("c"), false); queue.CallSubscribeForPast(SubscribeWindow( 0, MoqtForwardingPreference::kGroup, FullSequence(0, 3), 0, 1)); } TEST(MoqtOutgoingQueue, TwoGroups) { TestMoqtOutgoingQueue queue; { testing::InSequence seq; EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, PublishObject(0, 2, "c")); EXPECT_CALL(queue, CloseStreamForGroup(0)); EXPECT_CALL(queue, PublishObject(1, 0, "d")); EXPECT_CALL(queue, PublishObject(1, 1, "e")); EXPECT_CALL(queue, PublishObject(1, 2, "f")); } queue.AddObject(MemSliceFromString("a"), true); queue.AddObject(MemSliceFromString("b"), false); queue.AddObject(MemSliceFromString("c"), false); queue.AddObject(MemSliceFromString("d"), true); queue.AddObject(MemSliceFromString("e"), false); queue.AddObject(MemSliceFromString("f"), false); } TEST(MoqtOutgoingQueue, TwoGroupsPastSubscribe) { TestMoqtOutgoingQueue queue; { testing::InSequence seq; EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, PublishObject(0, 2, "c")); EXPECT_CALL(queue, CloseStreamForGroup(0)); EXPECT_CALL(queue, PublishObject(1, 0, "d")); EXPECT_CALL(queue, PublishObject(1, 1, "e")); EXPECT_CALL(queue, PublishObject(1, 2, "f")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, PublishObject(0, 2, "c")); EXPECT_CALL(queue, CloseStreamForGroup(0)); EXPECT_CALL(queue, PublishObject(1, 0, "d")); EXPECT_CALL(queue, PublishObject(1, 1, "e")); EXPECT_CALL(queue, PublishObject(1, 2, "f")); } queue.AddObject(MemSliceFromString("a"), true); queue.AddObject(MemSliceFromString("b"), false); queue.AddObject(MemSliceFromString("c"), false); queue.AddObject(MemSliceFromString("d"), true); queue.AddObject(MemSliceFromString("e"), false); queue.AddObject(MemSliceFromString("f"), false); queue.CallSubscribeForPast(SubscribeWindow( 0, MoqtForwardingPreference::kGroup, FullSequence(1, 3), 0, 1)); } TEST(MoqtOutgoingQueue, FiveGroups) { TestMoqtOutgoingQueue queue; { testing::InSequence seq; EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, CloseStreamForGroup(0)); EXPECT_CALL(queue, PublishObject(1, 0, "c")); EXPECT_CALL(queue, PublishObject(1, 1, "d")); EXPECT_CALL(queue, CloseStreamForGroup(1)); EXPECT_CALL(queue, PublishObject(2, 0, "e")); EXPECT_CALL(queue, PublishObject(2, 1, "f")); EXPECT_CALL(queue, CloseStreamForGroup(2)); EXPECT_CALL(queue, PublishObject(3, 0, "g")); EXPECT_CALL(queue, PublishObject(3, 1, "h")); EXPECT_CALL(queue, CloseStreamForGroup(3)); EXPECT_CALL(queue, PublishObject(4, 0, "i")); EXPECT_CALL(queue, PublishObject(4, 1, "j")); } queue.AddObject(MemSliceFromString("a"), true); queue.AddObject(MemSliceFromString("b"), false); queue.AddObject(MemSliceFromString("c"), true); queue.AddObject(MemSliceFromString("d"), false); queue.AddObject(MemSliceFromString("e"), true); queue.AddObject(MemSliceFromString("f"), false); queue.AddObject(MemSliceFromString("g"), true); queue.AddObject(MemSliceFromString("h"), false); queue.AddObject(MemSliceFromString("i"), true); queue.AddObject(MemSliceFromString("j"), false); } TEST(MoqtOutgoingQueue, FiveGroupsPastSubscribe) { TestMoqtOutgoingQueue queue; { testing::InSequence seq; EXPECT_CALL(queue, PublishObject(0, 0, "a")); EXPECT_CALL(queue, PublishObject(0, 1, "b")); EXPECT_CALL(queue, CloseStreamForGroup(0)); EXPECT_CALL(queue, PublishObject(1, 0, "c")); EXPECT_CALL(queue, PublishObject(1, 1, "d")); EXPECT_CALL(queue, CloseStreamForGroup(1)); EXPECT_CALL(queue, PublishObject(2, 0, "e")); EXPECT_CALL(queue, PublishObject(2, 1, "f")); EXPECT_CALL(queue, CloseStreamForGroup(2)); EXPECT_CALL(queue, PublishObject(3, 0, "g")); EXPECT_CALL(queue, PublishObject(3, 1, "h")); EXPECT_CALL(queue, CloseStreamForGroup(3)); EXPECT_CALL(queue, PublishObject(4, 0, "i")); EXPECT_CALL(queue, PublishObject(4, 1, "j")); EXPECT_CALL(queue, PublishObject(2, 0, "e")); EXPECT_CALL(queue, PublishObject(2, 1, "f")); EXPECT_CALL(queue, CloseStreamForGroup(2)); EXPECT_CALL(queue, PublishObject(3, 0, "g")); EXPECT_CALL(queue, PublishObject(3, 1, "h")); EXPECT_CALL(queue, CloseStreamForGroup(3)); EXPECT_CALL(queue, PublishObject(4, 0, "i")); EXPECT_CALL(queue, PublishObject(4, 1, "j")); } queue.AddObject(MemSliceFromString("a"), true); queue.AddObject(MemSliceFromString("b"), false); queue.AddObject(MemSliceFromString("c"), true); queue.AddObject(MemSliceFromString("d"), false); queue.AddObject(MemSliceFromString("e"), true); queue.AddObject(MemSliceFromString("f"), false); queue.AddObject(MemSliceFromString("g"), true); queue.AddObject(MemSliceFromString("h"), false); queue.AddObject(MemSliceFromString("i"), true); queue.AddObject(MemSliceFromString("j"), false); queue.CallSubscribeForPast(SubscribeWindow( 0, MoqtForwardingPreference::kGroup, FullSequence(4, 2), 0, 0)); } } }
374
cpp
google/quiche
simple_session_notifier
quiche/quic/test_tools/simple_session_notifier.cc
quiche/quic/test_tools/simple_session_notifier_test.cc
#ifndef QUICHE_QUIC_TEST_TOOLS_SIMPLE_SESSION_NOTIFIER_H_ #define QUICHE_QUIC_TEST_TOOLS_SIMPLE_SESSION_NOTIFIER_H_ #include "absl/container/flat_hash_map.h" #include "quiche/quic/core/quic_interval_set.h" #include "quiche/quic/core/session_notifier_interface.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/common/quiche_circular_deque.h" #include "quiche/common/quiche_linked_hash_map.h" namespace quic { class QuicConnection; namespace test { class SimpleSessionNotifier : public SessionNotifierInterface { public: explicit SimpleSessionNotifier(QuicConnection* connection); ~SimpleSessionNotifier() override; QuicConsumedData WriteOrBufferData(QuicStreamId id, QuicByteCount data_length, StreamSendingState state); QuicConsumedData WriteOrBufferData(QuicStreamId id, QuicByteCount data_length, StreamSendingState state, TransmissionType transmission_type); void WriteOrBufferRstStream(QuicStreamId id, QuicRstStreamErrorCode error, QuicStreamOffset bytes_written); void WriteOrBufferWindowUpate(QuicStreamId id, QuicStreamOffset byte_offset); void WriteOrBufferPing(); void WriteOrBufferAckFrequency( const QuicAckFrequencyFrame& ack_frequency_frame); size_t WriteCryptoData(EncryptionLevel level, QuicByteCount data_length, QuicStreamOffset offset); void NeuterUnencryptedData(); void OnCanWrite(); void OnStreamReset(QuicStreamId id, QuicRstStreamErrorCode error); bool WillingToWrite() const; QuicByteCount StreamBytesSent() const; QuicByteCount StreamBytesToSend() const; bool HasBufferedStreamData() const; bool StreamIsWaitingForAcks(QuicStreamId id) const; bool OnFrameAcked(const QuicFrame& frame, QuicTime::Delta ack_delay_time, QuicTime receive_timestamp) override; void OnStreamFrameRetransmitted(const QuicStreamFrame& ) override {} void OnFrameLost(const QuicFrame& frame) override; bool RetransmitFrames(const QuicFrames& frames, TransmissionType type) override; bool IsFrameOutstanding(const QuicFrame& frame) const override; bool HasUnackedCryptoData() const override; bool HasUnackedStreamData() const override; bool HasLostStreamData() const; private: struct StreamState { StreamState(); ~StreamState(); QuicByteCount bytes_total; QuicByteCount bytes_sent; QuicIntervalSet<QuicStreamOffset> bytes_acked; QuicIntervalSet<QuicStreamOffset> pending_retransmissions; bool fin_buffered; bool fin_sent; bool fin_outstanding; bool fin_lost; }; friend std::ostream& operator<<(std::ostream& os, const StreamState& s); using StreamMap = absl::flat_hash_map<QuicStreamId, StreamState>; void OnStreamDataConsumed(QuicStreamId id, QuicStreamOffset offset, QuicByteCount data_length, bool fin); bool OnControlFrameAcked(const QuicFrame& frame); void OnControlFrameLost(const QuicFrame& frame); bool RetransmitLostControlFrames(); bool RetransmitLostCryptoData(); bool RetransmitLostStreamData(); bool WriteBufferedControlFrames(); bool WriteBufferedCryptoData(); bool IsControlFrameOutstanding(const QuicFrame& frame) const; bool HasBufferedControlFrames() const; bool StreamHasBufferedData(QuicStreamId id) const; quiche::QuicheCircularDeque<QuicFrame> control_frames_; quiche::QuicheLinkedHashMap<QuicControlFrameId, bool> lost_control_frames_; QuicControlFrameId last_control_frame_id_; QuicControlFrameId least_unacked_; QuicControlFrameId least_unsent_; StreamMap stream_map_; QuicIntervalSet<QuicStreamOffset> crypto_bytes_transferred_[NUM_ENCRYPTION_LEVELS]; StreamState crypto_state_[NUM_ENCRYPTION_LEVELS]; QuicConnection* connection_; }; } } #endif #include "quiche/quic/test_tools/simple_session_notifier.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { namespace test { SimpleSessionNotifier::SimpleSessionNotifier(QuicConnection* connection) : last_control_frame_id_(kInvalidControlFrameId), least_unacked_(1), least_unsent_(1), connection_(connection) {} SimpleSessionNotifier::~SimpleSessionNotifier() { while (!control_frames_.empty()) { DeleteFrame(&control_frames_.front()); control_frames_.pop_front(); } } SimpleSessionNotifier::StreamState::StreamState() : bytes_total(0), bytes_sent(0), fin_buffered(false), fin_sent(false), fin_outstanding(false), fin_lost(false) {} SimpleSessionNotifier::StreamState::~StreamState() {} QuicConsumedData SimpleSessionNotifier::WriteOrBufferData( QuicStreamId id, QuicByteCount data_length, StreamSendingState state) { return WriteOrBufferData(id, data_length, state, NOT_RETRANSMISSION); } QuicConsumedData SimpleSessionNotifier::WriteOrBufferData( QuicStreamId id, QuicByteCount data_length, StreamSendingState state, TransmissionType transmission_type) { if (!stream_map_.contains(id)) { stream_map_[id] = StreamState(); } StreamState& stream_state = stream_map_.find(id)->second; const bool had_buffered_data = HasBufferedStreamData() || HasBufferedControlFrames(); QuicStreamOffset offset = stream_state.bytes_sent; QUIC_DVLOG(1) << "WriteOrBuffer stream_id: " << id << " [" << offset << ", " << offset + data_length << "), fin: " << (state != NO_FIN); stream_state.bytes_total += data_length; stream_state.fin_buffered = state != NO_FIN; if (had_buffered_data) { QUIC_DLOG(WARNING) << "Connection is write blocked"; return {0, false}; } const size_t length = stream_state.bytes_total - stream_state.bytes_sent; connection_->SetTransmissionType(transmission_type); QuicConsumedData consumed = connection_->SendStreamData(id, length, stream_state.bytes_sent, state); QUIC_DVLOG(1) << "consumed: " << consumed; OnStreamDataConsumed(id, stream_state.bytes_sent, consumed.bytes_consumed, consumed.fin_consumed); return consumed; } void SimpleSessionNotifier::OnStreamDataConsumed(QuicStreamId id, QuicStreamOffset offset, QuicByteCount data_length, bool fin) { StreamState& state = stream_map_.find(id)->second; if (QuicUtils::IsCryptoStreamId(connection_->transport_version(), id) && data_length > 0) { crypto_bytes_transferred_[connection_->encryption_level()].Add( offset, offset + data_length); } state.bytes_sent += data_length; state.fin_sent = fin; state.fin_outstanding = fin; } size_t SimpleSessionNotifier::WriteCryptoData(EncryptionLevel level, QuicByteCount data_length, QuicStreamOffset offset) { crypto_state_[level].bytes_total += data_length; size_t bytes_written = connection_->SendCryptoData(level, data_length, offset); crypto_state_[level].bytes_sent += bytes_written; crypto_bytes_transferred_[level].Add(offset, offset + bytes_written); return bytes_written; } void SimpleSessionNotifier::WriteOrBufferRstStream( QuicStreamId id, QuicRstStreamErrorCode error, QuicStreamOffset bytes_written) { QUIC_DVLOG(1) << "Writing RST_STREAM_FRAME"; const bool had_buffered_data = HasBufferedStreamData() || HasBufferedControlFrames(); control_frames_.emplace_back((QuicFrame(new QuicRstStreamFrame( ++last_control_frame_id_, id, error, bytes_written)))); if (error != QUIC_STREAM_NO_ERROR) { stream_map_.erase(id); } if (had_buffered_data) { QUIC_DLOG(WARNING) << "Connection is write blocked"; return; } WriteBufferedControlFrames(); } void SimpleSessionNotifier::WriteOrBufferWindowUpate( QuicStreamId id, QuicStreamOffset byte_offset) { QUIC_DVLOG(1) << "Writing WINDOW_UPDATE"; const bool had_buffered_data = HasBufferedStreamData() || HasBufferedControlFrames(); QuicControlFrameId control_frame_id = ++last_control_frame_id_; control_frames_.emplace_back( (QuicFrame(QuicWindowUpdateFrame(control_frame_id, id, byte_offset)))); if (had_buffered_data) { QUIC_DLOG(WARNING) << "Connection is write blocked"; return; } WriteBufferedControlFrames(); } void SimpleSessionNotifier::WriteOrBufferPing() { QUIC_DVLOG(1) << "Writing PING_FRAME"; const bool had_buffered_data = HasBufferedStreamData() || HasBufferedControlFrames(); control_frames_.emplace_back( (QuicFrame(QuicPingFrame(++last_control_frame_id_)))); if (had_buffered_data) { QUIC_DLOG(WARNING) << "Connection is write blocked"; return; } WriteBufferedControlFrames(); } void SimpleSessionNotifier::WriteOrBufferAckFrequency( const QuicAckFrequencyFrame& ack_frequency_frame) { QUIC_DVLOG(1) << "Writing ACK_FREQUENCY"; const bool had_buffered_data = HasBufferedStreamData() || HasBufferedControlFrames(); QuicControlFrameId control_frame_id = ++last_control_frame_id_; control_frames_.emplace_back(( QuicFrame(new QuicAckFrequencyFrame(control_frame_id, control_frame_id, ack_frequency_frame.packet_tolerance, ack_frequency_frame.max_ack_delay)))); if (had_buffered_data) { QUIC_DLOG(WARNING) << "Connection is write blocked"; return; } WriteBufferedControlFrames(); } void SimpleSessionNotifier::NeuterUnencryptedData() { if (QuicVersionUsesCryptoFrames(connection_->transport_version())) { for (const auto& interval : crypto_bytes_transferred_[ENCRYPTION_INITIAL]) { QuicCryptoFrame crypto_frame(ENCRYPTION_INITIAL, interval.min(), interval.max() - interval.min()); OnFrameAcked(QuicFrame(&crypto_frame), QuicTime::Delta::Zero(), QuicTime::Zero()); } return; } for (const auto& interval : crypto_bytes_transferred_[ENCRYPTION_INITIAL]) { QuicStreamFrame stream_frame( QuicUtils::GetCryptoStreamId(connection_->transport_version()), false, interval.min(), interval.max() - interval.min()); OnFrameAcked(QuicFrame(stream_frame), QuicTime::Delta::Zero(), QuicTime::Zero()); } } void SimpleSessionNotifier::OnCanWrite() { if (connection_->framer().is_processing_packet()) { QUIC_BUG(simple_notifier_write_mid_packet_processing) << "Try to write mid packet processing."; return; } if (!RetransmitLostCryptoData() || !RetransmitLostControlFrames() || !RetransmitLostStreamData()) { return; } if (!WriteBufferedCryptoData() || !WriteBufferedControlFrames()) { return; } for (const auto& pair : stream_map_) { const auto& state = pair.second; if (!StreamHasBufferedData(pair.first)) { continue; } const size_t length = state.bytes_total - state.bytes_sent; const bool can_bundle_fin = state.fin_buffered && (state.bytes_sent + length == state.bytes_total); connection_->SetTransmissionType(NOT_RETRANSMISSION); QuicConnection::ScopedEncryptionLevelContext context( connection_, connection_->framer().GetEncryptionLevelToSendApplicationData()); QuicConsumedData consumed = connection_->SendStreamData( pair.first, length, state.bytes_sent, can_bundle_fin ? FIN : NO_FIN); QUIC_DVLOG(1) << "Tries to write stream_id: " << pair.first << " [" << state.bytes_sent << ", " << state.bytes_sent + length << "), fin: " << can_bundle_fin << ", and consumed: " << consumed; OnStreamDataConsumed(pair.first, state.bytes_sent, consumed.bytes_consumed, consumed.fin_consumed); if (length != consumed.bytes_consumed || (can_bundle_fin && !consumed.fin_consumed)) { break; } } } void SimpleSessionNotifier::OnStreamReset(QuicStreamId id, QuicRstStreamErrorCode error) { if (error != QUIC_STREAM_NO_ERROR) { stream_map_.erase(id); } } bool SimpleSessionNotifier::WillingToWrite() const { QUIC_DVLOG(1) << "has_buffered_control_frames: " << HasBufferedControlFrames() << " as_lost_control_frames: " << !lost_control_frames_.empty() << " has_buffered_stream_data: " << HasBufferedStreamData() << " has_lost_stream_data: " << HasLostStreamData(); return HasBufferedControlFrames() || !lost_control_frames_.empty() || HasBufferedStreamData() || HasLostStreamData(); } QuicByteCount SimpleSessionNotifier::StreamBytesSent() const { QuicByteCount bytes_sent = 0; for (const auto& pair : stream_map_) { const auto& state = pair.second; bytes_sent += state.bytes_sent; } return bytes_sent; } QuicByteCount SimpleSessionNotifier::StreamBytesToSend() const { QuicByteCount bytes_to_send = 0; for (const auto& pair : stream_map_) { const auto& state = pair.second; bytes_to_send += (state.bytes_total - state.bytes_sent); } return bytes_to_send; } bool SimpleSessionNotifier::OnFrameAcked(const QuicFrame& frame, QuicTime::Delta , QuicTime ) { QUIC_DVLOG(1) << "Acking " << frame; if (frame.type == CRYPTO_FRAME) { StreamState* state = &crypto_state_[frame.crypto_frame->level]; QuicStreamOffset offset = frame.crypto_frame->offset; QuicByteCount data_length = frame.crypto_frame->data_length; QuicIntervalSet<QuicStreamOffset> newly_acked(offset, offset + data_length); newly_acked.Difference(state->bytes_acked); if (newly_acked.Empty()) { return false; } state->bytes_acked.Add(offset, offset + data_length); state->pending_retransmissions.Difference(offset, offset + data_length); return true; } if (frame.type != STREAM_FRAME) { return OnControlFrameAcked(frame); } if (!stream_map_.contains(frame.stream_frame.stream_id)) { return false; } auto* state = &stream_map_.find(frame.stream_frame.stream_id)->second; QuicStreamOffset offset = frame.stream_frame.offset; QuicByteCount data_length = frame.stream_frame.data_length; QuicIntervalSet<QuicStreamOffset> newly_acked(offset, offset + data_length); newly_acked.Difference(state->bytes_acked); const bool fin_newly_acked = frame.stream_frame.fin && state->fin_outstanding; if (newly_acked.Empty() && !fin_newly_acked) { return false; } state->bytes_acked.Add(offset, offset + data_length); if (fin_newly_acked) { state->fin_outstanding = false; state->fin_lost = false; } state->pending_retransmissions.Difference(offset, offset + data_length); return true; } void SimpleSessionNotifier::OnFrameLost(const QuicFrame& frame) { QUIC_DVLOG(1) << "Losting " << frame; if (frame.type == CRYPTO_FRAME) { StreamState* state = &crypto_state_[frame.crypto_frame->level]; QuicStreamOffset offset = frame.crypto_frame->offset; QuicByteCount data_length = frame.crypto_frame->data_length; QuicIntervalSet<QuicStreamOffset> bytes_lost(offset, offset + data_length); bytes_lost.Difference(state->bytes_acked); if (bytes_lost.Empty()) { return; } for (const auto& lost : bytes_lost) { state->pending_retransmissions.Add(lost.min(), lost.max()); } return; } if (frame.type != STREAM_FRAME) { OnControlFrameLost(frame); return; } if (!stream_map_.contains(frame.stream_frame.stream_id)) { return; } auto* state = &stream_map_.find(frame.stream_frame.stream_id)->second; QuicStreamOffset offset = frame.stream_frame.offset; QuicByteCount data_length = frame.stream_frame.data_length; QuicIntervalSet<QuicStreamOffset> bytes_lost(offset, offset + data_length); bytes_lost.Difference(state->bytes_acked); const bool fin_lost = state->fin_outstanding && frame.stream_frame.fin; if (bytes_lost.Empty() && !fin_lost) { return; } for (const auto& lost : bytes_lost) { state->pending_retransmissions.Add(lost.min(), lost.max()); } state->fin_lost = fin_lost; } bool SimpleSessionNotifier::RetransmitFrames(const QuicFrames& frames, TransmissionType type) { QuicConnection::ScopedPacketFlusher retransmission_flusher(connection_); connection_->SetTransmissionType(type); for (const QuicFrame& frame : frames) { if (frame.type == CRYPTO_FRAME) { const StreamState& state = crypto_state_[frame.crypto_frame->level]; const EncryptionLevel current_encryption_level = connection_->encryption_level(); QuicIntervalSet<QuicStreamOffset> retransmission( frame.crypto_frame->offset, frame.crypto_frame->offset + frame.crypto_frame->data_length); retransmission.Difference(state.bytes_acked); for (const auto& interval : retransmission) { QuicStreamOffset offset = interval.min(); QuicByteCount length = interval.max() - interval.min(); connection_->SetDefaultEncryptionLevel(frame.crypto_frame->level); size_t consumed = connection_->SendCryptoData(frame.crypto_frame->level, length, offset); if (consumed < length) { return false; } } connection_->SetDefaultEncryptionLevel(current_encryption_level); } if (frame.type != STREAM_FRAME) { if (GetControlFrameId(frame) == kInvalidControlFrameId) { continue; } QuicFrame copy = CopyRetransmittableControlFrame(frame); if (!connection_->SendControlFrame(copy)) { DeleteFrame(&copy); return false; } continue; } if (!stream_map_.contains(frame.stream_frame.stream_id)) { continue; } const auto& state = stream_map_.find(frame.stream_frame.stream_id)->second; QuicIntervalSet<QuicStreamOffset> retransmission( frame.stream_frame.offset, frame.stream_frame.offset + frame.stream_frame.data_length); EncryptionLevel retransmission_encryption_level = connection_->encryption_level(); if (QuicUtils::IsCryptoStreamId(connection_->transport_version(), frame.stream_frame.stream_id)) { for (size_t i = 0; i < NUM_ENCRYPTION_LEVELS; ++i) { if (retransmission.Intersects(crypto_bytes_transferred_[i])) { retransmission_encryption_level = static_cast<EncryptionLevel>(i); retransmission.Intersection(crypto_bytes_transferred_[i]); break; } } } retransmission.Difference(state.bytes_acked); bool retransmit_fin = frame.stream_frame.fin && state.fin_outstanding; QuicConsumedData consumed(0, false); for (const auto& interval : retransmission) { QuicStreamOffset retransmission_offset = interval.min(); QuicByteCount retransmission_length = interval.max() - interval.min(); const bool can_bundle_fin = retransmit_fin && (retransmission_offset + retransmission_length == state.bytes_sent); QuicConnection::ScopedEncryptionLevelContext context( connection_, QuicUtils::IsCryptoStreamId(connection_->transport_version(), frame.stream_frame.stream_id) ? retransmission_encryption_level : connection_->framer() .GetEncryptionLevelToSendApplicationData()); consumed = connection_->SendStreamData( frame.stream_frame.stream_id, retransmission_length, retransmission_offset, can_bundle_fin ? FIN : NO_FIN); QUIC_DVLOG(1) << "stream " << frame.stream_frame.stream_id << " is forced to retransmit stream data [" << retransmission_offset << ", " << retransmission_offset + retransmission_length << ") and fin: " << can_bundle_fin << ", consumed: " << consumed; if (can_bundle_fin) { retransmit_fin = !consumed.fin_consumed; } if (consumed.bytes_consumed < retransmission_length || (can_bundle_fin && !consumed.fin_consumed)) { return false; } } if (retransmit_fin) { QUIC_DVLOG(1) << "stream " << frame.stream_frame.stream_id << " retransmits fin only frame."; consumed = connection_->SendStreamData(frame.stream_frame.stream_id, 0, state.bytes_sent, FIN); if (!consumed.fin_consumed) { return false; } } } return true; } bool SimpleSessionNotifier::IsFrameOutstanding(const QuicFrame& frame) const { if (frame.type == CRYPTO_FRAME) { QuicStreamOffset offset = frame.crypto_frame->offset; QuicByteCount data_length = frame.crypto_frame->data_length; bool ret = data_length > 0 && !crypto_state_[frame.crypto_frame->level].bytes_acked.Contains( offset, offset + data_length); return ret; } if (frame.type != STREAM_FRAME) { return IsControlFrameOutstanding(frame); } if (!stream_map_.contains(frame.stream_frame.stream_id)) { return false; } const auto& state = stream_map_.find(frame.stream_frame.stream_id)->second; QuicStreamOffset offset = frame.stream_frame.offset; QuicByteCount data_length = frame.stream_frame.data_length; return (data_length > 0 && !state.bytes_acked.Contains(offset, offset + data_length)) || (frame.stream_frame.fin && state.fin_outstanding); } bool SimpleSessionNotifier::HasUnackedCryptoData() const { if (QuicVersionUsesCryptoFrames(connection_->transport_version())) { for (size_t i = 0; i < NUM_ENCRYPTION_LEVELS; ++i) { const StreamState& state = crypto_state_[i]; if (state.bytes_total > state.bytes_sent) { return true; } QuicIntervalSet<QuicStreamOffset> bytes_to_ack(0, state.bytes_total); bytes_to_ack.Difference(state.bytes_acked); if (!bytes_to_ack.Empty()) { return true; } } return false; } if (!stream_map_.contains( QuicUtils::GetCryptoStreamId(connection_->transport_version()))) { return false; } const auto& state = stream_map_ .find(QuicUtils::GetCryptoStreamId(connection_->transport_version())) ->second; if (state.bytes_total > state.bytes_sent) { return true; } QuicIntervalSet<QuicStreamOffset> bytes_to_ack(0, state.bytes_total); bytes_to_ack.Difference(state.bytes_acked); return !bytes_to_ack.Empty(); } bool SimpleSessionNotifier::HasUnackedStreamData() const { for (const auto& it : stream_map_) { if (StreamIsWaitingForAcks(it.first)) return true; } return false; } bool SimpleSessionNotifier::OnControlFrameAcked(const QuicFrame& frame) { QuicControlFrameId id = GetControlFrameId(frame); if (id == kInvalidControlFrameId) { return false; } QUICHE_DCHECK(id < least_unacked_ + control_frames_.size()); if (id < least_unacked_ || GetControlFrameId(control_frames_.at(id - least_unacked_)) == kInvalidControlFrameId) { return false; } SetControlFrameId(kInvalidControlFrameId, &control_frames_.at(id - least_unacked_)); lost_control_frames_.erase(id); while (!control_frames_.empty() && GetControlFrameId(control_frames_.front()) == kInvalidControlFrameId) { DeleteFrame(&control_frames_.front()); control_frames_.pop_front(); ++least_unacked_; } return true; } void SimpleSessionNotifier::OnControlFrameLost(const QuicFrame& frame) { QuicControlFrameId id = GetControlFrameId(frame); if (id == kInvalidControlFrameId) { return; } QUICHE_DCHECK(id < least_unacked_ + control_frames_.size()); if (id < least_unacked_ || GetControlFrameId(control_frames_.at(id - least_unacked_)) == kInvalidControlFrameId) { return; } if (!lost_control_frames_.contains(id)) { lost_control_frames_[id] = true; } } bool SimpleSessionNotifier::IsControlFrameOutstanding( const QuicFrame& frame) const { QuicControlFrameId id = GetControlFrameId(frame); if (id == kInvalidControlFrameId) { return false; } return id < least_unacked_ + control_frames_.size() && id >= least_unacked_ && GetControlFrameId(control_frames_.at(id - least_unacked_)) != kInvalidControlFrameId; } bool SimpleSessionNotifier::RetransmitLostControlFrames() { while (!lost_control_frames_.empty()) { QuicFrame pending = control_frames_.at(lost_control_frames_.begin()->first - least_unacked_); QuicFrame copy = CopyRetransmittableControlFrame(pending); connection_->SetTransmissionType(LOSS_RETRANSMISSION); if (!connection_->SendControlFrame(copy)) { DeleteFrame(&copy); break; } lost_control_frames_.pop_front(); } return lost_control_frames_.empty(); } bool SimpleSessionNotifier::RetransmitLostCryptoData() { if (QuicVersionUsesCryptoFrames(connection_->transport_version())) { for (EncryptionLevel level : {ENCRYPTION_INITIAL, ENCRYPTION_HANDSHAKE, ENCRYPTION_ZERO_RTT, ENCRYPTION_FORWARD_SECURE}) { auto& state = crypto_state_[level]; while (!state.pending_retransmissions.Empty()) { connection_->SetTransmissionType(HANDSHAKE_RETRANSMISSION); EncryptionLevel current_encryption_level = connection_->encryption_level(); connection_->SetDefaultEncryptionLevel(level); QuicIntervalSet<QuicStreamOffset> retransmission( state.pending_retransmissions.begin()->min(), state.pending_retransmissions.begin()->max()); retransmission.Intersection(crypto_bytes_transferred_[level]); QuicStreamOffset retransmission_offset = retransmission.begin()->min(); QuicByteCount retransmission_length = retransmission.begin()->max() - retransmission.begin()->min(); size_t bytes_consumed = connection_->SendCryptoData( level, retransmission_length, retransmission_offset); connection_->SetDefaultEncryptionLevel(current_encryption_level); state.pending_retransmissions.Difference( retransmission_offset, retransmission_offset + bytes_consumed); if (bytes_consumed < retransmission_length) { return false; } } } return true; } if (!stream_map_.contains( QuicUtils::GetCryptoStreamId(connection_->transport_version()))) { return true; } auto& state = stream_map_ .find(QuicUtils::GetCryptoStreamId(connection_->transport_version())) ->second; while (!state.pending_retransmissions.Empty()) { connection_->SetTransmissionType(HANDSHAKE_RETRANSMISSION); QuicIntervalSet<QuicStreamOffset> retransmission( state.pending_retransmissions.begin()->min(), state.pending_retransmissions.begin()->max()); EncryptionLevel retransmission_encryption_level = ENCRYPTION_INITIAL; for (size_t i = 0; i < NUM_ENCRYPTION_LEVELS; ++i) { if (retransmission.Intersects(crypto_bytes_transferred_[i])) { retransmission_encryption_level = static_cast<EncryptionLevel>(i); retransmission.Intersection(crypto_bytes_transferred_[i]); break; } } QuicStreamOffset retransmission_offset = retransmission.begin()->min(); QuicByteCount retransmission_length = retransmission.begin()->max() - retransmission.begin()->min(); EncryptionLevel current_encryption_level = connection_->encryption_level(); connection_->SetDefaultEncryptionLevel(retransmission_encryption_level); QuicConsumedData consumed = connection_->SendStreamData( QuicUtils::GetCryptoStreamId(connection_->transport_version()), retransmission_length, retransmission_offset, NO_FIN); connection_->SetDefaultEncryptionLevel(current_encryption_level); state.pending_retransmissions.Difference( retransmission_offset, retransmission_offset + consumed.bytes_consumed); if (consumed.bytes_consumed < retransmission_length) { break; } } return state.pending_retransmissions.Empty(); } bool SimpleSessionNotifier::RetransmitLostStreamData() { for (auto& pair : stream_map_) { StreamState& state = pair.second; QuicConsumedData consumed(0, false); while (!state.pending_retransmissions.Empty() || state.fin_lost) { connection_->SetTransmissionType(LOSS_RETRANSMISSION); if (state.pending_retransmissions.Empty()) { QUIC_DVLOG(1) << "stream " << pair.first << " retransmits fin only frame."; consumed = connection_->SendStreamData(pair.first, 0, state.bytes_sent, FIN); state.fin_lost = !consumed.fin_consumed; if (state.fin_lost) { QUIC_DLOG(INFO) << "Connection is write blocked"; return false; } } else { QuicStreamOffset offset = state.pending_retransmissions.begin()->min(); QuicByteCount length = state.pending_retransmissions.begin()->max() - state.pending_retransmissions.begin()->min(); const bool can_bundle_fin = state.fin_lost && (offset + length == state.bytes_sent); consumed = connection_->SendStreamData(pair.first, length, offset, can_bundle_fin ? FIN : NO_FIN); QUIC_DVLOG(1) << "stream " << pair.first << " tries to retransmit stream data [" << offset << ", " << offset + length << ") and fin: " << can_bundle_fin << ", consumed: " << consumed; state.pending_retransmissions.Difference( offset, offset + consumed.bytes_consumed); if (consumed.fin_consumed) { state.fin_lost = false; } if (length > consumed.bytes_consumed ||
#include "quiche/quic/test_tools/simple_session_notifier.h" #include <memory> #include <string> #include <utility> #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simple_data_producer.h" using testing::_; using testing::InSequence; using testing::Return; using testing::StrictMock; namespace quic { namespace test { namespace { class MockQuicConnectionWithSendStreamData : public MockQuicConnection { public: MockQuicConnectionWithSendStreamData(MockQuicConnectionHelper* helper, MockAlarmFactory* alarm_factory, Perspective perspective) : MockQuicConnection(helper, alarm_factory, perspective) {} MOCK_METHOD(QuicConsumedData, SendStreamData, (QuicStreamId id, size_t write_length, QuicStreamOffset offset, StreamSendingState state), (override)); }; class SimpleSessionNotifierTest : public QuicTest { public: SimpleSessionNotifierTest() : connection_(&helper_, &alarm_factory_, Perspective::IS_CLIENT), notifier_(&connection_) { connection_.set_visitor(&visitor_); connection_.SetSessionNotifier(&notifier_); EXPECT_FALSE(notifier_.WillingToWrite()); EXPECT_EQ(0u, notifier_.StreamBytesSent()); EXPECT_FALSE(notifier_.HasBufferedStreamData()); } bool ControlFrameConsumed(const QuicFrame& frame) { DeleteFrame(&const_cast<QuicFrame&>(frame)); return true; } MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; MockQuicConnectionVisitor visitor_; StrictMock<MockQuicConnectionWithSendStreamData> connection_; SimpleSessionNotifier notifier_; }; TEST_F(SimpleSessionNotifierTest, WriteOrBufferData) { InSequence s; EXPECT_CALL(connection_, SendStreamData(3, 1024, 0, NO_FIN)) .WillOnce(Return(QuicConsumedData(1024, false))); notifier_.WriteOrBufferData(3, 1024, NO_FIN); EXPECT_EQ(0u, notifier_.StreamBytesToSend()); EXPECT_CALL(connection_, SendStreamData(5, 512, 0, NO_FIN)) .WillOnce(Return(QuicConsumedData(512, false))); notifier_.WriteOrBufferData(5, 512, NO_FIN); EXPECT_FALSE(notifier_.WillingToWrite()); EXPECT_CALL(connection_, SendStreamData(5, 512, 512, FIN)) .WillOnce(Return(QuicConsumedData(256, false))); notifier_.WriteOrBufferData(5, 512, FIN); EXPECT_TRUE(notifier_.WillingToWrite()); EXPECT_EQ(1792u, notifier_.StreamBytesSent()); EXPECT_EQ(256u, notifier_.StreamBytesToSend()); EXPECT_TRUE(notifier_.HasBufferedStreamData()); EXPECT_CALL(connection_, SendStreamData(7, 1024, 0, FIN)).Times(0); notifier_.WriteOrBufferData(7, 1024, FIN); EXPECT_EQ(1792u, notifier_.StreamBytesSent()); } TEST_F(SimpleSessionNotifierTest, WriteOrBufferRstStream) { InSequence s; EXPECT_CALL(connection_, SendStreamData(5, 1024, 0, FIN)) .WillOnce(Return(QuicConsumedData(1024, true))); notifier_.WriteOrBufferData(5, 1024, FIN); EXPECT_TRUE(notifier_.StreamIsWaitingForAcks(5)); EXPECT_TRUE(notifier_.HasUnackedStreamData()); EXPECT_CALL(connection_, SendControlFrame(_)) .WillRepeatedly( Invoke(this, &SimpleSessionNotifierTest::ControlFrameConsumed)); notifier_.WriteOrBufferRstStream(5, QUIC_STREAM_NO_ERROR, 1024); EXPECT_TRUE(notifier_.StreamIsWaitingForAcks(5)); EXPECT_TRUE(notifier_.HasUnackedStreamData()); notifier_.WriteOrBufferRstStream(5, QUIC_ERROR_PROCESSING_STREAM, 1024); EXPECT_FALSE(notifier_.StreamIsWaitingForAcks(5)); EXPECT_FALSE(notifier_.HasUnackedStreamData()); } TEST_F(SimpleSessionNotifierTest, WriteOrBufferPing) { InSequence s; EXPECT_CALL(connection_, SendControlFrame(_)) .WillRepeatedly( Invoke(this, &SimpleSessionNotifierTest::ControlFrameConsumed)); notifier_.WriteOrBufferPing(); EXPECT_EQ(0u, notifier_.StreamBytesToSend()); EXPECT_FALSE(notifier_.WillingToWrite()); EXPECT_CALL(connection_, SendStreamData(3, 1024, 0, NO_FIN)) .WillOnce(Return(QuicConsumedData(1024, false))); notifier_.WriteOrBufferData(3, 1024, NO_FIN); EXPECT_EQ(0u, notifier_.StreamBytesToSend()); EXPECT_CALL(connection_, SendStreamData(5, 512, 0, NO_FIN)) .WillOnce(Return(QuicConsumedData(256, false))); notifier_.WriteOrBufferData(5, 512, NO_FIN); EXPECT_TRUE(notifier_.WillingToWrite()); EXPECT_CALL(connection_, SendControlFrame(_)).Times(0); notifier_.WriteOrBufferPing(); } TEST_F(SimpleSessionNotifierTest, NeuterUnencryptedData) { if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { return; } InSequence s; connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); EXPECT_CALL(connection_, SendStreamData(QuicUtils::GetCryptoStreamId( connection_.transport_version()), 1024, 0, NO_FIN)) .WillOnce(Return(QuicConsumedData(1024, false))); notifier_.WriteOrBufferData( QuicUtils::GetCryptoStreamId(connection_.transport_version()), 1024, NO_FIN); connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); EXPECT_CALL(connection_, SendStreamData(QuicUtils::GetCryptoStreamId( connection_.transport_version()), 1024, 1024, NO_FIN)) .WillOnce(Return(QuicConsumedData(1024, false))); notifier_.WriteOrBufferData( QuicUtils::GetCryptoStreamId(connection_.transport_version()), 1024, NO_FIN); QuicStreamFrame stream_frame( QuicUtils::GetCryptoStreamId(connection_.transport_version()), false, 1024, 1024); notifier_.OnFrameAcked(QuicFrame(stream_frame), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_TRUE(notifier_.StreamIsWaitingForAcks( QuicUtils::GetCryptoStreamId(connection_.transport_version()))); EXPECT_TRUE(notifier_.HasUnackedStreamData()); notifier_.NeuterUnencryptedData(); EXPECT_FALSE(notifier_.StreamIsWaitingForAcks( QuicUtils::GetCryptoStreamId(connection_.transport_version()))); EXPECT_FALSE(notifier_.HasUnackedStreamData()); } TEST_F(SimpleSessionNotifierTest, OnCanWrite) { if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { return; } InSequence s; connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); EXPECT_CALL(connection_, SendStreamData(QuicUtils::GetCryptoStreamId( connection_.transport_version()), 1024, 0, NO_FIN)) .WillOnce(Return(QuicConsumedData(1024, false))); notifier_.WriteOrBufferData( QuicUtils::GetCryptoStreamId(connection_.transport_version()), 1024, NO_FIN); connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); EXPECT_CALL(connection_, SendStreamData(QuicUtils::GetCryptoStreamId( connection_.transport_version()), 1024, 1024, NO_FIN)) .WillOnce(Return(QuicConsumedData(1024, false))); notifier_.WriteOrBufferData( QuicUtils::GetCryptoStreamId(connection_.transport_version()), 1024, NO_FIN); EXPECT_CALL(connection_, SendStreamData(3, 1024, 0, FIN)) .WillOnce(Return(QuicConsumedData(512, false))); notifier_.WriteOrBufferData(3, 1024, FIN); EXPECT_CALL(connection_, SendStreamData(5, _, _, _)).Times(0); notifier_.WriteOrBufferData(5, 1024, NO_FIN); EXPECT_CALL(connection_, SendControlFrame(_)).Times(0); notifier_.WriteOrBufferRstStream(5, QUIC_ERROR_PROCESSING_STREAM, 1024); QuicStreamFrame frame1( QuicUtils::GetCryptoStreamId(connection_.transport_version()), false, 500, 1000); QuicStreamFrame frame2(3, false, 0, 512); notifier_.OnFrameLost(QuicFrame(frame1)); notifier_.OnFrameLost(QuicFrame(frame2)); EXPECT_CALL(connection_, SendStreamData(QuicUtils::GetCryptoStreamId( connection_.transport_version()), 524, 500, NO_FIN)) .WillOnce(Return(QuicConsumedData(524, false))); EXPECT_CALL(connection_, SendStreamData(QuicUtils::GetCryptoStreamId( connection_.transport_version()), 476, 1024, NO_FIN)) .WillOnce(Return(QuicConsumedData(476, false))); EXPECT_CALL(connection_, SendStreamData(3, 512, 0, NO_FIN)) .WillOnce(Return(QuicConsumedData(512, false))); EXPECT_CALL(connection_, SendControlFrame(_)) .WillOnce(Invoke(this, &SimpleSessionNotifierTest::ControlFrameConsumed)); EXPECT_CALL(connection_, SendStreamData(3, 512, 512, FIN)) .WillOnce(Return(QuicConsumedData(512, true))); notifier_.OnCanWrite(); EXPECT_FALSE(notifier_.WillingToWrite()); } TEST_F(SimpleSessionNotifierTest, OnCanWriteCryptoFrames) { if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) { return; } SimpleDataProducer producer; connection_.SetDataProducer(&producer); InSequence s; connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); EXPECT_CALL(connection_, SendCryptoData(ENCRYPTION_INITIAL, 1024, 0)) .WillOnce(Invoke(&connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); EXPECT_CALL(connection_, CloseConnection(QUIC_PACKET_WRITE_ERROR, _, _)); std::string crypto_data1(1024, 'a'); producer.SaveCryptoData(ENCRYPTION_INITIAL, 0, crypto_data1); std::string crypto_data2(524, 'a'); producer.SaveCryptoData(ENCRYPTION_INITIAL, 500, crypto_data2); notifier_.WriteCryptoData(ENCRYPTION_INITIAL, 1024, 0); connection_.SetEncrypter(ENCRYPTION_ZERO_RTT, std::make_unique<NullEncrypter>( Perspective::IS_CLIENT)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); EXPECT_CALL(connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 1024, 0)) .WillOnce(Invoke(&connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); std::string crypto_data3(1024, 'a'); producer.SaveCryptoData(ENCRYPTION_ZERO_RTT, 0, crypto_data3); notifier_.WriteCryptoData(ENCRYPTION_ZERO_RTT, 1024, 0); EXPECT_CALL(connection_, SendStreamData(3, 1024, 0, FIN)) .WillOnce(Return(QuicConsumedData(512, false))); notifier_.WriteOrBufferData(3, 1024, FIN); EXPECT_CALL(connection_, SendStreamData(5, _, _, _)).Times(0); notifier_.WriteOrBufferData(5, 1024, NO_FIN); EXPECT_CALL(connection_, SendControlFrame(_)).Times(0); notifier_.WriteOrBufferRstStream(5, QUIC_ERROR_PROCESSING_STREAM, 1024); QuicCryptoFrame crypto_frame1(ENCRYPTION_INITIAL, 500, 524); QuicCryptoFrame crypto_frame2(ENCRYPTION_ZERO_RTT, 0, 476); QuicStreamFrame stream3_frame(3, false, 0, 512); notifier_.OnFrameLost(QuicFrame(&crypto_frame1)); notifier_.OnFrameLost(QuicFrame(&crypto_frame2)); notifier_.OnFrameLost(QuicFrame(stream3_frame)); EXPECT_CALL(connection_, SendCryptoData(ENCRYPTION_INITIAL, 524, 500)) .WillOnce(Invoke(&connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); EXPECT_CALL(connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 476, 0)) .WillOnce(Invoke(&connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); EXPECT_CALL(connection_, SendStreamData(3, 512, 0, NO_FIN)) .WillOnce(Return(QuicConsumedData(512, false))); EXPECT_CALL(connection_, SendControlFrame(_)) .WillOnce(Invoke(this, &SimpleSessionNotifierTest::ControlFrameConsumed)); EXPECT_CALL(connection_, SendStreamData(3, 512, 512, FIN)) .WillOnce(Return(QuicConsumedData(512, true))); notifier_.OnCanWrite(); EXPECT_FALSE(notifier_.WillingToWrite()); } TEST_F(SimpleSessionNotifierTest, RetransmitFrames) { InSequence s; connection_.SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(Perspective::IS_CLIENT)); EXPECT_CALL(connection_, SendStreamData(3, 10, 0, FIN)) .WillOnce(Return(QuicConsumedData(10, true))); notifier_.WriteOrBufferData(3, 10, FIN); QuicStreamFrame frame1(3, true, 0, 10); EXPECT_CALL(connection_, SendStreamData(5, 10, 0, FIN)) .WillOnce(Return(QuicConsumedData(10, true))); notifier_.WriteOrBufferData(5, 10, FIN); QuicStreamFrame frame2(5, true, 0, 10); EXPECT_CALL(connection_, SendControlFrame(_)) .WillOnce(Invoke(this, &SimpleSessionNotifierTest::ControlFrameConsumed)); notifier_.WriteOrBufferRstStream(5, QUIC_STREAM_NO_ERROR, 10); QuicStreamFrame ack_frame1(3, false, 3, 4); QuicStreamFrame ack_frame2(5, false, 8, 2); notifier_.OnFrameAcked(QuicFrame(ack_frame1), QuicTime::Delta::Zero(), QuicTime::Zero()); notifier_.OnFrameAcked(QuicFrame(ack_frame2), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_FALSE(notifier_.WillingToWrite()); QuicRstStreamFrame rst_stream(1, 5, QUIC_STREAM_NO_ERROR, 10); QuicFrames frames; frames.push_back(QuicFrame(frame2)); frames.push_back(QuicFrame(&rst_stream)); frames.push_back(QuicFrame(frame1)); EXPECT_CALL(connection_, SendStreamData(5, 8, 0, NO_FIN)) .WillOnce(Return(QuicConsumedData(8, false))); EXPECT_CALL(connection_, SendStreamData(5, 0, 10, FIN)) .WillOnce(Return(QuicConsumedData(0, true))); EXPECT_CALL(connection_, SendControlFrame(_)) .WillOnce(Invoke(this, &SimpleSessionNotifierTest::ControlFrameConsumed)); EXPECT_CALL(connection_, SendStreamData(3, 3, 0, NO_FIN)) .WillOnce(Return(QuicConsumedData(2, false))); notifier_.RetransmitFrames(frames, PTO_RETRANSMISSION); EXPECT_FALSE(notifier_.WillingToWrite()); } } } }
375
cpp
google/quiche
test_ip_packets
quiche/quic/test_tools/test_ip_packets.cc
quiche/quic/test_tools/test_ip_packets_test.cc
#ifndef QUICHE_QUIC_TEST_TOOLS_IP_PACKET_GENERATION_H_ #define QUICHE_QUIC_TEST_TOOLS_IP_PACKET_GENERATION_H_ #include <string> #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/common/quiche_ip_address.h" namespace quic::test { enum class IpPacketPayloadType { kUdp, }; std::string CreateIpPacket( const quiche::QuicheIpAddress& source_address, const quiche::QuicheIpAddress& destination_address, absl::string_view payload, IpPacketPayloadType payload_type = IpPacketPayloadType::kUdp); std::string CreateUdpPacket(const QuicSocketAddress& source_address, const QuicSocketAddress& destination_address, absl::string_view payload); } #endif #include "quiche/quic/test_tools/test_ip_packets.h" #include <cstdint> #include <limits> #include <string> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/internet_checksum.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_data_writer.h" #include "quiche/common/quiche_endian.h" #include "quiche/common/quiche_ip_address.h" #include "quiche/common/quiche_ip_address_family.h" #if defined(__linux__) #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/ip6.h> #include <netinet/udp.h> #endif namespace quic::test { namespace { constexpr uint16_t kIpv4HeaderSize = 20; constexpr uint16_t kIpv6HeaderSize = 40; constexpr uint16_t kUdpHeaderSize = 8; constexpr uint8_t kUdpProtocol = 0x11; #if defined(__linux__) static_assert(kIpv4HeaderSize == sizeof(iphdr)); static_assert(kIpv6HeaderSize == sizeof(ip6_hdr)); static_assert(kUdpHeaderSize == sizeof(udphdr)); static_assert(kUdpProtocol == IPPROTO_UDP); #endif std::string CreateIpv4Header(int payload_length, quiche::QuicheIpAddress source_address, quiche::QuicheIpAddress destination_address, uint8_t protocol) { QUICHE_CHECK_GT(payload_length, 0); QUICHE_CHECK_LE(payload_length, std::numeric_limits<uint16_t>::max() - kIpv4HeaderSize); QUICHE_CHECK(source_address.address_family() == quiche::IpAddressFamily::IP_V4); QUICHE_CHECK(destination_address.address_family() == quiche::IpAddressFamily::IP_V4); std::string header(kIpv4HeaderSize, '\0'); quiche::QuicheDataWriter header_writer(header.size(), header.data()); header_writer.WriteUInt8(0x45); header_writer.WriteUInt8(0x00); header_writer.WriteUInt16(kIpv4HeaderSize + payload_length); header_writer.WriteUInt16(0x0000); header_writer.WriteUInt16(0x0000); header_writer.WriteUInt8(64); header_writer.WriteUInt8(protocol); header_writer.WriteUInt16(0x0000); header_writer.WriteStringPiece(source_address.ToPackedString()); header_writer.WriteStringPiece(destination_address.ToPackedString()); QUICHE_CHECK_EQ(header_writer.remaining(), 0u); return header; } std::string CreateIpv6Header(int payload_length, quiche::QuicheIpAddress source_address, quiche::QuicheIpAddress destination_address, uint8_t next_header) { QUICHE_CHECK_GT(payload_length, 0); QUICHE_CHECK_LE(payload_length, std::numeric_limits<uint16_t>::max()); QUICHE_CHECK(source_address.address_family() == quiche::IpAddressFamily::IP_V6); QUICHE_CHECK(destination_address.address_family() == quiche::IpAddressFamily::IP_V6); std::string header(kIpv6HeaderSize, '\0'); quiche::QuicheDataWriter header_writer(header.size(), header.data()); header_writer.WriteUInt32(0x60000000); header_writer.WriteUInt16(payload_length); header_writer.WriteUInt8(next_header); header_writer.WriteUInt8(64); header_writer.WriteStringPiece(source_address.ToPackedString()); header_writer.WriteStringPiece(destination_address.ToPackedString()); QUICHE_CHECK_EQ(header_writer.remaining(), 0u); return header; } } std::string CreateIpPacket(const quiche::QuicheIpAddress& source_address, const quiche::QuicheIpAddress& destination_address, absl::string_view payload, IpPacketPayloadType payload_type) { QUICHE_CHECK(source_address.address_family() == destination_address.address_family()); uint8_t payload_protocol; switch (payload_type) { case IpPacketPayloadType::kUdp: payload_protocol = kUdpProtocol; break; default: QUICHE_NOTREACHED(); return ""; } std::string header; switch (source_address.address_family()) { case quiche::IpAddressFamily::IP_V4: header = CreateIpv4Header(payload.size(), source_address, destination_address, payload_protocol); break; case quiche::IpAddressFamily::IP_V6: header = CreateIpv6Header(payload.size(), source_address, destination_address, payload_protocol); break; default: QUICHE_NOTREACHED(); return ""; } return absl::StrCat(header, payload); } std::string CreateUdpPacket(const QuicSocketAddress& source_address, const QuicSocketAddress& destination_address, absl::string_view payload) { QUICHE_CHECK(source_address.host().address_family() == destination_address.host().address_family()); QUICHE_CHECK(!payload.empty()); QUICHE_CHECK_LE(payload.size(), static_cast<uint16_t>(std::numeric_limits<uint16_t>::max() - kUdpHeaderSize)); std::string header(kUdpHeaderSize, '\0'); quiche::QuicheDataWriter header_writer(header.size(), header.data()); header_writer.WriteUInt16(source_address.port()); header_writer.WriteUInt16(destination_address.port()); header_writer.WriteUInt16(kUdpHeaderSize + payload.size()); InternetChecksum checksum; switch (source_address.host().address_family()) { case quiche::IpAddressFamily::IP_V4: { checksum.Update(source_address.host().ToPackedString()); checksum.Update(destination_address.host().ToPackedString()); uint8_t protocol[] = {0x00, kUdpProtocol}; checksum.Update(protocol, sizeof(protocol)); uint16_t udp_length = quiche::QuicheEndian::HostToNet16(kUdpHeaderSize + payload.size()); checksum.Update(reinterpret_cast<uint8_t*>(&udp_length), sizeof(udp_length)); break; } case quiche::IpAddressFamily::IP_V6: { checksum.Update(source_address.host().ToPackedString()); checksum.Update(destination_address.host().ToPackedString()); uint32_t udp_length = quiche::QuicheEndian::HostToNet32(kUdpHeaderSize + payload.size()); checksum.Update(reinterpret_cast<uint8_t*>(&udp_length), sizeof(udp_length)); uint8_t protocol[] = {0x00, 0x00, 0x00, kUdpProtocol}; checksum.Update(protocol, sizeof(protocol)); break; } default: QUICHE_NOTREACHED(); return ""; } checksum.Update(header.data(), header.size()); checksum.Update(payload.data(), payload.size()); uint16_t checksum_val = checksum.Value(); header_writer.WriteBytes(&checksum_val, sizeof(checksum_val)); QUICHE_CHECK_EQ(header_writer.remaining(), 0u); return absl::StrCat(header, payload); } }
#include "quiche/quic/test_tools/test_ip_packets.h" #include <string> #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/quiche_ip_address.h" namespace quic::test { namespace { TEST(TestIpPacketsTest, CreateIpv4Packet) { quiche::QuicheIpAddress source_ip; ASSERT_TRUE(source_ip.FromString("192.0.2.45")); ASSERT_TRUE(source_ip.IsIPv4()); QuicSocketAddress source_address{source_ip, 54131}; quiche::QuicheIpAddress destination_ip; ASSERT_TRUE(destination_ip.FromString("192.0.2.67")); ASSERT_TRUE(destination_ip.IsIPv4()); QuicSocketAddress destination_address(destination_ip, 57542); std::string packet = CreateIpPacket(source_ip, destination_ip, CreateUdpPacket(source_address, destination_address, "foo"), IpPacketPayloadType::kUdp); constexpr static char kExpected[] = "\x45" "\x00" "\x00\x1F" "\x00\x00" "\x00\x00" "\x40" "\x11" "\x00\x00" "\xC0\x00\x02\x2D" "\xC0\x00\x02\x43" "\xD3\x73" "\xE0\xC6" "\x00\x0B" "\xF1\xBC" "foo"; EXPECT_EQ(absl::string_view(packet), absl::string_view(kExpected, sizeof(kExpected) - 1)); } TEST(TestIpPacketsTest, CreateIpv6Packet) { quiche::QuicheIpAddress source_ip; ASSERT_TRUE(source_ip.FromString("2001:db8::45")); ASSERT_TRUE(source_ip.IsIPv6()); QuicSocketAddress source_address{source_ip, 51941}; quiche::QuicheIpAddress destination_ip; ASSERT_TRUE(destination_ip.FromString("2001:db8::67")); ASSERT_TRUE(destination_ip.IsIPv6()); QuicSocketAddress destination_address(destination_ip, 55341); std::string packet = CreateIpPacket(source_ip, destination_ip, CreateUdpPacket(source_address, destination_address, "foo"), IpPacketPayloadType::kUdp); constexpr static char kExpected[] = "\x60\x00\x00\x00" "\x00\x0b" "\x11" "\x40" "\x20\x01\x0D\xB8\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x45" "\x20\x01\x0D\xB8\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x67" "\xCA\xE5" "\xD8\x2D" "\x00\x0B" "\x2B\x37" "foo"; EXPECT_EQ(absl::string_view(packet), absl::string_view(kExpected, sizeof(kExpected) - 1)); } } }
376
cpp
google/quiche
quic_test_utils
quiche/quic/test_tools/quic_test_utils.cc
quiche/quic/test_tools/quic_test_utils_test.cc
#ifndef QUICHE_QUIC_TEST_TOOLS_QUIC_TEST_UTILS_H_ #define QUICHE_QUIC_TEST_TOOLS_QUIC_TEST_UTILS_H_ #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/strings/ascii.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/congestion_control/loss_detection_interface.h" #include "quiche/quic/core/congestion_control/send_algorithm_interface.h" #include "quiche/quic/core/crypto/transport_parameters.h" #include "quiche/quic/core/frames/quic_reset_stream_at_frame.h" #include "quiche/quic/core/http/http_decoder.h" #include "quiche/quic/core/http/quic_server_session_base.h" #include "quiche/quic/core/http/quic_spdy_client_session_base.h" #include "quiche/quic/core/http/quic_spdy_session.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_framer.h" #include "quiche/quic/core/quic_packet_writer.h" #include "quiche/quic/core/quic_packet_writer_wrapper.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_path_validator.h" #include "quiche/quic/core/quic_sent_packet_manager.h" #include "quiche/quic/core/quic_server_id.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_mutex.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/test_tools/mock_clock.h" #include "quiche/quic/test_tools/mock_connection_id_generator.h" #include "quiche/quic/test_tools/mock_quic_session_visitor.h" #include "quiche/quic/test_tools/mock_random.h" #include "quiche/quic/test_tools/quic_framer_peer.h" #include "quiche/quic/test_tools/simple_quic_framer.h" #include "quiche/common/capsule.h" #include "quiche/common/simple_buffer_allocator.h" #include "quiche/spdy/core/http2_header_block.h" namespace quic { namespace test { QuicConnectionId TestConnectionId(); QuicConnectionId TestConnectionId(uint64_t connection_number); QuicConnectionId TestConnectionIdNineBytesLong(uint64_t connection_number); uint64_t TestConnectionIdToUInt64(QuicConnectionId connection_id); enum : uint16_t { kTestPort = 12345 }; enum : uint32_t { kMaxDatagramFrameSizeForTest = 1333, kMaxPacketSizeForTest = 9001, kInitialStreamFlowControlWindowForTest = 1024 * 1024, kInitialSessionFlowControlWindowForTest = 1536 * 1024, }; enum : uint64_t { kAckDelayExponentForTest = 10, kMaxAckDelayForTest = 51, kActiveConnectionIdLimitForTest = 52, kMinAckDelayUsForTest = 1000 }; std::vector<uint8_t> CreateStatelessResetTokenForTest(); std::string TestHostname(); QuicServerId TestServerId(); QuicIpAddress TestPeerIPAddress(); ParsedQuicVersion QuicVersionMax(); ParsedQuicVersion QuicVersionMin(); void DisableQuicVersionsWithTls(); QuicEncryptedPacket* ConstructEncryptedPacket( QuicConnectionId destination_connection_id, QuicConnectionId source_connection_id, bool version_flag, bool reset_flag, uint64_t packet_number, const std::string& data, bool full_padding, QuicConnectionIdIncluded destination_connection_id_included, QuicConnectionIdIncluded source_connection_id_included, QuicPacketNumberLength packet_number_length, ParsedQuicVersionVector* versions, Perspective perspective); QuicEncryptedPacket* ConstructEncryptedPacket( QuicConnectionId destination_connection_id, QuicConnectionId source_connection_id, bool version_flag, bool reset_flag, uint64_t packet_number, const std::string& data, bool full_padding, QuicConnectionIdIncluded destination_connection_id_included, QuicConnectionIdIncluded source_connection_id_included, QuicPacketNumberLength packet_number_length, ParsedQuicVersionVector* versions); QuicEncryptedPacket* ConstructEncryptedPacket( QuicConnectionId destination_connection_id, QuicConnectionId source_connection_id, bool version_flag, bool reset_flag, uint64_t packet_number, const std::string& data, QuicConnectionIdIncluded destination_connection_id_included, QuicConnectionIdIncluded source_connection_id_included, QuicPacketNumberLength packet_number_length, ParsedQuicVersionVector* versions); QuicEncryptedPacket* ConstructEncryptedPacket( QuicConnectionId destination_connection_id, QuicConnectionId source_connection_id, bool version_flag, bool reset_flag, uint64_t packet_number, const std::string& data, QuicConnectionIdIncluded destination_connection_id_included, QuicConnectionIdIncluded source_connection_id_included, QuicPacketNumberLength packet_number_length); QuicEncryptedPacket* ConstructEncryptedPacket( QuicConnectionId destination_connection_id, QuicConnectionId source_connection_id, bool version_flag, bool reset_flag, uint64_t packet_number, const std::string& data); std::unique_ptr<QuicEncryptedPacket> GetUndecryptableEarlyPacket( const ParsedQuicVersion& version, const QuicConnectionId& server_connection_id); QuicReceivedPacket* ConstructReceivedPacket( const QuicEncryptedPacket& encrypted_packet, QuicTime receipt_time); QuicReceivedPacket* ConstructReceivedPacket( const QuicEncryptedPacket& encrypted_packet, QuicTime receipt_time, QuicEcnCodepoint ecn); QuicEncryptedPacket* ConstructMisFramedEncryptedPacket( QuicConnectionId destination_connection_id, QuicConnectionId source_connection_id, bool version_flag, bool reset_flag, uint64_t packet_number, const std::string& data, QuicConnectionIdIncluded destination_connection_id_included, QuicConnectionIdIncluded source_connection_id_included, QuicPacketNumberLength packet_number_length, ParsedQuicVersion version, Perspective perspective); QuicConfig DefaultQuicConfig(); ParsedQuicVersionVector SupportedVersions(ParsedQuicVersion version); struct QuicAckBlock { QuicPacketNumber start; QuicPacketNumber limit; }; QuicAckFrame InitAckFrame(const std::vector<QuicAckBlock>& ack_blocks); QuicAckFrame InitAckFrame(uint64_t largest_acked); QuicAckFrame InitAckFrame(QuicPacketNumber largest_acked); QuicAckFrame MakeAckFrameWithAckBlocks(size_t num_ack_blocks, uint64_t least_unacked); QuicAckFrame MakeAckFrameWithGaps(uint64_t gap_size, size_t max_num_gaps, uint64_t largest_acked); EncryptionLevel HeaderToEncryptionLevel(const QuicPacketHeader& header); std::unique_ptr<QuicPacket> BuildUnsizedDataPacket( QuicFramer* framer, const QuicPacketHeader& header, const QuicFrames& frames); std::unique_ptr<QuicPacket> BuildUnsizedDataPacket( QuicFramer* framer, const QuicPacketHeader& header, const QuicFrames& frames, size_t packet_size); std::string Sha1Hash(absl::string_view data); bool ClearControlFrame(const QuicFrame& frame); bool ClearControlFrameWithTransmissionType(const QuicFrame& frame, TransmissionType type); class SimpleRandom : public QuicRandom { public: SimpleRandom() { set_seed(0); } SimpleRandom(const SimpleRandom&) = delete; SimpleRandom& operator=(const SimpleRandom&) = delete; ~SimpleRandom() override {} void RandBytes(void* data, size_t len) override; uint64_t RandUint64() override; void InsecureRandBytes(void* data, size_t len) override; uint64_t InsecureRandUint64() override; void set_seed(uint64_t seed); private: uint8_t buffer_[4096]; size_t buffer_offset_ = 0; uint8_t key_[32]; void FillBuffer(); }; class MockFramerVisitor : public QuicFramerVisitorInterface { public: MockFramerVisitor(); MockFramerVisitor(const MockFramerVisitor&) = delete; MockFramerVisitor& operator=(const MockFramerVisitor&) = delete; ~MockFramerVisitor() override; MOCK_METHOD(void, OnError, (QuicFramer*), (override)); MOCK_METHOD(bool, OnProtocolVersionMismatch, (ParsedQuicVersion version), (override)); MOCK_METHOD(void, OnPacket, (), (override)); MOCK_METHOD(void, OnVersionNegotiationPacket, (const QuicVersionNegotiationPacket& packet), (override)); MOCK_METHOD(void, OnRetryPacket, (QuicConnectionId original_connection_id, QuicConnectionId new_connection_id, absl::string_view retry_token, absl::string_view retry_integrity_tag, absl::string_view retry_without_tag), (override)); MOCK_METHOD(bool, OnUnauthenticatedHeader, (const QuicPacketHeader& header), (override)); MOCK_METHOD(bool, OnUnauthenticatedPublicHeader, (const QuicPacketHeader& header), (override)); MOCK_METHOD(void, OnDecryptedPacket, (size_t length, EncryptionLevel level), (override)); MOCK_METHOD(bool, OnPacketHeader, (const QuicPacketHeader& header), (override)); MOCK_METHOD(void, OnCoalescedPacket, (const QuicEncryptedPacket& packet), (override)); MOCK_METHOD(void, OnUndecryptablePacket, (const QuicEncryptedPacket& packet, EncryptionLevel decryption_level, bool has_decryption_key), (override)); MOCK_METHOD(bool, OnStreamFrame, (const QuicStreamFrame& frame), (override)); MOCK_METHOD(bool, OnCryptoFrame, (const QuicCryptoFrame& frame), (override)); MOCK_METHOD(bool, OnAckFrameStart, (QuicPacketNumber, QuicTime::Delta), (override)); MOCK_METHOD(bool, OnAckRange, (QuicPacketNumber, QuicPacketNumber), (override)); MOCK_METHOD(bool, OnAckTimestamp, (QuicPacketNumber, QuicTime), (override)); MOCK_METHOD(bool, OnAckFrameEnd, (QuicPacketNumber, const std::optional<QuicEcnCounts>&), (override)); MOCK_METHOD(bool, OnStopWaitingFrame, (const QuicStopWaitingFrame& frame), (override)); MOCK_METHOD(bool, OnPaddingFrame, (const QuicPaddingFrame& frame), (override)); MOCK_METHOD(bool, OnPingFrame, (const QuicPingFrame& frame), (override)); MOCK_METHOD(bool, OnRstStreamFrame, (const QuicRstStreamFrame& frame), (override)); MOCK_METHOD(bool, OnConnectionCloseFrame, (const QuicConnectionCloseFrame& frame), (override)); MOCK_METHOD(bool, OnNewConnectionIdFrame, (const QuicNewConnectionIdFrame& frame), (override)); MOCK_METHOD(bool, OnRetireConnectionIdFrame, (const QuicRetireConnectionIdFrame& frame), (override)); MOCK_METHOD(bool, OnNewTokenFrame, (const QuicNewTokenFrame& frame), (override)); MOCK_METHOD(bool, OnStopSendingFrame, (const QuicStopSendingFrame& frame), (override)); MOCK_METHOD(bool, OnPathChallengeFrame, (const QuicPathChallengeFrame& frame), (override)); MOCK_METHOD(bool, OnPathResponseFrame, (const QuicPathResponseFrame& frame), (override)); MOCK_METHOD(bool, OnGoAwayFrame, (const QuicGoAwayFrame& frame), (override)); MOCK_METHOD(bool, OnMaxStreamsFrame, (const QuicMaxStreamsFrame& frame), (override)); MOCK_METHOD(bool, OnStreamsBlockedFrame, (const QuicStreamsBlockedFrame& frame), (override)); MOCK_METHOD(bool, OnWindowUpdateFrame, (const QuicWindowUpdateFrame& frame), (override)); MOCK_METHOD(bool, OnBlockedFrame, (const QuicBlockedFrame& frame), (override)); MOCK_METHOD(bool, OnMessageFrame, (const QuicMessageFrame& frame), (override)); MOCK_METHOD(bool, OnHandshakeDoneFrame, (const QuicHandshakeDoneFrame& frame), (override)); MOCK_METHOD(bool, OnAckFrequencyFrame, (const QuicAckFrequencyFrame& frame), (override)); MOCK_METHOD(bool, OnResetStreamAtFrame, (const QuicResetStreamAtFrame& frame), (override)); MOCK_METHOD(void, OnPacketComplete, (), (override)); MOCK_METHOD(bool, IsValidStatelessResetToken, (const StatelessResetToken&), (const, override)); MOCK_METHOD(void, OnAuthenticatedIetfStatelessResetPacket, (const QuicIetfStatelessResetPacket&), (override)); MOCK_METHOD(void, OnKeyUpdate, (KeyUpdateReason), (override)); MOCK_METHOD(void, OnDecryptedFirstPacketInKeyPhase, (), (override)); MOCK_METHOD(std::unique_ptr<QuicDecrypter>, AdvanceKeysAndCreateCurrentOneRttDecrypter, (), (override)); MOCK_METHOD(std::unique_ptr<QuicEncrypter>, CreateCurrentOneRttEncrypter, (), (override)); }; class NoOpFramerVisitor : public QuicFramerVisitorInterface { public: NoOpFramerVisitor() {} NoOpFramerVisitor(const NoOpFramerVisitor&) = delete; NoOpFramerVisitor& operator=(const NoOpFramerVisitor&) = delete; void OnError(QuicFramer* ) override {} void OnPacket() override {} void OnVersionNegotiationPacket( const QuicVersionNegotiationPacket& ) override {} void OnRetryPacket(QuicConnectionId , QuicConnectionId , absl::string_view , absl::string_view , absl::string_view ) override {} bool OnProtocolVersionMismatch(ParsedQuicVersion version) override; bool OnUnauthenticatedHeader(const QuicPacketHeader& header) override; bool OnUnauthenticatedPublicHeader(const QuicPacketHeader& header) override; void OnDecryptedPacket(size_t , EncryptionLevel ) override {} bool OnPacketHeader(const QuicPacketHeader& header) override; void OnCoalescedPacket(const QuicEncryptedPacket& packet) override; void OnUndecryptablePacket(const QuicEncryptedPacket& packet, EncryptionLevel decryption_level, bool has_decryption_key) override; bool OnStreamFrame(const QuicStreamFrame& frame) override; bool OnCryptoFrame(const QuicCryptoFrame& frame) override; bool OnAckFrameStart(QuicPacketNumber largest_acked, QuicTime::Delta ack_delay_time) override; bool OnAckRange(QuicPacketNumber start, QuicPacketNumber end) override; bool OnAckTimestamp(QuicPacketNumber packet_number, QuicTime timestamp) override; bool OnAckFrameEnd(QuicPacketNumber start, const std::optional<QuicEcnCounts>& ecn_counts) override; bool OnStopWaitingFrame(const QuicStopWaitingFrame& frame) override; bool OnPaddingFrame(const QuicPaddingFrame& frame) override; bool OnPingFrame(const QuicPingFrame& frame) override; bool OnRstStreamFrame(const QuicRstStreamFrame& frame) override; bool OnConnectionCloseFrame(const QuicConnectionCloseFrame& frame) override; bool OnNewConnectionIdFrame(const QuicNewConnectionIdFrame& frame) override; bool OnRetireConnectionIdFrame( const QuicRetireConnectionIdFrame& frame) override; bool OnNewTokenFrame(const QuicNewTokenFrame& frame) override; bool OnStopSendingFrame(const QuicStopSendingFrame& frame) override; bool OnPathChallengeFrame(const QuicPathChallengeFrame& frame) override; bool OnPathResponseFrame(const QuicPathResponseFrame& frame) override; bool OnGoAwayFrame(const QuicGoAwayFrame& frame) override; bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) override; bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) override; bool OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) override; bool OnBlockedFrame(const QuicBlockedFrame& frame) override; bool OnMessageFrame(const QuicMessageFrame& frame) override; bool OnHandshakeDoneFrame(const QuicHandshakeDoneFrame& frame) override; bool OnAckFrequencyFrame(const QuicAckFrequencyFrame& frame) override; bool OnResetStreamAtFrame(const QuicResetStreamAtFrame& frame) override; void OnPacketComplete() override {} bool IsValidStatelessResetToken( const StatelessResetToken& token) const override; void OnAuthenticatedIetfStatelessResetPacket( const QuicIetfStatelessResetPacket& ) override {} void OnKeyUpdate(KeyUpdateReason ) override {} void OnDecryptedFirstPacketInKeyPhase() override {} std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter() override { return nullptr; } std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override { return nullptr; } }; class MockQuicConnectionVisitor : public QuicConnectionVisitorInterface { public: MockQuicConnectionVisitor(); MockQuicConnectionVisitor(const MockQuicConnectionVisitor&) = delete; MockQuicConnectionVisitor& operator=(const MockQuicConnectionVisitor&) = delete; ~MockQuicConnectionVisitor() override; MOCK_METHOD(void, OnStreamFrame, (const QuicStreamFrame& frame), (override)); MOCK_METHOD(void, OnCryptoFrame, (const QuicCryptoFrame& frame), (override)); MOCK_METHOD(void, OnWindowUpdateFrame, (const QuicWindowUpdateFrame& frame), (override)); MOCK_METHOD(void, OnBlockedFrame, (const QuicBlockedFrame& frame), (override)); MOCK_METHOD(void, OnRstStream, (const QuicRstStreamFrame& frame), (override)); MOCK_METHOD(void, OnGoAway, (const QuicGoAwayFrame& frame), (override)); MOCK_METHOD(void, OnMessageReceived, (absl::string_view message), (override)); MOCK_METHOD(void, OnHandshakeDoneReceived, (), (override)); MOCK_METHOD(void, OnNewTokenReceived, (absl::string_view token), (override)); MOCK_METHOD(void, OnConnectionClosed, (const QuicConnectionCloseFrame& frame, ConnectionCloseSource source), (override)); MOCK_METHOD(void, OnWriteBlocked, (), (override)); MOCK_METHOD(void, OnCanWrite, (), (override)); MOCK_METHOD(void, OnCongestionWindowChange, (QuicTime now), (override)); MOCK_METHOD(void, OnConnectionMigration, (AddressChangeType type), (override)); MOCK_METHOD(void, OnPathDegrading, (), (override)); MOCK_METHOD(void, OnForwardProgressMadeAfterPathDegrading, (), (override)); MOCK_METHOD(bool, WillingAndAbleToWrite, (), (const, override)); MOCK_METHOD(bool, ShouldKeepConnectionAlive, (), (const, override)); MOCK_METHOD(std::string, GetStreamsInfoForLogging, (), (const, override)); MOCK_METHOD(void, OnSuccessfulVersionNegotiation, (const ParsedQuicVersion& version), (override)); MOCK_METHOD(void, OnPacketReceived, (const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, bool is_connectivity_probe), (override)); MOCK_METHOD(void, OnAckNeedsRetransmittableFrame, (), (override)); MOCK_METHOD(void, SendAckFrequency, (const QuicAckFrequencyFrame& frame), (override)); MOCK_METHOD(void, SendNewConnectionId, (const QuicNewConnectionIdFrame& frame), (override)); MOCK_METHOD(void, SendRetireConnectionId, (uint64_t sequence_number), (override)); MOCK_METHOD(bool, MaybeReserveConnectionId, (const QuicConnectionId& server_connection_id), (override)); MOCK_METHOD(void, OnServerConnectionIdRetired, (const QuicConnectionId& server_connection_id), (override)); MOCK_METHOD(bool, AllowSelfAddressChange, (), (const, override)); MOCK_METHOD(HandshakeState, GetHandshakeState, (), (const, override)); MOCK_METHOD(bool, OnMaxStreamsFrame, (const QuicMaxStreamsFrame& frame), (override)); MOCK_METHOD(bool, OnStreamsBlockedFrame, (const QuicStreamsBlockedFrame& frame), (override)); MOCK_METHOD(void, OnStopSendingFrame, (const QuicStopSendingFrame& frame), (override)); MOCK_METHOD(void, OnPacketDecrypted, (EncryptionLevel), (override)); MOCK_METHOD(void, OnOneRttPacketAcknowledged, (), (override)); MOCK_METHOD(void, OnHandshakePacketSent, (), (override)); MOCK_METHOD(void, OnKeyUpdate, (KeyUpdateReason), (override)); MOCK_METHOD(std::unique_ptr<QuicDecrypter>, AdvanceKeysAndCreateCurrentOneRttDecrypter, (), (override)); MOCK_METHOD(std::unique_ptr<QuicEncrypter>, CreateCurrentOneRttEncrypter, (), (override)); MOCK_METHOD(void, BeforeConnectionCloseSent, (), (override)); MOCK_METHOD(bool, ValidateToken, (absl::string_view), (override)); MOCK_METHOD(bool, MaybeSendAddressToken, (), (override)); MOCK_METHOD(void, CreateContextForMultiPortPath, (std::unique_ptr<MultiPortPathContextObserver>), (override)); MOCK_METHOD(void, MigrateToMultiPortPath, (std::unique_ptr<QuicPathValidationContext>), (override)); MOCK_METHOD(void, OnServerPreferredAddressAvailable, (const QuicSocketAddress&), (override)); MOCK_METHOD(void, MaybeBundleOpportunistically, (), (override)); MOCK_METHOD(QuicByteCount, GetFlowControlSendWindowSize, (QuicStreamId), (override)); }; class MockQuicConnectionHelper : public QuicConnectionHelperInterface { public: MockQuicConnectionHelper(); MockQuicConnectionHelper(const MockQuicConnectionHelper&) = delete; MockQuicConnectionHelper& operator=(const MockQuicConnectionHelper&) = delete; ~MockQuicConnectionHelper() override; const MockClock* GetClock() const override; MockClock* GetClock(); QuicRandom* GetRandomGenerator() override; quiche::QuicheBufferAllocator* GetStreamSendBufferAllocator() override; void AdvanceTime(QuicTime::Delta delta); private: MockClock clock_; testing::NiceMock<MockRandom> random_generator_; quiche::SimpleBufferAllocator buffer_allocator_; }; class MockAlarmFactory : public QuicAlarmFactory { public: QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override; QuicArenaScopedPtr<QuicAlarm> CreateAlarm( QuicArenaScopedPtr<QuicAlarm::Delegate> delegate, QuicConnectionArena* arena) override; class TestAlarm : public QuicAlarm { public: explicit TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate> delegate) : QuicAlarm(std::move(delegate)) {} void SetImpl() override {} void CancelImpl() override {} using QuicAlarm::Fire; }; void FireAlarm(QuicAlarm* alarm) { reinterpret_cast<TestAlarm*>(alarm)->Fire(); } }; class TestAlarmFactory : public QuicAlarmFactory { public: class TestAlarm : public QuicAlarm { public: explicit TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate> delegate) : QuicAlarm(std::move(delegate)) {} void SetImpl() override {} void CancelImpl() override {} using QuicAlarm::Fire; }; TestAlarmFactory() {} TestAlarmFactory(const TestAlarmFactory&) = delete; TestAlarmFactory& operator=(const TestAlarmFactory&) = delete; QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override { return new TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate>(delegate)); } QuicArenaScopedPtr<QuicAlarm> CreateAlarm( QuicArenaScopedPtr<QuicAlarm::Delegate> delegate, QuicConnectionArena* arena) override { return arena->New<TestAlarm>(std::move(delegate)); } }; class MockQuicConnection : public QuicConnection { public: MockQuicConnection(QuicConnectionHelperInterface* helper, QuicAlarmFactory* alarm_factory, Perspective perspective); MockQuicConnection(QuicSocketAddress address, QuicConnectionHelperInterface* helper, QuicAlarmFactory* alarm_factory, Perspective perspective); MockQuicConnection(QuicConnectionId connection_id, QuicConnectionHelperInterface* helper, QuicAlarmFactory* alarm_factory, Perspective perspective); MockQuicConnection(QuicConnectionHelperInterface* helper, QuicAlarmFactory* alarm_factory, Perspective perspective, const ParsedQuicVersionVector& supported_versions); MockQuicConnection(QuicConnectionId connection_id, QuicSocketAddress address, QuicConnectionHelperInterface* helper, QuicAlarmFactory* alarm_factory, Perspective perspective, const ParsedQuicVersionVector& supported_versions); MockQuicConnection(const MockQuicConnection&) = delete; MockQuicConnection& operator=(const MockQuicConnection&) = delete; ~MockQuicConnection() override; void AdvanceTime(QuicTime::Delta delta); MOCK_METHOD(void, ProcessUdpPacket, (const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, const QuicReceivedPacket& packet), (override)); MOCK_METHOD(void, CloseConnection, (QuicErrorCode error, const std::string& details, ConnectionCloseBehavior connection_close_behavior), (override)); MOCK_METHOD(void, CloseConnection, (QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error, const std::string& details, ConnectionCloseBehavior connection_close_behavior), (override)); MOCK_METHOD(void, SendConnectionClosePacket, (QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error, const std::string& details), (override)); MOCK_METHOD(void, OnCanWrite, (), (override)); MOCK_METHOD(bool, SendConnectivityProbingPacket, (QuicPacketWriter*, const QuicSocketAddress& peer_address), (override)); MOCK_METHOD(void, MaybeProbeMultiPortPath, (), (override)); MOCK_METHOD(void, OnSendConnectionState, (const CachedNetworkParameters&), (override)); MOCK_METHOD(void, ResumeConnectionState, (const CachedNetworkParameters&, bool), (override)); MOCK_METHOD(void, SetMaxPacingRate, (QuicBandwidth), (override)); MOCK_METHOD(void, OnStreamReset, (QuicStreamId, QuicRstStreamErrorCode), (override)); MOCK_METHOD(bool, SendControlFrame, (const QuicFrame& frame), (override)); MOCK_METHOD(MessageStatus, SendMessage, (QuicMessageId, absl::Span<quiche::QuicheMemSlice>, bool), (override)); MOCK_METHOD(bool, SendPathChallenge, (const QuicPathFrameBuffer&, const QuicSocketAddress&, const QuicSocketAddress&, const QuicSocketAddress&, QuicPacketWriter*), (override)); MOCK_METHOD(void, OnError, (QuicFramer*), (override)); void QuicConnection_OnError(QuicFramer* framer) { QuicConnection::OnError(framer); } void ReallyOnCanWrite() { QuicConnection::OnCanWrite(); } void ReallyCloseConnection( QuicErrorCode error, const std::string& details, ConnectionCloseBehavior connection_close_behavior) { QuicConnection::CloseConnection(error, NO_IETF_QUIC_ERROR, details, connection_close_behavior); } void ReallyCloseConnection4( QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error, const std::string& details, ConnectionCloseBehavior connection_close_behavior) { QuicConnection::CloseConnection(error, ietf_error, details, connection_close_behavior); } void ReallySendConnectionClosePacket(QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error, const std::string& details) { QuicConnection::SendConnectionClosePacket(error, ietf_error, details); } void ReallyProcessUdpPacket(const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, const QuicReceivedPacket& packet) { QuicConnection::ProcessUdpPacket(self_address, peer_address, packet); } bool OnProtocolVersionMismatch(ParsedQuicVersion version) override; void OnIdleNetworkDetected() override {} bool ReallySendControlFrame(const QuicFrame& frame) { return QuicConnection::SendControlFrame(frame); } bool ReallySendConnectivityProbingPacket( QuicPac
#include "quiche/quic/test_tools/quic_test_utils.h" #include <string> #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { class QuicTestUtilsTest : public QuicTest {}; TEST_F(QuicTestUtilsTest, ConnectionId) { EXPECT_NE(EmptyQuicConnectionId(), TestConnectionId()); EXPECT_NE(EmptyQuicConnectionId(), TestConnectionId(1)); EXPECT_EQ(TestConnectionId(), TestConnectionId()); EXPECT_EQ(TestConnectionId(33), TestConnectionId(33)); EXPECT_NE(TestConnectionId(0xdead), TestConnectionId(0xbeef)); EXPECT_EQ(0x1337u, TestConnectionIdToUInt64(TestConnectionId(0x1337))); EXPECT_NE(0xdeadu, TestConnectionIdToUInt64(TestConnectionId(0xbeef))); } TEST_F(QuicTestUtilsTest, BasicApproxEq) { EXPECT_APPROX_EQ(10, 10, 1e-6f); EXPECT_APPROX_EQ(1000, 1001, 0.01f); EXPECT_NONFATAL_FAILURE(EXPECT_APPROX_EQ(1000, 1100, 0.01f), ""); EXPECT_APPROX_EQ(64, 31, 0.55f); EXPECT_NONFATAL_FAILURE(EXPECT_APPROX_EQ(31, 64, 0.55f), ""); } TEST_F(QuicTestUtilsTest, QuicTimeDelta) { EXPECT_APPROX_EQ(QuicTime::Delta::FromMicroseconds(1000), QuicTime::Delta::FromMicroseconds(1003), 0.01f); EXPECT_NONFATAL_FAILURE( EXPECT_APPROX_EQ(QuicTime::Delta::FromMicroseconds(1000), QuicTime::Delta::FromMicroseconds(1200), 0.01f), ""); } TEST_F(QuicTestUtilsTest, QuicBandwidth) { EXPECT_APPROX_EQ(QuicBandwidth::FromBytesPerSecond(1000), QuicBandwidth::FromBitsPerSecond(8005), 0.01f); EXPECT_NONFATAL_FAILURE( EXPECT_APPROX_EQ(QuicBandwidth::FromBytesPerSecond(1000), QuicBandwidth::FromBitsPerSecond(9005), 0.01f), ""); } TEST_F(QuicTestUtilsTest, SimpleRandomStability) { SimpleRandom rng; rng.set_seed(UINT64_C(0x1234567800010001)); EXPECT_EQ(UINT64_C(12589383305231984671), rng.RandUint64()); EXPECT_EQ(UINT64_C(17775425089941798664), rng.RandUint64()); } TEST_F(QuicTestUtilsTest, SimpleRandomChunks) { SimpleRandom rng; std::string reference(16 * 1024, '\0'); rng.RandBytes(&reference[0], reference.size()); for (size_t chunk_size : {3, 4, 7, 4096}) { rng.set_seed(0); size_t chunks = reference.size() / chunk_size; std::string buffer(chunks * chunk_size, '\0'); for (size_t i = 0; i < chunks; i++) { rng.RandBytes(&buffer[i * chunk_size], chunk_size); } EXPECT_EQ(reference.substr(0, buffer.size()), buffer) << "Failed for chunk_size = " << chunk_size; } } } }
377
cpp
google/quiche
crypto_test_utils
quiche/quic/test_tools/crypto_test_utils.cc
quiche/quic/test_tools/crypto_test_utils_test.cc
#ifndef QUICHE_QUIC_TEST_TOOLS_CRYPTO_TEST_UTILS_H_ #define QUICHE_QUIC_TEST_TOOLS_CRYPTO_TEST_UTILS_H_ #include <cstdarg> #include <cstddef> #include <cstdint> #include <memory> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "openssl/evp.h" #include "quiche/quic/core/crypto/crypto_framer.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_framer.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/quiche_callbacks.h" namespace quic { class ProofSource; class ProofVerifier; class ProofVerifyContext; class QuicClock; class QuicConfig; class QuicCryptoClientStream; class QuicCryptoServerConfig; class QuicCryptoServerStreamBase; class QuicCryptoStream; class QuicServerId; namespace test { class PacketSaver; class PacketSavingConnection; namespace crypto_test_utils { class CallbackSource { public: virtual ~CallbackSource() {} virtual void RunPendingCallbacks() = 0; }; struct FakeClientOptions { FakeClientOptions(); ~FakeClientOptions(); bool only_tls_versions = false; bool only_quic_crypto_versions = false; }; std::unique_ptr<QuicCryptoServerConfig> CryptoServerConfigForTesting(); int HandshakeWithFakeServer(QuicConfig* server_quic_config, QuicCryptoServerConfig* crypto_config, MockQuicConnectionHelper* helper, MockAlarmFactory* alarm_factory, PacketSavingConnection* client_conn, QuicCryptoClientStreamBase* client, std::string alpn); int HandshakeWithFakeClient(MockQuicConnectionHelper* helper, MockAlarmFactory* alarm_factory, PacketSavingConnection* server_conn, QuicCryptoServerStreamBase* server, const QuicServerId& server_id, const FakeClientOptions& options, std::string alpn); void SetupCryptoServerConfigForTest(const QuicClock* clock, QuicRandom* rand, QuicCryptoServerConfig* crypto_config); void SendHandshakeMessageToStream(QuicCryptoStream* stream, const CryptoHandshakeMessage& message, Perspective perspective); void CommunicateHandshakeMessages(PacketSavingConnection* client_conn, QuicCryptoStream* client, PacketSavingConnection* server_conn, QuicCryptoStream* server); void CommunicateHandshakeMessages(QuicConnection& client_conn, QuicCryptoStream& client, QuicConnection& server_conn, QuicCryptoStream& server, PacketProvider& packets_from_client, PacketProvider& packets_from_server); bool CommunicateHandshakeMessagesUntil( PacketSavingConnection* client_conn, QuicCryptoStream* client, quiche::UnretainedCallback<bool()> client_condition, PacketSavingConnection* server_conn, QuicCryptoStream* server, quiche::UnretainedCallback<bool()> server_condition, bool process_stream_data); bool CommunicateHandshakeMessagesUntil( QuicConnection& client_conn, QuicCryptoStream& client, quiche::UnretainedCallback<bool()> client_condition, QuicConnection& server_conn, QuicCryptoStream& server, quiche::UnretainedCallback<bool()> server_condition, bool process_stream_data, PacketProvider& packets_from_client, PacketProvider& packets_from_server); std::pair<size_t, size_t> AdvanceHandshake(PacketSavingConnection* client_conn, QuicCryptoStream* client, size_t client_i, PacketSavingConnection* server_conn, QuicCryptoStream* server, size_t server_i); void AdvanceHandshake( absl::Span<const QuicEncryptedPacket* const> packets_from_client, QuicConnection& client_conn, QuicCryptoStream& client, absl::Span<const QuicEncryptedPacket* const> packets_from_server, QuicConnection& server_conn, QuicCryptoStream& server); std::string GetValueForTag(const CryptoHandshakeMessage& message, QuicTag tag); std::unique_ptr<ProofSource> ProofSourceForTesting(); std::unique_ptr<ProofVerifier> ProofVerifierForTesting(); std::string CertificateHostnameForTesting(); uint64_t LeafCertHashForTesting(); std::unique_ptr<ProofVerifyContext> ProofVerifyContextForTesting(); void FillInDummyReject(CryptoHandshakeMessage* rej); QuicTag ParseTag(const char* tagstr); CryptoHandshakeMessage CreateCHLO( std::vector<std::pair<std::string, std::string>> tags_and_values); CryptoHandshakeMessage CreateCHLO( std::vector<std::pair<std::string, std::string>> tags_and_values, int minimum_size_bytes); CryptoHandshakeMessage GenerateDefaultInchoateCHLO( const QuicClock* clock, QuicTransportVersion version, QuicCryptoServerConfig* crypto_config); void GenerateFullCHLO( const CryptoHandshakeMessage& inchoate_chlo, QuicCryptoServerConfig* crypto_config, QuicSocketAddress server_addr, QuicSocketAddress client_addr, QuicTransportVersion transport_version, const QuicClock* clock, quiche::QuicheReferenceCountedPointer<QuicSignedServerConfig> signed_config, QuicCompressedCertsCache* compressed_certs_cache, CryptoHandshakeMessage* out); void CompareClientAndServerKeys(QuicCryptoClientStreamBase* client, QuicCryptoServerStreamBase* server); std::string GenerateClientNonceHex(const QuicClock* clock, QuicCryptoServerConfig* crypto_config); std::string GenerateClientPublicValuesHex(); } } } #endif #include "quiche/quic/test_tools/crypto_test_utils.h" #include <algorithm> #include <cstddef> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/core/crypto/certificate_view.h" #include "quiche/quic/core/crypto/crypto_handshake.h" #include "quiche/quic/core/crypto/crypto_utils.h" #include "quiche/quic/core/crypto/proof_source_x509.h" #include "quiche/quic/core/crypto/quic_crypto_server_config.h" #include "quiche/quic/core/crypto/quic_decrypter.h" #include "quiche/quic/core/crypto/quic_encrypter.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/proto/crypto_server_config_proto.h" #include "quiche/quic/core/quic_clock.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_crypto_client_stream.h" #include "quiche/quic/core/quic_crypto_server_stream_base.h" #include "quiche/quic/core/quic_crypto_stream.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_server_id.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_hostname_utils.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_framer_peer.h" #include "quiche/quic/test_tools/quic_stream_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simple_quic_framer.h" #include "quiche/quic/test_tools/test_certificates.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_callbacks.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace quic { namespace test { namespace crypto_test_utils { namespace { using testing::_; class CryptoFramerVisitor : public CryptoFramerVisitorInterface { public: CryptoFramerVisitor() : error_(false) {} void OnError(CryptoFramer* ) override { error_ = true; } void OnHandshakeMessage(const CryptoHandshakeMessage& message) override { messages_.push_back(message); } bool error() const { return error_; } const std::vector<CryptoHandshakeMessage>& messages() const { return messages_; } private: bool error_; std::vector<CryptoHandshakeMessage> messages_; }; bool HexChar(char c, uint8_t* value) { if (c >= '0' && c <= '9') { *value = c - '0'; return true; } if (c >= 'a' && c <= 'f') { *value = c - 'a' + 10; return true; } if (c >= 'A' && c <= 'F') { *value = c - 'A' + 10; return true; } return false; } void MovePackets(const QuicConnection& source_conn, absl::Span<const QuicEncryptedPacket* const> packets, QuicCryptoStream& dest_stream, QuicConnection& dest_conn, Perspective dest_perspective, bool process_stream_data) { QUICHE_CHECK(!packets.empty()); SimpleQuicFramer framer(source_conn.supported_versions(), dest_perspective); QuicFramerPeer::SetLastSerializedServerConnectionId(framer.framer(), TestConnectionId()); SimpleQuicFramer null_encryption_framer(source_conn.supported_versions(), dest_perspective); QuicFramerPeer::SetLastSerializedServerConnectionId( null_encryption_framer.framer(), TestConnectionId()); for (const QuicEncryptedPacket* const packet : packets) { if (!dest_conn.connected()) { QUIC_LOG(INFO) << "Destination connection disconnected. Skipping packet."; continue; } QuicConnectionPeer::SwapCrypters(&dest_conn, framer.framer()); QuicConnectionPeer::AddBytesReceived(&dest_conn, packet->length()); if (!framer.ProcessPacket(*packet)) { QuicConnectionPeer::SwapCrypters(&dest_conn, framer.framer()); continue; } QuicConnectionPeer::SwapCrypters(&dest_conn, framer.framer()); QuicConnection::ScopedPacketFlusher flusher(&dest_conn); dest_conn.OnDecryptedPacket(packet->length(), framer.last_decrypted_level()); if (dest_stream.handshake_protocol() == PROTOCOL_TLS1_3) { QUIC_LOG(INFO) << "Attempting to decrypt with NullDecrypter: " "expect a decryption failure on the next log line."; ASSERT_FALSE(null_encryption_framer.ProcessPacket(*packet)) << "No TLS packets should be encrypted with the NullEncrypter"; } dest_conn.OnDecryptedPacket(packet->length(), framer.last_decrypted_level()); QuicConnectionPeer::SetCurrentPacket(&dest_conn, packet->AsStringPiece()); for (const auto& stream_frame : framer.stream_frames()) { if (process_stream_data && dest_stream.handshake_protocol() == PROTOCOL_TLS1_3) { dest_conn.OnStreamFrame(*stream_frame); } else { if (stream_frame->stream_id == dest_stream.id()) { dest_stream.OnStreamFrame(*stream_frame); } } } for (const auto& crypto_frame : framer.crypto_frames()) { dest_stream.OnCryptoFrame(*crypto_frame); } if (!framer.connection_close_frames().empty() && dest_conn.connected()) { dest_conn.OnConnectionCloseFrame(framer.connection_close_frames()[0]); } } QuicConnectionPeer::SetCurrentPacket(&dest_conn, absl::string_view(nullptr, 0)); } } FakeClientOptions::FakeClientOptions() {} FakeClientOptions::~FakeClientOptions() {} namespace { class FullChloGenerator { public: FullChloGenerator( QuicCryptoServerConfig* crypto_config, QuicSocketAddress server_addr, QuicSocketAddress client_addr, const QuicClock* clock, ParsedQuicVersion version, quiche::QuicheReferenceCountedPointer<QuicSignedServerConfig> signed_config, QuicCompressedCertsCache* compressed_certs_cache, CryptoHandshakeMessage* out) : crypto_config_(crypto_config), server_addr_(server_addr), client_addr_(client_addr), clock_(clock), version_(version), signed_config_(signed_config), compressed_certs_cache_(compressed_certs_cache), out_(out), params_(new QuicCryptoNegotiatedParameters) {} class ValidateClientHelloCallback : public ValidateClientHelloResultCallback { public: explicit ValidateClientHelloCallback(FullChloGenerator* generator) : generator_(generator) {} void Run(quiche::QuicheReferenceCountedPointer< ValidateClientHelloResultCallback::Result> result, std::unique_ptr<ProofSource::Details> ) override { generator_->ValidateClientHelloDone(std::move(result)); } private: FullChloGenerator* generator_; }; std::unique_ptr<ValidateClientHelloCallback> GetValidateClientHelloCallback() { return std::make_unique<ValidateClientHelloCallback>(this); } private: void ValidateClientHelloDone(quiche::QuicheReferenceCountedPointer< ValidateClientHelloResultCallback::Result> result) { result_ = result; crypto_config_->ProcessClientHello( result_, false, TestConnectionId(1), server_addr_, client_addr_, version_, {version_}, clock_, QuicRandom::GetInstance(), compressed_certs_cache_, params_, signed_config_, 50, kDefaultMaxPacketSize, GetProcessClientHelloCallback()); } class ProcessClientHelloCallback : public ProcessClientHelloResultCallback { public: explicit ProcessClientHelloCallback(FullChloGenerator* generator) : generator_(generator) {} void Run(QuicErrorCode error, const std::string& error_details, std::unique_ptr<CryptoHandshakeMessage> message, std::unique_ptr<DiversificationNonce> , std::unique_ptr<ProofSource::Details> ) override { ASSERT_TRUE(message) << QuicErrorCodeToString(error) << " " << error_details; generator_->ProcessClientHelloDone(std::move(message)); } private: FullChloGenerator* generator_; }; std::unique_ptr<ProcessClientHelloCallback> GetProcessClientHelloCallback() { return std::make_unique<ProcessClientHelloCallback>(this); } void ProcessClientHelloDone(std::unique_ptr<CryptoHandshakeMessage> rej) { EXPECT_THAT(rej->tag(), testing::Eq(kREJ)); QUIC_VLOG(1) << "Extract valid STK and SCID from\n" << rej->DebugString(); absl::string_view srct; ASSERT_TRUE(rej->GetStringPiece(kSourceAddressTokenTag, &srct)); absl::string_view scfg; ASSERT_TRUE(rej->GetStringPiece(kSCFG, &scfg)); std::unique_ptr<CryptoHandshakeMessage> server_config( CryptoFramer::ParseMessage(scfg)); absl::string_view scid; ASSERT_TRUE(server_config->GetStringPiece(kSCID, &scid)); *out_ = result_->client_hello; out_->SetStringPiece(kSCID, scid); out_->SetStringPiece(kSourceAddressTokenTag, srct); uint64_t xlct = LeafCertHashForTesting(); out_->SetValue(kXLCT, xlct); } protected: QuicCryptoServerConfig* crypto_config_; QuicSocketAddress server_addr_; QuicSocketAddress client_addr_; const QuicClock* clock_; ParsedQuicVersion version_; quiche::QuicheReferenceCountedPointer<QuicSignedServerConfig> signed_config_; QuicCompressedCertsCache* compressed_certs_cache_; CryptoHandshakeMessage* out_; quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> params_; quiche::QuicheReferenceCountedPointer< ValidateClientHelloResultCallback::Result> result_; }; } std::unique_ptr<QuicCryptoServerConfig> CryptoServerConfigForTesting() { return std::make_unique<QuicCryptoServerConfig>( QuicCryptoServerConfig::TESTING, QuicRandom::GetInstance(), ProofSourceForTesting(), KeyExchangeSource::Default()); } int HandshakeWithFakeServer(QuicConfig* server_quic_config, QuicCryptoServerConfig* crypto_config, MockQuicConnectionHelper* helper, MockAlarmFactory* alarm_factory, PacketSavingConnection* client_conn, QuicCryptoClientStreamBase* client, std::string alpn) { auto* server_conn = new testing::NiceMock<PacketSavingConnection>( helper, alarm_factory, Perspective::IS_SERVER, ParsedVersionOfIndex(client_conn->supported_versions(), 0)); QuicCompressedCertsCache compressed_certs_cache( QuicCompressedCertsCache::kQuicCompressedCertsCacheSize); SetupCryptoServerConfigForTest( server_conn->clock(), server_conn->random_generator(), crypto_config); TestQuicSpdyServerSession server_session( server_conn, *server_quic_config, client_conn->supported_versions(), crypto_config, &compressed_certs_cache); server_session.Initialize(); server_session.GetMutableCryptoStream() ->SetServerApplicationStateForResumption( std::make_unique<ApplicationState>()); EXPECT_CALL(*server_session.helper(), CanAcceptClientHello(testing::_, testing::_, testing::_, testing::_, testing::_)) .Times(testing::AnyNumber()); EXPECT_CALL(*server_conn, OnCanWrite()).Times(testing::AnyNumber()); EXPECT_CALL(*client_conn, OnCanWrite()).Times(testing::AnyNumber()); EXPECT_CALL(*server_conn, SendCryptoData(_, _, _)) .Times(testing::AnyNumber()); EXPECT_CALL(server_session, SelectAlpn(_)) .WillRepeatedly([alpn](const std::vector<absl::string_view>& alpns) { return std::find(alpns.cbegin(), alpns.cend(), alpn); }); QUICHE_CHECK_NE(0u, client_conn->encrypted_packets_.size()); CommunicateHandshakeMessages(client_conn, client, server_conn, server_session.GetMutableCryptoStream()); if (client_conn->connected() && server_conn->connected()) { CompareClientAndServerKeys(client, server_session.GetMutableCryptoStream()); } return client->num_sent_client_hellos(); } int HandshakeWithFakeClient(MockQuicConnectionHelper* helper, MockAlarmFactory* alarm_factory, PacketSavingConnection* server_conn, QuicCryptoServerStreamBase* server, const QuicServerId& server_id, const FakeClientOptions& options, std::string alpn) { ParsedQuicVersionVector supported_versions = server_conn->supported_versions(); if (options.only_tls_versions) { supported_versions.erase( std::remove_if(supported_versions.begin(), supported_versions.end(), [](const ParsedQuicVersion& version) { return version.handshake_protocol != PROTOCOL_TLS1_3; }), supported_versions.end()); QUICHE_CHECK(!options.only_quic_crypto_versions); } else if (options.only_quic_crypto_versions) { supported_versions.erase( std::remove_if(supported_versions.begin(), supported_versions.end(), [](const ParsedQuicVersion& version) { return version.handshake_protocol != PROTOCOL_QUIC_CRYPTO; }), supported_versions.end()); } PacketSavingConnection* client_conn = new PacketSavingConnection( helper, alarm_factory, Perspective::IS_CLIENT, supported_versions); client_conn->AdvanceTime(QuicTime::Delta::FromSeconds(1)); QuicCryptoClientConfig crypto_config(ProofVerifierForTesting()); TestQuicSpdyClientSession client_session(client_conn, DefaultQuicConfig(), supported_versions, server_id, &crypto_config); EXPECT_CALL(client_session, OnProofValid(testing::_)) .Times(testing::AnyNumber()); EXPECT_CALL(client_session, OnProofVerifyDetailsAvailable(testing::_)) .Times(testing::AnyNumber()); EXPECT_CALL(*client_conn, OnCanWrite()).Times(testing::AnyNumber()); if (!alpn.empty()) { EXPECT_CALL(client_session, GetAlpnsToOffer()) .WillRepeatedly(testing::Return(std::vector<std::string>({alpn}))); } else { EXPECT_CALL(client_session, GetAlpnsToOffer()) .WillRepeatedly(testing::Return(std::vector<std::string>( {AlpnForVersion(client_conn->version())}))); } client_session.GetMutableCryptoStream()->CryptoConnect(); QUICHE_CHECK_EQ(1u, client_conn->encrypted_packets_.size()); CommunicateHandshakeMessages(client_conn, client_session.GetMutableCryptoStream(), server_conn, server); if (server->one_rtt_keys_available() && server->encryption_established()) { CompareClientAndServerKeys(client_session.GetMutableCryptoStream(), server); } return client_session.GetCryptoStream()->num_sent_client_hellos(); } void SetupCryptoServerConfigForTest(const QuicClock* clock, QuicRandom* rand, QuicCryptoServerConfig* crypto_config) { QuicCryptoServerConfig::ConfigOptions options; options.channel_id_enabled = true; std::unique_ptr<CryptoHandshakeMessage> scfg = crypto_config->AddDefaultConfig(rand, clock, options); } void SendHandshakeMessageToStream(QuicCryptoStream* stream, const CryptoHandshakeMessage& message, Perspective ) { const QuicData& data = message.GetSerialized(); QuicSession* session = QuicStreamPeer::session(stream); if (!QuicVersionUsesCryptoFrames(session->transport_version())) { QuicStreamFrame frame( QuicUtils::GetCryptoStreamId(session->transport_version()), false, stream->crypto_bytes_read(), data.AsStringPiece()); stream->OnStreamFrame(frame); } else { EncryptionLevel level = session->connection()->last_decrypted_level(); QuicCryptoFrame frame(level, stream->BytesReadOnLevel(level), data.AsStringPiece()); stream->OnCryptoFrame(frame); } } void CommunicateHandshakeMessages(PacketSavingConnection* client_conn, QuicCryptoStream* client, PacketSavingConnection* server_conn, QuicCryptoStream* server) { CommunicateHandshakeMessages(*client_conn, *client, *server_conn, *server, *client_conn, *server_conn); } void CommunicateHandshakeMessages(QuicConnection& client_conn, QuicCryptoStream& client, QuicConnection& server_conn, QuicCryptoStream& server, PacketProvider& packets_from_client, PacketProvider& packets_from_server) { while ( client_conn.connected() && server_conn.connected() && (!client.one_rtt_keys_available() || !server.one_rtt_keys_available())) { QUICHE_CHECK(!packets_from_client.GetPackets().empty()); QUIC_LOG(INFO) << "Processing " << packets_from_client.GetPackets().size() << " packets client->server"; MovePackets(client_conn, packets_from_client.GetPackets(), server, server_conn, Perspective::IS_SERVER, false); packets_from_client.ClearPackets(); if (client.one_rtt_keys_available() && server.one_rtt_keys_available() && packets_from_server.GetPackets().empty()) { break; } QUIC_LOG(INFO) << "Processing " << packets_from_server.GetPackets().size() << " packets server->client"; MovePackets(server_conn, packets_from_server.GetPackets(), client, client_conn, Perspective::IS_CLIENT, false); packets_from_server.ClearPackets(); } } bool CommunicateHandshakeMessagesUntil( PacketSavingConnection* client_conn, QuicCryptoStream* client, quiche::UnretainedCallback<bool()> client_condition, PacketSavingConnection* server_conn, QuicCryptoStream* server, quiche::UnretainedCallback<bool()> server_condition, bool process_stream_data) { return CommunicateHandshakeMessagesUntil( *client_conn, *client, client_condition, *server_conn, *server, server_condition, process_stream_data, *client_conn, *server_conn); } bool CommunicateHandshakeMessagesUntil( QuicConnection& client_conn, QuicCryptoStream& client, quiche::UnretainedCallback<bool()> client_condition, QuicConnection& server_conn, QuicCryptoStream& server, quiche::UnretainedCallback<bool()> server_condition, bool process_stream_data, PacketProvider& packets_from_client, PacketProvider& packets_from_server) { while (cli
#include "quiche/quic/test_tools/crypto_test_utils.h" #include <memory> #include <string> #include <utility> #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/proto/crypto_server_config_proto.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_clock.h" namespace quic { namespace test { class ShloVerifier { public: ShloVerifier(QuicCryptoServerConfig* crypto_config, QuicSocketAddress server_addr, QuicSocketAddress client_addr, const QuicClock* clock, quiche::QuicheReferenceCountedPointer<QuicSignedServerConfig> signed_config, QuicCompressedCertsCache* compressed_certs_cache, ParsedQuicVersion version) : crypto_config_(crypto_config), server_addr_(server_addr), client_addr_(client_addr), clock_(clock), signed_config_(signed_config), compressed_certs_cache_(compressed_certs_cache), params_(new QuicCryptoNegotiatedParameters), version_(version) {} class ValidateClientHelloCallback : public ValidateClientHelloResultCallback { public: explicit ValidateClientHelloCallback(ShloVerifier* shlo_verifier) : shlo_verifier_(shlo_verifier) {} void Run(quiche::QuicheReferenceCountedPointer< ValidateClientHelloResultCallback::Result> result, std::unique_ptr<ProofSource::Details> ) override { shlo_verifier_->ValidateClientHelloDone(result); } private: ShloVerifier* shlo_verifier_; }; std::unique_ptr<ValidateClientHelloCallback> GetValidateClientHelloCallback() { return std::make_unique<ValidateClientHelloCallback>(this); } absl::string_view server_nonce() { return server_nonce_; } bool chlo_accepted() const { return chlo_accepted_; } private: void ValidateClientHelloDone( const quiche::QuicheReferenceCountedPointer< ValidateClientHelloResultCallback::Result>& result) { result_ = result; crypto_config_->ProcessClientHello( result_, false, TestConnectionId(1), server_addr_, client_addr_, version_, AllSupportedVersions(), clock_, QuicRandom::GetInstance(), compressed_certs_cache_, params_, signed_config_, 50, kDefaultMaxPacketSize, GetProcessClientHelloCallback()); } class ProcessClientHelloCallback : public ProcessClientHelloResultCallback { public: explicit ProcessClientHelloCallback(ShloVerifier* shlo_verifier) : shlo_verifier_(shlo_verifier) {} void Run(QuicErrorCode , const std::string& , std::unique_ptr<CryptoHandshakeMessage> message, std::unique_ptr<DiversificationNonce> , std::unique_ptr<ProofSource::Details> ) override { shlo_verifier_->ProcessClientHelloDone(std::move(message)); } private: ShloVerifier* shlo_verifier_; }; std::unique_ptr<ProcessClientHelloCallback> GetProcessClientHelloCallback() { return std::make_unique<ProcessClientHelloCallback>(this); } void ProcessClientHelloDone(std::unique_ptr<CryptoHandshakeMessage> message) { if (message->tag() == kSHLO) { chlo_accepted_ = true; } else { QUIC_LOG(INFO) << "Fail to pass validation. Get " << message->DebugString(); chlo_accepted_ = false; EXPECT_EQ(1u, result_->info.reject_reasons.size()); EXPECT_EQ(SERVER_NONCE_REQUIRED_FAILURE, result_->info.reject_reasons[0]); server_nonce_ = result_->info.server_nonce; } } QuicCryptoServerConfig* crypto_config_; QuicSocketAddress server_addr_; QuicSocketAddress client_addr_; const QuicClock* clock_; quiche::QuicheReferenceCountedPointer<QuicSignedServerConfig> signed_config_; QuicCompressedCertsCache* compressed_certs_cache_; quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> params_; quiche::QuicheReferenceCountedPointer< ValidateClientHelloResultCallback::Result> result_; const ParsedQuicVersion version_; bool chlo_accepted_ = false; absl::string_view server_nonce_; }; class CryptoTestUtilsTest : public QuicTest {}; TEST_F(CryptoTestUtilsTest, TestGenerateFullCHLO) { MockClock clock; QuicCryptoServerConfig crypto_config( QuicCryptoServerConfig::TESTING, QuicRandom::GetInstance(), crypto_test_utils::ProofSourceForTesting(), KeyExchangeSource::Default()); QuicSocketAddress server_addr(QuicIpAddress::Any4(), 5); QuicSocketAddress client_addr(QuicIpAddress::Loopback4(), 1); quiche::QuicheReferenceCountedPointer<QuicSignedServerConfig> signed_config( new QuicSignedServerConfig); QuicCompressedCertsCache compressed_certs_cache( QuicCompressedCertsCache::kQuicCompressedCertsCacheSize); CryptoHandshakeMessage full_chlo; QuicCryptoServerConfig::ConfigOptions old_config_options; old_config_options.id = "old-config-id"; crypto_config.AddDefaultConfig(QuicRandom::GetInstance(), &clock, old_config_options); QuicCryptoServerConfig::ConfigOptions new_config_options; QuicServerConfigProtobuf primary_config = crypto_config.GenerateConfig( QuicRandom::GetInstance(), &clock, new_config_options); primary_config.set_primary_time(clock.WallNow().ToUNIXSeconds()); std::unique_ptr<CryptoHandshakeMessage> msg = crypto_config.AddConfig(primary_config, clock.WallNow()); absl::string_view orbit; ASSERT_TRUE(msg->GetStringPiece(kORBT, &orbit)); std::string nonce; CryptoUtils::GenerateNonce(clock.WallNow(), QuicRandom::GetInstance(), orbit, &nonce); std::string nonce_hex = "#" + absl::BytesToHexString(nonce); char public_value[32]; memset(public_value, 42, sizeof(public_value)); std::string pub_hex = "#" + absl::BytesToHexString(absl::string_view( public_value, sizeof(public_value))); QuicTransportVersion transport_version = QUIC_VERSION_UNSUPPORTED; for (const ParsedQuicVersion& version : AllSupportedVersions()) { if (version.handshake_protocol == PROTOCOL_QUIC_CRYPTO) { transport_version = version.transport_version; break; } } ASSERT_NE(QUIC_VERSION_UNSUPPORTED, transport_version); CryptoHandshakeMessage inchoate_chlo = crypto_test_utils::CreateCHLO( {{"PDMD", "X509"}, {"AEAD", "AESG"}, {"KEXS", "C255"}, {"COPT", "SREJ"}, {"PUBS", pub_hex}, {"NONC", nonce_hex}, {"VER\0", QuicVersionLabelToString(CreateQuicVersionLabel( ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, transport_version)))}}, kClientHelloMinimumSize); crypto_test_utils::GenerateFullCHLO(inchoate_chlo, &crypto_config, server_addr, client_addr, transport_version, &clock, signed_config, &compressed_certs_cache, &full_chlo); ShloVerifier shlo_verifier( &crypto_config, server_addr, client_addr, &clock, signed_config, &compressed_certs_cache, ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, transport_version)); crypto_config.ValidateClientHello( full_chlo, client_addr, server_addr, transport_version, &clock, signed_config, shlo_verifier.GetValidateClientHelloCallback()); ASSERT_EQ(shlo_verifier.chlo_accepted(), !GetQuicReloadableFlag(quic_require_handshake_confirmation)); if (!shlo_verifier.chlo_accepted()) { ShloVerifier shlo_verifier2( &crypto_config, server_addr, client_addr, &clock, signed_config, &compressed_certs_cache, ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, transport_version)); full_chlo.SetStringPiece( kServerNonceTag, "#" + absl::BytesToHexString(shlo_verifier.server_nonce())); crypto_config.ValidateClientHello( full_chlo, client_addr, server_addr, transport_version, &clock, signed_config, shlo_verifier2.GetValidateClientHelloCallback()); EXPECT_TRUE(shlo_verifier2.chlo_accepted()) << full_chlo.DebugString(); } } } }
378
cpp
google/quiche
simulator
quiche/quic/test_tools/simulator/simulator.cc
quiche/quic/test_tools/simulator/simulator_test.cc
#ifndef QUICHE_QUIC_TEST_TOOLS_SIMULATOR_SIMULATOR_H_ #define QUICHE_QUIC_TEST_TOOLS_SIMULATOR_SIMULATOR_H_ #include <map> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/test_tools/simulator/actor.h" #include "quiche/quic/test_tools/simulator/alarm_factory.h" #include "quiche/common/simple_buffer_allocator.h" namespace quic { namespace simulator { class Simulator : public QuicConnectionHelperInterface { public: Simulator(); explicit Simulator(QuicRandom* random_generator); Simulator(const Simulator&) = delete; Simulator& operator=(const Simulator&) = delete; ~Simulator() override; void Schedule(Actor* actor, QuicTime new_time); void Unschedule(Actor* actor); const QuicClock* GetClock() const override; QuicRandom* GetRandomGenerator() override; quiche::QuicheBufferAllocator* GetStreamSendBufferAllocator() override; QuicAlarmFactory* GetAlarmFactory(); void set_random_generator(QuicRandom* random) { random_generator_ = random; } bool enable_random_delays() const { return enable_random_delays_; } template <class TerminationPredicate> bool RunUntil(TerminationPredicate termination_predicate); template <class TerminationPredicate> bool RunUntilOrTimeout(TerminationPredicate termination_predicate, QuicTime::Delta deadline); void RunFor(QuicTime::Delta time_span); private: friend class Actor; class Clock : public QuicClock { public: const QuicTime kStartTime = QuicTime::Zero() + QuicTime::Delta::FromMicroseconds(1); Clock(); QuicTime ApproximateNow() const override; QuicTime Now() const override; QuicWallTime WallNow() const override; QuicTime now_; }; class RunForDelegate : public QuicAlarm::DelegateWithoutContext { public: explicit RunForDelegate(bool* run_for_should_stop); void OnAlarm() override; private: bool* run_for_should_stop_; }; void AddActor(Actor* actor); void RemoveActor(Actor* actor); void HandleNextScheduledActor(); Clock clock_; QuicRandom* random_generator_; quiche::SimpleBufferAllocator buffer_allocator_; AlarmFactory alarm_factory_; std::unique_ptr<QuicAlarm> run_for_alarm_; bool run_for_should_stop_; bool enable_random_delays_; std::multimap<QuicTime, Actor*> schedule_; absl::flat_hash_map<Actor*, QuicTime> scheduled_times_; absl::flat_hash_set<std::string> actor_names_; }; template <class TerminationPredicate> bool Simulator::RunUntil(TerminationPredicate termination_predicate) { bool predicate_value = false; while (true) { predicate_value = termination_predicate(); if (predicate_value || schedule_.empty()) { break; } HandleNextScheduledActor(); } return predicate_value; } template <class TerminationPredicate> bool Simulator::RunUntilOrTimeout(TerminationPredicate termination_predicate, QuicTime::Delta timeout) { QuicTime end_time = clock_.Now() + timeout; bool return_value = RunUntil([end_time, &termination_predicate, this]() { return termination_predicate() || clock_.Now() >= end_time; }); if (clock_.Now() >= end_time) { return false; } return return_value; } } } #endif #include "quiche/quic/test_tools/simulator/simulator.h" #include <utility> #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { namespace simulator { Simulator::Simulator() : Simulator(nullptr) {} Simulator::Simulator(QuicRandom* random_generator) : random_generator_(random_generator), alarm_factory_(this, "Default Alarm Manager"), run_for_should_stop_(false), enable_random_delays_(false) { run_for_alarm_.reset( alarm_factory_.CreateAlarm(new RunForDelegate(&run_for_should_stop_))); } Simulator::~Simulator() { run_for_alarm_.reset(); } Simulator::Clock::Clock() : now_(kStartTime) {} QuicTime Simulator::Clock::ApproximateNow() const { return now_; } QuicTime Simulator::Clock::Now() const { return now_; } QuicWallTime Simulator::Clock::WallNow() const { return QuicWallTime::FromUNIXMicroseconds( (now_ - QuicTime::Zero()).ToMicroseconds()); } void Simulator::AddActor(Actor* actor) { auto emplace_times_result = scheduled_times_.insert(std::make_pair(actor, QuicTime::Infinite())); auto emplace_names_result = actor_names_.insert(actor->name()); QUICHE_DCHECK(emplace_times_result.second); QUICHE_DCHECK(emplace_names_result.second); } void Simulator::RemoveActor(Actor* actor) { auto scheduled_time_it = scheduled_times_.find(actor); auto actor_names_it = actor_names_.find(actor->name()); QUICHE_DCHECK(scheduled_time_it != scheduled_times_.end()); QUICHE_DCHECK(actor_names_it != actor_names_.end()); QuicTime scheduled_time = scheduled_time_it->second; if (scheduled_time != QuicTime::Infinite()) { Unschedule(actor); } scheduled_times_.erase(scheduled_time_it); actor_names_.erase(actor_names_it); } void Simulator::Schedule(Actor* actor, QuicTime new_time) { auto scheduled_time_it = scheduled_times_.find(actor); QUICHE_DCHECK(scheduled_time_it != scheduled_times_.end()); QuicTime scheduled_time = scheduled_time_it->second; if (scheduled_time <= new_time) { return; } if (scheduled_time != QuicTime::Infinite()) { Unschedule(actor); } scheduled_time_it->second = new_time; schedule_.insert(std::make_pair(new_time, actor)); } void Simulator::Unschedule(Actor* actor) { auto scheduled_time_it = scheduled_times_.find(actor); QUICHE_DCHECK(scheduled_time_it != scheduled_times_.end()); QuicTime scheduled_time = scheduled_time_it->second; QUICHE_DCHECK(scheduled_time != QuicTime::Infinite()); auto range = schedule_.equal_range(scheduled_time); for (auto it = range.first; it != range.second; ++it) { if (it->second == actor) { schedule_.erase(it); scheduled_time_it->second = QuicTime::Infinite(); return; } } QUICHE_DCHECK(false); } const QuicClock* Simulator::GetClock() const { return &clock_; } QuicRandom* Simulator::GetRandomGenerator() { if (random_generator_ == nullptr) { random_generator_ = QuicRandom::GetInstance(); } return random_generator_; } quiche::QuicheBufferAllocator* Simulator::GetStreamSendBufferAllocator() { return &buffer_allocator_; } QuicAlarmFactory* Simulator::GetAlarmFactory() { return &alarm_factory_; } Simulator::RunForDelegate::RunForDelegate(bool* run_for_should_stop) : run_for_should_stop_(run_for_should_stop) {} void Simulator::RunForDelegate::OnAlarm() { *run_for_should_stop_ = true; } void Simulator::RunFor(QuicTime::Delta time_span) { QUICHE_DCHECK(!run_for_alarm_->IsSet()); const QuicTime end_time = clock_.Now() + time_span; run_for_alarm_->Set(end_time); run_for_should_stop_ = false; bool simulation_result = RunUntil([this]() { return run_for_should_stop_; }); QUICHE_DCHECK(simulation_result); QUICHE_DCHECK(clock_.Now() == end_time); } void Simulator::HandleNextScheduledActor() { const auto current_event_it = schedule_.begin(); QuicTime event_time = current_event_it->first; Actor* actor = current_event_it->second; QUIC_DVLOG(3) << "At t = " << event_time.ToDebuggingValue() << ", calling " << actor->name(); Unschedule(actor); if (clock_.Now() > event_time) { QUIC_BUG(quic_bug_10150_1) << "Error: event registered by [" << actor->name() << "] requires travelling back in time. Current time: " << clock_.Now().ToDebuggingValue() << ", scheduled time: " << event_time.ToDebuggingValue(); } clock_.now_ = event_time; actor->Act(); } } }
#include "quiche/quic/test_tools/simulator/simulator.h" #include <memory> #include <string> #include <utility> #include <vector> #include "absl/container/node_hash_map.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simulator/alarm_factory.h" #include "quiche/quic/test_tools/simulator/link.h" #include "quiche/quic/test_tools/simulator/packet_filter.h" #include "quiche/quic/test_tools/simulator/queue.h" #include "quiche/quic/test_tools/simulator/switch.h" #include "quiche/quic/test_tools/simulator/traffic_policer.h" using testing::_; using testing::Return; using testing::StrictMock; namespace quic { namespace simulator { class Counter : public Actor { public: Counter(Simulator* simulator, std::string name, QuicTime::Delta period) : Actor(simulator, name), value_(-1), period_(period) { Schedule(clock_->Now()); } ~Counter() override {} inline int get_value() const { return value_; } void Act() override { ++value_; QUIC_DVLOG(1) << name_ << " has value " << value_ << " at time " << clock_->Now().ToDebuggingValue(); Schedule(clock_->Now() + period_); } private: int value_; QuicTime::Delta period_; }; class SimulatorTest : public quic::test::QuicTest {}; TEST_F(SimulatorTest, Counters) { Simulator simulator; for (int i = 0; i < 2; ++i) { Counter fast_counter(&simulator, "fast_counter", QuicTime::Delta::FromSeconds(3)); Counter slow_counter(&simulator, "slow_counter", QuicTime::Delta::FromSeconds(10)); simulator.RunUntil( [&slow_counter]() { return slow_counter.get_value() >= 10; }); EXPECT_EQ(10, slow_counter.get_value()); EXPECT_EQ(10 * 10 / 3, fast_counter.get_value()); } } class CounterPort : public UnconstrainedPortInterface { public: CounterPort() { Reset(); } ~CounterPort() override {} inline QuicByteCount bytes() const { return bytes_; } inline QuicPacketCount packets() const { return packets_; } void AcceptPacket(std::unique_ptr<Packet> packet) override { bytes_ += packet->size; packets_ += 1; per_destination_packet_counter_[packet->destination] += 1; } void Reset() { bytes_ = 0; packets_ = 0; per_destination_packet_counter_.clear(); } QuicPacketCount CountPacketsForDestination(std::string destination) const { auto result_it = per_destination_packet_counter_.find(destination); if (result_it == per_destination_packet_counter_.cend()) { return 0; } return result_it->second; } private: QuicByteCount bytes_; QuicPacketCount packets_; absl::node_hash_map<std::string, QuicPacketCount> per_destination_packet_counter_; }; class LinkSaturator : public Endpoint { public: LinkSaturator(Simulator* simulator, std::string name, QuicByteCount packet_size, std::string destination) : Endpoint(simulator, name), packet_size_(packet_size), destination_(std::move(destination)), bytes_transmitted_(0), packets_transmitted_(0) { Schedule(clock_->Now()); } void Act() override { if (tx_port_->TimeUntilAvailable().IsZero()) { auto packet = std::make_unique<Packet>(); packet->source = name_; packet->destination = destination_; packet->tx_timestamp = clock_->Now(); packet->size = packet_size_; tx_port_->AcceptPacket(std::move(packet)); bytes_transmitted_ += packet_size_; packets_transmitted_ += 1; } Schedule(clock_->Now() + tx_port_->TimeUntilAvailable()); } UnconstrainedPortInterface* GetRxPort() override { return static_cast<UnconstrainedPortInterface*>(&rx_port_); } void SetTxPort(ConstrainedPortInterface* port) override { tx_port_ = port; } CounterPort* counter() { return &rx_port_; } inline QuicByteCount bytes_transmitted() const { return bytes_transmitted_; } inline QuicPacketCount packets_transmitted() const { return packets_transmitted_; } void Pause() { Unschedule(); } void Resume() { Schedule(clock_->Now()); } private: QuicByteCount packet_size_; std::string destination_; ConstrainedPortInterface* tx_port_; CounterPort rx_port_; QuicByteCount bytes_transmitted_; QuicPacketCount packets_transmitted_; }; TEST_F(SimulatorTest, DirectLinkSaturation) { Simulator simulator; LinkSaturator saturator_a(&simulator, "Saturator A", 1000, "Saturator B"); LinkSaturator saturator_b(&simulator, "Saturator B", 100, "Saturator A"); SymmetricLink link(&saturator_a, &saturator_b, QuicBandwidth::FromKBytesPerSecond(1000), QuicTime::Delta::FromMilliseconds(100) + QuicTime::Delta::FromMicroseconds(1)); const QuicTime start_time = simulator.GetClock()->Now(); const QuicTime after_first_50_ms = start_time + QuicTime::Delta::FromMilliseconds(50); simulator.RunUntil([&simulator, after_first_50_ms]() { return simulator.GetClock()->Now() >= after_first_50_ms; }); EXPECT_LE(1000u * 50u, saturator_a.bytes_transmitted()); EXPECT_GE(1000u * 51u, saturator_a.bytes_transmitted()); EXPECT_LE(1000u * 50u, saturator_b.bytes_transmitted()); EXPECT_GE(1000u * 51u, saturator_b.bytes_transmitted()); EXPECT_LE(50u, saturator_a.packets_transmitted()); EXPECT_GE(51u, saturator_a.packets_transmitted()); EXPECT_LE(500u, saturator_b.packets_transmitted()); EXPECT_GE(501u, saturator_b.packets_transmitted()); EXPECT_EQ(0u, saturator_a.counter()->bytes()); EXPECT_EQ(0u, saturator_b.counter()->bytes()); simulator.RunUntil([&saturator_a, &saturator_b]() { if (saturator_a.counter()->packets() > 1000 || saturator_b.counter()->packets() > 100) { ADD_FAILURE() << "The simulation did not arrive at the expected " "termination contidition. Saturator A counter: " << saturator_a.counter()->packets() << ", saturator B counter: " << saturator_b.counter()->packets(); return true; } return saturator_a.counter()->packets() == 1000 && saturator_b.counter()->packets() == 100; }); EXPECT_EQ(201u, saturator_a.packets_transmitted()); EXPECT_EQ(2001u, saturator_b.packets_transmitted()); EXPECT_EQ(201u * 1000, saturator_a.bytes_transmitted()); EXPECT_EQ(2001u * 100, saturator_b.bytes_transmitted()); EXPECT_EQ(1000u, saturator_a.counter()->CountPacketsForDestination("Saturator A")); EXPECT_EQ(100u, saturator_b.counter()->CountPacketsForDestination("Saturator B")); EXPECT_EQ(0u, saturator_a.counter()->CountPacketsForDestination("Saturator B")); EXPECT_EQ(0u, saturator_b.counter()->CountPacketsForDestination("Saturator A")); const QuicTime end_time = simulator.GetClock()->Now(); const QuicBandwidth observed_bandwidth = QuicBandwidth::FromBytesAndTimeDelta( saturator_a.bytes_transmitted(), end_time - start_time); EXPECT_APPROX_EQ(link.bandwidth(), observed_bandwidth, 0.01f); } class PacketAcceptor : public ConstrainedPortInterface { public: void AcceptPacket(std::unique_ptr<Packet> packet) override { packets_.emplace_back(std::move(packet)); } QuicTime::Delta TimeUntilAvailable() override { return QuicTime::Delta::Zero(); } std::vector<std::unique_ptr<Packet>>* packets() { return &packets_; } private: std::vector<std::unique_ptr<Packet>> packets_; }; TEST_F(SimulatorTest, Queue) { Simulator simulator; Queue queue(&simulator, "Queue", 1000); PacketAcceptor acceptor; queue.set_tx_port(&acceptor); EXPECT_EQ(0u, queue.bytes_queued()); EXPECT_EQ(0u, queue.packets_queued()); EXPECT_EQ(0u, acceptor.packets()->size()); auto first_packet = std::make_unique<Packet>(); first_packet->size = 600; queue.AcceptPacket(std::move(first_packet)); EXPECT_EQ(600u, queue.bytes_queued()); EXPECT_EQ(1u, queue.packets_queued()); EXPECT_EQ(0u, acceptor.packets()->size()); auto second_packet = std::make_unique<Packet>(); second_packet->size = 500; queue.AcceptPacket(std::move(second_packet)); EXPECT_EQ(600u, queue.bytes_queued()); EXPECT_EQ(1u, queue.packets_queued()); EXPECT_EQ(0u, acceptor.packets()->size()); auto third_packet = std::make_unique<Packet>(); third_packet->size = 400; queue.AcceptPacket(std::move(third_packet)); EXPECT_EQ(1000u, queue.bytes_queued()); EXPECT_EQ(2u, queue.packets_queued()); EXPECT_EQ(0u, acceptor.packets()->size()); simulator.RunUntil([]() { return false; }); EXPECT_EQ(0u, queue.bytes_queued()); EXPECT_EQ(0u, queue.packets_queued()); ASSERT_EQ(2u, acceptor.packets()->size()); EXPECT_EQ(600u, acceptor.packets()->at(0)->size); EXPECT_EQ(400u, acceptor.packets()->at(1)->size); } TEST_F(SimulatorTest, QueueBottleneck) { const QuicBandwidth local_bandwidth = QuicBandwidth::FromKBytesPerSecond(1000); const QuicBandwidth bottleneck_bandwidth = 0.1f * local_bandwidth; const QuicTime::Delta local_propagation_delay = QuicTime::Delta::FromMilliseconds(1); const QuicTime::Delta bottleneck_propagation_delay = QuicTime::Delta::FromMilliseconds(20); const QuicByteCount bdp = bottleneck_bandwidth * (local_propagation_delay + bottleneck_propagation_delay); Simulator simulator; LinkSaturator saturator(&simulator, "Saturator", 1000, "Counter"); ASSERT_GE(bdp, 1000u); Queue queue(&simulator, "Queue", bdp); CounterPort counter; OneWayLink local_link(&simulator, "Local link", &queue, local_bandwidth, local_propagation_delay); OneWayLink bottleneck_link(&simulator, "Bottleneck link", &counter, bottleneck_bandwidth, bottleneck_propagation_delay); saturator.SetTxPort(&local_link); queue.set_tx_port(&bottleneck_link); static const QuicPacketCount packets_received = 1000; simulator.RunUntil( [&counter]() { return counter.packets() == packets_received; }); const double loss_ratio = 1 - static_cast<double>(packets_received) / saturator.packets_transmitted(); EXPECT_NEAR(loss_ratio, 0.9, 0.001); } TEST_F(SimulatorTest, OnePacketQueue) { const QuicBandwidth local_bandwidth = QuicBandwidth::FromKBytesPerSecond(1000); const QuicBandwidth bottleneck_bandwidth = 0.1f * local_bandwidth; const QuicTime::Delta local_propagation_delay = QuicTime::Delta::FromMilliseconds(1); const QuicTime::Delta bottleneck_propagation_delay = QuicTime::Delta::FromMilliseconds(20); Simulator simulator; LinkSaturator saturator(&simulator, "Saturator", 1000, "Counter"); Queue queue(&simulator, "Queue", 1000); CounterPort counter; OneWayLink local_link(&simulator, "Local link", &queue, local_bandwidth, local_propagation_delay); OneWayLink bottleneck_link(&simulator, "Bottleneck link", &counter, bottleneck_bandwidth, bottleneck_propagation_delay); saturator.SetTxPort(&local_link); queue.set_tx_port(&bottleneck_link); static const QuicPacketCount packets_received = 10; const QuicTime deadline = simulator.GetClock()->Now() + QuicTime::Delta::FromSeconds(10); simulator.RunUntil([&simulator, &counter, deadline]() { return counter.packets() == packets_received || simulator.GetClock()->Now() > deadline; }); ASSERT_EQ(packets_received, counter.packets()); } TEST_F(SimulatorTest, SwitchedNetwork) { const QuicBandwidth bandwidth = QuicBandwidth::FromBytesPerSecond(10000); const QuicTime::Delta base_propagation_delay = QuicTime::Delta::FromMilliseconds(50); Simulator simulator; LinkSaturator saturator1(&simulator, "Saturator 1", 1000, "Saturator 2"); LinkSaturator saturator2(&simulator, "Saturator 2", 1000, "Saturator 3"); LinkSaturator saturator3(&simulator, "Saturator 3", 1000, "Saturator 1"); Switch network_switch(&simulator, "Switch", 8, bandwidth * base_propagation_delay * 10); SymmetricLink link1(&saturator1, network_switch.port(1), bandwidth, base_propagation_delay); SymmetricLink link2(&saturator2, network_switch.port(2), bandwidth, base_propagation_delay * 2); SymmetricLink link3(&saturator3, network_switch.port(3), bandwidth, base_propagation_delay * 3); const QuicTime start_time = simulator.GetClock()->Now(); static const QuicPacketCount bytes_received = 64 * 1000; simulator.RunUntil([&saturator1]() { return saturator1.counter()->bytes() >= bytes_received; }); const QuicTime end_time = simulator.GetClock()->Now(); const QuicBandwidth observed_bandwidth = QuicBandwidth::FromBytesAndTimeDelta( bytes_received, end_time - start_time); const double bandwidth_ratio = static_cast<double>(observed_bandwidth.ToBitsPerSecond()) / bandwidth.ToBitsPerSecond(); EXPECT_NEAR(1, bandwidth_ratio, 0.1); const double normalized_received_packets_for_saturator_2 = static_cast<double>(saturator2.counter()->packets()) / saturator1.counter()->packets(); const double normalized_received_packets_for_saturator_3 = static_cast<double>(saturator3.counter()->packets()) / saturator1.counter()->packets(); EXPECT_NEAR(1, normalized_received_packets_for_saturator_2, 0.1); EXPECT_NEAR(1, normalized_received_packets_for_saturator_3, 0.1); EXPECT_EQ(0u, saturator2.counter()->CountPacketsForDestination("Saturator 1")); EXPECT_EQ(0u, saturator3.counter()->CountPacketsForDestination("Saturator 1")); EXPECT_EQ(1u, saturator1.counter()->CountPacketsForDestination("Saturator 2")); EXPECT_EQ(1u, saturator3.counter()->CountPacketsForDestination("Saturator 2")); EXPECT_EQ(1u, saturator1.counter()->CountPacketsForDestination("Saturator 3")); EXPECT_EQ(1u, saturator2.counter()->CountPacketsForDestination("Saturator 3")); } class AlarmToggler : public Actor { public: AlarmToggler(Simulator* simulator, std::string name, QuicAlarm* alarm, QuicTime::Delta interval) : Actor(simulator, name), alarm_(alarm), interval_(interval), deadline_(alarm->deadline()), times_set_(0), times_cancelled_(0) { EXPECT_TRUE(alarm->IsSet()); EXPECT_GE(alarm->deadline(), clock_->Now()); Schedule(clock_->Now()); } void Act() override { if (deadline_ <= clock_->Now()) { return; } if (alarm_->IsSet()) { alarm_->Cancel(); times_cancelled_++; } else { alarm_->Set(deadline_); times_set_++; } Schedule(clock_->Now() + interval_); } inline int times_set() { return times_set_; } inline int times_cancelled() { return times_cancelled_; } private: QuicAlarm* alarm_; QuicTime::Delta interval_; QuicTime deadline_; int times_set_; int times_cancelled_; }; class CounterDelegate : public QuicAlarm::DelegateWithoutContext { public: explicit CounterDelegate(size_t* counter) : counter_(counter) {} void OnAlarm() override { *counter_ += 1; } private: size_t* counter_; }; TEST_F(SimulatorTest, Alarms) { Simulator simulator; QuicAlarmFactory* alarm_factory = simulator.GetAlarmFactory(); size_t fast_alarm_counter = 0; size_t slow_alarm_counter = 0; std::unique_ptr<QuicAlarm> alarm_fast( alarm_factory->CreateAlarm(new CounterDelegate(&fast_alarm_counter))); std::unique_ptr<QuicAlarm> alarm_slow( alarm_factory->CreateAlarm(new CounterDelegate(&slow_alarm_counter))); const QuicTime start_time = simulator.GetClock()->Now(); alarm_fast->Set(start_time + QuicTime::Delta::FromMilliseconds(100)); alarm_slow->Set(start_time + QuicTime::Delta::FromMilliseconds(750)); AlarmToggler toggler(&simulator, "Toggler", alarm_slow.get(), QuicTime::Delta::FromMilliseconds(100)); const QuicTime end_time = start_time + QuicTime::Delta::FromMilliseconds(1000); EXPECT_FALSE(simulator.RunUntil([&simulator, end_time]() { return simulator.GetClock()->Now() >= end_time; })); EXPECT_EQ(1u, slow_alarm_counter); EXPECT_EQ(1u, fast_alarm_counter); EXPECT_EQ(4, toggler.times_set()); EXPECT_EQ(4, toggler.times_cancelled()); } TEST_F(SimulatorTest, AlarmCancelling) { Simulator simulator; QuicAlarmFactory* alarm_factory = simulator.GetAlarmFactory(); size_t alarm_counter = 0; std::unique_ptr<QuicAlarm> alarm( alarm_factory->CreateAlarm(new CounterDelegate(&alarm_counter))); const QuicTime start_time = simulator.GetClock()->Now(); const QuicTime alarm_at = start_time + QuicTime::Delta::FromMilliseconds(300); const QuicTime end_time = start_time + QuicTime::Delta::FromMilliseconds(400); alarm->Set(alarm_at); alarm->Cancel(); EXPECT_FALSE(alarm->IsSet()); EXPECT_FALSE(simulator.RunUntil([&simulator, end_time]() { return simulator.GetClock()->Now() >= end_time; })); EXPECT_FALSE(alarm->IsSet()); EXPECT_EQ(0u, alarm_counter); } TEST_F(SimulatorTest, AlarmInPast) { Simulator simulator; QuicAlarmFactory* alarm_factory = simulator.GetAlarmFactory(); size_t alarm_counter = 0; std::unique_ptr<QuicAlarm> alarm( alarm_factory->CreateAlarm(new CounterDelegate(&alarm_counter))); const QuicTime start_time = simulator.GetClock()->Now(); simulator.RunFor(QuicTime::Delta::FromMilliseconds(400)); alarm->Set(start_time); simulator.RunFor(QuicTime::Delta::FromMilliseconds(1)); EXPECT_FALSE(alarm->IsSet()); EXPECT_EQ(1u, alarm_counter); } TEST_F(SimulatorTest, RunUntilOrTimeout) { Simulator simulator; bool simulation_result; Counter counter(&simulator, "counter", QuicTime::Delta::FromSeconds(1)); simulation_result = simulator.RunUntilOrTimeout( [&counter]() { return counter.get_value() == 10; }, QuicTime::Delta::FromSeconds(20)); ASSERT_TRUE(simulation_result); simulation_result = simulator.RunUntilOrTimeout( [&counter]() { return counter.get_value() == 100; }, QuicTime::Delta::FromSeconds(20)); ASSERT_FALSE(simulation_result); } TEST_F(SimulatorTest, RunFor) { Simulator simulator; Counter counter(&simulator, "counter", QuicTime::Delta::FromSeconds(3)); simulator.RunFor(QuicTime::Delta::FromSeconds(100)); EXPECT_EQ(33, counter.get_value()); } class MockPacketFilter : public PacketFilter { public: MockPacketFilter(Simulator* simulator, std::string name, Endpoint* endpoint) : PacketFilter(simulator, name, endpoint) {} MOCK_METHOD(bool, FilterPacket, (const Packet&), (override)); }; TEST_F(SimulatorTest, PacketFilter) { const QuicBandwidth bandwidth = QuicBandwidth::FromBytesPerSecond(1024 * 1024); const QuicTime::Delta base_propagation_delay = QuicTime::Delta::FromMilliseconds(5); Simulator simulator; LinkSaturator saturator_a(&simulator, "Saturator A", 1000, "Saturator B"); LinkSaturator saturator_b(&simulator, "Saturator B", 1000, "Saturator A"); Switch network_switch(&simulator, "Switch", 8, bandwidth * base_propagation_delay * 10); StrictMock<MockPacketFilter> a_to_b_filter(&simulator, "A -> B filter", network_switch.port(1)); StrictMock<MockPacketFilter> b_to_a_filter(&simulator, "B -> A filter", network_switch.port(2)); SymmetricLink link_a(&a_to_b_filter, &saturator_b, bandwidth, base_propagation_delay); SymmetricLink link_b(&b_to_a_filter, &saturator_a, bandwidth, base_propagation_delay); EXPECT_CALL(a_to_b_filter, FilterPacket(_)).WillRepeatedly(Return(true)); EXPECT_CALL(b_to_a_filter, FilterPacket(_)).WillRepeatedly(Return(false)); simulator.RunFor(QuicTime::Delta::FromSeconds(10)); EXPECT_GE(saturator_b.counter()->packets(), 1u); EXPECT_EQ(saturator_a.counter()->packets(), 0u); } TEST_F(SimulatorTest, TrafficPolicer) { const QuicBandwidth bandwidth = QuicBandwidth::FromBytesPerSecond(1024 * 1024); const QuicTime::Delta base_propagation_delay = QuicTime::Delta::FromMilliseconds(5); const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(10); Simulator simulator; LinkSaturator saturator1(&simulator, "Saturator 1", 1000, "Saturator 2"); LinkSaturator saturator2(&simulator, "Saturator 2", 1000, "Saturator 1"); Switch network_switch(&simulator, "Switch", 8, bandwidth * base_propagation_delay * 10); static const QuicByteCount initial_burst = 1000 * 10; static const QuicByteCount max_bucket_size = 1000 * 100; static const QuicBandwidth target_bandwidth = bandwidth * 0.25; TrafficPolicer policer(&simulator, "Policer", initial_burst, max_bucket_size, target_bandwidth, network_switch.port(2)); SymmetricLink link1(&saturator1, network_switch.port(1), bandwidth, base_propagation_delay); SymmetricLink link2(&saturator2, &policer, bandwidth, base_propagation_delay); bool simulator_result = simulator.RunUntilOrTimeout( [&saturator1]() { return saturator1.bytes_transmitted() == initial_burst; }, timeout); ASSERT_TRUE(simulator_result); saturator1.Pause(); simulator_result = simulator.RunUntilOrTimeout( [&saturator2]() { return saturator2.counter()->bytes() == initial_burst; }, timeout); ASSERT_TRUE(simulator_result); saturator1.Resume(); const QuicTime::Delta simulation_time = QuicTime::Delta::FromSeconds(10); simulator.RunFor(simulation_time); for (auto* saturator : {&saturator1, &saturator2}) { EXPECT_APPROX_EQ(bandwidth * simulation_time, saturator->bytes_transmitted(), 0.01f); } EXPECT_APPROX_EQ(saturator1.bytes_transmitted() / 4, saturator2.counter()->bytes(), 0.1f); EXPECT_APPROX_EQ(saturator2.bytes_transmitted(), saturator1.counter()->bytes(), 0.1f); } TEST_F(SimulatorTest, TrafficPolicerBurst) { const QuicBandwidth bandwidth = QuicBandwidth::FromBytesPerSecond(1024 * 1024); const QuicTime::Delta base_propagation_delay = QuicTime::Delta::FromMilliseconds(5); const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(10); Simulator simulator; LinkSaturator saturator1(&simulator, "Saturator 1", 1000, "Saturator 2"); LinkSaturator saturator2(&simulator, "Saturator 2", 1000, "Saturator 1"); Switch network_switch(&simulator, "Switch", 8, bandwidth * base_propagation_delay * 10); const QuicByteCount initial_burst = 1000 * 10; const QuicByteCount max_bucket_size = 1000 * 100; const QuicBandwidth target_bandwidth = bandwidth * 0.25; TrafficPolicer policer(&simulator, "Policer", initial_burst, max_bucket_size, target_bandwidth, network_switch.port(2)); SymmetricLink link1(&saturator1, network_switch.port(1), bandwidth, base_propagation_delay); SymmetricLink link2(&saturator2, &policer, bandwidth, base_propagation_delay); bool simulator_result = simulator.RunUntilOrTimeout( [&saturator1, &saturator2]() { return saturator1.packets_transmitted() > 0 && saturator2.packets_transmitted() > 0; }, timeout); ASSERT_TRUE(simulator_result); saturator1.Pause(); saturator2.Pause(); simulator.RunFor(1.5f * target_bandwidth.TransferTime(max_bucket_size)); saturator1.Resume(); simulator.RunFor(bandwidth.TransferTime(max_bucket_size)); saturator1.Pause(); simulator.RunFor(2 * base_propagation_delay); EXPECT_APPROX_EQ(saturator1.bytes_transmitted(), saturator2.counter()->bytes(), 0.1f); saturator1.Resume(); simulator.RunFor(QuicTime::Delta::FromSeconds(10)); EXPECT_APPROX_EQ(saturator1.bytes_transmitted() / 4, saturator2.counter()->bytes(), 0.1f); } TEST_F(SimulatorTest, PacketAggregation) { const QuicBandwidth bandwidth = QuicBandwidth::FromBytesPerSecond(1000); const QuicTime::Delta base_propagation_delay = QuicTime::Delta::FromMicroseconds(1); const QuicByteCount aggregation_threshold = 1000; const QuicTime::Delta aggregation_timeout = QuicTime::Delta::FromSeconds(30); Simulator simulator; LinkSaturator saturator1(&simulator, "Saturator 1", 10, "Saturator 2"); LinkSaturator saturator2(&simulator, "Saturator 2", 10, "Saturator 1"); Switch network_switch(&simulator, "Switch", 8, 10 * aggregation_threshold); SymmetricLink link1(&saturator1, network_switch.port(1), bandwidth, base_propagation_delay); SymmetricLink link2(&saturator2, network_switch.port(2), bandwidth, 2 * base_propagation_delay); Queue* queue = network_switch.port_queue(2); queue->EnableAggregation(aggregation_threshold, aggregation_timeout); network_switch.port_queue(1)->EnableAggregation(5, aggregation_timeout); simulator.RunFor(0.9 * bandwidth.TransferTime(aggregation_threshold)); EXPECT_EQ(0u, saturator2.counter()->bytes()); saturator1.Pause(); saturator2.Pause(); simulator.RunFor(QuicTime::Delta::FromSeconds(10)); EXPECT_EQ(0u, saturator2.counter()->bytes()); EXPECT_EQ(900u, queue->bytes_queued()); EXPECT_EQ(910u, saturator1.counter()->bytes()); saturator1.Resume(); simulator.RunFor(0.5 * bandwidth.TransferTime(aggregation_threshold)); saturator1.Pause(); simulator.RunFor(QuicTime::Delta::FromSeconds(10)); EXPECT_EQ(1000u, saturator2.counter()->bytes()); EXPECT_EQ(400u, queue->bytes_queued()); simulator.RunFor(aggregation_timeout); EXPECT_EQ(1400u, saturator2.counter()->bytes()); EXPECT_EQ(0u, queue->bytes_queued()); saturator1.Resume(); simulator.RunFor(5.5 * bandwidth.TransferTime(aggregation_threshold)); saturator1.Pause(); simulator.RunFor(QuicTime::Delta::FromSeconds(10)); EXPECT_EQ(6400u, saturator2.counter()->bytes()); EXPECT_EQ(500u, queue->bytes_queued()); simulator.RunFor(aggregation_timeout); EXPECT_EQ(6900u, saturator2.counter()->bytes()); EXPECT_EQ(0u, queue->bytes_queued()); } } }
379
cpp
google/quiche
quic_endpoint
quiche/quic/test_tools/simulator/quic_endpoint.cc
quiche/quic/test_tools/simulator/quic_endpoint_test.cc
#ifndef QUICHE_QUIC_TEST_TOOLS_SIMULATOR_QUIC_ENDPOINT_H_ #define QUICHE_QUIC_TEST_TOOLS_SIMULATOR_QUIC_ENDPOINT_H_ #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/null_decrypter.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_packet_writer.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_stream_frame_data_producer.h" #include "quiche/quic/core/quic_trace_visitor.h" #include "quiche/quic/test_tools/simple_session_notifier.h" #include "quiche/quic/test_tools/simulator/link.h" #include "quiche/quic/test_tools/simulator/queue.h" #include "quiche/quic/test_tools/simulator/quic_endpoint_base.h" namespace quic { namespace simulator { class QuicEndpoint : public QuicEndpointBase, public QuicConnectionVisitorInterface, public SessionNotifierInterface { public: QuicEndpoint(Simulator* simulator, std::string name, std::string peer_name, Perspective perspective, QuicConnectionId connection_id); QuicByteCount bytes_to_transfer() const; QuicByteCount bytes_transferred() const; QuicByteCount bytes_received() const; bool wrong_data_received() const { return wrong_data_received_; } void AddBytesToTransfer(QuicByteCount bytes); void OnStreamFrame(const QuicStreamFrame& frame) override; void OnCryptoFrame(const QuicCryptoFrame& frame) override; void OnCanWrite() override; bool WillingAndAbleToWrite() const override; bool ShouldKeepConnectionAlive() const override; std::string GetStreamsInfoForLogging() const override { return ""; } void OnWindowUpdateFrame(const QuicWindowUpdateFrame& ) override {} void OnBlockedFrame(const QuicBlockedFrame& ) override {} void OnRstStream(const QuicRstStreamFrame& ) override {} void OnGoAway(const QuicGoAwayFrame& ) override {} void OnMessageReceived(absl::string_view ) override {} void OnHandshakeDoneReceived() override {} void OnNewTokenReceived(absl::string_view ) override {} void OnConnectionClosed(const QuicConnectionCloseFrame& , ConnectionCloseSource ) override {} void OnWriteBlocked() override {} void OnSuccessfulVersionNegotiation( const ParsedQuicVersion& ) override {} void OnPacketReceived(const QuicSocketAddress& , const QuicSocketAddress& , bool ) override {} void OnCongestionWindowChange(QuicTime ) override {} void OnConnectionMigration(AddressChangeType ) override {} void OnPathDegrading() override {} void OnForwardProgressMadeAfterPathDegrading() override {} void OnAckNeedsRetransmittableFrame() override {} void SendAckFrequency(const QuicAckFrequencyFrame& ) override {} void SendNewConnectionId(const QuicNewConnectionIdFrame& ) override { } void SendRetireConnectionId(uint64_t ) override {} bool MaybeReserveConnectionId( const QuicConnectionId& ) override { return true; } void OnServerConnectionIdRetired( const QuicConnectionId& ) override {} bool AllowSelfAddressChange() const override; HandshakeState GetHandshakeState() const override; bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& ) override { return true; } bool OnStreamsBlockedFrame( const QuicStreamsBlockedFrame& ) override { return true; } void OnStopSendingFrame(const QuicStopSendingFrame& ) override {} void OnPacketDecrypted(EncryptionLevel ) override {} void OnOneRttPacketAcknowledged() override {} void OnHandshakePacketSent() override {} void OnKeyUpdate(KeyUpdateReason ) override {} std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter() override { return nullptr; } std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override { return nullptr; } void BeforeConnectionCloseSent() override {} bool ValidateToken(absl::string_view ) override { return true; } bool MaybeSendAddressToken() override { return false; } void CreateContextForMultiPortPath( std::unique_ptr<MultiPortPathContextObserver> ) override {} void MigrateToMultiPortPath( std::unique_ptr<QuicPathValidationContext> ) override {} void OnServerPreferredAddressAvailable( const QuicSocketAddress& ) override {} void MaybeBundleOpportunistically() override {} QuicByteCount GetFlowControlSendWindowSize(QuicStreamId ) override { return std::numeric_limits<QuicByteCount>::max(); } bool OnFrameAcked(const QuicFrame& frame, QuicTime::Delta ack_delay_time, QuicTime receive_timestamp) override; void OnStreamFrameRetransmitted(const QuicStreamFrame& ) override {} void OnFrameLost(const QuicFrame& frame) override; bool RetransmitFrames(const QuicFrames& frames, TransmissionType type) override; bool IsFrameOutstanding(const QuicFrame& frame) const override; bool HasUnackedCryptoData() const override; bool HasUnackedStreamData() const override; private: class DataProducer : public QuicStreamFrameDataProducer { public: WriteStreamDataResult WriteStreamData(QuicStreamId id, QuicStreamOffset offset, QuicByteCount data_length, QuicDataWriter* writer) override; bool WriteCryptoData(EncryptionLevel level, QuicStreamOffset offset, QuicByteCount data_length, QuicDataWriter* writer) override; }; std::unique_ptr<QuicConnection> CreateConnection( Simulator* simulator, std::string name, std::string peer_name, Perspective perspective, QuicConnectionId connection_id); void WriteStreamData(); DataProducer producer_; QuicByteCount bytes_to_transfer_; QuicByteCount bytes_transferred_; bool wrong_data_received_; QuicIntervalSet<QuicStreamOffset> offsets_received_; std::unique_ptr<test::SimpleSessionNotifier> notifier_; }; } } #endif #include "quiche/quic/test_tools/simulator/quic_endpoint.h" #include <algorithm> #include <memory> #include <string> #include <utility> #include "quiche/quic/core/crypto/crypto_handshake_message.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/platform/api/quic_test_output.h" #include "quiche/quic/test_tools/quic_config_peer.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simulator/simulator.h" namespace quic { namespace simulator { const QuicStreamId kDataStream = 3; const QuicByteCount kWriteChunkSize = 128 * 1024; const char kStreamDataContents = 'Q'; QuicEndpoint::QuicEndpoint(Simulator* simulator, std::string name, std::string peer_name, Perspective perspective, QuicConnectionId connection_id) : QuicEndpointBase(simulator, name, peer_name), bytes_to_transfer_(0), bytes_transferred_(0), wrong_data_received_(false), notifier_(nullptr) { connection_ = std::make_unique<QuicConnection>( connection_id, GetAddressFromName(name), GetAddressFromName(peer_name), simulator, simulator->GetAlarmFactory(), &writer_, false, perspective, ParsedVersionOfIndex(CurrentSupportedVersions(), 0), connection_id_generator_); connection_->set_visitor(this); connection_->SetEncrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<quic::test::TaggingEncrypter>( ENCRYPTION_FORWARD_SECURE)); connection_->SetEncrypter(ENCRYPTION_INITIAL, nullptr); if (connection_->version().KnowsWhichDecrypterToUse()) { connection_->InstallDecrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<quic::test::StrictTaggingDecrypter>( ENCRYPTION_FORWARD_SECURE)); connection_->RemoveDecrypter(ENCRYPTION_INITIAL); } else { connection_->SetDecrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<quic::test::StrictTaggingDecrypter>( ENCRYPTION_FORWARD_SECURE)); } connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_->OnHandshakeComplete(); if (perspective == Perspective::IS_SERVER) { test::QuicConnectionPeer::SetNegotiatedVersion(connection_.get()); } test::QuicConnectionPeer::SetAddressValidated(connection_.get()); connection_->SetDataProducer(&producer_); connection_->SetSessionNotifier(this); notifier_ = std::make_unique<test::SimpleSessionNotifier>(connection_.get()); std::string error; CryptoHandshakeMessage peer_hello; peer_hello.SetValue(kICSL, static_cast<uint32_t>(kMaximumIdleTimeoutSecs - 1)); peer_hello.SetValue(kMIBS, static_cast<uint32_t>(kDefaultMaxStreamsPerConnection)); QuicConfig config; QuicErrorCode error_code = config.ProcessPeerHello( peer_hello, perspective == Perspective::IS_CLIENT ? SERVER : CLIENT, &error); QUICHE_DCHECK_EQ(error_code, QUIC_NO_ERROR) << "Configuration failed: " << error; if (connection_->version().UsesTls()) { if (connection_->perspective() == Perspective::IS_CLIENT) { test::QuicConfigPeer::SetReceivedOriginalConnectionId( &config, connection_->connection_id()); test::QuicConfigPeer::SetReceivedInitialSourceConnectionId( &config, connection_->connection_id()); } else { test::QuicConfigPeer::SetReceivedInitialSourceConnectionId( &config, connection_->client_connection_id()); } } connection_->SetFromConfig(config); connection_->DisableMtuDiscovery(); } QuicByteCount QuicEndpoint::bytes_received() const { QuicByteCount total = 0; for (auto& interval : offsets_received_) { total += interval.max() - interval.min(); } return total; } QuicByteCount QuicEndpoint::bytes_to_transfer() const { if (notifier_ != nullptr) { return notifier_->StreamBytesToSend(); } return bytes_to_transfer_; } QuicByteCount QuicEndpoint::bytes_transferred() const { if (notifier_ != nullptr) { return notifier_->StreamBytesSent(); } return bytes_transferred_; } void QuicEndpoint::AddBytesToTransfer(QuicByteCount bytes) { if (notifier_ != nullptr) { if (notifier_->HasBufferedStreamData()) { Schedule(clock_->Now()); } notifier_->WriteOrBufferData(kDataStream, bytes, NO_FIN); return; } if (bytes_to_transfer_ > 0) { Schedule(clock_->Now()); } bytes_to_transfer_ += bytes; WriteStreamData(); } void QuicEndpoint::OnStreamFrame(const QuicStreamFrame& frame) { QUICHE_DCHECK(frame.stream_id == kDataStream); for (size_t i = 0; i < frame.data_length; i++) { if (frame.data_buffer[i] != kStreamDataContents) { wrong_data_received_ = true; } } offsets_received_.Add(frame.offset, frame.offset + frame.data_length); QUICHE_DCHECK_LE(offsets_received_.Size(), 1000u); } void QuicEndpoint::OnCryptoFrame(const QuicCryptoFrame& ) {} void QuicEndpoint::OnCanWrite() { if (notifier_ != nullptr) { notifier_->OnCanWrite(); return; } WriteStreamData(); } bool QuicEndpoint::WillingAndAbleToWrite() const { if (notifier_ != nullptr) { return notifier_->WillingToWrite(); } return bytes_to_transfer_ != 0; } bool QuicEndpoint::ShouldKeepConnectionAlive() const { return true; } bool QuicEndpoint::AllowSelfAddressChange() const { return false; } bool QuicEndpoint::OnFrameAcked(const QuicFrame& frame, QuicTime::Delta ack_delay_time, QuicTime receive_timestamp) { if (notifier_ != nullptr) { return notifier_->OnFrameAcked(frame, ack_delay_time, receive_timestamp); } return false; } void QuicEndpoint::OnFrameLost(const QuicFrame& frame) { QUICHE_DCHECK(notifier_); notifier_->OnFrameLost(frame); } bool QuicEndpoint::RetransmitFrames(const QuicFrames& frames, TransmissionType type) { QUICHE_DCHECK(notifier_); return notifier_->RetransmitFrames(frames, type); } bool QuicEndpoint::IsFrameOutstanding(const QuicFrame& frame) const { QUICHE_DCHECK(notifier_); return notifier_->IsFrameOutstanding(frame); } bool QuicEndpoint::HasUnackedCryptoData() const { return false; } bool QuicEndpoint::HasUnackedStreamData() const { if (notifier_ != nullptr) { return notifier_->HasUnackedStreamData(); } return false; } HandshakeState QuicEndpoint::GetHandshakeState() const { return HANDSHAKE_COMPLETE; } WriteStreamDataResult QuicEndpoint::DataProducer::WriteStreamData( QuicStreamId , QuicStreamOffset , QuicByteCount data_length, QuicDataWriter* writer) { writer->WriteRepeatedByte(kStreamDataContents, data_length); return WRITE_SUCCESS; } bool QuicEndpoint::DataProducer::WriteCryptoData(EncryptionLevel , QuicStreamOffset , QuicByteCount , QuicDataWriter* ) { QUIC_BUG(quic_bug_10157_1) << "QuicEndpoint::DataProducer::WriteCryptoData is unimplemented"; return false; } void QuicEndpoint::WriteStreamData() { QuicConnection::ScopedPacketFlusher flusher(connection_.get()); while (bytes_to_transfer_ > 0) { const size_t transmission_size = std::min(kWriteChunkSize, bytes_to_transfer_); QuicConsumedData consumed_data = connection_->SendStreamData( kDataStream, transmission_size, bytes_transferred_, NO_FIN); QUICHE_DCHECK(consumed_data.bytes_consumed <= transmission_size); bytes_transferred_ += consumed_data.bytes_consumed; bytes_to_transfer_ -= consumed_data.bytes_consumed; if (consumed_data.bytes_consumed != transmission_size) { return; } } } } }
#include "quiche/quic/test_tools/simulator/quic_endpoint.h" #include <memory> #include <utility> #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simulator/simulator.h" #include "quiche/quic/test_tools/simulator/switch.h" using ::testing::_; using ::testing::NiceMock; using ::testing::Return; namespace quic { namespace simulator { const QuicBandwidth kDefaultBandwidth = QuicBandwidth::FromKBitsPerSecond(10 * 1000); const QuicTime::Delta kDefaultPropagationDelay = QuicTime::Delta::FromMilliseconds(20); const QuicByteCount kDefaultBdp = kDefaultBandwidth * kDefaultPropagationDelay; class QuicEndpointTest : public quic::test::QuicTest { public: QuicEndpointTest() : simulator_(), switch_(&simulator_, "Switch", 8, kDefaultBdp * 2) {} protected: Simulator simulator_; Switch switch_; std::unique_ptr<SymmetricLink> Link(Endpoint* a, Endpoint* b) { return std::make_unique<SymmetricLink>(a, b, kDefaultBandwidth, kDefaultPropagationDelay); } std::unique_ptr<SymmetricLink> CustomLink(Endpoint* a, Endpoint* b, uint64_t extra_rtt_ms) { return std::make_unique<SymmetricLink>( a, b, kDefaultBandwidth, kDefaultPropagationDelay + QuicTime::Delta::FromMilliseconds(extra_rtt_ms)); } }; TEST_F(QuicEndpointTest, OneWayTransmission) { QuicEndpoint endpoint_a(&simulator_, "Endpoint A", "Endpoint B", Perspective::IS_CLIENT, test::TestConnectionId(42)); QuicEndpoint endpoint_b(&simulator_, "Endpoint B", "Endpoint A", Perspective::IS_SERVER, test::TestConnectionId(42)); auto link_a = Link(&endpoint_a, switch_.port(1)); auto link_b = Link(&endpoint_b, switch_.port(2)); endpoint_a.AddBytesToTransfer(600); QuicTime end_time = simulator_.GetClock()->Now() + QuicTime::Delta::FromMilliseconds(1000); simulator_.RunUntil( [this, end_time]() { return simulator_.GetClock()->Now() >= end_time; }); EXPECT_EQ(600u, endpoint_a.bytes_transferred()); ASSERT_EQ(600u, endpoint_b.bytes_received()); EXPECT_FALSE(endpoint_a.wrong_data_received()); EXPECT_FALSE(endpoint_b.wrong_data_received()); endpoint_a.AddBytesToTransfer(2 * 1024 * 1024); end_time = simulator_.GetClock()->Now() + QuicTime::Delta::FromSeconds(5); simulator_.RunUntil( [this, end_time]() { return simulator_.GetClock()->Now() >= end_time; }); const QuicByteCount total_bytes_transferred = 600 + 2 * 1024 * 1024; EXPECT_EQ(total_bytes_transferred, endpoint_a.bytes_transferred()); EXPECT_EQ(total_bytes_transferred, endpoint_b.bytes_received()); EXPECT_EQ(0u, endpoint_a.write_blocked_count()); EXPECT_FALSE(endpoint_a.wrong_data_received()); EXPECT_FALSE(endpoint_b.wrong_data_received()); } TEST_F(QuicEndpointTest, WriteBlocked) { QuicEndpoint endpoint_a(&simulator_, "Endpoint A", "Endpoint B", Perspective::IS_CLIENT, test::TestConnectionId(42)); QuicEndpoint endpoint_b(&simulator_, "Endpoint B", "Endpoint A", Perspective::IS_SERVER, test::TestConnectionId(42)); auto link_a = Link(&endpoint_a, switch_.port(1)); auto link_b = Link(&endpoint_b, switch_.port(2)); auto* sender = new NiceMock<test::MockSendAlgorithm>(); EXPECT_CALL(*sender, CanSend(_)).WillRepeatedly(Return(true)); EXPECT_CALL(*sender, PacingRate(_)) .WillRepeatedly(Return(10 * kDefaultBandwidth)); EXPECT_CALL(*sender, BandwidthEstimate()) .WillRepeatedly(Return(10 * kDefaultBandwidth)); EXPECT_CALL(*sender, GetCongestionWindow()) .WillRepeatedly(Return(kMaxOutgoingPacketSize * GetQuicFlag(quic_max_congestion_window))); test::QuicConnectionPeer::SetSendAlgorithm(endpoint_a.connection(), sender); QuicByteCount bytes_to_transfer = 3 * 1024 * 1024; endpoint_a.AddBytesToTransfer(bytes_to_transfer); QuicTime end_time = simulator_.GetClock()->Now() + QuicTime::Delta::FromSeconds(30); simulator_.RunUntil([this, &endpoint_b, bytes_to_transfer, end_time]() { return endpoint_b.bytes_received() == bytes_to_transfer || simulator_.GetClock()->Now() >= end_time; }); EXPECT_EQ(bytes_to_transfer, endpoint_a.bytes_transferred()); EXPECT_EQ(bytes_to_transfer, endpoint_b.bytes_received()); EXPECT_GT(endpoint_a.write_blocked_count(), 0u); EXPECT_FALSE(endpoint_a.wrong_data_received()); EXPECT_FALSE(endpoint_b.wrong_data_received()); } TEST_F(QuicEndpointTest, TwoWayTransmission) { QuicEndpoint endpoint_a(&simulator_, "Endpoint A", "Endpoint B", Perspective::IS_CLIENT, test::TestConnectionId(42)); QuicEndpoint endpoint_b(&simulator_, "Endpoint B", "Endpoint A", Perspective::IS_SERVER, test::TestConnectionId(42)); auto link_a = Link(&endpoint_a, switch_.port(1)); auto link_b = Link(&endpoint_b, switch_.port(2)); endpoint_a.RecordTrace(); endpoint_b.RecordTrace(); endpoint_a.AddBytesToTransfer(1024 * 1024); endpoint_b.AddBytesToTransfer(1024 * 1024); QuicTime end_time = simulator_.GetClock()->Now() + QuicTime::Delta::FromSeconds(5); simulator_.RunUntil( [this, end_time]() { return simulator_.GetClock()->Now() >= end_time; }); EXPECT_EQ(1024u * 1024u, endpoint_a.bytes_transferred()); EXPECT_EQ(1024u * 1024u, endpoint_b.bytes_transferred()); EXPECT_EQ(1024u * 1024u, endpoint_a.bytes_received()); EXPECT_EQ(1024u * 1024u, endpoint_b.bytes_received()); EXPECT_FALSE(endpoint_a.wrong_data_received()); EXPECT_FALSE(endpoint_b.wrong_data_received()); } TEST_F(QuicEndpointTest, Competition) { auto endpoint_a = std::make_unique<QuicEndpoint>( &simulator_, "Endpoint A", "Endpoint D (A)", Perspective::IS_CLIENT, test::TestConnectionId(42)); auto endpoint_b = std::make_unique<QuicEndpoint>( &simulator_, "Endpoint B", "Endpoint D (B)", Perspective::IS_CLIENT, test::TestConnectionId(43)); auto endpoint_c = std::make_unique<QuicEndpoint>( &simulator_, "Endpoint C", "Endpoint D (C)", Perspective::IS_CLIENT, test::TestConnectionId(44)); auto endpoint_d_a = std::make_unique<QuicEndpoint>( &simulator_, "Endpoint D (A)", "Endpoint A", Perspective::IS_SERVER, test::TestConnectionId(42)); auto endpoint_d_b = std::make_unique<QuicEndpoint>( &simulator_, "Endpoint D (B)", "Endpoint B", Perspective::IS_SERVER, test::TestConnectionId(43)); auto endpoint_d_c = std::make_unique<QuicEndpoint>( &simulator_, "Endpoint D (C)", "Endpoint C", Perspective::IS_SERVER, test::TestConnectionId(44)); QuicEndpointMultiplexer endpoint_d( "Endpoint D", {endpoint_d_a.get(), endpoint_d_b.get(), endpoint_d_c.get()}); auto link_a = CustomLink(endpoint_a.get(), switch_.port(1), 0); auto link_b = CustomLink(endpoint_b.get(), switch_.port(2), 1); auto link_c = CustomLink(endpoint_c.get(), switch_.port(3), 2); auto link_d = Link(&endpoint_d, switch_.port(4)); endpoint_a->AddBytesToTransfer(2 * 1024 * 1024); endpoint_b->AddBytesToTransfer(2 * 1024 * 1024); endpoint_c->AddBytesToTransfer(2 * 1024 * 1024); QuicTime end_time = simulator_.GetClock()->Now() + QuicTime::Delta::FromSeconds(12); simulator_.RunUntil( [this, end_time]() { return simulator_.GetClock()->Now() >= end_time; }); for (QuicEndpoint* endpoint : {endpoint_a.get(), endpoint_b.get(), endpoint_c.get()}) { EXPECT_EQ(2u * 1024u * 1024u, endpoint->bytes_transferred()); EXPECT_GE(endpoint->connection()->GetStats().packets_lost, 0u); } for (QuicEndpoint* endpoint : {endpoint_d_a.get(), endpoint_d_b.get(), endpoint_d_c.get()}) { EXPECT_EQ(2u * 1024u * 1024u, endpoint->bytes_received()); EXPECT_FALSE(endpoint->wrong_data_received()); } } } }
380
cpp
google/quiche
binary_http_message
quiche/binary_http/binary_http_message.cc
quiche/binary_http/binary_http_message_test.cc
#ifndef QUICHE_BINARY_HTTP_BINARY_HTTP_MESSAGE_H_ #define QUICHE_BINARY_HTTP_BINARY_HTTP_MESSAGE_H_ #include <cstddef> #include <cstdint> #include <functional> #include <memory> #include <ostream> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/quiche_data_writer.h" namespace quiche { class QUICHE_EXPORT BinaryHttpMessage { public: struct QUICHE_EXPORT Field { std::string name; std::string value; bool operator==(const BinaryHttpMessage::Field& rhs) const { return name == rhs.name && value == rhs.value; } bool operator!=(const BinaryHttpMessage::Field& rhs) const { return !(*this == rhs); } std::string DebugString() const; }; virtual ~BinaryHttpMessage() = default; BinaryHttpMessage* AddHeaderField(Field header_field); const std::vector<Field>& GetHeaderFields() const { return header_fields_.fields(); } BinaryHttpMessage* set_body(std::string body) { body_ = std::move(body); return this; } void swap_body(std::string& body) { body_.swap(body); } void set_num_padding_bytes(size_t num_padding_bytes) { num_padding_bytes_ = num_padding_bytes; } size_t num_padding_bytes() const { return num_padding_bytes_; } absl::string_view body() const { return body_; } virtual size_t EncodedSize() const = 0; virtual absl::StatusOr<std::string> Serialize() const = 0; virtual std::string DebugString() const; protected: class Fields { public: void AddField(BinaryHttpMessage::Field field); const std::vector<BinaryHttpMessage::Field>& fields() const { return fields_; } bool operator==(const BinaryHttpMessage::Fields& rhs) const { return fields_ == rhs.fields_; } absl::Status Encode(quiche::QuicheDataWriter& writer) const; size_t EncodedSize() const; private: size_t EncodedFieldsSize() const; std::vector<BinaryHttpMessage::Field> fields_; }; bool IsPayloadEqual(const BinaryHttpMessage& rhs) const { return body_ == rhs.body_ && header_fields_ == rhs.header_fields_; } absl::Status EncodeKnownLengthFieldsAndBody( quiche::QuicheDataWriter& writer) const; size_t EncodedKnownLengthFieldsAndBodySize() const; bool has_host() const { return has_host_; } private: std::string body_; Fields header_fields_; bool has_host_ = false; size_t num_padding_bytes_ = 0; }; void QUICHE_EXPORT PrintTo(const BinaryHttpMessage::Field& msg, std::ostream* os); class QUICHE_EXPORT BinaryHttpRequest : public BinaryHttpMessage { public: struct QUICHE_EXPORT ControlData { std::string method; std::string scheme; std::string authority; std::string path; bool operator==(const BinaryHttpRequest::ControlData& rhs) const { return method == rhs.method && scheme == rhs.scheme && authority == rhs.authority && path == rhs.path; } bool operator!=(const BinaryHttpRequest::ControlData& rhs) const { return !(*this == rhs); } }; explicit BinaryHttpRequest(ControlData control_data) : control_data_(std::move(control_data)) {} static absl::StatusOr<BinaryHttpRequest> Create(absl::string_view data); size_t EncodedSize() const override; absl::StatusOr<std::string> Serialize() const override; const ControlData& control_data() const { return control_data_; } virtual std::string DebugString() const override; bool IsPayloadEqual(const BinaryHttpRequest& rhs) const { return control_data_ == rhs.control_data_ && BinaryHttpMessage::IsPayloadEqual(rhs); } bool operator==(const BinaryHttpRequest& rhs) const { return IsPayloadEqual(rhs) && num_padding_bytes() == rhs.num_padding_bytes(); } bool operator!=(const BinaryHttpRequest& rhs) const { return !(*this == rhs); } private: absl::Status EncodeControlData(quiche::QuicheDataWriter& writer) const; size_t EncodedControlDataSize() const; absl::StatusOr<std::string> EncodeAsKnownLength() const; const ControlData control_data_; }; void QUICHE_EXPORT PrintTo(const BinaryHttpRequest& msg, std::ostream* os); class QUICHE_EXPORT BinaryHttpResponse : public BinaryHttpMessage { public: class QUICHE_EXPORT InformationalResponse { public: explicit InformationalResponse(uint16_t status_code) : status_code_(status_code) {} InformationalResponse(uint16_t status_code, const std::vector<BinaryHttpMessage::Field>& fields) : status_code_(status_code) { for (const BinaryHttpMessage::Field& field : fields) { AddField(field.name, field.value); } } bool operator==( const BinaryHttpResponse::InformationalResponse& rhs) const { return status_code_ == rhs.status_code_ && fields_ == rhs.fields_; } bool operator!=( const BinaryHttpResponse::InformationalResponse& rhs) const { return !(*this == rhs); } void AddField(absl::string_view name, std::string value); const std::vector<BinaryHttpMessage::Field>& fields() const { return fields_.fields(); } uint16_t status_code() const { return status_code_; } std::string DebugString() const; private: friend class BinaryHttpResponse; size_t EncodedSize() const; absl::Status Encode(quiche::QuicheDataWriter& writer) const; const uint16_t status_code_; BinaryHttpMessage::Fields fields_; }; explicit BinaryHttpResponse(uint16_t status_code) : status_code_(status_code) {} static absl::StatusOr<BinaryHttpResponse> Create(absl::string_view data); size_t EncodedSize() const override; absl::StatusOr<std::string> Serialize() const override; absl::Status AddInformationalResponse(uint16_t status_code, std::vector<Field> header_fields); uint16_t status_code() const { return status_code_; } const std::vector<InformationalResponse>& informational_responses() const { return informational_response_control_data_; } virtual std::string DebugString() const override; bool IsPayloadEqual(const BinaryHttpResponse& rhs) const { return informational_response_control_data_ == rhs.informational_response_control_data_ && status_code_ == rhs.status_code_ && BinaryHttpMessage::IsPayloadEqual(rhs); } bool operator==(const BinaryHttpResponse& rhs) const { return IsPayloadEqual(rhs) && num_padding_bytes() == rhs.num_padding_bytes(); } bool operator!=(const BinaryHttpResponse& rhs) const { return !(*this == rhs); } private: absl::StatusOr<std::string> EncodeAsKnownLength() const; std::vector<InformationalResponse> informational_response_control_data_; const uint16_t status_code_; }; void QUICHE_EXPORT PrintTo(const BinaryHttpResponse& msg, std::ostream* os); } #endif #include "quiche/binary_http/binary_http_message.h" #include <algorithm> #include <cstdint> #include <functional> #include <iterator> #include <memory> #include <ostream> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/ascii.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "quiche/common/quiche_callbacks.h" #include "quiche/common/quiche_data_reader.h" #include "quiche/common/quiche_data_writer.h" namespace quiche { namespace { constexpr uint8_t kKnownLengthRequestFraming = 0; constexpr uint8_t kKnownLengthResponseFraming = 1; bool ReadStringValue(quiche::QuicheDataReader& reader, std::string& data) { absl::string_view data_view; if (!reader.ReadStringPieceVarInt62(&data_view)) { return false; } data = std::string(data_view); return true; } bool IsValidPadding(absl::string_view data) { return std::all_of(data.begin(), data.end(), [](char c) { return c == '\0'; }); } absl::StatusOr<BinaryHttpRequest::ControlData> DecodeControlData( quiche::QuicheDataReader& reader) { BinaryHttpRequest::ControlData control_data; if (!ReadStringValue(reader, control_data.method)) { return absl::InvalidArgumentError("Failed to read method."); } if (!ReadStringValue(reader, control_data.scheme)) { return absl::InvalidArgumentError("Failed to read scheme."); } if (!ReadStringValue(reader, control_data.authority)) { return absl::InvalidArgumentError("Failed to read authority."); } if (!ReadStringValue(reader, control_data.path)) { return absl::InvalidArgumentError("Failed to read path."); } return control_data; } absl::Status DecodeFields(quiche::QuicheDataReader& reader, quiche::UnretainedCallback<void( absl::string_view name, absl::string_view value)> callback) { absl::string_view fields; if (!reader.ReadStringPieceVarInt62(&fields)) { return absl::InvalidArgumentError("Failed to read fields."); } quiche::QuicheDataReader fields_reader(fields); while (!fields_reader.IsDoneReading()) { absl::string_view name; if (!fields_reader.ReadStringPieceVarInt62(&name)) { return absl::InvalidArgumentError("Failed to read field name."); } absl::string_view value; if (!fields_reader.ReadStringPieceVarInt62(&value)) { return absl::InvalidArgumentError("Failed to read field value."); } callback(name, value); } return absl::OkStatus(); } absl::Status DecodeFieldsAndBody(quiche::QuicheDataReader& reader, BinaryHttpMessage& message) { if (const absl::Status status = DecodeFields( reader, [&message](absl::string_view name, absl::string_view value) { message.AddHeaderField({std::string(name), std::string(value)}); }); !status.ok()) { return status; } if (reader.IsDoneReading()) { return absl::OkStatus(); } absl::string_view body; if (!reader.ReadStringPieceVarInt62(&body)) { return absl::InvalidArgumentError("Failed to read body."); } message.set_body(std::string(body)); return absl::OkStatus(); } absl::StatusOr<BinaryHttpRequest> DecodeKnownLengthRequest( quiche::QuicheDataReader& reader) { const auto control_data = DecodeControlData(reader); if (!control_data.ok()) { return control_data.status(); } BinaryHttpRequest request(std::move(*control_data)); if (const absl::Status status = DecodeFieldsAndBody(reader, request); !status.ok()) { return status; } if (!IsValidPadding(reader.PeekRemainingPayload())) { return absl::InvalidArgumentError("Non-zero padding."); } request.set_num_padding_bytes(reader.BytesRemaining()); return request; } absl::StatusOr<BinaryHttpResponse> DecodeKnownLengthResponse( quiche::QuicheDataReader& reader) { std::vector<std::pair<uint16_t, std::vector<BinaryHttpMessage::Field>>> informational_responses; uint64_t status_code; bool reading_response_control_data = true; while (reading_response_control_data) { if (!reader.ReadVarInt62(&status_code)) { return absl::InvalidArgumentError("Failed to read status code."); } if (status_code >= 100 && status_code <= 199) { std::vector<BinaryHttpMessage::Field> fields; if (const absl::Status status = DecodeFields( reader, [&fields](absl::string_view name, absl::string_view value) { fields.push_back({std::string(name), std::string(value)}); }); !status.ok()) { return status; } informational_responses.emplace_back(status_code, std::move(fields)); } else { reading_response_control_data = false; } } BinaryHttpResponse response(status_code); for (const auto& informational_response : informational_responses) { if (const absl::Status status = response.AddInformationalResponse( informational_response.first, std::move(informational_response.second)); !status.ok()) { return status; } } if (const absl::Status status = DecodeFieldsAndBody(reader, response); !status.ok()) { return status; } if (!IsValidPadding(reader.PeekRemainingPayload())) { return absl::InvalidArgumentError("Non-zero padding."); } response.set_num_padding_bytes(reader.BytesRemaining()); return response; } uint64_t StringPieceVarInt62Len(absl::string_view s) { return quiche::QuicheDataWriter::GetVarInt62Len(s.length()) + s.length(); } } void BinaryHttpMessage::Fields::AddField(BinaryHttpMessage::Field field) { fields_.push_back(std::move(field)); } absl::Status BinaryHttpMessage::Fields::Encode( quiche::QuicheDataWriter& writer) const { if (!writer.WriteVarInt62(EncodedFieldsSize())) { return absl::InvalidArgumentError("Failed to write encoded field size."); } for (const BinaryHttpMessage::Field& field : fields_) { if (!writer.WriteStringPieceVarInt62(field.name)) { return absl::InvalidArgumentError("Failed to write field name."); } if (!writer.WriteStringPieceVarInt62(field.value)) { return absl::InvalidArgumentError("Failed to write field value."); } } return absl::OkStatus(); } size_t BinaryHttpMessage::Fields::EncodedSize() const { const size_t size = EncodedFieldsSize(); return size + quiche::QuicheDataWriter::GetVarInt62Len(size); } size_t BinaryHttpMessage::Fields::EncodedFieldsSize() const { size_t size = 0; for (const BinaryHttpMessage::Field& field : fields_) { size += StringPieceVarInt62Len(field.name) + StringPieceVarInt62Len(field.value); } return size; } BinaryHttpMessage* BinaryHttpMessage::AddHeaderField( BinaryHttpMessage::Field field) { const std::string lower_name = absl::AsciiStrToLower(field.name); if (lower_name == "host") { has_host_ = true; } header_fields_.AddField({std::move(lower_name), std::move(field.value)}); return this; } absl::Status BinaryHttpMessage::EncodeKnownLengthFieldsAndBody( quiche::QuicheDataWriter& writer) const { if (const absl::Status status = header_fields_.Encode(writer); !status.ok()) { return status; } if (!writer.WriteStringPieceVarInt62(body_)) { return absl::InvalidArgumentError("Failed to encode body."); } return absl::OkStatus(); } size_t BinaryHttpMessage::EncodedKnownLengthFieldsAndBodySize() const { return header_fields_.EncodedSize() + StringPieceVarInt62Len(body_); } absl::Status BinaryHttpResponse::AddInformationalResponse( uint16_t status_code, std::vector<Field> header_fields) { if (status_code < 100) { return absl::InvalidArgumentError("status code < 100"); } if (status_code > 199) { return absl::InvalidArgumentError("status code > 199"); } InformationalResponse data(status_code); for (Field& header : header_fields) { data.AddField(header.name, std::move(header.value)); } informational_response_control_data_.push_back(std::move(data)); return absl::OkStatus(); } absl::StatusOr<std::string> BinaryHttpResponse::Serialize() const { return EncodeAsKnownLength(); } absl::StatusOr<std::string> BinaryHttpResponse::EncodeAsKnownLength() const { std::string data; data.resize(EncodedSize()); quiche::QuicheDataWriter writer(data.size(), data.data()); if (!writer.WriteUInt8(kKnownLengthResponseFraming)) { return absl::InvalidArgumentError("Failed to write framing indicator"); } for (const auto& informational : informational_response_control_data_) { if (const absl::Status status = informational.Encode(writer); !status.ok()) { return status; } } if (!writer.WriteVarInt62(status_code_)) { return absl::InvalidArgumentError("Failed to write status code"); } if (const absl::Status status = EncodeKnownLengthFieldsAndBody(writer); !status.ok()) { return status; } QUICHE_DCHECK_EQ(writer.remaining(), num_padding_bytes()); writer.WritePadding(); return data; } size_t BinaryHttpResponse::EncodedSize() const { size_t size = sizeof(kKnownLengthResponseFraming); for (const auto& informational : informational_response_control_data_) { size += informational.EncodedSize(); } return size + quiche::QuicheDataWriter::GetVarInt62Len(status_code_) + EncodedKnownLengthFieldsAndBodySize() + num_padding_bytes(); } void BinaryHttpResponse::InformationalResponse::AddField(absl::string_view name, std::string value) { fields_.AddField({absl::AsciiStrToLower(name), std::move(value)}); } absl::Status BinaryHttpResponse::InformationalResponse::Encode( quiche::QuicheDataWriter& writer) const { writer.WriteVarInt62(status_code_); return fields_.Encode(writer); } size_t BinaryHttpResponse::InformationalResponse::EncodedSize() const { return quiche::QuicheDataWriter::GetVarInt62Len(status_code_) + fields_.EncodedSize(); } absl::StatusOr<std::string> BinaryHttpRequest::Serialize() const { return EncodeAsKnownLength(); } absl::Status BinaryHttpRequest::EncodeControlData( quiche::QuicheDataWriter& writer) const { if (!writer.WriteStringPieceVarInt62(control_data_.method)) { return absl::InvalidArgumentError("Failed to encode method."); } if (!writer.WriteStringPieceVarInt62(control_data_.scheme)) { return absl::InvalidArgumentError("Failed to encode scheme."); } if (!has_host()) { if (!writer.WriteStringPieceVarInt62(control_data_.authority)) { return absl::InvalidArgumentError("Failed to encode authority."); } } else { if (!writer.WriteStringPieceVarInt62("")) { return absl::InvalidArgumentError("Failed to encode authority."); } } if (!writer.WriteStringPieceVarInt62(control_data_.path)) { return absl::InvalidArgumentError("Failed to encode path."); } return absl::OkStatus(); } size_t BinaryHttpRequest::EncodedControlDataSize() const { size_t size = StringPieceVarInt62Len(control_data_.method) + StringPieceVarInt62Len(control_data_.scheme) + StringPieceVarInt62Len(control_data_.path); if (!has_host()) { size += StringPieceVarInt62Len(control_data_.authority); } else { size += StringPieceVarInt62Len(""); } return size; } size_t BinaryHttpRequest::EncodedSize() const { return sizeof(kKnownLengthRequestFraming) + EncodedControlDataSize() + EncodedKnownLengthFieldsAndBodySize() + num_padding_bytes(); } absl::StatusOr<std::string> BinaryHttpRequest::EncodeAsKnownLength() const { std::string data; data.resize(EncodedSize()); quiche::QuicheDataWriter writer(data.size(), data.data()); if (!writer.WriteUInt8(kKnownLengthRequestFraming)) { return absl::InvalidArgumentError("Failed to encode framing indicator."); } if (const absl::Status status = EncodeControlData(writer); !status.ok()) { return status; } if (const absl::Status status = EncodeKnownLengthFieldsAndBody(writer); !status.ok()) { return status; } QUICHE_DCHECK_EQ(writer.remaining(), num_padding_bytes()); writer.WritePadding(); return data; } absl::StatusOr<BinaryHttpRequest> BinaryHttpRequest::Create( absl::string_view data) { quiche::QuicheDataReader reader(data); uint8_t framing; if (!reader.ReadUInt8(&framing)) { return absl::InvalidArgumentError("Missing framing indicator."); } if (framing == kKnownLengthRequestFraming) { return DecodeKnownLengthRequest(reader); } return absl::UnimplementedError( absl::StrCat("Unsupported framing type ", framing)); } absl::StatusOr<BinaryHttpResponse> BinaryHttpResponse::Create( absl::string_view data) { quiche::QuicheDataReader reader(data); uint8_t framing; if (!reader.ReadUInt8(&framing)) { return absl::InvalidArgumentError("Missing framing indicator."); } if (framing == kKnownLengthResponseFraming) { return DecodeKnownLengthResponse(reader); } return absl::UnimplementedError( absl::StrCat("Unsupported framing type ", framing)); } std::string BinaryHttpMessage::DebugString() const { std::vector<std::string> headers; for (const auto& field : GetHeaderFields()) { headers.emplace_back(field.DebugString()); } return absl::StrCat("BinaryHttpMessage{Headers{", absl::StrJoin(headers, ";"), "}Body{", body(), "}}"); } std::string BinaryHttpMessage::Field::DebugString() const { return absl::StrCat("Field{", name, "=", value, "}"); } std::string BinaryHttpResponse::InformationalResponse::DebugString() const { std::vector<std::string> fs; for (const auto& field : fields()) { fs.emplace_back(field.DebugString()); } return absl::StrCat("InformationalResponse{", absl::StrJoin(fs, ";"), "}"); } std::string BinaryHttpResponse::DebugString() const { std::vector<std::string> irs; for (const auto& ir : informational_responses()) { irs.emplace_back(ir.DebugString()); } return absl::StrCat("BinaryHttpResponse(", status_code_, "){", BinaryHttpMessage::DebugString(), absl::StrJoin(irs, ";"), "}"); } std::string BinaryHttpRequest::DebugString() const { return absl::StrCat("BinaryHttpRequest{", BinaryHttpMessage::DebugString(), "}"); } void PrintTo(const BinaryHttpRequest& msg, std::ostream* os) { *os << msg.DebugString(); } void PrintTo(const BinaryHttpResponse& msg, std::ostream* os) { *os << msg.DebugString(); } void PrintTo(const BinaryHttpMessage::Field& msg, std::ostream* os) { *os << msg.DebugString(); } }
#include "quiche/binary_http/binary_http_message.h" #include <cstdint> #include <memory> #include <sstream> #include <string> #include <vector> #include "absl/container/flat_hash_map.h" #include "quiche/common/platform/api/quiche_test.h" using ::testing::ContainerEq; using ::testing::FieldsAre; using ::testing::StrEq; namespace quiche { namespace { std::string WordToBytes(uint32_t word) { return std::string({static_cast<char>(word >> 24), static_cast<char>(word >> 16), static_cast<char>(word >> 8), static_cast<char>(word)}); } template <class T> void TestPrintTo(const T& resp) { std::ostringstream os; PrintTo(resp, &os); EXPECT_EQ(os.str(), resp.DebugString()); } } TEST(BinaryHttpRequest, EncodeGetNoBody) { BinaryHttpRequest request({"GET", "https", "www.example.com", "/hello.txt"}); request .AddHeaderField({"User-Agent", "curl/7.16.3 libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3"}) ->AddHeaderField({"Host", "www.example.com"}) ->AddHeaderField({"Accept-Language", "en, mi"}); const uint32_t expected_words[] = { 0x00034745, 0x54056874, 0x74707300, 0x0a2f6865, 0x6c6c6f2e, 0x74787440, 0x6c0a7573, 0x65722d61, 0x67656e74, 0x34637572, 0x6c2f372e, 0x31362e33, 0x206c6962, 0x6375726c, 0x2f372e31, 0x362e3320, 0x4f70656e, 0x53534c2f, 0x302e392e, 0x376c207a, 0x6c69622f, 0x312e322e, 0x3304686f, 0x73740f77, 0x77772e65, 0x78616d70, 0x6c652e63, 0x6f6d0f61, 0x63636570, 0x742d6c61, 0x6e677561, 0x67650665, 0x6e2c206d, 0x69000000}; std::string expected; for (const auto& word : expected_words) { expected += WordToBytes(word); } expected.resize(expected.size() - 2); const auto result = request.Serialize(); ASSERT_TRUE(result.ok()); ASSERT_EQ(*result, expected); EXPECT_THAT( request.DebugString(), StrEq("BinaryHttpRequest{BinaryHttpMessage{Headers{Field{user-agent=curl/" "7.16.3 " "libcurl/7.16.3 OpenSSL/0.9.7l " "zlib/1.2.3};Field{host=www.example.com};Field{accept-language=en, " "mi}}Body{}}}")); TestPrintTo(request); } TEST(BinaryHttpRequest, DecodeGetNoBody) { const uint32_t words[] = { 0x00034745, 0x54056874, 0x74707300, 0x0a2f6865, 0x6c6c6f2e, 0x74787440, 0x6c0a7573, 0x65722d61, 0x67656e74, 0x34637572, 0x6c2f372e, 0x31362e33, 0x206c6962, 0x6375726c, 0x2f372e31, 0x362e3320, 0x4f70656e, 0x53534c2f, 0x302e392e, 0x376c207a, 0x6c69622f, 0x312e322e, 0x3304686f, 0x73740f77, 0x77772e65, 0x78616d70, 0x6c652e63, 0x6f6d0f61, 0x63636570, 0x742d6c61, 0x6e677561, 0x67650665, 0x6e2c206d, 0x69000000}; std::string data; for (const auto& word : words) { data += WordToBytes(word); } data.resize(data.size() - 3); const auto request_so = BinaryHttpRequest::Create(data); ASSERT_TRUE(request_so.ok()); const BinaryHttpRequest request = *request_so; ASSERT_THAT(request.control_data(), FieldsAre("GET", "https", "", "/hello.txt")); std::vector<BinaryHttpMessage::Field> expected_fields = { {"user-agent", "curl/7.16.3 libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3"}, {"host", "www.example.com"}, {"accept-language", "en, mi"}}; for (const auto& field : expected_fields) { TestPrintTo(field); } ASSERT_THAT(request.GetHeaderFields(), ContainerEq(expected_fields)); ASSERT_EQ(request.body(), ""); EXPECT_THAT( request.DebugString(), StrEq("BinaryHttpRequest{BinaryHttpMessage{Headers{Field{user-agent=curl/" "7.16.3 " "libcurl/7.16.3 OpenSSL/0.9.7l " "zlib/1.2.3};Field{host=www.example.com};Field{accept-language=en, " "mi}}Body{}}}")); TestPrintTo(request); } TEST(BinaryHttpRequest, EncodeGetWithAuthority) { BinaryHttpRequest request({"GET", "https", "www.example.com", "/hello.txt"}); request .AddHeaderField({"User-Agent", "curl/7.16.3 libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3"}) ->AddHeaderField({"Accept-Language", "en, mi"}); const uint32_t expected_words[] = { 0x00034745, 0x54056874, 0x7470730f, 0x7777772e, 0x6578616d, 0x706c652e, 0x636f6d0a, 0x2f68656c, 0x6c6f2e74, 0x78744057, 0x0a757365, 0x722d6167, 0x656e7434, 0x6375726c, 0x2f372e31, 0x362e3320, 0x6c696263, 0x75726c2f, 0x372e3136, 0x2e33204f, 0x70656e53, 0x534c2f30, 0x2e392e37, 0x6c207a6c, 0x69622f31, 0x2e322e33, 0x0f616363, 0x6570742d, 0x6c616e67, 0x75616765, 0x06656e2c, 0x206d6900}; std::string expected; for (const auto& word : expected_words) { expected += WordToBytes(word); } const auto result = request.Serialize(); ASSERT_TRUE(result.ok()); ASSERT_EQ(*result, expected); EXPECT_THAT( request.DebugString(), StrEq("BinaryHttpRequest{BinaryHttpMessage{Headers{Field{user-agent=curl/" "7.16.3 libcurl/7.16.3 OpenSSL/0.9.7l " "zlib/1.2.3};Field{accept-language=en, mi}}Body{}}}")); } TEST(BinaryHttpRequest, DecodeGetWithAuthority) { const uint32_t words[] = { 0x00034745, 0x54056874, 0x7470730f, 0x7777772e, 0x6578616d, 0x706c652e, 0x636f6d0a, 0x2f68656c, 0x6c6f2e74, 0x78744057, 0x0a757365, 0x722d6167, 0x656e7434, 0x6375726c, 0x2f372e31, 0x362e3320, 0x6c696263, 0x75726c2f, 0x372e3136, 0x2e33204f, 0x70656e53, 0x534c2f30, 0x2e392e37, 0x6c207a6c, 0x69622f31, 0x2e322e33, 0x0f616363, 0x6570742d, 0x6c616e67, 0x75616765, 0x06656e2c, 0x206d6900, 0x00}; std::string data; for (const auto& word : words) { data += WordToBytes(word); } const auto request_so = BinaryHttpRequest::Create(data); ASSERT_TRUE(request_so.ok()); const BinaryHttpRequest request = *request_so; ASSERT_THAT(request.control_data(), FieldsAre("GET", "https", "www.example.com", "/hello.txt")); std::vector<BinaryHttpMessage::Field> expected_fields = { {"user-agent", "curl/7.16.3 libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3"}, {"accept-language", "en, mi"}}; ASSERT_THAT(request.GetHeaderFields(), ContainerEq(expected_fields)); ASSERT_EQ(request.body(), ""); EXPECT_THAT( request.DebugString(), StrEq("BinaryHttpRequest{BinaryHttpMessage{Headers{Field{user-agent=curl/" "7.16.3 libcurl/7.16.3 OpenSSL/0.9.7l " "zlib/1.2.3};Field{accept-language=en, mi}}Body{}}}")); } TEST(BinaryHttpRequest, EncodePostBody) { BinaryHttpRequest request({"POST", "https", "www.example.com", "/hello.txt"}); request.AddHeaderField({"User-Agent", "not/telling"}) ->AddHeaderField({"Host", "www.example.com"}) ->AddHeaderField({"Accept-Language", "en"}) ->set_body({"Some body that I used to post.\r\n"}); const uint32_t expected_words[] = { 0x0004504f, 0x53540568, 0x74747073, 0x000a2f68, 0x656c6c6f, 0x2e747874, 0x3f0a7573, 0x65722d61, 0x67656e74, 0x0b6e6f74, 0x2f74656c, 0x6c696e67, 0x04686f73, 0x740f7777, 0x772e6578, 0x616d706c, 0x652e636f, 0x6d0f6163, 0x63657074, 0x2d6c616e, 0x67756167, 0x6502656e, 0x20536f6d, 0x6520626f, 0x64792074, 0x68617420, 0x49207573, 0x65642074, 0x6f20706f, 0x73742e0d, 0x0a000000}; std::string expected; for (const auto& word : expected_words) { expected += WordToBytes(word); } expected.resize(expected.size() - 3); const auto result = request.Serialize(); ASSERT_TRUE(result.ok()); ASSERT_EQ(*result, expected); EXPECT_THAT( request.DebugString(), StrEq("BinaryHttpRequest{BinaryHttpMessage{Headers{Field{user-agent=not/" "telling};Field{host=www.example.com};Field{accept-language=en}}" "Body{Some " "body that I used to post.\r\n}}}")); } TEST(BinaryHttpRequest, DecodePostBody) { const uint32_t words[] = { 0x0004504f, 0x53540568, 0x74747073, 0x000a2f68, 0x656c6c6f, 0x2e747874, 0x3f0a7573, 0x65722d61, 0x67656e74, 0x0b6e6f74, 0x2f74656c, 0x6c696e67, 0x04686f73, 0x740f7777, 0x772e6578, 0x616d706c, 0x652e636f, 0x6d0f6163, 0x63657074, 0x2d6c616e, 0x67756167, 0x6502656e, 0x20536f6d, 0x6520626f, 0x64792074, 0x68617420, 0x49207573, 0x65642074, 0x6f20706f, 0x73742e0d, 0x0a000000}; std::string data; for (const auto& word : words) { data += WordToBytes(word); } const auto request_so = BinaryHttpRequest::Create(data); ASSERT_TRUE(request_so.ok()); BinaryHttpRequest request = *request_so; ASSERT_THAT(request.control_data(), FieldsAre("POST", "https", "", "/hello.txt")); std::vector<BinaryHttpMessage::Field> expected_fields = { {"user-agent", "not/telling"}, {"host", "www.example.com"}, {"accept-language", "en"}}; ASSERT_THAT(request.GetHeaderFields(), ContainerEq(expected_fields)); ASSERT_EQ(request.body(), "Some body that I used to post.\r\n"); EXPECT_THAT( request.DebugString(), StrEq("BinaryHttpRequest{BinaryHttpMessage{Headers{Field{user-agent=not/" "telling};Field{host=www.example.com};Field{accept-language=en}}" "Body{Some " "body that I used to post.\r\n}}}")); } TEST(BinaryHttpRequest, Equality) { BinaryHttpRequest request({"POST", "https", "www.example.com", "/hello.txt"}); request.AddHeaderField({"User-Agent", "not/telling"}) ->set_body({"hello, world!\r\n"}); BinaryHttpRequest same({"POST", "https", "www.example.com", "/hello.txt"}); same.AddHeaderField({"User-Agent", "not/telling"}) ->set_body({"hello, world!\r\n"}); EXPECT_EQ(request, same); } TEST(BinaryHttpRequest, Inequality) { BinaryHttpRequest request({"POST", "https", "www.example.com", "/hello.txt"}); request.AddHeaderField({"User-Agent", "not/telling"}) ->set_body({"hello, world!\r\n"}); BinaryHttpRequest different_control( {"PUT", "https", "www.example.com", "/hello.txt"}); different_control.AddHeaderField({"User-Agent", "not/telling"}) ->set_body({"hello, world!\r\n"}); EXPECT_NE(request, different_control); BinaryHttpRequest different_header( {"PUT", "https", "www.example.com", "/hello.txt"}); different_header.AddHeaderField({"User-Agent", "told/you"}) ->set_body({"hello, world!\r\n"}); EXPECT_NE(request, different_header); BinaryHttpRequest no_header( {"PUT", "https", "www.example.com", "/hello.txt"}); no_header.set_body({"hello, world!\r\n"}); EXPECT_NE(request, no_header); BinaryHttpRequest different_body( {"POST", "https", "www.example.com", "/hello.txt"}); different_body.AddHeaderField({"User-Agent", "not/telling"}) ->set_body({"goodbye, world!\r\n"}); EXPECT_NE(request, different_body); BinaryHttpRequest no_body({"POST", "https", "www.example.com", "/hello.txt"}); no_body.AddHeaderField({"User-Agent", "not/telling"}); EXPECT_NE(request, no_body); } TEST(BinaryHttpResponse, EncodeNoBody) { BinaryHttpResponse response(404); response.AddHeaderField({"Server", "Apache"}); const uint32_t expected_words[] = {0x0141940e, 0x06736572, 0x76657206, 0x41706163, 0x68650000}; std::string expected; for (const auto& word : expected_words) { expected += WordToBytes(word); } expected.resize(expected.size() - 1); const auto result = response.Serialize(); ASSERT_TRUE(result.ok()); ASSERT_EQ(*result, expected); EXPECT_THAT( response.DebugString(), StrEq("BinaryHttpResponse(404){BinaryHttpMessage{Headers{Field{server=" "Apache}}Body{}}}")); } TEST(BinaryHttpResponse, DecodeNoBody) { const uint32_t words[] = {0x0141940e, 0x06736572, 0x76657206, 0x41706163, 0x68650000}; std::string data; for (const auto& word : words) { data += WordToBytes(word); } const auto response_so = BinaryHttpResponse::Create(data); ASSERT_TRUE(response_so.ok()); const BinaryHttpResponse response = *response_so; ASSERT_EQ(response.status_code(), 404); std::vector<BinaryHttpMessage::Field> expected_fields = { {"server", "Apache"}}; ASSERT_THAT(response.GetHeaderFields(), ContainerEq(expected_fields)); ASSERT_EQ(response.body(), ""); ASSERT_TRUE(response.informational_responses().empty()); EXPECT_THAT( response.DebugString(), StrEq("BinaryHttpResponse(404){BinaryHttpMessage{Headers{Field{server=" "Apache}}Body{}}}")); } TEST(BinaryHttpResponse, EncodeBody) { BinaryHttpResponse response(200); response.AddHeaderField({"Server", "Apache"}); response.set_body("Hello, world!\r\n"); const uint32_t expected_words[] = {0x0140c80e, 0x06736572, 0x76657206, 0x41706163, 0x68650f48, 0x656c6c6f, 0x2c20776f, 0x726c6421, 0x0d0a0000}; std::string expected; for (const auto& word : expected_words) { expected += WordToBytes(word); } expected.resize(expected.size() - 2); const auto result = response.Serialize(); ASSERT_TRUE(result.ok()); ASSERT_EQ(*result, expected); EXPECT_THAT( response.DebugString(), StrEq("BinaryHttpResponse(200){BinaryHttpMessage{Headers{Field{server=" "Apache}}Body{Hello, world!\r\n}}}")); } TEST(BinaryHttpResponse, DecodeBody) { const uint32_t words[] = {0x0140c80e, 0x06736572, 0x76657206, 0x41706163, 0x68650f48, 0x656c6c6f, 0x2c20776f, 0x726c6421, 0x0d0a0000}; std::string data; for (const auto& word : words) { data += WordToBytes(word); } const auto response_so = BinaryHttpResponse::Create(data); ASSERT_TRUE(response_so.ok()); const BinaryHttpResponse response = *response_so; ASSERT_EQ(response.status_code(), 200); std::vector<BinaryHttpMessage::Field> expected_fields = { {"server", "Apache"}}; ASSERT_THAT(response.GetHeaderFields(), ContainerEq(expected_fields)); ASSERT_EQ(response.body(), "Hello, world!\r\n"); ASSERT_TRUE(response.informational_responses().empty()); EXPECT_THAT( response.DebugString(), StrEq("BinaryHttpResponse(200){BinaryHttpMessage{Headers{Field{server=" "Apache}}Body{Hello, world!\r\n}}}")); } TEST(BHttpResponse, AddBadInformationalResponseCode) { BinaryHttpResponse response(200); ASSERT_FALSE(response.AddInformationalResponse(50, {}).ok()); ASSERT_FALSE(response.AddInformationalResponse(300, {}).ok()); } TEST(BinaryHttpResponse, EncodeMultiInformationalWithBody) { BinaryHttpResponse response(200); response.AddHeaderField({"Date", "Mon, 27 Jul 2009 12:28:53 GMT"}) ->AddHeaderField({"Server", "Apache"}) ->AddHeaderField({"Last-Modified", "Wed, 22 Jul 2009 19:15:56 GMT"}) ->AddHeaderField({"ETag", "\"34aa387-d-1568eb00\""}) ->AddHeaderField({"Accept-Ranges", "bytes"}) ->AddHeaderField({"Content-Length", "51"}) ->AddHeaderField({"Vary", "Accept-Encoding"}) ->AddHeaderField({"Content-Type", "text/plain"}); response.set_body("Hello World! My content includes a trailing CRLF.\r\n"); ASSERT_TRUE( response.AddInformationalResponse(102, {{"Running", "\"sleep 15\""}}) .ok()); ASSERT_TRUE(response .AddInformationalResponse( 103, {{"Link", "</style.css>; rel=preload; as=style"}, {"Link", "</script.js>; rel=preload; as=script"}}) .ok()); const uint32_t expected_words[] = { 0x01406613, 0x0772756e, 0x6e696e67, 0x0a22736c, 0x65657020, 0x31352240, 0x67405304, 0x6c696e6b, 0x233c2f73, 0x74796c65, 0x2e637373, 0x3e3b2072, 0x656c3d70, 0x72656c6f, 0x61643b20, 0x61733d73, 0x74796c65, 0x046c696e, 0x6b243c2f, 0x73637269, 0x70742e6a, 0x733e3b20, 0x72656c3d, 0x7072656c, 0x6f61643b, 0x2061733d, 0x73637269, 0x707440c8, 0x40ca0464, 0x6174651d, 0x4d6f6e2c, 0x20323720, 0x4a756c20, 0x32303039, 0x2031323a, 0x32383a35, 0x3320474d, 0x54067365, 0x72766572, 0x06417061, 0x6368650d, 0x6c617374, 0x2d6d6f64, 0x69666965, 0x641d5765, 0x642c2032, 0x32204a75, 0x6c203230, 0x30392031, 0x393a3135, 0x3a353620, 0x474d5404, 0x65746167, 0x14223334, 0x61613338, 0x372d642d, 0x31353638, 0x65623030, 0x220d6163, 0x63657074, 0x2d72616e, 0x67657305, 0x62797465, 0x730e636f, 0x6e74656e, 0x742d6c65, 0x6e677468, 0x02353104, 0x76617279, 0x0f416363, 0x6570742d, 0x456e636f, 0x64696e67, 0x0c636f6e, 0x74656e74, 0x2d747970, 0x650a7465, 0x78742f70, 0x6c61696e, 0x3348656c, 0x6c6f2057, 0x6f726c64, 0x21204d79, 0x20636f6e, 0x74656e74, 0x20696e63, 0x6c756465, 0x73206120, 0x74726169, 0x6c696e67, 0x2043524c, 0x462e0d0a}; std::string expected; for (const auto& word : expected_words) { expected += WordToBytes(word); } const auto result = response.Serialize(); ASSERT_TRUE(result.ok()); ASSERT_EQ(*result, expected); EXPECT_THAT( response.DebugString(), StrEq( "BinaryHttpResponse(200){BinaryHttpMessage{Headers{Field{date=Mon, " "27 Jul 2009 12:28:53 " "GMT};Field{server=Apache};Field{last-modified=Wed, 22 Jul 2009 " "19:15:56 " "GMT};Field{etag=\"34aa387-d-1568eb00\"};Field{accept-ranges=bytes};" "Field{" "content-length=51};Field{vary=Accept-Encoding};Field{content-type=" "text/plain}}Body{Hello World! My content includes a trailing " "CRLF.\r\n}}InformationalResponse{Field{running=\"sleep " "15\"}};InformationalResponse{Field{link=</style.css>; rel=preload; " "as=style};Field{link=</script.js>; rel=preload; as=script}}}")); TestPrintTo(response); } TEST(BinaryHttpResponse, DecodeMultiInformationalWithBody) { const uint32_t words[] = { 0x01406613, 0x0772756e, 0x6e696e67, 0x0a22736c, 0x65657020, 0x31352240, 0x67405304, 0x6c696e6b, 0x233c2f73, 0x74796c65, 0x2e637373, 0x3e3b2072, 0x656c3d70, 0x72656c6f, 0x61643b20, 0x61733d73, 0x74796c65, 0x046c696e, 0x6b243c2f, 0x73637269, 0x70742e6a, 0x733e3b20, 0x72656c3d, 0x7072656c, 0x6f61643b, 0x2061733d, 0x73637269, 0x707440c8, 0x40ca0464, 0x6174651d, 0x4d6f6e2c, 0x20323720, 0x4a756c20, 0x32303039, 0x2031323a, 0x32383a35, 0x3320474d, 0x54067365, 0x72766572, 0x06417061, 0x6368650d, 0x6c617374, 0x2d6d6f64, 0x69666965, 0x641d5765, 0x642c2032, 0x32204a75, 0x6c203230, 0x30392031, 0x393a3135, 0x3a353620, 0x474d5404, 0x65746167, 0x14223334, 0x61613338, 0x372d642d, 0x31353638, 0x65623030, 0x220d6163, 0x63657074, 0x2d72616e, 0x67657305, 0x62797465, 0x730e636f, 0x6e74656e, 0x742d6c65, 0x6e677468, 0x02353104, 0x76617279, 0x0f416363, 0x6570742d, 0x456e636f, 0x64696e67, 0x0c636f6e, 0x74656e74, 0x2d747970, 0x650a7465, 0x78742f70, 0x6c61696e, 0x3348656c, 0x6c6f2057, 0x6f726c64, 0x21204d79, 0x20636f6e, 0x74656e74, 0x20696e63, 0x6c756465, 0x73206120, 0x74726169, 0x6c696e67, 0x2043524c, 0x462e0d0a, 0x00000000}; std::string data; for (const auto& word : words) { data += WordToBytes(word); } const auto response_so = BinaryHttpResponse::Create(data); ASSERT_TRUE(response_so.ok()); const BinaryHttpResponse response = *response_so; std::vector<BinaryHttpMessage::Field> expected_fields = { {"date", "Mon, 27 Jul 2009 12:28:53 GMT"}, {"server", "Apache"}, {"last-modified", "Wed, 22 Jul 2009 19:15:56 GMT"}, {"etag", "\"34aa387-d-1568eb00\""}, {"accept-ranges", "bytes"}, {"content-length", "51"}, {"vary", "Accept-Encoding"}, {"content-type", "text/plain"}}; ASSERT_THAT(response.GetHeaderFields(), ContainerEq(expected_fields)); ASSERT_EQ(response.body(), "Hello World! My content includes a trailing CRLF.\r\n"); std::vector<BinaryHttpMessage::Field> header102 = { {"running", "\"sleep 15\""}}; std::vector<BinaryHttpMessage::Field> header103 = { {"link", "</style.css>; rel=preload; as=style"}, {"link", "</script.js>; rel=preload; as=script"}}; std::vector<BinaryHttpResponse::InformationalResponse> expected_control = { {102, header102}, {103, header103}}; ASSERT_THAT(response.informational_responses(), ContainerEq(expected_control)); EXPECT_THAT( response.DebugString(), StrEq( "BinaryHttpResponse(200){BinaryHttpMessage{Headers{Field{date=Mon, " "27 Jul 2009 12:28:53 " "GMT};Field{server=Apache};Field{last-modified=Wed, 22 Jul 2009 " "19:15:56 " "GMT};Field{etag=\"34aa387-d-1568eb00\"};Field{accept-ranges=bytes};" "Field{" "content-length=51};Field{vary=Accept-Encoding};Field{content-type=" "text/plain}}Body{Hello World! My content includes a trailing " "CRLF.\r\n}}InformationalResponse{Field{running=\"sleep " "15\"}};InformationalResponse{Field{link=</style.css>; rel=preload; " "as=style};Field{link=</script.js>; rel=preload; as=script}}}")); TestPrintTo(response); } TEST(BinaryHttpMessage, SwapBody) { BinaryHttpRequest request({}); request.set_body("hello, world!"); std::string other = "goodbye, world!"; request.swap_body(other); EXPECT_EQ(request.body(), "goodbye, world!"); EXPECT_EQ(other, "hello, world!"); } TEST(BinaryHttpResponse, Equality) { BinaryHttpResponse response(200); response.AddHeaderField({"Server", "Apache"})->set_body("Hello, world!\r\n"); ASSERT_TRUE( response.AddInformationalResponse(102, {{"Running", "\"sleep 15\""}}) .ok()); BinaryHttpResponse same(200); same.AddHeaderField({"Server", "Apache"})->set_body("Hello, world!\r\n"); ASSERT_TRUE( same.AddInformationalResponse(102, {{"Running", "\"sleep 15\""}}).ok()); ASSERT_EQ(response, same); } TEST(BinaryHttpResponse, Inequality) { BinaryHttpResponse response(200); response.AddHeaderField({"Server", "Apache"})->set_body("Hello, world!\r\n"); ASSERT_TRUE( response.AddInformationalResponse(102, {{"Running", "\"sleep 15\""}}) .ok()); BinaryHttpResponse different_status(201); different_status.AddHeaderField({"Server", "Apache"}) ->set_body("Hello, world!\r\n"); EXPECT_TRUE(different_status .AddInformationalResponse(102, {{"Running", "\"sleep 15\""}}) .ok()); EXPECT_NE(response, different_status); BinaryHttpResponse different_header(200); different_header.AddHeaderField({"Server", "python3"}) ->set_body("Hello, world!\r\n"); EXPECT_TRUE(different_header .AddInformationalResponse(102, {{"Running", "\"sleep 15\""}}) .ok()); EXPECT_NE(response, different_header); BinaryHttpResponse no_header(200); no_header.set_body("Hello, world!\r\n"); EXPECT_TRUE( no_header.AddInformationalResponse(102, {{"Running", "\"sleep 15\""}}) .ok()); EXPECT_NE(response, no_header); BinaryHttpResponse different_body(200); different_body.AddHeaderField({"Server", "Apache"}) ->set_body("Goodbye, world!\r\n"); EXPECT_TRUE(different_body .AddInformationalResponse(102, {{"Running", "\"sleep 15\""}}) .ok()); EXPECT_NE(response, different_body); BinaryHttpResponse no_body(200); no_body.AddHeaderField({"Server", "Apache"}); EXPECT_TRUE( no_body.AddInformationalResponse(102, {{"Running", "\"sleep 15\""}}) .ok()); EXPECT_NE(response, no_body); BinaryHttpResponse different_informational(200); different_informational.AddHeaderField({"Server", "Apache"}) ->set_body("Hello, world!\r\n"); EXPECT_TRUE(different_informational .AddInformationalResponse(198, {{"Running", "\"sleep 15\""}}) .ok()); EXPECT_NE(response, different_informational); BinaryHttpResponse no_informational(200); no_informational.AddHeaderField({"Server", "Apache"}) ->set_body("Hello, world!\r\n"); EXPECT_NE(response, no_informational); } MATCHER_P(HasEqPayload, value, "Payloads of messages are equivalent.") { return arg.IsPayloadEqual(value); } template <typename T> void TestPadding(T& message) { const auto data_so = message.Serialize(); ASSERT_TRUE(data_so.ok()); auto data = *data_so; ASSERT_EQ(data.size(), message.EncodedSize()); message.set_num_padding_bytes(10); const auto padded_data_so = message.Serialize(); ASSERT_TRUE(padded_data_so.ok()); const auto padded_data = *padded_data_so; ASSERT_EQ(padded_data.size(), message.EncodedSize()); ASSERT_EQ(data.size() + 10, padded_data.size()); data.resize(data.size() + 10); ASSERT_EQ(data, padded_data); const auto deserialized_padded_message_so = T::Create(data); ASSERT_TRUE(deserialized_padded_message_so.ok()); const auto deserialized_padded_message = *deserialized_padded_message_so; ASSERT_EQ(deserialized_padded_message, message); ASSERT_EQ(deserialized_padded_message.num_padding_bytes(), size_t(10)); data[data.size() - 1] = 'a'; const auto bad_so = T::Create(data); ASSERT_FALSE(bad_so.ok()); data.resize(data.size() - 10); const auto deserialized_message_so = T::Create(data); ASSERT_TRUE(deserialized_message_so.ok()); const auto deserialized_message = *deserialized_message_so; ASSERT_EQ(deserialized_message.num_padding_bytes(), size_t(0)); ASSERT_THAT(deserialized_message, HasEqPayload(deserialized_padded_message)); ASSERT_NE(deserialized_message, deserialized_padded_message); } TEST(BinaryHttpRequest, Padding) { BinaryHttpRequest request({"GET", "https", "", "/hello.txt"}); request .AddHeaderField({"User-Agent", "curl/7.16.3 libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3"}) ->AddHeaderField({"Host", "www.example.com"}) ->AddHeaderField({"Accept-Language", "en, mi"}); TestPadding(request); } TEST(BinaryHttpResponse, Padding) { BinaryHttpResponse response(200); response.AddHeaderField({"Server", "Apache"}); response.set_body("Hello, world!\r\n"); TestPadding(response); } }
381
cpp
google/quiche
oblivious_http_client
quiche/oblivious_http/oblivious_http_client.cc
quiche/oblivious_http/oblivious_http_client_test.cc
#ifndef QUICHE_OBLIVIOUS_HTTP_OBLIVIOUS_HTTP_CLIENT_H_ #define QUICHE_OBLIVIOUS_HTTP_OBLIVIOUS_HTTP_CLIENT_H_ #include <string> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "openssl/base.h" #include "openssl/hpke.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/oblivious_http/buffers/oblivious_http_request.h" #include "quiche/oblivious_http/buffers/oblivious_http_response.h" #include "quiche/oblivious_http/common/oblivious_http_header_key_config.h" namespace quiche { class QUICHE_EXPORT ObliviousHttpClient { public: static absl::StatusOr<ObliviousHttpClient> Create( absl::string_view hpke_public_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config); ObliviousHttpClient(const ObliviousHttpClient& other) = default; ObliviousHttpClient& operator=(const ObliviousHttpClient& other) = default; ObliviousHttpClient(ObliviousHttpClient&& other) = default; ObliviousHttpClient& operator=(ObliviousHttpClient&& other) = default; ~ObliviousHttpClient() = default; absl::StatusOr<ObliviousHttpRequest> CreateObliviousHttpRequest( std::string plaintext_data) const; absl::StatusOr<ObliviousHttpResponse> DecryptObliviousHttpResponse( std::string encrypted_data, ObliviousHttpRequest::Context& oblivious_http_request_context) const; private: explicit ObliviousHttpClient( std::string client_public_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config); std::string hpke_public_key_; ObliviousHttpHeaderKeyConfig ohttp_key_config_; }; } #endif #include "quiche/oblivious_http/oblivious_http_client.h" #include <stddef.h> #include <stdint.h> #include <memory> #include <string> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/common/quiche_crypto_logging.h" namespace quiche { namespace { absl::Status ValidateClientParameters( absl::string_view hpke_public_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config) { bssl::UniquePtr<EVP_HPKE_CTX> client_ctx(EVP_HPKE_CTX_new()); if (client_ctx == nullptr) { return SslErrorAsStatus( "Failed to initialize HPKE ObliviousHttpClient Context."); } std::string encapsulated_key(EVP_HPKE_MAX_ENC_LENGTH, '\0'); size_t enc_len; absl::string_view info = "verify if given HPKE public key is valid"; if (!EVP_HPKE_CTX_setup_sender( client_ctx.get(), reinterpret_cast<uint8_t*>(encapsulated_key.data()), &enc_len, encapsulated_key.size(), ohttp_key_config.GetHpkeKem(), ohttp_key_config.GetHpkeKdf(), ohttp_key_config.GetHpkeAead(), reinterpret_cast<const uint8_t*>(hpke_public_key.data()), hpke_public_key.size(), reinterpret_cast<const uint8_t*>(info.data()), info.size())) { return SslErrorAsStatus( "Failed to setup HPKE context with given public key param " "hpke_public_key."); } return absl::OkStatus(); } } ObliviousHttpClient::ObliviousHttpClient( std::string client_public_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config) : hpke_public_key_(std::move(client_public_key)), ohttp_key_config_(ohttp_key_config) {} absl::StatusOr<ObliviousHttpClient> ObliviousHttpClient::Create( absl::string_view hpke_public_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config) { if (hpke_public_key.empty()) { return absl::InvalidArgumentError("Invalid/Empty HPKE public key."); } auto is_valid_input = ValidateClientParameters(hpke_public_key, ohttp_key_config); if (!is_valid_input.ok()) { return absl::InvalidArgumentError( absl::StrCat("Invalid input received in method parameters. ", is_valid_input.message())); } return ObliviousHttpClient(std::string(hpke_public_key), ohttp_key_config); } absl::StatusOr<ObliviousHttpRequest> ObliviousHttpClient::CreateObliviousHttpRequest( std::string plaintext_data) const { return ObliviousHttpRequest::CreateClientObliviousRequest( std::move(plaintext_data), hpke_public_key_, ohttp_key_config_); } absl::StatusOr<ObliviousHttpResponse> ObliviousHttpClient::DecryptObliviousHttpResponse( std::string encrypted_data, ObliviousHttpRequest::Context& oblivious_http_request_context) const { return ObliviousHttpResponse::CreateClientObliviousResponse( std::move(encrypted_data), oblivious_http_request_context); } }
#include "quiche/oblivious_http/oblivious_http_client.h" #include <stdint.h> #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 "quiche/common/platform/api/quiche_test.h" #include "quiche/common/platform/api/quiche_thread.h" namespace quiche { std::string GetHpkePrivateKey() { absl::string_view hpke_key_hex = "b77431ecfa8f4cfc30d6e467aafa06944dffe28cb9dd1409e33a3045f5adc8a1"; std::string hpke_key_bytes; EXPECT_TRUE(absl::HexStringToBytes(hpke_key_hex, &hpke_key_bytes)); return hpke_key_bytes; } std::string GetHpkePublicKey() { absl::string_view public_key = "6d21cfe09fbea5122f9ebc2eb2a69fcc4f06408cd54aac934f012e76fcdcef62"; std::string public_key_bytes; EXPECT_TRUE(absl::HexStringToBytes(public_key, &public_key_bytes)); return public_key_bytes; } const ObliviousHttpHeaderKeyConfig GetOhttpKeyConfig(uint8_t key_id, uint16_t kem_id, uint16_t kdf_id, uint16_t aead_id) { auto ohttp_key_config = ObliviousHttpHeaderKeyConfig::Create(key_id, kem_id, kdf_id, aead_id); EXPECT_TRUE(ohttp_key_config.ok()); return ohttp_key_config.value(); } bssl::UniquePtr<EVP_HPKE_KEY> ConstructHpkeKey( absl::string_view hpke_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config) { bssl::UniquePtr<EVP_HPKE_KEY> bssl_hpke_key(EVP_HPKE_KEY_new()); EXPECT_NE(bssl_hpke_key, nullptr); EXPECT_TRUE(EVP_HPKE_KEY_init( bssl_hpke_key.get(), ohttp_key_config.GetHpkeKem(), reinterpret_cast<const uint8_t*>(hpke_key.data()), hpke_key.size())); return bssl_hpke_key; } TEST(ObliviousHttpClient, TestEncapsulate) { auto client = ObliviousHttpClient::Create( GetHpkePublicKey(), GetOhttpKeyConfig(8, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM)); ASSERT_TRUE(client.ok()); auto encrypted_req = client->CreateObliviousHttpRequest("test string 1"); ASSERT_TRUE(encrypted_req.ok()); auto serialized_encrypted_req = encrypted_req->EncapsulateAndSerialize(); ASSERT_FALSE(serialized_encrypted_req.empty()); } TEST(ObliviousHttpClient, TestEncryptingMultipleRequestsWithSingleInstance) { auto client = ObliviousHttpClient::Create( GetHpkePublicKey(), GetOhttpKeyConfig(1, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM)); ASSERT_TRUE(client.ok()); auto ohttp_req_1 = client->CreateObliviousHttpRequest("test string 1"); ASSERT_TRUE(ohttp_req_1.ok()); auto serialized_ohttp_req_1 = ohttp_req_1->EncapsulateAndSerialize(); ASSERT_FALSE(serialized_ohttp_req_1.empty()); auto ohttp_req_2 = client->CreateObliviousHttpRequest("test string 2"); ASSERT_TRUE(ohttp_req_2.ok()); auto serialized_ohttp_req_2 = ohttp_req_2->EncapsulateAndSerialize(); ASSERT_FALSE(serialized_ohttp_req_2.empty()); EXPECT_NE(serialized_ohttp_req_1, serialized_ohttp_req_2); } TEST(ObliviousHttpClient, TestInvalidHPKEKey) { EXPECT_EQ(ObliviousHttpClient::Create( "Invalid HPKE key", GetOhttpKeyConfig(50, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM)) .status() .code(), absl::StatusCode::kInvalidArgument); EXPECT_EQ(ObliviousHttpClient::Create( "", GetOhttpKeyConfig(50, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM)) .status() .code(), absl::StatusCode::kInvalidArgument); } TEST(ObliviousHttpClient, TestTwoSamePlaintextsWillGenerateDifferentEncryptedPayloads) { auto client = ObliviousHttpClient::Create( GetHpkePublicKey(), GetOhttpKeyConfig(1, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM)); ASSERT_TRUE(client.ok()); auto encrypted_request_1 = client->CreateObliviousHttpRequest("same plaintext"); ASSERT_TRUE(encrypted_request_1.ok()); auto serialized_encrypted_request_1 = encrypted_request_1->EncapsulateAndSerialize(); ASSERT_FALSE(serialized_encrypted_request_1.empty()); auto encrypted_request_2 = client->CreateObliviousHttpRequest("same plaintext"); ASSERT_TRUE(encrypted_request_2.ok()); auto serialized_encrypted_request_2 = encrypted_request_2->EncapsulateAndSerialize(); ASSERT_FALSE(serialized_encrypted_request_2.empty()); EXPECT_NE(serialized_encrypted_request_1, serialized_encrypted_request_2); } TEST(ObliviousHttpClient, TestObliviousResponseHandling) { auto ohttp_key_config = GetOhttpKeyConfig(1, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); auto encapsulate_req_on_client = ObliviousHttpRequest::CreateClientObliviousRequest( "test", GetHpkePublicKey(), ohttp_key_config); ASSERT_TRUE(encapsulate_req_on_client.ok()); auto decapsulate_req_on_gateway = ObliviousHttpRequest::CreateServerObliviousRequest( encapsulate_req_on_client->EncapsulateAndSerialize(), *(ConstructHpkeKey(GetHpkePrivateKey(), ohttp_key_config)), ohttp_key_config); ASSERT_TRUE(decapsulate_req_on_gateway.ok()); auto gateway_request_context = std::move(decapsulate_req_on_gateway.value()).ReleaseContext(); auto encapsulate_resp_on_gateway = ObliviousHttpResponse::CreateServerObliviousResponse( "test response", gateway_request_context); ASSERT_TRUE(encapsulate_resp_on_gateway.ok()); auto client = ObliviousHttpClient::Create(GetHpkePublicKey(), ohttp_key_config); ASSERT_TRUE(client.ok()); auto client_request_context = std::move(encapsulate_req_on_client.value()).ReleaseContext(); auto decapsulate_resp_on_client = client->DecryptObliviousHttpResponse( encapsulate_resp_on_gateway->EncapsulateAndSerialize(), client_request_context); ASSERT_TRUE(decapsulate_resp_on_client.ok()); EXPECT_EQ(decapsulate_resp_on_client->GetPlaintextData(), "test response"); } TEST(ObliviousHttpClient, DecryptResponseReceivedByTheClientUsingServersObliviousContext) { auto ohttp_key_config = GetOhttpKeyConfig(1, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); auto encapsulate_req_on_client = ObliviousHttpRequest::CreateClientObliviousRequest( "test", GetHpkePublicKey(), ohttp_key_config); ASSERT_TRUE(encapsulate_req_on_client.ok()); auto decapsulate_req_on_gateway = ObliviousHttpRequest::CreateServerObliviousRequest( encapsulate_req_on_client->EncapsulateAndSerialize(), *(ConstructHpkeKey(GetHpkePrivateKey(), ohttp_key_config)), ohttp_key_config); ASSERT_TRUE(decapsulate_req_on_gateway.ok()); auto gateway_request_context = std::move(decapsulate_req_on_gateway.value()).ReleaseContext(); auto encapsulate_resp_on_gateway = ObliviousHttpResponse::CreateServerObliviousResponse( "test response", gateway_request_context); ASSERT_TRUE(encapsulate_resp_on_gateway.ok()); auto client = ObliviousHttpClient::Create(GetHpkePublicKey(), ohttp_key_config); ASSERT_TRUE(client.ok()); auto decapsulate_resp_on_client = client->DecryptObliviousHttpResponse( encapsulate_resp_on_gateway->EncapsulateAndSerialize(), gateway_request_context); ASSERT_TRUE(decapsulate_resp_on_client.ok()); EXPECT_EQ(decapsulate_resp_on_client->GetPlaintextData(), "test response"); } TEST(ObliviousHttpClient, TestWithMultipleThreads) { class TestQuicheThread : public QuicheThread { public: TestQuicheThread(const ObliviousHttpClient& client, std::string request_payload, ObliviousHttpHeaderKeyConfig ohttp_key_config) : QuicheThread("client_thread"), client_(client), request_payload_(request_payload), ohttp_key_config_(ohttp_key_config) {} protected: void Run() override { auto encrypted_request = client_.CreateObliviousHttpRequest(request_payload_); ASSERT_TRUE(encrypted_request.ok()); ASSERT_FALSE(encrypted_request->EncapsulateAndSerialize().empty()); auto decapsulate_req_on_gateway = ObliviousHttpRequest::CreateServerObliviousRequest( encrypted_request->EncapsulateAndSerialize(), *(ConstructHpkeKey(GetHpkePrivateKey(), ohttp_key_config_)), ohttp_key_config_); ASSERT_TRUE(decapsulate_req_on_gateway.ok()); auto gateway_request_context = std::move(decapsulate_req_on_gateway.value()).ReleaseContext(); auto encapsulate_resp_on_gateway = ObliviousHttpResponse::CreateServerObliviousResponse( "test response", gateway_request_context); ASSERT_TRUE(encapsulate_resp_on_gateway.ok()); ASSERT_FALSE( encapsulate_resp_on_gateway->EncapsulateAndSerialize().empty()); auto client_request_context = std::move(encrypted_request.value()).ReleaseContext(); auto decrypted_response = client_.DecryptObliviousHttpResponse( encapsulate_resp_on_gateway->EncapsulateAndSerialize(), client_request_context); ASSERT_TRUE(decrypted_response.ok()); ASSERT_FALSE(decrypted_response->GetPlaintextData().empty()); } private: const ObliviousHttpClient& client_; std::string request_payload_; ObliviousHttpHeaderKeyConfig ohttp_key_config_; }; auto ohttp_key_config = GetOhttpKeyConfig(1, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); auto client = ObliviousHttpClient::Create(GetHpkePublicKey(), ohttp_key_config); TestQuicheThread t1(*client, "test request 1", ohttp_key_config); TestQuicheThread t2(*client, "test request 2", ohttp_key_config); t1.Start(); t2.Start(); t1.Join(); t2.Join(); } }
382
cpp
google/quiche
oblivious_http_gateway
quiche/oblivious_http/oblivious_http_gateway.cc
quiche/oblivious_http/oblivious_http_gateway_test.cc
#ifndef QUICHE_OBLIVIOUS_HTTP_OBLIVIOUS_HTTP_GATEWAY_H_ #define QUICHE_OBLIVIOUS_HTTP_OBLIVIOUS_HTTP_GATEWAY_H_ #include <memory> #include <string> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "openssl/base.h" #include "openssl/hpke.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/quiche_random.h" #include "quiche/oblivious_http/buffers/oblivious_http_request.h" #include "quiche/oblivious_http/buffers/oblivious_http_response.h" #include "quiche/oblivious_http/common/oblivious_http_header_key_config.h" namespace quiche { class QUICHE_EXPORT ObliviousHttpGateway { public: static absl::StatusOr<ObliviousHttpGateway> Create( absl::string_view hpke_private_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config, QuicheRandom* quiche_random = nullptr); ObliviousHttpGateway(ObliviousHttpGateway&& other) = default; ObliviousHttpGateway& operator=(ObliviousHttpGateway&& other) = default; ~ObliviousHttpGateway() = default; absl::StatusOr<ObliviousHttpRequest> DecryptObliviousHttpRequest( absl::string_view encrypted_data, absl::string_view request_label = ObliviousHttpHeaderKeyConfig::kOhttpRequestLabel) const; absl::StatusOr<ObliviousHttpResponse> CreateObliviousHttpResponse( std::string plaintext_data, ObliviousHttpRequest::Context& oblivious_http_request_context, absl::string_view response_label = ObliviousHttpHeaderKeyConfig::kOhttpResponseLabel) const; private: explicit ObliviousHttpGateway( bssl::UniquePtr<EVP_HPKE_KEY> recipient_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config, QuicheRandom* quiche_random); bssl::UniquePtr<EVP_HPKE_KEY> server_hpke_key_; ObliviousHttpHeaderKeyConfig ohttp_key_config_; QuicheRandom* quiche_random_; }; } #endif #include "quiche/oblivious_http/oblivious_http_gateway.h" #include <stdint.h> #include <memory> #include <string> #include <utility> #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "quiche/common/quiche_crypto_logging.h" #include "quiche/common/quiche_random.h" namespace quiche { ObliviousHttpGateway::ObliviousHttpGateway( bssl::UniquePtr<EVP_HPKE_KEY> recipient_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config, QuicheRandom* quiche_random) : server_hpke_key_(std::move(recipient_key)), ohttp_key_config_(ohttp_key_config), quiche_random_(quiche_random) {} absl::StatusOr<ObliviousHttpGateway> ObliviousHttpGateway::Create( absl::string_view hpke_private_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config, QuicheRandom* quiche_random) { if (hpke_private_key.empty()) { return absl::InvalidArgumentError("Invalid/Empty HPKE private key."); } bssl::UniquePtr<EVP_HPKE_KEY> recipient_key(EVP_HPKE_KEY_new()); if (recipient_key == nullptr) { return SslErrorAsStatus( "Failed to initialize ObliviousHttpGateway/Server's Key."); } if (!EVP_HPKE_KEY_init( recipient_key.get(), ohttp_key_config.GetHpkeKem(), reinterpret_cast<const uint8_t*>(hpke_private_key.data()), hpke_private_key.size())) { return SslErrorAsStatus("Failed to import HPKE private key."); } if (quiche_random == nullptr) quiche_random = QuicheRandom::GetInstance(); return ObliviousHttpGateway(std::move(recipient_key), ohttp_key_config, quiche_random); } absl::StatusOr<ObliviousHttpRequest> ObliviousHttpGateway::DecryptObliviousHttpRequest( absl::string_view encrypted_data, absl::string_view request_label) const { return ObliviousHttpRequest::CreateServerObliviousRequest( encrypted_data, *(server_hpke_key_), ohttp_key_config_, request_label); } absl::StatusOr<ObliviousHttpResponse> ObliviousHttpGateway::CreateObliviousHttpResponse( std::string plaintext_data, ObliviousHttpRequest::Context& oblivious_http_request_context, absl::string_view response_label) const { return ObliviousHttpResponse::CreateServerObliviousResponse( std::move(plaintext_data), oblivious_http_request_context, response_label, quiche_random_); } }
#include "quiche/oblivious_http/oblivious_http_gateway.h" #include <stdint.h> #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 "quiche/common/platform/api/quiche_test.h" #include "quiche/common/platform/api/quiche_thread.h" #include "quiche/common/quiche_random.h" #include "quiche/oblivious_http/buffers/oblivious_http_request.h" namespace quiche { namespace { std::string GetHpkePrivateKey() { absl::string_view hpke_key_hex = "b77431ecfa8f4cfc30d6e467aafa06944dffe28cb9dd1409e33a3045f5adc8a1"; std::string hpke_key_bytes; EXPECT_TRUE(absl::HexStringToBytes(hpke_key_hex, &hpke_key_bytes)); return hpke_key_bytes; } std::string GetHpkePublicKey() { absl::string_view public_key = "6d21cfe09fbea5122f9ebc2eb2a69fcc4f06408cd54aac934f012e76fcdcef62"; std::string public_key_bytes; EXPECT_TRUE(absl::HexStringToBytes(public_key, &public_key_bytes)); return public_key_bytes; } const ObliviousHttpHeaderKeyConfig GetOhttpKeyConfig(uint8_t key_id, uint16_t kem_id, uint16_t kdf_id, uint16_t aead_id) { auto ohttp_key_config = ObliviousHttpHeaderKeyConfig::Create(key_id, kem_id, kdf_id, aead_id); EXPECT_TRUE(ohttp_key_config.ok()); return std::move(ohttp_key_config.value()); } TEST(ObliviousHttpGateway, TestProvisioningKeyAndDecapsulate) { constexpr absl::string_view kX25519SecretKey = "3c168975674b2fa8e465970b79c8dcf09f1c741626480bd4c6162fc5b6a98e1a"; std::string x25519_secret_key_bytes; ASSERT_TRUE( absl::HexStringToBytes(kX25519SecretKey, &x25519_secret_key_bytes)); auto instance = ObliviousHttpGateway::Create( x25519_secret_key_bytes, GetOhttpKeyConfig( 1, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_128_GCM)); constexpr absl::string_view kEncapsulatedRequest = "010020000100014b28f881333e7c164ffc499ad9796f877f4e1051ee6d31bad19dec96c2" "08b4726374e469135906992e1268c594d2a10c695d858c40a026e7965e7d86b83dd440b2" "c0185204b4d63525"; std::string encapsulated_request_bytes; ASSERT_TRUE(absl::HexStringToBytes(kEncapsulatedRequest, &encapsulated_request_bytes)); auto decrypted_req = instance->DecryptObliviousHttpRequest(encapsulated_request_bytes); ASSERT_TRUE(decrypted_req.ok()); ASSERT_FALSE(decrypted_req->GetPlaintextData().empty()); } TEST(ObliviousHttpGateway, TestDecryptingMultipleRequestsWithSingleInstance) { auto instance = ObliviousHttpGateway::Create( GetHpkePrivateKey(), GetOhttpKeyConfig(1, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM)); absl::string_view encrypted_req_1 = "010020000100025f20b60306b61ad9ecad389acd752ca75c4e2969469809fe3d84aae137" "f73e4ccfe9ba71f12831fdce6c8202fbd38a84c5d8a73ac4c8ea6c10592594845f"; std::string encrypted_req_1_bytes; ASSERT_TRUE(absl::HexStringToBytes(encrypted_req_1, &encrypted_req_1_bytes)); auto decapsulated_req_1 = instance->DecryptObliviousHttpRequest(encrypted_req_1_bytes); ASSERT_TRUE(decapsulated_req_1.ok()); ASSERT_FALSE(decapsulated_req_1->GetPlaintextData().empty()); absl::string_view encrypted_req_2 = "01002000010002285ebc2fcad72cc91b378050cac29a62feea9cd97829335ee9fc87e672" "4fa13ff2efdff620423d54225d3099088e7b32a5165f805a5d922918865a0a447a"; std::string encrypted_req_2_bytes; ASSERT_TRUE(absl::HexStringToBytes(encrypted_req_2, &encrypted_req_2_bytes)); auto decapsulated_req_2 = instance->DecryptObliviousHttpRequest(encrypted_req_2_bytes); ASSERT_TRUE(decapsulated_req_2.ok()); ASSERT_FALSE(decapsulated_req_2->GetPlaintextData().empty()); } TEST(ObliviousHttpGateway, TestInvalidHPKEKey) { EXPECT_EQ(ObliviousHttpGateway::Create( "Invalid HPKE key", GetOhttpKeyConfig(70, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM)) .status() .code(), absl::StatusCode::kInternal); EXPECT_EQ(ObliviousHttpGateway::Create( "", GetOhttpKeyConfig(70, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM)) .status() .code(), absl::StatusCode::kInvalidArgument); } TEST(ObliviousHttpGateway, TestObliviousResponseHandling) { auto ohttp_key_config = GetOhttpKeyConfig(3, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); auto instance = ObliviousHttpGateway::Create(GetHpkePrivateKey(), ohttp_key_config); ASSERT_TRUE(instance.ok()); auto encapsualte_request_on_client = ObliviousHttpRequest::CreateClientObliviousRequest( "test", GetHpkePublicKey(), ohttp_key_config); ASSERT_TRUE(encapsualte_request_on_client.ok()); auto decapsulated_req_on_server = instance->DecryptObliviousHttpRequest( encapsualte_request_on_client->EncapsulateAndSerialize()); ASSERT_TRUE(decapsulated_req_on_server.ok()); auto server_request_context = std::move(decapsulated_req_on_server.value()).ReleaseContext(); auto encapsulate_resp_on_gateway = instance->CreateObliviousHttpResponse( "some response", server_request_context); ASSERT_TRUE(encapsulate_resp_on_gateway.ok()); ASSERT_FALSE(encapsulate_resp_on_gateway->EncapsulateAndSerialize().empty()); } TEST(ObliviousHttpGateway, TestHandlingMultipleResponsesForMultipleRequestsWithSingleInstance) { auto instance = ObliviousHttpGateway::Create( GetHpkePrivateKey(), GetOhttpKeyConfig(1, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM), QuicheRandom::GetInstance()); std::string encrypted_request_1_bytes; ASSERT_TRUE( absl::HexStringToBytes("010020000100025f20b60306b61ad9ecad389acd752ca75c4" "e2969469809fe3d84aae137" "f73e4ccfe9ba71f12831fdce6c8202fbd38a84c5d8a73ac4c" "8ea6c10592594845f", &encrypted_request_1_bytes)); auto decrypted_request_1 = instance->DecryptObliviousHttpRequest(encrypted_request_1_bytes); ASSERT_TRUE(decrypted_request_1.ok()); std::string encrypted_request_2_bytes; ASSERT_TRUE( absl::HexStringToBytes("01002000010002285ebc2fcad72cc91b378050cac29a62fee" "a9cd97829335ee9fc87e672" "4fa13ff2efdff620423d54225d3099088e7b32a5165f805a5" "d922918865a0a447a", &encrypted_request_2_bytes)); auto decrypted_request_2 = instance->DecryptObliviousHttpRequest(encrypted_request_2_bytes); ASSERT_TRUE(decrypted_request_2.ok()); auto oblivious_request_context_1 = std::move(decrypted_request_1.value()).ReleaseContext(); auto encrypted_response_1 = instance->CreateObliviousHttpResponse( "test response 1", oblivious_request_context_1); ASSERT_TRUE(encrypted_response_1.ok()); ASSERT_FALSE(encrypted_response_1->EncapsulateAndSerialize().empty()); auto oblivious_request_context_2 = std::move(decrypted_request_2.value()).ReleaseContext(); auto encrypted_response_2 = instance->CreateObliviousHttpResponse( "test response 2", oblivious_request_context_2); ASSERT_TRUE(encrypted_response_2.ok()); ASSERT_FALSE(encrypted_response_2->EncapsulateAndSerialize().empty()); } TEST(ObliviousHttpGateway, TestWithMultipleThreads) { class TestQuicheThread : public QuicheThread { public: TestQuicheThread(const ObliviousHttpGateway& gateway_receiver, std::string request_payload, std::string response_payload) : QuicheThread("gateway_thread"), gateway_receiver_(gateway_receiver), request_payload_(request_payload), response_payload_(response_payload) {} protected: void Run() override { auto decrypted_request = gateway_receiver_.DecryptObliviousHttpRequest(request_payload_); ASSERT_TRUE(decrypted_request.ok()); ASSERT_FALSE(decrypted_request->GetPlaintextData().empty()); auto gateway_request_context = std::move(decrypted_request.value()).ReleaseContext(); auto encrypted_response = gateway_receiver_.CreateObliviousHttpResponse( response_payload_, gateway_request_context); ASSERT_TRUE(encrypted_response.ok()); ASSERT_FALSE(encrypted_response->EncapsulateAndSerialize().empty()); } private: const ObliviousHttpGateway& gateway_receiver_; std::string request_payload_, response_payload_; }; auto gateway_receiver = ObliviousHttpGateway::Create( GetHpkePrivateKey(), GetOhttpKeyConfig(1, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM), QuicheRandom::GetInstance()); std::string request_payload_1; ASSERT_TRUE( absl::HexStringToBytes("010020000100025f20b60306b61ad9ecad389acd752ca75c4" "e2969469809fe3d84aae137" "f73e4ccfe9ba71f12831fdce6c8202fbd38a84c5d8a73ac4c" "8ea6c10592594845f", &request_payload_1)); TestQuicheThread t1(*gateway_receiver, request_payload_1, "test response 1"); std::string request_payload_2; ASSERT_TRUE( absl::HexStringToBytes("01002000010002285ebc2fcad72cc91b378050cac29a62fee" "a9cd97829335ee9fc87e672" "4fa13ff2efdff620423d54225d3099088e7b32a5165f805a5" "d922918865a0a447a", &request_payload_2)); TestQuicheThread t2(*gateway_receiver, request_payload_2, "test response 2"); t1.Start(); t2.Start(); t1.Join(); t2.Join(); } } }
383
cpp
google/quiche
oblivious_http_header_key_config
quiche/oblivious_http/common/oblivious_http_header_key_config.cc
quiche/oblivious_http/common/oblivious_http_header_key_config_test.cc
#ifndef QUICHE_OBLIVIOUS_HTTP_COMMON_OBLIVIOUS_HTTP_HEADER_KEY_CONFIG_H_ #define QUICHE_OBLIVIOUS_HTTP_COMMON_OBLIVIOUS_HTTP_HEADER_KEY_CONFIG_H_ #include <stdint.h> #include "absl/container/btree_map.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "openssl/base.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/quiche_data_reader.h" namespace quiche { class QUICHE_EXPORT ObliviousHttpHeaderKeyConfig { public: static constexpr absl::string_view kOhttpRequestLabel = "message/bhttp request"; static constexpr absl::string_view kOhttpResponseLabel = "message/bhttp response"; static constexpr uint32_t kHeaderLength = sizeof(uint8_t) + (3 * sizeof(uint16_t)); static constexpr absl::string_view kKeyHkdfInfo = "key"; static constexpr absl::string_view kNonceHkdfInfo = "nonce"; static absl::StatusOr<ObliviousHttpHeaderKeyConfig> Create(uint8_t key_id, uint16_t kem_id, uint16_t kdf_id, uint16_t aead_id); ObliviousHttpHeaderKeyConfig(const ObliviousHttpHeaderKeyConfig& other) = default; ObliviousHttpHeaderKeyConfig& operator=( const ObliviousHttpHeaderKeyConfig& other) = default; ObliviousHttpHeaderKeyConfig(ObliviousHttpHeaderKeyConfig&& other) = default; ObliviousHttpHeaderKeyConfig& operator=( ObliviousHttpHeaderKeyConfig&& other) = default; ~ObliviousHttpHeaderKeyConfig() = default; const EVP_HPKE_KEM* GetHpkeKem() const; const EVP_HPKE_KDF* GetHpkeKdf() const; const EVP_HPKE_AEAD* GetHpkeAead() const; uint8_t GetKeyId() const { return key_id_; } uint16_t GetHpkeKemId() const { return kem_id_; } uint16_t GetHpkeKdfId() const { return kdf_id_; } uint16_t GetHpkeAeadId() const { return aead_id_; } std::string SerializeRecipientContextInfo( absl::string_view request_label = ObliviousHttpHeaderKeyConfig::kOhttpRequestLabel) const; absl::Status ParseOhttpPayloadHeader(absl::string_view payload_bytes) const; absl::Status ParseOhttpPayloadHeader(QuicheDataReader& reader) const; static absl::StatusOr<uint8_t> ParseKeyIdFromObliviousHttpRequestPayload( absl::string_view payload_bytes); std::string SerializeOhttpPayloadHeader() const; private: explicit ObliviousHttpHeaderKeyConfig(uint8_t key_id, uint16_t kem_id, uint16_t kdf_id, uint16_t aead_id); absl::Status ValidateKeyConfig() const; uint8_t key_id_; uint16_t kem_id_; uint16_t kdf_id_; uint16_t aead_id_; }; class QUICHE_EXPORT ObliviousHttpKeyConfigs { public: struct SymmetricAlgorithmsConfig { uint16_t kdf_id; uint16_t aead_id; bool operator==(const SymmetricAlgorithmsConfig& other) const { return kdf_id == other.kdf_id && aead_id == other.aead_id; } template <typename H> friend H AbslHashValue(H h, const SymmetricAlgorithmsConfig& sym_alg_cfg) { return H::combine(std::move(h), sym_alg_cfg.kdf_id, sym_alg_cfg.aead_id); } }; struct OhttpKeyConfig { uint8_t key_id; uint16_t kem_id; std::string public_key; absl::flat_hash_set<SymmetricAlgorithmsConfig> symmetric_algorithms; bool operator==(const OhttpKeyConfig& other) const { return key_id == other.key_id && kem_id == other.kem_id && public_key == other.public_key && symmetric_algorithms == other.symmetric_algorithms; } template <typename H> friend H AbslHashValue(H h, const OhttpKeyConfig& ohttp_key_cfg) { return H::combine(std::move(h), ohttp_key_cfg.key_id, ohttp_key_cfg.kem_id, ohttp_key_cfg.public_key, ohttp_key_cfg.symmetric_algorithms); } }; static absl::StatusOr<ObliviousHttpKeyConfigs> ParseConcatenatedKeys( absl::string_view key_configs); static absl::StatusOr<ObliviousHttpKeyConfigs> Create( absl::flat_hash_set<OhttpKeyConfig> ohttp_key_configs); static absl::StatusOr<ObliviousHttpKeyConfigs> Create( const ObliviousHttpHeaderKeyConfig& single_key_config, absl::string_view public_key); absl::StatusOr<std::string> GenerateConcatenatedKeys() const; int NumKeys() const { return public_keys_.size(); } ObliviousHttpHeaderKeyConfig PreferredConfig() const; absl::StatusOr<absl::string_view> GetPublicKeyForId(uint8_t key_id) const; private: using PublicKeyMap = absl::flat_hash_map<uint8_t, std::string>; using ConfigMap = absl::btree_map<uint8_t, std::vector<ObliviousHttpHeaderKeyConfig>, std::greater<uint8_t>>; ObliviousHttpKeyConfigs(ConfigMap cm, PublicKeyMap km) : configs_(std::move(cm)), public_keys_(std::move(km)) {} static absl::Status ReadSingleKeyConfig(QuicheDataReader& reader, ConfigMap& configs, PublicKeyMap& keys); const ConfigMap configs_; const PublicKeyMap public_keys_; }; } #endif #include "quiche/oblivious_http/common/oblivious_http_header_key_config.h" #include <algorithm> #include <cstdint> #include <functional> #include <string> #include <utility> #include <vector> #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "openssl/base.h" #include "openssl/hpke.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_data_writer.h" #include "quiche/common/quiche_endian.h" namespace quiche { namespace { constexpr size_t kSizeOfHpkeKemId = 2; constexpr size_t kSizeOfSymmetricAlgorithmHpkeKdfId = 2; constexpr size_t kSizeOfSymmetricAlgorithmHpkeAeadId = 2; absl::StatusOr<const EVP_HPKE_KEM*> CheckKemId(uint16_t kem_id) { switch (kem_id) { case EVP_HPKE_DHKEM_X25519_HKDF_SHA256: return EVP_hpke_x25519_hkdf_sha256(); default: return absl::UnimplementedError("No support for this KEM ID."); } } absl::StatusOr<const EVP_HPKE_KDF*> CheckKdfId(uint16_t kdf_id) { switch (kdf_id) { case EVP_HPKE_HKDF_SHA256: return EVP_hpke_hkdf_sha256(); default: return absl::UnimplementedError("No support for this KDF ID."); } } absl::StatusOr<const EVP_HPKE_AEAD*> CheckAeadId(uint16_t aead_id) { switch (aead_id) { case EVP_HPKE_AES_128_GCM: return EVP_hpke_aes_128_gcm(); case EVP_HPKE_AES_256_GCM: return EVP_hpke_aes_256_gcm(); case EVP_HPKE_CHACHA20_POLY1305: return EVP_hpke_chacha20_poly1305(); default: return absl::UnimplementedError("No support for this AEAD ID."); } } } ObliviousHttpHeaderKeyConfig::ObliviousHttpHeaderKeyConfig(uint8_t key_id, uint16_t kem_id, uint16_t kdf_id, uint16_t aead_id) : key_id_(key_id), kem_id_(kem_id), kdf_id_(kdf_id), aead_id_(aead_id) {} absl::StatusOr<ObliviousHttpHeaderKeyConfig> ObliviousHttpHeaderKeyConfig::Create(uint8_t key_id, uint16_t kem_id, uint16_t kdf_id, uint16_t aead_id) { ObliviousHttpHeaderKeyConfig instance(key_id, kem_id, kdf_id, aead_id); auto is_config_ok = instance.ValidateKeyConfig(); if (!is_config_ok.ok()) { return is_config_ok; } return instance; } absl::Status ObliviousHttpHeaderKeyConfig::ValidateKeyConfig() const { auto supported_kem = CheckKemId(kem_id_); if (!supported_kem.ok()) { return absl::InvalidArgumentError( absl::StrCat("Unsupported KEM ID:", kem_id_)); } auto supported_kdf = CheckKdfId(kdf_id_); if (!supported_kdf.ok()) { return absl::InvalidArgumentError( absl::StrCat("Unsupported KDF ID:", kdf_id_)); } auto supported_aead = CheckAeadId(aead_id_); if (!supported_aead.ok()) { return absl::InvalidArgumentError( absl::StrCat("Unsupported AEAD ID:", aead_id_)); } return absl::OkStatus(); } const EVP_HPKE_KEM* ObliviousHttpHeaderKeyConfig::GetHpkeKem() const { auto kem = CheckKemId(kem_id_); QUICHE_CHECK_OK(kem.status()); return kem.value(); } const EVP_HPKE_KDF* ObliviousHttpHeaderKeyConfig::GetHpkeKdf() const { auto kdf = CheckKdfId(kdf_id_); QUICHE_CHECK_OK(kdf.status()); return kdf.value(); } const EVP_HPKE_AEAD* ObliviousHttpHeaderKeyConfig::GetHpkeAead() const { auto aead = CheckAeadId(aead_id_); QUICHE_CHECK_OK(aead.status()); return aead.value(); } std::string ObliviousHttpHeaderKeyConfig::SerializeRecipientContextInfo( absl::string_view request_label) const { uint8_t zero_byte = 0x00; int buf_len = request_label.size() + kHeaderLength + sizeof(zero_byte); std::string info(buf_len, '\0'); QuicheDataWriter writer(info.size(), info.data()); QUICHE_CHECK(writer.WriteStringPiece(request_label)); QUICHE_CHECK(writer.WriteUInt8(zero_byte)); QUICHE_CHECK(writer.WriteUInt8(key_id_)); QUICHE_CHECK(writer.WriteUInt16(kem_id_)); QUICHE_CHECK(writer.WriteUInt16(kdf_id_)); QUICHE_CHECK(writer.WriteUInt16(aead_id_)); return info; } absl::Status ObliviousHttpHeaderKeyConfig::ParseOhttpPayloadHeader( absl::string_view payload_bytes) const { if (payload_bytes.empty()) { return absl::InvalidArgumentError("Empty request payload."); } QuicheDataReader reader(payload_bytes); return ParseOhttpPayloadHeader(reader); } absl::Status ObliviousHttpHeaderKeyConfig::ParseOhttpPayloadHeader( QuicheDataReader& reader) const { uint8_t key_id; if (!reader.ReadUInt8(&key_id)) { return absl::InvalidArgumentError("Failed to read key_id from header."); } if (key_id != key_id_) { return absl::InvalidArgumentError( absl::StrCat("KeyID in request:", static_cast<uint16_t>(key_id), " doesn't match with server's public key " "configuration KeyID:", static_cast<uint16_t>(key_id_))); } uint16_t kem_id; if (!reader.ReadUInt16(&kem_id)) { return absl::InvalidArgumentError("Failed to read kem_id from header."); } if (kem_id != kem_id_) { return absl::InvalidArgumentError( absl::StrCat("Received Invalid kemID:", kem_id, " Expected:", kem_id_)); } uint16_t kdf_id; if (!reader.ReadUInt16(&kdf_id)) { return absl::InvalidArgumentError("Failed to read kdf_id from header."); } if (kdf_id != kdf_id_) { return absl::InvalidArgumentError( absl::StrCat("Received Invalid kdfID:", kdf_id, " Expected:", kdf_id_)); } uint16_t aead_id; if (!reader.ReadUInt16(&aead_id)) { return absl::InvalidArgumentError("Failed to read aead_id from header."); } if (aead_id != aead_id_) { return absl::InvalidArgumentError(absl::StrCat( "Received Invalid aeadID:", aead_id, " Expected:", aead_id_)); } return absl::OkStatus(); } absl::StatusOr<uint8_t> ObliviousHttpHeaderKeyConfig::ParseKeyIdFromObliviousHttpRequestPayload( absl::string_view payload_bytes) { if (payload_bytes.empty()) { return absl::InvalidArgumentError("Empty request payload."); } QuicheDataReader reader(payload_bytes); uint8_t key_id; if (!reader.ReadUInt8(&key_id)) { return absl::InvalidArgumentError("Failed to read key_id from payload."); } return key_id; } std::string ObliviousHttpHeaderKeyConfig::SerializeOhttpPayloadHeader() const { int buf_len = sizeof(key_id_) + sizeof(kem_id_) + sizeof(kdf_id_) + sizeof(aead_id_); std::string hdr(buf_len, '\0'); QuicheDataWriter writer(hdr.size(), hdr.data()); QUICHE_CHECK(writer.WriteUInt8(key_id_)); QUICHE_CHECK(writer.WriteUInt16(kem_id_)); QUICHE_CHECK(writer.WriteUInt16(kdf_id_)); QUICHE_CHECK(writer.WriteUInt16(aead_id_)); return hdr; } namespace { absl::StatusOr<uint16_t> KeyLength(uint16_t kem_id) { auto supported_kem = CheckKemId(kem_id); if (!supported_kem.ok()) { return absl::InvalidArgumentError(absl::StrCat( "Unsupported KEM ID:", kem_id, ". public key length is unknown.")); } return EVP_HPKE_KEM_public_key_len(supported_kem.value()); } absl::StatusOr<std::string> SerializeOhttpKeyWithPublicKey( uint8_t key_id, absl::string_view public_key, const std::vector<ObliviousHttpHeaderKeyConfig>& ohttp_configs) { auto ohttp_config = ohttp_configs[0]; static_assert(sizeof(ohttp_config.GetHpkeKemId()) == kSizeOfHpkeKemId && sizeof(ohttp_config.GetHpkeKdfId()) == kSizeOfSymmetricAlgorithmHpkeKdfId && sizeof(ohttp_config.GetHpkeAeadId()) == kSizeOfSymmetricAlgorithmHpkeAeadId, "Size of HPKE IDs should match RFC specification."); uint16_t symmetric_algs_length = ohttp_configs.size() * (kSizeOfSymmetricAlgorithmHpkeKdfId + kSizeOfSymmetricAlgorithmHpkeAeadId); int buf_len = sizeof(key_id) + kSizeOfHpkeKemId + public_key.size() + sizeof(symmetric_algs_length) + symmetric_algs_length; std::string ohttp_key_configuration(buf_len, '\0'); QuicheDataWriter writer(ohttp_key_configuration.size(), ohttp_key_configuration.data()); if (!writer.WriteUInt8(key_id)) { return absl::InternalError("Failed to serialize OHTTP key.[key_id]"); } if (!writer.WriteUInt16(ohttp_config.GetHpkeKemId())) { return absl::InternalError( "Failed to serialize OHTTP key.[kem_id]"); } if (!writer.WriteStringPiece(public_key)) { return absl::InternalError( "Failed to serialize OHTTP key.[public_key]"); } if (!writer.WriteUInt16(symmetric_algs_length)) { return absl::InternalError( "Failed to serialize OHTTP key.[symmetric_algs_length]"); } for (const auto& item : ohttp_configs) { if (item.GetHpkeKemId() != ohttp_config.GetHpkeKemId()) { QUICHE_BUG(ohttp_key_configs_builder_parser) << "ObliviousHttpKeyConfigs object cannot hold ConfigMap of " "different KEM IDs:[ " << item.GetHpkeKemId() << "," << ohttp_config.GetHpkeKemId() << " ]for a given key_id:" << static_cast<uint16_t>(key_id); } if (!writer.WriteUInt16(item.GetHpkeKdfId())) { return absl::InternalError( "Failed to serialize OHTTP key.[kdf_id]"); } if (!writer.WriteUInt16(item.GetHpkeAeadId())) { return absl::InternalError( "Failed to serialize OHTTP key.[aead_id]"); } } QUICHE_DCHECK_EQ(writer.remaining(), 0u); return ohttp_key_configuration; } std::string GetDebugStringForFailedKeyConfig( const ObliviousHttpKeyConfigs::OhttpKeyConfig& failed_key_config) { std::string debug_string = "[ "; absl::StrAppend(&debug_string, "key_id:", static_cast<uint16_t>(failed_key_config.key_id), " , kem_id:", failed_key_config.kem_id, ". Printing HEX formatted public_key:", absl::BytesToHexString(failed_key_config.public_key)); absl::StrAppend(&debug_string, ", symmetric_algorithms: { "); for (const auto& symmetric_config : failed_key_config.symmetric_algorithms) { absl::StrAppend(&debug_string, "{kdf_id: ", symmetric_config.kdf_id, ", aead_id:", symmetric_config.aead_id, " }"); } absl::StrAppend(&debug_string, " } ]"); return debug_string; } absl::Status StoreKeyConfigIfValid( ObliviousHttpKeyConfigs::OhttpKeyConfig key_config, absl::btree_map<uint8_t, std::vector<ObliviousHttpHeaderKeyConfig>, std::greater<uint8_t>>& configs, absl::flat_hash_map<uint8_t, std::string>& keys) { if (!CheckKemId(key_config.kem_id).ok() || key_config.public_key.size() != KeyLength(key_config.kem_id).value()) { QUICHE_LOG(ERROR) << "Failed to process: " << GetDebugStringForFailedKeyConfig(key_config); return absl::InvalidArgumentError( absl::StrCat("Invalid key_config! [KEM ID:", key_config.kem_id, "]")); } for (const auto& symmetric_config : key_config.symmetric_algorithms) { if (!CheckKdfId(symmetric_config.kdf_id).ok() || !CheckAeadId(symmetric_config.aead_id).ok()) { QUICHE_LOG(ERROR) << "Failed to process: " << GetDebugStringForFailedKeyConfig(key_config); return absl::InvalidArgumentError( absl::StrCat("Invalid key_config! [KDF ID:", symmetric_config.kdf_id, ", AEAD ID:", symmetric_config.aead_id, "]")); } auto ohttp_config = ObliviousHttpHeaderKeyConfig::Create( key_config.key_id, key_config.kem_id, symmetric_config.kdf_id, symmetric_config.aead_id); if (ohttp_config.ok()) { configs[key_config.key_id].emplace_back(std::move(ohttp_config.value())); } } keys.emplace(key_config.key_id, std::move(key_config.public_key)); return absl::OkStatus(); } } absl::StatusOr<ObliviousHttpKeyConfigs> ObliviousHttpKeyConfigs::ParseConcatenatedKeys(absl::string_view key_config) { ConfigMap configs; PublicKeyMap keys; auto reader = QuicheDataReader(key_config); while (!reader.IsDoneReading()) { absl::Status status = ReadSingleKeyConfig(reader, configs, keys); if (!status.ok()) return status; } return ObliviousHttpKeyConfigs(std::move(configs), std::move(keys)); } absl::StatusOr<ObliviousHttpKeyConfigs> ObliviousHttpKeyConfigs::Create( absl::flat_hash_set<ObliviousHttpKeyConfigs::OhttpKeyConfig> ohttp_key_configs) { if (ohttp_key_configs.empty()) { return absl::InvalidArgumentError("Empty input."); } ConfigMap configs_map; PublicKeyMap keys_map; for (auto& ohttp_key_config : ohttp_key_configs) { auto result = StoreKeyConfigIfValid(std::move(ohttp_key_config), configs_map, keys_map); if (!result.ok()) { return result; } } auto oblivious_configs = ObliviousHttpKeyConfigs(std::move(configs_map), std::move(keys_map)); return oblivious_configs; } absl::StatusOr<ObliviousHttpKeyConfigs> ObliviousHttpKeyConfigs::Create( const ObliviousHttpHeaderKeyConfig& single_key_config, absl::string_view public_key) { if (public_key.empty()) { return absl::InvalidArgumentError("Empty input."); } if (auto key_length = KeyLength(single_key_config.GetHpkeKemId()); public_key.size() != key_length.value()) { return absl::InvalidArgumentError(absl::StrCat( "Invalid key. Key size mismatch. Expected:", key_length.value(), " Actual:", public_key.size())); } ConfigMap configs; PublicKeyMap keys; uint8_t key_id = single_key_config.GetKeyId(); keys.emplace(key_id, public_key); configs[key_id].emplace_back(std::move(single_key_config)); return ObliviousHttpKeyConfigs(std::move(configs), std::move(keys)); } absl::StatusOr<std::string> ObliviousHttpKeyConfigs::GenerateConcatenatedKeys() const { std::string concatenated_keys; for (const auto& [key_id, ohttp_configs] : configs_) { auto key = public_keys_.find(key_id); if (key == public_keys_.end()) { return absl::InternalError( "Failed to serialize. No public key found for key_id"); } auto serialized = SerializeOhttpKeyWithPublicKey(key_id, key->second, ohttp_configs); if (!serialized.ok()) { return absl::InternalError("Failed to serialize OHTTP key configs."); } absl::StrAppend(&concatenated_keys, serialized.value()); } return concatenated_keys; } ObliviousHttpHeaderKeyConfig ObliviousHttpKeyConfigs::PreferredConfig() const { return configs_.begin()->second.front(); } absl::StatusOr<absl::string_view> ObliviousHttpKeyConfigs::GetPublicKeyForId( uint8_t key_id) const { auto key = public_keys_.find(key_id); if (key == public_keys_.end()) { return absl::NotFoundError("No public key found for key_id"); } return key->second; } absl::Status ObliviousHttpKeyConfigs::ReadSingleKeyConfig( QuicheDataReader& reader, ConfigMap& configs, PublicKeyMap& keys) { uint8_t key_id; uint16_t kem_id; if (!reader.ReadUInt8(&key_id) || !reader.ReadUInt16(&kem_id)) { return absl::InvalidArgumentError("Invalid key_config!"); } auto maybe_key_length = KeyLength(kem_id); if (!maybe_key_length.ok()) { return maybe_key_length.status(); } const int key_length = maybe_key_length.value(); std::string key_str(key_length, '\0'); if (!reader.ReadBytes(key_str.data(), key_length)) { return absl::InvalidArgumentError("Invalid key_config!"); } if (!keys.insert({key_id, std::move(key_str)}).second) { return absl::InvalidArgumentError("Duplicate key_id's in key_config!"); } absl::string_view alg_bytes; if (!reader.ReadStringPiece16(&alg_bytes)) { return absl::InvalidArgumentError("Invalid key_config!"); } QuicheDataReader sub_reader(alg_bytes); while (!sub_reader.IsDoneReading()) { uint16_t kdf_id; uint16_t aead_id; if (!sub_reader.ReadUInt16(&kdf_id) || !sub_reader.ReadUInt16(&aead_id)) { return absl::InvalidArgumentError("Invalid key_config!"); } absl::StatusOr<ObliviousHttpHeaderKeyConfig> maybe_cfg = ObliviousHttpHeaderKeyConfig::Create(key_id, kem_id, kdf_id, aead_id); if (!maybe_cfg.ok()) { return maybe_cfg.status(); } configs[key_id].emplace_back(std::move(maybe_cfg.value())); } return absl::OkStatus(); } }
#include "quiche/oblivious_http/common/oblivious_http_header_key_config.h" #include <cstdint> #include <string> #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "openssl/hpke.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/quiche_data_writer.h" namespace quiche { namespace { using ::testing::AllOf; using ::testing::Property; using ::testing::StrEq; using ::testing::UnorderedElementsAre; using ::testing::UnorderedElementsAreArray; std::string BuildHeader(uint8_t key_id, uint16_t kem_id, uint16_t kdf_id, uint16_t aead_id) { int buf_len = sizeof(key_id) + sizeof(kem_id) + sizeof(kdf_id) + sizeof(aead_id); std::string hdr(buf_len, '\0'); QuicheDataWriter writer(hdr.size(), hdr.data()); EXPECT_TRUE(writer.WriteUInt8(key_id)); EXPECT_TRUE(writer.WriteUInt16(kem_id)); EXPECT_TRUE(writer.WriteUInt16(kdf_id)); EXPECT_TRUE(writer.WriteUInt16(aead_id)); return hdr; } std::string GetSerializedKeyConfig( ObliviousHttpKeyConfigs::OhttpKeyConfig& key_config) { uint16_t symmetric_algs_length = key_config.symmetric_algorithms.size() * (sizeof(key_config.symmetric_algorithms.cbegin()->kdf_id) + sizeof(key_config.symmetric_algorithms.cbegin()->aead_id)); int buf_len = sizeof(key_config.key_id) + sizeof(key_config.kem_id) + key_config.public_key.size() + sizeof(symmetric_algs_length) + symmetric_algs_length; std::string ohttp_key(buf_len, '\0'); QuicheDataWriter writer(ohttp_key.size(), ohttp_key.data()); EXPECT_TRUE(writer.WriteUInt8(key_config.key_id)); EXPECT_TRUE(writer.WriteUInt16(key_config.kem_id)); EXPECT_TRUE(writer.WriteStringPiece(key_config.public_key)); EXPECT_TRUE(writer.WriteUInt16(symmetric_algs_length)); for (const auto& symmetric_alg : key_config.symmetric_algorithms) { EXPECT_TRUE(writer.WriteUInt16(symmetric_alg.kdf_id)); EXPECT_TRUE(writer.WriteUInt16(symmetric_alg.aead_id)); } return ohttp_key; } TEST(ObliviousHttpHeaderKeyConfig, TestSerializeRecipientContextInfo) { uint8_t key_id = 3; uint16_t kem_id = EVP_HPKE_DHKEM_X25519_HKDF_SHA256; uint16_t kdf_id = EVP_HPKE_HKDF_SHA256; uint16_t aead_id = EVP_HPKE_AES_256_GCM; absl::string_view ohttp_req_label = "message/bhttp request"; std::string expected(ohttp_req_label); uint8_t zero_byte = 0x00; int buf_len = ohttp_req_label.size() + sizeof(zero_byte) + sizeof(key_id) + sizeof(kem_id) + sizeof(kdf_id) + sizeof(aead_id); expected.reserve(buf_len); expected.push_back(zero_byte); std::string ohttp_cfg(BuildHeader(key_id, kem_id, kdf_id, aead_id)); expected.insert(expected.end(), ohttp_cfg.begin(), ohttp_cfg.end()); auto instance = ObliviousHttpHeaderKeyConfig::Create(key_id, kem_id, kdf_id, aead_id); ASSERT_TRUE(instance.ok()); EXPECT_EQ(instance.value().SerializeRecipientContextInfo(), expected); } TEST(ObliviousHttpHeaderKeyConfig, TestValidKeyConfig) { auto valid_key_config = ObliviousHttpHeaderKeyConfig::Create( 2, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); ASSERT_TRUE(valid_key_config.ok()); } TEST(ObliviousHttpHeaderKeyConfig, TestInvalidKeyConfig) { auto invalid_kem = ObliviousHttpHeaderKeyConfig::Create( 3, 0, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); EXPECT_EQ(invalid_kem.status().code(), absl::StatusCode::kInvalidArgument); auto invalid_kdf = ObliviousHttpHeaderKeyConfig::Create( 3, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, 0, EVP_HPKE_AES_256_GCM); EXPECT_EQ(invalid_kdf.status().code(), absl::StatusCode::kInvalidArgument); auto invalid_aead = ObliviousHttpHeaderKeyConfig::Create( 3, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, 0); EXPECT_EQ(invalid_kdf.status().code(), absl::StatusCode::kInvalidArgument); } TEST(ObliviousHttpHeaderKeyConfig, TestParsingValidHeader) { auto instance = ObliviousHttpHeaderKeyConfig::Create( 5, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); ASSERT_TRUE(instance.ok()); std::string good_hdr(BuildHeader(5, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM)); ASSERT_TRUE(instance.value().ParseOhttpPayloadHeader(good_hdr).ok()); } TEST(ObliviousHttpHeaderKeyConfig, TestParsingInvalidHeader) { auto instance = ObliviousHttpHeaderKeyConfig::Create( 8, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); ASSERT_TRUE(instance.ok()); std::string keyid_mismatch_hdr( BuildHeader(0, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM)); EXPECT_EQ(instance.value().ParseOhttpPayloadHeader(keyid_mismatch_hdr).code(), absl::StatusCode::kInvalidArgument); std::string invalid_hpke_hdr(BuildHeader(8, 0, 0, 0)); EXPECT_EQ(instance.value().ParseOhttpPayloadHeader(invalid_hpke_hdr).code(), absl::StatusCode::kInvalidArgument); } TEST(ObliviousHttpHeaderKeyConfig, TestParsingKeyIdFromObliviousHttpRequest) { std::string key_id(sizeof(uint8_t), '\0'); QuicheDataWriter writer(key_id.size(), key_id.data()); EXPECT_TRUE(writer.WriteUInt8(99)); auto parsed_key_id = ObliviousHttpHeaderKeyConfig::ParseKeyIdFromObliviousHttpRequestPayload( key_id); ASSERT_TRUE(parsed_key_id.ok()); EXPECT_EQ(parsed_key_id.value(), 99); } TEST(ObliviousHttpHeaderKeyConfig, TestCopyable) { auto obj1 = ObliviousHttpHeaderKeyConfig::Create( 4, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); ASSERT_TRUE(obj1.ok()); auto copy_obj1_to_obj2 = obj1.value(); EXPECT_EQ(copy_obj1_to_obj2.kHeaderLength, obj1->kHeaderLength); EXPECT_EQ(copy_obj1_to_obj2.SerializeRecipientContextInfo(), obj1->SerializeRecipientContextInfo()); } TEST(ObliviousHttpHeaderKeyConfig, TestSerializeOhttpPayloadHeader) { auto instance = ObliviousHttpHeaderKeyConfig::Create( 7, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_128_GCM); ASSERT_TRUE(instance.ok()); EXPECT_EQ(instance->SerializeOhttpPayloadHeader(), BuildHeader(7, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_128_GCM)); } MATCHER_P(HasKeyId, id, "") { *result_listener << "has key_id=" << arg.GetKeyId(); return arg.GetKeyId() == id; } MATCHER_P(HasKemId, id, "") { *result_listener << "has kem_id=" << arg.GetHpkeKemId(); return arg.GetHpkeKemId() == id; } MATCHER_P(HasKdfId, id, "") { *result_listener << "has kdf_id=" << arg.GetHpkeKdfId(); return arg.GetHpkeKdfId() == id; } MATCHER_P(HasAeadId, id, "") { *result_listener << "has aead_id=" << arg.GetHpkeAeadId(); return arg.GetHpkeAeadId() == id; } TEST(ObliviousHttpKeyConfigs, SingleKeyConfig) { std::string key; ASSERT_TRUE(absl::HexStringToBytes( "4b0020f83e0a17cbdb18d2684dd2a9b087a43e5f3fa3fa27a049bc746a6e97a1e0244b00" "0400010002", &key)); auto configs = ObliviousHttpKeyConfigs::ParseConcatenatedKeys(key).value(); EXPECT_THAT(configs, Property(&ObliviousHttpKeyConfigs::NumKeys, 1)); EXPECT_THAT( configs.PreferredConfig(), AllOf(HasKeyId(0x4b), HasKemId(EVP_HPKE_DHKEM_X25519_HKDF_SHA256), HasKdfId(EVP_HPKE_HKDF_SHA256), HasAeadId(EVP_HPKE_AES_256_GCM))); std::string expected_public_key; ASSERT_TRUE(absl::HexStringToBytes( "f83e0a17cbdb18d2684dd2a9b087a43e5f3fa3fa27a049bc746a6e97a1e0244b", &expected_public_key)); EXPECT_THAT( configs.GetPublicKeyForId(configs.PreferredConfig().GetKeyId()).value(), StrEq(expected_public_key)); } TEST(ObliviousHttpKeyConfigs, TwoSimilarKeyConfigs) { std::string key; ASSERT_TRUE(absl::HexStringToBytes( "4b0020f83e0a17cbdb18d2684dd2a9b087a43e5f3fa3fa27a049bc746a6e97a1e0244b00" "0400010002" "4f0020f83e0a17cbdb18d2684dd2a9b087a43e5f3fa3fa27a049bc746a6e97a1e0244b00" "0400010001", &key)); EXPECT_THAT(ObliviousHttpKeyConfigs::ParseConcatenatedKeys(key).value(), Property(&ObliviousHttpKeyConfigs::NumKeys, 2)); EXPECT_THAT( ObliviousHttpKeyConfigs::ParseConcatenatedKeys(key)->PreferredConfig(), AllOf(HasKeyId(0x4f), HasKemId(EVP_HPKE_DHKEM_X25519_HKDF_SHA256), HasKdfId(EVP_HPKE_HKDF_SHA256), HasAeadId(EVP_HPKE_AES_128_GCM))); } TEST(ObliviousHttpKeyConfigs, RFCExample) { std::string key; ASSERT_TRUE(absl::HexStringToBytes( "01002031e1f05a740102115220e9af918f738674aec95f54db6e04eb705aae8e79815500" "080001000100010003", &key)); auto configs = ObliviousHttpKeyConfigs::ParseConcatenatedKeys(key).value(); EXPECT_THAT(configs, Property(&ObliviousHttpKeyConfigs::NumKeys, 1)); EXPECT_THAT( configs.PreferredConfig(), AllOf(HasKeyId(0x01), HasKemId(EVP_HPKE_DHKEM_X25519_HKDF_SHA256), HasKdfId(EVP_HPKE_HKDF_SHA256), HasAeadId(EVP_HPKE_AES_128_GCM))); std::string expected_public_key; ASSERT_TRUE(absl::HexStringToBytes( "31e1f05a740102115220e9af918f738674aec95f54db6e04eb705aae8e798155", &expected_public_key)); EXPECT_THAT( configs.GetPublicKeyForId(configs.PreferredConfig().GetKeyId()).value(), StrEq(expected_public_key)); } TEST(ObliviousHttpKeyConfigs, DuplicateKeyId) { std::string key; ASSERT_TRUE(absl::HexStringToBytes( "4b0020f83e0a17cbdb18d2684dd2a9b087a43e5f3fa3fa27a049bc746a6e97a1e0244b00" "0400010002" "4b0020f83e0a17cbdb18d2684dd2a9b087a43e5f3fa3fb27a049bc746a6e97a1e0244b00" "0400010001", &key)); EXPECT_FALSE(ObliviousHttpKeyConfigs::ParseConcatenatedKeys(key).ok()); } TEST(ObliviousHttpHeaderKeyConfigs, TestCreateWithSingleKeyConfig) { auto instance = ObliviousHttpHeaderKeyConfig::Create( 123, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_CHACHA20_POLY1305); EXPECT_TRUE(instance.ok()); std::string test_public_key( EVP_HPKE_KEM_public_key_len(instance->GetHpkeKem()), 'a'); auto configs = ObliviousHttpKeyConfigs::Create(instance.value(), test_public_key); EXPECT_TRUE(configs.ok()); auto serialized_key = configs->GenerateConcatenatedKeys(); EXPECT_TRUE(serialized_key.ok()); auto ohttp_configs = ObliviousHttpKeyConfigs::ParseConcatenatedKeys(serialized_key.value()); EXPECT_TRUE(ohttp_configs.ok()); ASSERT_EQ(ohttp_configs->PreferredConfig().GetKeyId(), 123); auto parsed_public_key = ohttp_configs->GetPublicKeyForId(123); EXPECT_TRUE(parsed_public_key.ok()); EXPECT_EQ(parsed_public_key.value(), test_public_key); } TEST(ObliviousHttpHeaderKeyConfigs, TestCreateWithWithMultipleKeys) { std::string expected_preferred_public_key(32, 'b'); ObliviousHttpKeyConfigs::OhttpKeyConfig config1 = { 100, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, std::string(32, 'a'), {{EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM}}}; ObliviousHttpKeyConfigs::OhttpKeyConfig config2 = { 200, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, expected_preferred_public_key, {{EVP_HPKE_HKDF_SHA256, EVP_HPKE_CHACHA20_POLY1305}}}; auto configs = ObliviousHttpKeyConfigs::Create({config1, config2}); EXPECT_TRUE(configs.ok()); auto serialized_key = configs->GenerateConcatenatedKeys(); EXPECT_TRUE(serialized_key.ok()); ASSERT_EQ(serialized_key.value(), absl::StrCat(GetSerializedKeyConfig(config2), GetSerializedKeyConfig(config1))); auto ohttp_configs = ObliviousHttpKeyConfigs::ParseConcatenatedKeys(serialized_key.value()); EXPECT_TRUE(ohttp_configs.ok()); ASSERT_EQ(ohttp_configs->NumKeys(), 2); EXPECT_THAT(configs->PreferredConfig(), AllOf(HasKeyId(200), HasKemId(EVP_HPKE_DHKEM_X25519_HKDF_SHA256), HasKdfId(EVP_HPKE_HKDF_SHA256), HasAeadId(EVP_HPKE_CHACHA20_POLY1305))); auto parsed_preferred_public_key = ohttp_configs->GetPublicKeyForId( ohttp_configs->PreferredConfig().GetKeyId()); EXPECT_TRUE(parsed_preferred_public_key.ok()); EXPECT_EQ(parsed_preferred_public_key.value(), expected_preferred_public_key); } TEST(ObliviousHttpHeaderKeyConfigs, TestCreateWithInvalidConfigs) { ASSERT_EQ(ObliviousHttpKeyConfigs::Create({}).status().code(), absl::StatusCode::kInvalidArgument); ASSERT_EQ(ObliviousHttpKeyConfigs::Create( {{100, 2, std::string(32, 'a'), {{2, 3}, {4, 5}}}, {200, 6, std::string(32, 'b'), {{7, 8}, {9, 10}}}}) .status() .code(), absl::StatusCode::kInvalidArgument); EXPECT_EQ( ObliviousHttpKeyConfigs::Create( {{123, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, "invalid key length" , {{EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_128_GCM}}}}) .status() .code(), absl::StatusCode::kInvalidArgument); } TEST(ObliviousHttpHeaderKeyConfigs, TestCreateSingleKeyConfigWithInvalidConfig) { const auto sample_ohttp_hdr_config = ObliviousHttpHeaderKeyConfig::Create( 123, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_128_GCM); ASSERT_TRUE(sample_ohttp_hdr_config.ok()); ASSERT_EQ(ObliviousHttpKeyConfigs::Create(sample_ohttp_hdr_config.value(), "" ) .status() .code(), absl::StatusCode::kInvalidArgument); EXPECT_EQ(ObliviousHttpKeyConfigs::Create( sample_ohttp_hdr_config.value(), "invalid key length" ) .status() .code(), absl::StatusCode::kInvalidArgument); } TEST(ObliviousHttpHeaderKeyConfigs, TestHashImplWithObliviousStruct) { absl::flat_hash_set<ObliviousHttpKeyConfigs::SymmetricAlgorithmsConfig> symmetric_algs_set; for (int i = 0; i < 50; ++i) { symmetric_algs_set.insert({EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_128_GCM}); symmetric_algs_set.insert({EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM}); symmetric_algs_set.insert( {EVP_HPKE_HKDF_SHA256, EVP_HPKE_CHACHA20_POLY1305}); } ASSERT_EQ(symmetric_algs_set.size(), 3); EXPECT_THAT(symmetric_algs_set, UnorderedElementsAreArray< ObliviousHttpKeyConfigs::SymmetricAlgorithmsConfig>({ {EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_128_GCM}, {EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM}, {EVP_HPKE_HKDF_SHA256, EVP_HPKE_CHACHA20_POLY1305}, })); absl::flat_hash_set<ObliviousHttpKeyConfigs::OhttpKeyConfig> ohttp_key_configs_set; ObliviousHttpKeyConfigs::OhttpKeyConfig expected_key_config{ 100, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, std::string(32, 'c'), {{EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_128_GCM}, {EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM}}}; for (int i = 0; i < 50; ++i) { ohttp_key_configs_set.insert(expected_key_config); } ASSERT_EQ(ohttp_key_configs_set.size(), 1); EXPECT_THAT(ohttp_key_configs_set, UnorderedElementsAre(expected_key_config)); } } }
384
cpp
google/quiche
oblivious_http_request
quiche/oblivious_http/buffers/oblivious_http_request.cc
quiche/oblivious_http/buffers/oblivious_http_request_test.cc
#ifndef QUICHE_OBLIVIOUS_HTTP_BUFFERS_OBLIVIOUS_HTTP_REQUEST_H_ #define QUICHE_OBLIVIOUS_HTTP_BUFFERS_OBLIVIOUS_HTTP_REQUEST_H_ #include <memory> #include <optional> #include <string> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "openssl/hpke.h" #include "quiche/oblivious_http/common/oblivious_http_header_key_config.h" namespace quiche { class QUICHE_EXPORT ObliviousHttpRequest { public: class QUICHE_EXPORT Context { public: ~Context() = default; Context(Context&& other) = default; Context& operator=(Context&& other) = default; private: explicit Context(bssl::UniquePtr<EVP_HPKE_CTX> hpke_context, std::string encapsulated_key); friend class ObliviousHttpRequest; friend class ObliviousHttpResponse; friend class ObliviousHttpRequest_TestDecapsulateWithSpecAppendixAExample_Test; friend class ObliviousHttpRequest_TestEncapsulatedRequestStructure_Test; friend class ObliviousHttpRequest_TestEncapsulatedOhttpEncryptedPayload_Test; friend class ObliviousHttpRequest_TestDeterministicSeededOhttpRequest_Test; friend class ObliviousHttpResponse_EndToEndTestForResponse_Test; friend class ObliviousHttpResponse_TestEncapsulateWithQuicheRandom_Test; bssl::UniquePtr<EVP_HPKE_CTX> hpke_context_; std::string encapsulated_key_; }; static absl::StatusOr<ObliviousHttpRequest> CreateServerObliviousRequest( absl::string_view encrypted_data, const EVP_HPKE_KEY& gateway_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config, absl::string_view request_label = ObliviousHttpHeaderKeyConfig::kOhttpRequestLabel); static absl::StatusOr<ObliviousHttpRequest> CreateClientObliviousRequest( std::string plaintext_payload, absl::string_view hpke_public_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config, absl::string_view request_label = ObliviousHttpHeaderKeyConfig::kOhttpRequestLabel); static absl::StatusOr<ObliviousHttpRequest> CreateClientWithSeedForTesting( std::string plaintext_payload, absl::string_view hpke_public_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config, absl::string_view seed, absl::string_view request_label = ObliviousHttpHeaderKeyConfig::kOhttpRequestLabel); ObliviousHttpRequest(ObliviousHttpRequest&& other) = default; ObliviousHttpRequest& operator=(ObliviousHttpRequest&& other) = default; ~ObliviousHttpRequest() = default; std::string EncapsulateAndSerialize() const; absl::string_view GetPlaintextData() const; Context ReleaseContext() && { return std::move(oblivious_http_request_context_.value()); } private: explicit ObliviousHttpRequest( bssl::UniquePtr<EVP_HPKE_CTX> hpke_context, std::string encapsulated_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config, std::string req_ciphertext, std::string req_plaintext); static absl::StatusOr<ObliviousHttpRequest> EncapsulateWithSeed( std::string plaintext_payload, absl::string_view hpke_public_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config, absl::string_view seed, absl::string_view request_label); std::optional<Context> oblivious_http_request_context_; ObliviousHttpHeaderKeyConfig key_config_; std::string request_ciphertext_; std::string request_plaintext_; }; } #endif #include "quiche/oblivious_http/buffers/oblivious_http_request.h" #include <stddef.h> #include <stdint.h> #include <memory> #include <optional> #include <string> #include <utility> #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "openssl/hpke.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_crypto_logging.h" namespace quiche { ObliviousHttpRequest::Context::Context( bssl::UniquePtr<EVP_HPKE_CTX> hpke_context, std::string encapsulated_key) : hpke_context_(std::move(hpke_context)), encapsulated_key_(std::move(encapsulated_key)) {} ObliviousHttpRequest::ObliviousHttpRequest( bssl::UniquePtr<EVP_HPKE_CTX> hpke_context, std::string encapsulated_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config, std::string req_ciphertext, std::string req_plaintext) : oblivious_http_request_context_(absl::make_optional( Context(std::move(hpke_context), std::move(encapsulated_key)))), key_config_(ohttp_key_config), request_ciphertext_(std::move(req_ciphertext)), request_plaintext_(std::move(req_plaintext)) {} absl::StatusOr<ObliviousHttpRequest> ObliviousHttpRequest::CreateServerObliviousRequest( absl::string_view encrypted_data, const EVP_HPKE_KEY& gateway_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config, absl::string_view request_label) { if (EVP_HPKE_KEY_kem(&gateway_key) == nullptr) { return absl::InvalidArgumentError( "Invalid input param. Failed to import gateway_key."); } bssl::UniquePtr<EVP_HPKE_CTX> gateway_ctx(EVP_HPKE_CTX_new()); if (gateway_ctx == nullptr) { return SslErrorAsStatus("Failed to initialize Gateway/Server's Context."); } QuicheDataReader reader(encrypted_data); auto is_hdr_ok = ohttp_key_config.ParseOhttpPayloadHeader(reader); if (!is_hdr_ok.ok()) { return is_hdr_ok; } size_t enc_key_len = EVP_HPKE_KEM_enc_len(EVP_HPKE_KEY_kem(&gateway_key)); absl::string_view enc_key_received; if (!reader.ReadStringPiece(&enc_key_received, enc_key_len)) { return absl::FailedPreconditionError(absl::StrCat( "Failed to extract encapsulation key of expected len=", enc_key_len, "from payload.")); } std::string info = ohttp_key_config.SerializeRecipientContextInfo(request_label); if (!EVP_HPKE_CTX_setup_recipient( gateway_ctx.get(), &gateway_key, ohttp_key_config.GetHpkeKdf(), ohttp_key_config.GetHpkeAead(), reinterpret_cast<const uint8_t*>(enc_key_received.data()), enc_key_received.size(), reinterpret_cast<const uint8_t*>(info.data()), info.size())) { return SslErrorAsStatus("Failed to setup recipient context"); } absl::string_view ciphertext_received = reader.ReadRemainingPayload(); std::string decrypted(ciphertext_received.size(), '\0'); size_t decrypted_len; if (!EVP_HPKE_CTX_open( gateway_ctx.get(), reinterpret_cast<uint8_t*>(decrypted.data()), &decrypted_len, decrypted.size(), reinterpret_cast<const uint8_t*>(ciphertext_received.data()), ciphertext_received.size(), nullptr, 0)) { return SslErrorAsStatus("Failed to decrypt.", absl::StatusCode::kInvalidArgument); } decrypted.resize(decrypted_len); return ObliviousHttpRequest( std::move(gateway_ctx), std::string(enc_key_received), ohttp_key_config, std::string(ciphertext_received), std::move(decrypted)); } absl::StatusOr<ObliviousHttpRequest> ObliviousHttpRequest::CreateClientObliviousRequest( std::string plaintext_payload, absl::string_view hpke_public_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config, absl::string_view request_label) { return EncapsulateWithSeed(std::move(plaintext_payload), hpke_public_key, ohttp_key_config, "", request_label); } absl::StatusOr<ObliviousHttpRequest> ObliviousHttpRequest::CreateClientWithSeedForTesting( std::string plaintext_payload, absl::string_view hpke_public_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config, absl::string_view seed, absl::string_view request_label) { return ObliviousHttpRequest::EncapsulateWithSeed( std::move(plaintext_payload), hpke_public_key, ohttp_key_config, seed, request_label); } absl::StatusOr<ObliviousHttpRequest> ObliviousHttpRequest::EncapsulateWithSeed( std::string plaintext_payload, absl::string_view hpke_public_key, const ObliviousHttpHeaderKeyConfig& ohttp_key_config, absl::string_view seed, absl::string_view request_label) { if (plaintext_payload.empty() || hpke_public_key.empty()) { return absl::InvalidArgumentError("Invalid input."); } bssl::UniquePtr<EVP_HPKE_KEY> client_key(EVP_HPKE_KEY_new()); if (client_key == nullptr) { return SslErrorAsStatus("Failed to initialize HPKE Client Key."); } bssl::UniquePtr<EVP_HPKE_CTX> client_ctx(EVP_HPKE_CTX_new()); if (client_ctx == nullptr) { return SslErrorAsStatus("Failed to initialize HPKE Client Context."); } std::string encapsulated_key(EVP_HPKE_MAX_ENC_LENGTH, '\0'); size_t enc_len; std::string info = ohttp_key_config.SerializeRecipientContextInfo(request_label); if (seed.empty()) { if (!EVP_HPKE_CTX_setup_sender( client_ctx.get(), reinterpret_cast<uint8_t*>(encapsulated_key.data()), &enc_len, encapsulated_key.size(), ohttp_key_config.GetHpkeKem(), ohttp_key_config.GetHpkeKdf(), ohttp_key_config.GetHpkeAead(), reinterpret_cast<const uint8_t*>(hpke_public_key.data()), hpke_public_key.size(), reinterpret_cast<const uint8_t*>(info.data()), info.size())) { return SslErrorAsStatus( "Failed to setup HPKE context with given public key param " "hpke_public_key."); } } else { if (!EVP_HPKE_CTX_setup_sender_with_seed_for_testing( client_ctx.get(), reinterpret_cast<uint8_t*>(encapsulated_key.data()), &enc_len, encapsulated_key.size(), ohttp_key_config.GetHpkeKem(), ohttp_key_config.GetHpkeKdf(), ohttp_key_config.GetHpkeAead(), reinterpret_cast<const uint8_t*>(hpke_public_key.data()), hpke_public_key.size(), reinterpret_cast<const uint8_t*>(info.data()), info.size(), reinterpret_cast<const uint8_t*>(seed.data()), seed.size())) { return SslErrorAsStatus( "Failed to setup HPKE context with given public key param " "hpke_public_key and seed."); } } encapsulated_key.resize(enc_len); std::string ciphertext( plaintext_payload.size() + EVP_HPKE_CTX_max_overhead(client_ctx.get()), '\0'); size_t ciphertext_len; if (!EVP_HPKE_CTX_seal( client_ctx.get(), reinterpret_cast<uint8_t*>(ciphertext.data()), &ciphertext_len, ciphertext.size(), reinterpret_cast<const uint8_t*>(plaintext_payload.data()), plaintext_payload.size(), nullptr, 0)) { return SslErrorAsStatus( "Failed to encrypt plaintext_payload with given public key param " "hpke_public_key."); } ciphertext.resize(ciphertext_len); if (encapsulated_key.empty() || ciphertext.empty()) { return absl::InternalError(absl::StrCat( "Failed to generate required data: ", (encapsulated_key.empty() ? "encapsulated key is empty" : ""), (ciphertext.empty() ? "encrypted data is empty" : ""), ".")); } return ObliviousHttpRequest( std::move(client_ctx), std::move(encapsulated_key), ohttp_key_config, std::move(ciphertext), std::move(plaintext_payload)); } std::string ObliviousHttpRequest::EncapsulateAndSerialize() const { if (!oblivious_http_request_context_.has_value()) { QUICHE_BUG(ohttp_encapsulate_after_context_extract) << "EncapsulateAndSerialize cannot be called after ReleaseContext()"; return ""; } return absl::StrCat(key_config_.SerializeOhttpPayloadHeader(), oblivious_http_request_context_->encapsulated_key_, request_ciphertext_); } absl::string_view ObliviousHttpRequest::GetPlaintextData() const { return request_plaintext_; } }
#include "quiche/oblivious_http/buffers/oblivious_http_request.h" #include <stddef.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/str_cat.h" #include "absl/strings/string_view.h" #include "openssl/hkdf.h" #include "openssl/hpke.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/quiche_data_reader.h" #include "quiche/oblivious_http/common/oblivious_http_header_key_config.h" namespace quiche { namespace { const uint32_t kHeaderLength = ObliviousHttpHeaderKeyConfig::kHeaderLength; std::string GetHpkePrivateKey() { absl::string_view hpke_key_hex = "b77431ecfa8f4cfc30d6e467aafa06944dffe28cb9dd1409e33a3045f5adc8a1"; std::string hpke_key_bytes; EXPECT_TRUE(absl::HexStringToBytes(hpke_key_hex, &hpke_key_bytes)); return hpke_key_bytes; } std::string GetHpkePublicKey() { absl::string_view public_key = "6d21cfe09fbea5122f9ebc2eb2a69fcc4f06408cd54aac934f012e76fcdcef62"; std::string public_key_bytes; EXPECT_TRUE(absl::HexStringToBytes(public_key, &public_key_bytes)); return public_key_bytes; } std::string GetAlternativeHpkePublicKey() { absl::string_view public_key = "6d21cfe09fbea5122f9ebc2eb2a69fcc4f06408cd54aac934f012e76fcdcef63"; std::string public_key_bytes; EXPECT_TRUE(absl::HexStringToBytes(public_key, &public_key_bytes)); return public_key_bytes; } std::string GetSeed() { absl::string_view seed = "52c4a758a802cd8b936eceea314432798d5baf2d7e9235dc084ab1b9cfa2f736"; std::string seed_bytes; EXPECT_TRUE(absl::HexStringToBytes(seed, &seed_bytes)); return seed_bytes; } std::string GetSeededEncapsulatedKey() { absl::string_view encapsulated_key = "37fda3567bdbd628e88668c3c8d7e97d1d1253b6d4ea6d44c150f741f1bf4431"; std::string encapsulated_key_bytes; EXPECT_TRUE( absl::HexStringToBytes(encapsulated_key, &encapsulated_key_bytes)); return encapsulated_key_bytes; } bssl::UniquePtr<EVP_HPKE_KEY> ConstructHpkeKey( absl::string_view hpke_key, const ObliviousHttpHeaderKeyConfig &ohttp_key_config) { bssl::UniquePtr<EVP_HPKE_KEY> bssl_hpke_key(EVP_HPKE_KEY_new()); EXPECT_NE(bssl_hpke_key, nullptr); EXPECT_TRUE(EVP_HPKE_KEY_init( bssl_hpke_key.get(), ohttp_key_config.GetHpkeKem(), reinterpret_cast<const uint8_t *>(hpke_key.data()), hpke_key.size())); return bssl_hpke_key; } const ObliviousHttpHeaderKeyConfig GetOhttpKeyConfig(uint8_t key_id, uint16_t kem_id, uint16_t kdf_id, uint16_t aead_id) { auto ohttp_key_config = ObliviousHttpHeaderKeyConfig::Create(key_id, kem_id, kdf_id, aead_id); EXPECT_TRUE(ohttp_key_config.ok()); return std::move(ohttp_key_config.value()); } } TEST(ObliviousHttpRequest, TestDecapsulateWithSpecAppendixAExample) { auto ohttp_key_config = GetOhttpKeyConfig(1, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_128_GCM); constexpr absl::string_view kX25519SecretKey = "3c168975674b2fa8e465970b79c8dcf09f1c741626480bd4c6162fc5b6a98e1a"; constexpr absl::string_view kEncapsulatedRequest = "010020000100014b28f881333e7c164ffc499ad9796f877f4e1051ee6d31bad19dec96c2" "08b4726374e469135906992e1268c594d2a10c695d858c40a026e7965e7d86b83dd440b2" "c0185204b4d63525"; std::string encapsulated_request_bytes; ASSERT_TRUE(absl::HexStringToBytes(kEncapsulatedRequest, &encapsulated_request_bytes)); std::string x25519_secret_key_bytes; ASSERT_TRUE( absl::HexStringToBytes(kX25519SecretKey, &x25519_secret_key_bytes)); auto instance = ObliviousHttpRequest::CreateServerObliviousRequest( encapsulated_request_bytes, *(ConstructHpkeKey(x25519_secret_key_bytes, ohttp_key_config)), ohttp_key_config); ASSERT_TRUE(instance.ok()); auto decrypted = instance->GetPlaintextData(); constexpr absl::string_view kExpectedEphemeralPublicKey = "4b28f881333e7c164ffc499ad9796f877f4e1051ee6d31bad19dec96c208b472"; std::string expected_ephemeral_public_key_bytes; ASSERT_TRUE(absl::HexStringToBytes(kExpectedEphemeralPublicKey, &expected_ephemeral_public_key_bytes)); auto oblivious_request_context = std::move(instance.value()).ReleaseContext(); EXPECT_EQ(oblivious_request_context.encapsulated_key_, expected_ephemeral_public_key_bytes); constexpr absl::string_view kExpectedBinaryHTTPMessage = "00034745540568747470730b6578616d706c652e636f6d012f"; std::string expected_binary_http_message_bytes; ASSERT_TRUE(absl::HexStringToBytes(kExpectedBinaryHTTPMessage, &expected_binary_http_message_bytes)); EXPECT_EQ(decrypted, expected_binary_http_message_bytes); } TEST(ObliviousHttpRequest, TestEncapsulatedRequestStructure) { uint8_t test_key_id = 7; uint16_t test_kem_id = EVP_HPKE_DHKEM_X25519_HKDF_SHA256; uint16_t test_kdf_id = EVP_HPKE_HKDF_SHA256; uint16_t test_aead_id = EVP_HPKE_AES_256_GCM; std::string plaintext = "test"; auto instance = ObliviousHttpRequest::CreateClientObliviousRequest( plaintext, GetHpkePublicKey(), GetOhttpKeyConfig(test_key_id, test_kem_id, test_kdf_id, test_aead_id)); ASSERT_TRUE(instance.ok()); auto payload_bytes = instance->EncapsulateAndSerialize(); EXPECT_GE(payload_bytes.size(), kHeaderLength); QuicheDataReader reader(payload_bytes); uint8_t key_id; EXPECT_TRUE(reader.ReadUInt8(&key_id)); EXPECT_EQ(key_id, test_key_id); uint16_t kem_id; EXPECT_TRUE(reader.ReadUInt16(&kem_id)); EXPECT_EQ(kem_id, test_kem_id); uint16_t kdf_id; EXPECT_TRUE(reader.ReadUInt16(&kdf_id)); EXPECT_EQ(kdf_id, test_kdf_id); uint16_t aead_id; EXPECT_TRUE(reader.ReadUInt16(&aead_id)); EXPECT_EQ(aead_id, test_aead_id); auto client_request_context = std::move(instance.value()).ReleaseContext(); auto client_encapsulated_key = client_request_context.encapsulated_key_; EXPECT_EQ(client_encapsulated_key.size(), X25519_PUBLIC_VALUE_LEN); auto enc_key_plus_ciphertext = payload_bytes.substr(kHeaderLength); auto packed_encapsulated_key = enc_key_plus_ciphertext.substr(0, X25519_PUBLIC_VALUE_LEN); EXPECT_EQ(packed_encapsulated_key, client_encapsulated_key); auto ciphertext = enc_key_plus_ciphertext.substr(X25519_PUBLIC_VALUE_LEN); EXPECT_GE(ciphertext.size(), plaintext.size()); } TEST(ObliviousHttpRequest, TestDeterministicSeededOhttpRequest) { auto ohttp_key_config = GetOhttpKeyConfig(4, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); auto encapsulated = ObliviousHttpRequest::CreateClientWithSeedForTesting( "test", GetHpkePublicKey(), ohttp_key_config, GetSeed()); ASSERT_TRUE(encapsulated.ok()); auto encapsulated_request = encapsulated->EncapsulateAndSerialize(); auto ohttp_request_context = std::move(encapsulated.value()).ReleaseContext(); EXPECT_EQ(ohttp_request_context.encapsulated_key_, GetSeededEncapsulatedKey()); absl::string_view expected_encrypted_request = "9f37cfed07d0111ecd2c34f794671759bcbd922a"; std::string expected_encrypted_request_bytes; ASSERT_TRUE(absl::HexStringToBytes(expected_encrypted_request, &expected_encrypted_request_bytes)); EXPECT_NE(ohttp_request_context.hpke_context_, nullptr); size_t encapsulated_key_len = EVP_HPKE_KEM_enc_len( EVP_HPKE_CTX_kem(ohttp_request_context.hpke_context_.get())); int encrypted_payload_offset = kHeaderLength + encapsulated_key_len; EXPECT_EQ(encapsulated_request.substr(encrypted_payload_offset), expected_encrypted_request_bytes); } TEST(ObliviousHttpRequest, TestSeededEncapsulatedKeySamePlaintextsSameCiphertexts) { auto ohttp_key_config = GetOhttpKeyConfig(8, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); auto req_with_same_plaintext_1 = ObliviousHttpRequest::CreateClientWithSeedForTesting( "same plaintext", GetHpkePublicKey(), ohttp_key_config, GetSeed()); ASSERT_TRUE(req_with_same_plaintext_1.ok()); auto ciphertext_1 = req_with_same_plaintext_1->EncapsulateAndSerialize(); auto req_with_same_plaintext_2 = ObliviousHttpRequest::CreateClientWithSeedForTesting( "same plaintext", GetHpkePublicKey(), ohttp_key_config, GetSeed()); ASSERT_TRUE(req_with_same_plaintext_2.ok()); auto ciphertext_2 = req_with_same_plaintext_2->EncapsulateAndSerialize(); EXPECT_EQ(ciphertext_1, ciphertext_2); } TEST(ObliviousHttpRequest, TestSeededEncapsulatedKeyDifferentPlaintextsDifferentCiphertexts) { auto ohttp_key_config = GetOhttpKeyConfig(8, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); auto req_with_different_plaintext_1 = ObliviousHttpRequest::CreateClientWithSeedForTesting( "different 1", GetHpkePublicKey(), ohttp_key_config, GetSeed()); ASSERT_TRUE(req_with_different_plaintext_1.ok()); auto ciphertext_1 = req_with_different_plaintext_1->EncapsulateAndSerialize(); auto req_with_different_plaintext_2 = ObliviousHttpRequest::CreateClientWithSeedForTesting( "different 2", GetHpkePublicKey(), ohttp_key_config, GetSeed()); ASSERT_TRUE(req_with_different_plaintext_2.ok()); auto ciphertext_2 = req_with_different_plaintext_2->EncapsulateAndSerialize(); EXPECT_NE(ciphertext_1, ciphertext_2); } TEST(ObliviousHttpRequest, TestInvalidInputsOnClientSide) { auto ohttp_key_config = GetOhttpKeyConfig(30, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); EXPECT_EQ(ObliviousHttpRequest::CreateClientObliviousRequest( "", GetHpkePublicKey(), ohttp_key_config) .status() .code(), absl::StatusCode::kInvalidArgument); EXPECT_EQ(ObliviousHttpRequest::CreateClientObliviousRequest( "some plaintext", "", ohttp_key_config) .status() .code(), absl::StatusCode::kInvalidArgument); } TEST(ObliviousHttpRequest, TestInvalidInputsOnServerSide) { auto ohttp_key_config = GetOhttpKeyConfig(4, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); EXPECT_EQ(ObliviousHttpRequest::CreateServerObliviousRequest( "", *(ConstructHpkeKey(GetHpkePrivateKey(), ohttp_key_config)), ohttp_key_config) .status() .code(), absl::StatusCode::kInvalidArgument); EXPECT_EQ(ObliviousHttpRequest::CreateServerObliviousRequest( absl::StrCat(ohttp_key_config.SerializeOhttpPayloadHeader(), GetSeededEncapsulatedKey(), "9f37cfed07d0111ecd2c34f794671759bcbd922a"), {}, ohttp_key_config) .status() .code(), absl::StatusCode::kInvalidArgument); } TEST(ObliviousHttpRequest, EndToEndTestForRequest) { auto ohttp_key_config = GetOhttpKeyConfig(5, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); auto encapsulate = ObliviousHttpRequest::CreateClientObliviousRequest( "test", GetHpkePublicKey(), ohttp_key_config); ASSERT_TRUE(encapsulate.ok()); auto oblivious_request = encapsulate->EncapsulateAndSerialize(); auto decapsulate = ObliviousHttpRequest::CreateServerObliviousRequest( oblivious_request, *(ConstructHpkeKey(GetHpkePrivateKey(), ohttp_key_config)), ohttp_key_config); ASSERT_TRUE(decapsulate.ok()); auto decrypted = decapsulate->GetPlaintextData(); EXPECT_EQ(decrypted, "test"); } TEST(ObliviousHttpRequest, EndToEndTestForRequestWithWrongKey) { auto ohttp_key_config = GetOhttpKeyConfig(5, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM); auto encapsulate = ObliviousHttpRequest::CreateClientObliviousRequest( "test", GetAlternativeHpkePublicKey(), ohttp_key_config); ASSERT_TRUE(encapsulate.ok()); auto oblivious_request = encapsulate->EncapsulateAndSerialize(); auto decapsulate = ObliviousHttpRequest::CreateServerObliviousRequest( oblivious_request, *(ConstructHpkeKey(GetHpkePrivateKey(), ohttp_key_config)), ohttp_key_config); EXPECT_EQ(decapsulate.status().code(), absl::StatusCode::kInvalidArgument); } }
385
cpp
google/quiche
oblivious_http_response
quiche/oblivious_http/buffers/oblivious_http_response.cc
quiche/oblivious_http/buffers/oblivious_http_response_test.cc
#ifndef QUICHE_OBLIVIOUS_HTTP_BUFFERS_OBLIVIOUS_HTTP_RESPONSE_H_ #define QUICHE_OBLIVIOUS_HTTP_BUFFERS_OBLIVIOUS_HTTP_RESPONSE_H_ #include <stddef.h> #include <string> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "quiche/common/quiche_random.h" #include "quiche/oblivious_http/buffers/oblivious_http_request.h" #include "quiche/oblivious_http/common/oblivious_http_header_key_config.h" namespace quiche { class QUICHE_EXPORT ObliviousHttpResponse { public: static absl::StatusOr<ObliviousHttpResponse> CreateClientObliviousResponse( std::string encrypted_data, ObliviousHttpRequest::Context& oblivious_http_request_context, absl::string_view resp_label = ObliviousHttpHeaderKeyConfig::kOhttpResponseLabel); static absl::StatusOr<ObliviousHttpResponse> CreateServerObliviousResponse( std::string plaintext_payload, ObliviousHttpRequest::Context& oblivious_http_request_context, absl::string_view resp_label = ObliviousHttpHeaderKeyConfig::kOhttpResponseLabel, QuicheRandom* quiche_random = nullptr); ObliviousHttpResponse(const ObliviousHttpResponse& other) = default; ObliviousHttpResponse& operator=(const ObliviousHttpResponse& other) = default; ObliviousHttpResponse(ObliviousHttpResponse&& other) = default; ObliviousHttpResponse& operator=(ObliviousHttpResponse&& other) = default; ~ObliviousHttpResponse() = default; const std::string& EncapsulateAndSerialize() const; const std::string& GetPlaintextData() const; std::string ConsumePlaintextData() && { return std::move(response_plaintext_); } private: struct CommonAeadParamsResult { const EVP_AEAD* evp_hpke_aead; const size_t aead_key_len; const size_t aead_nonce_len; const size_t secret_len; }; struct CommonOperationsResult { bssl::UniquePtr<EVP_AEAD_CTX> aead_ctx; const std::string aead_nonce; }; explicit ObliviousHttpResponse(std::string encrypted_data, std::string resp_plaintext); static absl::StatusOr<CommonAeadParamsResult> GetCommonAeadParams( ObliviousHttpRequest::Context& oblivious_http_request_context); static absl::StatusOr<CommonOperationsResult> CommonOperationsToEncapDecap( absl::string_view response_nonce, ObliviousHttpRequest::Context& oblivious_http_request_context, absl::string_view resp_label, const size_t aead_key_len, const size_t aead_nonce_len, const size_t secret_len); std::string encrypted_data_; std::string response_plaintext_; }; } #endif #include "quiche/oblivious_http/buffers/oblivious_http_response.h" #include <stddef.h> #include <stdint.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "openssl/aead.h" #include "openssl/hkdf.h" #include "openssl/hpke.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/quiche_crypto_logging.h" #include "quiche/common/quiche_random.h" #include "quiche/oblivious_http/common/oblivious_http_header_key_config.h" namespace quiche { namespace { void random(QuicheRandom* quiche_random, char* dest, size_t len) { if (quiche_random == nullptr) { quiche_random = QuicheRandom::GetInstance(); } quiche_random->RandBytes(dest, len); } } ObliviousHttpResponse::ObliviousHttpResponse(std::string encrypted_data, std::string resp_plaintext) : encrypted_data_(std::move(encrypted_data)), response_plaintext_(std::move(resp_plaintext)) {} absl::StatusOr<ObliviousHttpResponse> ObliviousHttpResponse::CreateClientObliviousResponse( std::string encrypted_data, ObliviousHttpRequest::Context& oblivious_http_request_context, absl::string_view resp_label) { if (oblivious_http_request_context.hpke_context_ == nullptr) { return absl::FailedPreconditionError( "HPKE context wasn't initialized before proceeding with this Response " "Decapsulation on Client-side."); } size_t expected_key_len = EVP_HPKE_KEM_enc_len( EVP_HPKE_CTX_kem(oblivious_http_request_context.hpke_context_.get())); if (oblivious_http_request_context.encapsulated_key_.size() != expected_key_len) { return absl::InvalidArgumentError(absl::StrCat( "Invalid len for encapsulated_key arg. Expected:", expected_key_len, " Actual:", oblivious_http_request_context.encapsulated_key_.size())); } if (encrypted_data.empty()) { return absl::InvalidArgumentError("Empty encrypted_data input param."); } absl::StatusOr<CommonAeadParamsResult> aead_params_st = GetCommonAeadParams(oblivious_http_request_context); if (!aead_params_st.ok()) { return aead_params_st.status(); } size_t secret_len = aead_params_st.value().secret_len; if (encrypted_data.size() < secret_len) { return absl::InvalidArgumentError( absl::StrCat("Invalid input response. Failed to parse required minimum " "expected_len=", secret_len, " bytes.")); } absl::string_view response_nonce = absl::string_view(encrypted_data).substr(0, secret_len); absl::string_view encrypted_response = absl::string_view(encrypted_data).substr(secret_len); auto common_ops_st = CommonOperationsToEncapDecap( response_nonce, oblivious_http_request_context, resp_label, aead_params_st.value().aead_key_len, aead_params_st.value().aead_nonce_len, aead_params_st.value().secret_len); if (!common_ops_st.ok()) { return common_ops_st.status(); } std::string decrypted(encrypted_response.size(), '\0'); size_t decrypted_len; if (!EVP_AEAD_CTX_open( common_ops_st.value().aead_ctx.get(), reinterpret_cast<uint8_t*>(decrypted.data()), &decrypted_len, decrypted.size(), reinterpret_cast<const uint8_t*>( common_ops_st.value().aead_nonce.data()), aead_params_st.value().aead_nonce_len, reinterpret_cast<const uint8_t*>(encrypted_response.data()), encrypted_response.size(), nullptr, 0)) { return SslErrorAsStatus( "Failed to decrypt the response with derived AEAD key and nonce."); } decrypted.resize(decrypted_len); ObliviousHttpResponse oblivious_response(std::move(encrypted_data), std::move(decrypted)); return oblivious_response; } absl::StatusOr<ObliviousHttpResponse> ObliviousHttpResponse::CreateServerObliviousResponse( std::string plaintext_payload, ObliviousHttpRequest::Context& oblivious_http_request_context, absl::string_view response_label, QuicheRandom* quiche_random) { if (oblivious_http_request_context.hpke_context_ == nullptr) { return absl::FailedPreconditionError( "HPKE context wasn't initialized before proceeding with this Response " "Encapsulation on Server-side."); } size_t expected_key_len = EVP_HPKE_KEM_enc_len( EVP_HPKE_CTX_kem(oblivious_http_request_context.hpke_context_.get())); if (oblivious_http_request_context.encapsulated_key_.size() != expected_key_len) { return absl::InvalidArgumentError(absl::StrCat( "Invalid len for encapsulated_key arg. Expected:", expected_key_len, " Actual:", oblivious_http_request_context.encapsulated_key_.size())); } if (plaintext_payload.empty()) { return absl::InvalidArgumentError("Empty plaintext_payload input param."); } absl::StatusOr<CommonAeadParamsResult> aead_params_st = GetCommonAeadParams(oblivious_http_request_context); if (!aead_params_st.ok()) { return aead_params_st.status(); } const size_t nonce_size = aead_params_st->secret_len; const size_t max_encrypted_data_size = nonce_size + plaintext_payload.size() + EVP_AEAD_max_overhead(EVP_HPKE_AEAD_aead(EVP_HPKE_CTX_aead( oblivious_http_request_context.hpke_context_.get()))); std::string encrypted_data(max_encrypted_data_size, '\0'); random(quiche_random, encrypted_data.data(), nonce_size); absl::string_view response_nonce = absl::string_view(encrypted_data).substr(0, nonce_size); auto common_ops_st = CommonOperationsToEncapDecap( response_nonce, oblivious_http_request_context, response_label, aead_params_st.value().aead_key_len, aead_params_st.value().aead_nonce_len, aead_params_st.value().secret_len); if (!common_ops_st.ok()) { return common_ops_st.status(); } size_t ciphertext_len; if (!EVP_AEAD_CTX_seal( common_ops_st.value().aead_ctx.get(), reinterpret_cast<uint8_t*>(encrypted_data.data() + nonce_size), &ciphertext_len, encrypted_data.size() - nonce_size, reinterpret_cast<const uint8_t*>( common_ops_st.value().aead_nonce.data()), aead_params_st.value().aead_nonce_len, reinterpret_cast<const uint8_t*>(plaintext_payload.data()), plaintext_payload.size(), nullptr, 0)) { return SslErrorAsStatus( "Failed to encrypt the payload with derived AEAD key."); } encrypted_data.resize(nonce_size + ciphertext_len); if (nonce_size == 0 || ciphertext_len == 0) { return absl::InternalError(absl::StrCat( "ObliviousHttpResponse Object wasn't initialized with required fields.", (nonce_size == 0 ? "Generated nonce is empty." : ""), (ciphertext_len == 0 ? "Generated Encrypted payload is empty." : ""))); } ObliviousHttpResponse oblivious_response(std::move(encrypted_data), std::move(plaintext_payload)); return oblivious_response; } const std::string& ObliviousHttpResponse::EncapsulateAndSerialize() const { return encrypted_data_; } const std::string& ObliviousHttpResponse::GetPlaintextData() const { return response_plaintext_; } absl::StatusOr<ObliviousHttpResponse::CommonAeadParamsResult> ObliviousHttpResponse::GetCommonAeadParams( ObliviousHttpRequest::Context& oblivious_http_request_context) { const EVP_AEAD* evp_hpke_aead = EVP_HPKE_AEAD_aead( EVP_HPKE_CTX_aead(oblivious_http_request_context.hpke_context_.get())); if (evp_hpke_aead == nullptr) { return absl::FailedPreconditionError( "Key Configuration not supported by HPKE AEADs. Check your key " "config."); } const size_t aead_key_len = EVP_AEAD_key_length(evp_hpke_aead); const size_t aead_nonce_len = EVP_AEAD_nonce_length(evp_hpke_aead); const size_t secret_len = std::max(aead_key_len, aead_nonce_len); CommonAeadParamsResult result{evp_hpke_aead, aead_key_len, aead_nonce_len, secret_len}; return result; } absl::StatusOr<ObliviousHttpResponse::CommonOperationsResult> ObliviousHttpResponse::CommonOperationsToEncapDecap( absl::string_view response_nonce, ObliviousHttpRequest::Context& oblivious_http_request_context, absl::string_view resp_label, const size_t aead_key_len, const size_t aead_nonce_len, const size_t secret_len) { if (response_nonce.empty()) { return absl::InvalidArgumentError("Invalid input params."); } std::string secret(secret_len, '\0'); if (!EVP_HPKE_CTX_export(oblivious_http_request_context.hpke_context_.get(), reinterpret_cast<uint8_t*>(secret.data()), secret.size(), reinterpret_cast<const uint8_t*>(resp_label.data()), resp_label.size())) { return SslErrorAsStatus("Failed to export secret."); } std::string salt = absl::StrCat( oblivious_http_request_context.encapsulated_key_, response_nonce); std::string pseudorandom_key(EVP_MAX_MD_SIZE, '\0'); size_t prk_len; auto evp_md = EVP_HPKE_KDF_hkdf_md( EVP_HPKE_CTX_kdf(oblivious_http_request_context.hpke_context_.get())); if (evp_md == nullptr) { QUICHE_BUG(Invalid Key Configuration : Unsupported BoringSSL HPKE KDFs) << "Update KeyConfig to support only BoringSSL HKDFs."; return absl::FailedPreconditionError( "Key Configuration not supported by BoringSSL HPKE KDFs. Check your " "Key " "Config."); } if (!HKDF_extract( reinterpret_cast<uint8_t*>(pseudorandom_key.data()), &prk_len, evp_md, reinterpret_cast<const uint8_t*>(secret.data()), secret_len, reinterpret_cast<const uint8_t*>(salt.data()), salt.size())) { return SslErrorAsStatus( "Failed to derive pesudorandom key from salt and secret."); } pseudorandom_key.resize(prk_len); std::string aead_key(aead_key_len, '\0'); absl::string_view hkdf_info = ObliviousHttpHeaderKeyConfig::kKeyHkdfInfo; if (!HKDF_expand(reinterpret_cast<uint8_t*>(aead_key.data()), aead_key_len, evp_md, reinterpret_cast<const uint8_t*>(pseudorandom_key.data()), prk_len, reinterpret_cast<const uint8_t*>(hkdf_info.data()), hkdf_info.size())) { return SslErrorAsStatus( "Failed to expand AEAD key using pseudorandom key(prk)."); } std::string aead_nonce(aead_nonce_len, '\0'); hkdf_info = ObliviousHttpHeaderKeyConfig::kNonceHkdfInfo; if (!HKDF_expand(reinterpret_cast<uint8_t*>(aead_nonce.data()), aead_nonce_len, evp_md, reinterpret_cast<const uint8_t*>(pseudorandom_key.data()), prk_len, reinterpret_cast<const uint8_t*>(hkdf_info.data()), hkdf_info.size())) { return SslErrorAsStatus( "Failed to expand AEAD nonce using pseudorandom key(prk)."); } const EVP_AEAD* evp_hpke_aead = EVP_HPKE_AEAD_aead( EVP_HPKE_CTX_aead(oblivious_http_request_context.hpke_context_.get())); if (evp_hpke_aead == nullptr) { return absl::FailedPreconditionError( "Key Configuration not supported by HPKE AEADs. Check your key " "config."); } bssl::UniquePtr<EVP_AEAD_CTX> aead_ctx(EVP_AEAD_CTX_new( evp_hpke_aead, reinterpret_cast<const uint8_t*>(aead_key.data()), aead_key.size(), 0)); if (aead_ctx == nullptr) { return SslErrorAsStatus("Failed to initialize AEAD context."); } if (!EVP_AEAD_CTX_init(aead_ctx.get(), evp_hpke_aead, reinterpret_cast<const uint8_t*>(aead_key.data()), aead_key.size(), 0, nullptr)) { return SslErrorAsStatus( "Failed to initialize AEAD context with derived key."); } CommonOperationsResult result{std::move(aead_ctx), std::move(aead_nonce)}; return result; } }
#include "quiche/oblivious_http/buffers/oblivious_http_response.h" #include <stddef.h> #include <stdint.h> #include <string.h> #include <algorithm> #include <memory> #include <string> #include <utility> #include "absl/status/statusor.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "openssl/hpke.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/oblivious_http/buffers/oblivious_http_request.h" #include "quiche/oblivious_http/common/oblivious_http_header_key_config.h" namespace quiche { namespace { std::string GetHpkePrivateKey() { absl::string_view hpke_key_hex = "b77431ecfa8f4cfc30d6e467aafa06944dffe28cb9dd1409e33a3045f5adc8a1"; std::string hpke_key_bytes; EXPECT_TRUE(absl::HexStringToBytes(hpke_key_hex, &hpke_key_bytes)); return hpke_key_bytes; } std::string GetHpkePublicKey() { absl::string_view public_key = "6d21cfe09fbea5122f9ebc2eb2a69fcc4f06408cd54aac934f012e76fcdcef62"; std::string public_key_bytes; EXPECT_TRUE(absl::HexStringToBytes(public_key, &public_key_bytes)); return public_key_bytes; } std::string GetSeed() { absl::string_view seed = "52c4a758a802cd8b936eceea314432798d5baf2d7e9235dc084ab1b9cfa2f736"; std::string seed_bytes; EXPECT_TRUE(absl::HexStringToBytes(seed, &seed_bytes)); return seed_bytes; } std::string GetSeededEncapsulatedKey() { absl::string_view encapsulated_key = "37fda3567bdbd628e88668c3c8d7e97d1d1253b6d4ea6d44c150f741f1bf4431"; std::string encapsulated_key_bytes; EXPECT_TRUE( absl::HexStringToBytes(encapsulated_key, &encapsulated_key_bytes)); return encapsulated_key_bytes; } const ObliviousHttpHeaderKeyConfig GetOhttpKeyConfig(uint8_t key_id, uint16_t kem_id, uint16_t kdf_id, uint16_t aead_id) { auto ohttp_key_config = ObliviousHttpHeaderKeyConfig::Create(key_id, kem_id, kdf_id, aead_id); EXPECT_TRUE(ohttp_key_config.ok()); return ohttp_key_config.value(); } bssl::UniquePtr<EVP_HPKE_CTX> GetSeededClientContext(uint8_t key_id, uint16_t kem_id, uint16_t kdf_id, uint16_t aead_id) { bssl::UniquePtr<EVP_HPKE_CTX> client_ctx(EVP_HPKE_CTX_new()); std::string encapsulated_key(EVP_HPKE_MAX_ENC_LENGTH, '\0'); size_t enc_len; std::string info = GetOhttpKeyConfig(key_id, kem_id, kdf_id, aead_id) .SerializeRecipientContextInfo(); EXPECT_TRUE(EVP_HPKE_CTX_setup_sender_with_seed_for_testing( client_ctx.get(), reinterpret_cast<uint8_t *>(encapsulated_key.data()), &enc_len, encapsulated_key.size(), EVP_hpke_x25519_hkdf_sha256(), EVP_hpke_hkdf_sha256(), EVP_hpke_aes_256_gcm(), reinterpret_cast<const uint8_t *>(GetHpkePublicKey().data()), GetHpkePublicKey().size(), reinterpret_cast<const uint8_t *>(info.data()), info.size(), reinterpret_cast<const uint8_t *>(GetSeed().data()), GetSeed().size())); encapsulated_key.resize(enc_len); EXPECT_EQ(encapsulated_key, GetSeededEncapsulatedKey()); return client_ctx; } bssl::UniquePtr<EVP_HPKE_KEY> ConstructHpkeKey( absl::string_view hpke_key, const ObliviousHttpHeaderKeyConfig &ohttp_key_config) { bssl::UniquePtr<EVP_HPKE_KEY> bssl_hpke_key(EVP_HPKE_KEY_new()); EXPECT_NE(bssl_hpke_key, nullptr); EXPECT_TRUE(EVP_HPKE_KEY_init( bssl_hpke_key.get(), ohttp_key_config.GetHpkeKem(), reinterpret_cast<const uint8_t *>(hpke_key.data()), hpke_key.size())); return bssl_hpke_key; } ObliviousHttpRequest SetUpObliviousHttpContext(uint8_t key_id, uint16_t kem_id, uint16_t kdf_id, uint16_t aead_id, std::string plaintext) { auto ohttp_key_config = GetOhttpKeyConfig(key_id, kem_id, kdf_id, aead_id); auto client_request_encapsulate = ObliviousHttpRequest::CreateClientWithSeedForTesting( std::move(plaintext), GetHpkePublicKey(), ohttp_key_config, GetSeed()); EXPECT_TRUE(client_request_encapsulate.ok()); auto oblivious_request = client_request_encapsulate->EncapsulateAndSerialize(); auto server_request_decapsulate = ObliviousHttpRequest::CreateServerObliviousRequest( oblivious_request, *(ConstructHpkeKey(GetHpkePrivateKey(), ohttp_key_config)), ohttp_key_config); EXPECT_TRUE(server_request_decapsulate.ok()); return std::move(server_request_decapsulate.value()); } class TestQuicheRandom : public QuicheRandom { public: TestQuicheRandom(char seed) : seed_(seed) {} ~TestQuicheRandom() override {} void RandBytes(void *data, size_t len) override { memset(data, seed_, len); } uint64_t RandUint64() override { uint64_t random_int; memset(&random_int, seed_, sizeof(random_int)); return random_int; } void InsecureRandBytes(void *data, size_t len) override { return RandBytes(data, len); } uint64_t InsecureRandUint64() override { return RandUint64(); } private: char seed_; }; size_t GetResponseNonceLength(const EVP_HPKE_CTX &hpke_context) { EXPECT_NE(&hpke_context, nullptr); const EVP_AEAD *evp_hpke_aead = EVP_HPKE_AEAD_aead(EVP_HPKE_CTX_aead(&hpke_context)); EXPECT_NE(evp_hpke_aead, nullptr); const size_t aead_key_len = EVP_AEAD_key_length(evp_hpke_aead); const size_t aead_nonce_len = EVP_AEAD_nonce_length(evp_hpke_aead); const size_t secret_len = std::max(aead_key_len, aead_nonce_len); return secret_len; } TEST(ObliviousHttpResponse, TestDecapsulateReceivedResponse) { absl::string_view encrypted_response = "39d5b03c02c97e216df444e4681007105974d4df1585aae05e7b53f3ccdb55d51f711d48" "eeefbc1a555d6d928e35df33fd23c23846fa7b083e30692f7b"; std::string encrypted_response_bytes; ASSERT_TRUE( absl::HexStringToBytes(encrypted_response, &encrypted_response_bytes)); auto oblivious_context = SetUpObliviousHttpContext(4, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM, "test") .ReleaseContext(); auto decapsulated = ObliviousHttpResponse::CreateClientObliviousResponse( std::move(encrypted_response_bytes), oblivious_context); EXPECT_TRUE(decapsulated.ok()); auto decrypted = decapsulated->GetPlaintextData(); EXPECT_EQ(decrypted, "test response"); } } TEST(ObliviousHttpResponse, EndToEndTestForResponse) { auto oblivious_ctx = ObliviousHttpRequest::Context( GetSeededClientContext(5, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM), GetSeededEncapsulatedKey()); auto server_response_encapsulate = ObliviousHttpResponse::CreateServerObliviousResponse("test response", oblivious_ctx); EXPECT_TRUE(server_response_encapsulate.ok()); auto oblivious_response = server_response_encapsulate->EncapsulateAndSerialize(); auto client_response_encapsulate = ObliviousHttpResponse::CreateClientObliviousResponse(oblivious_response, oblivious_ctx); auto decrypted = client_response_encapsulate->GetPlaintextData(); EXPECT_EQ(decrypted, "test response"); } TEST(ObliviousHttpResponse, TestEncapsulateWithQuicheRandom) { auto random = TestQuicheRandom('z'); auto server_seeded_request = SetUpObliviousHttpContext( 6, EVP_HPKE_DHKEM_X25519_HKDF_SHA256, EVP_HPKE_HKDF_SHA256, EVP_HPKE_AES_256_GCM, "test"); auto server_request_context = std::move(server_seeded_request).ReleaseContext(); auto server_response_encapsulate = ObliviousHttpResponse::CreateServerObliviousResponse( "test response", server_request_context, ObliviousHttpHeaderKeyConfig::kOhttpResponseLabel, &random); EXPECT_TRUE(server_response_encapsulate.ok()); std::string response_nonce = server_response_encapsulate->EncapsulateAndSerialize().substr( 0, GetResponseNonceLength(*(server_request_context.hpke_context_))); EXPECT_EQ(response_nonce, std::string( GetResponseNonceLength(*(server_request_context.hpke_context_)), 'z')); absl::string_view expected_encrypted_response = "2a3271ac4e6a501f51d0264d3dd7d0bc8a06973b58e89c26d6dac06144"; std::string expected_encrypted_response_bytes; ASSERT_TRUE(absl::HexStringToBytes(expected_encrypted_response, &expected_encrypted_response_bytes)); EXPECT_EQ( server_response_encapsulate->EncapsulateAndSerialize().substr( GetResponseNonceLength(*(server_request_context.hpke_context_))), expected_encrypted_response_bytes); } }
386
cpp
google/quiche
array_output_buffer
quiche/http2/core/array_output_buffer.cc
quiche/http2/core/array_output_buffer_test.cc
#ifndef QUICHE_SPDY_CORE_ARRAY_OUTPUT_BUFFER_H_ #define QUICHE_SPDY_CORE_ARRAY_OUTPUT_BUFFER_H_ #include <cstddef> #include <cstdint> #include "quiche/common/platform/api/quiche_export.h" #include "quiche/spdy/core/zero_copy_output_buffer.h" namespace spdy { class QUICHE_EXPORT ArrayOutputBuffer : public ZeroCopyOutputBuffer { public: ArrayOutputBuffer(char* buffer, int64_t size) : current_(buffer), begin_(buffer), capacity_(size) {} ~ArrayOutputBuffer() override {} ArrayOutputBuffer(const ArrayOutputBuffer&) = delete; ArrayOutputBuffer& operator=(const ArrayOutputBuffer&) = delete; void Next(char** data, int* size) override; void AdvanceWritePtr(int64_t count) override; uint64_t BytesFree() const override; size_t Size() const { return current_ - begin_; } char* Begin() const { return begin_; } void Reset() { capacity_ += Size(); current_ = begin_; } private: char* current_ = nullptr; char* begin_ = nullptr; uint64_t capacity_ = 0; }; } #endif #include "quiche/spdy/core/array_output_buffer.h" #include <cstdint> namespace spdy { void ArrayOutputBuffer::Next(char** data, int* size) { *data = current_; *size = capacity_ > 0 ? capacity_ : 0; } void ArrayOutputBuffer::AdvanceWritePtr(int64_t count) { current_ += count; capacity_ -= count; } uint64_t ArrayOutputBuffer::BytesFree() const { return capacity_; } }
#include "quiche/spdy/core/array_output_buffer.h" #include <cstdint> #include <cstring> #include "quiche/common/platform/api/quiche_test.h" namespace spdy { namespace test { TEST(ArrayOutputBufferTest, InitializedFromArray) { char array[100]; ArrayOutputBuffer buffer(array, sizeof(array)); EXPECT_EQ(sizeof(array), buffer.BytesFree()); EXPECT_EQ(0u, buffer.Size()); EXPECT_EQ(array, buffer.Begin()); } TEST(ArrayOutputBufferTest, WriteAndReset) { char array[100]; ArrayOutputBuffer buffer(array, sizeof(array)); char* dst; int size; buffer.Next(&dst, &size); ASSERT_GT(size, 1); ASSERT_NE(nullptr, dst); const int64_t written = size / 2; memset(dst, 'x', written); buffer.AdvanceWritePtr(written); EXPECT_EQ(static_cast<uint64_t>(size) - written, buffer.BytesFree()); EXPECT_EQ(static_cast<uint64_t>(written), buffer.Size()); buffer.Reset(); EXPECT_EQ(sizeof(array), buffer.BytesFree()); EXPECT_EQ(0u, buffer.Size()); } } }
387
cpp
google/quiche
spdy_alt_svc_wire_format
quiche/http2/core/spdy_alt_svc_wire_format.cc
quiche/http2/core/spdy_alt_svc_wire_format_test.cc
#ifndef QUICHE_SPDY_CORE_SPDY_ALT_SVC_WIRE_FORMAT_H_ #define QUICHE_SPDY_CORE_SPDY_ALT_SVC_WIRE_FORMAT_H_ #include <cstdint> #include <string> #include <vector> #include "absl/container/inlined_vector.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_export.h" namespace spdy { namespace test { class SpdyAltSvcWireFormatPeer; } class QUICHE_EXPORT SpdyAltSvcWireFormat { public: using VersionVector = absl::InlinedVector<uint32_t, 8>; struct QUICHE_EXPORT AlternativeService { std::string protocol_id; std::string host; uint16_t port = 0; uint32_t max_age_seconds = 86400; VersionVector version; AlternativeService(); AlternativeService(const std::string& protocol_id, const std::string& host, uint16_t port, uint32_t max_age_seconds, VersionVector version); AlternativeService(const AlternativeService& other); ~AlternativeService(); bool operator==(const AlternativeService& other) const { return protocol_id == other.protocol_id && host == other.host && port == other.port && version == other.version && max_age_seconds == other.max_age_seconds; } }; typedef std::vector<AlternativeService> AlternativeServiceVector; friend class test::SpdyAltSvcWireFormatPeer; static bool ParseHeaderFieldValue(absl::string_view value, AlternativeServiceVector* altsvc_vector); static std::string SerializeHeaderFieldValue( const AlternativeServiceVector& altsvc_vector); private: static void SkipWhiteSpace(absl::string_view::const_iterator* c, absl::string_view::const_iterator end); static bool PercentDecode(absl::string_view::const_iterator c, absl::string_view::const_iterator end, std::string* output); static bool ParseAltAuthority(absl::string_view::const_iterator c, absl::string_view::const_iterator end, std::string* host, uint16_t* port); static bool ParsePositiveInteger16(absl::string_view::const_iterator c, absl::string_view::const_iterator end, uint16_t* value); static bool ParsePositiveInteger32(absl::string_view::const_iterator c, absl::string_view::const_iterator end, uint32_t* value); static char HexDigitToInt(char c); static bool HexDecodeToUInt32(absl::string_view data, uint32_t* value); }; } #endif #include "quiche/spdy/core/spdy_alt_svc_wire_format.h" #include <algorithm> #include <cctype> #include <cstdint> #include <limits> #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_logging.h" namespace spdy { namespace { template <class T> bool ParsePositiveIntegerImpl(absl::string_view::const_iterator c, absl::string_view::const_iterator end, T* value) { *value = 0; for (; c != end && std::isdigit(*c); ++c) { if (*value > std::numeric_limits<T>::max() / 10) { return false; } *value *= 10; if (*value > std::numeric_limits<T>::max() - (*c - '0')) { return false; } *value += *c - '0'; } return (c == end && *value > 0); } } SpdyAltSvcWireFormat::AlternativeService::AlternativeService() = default; SpdyAltSvcWireFormat::AlternativeService::AlternativeService( const std::string& protocol_id, const std::string& host, uint16_t port, uint32_t max_age_seconds, VersionVector version) : protocol_id(protocol_id), host(host), port(port), max_age_seconds(max_age_seconds), version(std::move(version)) {} SpdyAltSvcWireFormat::AlternativeService::~AlternativeService() = default; SpdyAltSvcWireFormat::AlternativeService::AlternativeService( const AlternativeService& other) = default; bool SpdyAltSvcWireFormat::ParseHeaderFieldValue( absl::string_view value, AlternativeServiceVector* altsvc_vector) { if (value.empty()) { return false; } altsvc_vector->clear(); if (value == absl::string_view("clear")) { return true; } absl::string_view::const_iterator c = value.begin(); while (c != value.end()) { absl::string_view::const_iterator percent_encoded_protocol_id_end = std::find(c, value.end(), '='); std::string protocol_id; if (percent_encoded_protocol_id_end == c || !PercentDecode(c, percent_encoded_protocol_id_end, &protocol_id)) { return false; } const bool is_ietf_format_quic = (protocol_id == "hq"); c = percent_encoded_protocol_id_end; if (c == value.end()) { return false; } QUICHE_DCHECK_EQ('=', *c); ++c; if (c == value.end() || *c != '"') { return false; } ++c; absl::string_view::const_iterator alt_authority_begin = c; for (; c != value.end() && *c != '"'; ++c) { if (*c != '\\') { continue; } ++c; if (c == value.end()) { return false; } } if (c == alt_authority_begin || c == value.end()) { return false; } QUICHE_DCHECK_EQ('"', *c); std::string host; uint16_t port; if (!ParseAltAuthority(alt_authority_begin, c, &host, &port)) { return false; } ++c; uint32_t max_age_seconds = 86400; VersionVector version; absl::string_view::const_iterator parameters_end = std::find(c, value.end(), ','); while (c != parameters_end) { SkipWhiteSpace(&c, parameters_end); if (c == parameters_end) { break; } if (*c != ';') { return false; } ++c; SkipWhiteSpace(&c, parameters_end); if (c == parameters_end) { break; } std::string parameter_name; for (; c != parameters_end && *c != '=' && *c != ' ' && *c != '\t'; ++c) { parameter_name.push_back(tolower(*c)); } SkipWhiteSpace(&c, parameters_end); if (c == parameters_end || *c != '=') { return false; } ++c; SkipWhiteSpace(&c, parameters_end); absl::string_view::const_iterator parameter_value_begin = c; for (; c != parameters_end && *c != ';' && *c != ' ' && *c != '\t'; ++c) { } if (c == parameter_value_begin) { return false; } if (parameter_name == "ma") { if (!ParsePositiveInteger32(parameter_value_begin, c, &max_age_seconds)) { return false; } } else if (!is_ietf_format_quic && parameter_name == "v") { if (*parameter_value_begin != '"') { return false; } c = std::find(parameter_value_begin + 1, value.end(), '"'); if (c == value.end()) { return false; } ++c; parameters_end = std::find(c, value.end(), ','); absl::string_view::const_iterator v_begin = parameter_value_begin + 1; while (v_begin < c) { absl::string_view::const_iterator v_end = v_begin; while (v_end < c - 1 && *v_end != ',') { ++v_end; } uint16_t v; if (!ParsePositiveInteger16(v_begin, v_end, &v)) { return false; } version.push_back(v); v_begin = v_end + 1; if (v_begin == c - 1) { return false; } } } else if (is_ietf_format_quic && parameter_name == "quic") { if (*parameter_value_begin == '0') { return false; } uint32_t quic_version; if (!HexDecodeToUInt32(absl::string_view(&*parameter_value_begin, c - parameter_value_begin), &quic_version) || quic_version == 0) { return false; } version.push_back(quic_version); } } altsvc_vector->emplace_back(protocol_id, host, port, max_age_seconds, version); for (; c != value.end() && (*c == ' ' || *c == '\t' || *c == ','); ++c) { } } return true; } std::string SpdyAltSvcWireFormat::SerializeHeaderFieldValue( const AlternativeServiceVector& altsvc_vector) { if (altsvc_vector.empty()) { return std::string("clear"); } const char kNibbleToHex[] = "0123456789ABCDEF"; std::string value; for (const AlternativeService& altsvc : altsvc_vector) { if (!value.empty()) { value.push_back(','); } const bool is_ietf_format_quic = (altsvc.protocol_id == "hq"); for (char c : altsvc.protocol_id) { if (isalnum(c)) { value.push_back(c); continue; } switch (c) { case '!': case '#': case '$': case '&': case '\'': case '*': case '+': case '-': case '.': case '^': case '_': case '`': case '|': case '~': value.push_back(c); break; default: value.push_back('%'); value.push_back(kNibbleToHex[c >> 4]); value.push_back(kNibbleToHex[c & 0x0f]); break; } } value.push_back('='); value.push_back('"'); for (char c : altsvc.host) { if (c == '"' || c == '\\') { value.push_back('\\'); } value.push_back(c); } absl::StrAppend(&value, ":", altsvc.port, "\""); if (altsvc.max_age_seconds != 86400) { absl::StrAppend(&value, "; ma=", altsvc.max_age_seconds); } if (!altsvc.version.empty()) { if (is_ietf_format_quic) { for (uint32_t quic_version : altsvc.version) { absl::StrAppend(&value, "; quic=", absl::Hex(quic_version)); } } else { value.append("; v=\""); for (auto it = altsvc.version.begin(); it != altsvc.version.end(); ++it) { if (it != altsvc.version.begin()) { value.append(","); } absl::StrAppend(&value, *it); } value.append("\""); } } } return value; } void SpdyAltSvcWireFormat::SkipWhiteSpace( absl::string_view::const_iterator* c, absl::string_view::const_iterator end) { for (; *c != end && (**c == ' ' || **c == '\t'); ++*c) { } } bool SpdyAltSvcWireFormat::PercentDecode(absl::string_view::const_iterator c, absl::string_view::const_iterator end, std::string* output) { output->clear(); for (; c != end; ++c) { if (*c != '%') { output->push_back(*c); continue; } QUICHE_DCHECK_EQ('%', *c); ++c; if (c == end || !std::isxdigit(*c)) { return false; } char decoded = HexDigitToInt(*c) << 4; ++c; if (c == end || !std::isxdigit(*c)) { return false; } decoded += HexDigitToInt(*c); output->push_back(decoded); } return true; } bool SpdyAltSvcWireFormat::ParseAltAuthority( absl::string_view::const_iterator c, absl::string_view::const_iterator end, std::string* host, uint16_t* port) { host->clear(); if (c == end) { return false; } if (*c == '[') { for (; c != end && *c != ']'; ++c) { if (*c == '"') { return false; } host->push_back(*c); } if (c == end) { return false; } QUICHE_DCHECK_EQ(']', *c); host->push_back(*c); ++c; } else { for (; c != end && *c != ':'; ++c) { if (*c == '"') { return false; } if (*c == '\\') { ++c; if (c == end) { return false; } } host->push_back(*c); } } if (c == end || *c != ':') { return false; } QUICHE_DCHECK_EQ(':', *c); ++c; return ParsePositiveInteger16(c, end, port); } bool SpdyAltSvcWireFormat::ParsePositiveInteger16( absl::string_view::const_iterator c, absl::string_view::const_iterator end, uint16_t* value) { return ParsePositiveIntegerImpl<uint16_t>(c, end, value); } bool SpdyAltSvcWireFormat::ParsePositiveInteger32( absl::string_view::const_iterator c, absl::string_view::const_iterator end, uint32_t* value) { return ParsePositiveIntegerImpl<uint32_t>(c, end, value); } char SpdyAltSvcWireFormat::HexDigitToInt(char c) { QUICHE_DCHECK(std::isxdigit(c)); if (std::isdigit(c)) { return c - '0'; } if (c >= 'A' && c <= 'F') { return c - 'A' + 10; } if (c >= 'a' && c <= 'f') { return c - 'a' + 10; } return 0; } bool SpdyAltSvcWireFormat::HexDecodeToUInt32(absl::string_view data, uint32_t* value) { if (data.empty() || data.length() > 8u) { return false; } *value = 0; for (char c : data) { if (!std::isxdigit(c)) { return false; } *value <<= 4; *value += HexDigitToInt(c); } return true; } }
#include "quiche/spdy/core/spdy_alt_svc_wire_format.h" #include <cstddef> #include <cstdint> #include <string> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_test.h" namespace spdy { namespace test { class SpdyAltSvcWireFormatPeer { public: static void SkipWhiteSpace(absl::string_view::const_iterator* c, absl::string_view::const_iterator end) { SpdyAltSvcWireFormat::SkipWhiteSpace(c, end); } static bool PercentDecode(absl::string_view::const_iterator c, absl::string_view::const_iterator end, std::string* output) { return SpdyAltSvcWireFormat::PercentDecode(c, end, output); } static bool ParseAltAuthority(absl::string_view::const_iterator c, absl::string_view::const_iterator end, std::string* host, uint16_t* port) { return SpdyAltSvcWireFormat::ParseAltAuthority(c, end, host, port); } static bool ParsePositiveInteger16(absl::string_view::const_iterator c, absl::string_view::const_iterator end, uint16_t* max_age_seconds) { return SpdyAltSvcWireFormat::ParsePositiveInteger16(c, end, max_age_seconds); } static bool ParsePositiveInteger32(absl::string_view::const_iterator c, absl::string_view::const_iterator end, uint32_t* max_age_seconds) { return SpdyAltSvcWireFormat::ParsePositiveInteger32(c, end, max_age_seconds); } static char HexDigitToInt(char c) { return SpdyAltSvcWireFormat::HexDigitToInt(c); } static bool HexDecodeToUInt32(absl::string_view data, uint32_t* value) { return SpdyAltSvcWireFormat::HexDecodeToUInt32(data, value); } }; namespace { void FuzzHeaderFieldValue( int i, std::string* header_field_value, SpdyAltSvcWireFormat::AlternativeService* expected_altsvc) { if (!header_field_value->empty()) { header_field_value->push_back(','); } bool is_ietf_format_quic = (i & 1 << 0) != 0; if (i & 1 << 0) { expected_altsvc->protocol_id = "hq"; header_field_value->append("hq=\""); } else { expected_altsvc->protocol_id = "a=b%c"; header_field_value->append("a%3Db%25c=\""); } if (i & 1 << 1) { expected_altsvc->host = "foo\"bar\\baz"; header_field_value->append("foo\\\"bar\\\\baz"); } else { expected_altsvc->host = ""; } expected_altsvc->port = 42; header_field_value->append(":42\""); if (i & 1 << 2) { header_field_value->append(" "); } if (i & 3 << 3) { expected_altsvc->max_age_seconds = 1111; header_field_value->append(";"); if (i & 1 << 3) { header_field_value->append(" "); } header_field_value->append("mA=1111"); if (i & 2 << 3) { header_field_value->append(" "); } } if (i & 1 << 5) { header_field_value->append("; J=s"); } if (i & 1 << 6) { if (is_ietf_format_quic) { if (i & 1 << 7) { expected_altsvc->version.push_back(0x923457e); header_field_value->append("; quic=923457E"); } else { expected_altsvc->version.push_back(1); expected_altsvc->version.push_back(0xFFFFFFFF); header_field_value->append("; quic=1; quic=fFfFffFf"); } } else { if (i & i << 7) { expected_altsvc->version.push_back(24); header_field_value->append("; v=\"24\""); } else { expected_altsvc->version.push_back(1); expected_altsvc->version.push_back(65535); header_field_value->append("; v=\"1,65535\""); } } } if (i & 1 << 8) { expected_altsvc->max_age_seconds = 999999999; header_field_value->append("; Ma=999999999"); } if (i & 1 << 9) { header_field_value->append(";"); } if (i & 1 << 10) { header_field_value->append(" "); } if (i & 1 << 11) { header_field_value->append(","); } if (i & 1 << 12) { header_field_value->append(" "); } } void FuzzAlternativeService(int i, SpdyAltSvcWireFormat::AlternativeService* altsvc, std::string* expected_header_field_value) { if (!expected_header_field_value->empty()) { expected_header_field_value->push_back(','); } altsvc->protocol_id = "a=b%c"; altsvc->port = 42; expected_header_field_value->append("a%3Db%25c=\""); if (i & 1 << 0) { altsvc->host = "foo\"bar\\baz"; expected_header_field_value->append("foo\\\"bar\\\\baz"); } expected_header_field_value->append(":42\""); if (i & 1 << 1) { altsvc->max_age_seconds = 1111; expected_header_field_value->append("; ma=1111"); } if (i & 1 << 2) { altsvc->version.push_back(24); altsvc->version.push_back(25); expected_header_field_value->append("; v=\"24,25\""); } } TEST(SpdyAltSvcWireFormatTest, DefaultValues) { SpdyAltSvcWireFormat::AlternativeService altsvc; EXPECT_EQ("", altsvc.protocol_id); EXPECT_EQ("", altsvc.host); EXPECT_EQ(0u, altsvc.port); EXPECT_EQ(86400u, altsvc.max_age_seconds); EXPECT_TRUE(altsvc.version.empty()); } TEST(SpdyAltSvcWireFormatTest, ParseInvalidEmptyHeaderFieldValue) { SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; ASSERT_FALSE(SpdyAltSvcWireFormat::ParseHeaderFieldValue("", &altsvc_vector)); } TEST(SpdyAltSvcWireFormatTest, ParseHeaderFieldValueClear) { SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; ASSERT_TRUE( SpdyAltSvcWireFormat::ParseHeaderFieldValue("clear", &altsvc_vector)); EXPECT_EQ(0u, altsvc_vector.size()); } TEST(SpdyAltSvcWireFormatTest, ParseHeaderFieldValue) { for (int i = 0; i < 1 << 13; ++i) { std::string header_field_value; SpdyAltSvcWireFormat::AlternativeService expected_altsvc; FuzzHeaderFieldValue(i, &header_field_value, &expected_altsvc); SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; ASSERT_TRUE(SpdyAltSvcWireFormat::ParseHeaderFieldValue(header_field_value, &altsvc_vector)); ASSERT_EQ(1u, altsvc_vector.size()); EXPECT_EQ(expected_altsvc.protocol_id, altsvc_vector[0].protocol_id); EXPECT_EQ(expected_altsvc.host, altsvc_vector[0].host); EXPECT_EQ(expected_altsvc.port, altsvc_vector[0].port); EXPECT_EQ(expected_altsvc.max_age_seconds, altsvc_vector[0].max_age_seconds); EXPECT_EQ(expected_altsvc.version, altsvc_vector[0].version); std::string reserialized_header_field_value = SpdyAltSvcWireFormat::SerializeHeaderFieldValue(altsvc_vector); SpdyAltSvcWireFormat::AlternativeServiceVector roundtrip_altsvc_vector; ASSERT_TRUE(SpdyAltSvcWireFormat::ParseHeaderFieldValue( reserialized_header_field_value, &roundtrip_altsvc_vector)); ASSERT_EQ(1u, roundtrip_altsvc_vector.size()); EXPECT_EQ(expected_altsvc.protocol_id, roundtrip_altsvc_vector[0].protocol_id); EXPECT_EQ(expected_altsvc.host, roundtrip_altsvc_vector[0].host); EXPECT_EQ(expected_altsvc.port, roundtrip_altsvc_vector[0].port); EXPECT_EQ(expected_altsvc.max_age_seconds, roundtrip_altsvc_vector[0].max_age_seconds); EXPECT_EQ(expected_altsvc.version, roundtrip_altsvc_vector[0].version); } } TEST(SpdyAltSvcWireFormatTest, ParseHeaderFieldValueMultiple) { for (int i = 0; i < 1 << 13;) { std::string header_field_value; SpdyAltSvcWireFormat::AlternativeServiceVector expected_altsvc_vector; do { SpdyAltSvcWireFormat::AlternativeService expected_altsvc; FuzzHeaderFieldValue(i, &header_field_value, &expected_altsvc); expected_altsvc_vector.push_back(expected_altsvc); ++i; } while (i % 6 < i % 7); SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; ASSERT_TRUE(SpdyAltSvcWireFormat::ParseHeaderFieldValue(header_field_value, &altsvc_vector)); ASSERT_EQ(expected_altsvc_vector.size(), altsvc_vector.size()); for (unsigned int j = 0; j < altsvc_vector.size(); ++j) { EXPECT_EQ(expected_altsvc_vector[j].protocol_id, altsvc_vector[j].protocol_id); EXPECT_EQ(expected_altsvc_vector[j].host, altsvc_vector[j].host); EXPECT_EQ(expected_altsvc_vector[j].port, altsvc_vector[j].port); EXPECT_EQ(expected_altsvc_vector[j].max_age_seconds, altsvc_vector[j].max_age_seconds); EXPECT_EQ(expected_altsvc_vector[j].version, altsvc_vector[j].version); } std::string reserialized_header_field_value = SpdyAltSvcWireFormat::SerializeHeaderFieldValue(altsvc_vector); SpdyAltSvcWireFormat::AlternativeServiceVector roundtrip_altsvc_vector; ASSERT_TRUE(SpdyAltSvcWireFormat::ParseHeaderFieldValue( reserialized_header_field_value, &roundtrip_altsvc_vector)); ASSERT_EQ(expected_altsvc_vector.size(), roundtrip_altsvc_vector.size()); for (unsigned int j = 0; j < roundtrip_altsvc_vector.size(); ++j) { EXPECT_EQ(expected_altsvc_vector[j].protocol_id, roundtrip_altsvc_vector[j].protocol_id); EXPECT_EQ(expected_altsvc_vector[j].host, roundtrip_altsvc_vector[j].host); EXPECT_EQ(expected_altsvc_vector[j].port, roundtrip_altsvc_vector[j].port); EXPECT_EQ(expected_altsvc_vector[j].max_age_seconds, roundtrip_altsvc_vector[j].max_age_seconds); EXPECT_EQ(expected_altsvc_vector[j].version, roundtrip_altsvc_vector[j].version); } } } TEST(SpdyAltSvcWireFormatTest, SerializeEmptyHeaderFieldValue) { SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; EXPECT_EQ("clear", SpdyAltSvcWireFormat::SerializeHeaderFieldValue(altsvc_vector)); } TEST(SpdyAltSvcWireFormatTest, RoundTrip) { for (int i = 0; i < 1 << 3; ++i) { SpdyAltSvcWireFormat::AlternativeService altsvc; std::string expected_header_field_value; FuzzAlternativeService(i, &altsvc, &expected_header_field_value); SpdyAltSvcWireFormat::AlternativeServiceVector parsed_altsvc_vector; ASSERT_TRUE(SpdyAltSvcWireFormat::ParseHeaderFieldValue( expected_header_field_value, &parsed_altsvc_vector)); ASSERT_EQ(1u, parsed_altsvc_vector.size()); EXPECT_EQ(altsvc.protocol_id, parsed_altsvc_vector[0].protocol_id); EXPECT_EQ(altsvc.host, parsed_altsvc_vector[0].host); EXPECT_EQ(altsvc.port, parsed_altsvc_vector[0].port); EXPECT_EQ(altsvc.max_age_seconds, parsed_altsvc_vector[0].max_age_seconds); EXPECT_EQ(altsvc.version, parsed_altsvc_vector[0].version); SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; altsvc_vector.push_back(altsvc); EXPECT_EQ(expected_header_field_value, SpdyAltSvcWireFormat::SerializeHeaderFieldValue(altsvc_vector)); } } TEST(SpdyAltSvcWireFormatTest, RoundTripMultiple) { SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; std::string expected_header_field_value; for (int i = 0; i < 1 << 3; ++i) { SpdyAltSvcWireFormat::AlternativeService altsvc; FuzzAlternativeService(i, &altsvc, &expected_header_field_value); altsvc_vector.push_back(altsvc); } SpdyAltSvcWireFormat::AlternativeServiceVector parsed_altsvc_vector; ASSERT_TRUE(SpdyAltSvcWireFormat::ParseHeaderFieldValue( expected_header_field_value, &parsed_altsvc_vector)); ASSERT_EQ(altsvc_vector.size(), parsed_altsvc_vector.size()); auto expected_it = altsvc_vector.begin(); auto parsed_it = parsed_altsvc_vector.begin(); for (; expected_it != altsvc_vector.end(); ++expected_it, ++parsed_it) { EXPECT_EQ(expected_it->protocol_id, parsed_it->protocol_id); EXPECT_EQ(expected_it->host, parsed_it->host); EXPECT_EQ(expected_it->port, parsed_it->port); EXPECT_EQ(expected_it->max_age_seconds, parsed_it->max_age_seconds); EXPECT_EQ(expected_it->version, parsed_it->version); } EXPECT_EQ(expected_header_field_value, SpdyAltSvcWireFormat::SerializeHeaderFieldValue(altsvc_vector)); } TEST(SpdyAltSvcWireFormatTest, ParseHeaderFieldValueInvalid) { SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; const char* invalid_field_value_array[] = {"a%", "a%x", "a%b", "a%9z", "a=", "a=\"", "a=\"b\"", "a=\":\"", "a=\"c:\"", "a=\"c:foo\"", "a=\"c:42foo\"", "a=\"b:42\"bar", "a=\"b:42\" ; m", "a=\"b:42\" ; min-age", "a=\"b:42\" ; ma", "a=\"b:42\" ; ma=", "a=\"b:42\" ; v=\"..\"", "a=\"b:42\" ; ma=ma", "a=\"b:42\" ; ma=123bar", "a=\"b:42\" ; v=24", "a=\"b:42\" ; v=24,25", "a=\"b:42\" ; v=\"-3\"", "a=\"b:42\" ; v=\"1.2\"", "a=\"b:42\" ; v=\"24,\""}; for (const char* invalid_field_value : invalid_field_value_array) { EXPECT_FALSE(SpdyAltSvcWireFormat::ParseHeaderFieldValue( invalid_field_value, &altsvc_vector)) << invalid_field_value; } } TEST(SpdyAltSvcWireFormatTest, ParseTruncatedHeaderFieldValue) { SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; const char* field_value_array[] = {"a=\":137\"", "a=\"foo:137\"", "a%25=\"foo\\\"bar\\\\baz:137\""}; for (const absl::string_view field_value : field_value_array) { for (size_t len = 1; len < field_value.size(); ++len) { EXPECT_FALSE(SpdyAltSvcWireFormat::ParseHeaderFieldValue( field_value.substr(0, len), &altsvc_vector)) << len; } } } TEST(SpdyAltSvcWireFormatTest, SkipWhiteSpace) { absl::string_view input("a \tb "); absl::string_view::const_iterator c = input.begin(); SpdyAltSvcWireFormatPeer::SkipWhiteSpace(&c, input.end()); ASSERT_EQ(input.begin(), c); ++c; SpdyAltSvcWireFormatPeer::SkipWhiteSpace(&c, input.end()); ASSERT_EQ(input.begin() + 3, c); ++c; SpdyAltSvcWireFormatPeer::SkipWhiteSpace(&c, input.end()); ASSERT_EQ(input.end(), c); } TEST(SpdyAltSvcWireFormatTest, PercentDecodeValid) { absl::string_view input(""); std::string output; ASSERT_TRUE(SpdyAltSvcWireFormatPeer::PercentDecode(input.begin(), input.end(), &output)); EXPECT_EQ("", output); input = absl::string_view("foo"); output.clear(); ASSERT_TRUE(SpdyAltSvcWireFormatPeer::PercentDecode(input.begin(), input.end(), &output)); EXPECT_EQ("foo", output); input = absl::string_view("%2ca%5Cb"); output.clear(); ASSERT_TRUE(SpdyAltSvcWireFormatPeer::PercentDecode(input.begin(), input.end(), &output)); EXPECT_EQ(",a\\b", output); } TEST(SpdyAltSvcWireFormatTest, PercentDecodeInvalid) { const char* invalid_input_array[] = {"a%", "a%x", "a%b", "%J22", "%9z"}; for (const char* invalid_input : invalid_input_array) { absl::string_view input(invalid_input); std::string output; EXPECT_FALSE(SpdyAltSvcWireFormatPeer::PercentDecode(input.begin(), input.end(), &output)) << input; } } TEST(SpdyAltSvcWireFormatTest, ParseAltAuthorityValid) { absl::string_view input(":42"); std::string host; uint16_t port; ASSERT_TRUE(SpdyAltSvcWireFormatPeer::ParseAltAuthority( input.begin(), input.end(), &host, &port)); EXPECT_TRUE(host.empty()); EXPECT_EQ(42, port); input = absl::string_view("foo:137"); ASSERT_TRUE(SpdyAltSvcWireFormatPeer::ParseAltAuthority( input.begin(), input.end(), &host, &port)); EXPECT_EQ("foo", host); EXPECT_EQ(137, port); input = absl::string_view("[2003:8:0:16::509d:9615]:443"); ASSERT_TRUE(SpdyAltSvcWireFormatPeer::ParseAltAuthority( input.begin(), input.end(), &host, &port)); EXPECT_EQ("[2003:8:0:16::509d:9615]", host); EXPECT_EQ(443, port); } TEST(SpdyAltSvcWireFormatTest, ParseAltAuthorityInvalid) { const char* invalid_input_array[] = {"", ":", "foo:", ":bar", ":0", "foo:0", ":12bar", "foo:23bar", " ", ":12 ", "foo:12 ", "[2003:8:0:16::509d:9615]", "[2003:8:0:16::509d:9615]:", "[2003:8:0:16::509d:9615]foo:443", "[2003:8:0:16::509d:9615:443", "2003:8:0:16::509d:9615]:443"}; for (const char* invalid_input : invalid_input_array) { absl::string_view input(invalid_input); std::string host; uint16_t port; EXPECT_FALSE(SpdyAltSvcWireFormatPeer::ParseAltAuthority( input.begin(), input.end(), &host, &port)) << input; } } TEST(SpdyAltSvcWireFormatTest, ParseIntegerValid) { absl::string_view input("3"); uint16_t value; ASSERT_TRUE(SpdyAltSvcWireFormatPeer::ParsePositiveInteger16( input.begin(), input.end(), &value)); EXPECT_EQ(3, value); input = absl::string_view("1337"); ASSERT_TRUE(SpdyAltSvcWireFormatPeer::ParsePositiveInteger16( input.begin(), input.end(), &value)); EXPECT_EQ(1337, value); } TEST(SpdyAltSvcWireFormatTest, ParseIntegerInvalid) { const char* invalid_input_array[] = {"", " ", "a", "0", "00", "1 ", "12b"}; for (const char* invalid_input : invalid_input_array) { absl::string_view input(invalid_input); uint16_t value; EXPECT_FALSE(SpdyAltSvcWireFormatPeer::ParsePositiveInteger16( input.begin(), input.end(), &value)) << input; } } TEST(SpdyAltSvcWireFormatTest, ParseIntegerOverflow) { absl::string_view input("65535"); uint16_t value16; ASSERT_TRUE(SpdyAltSvcWireFormatPeer::ParsePositiveInteger16( input.begin(), input.end(), &value16)); EXPECT_EQ(65535, value16); input = absl::string_view("65536"); ASSERT_FALSE(SpdyAltSvcWireFormatPeer::ParsePositiveInteger16( input.begin(), input.end(), &value16)); input = absl::string_view("65537"); ASSERT_FALSE(SpdyAltSvcWireFormatPeer::ParsePositiveInteger16( input.begin(), input.end(), &value16)); input = absl::string_view("4294967295"); uint32_t value32; ASSERT_TRUE(SpdyAltSvcWireFormatPeer::ParsePositiveInteger32( input.begin(), input.end(), &value32)); EXPECT_EQ(4294967295, value32); input = absl::string_view("4294967296"); ASSERT_FALSE(SpdyAltSvcWireFormatPeer::ParsePositiveInteger32( input.begin(), input.end(), &value32)); input = absl::string_view("4294967297"); ASSERT_FALSE(SpdyAltSvcWireFormatPeer::ParsePositiveInteger32( input.begin(), input.end(), &value32)); } TEST(SpdyAltSvcWireFormatTest, ParseIPLiteral) { const char* input = "quic=\"[2003:8:0:16::509d:9615]:443\"; v=\"36,35\"; ma=60"; SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; ASSERT_TRUE( SpdyAltSvcWireFormat::ParseHeaderFieldValue(input, &altsvc_vector)); EXPECT_EQ(1u, altsvc_vector.size()); EXPECT_EQ("quic", altsvc_vector[0].protocol_id); EXPECT_EQ("[2003:8:0:16::509d:9615]", altsvc_vector[0].host); EXPECT_EQ(443u, altsvc_vector[0].port); EXPECT_EQ(60u, altsvc_vector[0].max_age_seconds); EXPECT_THAT(altsvc_vector[0].version, ::testing::ElementsAre(36, 35)); } TEST(SpdyAltSvcWireFormatTest, HexDigitToInt) { EXPECT_EQ(0, SpdyAltSvcWireFormatPeer::HexDigitToInt('0')); EXPECT_EQ(1, SpdyAltSvcWireFormatPeer::HexDigitToInt('1')); EXPECT_EQ(2, SpdyAltSvcWireFormatPeer::HexDigitToInt('2')); EXPECT_EQ(3, SpdyAltSvcWireFormatPeer::HexDigitToInt('3')); EXPECT_EQ(4, SpdyAltSvcWireFormatPeer::HexDigitToInt('4')); EXPECT_EQ(5, SpdyAltSvcWireFormatPeer::HexDigitToInt('5')); EXPECT_EQ(6, SpdyAltSvcWireFormatPeer::HexDigitToInt('6')); EXPECT_EQ(7, SpdyAltSvcWireFormatPeer::HexDigitToInt('7')); EXPECT_EQ(8, SpdyAltSvcWireFormatPeer::HexDigitToInt('8')); EXPECT_EQ(9, SpdyAltSvcWireFormatPeer::HexDigitToInt('9')); EXPECT_EQ(10, SpdyAltSvcWireFormatPeer::HexDigitToInt('a')); EXPECT_EQ(11, SpdyAltSvcWireFormatPeer::HexDigitToInt('b')); EXPECT_EQ(12, SpdyAltSvcWireFormatPeer::HexDigitToInt('c')); EXPECT_EQ(13, SpdyAltSvcWireFormatPeer::HexDigitToInt('d')); EXPECT_EQ(14, SpdyAltSvcWireFormatPeer::HexDigitToInt('e')); EXPECT_EQ(15, SpdyAltSvcWireFormatPeer::HexDigitToInt('f')); EXPECT_EQ(10, SpdyAltSvcWireFormatPeer::HexDigitToInt('A')); EXPECT_EQ(11, SpdyAltSvcWireFormatPeer::HexDigitToInt('B')); EXPECT_EQ(12, SpdyAltSvcWireFormatPeer::HexDigitToInt('C')); EXPECT_EQ(13, SpdyAltSvcWireFormatPeer::HexDigitToInt('D')); EXPECT_EQ(14, SpdyAltSvcWireFormatPeer::HexDigitToInt('E')); EXPECT_EQ(15, SpdyAltSvcWireFormatPeer::HexDigitToInt('F')); } TEST(SpdyAltSvcWireFormatTest, HexDecodeToUInt32) { uint32_t out; EXPECT_TRUE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("0", &out)); EXPECT_EQ(0u, out); EXPECT_TRUE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("00", &out)); EXPECT_EQ(0u, out); EXPECT_TRUE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("0000000", &out)); EXPECT_EQ(0u, out); EXPECT_TRUE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("00000000", &out)); EXPECT_EQ(0u, out); EXPECT_TRUE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("1", &out)); EXPECT_EQ(1u, out); EXPECT_TRUE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("ffffFFF", &out)); EXPECT_EQ(0xFFFFFFFu, out); EXPECT_TRUE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("fFfFffFf", &out)); EXPECT_EQ(0xFFFFFFFFu, out); EXPECT_TRUE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("01AEF", &out)); EXPECT_EQ(0x1AEFu, out); EXPECT_TRUE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("abcde", &out)); EXPECT_EQ(0xABCDEu, out); EXPECT_TRUE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("1234abcd", &out)); EXPECT_EQ(0x1234ABCDu, out); EXPECT_FALSE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("", &out)); EXPECT_FALSE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("111111111", &out)); EXPECT_FALSE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("1111111111", &out)); EXPECT_FALSE(SpdyAltSvcWireFormatPeer::HexDecodeToUInt32("0x1111", &out)); } } } }
388
cpp
google/quiche
spdy_frame_builder
quiche/http2/core/spdy_frame_builder.cc
quiche/http2/core/spdy_frame_builder_test.cc
#ifndef QUICHE_SPDY_CORE_SPDY_FRAME_BUILDER_H_ #define QUICHE_SPDY_CORE_SPDY_FRAME_BUILDER_H_ #include <cstddef> #include <cstdint> #include <memory> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/quiche_endian.h" #include "quiche/spdy/core/spdy_protocol.h" #include "quiche/spdy/core/zero_copy_output_buffer.h" namespace spdy { namespace test { class SpdyFrameBuilderPeer; } class QUICHE_EXPORT SpdyFrameBuilder { public: explicit SpdyFrameBuilder(size_t size); SpdyFrameBuilder(size_t size, ZeroCopyOutputBuffer* output); ~SpdyFrameBuilder(); size_t length() const { return offset_ + length_; } bool Seek(size_t length); bool BeginNewFrame(SpdyFrameType type, uint8_t flags, SpdyStreamId stream_id); bool BeginNewFrame(SpdyFrameType type, uint8_t flags, SpdyStreamId stream_id, size_t length); bool BeginNewUncheckedFrame(uint8_t raw_frame_type, uint8_t flags, SpdyStreamId stream_id, size_t length); SpdySerializedFrame take() { QUICHE_BUG_IF(spdy_bug_39_1, output_ != nullptr) << "ZeroCopyOutputBuffer is used to build " << "frames. take() shouldn't be called"; QUICHE_BUG_IF(spdy_bug_39_2, kMaxFrameSizeLimit < length_) << "Frame length " << length_ << " is longer than the maximum possible allowed length."; SpdySerializedFrame rv(std::move(buffer_), length()); capacity_ = 0; length_ = 0; offset_ = 0; return rv; } bool WriteUInt8(uint8_t value) { return WriteBytes(&value, sizeof(value)); } bool WriteUInt16(uint16_t value) { value = quiche::QuicheEndian::HostToNet16(value); return WriteBytes(&value, sizeof(value)); } bool WriteUInt24(uint32_t value) { value = quiche::QuicheEndian::HostToNet32(value); return WriteBytes(reinterpret_cast<char*>(&value) + 1, sizeof(value) - 1); } bool WriteUInt32(uint32_t value) { value = quiche::QuicheEndian::HostToNet32(value); return WriteBytes(&value, sizeof(value)); } bool WriteUInt64(uint64_t value) { uint32_t upper = quiche::QuicheEndian::HostToNet32(static_cast<uint32_t>(value >> 32)); uint32_t lower = quiche::QuicheEndian::HostToNet32(static_cast<uint32_t>(value)); return (WriteBytes(&upper, sizeof(upper)) && WriteBytes(&lower, sizeof(lower))); } bool WriteStringPiece32(const absl::string_view value); bool WriteBytes(const void* data, uint32_t data_len); private: friend class test::SpdyFrameBuilderPeer; bool BeginNewFrameInternal(uint8_t raw_frame_type, uint8_t flags, SpdyStreamId stream_id, size_t length); char* GetWritableBuffer(size_t length); char* GetWritableOutput(size_t desired_length, size_t* actual_length); bool CanWrite(size_t length) const; std::unique_ptr<char[]> buffer_; ZeroCopyOutputBuffer* output_ = nullptr; size_t capacity_; size_t length_; size_t offset_; }; } #endif #include "quiche/spdy/core/spdy_frame_builder.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <cstring> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/spdy/core/spdy_bitmasks.h" #include "quiche/spdy/core/spdy_protocol.h" #include "quiche/spdy/core/zero_copy_output_buffer.h" namespace spdy { SpdyFrameBuilder::SpdyFrameBuilder(size_t size) : buffer_(new char[size]), capacity_(size), length_(0), offset_(0) {} SpdyFrameBuilder::SpdyFrameBuilder(size_t size, ZeroCopyOutputBuffer* output) : buffer_(output == nullptr ? new char[size] : nullptr), output_(output), capacity_(size), length_(0), offset_(0) {} SpdyFrameBuilder::~SpdyFrameBuilder() = default; char* SpdyFrameBuilder::GetWritableBuffer(size_t length) { if (!CanWrite(length)) { return nullptr; } return buffer_.get() + offset_ + length_; } char* SpdyFrameBuilder::GetWritableOutput(size_t length, size_t* actual_length) { char* dest = nullptr; int size = 0; if (!CanWrite(length)) { return nullptr; } output_->Next(&dest, &size); *actual_length = std::min<size_t>(length, size); return dest; } bool SpdyFrameBuilder::Seek(size_t length) { if (!CanWrite(length)) { return false; } if (output_ == nullptr) { length_ += length; } else { output_->AdvanceWritePtr(length); length_ += length; } return true; } bool SpdyFrameBuilder::BeginNewFrame(SpdyFrameType type, uint8_t flags, SpdyStreamId stream_id) { uint8_t raw_frame_type = SerializeFrameType(type); QUICHE_DCHECK(IsDefinedFrameType(raw_frame_type)); QUICHE_DCHECK_EQ(0u, stream_id & ~kStreamIdMask); bool success = true; if (length_ > 0) { QUICHE_BUG(spdy_bug_73_1) << "SpdyFrameBuilder doesn't have a clean state when BeginNewFrame" << "is called. Leftover length_ is " << length_; offset_ += length_; length_ = 0; } success &= WriteUInt24(capacity_ - offset_ - kFrameHeaderSize); success &= WriteUInt8(raw_frame_type); success &= WriteUInt8(flags); success &= WriteUInt32(stream_id); QUICHE_DCHECK_EQ(kDataFrameMinimumSize, length_); return success; } bool SpdyFrameBuilder::BeginNewFrame(SpdyFrameType type, uint8_t flags, SpdyStreamId stream_id, size_t length) { uint8_t raw_frame_type = SerializeFrameType(type); QUICHE_DCHECK(IsDefinedFrameType(raw_frame_type)); QUICHE_DCHECK_EQ(0u, stream_id & ~kStreamIdMask); QUICHE_BUG_IF(spdy_bug_73_2, length > kSpdyMaxFrameSizeLimit) << "Frame length " << length << " is longer than frame size limit."; return BeginNewFrameInternal(raw_frame_type, flags, stream_id, length); } bool SpdyFrameBuilder::BeginNewUncheckedFrame(uint8_t raw_frame_type, uint8_t flags, SpdyStreamId stream_id, size_t length) { return BeginNewFrameInternal(raw_frame_type, flags, stream_id, length); } bool SpdyFrameBuilder::BeginNewFrameInternal(uint8_t raw_frame_type, uint8_t flags, SpdyStreamId stream_id, size_t length) { QUICHE_DCHECK_EQ(length, length & kLengthMask); bool success = true; offset_ += length_; length_ = 0; success &= WriteUInt24(length); success &= WriteUInt8(raw_frame_type); success &= WriteUInt8(flags); success &= WriteUInt32(stream_id); QUICHE_DCHECK_EQ(kDataFrameMinimumSize, length_); return success; } bool SpdyFrameBuilder::WriteStringPiece32(const absl::string_view value) { if (!WriteUInt32(value.size())) { return false; } return WriteBytes(value.data(), value.size()); } bool SpdyFrameBuilder::WriteBytes(const void* data, uint32_t data_len) { if (!CanWrite(data_len)) { return false; } if (output_ == nullptr) { char* dest = GetWritableBuffer(data_len); memcpy(dest, data, data_len); Seek(data_len); } else { char* dest = nullptr; size_t size = 0; size_t total_written = 0; const char* data_ptr = reinterpret_cast<const char*>(data); while (data_len > 0) { dest = GetWritableOutput(data_len, &size); if (dest == nullptr || size == 0) { return false; } uint32_t to_copy = std::min<uint32_t>(data_len, size); const char* src = data_ptr + total_written; memcpy(dest, src, to_copy); Seek(to_copy); data_len -= to_copy; total_written += to_copy; } } return true; } bool SpdyFrameBuilder::CanWrite(size_t length) const { if (length > kLengthMask) { QUICHE_DCHECK(false); return false; } if (output_ == nullptr) { if (offset_ + length_ + length > capacity_) { QUICHE_DLOG(FATAL) << "Requested: " << length << " capacity: " << capacity_ << " used: " << offset_ + length_; return false; } } else { if (length > output_->BytesFree()) { return false; } } return true; } }
#include "quiche/spdy/core/spdy_frame_builder.h" #include <cstddef> #include <cstdint> #include <cstring> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/spdy/core/array_output_buffer.h" #include "quiche/spdy/core/spdy_protocol.h" #include "quiche/spdy/test_tools/spdy_test_utils.h" namespace spdy { namespace test { class QUICHE_EXPORT SpdyFrameBuilderPeer { public: static char* GetWritableBuffer(SpdyFrameBuilder* builder, size_t length) { return builder->GetWritableBuffer(length); } static char* GetWritableOutput(SpdyFrameBuilder* builder, size_t desired_length, size_t* actual_length) { return builder->GetWritableOutput(desired_length, actual_length); } }; namespace { const int64_t kSize = 64 * 1024; char output_buffer[kSize] = ""; } TEST(SpdyFrameBuilderTest, GetWritableBuffer) { const size_t kBuilderSize = 10; SpdyFrameBuilder builder(kBuilderSize); char* writable_buffer = SpdyFrameBuilderPeer::GetWritableBuffer(&builder, kBuilderSize); memset(writable_buffer, ~1, kBuilderSize); EXPECT_TRUE(builder.Seek(kBuilderSize)); SpdySerializedFrame frame(builder.take()); char expected[kBuilderSize]; memset(expected, ~1, kBuilderSize); EXPECT_EQ(absl::string_view(expected, kBuilderSize), frame); } TEST(SpdyFrameBuilderTest, GetWritableOutput) { ArrayOutputBuffer output(output_buffer, kSize); const size_t kBuilderSize = 10; SpdyFrameBuilder builder(kBuilderSize, &output); size_t actual_size = 0; char* writable_buffer = SpdyFrameBuilderPeer::GetWritableOutput( &builder, kBuilderSize, &actual_size); memset(writable_buffer, ~1, kBuilderSize); EXPECT_TRUE(builder.Seek(kBuilderSize)); SpdySerializedFrame frame = MakeSerializedFrame(output.Begin(), kBuilderSize); char expected[kBuilderSize]; memset(expected, ~1, kBuilderSize); EXPECT_EQ(absl::string_view(expected, kBuilderSize), frame); } TEST(SpdyFrameBuilderTest, GetWritableOutputNegative) { size_t small_cap = 1; ArrayOutputBuffer output(output_buffer, small_cap); const size_t kBuilderSize = 10; SpdyFrameBuilder builder(kBuilderSize, &output); size_t actual_size = 0; char* writable_buffer = SpdyFrameBuilderPeer::GetWritableOutput( &builder, kBuilderSize, &actual_size); EXPECT_EQ(0u, actual_size); EXPECT_EQ(nullptr, writable_buffer); } } }
389
cpp
google/quiche
spdy_framer
quiche/http2/core/spdy_framer.cc
quiche/http2/core/spdy_framer_test.cc
#ifndef QUICHE_SPDY_CORE_SPDY_FRAMER_H_ #define QUICHE_SPDY_CORE_SPDY_FRAMER_H_ #include <stddef.h> #include <cstdint> #include <memory> #include <string> #include <utility> #include "quiche/common/platform/api/quiche_export.h" #include "quiche/spdy/core/hpack/hpack_encoder.h" #include "quiche/spdy/core/spdy_protocol.h" #include "quiche/spdy/core/zero_copy_output_buffer.h" namespace spdy { namespace test { class SpdyFramerPeer; class SpdyFramerTest_MultipleContinuationFramesWithIterator_Test; class SpdyFramerTest_PushPromiseFramesWithIterator_Test; } class QUICHE_EXPORT SpdyFrameSequence { public: virtual ~SpdyFrameSequence() {} virtual size_t NextFrame(ZeroCopyOutputBuffer* output) = 0; virtual bool HasNextFrame() const = 0; virtual const SpdyFrameIR& GetIR() const = 0; }; class QUICHE_EXPORT SpdyFramer { public: enum CompressionOption { ENABLE_COMPRESSION, DISABLE_COMPRESSION, }; static std::unique_ptr<SpdyFrameSequence> CreateIterator( SpdyFramer* framer, std::unique_ptr<const SpdyFrameIR> frame_ir); static uint8_t GetSerializedFlags(const SpdyFrameIR& frame); static SpdySerializedFrame SerializeData(const SpdyDataIR& data_ir); static SpdySerializedFrame SerializeDataFrameHeaderWithPaddingLengthField( const SpdyDataIR& data_ir); static SpdySerializedFrame SerializeWindowUpdate( const SpdyWindowUpdateIR& window_update); explicit SpdyFramer(CompressionOption option); virtual ~SpdyFramer(); void set_debug_visitor(SpdyFramerDebugVisitorInterface* debug_visitor); SpdySerializedFrame SerializeRstStream( const SpdyRstStreamIR& rst_stream) const; SpdySerializedFrame SerializeSettings(const SpdySettingsIR& settings) const; SpdySerializedFrame SerializePing(const SpdyPingIR& ping) const; SpdySerializedFrame SerializeGoAway(const SpdyGoAwayIR& goaway) const; SpdySerializedFrame SerializeHeaders(const SpdyHeadersIR& headers); SpdySerializedFrame SerializePushPromise( const SpdyPushPromiseIR& push_promise); SpdySerializedFrame SerializeContinuation( const SpdyContinuationIR& continuation) const; SpdySerializedFrame SerializeAltSvc(const SpdyAltSvcIR& altsvc); SpdySerializedFrame SerializePriority(const SpdyPriorityIR& priority) const; SpdySerializedFrame SerializePriorityUpdate( const SpdyPriorityUpdateIR& priority_update) const; SpdySerializedFrame SerializeAcceptCh(const SpdyAcceptChIR& accept_ch) const; SpdySerializedFrame SerializeUnknown(const SpdyUnknownIR& unknown) const; SpdySerializedFrame SerializeFrame(const SpdyFrameIR& frame); bool SerializeData(const SpdyDataIR& data, ZeroCopyOutputBuffer* output) const; bool SerializeDataFrameHeaderWithPaddingLengthField( const SpdyDataIR& data, ZeroCopyOutputBuffer* output) const; bool SerializeRstStream(const SpdyRstStreamIR& rst_stream, ZeroCopyOutputBuffer* output) const; bool SerializeSettings(const SpdySettingsIR& settings, ZeroCopyOutputBuffer* output) const; bool SerializePing(const SpdyPingIR& ping, ZeroCopyOutputBuffer* output) const; bool SerializeGoAway(const SpdyGoAwayIR& goaway, ZeroCopyOutputBuffer* output) const; bool SerializeHeaders(const SpdyHeadersIR& headers, ZeroCopyOutputBuffer* output); bool SerializeWindowUpdate(const SpdyWindowUpdateIR& window_update, ZeroCopyOutputBuffer* output) const; bool SerializePushPromise(const SpdyPushPromiseIR& push_promise, ZeroCopyOutputBuffer* output); bool SerializeContinuation(const SpdyContinuationIR& continuation, ZeroCopyOutputBuffer* output) const; bool SerializeAltSvc(const SpdyAltSvcIR& altsvc, ZeroCopyOutputBuffer* output); bool SerializePriority(const SpdyPriorityIR& priority, ZeroCopyOutputBuffer* output) const; bool SerializePriorityUpdate(const SpdyPriorityUpdateIR& priority_update, ZeroCopyOutputBuffer* output) const; bool SerializeAcceptCh(const SpdyAcceptChIR& accept_ch, ZeroCopyOutputBuffer* output) const; bool SerializeUnknown(const SpdyUnknownIR& unknown, ZeroCopyOutputBuffer* output) const; size_t SerializeFrame(const SpdyFrameIR& frame, ZeroCopyOutputBuffer* output); bool compression_enabled() const { return compression_option_ == ENABLE_COMPRESSION; } void SetHpackIndexingPolicy(HpackEncoder::IndexingPolicy policy) { GetHpackEncoder()->SetIndexingPolicy(std::move(policy)); } void UpdateHeaderEncoderTableSize(uint32_t value); size_t header_encoder_table_size() const; HpackEncoder* GetHpackEncoder(); const HpackEncoder* GetHpackEncoder() const { return hpack_encoder_.get(); } protected: friend class test::SpdyFramerPeer; friend class test::SpdyFramerTest_MultipleContinuationFramesWithIterator_Test; friend class test::SpdyFramerTest_PushPromiseFramesWithIterator_Test; class QUICHE_EXPORT SpdyFrameIterator : public SpdyFrameSequence { public: explicit SpdyFrameIterator(SpdyFramer* framer); ~SpdyFrameIterator() override; size_t NextFrame(ZeroCopyOutputBuffer* output) override; bool HasNextFrame() const override; SpdyFrameIterator(const SpdyFrameIterator&) = delete; SpdyFrameIterator& operator=(const SpdyFrameIterator&) = delete; protected: virtual size_t GetFrameSizeSansBlock() const = 0; virtual bool SerializeGivenEncoding(const std::string& encoding, ZeroCopyOutputBuffer* output) const = 0; SpdyFramer* GetFramer() const { return framer_; } void SetEncoder(const SpdyFrameWithHeaderBlockIR* ir) { encoder_ = framer_->GetHpackEncoder()->EncodeHeaderSet(ir->header_block()); } bool has_next_frame() const { return has_next_frame_; } private: SpdyFramer* const framer_; std::unique_ptr<HpackEncoder::ProgressiveEncoder> encoder_; bool is_first_frame_; bool has_next_frame_; }; class QUICHE_EXPORT SpdyHeaderFrameIterator : public SpdyFrameIterator { public: SpdyHeaderFrameIterator(SpdyFramer* framer, std::unique_ptr<const SpdyHeadersIR> headers_ir); ~SpdyHeaderFrameIterator() override; private: const SpdyFrameIR& GetIR() const override; size_t GetFrameSizeSansBlock() const override; bool SerializeGivenEncoding(const std::string& encoding, ZeroCopyOutputBuffer* output) const override; const std::unique_ptr<const SpdyHeadersIR> headers_ir_; }; class QUICHE_EXPORT SpdyPushPromiseFrameIterator : public SpdyFrameIterator { public: SpdyPushPromiseFrameIterator( SpdyFramer* framer, std::unique_ptr<const SpdyPushPromiseIR> push_promise_ir); ~SpdyPushPromiseFrameIterator() override; private: const SpdyFrameIR& GetIR() const override; size_t GetFrameSizeSansBlock() const override; bool SerializeGivenEncoding(const std::string& encoding, ZeroCopyOutputBuffer* output) const override; const std::unique_ptr<const SpdyPushPromiseIR> push_promise_ir_; }; class QUICHE_EXPORT SpdyControlFrameIterator : public SpdyFrameSequence { public: SpdyControlFrameIterator(SpdyFramer* framer, std::unique_ptr<const SpdyFrameIR> frame_ir); ~SpdyControlFrameIterator() override; size_t NextFrame(ZeroCopyOutputBuffer* output) override; bool HasNextFrame() const override; const SpdyFrameIR& GetIR() const override; private: SpdyFramer* const framer_; std::unique_ptr<const SpdyFrameIR> frame_ir_; bool has_next_frame_ = true; }; private: void SerializeHeadersBuilderHelper(const SpdyHeadersIR& headers, uint8_t* flags, size_t* size, std::string* hpack_encoding, int* weight, size_t* length_field); void SerializePushPromiseBuilderHelper(const SpdyPushPromiseIR& push_promise, uint8_t* flags, std::string* hpack_encoding, size_t* size); std::unique_ptr<HpackEncoder> hpack_encoder_; SpdyFramerDebugVisitorInterface* debug_visitor_; const CompressionOption compression_option_; }; } #endif #include "quiche/spdy/core/spdy_framer.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <memory> #include <string> #include <utility> #include "absl/base/attributes.h" #include "absl/memory/memory.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/spdy/core/hpack/hpack_constants.h" #include "quiche/spdy/core/hpack/hpack_encoder.h" #include "quiche/spdy/core/http2_header_block.h" #include "quiche/spdy/core/spdy_alt_svc_wire_format.h" #include "quiche/spdy/core/spdy_frame_builder.h" #include "quiche/spdy/core/spdy_protocol.h" #include "quiche/spdy/core/zero_copy_output_buffer.h" namespace spdy { namespace { uint32_t PackStreamDependencyValues(bool exclusive, SpdyStreamId parent_stream_id) { uint32_t parent = parent_stream_id & 0x7fffffff; uint32_t e_bit = exclusive ? 0x80000000 : 0; return parent | e_bit; } const uint8_t kNoFlags = 0; const size_t kPadLengthFieldSize = 1; const size_t kOneSettingParameterSize = 6; size_t GetUncompressedSerializedLength(const Http2HeaderBlock& headers) { const size_t num_name_value_pairs_size = sizeof(uint32_t); const size_t length_of_name_size = num_name_value_pairs_size; const size_t length_of_value_size = num_name_value_pairs_size; size_t total_length = num_name_value_pairs_size; for (const auto& header : headers) { total_length += length_of_name_size + header.first.size() + length_of_value_size + header.second.size(); } return total_length; } uint8_t SerializeHeaderFrameFlags(const SpdyHeadersIR& header_ir, const bool end_headers) { uint8_t flags = 0; if (header_ir.fin()) { flags |= CONTROL_FLAG_FIN; } if (end_headers) { flags |= HEADERS_FLAG_END_HEADERS; } if (header_ir.padded()) { flags |= HEADERS_FLAG_PADDED; } if (header_ir.has_priority()) { flags |= HEADERS_FLAG_PRIORITY; } return flags; } uint8_t SerializePushPromiseFrameFlags(const SpdyPushPromiseIR& push_promise_ir, const bool end_headers) { uint8_t flags = 0; if (push_promise_ir.padded()) { flags = flags | PUSH_PROMISE_FLAG_PADDED; } if (end_headers) { flags |= PUSH_PROMISE_FLAG_END_PUSH_PROMISE; } return flags; } bool SerializeHeadersGivenEncoding(const SpdyHeadersIR& headers, const std::string& encoding, const bool end_headers, ZeroCopyOutputBuffer* output) { const size_t frame_size = GetHeaderFrameSizeSansBlock(headers) + encoding.size(); SpdyFrameBuilder builder(frame_size, output); bool ret = builder.BeginNewFrame( SpdyFrameType::HEADERS, SerializeHeaderFrameFlags(headers, end_headers), headers.stream_id(), frame_size - kFrameHeaderSize); QUICHE_DCHECK_EQ(kFrameHeaderSize, builder.length()); if (ret && headers.padded()) { ret &= builder.WriteUInt8(headers.padding_payload_len()); } if (ret && headers.has_priority()) { int weight = ClampHttp2Weight(headers.weight()); ret &= builder.WriteUInt32(PackStreamDependencyValues( headers.exclusive(), headers.parent_stream_id())); ret &= builder.WriteUInt8(weight - 1); } if (ret) { ret &= builder.WriteBytes(encoding.data(), encoding.size()); } if (ret && headers.padding_payload_len() > 0) { std::string padding(headers.padding_payload_len(), 0); ret &= builder.WriteBytes(padding.data(), padding.length()); } if (!ret) { QUICHE_DLOG(WARNING) << "Failed to build HEADERS. Not enough space in output"; } return ret; } bool SerializePushPromiseGivenEncoding(const SpdyPushPromiseIR& push_promise, const std::string& encoding, const bool end_headers, ZeroCopyOutputBuffer* output) { const size_t frame_size = GetPushPromiseFrameSizeSansBlock(push_promise) + encoding.size(); SpdyFrameBuilder builder(frame_size, output); bool ok = builder.BeginNewFrame( SpdyFrameType::PUSH_PROMISE, SerializePushPromiseFrameFlags(push_promise, end_headers), push_promise.stream_id(), frame_size - kFrameHeaderSize); if (push_promise.padded()) { ok = ok && builder.WriteUInt8(push_promise.padding_payload_len()); } ok = ok && builder.WriteUInt32(push_promise.promised_stream_id()) && builder.WriteBytes(encoding.data(), encoding.size()); if (ok && push_promise.padding_payload_len() > 0) { std::string padding(push_promise.padding_payload_len(), 0); ok = builder.WriteBytes(padding.data(), padding.length()); } QUICHE_DLOG_IF(ERROR, !ok) << "Failed to write PUSH_PROMISE encoding, not enough " << "space in output"; return ok; } bool WritePayloadWithContinuation(SpdyFrameBuilder* builder, const std::string& hpack_encoding, SpdyStreamId stream_id, SpdyFrameType type, int padding_payload_len) { uint8_t end_flag = 0; uint8_t flags = 0; if (type == SpdyFrameType::HEADERS) { end_flag = HEADERS_FLAG_END_HEADERS; } else if (type == SpdyFrameType::PUSH_PROMISE) { end_flag = PUSH_PROMISE_FLAG_END_PUSH_PROMISE; } else { QUICHE_DLOG(FATAL) << "CONTINUATION frames cannot be used with frame type " << FrameTypeToString(type); } size_t bytes_remaining = 0; bytes_remaining = hpack_encoding.size() - std::min(hpack_encoding.size(), kHttp2MaxControlFrameSendSize - builder->length() - padding_payload_len); bool ret = builder->WriteBytes(&hpack_encoding[0], hpack_encoding.size() - bytes_remaining); if (padding_payload_len > 0) { std::string padding = std::string(padding_payload_len, 0); ret &= builder->WriteBytes(padding.data(), padding.length()); } while (bytes_remaining > 0 && ret) { size_t bytes_to_write = std::min(bytes_remaining, kHttp2MaxControlFrameSendSize - kContinuationFrameMinimumSize); if (bytes_remaining == bytes_to_write) { flags |= end_flag; } ret &= builder->BeginNewFrame(SpdyFrameType::CONTINUATION, flags, stream_id, bytes_to_write); ret &= builder->WriteBytes( &hpack_encoding[hpack_encoding.size() - bytes_remaining], bytes_to_write); bytes_remaining -= bytes_to_write; } return ret; } void SerializeDataBuilderHelper(const SpdyDataIR& data_ir, uint8_t* flags, int* num_padding_fields, size_t* size_with_padding) { if (data_ir.fin()) { *flags = DATA_FLAG_FIN; } if (data_ir.padded()) { *flags = *flags | DATA_FLAG_PADDED; ++*num_padding_fields; } *size_with_padding = *num_padding_fields + data_ir.data_len() + data_ir.padding_payload_len() + kDataFrameMinimumSize; } void SerializeDataFrameHeaderWithPaddingLengthFieldBuilderHelper( const SpdyDataIR& data_ir, uint8_t* flags, size_t* frame_size, size_t* num_padding_fields) { *flags = DATA_FLAG_NONE; if (data_ir.fin()) { *flags = DATA_FLAG_FIN; } *frame_size = kDataFrameMinimumSize; if (data_ir.padded()) { *flags = *flags | DATA_FLAG_PADDED; ++(*num_padding_fields); *frame_size = *frame_size + *num_padding_fields; } } void SerializeSettingsBuilderHelper(const SpdySettingsIR& settings, uint8_t* flags, const SettingsMap* values, size_t* size) { if (settings.is_ack()) { *flags = *flags | SETTINGS_FLAG_ACK; } *size = kSettingsFrameMinimumSize + (values->size() * kOneSettingParameterSize); } void SerializeAltSvcBuilderHelper(const SpdyAltSvcIR& altsvc_ir, std::string* value, size_t* size) { *size = kGetAltSvcFrameMinimumSize; *size = *size + altsvc_ir.origin().length(); *value = SpdyAltSvcWireFormat::SerializeHeaderFieldValue( altsvc_ir.altsvc_vector()); *size = *size + value->length(); } } SpdyFramer::SpdyFramer(CompressionOption option) : debug_visitor_(nullptr), compression_option_(option) { static_assert(kHttp2MaxControlFrameSendSize <= kHttp2DefaultFrameSizeLimit, "Our send limit should be at most our receive limit."); } SpdyFramer::~SpdyFramer() = default; void SpdyFramer::set_debug_visitor( SpdyFramerDebugVisitorInterface* debug_visitor) { debug_visitor_ = debug_visitor; } SpdyFramer::SpdyFrameIterator::SpdyFrameIterator(SpdyFramer* framer) : framer_(framer), is_first_frame_(true), has_next_frame_(true) {} SpdyFramer::SpdyFrameIterator::~SpdyFrameIterator() = default; size_t SpdyFramer::SpdyFrameIterator::NextFrame(ZeroCopyOutputBuffer* output) { const SpdyFrameIR& frame_ir = GetIR(); if (!has_next_frame_) { QUICHE_BUG(spdy_bug_75_1) << "SpdyFramer::SpdyFrameIterator::NextFrame called without " << "a next frame."; return false; } const size_t size_without_block = is_first_frame_ ? GetFrameSizeSansBlock() : kContinuationFrameMinimumSize; std::string encoding = encoder_->Next(kHttp2MaxControlFrameSendSize - size_without_block); has_next_frame_ = encoder_->HasNext(); if (framer_->debug_visitor_ != nullptr) { const auto& header_block_frame_ir = static_cast<const SpdyFrameWithHeaderBlockIR&>(frame_ir); const size_t header_list_size = GetUncompressedSerializedLength(header_block_frame_ir.header_block()); framer_->debug_visitor_->OnSendCompressedFrame( frame_ir.stream_id(), is_first_frame_ ? frame_ir.frame_type() : SpdyFrameType::CONTINUATION, header_list_size, size_without_block + encoding.size()); } const size_t free_bytes_before = output->BytesFree(); bool ok = false; if (is_first_frame_) { is_first_frame_ = false; ok = SerializeGivenEncoding(encoding, output); } else { SpdyContinuationIR continuation_ir(frame_ir.stream_id()); continuation_ir.take_encoding(std::move(encoding)); continuation_ir.set_end_headers(!has_next_frame_); ok = framer_->SerializeContinuation(continuation_ir, output); } return ok ? free_bytes_before - output->BytesFree() : 0; } bool SpdyFramer::SpdyFrameIterator::HasNextFrame() const { return has_next_frame_; } SpdyFramer::SpdyHeaderFrameIterator::SpdyHeaderFrameIterator( SpdyFramer* framer, std::unique_ptr<const SpdyHeadersIR> headers_ir) : SpdyFrameIterator(framer), headers_ir_(std::move(headers_ir)) { SetEncoder(headers_ir_.get()); } SpdyFramer::SpdyHeaderFrameIterator::~SpdyHeaderFrameIterator() = default; const SpdyFrameIR& SpdyFramer::SpdyHeaderFrameIterator::GetIR() const { return *headers_ir_; } size_t SpdyFramer::SpdyHeaderFrameIterator::GetFrameSizeSansBlock() const { return GetHeaderFrameSizeSansBlock(*headers_ir_); } bool SpdyFramer::SpdyHeaderFrameIterator::SerializeGivenEncoding( const std::string& encoding, ZeroCopyOutputBuffer* output) const { return SerializeHeadersGivenEncoding(*headers_ir_, encoding, !has_next_frame(), output); } SpdyFramer::SpdyPushPromiseFrameIterator::SpdyPushPromiseFrameIterator( SpdyFramer* framer, std::unique_ptr<const SpdyPushPromiseIR> push_promise_ir) : SpdyFrameIterator(framer), push_promise_ir_(std::move(push_promise_ir)) { SetEncoder(push_promise_ir_.get()); } SpdyFramer::SpdyPushPromiseFrameIterator::~SpdyPushPromiseFrameIterator() = default; const SpdyFrameIR& SpdyFramer::SpdyPushPromiseFrameIterator::GetIR() const { return *push_promise_ir_; } size_t SpdyFramer::SpdyPushPromiseFrameIterator::GetFrameSizeSansBlock() const { return GetPushPromiseFrameSizeSansBlock(*push_promise_ir_); } bool SpdyFramer::SpdyPushPromiseFrameIterator::SerializeGivenEncoding( const std::string& encoding, ZeroCopyOutputBuffer* output) const { return SerializePushPromiseGivenEncoding(*push_promise_ir_, encoding, !has_next_frame(), output); } SpdyFramer::SpdyControlFrameIterator::SpdyControlFrameIterator( SpdyFramer* framer, std::unique_ptr<const SpdyFrameIR> frame_ir) : framer_(framer), frame_ir_(std::move(frame_ir)) {} SpdyFramer::SpdyControlFrameIterator::~SpdyControlFrameIterator() = default; size_t SpdyFramer::SpdyControlFrameIterator::NextFrame( ZeroCopyOutputBuffer* output) { size_t size_written = framer_->SerializeFrame(*frame_ir_, output); has_next_frame_ = false; return size_written; } bool SpdyFramer::SpdyControlFrameIterator::HasNextFrame() const { return has_next_frame_; } const SpdyFrameIR& SpdyFramer::SpdyControlFrameIterator::GetIR() const { return *frame_ir_; } std::unique_ptr<SpdyFrameSequence> SpdyFramer::CreateIterator( SpdyFramer* framer, std::unique_ptr<const SpdyFrameIR> frame_ir) { switch (frame_ir->frame_type()) { case SpdyFrameType::HEADERS: { return std::make_unique<SpdyHeaderFrameIterator>( framer, absl::WrapUnique( static_cast<const SpdyHeadersIR*>(frame_ir.release()))); } case SpdyFrameType::PUSH_PROMISE: { return std::make_unique<SpdyPushPromiseFrameIterator>( framer, absl::WrapUnique(static_cast<const SpdyPushPromiseIR*>( frame_ir.release()))); } case SpdyFrameType::DATA: { QUICHE_DVLOG(1) << "Serialize a stream end DATA frame for VTL"; ABSL_FALLTHROUGH_INTENDED; } default: { return std::make_unique<SpdyControlFrameIterator>(framer, std::move(frame_ir)); } } } SpdySerializedFrame SpdyFramer::SerializeData(const SpdyDataIR& data_ir) { uint8_t flags = DATA_FLAG_NONE; int num_padding_fields = 0; size_t size_with_padding = 0; SerializeDataBuilderHelper(data_ir, &flags, &num_padding_fields, &size_with_padding); SpdyFrameBuilder builder(size_with_padding); builder.BeginNewFrame(SpdyFrameType::DATA, flags, data_ir.stream_id()); if (data_ir.padded()) { builder.WriteUInt8(data_ir.padding_payload_len() & 0xff); } builder.WriteBytes(data_ir.data(), data_ir.data_len()); if (data_ir.padding_payload_len() > 0) { std::string padding(data_ir.padding_payload_len(), 0); builder.WriteBytes(padding.data(), padding.length()); } QUICHE_DCHECK_EQ(size_with_padding, builder.length()); return builder.take(); } SpdySerializedFrame SpdyFramer::SerializeDataFrameHeaderWithPaddingLengthField( const SpdyDataIR& data_ir) { uint8_t flags = DATA_FLAG_NONE; size_t frame_size = 0; size_t num_padding_fields = 0; SerializeDataFrameHeaderWithPaddingLengthFieldBuilderHelper( data_ir, &flags, &frame_size, &num_padding_fields); SpdyFrameBuilder builder(frame_size); builder.BeginNewFrame( SpdyFrameType::DATA, flags, data_ir.stream_id(), num_padding_fields + data_ir.data_len() + data_ir.padding_payload_len()); if (data_ir.padded()) { builder.WriteUInt8(data_ir.padding_payload_len() & 0xff); } QUICHE_DCHECK_EQ(frame_size, builder.length()); return builder.take(); } SpdySerializedFrame SpdyFramer::SerializeRstStream( const SpdyRstStreamIR& rst_stream) const { size_t expected_length = kRstStreamFrameSize; SpdyFrameBuilder builder(expected_length); builder.BeginNewFrame(SpdyFrameType::RST_STREAM, 0, rst_stream.stream_id()); builder.WriteUInt32(rst_stream.error_code()); QUICHE_DCHECK_EQ(expected_length, builder.length()); return builder.take(); } SpdySerializedFrame SpdyFramer::SerializeSettings( const SpdySettingsIR& settings) const { uint8_t flags = 0; size_t size = 0; const SettingsMap* values = &(settings.values()); SerializeSettingsBuilderHelper(settings, &flags, values, &size); SpdyFrameBuilder builder(size); builder.BeginNewFrame(SpdyFrameType::SETTINGS, flags, 0); if (settings.is_ack()) { return builder.take(); } QUICHE_DCHECK_EQ(kSettingsFrameMinimumSize, builder.length()); for (auto it = values->begin(); it != values->end(); ++it) { int setting_id =
#include "quiche/spdy/core/spdy_framer.h" #include <stdlib.h> #include <algorithm> #include <cstdint> #include <cstring> #include <ios> #include <limits> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/quiche_text_utils.h" #include "quiche/spdy/core/array_output_buffer.h" #include "quiche/spdy/core/hpack/hpack_encoder.h" #include "quiche/spdy/core/http2_frame_decoder_adapter.h" #include "quiche/spdy/core/http2_header_block.h" #include "quiche/spdy/core/recording_headers_handler.h" #include "quiche/spdy/core/spdy_alt_svc_wire_format.h" #include "quiche/spdy/core/spdy_bitmasks.h" #include "quiche/spdy/core/spdy_frame_builder.h" #include "quiche/spdy/core/spdy_headers_handler_interface.h" #include "quiche/spdy/core/spdy_protocol.h" #include "quiche/spdy/test_tools/mock_spdy_framer_visitor.h" #include "quiche/spdy/test_tools/spdy_test_utils.h" using ::http2::Http2DecoderAdapter; using ::testing::_; namespace spdy { namespace test { namespace { const int64_t kSize = 1024 * 1024; char output_buffer[kSize] = ""; const int64_t buffer_size = 64 * 1024; char frame_list_char[buffer_size] = ""; } class MockDebugVisitor : public SpdyFramerDebugVisitorInterface { public: MOCK_METHOD(void, OnSendCompressedFrame, (SpdyStreamId stream_id, SpdyFrameType type, size_t payload_len, size_t frame_len), (override)); MOCK_METHOD(void, OnReceiveCompressedFrame, (SpdyStreamId stream_id, SpdyFrameType type, size_t frame_len), (override)); }; MATCHER_P(IsFrameUnionOf, frame_list, "") { size_t size_verified = 0; for (const auto& frame : *frame_list) { if (arg.size() < size_verified + frame.size()) { QUICHE_LOG(FATAL) << "Incremental header serialization should not lead to a " << "higher total frame length than non-incremental method."; return false; } if (memcmp(arg.data() + size_verified, frame.data(), frame.size())) { CompareCharArraysWithHexError( "Header serialization methods should be equivalent: ", reinterpret_cast<unsigned char*>(arg.data() + size_verified), frame.size(), reinterpret_cast<unsigned char*>(frame.data()), frame.size()); return false; } size_verified += frame.size(); } return size_verified == arg.size(); } class SpdyFramerPeer { public: static std::unique_ptr<SpdyHeadersIR> CloneSpdyHeadersIR( const SpdyHeadersIR& headers) { auto new_headers = std::make_unique<SpdyHeadersIR>( headers.stream_id(), headers.header_block().Clone()); new_headers->set_fin(headers.fin()); new_headers->set_has_priority(headers.has_priority()); new_headers->set_weight(headers.weight()); new_headers->set_parent_stream_id(headers.parent_stream_id()); new_headers->set_exclusive(headers.exclusive()); if (headers.padded()) { new_headers->set_padding_len(headers.padding_payload_len() + 1); } return new_headers; } static SpdySerializedFrame SerializeHeaders(SpdyFramer* framer, const SpdyHeadersIR& headers) { SpdySerializedFrame serialized_headers_old_version( framer->SerializeHeaders(headers)); framer->hpack_encoder_.reset(nullptr); auto* saved_debug_visitor = framer->debug_visitor_; framer->debug_visitor_ = nullptr; std::vector<SpdySerializedFrame> frame_list; ArrayOutputBuffer frame_list_buffer(frame_list_char, buffer_size); SpdyFramer::SpdyHeaderFrameIterator it(framer, CloneSpdyHeadersIR(headers)); while (it.HasNextFrame()) { size_t size_before = frame_list_buffer.Size(); EXPECT_GT(it.NextFrame(&frame_list_buffer), 0u); frame_list.emplace_back( MakeSerializedFrame(frame_list_buffer.Begin() + size_before, frame_list_buffer.Size() - size_before)); } framer->debug_visitor_ = saved_debug_visitor; EXPECT_THAT(serialized_headers_old_version, IsFrameUnionOf(&frame_list)); return serialized_headers_old_version; } static SpdySerializedFrame SerializeHeaders(SpdyFramer* framer, const SpdyHeadersIR& headers, ArrayOutputBuffer* output) { if (output == nullptr) { return SerializeHeaders(framer, headers); } output->Reset(); EXPECT_TRUE(framer->SerializeHeaders(headers, output)); SpdySerializedFrame serialized_headers_old_version = MakeSerializedFrame(output->Begin(), output->Size()); framer->hpack_encoder_.reset(nullptr); auto* saved_debug_visitor = framer->debug_visitor_; framer->debug_visitor_ = nullptr; std::vector<SpdySerializedFrame> frame_list; ArrayOutputBuffer frame_list_buffer(frame_list_char, buffer_size); SpdyFramer::SpdyHeaderFrameIterator it(framer, CloneSpdyHeadersIR(headers)); while (it.HasNextFrame()) { size_t size_before = frame_list_buffer.Size(); EXPECT_GT(it.NextFrame(&frame_list_buffer), 0u); frame_list.emplace_back( MakeSerializedFrame(frame_list_buffer.Begin() + size_before, frame_list_buffer.Size() - size_before)); } framer->debug_visitor_ = saved_debug_visitor; EXPECT_THAT(serialized_headers_old_version, IsFrameUnionOf(&frame_list)); return serialized_headers_old_version; } static std::unique_ptr<SpdyPushPromiseIR> CloneSpdyPushPromiseIR( const SpdyPushPromiseIR& push_promise) { auto new_push_promise = std::make_unique<SpdyPushPromiseIR>( push_promise.stream_id(), push_promise.promised_stream_id(), push_promise.header_block().Clone()); new_push_promise->set_fin(push_promise.fin()); if (push_promise.padded()) { new_push_promise->set_padding_len(push_promise.padding_payload_len() + 1); } return new_push_promise; } static SpdySerializedFrame SerializePushPromise( SpdyFramer* framer, const SpdyPushPromiseIR& push_promise) { SpdySerializedFrame serialized_headers_old_version = framer->SerializePushPromise(push_promise); framer->hpack_encoder_.reset(nullptr); auto* saved_debug_visitor = framer->debug_visitor_; framer->debug_visitor_ = nullptr; std::vector<SpdySerializedFrame> frame_list; ArrayOutputBuffer frame_list_buffer(frame_list_char, buffer_size); frame_list_buffer.Reset(); SpdyFramer::SpdyPushPromiseFrameIterator it( framer, CloneSpdyPushPromiseIR(push_promise)); while (it.HasNextFrame()) { size_t size_before = frame_list_buffer.Size(); EXPECT_GT(it.NextFrame(&frame_list_buffer), 0u); frame_list.emplace_back( MakeSerializedFrame(frame_list_buffer.Begin() + size_before, frame_list_buffer.Size() - size_before)); } framer->debug_visitor_ = saved_debug_visitor; EXPECT_THAT(serialized_headers_old_version, IsFrameUnionOf(&frame_list)); return serialized_headers_old_version; } static SpdySerializedFrame SerializePushPromise( SpdyFramer* framer, const SpdyPushPromiseIR& push_promise, ArrayOutputBuffer* output) { if (output == nullptr) { return SerializePushPromise(framer, push_promise); } output->Reset(); EXPECT_TRUE(framer->SerializePushPromise(push_promise, output)); SpdySerializedFrame serialized_headers_old_version = MakeSerializedFrame(output->Begin(), output->Size()); framer->hpack_encoder_.reset(nullptr); auto* saved_debug_visitor = framer->debug_visitor_; framer->debug_visitor_ = nullptr; std::vector<SpdySerializedFrame> frame_list; ArrayOutputBuffer frame_list_buffer(frame_list_char, buffer_size); frame_list_buffer.Reset(); SpdyFramer::SpdyPushPromiseFrameIterator it( framer, CloneSpdyPushPromiseIR(push_promise)); while (it.HasNextFrame()) { size_t size_before = frame_list_buffer.Size(); EXPECT_GT(it.NextFrame(&frame_list_buffer), 0u); frame_list.emplace_back( MakeSerializedFrame(frame_list_buffer.Begin() + size_before, frame_list_buffer.Size() - size_before)); } framer->debug_visitor_ = saved_debug_visitor; EXPECT_THAT(serialized_headers_old_version, IsFrameUnionOf(&frame_list)); return serialized_headers_old_version; } }; class TestSpdyVisitor : public SpdyFramerVisitorInterface, public SpdyFramerDebugVisitorInterface { public: static constexpr size_t kDefaultHeaderBufferSize = 16 * 1024 * 1024; explicit TestSpdyVisitor(SpdyFramer::CompressionOption option) : framer_(option), error_count_(0), headers_frame_count_(0), push_promise_frame_count_(0), goaway_count_(0), setting_count_(0), settings_ack_sent_(0), settings_ack_received_(0), continuation_count_(0), altsvc_count_(0), priority_count_(0), unknown_frame_count_(0), on_unknown_frame_result_(false), last_window_update_stream_(0), last_window_update_delta_(0), last_push_promise_stream_(0), last_push_promise_promised_stream_(0), data_bytes_(0), fin_frame_count_(0), fin_flag_count_(0), end_of_stream_count_(0), control_frame_header_data_count_(0), zero_length_control_frame_header_data_count_(0), data_frame_count_(0), last_payload_len_(0), last_frame_len_(0), unknown_payload_len_(0), header_buffer_(new char[kDefaultHeaderBufferSize]), header_buffer_length_(0), header_buffer_size_(kDefaultHeaderBufferSize), header_stream_id_(static_cast<SpdyStreamId>(-1)), header_control_type_(SpdyFrameType::DATA), header_buffer_valid_(false) {} void OnError(Http2DecoderAdapter::SpdyFramerError error, std::string ) override { QUICHE_VLOG(1) << "SpdyFramer Error: " << Http2DecoderAdapter::SpdyFramerErrorToString(error); ++error_count_; } void OnDataFrameHeader(SpdyStreamId stream_id, size_t length, bool fin) override { QUICHE_VLOG(1) << "OnDataFrameHeader(" << stream_id << ", " << length << ", " << fin << ")"; ++data_frame_count_; header_stream_id_ = stream_id; } void OnStreamFrameData(SpdyStreamId stream_id, const char* data, size_t len) override { QUICHE_VLOG(1) << "OnStreamFrameData(" << stream_id << ", data, " << len << ", " << ") data:\n" << quiche::QuicheTextUtils::HexDump( absl::string_view(data, len)); EXPECT_EQ(header_stream_id_, stream_id); data_bytes_ += len; } void OnStreamEnd(SpdyStreamId stream_id) override { QUICHE_VLOG(1) << "OnStreamEnd(" << stream_id << ")"; EXPECT_EQ(header_stream_id_, stream_id); ++end_of_stream_count_; } void OnStreamPadLength(SpdyStreamId stream_id, size_t value) override { QUICHE_VLOG(1) << "OnStreamPadding(" << stream_id << ", " << value << ")\n"; EXPECT_EQ(header_stream_id_, stream_id); data_bytes_ += 1; } void OnStreamPadding(SpdyStreamId stream_id, size_t len) override { QUICHE_VLOG(1) << "OnStreamPadding(" << stream_id << ", " << len << ")\n"; EXPECT_EQ(header_stream_id_, stream_id); data_bytes_ += len; } SpdyHeadersHandlerInterface* OnHeaderFrameStart( SpdyStreamId ) override { if (headers_handler_ == nullptr) { headers_handler_ = std::make_unique<RecordingHeadersHandler>(); } return headers_handler_.get(); } void OnHeaderFrameEnd(SpdyStreamId ) override { QUICHE_CHECK(headers_handler_ != nullptr); headers_ = headers_handler_->decoded_block().Clone(); header_bytes_received_ = headers_handler_->uncompressed_header_bytes(); headers_handler_.reset(); } void OnRstStream(SpdyStreamId stream_id, SpdyErrorCode error_code) override { QUICHE_VLOG(1) << "OnRstStream(" << stream_id << ", " << error_code << ")"; ++fin_frame_count_; } void OnSetting(SpdySettingsId id, uint32_t value) override { QUICHE_VLOG(1) << "OnSetting(" << id << ", " << std::hex << value << ")"; ++setting_count_; } void OnSettingsAck() override { QUICHE_VLOG(1) << "OnSettingsAck"; ++settings_ack_received_; } void OnSettingsEnd() override { QUICHE_VLOG(1) << "OnSettingsEnd"; ++settings_ack_sent_; } void OnPing(SpdyPingId unique_id, bool is_ack) override { QUICHE_LOG(DFATAL) << "OnPing(" << unique_id << ", " << (is_ack ? 1 : 0) << ")"; } void OnGoAway(SpdyStreamId last_accepted_stream_id, SpdyErrorCode error_code) override { QUICHE_VLOG(1) << "OnGoAway(" << last_accepted_stream_id << ", " << error_code << ")"; ++goaway_count_; } void OnHeaders(SpdyStreamId stream_id, size_t payload_length, bool has_priority, int weight, SpdyStreamId parent_stream_id, bool exclusive, bool fin, bool end) override { QUICHE_VLOG(1) << "OnHeaders(" << stream_id << ", " << payload_length << ", " << has_priority << ", " << weight << ", " << parent_stream_id << ", " << exclusive << ", " << fin << ", " << end << ")"; ++headers_frame_count_; InitHeaderStreaming(SpdyFrameType::HEADERS, stream_id); if (fin) { ++fin_flag_count_; } header_has_priority_ = has_priority; header_parent_stream_id_ = parent_stream_id; header_exclusive_ = exclusive; } void OnWindowUpdate(SpdyStreamId stream_id, int delta_window_size) override { QUICHE_VLOG(1) << "OnWindowUpdate(" << stream_id << ", " << delta_window_size << ")"; last_window_update_stream_ = stream_id; last_window_update_delta_ = delta_window_size; } void OnPushPromise(SpdyStreamId stream_id, SpdyStreamId promised_stream_id, bool end) override { QUICHE_VLOG(1) << "OnPushPromise(" << stream_id << ", " << promised_stream_id << ", " << end << ")"; ++push_promise_frame_count_; InitHeaderStreaming(SpdyFrameType::PUSH_PROMISE, stream_id); last_push_promise_stream_ = stream_id; last_push_promise_promised_stream_ = promised_stream_id; } void OnContinuation(SpdyStreamId stream_id, size_t payload_size, bool end) override { QUICHE_VLOG(1) << "OnContinuation(" << stream_id << ", " << payload_size << ", " << end << ")"; ++continuation_count_; } void OnAltSvc(SpdyStreamId stream_id, absl::string_view origin, const SpdyAltSvcWireFormat::AlternativeServiceVector& altsvc_vector) override { QUICHE_VLOG(1) << "OnAltSvc(" << stream_id << ", \"" << origin << "\", altsvc_vector)"; test_altsvc_ir_ = std::make_unique<SpdyAltSvcIR>(stream_id); if (origin.length() > 0) { test_altsvc_ir_->set_origin(std::string(origin)); } for (const auto& altsvc : altsvc_vector) { test_altsvc_ir_->add_altsvc(altsvc); } ++altsvc_count_; } void OnPriority(SpdyStreamId stream_id, SpdyStreamId parent_stream_id, int weight, bool exclusive) override { QUICHE_VLOG(1) << "OnPriority(" << stream_id << ", " << parent_stream_id << ", " << weight << ", " << (exclusive ? 1 : 0) << ")"; ++priority_count_; } void OnPriorityUpdate(SpdyStreamId prioritized_stream_id, absl::string_view priority_field_value) override { QUICHE_VLOG(1) << "OnPriorityUpdate(" << prioritized_stream_id << ", " << priority_field_value << ")"; } bool OnUnknownFrame(SpdyStreamId stream_id, uint8_t frame_type) override { QUICHE_VLOG(1) << "OnUnknownFrame(" << stream_id << ", " << frame_type << ")"; return on_unknown_frame_result_; } void OnUnknownFrameStart(SpdyStreamId stream_id, size_t length, uint8_t type, uint8_t flags) override { QUICHE_VLOG(1) << "OnUnknownFrameStart(" << stream_id << ", " << length << ", " << static_cast<int>(type) << ", " << static_cast<int>(flags) << ")"; ++unknown_frame_count_; } void OnUnknownFramePayload(SpdyStreamId stream_id, absl::string_view payload) override { QUICHE_VLOG(1) << "OnUnknownFramePayload(" << stream_id << ", " << payload << ")"; unknown_payload_len_ += payload.length(); } void OnSendCompressedFrame(SpdyStreamId stream_id, SpdyFrameType type, size_t payload_len, size_t frame_len) override { QUICHE_VLOG(1) << "OnSendCompressedFrame(" << stream_id << ", " << type << ", " << payload_len << ", " << frame_len << ")"; last_payload_len_ = payload_len; last_frame_len_ = frame_len; } void OnReceiveCompressedFrame(SpdyStreamId stream_id, SpdyFrameType type, size_t frame_len) override { QUICHE_VLOG(1) << "OnReceiveCompressedFrame(" << stream_id << ", " << type << ", " << frame_len << ")"; last_frame_len_ = frame_len; } void SimulateInFramer(const unsigned char* input, size_t size) { deframer_.set_visitor(this); size_t input_remaining = size; const char* input_ptr = reinterpret_cast<const char*>(input); while (input_remaining > 0 && deframer_.spdy_framer_error() == Http2DecoderAdapter::SPDY_NO_ERROR) { const size_t kMaxReadSize = 32; size_t bytes_read = (rand() % std::min(input_remaining, kMaxReadSize)) + 1; size_t bytes_processed = deframer_.ProcessInput(input_ptr, bytes_read); input_remaining -= bytes_processed; input_ptr += bytes_processed; } } void InitHeaderStreaming(SpdyFrameType header_control_type, SpdyStreamId stream_id) { if (!IsDefinedFrameType(SerializeFrameType(header_control_type))) { QUICHE_DLOG(FATAL) << "Attempted to init header streaming with " << "invalid control frame type: " << header_control_type; } memset(header_buffer_.get(), 0, header_buffer_size_); header_buffer_length_ = 0; header_stream_id_ = stream_id; header_control_type_ = header_control_type; header_buffer_valid_ = true; } void set_extension_visitor(ExtensionVisitorInterface* extension) { deframer_.set_extension_visitor(extension); } void set_header_buffer_size(size_t header_buffer_size) { header_buffer_size_ = header_buffer_size; header_buffer_.reset(new char[header_buffer_size]); } SpdyFramer framer_; Http2DecoderAdapter deframer_; int error_count_; int headers_frame_count_; int push_promise_frame_count_; int goaway_count_; int setting_count_; int settings_ack_sent_; int settings_ack_received_; int continuation_count_; int altsvc_count_; int priority_count_; std::unique_ptr<SpdyAltSvcIR> test_altsvc_ir_; int unknown_frame_count_; bool on_unknown_frame_result_; SpdyStreamId last_window_update_stream_; int last_window_update_delta_; SpdyStreamId last_push_promise_stream_; SpdyStreamId last_push_promise_promised_stream_; int data_bytes_; int fin_frame_count_; int fin_flag_count_; int end_of_stream_count_; int control_frame_header_data_count_; int zero_length_control_frame_header_data_count_; int data_frame_count_; size_t last_payload_len_; size_t last_frame_len_; size_t unknown_payload_len_; std::unique_ptr<char[]> header_buffer_; size_t header_buffer_length_; size_t header_buffer_size_; size_t header_bytes_received_; SpdyStreamId header_stream_id_; SpdyFrameType header_control_type_; bool header_buffer_valid_; std::unique_ptr<RecordingHeadersHandler> headers_handler_; Http2HeaderBlock headers_; bool header_has_priority_; SpdyStreamId header_parent_stream_id_; bool header_exclusive_; }; class TestExtension : public ExtensionVisitorInterface { public: void OnSetting(SpdySettingsId id, uint32_t value) override { settings_received_.push_back({id, value}); } bool OnFrameHeader(SpdyStreamId stream_id, size_t length, uint8_t type, uint8_t flags) override { stream_id_ = stream_id; length_ = length; type_ = type; flags_ = flags; return true; } void OnFramePayload(const char* data, size_t len) override { payload_.append(data, len); } std::vector<std::pair<SpdySettingsId, uint32_t>> settings_received_; SpdyStreamId stream_id_ = 0; size_t length_ = 0; uint8_t type_ = 0; uint8_t flags_ = 0; std::string payload_; }; class TestSpdyUnknownIR : public SpdyUnknownIR { public: using SpdyUnknownIR::set_length; using SpdyUnknownIR::SpdyUnknownIR; }; enum Output { USE, NOT_USE }; class SpdyFramerTest : public quiche::test::QuicheTestWithParam<Output> { public: SpdyFramerTest() : output_(output_buffer, kSize), framer_(SpdyFramer::ENABLE_COMPRESSION), deframer_(std::make_unique<Http2DecoderAdapter>()) {} protected: void SetUp() override { switch (GetParam()) { case USE: use_output_ = true; break; case NOT_USE: use_output_ = false; break; } } void CompareFrame(const std::string& description, const SpdySerializedFrame& actual_frame, const unsigned char* expected, const int expected_len) { const unsigned char* actual = reinterpret_cast<const unsigned char*>(actual_frame.data()); CompareCharArraysWithHexError(description, actual, actual_frame.size(), expected, expected_len); } bool use_output_ = false; ArrayOutputBuffer output_; SpdyFramer framer_; std::unique_ptr<Http2DecoderAdapter> deframer_; }; INSTANTIATE_TEST_SUITE_P(SpdyFramerTests, SpdyFramerTest, ::testing::Values(USE, NOT_USE)); TEST_P(SpdyFramerTest, HeaderBlockInBuffer) { SpdyFramer framer(SpdyFramer::DISABLE_COMPRESSION); SpdyHeadersIR headers( 1); headers.SetHeader("alpha", "beta"); headers.SetHeader("gamma", "charlie"); headers.SetHeader("cookie", "key1=value1; key2=value2"); SpdySerializedFrame frame( SpdyFramerPeer::SerializeHeaders(&framer, headers, &output_)); TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer(reinterpret_cast<unsigned char*>(frame.data()), frame.size()); EXPECT_EQ(0, visitor.zero_length_control_frame_header_data_count_); EXPECT_EQ(headers.header_block(), visitor.headers_); } TEST_P(SpdyFramerTest, UndersizedHeaderBlockInBuffer) { SpdyFramer framer(SpdyFramer::DISABLE_COMPRESSION); SpdyHeadersIR headers( 1); headers.SetHeader("alpha", "beta"); headers.SetHeader("gamma", "charlie"); SpdySerializedFrame frame( SpdyFramerPeer::SerializeHeaders(&framer, headers, &output_)); TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer(reinterpret_cast<unsigned char*>(frame.data()), frame.size() - 2); EXPECT_EQ(0, visitor.zero_length_control_frame_header_data_count_); EXPECT_THAT(visitor.headers_, testing::IsEmpty()); } TEST_P(SpdyFramerTest, HeaderStreamDependencyValues) { SpdyFramer framer(SpdyFramer::DISABLE_COMPRESSION); const SpdyStreamId parent_stream_id_test_array[] = {0, 3}; for (SpdyStreamId parent_stream_id : parent_stream_id_test_array) { const bool exclusive_test_array[] = {true, false}; for (bool exclusive : exclusive_test_array) { SpdyHeadersIR headers(1); headers.set_has_priority(true); headers.set_parent_stream_id(parent_stream_id); headers.set_exclusive(exclusive); SpdySerializedFrame frame( SpdyFramerPeer::SerializeHeaders(&framer, headers, &output_)); TestSpdyVisitor visitor(SpdyFramer::DISABLE_COMPRESSION); visitor.SimulateInFramer(reinterpret_cast<unsigned char*>(frame.data()), frame.size()); EXPECT_TRUE(visitor.header_has_priority_); EXPECT_EQ(parent_stream_id, visitor.header_parent_stream_id_); EXPECT_EQ(exclusive, visitor.header_exclusive_); } } } TEST_P(SpdyFramerTest, AcceptMaxFrameSizeSetting) { testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); unsigned char kH2FrameData[] = { 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, }; SpdySerializedFrame frame = MakeSerializedFrame( reinterpret_cast<char*>(kH2FrameData), sizeof(kH2FrameData)); EXPECT_CALL(visitor, OnCommonHeader(1, 16384, 0x0, 0x0)); EXPECT_CALL(visitor, OnDataFrameHeader(1, 1 << 14, false)); EXPECT_CALL(visitor, OnStreamFrameData(1, _, 4)); deframer_->ProcessInput(frame.data(), frame.size()); EXPECT_FALSE(deframer_->HasError()); } TEST_P(SpdyFramerTest, ExceedMaxFrameSizeSetting) { testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); unsigned char kH2FrameData[] = { 0x00, 0x40, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, }; SpdySerializedFrame frame = MakeSerializedFrame( reinterpret_cast<char*>(kH2FrameData), sizeof(kH2FrameData)); EXPECT_CALL(visitor, OnCommonHeader(1, 16385, 0x0, 0x0)); EXPECT_CALL(visitor, OnError(Http2DecoderAdapter::SPDY_OVERSIZED_PAYLOAD, _)); deframer_->ProcessInput(frame.data(), frame.size()); EXPECT_TRUE(deframer_->HasError()); EXPECT_EQ(Http2DecoderAdapter::SPDY_OVERSIZED_PAYLOAD, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } TEST_P(SpdyFramerTest, AcceptLargerMaxFrameSizeSetting) { testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); const size_t big_frame_size = (1 << 14) + 1; deframer_->SetMaxFrameSize(big_frame_size); unsigned char kH2FrameData[] = { 0x00, 0x40, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, }; SpdySerializedFrame frame = MakeSerializedFrame( reinterpret_cast<char*>(kH2FrameData), sizeof(kH2FrameData)); EXPECT_CALL(visitor, OnCommonHeader(1, big_frame_size, 0x0, 0x0)); EXPECT_CALL(visitor, OnDataFrameHeader(1, big_frame_size, false)); EXPECT_CALL(visitor, OnStreamFrameData(1, _, 4)); deframer_->ProcessInput(frame.data(), frame.size()); EXPECT_FALSE(deframer_->HasError()); } TEST_P(SpdyFramerTest, OversizedDataPaddingError) { testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); unsigned char kH2FrameData[] = { 0x00, 0x00, 0x05, 0x00, 0x09, 0x00, 0x00, 0x00, 0x01, 0xff, 0x00, 0x00, 0x00, 0x00, }; SpdySerializedFrame frame = MakeSerializedFrame( reinterpret_cast<char*>(kH2FrameData), sizeof(kH2FrameData)); { testing::InSequence seq; EXPECT_CALL(visitor, OnCommonHeader(1, 5, 0x0, 0x9)); EXPECT_CALL(visitor, OnDataFrameHeader(1, 5, 1)); EXPECT_CALL(visitor, OnStreamPadding(1, 1)); EXPECT_CALL(visitor, OnError(Http2DecoderAdapter::SPDY_INVALID_PADDING, _)); } EXPECT_GT(frame.size(), deframer_->ProcessInput(frame.data(), frame.size())); EXPECT_TRUE(deframer_->HasError()); EXPECT_EQ(Http2DecoderAdapter::SPDY_INVALID_PADDING, deframer_->spdy_framer_error()) << Http2DecoderAdapter::SpdyFramerErrorToString( deframer_->spdy_framer_error()); } TEST_P(SpdyFramerTest, CorrectlySizedDataPaddingNoError) { testing::StrictMock<test::MockSpdyFramerVisitor> visitor; deframer_->set_visitor(&visitor); char kH2FrameData[] = { 0x00, 0x00, 0x05, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x00, }; SpdySerializedFrame frame = MakeSerializedFrame(kH2FrameData, sizeof(kH2FrameData)); { testing::InSequence seq; EXPECT_CALL(visitor, OnCommonHeader(1, 5, 0x0, 0x8)); EXPECT_CALL(visitor, OnDataFrameHeader(1, 5, false)); EXPECT_CALL(visitor, OnStreamPadLength(1, 4)); EXPECT_CALL(visitor, OnError(_, _)).Times(0); EXPECT_CALL(visitor, OnStreamPadding(1, 4)); } EXP
390
cpp
google/quiche
spdy_protocol
quiche/http2/core/spdy_protocol.cc
quiche/http2/core/spdy_protocol_test.cc
#ifndef QUICHE_SPDY_CORE_SPDY_PROTOCOL_H_ #define QUICHE_SPDY_CORE_SPDY_PROTOCOL_H_ #include <cstddef> #include <cstdint> #include <cstring> #include <iosfwd> #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "absl/types/variant.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/platform/api/quiche_flags.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/spdy/core/http2_header_block.h" #include "quiche/spdy/core/spdy_alt_svc_wire_format.h" #include "quiche/spdy/core/spdy_bitmasks.h" namespace spdy { using SpdyStreamId = uint32_t; using SpdySettingsId = uint16_t; inline constexpr SpdyStreamId kSessionFlowControlStreamId = 0; inline constexpr SpdyStreamId kInvalidStreamId = 0; inline constexpr SpdyStreamId kMaxStreamId = 0x7fffffff; inline constexpr uint32_t kSpdyMaxFrameSizeLimit = (1 << 24) - 1; inline constexpr uint32_t kHttp2DefaultFramePayloadLimit = 1 << 14; inline constexpr size_t kHttp2MaxControlFrameSendSize = kHttp2DefaultFramePayloadLimit - 1; inline constexpr size_t kFrameHeaderSize = 9; inline constexpr uint32_t kHttp2DefaultFrameSizeLimit = kHttp2DefaultFramePayloadLimit + kFrameHeaderSize; inline constexpr uint32_t kSpdyInitialHeaderListSizeLimit = 0xFFFFFFFF; inline constexpr int32_t kSpdyMaximumWindowSize = 0x7FFFFFFF; inline constexpr int32_t kPaddingSizePerFrame = 256; QUICHE_EXPORT extern const char* const kHttp2ConnectionHeaderPrefix; inline constexpr int kHttp2ConnectionHeaderPrefixSize = 24; enum class SpdyFrameType : uint8_t { DATA = 0x00, HEADERS = 0x01, PRIORITY = 0x02, RST_STREAM = 0x03, SETTINGS = 0x04, PUSH_PROMISE = 0x05, PING = 0x06, GOAWAY = 0x07, WINDOW_UPDATE = 0x08, CONTINUATION = 0x09, ALTSVC = 0x0a, PRIORITY_UPDATE = 0x10, ACCEPT_CH = 0x89, }; enum SpdyDataFlags { DATA_FLAG_NONE = 0x00, DATA_FLAG_FIN = 0x01, DATA_FLAG_PADDED = 0x08, }; enum SpdyControlFlags { CONTROL_FLAG_NONE = 0x00, CONTROL_FLAG_FIN = 0x01, }; enum SpdyPingFlags { PING_FLAG_ACK = 0x01, }; enum SpdyHeadersFlags { HEADERS_FLAG_END_HEADERS = 0x04, HEADERS_FLAG_PADDED = 0x08, HEADERS_FLAG_PRIORITY = 0x20, }; enum SpdyPushPromiseFlags { PUSH_PROMISE_FLAG_END_PUSH_PROMISE = 0x04, PUSH_PROMISE_FLAG_PADDED = 0x08, }; enum Http2SettingsControlFlags { SETTINGS_FLAG_ACK = 0x01, }; enum SpdyKnownSettingsId : SpdySettingsId { SETTINGS_HEADER_TABLE_SIZE = 0x1, SETTINGS_MIN = SETTINGS_HEADER_TABLE_SIZE, SETTINGS_ENABLE_PUSH = 0x2, SETTINGS_MAX_CONCURRENT_STREAMS = 0x3, SETTINGS_INITIAL_WINDOW_SIZE = 0x4, SETTINGS_MAX_FRAME_SIZE = 0x5, SETTINGS_MAX_HEADER_LIST_SIZE = 0x6, SETTINGS_ENABLE_CONNECT_PROTOCOL = 0x8, SETTINGS_DEPRECATE_HTTP2_PRIORITIES = 0x9, SETTINGS_MAX = SETTINGS_DEPRECATE_HTTP2_PRIORITIES, SETTINGS_EXPERIMENT_SCHEDULER = 0xFF45, }; QUICHE_EXPORT std::ostream& operator<<(std::ostream& out, SpdyKnownSettingsId id); QUICHE_EXPORT std::ostream& operator<<(std::ostream& out, SpdyFrameType frame_type); using SettingsMap = std::map<SpdySettingsId, uint32_t>; enum SpdyErrorCode : uint32_t { ERROR_CODE_NO_ERROR = 0x0, ERROR_CODE_PROTOCOL_ERROR = 0x1, ERROR_CODE_INTERNAL_ERROR = 0x2, ERROR_CODE_FLOW_CONTROL_ERROR = 0x3, ERROR_CODE_SETTINGS_TIMEOUT = 0x4, ERROR_CODE_STREAM_CLOSED = 0x5, ERROR_CODE_FRAME_SIZE_ERROR = 0x6, ERROR_CODE_REFUSED_STREAM = 0x7, ERROR_CODE_CANCEL = 0x8, ERROR_CODE_COMPRESSION_ERROR = 0x9, ERROR_CODE_CONNECT_ERROR = 0xa, ERROR_CODE_ENHANCE_YOUR_CALM = 0xb, ERROR_CODE_INADEQUATE_SECURITY = 0xc, ERROR_CODE_HTTP_1_1_REQUIRED = 0xd, ERROR_CODE_MAX = ERROR_CODE_HTTP_1_1_REQUIRED }; enum class WriteSchedulerType { LIFO, SPDY, HTTP2, FIFO, }; typedef uint8_t SpdyPriority; inline constexpr SpdyPriority kV3HighestPriority = 0; inline constexpr SpdyPriority kV3LowestPriority = 7; QUICHE_EXPORT SpdyPriority ClampSpdy3Priority(SpdyPriority priority); inline constexpr int kHttp2MinStreamWeight = 1; inline constexpr int kHttp2MaxStreamWeight = 256; inline constexpr int kHttp2DefaultStreamWeight = 16; QUICHE_EXPORT int ClampHttp2Weight(int weight); QUICHE_EXPORT int Spdy3PriorityToHttp2Weight(SpdyPriority priority); QUICHE_EXPORT SpdyPriority Http2WeightToSpdy3Priority(int weight); const unsigned int kHttp2RootStreamId = 0; typedef uint64_t SpdyPingId; QUICHE_EXPORT bool IsDefinedFrameType(uint8_t frame_type_field); QUICHE_EXPORT SpdyFrameType ParseFrameType(uint8_t frame_type_field); QUICHE_EXPORT uint8_t SerializeFrameType(SpdyFrameType frame_type); QUICHE_EXPORT bool IsValidHTTP2FrameStreamId( SpdyStreamId current_frame_stream_id, SpdyFrameType frame_type_field); QUICHE_EXPORT const char* FrameTypeToString(SpdyFrameType frame_type); QUICHE_EXPORT bool ParseSettingsId(SpdySettingsId wire_setting_id, SpdyKnownSettingsId* setting_id); QUICHE_EXPORT std::string SettingsIdToString(SpdySettingsId id); QUICHE_EXPORT SpdyErrorCode ParseErrorCode(uint32_t wire_error_code); QUICHE_EXPORT const char* ErrorCodeToString(SpdyErrorCode error_code); QUICHE_EXPORT const char* WriteSchedulerTypeToString(WriteSchedulerType type); inline constexpr size_t kFrameMinimumSize = kFrameHeaderSize; inline constexpr size_t kDataFrameMinimumSize = kFrameHeaderSize; inline constexpr size_t kHeadersFrameMinimumSize = kFrameHeaderSize; inline constexpr size_t kPriorityFrameSize = kFrameHeaderSize + 5; inline constexpr size_t kRstStreamFrameSize = kFrameHeaderSize + 4; inline constexpr size_t kSettingsFrameMinimumSize = kFrameHeaderSize; inline constexpr size_t kSettingsOneSettingSize = sizeof(uint32_t) + sizeof(SpdySettingsId); inline constexpr size_t kPushPromiseFrameMinimumSize = kFrameHeaderSize + 4; inline constexpr size_t kPingFrameSize = kFrameHeaderSize + 8; inline constexpr size_t kGoawayFrameMinimumSize = kFrameHeaderSize + 8; inline constexpr size_t kWindowUpdateFrameSize = kFrameHeaderSize + 4; inline constexpr size_t kContinuationFrameMinimumSize = kFrameHeaderSize; inline constexpr size_t kGetAltSvcFrameMinimumSize = kFrameHeaderSize + 2; inline constexpr size_t kPriorityUpdateFrameMinimumSize = kFrameHeaderSize + 4; inline constexpr size_t kAcceptChFrameMinimumSize = kFrameHeaderSize; inline constexpr size_t kAcceptChFramePerEntryOverhead = 4; inline constexpr size_t kMaxFrameSizeLimit = kSpdyMaxFrameSizeLimit + kFrameHeaderSize; inline constexpr size_t kSizeOfSizeField = sizeof(uint32_t); inline constexpr int32_t kInitialStreamWindowSize = 64 * 1024 - 1; inline constexpr int32_t kInitialSessionWindowSize = 64 * 1024 - 1; QUICHE_EXPORT extern const char* const kHttp2Npn; inline constexpr size_t kPerHeaderHpackOverheadNew = 6; inline constexpr size_t kPerHeaderHpackOverheadOld = 4; QUICHE_EXPORT extern const char* const kHttp2AuthorityHeader; QUICHE_EXPORT extern const char* const kHttp2MethodHeader; QUICHE_EXPORT extern const char* const kHttp2PathHeader; QUICHE_EXPORT extern const char* const kHttp2SchemeHeader; QUICHE_EXPORT extern const char* const kHttp2ProtocolHeader; QUICHE_EXPORT extern const char* const kHttp2StatusHeader; QUICHE_EXPORT size_t GetNumberRequiredContinuationFrames(size_t size); template <typename StreamIdType> class QUICHE_EXPORT StreamPrecedence { public: explicit StreamPrecedence(SpdyPriority priority) : precedence_(ClampSpdy3Priority(priority)) {} StreamPrecedence(StreamIdType parent_id, int weight, bool is_exclusive) : precedence_(Http2StreamDependency{parent_id, ClampHttp2Weight(weight), is_exclusive}) {} StreamPrecedence(const StreamPrecedence& other) = default; StreamPrecedence& operator=(const StreamPrecedence& other) = default; bool is_spdy3_priority() const { return absl::holds_alternative<SpdyPriority>(precedence_); } SpdyPriority spdy3_priority() const { return is_spdy3_priority() ? absl::get<SpdyPriority>(precedence_) : Http2WeightToSpdy3Priority( absl::get<Http2StreamDependency>(precedence_).weight); } StreamIdType parent_id() const { return is_spdy3_priority() ? kHttp2RootStreamId : absl::get<Http2StreamDependency>(precedence_).parent_id; } int weight() const { return is_spdy3_priority() ? Spdy3PriorityToHttp2Weight( absl::get<SpdyPriority>(precedence_)) : absl::get<Http2StreamDependency>(precedence_).weight; } bool is_exclusive() const { return absl::holds_alternative<Http2StreamDependency>(precedence_) && absl::get<Http2StreamDependency>(precedence_).is_exclusive; } bool operator==(const StreamPrecedence& other) const { return precedence_ == other.precedence_; } bool operator!=(const StreamPrecedence& other) const { return !(*this == other); } private: struct QUICHE_EXPORT Http2StreamDependency { StreamIdType parent_id; int weight; bool is_exclusive; bool operator==(const Http2StreamDependency& other) const { return parent_id == other.parent_id && weight == other.weight && is_exclusive == other.is_exclusive; } }; absl::variant<SpdyPriority, Http2StreamDependency> precedence_; }; typedef StreamPrecedence<SpdyStreamId> SpdyStreamPrecedence; class SpdyFrameVisitor; class QUICHE_EXPORT SpdyFrameIR { public: virtual ~SpdyFrameIR() {} virtual void Visit(SpdyFrameVisitor* visitor) const = 0; virtual SpdyFrameType frame_type() const = 0; SpdyStreamId stream_id() const { return stream_id_; } virtual bool fin() const; virtual size_t size() const = 0; virtual int flow_control_window_consumed() const; protected: SpdyFrameIR() : stream_id_(0) {} explicit SpdyFrameIR(SpdyStreamId stream_id) : stream_id_(stream_id) {} SpdyFrameIR(const SpdyFrameIR&) = delete; SpdyFrameIR& operator=(const SpdyFrameIR&) = delete; private: SpdyStreamId stream_id_; }; class QUICHE_EXPORT SpdyFrameWithFinIR : public SpdyFrameIR { public: ~SpdyFrameWithFinIR() override {} bool fin() const override; void set_fin(bool fin) { fin_ = fin; } protected: explicit SpdyFrameWithFinIR(SpdyStreamId stream_id) : SpdyFrameIR(stream_id), fin_(false) {} SpdyFrameWithFinIR(const SpdyFrameWithFinIR&) = delete; SpdyFrameWithFinIR& operator=(const SpdyFrameWithFinIR&) = delete; private: bool fin_; }; class QUICHE_EXPORT SpdyFrameWithHeaderBlockIR : public SpdyFrameWithFinIR { public: ~SpdyFrameWithHeaderBlockIR() override; const Http2HeaderBlock& header_block() const { return header_block_; } void set_header_block(Http2HeaderBlock header_block) { header_block_ = std::move(header_block); } void SetHeader(absl::string_view name, absl::string_view value) { header_block_[name] = value; } protected: SpdyFrameWithHeaderBlockIR(SpdyStreamId stream_id, Http2HeaderBlock header_block); SpdyFrameWithHeaderBlockIR(const SpdyFrameWithHeaderBlockIR&) = delete; SpdyFrameWithHeaderBlockIR& operator=(const SpdyFrameWithHeaderBlockIR&) = delete; private: Http2HeaderBlock header_block_; }; class QUICHE_EXPORT SpdyDataIR : public SpdyFrameWithFinIR { public: SpdyDataIR(SpdyStreamId stream_id, absl::string_view data); SpdyDataIR(SpdyStreamId stream_id, const char* data); SpdyDataIR(SpdyStreamId stream_id, std::string data); explicit SpdyDataIR(SpdyStreamId stream_id); SpdyDataIR(const SpdyDataIR&) = delete; SpdyDataIR& operator=(const SpdyDataIR&) = delete; ~SpdyDataIR() override; const char* data() const { return data_; } size_t data_len() const { return data_len_; } bool padded() const { return padded_; } int padding_payload_len() const { return padding_payload_len_; } void set_padding_len(int padding_len) { QUICHE_DCHECK_GT(padding_len, 0); QUICHE_DCHECK_LE(padding_len, kPaddingSizePerFrame); padded_ = true; padding_payload_len_ = padding_len - 1; } void SetDataDeep(absl::string_view data) { data_store_ = std::make_unique<std::string>(data.data(), data.size()); data_ = data_store_->data(); data_len_ = data.size(); } void SetDataShallow(absl::string_view data) { data_store_.reset(); data_ = data.data(); data_len_ = data.size(); } void SetDataShallow(size_t len) { data_store_.reset(); data_ = nullptr; data_len_ = len; } void Visit(SpdyFrameVisitor* visitor) const override; SpdyFrameType frame_type() const override; int flow_control_window_consumed() const override; size_t size() const override; private: std::unique_ptr<std::string> data_store_; const char* data_; size_t data_len_; bool padded_; int padding_payload_len_; }; class QUICHE_EXPORT SpdyRstStreamIR : public SpdyFrameIR { public: SpdyRstStreamIR(SpdyStreamId stream_id, SpdyErrorCode error_code); SpdyRstStreamIR(const SpdyRstStreamIR&) = delete; SpdyRstStreamIR& operator=(const SpdyRstStreamIR&) = delete; ~SpdyRstStreamIR() override; SpdyErrorCode error_code() const { return error_code_; } void set_error_code(SpdyErrorCode error_code) { error_code_ = error_code; } void Visit(SpdyFrameVisitor* visitor) const override; SpdyFrameType frame_type() const override; size_t size() const override; private: SpdyErrorCode error_code_; }; class QUICHE_EXPORT SpdySettingsIR : public SpdyFrameIR { public: SpdySettingsIR(); SpdySettingsIR(const SpdySettingsIR&) = delete; SpdySettingsIR& operator=(const SpdySettingsIR&) = delete; ~SpdySettingsIR() override; const SettingsMap& values() const { return values_; } void AddSetting(SpdySettingsId id, int32_t value) { values_[id] = value; } bool is_ack() const { return is_ack_; } void set_is_ack(bool is_ack) { is_ack_ = is_ack; } void Visit(SpdyFrameVisitor* visitor) const override; SpdyFrameType frame_type() const override; size_t size() const override; private: SettingsMap values_; bool is_ack_; }; class QUICHE_EXPORT SpdyPingIR : public SpdyFrameIR { public: explicit SpdyPingIR(SpdyPingId id) : id_(id), is_ack_(false) {} SpdyPingIR(const SpdyPingIR&) = delete; SpdyPingIR& operator=(const SpdyPingIR&) = delete; SpdyPingId id() const { return id_; } bool is_ack() const { return is_ack_; } void set_is_ack(bool is_ack) { is_ack_ = is_ack; } void Visit(SpdyFrameVisitor* visitor) const override; SpdyFrameType frame_type() const override; size_t size() const override; private: SpdyPingId id_; bool is_ack_; }; class QUICHE_EXPORT SpdyGoAwayIR : public SpdyFrameIR { public: SpdyGoAwayIR(SpdyStreamId last_good_stream_id, SpdyErrorCode error_code, absl::string_view description); SpdyGoAwayIR(SpdyStreamId last_good_stream_id, SpdyErrorCode error_code, const char* description); SpdyGoAwayIR(SpdyStreamId last_good_stream_id, SpdyErrorCode error_code, std::string description); SpdyGoAwayIR(const SpdyGoAwayIR&) = delete; SpdyGoAwayIR& operator=(const SpdyGoAwayIR&) = delete; ~SpdyGoAwayIR() override; SpdyStreamId last_good_stream_id() const { return last_good_stream_id_; } void set_last_good_stream_id(SpdyStreamId last_good_stream_id) { QUICHE_DCHECK_EQ(0u, last_good_stream_id & ~kStreamIdMask); last_good_stream_id_ = last_good_stream_id; } SpdyErrorCode error_code() const { return error_code_; } void set_error_code(SpdyErrorCode error_code) { error_code_ = error_code; } const absl::string_view& description() const { return description_; } void Visit(SpdyFrameVisitor* visitor) const override; SpdyFrameType frame_type() const override; size_t size() const override; private: SpdyStreamId last_good_stream_id_; SpdyErrorCode error_code_; const std::string description_store_; const absl::string_view description_; }; class QUICHE_EXPORT SpdyHeadersIR : public SpdyFrameWithHeaderBlockIR { public: explicit SpdyHeadersIR(SpdyStreamId stream_id) : SpdyHeadersIR(stream_id, Http2HeaderBlock()) {} SpdyHeadersIR(SpdyStreamId stream_id, Http2HeaderBlock header_block) : SpdyFrameWithHeaderBlockIR(stream_id, std::move(header_block)) {} SpdyHeadersIR(const SpdyHeadersIR&) = delete; SpdyHeadersIR& operator=(const SpdyHeadersIR&) = delete; void Visit(SpdyFrameVisitor* visitor) const override; SpdyFrameType frame_type() const override; size_t size() const override; bool has_priority() const { return has_priority_; } void set_has_priority(bool has_priority) { has_priority_ = has_priority; } int weight() const { return weight_; } void set_weight(int weight) { weight_ = weight; } SpdyStreamId parent_stream_id() const { return parent_stream_id_; } void set_parent_stream_id(SpdyStreamId id) { parent_stream_id_ = id; } bool exclusive() const { return exclusive_; } void set_exclusive(bool exclusive) { exclusive_ = exclusive; } bool padded() const { return padded_; } int padding_payload_len() const { return padding_payload_len_; } void set_padding_len(int padding_len) { QUICHE_DCHECK_GT(padding_len, 0); QUICHE_DCHECK_LE(padding_len, kPaddingSizePerFrame); padded_ = true; padding_payload_len_ = padding_len - 1; } private: bool has_priority_ = false; int weight_ = kHttp2DefaultStreamWeight; SpdyStreamId parent_stream_id_ = 0; bool exclusive_ = false; bool padded_ = false; int padding_payload_len_ = 0; const bool add_hpack_overhead_bytes_ = GetQuicheReloadableFlag(http2_add_hpack_overhead_bytes2); }; class QUICHE_EXPORT SpdyWindowUpdateIR : public SpdyFrameIR { public: SpdyWindowUpdateIR(SpdyStreamId stream_id, int32_t delta) : SpdyFrameIR(stream_id) { set_delta(delta); } SpdyWindowUpdateIR(const SpdyWindowUpdateIR&) = delete; SpdyWindowUpdateIR& operator=(const SpdyWindowUpdateIR&) = delete; int32_t delta() const { return delta_; } void set_delta(int32_t delta) { QUICHE_DCHECK_LE(0, delta); QUICHE_DCHECK_LE(delta, kSpdyMaximumWindowSize); delta_ = delta; } void Visit(SpdyFrameVisitor* visitor) const override; SpdyFrameType frame_type() const override; size_t size() const override; private: int32_t delta_; }; class QUICHE_EXPORT SpdyPushPromiseIR : public SpdyFrameWithHeaderBlockIR { public: SpdyPushPromiseIR(SpdyStreamId stream_id, SpdyStreamId promised_stream_id) : SpdyPushPromiseIR(stream_id, promised_stream_id, Http2HeaderBlock()) {} SpdyPushPromiseIR(SpdyStreamId stream_id, SpdyStreamId promised_stream_id, Http2HeaderBlock header_block) : SpdyFrameWithHeaderBlockIR(stream_id, std::move(header_block)), promised_stream_id_(promised_stream_id), padded_(false), padding_payload_len_(0) {} SpdyPushPromiseIR(const SpdyPushPromiseIR&) = delete; SpdyPushPromiseIR& operator=(const SpdyPushPromiseIR&) = delete; SpdyStreamId promised_stream_id() const { return promised_stream_id_; } void Visit(SpdyFrameVisitor* visitor) const override; SpdyFrameType frame_type() const override; size_t size() const override; bool padded() const { return padded_; } int padding_payload_len() const { return padding_payload_len_; } void set_padding_len(int padding_len) { QUICHE_DCHECK_GT(padding_len, 0); QUICHE_DCHECK_LE(padding_len, kPaddingSizePerFrame); padded_ = true; padding_payload_len_ = padding_len - 1; } private: SpdyStreamId promised_stream_id_; bool padded_; int padding_payload_len_; }; class QUICHE_EXPORT SpdyContinuationIR : public SpdyFrameIR { public: explicit SpdyContinuationIR(SpdyStreamId stream_id); SpdyContinuationIR(const SpdyContinuationIR&) = delete; SpdyContinuationIR& operator=(const SpdyContinuationIR&) = delete; ~SpdyContinuationIR() override; void Visit(SpdyFrameVisitor* visitor) const override; SpdyFrameType frame_type() const override; bool end_headers() const { return end_headers_; } void set_end_headers(bool end_headers) { end_headers_ = end_headers; } const std::string& encoding() const { return encoding_; } void take_encoding(std::string encoding) { encoding_ = std::move(encoding); } size_t size() const override; private: std::string encoding_; bool end_headers_; }; class QUICHE_EXPORT SpdyAltSvcIR : public SpdyFrameIR { public: explicit SpdyAltSvcIR(SpdyStreamId stream_id); SpdyAltSvcIR(const SpdyAltSvcIR&) = delete; SpdyAltSvcIR& operator=(const SpdyAltSvcIR&) = delete; ~SpdyAltSvcIR() override; std::string origin() const { return origin_; } const SpdyAltSvcWireFormat::AlternativeServiceVector& altsvc_vector() const { return altsvc_vector_; } void set_origin(std::string origin) { origin_ = std::move(origin); } void add_altsvc(const SpdyAltSvcWireFormat::AlternativeService& altsvc) { altsvc_vector_.push_back(altsvc); } void Visit(SpdyFrameVisitor* visitor) const override; SpdyFrameType frame_type() const override; size_t size() const override; private: std::string origin_; SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector_; }; class QUICHE_EXPORT SpdyPriorityIR : public SpdyFrameIR { public: SpdyPriorityIR(SpdyStreamId stream_id, SpdyStreamId parent_stream_id,
#include "quiche/spdy/core/spdy_protocol.h" #include <iostream> #include <string> #include <utility> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_expect_bug.h" #include "quiche/common/platform/api/quiche_test.h" namespace spdy { std::ostream& operator<<(std::ostream& os, const SpdyStreamPrecedence precedence) { if (precedence.is_spdy3_priority()) { os << "SpdyStreamPrecedence[spdy3_priority=" << precedence.spdy3_priority() << "]"; } else { os << "SpdyStreamPrecedence[parent_id=" << precedence.parent_id() << ", weight=" << precedence.weight() << ", is_exclusive=" << precedence.is_exclusive() << "]"; } return os; } namespace test { TEST(SpdyProtocolTest, ClampSpdy3Priority) { EXPECT_QUICHE_BUG(EXPECT_EQ(7, ClampSpdy3Priority(8)), "Invalid priority: 8"); EXPECT_EQ(kV3LowestPriority, ClampSpdy3Priority(kV3LowestPriority)); EXPECT_EQ(kV3HighestPriority, ClampSpdy3Priority(kV3HighestPriority)); } TEST(SpdyProtocolTest, ClampHttp2Weight) { EXPECT_QUICHE_BUG(EXPECT_EQ(kHttp2MinStreamWeight, ClampHttp2Weight(0)), "Invalid weight: 0"); EXPECT_QUICHE_BUG(EXPECT_EQ(kHttp2MaxStreamWeight, ClampHttp2Weight(300)), "Invalid weight: 300"); EXPECT_EQ(kHttp2MinStreamWeight, ClampHttp2Weight(kHttp2MinStreamWeight)); EXPECT_EQ(kHttp2MaxStreamWeight, ClampHttp2Weight(kHttp2MaxStreamWeight)); } TEST(SpdyProtocolTest, Spdy3PriorityToHttp2Weight) { EXPECT_EQ(256, Spdy3PriorityToHttp2Weight(0)); EXPECT_EQ(220, Spdy3PriorityToHttp2Weight(1)); EXPECT_EQ(183, Spdy3PriorityToHttp2Weight(2)); EXPECT_EQ(147, Spdy3PriorityToHttp2Weight(3)); EXPECT_EQ(110, Spdy3PriorityToHttp2Weight(4)); EXPECT_EQ(74, Spdy3PriorityToHttp2Weight(5)); EXPECT_EQ(37, Spdy3PriorityToHttp2Weight(6)); EXPECT_EQ(1, Spdy3PriorityToHttp2Weight(7)); } TEST(SpdyProtocolTest, Http2WeightToSpdy3Priority) { EXPECT_EQ(0u, Http2WeightToSpdy3Priority(256)); EXPECT_EQ(0u, Http2WeightToSpdy3Priority(221)); EXPECT_EQ(1u, Http2WeightToSpdy3Priority(220)); EXPECT_EQ(1u, Http2WeightToSpdy3Priority(184)); EXPECT_EQ(2u, Http2WeightToSpdy3Priority(183)); EXPECT_EQ(2u, Http2WeightToSpdy3Priority(148)); EXPECT_EQ(3u, Http2WeightToSpdy3Priority(147)); EXPECT_EQ(3u, Http2WeightToSpdy3Priority(111)); EXPECT_EQ(4u, Http2WeightToSpdy3Priority(110)); EXPECT_EQ(4u, Http2WeightToSpdy3Priority(75)); EXPECT_EQ(5u, Http2WeightToSpdy3Priority(74)); EXPECT_EQ(5u, Http2WeightToSpdy3Priority(38)); EXPECT_EQ(6u, Http2WeightToSpdy3Priority(37)); EXPECT_EQ(6u, Http2WeightToSpdy3Priority(2)); EXPECT_EQ(7u, Http2WeightToSpdy3Priority(1)); } TEST(SpdyProtocolTest, IsValidHTTP2FrameStreamId) { EXPECT_TRUE(IsValidHTTP2FrameStreamId(1, SpdyFrameType::DATA)); EXPECT_FALSE(IsValidHTTP2FrameStreamId(0, SpdyFrameType::DATA)); EXPECT_TRUE(IsValidHTTP2FrameStreamId(1, SpdyFrameType::HEADERS)); EXPECT_FALSE(IsValidHTTP2FrameStreamId(0, SpdyFrameType::HEADERS)); EXPECT_TRUE(IsValidHTTP2FrameStreamId(1, SpdyFrameType::PRIORITY)); EXPECT_FALSE(IsValidHTTP2FrameStreamId(0, SpdyFrameType::PRIORITY)); EXPECT_TRUE(IsValidHTTP2FrameStreamId(1, SpdyFrameType::RST_STREAM)); EXPECT_FALSE(IsValidHTTP2FrameStreamId(0, SpdyFrameType::RST_STREAM)); EXPECT_TRUE(IsValidHTTP2FrameStreamId(1, SpdyFrameType::CONTINUATION)); EXPECT_FALSE(IsValidHTTP2FrameStreamId(0, SpdyFrameType::CONTINUATION)); EXPECT_TRUE(IsValidHTTP2FrameStreamId(1, SpdyFrameType::PUSH_PROMISE)); EXPECT_FALSE(IsValidHTTP2FrameStreamId(0, SpdyFrameType::PUSH_PROMISE)); EXPECT_FALSE(IsValidHTTP2FrameStreamId(1, SpdyFrameType::GOAWAY)); EXPECT_TRUE(IsValidHTTP2FrameStreamId(0, SpdyFrameType::GOAWAY)); EXPECT_FALSE(IsValidHTTP2FrameStreamId(1, SpdyFrameType::SETTINGS)); EXPECT_TRUE(IsValidHTTP2FrameStreamId(0, SpdyFrameType::SETTINGS)); EXPECT_FALSE(IsValidHTTP2FrameStreamId(1, SpdyFrameType::PING)); EXPECT_TRUE(IsValidHTTP2FrameStreamId(0, SpdyFrameType::PING)); EXPECT_TRUE(IsValidHTTP2FrameStreamId(1, SpdyFrameType::WINDOW_UPDATE)); EXPECT_TRUE(IsValidHTTP2FrameStreamId(0, SpdyFrameType::WINDOW_UPDATE)); } TEST(SpdyProtocolTest, ParseSettingsId) { SpdyKnownSettingsId setting_id; EXPECT_FALSE(ParseSettingsId(0, &setting_id)); EXPECT_TRUE(ParseSettingsId(1, &setting_id)); EXPECT_EQ(SETTINGS_HEADER_TABLE_SIZE, setting_id); EXPECT_TRUE(ParseSettingsId(2, &setting_id)); EXPECT_EQ(SETTINGS_ENABLE_PUSH, setting_id); EXPECT_TRUE(ParseSettingsId(3, &setting_id)); EXPECT_EQ(SETTINGS_MAX_CONCURRENT_STREAMS, setting_id); EXPECT_TRUE(ParseSettingsId(4, &setting_id)); EXPECT_EQ(SETTINGS_INITIAL_WINDOW_SIZE, setting_id); EXPECT_TRUE(ParseSettingsId(5, &setting_id)); EXPECT_EQ(SETTINGS_MAX_FRAME_SIZE, setting_id); EXPECT_TRUE(ParseSettingsId(6, &setting_id)); EXPECT_EQ(SETTINGS_MAX_HEADER_LIST_SIZE, setting_id); EXPECT_FALSE(ParseSettingsId(7, &setting_id)); EXPECT_TRUE(ParseSettingsId(8, &setting_id)); EXPECT_EQ(SETTINGS_ENABLE_CONNECT_PROTOCOL, setting_id); EXPECT_TRUE(ParseSettingsId(9, &setting_id)); EXPECT_EQ(SETTINGS_DEPRECATE_HTTP2_PRIORITIES, setting_id); EXPECT_FALSE(ParseSettingsId(10, &setting_id)); EXPECT_FALSE(ParseSettingsId(0xFF44, &setting_id)); EXPECT_TRUE(ParseSettingsId(0xFF45, &setting_id)); EXPECT_EQ(SETTINGS_EXPERIMENT_SCHEDULER, setting_id); EXPECT_FALSE(ParseSettingsId(0xFF46, &setting_id)); } TEST(SpdyProtocolTest, SettingsIdToString) { struct { SpdySettingsId setting_id; const std::string expected_string; } test_cases[] = { {0, "SETTINGS_UNKNOWN_0"}, {SETTINGS_HEADER_TABLE_SIZE, "SETTINGS_HEADER_TABLE_SIZE"}, {SETTINGS_ENABLE_PUSH, "SETTINGS_ENABLE_PUSH"}, {SETTINGS_MAX_CONCURRENT_STREAMS, "SETTINGS_MAX_CONCURRENT_STREAMS"}, {SETTINGS_INITIAL_WINDOW_SIZE, "SETTINGS_INITIAL_WINDOW_SIZE"}, {SETTINGS_MAX_FRAME_SIZE, "SETTINGS_MAX_FRAME_SIZE"}, {SETTINGS_MAX_HEADER_LIST_SIZE, "SETTINGS_MAX_HEADER_LIST_SIZE"}, {7, "SETTINGS_UNKNOWN_7"}, {SETTINGS_ENABLE_CONNECT_PROTOCOL, "SETTINGS_ENABLE_CONNECT_PROTOCOL"}, {SETTINGS_DEPRECATE_HTTP2_PRIORITIES, "SETTINGS_DEPRECATE_HTTP2_PRIORITIES"}, {0xa, "SETTINGS_UNKNOWN_a"}, {0xFF44, "SETTINGS_UNKNOWN_ff44"}, {0xFF45, "SETTINGS_EXPERIMENT_SCHEDULER"}, {0xFF46, "SETTINGS_UNKNOWN_ff46"}}; for (auto test_case : test_cases) { EXPECT_EQ(test_case.expected_string, SettingsIdToString(test_case.setting_id)); } } TEST(SpdyStreamPrecedenceTest, Basic) { SpdyStreamPrecedence spdy3_prec(2); EXPECT_TRUE(spdy3_prec.is_spdy3_priority()); EXPECT_EQ(2, spdy3_prec.spdy3_priority()); EXPECT_EQ(kHttp2RootStreamId, spdy3_prec.parent_id()); EXPECT_EQ(Spdy3PriorityToHttp2Weight(2), spdy3_prec.weight()); EXPECT_FALSE(spdy3_prec.is_exclusive()); for (bool is_exclusive : {true, false}) { SpdyStreamPrecedence h2_prec(7, 123, is_exclusive); EXPECT_FALSE(h2_prec.is_spdy3_priority()); EXPECT_EQ(Http2WeightToSpdy3Priority(123), h2_prec.spdy3_priority()); EXPECT_EQ(7u, h2_prec.parent_id()); EXPECT_EQ(123, h2_prec.weight()); EXPECT_EQ(is_exclusive, h2_prec.is_exclusive()); } } TEST(SpdyStreamPrecedenceTest, Clamping) { EXPECT_QUICHE_BUG(EXPECT_EQ(7, SpdyStreamPrecedence(8).spdy3_priority()), "Invalid priority: 8"); EXPECT_QUICHE_BUG(EXPECT_EQ(kHttp2MinStreamWeight, SpdyStreamPrecedence(3, 0, false).weight()), "Invalid weight: 0"); EXPECT_QUICHE_BUG(EXPECT_EQ(kHttp2MaxStreamWeight, SpdyStreamPrecedence(3, 300, false).weight()), "Invalid weight: 300"); } TEST(SpdyStreamPrecedenceTest, Copying) { SpdyStreamPrecedence prec1(3); SpdyStreamPrecedence copy1(prec1); EXPECT_TRUE(copy1.is_spdy3_priority()); EXPECT_EQ(3, copy1.spdy3_priority()); SpdyStreamPrecedence prec2(4, 5, true); SpdyStreamPrecedence copy2(prec2); EXPECT_FALSE(copy2.is_spdy3_priority()); EXPECT_EQ(4u, copy2.parent_id()); EXPECT_EQ(5, copy2.weight()); EXPECT_TRUE(copy2.is_exclusive()); copy1 = prec2; EXPECT_FALSE(copy1.is_spdy3_priority()); EXPECT_EQ(4u, copy1.parent_id()); EXPECT_EQ(5, copy1.weight()); EXPECT_TRUE(copy1.is_exclusive()); copy2 = prec1; EXPECT_TRUE(copy2.is_spdy3_priority()); EXPECT_EQ(3, copy2.spdy3_priority()); } TEST(SpdyStreamPrecedenceTest, Equals) { EXPECT_EQ(SpdyStreamPrecedence(3), SpdyStreamPrecedence(3)); EXPECT_NE(SpdyStreamPrecedence(3), SpdyStreamPrecedence(4)); EXPECT_EQ(SpdyStreamPrecedence(1, 2, false), SpdyStreamPrecedence(1, 2, false)); EXPECT_NE(SpdyStreamPrecedence(1, 2, false), SpdyStreamPrecedence(2, 2, false)); EXPECT_NE(SpdyStreamPrecedence(1, 2, false), SpdyStreamPrecedence(1, 3, false)); EXPECT_NE(SpdyStreamPrecedence(1, 2, false), SpdyStreamPrecedence(1, 2, true)); SpdyStreamPrecedence spdy3_prec(3); SpdyStreamPrecedence h2_prec(spdy3_prec.parent_id(), spdy3_prec.weight(), spdy3_prec.is_exclusive()); EXPECT_NE(spdy3_prec, h2_prec); } TEST(SpdyDataIRTest, Construct) { absl::string_view s1; SpdyDataIR d1( 1, s1); EXPECT_EQ(0u, d1.data_len()); EXPECT_NE(nullptr, d1.data()); const char s2[] = "something"; SpdyDataIR d2( 2, s2); EXPECT_EQ(absl::string_view(d2.data(), d2.data_len()), s2); EXPECT_NE(absl::string_view(d1.data(), d1.data_len()), s2); EXPECT_EQ((int)d1.data_len(), d1.flow_control_window_consumed()); const std::string foo = "foo"; SpdyDataIR d3( 3, foo); EXPECT_EQ(foo, d3.data()); EXPECT_EQ((int)d3.data_len(), d3.flow_control_window_consumed()); std::string bar = "bar"; SpdyDataIR d4( 4, bar); EXPECT_EQ("bar", bar); EXPECT_EQ("bar", absl::string_view(d4.data(), d4.data_len())); std::string baz = "the quick brown fox"; SpdyDataIR d5( 5, std::move(baz)); EXPECT_EQ("", baz); EXPECT_EQ(absl::string_view(d5.data(), d5.data_len()), "the quick brown fox"); SpdyDataIR d7( 7, "something else"); EXPECT_EQ(absl::string_view(d7.data(), d7.data_len()), "something else"); SpdyDataIR d8( 8, "shawarma"); d8.set_padding_len(20); EXPECT_EQ(28, d8.flow_control_window_consumed()); } } }
391
cpp
google/quiche
hpack_encoder
quiche/http2/hpack/hpack_encoder.cc
quiche/http2/hpack/hpack_encoder_test.cc
#ifndef QUICHE_SPDY_CORE_HPACK_HPACK_ENCODER_H_ #define QUICHE_SPDY_CORE_HPACK_HPACK_ENCODER_H_ #include <stddef.h> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/quiche_callbacks.h" #include "quiche/spdy/core/hpack/hpack_header_table.h" #include "quiche/spdy/core/hpack/hpack_output_stream.h" #include "quiche/spdy/core/http2_header_block.h" namespace spdy { namespace test { class HpackEncoderPeer; } class QUICHE_EXPORT HpackEncoder { public: using Representation = std::pair<absl::string_view, absl::string_view>; using Representations = std::vector<Representation>; using HeaderListener = quiche::MultiUseCallback<void(absl::string_view, absl::string_view)>; using IndexingPolicy = quiche::MultiUseCallback<bool(absl::string_view, absl::string_view)>; HpackEncoder(); HpackEncoder(const HpackEncoder&) = delete; HpackEncoder& operator=(const HpackEncoder&) = delete; ~HpackEncoder(); std::string EncodeHeaderBlock(const Http2HeaderBlock& header_set); class QUICHE_EXPORT ProgressiveEncoder { public: virtual ~ProgressiveEncoder() {} virtual bool HasNext() const = 0; virtual std::string Next(size_t max_encoded_bytes) = 0; }; std::unique_ptr<ProgressiveEncoder> EncodeHeaderSet( const Http2HeaderBlock& header_set); std::unique_ptr<ProgressiveEncoder> EncodeRepresentations( const Representations& representations); void ApplyHeaderTableSizeSetting(size_t size_setting); size_t CurrentHeaderTableSizeSetting() const { return header_table_.settings_size_bound(); } void SetIndexingPolicy(IndexingPolicy policy) { should_index_ = std::move(policy); } void SetHeaderListener(HeaderListener listener) { listener_ = std::move(listener); } void DisableCompression() { enable_compression_ = false; } void DisableCookieCrumbling() { crumble_cookies_ = false; } size_t GetDynamicTableSize() const { return header_table_.size(); } private: friend class test::HpackEncoderPeer; class RepresentationIterator; class Encoderator; std::string EncodeRepresentations(RepresentationIterator* iter); void EmitIndex(size_t index); void EmitIndexedLiteral(const Representation& representation); void EmitNonIndexedLiteral(const Representation& representation, bool enable_compression); void EmitLiteral(const Representation& representation); void EmitString(absl::string_view str); void MaybeEmitTableSize(); static void CookieToCrumbs(const Representation& cookie, Representations* crumbs_out); static void DecomposeRepresentation(const Representation& header_field, Representations* out); HpackHeaderTable header_table_; HpackOutputStream output_stream_; size_t min_table_size_setting_received_; HeaderListener listener_; IndexingPolicy should_index_; bool enable_compression_; bool should_emit_table_size_; bool crumble_cookies_; }; } #endif #include "quiche/spdy/core/hpack/hpack_encoder.h" #include <algorithm> #include <cstddef> #include <limits> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "quiche/http2/hpack/huffman/hpack_huffman_encoder.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/spdy/core/hpack/hpack_constants.h" #include "quiche/spdy/core/hpack/hpack_header_table.h" #include "quiche/spdy/core/hpack/hpack_output_stream.h" #include "quiche/spdy/core/http2_header_block.h" namespace spdy { class HpackEncoder::RepresentationIterator { public: RepresentationIterator(const Representations& pseudo_headers, const Representations& regular_headers) : pseudo_begin_(pseudo_headers.begin()), pseudo_end_(pseudo_headers.end()), regular_begin_(regular_headers.begin()), regular_end_(regular_headers.end()) {} explicit RepresentationIterator(const Representations& headers) : pseudo_begin_(headers.begin()), pseudo_end_(headers.end()), regular_begin_(headers.end()), regular_end_(headers.end()) {} bool HasNext() { return pseudo_begin_ != pseudo_end_ || regular_begin_ != regular_end_; } const Representation Next() { if (pseudo_begin_ != pseudo_end_) { return *pseudo_begin_++; } else { return *regular_begin_++; } } private: Representations::const_iterator pseudo_begin_; Representations::const_iterator pseudo_end_; Representations::const_iterator regular_begin_; Representations::const_iterator regular_end_; }; namespace { void NoOpListener(absl::string_view , absl::string_view ) {} bool DefaultPolicy(absl::string_view name, absl::string_view ) { if (name.empty()) { return false; } if (name[0] == kPseudoHeaderPrefix) { return name == ":authority"; } return true; } } HpackEncoder::HpackEncoder() : output_stream_(), min_table_size_setting_received_(std::numeric_limits<size_t>::max()), listener_(NoOpListener), should_index_(DefaultPolicy), enable_compression_(true), should_emit_table_size_(false), crumble_cookies_(true) {} HpackEncoder::~HpackEncoder() = default; std::string HpackEncoder::EncodeHeaderBlock( const Http2HeaderBlock& header_set) { Representations pseudo_headers; Representations regular_headers; bool found_cookie = false; for (const auto& header : header_set) { if (!found_cookie && header.first == "cookie") { found_cookie = true; if (crumble_cookies_) { CookieToCrumbs(header, &regular_headers); } else { DecomposeRepresentation(header, &regular_headers); } } else if (!header.first.empty() && header.first[0] == kPseudoHeaderPrefix) { DecomposeRepresentation(header, &pseudo_headers); } else { DecomposeRepresentation(header, &regular_headers); } } RepresentationIterator iter(pseudo_headers, regular_headers); return EncodeRepresentations(&iter); } void HpackEncoder::ApplyHeaderTableSizeSetting(size_t size_setting) { if (size_setting == header_table_.settings_size_bound()) { return; } if (size_setting < header_table_.settings_size_bound()) { min_table_size_setting_received_ = std::min(size_setting, min_table_size_setting_received_); } header_table_.SetSettingsHeaderTableSize(size_setting); should_emit_table_size_ = true; } std::string HpackEncoder::EncodeRepresentations(RepresentationIterator* iter) { MaybeEmitTableSize(); while (iter->HasNext()) { const auto header = iter->Next(); listener_(header.first, header.second); if (enable_compression_) { size_t index = header_table_.GetByNameAndValue(header.first, header.second); if (index != kHpackEntryNotFound) { EmitIndex(index); } else if (should_index_(header.first, header.second)) { EmitIndexedLiteral(header); } else { EmitNonIndexedLiteral(header, enable_compression_); } } else { EmitNonIndexedLiteral(header, enable_compression_); } } return output_stream_.TakeString(); } void HpackEncoder::EmitIndex(size_t index) { QUICHE_DVLOG(2) << "Emitting index " << index; output_stream_.AppendPrefix(kIndexedOpcode); output_stream_.AppendUint32(index); } void HpackEncoder::EmitIndexedLiteral(const Representation& representation) { QUICHE_DVLOG(2) << "Emitting indexed literal: (" << representation.first << ", " << representation.second << ")"; output_stream_.AppendPrefix(kLiteralIncrementalIndexOpcode); EmitLiteral(representation); header_table_.TryAddEntry(representation.first, representation.second); } void HpackEncoder::EmitNonIndexedLiteral(const Representation& representation, bool enable_compression) { QUICHE_DVLOG(2) << "Emitting nonindexed literal: (" << representation.first << ", " << representation.second << ")"; output_stream_.AppendPrefix(kLiteralNoIndexOpcode); size_t name_index = header_table_.GetByName(representation.first); if (enable_compression && name_index != kHpackEntryNotFound) { output_stream_.AppendUint32(name_index); } else { output_stream_.AppendUint32(0); EmitString(representation.first); } EmitString(representation.second); } void HpackEncoder::EmitLiteral(const Representation& representation) { size_t name_index = header_table_.GetByName(representation.first); if (name_index != kHpackEntryNotFound) { output_stream_.AppendUint32(name_index); } else { output_stream_.AppendUint32(0); EmitString(representation.first); } EmitString(representation.second); } void HpackEncoder::EmitString(absl::string_view str) { size_t encoded_size = enable_compression_ ? http2::HuffmanSize(str) : str.size(); if (encoded_size < str.size()) { QUICHE_DVLOG(2) << "Emitted Huffman-encoded string of length " << encoded_size; output_stream_.AppendPrefix(kStringLiteralHuffmanEncoded); output_stream_.AppendUint32(encoded_size); http2::HuffmanEncodeFast(str, encoded_size, output_stream_.MutableString()); } else { QUICHE_DVLOG(2) << "Emitted literal string of length " << str.size(); output_stream_.AppendPrefix(kStringLiteralIdentityEncoded); output_stream_.AppendUint32(str.size()); output_stream_.AppendBytes(str); } } void HpackEncoder::MaybeEmitTableSize() { if (!should_emit_table_size_) { return; } const size_t current_size = CurrentHeaderTableSizeSetting(); QUICHE_DVLOG(1) << "MaybeEmitTableSize current_size=" << current_size; QUICHE_DVLOG(1) << "MaybeEmitTableSize min_table_size_setting_received_=" << min_table_size_setting_received_; if (min_table_size_setting_received_ < current_size) { output_stream_.AppendPrefix(kHeaderTableSizeUpdateOpcode); output_stream_.AppendUint32(min_table_size_setting_received_); } output_stream_.AppendPrefix(kHeaderTableSizeUpdateOpcode); output_stream_.AppendUint32(current_size); min_table_size_setting_received_ = std::numeric_limits<size_t>::max(); should_emit_table_size_ = false; } void HpackEncoder::CookieToCrumbs(const Representation& cookie, Representations* out) { absl::string_view cookie_value = cookie.second; absl::string_view::size_type first = cookie_value.find_first_not_of(" \t"); absl::string_view::size_type last = cookie_value.find_last_not_of(" \t"); if (first == absl::string_view::npos) { cookie_value = absl::string_view(); } else { cookie_value = cookie_value.substr(first, (last - first) + 1); } for (size_t pos = 0;;) { size_t end = cookie_value.find(';', pos); if (end == absl::string_view::npos) { out->push_back(std::make_pair(cookie.first, cookie_value.substr(pos))); break; } out->push_back( std::make_pair(cookie.first, cookie_value.substr(pos, end - pos))); pos = end + 1; if (pos != cookie_value.size() && cookie_value[pos] == ' ') { pos++; } } } void HpackEncoder::DecomposeRepresentation(const Representation& header_field, Representations* out) { std::vector<absl::string_view> pieces = absl::StrSplit(header_field.second, '\0'); out->reserve(pieces.size()); for (absl::string_view piece : pieces) { out->push_back(std::make_pair(header_field.first, piece)); } } class HpackEncoder::Encoderator : public ProgressiveEncoder { public: Encoderator(const Http2HeaderBlock& header_set, HpackEncoder* encoder); Encoderator(const Representations& representations, HpackEncoder* encoder); Encoderator(const Encoderator&) = delete; Encoderator& operator=(const Encoderator&) = delete; bool HasNext() const override { return has_next_; } std::string Next(size_t max_encoded_bytes) override; private: HpackEncoder* encoder_; std::unique_ptr<RepresentationIterator> header_it_; Representations pseudo_headers_; Representations regular_headers_; bool has_next_; }; HpackEncoder::Encoderator::Encoderator(const Http2HeaderBlock& header_set, HpackEncoder* encoder) : encoder_(encoder), has_next_(true) { bool found_cookie = false; for (const auto& header : header_set) { if (!found_cookie && header.first == "cookie") { found_cookie = true; if (encoder_->crumble_cookies_) { CookieToCrumbs(header, &regular_headers_); } else { DecomposeRepresentation(header, &regular_headers_); } } else if (!header.first.empty() && header.first[0] == kPseudoHeaderPrefix) { DecomposeRepresentation(header, &pseudo_headers_); } else { DecomposeRepresentation(header, &regular_headers_); } } header_it_ = std::make_unique<RepresentationIterator>(pseudo_headers_, regular_headers_); encoder_->MaybeEmitTableSize(); } HpackEncoder::Encoderator::Encoderator(const Representations& representations, HpackEncoder* encoder) : encoder_(encoder), has_next_(true) { for (const auto& header : representations) { if (header.first == "cookie") { if (encoder_->crumble_cookies_) { CookieToCrumbs(header, &regular_headers_); } else { DecomposeRepresentation(header, &regular_headers_); } } else if (!header.first.empty() && header.first[0] == kPseudoHeaderPrefix) { pseudo_headers_.push_back(header); } else { regular_headers_.push_back(header); } } header_it_ = std::make_unique<RepresentationIterator>(pseudo_headers_, regular_headers_); encoder_->MaybeEmitTableSize(); } std::string HpackEncoder::Encoderator::Next(size_t max_encoded_bytes) { QUICHE_BUG_IF(spdy_bug_61_1, !has_next_) << "Encoderator::Next called with nothing left to encode."; const bool enable_compression = encoder_->enable_compression_; while (header_it_->HasNext() && encoder_->output_stream_.size() <= max_encoded_bytes) { const Representation header = header_it_->Next(); encoder_->listener_(header.first, header.second); if (enable_compression) { size_t index = encoder_->header_table_.GetByNameAndValue(header.first, header.second); if (index != kHpackEntryNotFound) { encoder_->EmitIndex(index); } else if (encoder_->should_index_(header.first, header.second)) { encoder_->EmitIndexedLiteral(header); } else { encoder_->EmitNonIndexedLiteral(header, enable_compression); } } else { encoder_->EmitNonIndexedLiteral(header, enable_compression); } } has_next_ = encoder_->output_stream_.size() > max_encoded_bytes; return encoder_->output_stream_.BoundedTakeString(max_encoded_bytes); } std::unique_ptr<HpackEncoder::ProgressiveEncoder> HpackEncoder::EncodeHeaderSet( const Http2HeaderBlock& header_set) { return std::make_unique<Encoderator>(header_set, this); } std::unique_ptr<HpackEncoder::ProgressiveEncoder> HpackEncoder::EncodeRepresentations(const Representations& representations) { return std::make_unique<Encoderator>(representations, this); } }
#include "quiche/spdy/core/hpack/hpack_encoder.h" #include <cstddef> #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "quiche/http2/hpack/huffman/hpack_huffman_encoder.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_simple_arena.h" #include "quiche/spdy/core/hpack/hpack_constants.h" #include "quiche/spdy/core/hpack/hpack_entry.h" #include "quiche/spdy/core/hpack/hpack_header_table.h" #include "quiche/spdy/core/hpack/hpack_output_stream.h" #include "quiche/spdy/core/hpack/hpack_static_table.h" #include "quiche/spdy/core/http2_header_block.h" namespace spdy { namespace test { class HpackHeaderTablePeer { public: explicit HpackHeaderTablePeer(HpackHeaderTable* table) : table_(table) {} const HpackEntry* GetFirstStaticEntry() const { return &table_->static_entries_.front(); } HpackHeaderTable::DynamicEntryTable* dynamic_entries() { return &table_->dynamic_entries_; } private: HpackHeaderTable* table_; }; class HpackEncoderPeer { public: typedef HpackEncoder::Representation Representation; typedef HpackEncoder::Representations Representations; explicit HpackEncoderPeer(HpackEncoder* encoder) : encoder_(encoder) {} bool compression_enabled() const { return encoder_->enable_compression_; } HpackHeaderTable* table() { return &encoder_->header_table_; } HpackHeaderTablePeer table_peer() { return HpackHeaderTablePeer(table()); } void EmitString(absl::string_view str) { encoder_->EmitString(str); } void TakeString(std::string* out) { *out = encoder_->output_stream_.TakeString(); } static void CookieToCrumbs(absl::string_view cookie, std::vector<absl::string_view>* out) { Representations tmp; HpackEncoder::CookieToCrumbs(std::make_pair("", cookie), &tmp); out->clear(); for (size_t i = 0; i != tmp.size(); ++i) { out->push_back(tmp[i].second); } } static void DecomposeRepresentation(absl::string_view value, std::vector<absl::string_view>* out) { Representations tmp; HpackEncoder::DecomposeRepresentation(std::make_pair("foobar", value), &tmp); out->clear(); for (size_t i = 0; i != tmp.size(); ++i) { out->push_back(tmp[i].second); } } static std::string EncodeHeaderBlock(HpackEncoder* encoder, const Http2HeaderBlock& header_set) { return encoder->EncodeHeaderBlock(header_set); } static bool EncodeIncremental(HpackEncoder* encoder, const Http2HeaderBlock& header_set, std::string* output) { std::unique_ptr<HpackEncoder::ProgressiveEncoder> encoderator = encoder->EncodeHeaderSet(header_set); http2::test::Http2Random random; std::string output_buffer = encoderator->Next(random.UniformInRange(0, 16)); while (encoderator->HasNext()) { std::string second_buffer = encoderator->Next(random.UniformInRange(0, 16)); output_buffer.append(second_buffer); } *output = std::move(output_buffer); return true; } static bool EncodeRepresentations(HpackEncoder* encoder, const Representations& representations, std::string* output) { std::unique_ptr<HpackEncoder::ProgressiveEncoder> encoderator = encoder->EncodeRepresentations(representations); http2::test::Http2Random random; std::string output_buffer = encoderator->Next(random.UniformInRange(0, 16)); while (encoderator->HasNext()) { std::string second_buffer = encoderator->Next(random.UniformInRange(0, 16)); output_buffer.append(second_buffer); } *output = std::move(output_buffer); return true; } private: HpackEncoder* encoder_; }; } namespace { using testing::ElementsAre; using testing::Pair; const size_t kStaticEntryIndex = 1; enum EncodeStrategy { kDefault, kIncremental, kRepresentations, }; class HpackEncoderTest : public quiche::test::QuicheTestWithParam<EncodeStrategy> { protected: typedef test::HpackEncoderPeer::Representations Representations; HpackEncoderTest() : peer_(&encoder_), static_(peer_.table_peer().GetFirstStaticEntry()), dynamic_table_insertions_(0), headers_storage_(1024 ), strategy_(GetParam()) {} void SetUp() override { key_1_ = peer_.table()->TryAddEntry("key1", "value1"); key_1_index_ = dynamic_table_insertions_++; key_2_ = peer_.table()->TryAddEntry("key2", "value2"); key_2_index_ = dynamic_table_insertions_++; cookie_a_ = peer_.table()->TryAddEntry("cookie", "a=bb"); cookie_a_index_ = dynamic_table_insertions_++; cookie_c_ = peer_.table()->TryAddEntry("cookie", "c=dd"); cookie_c_index_ = dynamic_table_insertions_++; peer_.table()->SetMaxSize(peer_.table()->size()); QUICHE_CHECK_EQ(kInitialDynamicTableSize, peer_.table()->size()); } void SaveHeaders(absl::string_view name, absl::string_view value) { absl::string_view n(headers_storage_.Memdup(name.data(), name.size()), name.size()); absl::string_view v(headers_storage_.Memdup(value.data(), value.size()), value.size()); headers_observed_.push_back(std::make_pair(n, v)); } void ExpectIndex(size_t index) { expected_.AppendPrefix(kIndexedOpcode); expected_.AppendUint32(index); } void ExpectIndexedLiteral(size_t key_index, absl::string_view value) { expected_.AppendPrefix(kLiteralIncrementalIndexOpcode); expected_.AppendUint32(key_index); ExpectString(&expected_, value); } void ExpectIndexedLiteral(absl::string_view name, absl::string_view value) { expected_.AppendPrefix(kLiteralIncrementalIndexOpcode); expected_.AppendUint32(0); ExpectString(&expected_, name); ExpectString(&expected_, value); } void ExpectNonIndexedLiteral(absl::string_view name, absl::string_view value) { expected_.AppendPrefix(kLiteralNoIndexOpcode); expected_.AppendUint32(0); ExpectString(&expected_, name); ExpectString(&expected_, value); } void ExpectNonIndexedLiteralWithNameIndex(size_t key_index, absl::string_view value) { expected_.AppendPrefix(kLiteralNoIndexOpcode); expected_.AppendUint32(key_index); ExpectString(&expected_, value); } void ExpectString(HpackOutputStream* stream, absl::string_view str) { size_t encoded_size = peer_.compression_enabled() ? http2::HuffmanSize(str) : str.size(); if (encoded_size < str.size()) { expected_.AppendPrefix(kStringLiteralHuffmanEncoded); expected_.AppendUint32(encoded_size); http2::HuffmanEncodeFast(str, encoded_size, stream->MutableString()); } else { expected_.AppendPrefix(kStringLiteralIdentityEncoded); expected_.AppendUint32(str.size()); expected_.AppendBytes(str); } } void ExpectHeaderTableSizeUpdate(uint32_t size) { expected_.AppendPrefix(kHeaderTableSizeUpdateOpcode); expected_.AppendUint32(size); } Representations MakeRepresentations(const Http2HeaderBlock& header_set) { Representations r; for (const auto& header : header_set) { r.push_back(header); } return r; } void CompareWithExpectedEncoding(const Http2HeaderBlock& header_set) { std::string actual_out; std::string expected_out = expected_.TakeString(); switch (strategy_) { case kDefault: actual_out = test::HpackEncoderPeer::EncodeHeaderBlock(&encoder_, header_set); break; case kIncremental: EXPECT_TRUE(test::HpackEncoderPeer::EncodeIncremental( &encoder_, header_set, &actual_out)); break; case kRepresentations: EXPECT_TRUE(test::HpackEncoderPeer::EncodeRepresentations( &encoder_, MakeRepresentations(header_set), &actual_out)); break; } EXPECT_EQ(expected_out, actual_out); } void CompareWithExpectedEncoding(const Representations& representations) { std::string actual_out; std::string expected_out = expected_.TakeString(); EXPECT_TRUE(test::HpackEncoderPeer::EncodeRepresentations( &encoder_, representations, &actual_out)); EXPECT_EQ(expected_out, actual_out); } size_t DynamicIndexToWireIndex(size_t index) { return dynamic_table_insertions_ - index + kStaticTableSize; } HpackEncoder encoder_; test::HpackEncoderPeer peer_; const size_t kInitialDynamicTableSize = 4 * (10 + 32); const HpackEntry* static_; const HpackEntry* key_1_; const HpackEntry* key_2_; const HpackEntry* cookie_a_; const HpackEntry* cookie_c_; size_t key_1_index_; size_t key_2_index_; size_t cookie_a_index_; size_t cookie_c_index_; size_t dynamic_table_insertions_; quiche::QuicheSimpleArena headers_storage_; std::vector<std::pair<absl::string_view, absl::string_view>> headers_observed_; HpackOutputStream expected_; const EncodeStrategy strategy_; }; using HpackEncoderTestWithDefaultStrategy = HpackEncoderTest; INSTANTIATE_TEST_SUITE_P(HpackEncoderTests, HpackEncoderTestWithDefaultStrategy, ::testing::Values(kDefault)); TEST_P(HpackEncoderTestWithDefaultStrategy, EncodeRepresentations) { EXPECT_EQ(kInitialDynamicTableSize, encoder_.GetDynamicTableSize()); encoder_.SetHeaderListener( [this](absl::string_view name, absl::string_view value) { this->SaveHeaders(name, value); }); const std::vector<std::pair<absl::string_view, absl::string_view>> header_list = {{"cookie", "val1; val2;val3"}, {":path", "/home"}, {"accept", "text/html, text/plain,application/xml"}, {"cookie", "val4"}, {"withnul", absl::string_view("one\0two", 7)}}; ExpectNonIndexedLiteralWithNameIndex(peer_.table()->GetByName(":path"), "/home"); ExpectIndexedLiteral(peer_.table()->GetByName("cookie"), "val1"); ExpectIndexedLiteral(peer_.table()->GetByName("cookie"), "val2"); ExpectIndexedLiteral(peer_.table()->GetByName("cookie"), "val3"); ExpectIndexedLiteral(peer_.table()->GetByName("accept"), "text/html, text/plain,application/xml"); ExpectIndexedLiteral(peer_.table()->GetByName("cookie"), "val4"); ExpectIndexedLiteral("withnul", absl::string_view("one\0two", 7)); CompareWithExpectedEncoding(header_list); EXPECT_THAT( headers_observed_, ElementsAre(Pair(":path", "/home"), Pair("cookie", "val1"), Pair("cookie", "val2"), Pair("cookie", "val3"), Pair("accept", "text/html, text/plain,application/xml"), Pair("cookie", "val4"), Pair("withnul", absl::string_view("one\0two", 7)))); EXPECT_GE(kInitialDynamicTableSize, encoder_.GetDynamicTableSize()); } TEST_P(HpackEncoderTestWithDefaultStrategy, WithoutCookieCrumbling) { EXPECT_EQ(kInitialDynamicTableSize, encoder_.GetDynamicTableSize()); encoder_.SetHeaderListener( [this](absl::string_view name, absl::string_view value) { this->SaveHeaders(name, value); }); encoder_.DisableCookieCrumbling(); const std::vector<std::pair<absl::string_view, absl::string_view>> header_list = {{"cookie", "val1; val2;val3"}, {":path", "/home"}, {"accept", "text/html, text/plain,application/xml"}, {"cookie", "val4"}, {"withnul", absl::string_view("one\0two", 7)}}; ExpectNonIndexedLiteralWithNameIndex(peer_.table()->GetByName(":path"), "/home"); ExpectIndexedLiteral(peer_.table()->GetByName("cookie"), "val1; val2;val3"); ExpectIndexedLiteral(peer_.table()->GetByName("accept"), "text/html, text/plain,application/xml"); ExpectIndexedLiteral(peer_.table()->GetByName("cookie"), "val4"); ExpectIndexedLiteral("withnul", absl::string_view("one\0two", 7)); CompareWithExpectedEncoding(header_list); EXPECT_THAT( headers_observed_, ElementsAre(Pair(":path", "/home"), Pair("cookie", "val1; val2;val3"), Pair("accept", "text/html, text/plain,application/xml"), Pair("cookie", "val4"), Pair("withnul", absl::string_view("one\0two", 7)))); EXPECT_GE(kInitialDynamicTableSize, encoder_.GetDynamicTableSize()); } TEST_P(HpackEncoderTestWithDefaultStrategy, DynamicTableGrows) { EXPECT_EQ(kInitialDynamicTableSize, encoder_.GetDynamicTableSize()); peer_.table()->SetMaxSize(4096); encoder_.SetHeaderListener( [this](absl::string_view name, absl::string_view value) { this->SaveHeaders(name, value); }); const std::vector<std::pair<absl::string_view, absl::string_view>> header_list = {{"cookie", "val1; val2;val3"}, {":path", "/home"}, {"accept", "text/html, text/plain,application/xml"}, {"cookie", "val4"}, {"withnul", absl::string_view("one\0two", 7)}}; std::string out; EXPECT_TRUE(test::HpackEncoderPeer::EncodeRepresentations(&encoder_, header_list, &out)); EXPECT_FALSE(out.empty()); EXPECT_GT(encoder_.GetDynamicTableSize(), kInitialDynamicTableSize); } INSTANTIATE_TEST_SUITE_P(HpackEncoderTests, HpackEncoderTest, ::testing::Values(kDefault, kIncremental, kRepresentations)); TEST_P(HpackEncoderTest, SingleDynamicIndex) { encoder_.SetHeaderListener( [this](absl::string_view name, absl::string_view value) { this->SaveHeaders(name, value); }); ExpectIndex(DynamicIndexToWireIndex(key_2_index_)); Http2HeaderBlock headers; headers[key_2_->name()] = key_2_->value(); CompareWithExpectedEncoding(headers); EXPECT_THAT(headers_observed_, ElementsAre(Pair(key_2_->name(), key_2_->value()))); } TEST_P(HpackEncoderTest, SingleStaticIndex) { ExpectIndex(kStaticEntryIndex); Http2HeaderBlock headers; headers[static_->name()] = static_->value(); CompareWithExpectedEncoding(headers); } TEST_P(HpackEncoderTest, SingleStaticIndexTooLarge) { peer_.table()->SetMaxSize(1); ExpectIndex(kStaticEntryIndex); Http2HeaderBlock headers; headers[static_->name()] = static_->value(); CompareWithExpectedEncoding(headers); EXPECT_EQ(0u, peer_.table_peer().dynamic_entries()->size()); } TEST_P(HpackEncoderTest, SingleLiteralWithIndexName) { ExpectIndexedLiteral(DynamicIndexToWireIndex(key_2_index_), "value3"); Http2HeaderBlock headers; headers[key_2_->name()] = "value3"; CompareWithExpectedEncoding(headers); HpackEntry* new_entry = peer_.table_peer().dynamic_entries()->front().get(); EXPECT_EQ(new_entry->name(), key_2_->name()); EXPECT_EQ(new_entry->value(), "value3"); } TEST_P(HpackEncoderTest, SingleLiteralWithLiteralName) { ExpectIndexedLiteral("key3", "value3"); Http2HeaderBlock headers; headers["key3"] = "value3"; CompareWithExpectedEncoding(headers); HpackEntry* new_entry = peer_.table_peer().dynamic_entries()->front().get(); EXPECT_EQ(new_entry->name(), "key3"); EXPECT_EQ(new_entry->value(), "value3"); } TEST_P(HpackEncoderTest, SingleLiteralTooLarge) { peer_.table()->SetMaxSize(1); ExpectIndexedLiteral("key3", "value3"); Http2HeaderBlock headers; headers["key3"] = "value3"; CompareWithExpectedEncoding(headers); EXPECT_EQ(0u, peer_.table_peer().dynamic_entries()->size()); } TEST_P(HpackEncoderTest, EmitThanEvict) { ExpectIndex(DynamicIndexToWireIndex(key_1_index_)); ExpectIndexedLiteral("key3", "value3"); Http2HeaderBlock headers; headers[key_1_->name()] = key_1_->value(); headers["key3"] = "value3"; CompareWithExpectedEncoding(headers); } TEST_P(HpackEncoderTest, CookieHeaderIsCrumbled) { ExpectIndex(DynamicIndexToWireIndex(cookie_a_index_)); ExpectIndex(DynamicIndexToWireIndex(cookie_c_index_)); ExpectIndexedLiteral(peer_.table()->GetByName("cookie"), "e=ff"); Http2HeaderBlock headers; headers["cookie"] = "a=bb; c=dd; e=ff"; CompareWithExpectedEncoding(headers); } TEST_P(HpackEncoderTest, CookieHeaderIsNotCrumbled) { encoder_.DisableCookieCrumbling(); ExpectIndexedLiteral(peer_.table()->GetByName("cookie"), "a=bb; c=dd; e=ff"); Http2HeaderBlock headers; headers["cookie"] = "a=bb; c=dd; e=ff"; CompareWithExpectedEncoding(headers); } TEST_P(HpackEncoderTest, MultiValuedHeadersNotCrumbled) { ExpectIndexedLiteral("foo", "bar, baz"); Http2HeaderBlock headers; headers["foo"] = "bar, baz"; CompareWithExpectedEncoding(headers); } TEST_P(HpackEncoderTest, StringsDynamicallySelectHuffmanCoding) { peer_.EmitString("feedbeef"); expected_.AppendPrefix(kStringLiteralHuffmanEncoded); expected_.AppendUint32(6); expected_.AppendBytes("\x94\xA5\x92\x32\x96_"); peer_.EmitString("@@@@@@"); expected_.AppendPrefix(kStringLiteralIdentityEncoded); expected_.AppendUint32(6); expected_.AppendBytes("@@@@@@"); std::string actual_out; std::string expected_out = expected_.TakeString(); peer_.TakeString(&actual_out); EXPECT_EQ(expected_out, actual_out); } TEST_P(HpackEncoderTest, EncodingWithoutCompression) { encoder_.SetHeaderListener( [this](absl::string_view name, absl::string_view value) { this->SaveHeaders(name, value); }); encoder_.DisableCompression(); ExpectNonIndexedLiteral(":path", "/index.html"); ExpectNonIndexedLiteral("cookie", "foo=bar"); ExpectNonIndexedLiteral("cookie", "baz=bing"); if (strategy_ == kRepresentations) { ExpectNonIndexedLiteral("hello", std::string("goodbye\0aloha", 13)); } else { ExpectNonIndexedLiteral("hello", "goodbye"); ExpectNonIndexedLiteral("hello", "aloha"); } ExpectNonIndexedLiteral("multivalue", "value1, value2"); Http2HeaderBlock headers; headers[":path"] = "/index.html"; headers["cookie"] = "foo=bar; baz=bing"; headers["hello"] = "goodbye"; headers.AppendValueOrAddHeader("hello", "aloha"); headers["multivalue"] = "value1, value2"; CompareWithExpectedEncoding(headers); if (strategy_ == kRepresentations) { EXPECT_THAT( headers_observed_, ElementsAre(Pair(":path", "/index.html"), Pair("cookie", "foo=bar"), Pair("cookie", "baz=bing"), Pair("hello", absl::string_view("goodbye\0aloha", 13)), Pair("multivalue", "value1, value2"))); } else { EXPECT_THAT( headers_observed_, ElementsAre(Pair(":path", "/index.html"), Pair("cookie", "foo=bar"), Pair("cookie", "baz=bing"), Pair("hello", "goodbye"), Pair("hello", "aloha"), Pair("multivalue", "value1, value2"))); } EXPECT_EQ(kInitialDynamicTableSize, encoder_.GetDynamicTableSize()); } TEST_P(HpackEncoderTest, MultipleEncodingPasses) { encoder_.SetHeaderListener( [this](absl::string_view name, absl::string_view value) { this->SaveHeaders(name, value); }); { Http2HeaderBlock headers; headers["key1"] = "value1"; headers["cookie"] = "a=bb"; ExpectIndex(DynamicIndexToWireIndex(key_1_index_)); ExpectIndex(DynamicIndexToWireIndex(cookie_a_index_)); CompareWithExpectedEncoding(headers); } { Http2HeaderBlock headers; headers["key2"] = "value2"; headers["cookie"] = "c=dd; e=ff"; ExpectIndex(DynamicIndexToWireIndex(key_2_index_)); ExpectIndex(DynamicIndexToWireIndex(cookie_c_index_)); ExpectIndexedLiteral(peer_.table()->GetByName("cookie"), "e=ff"); dynamic_table_insertions_++; CompareWithExpectedEncoding(headers); } { Http2HeaderBlock headers; headers["key2"] = "value2"; headers["cookie"] = "a=bb; b=cc; c=dd"; EXPECT_EQ(65u, DynamicIndexToWireIndex(key_2_index_)); ExpectIndex(DynamicIndexToWireIndex(key_2_index_)); EXPECT_EQ(64u, DynamicIndexToWireIndex(cookie_a_index_)); ExpectIndex(DynamicIndexToWireIndex(cookie_a_index_)); ExpectIndexedLiteral(peer_.table()->GetByName("cookie"), "b=cc"); dynamic_table_insertions_++; ExpectIndex(DynamicIndexToWireIndex(cookie_c_index_)); CompareWithExpectedEncoding(headers); } EXPECT_THAT(headers_observed_, ElementsAre(Pair("key1", "value1"), Pair("cookie", "a=bb"), Pair("key2", "value2"), Pair("cookie", "c=dd"), Pair("cookie", "e=ff"), Pair("key2", "value2"), Pair("cookie", "a=bb"), Pair("cookie", "b=cc"), Pair("cookie", "c=dd"))); } TEST_P(HpackEncoderTest, PseudoHeadersFirst) { Http2HeaderBlock headers; headers[":path"] = "/spam/eggs.html"; headers[":authority"] = "www.example.com"; headers["-foo"] = "bar"; headers["foo"] = "bar"; headers["cookie"] = "c=dd"; ExpectNonIndexedLiteralWithNameIndex(peer_.table()->GetByName(":path"), "/spam/eggs.html"); ExpectIndexedLiteral(peer_.table()->GetByName(":authority"), "www.example.com"); ExpectIndexedLiteral("-foo", "bar"); ExpectIndexedLiteral("foo", "bar"); ExpectIndexedLiteral(peer_.table()->GetByName("cookie"), "c=dd"); CompareWithExpectedEncoding(headers); } TEST_P(HpackEncoderTest, CookieToCrumbs) { test::HpackEncoderPeer peer(nullptr); std::vector<absl::string_view> out; peer.CookieToCrumbs(" foo=1;bar=2 ; bar=3; bing=4; ", &out); EXPECT_THAT(out, ElementsAre("foo=1", "bar=2 ", "bar=3", " bing=4", "")); peer.CookieToCrumbs(";;foo = bar ;; ;baz =bing", &out); EXPECT_THAT(out, ElementsAre("", "", "foo = bar ", "", "", "baz =bing")); peer.CookieToCrumbs("baz=bing; foo=bar; baz=bing", &out); EXPECT_THAT(out, ElementsAre("baz=bing", "foo=bar", "baz=bing")); peer.CookieToCrumbs("baz=bing", &out); EXPECT_THAT(out, ElementsAre("baz=bing")); peer.CookieToCrumbs("", &out); EXPECT_THAT(out, ElementsAre("")); peer.CookieToCrumbs("foo;bar; baz;baz;bing;", &out); EXPECT_THAT(out, ElementsAre("foo", "bar", "baz", "baz", "bing", "")); peer.CookieToCrumbs(" \t foo=1;bar=2 ; bar=3;\t ", &out); EXPECT_THAT(out, ElementsAre("foo=1", "bar=2 ", "bar=3", "")); peer.CookieToCrumbs(" \t foo=1;bar=2 ; bar=3 \t ", &out); EXPECT_THAT(out, ElementsAre("foo=1", "bar=2 ", "bar=3")); } TEST_P(HpackEncoderTest, DecomposeRepresentation) { test::HpackEncoderPeer peer(nullptr); std::vector<absl::string_view> out; peer.DecomposeRepresentation("", &out); EXPECT_THAT(out, ElementsAre("")); peer.DecomposeRepresentation("foobar", &out); EXPECT_THAT(out, ElementsAre("foobar")); peer.DecomposeRepresentation(absl::string_view("foo\0bar", 7), &out); EXPECT_THAT(out, ElementsAre("foo", "bar")); peer.DecomposeRepresentation(absl::string_view("\0foo\0bar", 8), &out); EXPECT_THAT(out, ElementsAre("", "foo", "bar")); peer.DecomposeRepresentation(absl::string_view("foo\0bar\0", 8), &out); EXPECT_THAT(out, ElementsAre("foo", "bar", "")); peer.DecomposeRepresentation(absl::string_view("\0foo\0bar\0", 9), &out); EXPECT_THAT(out, ElementsAre("", "foo", "bar", "")); } TEST_P(HpackEncoderTest, CrumbleNullByteDelimitedValue) { if (strategy_ == kRepresentations) { return; } Http2HeaderBlock headers; headers["spam"] = std::string("foo\0bar", 7); ExpectIndexedLiteral("spam", "foo"); expected_.AppendPrefix(kLiteralIncrementalIndexOpcode); expected_.AppendUint32(62); expected_.AppendPrefix(kStringLiteralIdentityEncoded); expected_.AppendUint32(3); expected_.AppendBytes("bar"); CompareWithExpectedEncoding(headers); } TEST_P(HpackEncoderTest, HeaderTableSizeUpdate) { encoder_.ApplyHeaderTableSizeSetting(1024); ExpectHeaderTableSizeUpdate(1024); ExpectIndexedLiteral("key3", "value3"); Http2HeaderBlock headers; headers["key3"] = "value3"; CompareWithExpectedEncoding(headers); HpackEntry* new_entry = peer_.table_peer().dynamic_entries()->front().get(); EXPECT_EQ(new_entry->name(), "key3"); EXPECT_EQ(new_entry->value(), "value3"); } TEST_P(HpackEncoderTest, HeaderTableSizeUpdateWithMin) { const size_t starting_size = peer_.table()->settings_size_bound(); encoder_.ApplyHeaderTableSizeSetting(starting_size - 2); encoder_.ApplyHeaderTableSizeSetting(starting_size - 1); ExpectHeaderTableSizeUpdate(starting_size - 2); ExpectHeaderTableSizeUpdate(starting_size - 1); ExpectIndexedLiteral("key3", "value3"); Http2HeaderBlock headers; headers["key3"] = "value3"; CompareWithExpectedEncoding(headers); HpackEntry* new_entry = peer_.table_peer().dynamic_entries()->front().get(); EXPECT_EQ(new_entry->name(), "key3"); EXPECT_EQ(new_entry->value(), "value3"); } TEST_P(HpackEncoderTest, HeaderTableSizeUpdateWithExistingSize) { encoder_.ApplyHeaderTableSizeSetting(peer_.table()->settings_size_bound()); ExpectIndexedLiteral("key3", "value3"); Http2HeaderBlock headers; headers["key3"] = "value3"; CompareWithExpectedEncoding(headers); HpackEntry* new_entry = peer_.table_peer().dynamic_entries()->front().get(); EXPECT_EQ(new_entry->name(), "key3"); EXPECT_EQ(new_entry->value(), "value3"); } TEST_P(HpackEncoderTest, HeaderTableSizeUpdatesWithGreaterSize) { const size_t starting_size = peer_.table()->settings_size_bound(); encoder_.ApplyHeaderTableSizeSetting(starting_size + 1); encoder_.ApplyHeaderTableSizeSetting(starting_size + 2); ExpectHeaderTableSizeUpdate(starting_size + 2); ExpectIndexedLiteral("key3", "value3"); Http2HeaderBlock headers; headers["key3"] = "value3"; CompareWithExpectedEncoding(headers); HpackEntry* new_entry = peer_.table_peer().dynamic_entries()->front().get(); EXPECT_EQ(new_entry->name(), "key3"); EXPECT_EQ(new_entry->value(), "value3"); } } }
392
cpp
google/quiche
hpack_header_table
quiche/http2/hpack/hpack_header_table.cc
quiche/http2/hpack/hpack_header_table_test.cc
#ifndef QUICHE_SPDY_CORE_HPACK_HPACK_HEADER_TABLE_H_ #define QUICHE_SPDY_CORE_HPACK_HPACK_HEADER_TABLE_H_ #include <cstddef> #include <memory> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/quiche_circular_deque.h" #include "quiche/spdy/core/hpack/hpack_entry.h" namespace spdy { namespace test { class HpackHeaderTablePeer; } inline constexpr size_t kHpackEntryNotFound = 0; class QUICHE_EXPORT HpackHeaderTable { public: friend class test::HpackHeaderTablePeer; using StaticEntryTable = std::vector<HpackEntry>; using DynamicEntryTable = quiche::QuicheCircularDeque<std::unique_ptr<HpackEntry>>; using NameValueToEntryMap = absl::flat_hash_map<HpackLookupEntry, size_t>; using NameToEntryMap = absl::flat_hash_map<absl::string_view, size_t>; HpackHeaderTable(); HpackHeaderTable(const HpackHeaderTable&) = delete; HpackHeaderTable& operator=(const HpackHeaderTable&) = delete; ~HpackHeaderTable(); size_t settings_size_bound() const { return settings_size_bound_; } size_t size() const { return size_; } size_t max_size() const { return max_size_; } size_t GetByName(absl::string_view name); size_t GetByNameAndValue(absl::string_view name, absl::string_view value); void SetMaxSize(size_t max_size); void SetSettingsHeaderTableSize(size_t settings_size); void EvictionSet(absl::string_view name, absl::string_view value, DynamicEntryTable::iterator* begin_out, DynamicEntryTable::iterator* end_out); const HpackEntry* TryAddEntry(absl::string_view name, absl::string_view value); private: size_t EvictionCountForEntry(absl::string_view name, absl::string_view value) const; size_t EvictionCountToReclaim(size_t reclaim_size) const; void Evict(size_t count); const StaticEntryTable& static_entries_; DynamicEntryTable dynamic_entries_; const NameValueToEntryMap& static_index_; const NameToEntryMap& static_name_index_; NameValueToEntryMap dynamic_index_; NameToEntryMap dynamic_name_index_; size_t settings_size_bound_; size_t size_; size_t max_size_; size_t dynamic_table_insertions_; }; } #endif #include "quiche/spdy/core/hpack/hpack_header_table.h" #include <algorithm> #include <cstddef> #include <memory> #include <string> #include <utility> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/spdy/core/hpack/hpack_constants.h" #include "quiche/spdy/core/hpack/hpack_entry.h" #include "quiche/spdy/core/hpack/hpack_static_table.h" namespace spdy { HpackHeaderTable::HpackHeaderTable() : static_entries_(ObtainHpackStaticTable().GetStaticEntries()), static_index_(ObtainHpackStaticTable().GetStaticIndex()), static_name_index_(ObtainHpackStaticTable().GetStaticNameIndex()), settings_size_bound_(kDefaultHeaderTableSizeSetting), size_(0), max_size_(kDefaultHeaderTableSizeSetting), dynamic_table_insertions_(0) {} HpackHeaderTable::~HpackHeaderTable() = default; size_t HpackHeaderTable::GetByName(absl::string_view name) { { auto it = static_name_index_.find(name); if (it != static_name_index_.end()) { return 1 + it->second; } } { NameToEntryMap::const_iterator it = dynamic_name_index_.find(name); if (it != dynamic_name_index_.end()) { return dynamic_table_insertions_ - it->second + kStaticTableSize; } } return kHpackEntryNotFound; } size_t HpackHeaderTable::GetByNameAndValue(absl::string_view name, absl::string_view value) { HpackLookupEntry query{name, value}; { auto it = static_index_.find(query); if (it != static_index_.end()) { return 1 + it->second; } } { auto it = dynamic_index_.find(query); if (it != dynamic_index_.end()) { return dynamic_table_insertions_ - it->second + kStaticTableSize; } } return kHpackEntryNotFound; } void HpackHeaderTable::SetMaxSize(size_t max_size) { QUICHE_CHECK_LE(max_size, settings_size_bound_); max_size_ = max_size; if (size_ > max_size_) { Evict(EvictionCountToReclaim(size_ - max_size_)); QUICHE_CHECK_LE(size_, max_size_); } } void HpackHeaderTable::SetSettingsHeaderTableSize(size_t settings_size) { settings_size_bound_ = settings_size; SetMaxSize(settings_size_bound_); } void HpackHeaderTable::EvictionSet(absl::string_view name, absl::string_view value, DynamicEntryTable::iterator* begin_out, DynamicEntryTable::iterator* end_out) { size_t eviction_count = EvictionCountForEntry(name, value); *begin_out = dynamic_entries_.end() - eviction_count; *end_out = dynamic_entries_.end(); } size_t HpackHeaderTable::EvictionCountForEntry(absl::string_view name, absl::string_view value) const { size_t available_size = max_size_ - size_; size_t entry_size = HpackEntry::Size(name, value); if (entry_size <= available_size) { return 0; } return EvictionCountToReclaim(entry_size - available_size); } size_t HpackHeaderTable::EvictionCountToReclaim(size_t reclaim_size) const { size_t count = 0; for (auto it = dynamic_entries_.rbegin(); it != dynamic_entries_.rend() && reclaim_size != 0; ++it, ++count) { reclaim_size -= std::min(reclaim_size, (*it)->Size()); } return count; } void HpackHeaderTable::Evict(size_t count) { for (size_t i = 0; i != count; ++i) { QUICHE_CHECK(!dynamic_entries_.empty()); HpackEntry* entry = dynamic_entries_.back().get(); const size_t index = dynamic_table_insertions_ - dynamic_entries_.size(); size_ -= entry->Size(); auto it = dynamic_index_.find({entry->name(), entry->value()}); QUICHE_DCHECK(it != dynamic_index_.end()); if (it->second == index) { dynamic_index_.erase(it); } auto name_it = dynamic_name_index_.find(entry->name()); QUICHE_DCHECK(name_it != dynamic_name_index_.end()); if (name_it->second == index) { dynamic_name_index_.erase(name_it); } dynamic_entries_.pop_back(); } } const HpackEntry* HpackHeaderTable::TryAddEntry(absl::string_view name, absl::string_view value) { Evict(EvictionCountForEntry(name, value)); size_t entry_size = HpackEntry::Size(name, value); if (entry_size > (max_size_ - size_)) { QUICHE_DCHECK(dynamic_entries_.empty()); QUICHE_DCHECK_EQ(0u, size_); return nullptr; } const size_t index = dynamic_table_insertions_; dynamic_entries_.push_front( std::make_unique<HpackEntry>(std::string(name), std::string(value))); HpackEntry* new_entry = dynamic_entries_.front().get(); auto index_result = dynamic_index_.insert(std::make_pair( HpackLookupEntry{new_entry->name(), new_entry->value()}, index)); if (!index_result.second) { QUICHE_DVLOG(1) << "Found existing entry at: " << index_result.first->second << " replacing with: " << new_entry->GetDebugString() << " at: " << index; QUICHE_DCHECK_GT(index, index_result.first->second); dynamic_index_.erase(index_result.first); auto insert_result = dynamic_index_.insert(std::make_pair( HpackLookupEntry{new_entry->name(), new_entry->value()}, index)); QUICHE_CHECK(insert_result.second); } auto name_result = dynamic_name_index_.insert(std::make_pair(new_entry->name(), index)); if (!name_result.second) { QUICHE_DVLOG(1) << "Found existing entry at: " << name_result.first->second << " replacing with: " << new_entry->GetDebugString() << " at: " << index; QUICHE_DCHECK_GT(index, name_result.first->second); dynamic_name_index_.erase(name_result.first); auto insert_result = dynamic_name_index_.insert(std::make_pair(new_entry->name(), index)); QUICHE_CHECK(insert_result.second); } size_ += entry_size; ++dynamic_table_insertions_; return dynamic_entries_.front().get(); } }
#include "quiche/spdy/core/hpack/hpack_header_table.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <string> #include <vector> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/spdy/core/hpack/hpack_constants.h" #include "quiche/spdy/core/hpack/hpack_entry.h" #include "quiche/spdy/core/hpack/hpack_static_table.h" namespace spdy { using std::distance; namespace test { class HpackHeaderTablePeer { public: explicit HpackHeaderTablePeer(HpackHeaderTable* table) : table_(table) {} const HpackHeaderTable::DynamicEntryTable& dynamic_entries() { return table_->dynamic_entries_; } const HpackHeaderTable::StaticEntryTable& static_entries() { return table_->static_entries_; } const HpackEntry* GetFirstStaticEntry() { return &table_->static_entries_.front(); } const HpackEntry* GetLastStaticEntry() { return &table_->static_entries_.back(); } std::vector<HpackEntry*> EvictionSet(absl::string_view name, absl::string_view value) { HpackHeaderTable::DynamicEntryTable::iterator begin, end; table_->EvictionSet(name, value, &begin, &end); std::vector<HpackEntry*> result; for (; begin != end; ++begin) { result.push_back(begin->get()); } return result; } size_t dynamic_table_insertions() { return table_->dynamic_table_insertions_; } size_t EvictionCountForEntry(absl::string_view name, absl::string_view value) { return table_->EvictionCountForEntry(name, value); } size_t EvictionCountToReclaim(size_t reclaim_size) { return table_->EvictionCountToReclaim(reclaim_size); } void Evict(size_t count) { return table_->Evict(count); } private: HpackHeaderTable* table_; }; } namespace { class HpackHeaderTableTest : public quiche::test::QuicheTest { protected: typedef std::vector<HpackEntry> HpackEntryVector; HpackHeaderTableTest() : table_(), peer_(&table_) {} static HpackEntry MakeEntryOfSize(uint32_t size) { EXPECT_GE(size, kHpackEntrySizeOverhead); std::string name((size - kHpackEntrySizeOverhead) / 2, 'n'); std::string value(size - kHpackEntrySizeOverhead - name.size(), 'v'); HpackEntry entry(name, value); EXPECT_EQ(size, entry.Size()); return entry; } static HpackEntryVector MakeEntriesOfTotalSize(uint32_t total_size) { EXPECT_GE(total_size, kHpackEntrySizeOverhead); uint32_t entry_size = kHpackEntrySizeOverhead; uint32_t remaining_size = total_size; HpackEntryVector entries; while (remaining_size > 0) { EXPECT_LE(entry_size, remaining_size); entries.push_back(MakeEntryOfSize(entry_size)); remaining_size -= entry_size; entry_size = std::min(remaining_size, entry_size + 32); } return entries; } void AddEntriesExpectNoEviction(const HpackEntryVector& entries) { for (auto it = entries.begin(); it != entries.end(); ++it) { HpackHeaderTable::DynamicEntryTable::iterator begin, end; table_.EvictionSet(it->name(), it->value(), &begin, &end); EXPECT_EQ(0, distance(begin, end)); const HpackEntry* entry = table_.TryAddEntry(it->name(), it->value()); EXPECT_NE(entry, static_cast<HpackEntry*>(nullptr)); } } HpackHeaderTable table_; test::HpackHeaderTablePeer peer_; }; TEST_F(HpackHeaderTableTest, StaticTableInitialization) { EXPECT_EQ(0u, table_.size()); EXPECT_EQ(kDefaultHeaderTableSizeSetting, table_.max_size()); EXPECT_EQ(kDefaultHeaderTableSizeSetting, table_.settings_size_bound()); EXPECT_EQ(0u, peer_.dynamic_entries().size()); EXPECT_EQ(0u, peer_.dynamic_table_insertions()); const HpackHeaderTable::StaticEntryTable& static_entries = peer_.static_entries(); EXPECT_EQ(kStaticTableSize, static_entries.size()); size_t index = 1; for (const HpackEntry& entry : static_entries) { EXPECT_EQ(index, table_.GetByNameAndValue(entry.name(), entry.value())); index++; } } TEST_F(HpackHeaderTableTest, BasicDynamicEntryInsertionAndEviction) { EXPECT_EQ(kStaticTableSize, peer_.static_entries().size()); const HpackEntry* first_static_entry = peer_.GetFirstStaticEntry(); const HpackEntry* last_static_entry = peer_.GetLastStaticEntry(); const HpackEntry* entry = table_.TryAddEntry("header-key", "Header Value"); EXPECT_EQ("header-key", entry->name()); EXPECT_EQ("Header Value", entry->value()); EXPECT_EQ(entry->Size(), table_.size()); EXPECT_EQ(1u, peer_.dynamic_entries().size()); EXPECT_EQ(kStaticTableSize, peer_.static_entries().size()); EXPECT_EQ(62u, table_.GetByNameAndValue("header-key", "Header Value")); EXPECT_EQ(first_static_entry, peer_.GetFirstStaticEntry()); EXPECT_EQ(last_static_entry, peer_.GetLastStaticEntry()); peer_.Evict(1); EXPECT_EQ(0u, table_.size()); EXPECT_EQ(0u, peer_.dynamic_entries().size()); EXPECT_EQ(kStaticTableSize, peer_.static_entries().size()); EXPECT_EQ(first_static_entry, peer_.GetFirstStaticEntry()); EXPECT_EQ(last_static_entry, peer_.GetLastStaticEntry()); } TEST_F(HpackHeaderTableTest, EntryIndexing) { const HpackEntry* first_static_entry = peer_.GetFirstStaticEntry(); const HpackEntry* last_static_entry = peer_.GetLastStaticEntry(); EXPECT_EQ(1u, table_.GetByName(first_static_entry->name())); EXPECT_EQ(1u, table_.GetByNameAndValue(first_static_entry->name(), first_static_entry->value())); table_.TryAddEntry(first_static_entry->name(), first_static_entry->value()); table_.TryAddEntry(first_static_entry->name(), "Value Four"); table_.TryAddEntry("key-1", "Value One"); table_.TryAddEntry("key-2", "Value Three"); table_.TryAddEntry("key-1", "Value Two"); table_.TryAddEntry("key-2", "Value Three"); table_.TryAddEntry("key-2", "Value Four"); EXPECT_EQ(1u, table_.GetByNameAndValue(first_static_entry->name(), first_static_entry->value())); EXPECT_EQ(67u, table_.GetByNameAndValue(first_static_entry->name(), "Value Four")); EXPECT_EQ(66u, table_.GetByNameAndValue("key-1", "Value One")); EXPECT_EQ(64u, table_.GetByNameAndValue("key-1", "Value Two")); EXPECT_EQ(63u, table_.GetByNameAndValue("key-2", "Value Three")); EXPECT_EQ(62u, table_.GetByNameAndValue("key-2", "Value Four")); EXPECT_EQ(first_static_entry, peer_.GetFirstStaticEntry()); EXPECT_EQ(last_static_entry, peer_.GetLastStaticEntry()); EXPECT_EQ(64u, table_.GetByName("key-1")); EXPECT_EQ(62u, table_.GetByName("key-2")); EXPECT_EQ(1u, table_.GetByName(first_static_entry->name())); EXPECT_EQ(kHpackEntryNotFound, table_.GetByName("not-present")); EXPECT_EQ(66u, table_.GetByNameAndValue("key-1", "Value One")); EXPECT_EQ(64u, table_.GetByNameAndValue("key-1", "Value Two")); EXPECT_EQ(63u, table_.GetByNameAndValue("key-2", "Value Three")); EXPECT_EQ(62u, table_.GetByNameAndValue("key-2", "Value Four")); EXPECT_EQ(1u, table_.GetByNameAndValue(first_static_entry->name(), first_static_entry->value())); EXPECT_EQ(67u, table_.GetByNameAndValue(first_static_entry->name(), "Value Four")); EXPECT_EQ(kHpackEntryNotFound, table_.GetByNameAndValue("key-1", "Not Present")); EXPECT_EQ(kHpackEntryNotFound, table_.GetByNameAndValue("not-present", "Value One")); peer_.Evict(1); EXPECT_EQ(1u, table_.GetByNameAndValue(first_static_entry->name(), first_static_entry->value())); EXPECT_EQ(67u, table_.GetByNameAndValue(first_static_entry->name(), "Value Four")); peer_.Evict(1); EXPECT_EQ(kHpackEntryNotFound, table_.GetByNameAndValue(first_static_entry->name(), "Value Four")); EXPECT_EQ(first_static_entry, peer_.GetFirstStaticEntry()); EXPECT_EQ(last_static_entry, peer_.GetLastStaticEntry()); } TEST_F(HpackHeaderTableTest, SetSizes) { std::string key = "key", value = "value"; const HpackEntry* entry1 = table_.TryAddEntry(key, value); const HpackEntry* entry2 = table_.TryAddEntry(key, value); const HpackEntry* entry3 = table_.TryAddEntry(key, value); size_t max_size = entry1->Size() + entry2->Size() + entry3->Size(); table_.SetMaxSize(max_size); EXPECT_EQ(3u, peer_.dynamic_entries().size()); max_size = entry1->Size() + entry2->Size() + entry3->Size() - 1; table_.SetMaxSize(max_size); EXPECT_EQ(2u, peer_.dynamic_entries().size()); EXPECT_EQ(kDefaultHeaderTableSizeSetting, table_.settings_size_bound()); table_.SetSettingsHeaderTableSize(kDefaultHeaderTableSizeSetting * 3 + 1); EXPECT_EQ(kDefaultHeaderTableSizeSetting * 3 + 1, table_.max_size()); max_size = entry3->Size() - 1; table_.SetSettingsHeaderTableSize(max_size); EXPECT_EQ(max_size, table_.max_size()); EXPECT_EQ(max_size, table_.settings_size_bound()); EXPECT_EQ(0u, peer_.dynamic_entries().size()); } TEST_F(HpackHeaderTableTest, EvictionCountForEntry) { std::string key = "key", value = "value"; const HpackEntry* entry1 = table_.TryAddEntry(key, value); const HpackEntry* entry2 = table_.TryAddEntry(key, value); size_t entry3_size = HpackEntry::Size(key, value); table_.SetMaxSize(entry1->Size() + entry2->Size() + entry3_size); EXPECT_EQ(0u, peer_.EvictionCountForEntry(key, value)); EXPECT_EQ(1u, peer_.EvictionCountForEntry(key, value + "x")); table_.SetMaxSize(entry1->Size() + entry2->Size()); EXPECT_EQ(1u, peer_.EvictionCountForEntry(key, value)); EXPECT_EQ(2u, peer_.EvictionCountForEntry(key, value + "x")); } TEST_F(HpackHeaderTableTest, EvictionCountToReclaim) { std::string key = "key", value = "value"; const HpackEntry* entry1 = table_.TryAddEntry(key, value); const HpackEntry* entry2 = table_.TryAddEntry(key, value); EXPECT_EQ(1u, peer_.EvictionCountToReclaim(1)); EXPECT_EQ(1u, peer_.EvictionCountToReclaim(entry1->Size())); EXPECT_EQ(2u, peer_.EvictionCountToReclaim(entry1->Size() + 1)); EXPECT_EQ(2u, peer_.EvictionCountToReclaim(entry1->Size() + entry2->Size())); } TEST_F(HpackHeaderTableTest, TryAddEntryBasic) { EXPECT_EQ(0u, table_.size()); EXPECT_EQ(table_.settings_size_bound(), table_.max_size()); HpackEntryVector entries = MakeEntriesOfTotalSize(table_.max_size()); AddEntriesExpectNoEviction(entries); EXPECT_EQ(table_.max_size(), table_.size()); EXPECT_EQ(table_.settings_size_bound(), table_.size()); } TEST_F(HpackHeaderTableTest, SetMaxSize) { HpackEntryVector entries = MakeEntriesOfTotalSize(kDefaultHeaderTableSizeSetting / 2); AddEntriesExpectNoEviction(entries); for (auto it = entries.begin(); it != entries.end(); ++it) { size_t expected_count = distance(it, entries.end()); EXPECT_EQ(expected_count, peer_.dynamic_entries().size()); table_.SetMaxSize(table_.size() + 1); EXPECT_EQ(expected_count, peer_.dynamic_entries().size()); table_.SetMaxSize(table_.size()); EXPECT_EQ(expected_count, peer_.dynamic_entries().size()); --expected_count; table_.SetMaxSize(table_.size() - 1); EXPECT_EQ(expected_count, peer_.dynamic_entries().size()); } EXPECT_EQ(0u, table_.size()); } TEST_F(HpackHeaderTableTest, TryAddEntryEviction) { HpackEntryVector entries = MakeEntriesOfTotalSize(table_.max_size()); AddEntriesExpectNoEviction(entries); const HpackEntry* survivor_entry = peer_.dynamic_entries().front().get(); HpackEntry long_entry = MakeEntryOfSize(table_.max_size() - survivor_entry->Size()); EXPECT_EQ(peer_.dynamic_entries().size() - 1, peer_.EvictionSet(long_entry.name(), long_entry.value()).size()); table_.TryAddEntry(long_entry.name(), long_entry.value()); EXPECT_EQ(2u, peer_.dynamic_entries().size()); EXPECT_EQ(63u, table_.GetByNameAndValue(survivor_entry->name(), survivor_entry->value())); EXPECT_EQ(62u, table_.GetByNameAndValue(long_entry.name(), long_entry.value())); } TEST_F(HpackHeaderTableTest, TryAddTooLargeEntry) { HpackEntryVector entries = MakeEntriesOfTotalSize(table_.max_size()); AddEntriesExpectNoEviction(entries); const HpackEntry long_entry = MakeEntryOfSize(table_.max_size() + 1); EXPECT_EQ(peer_.dynamic_entries().size(), peer_.EvictionSet(long_entry.name(), long_entry.value()).size()); const HpackEntry* new_entry = table_.TryAddEntry(long_entry.name(), long_entry.value()); EXPECT_EQ(new_entry, static_cast<HpackEntry*>(nullptr)); EXPECT_EQ(0u, peer_.dynamic_entries().size()); } } }
393
cpp
google/quiche
hpack_decoder_adapter
quiche/spdy/core/hpack/hpack_decoder_adapter.cc
quiche/spdy/core/hpack/hpack_decoder_adapter_test.cc
#ifndef QUICHE_SPDY_CORE_HPACK_HPACK_DECODER_ADAPTER_H_ #define QUICHE_SPDY_CORE_HPACK_HPACK_DECODER_ADAPTER_H_ #include <stddef.h> #include <string> #include "absl/strings/string_view.h" #include "quiche/http2/hpack/decoder/hpack_decoder.h" #include "quiche/http2/hpack/decoder/hpack_decoder_listener.h" #include "quiche/http2/hpack/decoder/hpack_decoding_error.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/spdy/core/http2_header_block.h" #include "quiche/spdy/core/no_op_headers_handler.h" #include "quiche/spdy/core/spdy_headers_handler_interface.h" namespace spdy { namespace test { class HpackDecoderAdapterPeer; } class QUICHE_EXPORT HpackDecoderAdapter { public: friend test::HpackDecoderAdapterPeer; HpackDecoderAdapter(); HpackDecoderAdapter(const HpackDecoderAdapter&) = delete; HpackDecoderAdapter& operator=(const HpackDecoderAdapter&) = delete; ~HpackDecoderAdapter(); void ApplyHeaderTableSizeSetting(size_t size_setting); size_t GetCurrentHeaderTableSizeSetting() const; void HandleControlFrameHeadersStart(SpdyHeadersHandlerInterface* handler); bool HandleControlFrameHeadersData(const char* headers_data, size_t headers_data_length); bool HandleControlFrameHeadersComplete(); size_t GetDynamicTableSize() const { return hpack_decoder_.GetDynamicTableSize(); } void set_max_decode_buffer_size_bytes(size_t max_decode_buffer_size_bytes); void set_max_header_block_bytes(size_t max_header_block_bytes); http2::HpackDecodingError error() const { return error_; } private: class QUICHE_EXPORT ListenerAdapter : public http2::HpackDecoderListener { public: ListenerAdapter(); ~ListenerAdapter() override; void set_handler(SpdyHeadersHandlerInterface* handler); void OnHeaderListStart() override; void OnHeader(absl::string_view name, absl::string_view value) override; void OnHeaderListEnd() override; void OnHeaderErrorDetected(absl::string_view error_message) override; void AddToTotalHpackBytes(size_t delta) { total_hpack_bytes_ += delta; } size_t total_hpack_bytes() const { return total_hpack_bytes_; } private: NoOpHeadersHandler no_op_handler_; SpdyHeadersHandlerInterface* handler_; size_t total_hpack_bytes_; size_t total_uncompressed_bytes_; }; ListenerAdapter listener_adapter_; http2::HpackDecoder hpack_decoder_; size_t max_decode_buffer_size_bytes_; size_t max_header_block_bytes_; bool header_block_started_; http2::HpackDecodingError error_; }; } #endif #include "quiche/spdy/core/hpack/hpack_decoder_adapter.h" #include <cstddef> #include <string> #include "absl/strings/string_view.h" #include "quiche/http2/decoder/decode_buffer.h" #include "quiche/http2/hpack/decoder/hpack_decoding_error.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/spdy/core/http2_header_block.h" #include "quiche/spdy/core/spdy_headers_handler_interface.h" namespace spdy { namespace { const size_t kMaxDecodeBufferSizeBytes = 32 * 1024; } HpackDecoderAdapter::HpackDecoderAdapter() : hpack_decoder_(&listener_adapter_, kMaxDecodeBufferSizeBytes), max_decode_buffer_size_bytes_(kMaxDecodeBufferSizeBytes), max_header_block_bytes_(0), header_block_started_(false), error_(http2::HpackDecodingError::kOk) {} HpackDecoderAdapter::~HpackDecoderAdapter() = default; void HpackDecoderAdapter::ApplyHeaderTableSizeSetting(size_t size_setting) { QUICHE_DVLOG(2) << "HpackDecoderAdapter::ApplyHeaderTableSizeSetting"; hpack_decoder_.ApplyHeaderTableSizeSetting(size_setting); } size_t HpackDecoderAdapter::GetCurrentHeaderTableSizeSetting() const { return hpack_decoder_.GetCurrentHeaderTableSizeSetting(); } void HpackDecoderAdapter::HandleControlFrameHeadersStart( SpdyHeadersHandlerInterface* handler) { QUICHE_DVLOG(2) << "HpackDecoderAdapter::HandleControlFrameHeadersStart"; QUICHE_DCHECK(!header_block_started_); listener_adapter_.set_handler(handler); } bool HpackDecoderAdapter::HandleControlFrameHeadersData( const char* headers_data, size_t headers_data_length) { QUICHE_DVLOG(2) << "HpackDecoderAdapter::HandleControlFrameHeadersData: len=" << headers_data_length; if (!header_block_started_) { header_block_started_ = true; if (!hpack_decoder_.StartDecodingBlock()) { header_block_started_ = false; error_ = hpack_decoder_.error(); return false; } } if (headers_data_length > 0) { QUICHE_DCHECK_NE(headers_data, nullptr); if (headers_data_length > max_decode_buffer_size_bytes_) { QUICHE_DVLOG(1) << "max_decode_buffer_size_bytes_ < headers_data_length: " << max_decode_buffer_size_bytes_ << " < " << headers_data_length; error_ = http2::HpackDecodingError::kFragmentTooLong; return false; } listener_adapter_.AddToTotalHpackBytes(headers_data_length); if (max_header_block_bytes_ != 0 && listener_adapter_.total_hpack_bytes() > max_header_block_bytes_) { error_ = http2::HpackDecodingError::kCompressedHeaderSizeExceedsLimit; return false; } http2::DecodeBuffer db(headers_data, headers_data_length); bool ok = hpack_decoder_.DecodeFragment(&db); QUICHE_DCHECK(!ok || db.Empty()) << "Remaining=" << db.Remaining(); if (!ok) { error_ = hpack_decoder_.error(); } return ok; } return true; } bool HpackDecoderAdapter::HandleControlFrameHeadersComplete() { QUICHE_DVLOG(2) << "HpackDecoderAdapter::HandleControlFrameHeadersComplete"; if (!hpack_decoder_.EndDecodingBlock()) { QUICHE_DVLOG(3) << "EndDecodingBlock returned false"; error_ = hpack_decoder_.error(); return false; } header_block_started_ = false; return true; } void HpackDecoderAdapter::set_max_decode_buffer_size_bytes( size_t max_decode_buffer_size_bytes) { QUICHE_DVLOG(2) << "HpackDecoderAdapter::set_max_decode_buffer_size_bytes"; max_decode_buffer_size_bytes_ = max_decode_buffer_size_bytes; hpack_decoder_.set_max_string_size_bytes(max_decode_buffer_size_bytes); } void HpackDecoderAdapter::set_max_header_block_bytes( size_t max_header_block_bytes) { max_header_block_bytes_ = max_header_block_bytes; } HpackDecoderAdapter::ListenerAdapter::ListenerAdapter() : no_op_handler_(nullptr), handler_(&no_op_handler_) {} HpackDecoderAdapter::ListenerAdapter::~ListenerAdapter() = default; void HpackDecoderAdapter::ListenerAdapter::set_handler( SpdyHeadersHandlerInterface* handler) { QUICHE_CHECK_NE(handler, nullptr); handler_ = handler; } void HpackDecoderAdapter::ListenerAdapter::OnHeaderListStart() { QUICHE_DVLOG(2) << "HpackDecoderAdapter::ListenerAdapter::OnHeaderListStart"; total_hpack_bytes_ = 0; total_uncompressed_bytes_ = 0; handler_->OnHeaderBlockStart(); } void HpackDecoderAdapter::ListenerAdapter::OnHeader(absl::string_view name, absl::string_view value) { QUICHE_DVLOG(2) << "HpackDecoderAdapter::ListenerAdapter::OnHeader:\n name: " << name << "\n value: " << value; total_uncompressed_bytes_ += name.size() + value.size(); handler_->OnHeader(name, value); } void HpackDecoderAdapter::ListenerAdapter::OnHeaderListEnd() { QUICHE_DVLOG(2) << "HpackDecoderAdapter::ListenerAdapter::OnHeaderListEnd"; handler_->OnHeaderBlockEnd(total_uncompressed_bytes_, total_hpack_bytes_); handler_ = &no_op_handler_; } void HpackDecoderAdapter::ListenerAdapter::OnHeaderErrorDetected( absl::string_view error_message) { QUICHE_VLOG(1) << error_message; } }
#include "quiche/spdy/core/hpack/hpack_decoder_adapter.h" #include <stdint.h> #include <cstddef> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "quiche/http2/hpack/decoder/hpack_decoder.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/test_tools/hpack_block_builder.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_text_utils.h" #include "quiche/spdy/core/hpack/hpack_constants.h" #include "quiche/spdy/core/hpack/hpack_encoder.h" #include "quiche/spdy/core/hpack/hpack_output_stream.h" #include "quiche/spdy/core/http2_header_block.h" #include "quiche/spdy/core/recording_headers_handler.h" using ::http2::HpackEntryType; using ::http2::HpackStringPair; using ::http2::test::HpackBlockBuilder; using ::http2::test::HpackDecoderPeer; using ::testing::ElementsAre; using ::testing::Pair; namespace http2 { namespace test { class HpackDecoderStatePeer { public: static HpackDecoderTables* GetDecoderTables(HpackDecoderState* state) { return &state->decoder_tables_; } }; class HpackDecoderPeer { public: static HpackDecoderState* GetDecoderState(HpackDecoder* decoder) { return &decoder->decoder_state_; } static HpackDecoderTables* GetDecoderTables(HpackDecoder* decoder) { return HpackDecoderStatePeer::GetDecoderTables(GetDecoderState(decoder)); } }; } } namespace spdy { namespace test { class HpackDecoderAdapterPeer { public: explicit HpackDecoderAdapterPeer(HpackDecoderAdapter* decoder) : decoder_(decoder) {} void HandleHeaderRepresentation(const std::string& name, const std::string& value) { decoder_->listener_adapter_.OnHeader(name, value); } http2::HpackDecoderTables* GetDecoderTables() { return HpackDecoderPeer::GetDecoderTables(&decoder_->hpack_decoder_); } const HpackStringPair* GetTableEntry(uint32_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) { return GetDecoderTables()->DynamicTableSizeUpdate(size); } private: HpackDecoderAdapter* decoder_; }; class HpackEncoderPeer { public: static void CookieToCrumbs(const HpackEncoder::Representation& cookie, HpackEncoder::Representations* crumbs_out) { HpackEncoder::CookieToCrumbs(cookie, crumbs_out); } }; namespace { const bool kNoCheckDecodedSize = false; const char* kCookieKey = "cookie"; class HpackDecoderAdapterTest : public quiche::test::QuicheTestWithParam<bool> { protected: HpackDecoderAdapterTest() : decoder_(), decoder_peer_(&decoder_) {} void SetUp() override { randomly_split_input_buffer_ = GetParam(); } void HandleControlFrameHeadersStart() { bytes_passed_in_ = 0; decoder_.HandleControlFrameHeadersStart(&handler_); } bool HandleControlFrameHeadersData(absl::string_view str) { QUICHE_VLOG(3) << "HandleControlFrameHeadersData:\n" << quiche::QuicheTextUtils::HexDump(str); bytes_passed_in_ += str.size(); return decoder_.HandleControlFrameHeadersData(str.data(), str.size()); } bool HandleControlFrameHeadersComplete() { bool rc = decoder_.HandleControlFrameHeadersComplete(); return rc; } bool DecodeHeaderBlock(absl::string_view str, bool check_decoded_size = true) { EXPECT_FALSE(decode_has_failed_); HandleControlFrameHeadersStart(); if (randomly_split_input_buffer_) { do { size_t bytes = str.size(); if (!str.empty()) { bytes = random_.Uniform(str.size()) + 1; } EXPECT_LE(bytes, str.size()); if (!HandleControlFrameHeadersData(str.substr(0, bytes))) { decode_has_failed_ = true; return false; } str.remove_prefix(bytes); } while (!str.empty()); } else if (!HandleControlFrameHeadersData(str)) { decode_has_failed_ = true; return false; } if (!HandleControlFrameHeadersComplete()) { decode_has_failed_ = true; return false; } EXPECT_EQ(handler_.compressed_header_bytes(), bytes_passed_in_); if (check_decoded_size) { EXPECT_EQ(handler_.uncompressed_header_bytes(), SizeOfHeaders(decoded_block())); } return true; } bool EncodeAndDecodeDynamicTableSizeUpdates(size_t first, size_t second) { HpackBlockBuilder hbb; hbb.AppendDynamicTableSizeUpdate(first); if (second != first) { hbb.AppendDynamicTableSizeUpdate(second); } return DecodeHeaderBlock(hbb.buffer()); } const Http2HeaderBlock& decoded_block() const { return handler_.decoded_block(); } static size_t SizeOfHeaders(const Http2HeaderBlock& headers) { size_t size = 0; for (const auto& kv : headers) { if (kv.first == kCookieKey) { HpackEncoder::Representations crumbs; HpackEncoderPeer::CookieToCrumbs(kv, &crumbs); for (const auto& crumb : crumbs) { size += crumb.first.size() + crumb.second.size(); } } else { size += kv.first.size() + kv.second.size(); } } return size; } const Http2HeaderBlock& DecodeBlockExpectingSuccess(absl::string_view str) { EXPECT_TRUE(DecodeHeaderBlock(str)); return decoded_block(); } void expectEntry(size_t index, size_t size, const std::string& name, const std::string& value) { const HpackStringPair* entry = decoder_peer_.GetTableEntry(index); EXPECT_EQ(name, entry->name) << "index " << index; EXPECT_EQ(value, entry->value); EXPECT_EQ(size, entry->size()); } Http2HeaderBlock MakeHeaderBlock( const std::vector<std::pair<std::string, std::string>>& headers) { Http2HeaderBlock result; for (const auto& kv : headers) { result.AppendValueOrAddHeader(kv.first, kv.second); } return result; } http2::test::Http2Random random_; HpackDecoderAdapter decoder_; test::HpackDecoderAdapterPeer decoder_peer_; RecordingHeadersHandler handler_; const Http2HeaderBlock dummy_block_; bool randomly_split_input_buffer_; bool decode_has_failed_ = false; size_t bytes_passed_in_; }; INSTANTIATE_TEST_SUITE_P(NoHandler, HpackDecoderAdapterTest, ::testing::Bool()); INSTANTIATE_TEST_SUITE_P(WithHandler, HpackDecoderAdapterTest, ::testing::Bool()); TEST_P(HpackDecoderAdapterTest, ApplyHeaderTableSizeSetting) { EXPECT_EQ(4096u, decoder_.GetCurrentHeaderTableSizeSetting()); decoder_.ApplyHeaderTableSizeSetting(12 * 1024); EXPECT_EQ(12288u, decoder_.GetCurrentHeaderTableSizeSetting()); } TEST_P(HpackDecoderAdapterTest, AddHeaderDataWithHandleControlFrameHeadersData) { HandleControlFrameHeadersStart(); const size_t kMaxBufferSizeBytes = 50; const std::string a_value = std::string(49, 'x'); decoder_.set_max_decode_buffer_size_bytes(kMaxBufferSizeBytes); HpackBlockBuilder hbb; hbb.AppendLiteralNameAndValue(HpackEntryType::kNeverIndexedLiteralHeader, false, "a", false, a_value); const std::string& s = hbb.buffer(); EXPECT_GT(s.size(), kMaxBufferSizeBytes); EXPECT_TRUE(HandleControlFrameHeadersData(s.substr(0, s.size() / 2))); EXPECT_TRUE(HandleControlFrameHeadersData(s.substr(s.size() / 2))); EXPECT_FALSE(HandleControlFrameHeadersData(s)); Http2HeaderBlock expected_block = MakeHeaderBlock({{"a", a_value}}); EXPECT_EQ(expected_block, decoded_block()); } TEST_P(HpackDecoderAdapterTest, NameTooLong) { const size_t kMaxBufferSizeBytes = 50; const std::string name = std::string(2 * kMaxBufferSizeBytes, 'x'); const std::string value = "abc"; decoder_.set_max_decode_buffer_size_bytes(kMaxBufferSizeBytes); HpackBlockBuilder hbb; hbb.AppendLiteralNameAndValue(HpackEntryType::kNeverIndexedLiteralHeader, false, name, false, value); const size_t fragment_size = (3 * kMaxBufferSizeBytes) / 2; const std::string fragment = hbb.buffer().substr(0, fragment_size); HandleControlFrameHeadersStart(); EXPECT_FALSE(HandleControlFrameHeadersData(fragment)); } TEST_P(HpackDecoderAdapterTest, HeaderTooLongToBuffer) { const std::string name = "some-key"; const std::string value = "some-value"; const size_t kMaxBufferSizeBytes = name.size() + value.size() - 2; decoder_.set_max_decode_buffer_size_bytes(kMaxBufferSizeBytes); HpackBlockBuilder hbb; hbb.AppendLiteralNameAndValue(HpackEntryType::kNeverIndexedLiteralHeader, false, name, false, value); const size_t fragment_size = hbb.size() - 1; const std::string fragment = hbb.buffer().substr(0, fragment_size); HandleControlFrameHeadersStart(); EXPECT_FALSE(HandleControlFrameHeadersData(fragment)); } TEST_P(HpackDecoderAdapterTest, HeaderBlockTooLong) { const std::string name = "some-key"; const std::string value = "some-value"; const size_t kMaxBufferSizeBytes = 1024; HpackBlockBuilder hbb; hbb.AppendLiteralNameAndValue(HpackEntryType::kIndexedLiteralHeader, false, name, false, value); while (hbb.size() < kMaxBufferSizeBytes) { hbb.AppendLiteralNameAndValue(HpackEntryType::kIndexedLiteralHeader, false, "", false, ""); } HandleControlFrameHeadersStart(); EXPECT_TRUE(HandleControlFrameHeadersData(hbb.buffer())); EXPECT_TRUE(HandleControlFrameHeadersComplete()); decoder_.set_max_header_block_bytes(kMaxBufferSizeBytes); HandleControlFrameHeadersStart(); EXPECT_FALSE(HandleControlFrameHeadersData(hbb.buffer())); } TEST_P(HpackDecoderAdapterTest, DecodeWithIncompleteData) { HandleControlFrameHeadersStart(); EXPECT_TRUE(HandleControlFrameHeadersData("\x82\x85\x82")); std::vector<std::pair<std::string, std::string>> expected_headers = { {":method", "GET"}, {":path", "/index.html"}, {":method", "GET"}}; Http2HeaderBlock expected_block1 = MakeHeaderBlock(expected_headers); EXPECT_EQ(expected_block1, decoded_block()); EXPECT_TRUE( HandleControlFrameHeadersData("\x40\x03goo" "\x03gar\xbe\x40\x04spam")); expected_headers.push_back({"goo", "gar"}); expected_headers.push_back({"goo", "gar"}); Http2HeaderBlock expected_block2 = MakeHeaderBlock(expected_headers); EXPECT_EQ(expected_block2, decoded_block()); EXPECT_TRUE(HandleControlFrameHeadersData("\x04gggs")); EXPECT_TRUE(HandleControlFrameHeadersComplete()); expected_headers.push_back({"spam", "gggs"}); Http2HeaderBlock expected_block3 = MakeHeaderBlock(expected_headers); EXPECT_EQ(expected_block3, decoded_block()); } TEST_P(HpackDecoderAdapterTest, HandleHeaderRepresentation) { HandleControlFrameHeadersStart(); HandleControlFrameHeadersData(""); decoder_peer_.HandleHeaderRepresentation("cookie", " part 1"); decoder_peer_.HandleHeaderRepresentation("cookie", "part 2 "); decoder_peer_.HandleHeaderRepresentation("cookie", "part3"); decoder_peer_.HandleHeaderRepresentation("passed-through", std::string("foo\0baz", 7)); decoder_peer_.HandleHeaderRepresentation("joined", "joined"); decoder_peer_.HandleHeaderRepresentation("joineD", "value 1"); decoder_peer_.HandleHeaderRepresentation("joineD", "value 2"); decoder_peer_.HandleHeaderRepresentation("empty", ""); decoder_peer_.HandleHeaderRepresentation("empty-joined", ""); decoder_peer_.HandleHeaderRepresentation("empty-joined", "foo"); decoder_peer_.HandleHeaderRepresentation("empty-joined", ""); decoder_peer_.HandleHeaderRepresentation("empty-joined", ""); decoder_peer_.HandleHeaderRepresentation("cookie", " fin!"); decoder_.HandleControlFrameHeadersComplete(); EXPECT_THAT( decoded_block(), ElementsAre( Pair("cookie", " part 1; part 2 ; part3; fin!"), Pair("passed-through", absl::string_view("foo\0baz", 7)), Pair("joined", absl::string_view("joined\0value 1\0value 2", 22)), Pair("empty", ""), Pair("empty-joined", absl::string_view("\0foo\0\0", 6)))); } TEST_P(HpackDecoderAdapterTest, IndexedHeaderStatic) { const Http2HeaderBlock& header_set1 = DecodeBlockExpectingSuccess("\x82\x85"); Http2HeaderBlock expected_header_set1; expected_header_set1[":method"] = "GET"; expected_header_set1[":path"] = "/index.html"; EXPECT_EQ(expected_header_set1, header_set1); const Http2HeaderBlock& header_set2 = DecodeBlockExpectingSuccess("\x82"); Http2HeaderBlock expected_header_set2; expected_header_set2[":method"] = "GET"; EXPECT_EQ(expected_header_set2, header_set2); } TEST_P(HpackDecoderAdapterTest, IndexedHeaderDynamic) { const Http2HeaderBlock& header_set1 = DecodeBlockExpectingSuccess( "\x40\x03" "foo" "\x03" "bar"); Http2HeaderBlock expected_header_set1; expected_header_set1["foo"] = "bar"; EXPECT_EQ(expected_header_set1, header_set1); const Http2HeaderBlock& header_set2 = DecodeBlockExpectingSuccess( "\xbe\x40\x04" "spam" "\x04" "eggs"); Http2HeaderBlock expected_header_set2; expected_header_set2["foo"] = "bar"; expected_header_set2["spam"] = "eggs"; EXPECT_EQ(expected_header_set2, header_set2); const Http2HeaderBlock& header_set3 = DecodeBlockExpectingSuccess("\xbe"); Http2HeaderBlock expected_header_set3; expected_header_set3["spam"] = "eggs"; EXPECT_EQ(expected_header_set3, header_set3); } TEST_P(HpackDecoderAdapterTest, InvalidIndexedHeader) { EXPECT_FALSE(DecodeHeaderBlock("\xbe")); } TEST_P(HpackDecoderAdapterTest, ContextUpdateMaximumSize) { EXPECT_EQ(kDefaultHeaderTableSizeSetting, decoder_peer_.header_table_size_limit()); std::string input; { HpackOutputStream output_stream; output_stream.AppendPrefix(kHeaderTableSizeUpdateOpcode); output_stream.AppendUint32(126); input = output_stream.TakeString(); EXPECT_TRUE(DecodeHeaderBlock(input)); EXPECT_EQ(126u, decoder_peer_.header_table_size_limit()); } { HpackOutputStream output_stream; output_stream.AppendPrefix(kHeaderTableSizeUpdateOpcode); output_stream.AppendUint32(kDefaultHeaderTableSizeSetting); input = output_stream.TakeString(); EXPECT_TRUE(DecodeHeaderBlock(input)); EXPECT_EQ(kDefaultHeaderTableSizeSetting, decoder_peer_.header_table_size_limit()); } { HpackOutputStream output_stream; output_stream.AppendPrefix(kHeaderTableSizeUpdateOpcode); output_stream.AppendUint32(kDefaultHeaderTableSizeSetting + 1); input = output_stream.TakeString(); EXPECT_FALSE(DecodeHeaderBlock(input)); EXPECT_EQ(kDefaultHeaderTableSizeSetting, decoder_peer_.header_table_size_limit()); } } TEST_P(HpackDecoderAdapterTest, TwoTableSizeUpdates) { std::string input; { HpackOutputStream output_stream; output_stream.AppendPrefix(kHeaderTableSizeUpdateOpcode); output_stream.AppendUint32(0); output_stream.AppendPrefix(kHeaderTableSizeUpdateOpcode); output_stream.AppendUint32(122); input = output_stream.TakeString(); EXPECT_TRUE(DecodeHeaderBlock(input)); EXPECT_EQ(122u, decoder_peer_.header_table_size_limit()); } } TEST_P(HpackDecoderAdapterTest, ThreeTableSizeUpdatesError) { std::string input; { HpackOutputStream output_stream; output_stream.AppendPrefix(kHeaderTableSizeUpdateOpcode); output_stream.AppendUint32(5); output_stream.AppendPrefix(kHeaderTableSizeUpdateOpcode); output_stream.AppendUint32(10); output_stream.AppendPrefix(kHeaderTableSizeUpdateOpcode); output_stream.AppendUint32(15); input = output_stream.TakeString(); EXPECT_FALSE(DecodeHeaderBlock(input)); EXPECT_EQ(10u, decoder_peer_.header_table_size_limit()); } } TEST_P(HpackDecoderAdapterTest, TableSizeUpdateSecondError) { std::string input; { HpackOutputStream output_stream; output_stream.AppendBytes("\x82\x85"); output_stream.AppendPrefix(kHeaderTableSizeUpdateOpcode); output_stream.AppendUint32(123); input = output_stream.TakeString(); EXPECT_FALSE(DecodeHeaderBlock(input)); EXPECT_EQ(kDefaultHeaderTableSizeSetting, decoder_peer_.header_table_size_limit()); } } TEST_P(HpackDecoderAdapterTest, TableSizeUpdateFirstThirdError) { std::string input; { HpackOutputStream output_stream; output_stream.AppendPrefix(kHeaderTableSizeUpdateOpcode); output_stream.AppendUint32(60); output_stream.AppendBytes("\x82\x85"); output_stream.AppendPrefix(kHeaderTableSizeUpdateOpcode); output_stream.AppendUint32(125); input = output_stream.TakeString(); EXPECT_FALSE(DecodeHeaderBlock(input)); EXPECT_EQ(60u, decoder_peer_.header_table_size_limit()); } } TEST_P(HpackDecoderAdapterTest, LiteralHeaderNoIndexing) { const char input[] = "\x04\x0c/sample/path\x00\x06:path2\x0e/sample/path/2"; const Http2HeaderBlock& header_set = DecodeBlockExpectingSuccess( absl::string_view(input, ABSL_ARRAYSIZE(input) - 1)); Http2HeaderBlock expected_header_set; expected_header_set[":path"] = "/sample/path"; expected_header_set[":path2"] = "/sample/path/2"; EXPECT_EQ(expected_header_set, header_set); } TEST_P(HpackDecoderAdapterTest, LiteralHeaderIncrementalIndexing) { const char input[] = "\x44\x0c/sample/path\x40\x06:path2\x0e/sample/path/2"; const Http2HeaderBlock& header_set = DecodeBlockExpectingSuccess( absl::string_view(input, ABSL_ARRAYSIZE(input) - 1)); Http2HeaderBlock expected_header_set; expected_header_set[":path"] = "/sample/path"; expected_header_set[":path2"] = "/sample/path/2"; EXPECT_EQ(expected_header_set, header_set); } TEST_P(HpackDecoderAdapterTest, LiteralHeaderWithIndexingInvalidNameIndex) { decoder_.ApplyHeaderTableSizeSetting(0); EXPECT_TRUE(EncodeAndDecodeDynamicTableSizeUpdates(0, 0)); EXPECT_TRUE(DecodeHeaderBlock(absl::string_view("\x7d\x03ooo"))); EXPECT_FALSE(DecodeHeaderBlock(absl::string_view("\x7e\x03ooo"))); } TEST_P(HpackDecoderAdapterTest, LiteralHeaderNoIndexingInvalidNameIndex) { EXPECT_TRUE(DecodeHeaderBlock(absl::string_view("\x0f\x2e\x03ooo"))); EXPECT_FALSE(DecodeHeaderBlock(absl::string_view("\x0f\x2f\x03ooo"))); } TEST_P(HpackDecoderAdapterTest, LiteralHeaderNeverIndexedInvalidNameIndex) { EXPECT_TRUE(DecodeHeaderBlock(absl::string_view("\x1f\x2e\x03ooo"))); EXPECT_FALSE(DecodeHeaderBlock(absl::string_view("\x1f\x2f\x03ooo"))); } TEST_P(HpackDecoderAdapterTest, TruncatedIndex) { EXPECT_FALSE(DecodeHeaderBlock("\xff")); } TEST_P(HpackDecoderAdapterTest, TruncatedHuffmanLiteral) { std::string first; ASSERT_TRUE(absl::HexStringToBytes("418cf1e3c2e5f23a6ba0ab90f4ff", &first)); EXPECT_TRUE(DecodeHeaderBlock(first)); first.pop_back(); EXPECT_FALSE(DecodeHeaderBlock(first)); } TEST_P(HpackDecoderAdapterTest, HuffmanEOSError) { std::string first; ASSERT_TRUE(absl::HexStringToBytes("418cf1e3c2e5f23a6ba0ab90f4ff", &first)); EXPECT_TRUE(DecodeHeaderBlock(first)); ASSERT_TRUE(absl::HexStringToBytes("418df1e3c2e5f23a6ba0ab90f4ffff", &first)); EXPECT_FALSE(DecodeHeaderBlock(first)); } TEST_P(HpackDecoderAdapterTest, BasicC31) { HpackEncoder encoder; Http2HeaderBlock expected_header_set; expected_header_set[":method"] = "GET"; expected_header_set[":scheme"] = "http"; expected_header_set[":path"] = "/"; expected_header_set[":authority"] = "www.example.com"; std::string encoded_header_set = encoder.EncodeHeaderBlock(expected_header_set); EXPECT_TRUE(DecodeHeaderBlock(encoded_header_set)); EXPECT_EQ(expected_header_set, decoded_block()); } TEST_P(HpackDecoderAdapterTest, SectionC4RequestHuffmanExamples) { std::string first; ASSERT_TRUE( absl::HexStringToBytes("828684418cf1e3c2e5f23a6ba0ab90f4ff", &first)); const Http2HeaderBlock& first_header_set = DecodeBlockExpectingSuccess(first); EXPECT_THAT(first_header_set, ElementsAre( Pair(":method", "GET"), Pair(":scheme", "http"), Pair(":path", "/"), Pair(":authority", "www.example.com"))); expectEntry(62, 57, ":authority", "www.example.com"); EXPECT_EQ(57u, decoder_peer_.current_header_table_size()); std::string second; ASSERT_TRUE(absl::HexStringToBytes("828684be5886a8eb10649cbf", &second)); const Http2HeaderBlock& second_header_set = DecodeBlockExpectingSuccess(second); EXPECT_THAT(second_header_set, ElementsAre( Pair(":method", "GET"), Pair(":scheme", "http"), Pair(":path", "/"), Pair(":authority", "www.example.com"), Pair("cache-control", "no-cache"))); expectEntry(62, 53, "cache-control", "no-cache"); expectEntry(63, 57, ":authority", "www.example.com"); EXPECT_EQ(110u, decoder_peer_.current_header_table_size()); std::string third; ASSERT_TRUE(absl::HexStringToBytes( "828785bf408825a849e95ba97d7f8925a849e95bb8e8b4bf", &third)); const Http2HeaderBlock& third_header_set = DecodeBlockExpectingSuccess(third); EXPECT_THAT( third_header_set, ElementsAre( Pair(":method", "GET"), Pair(":scheme", "https"), Pair(":path", "/index.html"), Pair(":authority", "www.example.com"), Pair("custom-key", "custom-value"))); expectEntry(62, 54, "custom-key", "custom-value"); expectEntry(63, 53, "cache-control", "no-cache"); expectEntry(64, 57, ":authority", "www.example.com"); EXPECT_EQ(164u, decoder_peer_.current_header_table_size()); } TEST_P(HpackDecoderAdapterTest, SectionC6ResponseHuffmanExamples) { decoder_peer_.set_header_table_size_limit(256);
394
cpp
google/quiche
hpack_output_stream
quiche/http2/hpack/hpack_output_stream.cc
quiche/http2/hpack/hpack_output_stream_test.cc
#ifndef QUICHE_SPDY_CORE_HPACK_HPACK_OUTPUT_STREAM_H_ #define QUICHE_SPDY_CORE_HPACK_HPACK_OUTPUT_STREAM_H_ #include <cstddef> #include <cstdint> #include <string> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/spdy/core/hpack/hpack_constants.h" namespace spdy { class QUICHE_EXPORT HpackOutputStream { public: HpackOutputStream(); HpackOutputStream(const HpackOutputStream&) = delete; HpackOutputStream& operator=(const HpackOutputStream&) = delete; ~HpackOutputStream(); void AppendBits(uint8_t bits, size_t bit_size); void AppendPrefix(HpackPrefix prefix); void AppendBytes(absl::string_view buffer); void AppendUint32(uint32_t I); std::string* MutableString(); std::string TakeString(); std::string BoundedTakeString(size_t max_size); size_t size() const { return buffer_.size(); } private: std::string buffer_; size_t bit_offset_; }; } #endif #include "quiche/spdy/core/hpack/hpack_output_stream.h" #include <cstddef> #include <cstdint> #include <string> #include <utility> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/spdy/core/hpack/hpack_constants.h" namespace spdy { HpackOutputStream::HpackOutputStream() : bit_offset_(0) {} HpackOutputStream::~HpackOutputStream() = default; void HpackOutputStream::AppendBits(uint8_t bits, size_t bit_size) { QUICHE_DCHECK_GT(bit_size, 0u); QUICHE_DCHECK_LE(bit_size, 8u); QUICHE_DCHECK_EQ(bits >> bit_size, 0); size_t new_bit_offset = bit_offset_ + bit_size; if (bit_offset_ == 0) { QUICHE_DCHECK_LE(bit_size, 8u); buffer_.append(1, bits << (8 - bit_size)); } else if (new_bit_offset <= 8) { buffer_.back() |= bits << (8 - new_bit_offset); } else { buffer_.back() |= bits >> (new_bit_offset - 8); buffer_.append(1, bits << (16 - new_bit_offset)); } bit_offset_ = new_bit_offset % 8; } void HpackOutputStream::AppendPrefix(HpackPrefix prefix) { AppendBits(prefix.bits, prefix.bit_size); } void HpackOutputStream::AppendBytes(absl::string_view buffer) { QUICHE_DCHECK_EQ(bit_offset_, 0u); buffer_.append(buffer.data(), buffer.size()); } void HpackOutputStream::AppendUint32(uint32_t I) { size_t N = 8 - bit_offset_; uint8_t max_first_byte = static_cast<uint8_t>((1 << N) - 1); if (I < max_first_byte) { AppendBits(static_cast<uint8_t>(I), N); } else { AppendBits(max_first_byte, N); I -= max_first_byte; while ((I & ~0x7f) != 0) { buffer_.append(1, (I & 0x7f) | 0x80); I >>= 7; } AppendBits(static_cast<uint8_t>(I), 8); } QUICHE_DCHECK_EQ(bit_offset_, 0u); } std::string* HpackOutputStream::MutableString() { QUICHE_DCHECK_EQ(bit_offset_, 0u); return &buffer_; } std::string HpackOutputStream::TakeString() { QUICHE_DCHECK_EQ(bit_offset_, 0u); std::string out = std::move(buffer_); buffer_ = {}; bit_offset_ = 0; return out; } std::string HpackOutputStream::BoundedTakeString(size_t max_size) { if (buffer_.size() > max_size) { std::string overflow = buffer_.substr(max_size); buffer_.resize(max_size); std::string out = std::move(buffer_); buffer_ = std::move(overflow); return out; } else { return TakeString(); } } }
#include "quiche/spdy/core/hpack/hpack_output_stream.h" #include <cstdint> #include <string> #include "quiche/common/platform/api/quiche_test.h" namespace spdy { namespace { TEST(HpackOutputStreamTest, AppendBits) { HpackOutputStream output_stream; std::string expected_str; output_stream.AppendBits(0x1, 1); expected_str.append(1, 0x00); expected_str.back() |= (0x1 << 7); output_stream.AppendBits(0x0, 1); output_stream.AppendBits(0x3, 2); *expected_str.rbegin() |= (0x3 << 4); output_stream.AppendBits(0x0, 2); output_stream.AppendBits(0x7, 3); *expected_str.rbegin() |= (0x7 >> 1); expected_str.append(1, 0x00); expected_str.back() |= (0x7 << 7); output_stream.AppendBits(0x0, 7); std::string str = output_stream.TakeString(); EXPECT_EQ(expected_str, str); } std::string EncodeUint32(uint8_t N, uint32_t I) { HpackOutputStream output_stream; if (N < 8) { output_stream.AppendBits(0x00, 8 - N); } output_stream.AppendUint32(I); std::string str = output_stream.TakeString(); return str; } TEST(HpackOutputStreamTest, OneByteIntegersEightBitPrefix) { EXPECT_EQ(std::string("\x00", 1), EncodeUint32(8, 0x00)); EXPECT_EQ("\x7f", EncodeUint32(8, 0x7f)); EXPECT_EQ("\xfe", EncodeUint32(8, 0xfe)); } TEST(HpackOutputStreamTest, TwoByteIntegersEightBitPrefix) { EXPECT_EQ(std::string("\xff\x00", 2), EncodeUint32(8, 0xff)); EXPECT_EQ("\xff\x01", EncodeUint32(8, 0x0100)); EXPECT_EQ("\xff\x7f", EncodeUint32(8, 0x017e)); } TEST(HpackOutputStreamTest, ThreeByteIntegersEightBitPrefix) { EXPECT_EQ("\xff\x80\x01", EncodeUint32(8, 0x017f)); EXPECT_EQ("\xff\x80\x1e", EncodeUint32(8, 0x0fff)); EXPECT_EQ("\xff\xff\x7f", EncodeUint32(8, 0x40fe)); } TEST(HpackOutputStreamTest, FourByteIntegersEightBitPrefix) { EXPECT_EQ("\xff\x80\x80\x01", EncodeUint32(8, 0x40ff)); EXPECT_EQ("\xff\x80\xfe\x03", EncodeUint32(8, 0xffff)); EXPECT_EQ("\xff\xff\xff\x7f", EncodeUint32(8, 0x002000fe)); } TEST(HpackOutputStreamTest, FiveByteIntegersEightBitPrefix) { EXPECT_EQ("\xff\x80\x80\x80\x01", EncodeUint32(8, 0x002000ff)); EXPECT_EQ("\xff\x80\xfe\xff\x07", EncodeUint32(8, 0x00ffffff)); EXPECT_EQ("\xff\xff\xff\xff\x7f", EncodeUint32(8, 0x100000fe)); } TEST(HpackOutputStreamTest, SixByteIntegersEightBitPrefix) { EXPECT_EQ("\xff\x80\x80\x80\x80\x01", EncodeUint32(8, 0x100000ff)); EXPECT_EQ("\xff\x80\xfe\xff\xff\x0f", EncodeUint32(8, 0xffffffff)); } TEST(HpackOutputStreamTest, OneByteIntegersOneToSevenBitPrefixes) { EXPECT_EQ(std::string("\x00", 1), EncodeUint32(7, 0x00)); EXPECT_EQ(std::string("\x00", 1), EncodeUint32(6, 0x00)); EXPECT_EQ(std::string("\x00", 1), EncodeUint32(5, 0x00)); EXPECT_EQ(std::string("\x00", 1), EncodeUint32(4, 0x00)); EXPECT_EQ(std::string("\x00", 1), EncodeUint32(3, 0x00)); EXPECT_EQ(std::string("\x00", 1), EncodeUint32(2, 0x00)); EXPECT_EQ(std::string("\x00", 1), EncodeUint32(1, 0x00)); EXPECT_EQ("\x7e", EncodeUint32(7, 0x7e)); EXPECT_EQ("\x3e", EncodeUint32(6, 0x3e)); EXPECT_EQ("\x1e", EncodeUint32(5, 0x1e)); EXPECT_EQ("\x0e", EncodeUint32(4, 0x0e)); EXPECT_EQ("\x06", EncodeUint32(3, 0x06)); EXPECT_EQ("\x02", EncodeUint32(2, 0x02)); EXPECT_EQ(std::string("\x00", 1), EncodeUint32(1, 0x00)); } TEST(HpackOutputStreamTest, TwoByteIntegersOneToSevenBitPrefixes) { EXPECT_EQ(std::string("\x7f\x00", 2), EncodeUint32(7, 0x7f)); EXPECT_EQ(std::string("\x3f\x00", 2), EncodeUint32(6, 0x3f)); EXPECT_EQ(std::string("\x1f\x00", 2), EncodeUint32(5, 0x1f)); EXPECT_EQ(std::string("\x0f\x00", 2), EncodeUint32(4, 0x0f)); EXPECT_EQ(std::string("\x07\x00", 2), EncodeUint32(3, 0x07)); EXPECT_EQ(std::string("\x03\x00", 2), EncodeUint32(2, 0x03)); EXPECT_EQ(std::string("\x01\x00", 2), EncodeUint32(1, 0x01)); EXPECT_EQ("\x7f\x7f", EncodeUint32(7, 0xfe)); EXPECT_EQ("\x3f\x7f", EncodeUint32(6, 0xbe)); EXPECT_EQ("\x1f\x7f", EncodeUint32(5, 0x9e)); EXPECT_EQ("\x0f\x7f", EncodeUint32(4, 0x8e)); EXPECT_EQ("\x07\x7f", EncodeUint32(3, 0x86)); EXPECT_EQ("\x03\x7f", EncodeUint32(2, 0x82)); EXPECT_EQ("\x01\x7f", EncodeUint32(1, 0x80)); } TEST(HpackOutputStreamTest, ThreeByteIntegersOneToSevenBitPrefixes) { EXPECT_EQ("\x7f\x80\x01", EncodeUint32(7, 0xff)); EXPECT_EQ("\x3f\x80\x01", EncodeUint32(6, 0xbf)); EXPECT_EQ("\x1f\x80\x01", EncodeUint32(5, 0x9f)); EXPECT_EQ("\x0f\x80\x01", EncodeUint32(4, 0x8f)); EXPECT_EQ("\x07\x80\x01", EncodeUint32(3, 0x87)); EXPECT_EQ("\x03\x80\x01", EncodeUint32(2, 0x83)); EXPECT_EQ("\x01\x80\x01", EncodeUint32(1, 0x81)); EXPECT_EQ("\x7f\xff\x7f", EncodeUint32(7, 0x407e)); EXPECT_EQ("\x3f\xff\x7f", EncodeUint32(6, 0x403e)); EXPECT_EQ("\x1f\xff\x7f", EncodeUint32(5, 0x401e)); EXPECT_EQ("\x0f\xff\x7f", EncodeUint32(4, 0x400e)); EXPECT_EQ("\x07\xff\x7f", EncodeUint32(3, 0x4006)); EXPECT_EQ("\x03\xff\x7f", EncodeUint32(2, 0x4002)); EXPECT_EQ("\x01\xff\x7f", EncodeUint32(1, 0x4000)); } TEST(HpackOutputStreamTest, FourByteIntegersOneToSevenBitPrefixes) { EXPECT_EQ("\x7f\x80\x80\x01", EncodeUint32(7, 0x407f)); EXPECT_EQ("\x3f\x80\x80\x01", EncodeUint32(6, 0x403f)); EXPECT_EQ("\x1f\x80\x80\x01", EncodeUint32(5, 0x401f)); EXPECT_EQ("\x0f\x80\x80\x01", EncodeUint32(4, 0x400f)); EXPECT_EQ("\x07\x80\x80\x01", EncodeUint32(3, 0x4007)); EXPECT_EQ("\x03\x80\x80\x01", EncodeUint32(2, 0x4003)); EXPECT_EQ("\x01\x80\x80\x01", EncodeUint32(1, 0x4001)); EXPECT_EQ("\x7f\xff\xff\x7f", EncodeUint32(7, 0x20007e)); EXPECT_EQ("\x3f\xff\xff\x7f", EncodeUint32(6, 0x20003e)); EXPECT_EQ("\x1f\xff\xff\x7f", EncodeUint32(5, 0x20001e)); EXPECT_EQ("\x0f\xff\xff\x7f", EncodeUint32(4, 0x20000e)); EXPECT_EQ("\x07\xff\xff\x7f", EncodeUint32(3, 0x200006)); EXPECT_EQ("\x03\xff\xff\x7f", EncodeUint32(2, 0x200002)); EXPECT_EQ("\x01\xff\xff\x7f", EncodeUint32(1, 0x200000)); } TEST(HpackOutputStreamTest, FiveByteIntegersOneToSevenBitPrefixes) { EXPECT_EQ("\x7f\x80\x80\x80\x01", EncodeUint32(7, 0x20007f)); EXPECT_EQ("\x3f\x80\x80\x80\x01", EncodeUint32(6, 0x20003f)); EXPECT_EQ("\x1f\x80\x80\x80\x01", EncodeUint32(5, 0x20001f)); EXPECT_EQ("\x0f\x80\x80\x80\x01", EncodeUint32(4, 0x20000f)); EXPECT_EQ("\x07\x80\x80\x80\x01", EncodeUint32(3, 0x200007)); EXPECT_EQ("\x03\x80\x80\x80\x01", EncodeUint32(2, 0x200003)); EXPECT_EQ("\x01\x80\x80\x80\x01", EncodeUint32(1, 0x200001)); EXPECT_EQ("\x7f\xff\xff\xff\x7f", EncodeUint32(7, 0x1000007e)); EXPECT_EQ("\x3f\xff\xff\xff\x7f", EncodeUint32(6, 0x1000003e)); EXPECT_EQ("\x1f\xff\xff\xff\x7f", EncodeUint32(5, 0x1000001e)); EXPECT_EQ("\x0f\xff\xff\xff\x7f", EncodeUint32(4, 0x1000000e)); EXPECT_EQ("\x07\xff\xff\xff\x7f", EncodeUint32(3, 0x10000006)); EXPECT_EQ("\x03\xff\xff\xff\x7f", EncodeUint32(2, 0x10000002)); EXPECT_EQ("\x01\xff\xff\xff\x7f", EncodeUint32(1, 0x10000000)); } TEST(HpackOutputStreamTest, SixByteIntegersOneToSevenBitPrefixes) { EXPECT_EQ("\x7f\x80\x80\x80\x80\x01", EncodeUint32(7, 0x1000007f)); EXPECT_EQ("\x3f\x80\x80\x80\x80\x01", EncodeUint32(6, 0x1000003f)); EXPECT_EQ("\x1f\x80\x80\x80\x80\x01", EncodeUint32(5, 0x1000001f)); EXPECT_EQ("\x0f\x80\x80\x80\x80\x01", EncodeUint32(4, 0x1000000f)); EXPECT_EQ("\x07\x80\x80\x80\x80\x01", EncodeUint32(3, 0x10000007)); EXPECT_EQ("\x03\x80\x80\x80\x80\x01", EncodeUint32(2, 0x10000003)); EXPECT_EQ("\x01\x80\x80\x80\x80\x01", EncodeUint32(1, 0x10000001)); EXPECT_EQ("\x7f\x80\xff\xff\xff\x0f", EncodeUint32(7, 0xffffffff)); EXPECT_EQ("\x3f\xc0\xff\xff\xff\x0f", EncodeUint32(6, 0xffffffff)); EXPECT_EQ("\x1f\xe0\xff\xff\xff\x0f", EncodeUint32(5, 0xffffffff)); EXPECT_EQ("\x0f\xf0\xff\xff\xff\x0f", EncodeUint32(4, 0xffffffff)); EXPECT_EQ("\x07\xf8\xff\xff\xff\x0f", EncodeUint32(3, 0xffffffff)); EXPECT_EQ("\x03\xfc\xff\xff\xff\x0f", EncodeUint32(2, 0xffffffff)); EXPECT_EQ("\x01\xfe\xff\xff\xff\x0f", EncodeUint32(1, 0xffffffff)); } TEST(HpackOutputStreamTest, AppendUint32PreservesUpperBits) { HpackOutputStream output_stream; output_stream.AppendBits(0x7f, 7); output_stream.AppendUint32(0x01); std::string str = output_stream.TakeString(); EXPECT_EQ(std::string("\xff\x00", 2), str); } TEST(HpackOutputStreamTest, AppendBytes) { HpackOutputStream output_stream; output_stream.AppendBytes("buffer1"); output_stream.AppendBytes("buffer2"); std::string str = output_stream.TakeString(); EXPECT_EQ("buffer1buffer2", str); } TEST(HpackOutputStreamTest, BoundedTakeString) { HpackOutputStream output_stream; output_stream.AppendBytes("buffer12"); output_stream.AppendBytes("buffer456"); std::string str = output_stream.BoundedTakeString(9); EXPECT_EQ("buffer12b", str); output_stream.AppendBits(0x7f, 7); output_stream.AppendUint32(0x11); str = output_stream.BoundedTakeString(9); EXPECT_EQ("uffer456\xff", str); str = output_stream.BoundedTakeString(9); EXPECT_EQ("\x10", str); } TEST(HpackOutputStreamTest, MutableString) { HpackOutputStream output_stream; output_stream.AppendBytes("1"); output_stream.MutableString()->append("2"); output_stream.AppendBytes("foo"); output_stream.MutableString()->append("bar"); std::string str = output_stream.TakeString(); EXPECT_EQ("12foobar", str); } } }
395
cpp
google/quiche
hpack_entry
quiche/http2/hpack/hpack_entry.cc
quiche/http2/hpack/hpack_entry_test.cc
#ifndef QUICHE_SPDY_CORE_HPACK_HPACK_ENTRY_H_ #define QUICHE_SPDY_CORE_HPACK_HPACK_ENTRY_H_ #include <cstddef> #include <string> #include <utility> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_export.h" namespace spdy { inline constexpr size_t kHpackEntrySizeOverhead = 32; struct QUICHE_EXPORT HpackLookupEntry { absl::string_view name; absl::string_view value; bool operator==(const HpackLookupEntry& other) const { return name == other.name && value == other.value; } template <typename H> friend H AbslHashValue(H h, const HpackLookupEntry& entry) { return H::combine(std::move(h), entry.name, entry.value); } }; class QUICHE_EXPORT HpackEntry { public: HpackEntry(std::string name, std::string value); HpackEntry(const HpackEntry&) = delete; HpackEntry& operator=(const HpackEntry&) = delete; HpackEntry(HpackEntry&&) = default; HpackEntry& operator=(HpackEntry&&) = default; absl::string_view name() const { return name_; } absl::string_view value() const { return value_; } static size_t Size(absl::string_view name, absl::string_view value); size_t Size() const; std::string GetDebugString() const; private: std::string name_; std::string value_; }; } #endif #include "quiche/spdy/core/hpack/hpack_entry.h" #include <cstddef> #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" namespace spdy { HpackEntry::HpackEntry(std::string name, std::string value) : name_(std::move(name)), value_(std::move(value)) {} size_t HpackEntry::Size(absl::string_view name, absl::string_view value) { return name.size() + value.size() + kHpackEntrySizeOverhead; } size_t HpackEntry::Size() const { return Size(name(), value()); } std::string HpackEntry::GetDebugString() const { return absl::StrCat("{ name: \"", name_, "\", value: \"", value_, "\" }"); } }
#include "quiche/spdy/core/hpack/hpack_entry.h" #include "absl/hash/hash.h" #include "quiche/common/platform/api/quiche_test.h" namespace spdy { namespace { TEST(HpackLookupEntryTest, EntryNamesDiffer) { HpackLookupEntry entry1{"header", "value"}; HpackLookupEntry entry2{"HEADER", "value"}; EXPECT_FALSE(entry1 == entry2); EXPECT_NE(absl::Hash<HpackLookupEntry>()(entry1), absl::Hash<HpackLookupEntry>()(entry2)); } TEST(HpackLookupEntryTest, EntryValuesDiffer) { HpackLookupEntry entry1{"header", "value"}; HpackLookupEntry entry2{"header", "VALUE"}; EXPECT_FALSE(entry1 == entry2); EXPECT_NE(absl::Hash<HpackLookupEntry>()(entry1), absl::Hash<HpackLookupEntry>()(entry2)); } TEST(HpackLookupEntryTest, EntriesEqual) { HpackLookupEntry entry1{"name", "value"}; HpackLookupEntry entry2{"name", "value"}; EXPECT_TRUE(entry1 == entry2); EXPECT_EQ(absl::Hash<HpackLookupEntry>()(entry1), absl::Hash<HpackLookupEntry>()(entry2)); } TEST(HpackEntryTest, BasicEntry) { HpackEntry entry("header-name", "header value"); EXPECT_EQ("header-name", entry.name()); EXPECT_EQ("header value", entry.value()); EXPECT_EQ(55u, entry.Size()); EXPECT_EQ(55u, HpackEntry::Size("header-name", "header value")); } } }
396
cpp
google/quiche
hpack_static_table
quiche/http2/hpack/hpack_static_table.cc
quiche/http2/hpack/hpack_static_table_test.cc
#ifndef QUICHE_SPDY_CORE_HPACK_HPACK_STATIC_TABLE_H_ #define QUICHE_SPDY_CORE_HPACK_HPACK_STATIC_TABLE_H_ #include <cstddef> #include "quiche/common/platform/api/quiche_export.h" #include "quiche/spdy/core/hpack/hpack_header_table.h" namespace spdy { struct HpackStaticEntry; inline constexpr size_t kStaticTableSize = 61; class QUICHE_EXPORT HpackStaticTable { public: HpackStaticTable(); ~HpackStaticTable(); void Initialize(const HpackStaticEntry* static_entry_table, size_t static_entry_count); bool IsInitialized() const; const HpackHeaderTable::StaticEntryTable& GetStaticEntries() const { return static_entries_; } const HpackHeaderTable::NameValueToEntryMap& GetStaticIndex() const { return static_index_; } const HpackHeaderTable::NameToEntryMap& GetStaticNameIndex() const { return static_name_index_; } private: HpackHeaderTable::StaticEntryTable static_entries_; HpackHeaderTable::NameValueToEntryMap static_index_; HpackHeaderTable::NameToEntryMap static_name_index_; }; } #endif #include "quiche/spdy/core/hpack/hpack_static_table.h" #include <cstddef> #include <string> #include <utility> #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/spdy/core/hpack/hpack_constants.h" #include "quiche/spdy/core/hpack/hpack_entry.h" namespace spdy { HpackStaticTable::HpackStaticTable() = default; HpackStaticTable::~HpackStaticTable() = default; void HpackStaticTable::Initialize(const HpackStaticEntry* static_entry_table, size_t static_entry_count) { QUICHE_CHECK(!IsInitialized()); static_entries_.reserve(static_entry_count); for (const HpackStaticEntry* it = static_entry_table; it != static_entry_table + static_entry_count; ++it) { std::string name(it->name, it->name_len); std::string value(it->value, it->value_len); static_entries_.push_back(HpackEntry(std::move(name), std::move(value))); } int insertion_count = 0; for (const auto& entry : static_entries_) { auto result = static_index_.insert(std::make_pair( HpackLookupEntry{entry.name(), entry.value()}, insertion_count)); QUICHE_CHECK(result.second); static_name_index_.insert(std::make_pair(entry.name(), insertion_count)); ++insertion_count; } } bool HpackStaticTable::IsInitialized() const { return !static_entries_.empty(); } }
#include "quiche/spdy/core/hpack/hpack_static_table.h" #include <set> #include <vector> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/spdy/core/hpack/hpack_constants.h" #include "quiche/spdy/core/hpack/hpack_header_table.h" namespace spdy { namespace test { namespace { class HpackStaticTableTest : public quiche::test::QuicheTest { protected: HpackStaticTableTest() : table_() {} HpackStaticTable table_; }; TEST_F(HpackStaticTableTest, Initialize) { EXPECT_FALSE(table_.IsInitialized()); table_.Initialize(HpackStaticTableVector().data(), HpackStaticTableVector().size()); EXPECT_TRUE(table_.IsInitialized()); const HpackHeaderTable::StaticEntryTable& static_entries = table_.GetStaticEntries(); EXPECT_EQ(kStaticTableSize, static_entries.size()); const HpackHeaderTable::NameValueToEntryMap& static_index = table_.GetStaticIndex(); EXPECT_EQ(kStaticTableSize, static_index.size()); const HpackHeaderTable::NameToEntryMap& static_name_index = table_.GetStaticNameIndex(); std::set<absl::string_view> names; for (const auto& entry : static_entries) { names.insert(entry.name()); } EXPECT_EQ(names.size(), static_name_index.size()); } TEST_F(HpackStaticTableTest, IsSingleton) { const HpackStaticTable* static_table_one = &ObtainHpackStaticTable(); const HpackStaticTable* static_table_two = &ObtainHpackStaticTable(); EXPECT_EQ(static_table_one, static_table_two); } } } }
397
cpp
google/quiche
http2_structures
quiche/http2/http2_structures.cc
quiche/http2/http2_structures_test.cc
#ifndef QUICHE_HTTP2_HTTP2_STRUCTURES_H_ #define QUICHE_HTTP2_HTTP2_STRUCTURES_H_ #include <stddef.h> #include <cstdint> #include <ostream> #include <string> #include "quiche/http2/http2_constants.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { struct QUICHE_EXPORT Http2FrameHeader { Http2FrameHeader() {} Http2FrameHeader(uint32_t payload_length, Http2FrameType type, uint8_t flags, uint32_t stream_id) : payload_length(payload_length), stream_id(stream_id), type(type), flags(flags) { QUICHE_DCHECK_LT(payload_length, static_cast<uint32_t>(1 << 24)) << "Payload Length is only a 24 bit field\n" << ToString(); } static constexpr size_t EncodedSize() { return 9; } void RetainFlags(uint8_t valid_flags) { flags = (flags & valid_flags); } bool HasAnyFlags(uint8_t flag_mask) const { return 0 != (flags & flag_mask); } bool IsEndStream() const { QUICHE_DCHECK(type == Http2FrameType::DATA || type == Http2FrameType::HEADERS) << ToString(); return (flags & Http2FrameFlag::END_STREAM) != 0; } bool IsAck() const { QUICHE_DCHECK(type == Http2FrameType::SETTINGS || type == Http2FrameType::PING) << ToString(); return (flags & Http2FrameFlag::ACK) != 0; } bool IsEndHeaders() const { QUICHE_DCHECK(type == Http2FrameType::HEADERS || type == Http2FrameType::PUSH_PROMISE || type == Http2FrameType::CONTINUATION) << ToString(); return (flags & Http2FrameFlag::END_HEADERS) != 0; } bool IsPadded() const { QUICHE_DCHECK(type == Http2FrameType::DATA || type == Http2FrameType::HEADERS || type == Http2FrameType::PUSH_PROMISE) << ToString(); return (flags & Http2FrameFlag::PADDED) != 0; } bool HasPriority() const { QUICHE_DCHECK_EQ(type, Http2FrameType::HEADERS) << ToString(); return (flags & Http2FrameFlag::PRIORITY) != 0; } bool IsProbableHttpResponse() const; std::string ToString() const; std::string FlagsToString() const; uint32_t payload_length; uint32_t stream_id; Http2FrameType type; uint8_t flags; }; QUICHE_EXPORT bool operator==(const Http2FrameHeader& a, const Http2FrameHeader& b); QUICHE_EXPORT inline bool operator!=(const Http2FrameHeader& a, const Http2FrameHeader& b) { return !(a == b); } QUICHE_EXPORT std::ostream& operator<<(std::ostream& out, const Http2FrameHeader& v); struct QUICHE_EXPORT Http2PriorityFields { Http2PriorityFields() {} Http2PriorityFields(uint32_t stream_dependency, uint32_t weight, bool is_exclusive) : stream_dependency(stream_dependency), weight(weight), is_exclusive(is_exclusive) { QUICHE_DCHECK_EQ(stream_dependency, stream_dependency & StreamIdMask()) << "Stream Dependency is only a 31-bit field.\n" << ToString(); QUICHE_DCHECK_LE(1u, weight) << "Weight is too small."; QUICHE_DCHECK_LE(weight, 256u) << "Weight is too large."; } static constexpr size_t EncodedSize() { return 5; } std::string ToString() const; uint32_t stream_dependency; uint32_t weight; bool is_exclusive; }; QUICHE_EXPORT bool operator==(const Http2PriorityFields& a, const Http2PriorityFields& b); QUICHE_EXPORT inline bool operator!=(const Http2PriorityFields& a, const Http2PriorityFields& b) { return !(a == b); } QUICHE_EXPORT std::ostream& operator<<(std::ostream& out, const Http2PriorityFields& v); struct QUICHE_EXPORT Http2RstStreamFields { static constexpr size_t EncodedSize() { return 4; } bool IsSupportedErrorCode() const { return IsSupportedHttp2ErrorCode(error_code); } Http2ErrorCode error_code; }; QUICHE_EXPORT bool operator==(const Http2RstStreamFields& a, const Http2RstStreamFields& b); QUICHE_EXPORT inline bool operator!=(const Http2RstStreamFields& a, const Http2RstStreamFields& b) { return !(a == b); } QUICHE_EXPORT std::ostream& operator<<(std::ostream& out, const Http2RstStreamFields& v); struct QUICHE_EXPORT Http2SettingFields { Http2SettingFields() {} Http2SettingFields(Http2SettingsParameter parameter, uint32_t value) : parameter(parameter), value(value) {} static constexpr size_t EncodedSize() { return 6; } bool IsSupportedParameter() const { return IsSupportedHttp2SettingsParameter(parameter); } Http2SettingsParameter parameter; uint32_t value; }; QUICHE_EXPORT bool operator==(const Http2SettingFields& a, const Http2SettingFields& b); QUICHE_EXPORT inline bool operator!=(const Http2SettingFields& a, const Http2SettingFields& b) { return !(a == b); } QUICHE_EXPORT std::ostream& operator<<(std::ostream& out, const Http2SettingFields& v); struct QUICHE_EXPORT Http2PushPromiseFields { static constexpr size_t EncodedSize() { return 4; } uint32_t promised_stream_id; }; QUICHE_EXPORT bool operator==(const Http2PushPromiseFields& a, const Http2PushPromiseFields& b); QUICHE_EXPORT inline bool operator!=(const Http2PushPromiseFields& a, const Http2PushPromiseFields& b) { return !(a == b); } QUICHE_EXPORT std::ostream& operator<<(std::ostream& out, const Http2PushPromiseFields& v); struct QUICHE_EXPORT Http2PingFields { static constexpr size_t EncodedSize() { return 8; } uint8_t opaque_bytes[8]; }; QUICHE_EXPORT bool operator==(const Http2PingFields& a, const Http2PingFields& b); QUICHE_EXPORT inline bool operator!=(const Http2PingFields& a, const Http2PingFields& b) { return !(a == b); } QUICHE_EXPORT std::ostream& operator<<(std::ostream& out, const Http2PingFields& v); struct QUICHE_EXPORT Http2GoAwayFields { Http2GoAwayFields() {} Http2GoAwayFields(uint32_t last_stream_id, Http2ErrorCode error_code) : last_stream_id(last_stream_id), error_code(error_code) {} static constexpr size_t EncodedSize() { return 8; } bool IsSupportedErrorCode() const { return IsSupportedHttp2ErrorCode(error_code); } uint32_t last_stream_id; Http2ErrorCode error_code; }; QUICHE_EXPORT bool operator==(const Http2GoAwayFields& a, const Http2GoAwayFields& b); QUICHE_EXPORT inline bool operator!=(const Http2GoAwayFields& a, const Http2GoAwayFields& b) { return !(a == b); } QUICHE_EXPORT std::ostream& operator<<(std::ostream& out, const Http2GoAwayFields& v); struct QUICHE_EXPORT Http2WindowUpdateFields { static constexpr size_t EncodedSize() { return 4; } uint32_t window_size_increment; }; QUICHE_EXPORT bool operator==(const Http2WindowUpdateFields& a, const Http2WindowUpdateFields& b); QUICHE_EXPORT inline bool operator!=(const Http2WindowUpdateFields& a, const Http2WindowUpdateFields& b) { return !(a == b); } QUICHE_EXPORT std::ostream& operator<<(std::ostream& out, const Http2WindowUpdateFields& v); struct QUICHE_EXPORT Http2AltSvcFields { static constexpr size_t EncodedSize() { return 2; } uint16_t origin_length; }; QUICHE_EXPORT bool operator==(const Http2AltSvcFields& a, const Http2AltSvcFields& b); QUICHE_EXPORT inline bool operator!=(const Http2AltSvcFields& a, const Http2AltSvcFields& b) { return !(a == b); } QUICHE_EXPORT std::ostream& operator<<(std::ostream& out, const Http2AltSvcFields& v); struct QUICHE_EXPORT Http2PriorityUpdateFields { Http2PriorityUpdateFields() {} Http2PriorityUpdateFields(uint32_t prioritized_stream_id) : prioritized_stream_id(prioritized_stream_id) {} static constexpr size_t EncodedSize() { return 4; } std::string ToString() const; uint32_t prioritized_stream_id; }; QUICHE_EXPORT bool operator==(const Http2PriorityUpdateFields& a, const Http2PriorityUpdateFields& b); QUICHE_EXPORT inline bool operator!=(const Http2PriorityUpdateFields& a, const Http2PriorityUpdateFields& b) { return !(a == b); } QUICHE_EXPORT std::ostream& operator<<(std::ostream& out, const Http2PriorityUpdateFields& v); } #endif #include "quiche/http2/http2_structures.h" #include <cstring> #include <ostream> #include <sstream> #include <string> #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" namespace http2 { bool Http2FrameHeader::IsProbableHttpResponse() const { return (payload_length == 0x485454 && static_cast<char>(type) == 'P' && flags == '/'); } std::string Http2FrameHeader::ToString() const { return absl::StrCat("length=", payload_length, ", type=", Http2FrameTypeToString(type), ", flags=", FlagsToString(), ", stream=", stream_id); } std::string Http2FrameHeader::FlagsToString() const { return Http2FrameFlagsToString(type, flags); } bool operator==(const Http2FrameHeader& a, const Http2FrameHeader& b) { return a.payload_length == b.payload_length && a.stream_id == b.stream_id && a.type == b.type && a.flags == b.flags; } std::ostream& operator<<(std::ostream& out, const Http2FrameHeader& v) { return out << v.ToString(); } bool operator==(const Http2PriorityFields& a, const Http2PriorityFields& b) { return a.stream_dependency == b.stream_dependency && a.weight == b.weight; } std::string Http2PriorityFields::ToString() const { std::stringstream ss; ss << "E=" << (is_exclusive ? "true" : "false") << ", stream=" << stream_dependency << ", weight=" << static_cast<uint32_t>(weight); return ss.str(); } std::ostream& operator<<(std::ostream& out, const Http2PriorityFields& v) { return out << v.ToString(); } bool operator==(const Http2RstStreamFields& a, const Http2RstStreamFields& b) { return a.error_code == b.error_code; } std::ostream& operator<<(std::ostream& out, const Http2RstStreamFields& v) { return out << "error_code=" << v.error_code; } bool operator==(const Http2SettingFields& a, const Http2SettingFields& b) { return a.parameter == b.parameter && a.value == b.value; } std::ostream& operator<<(std::ostream& out, const Http2SettingFields& v) { return out << "parameter=" << v.parameter << ", value=" << v.value; } bool operator==(const Http2PushPromiseFields& a, const Http2PushPromiseFields& b) { return a.promised_stream_id == b.promised_stream_id; } std::ostream& operator<<(std::ostream& out, const Http2PushPromiseFields& v) { return out << "promised_stream_id=" << v.promised_stream_id; } bool operator==(const Http2PingFields& a, const Http2PingFields& b) { static_assert((sizeof a.opaque_bytes) == Http2PingFields::EncodedSize(), "Why not the same size?"); return 0 == std::memcmp(a.opaque_bytes, b.opaque_bytes, sizeof a.opaque_bytes); } std::ostream& operator<<(std::ostream& out, const Http2PingFields& v) { return out << "opaque_bytes=0x" << absl::BytesToHexString(absl::string_view( reinterpret_cast<const char*>(v.opaque_bytes), sizeof v.opaque_bytes)); } bool operator==(const Http2GoAwayFields& a, const Http2GoAwayFields& b) { return a.last_stream_id == b.last_stream_id && a.error_code == b.error_code; } std::ostream& operator<<(std::ostream& out, const Http2GoAwayFields& v) { return out << "last_stream_id=" << v.last_stream_id << ", error_code=" << v.error_code; } bool operator==(const Http2WindowUpdateFields& a, const Http2WindowUpdateFields& b) { return a.window_size_increment == b.window_size_increment; } std::ostream& operator<<(std::ostream& out, const Http2WindowUpdateFields& v) { return out << "window_size_increment=" << v.window_size_increment; } bool operator==(const Http2AltSvcFields& a, const Http2AltSvcFields& b) { return a.origin_length == b.origin_length; } std::ostream& operator<<(std::ostream& out, const Http2AltSvcFields& v) { return out << "origin_length=" << v.origin_length; } bool operator==(const Http2PriorityUpdateFields& a, const Http2PriorityUpdateFields& b) { return a.prioritized_stream_id == b.prioritized_stream_id; } std::string Http2PriorityUpdateFields::ToString() const { std::stringstream ss; ss << "prioritized_stream_id=" << prioritized_stream_id; return ss.str(); } std::ostream& operator<<(std::ostream& out, const Http2PriorityUpdateFields& v) { return out << v.ToString(); } }
#include "quiche/http2/http2_structures.h" #include <memory> #include <ostream> #include <sstream> #include <string> #include <tuple> #include <type_traits> #include <vector> #include "absl/strings/str_cat.h" #include "quiche/http2/test_tools/http2_random.h" #include "quiche/http2/test_tools/http2_structures_test_util.h" #include "quiche/http2/test_tools/verify_macros.h" #include "quiche/common/platform/api/quiche_test.h" using ::testing::AssertionResult; using ::testing::AssertionSuccess; using ::testing::Combine; using ::testing::HasSubstr; using ::testing::MatchesRegex; using ::testing::Not; using ::testing::Values; using ::testing::ValuesIn; namespace http2 { namespace test { namespace { template <typename E> E IncrementEnum(E e) { using I = typename std::underlying_type<E>::type; return static_cast<E>(1 + static_cast<I>(e)); } template <class T> AssertionResult VerifyRandomCalls() { T t1; Http2Random seq1( "6d9a61ddf2bc1fc0b8245505a1f28e324559d8b5c9c3268f38b42b1af3287c47"); Randomize(&t1, &seq1); T t2; Http2Random seq2(seq1.Key()); Randomize(&t2, &seq2); HTTP2_VERIFY_EQ(seq1.Rand64(), seq2.Rand64()); HTTP2_VERIFY_EQ(t1, t2); Randomize(&t2, &seq2); HTTP2_VERIFY_NE(t1, t2); Randomize(&t1, &seq1); HTTP2_VERIFY_EQ(t1, t2); HTTP2_VERIFY_EQ(seq1.Rand64(), seq2.Rand64()); return AssertionSuccess(); } #if GTEST_HAS_DEATH_TEST && !defined(NDEBUG) std::vector<Http2FrameType> ValidFrameTypes() { std::vector<Http2FrameType> valid_types{Http2FrameType::DATA}; while (valid_types.back() != Http2FrameType::ALTSVC) { valid_types.push_back(IncrementEnum(valid_types.back())); } return valid_types; } #endif TEST(Http2FrameHeaderTest, Constructor) { Http2Random random; uint8_t frame_type = 0; do { uint32_t payload_length = random.Rand32() & 0xffffff; Http2FrameType type = static_cast<Http2FrameType>(frame_type); uint8_t flags = random.Rand8(); uint32_t stream_id = random.Rand32(); Http2FrameHeader v(payload_length, type, flags, stream_id); EXPECT_EQ(payload_length, v.payload_length); EXPECT_EQ(type, v.type); EXPECT_EQ(flags, v.flags); EXPECT_EQ(stream_id, v.stream_id); } while (frame_type++ != 255); #if GTEST_HAS_DEATH_TEST && !defined(NDEBUG) EXPECT_QUICHE_DEBUG_DEATH( Http2FrameHeader(0x01000000, Http2FrameType::DATA, 0, 1), "payload_length"); #endif } TEST(Http2FrameHeaderTest, Eq) { Http2Random random; uint32_t payload_length = random.Rand32() & 0xffffff; Http2FrameType type = static_cast<Http2FrameType>(random.Rand8()); uint8_t flags = random.Rand8(); uint32_t stream_id = random.Rand32(); Http2FrameHeader v(payload_length, type, flags, stream_id); EXPECT_EQ(payload_length, v.payload_length); EXPECT_EQ(type, v.type); EXPECT_EQ(flags, v.flags); EXPECT_EQ(stream_id, v.stream_id); Http2FrameHeader u(0, type, ~flags, stream_id); EXPECT_NE(u, v); EXPECT_NE(v, u); EXPECT_FALSE(u == v); EXPECT_FALSE(v == u); EXPECT_TRUE(u != v); EXPECT_TRUE(v != u); u = v; EXPECT_EQ(u, v); EXPECT_EQ(v, u); EXPECT_TRUE(u == v); EXPECT_TRUE(v == u); EXPECT_FALSE(u != v); EXPECT_FALSE(v != u); EXPECT_TRUE(VerifyRandomCalls<Http2FrameHeader>()); } #if GTEST_HAS_DEATH_TEST && !defined(NDEBUG) using TestParams = std::tuple<Http2FrameType, uint8_t>; std::string TestParamToString(const testing::TestParamInfo<TestParams>& info) { Http2FrameType type = std::get<0>(info.param); uint8_t flags = std::get<1>(info.param); return absl::StrCat(Http2FrameTypeToString(type), static_cast<int>(flags)); } class Http2FrameHeaderTypeAndFlagTest : public quiche::test::QuicheTestWithParam<TestParams> { protected: Http2FrameHeaderTypeAndFlagTest() : type_(std::get<0>(GetParam())), flags_(std::get<1>(GetParam())) { QUICHE_LOG(INFO) << "Frame type: " << type_; QUICHE_LOG(INFO) << "Frame flags: " << Http2FrameFlagsToString(type_, flags_); } const Http2FrameType type_; const uint8_t flags_; }; class IsEndStreamTest : public Http2FrameHeaderTypeAndFlagTest {}; INSTANTIATE_TEST_SUITE_P(IsEndStream, IsEndStreamTest, Combine(ValuesIn(ValidFrameTypes()), Values(~Http2FrameFlag::END_STREAM, 0xff)), TestParamToString); TEST_P(IsEndStreamTest, IsEndStream) { const bool is_set = (flags_ & Http2FrameFlag::END_STREAM) == Http2FrameFlag::END_STREAM; std::string flags_string; Http2FrameHeader v(0, type_, flags_, 0); switch (type_) { case Http2FrameType::DATA: case Http2FrameType::HEADERS: EXPECT_EQ(is_set, v.IsEndStream()) << v; flags_string = v.FlagsToString(); if (is_set) { EXPECT_THAT(flags_string, MatchesRegex(".*\\|?END_STREAM\\|.*")); } else { EXPECT_THAT(flags_string, Not(HasSubstr("END_STREAM"))); } v.RetainFlags(Http2FrameFlag::END_STREAM); EXPECT_EQ(is_set, v.IsEndStream()) << v; { std::stringstream s; s << v; EXPECT_EQ(v.ToString(), s.str()); if (is_set) { EXPECT_THAT(s.str(), HasSubstr("flags=END_STREAM,")); } else { EXPECT_THAT(s.str(), HasSubstr("flags=,")); } } break; default: EXPECT_QUICHE_DEBUG_DEATH(v.IsEndStream(), "DATA.*HEADERS"); } } class IsACKTest : public Http2FrameHeaderTypeAndFlagTest {}; INSTANTIATE_TEST_SUITE_P(IsAck, IsACKTest, Combine(ValuesIn(ValidFrameTypes()), Values(~Http2FrameFlag::ACK, 0xff)), TestParamToString); TEST_P(IsACKTest, IsAck) { const bool is_set = (flags_ & Http2FrameFlag::ACK) == Http2FrameFlag::ACK; std::string flags_string; Http2FrameHeader v(0, type_, flags_, 0); switch (type_) { case Http2FrameType::SETTINGS: case Http2FrameType::PING: EXPECT_EQ(is_set, v.IsAck()) << v; flags_string = v.FlagsToString(); if (is_set) { EXPECT_THAT(flags_string, MatchesRegex(".*\\|?ACK\\|.*")); } else { EXPECT_THAT(flags_string, Not(HasSubstr("ACK"))); } v.RetainFlags(Http2FrameFlag::ACK); EXPECT_EQ(is_set, v.IsAck()) << v; { std::stringstream s; s << v; EXPECT_EQ(v.ToString(), s.str()); if (is_set) { EXPECT_THAT(s.str(), HasSubstr("flags=ACK,")); } else { EXPECT_THAT(s.str(), HasSubstr("flags=,")); } } break; default: EXPECT_QUICHE_DEBUG_DEATH(v.IsAck(), "SETTINGS.*PING"); } } class IsEndHeadersTest : public Http2FrameHeaderTypeAndFlagTest {}; INSTANTIATE_TEST_SUITE_P(IsEndHeaders, IsEndHeadersTest, Combine(ValuesIn(ValidFrameTypes()), Values(~Http2FrameFlag::END_HEADERS, 0xff)), TestParamToString); TEST_P(IsEndHeadersTest, IsEndHeaders) { const bool is_set = (flags_ & Http2FrameFlag::END_HEADERS) == Http2FrameFlag::END_HEADERS; std::string flags_string; Http2FrameHeader v(0, type_, flags_, 0); switch (type_) { case Http2FrameType::HEADERS: case Http2FrameType::PUSH_PROMISE: case Http2FrameType::CONTINUATION: EXPECT_EQ(is_set, v.IsEndHeaders()) << v; flags_string = v.FlagsToString(); if (is_set) { EXPECT_THAT(flags_string, MatchesRegex(".*\\|?END_HEADERS\\|.*")); } else { EXPECT_THAT(flags_string, Not(HasSubstr("END_HEADERS"))); } v.RetainFlags(Http2FrameFlag::END_HEADERS); EXPECT_EQ(is_set, v.IsEndHeaders()) << v; { std::stringstream s; s << v; EXPECT_EQ(v.ToString(), s.str()); if (is_set) { EXPECT_THAT(s.str(), HasSubstr("flags=END_HEADERS,")); } else { EXPECT_THAT(s.str(), HasSubstr("flags=,")); } } break; default: EXPECT_QUICHE_DEBUG_DEATH(v.IsEndHeaders(), "HEADERS.*PUSH_PROMISE.*CONTINUATION"); } } class IsPaddedTest : public Http2FrameHeaderTypeAndFlagTest {}; INSTANTIATE_TEST_SUITE_P(IsPadded, IsPaddedTest, Combine(ValuesIn(ValidFrameTypes()), Values(~Http2FrameFlag::PADDED, 0xff)), TestParamToString); TEST_P(IsPaddedTest, IsPadded) { const bool is_set = (flags_ & Http2FrameFlag::PADDED) == Http2FrameFlag::PADDED; std::string flags_string; Http2FrameHeader v(0, type_, flags_, 0); switch (type_) { case Http2FrameType::DATA: case Http2FrameType::HEADERS: case Http2FrameType::PUSH_PROMISE: EXPECT_EQ(is_set, v.IsPadded()) << v; flags_string = v.FlagsToString(); if (is_set) { EXPECT_THAT(flags_string, MatchesRegex(".*\\|?PADDED\\|.*")); } else { EXPECT_THAT(flags_string, Not(HasSubstr("PADDED"))); } v.RetainFlags(Http2FrameFlag::PADDED); EXPECT_EQ(is_set, v.IsPadded()) << v; { std::stringstream s; s << v; EXPECT_EQ(v.ToString(), s.str()); if (is_set) { EXPECT_THAT(s.str(), HasSubstr("flags=PADDED,")); } else { EXPECT_THAT(s.str(), HasSubstr("flags=,")); } } break; default: EXPECT_QUICHE_DEBUG_DEATH(v.IsPadded(), "DATA.*HEADERS.*PUSH_PROMISE"); } } class HasPriorityTest : public Http2FrameHeaderTypeAndFlagTest {}; INSTANTIATE_TEST_SUITE_P(HasPriority, HasPriorityTest, Combine(ValuesIn(ValidFrameTypes()), Values(~Http2FrameFlag::PRIORITY, 0xff)), TestParamToString); TEST_P(HasPriorityTest, HasPriority) { const bool is_set = (flags_ & Http2FrameFlag::PRIORITY) == Http2FrameFlag::PRIORITY; std::string flags_string; Http2FrameHeader v(0, type_, flags_, 0); switch (type_) { case Http2FrameType::HEADERS: EXPECT_EQ(is_set, v.HasPriority()) << v; flags_string = v.FlagsToString(); if (is_set) { EXPECT_THAT(flags_string, MatchesRegex(".*\\|?PRIORITY\\|.*")); } else { EXPECT_THAT(flags_string, Not(HasSubstr("PRIORITY"))); } v.RetainFlags(Http2FrameFlag::PRIORITY); EXPECT_EQ(is_set, v.HasPriority()) << v; { std::stringstream s; s << v; EXPECT_EQ(v.ToString(), s.str()); if (is_set) { EXPECT_THAT(s.str(), HasSubstr("flags=PRIORITY,")); } else { EXPECT_THAT(s.str(), HasSubstr("flags=,")); } } break; default: EXPECT_QUICHE_DEBUG_DEATH(v.HasPriority(), "HEADERS"); } } TEST(Http2PriorityFieldsTest, Constructor) { Http2Random random; uint32_t stream_dependency = random.Rand32() & StreamIdMask(); uint32_t weight = 1 + random.Rand8(); bool is_exclusive = random.OneIn(2); Http2PriorityFields v(stream_dependency, weight, is_exclusive); EXPECT_EQ(stream_dependency, v.stream_dependency); EXPECT_EQ(weight, v.weight); EXPECT_EQ(is_exclusive, v.is_exclusive); EXPECT_QUICHE_DEBUG_DEATH( Http2PriorityFields(stream_dependency | 0x80000000, weight, is_exclusive), "31-bit"); EXPECT_QUICHE_DEBUG_DEATH( Http2PriorityFields(stream_dependency, 0, is_exclusive), "too small"); EXPECT_QUICHE_DEBUG_DEATH( Http2PriorityFields(stream_dependency, weight + 256, is_exclusive), "too large"); EXPECT_TRUE(VerifyRandomCalls<Http2PriorityFields>()); } #endif TEST(Http2RstStreamFieldsTest, IsSupported) { Http2RstStreamFields v{Http2ErrorCode::HTTP2_NO_ERROR}; EXPECT_TRUE(v.IsSupportedErrorCode()) << v; Http2RstStreamFields u{static_cast<Http2ErrorCode>(~0)}; EXPECT_FALSE(u.IsSupportedErrorCode()) << v; EXPECT_TRUE(VerifyRandomCalls<Http2RstStreamFields>()); } TEST(Http2SettingFieldsTest, Misc) { Http2Random random; Http2SettingsParameter parameter = static_cast<Http2SettingsParameter>(random.Rand16()); uint32_t value = random.Rand32(); Http2SettingFields v(parameter, value); EXPECT_EQ(v, v); EXPECT_EQ(parameter, v.parameter); EXPECT_EQ(value, v.value); if (static_cast<uint16_t>(parameter) < 7) { EXPECT_TRUE(v.IsSupportedParameter()) << v; } else { EXPECT_FALSE(v.IsSupportedParameter()) << v; } Http2SettingFields u(parameter, ~value); EXPECT_NE(v, u); EXPECT_EQ(v.parameter, u.parameter); EXPECT_NE(v.value, u.value); Http2SettingFields w(IncrementEnum(parameter), value); EXPECT_NE(v, w); EXPECT_NE(v.parameter, w.parameter); EXPECT_EQ(v.value, w.value); Http2SettingFields x(Http2SettingsParameter::MAX_FRAME_SIZE, 123); std::stringstream s; s << x; EXPECT_EQ("parameter=MAX_FRAME_SIZE, value=123", s.str()); EXPECT_TRUE(VerifyRandomCalls<Http2SettingFields>()); } TEST(Http2PushPromiseTest, Misc) { Http2Random random; uint32_t promised_stream_id = random.Rand32() & StreamIdMask(); Http2PushPromiseFields v{promised_stream_id}; EXPECT_EQ(promised_stream_id, v.promised_stream_id); EXPECT_EQ(v, v); std::stringstream s; s << v; EXPECT_EQ(absl::StrCat("promised_stream_id=", promised_stream_id), s.str()); promised_stream_id |= 0x80000000; Http2PushPromiseFields w{promised_stream_id}; EXPECT_EQ(w, w); EXPECT_NE(v, w); v.promised_stream_id = promised_stream_id; EXPECT_EQ(v, w); EXPECT_TRUE(VerifyRandomCalls<Http2PushPromiseFields>()); } TEST(Http2PingFieldsTest, Misc) { Http2PingFields v{{'8', ' ', 'b', 'y', 't', 'e', 's', '\0'}}; std::stringstream s; s << v; EXPECT_EQ("opaque_bytes=0x3820627974657300", s.str()); EXPECT_TRUE(VerifyRandomCalls<Http2PingFields>()); } TEST(Http2GoAwayFieldsTest, Misc) { Http2Random random; uint32_t last_stream_id = random.Rand32() & StreamIdMask(); Http2ErrorCode error_code = static_cast<Http2ErrorCode>(random.Rand32()); Http2GoAwayFields v(last_stream_id, error_code); EXPECT_EQ(v, v); EXPECT_EQ(last_stream_id, v.last_stream_id); EXPECT_EQ(error_code, v.error_code); if (static_cast<uint32_t>(error_code) < 14) { EXPECT_TRUE(v.IsSupportedErrorCode()) << v; } else { EXPECT_FALSE(v.IsSupportedErrorCode()) << v; } Http2GoAwayFields u(~last_stream_id, error_code); EXPECT_NE(v, u); EXPECT_NE(v.last_stream_id, u.last_stream_id); EXPECT_EQ(v.error_code, u.error_code); EXPECT_TRUE(VerifyRandomCalls<Http2GoAwayFields>()); } TEST(Http2WindowUpdateTest, Misc) { Http2Random random; uint32_t window_size_increment = random.Rand32() & UInt31Mask(); Http2WindowUpdateFields v{window_size_increment}; EXPECT_EQ(window_size_increment, v.window_size_increment); EXPECT_EQ(v, v); std::stringstream s; s << v; EXPECT_EQ(absl::StrCat("window_size_increment=", window_size_increment), s.str()); window_size_increment |= 0x80000000; Http2WindowUpdateFields w{window_size_increment}; EXPECT_EQ(w, w); EXPECT_NE(v, w); v.window_size_increment = window_size_increment; EXPECT_EQ(v, w); EXPECT_TRUE(VerifyRandomCalls<Http2WindowUpdateFields>()); } TEST(Http2AltSvcTest, Misc) { Http2Random random; uint16_t origin_length = random.Rand16(); Http2AltSvcFields v{origin_length}; EXPECT_EQ(origin_length, v.origin_length); EXPECT_EQ(v, v); std::stringstream s; s << v; EXPECT_EQ(absl::StrCat("origin_length=", origin_length), s.str()); Http2AltSvcFields w{++origin_length}; EXPECT_EQ(w, w); EXPECT_NE(v, w); v.origin_length = w.origin_length; EXPECT_EQ(v, w); EXPECT_TRUE(VerifyRandomCalls<Http2AltSvcFields>()); } TEST(Http2PriorityUpdateFieldsTest, Eq) { Http2PriorityUpdateFields u( 1); Http2PriorityUpdateFields v( 3); EXPECT_NE(u, v); EXPECT_FALSE(u == v); EXPECT_TRUE(u != v); u = v; EXPECT_EQ(u, v); EXPECT_TRUE(u == v); EXPECT_FALSE(u != v); } TEST(Http2PriorityUpdateFieldsTest, Misc) { Http2PriorityUpdateFields u( 1); EXPECT_EQ("prioritized_stream_id=1", u.ToString()); EXPECT_TRUE(VerifyRandomCalls<Http2PriorityUpdateFields>()); } } } }
398
cpp
google/quiche
http2_constants
quiche/http2/http2_constants.cc
quiche/http2/http2_constants_test.cc
#ifndef QUICHE_HTTP2_HTTP2_CONSTANTS_H_ #define QUICHE_HTTP2_HTTP2_CONSTANTS_H_ #include <cstdint> #include <iosfwd> #include <ostream> #include <string> #include "absl/container/flat_hash_set.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/quiche_text_utils.h" namespace http2 { constexpr uint32_t UInt31Mask() { return 0x7fffffff; } constexpr uint32_t StreamIdMask() { return UInt31Mask(); } enum class Http2FrameType : uint8_t { DATA = 0, HEADERS = 1, PRIORITY = 2, RST_STREAM = 3, SETTINGS = 4, PUSH_PROMISE = 5, PING = 6, GOAWAY = 7, WINDOW_UPDATE = 8, CONTINUATION = 9, ALTSVC = 10, PRIORITY_UPDATE = 16, }; inline bool IsSupportedHttp2FrameType(uint32_t v) { return v <= static_cast<uint32_t>(Http2FrameType::ALTSVC) || v == static_cast<uint32_t>(Http2FrameType::PRIORITY_UPDATE); } inline bool IsSupportedHttp2FrameType(Http2FrameType v) { return IsSupportedHttp2FrameType(static_cast<uint32_t>(v)); } QUICHE_EXPORT std::string Http2FrameTypeToString(Http2FrameType v); QUICHE_EXPORT std::string Http2FrameTypeToString(uint8_t v); QUICHE_EXPORT inline std::ostream& operator<<(std::ostream& out, Http2FrameType v) { return out << Http2FrameTypeToString(v); } enum Http2FrameFlag : uint8_t { END_STREAM = 0x01, ACK = 0x01, END_HEADERS = 0x04, PADDED = 0x08, PRIORITY = 0x20, }; QUICHE_EXPORT std::string Http2FrameFlagsToString(Http2FrameType type, uint8_t flags); QUICHE_EXPORT std::string Http2FrameFlagsToString(uint8_t type, uint8_t flags); enum class Http2ErrorCode : uint32_t { HTTP2_NO_ERROR = 0x0, PROTOCOL_ERROR = 0x1, INTERNAL_ERROR = 0x2, FLOW_CONTROL_ERROR = 0x3, SETTINGS_TIMEOUT = 0x4, STREAM_CLOSED = 0x5, FRAME_SIZE_ERROR = 0x6, REFUSED_STREAM = 0x7, CANCEL = 0x8, COMPRESSION_ERROR = 0x9, CONNECT_ERROR = 0xa, ENHANCE_YOUR_CALM = 0xb, INADEQUATE_SECURITY = 0xc, HTTP_1_1_REQUIRED = 0xd, }; inline bool IsSupportedHttp2ErrorCode(uint32_t v) { return v <= static_cast<uint32_t>(Http2ErrorCode::HTTP_1_1_REQUIRED); } inline bool IsSupportedHttp2ErrorCode(Http2ErrorCode v) { return IsSupportedHttp2ErrorCode(static_cast<uint32_t>(v)); } QUICHE_EXPORT std::string Http2ErrorCodeToString(uint32_t v); QUICHE_EXPORT std::string Http2ErrorCodeToString(Http2ErrorCode v); QUICHE_EXPORT inline std::ostream& operator<<(std::ostream& out, Http2ErrorCode v) { return out << Http2ErrorCodeToString(v); } enum class Http2SettingsParameter : uint16_t { HEADER_TABLE_SIZE = 0x1, ENABLE_PUSH = 0x2, MAX_CONCURRENT_STREAMS = 0x3, INITIAL_WINDOW_SIZE = 0x4, MAX_FRAME_SIZE = 0x5, MAX_HEADER_LIST_SIZE = 0x6, }; inline bool IsSupportedHttp2SettingsParameter(uint32_t v) { return 0 < v && v <= static_cast<uint32_t>( Http2SettingsParameter::MAX_HEADER_LIST_SIZE); } inline bool IsSupportedHttp2SettingsParameter(Http2SettingsParameter v) { return IsSupportedHttp2SettingsParameter(static_cast<uint32_t>(v)); } QUICHE_EXPORT std::string Http2SettingsParameterToString(uint32_t v); QUICHE_EXPORT std::string Http2SettingsParameterToString( Http2SettingsParameter v); inline std::ostream& operator<<(std::ostream& out, Http2SettingsParameter v) { return out << Http2SettingsParameterToString(v); } class QUICHE_EXPORT Http2SettingsInfo { public: static constexpr uint32_t DefaultHeaderTableSize() { return 4096; } static constexpr bool DefaultEnablePush() { return true; } static constexpr uint32_t DefaultInitialWindowSize() { return 65535; } static constexpr uint32_t MaximumWindowSize() { return UInt31Mask(); } static constexpr uint32_t DefaultMaxFrameSize() { return 16384; } static constexpr uint32_t MinimumMaxFrameSize() { return 16384; } static constexpr uint32_t MaximumMaxFrameSize() { return (1 << 24) - 1; } }; using InvalidHeaderSet = absl::flat_hash_set<absl::string_view, quiche::StringPieceCaseHash, quiche::StringPieceCaseEqual>; QUICHE_EXPORT const InvalidHeaderSet& GetInvalidHttp2HeaderSet(); } #endif #include "quiche/http2/http2_constants.h" #include <string> #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { std::string Http2FrameTypeToString(Http2FrameType v) { switch (v) { case Http2FrameType::DATA: return "DATA"; case Http2FrameType::HEADERS: return "HEADERS"; case Http2FrameType::PRIORITY: return "PRIORITY"; case Http2FrameType::RST_STREAM: return "RST_STREAM"; case Http2FrameType::SETTINGS: return "SETTINGS"; case Http2FrameType::PUSH_PROMISE: return "PUSH_PROMISE"; case Http2FrameType::PING: return "PING"; case Http2FrameType::GOAWAY: return "GOAWAY"; case Http2FrameType::WINDOW_UPDATE: return "WINDOW_UPDATE"; case Http2FrameType::CONTINUATION: return "CONTINUATION"; case Http2FrameType::ALTSVC: return "ALTSVC"; case Http2FrameType::PRIORITY_UPDATE: return "PRIORITY_UPDATE"; } return absl::StrCat("UnknownFrameType(", static_cast<int>(v), ")"); } std::string Http2FrameTypeToString(uint8_t v) { return Http2FrameTypeToString(static_cast<Http2FrameType>(v)); } std::string Http2FrameFlagsToString(Http2FrameType type, uint8_t flags) { std::string s; auto append_and_clear = [&s, &flags](absl::string_view v, uint8_t bit) { if (!s.empty()) { s.push_back('|'); } absl::StrAppend(&s, v); flags ^= bit; }; if (flags & 0x01) { if (type == Http2FrameType::DATA || type == Http2FrameType::HEADERS) { append_and_clear("END_STREAM", Http2FrameFlag::END_STREAM); } else if (type == Http2FrameType::SETTINGS || type == Http2FrameType::PING) { append_and_clear("ACK", Http2FrameFlag::ACK); } } if (flags & 0x04) { if (type == Http2FrameType::HEADERS || type == Http2FrameType::PUSH_PROMISE || type == Http2FrameType::CONTINUATION) { append_and_clear("END_HEADERS", Http2FrameFlag::END_HEADERS); } } if (flags & 0x08) { if (type == Http2FrameType::DATA || type == Http2FrameType::HEADERS || type == Http2FrameType::PUSH_PROMISE) { append_and_clear("PADDED", Http2FrameFlag::PADDED); } } if (flags & 0x20) { if (type == Http2FrameType::HEADERS) { append_and_clear("PRIORITY", Http2FrameFlag::PRIORITY); } } if (flags != 0) { append_and_clear(absl::StrFormat("0x%02x", flags), flags); } QUICHE_DCHECK_EQ(0, flags); return s; } std::string Http2FrameFlagsToString(uint8_t type, uint8_t flags) { return Http2FrameFlagsToString(static_cast<Http2FrameType>(type), flags); } std::string Http2ErrorCodeToString(uint32_t v) { switch (v) { case 0x0: return "NO_ERROR"; case 0x1: return "PROTOCOL_ERROR"; case 0x2: return "INTERNAL_ERROR"; case 0x3: return "FLOW_CONTROL_ERROR"; case 0x4: return "SETTINGS_TIMEOUT"; case 0x5: return "STREAM_CLOSED"; case 0x6: return "FRAME_SIZE_ERROR"; case 0x7: return "REFUSED_STREAM"; case 0x8: return "CANCEL"; case 0x9: return "COMPRESSION_ERROR"; case 0xa: return "CONNECT_ERROR"; case 0xb: return "ENHANCE_YOUR_CALM"; case 0xc: return "INADEQUATE_SECURITY"; case 0xd: return "HTTP_1_1_REQUIRED"; } return absl::StrCat("UnknownErrorCode(0x", absl::Hex(v), ")"); } std::string Http2ErrorCodeToString(Http2ErrorCode v) { return Http2ErrorCodeToString(static_cast<uint32_t>(v)); } std::string Http2SettingsParameterToString(uint32_t v) { switch (v) { case 0x1: return "HEADER_TABLE_SIZE"; case 0x2: return "ENABLE_PUSH"; case 0x3: return "MAX_CONCURRENT_STREAMS"; case 0x4: return "INITIAL_WINDOW_SIZE"; case 0x5: return "MAX_FRAME_SIZE"; case 0x6: return "MAX_HEADER_LIST_SIZE"; } return absl::StrCat("UnknownSettingsParameter(0x", absl::Hex(v), ")"); } std::string Http2SettingsParameterToString(Http2SettingsParameter v) { return Http2SettingsParameterToString(static_cast<uint32_t>(v)); } constexpr char const* kHttp2InvalidHeaderNames[] = { "connection", "host", "keep-alive", "proxy-connection", "transfer-encoding", "", }; const InvalidHeaderSet& GetInvalidHttp2HeaderSet() { static const auto* invalid_header_set = new InvalidHeaderSet(std::begin(http2::kHttp2InvalidHeaderNames), std::end(http2::kHttp2InvalidHeaderNames)); return *invalid_header_set; } }
#include "quiche/http2/http2_constants.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { namespace { class Http2ConstantsTest : public quiche::test::QuicheTest {}; TEST(Http2ConstantsTest, Http2FrameType) { EXPECT_EQ(Http2FrameType::DATA, static_cast<Http2FrameType>(0)); EXPECT_EQ(Http2FrameType::HEADERS, static_cast<Http2FrameType>(1)); EXPECT_EQ(Http2FrameType::PRIORITY, static_cast<Http2FrameType>(2)); EXPECT_EQ(Http2FrameType::RST_STREAM, static_cast<Http2FrameType>(3)); EXPECT_EQ(Http2FrameType::SETTINGS, static_cast<Http2FrameType>(4)); EXPECT_EQ(Http2FrameType::PUSH_PROMISE, static_cast<Http2FrameType>(5)); EXPECT_EQ(Http2FrameType::PING, static_cast<Http2FrameType>(6)); EXPECT_EQ(Http2FrameType::GOAWAY, static_cast<Http2FrameType>(7)); EXPECT_EQ(Http2FrameType::WINDOW_UPDATE, static_cast<Http2FrameType>(8)); EXPECT_EQ(Http2FrameType::CONTINUATION, static_cast<Http2FrameType>(9)); EXPECT_EQ(Http2FrameType::ALTSVC, static_cast<Http2FrameType>(10)); } TEST(Http2ConstantsTest, Http2FrameTypeToString) { EXPECT_EQ("DATA", Http2FrameTypeToString(Http2FrameType::DATA)); EXPECT_EQ("HEADERS", Http2FrameTypeToString(Http2FrameType::HEADERS)); EXPECT_EQ("PRIORITY", Http2FrameTypeToString(Http2FrameType::PRIORITY)); EXPECT_EQ("RST_STREAM", Http2FrameTypeToString(Http2FrameType::RST_STREAM)); EXPECT_EQ("SETTINGS", Http2FrameTypeToString(Http2FrameType::SETTINGS)); EXPECT_EQ("PUSH_PROMISE", Http2FrameTypeToString(Http2FrameType::PUSH_PROMISE)); EXPECT_EQ("PING", Http2FrameTypeToString(Http2FrameType::PING)); EXPECT_EQ("GOAWAY", Http2FrameTypeToString(Http2FrameType::GOAWAY)); EXPECT_EQ("WINDOW_UPDATE", Http2FrameTypeToString(Http2FrameType::WINDOW_UPDATE)); EXPECT_EQ("CONTINUATION", Http2FrameTypeToString(Http2FrameType::CONTINUATION)); EXPECT_EQ("ALTSVC", Http2FrameTypeToString(Http2FrameType::ALTSVC)); EXPECT_EQ("DATA", Http2FrameTypeToString(0)); EXPECT_EQ("HEADERS", Http2FrameTypeToString(1)); EXPECT_EQ("PRIORITY", Http2FrameTypeToString(2)); EXPECT_EQ("RST_STREAM", Http2FrameTypeToString(3)); EXPECT_EQ("SETTINGS", Http2FrameTypeToString(4)); EXPECT_EQ("PUSH_PROMISE", Http2FrameTypeToString(5)); EXPECT_EQ("PING", Http2FrameTypeToString(6)); EXPECT_EQ("GOAWAY", Http2FrameTypeToString(7)); EXPECT_EQ("WINDOW_UPDATE", Http2FrameTypeToString(8)); EXPECT_EQ("CONTINUATION", Http2FrameTypeToString(9)); EXPECT_EQ("ALTSVC", Http2FrameTypeToString(10)); EXPECT_EQ("UnknownFrameType(99)", Http2FrameTypeToString(99)); } TEST(Http2ConstantsTest, Http2FrameFlag) { EXPECT_EQ(Http2FrameFlag::END_STREAM, static_cast<Http2FrameFlag>(0x01)); EXPECT_EQ(Http2FrameFlag::ACK, static_cast<Http2FrameFlag>(0x01)); EXPECT_EQ(Http2FrameFlag::END_HEADERS, static_cast<Http2FrameFlag>(0x04)); EXPECT_EQ(Http2FrameFlag::PADDED, static_cast<Http2FrameFlag>(0x08)); EXPECT_EQ(Http2FrameFlag::PRIORITY, static_cast<Http2FrameFlag>(0x20)); EXPECT_EQ(Http2FrameFlag::END_STREAM, 0x01); EXPECT_EQ(Http2FrameFlag::ACK, 0x01); EXPECT_EQ(Http2FrameFlag::END_HEADERS, 0x04); EXPECT_EQ(Http2FrameFlag::PADDED, 0x08); EXPECT_EQ(Http2FrameFlag::PRIORITY, 0x20); } TEST(Http2ConstantsTest, Http2FrameFlagsToString) { EXPECT_EQ("END_STREAM", Http2FrameFlagsToString(Http2FrameType::DATA, Http2FrameFlag::END_STREAM)); EXPECT_EQ("END_STREAM", Http2FrameFlagsToString(Http2FrameType::HEADERS, 0x01)); EXPECT_EQ("ACK", Http2FrameFlagsToString(Http2FrameType::SETTINGS, Http2FrameFlag::ACK)); EXPECT_EQ("ACK", Http2FrameFlagsToString(Http2FrameType::PING, 0x01)); EXPECT_EQ("0x02", Http2FrameFlagsToString(0xff, 0x02)); EXPECT_EQ("END_HEADERS", Http2FrameFlagsToString(Http2FrameType::HEADERS, Http2FrameFlag::END_HEADERS)); EXPECT_EQ("END_HEADERS", Http2FrameFlagsToString(Http2FrameType::PUSH_PROMISE, 0x04)); EXPECT_EQ("END_HEADERS", Http2FrameFlagsToString(0x09, 0x04)); EXPECT_EQ("0x04", Http2FrameFlagsToString(0xff, 0x04)); EXPECT_EQ("PADDED", Http2FrameFlagsToString(Http2FrameType::DATA, Http2FrameFlag::PADDED)); EXPECT_EQ("PADDED", Http2FrameFlagsToString(Http2FrameType::HEADERS, 0x08)); EXPECT_EQ("PADDED", Http2FrameFlagsToString(0x05, 0x08)); EXPECT_EQ("0x08", Http2FrameFlagsToString(0xff, Http2FrameFlag::PADDED)); EXPECT_EQ("0x10", Http2FrameFlagsToString(Http2FrameType::SETTINGS, 0x10)); EXPECT_EQ("PRIORITY", Http2FrameFlagsToString(Http2FrameType::HEADERS, 0x20)); EXPECT_EQ("0x20", Http2FrameFlagsToString(Http2FrameType::PUSH_PROMISE, 0x20)); EXPECT_EQ("0x40", Http2FrameFlagsToString(0xff, 0x40)); EXPECT_EQ("0x80", Http2FrameFlagsToString(0xff, 0x80)); EXPECT_EQ("END_STREAM|PADDED|0xf6", Http2FrameFlagsToString(Http2FrameType::DATA, 0xff)); EXPECT_EQ("END_STREAM|END_HEADERS|PADDED|PRIORITY|0xd2", Http2FrameFlagsToString(Http2FrameType::HEADERS, 0xff)); EXPECT_EQ("0xff", Http2FrameFlagsToString(Http2FrameType::PRIORITY, 0xff)); EXPECT_EQ("0xff", Http2FrameFlagsToString(Http2FrameType::RST_STREAM, 0xff)); EXPECT_EQ("ACK|0xfe", Http2FrameFlagsToString(Http2FrameType::SETTINGS, 0xff)); EXPECT_EQ("END_HEADERS|PADDED|0xf3", Http2FrameFlagsToString(Http2FrameType::PUSH_PROMISE, 0xff)); EXPECT_EQ("ACK|0xfe", Http2FrameFlagsToString(Http2FrameType::PING, 0xff)); EXPECT_EQ("0xff", Http2FrameFlagsToString(Http2FrameType::GOAWAY, 0xff)); EXPECT_EQ("0xff", Http2FrameFlagsToString(Http2FrameType::WINDOW_UPDATE, 0xff)); EXPECT_EQ("END_HEADERS|0xfb", Http2FrameFlagsToString(Http2FrameType::CONTINUATION, 0xff)); EXPECT_EQ("0xff", Http2FrameFlagsToString(Http2FrameType::ALTSVC, 0xff)); EXPECT_EQ("0xff", Http2FrameFlagsToString(0xff, 0xff)); } TEST(Http2ConstantsTest, Http2ErrorCode) { EXPECT_EQ(Http2ErrorCode::HTTP2_NO_ERROR, static_cast<Http2ErrorCode>(0x0)); EXPECT_EQ(Http2ErrorCode::PROTOCOL_ERROR, static_cast<Http2ErrorCode>(0x1)); EXPECT_EQ(Http2ErrorCode::INTERNAL_ERROR, static_cast<Http2ErrorCode>(0x2)); EXPECT_EQ(Http2ErrorCode::FLOW_CONTROL_ERROR, static_cast<Http2ErrorCode>(0x3)); EXPECT_EQ(Http2ErrorCode::SETTINGS_TIMEOUT, static_cast<Http2ErrorCode>(0x4)); EXPECT_EQ(Http2ErrorCode::STREAM_CLOSED, static_cast<Http2ErrorCode>(0x5)); EXPECT_EQ(Http2ErrorCode::FRAME_SIZE_ERROR, static_cast<Http2ErrorCode>(0x6)); EXPECT_EQ(Http2ErrorCode::REFUSED_STREAM, static_cast<Http2ErrorCode>(0x7)); EXPECT_EQ(Http2ErrorCode::CANCEL, static_cast<Http2ErrorCode>(0x8)); EXPECT_EQ(Http2ErrorCode::COMPRESSION_ERROR, static_cast<Http2ErrorCode>(0x9)); EXPECT_EQ(Http2ErrorCode::CONNECT_ERROR, static_cast<Http2ErrorCode>(0xa)); EXPECT_EQ(Http2ErrorCode::ENHANCE_YOUR_CALM, static_cast<Http2ErrorCode>(0xb)); EXPECT_EQ(Http2ErrorCode::INADEQUATE_SECURITY, static_cast<Http2ErrorCode>(0xc)); EXPECT_EQ(Http2ErrorCode::HTTP_1_1_REQUIRED, static_cast<Http2ErrorCode>(0xd)); } TEST(Http2ConstantsTest, Http2ErrorCodeToString) { EXPECT_EQ("NO_ERROR", Http2ErrorCodeToString(Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_EQ("NO_ERROR", Http2ErrorCodeToString(0x0)); EXPECT_EQ("PROTOCOL_ERROR", Http2ErrorCodeToString(Http2ErrorCode::PROTOCOL_ERROR)); EXPECT_EQ("PROTOCOL_ERROR", Http2ErrorCodeToString(0x1)); EXPECT_EQ("INTERNAL_ERROR", Http2ErrorCodeToString(Http2ErrorCode::INTERNAL_ERROR)); EXPECT_EQ("INTERNAL_ERROR", Http2ErrorCodeToString(0x2)); EXPECT_EQ("FLOW_CONTROL_ERROR", Http2ErrorCodeToString(Http2ErrorCode::FLOW_CONTROL_ERROR)); EXPECT_EQ("FLOW_CONTROL_ERROR", Http2ErrorCodeToString(0x3)); EXPECT_EQ("SETTINGS_TIMEOUT", Http2ErrorCodeToString(Http2ErrorCode::SETTINGS_TIMEOUT)); EXPECT_EQ("SETTINGS_TIMEOUT", Http2ErrorCodeToString(0x4)); EXPECT_EQ("STREAM_CLOSED", Http2ErrorCodeToString(Http2ErrorCode::STREAM_CLOSED)); EXPECT_EQ("STREAM_CLOSED", Http2ErrorCodeToString(0x5)); EXPECT_EQ("FRAME_SIZE_ERROR", Http2ErrorCodeToString(Http2ErrorCode::FRAME_SIZE_ERROR)); EXPECT_EQ("FRAME_SIZE_ERROR", Http2ErrorCodeToString(0x6)); EXPECT_EQ("REFUSED_STREAM", Http2ErrorCodeToString(Http2ErrorCode::REFUSED_STREAM)); EXPECT_EQ("REFUSED_STREAM", Http2ErrorCodeToString(0x7)); EXPECT_EQ("CANCEL", Http2ErrorCodeToString(Http2ErrorCode::CANCEL)); EXPECT_EQ("CANCEL", Http2ErrorCodeToString(0x8)); EXPECT_EQ("COMPRESSION_ERROR", Http2ErrorCodeToString(Http2ErrorCode::COMPRESSION_ERROR)); EXPECT_EQ("COMPRESSION_ERROR", Http2ErrorCodeToString(0x9)); EXPECT_EQ("CONNECT_ERROR", Http2ErrorCodeToString(Http2ErrorCode::CONNECT_ERROR)); EXPECT_EQ("CONNECT_ERROR", Http2ErrorCodeToString(0xa)); EXPECT_EQ("ENHANCE_YOUR_CALM", Http2ErrorCodeToString(Http2ErrorCode::ENHANCE_YOUR_CALM)); EXPECT_EQ("ENHANCE_YOUR_CALM", Http2ErrorCodeToString(0xb)); EXPECT_EQ("INADEQUATE_SECURITY", Http2ErrorCodeToString(Http2ErrorCode::INADEQUATE_SECURITY)); EXPECT_EQ("INADEQUATE_SECURITY", Http2ErrorCodeToString(0xc)); EXPECT_EQ("HTTP_1_1_REQUIRED", Http2ErrorCodeToString(Http2ErrorCode::HTTP_1_1_REQUIRED)); EXPECT_EQ("HTTP_1_1_REQUIRED", Http2ErrorCodeToString(0xd)); EXPECT_EQ("UnknownErrorCode(0x123)", Http2ErrorCodeToString(0x123)); } TEST(Http2ConstantsTest, Http2SettingsParameter) { EXPECT_EQ(Http2SettingsParameter::HEADER_TABLE_SIZE, static_cast<Http2SettingsParameter>(0x1)); EXPECT_EQ(Http2SettingsParameter::ENABLE_PUSH, static_cast<Http2SettingsParameter>(0x2)); EXPECT_EQ(Http2SettingsParameter::MAX_CONCURRENT_STREAMS, static_cast<Http2SettingsParameter>(0x3)); EXPECT_EQ(Http2SettingsParameter::INITIAL_WINDOW_SIZE, static_cast<Http2SettingsParameter>(0x4)); EXPECT_EQ(Http2SettingsParameter::MAX_FRAME_SIZE, static_cast<Http2SettingsParameter>(0x5)); EXPECT_EQ(Http2SettingsParameter::MAX_HEADER_LIST_SIZE, static_cast<Http2SettingsParameter>(0x6)); EXPECT_TRUE(IsSupportedHttp2SettingsParameter( Http2SettingsParameter::HEADER_TABLE_SIZE)); EXPECT_TRUE( IsSupportedHttp2SettingsParameter(Http2SettingsParameter::ENABLE_PUSH)); EXPECT_TRUE(IsSupportedHttp2SettingsParameter( Http2SettingsParameter::MAX_CONCURRENT_STREAMS)); EXPECT_TRUE(IsSupportedHttp2SettingsParameter( Http2SettingsParameter::INITIAL_WINDOW_SIZE)); EXPECT_TRUE(IsSupportedHttp2SettingsParameter( Http2SettingsParameter::MAX_FRAME_SIZE)); EXPECT_TRUE(IsSupportedHttp2SettingsParameter( Http2SettingsParameter::MAX_HEADER_LIST_SIZE)); EXPECT_FALSE(IsSupportedHttp2SettingsParameter( static_cast<Http2SettingsParameter>(0))); EXPECT_FALSE(IsSupportedHttp2SettingsParameter( static_cast<Http2SettingsParameter>(7))); } TEST(Http2ConstantsTest, Http2SettingsParameterToString) { EXPECT_EQ("HEADER_TABLE_SIZE", Http2SettingsParameterToString( Http2SettingsParameter::HEADER_TABLE_SIZE)); EXPECT_EQ("HEADER_TABLE_SIZE", Http2SettingsParameterToString(0x1)); EXPECT_EQ("ENABLE_PUSH", Http2SettingsParameterToString( Http2SettingsParameter::ENABLE_PUSH)); EXPECT_EQ("ENABLE_PUSH", Http2SettingsParameterToString(0x2)); EXPECT_EQ("MAX_CONCURRENT_STREAMS", Http2SettingsParameterToString( Http2SettingsParameter::MAX_CONCURRENT_STREAMS)); EXPECT_EQ("MAX_CONCURRENT_STREAMS", Http2SettingsParameterToString(0x3)); EXPECT_EQ("INITIAL_WINDOW_SIZE", Http2SettingsParameterToString( Http2SettingsParameter::INITIAL_WINDOW_SIZE)); EXPECT_EQ("INITIAL_WINDOW_SIZE", Http2SettingsParameterToString(0x4)); EXPECT_EQ("MAX_FRAME_SIZE", Http2SettingsParameterToString( Http2SettingsParameter::MAX_FRAME_SIZE)); EXPECT_EQ("MAX_FRAME_SIZE", Http2SettingsParameterToString(0x5)); EXPECT_EQ("MAX_HEADER_LIST_SIZE", Http2SettingsParameterToString( Http2SettingsParameter::MAX_HEADER_LIST_SIZE)); EXPECT_EQ("MAX_HEADER_LIST_SIZE", Http2SettingsParameterToString(0x6)); EXPECT_EQ("UnknownSettingsParameter(0x123)", Http2SettingsParameterToString(0x123)); } } } }
399
cpp
google/quiche
oghttp2_util
quiche/http2/adapter/oghttp2_util.cc
quiche/http2/adapter/oghttp2_util_test.cc
#ifndef QUICHE_HTTP2_ADAPTER_OGHTTP2_UTIL_H_ #define QUICHE_HTTP2_ADAPTER_OGHTTP2_UTIL_H_ #include "absl/types/span.h" #include "quiche/http2/adapter/http2_protocol.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/spdy/core/http2_header_block.h" namespace http2 { namespace adapter { QUICHE_EXPORT spdy::Http2HeaderBlock ToHeaderBlock( absl::Span<const Header> headers); } } #endif #include "quiche/http2/adapter/oghttp2_util.h" namespace http2 { namespace adapter { spdy::Http2HeaderBlock ToHeaderBlock(absl::Span<const Header> headers) { spdy::Http2HeaderBlock block; for (const Header& header : headers) { absl::string_view name = GetStringView(header.first).first; absl::string_view value = GetStringView(header.second).first; block.AppendValueOrAddHeader(name, value); } return block; } } }
#include "quiche/http2/adapter/oghttp2_util.h" #include <utility> #include <vector> #include "quiche/http2/adapter/http2_protocol.h" #include "quiche/http2/adapter/test_frame_sequence.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace adapter { namespace test { namespace { using HeaderPair = std::pair<absl::string_view, absl::string_view>; TEST(ToHeaderBlock, EmptySpan) { spdy::Http2HeaderBlock block = ToHeaderBlock({}); EXPECT_TRUE(block.empty()); } TEST(ToHeaderBlock, ExampleRequestHeaders) { const std::vector<HeaderPair> pairs = {{":authority", "example.com"}, {":method", "GET"}, {":path", "/example.html"}, {":scheme", "http"}, {"accept", "text/plain, text/html"}}; const std::vector<Header> headers = ToHeaders(pairs); spdy::Http2HeaderBlock block = ToHeaderBlock(headers); EXPECT_THAT(block, testing::ElementsAreArray(pairs)); } TEST(ToHeaderBlock, ExampleResponseHeaders) { const std::vector<HeaderPair> pairs = { {":status", "403"}, {"content-length", "1023"}, {"x-extra-info", "humblest apologies"}}; const std::vector<Header> headers = ToHeaders(pairs); spdy::Http2HeaderBlock block = ToHeaderBlock(headers); EXPECT_THAT(block, testing::ElementsAreArray(pairs)); } TEST(ToHeaderBlock, RepeatedRequestHeaderNames) { const std::vector<HeaderPair> pairs = { {":authority", "example.com"}, {":method", "GET"}, {":path", "/example.html"}, {":scheme", "http"}, {"cookie", "chocolate_chips=yes"}, {"accept", "text/plain, text/html"}, {"cookie", "raisins=no"}}; const std::vector<HeaderPair> expected = { {":authority", "example.com"}, {":method", "GET"}, {":path", "/example.html"}, {":scheme", "http"}, {"cookie", "chocolate_chips=yes; raisins=no"}, {"accept", "text/plain, text/html"}}; const std::vector<Header> headers = ToHeaders(pairs); spdy::Http2HeaderBlock block = ToHeaderBlock(headers); EXPECT_THAT(block, testing::ElementsAreArray(expected)); } TEST(ToHeaderBlock, RepeatedResponseHeaderNames) { const std::vector<HeaderPair> pairs = { {":status", "403"}, {"x-extra-info", "sorry"}, {"content-length", "1023"}, {"x-extra-info", "humblest apologies"}, {"content-length", "1024"}, {"set-cookie", "chocolate_chips=yes"}, {"set-cookie", "raisins=no"}}; const std::vector<HeaderPair> expected = { {":status", "403"}, {"x-extra-info", absl::string_view("sorry\0humblest apologies", 24)}, {"content-length", absl::string_view("1023" "\0" "1024", 9)}, {"set-cookie", absl::string_view("chocolate_chips=yes\0raisins=no", 30)}}; const std::vector<Header> headers = ToHeaders(pairs); spdy::Http2HeaderBlock block = ToHeaderBlock(headers); EXPECT_THAT(block, testing::ElementsAreArray(expected)); } } } } }