ID
stringlengths 36
36
| Language
stringclasses 1
value | Repository Name
stringclasses 13
values | File Name
stringlengths 2
48
| File Path in Repository
stringlengths 11
111
| File Path for Unit Test
stringlengths 13
116
| Code
stringlengths 0
278k
| Unit Test - (Ground Truth)
stringlengths 78
663k
| Code Url
stringlengths 91
198
| Test Code Url
stringlengths 93
203
| Commit Hash
stringclasses 13
values |
---|---|---|---|---|---|---|---|---|---|---|
2ddcade3-90af-477d-bd97-02873d860b31 | cpp | google/quiche | quic_chaos_protector | quiche/quic/core/quic_chaos_protector.cc | quiche/quic/core/quic_chaos_protector_test.cc | #include "quiche/quic/core/quic_chaos_protector.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <memory>
#include <optional>
#include "absl/strings/string_view.h"
#include "quiche/quic/core/crypto/quic_random.h"
#include "quiche/quic/core/frames/quic_crypto_frame.h"
#include "quiche/quic/core/frames/quic_frame.h"
#include "quiche/quic/core/frames/quic_padding_frame.h"
#include "quiche/quic/core/frames/quic_ping_frame.h"
#include "quiche/quic/core/quic_data_reader.h"
#include "quiche/quic/core/quic_data_writer.h"
#include "quiche/quic/core/quic_framer.h"
#include "quiche/quic/core/quic_packets.h"
#include "quiche/quic/core/quic_stream_frame_data_producer.h"
#include "quiche/quic/platform/api/quic_bug_tracker.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace quic {
QuicChaosProtector::QuicChaosProtector(const QuicCryptoFrame& crypto_frame,
int num_padding_bytes,
size_t packet_size, QuicFramer* framer,
QuicRandom* random)
: packet_size_(packet_size),
crypto_data_length_(crypto_frame.data_length),
crypto_buffer_offset_(crypto_frame.offset),
level_(crypto_frame.level),
remaining_padding_bytes_(num_padding_bytes),
framer_(framer),
random_(random) {
QUICHE_DCHECK_NE(framer_, nullptr);
QUICHE_DCHECK_NE(framer_->data_producer(), nullptr);
QUICHE_DCHECK_NE(random_, nullptr);
}
QuicChaosProtector::~QuicChaosProtector() { DeleteFrames(&frames_); }
std::optional<size_t> QuicChaosProtector::BuildDataPacket(
const QuicPacketHeader& header, char* buffer) {
if (!CopyCryptoDataToLocalBuffer()) {
return std::nullopt;
}
SplitCryptoFrame();
AddPingFrames();
SpreadPadding();
ReorderFrames();
return BuildPacket(header, buffer);
}
WriteStreamDataResult QuicChaosProtector::WriteStreamData(
QuicStreamId id, QuicStreamOffset offset, QuicByteCount data_length,
QuicDataWriter* ) {
QUIC_BUG(chaos stream) << "This should never be called; id " << id
<< " offset " << offset << " data_length "
<< data_length;
return STREAM_MISSING;
}
bool QuicChaosProtector::WriteCryptoData(EncryptionLevel level,
QuicStreamOffset offset,
QuicByteCount data_length,
QuicDataWriter* writer) {
if (level != level_) {
QUIC_BUG(chaos bad level) << "Unexpected " << level << " != " << level_;
return false;
}
if (offset < crypto_buffer_offset_ || data_length > crypto_data_length_ ||
offset - crypto_buffer_offset_ > crypto_data_length_ - data_length) {
QUIC_BUG(chaos bad lengths)
<< "Unexpected buffer_offset_ " << crypto_buffer_offset_ << " offset "
<< offset << " buffer_length_ " << crypto_data_length_
<< " data_length " << data_length;
return false;
}
writer->WriteBytes(&crypto_data_buffer_[offset - crypto_buffer_offset_],
data_length);
return true;
}
bool QuicChaosProtector::CopyCryptoDataToLocalBuffer() {
crypto_frame_buffer_ = std::make_unique<char[]>(packet_size_);
frames_.push_back(QuicFrame(
new QuicCryptoFrame(level_, crypto_buffer_offset_, crypto_data_length_)));
QuicDataWriter writer(packet_size_, crypto_frame_buffer_.get());
if (!framer_->AppendCryptoFrame(*frames_.front().crypto_frame, &writer)) {
QUIC_BUG(chaos write crypto data);
return false;
}
QuicDataReader reader(crypto_frame_buffer_.get(), writer.length());
uint64_t parsed_offset, parsed_length;
if (!reader.ReadVarInt62(&parsed_offset) ||
!reader.ReadVarInt62(&parsed_length)) {
QUIC_BUG(chaos parse crypto frame);
return false;
}
absl::string_view crypto_data = reader.ReadRemainingPayload();
crypto_data_buffer_ = crypto_data.data();
QUICHE_DCHECK_EQ(parsed_offset, crypto_buffer_offset_);
QUICHE_DCHECK_EQ(parsed_length, crypto_data_length_);
QUICHE_DCHECK_EQ(parsed_length, crypto_data.length());
return true;
}
void QuicChaosProtector::SplitCryptoFrame() {
const int max_overhead_of_adding_a_crypto_frame =
static_cast<int>(QuicFramer::GetMinCryptoFrameSize(
crypto_buffer_offset_ + crypto_data_length_, crypto_data_length_));
constexpr uint64_t kMaxAddedCryptoFrames = 10;
const uint64_t num_added_crypto_frames =
random_->InsecureRandUint64() % (kMaxAddedCryptoFrames + 1);
for (uint64_t i = 0; i < num_added_crypto_frames; i++) {
if (remaining_padding_bytes_ < max_overhead_of_adding_a_crypto_frame) {
break;
}
size_t frame_to_split_index =
random_->InsecureRandUint64() % frames_.size();
QuicCryptoFrame* frame_to_split =
frames_[frame_to_split_index].crypto_frame;
if (frame_to_split->data_length <= 1) {
continue;
}
const int frame_to_split_old_overhead =
static_cast<int>(QuicFramer::GetMinCryptoFrameSize(
frame_to_split->offset, frame_to_split->data_length));
const QuicPacketLength frame_to_split_new_data_length =
1 + (random_->InsecureRandUint64() % (frame_to_split->data_length - 1));
const QuicPacketLength new_frame_data_length =
frame_to_split->data_length - frame_to_split_new_data_length;
const QuicStreamOffset new_frame_offset =
frame_to_split->offset + frame_to_split_new_data_length;
frame_to_split->data_length -= new_frame_data_length;
frames_.push_back(QuicFrame(
new QuicCryptoFrame(level_, new_frame_offset, new_frame_data_length)));
const int frame_to_split_new_overhead =
static_cast<int>(QuicFramer::GetMinCryptoFrameSize(
frame_to_split->offset, frame_to_split->data_length));
const int new_frame_overhead =
static_cast<int>(QuicFramer::GetMinCryptoFrameSize(
new_frame_offset, new_frame_data_length));
QUICHE_DCHECK_LE(frame_to_split_new_overhead, frame_to_split_old_overhead);
remaining_padding_bytes_ -= new_frame_overhead;
remaining_padding_bytes_ -= frame_to_split_new_overhead;
remaining_padding_bytes_ += frame_to_split_old_overhead;
}
}
void QuicChaosProtector::AddPingFrames() {
if (remaining_padding_bytes_ == 0) {
return;
}
constexpr uint64_t kMaxAddedPingFrames = 10;
const uint64_t num_ping_frames =
random_->InsecureRandUint64() %
std::min<uint64_t>(kMaxAddedPingFrames, remaining_padding_bytes_);
for (uint64_t i = 0; i < num_ping_frames; i++) {
frames_.push_back(QuicFrame(QuicPingFrame()));
}
remaining_padding_bytes_ -= static_cast<int>(num_ping_frames);
}
void QuicChaosProtector::ReorderFrames() {
for (size_t i = frames_.size() - 1; i > 0; i--) {
std::swap(frames_[i], frames_[random_->InsecureRandUint64() % (i + 1)]);
}
}
void QuicChaosProtector::SpreadPadding() {
for (auto it = frames_.begin(); it != frames_.end(); ++it) {
const int padding_bytes_in_this_frame =
random_->InsecureRandUint64() % (remaining_padding_bytes_ + 1);
if (padding_bytes_in_this_frame <= 0) {
continue;
}
it = frames_.insert(
it, QuicFrame(QuicPaddingFrame(padding_bytes_in_this_frame)));
++it;
remaining_padding_bytes_ -= padding_bytes_in_this_frame;
}
if (remaining_padding_bytes_ > 0) {
frames_.push_back(QuicFrame(QuicPaddingFrame(remaining_padding_bytes_)));
}
}
std::optional<size_t> QuicChaosProtector::BuildPacket(
const QuicPacketHeader& header, char* buffer) {
QuicStreamFrameDataProducer* original_data_producer =
framer_->data_producer();
framer_->set_data_producer(this);
size_t length =
framer_->BuildDataPacket(header, frames_, buffer, packet_size_, level_);
framer_->set_data_producer(original_data_producer);
if (length == 0) {
return std::nullopt;
}
return length;
}
} | #include "quiche/quic/core/quic_chaos_protector.h"
#include <cstddef>
#include <memory>
#include <optional>
#include "absl/strings/string_view.h"
#include "quiche/quic/core/frames/quic_crypto_frame.h"
#include "quiche/quic/core/quic_connection_id.h"
#include "quiche/quic/core/quic_framer.h"
#include "quiche/quic/core/quic_packet_number.h"
#include "quiche/quic/core/quic_packets.h"
#include "quiche/quic/core/quic_stream_frame_data_producer.h"
#include "quiche/quic/core/quic_time.h"
#include "quiche/quic/core/quic_types.h"
#include "quiche/quic/core/quic_versions.h"
#include "quiche/quic/platform/api/quic_test.h"
#include "quiche/quic/test_tools/mock_random.h"
#include "quiche/quic/test_tools/quic_test_utils.h"
#include "quiche/quic/test_tools/simple_quic_framer.h"
namespace quic {
namespace test {
class QuicChaosProtectorTest : public QuicTestWithParam<ParsedQuicVersion>,
public QuicStreamFrameDataProducer {
public:
QuicChaosProtectorTest()
: version_(GetParam()),
framer_({version_}, QuicTime::Zero(), Perspective::IS_CLIENT,
kQuicDefaultConnectionIdLength),
validation_framer_({version_}),
random_(3),
level_(ENCRYPTION_INITIAL),
crypto_offset_(0),
crypto_data_length_(100),
crypto_frame_(level_, crypto_offset_, crypto_data_length_),
num_padding_bytes_(50),
packet_size_(1000),
packet_buffer_(std::make_unique<char[]>(packet_size_)) {
ReCreateChaosProtector();
}
void ReCreateChaosProtector() {
chaos_protector_ = std::make_unique<QuicChaosProtector>(
crypto_frame_, num_padding_bytes_, packet_size_,
SetupHeaderAndFramers(), &random_);
}
WriteStreamDataResult WriteStreamData(QuicStreamId ,
QuicStreamOffset ,
QuicByteCount ,
QuicDataWriter* ) override {
ADD_FAILURE() << "This should never be called";
return STREAM_MISSING;
}
bool WriteCryptoData(EncryptionLevel level, QuicStreamOffset offset,
QuicByteCount data_length,
QuicDataWriter* writer) override {
EXPECT_EQ(level, level);
EXPECT_EQ(offset, crypto_offset_);
EXPECT_EQ(data_length, crypto_data_length_);
for (QuicByteCount i = 0; i < data_length; i++) {
EXPECT_TRUE(writer->WriteUInt8(static_cast<uint8_t>(i & 0xFF)));
}
return true;
}
protected:
QuicFramer* SetupHeaderAndFramers() {
header_.destination_connection_id = TestConnectionId();
header_.destination_connection_id_included = CONNECTION_ID_PRESENT;
header_.source_connection_id = EmptyQuicConnectionId();
header_.source_connection_id_included = CONNECTION_ID_PRESENT;
header_.reset_flag = false;
header_.version_flag = true;
header_.has_possible_stateless_reset_token = false;
header_.packet_number_length = PACKET_4BYTE_PACKET_NUMBER;
header_.version = version_;
header_.packet_number = QuicPacketNumber(1);
header_.form = IETF_QUIC_LONG_HEADER_PACKET;
header_.long_packet_type = INITIAL;
header_.retry_token_length_length =
quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1;
header_.length_length = quiche::kQuicheDefaultLongHeaderLengthLength;
validation_framer_.framer()->SetInitialObfuscators(
header_.destination_connection_id);
framer_.SetInitialObfuscators(header_.destination_connection_id);
framer_.set_data_producer(this);
return &framer_;
}
void BuildEncryptAndParse() {
std::optional<size_t> length =
chaos_protector_->BuildDataPacket(header_, packet_buffer_.get());
ASSERT_TRUE(length.has_value());
ASSERT_GT(length.value(), 0u);
size_t encrypted_length = framer_.EncryptInPlace(
level_, header_.packet_number,
GetStartOfEncryptedData(framer_.transport_version(), header_),
length.value(), packet_size_, packet_buffer_.get());
ASSERT_GT(encrypted_length, 0u);
ASSERT_TRUE(validation_framer_.ProcessPacket(QuicEncryptedPacket(
absl::string_view(packet_buffer_.get(), encrypted_length))));
}
void ResetOffset(QuicStreamOffset offset) {
crypto_offset_ = offset;
crypto_frame_.offset = offset;
ReCreateChaosProtector();
}
void ResetLength(QuicByteCount length) {
crypto_data_length_ = length;
crypto_frame_.data_length = length;
ReCreateChaosProtector();
}
ParsedQuicVersion version_;
QuicPacketHeader header_;
QuicFramer framer_;
SimpleQuicFramer validation_framer_;
MockRandom random_;
EncryptionLevel level_;
QuicStreamOffset crypto_offset_;
QuicByteCount crypto_data_length_;
QuicCryptoFrame crypto_frame_;
int num_padding_bytes_;
size_t packet_size_;
std::unique_ptr<char[]> packet_buffer_;
std::unique_ptr<QuicChaosProtector> chaos_protector_;
};
namespace {
ParsedQuicVersionVector TestVersions() {
ParsedQuicVersionVector versions;
for (const ParsedQuicVersion& version : AllSupportedVersions()) {
if (version.UsesCryptoFrames()) {
versions.push_back(version);
}
}
return versions;
}
INSTANTIATE_TEST_SUITE_P(QuicChaosProtectorTests, QuicChaosProtectorTest,
::testing::ValuesIn(TestVersions()),
::testing::PrintToStringParamName());
TEST_P(QuicChaosProtectorTest, Main) {
BuildEncryptAndParse();
ASSERT_EQ(validation_framer_.crypto_frames().size(), 4u);
EXPECT_EQ(validation_framer_.crypto_frames()[0]->offset, 0u);
EXPECT_EQ(validation_framer_.crypto_frames()[0]->data_length, 1u);
ASSERT_EQ(validation_framer_.ping_frames().size(), 3u);
ASSERT_EQ(validation_framer_.padding_frames().size(), 7u);
EXPECT_EQ(validation_framer_.padding_frames()[0].num_padding_bytes, 3);
}
TEST_P(QuicChaosProtectorTest, DifferentRandom) {
random_.ResetBase(4);
BuildEncryptAndParse();
ASSERT_EQ(validation_framer_.crypto_frames().size(), 4u);
ASSERT_EQ(validation_framer_.ping_frames().size(), 4u);
ASSERT_EQ(validation_framer_.padding_frames().size(), 8u);
}
TEST_P(QuicChaosProtectorTest, RandomnessZero) {
random_.ResetBase(0);
BuildEncryptAndParse();
ASSERT_EQ(validation_framer_.crypto_frames().size(), 1u);
EXPECT_EQ(validation_framer_.crypto_frames()[0]->offset, crypto_offset_);
EXPECT_EQ(validation_framer_.crypto_frames()[0]->data_length,
crypto_data_length_);
ASSERT_EQ(validation_framer_.ping_frames().size(), 0u);
ASSERT_EQ(validation_framer_.padding_frames().size(), 1u);
}
TEST_P(QuicChaosProtectorTest, Offset) {
ResetOffset(123);
BuildEncryptAndParse();
ASSERT_EQ(validation_framer_.crypto_frames().size(), 4u);
EXPECT_EQ(validation_framer_.crypto_frames()[0]->offset, crypto_offset_);
EXPECT_EQ(validation_framer_.crypto_frames()[0]->data_length, 1u);
ASSERT_EQ(validation_framer_.ping_frames().size(), 3u);
ASSERT_EQ(validation_framer_.padding_frames().size(), 7u);
EXPECT_EQ(validation_framer_.padding_frames()[0].num_padding_bytes, 3);
}
TEST_P(QuicChaosProtectorTest, OffsetAndRandomnessZero) {
ResetOffset(123);
random_.ResetBase(0);
BuildEncryptAndParse();
ASSERT_EQ(validation_framer_.crypto_frames().size(), 1u);
EXPECT_EQ(validation_framer_.crypto_frames()[0]->offset, crypto_offset_);
EXPECT_EQ(validation_framer_.crypto_frames()[0]->data_length,
crypto_data_length_);
ASSERT_EQ(validation_framer_.ping_frames().size(), 0u);
ASSERT_EQ(validation_framer_.padding_frames().size(), 1u);
}
TEST_P(QuicChaosProtectorTest, ZeroRemainingBytesAfterSplit) {
QuicPacketLength new_length = 63;
num_padding_bytes_ = QuicFramer::GetMinCryptoFrameSize(
crypto_frame_.offset + new_length, new_length);
ResetLength(new_length);
BuildEncryptAndParse();
ASSERT_EQ(validation_framer_.crypto_frames().size(), 2u);
EXPECT_EQ(validation_framer_.crypto_frames()[0]->offset, crypto_offset_);
EXPECT_EQ(validation_framer_.crypto_frames()[0]->data_length, 4);
EXPECT_EQ(validation_framer_.crypto_frames()[1]->offset, crypto_offset_ + 4);
EXPECT_EQ(validation_framer_.crypto_frames()[1]->data_length,
crypto_data_length_ - 4);
ASSERT_EQ(validation_framer_.ping_frames().size(), 0u);
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_chaos_protector.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_chaos_protector_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
c91a26a0-92ce-4e83-b438-5e1d0370fa81 | cpp | google/quiche | quic_crypto_server_stream | quiche/quic/core/quic_crypto_server_stream.cc | quiche/quic/core/quic_crypto_server_stream_test.cc | #include "quiche/quic/core/quic_crypto_server_stream.h"
#include <memory>
#include <string>
#include <utility>
#include "absl/base/macros.h"
#include "absl/strings/string_view.h"
#include "openssl/sha.h"
#include "quiche/quic/core/quic_types.h"
#include "quiche/quic/platform/api/quic_flag_utils.h"
#include "quiche/quic/platform/api/quic_testvalue.h"
#include "quiche/common/platform/api/quiche_logging.h"
#include "quiche/common/quiche_text_utils.h"
namespace quic {
class QuicCryptoServerStream::ProcessClientHelloCallback
: public ProcessClientHelloResultCallback {
public:
ProcessClientHelloCallback(
QuicCryptoServerStream* parent,
const quiche::QuicheReferenceCountedPointer<
ValidateClientHelloResultCallback::Result>& result)
: parent_(parent), result_(result) {}
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> proof_source_details) override {
if (parent_ == nullptr) {
return;
}
parent_->FinishProcessingHandshakeMessageAfterProcessClientHello(
*result_, error, error_details, std::move(message),
std::move(diversification_nonce), std::move(proof_source_details));
}
void Cancel() { parent_ = nullptr; }
private:
QuicCryptoServerStream* parent_;
quiche::QuicheReferenceCountedPointer<
ValidateClientHelloResultCallback::Result>
result_;
};
QuicCryptoServerStream::QuicCryptoServerStream(
const QuicCryptoServerConfig* crypto_config,
QuicCompressedCertsCache* compressed_certs_cache, QuicSession* session,
QuicCryptoServerStreamBase::Helper* helper)
: QuicCryptoServerStreamBase(session),
QuicCryptoHandshaker(this, session),
session_(session),
delegate_(session),
crypto_config_(crypto_config),
compressed_certs_cache_(compressed_certs_cache),
signed_config_(new QuicSignedServerConfig),
helper_(helper),
num_handshake_messages_(0),
num_handshake_messages_with_server_nonces_(0),
send_server_config_update_cb_(nullptr),
num_server_config_update_messages_sent_(0),
zero_rtt_attempted_(false),
chlo_packet_size_(0),
validate_client_hello_cb_(nullptr),
encryption_established_(false),
one_rtt_keys_available_(false),
one_rtt_packet_decrypted_(false),
crypto_negotiated_params_(new QuicCryptoNegotiatedParameters) {}
QuicCryptoServerStream::~QuicCryptoServerStream() {
CancelOutstandingCallbacks();
}
void QuicCryptoServerStream::CancelOutstandingCallbacks() {
if (validate_client_hello_cb_ != nullptr) {
validate_client_hello_cb_->Cancel();
validate_client_hello_cb_ = nullptr;
}
if (send_server_config_update_cb_ != nullptr) {
send_server_config_update_cb_->Cancel();
send_server_config_update_cb_ = nullptr;
}
if (std::shared_ptr<ProcessClientHelloCallback> cb =
process_client_hello_cb_.lock()) {
cb->Cancel();
process_client_hello_cb_.reset();
}
}
void QuicCryptoServerStream::OnHandshakeMessage(
const CryptoHandshakeMessage& message) {
QuicCryptoHandshaker::OnHandshakeMessage(message);
++num_handshake_messages_;
chlo_packet_size_ = session()->connection()->GetCurrentPacket().length();
if (one_rtt_keys_available_) {
OnUnrecoverableError(QUIC_CRYPTO_MESSAGE_AFTER_HANDSHAKE_COMPLETE,
"Unexpected handshake message from client");
return;
}
if (message.tag() != kCHLO) {
OnUnrecoverableError(QUIC_INVALID_CRYPTO_MESSAGE_TYPE,
"Handshake packet not CHLO");
return;
}
if (validate_client_hello_cb_ != nullptr ||
!process_client_hello_cb_.expired()) {
OnUnrecoverableError(QUIC_CRYPTO_MESSAGE_WHILE_VALIDATING_CLIENT_HELLO,
"Unexpected handshake message while processing CHLO");
return;
}
chlo_hash_ =
CryptoUtils::HashHandshakeMessage(message, Perspective::IS_SERVER);
std::unique_ptr<ValidateCallback> cb(new ValidateCallback(this));
QUICHE_DCHECK(validate_client_hello_cb_ == nullptr);
QUICHE_DCHECK(process_client_hello_cb_.expired());
validate_client_hello_cb_ = cb.get();
crypto_config_->ValidateClientHello(
message, GetClientAddress(), session()->connection()->self_address(),
transport_version(), session()->connection()->clock(), signed_config_,
std::move(cb));
}
void QuicCryptoServerStream::FinishProcessingHandshakeMessage(
quiche::QuicheReferenceCountedPointer<
ValidateClientHelloResultCallback::Result>
result,
std::unique_ptr<ProofSource::Details> details) {
QUICHE_DCHECK(validate_client_hello_cb_ != nullptr);
QUICHE_DCHECK(process_client_hello_cb_.expired());
validate_client_hello_cb_ = nullptr;
auto cb = std::make_shared<ProcessClientHelloCallback>(this, result);
process_client_hello_cb_ = cb;
ProcessClientHello(result, std::move(details), std::move(cb));
}
void QuicCryptoServerStream::
FinishProcessingHandshakeMessageAfterProcessClientHello(
const ValidateClientHelloResultCallback::Result& result,
QuicErrorCode error, const std::string& error_details,
std::unique_ptr<CryptoHandshakeMessage> reply,
std::unique_ptr<DiversificationNonce> diversification_nonce,
std::unique_ptr<ProofSource::Details> proof_source_details) {
QUICHE_DCHECK(!process_client_hello_cb_.expired());
QUICHE_DCHECK(validate_client_hello_cb_ == nullptr);
process_client_hello_cb_.reset();
proof_source_details_ = std::move(proof_source_details);
AdjustTestValue("quic::QuicCryptoServerStream::after_process_client_hello",
session());
if (!session()->connection()->connected()) {
QUIC_CODE_COUNT(quic_crypto_disconnected_after_process_client_hello);
QUIC_LOG_FIRST_N(INFO, 10)
<< "After processing CHLO, QUIC connection has been closed with code "
<< session()->error() << ", details: " << session()->error_details();
return;
}
const CryptoHandshakeMessage& message = result.client_hello;
if (error != QUIC_NO_ERROR) {
OnUnrecoverableError(error, error_details);
return;
}
if (reply->tag() != kSHLO) {
session()->connection()->set_fully_pad_crypto_handshake_packets(
crypto_config_->pad_rej());
SendHandshakeMessage(*reply, ENCRYPTION_INITIAL);
return;
}
QuicConfig* config = session()->config();
OverrideQuicConfigDefaults(config);
std::string process_error_details;
const QuicErrorCode process_error =
config->ProcessPeerHello(message, CLIENT, &process_error_details);
if (process_error != QUIC_NO_ERROR) {
OnUnrecoverableError(process_error, process_error_details);
return;
}
session()->OnConfigNegotiated();
config->ToHandshakeMessage(reply.get(), session()->transport_version());
delegate_->OnNewEncryptionKeyAvailable(
ENCRYPTION_ZERO_RTT,
std::move(crypto_negotiated_params_->initial_crypters.encrypter));
delegate_->OnNewDecryptionKeyAvailable(
ENCRYPTION_ZERO_RTT,
std::move(crypto_negotiated_params_->initial_crypters.decrypter),
false,
false);
delegate_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
delegate_->DiscardOldDecryptionKey(ENCRYPTION_INITIAL);
session()->connection()->SetDiversificationNonce(*diversification_nonce);
session()->connection()->set_fully_pad_crypto_handshake_packets(
crypto_config_->pad_shlo());
SendHandshakeMessage(*reply, ENCRYPTION_ZERO_RTT);
delegate_->OnNewEncryptionKeyAvailable(
ENCRYPTION_FORWARD_SECURE,
std::move(crypto_negotiated_params_->forward_secure_crypters.encrypter));
delegate_->OnNewDecryptionKeyAvailable(
ENCRYPTION_FORWARD_SECURE,
std::move(crypto_negotiated_params_->forward_secure_crypters.decrypter),
true,
false);
encryption_established_ = true;
one_rtt_keys_available_ = true;
delegate_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
delegate_->DiscardOldEncryptionKey(ENCRYPTION_INITIAL);
}
void QuicCryptoServerStream::SendServerConfigUpdate(
const CachedNetworkParameters* cached_network_params) {
if (!one_rtt_keys_available_) {
return;
}
if (send_server_config_update_cb_ != nullptr) {
QUIC_DVLOG(1)
<< "Skipped server config update since one is already in progress";
return;
}
std::unique_ptr<SendServerConfigUpdateCallback> cb(
new SendServerConfigUpdateCallback(this));
send_server_config_update_cb_ = cb.get();
crypto_config_->BuildServerConfigUpdateMessage(
session()->transport_version(), chlo_hash_,
previous_source_address_tokens_, session()->connection()->self_address(),
GetClientAddress(), session()->connection()->clock(),
session()->connection()->random_generator(), compressed_certs_cache_,
*crypto_negotiated_params_, cached_network_params, std::move(cb));
}
QuicCryptoServerStream::SendServerConfigUpdateCallback::
SendServerConfigUpdateCallback(QuicCryptoServerStream* parent)
: parent_(parent) {}
void QuicCryptoServerStream::SendServerConfigUpdateCallback::Cancel() {
parent_ = nullptr;
}
void QuicCryptoServerStream::SendServerConfigUpdateCallback::Run(
bool ok, const CryptoHandshakeMessage& message) {
if (parent_ == nullptr) {
return;
}
parent_->FinishSendServerConfigUpdate(ok, message);
}
void QuicCryptoServerStream::FinishSendServerConfigUpdate(
bool ok, const CryptoHandshakeMessage& message) {
QUICHE_DCHECK(send_server_config_update_cb_ != nullptr);
send_server_config_update_cb_ = nullptr;
if (!ok) {
QUIC_DVLOG(1) << "Server: Failed to build server config update (SCUP)!";
return;
}
QUIC_DVLOG(1) << "Server: Sending server config update: "
<< message.DebugString();
SendHandshakeMessage(message, ENCRYPTION_FORWARD_SECURE);
++num_server_config_update_messages_sent_;
}
bool QuicCryptoServerStream::DisableResumption() {
QUICHE_DCHECK(false) << "Not supported for QUIC crypto.";
return false;
}
bool QuicCryptoServerStream::IsZeroRtt() const {
return num_handshake_messages_ == 1 &&
num_handshake_messages_with_server_nonces_ == 0;
}
bool QuicCryptoServerStream::IsResumption() const {
return IsZeroRtt();
}
int QuicCryptoServerStream::NumServerConfigUpdateMessagesSent() const {
return num_server_config_update_messages_sent_;
}
const CachedNetworkParameters*
QuicCryptoServerStream::PreviousCachedNetworkParams() const {
return previous_cached_network_params_.get();
}
bool QuicCryptoServerStream::ResumptionAttempted() const {
return zero_rtt_attempted_;
}
bool QuicCryptoServerStream::EarlyDataAttempted() const {
QUICHE_DCHECK(false) << "Not supported for QUIC crypto.";
return zero_rtt_attempted_;
}
void QuicCryptoServerStream::SetPreviousCachedNetworkParams(
CachedNetworkParameters cached_network_params) {
previous_cached_network_params_.reset(
new CachedNetworkParameters(cached_network_params));
}
void QuicCryptoServerStream::OnPacketDecrypted(EncryptionLevel level) {
if (level == ENCRYPTION_FORWARD_SECURE) {
one_rtt_packet_decrypted_ = true;
delegate_->NeuterHandshakeData();
}
}
void QuicCryptoServerStream::OnHandshakeDoneReceived() { QUICHE_DCHECK(false); }
void QuicCryptoServerStream::OnNewTokenReceived(absl::string_view ) {
QUICHE_DCHECK(false);
}
std::string QuicCryptoServerStream::GetAddressToken(
const CachedNetworkParameters* ) const {
QUICHE_DCHECK(false);
return "";
}
bool QuicCryptoServerStream::ValidateAddressToken(
absl::string_view ) const {
QUICHE_DCHECK(false);
return false;
}
bool QuicCryptoServerStream::ShouldSendExpectCTHeader() const {
return signed_config_->proof.send_expect_ct_header;
}
bool QuicCryptoServerStream::DidCertMatchSni() const {
return signed_config_->proof.cert_matched_sni;
}
const ProofSource::Details* QuicCryptoServerStream::ProofSourceDetails() const {
return proof_source_details_.get();
}
bool QuicCryptoServerStream::GetBase64SHA256ClientChannelID(
std::string* output) const {
if (!encryption_established() ||
crypto_negotiated_params_->channel_id.empty()) {
return false;
}
const std::string& channel_id(crypto_negotiated_params_->channel_id);
uint8_t digest[SHA256_DIGEST_LENGTH];
SHA256(reinterpret_cast<const uint8_t*>(channel_id.data()), channel_id.size(),
digest);
quiche::QuicheTextUtils::Base64Encode(digest, ABSL_ARRAYSIZE(digest), output);
return true;
}
ssl_early_data_reason_t QuicCryptoServerStream::EarlyDataReason() const {
if (IsZeroRtt()) {
return ssl_early_data_accepted;
}
if (zero_rtt_attempted_) {
return ssl_early_data_session_not_resumed;
}
return ssl_early_data_no_session_offered;
}
bool QuicCryptoServerStream::encryption_established() const {
return encryption_established_;
}
bool QuicCryptoServerStream::one_rtt_keys_available() const {
return one_rtt_keys_available_;
}
const QuicCryptoNegotiatedParameters&
QuicCryptoServerStream::crypto_negotiated_params() const {
return *crypto_negotiated_params_;
}
CryptoMessageParser* QuicCryptoServerStream::crypto_message_parser() {
return QuicCryptoHandshaker::crypto_message_parser();
}
HandshakeState QuicCryptoServerStream::GetHandshakeState() const {
return one_rtt_packet_decrypted_ ? HANDSHAKE_COMPLETE : HANDSHAKE_START;
}
void QuicCryptoServerStream::SetServerApplicationStateForResumption(
std::unique_ptr<ApplicationState> ) {
}
size_t QuicCryptoServerStream::BufferSizeLimitForLevel(
EncryptionLevel level) const {
return QuicCryptoHandshaker::BufferSizeLimitForLevel(level);
}
std::unique_ptr<QuicDecrypter>
QuicCryptoServerStream::AdvanceKeysAndCreateCurrentOneRttDecrypter() {
QUICHE_DCHECK(false);
return nullptr;
}
std::unique_ptr<QuicEncrypter>
QuicCryptoServerStream::CreateCurrentOneRttEncrypter() {
QUICHE_DCHECK(false);
return nullptr;
}
void QuicCryptoServerStream::ProcessClientHello(
quiche::QuicheReferenceCountedPointer<
ValidateClientHelloResultCallback::Result>
result,
std::unique_ptr<ProofSource::Details> proof_source_details,
std::shared_ptr<ProcessClientHelloResultCallback> done_cb) {
proof_source_details_ = std::move(proof_source_details);
const CryptoHandshakeMessage& message = result->client_hello;
std::string error_details;
if (!helper_->CanAcceptClientHello(
message, GetClientAddress(), session()->connection()->peer_address(),
session()->connection()->self_address(), &error_details)) {
done_cb->Run(QUIC_HANDSHAKE_FAILED, error_details, nullptr, nullptr,
nullptr);
return;
}
absl::string_view user_agent_id;
message.GetStringPiece(quic::kUAID, &user_agent_id);
if (!session()->user_agent_id().has_value() && !user_agent_id.empty()) {
session()->SetUserAgentId(std::string(user_agent_id));
}
if (!result->info.server_nonce.empty()) {
++num_handshake_messages_with_server_nonces_;
}
if (num_handshake_messages_ == 1) {
absl::string_view public_value;
zero_rtt_attempted_ = message.GetStringPiece(kPUBS, &public_value);
}
if (result->cached_network_params.bandwidth_estimate_bytes_per_second() > 0) {
previous_cached_network_params_.reset(
new CachedNetworkParameters(result->cached_network_params));
}
previous_source_address_tokens_ = result->info.source_address_tokens;
QuicConnection* connection = session()->connection();
crypto_config_->ProcessClientHello(
result, false, connection->connection_id(),
connection->self_address(), GetClientAddress(), connection->version(),
session()->supported_versions(), connection->clock(),
connection->random_generator(), compressed_certs_cache_,
crypto_negotiated_params_, signed_config_,
QuicCryptoStream::CryptoMessageFramingOverhead(
transport_version(), connection->connection_id()),
chlo_packet_size_, std::move(done_cb));
}
void QuicCryptoServerStream::OverrideQuicConfigDefaults(
QuicConfig* ) {}
QuicCryptoServerStream::ValidateCallback::ValidateCallback(
QuicCryptoServerStream* parent)
: parent_(parent) {}
void QuicCryptoServerStream::ValidateCallback::Cancel() { parent_ = nullptr; }
void QuicCryptoServerStream::ValidateCallback::Run(
quiche::QuicheReferenceCountedPointer<Result> result,
std::unique_ptr<ProofSource::Details> details) {
if (parent_ != nullptr) {
parent_->FinishProcessingHandshakeMessage(std::move(result),
std::move(details));
}
}
const QuicSocketAddress QuicCryptoServerStream::GetClientAddress() {
return session()->connection()->peer_address();
}
SSL* QuicCryptoServerStream::GetSsl() const { return nullptr; }
bool QuicCryptoServerStream::IsCryptoFrameExpectedForEncryptionLevel(
EncryptionLevel ) const {
return true;
}
EncryptionLevel
QuicCryptoServerStream::GetEncryptionLevelToSendCryptoDataOfSpace(
PacketNumberSpace space) const {
if (space == INITIAL_DATA) {
return ENCRYPTION_INITIAL;
}
if (space == APPLICATION_DATA) {
return ENCRYPTION_ZERO_RTT;
}
QUICHE_DCHECK(false);
return NUM_ENCRYPTION_LEVELS;
}
} | #include <algorithm>
#include <map>
#include <memory>
#include <utility>
#include <vector>
#include "absl/strings/string_view.h"
#include "quiche/quic/core/crypto/aes_128_gcm_12_encrypter.h"
#include "quiche/quic/core/crypto/crypto_framer.h"
#include "quiche/quic/core/crypto/crypto_handshake.h"
#include "quiche/quic/core/crypto/crypto_protocol.h"
#include "quiche/quic/core/crypto/crypto_utils.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/quic_crypto_client_stream.h"
#include "quiche/quic/core/quic_crypto_server_stream_base.h"
#include "quiche/quic/core/quic_packets.h"
#include "quiche/quic/core/quic_session.h"
#include "quiche/quic/core/quic_utils.h"
#include "quiche/quic/core/quic_versions.h"
#include "quiche/quic/platform/api/quic_flags.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/failing_proof_source.h"
#include "quiche/quic/test_tools/fake_proof_source.h"
#include "quiche/quic/test_tools/quic_crypto_server_config_peer.h"
#include "quiche/quic/test_tools/quic_test_utils.h"
namespace quic {
class QuicConnection;
class QuicStream;
}
using testing::_;
using testing::NiceMock;
namespace quic {
namespace test {
namespace {
const char kServerHostname[] = "test.example.com";
const uint16_t kServerPort = 443;
class QuicCryptoServerStreamTest : public QuicTest {
public:
QuicCryptoServerStreamTest()
: QuicCryptoServerStreamTest(crypto_test_utils::ProofSourceForTesting()) {
}
explicit QuicCryptoServerStreamTest(std::unique_ptr<ProofSource> proof_source)
: server_crypto_config_(
QuicCryptoServerConfig::TESTING, QuicRandom::GetInstance(),
std::move(proof_source), KeyExchangeSource::Default()),
server_compressed_certs_cache_(
QuicCompressedCertsCache::kQuicCompressedCertsCacheSize),
server_id_(kServerHostname, kServerPort),
client_crypto_config_(crypto_test_utils::ProofVerifierForTesting()) {}
void Initialize() { InitializeServer(); }
~QuicCryptoServerStreamTest() override {
server_session_.reset();
client_session_.reset();
helpers_.clear();
alarm_factories_.clear();
}
void InitializeServer() {
TestQuicSpdyServerSession* server_session = nullptr;
helpers_.push_back(std::make_unique<NiceMock<MockQuicConnectionHelper>>());
alarm_factories_.push_back(std::make_unique<MockAlarmFactory>());
CreateServerSessionForTest(
server_id_, QuicTime::Delta::FromSeconds(100000), supported_versions_,
helpers_.back().get(), alarm_factories_.back().get(),
&server_crypto_config_, &server_compressed_certs_cache_,
&server_connection_, &server_session);
QUICHE_CHECK(server_session);
server_session_.reset(server_session);
EXPECT_CALL(*server_session_->helper(), CanAcceptClientHello(_, _, _, _, _))
.Times(testing::AnyNumber());
EXPECT_CALL(*server_session_, SelectAlpn(_))
.WillRepeatedly([this](const std::vector<absl::string_view>& alpns) {
return std::find(
alpns.cbegin(), alpns.cend(),
AlpnForVersion(server_session_->connection()->version()));
});
crypto_test_utils::SetupCryptoServerConfigForTest(
server_connection_->clock(), server_connection_->random_generator(),
&server_crypto_config_);
}
QuicCryptoServerStreamBase* server_stream() {
return server_session_->GetMutableCryptoStream();
}
QuicCryptoClientStream* client_stream() {
return client_session_->GetMutableCryptoStream();
}
void InitializeFakeClient() {
TestQuicSpdyClientSession* client_session = nullptr;
helpers_.push_back(std::make_unique<NiceMock<MockQuicConnectionHelper>>());
alarm_factories_.push_back(std::make_unique<MockAlarmFactory>());
CreateClientSessionForTest(
server_id_, QuicTime::Delta::FromSeconds(100000), supported_versions_,
helpers_.back().get(), alarm_factories_.back().get(),
&client_crypto_config_, &client_connection_, &client_session);
QUICHE_CHECK(client_session);
client_session_.reset(client_session);
}
int CompleteCryptoHandshake() {
QUICHE_CHECK(server_connection_);
QUICHE_CHECK(server_session_ != nullptr);
return crypto_test_utils::HandshakeWithFakeClient(
helpers_.back().get(), alarm_factories_.back().get(),
server_connection_, server_stream(), server_id_, client_options_,
"");
}
void AdvanceHandshakeWithFakeClient() {
QUICHE_CHECK(server_connection_);
QUICHE_CHECK(client_session_ != nullptr);
EXPECT_CALL(*client_session_, OnProofValid(_)).Times(testing::AnyNumber());
EXPECT_CALL(*client_session_, OnProofVerifyDetailsAvailable(_))
.Times(testing::AnyNumber());
EXPECT_CALL(*client_connection_, OnCanWrite()).Times(testing::AnyNumber());
EXPECT_CALL(*server_connection_, OnCanWrite()).Times(testing::AnyNumber());
client_stream()->CryptoConnect();
crypto_test_utils::AdvanceHandshake(client_connection_, client_stream(), 0,
server_connection_, server_stream(), 0);
}
protected:
std::vector<std::unique_ptr<MockQuicConnectionHelper>> helpers_;
std::vector<std::unique_ptr<MockAlarmFactory>> alarm_factories_;
PacketSavingConnection* server_connection_;
std::unique_ptr<TestQuicSpdyServerSession> server_session_;
QuicCryptoServerConfig server_crypto_config_;
QuicCompressedCertsCache server_compressed_certs_cache_;
QuicServerId server_id_;
PacketSavingConnection* client_connection_;
QuicCryptoClientConfig client_crypto_config_;
std::unique_ptr<TestQuicSpdyClientSession> client_session_;
CryptoHandshakeMessage message_;
crypto_test_utils::FakeClientOptions client_options_;
ParsedQuicVersionVector supported_versions_ =
AllSupportedVersionsWithQuicCrypto();
};
TEST_F(QuicCryptoServerStreamTest, NotInitiallyConected) {
Initialize();
EXPECT_FALSE(server_stream()->encryption_established());
EXPECT_FALSE(server_stream()->one_rtt_keys_available());
}
TEST_F(QuicCryptoServerStreamTest, ConnectedAfterCHLO) {
Initialize();
EXPECT_EQ(2, CompleteCryptoHandshake());
EXPECT_TRUE(server_stream()->encryption_established());
EXPECT_TRUE(server_stream()->one_rtt_keys_available());
}
TEST_F(QuicCryptoServerStreamTest, ForwardSecureAfterCHLO) {
Initialize();
InitializeFakeClient();
AdvanceHandshakeWithFakeClient();
EXPECT_FALSE(server_stream()->encryption_established());
EXPECT_FALSE(server_stream()->one_rtt_keys_available());
InitializeServer();
InitializeFakeClient();
AdvanceHandshakeWithFakeClient();
if (GetQuicReloadableFlag(quic_require_handshake_confirmation)) {
crypto_test_utils::AdvanceHandshake(client_connection_, client_stream(), 0,
server_connection_, server_stream(), 0);
}
EXPECT_TRUE(server_stream()->encryption_established());
EXPECT_TRUE(server_stream()->one_rtt_keys_available());
EXPECT_EQ(ENCRYPTION_FORWARD_SECURE,
server_session_->connection()->encryption_level());
}
TEST_F(QuicCryptoServerStreamTest, ZeroRTT) {
Initialize();
InitializeFakeClient();
AdvanceHandshakeWithFakeClient();
EXPECT_FALSE(server_stream()->ResumptionAttempted());
QUIC_LOG(INFO) << "Resetting for 0-RTT handshake attempt";
InitializeFakeClient();
InitializeServer();
EXPECT_CALL(*client_session_, OnProofValid(_)).Times(testing::AnyNumber());
EXPECT_CALL(*client_session_, OnProofVerifyDetailsAvailable(_))
.Times(testing::AnyNumber());
EXPECT_CALL(*client_connection_, OnCanWrite()).Times(testing::AnyNumber());
client_stream()->CryptoConnect();
EXPECT_CALL(*client_session_, OnProofValid(_)).Times(testing::AnyNumber());
EXPECT_CALL(*client_session_, OnProofVerifyDetailsAvailable(_))
.Times(testing::AnyNumber());
EXPECT_CALL(*client_connection_, OnCanWrite()).Times(testing::AnyNumber());
crypto_test_utils::CommunicateHandshakeMessages(
client_connection_, client_stream(), server_connection_, server_stream());
EXPECT_EQ(
(GetQuicReloadableFlag(quic_require_handshake_confirmation) ? 2 : 1),
client_stream()->num_sent_client_hellos());
EXPECT_TRUE(server_stream()->ResumptionAttempted());
}
TEST_F(QuicCryptoServerStreamTest, FailByPolicy) {
Initialize();
InitializeFakeClient();
EXPECT_CALL(*server_session_->helper(), CanAcceptClientHello(_, _, _, _, _))
.WillOnce(testing::Return(false));
EXPECT_CALL(*server_connection_,
CloseConnection(QUIC_HANDSHAKE_FAILED, _, _));
AdvanceHandshakeWithFakeClient();
}
TEST_F(QuicCryptoServerStreamTest, MessageAfterHandshake) {
Initialize();
CompleteCryptoHandshake();
EXPECT_CALL(
*server_connection_,
CloseConnection(QUIC_CRYPTO_MESSAGE_AFTER_HANDSHAKE_COMPLETE, _, _));
message_.set_tag(kCHLO);
crypto_test_utils::SendHandshakeMessageToStream(server_stream(), message_,
Perspective::IS_CLIENT);
}
TEST_F(QuicCryptoServerStreamTest, BadMessageType) {
Initialize();
message_.set_tag(kSHLO);
EXPECT_CALL(*server_connection_,
CloseConnection(QUIC_INVALID_CRYPTO_MESSAGE_TYPE, _, _));
crypto_test_utils::SendHandshakeMessageToStream(server_stream(), message_,
Perspective::IS_SERVER);
}
TEST_F(QuicCryptoServerStreamTest, OnlySendSCUPAfterHandshakeComplete) {
Initialize();
server_stream()->SendServerConfigUpdate(nullptr);
EXPECT_EQ(0, server_stream()->NumServerConfigUpdateMessagesSent());
}
TEST_F(QuicCryptoServerStreamTest, SendSCUPAfterHandshakeComplete) {
Initialize();
InitializeFakeClient();
AdvanceHandshakeWithFakeClient();
InitializeServer();
InitializeFakeClient();
AdvanceHandshakeWithFakeClient();
if (GetQuicReloadableFlag(quic_require_handshake_confirmation)) {
crypto_test_utils::AdvanceHandshake(client_connection_, client_stream(), 0,
server_connection_, server_stream(), 0);
}
EXPECT_CALL(*client_connection_, CloseConnection(_, _, _)).Times(0);
server_stream()->SendServerConfigUpdate(nullptr);
crypto_test_utils::AdvanceHandshake(client_connection_, client_stream(), 1,
server_connection_, server_stream(), 1);
EXPECT_EQ(1, server_stream()->NumServerConfigUpdateMessagesSent());
EXPECT_EQ(1, client_stream()->num_scup_messages_received());
}
class QuicCryptoServerStreamTestWithFailingProofSource
: public QuicCryptoServerStreamTest {
public:
QuicCryptoServerStreamTestWithFailingProofSource()
: QuicCryptoServerStreamTest(
std::unique_ptr<FailingProofSource>(new FailingProofSource)) {}
};
TEST_F(QuicCryptoServerStreamTestWithFailingProofSource, Test) {
Initialize();
InitializeFakeClient();
EXPECT_CALL(*server_session_->helper(), CanAcceptClientHello(_, _, _, _, _))
.WillOnce(testing::Return(true));
EXPECT_CALL(*server_connection_,
CloseConnection(QUIC_HANDSHAKE_FAILED, "Failed to get proof", _));
AdvanceHandshakeWithFakeClient();
EXPECT_FALSE(server_stream()->encryption_established());
EXPECT_FALSE(server_stream()->one_rtt_keys_available());
}
class QuicCryptoServerStreamTestWithFakeProofSource
: public QuicCryptoServerStreamTest {
public:
QuicCryptoServerStreamTestWithFakeProofSource()
: QuicCryptoServerStreamTest(
std::unique_ptr<FakeProofSource>(new FakeProofSource)),
crypto_config_peer_(&server_crypto_config_) {}
FakeProofSource* GetFakeProofSource() const {
return static_cast<FakeProofSource*>(crypto_config_peer_.GetProofSource());
}
protected:
QuicCryptoServerConfigPeer crypto_config_peer_;
};
TEST_F(QuicCryptoServerStreamTestWithFakeProofSource, MultipleChlo) {
Initialize();
GetFakeProofSource()->Activate();
EXPECT_CALL(*server_session_->helper(), CanAcceptClientHello(_, _, _, _, _))
.WillOnce(testing::Return(true));
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);
MockClock clock;
CryptoHandshakeMessage chlo = crypto_test_utils::GenerateDefaultInchoateCHLO(
&clock, transport_version, &server_crypto_config_);
crypto_test_utils::SendHandshakeMessageToStream(server_stream(), chlo,
Perspective::IS_CLIENT);
EXPECT_EQ(GetFakeProofSource()->NumPendingCallbacks(), 1);
EXPECT_CALL(
*server_connection_,
CloseConnection(QUIC_CRYPTO_MESSAGE_WHILE_VALIDATING_CLIENT_HELLO,
"Unexpected handshake message while processing CHLO", _));
crypto_test_utils::SendHandshakeMessageToStream(server_stream(), chlo,
Perspective::IS_CLIENT);
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_crypto_server_stream.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_crypto_server_stream_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
481a858c-d1de-42f1-a7b5-2a39883b4e30 | cpp | google/quiche | quic_trace_visitor | quiche/quic/core/quic_trace_visitor.cc | quiche/quic/core/quic_trace_visitor_test.cc | #include "quiche/quic/core/quic_trace_visitor.h"
#include <string>
#include "quiche/quic/core/quic_types.h"
#include "quiche/common/quiche_endian.h"
namespace quic {
quic_trace::EncryptionLevel EncryptionLevelToProto(EncryptionLevel level) {
switch (level) {
case ENCRYPTION_INITIAL:
return quic_trace::ENCRYPTION_INITIAL;
case ENCRYPTION_HANDSHAKE:
return quic_trace::ENCRYPTION_HANDSHAKE;
case ENCRYPTION_ZERO_RTT:
return quic_trace::ENCRYPTION_0RTT;
case ENCRYPTION_FORWARD_SECURE:
return quic_trace::ENCRYPTION_1RTT;
case NUM_ENCRYPTION_LEVELS:
QUIC_BUG(EncryptionLevelToProto.Invalid)
<< "Invalid encryption level specified";
return quic_trace::ENCRYPTION_UNKNOWN;
}
QUIC_BUG(EncryptionLevelToProto.Unknown)
<< "Unknown encryption level specified " << static_cast<int>(level);
return quic_trace::ENCRYPTION_UNKNOWN;
}
QuicTraceVisitor::QuicTraceVisitor(const QuicConnection* connection)
: connection_(connection),
start_time_(connection_->clock()->ApproximateNow()) {
std::string binary_connection_id(connection->connection_id().data(),
connection->connection_id().length());
switch (connection->perspective()) {
case Perspective::IS_CLIENT:
trace_.set_destination_connection_id(binary_connection_id);
break;
case Perspective::IS_SERVER:
trace_.set_source_connection_id(binary_connection_id);
break;
}
}
void QuicTraceVisitor::OnPacketSent(
QuicPacketNumber packet_number, QuicPacketLength packet_length,
bool , TransmissionType ,
EncryptionLevel encryption_level, const QuicFrames& retransmittable_frames,
const QuicFrames& , QuicTime sent_time,
uint32_t ) {
quic_trace::Event* event = trace_.add_events();
event->set_event_type(quic_trace::PACKET_SENT);
event->set_time_us(ConvertTimestampToRecordedFormat(sent_time));
event->set_packet_number(packet_number.ToUint64());
event->set_packet_size(packet_length);
event->set_encryption_level(EncryptionLevelToProto(encryption_level));
for (const QuicFrame& frame : retransmittable_frames) {
switch (frame.type) {
case STREAM_FRAME:
case RST_STREAM_FRAME:
case CONNECTION_CLOSE_FRAME:
case WINDOW_UPDATE_FRAME:
case BLOCKED_FRAME:
case PING_FRAME:
case HANDSHAKE_DONE_FRAME:
case ACK_FREQUENCY_FRAME:
PopulateFrameInfo(frame, event->add_frames());
break;
case PADDING_FRAME:
case MTU_DISCOVERY_FRAME:
case STOP_WAITING_FRAME:
case ACK_FRAME:
QUIC_BUG(quic_bug_12732_1)
<< "Frames of type are not retransmittable and are not supposed "
"to be in retransmittable_frames";
break;
case NEW_CONNECTION_ID_FRAME:
case RETIRE_CONNECTION_ID_FRAME:
case MAX_STREAMS_FRAME:
case STREAMS_BLOCKED_FRAME:
case PATH_RESPONSE_FRAME:
case PATH_CHALLENGE_FRAME:
case STOP_SENDING_FRAME:
case MESSAGE_FRAME:
case CRYPTO_FRAME:
case NEW_TOKEN_FRAME:
case RESET_STREAM_AT_FRAME:
break;
case GOAWAY_FRAME:
break;
case NUM_FRAME_TYPES:
QUIC_BUG(quic_bug_10284_2) << "Unknown frame type encountered";
break;
}
}
if (connection_->sent_packet_manager()
.GetSendAlgorithm()
->GetCongestionControlType() == kPCC) {
PopulateTransportState(event->mutable_transport_state());
}
}
void QuicTraceVisitor::PopulateFrameInfo(const QuicFrame& frame,
quic_trace::Frame* frame_record) {
switch (frame.type) {
case STREAM_FRAME: {
frame_record->set_frame_type(quic_trace::STREAM);
quic_trace::StreamFrameInfo* info =
frame_record->mutable_stream_frame_info();
info->set_stream_id(frame.stream_frame.stream_id);
info->set_fin(frame.stream_frame.fin);
info->set_offset(frame.stream_frame.offset);
info->set_length(frame.stream_frame.data_length);
break;
}
case ACK_FRAME: {
frame_record->set_frame_type(quic_trace::ACK);
quic_trace::AckInfo* info = frame_record->mutable_ack_info();
info->set_ack_delay_us(frame.ack_frame->ack_delay_time.ToMicroseconds());
for (const auto& interval : frame.ack_frame->packets) {
quic_trace::AckBlock* block = info->add_acked_packets();
block->set_first_packet(interval.min().ToUint64());
block->set_last_packet(interval.max().ToUint64() - 1);
}
break;
}
case RST_STREAM_FRAME: {
frame_record->set_frame_type(quic_trace::RESET_STREAM);
quic_trace::ResetStreamInfo* info =
frame_record->mutable_reset_stream_info();
info->set_stream_id(frame.rst_stream_frame->stream_id);
info->set_final_offset(frame.rst_stream_frame->byte_offset);
info->set_application_error_code(frame.rst_stream_frame->error_code);
break;
}
case CONNECTION_CLOSE_FRAME: {
frame_record->set_frame_type(quic_trace::CONNECTION_CLOSE);
quic_trace::CloseInfo* info = frame_record->mutable_close_info();
info->set_error_code(frame.connection_close_frame->quic_error_code);
info->set_reason_phrase(frame.connection_close_frame->error_details);
info->set_close_type(static_cast<quic_trace::CloseType>(
frame.connection_close_frame->close_type));
info->set_transport_close_frame_type(
frame.connection_close_frame->transport_close_frame_type);
break;
}
case GOAWAY_FRAME:
break;
case WINDOW_UPDATE_FRAME: {
bool is_connection = frame.window_update_frame.stream_id == 0;
frame_record->set_frame_type(is_connection ? quic_trace::MAX_DATA
: quic_trace::MAX_STREAM_DATA);
quic_trace::FlowControlInfo* info =
frame_record->mutable_flow_control_info();
info->set_max_data(frame.window_update_frame.max_data);
if (!is_connection) {
info->set_stream_id(frame.window_update_frame.stream_id);
}
break;
}
case BLOCKED_FRAME: {
bool is_connection = frame.blocked_frame.stream_id == 0;
frame_record->set_frame_type(is_connection ? quic_trace::BLOCKED
: quic_trace::STREAM_BLOCKED);
quic_trace::FlowControlInfo* info =
frame_record->mutable_flow_control_info();
if (!is_connection) {
info->set_stream_id(frame.window_update_frame.stream_id);
}
break;
}
case PING_FRAME:
case MTU_DISCOVERY_FRAME:
case HANDSHAKE_DONE_FRAME:
frame_record->set_frame_type(quic_trace::PING);
break;
case PADDING_FRAME:
frame_record->set_frame_type(quic_trace::PADDING);
break;
case STOP_WAITING_FRAME:
break;
case NEW_CONNECTION_ID_FRAME:
case RETIRE_CONNECTION_ID_FRAME:
case MAX_STREAMS_FRAME:
case STREAMS_BLOCKED_FRAME:
case PATH_RESPONSE_FRAME:
case PATH_CHALLENGE_FRAME:
case STOP_SENDING_FRAME:
case MESSAGE_FRAME:
case CRYPTO_FRAME:
case NEW_TOKEN_FRAME:
case ACK_FREQUENCY_FRAME:
case RESET_STREAM_AT_FRAME:
break;
case NUM_FRAME_TYPES:
QUIC_BUG(quic_bug_10284_3) << "Unknown frame type encountered";
break;
}
}
void QuicTraceVisitor::OnIncomingAck(
QuicPacketNumber , EncryptionLevel ack_decrypted_level,
const QuicAckFrame& ack_frame, QuicTime ack_receive_time,
QuicPacketNumber , bool ,
QuicPacketNumber ) {
quic_trace::Event* event = trace_.add_events();
event->set_time_us(ConvertTimestampToRecordedFormat(ack_receive_time));
event->set_packet_number(connection_->GetLargestReceivedPacket().ToUint64());
event->set_event_type(quic_trace::PACKET_RECEIVED);
event->set_encryption_level(EncryptionLevelToProto(ack_decrypted_level));
QuicAckFrame copy_of_ack = ack_frame;
PopulateFrameInfo(QuicFrame(©_of_ack), event->add_frames());
PopulateTransportState(event->mutable_transport_state());
}
void QuicTraceVisitor::OnPacketLoss(QuicPacketNumber lost_packet_number,
EncryptionLevel encryption_level,
TransmissionType ,
QuicTime detection_time) {
quic_trace::Event* event = trace_.add_events();
event->set_time_us(ConvertTimestampToRecordedFormat(detection_time));
event->set_event_type(quic_trace::PACKET_LOST);
event->set_packet_number(lost_packet_number.ToUint64());
PopulateTransportState(event->mutable_transport_state());
event->set_encryption_level(EncryptionLevelToProto(encryption_level));
}
void QuicTraceVisitor::OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame,
const QuicTime& receive_time) {
quic_trace::Event* event = trace_.add_events();
event->set_time_us(ConvertTimestampToRecordedFormat(receive_time));
event->set_event_type(quic_trace::PACKET_RECEIVED);
event->set_packet_number(connection_->GetLargestReceivedPacket().ToUint64());
PopulateFrameInfo(QuicFrame(frame), event->add_frames());
}
void QuicTraceVisitor::OnSuccessfulVersionNegotiation(
const ParsedQuicVersion& version) {
uint32_t tag =
quiche::QuicheEndian::HostToNet32(CreateQuicVersionLabel(version));
std::string binary_tag(reinterpret_cast<const char*>(&tag), sizeof(tag));
trace_.set_protocol_version(binary_tag);
}
void QuicTraceVisitor::OnApplicationLimited() {
quic_trace::Event* event = trace_.add_events();
event->set_time_us(
ConvertTimestampToRecordedFormat(connection_->clock()->ApproximateNow()));
event->set_event_type(quic_trace::APPLICATION_LIMITED);
}
void QuicTraceVisitor::OnAdjustNetworkParameters(QuicBandwidth bandwidth,
QuicTime::Delta rtt,
QuicByteCount ,
QuicByteCount ) {
quic_trace::Event* event = trace_.add_events();
event->set_time_us(
ConvertTimestampToRecordedFormat(connection_->clock()->ApproximateNow()));
event->set_event_type(quic_trace::EXTERNAL_PARAMETERS);
quic_trace::ExternalNetworkParameters* parameters =
event->mutable_external_network_parameters();
if (!bandwidth.IsZero()) {
parameters->set_bandwidth_bps(bandwidth.ToBitsPerSecond());
}
if (!rtt.IsZero()) {
parameters->set_rtt_us(rtt.ToMicroseconds());
}
}
uint64_t QuicTraceVisitor::ConvertTimestampToRecordedFormat(
QuicTime timestamp) {
if (timestamp < start_time_) {
QUIC_BUG(quic_bug_10284_4)
<< "Timestamp went back in time while recording a trace";
return 0;
}
return (timestamp - start_time_).ToMicroseconds();
}
void QuicTraceVisitor::PopulateTransportState(
quic_trace::TransportState* state) {
const RttStats* rtt_stats = connection_->sent_packet_manager().GetRttStats();
state->set_min_rtt_us(rtt_stats->min_rtt().ToMicroseconds());
state->set_smoothed_rtt_us(rtt_stats->smoothed_rtt().ToMicroseconds());
state->set_last_rtt_us(rtt_stats->latest_rtt().ToMicroseconds());
state->set_cwnd_bytes(
connection_->sent_packet_manager().GetCongestionWindowInBytes());
QuicByteCount in_flight =
connection_->sent_packet_manager().GetBytesInFlight();
state->set_in_flight_bytes(in_flight);
state->set_pacing_rate_bps(connection_->sent_packet_manager()
.GetSendAlgorithm()
->PacingRate(in_flight)
.ToBitsPerSecond());
if (connection_->sent_packet_manager()
.GetSendAlgorithm()
->GetCongestionControlType() == kPCC) {
state->set_congestion_control_state(
connection_->sent_packet_manager().GetSendAlgorithm()->GetDebugState());
}
}
} | #include "quiche/quic/core/quic_trace_visitor.h"
#include <string>
#include <vector>
#include "quiche/quic/core/quic_constants.h"
#include "quiche/quic/platform/api/quic_test.h"
#include "quiche/quic/test_tools/quic_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"
namespace quic::test {
namespace {
const QuicByteCount kTransferSize = 1000 * kMaxOutgoingPacketSize;
const QuicByteCount kTestStreamNumber = 3;
const QuicTime::Delta kDelay = QuicTime::Delta::FromMilliseconds(20);
class QuicTraceVisitorTest : public QuicTest {
public:
QuicTraceVisitorTest() {
QuicConnectionId connection_id = test::TestConnectionId();
simulator::Simulator simulator;
simulator::QuicEndpoint client(&simulator, "Client", "Server",
Perspective::IS_CLIENT, connection_id);
simulator::QuicEndpoint server(&simulator, "Server", "Client",
Perspective::IS_SERVER, connection_id);
const QuicBandwidth kBandwidth = QuicBandwidth::FromKBitsPerSecond(1000);
const QuicByteCount kBdp = kBandwidth * (2 * kDelay);
simulator::Switch network_switch(&simulator, "Switch", 8, 0.5 * kBdp);
simulator::SymmetricLink client_link(&client, network_switch.port(1),
2 * kBandwidth, kDelay);
simulator::SymmetricLink server_link(&server, network_switch.port(2),
kBandwidth, kDelay);
QuicTraceVisitor visitor(client.connection());
client.connection()->set_debug_visitor(&visitor);
const QuicTime::Delta kDeadline =
3 * kBandwidth.TransferTime(kTransferSize);
client.AddBytesToTransfer(kTransferSize);
bool simulator_result = simulator.RunUntilOrTimeout(
[&]() { return server.bytes_received() >= kTransferSize; }, kDeadline);
QUICHE_CHECK(simulator_result);
trace_.Swap(visitor.trace());
QUICHE_CHECK_NE(0u, client.connection()->GetStats().packets_retransmitted);
packets_sent_ = client.connection()->GetStats().packets_sent;
}
std::vector<quic_trace::Event> AllEventsWithType(
quic_trace::EventType event_type) {
std::vector<quic_trace::Event> result;
for (const auto& event : trace_.events()) {
if (event.event_type() == event_type) {
result.push_back(event);
}
}
return result;
}
protected:
quic_trace::Trace trace_;
QuicPacketCount packets_sent_;
};
TEST_F(QuicTraceVisitorTest, ConnectionId) {
char expected_cid[] = {0, 0, 0, 0, 0, 0, 0, 42};
EXPECT_EQ(std::string(expected_cid, sizeof(expected_cid)),
trace_.destination_connection_id());
}
TEST_F(QuicTraceVisitorTest, Version) {
std::string version = trace_.protocol_version();
ASSERT_EQ(4u, version.size());
EXPECT_TRUE(version[0] != 0 || version[1] != 0 || version[2] != 0 ||
version[3] != 0);
}
TEST_F(QuicTraceVisitorTest, SentPacket) {
auto sent_packets = AllEventsWithType(quic_trace::PACKET_SENT);
EXPECT_EQ(packets_sent_, sent_packets.size());
ASSERT_GT(sent_packets.size(), 0u);
EXPECT_EQ(sent_packets[0].packet_size(), kDefaultMaxPacketSize);
EXPECT_EQ(sent_packets[0].packet_number(), 1u);
}
TEST_F(QuicTraceVisitorTest, SentStream) {
auto sent_packets = AllEventsWithType(quic_trace::PACKET_SENT);
QuicIntervalSet<QuicStreamOffset> offsets;
for (const quic_trace::Event& packet : sent_packets) {
for (const quic_trace::Frame& frame : packet.frames()) {
if (frame.frame_type() != quic_trace::STREAM) {
continue;
}
const quic_trace::StreamFrameInfo& info = frame.stream_frame_info();
if (info.stream_id() != kTestStreamNumber) {
continue;
}
ASSERT_GT(info.length(), 0u);
offsets.Add(info.offset(), info.offset() + info.length());
}
}
ASSERT_EQ(1u, offsets.Size());
EXPECT_EQ(0u, offsets.begin()->min());
EXPECT_EQ(kTransferSize, offsets.rbegin()->max());
}
TEST_F(QuicTraceVisitorTest, AckPackets) {
QuicIntervalSet<QuicPacketNumber> packets;
for (const quic_trace::Event& packet : trace_.events()) {
if (packet.event_type() == quic_trace::PACKET_RECEIVED) {
for (const quic_trace::Frame& frame : packet.frames()) {
if (frame.frame_type() != quic_trace::ACK) {
continue;
}
const quic_trace::AckInfo& info = frame.ack_info();
for (const auto& block : info.acked_packets()) {
packets.Add(QuicPacketNumber(block.first_packet()),
QuicPacketNumber(block.last_packet()) + 1);
}
}
}
if (packet.event_type() == quic_trace::PACKET_LOST) {
packets.Add(QuicPacketNumber(packet.packet_number()),
QuicPacketNumber(packet.packet_number()) + 1);
}
}
ASSERT_EQ(1u, packets.Size());
EXPECT_EQ(QuicPacketNumber(1u), packets.begin()->min());
EXPECT_GT(packets.rbegin()->max(), QuicPacketNumber(packets_sent_ - 20));
}
TEST_F(QuicTraceVisitorTest, TransportState) {
auto acks = AllEventsWithType(quic_trace::PACKET_RECEIVED);
ASSERT_EQ(1, acks[0].frames_size());
ASSERT_EQ(quic_trace::ACK, acks[0].frames(0).frame_type());
EXPECT_LE((4 * kDelay).ToMicroseconds() * 1.,
acks.rbegin()->transport_state().min_rtt_us());
EXPECT_GE((4 * kDelay).ToMicroseconds() * 1.25,
acks.rbegin()->transport_state().min_rtt_us());
}
TEST_F(QuicTraceVisitorTest, EncryptionLevels) {
for (const auto& event : trace_.events()) {
switch (event.event_type()) {
case quic_trace::PACKET_SENT:
case quic_trace::PACKET_RECEIVED:
case quic_trace::PACKET_LOST:
ASSERT_TRUE(event.has_encryption_level());
ASSERT_NE(event.encryption_level(), quic_trace::ENCRYPTION_UNKNOWN);
break;
default:
break;
}
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_trace_visitor.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_trace_visitor_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
3a502638-f7f6-4331-a6e7-35592c04f18e | cpp | google/quiche | quic_bandwidth | quiche/quic/core/quic_bandwidth.cc | quiche/quic/core/quic_bandwidth_test.cc | #include "quiche/quic/core/quic_bandwidth.h"
#include <cinttypes>
#include <string>
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
namespace quic {
std::string QuicBandwidth::ToDebuggingValue() const {
if (bits_per_second_ < 80000) {
return absl::StrFormat("%d bits/s (%d bytes/s)", bits_per_second_,
bits_per_second_ / 8);
}
double divisor;
char unit;
if (bits_per_second_ < 8 * 1000 * 1000) {
divisor = 1e3;
unit = 'k';
} else if (bits_per_second_ < INT64_C(8) * 1000 * 1000 * 1000) {
divisor = 1e6;
unit = 'M';
} else {
divisor = 1e9;
unit = 'G';
}
double bits_per_second_with_unit = bits_per_second_ / divisor;
double bytes_per_second_with_unit = bits_per_second_with_unit / 8;
return absl::StrFormat("%.2f %cbits/s (%.2f %cbytes/s)",
bits_per_second_with_unit, unit,
bytes_per_second_with_unit, unit);
}
} | #include "quiche/quic/core/quic_bandwidth.h"
#include <limits>
#include "quiche/quic/core/quic_time.h"
#include "quiche/quic/platform/api/quic_test.h"
namespace quic {
namespace test {
class QuicBandwidthTest : public QuicTest {};
TEST_F(QuicBandwidthTest, FromTo) {
EXPECT_EQ(QuicBandwidth::FromKBitsPerSecond(1),
QuicBandwidth::FromBitsPerSecond(1000));
EXPECT_EQ(QuicBandwidth::FromKBytesPerSecond(1),
QuicBandwidth::FromBytesPerSecond(1000));
EXPECT_EQ(QuicBandwidth::FromBitsPerSecond(8000),
QuicBandwidth::FromBytesPerSecond(1000));
EXPECT_EQ(QuicBandwidth::FromKBitsPerSecond(8),
QuicBandwidth::FromKBytesPerSecond(1));
EXPECT_EQ(0, QuicBandwidth::Zero().ToBitsPerSecond());
EXPECT_EQ(0, QuicBandwidth::Zero().ToKBitsPerSecond());
EXPECT_EQ(0, QuicBandwidth::Zero().ToBytesPerSecond());
EXPECT_EQ(0, QuicBandwidth::Zero().ToKBytesPerSecond());
EXPECT_EQ(1, QuicBandwidth::FromBitsPerSecond(1000).ToKBitsPerSecond());
EXPECT_EQ(1000, QuicBandwidth::FromKBitsPerSecond(1).ToBitsPerSecond());
EXPECT_EQ(1, QuicBandwidth::FromBytesPerSecond(1000).ToKBytesPerSecond());
EXPECT_EQ(1000, QuicBandwidth::FromKBytesPerSecond(1).ToBytesPerSecond());
}
TEST_F(QuicBandwidthTest, Add) {
QuicBandwidth bandwidht_1 = QuicBandwidth::FromKBitsPerSecond(1);
QuicBandwidth bandwidht_2 = QuicBandwidth::FromKBytesPerSecond(1);
EXPECT_EQ(9000, (bandwidht_1 + bandwidht_2).ToBitsPerSecond());
EXPECT_EQ(9000, (bandwidht_2 + bandwidht_1).ToBitsPerSecond());
}
TEST_F(QuicBandwidthTest, Subtract) {
QuicBandwidth bandwidht_1 = QuicBandwidth::FromKBitsPerSecond(1);
QuicBandwidth bandwidht_2 = QuicBandwidth::FromKBytesPerSecond(1);
EXPECT_EQ(7000, (bandwidht_2 - bandwidht_1).ToBitsPerSecond());
}
TEST_F(QuicBandwidthTest, TimeDelta) {
EXPECT_EQ(QuicBandwidth::FromKBytesPerSecond(1000),
QuicBandwidth::FromBytesAndTimeDelta(
1000, QuicTime::Delta::FromMilliseconds(1)));
EXPECT_EQ(QuicBandwidth::FromKBytesPerSecond(10),
QuicBandwidth::FromBytesAndTimeDelta(
1000, QuicTime::Delta::FromMilliseconds(100)));
EXPECT_EQ(QuicBandwidth::Zero(), QuicBandwidth::FromBytesAndTimeDelta(
0, QuicTime::Delta::FromSeconds(9)));
EXPECT_EQ(
QuicBandwidth::FromBitsPerSecond(1),
QuicBandwidth::FromBytesAndTimeDelta(1, QuicTime::Delta::FromSeconds(9)));
}
TEST_F(QuicBandwidthTest, Scale) {
EXPECT_EQ(QuicBandwidth::FromKBytesPerSecond(500),
QuicBandwidth::FromKBytesPerSecond(1000) * 0.5f);
EXPECT_EQ(QuicBandwidth::FromKBytesPerSecond(750),
0.75f * QuicBandwidth::FromKBytesPerSecond(1000));
EXPECT_EQ(QuicBandwidth::FromKBytesPerSecond(1250),
QuicBandwidth::FromKBytesPerSecond(1000) * 1.25f);
EXPECT_EQ(QuicBandwidth::FromBitsPerSecond(5),
QuicBandwidth::FromBitsPerSecond(9) * 0.5f);
EXPECT_EQ(QuicBandwidth::FromBitsPerSecond(2),
QuicBandwidth::FromBitsPerSecond(12) * 0.2f);
}
TEST_F(QuicBandwidthTest, BytesPerPeriod) {
EXPECT_EQ(2000, QuicBandwidth::FromKBytesPerSecond(2000).ToBytesPerPeriod(
QuicTime::Delta::FromMilliseconds(1)));
EXPECT_EQ(2, QuicBandwidth::FromKBytesPerSecond(2000).ToKBytesPerPeriod(
QuicTime::Delta::FromMilliseconds(1)));
EXPECT_EQ(200000, QuicBandwidth::FromKBytesPerSecond(2000).ToBytesPerPeriod(
QuicTime::Delta::FromMilliseconds(100)));
EXPECT_EQ(200, QuicBandwidth::FromKBytesPerSecond(2000).ToKBytesPerPeriod(
QuicTime::Delta::FromMilliseconds(100)));
EXPECT_EQ(200, QuicBandwidth::FromBitsPerSecond(1599).ToBytesPerPeriod(
QuicTime::Delta::FromMilliseconds(1001)));
EXPECT_EQ(200, QuicBandwidth::FromBitsPerSecond(1599).ToKBytesPerPeriod(
QuicTime::Delta::FromSeconds(1001)));
}
TEST_F(QuicBandwidthTest, TransferTime) {
EXPECT_EQ(QuicTime::Delta::FromSeconds(1),
QuicBandwidth::FromKBytesPerSecond(1).TransferTime(1000));
EXPECT_EQ(QuicTime::Delta::Zero(), QuicBandwidth::Zero().TransferTime(1000));
}
TEST_F(QuicBandwidthTest, RelOps) {
const QuicBandwidth b1 = QuicBandwidth::FromKBitsPerSecond(1);
const QuicBandwidth b2 = QuicBandwidth::FromKBytesPerSecond(2);
EXPECT_EQ(b1, b1);
EXPECT_NE(b1, b2);
EXPECT_LT(b1, b2);
EXPECT_GT(b2, b1);
EXPECT_LE(b1, b1);
EXPECT_LE(b1, b2);
EXPECT_GE(b1, b1);
EXPECT_GE(b2, b1);
}
TEST_F(QuicBandwidthTest, DebuggingValue) {
EXPECT_EQ("128 bits/s (16 bytes/s)",
QuicBandwidth::FromBytesPerSecond(16).ToDebuggingValue());
EXPECT_EQ("4096 bits/s (512 bytes/s)",
QuicBandwidth::FromBytesPerSecond(512).ToDebuggingValue());
QuicBandwidth bandwidth = QuicBandwidth::FromBytesPerSecond(1000 * 50);
EXPECT_EQ("400.00 kbits/s (50.00 kbytes/s)", bandwidth.ToDebuggingValue());
bandwidth = bandwidth * 1000;
EXPECT_EQ("400.00 Mbits/s (50.00 Mbytes/s)", bandwidth.ToDebuggingValue());
bandwidth = bandwidth * 1000;
EXPECT_EQ("400.00 Gbits/s (50.00 Gbytes/s)", bandwidth.ToDebuggingValue());
}
TEST_F(QuicBandwidthTest, SpecialValues) {
EXPECT_EQ(0, QuicBandwidth::Zero().ToBitsPerSecond());
EXPECT_EQ(std::numeric_limits<int64_t>::max(),
QuicBandwidth::Infinite().ToBitsPerSecond());
EXPECT_TRUE(QuicBandwidth::Zero().IsZero());
EXPECT_FALSE(QuicBandwidth::Zero().IsInfinite());
EXPECT_TRUE(QuicBandwidth::Infinite().IsInfinite());
EXPECT_FALSE(QuicBandwidth::Infinite().IsZero());
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_bandwidth.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_bandwidth_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
6a135d5f-6744-4874-af6f-dff8063fac3a | cpp | google/quiche | quic_crypto_client_handshaker | quiche/quic/core/quic_crypto_client_handshaker.cc | quiche/quic/core/quic_crypto_client_handshaker_test.cc | #include "quiche/quic/core/quic_crypto_client_handshaker.h"
#include <memory>
#include <string>
#include <utility>
#include "absl/strings/str_cat.h"
#include "quiche/quic/core/crypto/crypto_protocol.h"
#include "quiche/quic/core/crypto/crypto_utils.h"
#include "quiche/quic/core/quic_session.h"
#include "quiche/quic/core/quic_types.h"
#include "quiche/quic/platform/api/quic_client_stats.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 {
QuicCryptoClientHandshaker::ProofVerifierCallbackImpl::
ProofVerifierCallbackImpl(QuicCryptoClientHandshaker* parent)
: parent_(parent) {}
QuicCryptoClientHandshaker::ProofVerifierCallbackImpl::
~ProofVerifierCallbackImpl() {}
void QuicCryptoClientHandshaker::ProofVerifierCallbackImpl::Run(
bool ok, const std::string& error_details,
std::unique_ptr<ProofVerifyDetails>* details) {
if (parent_ == nullptr) {
return;
}
parent_->verify_ok_ = ok;
parent_->verify_error_details_ = error_details;
parent_->verify_details_ = std::move(*details);
parent_->proof_verify_callback_ = nullptr;
parent_->DoHandshakeLoop(nullptr);
}
void QuicCryptoClientHandshaker::ProofVerifierCallbackImpl::Cancel() {
parent_ = nullptr;
}
QuicCryptoClientHandshaker::QuicCryptoClientHandshaker(
const QuicServerId& server_id, QuicCryptoClientStream* stream,
QuicSession* session, std::unique_ptr<ProofVerifyContext> verify_context,
QuicCryptoClientConfig* crypto_config,
QuicCryptoClientStream::ProofHandler* proof_handler)
: QuicCryptoHandshaker(stream, session),
stream_(stream),
session_(session),
delegate_(session),
next_state_(STATE_IDLE),
num_client_hellos_(0),
crypto_config_(crypto_config),
server_id_(server_id),
generation_counter_(0),
verify_context_(std::move(verify_context)),
proof_verify_callback_(nullptr),
proof_handler_(proof_handler),
verify_ok_(false),
proof_verify_start_time_(QuicTime::Zero()),
num_scup_messages_received_(0),
encryption_established_(false),
one_rtt_keys_available_(false),
crypto_negotiated_params_(new QuicCryptoNegotiatedParameters) {}
QuicCryptoClientHandshaker::~QuicCryptoClientHandshaker() {
if (proof_verify_callback_) {
proof_verify_callback_->Cancel();
}
}
void QuicCryptoClientHandshaker::OnHandshakeMessage(
const CryptoHandshakeMessage& message) {
QuicCryptoHandshaker::OnHandshakeMessage(message);
if (message.tag() == kSCUP) {
if (!one_rtt_keys_available()) {
stream_->OnUnrecoverableError(
QUIC_CRYPTO_UPDATE_BEFORE_HANDSHAKE_COMPLETE,
"Early SCUP disallowed");
return;
}
HandleServerConfigUpdateMessage(message);
num_scup_messages_received_++;
return;
}
if (one_rtt_keys_available()) {
stream_->OnUnrecoverableError(QUIC_CRYPTO_MESSAGE_AFTER_HANDSHAKE_COMPLETE,
"Unexpected handshake message");
return;
}
DoHandshakeLoop(&message);
}
bool QuicCryptoClientHandshaker::CryptoConnect() {
next_state_ = STATE_INITIALIZE;
DoHandshakeLoop(nullptr);
return session()->connection()->connected();
}
int QuicCryptoClientHandshaker::num_sent_client_hellos() const {
return num_client_hellos_;
}
bool QuicCryptoClientHandshaker::ResumptionAttempted() const {
QUICHE_DCHECK(false);
return false;
}
bool QuicCryptoClientHandshaker::IsResumption() const {
QUIC_BUG_IF(quic_bug_12522_1, !one_rtt_keys_available_);
return false;
}
bool QuicCryptoClientHandshaker::EarlyDataAccepted() const {
QUIC_BUG_IF(quic_bug_12522_2, !one_rtt_keys_available_);
return num_client_hellos_ == 1;
}
ssl_early_data_reason_t QuicCryptoClientHandshaker::EarlyDataReason() const {
return early_data_reason_;
}
bool QuicCryptoClientHandshaker::ReceivedInchoateReject() const {
QUIC_BUG_IF(quic_bug_12522_3, !one_rtt_keys_available_);
return num_client_hellos_ >= 3;
}
int QuicCryptoClientHandshaker::num_scup_messages_received() const {
return num_scup_messages_received_;
}
std::string QuicCryptoClientHandshaker::chlo_hash() const { return chlo_hash_; }
bool QuicCryptoClientHandshaker::encryption_established() const {
return encryption_established_;
}
bool QuicCryptoClientHandshaker::IsCryptoFrameExpectedForEncryptionLevel(
EncryptionLevel ) const {
return true;
}
EncryptionLevel
QuicCryptoClientHandshaker::GetEncryptionLevelToSendCryptoDataOfSpace(
PacketNumberSpace space) const {
if (space == INITIAL_DATA) {
return ENCRYPTION_INITIAL;
}
QUICHE_DCHECK(false);
return NUM_ENCRYPTION_LEVELS;
}
bool QuicCryptoClientHandshaker::one_rtt_keys_available() const {
return one_rtt_keys_available_;
}
const QuicCryptoNegotiatedParameters&
QuicCryptoClientHandshaker::crypto_negotiated_params() const {
return *crypto_negotiated_params_;
}
CryptoMessageParser* QuicCryptoClientHandshaker::crypto_message_parser() {
return QuicCryptoHandshaker::crypto_message_parser();
}
HandshakeState QuicCryptoClientHandshaker::GetHandshakeState() const {
return one_rtt_keys_available() ? HANDSHAKE_COMPLETE : HANDSHAKE_START;
}
void QuicCryptoClientHandshaker::OnHandshakeDoneReceived() {
QUICHE_DCHECK(false);
}
void QuicCryptoClientHandshaker::OnNewTokenReceived(
absl::string_view ) {
QUICHE_DCHECK(false);
}
size_t QuicCryptoClientHandshaker::BufferSizeLimitForLevel(
EncryptionLevel level) const {
return QuicCryptoHandshaker::BufferSizeLimitForLevel(level);
}
std::unique_ptr<QuicDecrypter>
QuicCryptoClientHandshaker::AdvanceKeysAndCreateCurrentOneRttDecrypter() {
QUICHE_DCHECK(false);
return nullptr;
}
std::unique_ptr<QuicEncrypter>
QuicCryptoClientHandshaker::CreateCurrentOneRttEncrypter() {
QUICHE_DCHECK(false);
return nullptr;
}
void QuicCryptoClientHandshaker::OnConnectionClosed(
QuicErrorCode , ConnectionCloseSource ) {
next_state_ = STATE_CONNECTION_CLOSED;
}
void QuicCryptoClientHandshaker::HandleServerConfigUpdateMessage(
const CryptoHandshakeMessage& server_config_update) {
QUICHE_DCHECK(server_config_update.tag() == kSCUP);
std::string error_details;
QuicCryptoClientConfig::CachedState* cached =
crypto_config_->LookupOrCreate(server_id_);
QuicErrorCode error = crypto_config_->ProcessServerConfigUpdate(
server_config_update, session()->connection()->clock()->WallNow(),
session()->transport_version(), chlo_hash_, cached,
crypto_negotiated_params_, &error_details);
if (error != QUIC_NO_ERROR) {
stream_->OnUnrecoverableError(
error, "Server config update invalid: " + error_details);
return;
}
QUICHE_DCHECK(one_rtt_keys_available());
if (proof_verify_callback_) {
proof_verify_callback_->Cancel();
}
next_state_ = STATE_INITIALIZE_SCUP;
DoHandshakeLoop(nullptr);
}
void QuicCryptoClientHandshaker::DoHandshakeLoop(
const CryptoHandshakeMessage* in) {
QuicCryptoClientConfig::CachedState* cached =
crypto_config_->LookupOrCreate(server_id_);
QuicAsyncStatus rv = QUIC_SUCCESS;
do {
QUICHE_CHECK_NE(STATE_NONE, next_state_);
const State state = next_state_;
next_state_ = STATE_IDLE;
rv = QUIC_SUCCESS;
switch (state) {
case STATE_INITIALIZE:
DoInitialize(cached);
break;
case STATE_SEND_CHLO:
DoSendCHLO(cached);
return;
case STATE_RECV_REJ:
DoReceiveREJ(in, cached);
break;
case STATE_VERIFY_PROOF:
rv = DoVerifyProof(cached);
break;
case STATE_VERIFY_PROOF_COMPLETE:
DoVerifyProofComplete(cached);
break;
case STATE_RECV_SHLO:
DoReceiveSHLO(in, cached);
break;
case STATE_IDLE:
stream_->OnUnrecoverableError(QUIC_INVALID_CRYPTO_MESSAGE_TYPE,
"Handshake in idle state");
return;
case STATE_INITIALIZE_SCUP:
DoInitializeServerConfigUpdate(cached);
break;
case STATE_NONE:
QUICHE_NOTREACHED();
return;
case STATE_CONNECTION_CLOSED:
rv = QUIC_FAILURE;
return;
}
} while (rv != QUIC_PENDING && next_state_ != STATE_NONE);
}
void QuicCryptoClientHandshaker::DoInitialize(
QuicCryptoClientConfig::CachedState* cached) {
if (!cached->IsEmpty() && !cached->signature().empty()) {
QUICHE_DCHECK(crypto_config_->proof_verifier());
proof_verify_start_time_ = session()->connection()->clock()->Now();
chlo_hash_ = cached->chlo_hash();
next_state_ = STATE_VERIFY_PROOF;
} else {
next_state_ = STATE_SEND_CHLO;
}
}
void QuicCryptoClientHandshaker::DoSendCHLO(
QuicCryptoClientConfig::CachedState* cached) {
session()->connection()->SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
encryption_established_ = false;
if (num_client_hellos_ >= QuicCryptoClientStream::kMaxClientHellos) {
stream_->OnUnrecoverableError(
QUIC_CRYPTO_TOO_MANY_REJECTS,
absl::StrCat("More than ", QuicCryptoClientStream::kMaxClientHellos,
" rejects"));
return;
}
num_client_hellos_++;
CryptoHandshakeMessage out;
QUICHE_DCHECK(session() != nullptr);
QUICHE_DCHECK(session()->config() != nullptr);
session()->config()->ToHandshakeMessage(&out, session()->transport_version());
bool fill_inchoate_client_hello = false;
if (!cached->IsComplete(session()->connection()->clock()->WallNow())) {
early_data_reason_ = ssl_early_data_no_session_offered;
fill_inchoate_client_hello = true;
} else if (session()->config()->HasClientRequestedIndependentOption(
kQNZ2, session()->perspective()) &&
num_client_hellos_ == 1) {
early_data_reason_ = ssl_early_data_disabled;
fill_inchoate_client_hello = true;
}
if (fill_inchoate_client_hello) {
crypto_config_->FillInchoateClientHello(
server_id_, session()->supported_versions().front(), cached,
session()->connection()->random_generator(),
true, crypto_negotiated_params_, &out);
const QuicByteCount kFramingOverhead = 50;
const QuicByteCount max_packet_size =
session()->connection()->max_packet_length();
if (max_packet_size <= kFramingOverhead) {
QUIC_DLOG(DFATAL) << "max_packet_length (" << max_packet_size
<< ") has no room for framing overhead.";
stream_->OnUnrecoverableError(QUIC_INTERNAL_ERROR,
"max_packet_size too smalll");
return;
}
if (kClientHelloMinimumSize > max_packet_size - kFramingOverhead) {
QUIC_DLOG(DFATAL) << "Client hello won't fit in a single packet.";
stream_->OnUnrecoverableError(QUIC_INTERNAL_ERROR, "CHLO too large");
return;
}
next_state_ = STATE_RECV_REJ;
chlo_hash_ = CryptoUtils::HashHandshakeMessage(out, Perspective::IS_CLIENT);
session()->connection()->set_fully_pad_crypto_handshake_packets(
crypto_config_->pad_inchoate_hello());
SendHandshakeMessage(out, ENCRYPTION_INITIAL);
return;
}
std::string error_details;
QuicErrorCode error = crypto_config_->FillClientHello(
server_id_, session()->connection()->connection_id(),
session()->supported_versions().front(),
session()->connection()->version(), cached,
session()->connection()->clock()->WallNow(),
session()->connection()->random_generator(), crypto_negotiated_params_,
&out, &error_details);
if (error != QUIC_NO_ERROR) {
cached->InvalidateServerConfig();
stream_->OnUnrecoverableError(error, error_details);
return;
}
chlo_hash_ = CryptoUtils::HashHandshakeMessage(out, Perspective::IS_CLIENT);
if (cached->proof_verify_details()) {
proof_handler_->OnProofVerifyDetailsAvailable(
*cached->proof_verify_details());
}
next_state_ = STATE_RECV_SHLO;
session()->connection()->set_fully_pad_crypto_handshake_packets(
crypto_config_->pad_full_hello());
SendHandshakeMessage(out, ENCRYPTION_INITIAL);
delegate_->OnNewEncryptionKeyAvailable(
ENCRYPTION_ZERO_RTT,
std::move(crypto_negotiated_params_->initial_crypters.encrypter));
delegate_->OnNewDecryptionKeyAvailable(
ENCRYPTION_ZERO_RTT,
std::move(crypto_negotiated_params_->initial_crypters.decrypter),
true,
true);
encryption_established_ = true;
delegate_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
if (early_data_reason_ == ssl_early_data_unknown && num_client_hellos_ > 1) {
early_data_reason_ = ssl_early_data_peer_declined;
}
}
void QuicCryptoClientHandshaker::DoReceiveREJ(
const CryptoHandshakeMessage* in,
QuicCryptoClientConfig::CachedState* cached) {
if (in->tag() != kREJ) {
next_state_ = STATE_NONE;
stream_->OnUnrecoverableError(QUIC_INVALID_CRYPTO_MESSAGE_TYPE,
"Expected REJ");
return;
}
QuicTagVector reject_reasons;
static_assert(sizeof(QuicTag) == sizeof(uint32_t), "header out of sync");
if (in->GetTaglist(kRREJ, &reject_reasons) == QUIC_NO_ERROR) {
uint32_t packed_error = 0;
for (size_t i = 0; i < reject_reasons.size(); ++i) {
if (reject_reasons[i] == HANDSHAKE_OK || reject_reasons[i] >= 32) {
continue;
}
HandshakeFailureReason reason =
static_cast<HandshakeFailureReason>(reject_reasons[i]);
packed_error |= 1 << (reason - 1);
}
QUIC_DVLOG(1) << "Reasons for rejection: " << packed_error;
}
delegate_->NeuterUnencryptedData();
std::string error_details;
QuicErrorCode error = crypto_config_->ProcessRejection(
*in, session()->connection()->clock()->WallNow(),
session()->transport_version(), chlo_hash_, cached,
crypto_negotiated_params_, &error_details);
if (error != QUIC_NO_ERROR) {
next_state_ = STATE_NONE;
stream_->OnUnrecoverableError(error, error_details);
return;
}
if (!cached->proof_valid()) {
if (!cached->signature().empty()) {
next_state_ = STATE_VERIFY_PROOF;
return;
}
}
next_state_ = STATE_SEND_CHLO;
}
QuicAsyncStatus QuicCryptoClientHandshaker::DoVerifyProof(
QuicCryptoClientConfig::CachedState* cached) {
ProofVerifier* verifier = crypto_config_->proof_verifier();
QUICHE_DCHECK(verifier);
next_state_ = STATE_VERIFY_PROOF_COMPLETE;
generation_counter_ = cached->generation_counter();
ProofVerifierCallbackImpl* proof_verify_callback =
new ProofVerifierCallbackImpl(this);
verify_ok_ = false;
QuicAsyncStatus status = verifier->VerifyProof(
server_id_.host(), server_id_.port(), cached->server_config(),
session()->transport_version(), chlo_hash_, cached->certs(),
cached->cert_sct(), cached->signature(), verify_context_.get(),
&verify_error_details_, &verify_details_,
std::unique_ptr<ProofVerifierCallback>(proof_verify_callback));
switch (status) {
case QUIC_PENDING:
proof_verify_callback_ = proof_verify_callback;
QUIC_DVLOG(1) << "Doing VerifyProof";
break;
case QUIC_FAILURE:
break;
case QUIC_SUCCESS:
verify_ok_ = true;
break;
}
return status;
}
void QuicCryptoClientHandshaker::DoVerifyProofComplete(
QuicCryptoClientConfig::CachedState* cached) {
if (proof_verify_start_time_.IsInitialized()) {
QUIC_CLIENT_HISTOGRAM_TIMES(
"QuicSession.VerifyProofTime.CachedServerConfig",
(session()->connection()->clock()->Now() - proof_verify_start_time_),
QuicTime::Delta::FromMilliseconds(1), QuicTime::Delta::FromSeconds(10),
50, "");
}
if (!verify_ok_) {
if (verify_details_) {
proof_handler_->OnProofVerifyDetailsAvailable(*verify_details_);
}
if (num_client_hellos_ == 0) {
cached->Clear();
next_state_ = STATE_INITIALIZE;
return;
}
next_state_ = STATE_NONE;
QUIC_CLIENT_HISTOGRAM_BOOL("QuicVerifyProofFailed.HandshakeConfirmed",
one_rtt_keys_available(), "");
stream_->OnUnrecoverableError(QUIC_PROOF_INVALID,
"Proof invalid: " + verify_error_details_);
return;
}
if (generation_counter_ != cached->generation_counter()) {
next_state_ = STATE_VERIFY_PROOF;
} else {
SetCachedProofValid(cached);
cached->SetProofVerifyDetails(verify_details_.release());
if (!one_rtt_keys_available()) {
next_state_ = STATE_SEND_CHLO;
} else {
next_state_ = STATE_NONE;
}
}
}
void QuicCryptoClientHandshaker::DoReceiveSHLO(
const CryptoHandshakeMessage* in,
QuicCryptoClientConfig::CachedState* cached) {
next_state_ = STATE_NONE;
if (in->tag() == kREJ) {
if (session()->connection()->last_decrypted_level() != ENCRYPTION_INITIAL) {
stream_->OnUnrecoverableError(QUIC_CRYPTO_ENCRYPTION_LEVEL_INCORRECT,
"encrypted REJ message");
return;
}
next_state_ = STATE_RECV_REJ;
return;
}
if (in->tag() != kSHLO) {
stream_->OnUnrecoverableError(
QUIC_INVALID_CRYPTO_MESSAGE_TYPE,
absl::StrCat("Expected SHLO or REJ. Received: ",
QuicTagToString(in->tag())));
return;
}
if (session()->connection()->last_decrypted_level() == ENCRYPTION_INITIAL) {
stream_->OnUnrecoverableError(QUIC_CRYPTO_ENCRYPTION_LEVEL_INCORRECT,
"unencrypted SHLO message");
return;
}
if (num_client_hellos_ == 1) {
early_data_reason_ = ssl_early_data_accepted;
}
std::string error_details;
QuicErrorCode error = crypto_config_->ProcessServerHello(
*in, session()->connection()->connection_id(),
session()->connection()->version(),
session()->connection()->server_supported_versions(), cached,
crypto_negotiated_params_, &error_details);
if (error != QUIC_NO_ERROR) {
stream_->OnUnrecoverableError(error,
"Server hello invalid: " + error_details);
return;
}
error = session()->config()->ProcessPeerHello(*in, SERVER, &error_details);
if (error != QUIC_NO_ERROR) {
stream_->OnUnrecoverableError(error,
"Server hello invalid: " + error_details);
return;
}
session()->OnConfigNegotiated();
CrypterPair* crypters = &crypto_negotiated_params_->forward_secure_crypters;
delegate_->OnNewEncryptionKeyAvailable(ENCRYPTION_FORWARD_SECURE,
std::move(crypters->encrypter));
delegate_->OnNewDecryptionKeyAvailable(ENCRYPTION_FORWARD_SECURE,
std::move(crypters->decrypter),
true,
false);
one_rtt_keys_available_ = true;
delegate_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
delegate_->DiscardOldEncryptionKey(ENCRYPTION_INITIAL);
delegate_->NeuterHandshakeData();
}
void QuicCryptoClientHandshaker::DoInitializeServerConfigUpdate(
QuicCryptoClientConfig::CachedState* cached) {
bool update_ignored = false;
if (!cached->IsEmpty() && !cached->signature().empty()) {
QUICHE_DCHECK(crypto_config_->proof_verifier());
next_state_ = STATE_VERIFY_PROOF;
} else {
update_ignored = true;
next_state_ = STATE_NONE;
}
QUIC_CLIENT_HISTOGRAM_COUNTS("QuicNumServerConfig.UpdateMessagesIgnored",
update_ignored, 1, 1000000, 50, "");
}
void QuicCryptoClientHandshaker::SetCachedProofValid(
QuicCryptoClientConfig::CachedState* cached) {
cached->SetProofValid();
proof_handler_->OnProofValid(*cached);
}
} | #include "quiche/quic/core/quic_crypto_client_handshaker.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/strings/string_view.h"
#include "quiche/quic/core/proto/crypto_server_config_proto.h"
#include "quiche/quic/platform/api/quic_test.h"
#include "quiche/quic/test_tools/quic_test_utils.h"
namespace quic::test {
namespace {
class TestProofHandler : public QuicCryptoClientStream::ProofHandler {
public:
~TestProofHandler() override {}
void OnProofValid(
const QuicCryptoClientConfig::CachedState& ) override {}
void OnProofVerifyDetailsAvailable(
const ProofVerifyDetails& ) override {}
};
class InsecureProofVerifier : public ProofVerifier {
public:
InsecureProofVerifier() {}
~InsecureProofVerifier() override {}
QuicAsyncStatus 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* ,
std::unique_ptr<ProofVerifyDetails>* ,
std::unique_ptr<ProofVerifierCallback> ) override {
return QUIC_SUCCESS;
}
QuicAsyncStatus VerifyCertChain(
const std::string& , const uint16_t ,
const std::vector<std::string>& ,
const std::string& , const std::string& ,
const ProofVerifyContext* , std::string* ,
std::unique_ptr<ProofVerifyDetails>* , uint8_t* ,
std::unique_ptr<ProofVerifierCallback> ) override {
return QUIC_SUCCESS;
}
std::unique_ptr<ProofVerifyContext> CreateDefaultContext() override {
return nullptr;
}
};
class DummyProofSource : public ProofSource {
public:
DummyProofSource() {}
~DummyProofSource() override {}
void GetProof(const QuicSocketAddress& server_address,
const QuicSocketAddress& client_address,
const std::string& hostname,
const std::string& ,
QuicTransportVersion ,
absl::string_view ,
std::unique_ptr<Callback> callback) override {
bool cert_matched_sni;
quiche::QuicheReferenceCountedPointer<ProofSource::Chain> chain =
GetCertChain(server_address, client_address, hostname,
&cert_matched_sni);
QuicCryptoProof proof;
proof.signature = "Dummy signature";
proof.leaf_cert_scts = "Dummy timestamp";
proof.cert_matched_sni = cert_matched_sni;
callback->Run(true, chain, proof, nullptr);
}
quiche::QuicheReferenceCountedPointer<Chain> GetCertChain(
const QuicSocketAddress& ,
const QuicSocketAddress& ,
const std::string& , bool* ) override {
std::vector<std::string> certs;
certs.push_back("Dummy cert");
return quiche::QuicheReferenceCountedPointer<ProofSource::Chain>(
new ProofSource::Chain(certs));
}
void ComputeTlsSignature(
const QuicSocketAddress& ,
const QuicSocketAddress& ,
const std::string& , uint16_t ,
absl::string_view ,
std::unique_ptr<SignatureCallback> callback) override {
callback->Run(true, "Dummy signature", nullptr);
}
absl::InlinedVector<uint16_t, 8> SupportedTlsSignatureAlgorithms()
const override {
return {};
}
TicketCrypter* GetTicketCrypter() override { return nullptr; }
};
class Handshaker : public QuicCryptoClientHandshaker {
public:
Handshaker(const QuicServerId& server_id, QuicCryptoClientStream* stream,
QuicSession* session,
std::unique_ptr<ProofVerifyContext> verify_context,
QuicCryptoClientConfig* crypto_config,
QuicCryptoClientStream::ProofHandler* proof_handler)
: QuicCryptoClientHandshaker(server_id, stream, session,
std::move(verify_context), crypto_config,
proof_handler) {}
void DoSendCHLOTest(QuicCryptoClientConfig::CachedState* cached) {
QuicCryptoClientHandshaker::DoSendCHLO(cached);
}
};
class QuicCryptoClientHandshakerTest
: public QuicTestWithParam<ParsedQuicVersion> {
protected:
QuicCryptoClientHandshakerTest()
: version_(GetParam()),
proof_handler_(),
helper_(),
alarm_factory_(),
server_id_("host", 123),
connection_(new test::MockQuicConnection(
&helper_, &alarm_factory_, Perspective::IS_CLIENT, {version_})),
session_(connection_, false),
crypto_client_config_(std::make_unique<InsecureProofVerifier>()),
client_stream_(
new QuicCryptoClientStream(server_id_, &session_, nullptr,
&crypto_client_config_, &proof_handler_,
false)),
handshaker_(server_id_, client_stream_, &session_, nullptr,
&crypto_client_config_, &proof_handler_),
state_() {
session_.SetCryptoStream(client_stream_);
session_.Initialize();
}
void InitializeServerParametersToEnableFullHello() {
QuicCryptoServerConfig::ConfigOptions options;
QuicServerConfigProtobuf config = QuicCryptoServerConfig::GenerateConfig(
helper_.GetRandomGenerator(), helper_.GetClock(), options);
state_.Initialize(
config.config(), "sourcetoken", std::vector<std::string>{"Dummy cert"},
"", "chlo_hash", "signature", helper_.GetClock()->WallNow(),
helper_.GetClock()->WallNow().Add(QuicTime::Delta::FromSeconds(30)));
state_.SetProofValid();
}
ParsedQuicVersion version_;
TestProofHandler proof_handler_;
test::MockQuicConnectionHelper helper_;
test::MockAlarmFactory alarm_factory_;
QuicServerId server_id_;
test::MockQuicConnection* connection_;
test::MockQuicSession session_;
QuicCryptoClientConfig crypto_client_config_;
QuicCryptoClientStream* client_stream_;
Handshaker handshaker_;
QuicCryptoClientConfig::CachedState state_;
};
INSTANTIATE_TEST_SUITE_P(
QuicCryptoClientHandshakerTests, QuicCryptoClientHandshakerTest,
::testing::ValuesIn(AllSupportedVersionsWithQuicCrypto()),
::testing::PrintToStringParamName());
TEST_P(QuicCryptoClientHandshakerTest, TestSendFullPaddingInInchoateHello) {
handshaker_.DoSendCHLOTest(&state_);
EXPECT_TRUE(connection_->fully_pad_during_crypto_handshake());
}
TEST_P(QuicCryptoClientHandshakerTest, TestDisabledPaddingInInchoateHello) {
crypto_client_config_.set_pad_inchoate_hello(false);
handshaker_.DoSendCHLOTest(&state_);
EXPECT_FALSE(connection_->fully_pad_during_crypto_handshake());
}
TEST_P(QuicCryptoClientHandshakerTest,
TestPaddingInFullHelloEvenIfInchoateDisabled) {
crypto_client_config_.set_pad_inchoate_hello(false);
InitializeServerParametersToEnableFullHello();
handshaker_.DoSendCHLOTest(&state_);
EXPECT_TRUE(connection_->fully_pad_during_crypto_handshake());
}
TEST_P(QuicCryptoClientHandshakerTest, TestNoPaddingInFullHelloWhenDisabled) {
crypto_client_config_.set_pad_full_hello(false);
InitializeServerParametersToEnableFullHello();
handshaker_.DoSendCHLOTest(&state_);
EXPECT_FALSE(connection_->fully_pad_during_crypto_handshake());
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_crypto_client_handshaker.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_crypto_client_handshaker_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
7aa386ba-d412-45b1-a72a-31fec0ee84bf | cpp | google/quiche | quic_packet_number | quiche/quic/core/quic_packet_number.cc | quiche/quic/core/quic_packet_number_test.cc | #include "quiche/quic/core/quic_packet_number.h"
#include <algorithm>
#include <limits>
#include <ostream>
#include <string>
#include "absl/strings/str_cat.h"
namespace quic {
void QuicPacketNumber::Clear() { packet_number_ = UninitializedPacketNumber(); }
void QuicPacketNumber::UpdateMax(QuicPacketNumber new_value) {
if (!new_value.IsInitialized()) {
return;
}
if (!IsInitialized()) {
packet_number_ = new_value.ToUint64();
} else {
packet_number_ = std::max(packet_number_, new_value.ToUint64());
}
}
uint64_t QuicPacketNumber::Hash() const {
QUICHE_DCHECK(IsInitialized());
return packet_number_;
}
uint64_t QuicPacketNumber::ToUint64() const {
QUICHE_DCHECK(IsInitialized());
return packet_number_;
}
bool QuicPacketNumber::IsInitialized() const {
return packet_number_ != UninitializedPacketNumber();
}
QuicPacketNumber& QuicPacketNumber::operator++() {
#ifndef NDEBUG
QUICHE_DCHECK(IsInitialized());
QUICHE_DCHECK_LT(ToUint64(), std::numeric_limits<uint64_t>::max() - 1);
#endif
packet_number_++;
return *this;
}
QuicPacketNumber QuicPacketNumber::operator++(int) {
#ifndef NDEBUG
QUICHE_DCHECK(IsInitialized());
QUICHE_DCHECK_LT(ToUint64(), std::numeric_limits<uint64_t>::max() - 1);
#endif
QuicPacketNumber previous(*this);
packet_number_++;
return previous;
}
QuicPacketNumber& QuicPacketNumber::operator--() {
#ifndef NDEBUG
QUICHE_DCHECK(IsInitialized());
QUICHE_DCHECK_GE(ToUint64(), 1UL);
#endif
packet_number_--;
return *this;
}
QuicPacketNumber QuicPacketNumber::operator--(int) {
#ifndef NDEBUG
QUICHE_DCHECK(IsInitialized());
QUICHE_DCHECK_GE(ToUint64(), 1UL);
#endif
QuicPacketNumber previous(*this);
packet_number_--;
return previous;
}
QuicPacketNumber& QuicPacketNumber::operator+=(uint64_t delta) {
#ifndef NDEBUG
QUICHE_DCHECK(IsInitialized());
QUICHE_DCHECK_GT(std::numeric_limits<uint64_t>::max() - ToUint64(), delta);
#endif
packet_number_ += delta;
return *this;
}
QuicPacketNumber& QuicPacketNumber::operator-=(uint64_t delta) {
#ifndef NDEBUG
QUICHE_DCHECK(IsInitialized());
QUICHE_DCHECK_GE(ToUint64(), delta);
#endif
packet_number_ -= delta;
return *this;
}
std::string QuicPacketNumber::ToString() const {
if (!IsInitialized()) {
return "uninitialized";
}
return absl::StrCat(ToUint64());
}
std::ostream& operator<<(std::ostream& os, const QuicPacketNumber& p) {
os << p.ToString();
return os;
}
} | #include "quiche/quic/core/quic_packet_number.h"
#include "quiche/quic/platform/api/quic_flags.h"
#include "quiche/quic/platform/api/quic_test.h"
namespace quic {
namespace test {
namespace {
TEST(QuicPacketNumberTest, BasicTest) {
QuicPacketNumber num;
EXPECT_FALSE(num.IsInitialized());
QuicPacketNumber num2(10);
EXPECT_TRUE(num2.IsInitialized());
EXPECT_EQ(10u, num2.ToUint64());
EXPECT_EQ(10u, num2.Hash());
num2.UpdateMax(num);
EXPECT_EQ(10u, num2.ToUint64());
num2.UpdateMax(QuicPacketNumber(9));
EXPECT_EQ(10u, num2.ToUint64());
num2.UpdateMax(QuicPacketNumber(11));
EXPECT_EQ(11u, num2.ToUint64());
num2.Clear();
EXPECT_FALSE(num2.IsInitialized());
num2.UpdateMax(QuicPacketNumber(9));
EXPECT_EQ(9u, num2.ToUint64());
QuicPacketNumber num4(0);
EXPECT_TRUE(num4.IsInitialized());
EXPECT_EQ(0u, num4.ToUint64());
EXPECT_EQ(0u, num4.Hash());
num4.Clear();
EXPECT_FALSE(num4.IsInitialized());
}
TEST(QuicPacketNumberTest, Operators) {
QuicPacketNumber num(100);
EXPECT_EQ(QuicPacketNumber(100), num++);
EXPECT_EQ(QuicPacketNumber(101), num);
EXPECT_EQ(QuicPacketNumber(101), num--);
EXPECT_EQ(QuicPacketNumber(100), num);
EXPECT_EQ(QuicPacketNumber(101), ++num);
EXPECT_EQ(QuicPacketNumber(100), --num);
QuicPacketNumber num3(0);
EXPECT_EQ(QuicPacketNumber(0), num3++);
EXPECT_EQ(QuicPacketNumber(1), num3);
EXPECT_EQ(QuicPacketNumber(2), ++num3);
EXPECT_EQ(QuicPacketNumber(2), num3--);
EXPECT_EQ(QuicPacketNumber(1), num3);
EXPECT_EQ(QuicPacketNumber(0), --num3);
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_packet_number.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_packet_number_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
09cb284c-bf40-4c9c-9f0c-54355ea7ec3e | cpp | google/quiche | quic_stream_priority | quiche/quic/core/quic_stream_priority.cc | quiche/quic/core/quic_stream_priority_test.cc | #include "quiche/quic/core/quic_stream_priority.h"
#include <optional>
#include <string>
#include <vector>
#include "quiche/common/platform/api/quiche_bug_tracker.h"
#include "quiche/common/structured_headers.h"
namespace quic {
std::string SerializePriorityFieldValue(HttpStreamPriority priority) {
quiche::structured_headers::Dictionary dictionary;
if (priority.urgency != HttpStreamPriority::kDefaultUrgency &&
priority.urgency >= HttpStreamPriority::kMinimumUrgency &&
priority.urgency <= HttpStreamPriority::kMaximumUrgency) {
dictionary[HttpStreamPriority::kUrgencyKey] =
quiche::structured_headers::ParameterizedMember(
quiche::structured_headers::Item(
static_cast<int64_t>(priority.urgency)),
{});
}
if (priority.incremental != HttpStreamPriority::kDefaultIncremental) {
dictionary[HttpStreamPriority::kIncrementalKey] =
quiche::structured_headers::ParameterizedMember(
quiche::structured_headers::Item(priority.incremental), {});
}
std::optional<std::string> priority_field_value =
quiche::structured_headers::SerializeDictionary(dictionary);
if (!priority_field_value.has_value()) {
QUICHE_BUG(priority_field_value_serialization_failed);
return "";
}
return *priority_field_value;
}
std::optional<HttpStreamPriority> ParsePriorityFieldValue(
absl::string_view priority_field_value) {
std::optional<quiche::structured_headers::Dictionary> parsed_dictionary =
quiche::structured_headers::ParseDictionary(priority_field_value);
if (!parsed_dictionary.has_value()) {
return std::nullopt;
}
uint8_t urgency = HttpStreamPriority::kDefaultUrgency;
bool incremental = HttpStreamPriority::kDefaultIncremental;
for (const auto& [name, value] : *parsed_dictionary) {
if (value.member_is_inner_list) {
continue;
}
const std::vector<quiche::structured_headers::ParameterizedItem>& member =
value.member;
if (member.size() != 1) {
QUICHE_BUG(priority_field_value_parsing_internal_error);
continue;
}
const quiche::structured_headers::Item item = member[0].item;
if (name == HttpStreamPriority::kUrgencyKey && item.is_integer()) {
int parsed_urgency = item.GetInteger();
if (parsed_urgency >= HttpStreamPriority::kMinimumUrgency &&
parsed_urgency <= HttpStreamPriority::kMaximumUrgency) {
urgency = parsed_urgency;
}
} else if (name == HttpStreamPriority::kIncrementalKey &&
item.is_boolean()) {
incremental = item.GetBoolean();
}
}
return HttpStreamPriority{urgency, incremental};
}
} | #include "quiche/quic/core/quic_stream_priority.h"
#include <optional>
#include "quiche/quic/core/quic_types.h"
#include "quiche/common/platform/api/quiche_test.h"
namespace quic::test {
TEST(HttpStreamPriority, DefaultConstructed) {
HttpStreamPriority priority;
EXPECT_EQ(HttpStreamPriority::kDefaultUrgency, priority.urgency);
EXPECT_EQ(HttpStreamPriority::kDefaultIncremental, priority.incremental);
}
TEST(HttpStreamPriority, Equals) {
EXPECT_EQ((HttpStreamPriority()),
(HttpStreamPriority{HttpStreamPriority::kDefaultUrgency,
HttpStreamPriority::kDefaultIncremental}));
EXPECT_EQ((HttpStreamPriority{5, true}), (HttpStreamPriority{5, true}));
EXPECT_EQ((HttpStreamPriority{2, false}), (HttpStreamPriority{2, false}));
EXPECT_EQ((HttpStreamPriority{11, true}), (HttpStreamPriority{11, true}));
EXPECT_NE((HttpStreamPriority{1, true}), (HttpStreamPriority{3, true}));
EXPECT_NE((HttpStreamPriority{4, false}), (HttpStreamPriority{4, true}));
EXPECT_NE((HttpStreamPriority{6, true}), (HttpStreamPriority{2, false}));
EXPECT_NE((HttpStreamPriority{12, true}), (HttpStreamPriority{9, true}));
EXPECT_NE((HttpStreamPriority{2, false}), (HttpStreamPriority{8, false}));
}
TEST(WebTransportStreamPriority, DefaultConstructed) {
WebTransportStreamPriority priority;
EXPECT_EQ(priority.session_id, 0);
EXPECT_EQ(priority.send_group_number, 0);
EXPECT_EQ(priority.send_order, 0);
}
TEST(WebTransportStreamPriority, Equals) {
EXPECT_EQ(WebTransportStreamPriority(),
(WebTransportStreamPriority{0, 0, 0}));
EXPECT_NE(WebTransportStreamPriority(),
(WebTransportStreamPriority{1, 2, 3}));
EXPECT_NE(WebTransportStreamPriority(),
(WebTransportStreamPriority{0, 0, 1}));
}
TEST(QuicStreamPriority, Default) {
EXPECT_EQ(QuicStreamPriority().type(), QuicPriorityType::kHttp);
EXPECT_EQ(QuicStreamPriority().http(), HttpStreamPriority());
}
TEST(QuicStreamPriority, Equals) {
EXPECT_EQ(QuicStreamPriority(), QuicStreamPriority(HttpStreamPriority()));
}
TEST(QuicStreamPriority, Type) {
EXPECT_EQ(QuicStreamPriority(HttpStreamPriority()).type(),
QuicPriorityType::kHttp);
EXPECT_EQ(QuicStreamPriority(WebTransportStreamPriority()).type(),
QuicPriorityType::kWebTransport);
}
TEST(SerializePriorityFieldValueTest, SerializePriorityFieldValue) {
EXPECT_EQ("", SerializePriorityFieldValue(
{ 3, false}));
EXPECT_EQ("u=5", SerializePriorityFieldValue(
{ 5, false}));
EXPECT_EQ("i", SerializePriorityFieldValue(
{ 3, true}));
EXPECT_EQ("u=0, i", SerializePriorityFieldValue(
{ 0, true}));
EXPECT_EQ("i", SerializePriorityFieldValue(
{ 9, true}));
}
TEST(ParsePriorityFieldValueTest, ParsePriorityFieldValue) {
std::optional<HttpStreamPriority> result = ParsePriorityFieldValue("");
ASSERT_TRUE(result.has_value());
EXPECT_EQ(3, result->urgency);
EXPECT_FALSE(result->incremental);
result = ParsePriorityFieldValue("i=?1");
ASSERT_TRUE(result.has_value());
EXPECT_EQ(3, result->urgency);
EXPECT_TRUE(result->incremental);
result = ParsePriorityFieldValue("u=5");
ASSERT_TRUE(result.has_value());
EXPECT_EQ(5, result->urgency);
EXPECT_FALSE(result->incremental);
result = ParsePriorityFieldValue("u=5, i");
ASSERT_TRUE(result.has_value());
EXPECT_EQ(5, result->urgency);
EXPECT_TRUE(result->incremental);
result = ParsePriorityFieldValue("i, u=1");
ASSERT_TRUE(result.has_value());
EXPECT_EQ(1, result->urgency);
EXPECT_TRUE(result->incremental);
result = ParsePriorityFieldValue("u=5, i=?1, i=?0, u=2");
ASSERT_TRUE(result.has_value());
EXPECT_EQ(2, result->urgency);
EXPECT_FALSE(result->incremental);
result = ParsePriorityFieldValue("a=42, u=4, i=?0");
ASSERT_TRUE(result.has_value());
EXPECT_EQ(4, result->urgency);
EXPECT_FALSE(result->incremental);
result = ParsePriorityFieldValue("u=-2, i");
ASSERT_TRUE(result.has_value());
EXPECT_EQ(3, result->urgency);
EXPECT_TRUE(result->incremental);
result = ParsePriorityFieldValue("u=4.2, i=\"foo\"");
ASSERT_TRUE(result.has_value());
EXPECT_EQ(3, result->urgency);
EXPECT_FALSE(result->incremental);
result = ParsePriorityFieldValue("a=4, b=?1");
ASSERT_TRUE(result.has_value());
EXPECT_EQ(3, result->urgency);
EXPECT_FALSE(result->incremental);
result = ParsePriorityFieldValue("000");
EXPECT_FALSE(result.has_value());
result = ParsePriorityFieldValue("a=(1 2), u=1");
ASSERT_TRUE(result.has_value());
EXPECT_EQ(1, result->urgency);
EXPECT_FALSE(result->incremental);
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_stream_priority.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_stream_priority_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
7aae7bdd-3782-4a7a-a22a-065ac38df147 | cpp | google/quiche | quic_unacked_packet_map | quiche/quic/core/quic_unacked_packet_map.cc | quiche/quic/core/quic_unacked_packet_map_test.cc | #include "quiche/quic/core/quic_unacked_packet_map.h"
#include <cstddef>
#include <limits>
#include <type_traits>
#include <utility>
#include "absl/container/inlined_vector.h"
#include "quiche/quic/core/quic_connection_stats.h"
#include "quiche/quic/core/quic_packet_number.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"
namespace quic {
namespace {
bool WillStreamFrameLengthSumWrapAround(QuicPacketLength lhs,
QuicPacketLength rhs) {
static_assert(
std::is_unsigned<QuicPacketLength>::value,
"This function assumes QuicPacketLength is an unsigned integer type.");
return std::numeric_limits<QuicPacketLength>::max() - lhs < rhs;
}
enum QuicFrameTypeBitfield : uint32_t {
kInvalidFrameBitfield = 0,
kPaddingFrameBitfield = 1,
kRstStreamFrameBitfield = 1 << 1,
kConnectionCloseFrameBitfield = 1 << 2,
kGoawayFrameBitfield = 1 << 3,
kWindowUpdateFrameBitfield = 1 << 4,
kBlockedFrameBitfield = 1 << 5,
kStopWaitingFrameBitfield = 1 << 6,
kPingFrameBitfield = 1 << 7,
kCryptoFrameBitfield = 1 << 8,
kHandshakeDoneFrameBitfield = 1 << 9,
kStreamFrameBitfield = 1 << 10,
kAckFrameBitfield = 1 << 11,
kMtuDiscoveryFrameBitfield = 1 << 12,
kNewConnectionIdFrameBitfield = 1 << 13,
kMaxStreamsFrameBitfield = 1 << 14,
kStreamsBlockedFrameBitfield = 1 << 15,
kPathResponseFrameBitfield = 1 << 16,
kPathChallengeFrameBitfield = 1 << 17,
kStopSendingFrameBitfield = 1 << 18,
kMessageFrameBitfield = 1 << 19,
kNewTokenFrameBitfield = 1 << 20,
kRetireConnectionIdFrameBitfield = 1 << 21,
kAckFrequencyFrameBitfield = 1 << 22,
kResetStreamAtFrameBitfield = 1 << 23,
};
QuicFrameTypeBitfield GetFrameTypeBitfield(QuicFrameType type) {
switch (type) {
case PADDING_FRAME:
return kPaddingFrameBitfield;
case RST_STREAM_FRAME:
return kRstStreamFrameBitfield;
case CONNECTION_CLOSE_FRAME:
return kConnectionCloseFrameBitfield;
case GOAWAY_FRAME:
return kGoawayFrameBitfield;
case WINDOW_UPDATE_FRAME:
return kWindowUpdateFrameBitfield;
case BLOCKED_FRAME:
return kBlockedFrameBitfield;
case STOP_WAITING_FRAME:
return kStopWaitingFrameBitfield;
case PING_FRAME:
return kPingFrameBitfield;
case CRYPTO_FRAME:
return kCryptoFrameBitfield;
case HANDSHAKE_DONE_FRAME:
return kHandshakeDoneFrameBitfield;
case STREAM_FRAME:
return kStreamFrameBitfield;
case ACK_FRAME:
return kAckFrameBitfield;
case MTU_DISCOVERY_FRAME:
return kMtuDiscoveryFrameBitfield;
case NEW_CONNECTION_ID_FRAME:
return kNewConnectionIdFrameBitfield;
case MAX_STREAMS_FRAME:
return kMaxStreamsFrameBitfield;
case STREAMS_BLOCKED_FRAME:
return kStreamsBlockedFrameBitfield;
case PATH_RESPONSE_FRAME:
return kPathResponseFrameBitfield;
case PATH_CHALLENGE_FRAME:
return kPathChallengeFrameBitfield;
case STOP_SENDING_FRAME:
return kStopSendingFrameBitfield;
case MESSAGE_FRAME:
return kMessageFrameBitfield;
case NEW_TOKEN_FRAME:
return kNewTokenFrameBitfield;
case RETIRE_CONNECTION_ID_FRAME:
return kRetireConnectionIdFrameBitfield;
case ACK_FREQUENCY_FRAME:
return kAckFrequencyFrameBitfield;
case RESET_STREAM_AT_FRAME:
return kResetStreamAtFrameBitfield;
case NUM_FRAME_TYPES:
QUIC_BUG(quic_bug_10518_1) << "Unexpected frame type";
return kInvalidFrameBitfield;
}
QUIC_BUG(quic_bug_10518_2) << "Unexpected frame type";
return kInvalidFrameBitfield;
}
}
QuicUnackedPacketMap::QuicUnackedPacketMap(Perspective perspective)
: perspective_(perspective),
least_unacked_(FirstSendingPacketNumber()),
bytes_in_flight_(0),
bytes_in_flight_per_packet_number_space_{0, 0, 0},
packets_in_flight_(0),
last_inflight_packet_sent_time_(QuicTime::Zero()),
last_inflight_packets_sent_time_{
{QuicTime::Zero()}, {QuicTime::Zero()}, {QuicTime::Zero()}},
last_crypto_packet_sent_time_(QuicTime::Zero()),
session_notifier_(nullptr),
supports_multiple_packet_number_spaces_(false) {}
QuicUnackedPacketMap::~QuicUnackedPacketMap() {
for (QuicTransmissionInfo& transmission_info : unacked_packets_) {
DeleteFrames(&(transmission_info.retransmittable_frames));
}
}
const QuicTransmissionInfo& QuicUnackedPacketMap::AddDispatcherSentPacket(
const DispatcherSentPacket& packet) {
QuicPacketNumber packet_number = packet.packet_number;
QUICHE_DCHECK_EQ(least_unacked_, FirstSendingPacketNumber());
QUIC_BUG_IF(quic_unacked_map_dispatcher_packet_num_too_small,
largest_sent_packet_.IsInitialized() &&
largest_sent_packet_ >= packet_number)
<< "largest_sent_packet_: " << largest_sent_packet_
<< ", packet_number: " << packet_number;
QUICHE_DCHECK_GE(packet_number, least_unacked_ + unacked_packets_.size());
while (least_unacked_ + unacked_packets_.size() < packet_number) {
unacked_packets_.push_back(QuicTransmissionInfo());
unacked_packets_.back().state = NEVER_SENT;
}
QuicTransmissionInfo& info =
unacked_packets_.emplace_back(ENCRYPTION_INITIAL, NOT_RETRANSMISSION,
packet.sent_time, packet.bytes_sent,
false,
false, ECN_NOT_ECT);
QUICHE_DCHECK(!info.in_flight);
info.state = NOT_CONTRIBUTING_RTT;
info.largest_acked = packet.largest_acked;
largest_sent_largest_acked_.UpdateMax(packet.largest_acked);
largest_sent_packet_ = packet_number;
return info;
}
void QuicUnackedPacketMap::AddSentPacket(SerializedPacket* mutable_packet,
TransmissionType transmission_type,
QuicTime sent_time, bool set_in_flight,
bool measure_rtt,
QuicEcnCodepoint ecn_codepoint) {
const SerializedPacket& packet = *mutable_packet;
QuicPacketNumber packet_number = packet.packet_number;
QuicPacketLength bytes_sent = packet.encrypted_length;
QUIC_BUG_IF(quic_bug_12645_1, largest_sent_packet_.IsInitialized() &&
largest_sent_packet_ >= packet_number)
<< "largest_sent_packet_: " << largest_sent_packet_
<< ", packet_number: " << packet_number;
QUICHE_DCHECK_GE(packet_number, least_unacked_ + unacked_packets_.size());
while (least_unacked_ + unacked_packets_.size() < packet_number) {
unacked_packets_.push_back(QuicTransmissionInfo());
unacked_packets_.back().state = NEVER_SENT;
}
const bool has_crypto_handshake = packet.has_crypto_handshake == IS_HANDSHAKE;
QuicTransmissionInfo info(packet.encryption_level, transmission_type,
sent_time, bytes_sent, has_crypto_handshake,
packet.has_ack_frequency, ecn_codepoint);
info.largest_acked = packet.largest_acked;
largest_sent_largest_acked_.UpdateMax(packet.largest_acked);
if (!measure_rtt) {
QUIC_BUG_IF(quic_bug_12645_2, set_in_flight)
<< "Packet " << mutable_packet->packet_number << ", transmission type "
<< TransmissionTypeToString(mutable_packet->transmission_type)
<< ", retransmittable frames: "
<< QuicFramesToString(mutable_packet->retransmittable_frames)
<< ", nonretransmittable_frames: "
<< QuicFramesToString(mutable_packet->nonretransmittable_frames);
info.state = NOT_CONTRIBUTING_RTT;
}
largest_sent_packet_ = packet_number;
if (set_in_flight) {
const PacketNumberSpace packet_number_space =
GetPacketNumberSpace(info.encryption_level);
bytes_in_flight_ += bytes_sent;
bytes_in_flight_per_packet_number_space_[packet_number_space] += bytes_sent;
++packets_in_flight_;
info.in_flight = true;
largest_sent_retransmittable_packets_[packet_number_space] = packet_number;
last_inflight_packet_sent_time_ = sent_time;
last_inflight_packets_sent_time_[packet_number_space] = sent_time;
}
unacked_packets_.push_back(std::move(info));
if (has_crypto_handshake) {
last_crypto_packet_sent_time_ = sent_time;
}
mutable_packet->retransmittable_frames.swap(
unacked_packets_.back().retransmittable_frames);
}
void QuicUnackedPacketMap::RemoveObsoletePackets() {
while (!unacked_packets_.empty()) {
if (!IsPacketUseless(least_unacked_, unacked_packets_.front())) {
break;
}
DeleteFrames(&unacked_packets_.front().retransmittable_frames);
unacked_packets_.pop_front();
++least_unacked_;
}
}
bool QuicUnackedPacketMap::HasRetransmittableFrames(
QuicPacketNumber packet_number) const {
QUICHE_DCHECK_GE(packet_number, least_unacked_);
QUICHE_DCHECK_LT(packet_number, least_unacked_ + unacked_packets_.size());
return HasRetransmittableFrames(
unacked_packets_[packet_number - least_unacked_]);
}
bool QuicUnackedPacketMap::HasRetransmittableFrames(
const QuicTransmissionInfo& info) const {
if (!QuicUtils::IsAckable(info.state)) {
return false;
}
for (const auto& frame : info.retransmittable_frames) {
if (session_notifier_->IsFrameOutstanding(frame)) {
return true;
}
}
return false;
}
void QuicUnackedPacketMap::RemoveRetransmittability(
QuicTransmissionInfo* info) {
DeleteFrames(&info->retransmittable_frames);
info->first_sent_after_loss.Clear();
}
void QuicUnackedPacketMap::RemoveRetransmittability(
QuicPacketNumber packet_number) {
QUICHE_DCHECK_GE(packet_number, least_unacked_);
QUICHE_DCHECK_LT(packet_number, least_unacked_ + unacked_packets_.size());
QuicTransmissionInfo* info =
&unacked_packets_[packet_number - least_unacked_];
RemoveRetransmittability(info);
}
void QuicUnackedPacketMap::IncreaseLargestAcked(
QuicPacketNumber largest_acked) {
QUICHE_DCHECK(!largest_acked_.IsInitialized() ||
largest_acked_ <= largest_acked);
largest_acked_ = largest_acked;
}
void QuicUnackedPacketMap::MaybeUpdateLargestAckedOfPacketNumberSpace(
PacketNumberSpace packet_number_space, QuicPacketNumber packet_number) {
largest_acked_packets_[packet_number_space].UpdateMax(packet_number);
}
bool QuicUnackedPacketMap::IsPacketUsefulForMeasuringRtt(
QuicPacketNumber packet_number, const QuicTransmissionInfo& info) const {
return QuicUtils::IsAckable(info.state) &&
(!largest_acked_.IsInitialized() || packet_number > largest_acked_) &&
info.state != NOT_CONTRIBUTING_RTT;
}
bool QuicUnackedPacketMap::IsPacketUsefulForCongestionControl(
const QuicTransmissionInfo& info) const {
return info.in_flight;
}
bool QuicUnackedPacketMap::IsPacketUsefulForRetransmittableData(
const QuicTransmissionInfo& info) const {
return info.first_sent_after_loss.IsInitialized() &&
(!largest_acked_.IsInitialized() ||
info.first_sent_after_loss > largest_acked_);
}
bool QuicUnackedPacketMap::IsPacketUseless(
QuicPacketNumber packet_number, const QuicTransmissionInfo& info) const {
return !IsPacketUsefulForMeasuringRtt(packet_number, info) &&
!IsPacketUsefulForCongestionControl(info) &&
!IsPacketUsefulForRetransmittableData(info);
}
bool QuicUnackedPacketMap::IsUnacked(QuicPacketNumber packet_number) const {
if (packet_number < least_unacked_ ||
packet_number >= least_unacked_ + unacked_packets_.size()) {
return false;
}
return !IsPacketUseless(packet_number,
unacked_packets_[packet_number - least_unacked_]);
}
void QuicUnackedPacketMap::RemoveFromInFlight(QuicTransmissionInfo* info) {
if (info->in_flight) {
QUIC_BUG_IF(quic_bug_12645_3, bytes_in_flight_ < info->bytes_sent);
QUIC_BUG_IF(quic_bug_12645_4, packets_in_flight_ == 0);
bytes_in_flight_ -= info->bytes_sent;
--packets_in_flight_;
const PacketNumberSpace packet_number_space =
GetPacketNumberSpace(info->encryption_level);
if (bytes_in_flight_per_packet_number_space_[packet_number_space] <
info->bytes_sent) {
QUIC_BUG(quic_bug_10518_3)
<< "bytes_in_flight: "
<< bytes_in_flight_per_packet_number_space_[packet_number_space]
<< " is smaller than bytes_sent: " << info->bytes_sent
<< " for packet number space: "
<< PacketNumberSpaceToString(packet_number_space);
bytes_in_flight_per_packet_number_space_[packet_number_space] = 0;
} else {
bytes_in_flight_per_packet_number_space_[packet_number_space] -=
info->bytes_sent;
}
if (bytes_in_flight_per_packet_number_space_[packet_number_space] == 0) {
last_inflight_packets_sent_time_[packet_number_space] = QuicTime::Zero();
}
info->in_flight = false;
}
}
void QuicUnackedPacketMap::RemoveFromInFlight(QuicPacketNumber packet_number) {
QUICHE_DCHECK_GE(packet_number, least_unacked_);
QUICHE_DCHECK_LT(packet_number, least_unacked_ + unacked_packets_.size());
QuicTransmissionInfo* info =
&unacked_packets_[packet_number - least_unacked_];
RemoveFromInFlight(info);
}
absl::InlinedVector<QuicPacketNumber, 2>
QuicUnackedPacketMap::NeuterUnencryptedPackets() {
absl::InlinedVector<QuicPacketNumber, 2> neutered_packets;
QuicPacketNumber packet_number = GetLeastUnacked();
for (QuicUnackedPacketMap::iterator it = begin(); it != end();
++it, ++packet_number) {
if (!it->retransmittable_frames.empty() &&
it->encryption_level == ENCRYPTION_INITIAL) {
QUIC_DVLOG(2) << "Neutering unencrypted packet " << packet_number;
RemoveFromInFlight(packet_number);
it->state = NEUTERED;
neutered_packets.push_back(packet_number);
NotifyFramesAcked(*it, QuicTime::Delta::Zero(), QuicTime::Zero());
QUICHE_DCHECK(!HasRetransmittableFrames(*it));
}
}
QUICHE_DCHECK(!supports_multiple_packet_number_spaces_ ||
last_inflight_packets_sent_time_[INITIAL_DATA] ==
QuicTime::Zero());
return neutered_packets;
}
absl::InlinedVector<QuicPacketNumber, 2>
QuicUnackedPacketMap::NeuterHandshakePackets() {
absl::InlinedVector<QuicPacketNumber, 2> neutered_packets;
QuicPacketNumber packet_number = GetLeastUnacked();
for (QuicUnackedPacketMap::iterator it = begin(); it != end();
++it, ++packet_number) {
if (!it->retransmittable_frames.empty() &&
GetPacketNumberSpace(it->encryption_level) == HANDSHAKE_DATA) {
QUIC_DVLOG(2) << "Neutering handshake packet " << packet_number;
RemoveFromInFlight(packet_number);
it->state = NEUTERED;
neutered_packets.push_back(packet_number);
NotifyFramesAcked(*it, QuicTime::Delta::Zero(), QuicTime::Zero());
}
}
QUICHE_DCHECK(!supports_multiple_packet_number_spaces() ||
last_inflight_packets_sent_time_[HANDSHAKE_DATA] ==
QuicTime::Zero());
return neutered_packets;
}
bool QuicUnackedPacketMap::HasInFlightPackets() const {
return bytes_in_flight_ > 0;
}
const QuicTransmissionInfo& QuicUnackedPacketMap::GetTransmissionInfo(
QuicPacketNumber packet_number) const {
return unacked_packets_[packet_number - least_unacked_];
}
QuicTransmissionInfo* QuicUnackedPacketMap::GetMutableTransmissionInfo(
QuicPacketNumber packet_number) {
return &unacked_packets_[packet_number - least_unacked_];
}
QuicTime QuicUnackedPacketMap::GetLastInFlightPacketSentTime() const {
return last_inflight_packet_sent_time_;
}
QuicTime QuicUnackedPacketMap::GetLastCryptoPacketSentTime() const {
return last_crypto_packet_sent_time_;
}
size_t QuicUnackedPacketMap::GetNumUnackedPacketsDebugOnly() const {
size_t unacked_packet_count = 0;
QuicPacketNumber packet_number = least_unacked_;
for (auto it = begin(); it != end(); ++it, ++packet_number) {
if (!IsPacketUseless(packet_number, *it)) {
++unacked_packet_count;
}
}
return unacked_packet_count;
}
bool QuicUnackedPacketMap::HasMultipleInFlightPackets() const {
if (bytes_in_flight_ > kDefaultTCPMSS) {
return true;
}
size_t num_in_flight = 0;
for (auto it = rbegin(); it != rend(); ++it) {
if (it->in_flight) {
++num_in_flight;
}
if (num_in_flight > 1) {
return true;
}
}
return false;
}
bool QuicUnackedPacketMap::HasPendingCryptoPackets() const {
return session_notifier_->HasUnackedCryptoData();
}
bool QuicUnackedPacketMap::HasUnackedRetransmittableFrames() const {
for (auto it = rbegin(); it != rend(); ++it) {
if (it->in_flight && HasRetransmittableFrames(*it)) {
return true;
}
}
return false;
}
QuicPacketNumber QuicUnackedPacketMap::GetLeastUnacked() const {
return least_unacked_;
}
void QuicUnackedPacketMap::SetSessionNotifier(
SessionNotifierInterface* session_notifier) {
session_notifier_ = session_notifier;
}
bool QuicUnackedPacketMap::NotifyFramesAcked(const QuicTransmissionInfo& info,
QuicTime::Delta ack_delay,
QuicTime receive_timestamp) {
if (session_notifier_ == nullptr) {
return false;
}
bool new_data_acked = false;
for (const QuicFrame& frame : info.retransmittable_frames) {
if (session_notifier_->OnFrameAcked(frame, ack_delay, receive_timestamp)) {
new_data_acked = true;
}
}
return new_data_acked;
}
void QuicUnackedPacketMap::NotifyFramesLost(const QuicTransmissionInfo& info,
TransmissionType ) {
for (const QuicFrame& frame : info.retransmittable_frames) {
session_notifier_->OnFrameLost(frame);
}
}
bool QuicUnackedPacketMap::RetransmitFrames(const QuicFrames& frames,
TransmissionType type) {
return session_notifier_->RetransmitFrames(frames, type);
}
void QuicUnackedPacketMap::MaybeAggregateAckedStreamFrame(
const QuicTransmissionInfo& info, QuicTime::Delta ack_delay,
QuicTime receive_timestamp) {
if (session_notifier_ == nullptr) {
return;
}
for (const auto& frame : info.retransmittable_frames) {
const bool can_aggregate =
frame.type == STREAM_FRAME &&
frame.stream_frame.stream_id == aggregated_stream_frame_.stream_id &&
frame.stream_frame.offset == aggregated_stream_frame_.offset +
aggregated_stream_frame_.data_length &&
!WillStreamFrameLengthSumWrapAround(
aggregated_stream_frame_.data_length,
frame.stream_frame.data_length);
if (can_aggregate) {
aggregated_stream_frame_.data_length += frame.stream_frame.data_length;
aggregated_stream_frame_.fin = frame.stream_frame.fin;
if (aggregated_stream_frame_.fin) {
NotifyAggregatedStreamFrameAcked(ack_delay);
}
continue;
}
NotifyAggregatedStreamFrameAcked(ack_delay);
if (frame.type != STREAM_FRAME || frame.stream_frame.fin) {
session_notifier_->OnFrameAcked(frame, ack_delay, receive_timestamp);
continue;
}
aggregated_stream_frame_.stream_id = frame.stream_frame.stream_id;
aggregated_stream_frame_.offset = frame.stream_frame.offset;
aggregated_stream_frame_.data_length = frame.stream_frame.data_length;
aggregated_stream_frame_.fin = frame.stream_frame.fin;
}
}
void QuicUnackedPacketMap::NotifyAggregatedStreamFrameAcked(
QuicTime::Delta ack_delay) {
if (aggregated_stream_frame_.stream_id == static_cast<QuicStreamId>(-1) ||
session_notifier_ == nullptr) {
return;
}
session_notifier_->OnFrameAcked(QuicFrame(aggregated_stream_frame_),
ack_delay,
QuicTime::Zero());
aggregated_stream_frame_.stream_id = -1;
}
PacketNumberSpace QuicUnackedPacketMap::GetPacketNumberSpace(
QuicPacketNumber packet_number) const {
return GetPacketNumberSpace(
GetTransmissionInfo(packet_number).encryption_level);
}
PacketNumberSpace QuicUnackedPacketMap::GetPacketNumberSpace(
EncryptionLevel encryption_level) const {
if (supports_multiple_packet_number_spaces_) {
return QuicUtils::GetPacketNumberSpace(encryption_level);
}
if (perspective_ == Perspective::IS_CLIENT) {
return encryption_level == ENCRYPTION_INITIAL ? HANDSHAKE_DATA
: APPLICATION_DATA;
}
return encryption_level == ENCRYPTION_FORWARD_SECURE ? APPLICATION_DATA
: HANDSHAKE_DATA;
}
QuicPacketNumber QuicUnackedPacketMap::GetLargestAckedOfPacketNumberSpace(
PacketNumberSpace packet_number_space) const {
if (packet_number_space >= NUM_PACKET_NUMBER_SPACES) {
QUIC_BUG(quic_bug_10518_4)
<< "Invalid packet number space: " << packet_number_space;
return QuicPacketNumber();
}
return largest_acked_packets_[packet_number_space];
}
QuicTime QuicUnackedPacketMap::GetLastInFlightPacketSentTime(
PacketNumberSpace packet_number_space) const {
if (packet_number_space >= NUM_PACKET_NUMBER_SPACES) {
QUIC_BUG(quic_bug_10518_5)
<< "Invalid packet number space: " << packet_number_space;
return QuicTime::Zero();
}
return last_inflight_packets_sent_time_[packet_number_space];
}
QuicPacketNumber
QuicUnackedPacketMap::GetLargestSentRetransmittableOfPacketNumberSpace(
PacketNumberSpace packet_number_space) const {
if (packet_number_space >= NUM_PACKET_NUMBER_SPACES) {
QUIC_BUG(quic_bug_10518_6)
<< "Invalid packet number space: " << packet_number_space;
return QuicPacketNumber();
}
return largest_sent_retransmittable_packets_[packet_number_space];
}
const QuicTransmissionInfo*
QuicUnackedPacketMap::GetFirstInFlightTransmissionInfo() const {
QUICHE_DCHECK(HasInFlightPackets());
for (auto it = begin(); it != end(); ++it) {
if (it->in_flight) {
return &(*it);
}
}
QUICHE_DCHECK(false);
return nullptr;
}
const QuicTransmissionInfo*
QuicUnackedPacketMap::GetFirstInFlightTransmissionInfoOfSpace(
PacketNumberSpace packet_number_space) const {
for (auto it = begin(); it != end(); ++it) {
if (it->in_flight &&
GetPacketNumberSpace(it->encryption_level) == packet_number_space) {
return &(*it);
}
}
return nullptr;
}
void QuicUnackedPacketMap::EnableMultiplePacketNumberSpacesSupport() {
if (supports_multiple_packet_number_spaces_) {
QUIC_BUG(quic_bug_10518_7)
<< "Multiple packet number spaces has already been enabled";
return;
}
if (largest_sent_packet_.IsInitialized()) {
QUIC_BUG(quic_bug_10518_8)
<< "Try to enable multiple packet number spaces support after any "
"packet has been sent.";
return;
}
supports_multiple_packet_number_spaces_ = true;
}
int32_t QuicUnackedPacketMap::GetLastPacketContent() const {
if (empty()) {
return -1;
}
int32_t content = 0;
const QuicTransmissionInfo& last_packet = unacked_packets_.back();
for (const auto& frame : last_packet.retransmittable_frames) {
content |= GetFrameTypeBitfield(frame.type);
}
if (last_packet.largest_acked.IsInitialized()) {
content |= GetFrameTypeBitfield(ACK_FRAME);
}
return content;
}
} | #include "quiche/quic/core/quic_unacked_packet_map.h"
#include <cstddef>
#include <limits>
#include <vector>
#include "absl/base/macros.h"
#include "quiche/quic/core/frames/quic_stream_frame.h"
#include "quiche/quic/core/quic_packet_number.h"
#include "quiche/quic/core/quic_transmission_info.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/quic/test_tools/quic_unacked_packet_map_peer.h"
using testing::_;
using testing::Return;
using testing::StrictMock;
namespace quic {
namespace test {
namespace {
const uint32_t kDefaultLength = 1000;
class QuicUnackedPacketMapTest : public QuicTestWithParam<Perspective> {
protected:
QuicUnackedPacketMapTest()
: unacked_packets_(GetParam()),
now_(QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1000)) {
unacked_packets_.SetSessionNotifier(¬ifier_);
EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(true));
EXPECT_CALL(notifier_, OnStreamFrameRetransmitted(_))
.Times(testing::AnyNumber());
}
~QuicUnackedPacketMapTest() override {}
SerializedPacket CreateRetransmittablePacket(uint64_t packet_number) {
return CreateRetransmittablePacketForStream(
packet_number, QuicUtils::GetFirstBidirectionalStreamId(
CurrentSupportedVersions()[0].transport_version,
Perspective::IS_CLIENT));
}
SerializedPacket CreateRetransmittablePacketForStream(
uint64_t packet_number, QuicStreamId stream_id) {
SerializedPacket packet(QuicPacketNumber(packet_number),
PACKET_1BYTE_PACKET_NUMBER, nullptr, kDefaultLength,
false, false);
QuicStreamFrame frame;
frame.stream_id = stream_id;
packet.retransmittable_frames.push_back(QuicFrame(frame));
return packet;
}
SerializedPacket CreateNonRetransmittablePacket(uint64_t packet_number) {
return SerializedPacket(QuicPacketNumber(packet_number),
PACKET_1BYTE_PACKET_NUMBER, nullptr, kDefaultLength,
false, false);
}
void VerifyInFlightPackets(uint64_t* packets, size_t num_packets) {
unacked_packets_.RemoveObsoletePackets();
if (num_packets == 0) {
EXPECT_FALSE(unacked_packets_.HasInFlightPackets());
EXPECT_FALSE(unacked_packets_.HasMultipleInFlightPackets());
return;
}
if (num_packets == 1) {
EXPECT_TRUE(unacked_packets_.HasInFlightPackets());
EXPECT_FALSE(unacked_packets_.HasMultipleInFlightPackets());
ASSERT_TRUE(unacked_packets_.IsUnacked(QuicPacketNumber(packets[0])));
EXPECT_TRUE(
unacked_packets_.GetTransmissionInfo(QuicPacketNumber(packets[0]))
.in_flight);
}
for (size_t i = 0; i < num_packets; ++i) {
ASSERT_TRUE(unacked_packets_.IsUnacked(QuicPacketNumber(packets[i])));
EXPECT_TRUE(
unacked_packets_.GetTransmissionInfo(QuicPacketNumber(packets[i]))
.in_flight);
}
size_t in_flight_count = 0;
for (auto it = unacked_packets_.begin(); it != unacked_packets_.end();
++it) {
if (it->in_flight) {
++in_flight_count;
}
}
EXPECT_EQ(num_packets, in_flight_count);
}
void VerifyUnackedPackets(uint64_t* packets, size_t num_packets) {
unacked_packets_.RemoveObsoletePackets();
if (num_packets == 0) {
EXPECT_TRUE(unacked_packets_.empty());
EXPECT_FALSE(unacked_packets_.HasUnackedRetransmittableFrames());
return;
}
EXPECT_FALSE(unacked_packets_.empty());
for (size_t i = 0; i < num_packets; ++i) {
EXPECT_TRUE(unacked_packets_.IsUnacked(QuicPacketNumber(packets[i])))
<< packets[i];
}
EXPECT_EQ(num_packets, unacked_packets_.GetNumUnackedPacketsDebugOnly());
}
void VerifyRetransmittablePackets(uint64_t* packets, size_t num_packets) {
unacked_packets_.RemoveObsoletePackets();
size_t num_retransmittable_packets = 0;
for (auto it = unacked_packets_.begin(); it != unacked_packets_.end();
++it) {
if (unacked_packets_.HasRetransmittableFrames(*it)) {
++num_retransmittable_packets;
}
}
EXPECT_EQ(num_packets, num_retransmittable_packets);
for (size_t i = 0; i < num_packets; ++i) {
EXPECT_TRUE(unacked_packets_.HasRetransmittableFrames(
QuicPacketNumber(packets[i])))
<< " packets[" << i << "]:" << packets[i];
}
}
void UpdatePacketState(uint64_t packet_number, SentPacketState state) {
unacked_packets_
.GetMutableTransmissionInfo(QuicPacketNumber(packet_number))
->state = state;
}
void RetransmitAndSendPacket(uint64_t old_packet_number,
uint64_t new_packet_number,
TransmissionType transmission_type) {
QUICHE_DCHECK(unacked_packets_.HasRetransmittableFrames(
QuicPacketNumber(old_packet_number)));
QuicTransmissionInfo* info = unacked_packets_.GetMutableTransmissionInfo(
QuicPacketNumber(old_packet_number));
QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
CurrentSupportedVersions()[0].transport_version,
Perspective::IS_CLIENT);
for (const auto& frame : info->retransmittable_frames) {
if (frame.type == STREAM_FRAME) {
stream_id = frame.stream_frame.stream_id;
break;
}
}
UpdatePacketState(
old_packet_number,
QuicUtils::RetransmissionTypeToPacketState(transmission_type));
info->first_sent_after_loss = QuicPacketNumber(new_packet_number);
SerializedPacket packet(
CreateRetransmittablePacketForStream(new_packet_number, stream_id));
unacked_packets_.AddSentPacket(&packet, transmission_type, now_, true, true,
ECN_NOT_ECT);
}
QuicUnackedPacketMap unacked_packets_;
QuicTime now_;
StrictMock<MockSessionNotifier> notifier_;
};
INSTANTIATE_TEST_SUITE_P(Tests, QuicUnackedPacketMapTest,
::testing::ValuesIn({Perspective::IS_CLIENT,
Perspective::IS_SERVER}),
::testing::PrintToStringParamName());
TEST_P(QuicUnackedPacketMapTest, RttOnly) {
SerializedPacket packet(CreateNonRetransmittablePacket(1));
unacked_packets_.AddSentPacket(&packet, NOT_RETRANSMISSION, now_, false, true,
ECN_NOT_ECT);
uint64_t unacked[] = {1};
VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked));
VerifyInFlightPackets(nullptr, 0);
VerifyRetransmittablePackets(nullptr, 0);
unacked_packets_.IncreaseLargestAcked(QuicPacketNumber(1));
VerifyUnackedPackets(nullptr, 0);
VerifyInFlightPackets(nullptr, 0);
VerifyRetransmittablePackets(nullptr, 0);
}
TEST_P(QuicUnackedPacketMapTest, RetransmittableInflightAndRtt) {
SerializedPacket packet(CreateRetransmittablePacket(1));
unacked_packets_.AddSentPacket(&packet, NOT_RETRANSMISSION, now_, true, true,
ECN_NOT_ECT);
uint64_t unacked[] = {1};
VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked));
VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked));
VerifyRetransmittablePackets(unacked, ABSL_ARRAYSIZE(unacked));
unacked_packets_.RemoveRetransmittability(QuicPacketNumber(1));
VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked));
VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked));
VerifyRetransmittablePackets(nullptr, 0);
unacked_packets_.IncreaseLargestAcked(QuicPacketNumber(1));
VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked));
VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked));
VerifyRetransmittablePackets(nullptr, 0);
unacked_packets_.RemoveFromInFlight(QuicPacketNumber(1));
VerifyUnackedPackets(nullptr, 0);
VerifyInFlightPackets(nullptr, 0);
VerifyRetransmittablePackets(nullptr, 0);
}
TEST_P(QuicUnackedPacketMapTest, StopRetransmission) {
const QuicStreamId stream_id = 2;
SerializedPacket packet(CreateRetransmittablePacketForStream(1, stream_id));
unacked_packets_.AddSentPacket(&packet, NOT_RETRANSMISSION, now_, true, true,
ECN_NOT_ECT);
uint64_t unacked[] = {1};
VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked));
VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked));
uint64_t retransmittable[] = {1};
VerifyRetransmittablePackets(retransmittable,
ABSL_ARRAYSIZE(retransmittable));
EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(false));
VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked));
VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked));
VerifyRetransmittablePackets(nullptr, 0);
}
TEST_P(QuicUnackedPacketMapTest, StopRetransmissionOnOtherStream) {
const QuicStreamId stream_id = 2;
SerializedPacket packet(CreateRetransmittablePacketForStream(1, stream_id));
unacked_packets_.AddSentPacket(&packet, NOT_RETRANSMISSION, now_, true, true,
ECN_NOT_ECT);
uint64_t unacked[] = {1};
VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked));
VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked));
uint64_t retransmittable[] = {1};
VerifyRetransmittablePackets(retransmittable,
ABSL_ARRAYSIZE(retransmittable));
VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked));
VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked));
VerifyRetransmittablePackets(retransmittable,
ABSL_ARRAYSIZE(retransmittable));
}
TEST_P(QuicUnackedPacketMapTest, StopRetransmissionAfterRetransmission) {
const QuicStreamId stream_id = 2;
SerializedPacket packet1(CreateRetransmittablePacketForStream(1, stream_id));
unacked_packets_.AddSentPacket(&packet1, NOT_RETRANSMISSION, now_, true, true,
ECN_NOT_ECT);
RetransmitAndSendPacket(1, 2, LOSS_RETRANSMISSION);
uint64_t unacked[] = {1, 2};
VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked));
VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked));
std::vector<uint64_t> retransmittable = {1, 2};
VerifyRetransmittablePackets(&retransmittable[0], retransmittable.size());
EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(false));
VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked));
VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked));
VerifyRetransmittablePackets(nullptr, 0);
}
TEST_P(QuicUnackedPacketMapTest, RetransmittedPacket) {
SerializedPacket packet1(CreateRetransmittablePacket(1));
unacked_packets_.AddSentPacket(&packet1, NOT_RETRANSMISSION, now_, true, true,
ECN_NOT_ECT);
RetransmitAndSendPacket(1, 2, LOSS_RETRANSMISSION);
uint64_t unacked[] = {1, 2};
VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked));
VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked));
std::vector<uint64_t> retransmittable = {1, 2};
VerifyRetransmittablePackets(&retransmittable[0], retransmittable.size());
EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(false));
unacked_packets_.RemoveRetransmittability(QuicPacketNumber(1));
VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked));
VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked));
VerifyRetransmittablePackets(nullptr, 0);
unacked_packets_.IncreaseLargestAcked(QuicPacketNumber(2));
VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked));
VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked));
VerifyRetransmittablePackets(nullptr, 0);
unacked_packets_.RemoveFromInFlight(QuicPacketNumber(2));
uint64_t unacked2[] = {1};
VerifyUnackedPackets(unacked2, ABSL_ARRAYSIZE(unacked2));
VerifyInFlightPackets(unacked2, ABSL_ARRAYSIZE(unacked2));
VerifyRetransmittablePackets(nullptr, 0);
unacked_packets_.RemoveFromInFlight(QuicPacketNumber(1));
VerifyUnackedPackets(nullptr, 0);
VerifyInFlightPackets(nullptr, 0);
VerifyRetransmittablePackets(nullptr, 0);
}
TEST_P(QuicUnackedPacketMapTest, RetransmitThreeTimes) {
SerializedPacket packet1(CreateRetransmittablePacket(1));
unacked_packets_.AddSentPacket(&packet1, NOT_RETRANSMISSION, now_, true, true,
ECN_NOT_ECT);
SerializedPacket packet2(CreateRetransmittablePacket(2));
unacked_packets_.AddSentPacket(&packet2, NOT_RETRANSMISSION, now_, true, true,
ECN_NOT_ECT);
uint64_t unacked[] = {1, 2};
VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked));
VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked));
uint64_t retransmittable[] = {1, 2};
VerifyRetransmittablePackets(retransmittable,
ABSL_ARRAYSIZE(retransmittable));
unacked_packets_.IncreaseLargestAcked(QuicPacketNumber(2));
unacked_packets_.RemoveFromInFlight(QuicPacketNumber(2));
unacked_packets_.RemoveRetransmittability(QuicPacketNumber(2));
unacked_packets_.RemoveFromInFlight(QuicPacketNumber(1));
RetransmitAndSendPacket(1, 3, LOSS_RETRANSMISSION);
SerializedPacket packet4(CreateRetransmittablePacket(4));
unacked_packets_.AddSentPacket(&packet4, NOT_RETRANSMISSION, now_, true, true,
ECN_NOT_ECT);
uint64_t unacked2[] = {1, 3, 4};
VerifyUnackedPackets(unacked2, ABSL_ARRAYSIZE(unacked2));
uint64_t pending2[] = {3, 4};
VerifyInFlightPackets(pending2, ABSL_ARRAYSIZE(pending2));
std::vector<uint64_t> retransmittable2 = {1, 3, 4};
VerifyRetransmittablePackets(&retransmittable2[0], retransmittable2.size());
unacked_packets_.IncreaseLargestAcked(QuicPacketNumber(4));
unacked_packets_.RemoveFromInFlight(QuicPacketNumber(4));
unacked_packets_.RemoveRetransmittability(QuicPacketNumber(4));
RetransmitAndSendPacket(3, 5, LOSS_RETRANSMISSION);
SerializedPacket packet6(CreateRetransmittablePacket(6));
unacked_packets_.AddSentPacket(&packet6, NOT_RETRANSMISSION, now_, true, true,
ECN_NOT_ECT);
std::vector<uint64_t> unacked3 = {3, 5, 6};
std::vector<uint64_t> retransmittable3 = {3, 5, 6};
VerifyUnackedPackets(&unacked3[0], unacked3.size());
VerifyRetransmittablePackets(&retransmittable3[0], retransmittable3.size());
uint64_t pending3[] = {3, 5, 6};
VerifyInFlightPackets(pending3, ABSL_ARRAYSIZE(pending3));
unacked_packets_.IncreaseLargestAcked(QuicPacketNumber(6));
unacked_packets_.RemoveFromInFlight(QuicPacketNumber(6));
unacked_packets_.RemoveRetransmittability(QuicPacketNumber(6));
RetransmitAndSendPacket(5, 7, LOSS_RETRANSMISSION);
std::vector<uint64_t> unacked4 = {3, 5, 7};
std::vector<uint64_t> retransmittable4 = {3, 5, 7};
VerifyUnackedPackets(&unacked4[0], unacked4.size());
VerifyRetransmittablePackets(&retransmittable4[0], retransmittable4.size());
uint64_t pending4[] = {3, 5, 7};
VerifyInFlightPackets(pending4, ABSL_ARRAYSIZE(pending4));
unacked_packets_.RemoveFromInFlight(QuicPacketNumber(3));
unacked_packets_.RemoveFromInFlight(QuicPacketNumber(5));
uint64_t pending5[] = {7};
VerifyInFlightPackets(pending5, ABSL_ARRAYSIZE(pending5));
}
TEST_P(QuicUnackedPacketMapTest, RetransmitFourTimes) {
SerializedPacket packet1(CreateRetransmittablePacket(1));
unacked_packets_.AddSentPacket(&packet1, NOT_RETRANSMISSION, now_, true, true,
ECN_NOT_ECT);
SerializedPacket packet2(CreateRetransmittablePacket(2));
unacked_packets_.AddSentPacket(&packet2, NOT_RETRANSMISSION, now_, true, true,
ECN_NOT_ECT);
uint64_t unacked[] = {1, 2};
VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked));
VerifyInFlightPackets(unacked, ABSL_ARRAYSIZE(unacked));
uint64_t retransmittable[] = {1, 2};
VerifyRetransmittablePackets(retransmittable,
ABSL_ARRAYSIZE(retransmittable));
unacked_packets_.IncreaseLargestAcked(QuicPacketNumber(2));
unacked_packets_.RemoveFromInFlight(QuicPacketNumber(2));
unacked_packets_.RemoveRetransmittability(QuicPacketNumber(2));
unacked_packets_.RemoveFromInFlight(QuicPacketNumber(1));
RetransmitAndSendPacket(1, 3, LOSS_RETRANSMISSION);
uint64_t unacked2[] = {1, 3};
VerifyUnackedPackets(unacked2, ABSL_ARRAYSIZE(unacked2));
uint64_t pending2[] = {3};
VerifyInFlightPackets(pending2, ABSL_ARRAYSIZE(pending2));
std::vector<uint64_t> retransmittable2 = {1, 3};
VerifyRetransmittablePackets(&retransmittable2[0], retransmittable2.size());
RetransmitAndSendPacket(3, 4, PTO_RETRANSMISSION);
SerializedPacket packet5(CreateRetransmittablePacket(5));
unacked_packets_.AddSentPacket(&packet5, NOT_RETRANSMISSION, now_, true, true,
ECN_NOT_ECT);
uint64_t unacked3[] = {1, 3, 4, 5};
VerifyUnackedPackets(unacked3, ABSL_ARRAYSIZE(unacked3));
uint64_t pending3[] = {3, 4, 5};
VerifyInFlightPackets(pending3, ABSL_ARRAYSIZE(pending3));
std::vector<uint64_t> retransmittable3 = {1, 3, 4, 5};
VerifyRetransmittablePackets(&retransmittable3[0], retransmittable3.size());
unacked_packets_.IncreaseLargestAcked(QuicPacketNumber(5));
unacked_packets_.RemoveFromInFlight(QuicPacketNumber(5));
unacked_packets_.RemoveRetransmittability(QuicPacketNumber(5));
unacked_packets_.RemoveFromInFlight(QuicPacketNumber(3));
unacked_packets_.RemoveFromInFlight(QuicPacketNumber(4));
RetransmitAndSendPacket(4, 6, LOSS_RETRANSMISSION);
std::vector<uint64_t> unacked4 = {4, 6};
VerifyUnackedPackets(&unacked4[0], unacked4.size());
uint64_t pending4[] = {6};
VerifyInFlightPackets(pending4, ABSL_ARRAYSIZE(pending4));
std::vector<uint64_t> retransmittable4 = {4, 6};
VerifyRetransmittablePackets(&retransmittable4[0], retransmittable4.size());
}
TEST_P(QuicUnackedPacketMapTest, SendWithGap) {
SerializedPacket packet1(CreateRetransmittablePacket(1));
unacked_packets_.AddSentPacket(&packet1, NOT_RETRANSMISSION, now_, true, true,
ECN_NOT_ECT);
SerializedPacket packet3(CreateRetransmittablePacket(3));
unacked_packets_.AddSentPacket(&packet3, NOT_RETRANSMISSION, now_, true, true,
ECN_NOT_ECT);
RetransmitAndSendPacket(3, 5, LOSS_RETRANSMISSION);
EXPECT_EQ(QuicPacketNumber(1u), unacked_packets_.GetLeastUnacked());
EXPECT_TRUE(unacked_packets_.IsUnacked(QuicPacketNumber(1)));
EXPECT_FALSE(unacked_packets_.IsUnacked(QuicPacketNumber(2)));
EXPECT_TRUE(unacked_packets_.IsUnacked(QuicPacketNumber(3)));
EXPECT_FALSE(unacked_packets_.IsUnacked(QuicPacketNumber(4)));
EXPECT_TRUE(unacked_packets_.IsUnacked(QuicPacketNumber(5)));
EXPECT_EQ(QuicPacketNumber(5u), unacked_packets_.largest_sent_packet());
}
TEST_P(QuicUnackedPacketMapTest, AggregateContiguousAckedStreamFrames) {
testing::InSequence s;
EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).Times(0);
unacked_packets_.NotifyAggregatedStreamFrameAcked(QuicTime::Delta::Zero());
QuicTransmissionInfo info1;
QuicStreamFrame stream_frame1(3, false, 0, 100);
info1.retransmittable_frames.push_back(QuicFrame(stream_frame1));
QuicTransmissionInfo info2;
QuicStreamFrame stream_frame2(3, false, 100, 100);
info2.retransmittable_frames.push_back(QuicFrame(stream_frame2));
QuicTransmissionInfo info3;
QuicStreamFrame stream_frame3(3, false, 200, 100);
info3.retransmittable_frames.push_back(QuicFrame(stream_frame3));
QuicTransmissionInfo info4;
QuicStreamFrame stream_frame4(3, true, 300, 0);
info4.retransmittable_frames.push_back(QuicFrame(stream_frame4));
EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).Times(0);
unacked_packets_.MaybeAggregateAckedStreamFrame(
info1, QuicTime::Delta::Zero(), QuicTime::Zero());
EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).Times(0);
unacked_packets_.MaybeAggregateAckedStreamFrame(
info2, QuicTime::Delta::Zero(), QuicTime::Zero());
EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).Times(0);
unacked_packets_.MaybeAggregateAckedStreamFrame(
info3, QuicTime::Delta::Zero(), QuicTime::Zero());
EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).Times(1);
unacked_packets_.MaybeAggregateAckedStreamFrame(
info4, QuicTime::Delta::Zero(), QuicTime::Zero());
}
TEST_P(QuicUnackedPacketMapTest, CannotAggregateIfDataLengthOverflow) {
QuicByteCount kMaxAggregatedDataLength =
std::numeric_limits<decltype(QuicStreamFrame().data_length)>::max();
QuicStreamId stream_id = 2;
for (const QuicPacketLength acked_stream_length : {512, 1300}) {
++stream_id;
QuicStreamOffset offset = 0;
QuicByteCount aggregated_data_length = 0;
while (offset < 1e6) {
QuicTransmissionInfo info;
QuicStreamFrame stream_frame(stream_id, false, offset,
acked_stream_length);
info.retransmittable_frames.push_back(QuicFrame(stream_frame));
const QuicStreamFrame& aggregated_stream_frame =
QuicUnackedPacketMapPeer::GetAggregatedStreamFrame(unacked_packets_);
if (aggregated_stream_frame.data_length + acked_stream_length <=
kMaxAggregatedDataLength) {
EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).Times(0);
unacked_packets_.MaybeAggregateAckedStreamFrame(
info, QuicTime::Delta::Zero(), QuicTime::Zero());
aggregated_data_length += acked_stream_length;
testing::Mock::VerifyAndClearExpectations(¬ifier_);
} else {
EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).Times(1);
unacked_packets_.MaybeAggregateAckedStreamFrame(
info, QuicTime::Delta::Zero(), QuicTime::Zero());
aggregated_data_length = acked_stream_length;
testing::Mock::VerifyAndClearExpectations(¬ifier_);
}
EXPECT_EQ(aggregated_data_length, aggregated_stream_frame.data_length);
offset += acked_stream_length;
}
QuicTransmissionInfo info;
QuicStreamFrame stream_frame(stream_id, true, offset, acked_stream_length);
info.retransmittable_frames.push_back(QuicFrame(stream_frame));
EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).Times(1);
unacked_packets_.MaybeAggregateAckedStreamFrame(
info, QuicTime::Delta::Zero(), QuicTime::Zero());
testing::Mock::VerifyAndClearExpectations(¬ifier_);
}
}
TEST_P(QuicUnackedPacketMapTest, CannotAggregateAckedControlFrames) {
testing::InSequence s;
QuicWindowUpdateFrame window_update(1, 5, 100);
QuicStreamFrame stream_frame1(3, false, 0, 100);
QuicStreamFrame stream_frame2(3, false, 100, 100);
QuicBlockedFrame blocked(2, 5, 0);
QuicGoAwayFrame go_away(3, QUIC_PEER_GOING_AWAY, 5, "Going away.");
QuicTransmissionInfo info1;
info1.retransmittable_frames.push_back(QuicFrame(window_update));
info1.retransmittable_frames.push_back(QuicFrame(stream_frame1));
info1.retransmittable_frames.push_back(QuicFrame(stream_frame2));
QuicTransmissionInfo info2;
info2.retransmittable_frames.push_back(QuicFrame(blocked));
info2.retransmittable_frames.push_back(QuicFrame(&go_away));
EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).Times(1);
unacked_packets_.MaybeAggregateAckedStreamFrame(
info1, QuicTime::Delta::Zero(), QuicTime::Zero());
EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).Times(3);
unacked_packets_.MaybeAggregateAckedStreamFrame(
info2, QuicTime::Delta::Zero(), QuicTime::Zero());
EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).Times(0);
unacked_packets_.NotifyAggregatedStreamFrameAcked(QuicTime::Delta::Zero());
}
TEST_P(QuicUnackedPacketMapTest, LargestSentPacketMultiplePacketNumberSpaces) {
unacked_packets_.EnableMultiplePacketNumberSpacesSupport();
EXPECT_FALSE(
unacked_packets_
.GetLargestSentRetransmittableOfPacketNumberSpace(INITIAL_DATA)
.IsInitialized());
SerializedPacket packet1(CreateRetransmittablePacket(1));
packet1.encryption_level = ENCRYPTION_INITIAL;
unacked_packets_.AddSentPacket(&packet1, NOT_RETRANSMISSION, now_, true, true,
ECN_NOT_ECT);
EXPECT_EQ(QuicPacketNumber(1u), unacked_packets_.largest_sent_packet());
EXPECT_EQ(QuicPacketNumber(1),
unacked_packets_.GetLargestSentRetransmittableOfPacketNumberSpace(
INITIAL_DATA));
EXPECT_FALSE(
unacked_packets_
.GetLargestSentRetransmittableOfPacketNumberSpace(HANDSHAKE_DATA)
.IsInitialized());
SerializedPacket packet2(CreateRetransmittablePacket(2));
packet2.encryption_level = ENCRYPTION_HANDSHAKE;
unacked_packets_.AddSentPacket(&packet2, NOT_RETRANSMISSION, now_, true, true,
ECN_NOT_ECT);
EXPECT_EQ(QuicPacketNumber(2u), unacked_packets_.largest_sent_packet());
EXPECT_EQ(QuicPacketNumber(1),
unacked_packets_.GetLargestSentRetransmittableOfPacketNumberSpace(
INITIAL_DATA));
EXPECT_EQ(QuicPacketNumber(2),
unacked_packets_.GetLargestSentRetransmittableOfPacketNumberSpace(
HANDSHAKE_DATA));
EXPECT_FALSE(
unacked_packets_
.GetLargestSentRetransmittableOfPacketNumberSpace(APPLICATION_DATA)
.IsInitialized());
SerializedPacket packet3(CreateRetransmittablePacket(3));
packet3.encryption_level = ENCRYPTION_ZERO_RTT;
unacked_packets_.AddSentPacket(&packet3, NOT_RETRANSMISSION, now_, true, true,
ECN_NOT_ECT);
EXPECT_EQ(QuicPacketNumber(3u), unacked_packets_.largest_sent_packet());
EXPECT_EQ(QuicPacketNumber(1),
unacked_packets_.GetLargestSentRetransmittableOfPacketNumberSpace(
INITIAL_DATA));
EXPECT_EQ(QuicPacketNumber(2),
unacked_packets_.GetLargestSentRetransmittableOfPacketNumberSpace(
HANDSHAKE_DATA));
EXPECT_EQ(QuicPacketNumber(3),
unacked_packets_.GetLargestSentRetransmittableOfPacketNumberSpace(
APPLICATION_DATA));
EXPECT_EQ(QuicPacketNumber(3),
unacked_packets_.GetLargestSentRetransmittableOfPacketNumberSpace(
APPLICATION_DATA));
SerializedPacket packet4(CreateRetransmittablePacket(4));
packet4.encryption_level = ENCRYPTION_FORWARD_SECURE;
unacked_packets_.AddSentPacket(&packet4, NOT_RETRANSMISSION, now_, true, true,
ECN_NOT_ECT);
EXPECT_EQ(QuicPacketNumber(4u), unacked_packets_.largest_sent_packet());
EXPECT_EQ(QuicPacketNumber(1),
unacked_packets_.GetLargestSentRetransmittableOfPacketNumberSpace(
INITIAL_DATA));
EXPECT_EQ(QuicPacketNumber(2),
unacked_packets_.GetLargestSentRetransmittableOfPacketNumberSpace(
HANDSHAKE_DATA));
EXPECT_EQ(QuicPacketNumber(4),
unacked_packets_.GetLargestSentRetransmittableOfPacketNumberSpace(
APPLICATION_DATA));
EXPECT_EQ(QuicPacketNumber(4),
unacked_packets_.GetLargestSentRetransmittableOfPacketNumberSpace(
APPLICATION_DATA));
EXPECT_TRUE(unacked_packets_.GetLastPacketContent() & (1 << STREAM_FRAME));
EXPECT_FALSE(unacked_packets_.GetLastPacketContent() & (1 << ACK_FRAME));
}
TEST_P(QuicUnackedPacketMapTest, ReserveInitialCapacityTest) {
QuicUnackedPacketMap unacked_packets(GetParam());
ASSERT_EQ(QuicUnackedPacketMapPeer::GetCapacity(unacked_packets), 0u);
unacked_packets.ReserveInitialCapacity(16);
QuicStreamId stream_id(1);
SerializedPacket packet(CreateRetransmittablePacketForStream(1, stream_id));
unacked_packets.AddSentPacket(&packet, TransmissionType::NOT_RETRANSMISSION,
now_, true, true, ECN_NOT_ECT);
ASSERT_EQ(QuicUnackedPacketMapPeer::GetCapacity(unacked_packets), 16u);
}
TEST_P(QuicUnackedPacketMapTest, DebugString) {
EXPECT_EQ(unacked_packets_.DebugString(),
"{size: 0, least_unacked: 1, largest_sent_packet: uninitialized, "
"largest_acked: uninitialized, bytes_in_flight: 0, "
"packets_in_flight: 0}");
SerializedPacket packet1(CreateRetransmittablePacket(1));
unacked_packets_.AddSentPacket(&packet1, NOT_RETRANSMISSION, now_, true, true,
ECN_NOT_ECT);
EXPECT_EQ(
unacked_packets_.DebugString(),
"{size: 1, least_unacked: 1, largest_sent_packet: 1, largest_acked: "
"uninitialized, bytes_in_flight: 1000, packets_in_flight: 1}");
SerializedPacket packet2(CreateRetransmittablePacket(2));
unacked_packets_.AddSentPacket(&packet2, NOT_RETRANSMISSION, now_, true, true,
ECN_NOT_ECT);
unacked_packets_.RemoveFromInFlight(QuicPacketNumber(1));
unacked_packets_.IncreaseLargestAcked(QuicPacketNumber(1));
unacked_packets_.RemoveObsoletePackets();
EXPECT_EQ(
unacked_packets_.DebugString(),
"{size: 1, least_unacked: 2, largest_sent_packet: 2, largest_acked: 1, "
"bytes_in_flight: 1000, packets_in_flight: 1}");
}
TEST_P(QuicUnackedPacketMapTest, EcnInfoStored) {
SerializedPacket packet1(CreateRetransmittablePacket(1));
unacked_packets_.AddSentPacket(&packet1, NOT_RETRANSMISSION, now_, true, true,
ECN_NOT_ECT);
SerializedPacket packet2(CreateRetransmittablePacket(2));
unacked_packets_.AddSentPacket(&packet2, NOT_RETRANSMISSION, now_, true, true,
ECN_ECT0);
SerializedPacket packet3(CreateRetransmittablePacket(3));
unacked_packets_.AddSentPacket(&packet3, NOT_RETRANSMISSION, now_, true, true,
ECN_ECT1);
EXPECT_EQ(
unacked_packets_.GetTransmissionInfo(QuicPacketNumber(1)).ecn_codepoint,
ECN_NOT_ECT);
EXPECT_EQ(
unacked_packets_.GetTransmissionInfo(QuicPacketNumber(2)).ecn_codepoint,
ECN_ECT0);
EXPECT_EQ(
unacked_packets_.GetTransmissionInfo(QuicPacketNumber(3)).ecn_codepoint,
ECN_ECT1);
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_unacked_packet_map.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_unacked_packet_map_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
5c088239-3540-4667-9d39-2d5bbb9476af | cpp | google/quiche | quic_time | quiche/quic/core/quic_time.cc | quiche/quic/core/quic_time_test.cc | #include "quiche/quic/core/quic_time.h"
#include <cinttypes>
#include <cstdlib>
#include <limits>
#include <string>
#include "absl/strings/str_cat.h"
namespace quic {
std::string QuicTime::Delta::ToDebuggingValue() const {
constexpr int64_t kMillisecondInMicroseconds = 1000;
constexpr int64_t kSecondInMicroseconds = 1000 * kMillisecondInMicroseconds;
int64_t absolute_value = std::abs(time_offset_);
if (absolute_value >= kSecondInMicroseconds &&
absolute_value % kSecondInMicroseconds == 0) {
return absl::StrCat(time_offset_ / kSecondInMicroseconds, "s");
}
if (absolute_value >= kMillisecondInMicroseconds &&
absolute_value % kMillisecondInMicroseconds == 0) {
return absl::StrCat(time_offset_ / kMillisecondInMicroseconds, "ms");
}
return absl::StrCat(time_offset_, "us");
}
uint64_t QuicWallTime::ToUNIXSeconds() const { return microseconds_ / 1000000; }
uint64_t QuicWallTime::ToUNIXMicroseconds() const { return microseconds_; }
bool QuicWallTime::IsAfter(QuicWallTime other) const {
return microseconds_ > other.microseconds_;
}
bool QuicWallTime::IsBefore(QuicWallTime other) const {
return microseconds_ < other.microseconds_;
}
bool QuicWallTime::IsZero() const { return microseconds_ == 0; }
QuicTime::Delta QuicWallTime::AbsoluteDifference(QuicWallTime other) const {
uint64_t d;
if (microseconds_ > other.microseconds_) {
d = microseconds_ - other.microseconds_;
} else {
d = other.microseconds_ - microseconds_;
}
if (d > static_cast<uint64_t>(std::numeric_limits<int64_t>::max())) {
d = std::numeric_limits<int64_t>::max();
}
return QuicTime::Delta::FromMicroseconds(d);
}
QuicWallTime QuicWallTime::Add(QuicTime::Delta delta) const {
uint64_t microseconds = microseconds_ + delta.ToMicroseconds();
if (microseconds < microseconds_) {
microseconds = std::numeric_limits<uint64_t>::max();
}
return QuicWallTime(microseconds);
}
QuicWallTime QuicWallTime::Subtract(QuicTime::Delta delta) const {
uint64_t microseconds = microseconds_ - delta.ToMicroseconds();
if (microseconds > microseconds_) {
microseconds = 0;
}
return QuicWallTime(microseconds);
}
} | #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 {
namespace test {
class QuicTimeDeltaTest : public QuicTest {};
TEST_F(QuicTimeDeltaTest, Zero) {
EXPECT_TRUE(QuicTime::Delta::Zero().IsZero());
EXPECT_FALSE(QuicTime::Delta::Zero().IsInfinite());
EXPECT_FALSE(QuicTime::Delta::FromMilliseconds(1).IsZero());
}
TEST_F(QuicTimeDeltaTest, Infinite) {
EXPECT_TRUE(QuicTime::Delta::Infinite().IsInfinite());
EXPECT_FALSE(QuicTime::Delta::Zero().IsInfinite());
EXPECT_FALSE(QuicTime::Delta::FromMilliseconds(1).IsInfinite());
}
TEST_F(QuicTimeDeltaTest, FromTo) {
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(1),
QuicTime::Delta::FromMicroseconds(1000));
EXPECT_EQ(QuicTime::Delta::FromSeconds(1),
QuicTime::Delta::FromMilliseconds(1000));
EXPECT_EQ(QuicTime::Delta::FromSeconds(1),
QuicTime::Delta::FromMicroseconds(1000000));
EXPECT_EQ(1, QuicTime::Delta::FromMicroseconds(1000).ToMilliseconds());
EXPECT_EQ(2, QuicTime::Delta::FromMilliseconds(2000).ToSeconds());
EXPECT_EQ(1000, QuicTime::Delta::FromMilliseconds(1).ToMicroseconds());
EXPECT_EQ(1, QuicTime::Delta::FromMicroseconds(1000).ToMilliseconds());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(2000).ToMicroseconds(),
QuicTime::Delta::FromSeconds(2).ToMicroseconds());
}
TEST_F(QuicTimeDeltaTest, Add) {
EXPECT_EQ(QuicTime::Delta::FromMicroseconds(2000),
QuicTime::Delta::Zero() + QuicTime::Delta::FromMilliseconds(2));
}
TEST_F(QuicTimeDeltaTest, Subtract) {
EXPECT_EQ(QuicTime::Delta::FromMicroseconds(1000),
QuicTime::Delta::FromMilliseconds(2) -
QuicTime::Delta::FromMilliseconds(1));
}
TEST_F(QuicTimeDeltaTest, Multiply) {
int i = 2;
EXPECT_EQ(QuicTime::Delta::FromMicroseconds(4000),
QuicTime::Delta::FromMilliseconds(2) * i);
EXPECT_EQ(QuicTime::Delta::FromMicroseconds(4000),
i * QuicTime::Delta::FromMilliseconds(2));
double d = 2;
EXPECT_EQ(QuicTime::Delta::FromMicroseconds(4000),
QuicTime::Delta::FromMilliseconds(2) * d);
EXPECT_EQ(QuicTime::Delta::FromMicroseconds(4000),
d * QuicTime::Delta::FromMilliseconds(2));
EXPECT_EQ(QuicTime::Delta::FromMicroseconds(5),
QuicTime::Delta::FromMicroseconds(9) * 0.5);
EXPECT_EQ(QuicTime::Delta::FromMicroseconds(2),
QuicTime::Delta::FromMicroseconds(12) * 0.2);
}
TEST_F(QuicTimeDeltaTest, Max) {
EXPECT_EQ(QuicTime::Delta::FromMicroseconds(2000),
std::max(QuicTime::Delta::FromMicroseconds(1000),
QuicTime::Delta::FromMicroseconds(2000)));
}
TEST_F(QuicTimeDeltaTest, NotEqual) {
EXPECT_TRUE(QuicTime::Delta::FromSeconds(0) !=
QuicTime::Delta::FromSeconds(1));
EXPECT_FALSE(QuicTime::Delta::FromSeconds(0) !=
QuicTime::Delta::FromSeconds(0));
}
TEST_F(QuicTimeDeltaTest, DebuggingValue) {
const QuicTime::Delta one_us = QuicTime::Delta::FromMicroseconds(1);
const QuicTime::Delta one_ms = QuicTime::Delta::FromMilliseconds(1);
const QuicTime::Delta one_s = QuicTime::Delta::FromSeconds(1);
EXPECT_EQ("1s", one_s.ToDebuggingValue());
EXPECT_EQ("3s", (3 * one_s).ToDebuggingValue());
EXPECT_EQ("1ms", one_ms.ToDebuggingValue());
EXPECT_EQ("3ms", (3 * one_ms).ToDebuggingValue());
EXPECT_EQ("1us", one_us.ToDebuggingValue());
EXPECT_EQ("3us", (3 * one_us).ToDebuggingValue());
EXPECT_EQ("3001us", (3 * one_ms + one_us).ToDebuggingValue());
EXPECT_EQ("3001ms", (3 * one_s + one_ms).ToDebuggingValue());
EXPECT_EQ("3000001us", (3 * one_s + one_us).ToDebuggingValue());
}
class QuicTimeTest : public QuicTest {
protected:
MockClock clock_;
};
TEST_F(QuicTimeTest, Initialized) {
EXPECT_FALSE(QuicTime::Zero().IsInitialized());
EXPECT_TRUE((QuicTime::Zero() + QuicTime::Delta::FromMicroseconds(1))
.IsInitialized());
}
TEST_F(QuicTimeTest, CopyConstruct) {
QuicTime time_1 = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1234);
EXPECT_NE(time_1, QuicTime(QuicTime::Zero()));
EXPECT_EQ(time_1, QuicTime(time_1));
}
TEST_F(QuicTimeTest, CopyAssignment) {
QuicTime time_1 = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1234);
QuicTime time_2 = QuicTime::Zero();
EXPECT_NE(time_1, time_2);
time_2 = time_1;
EXPECT_EQ(time_1, time_2);
}
TEST_F(QuicTimeTest, Add) {
QuicTime time_1 = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1);
QuicTime time_2 = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(2);
QuicTime::Delta diff = time_2 - time_1;
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(1), diff);
EXPECT_EQ(1000, diff.ToMicroseconds());
EXPECT_EQ(1, diff.ToMilliseconds());
}
TEST_F(QuicTimeTest, Subtract) {
QuicTime time_1 = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1);
QuicTime time_2 = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(2);
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(1), time_2 - time_1);
}
TEST_F(QuicTimeTest, SubtractDelta) {
QuicTime time = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(2);
EXPECT_EQ(QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1),
time - QuicTime::Delta::FromMilliseconds(1));
}
TEST_F(QuicTimeTest, Max) {
QuicTime time_1 = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1);
QuicTime time_2 = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(2);
EXPECT_EQ(time_2, std::max(time_1, time_2));
}
TEST_F(QuicTimeTest, MockClock) {
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
QuicTime now = clock_.ApproximateNow();
QuicTime time = QuicTime::Zero() + QuicTime::Delta::FromMicroseconds(1000);
EXPECT_EQ(now, time);
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
now = clock_.ApproximateNow();
EXPECT_NE(now, time);
time = time + QuicTime::Delta::FromMilliseconds(1);
EXPECT_EQ(now, time);
}
TEST_F(QuicTimeTest, LE) {
const QuicTime zero = QuicTime::Zero();
const QuicTime one = zero + QuicTime::Delta::FromSeconds(1);
EXPECT_TRUE(zero <= zero);
EXPECT_TRUE(zero <= one);
EXPECT_TRUE(one <= one);
EXPECT_FALSE(one <= zero);
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_time.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_time_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
e4078ac1-cb85-470a-adbf-9698468e662b | cpp | google/quiche | quic_linux_socket_utils | quiche/quic/core/quic_linux_socket_utils.cc | quiche/quic/core/quic_linux_socket_utils_test.cc | #include "quiche/quic/core/quic_linux_socket_utils.h"
#include <linux/net_tstamp.h>
#include <netinet/in.h>
#include <cstddef>
#include <cstdint>
#include <string>
#include "quiche/quic/core/quic_syscall_wrapper.h"
#include "quiche/quic/platform/api/quic_ip_address.h"
#include "quiche/quic/platform/api/quic_logging.h"
#include "quiche/quic/platform/api/quic_socket_address.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace quic {
QuicMsgHdr::QuicMsgHdr(iovec* iov, size_t iov_len, char* cbuf, size_t cbuf_size)
: cbuf_(cbuf), cbuf_size_(cbuf_size), cmsg_(nullptr) {
hdr_.msg_name = nullptr;
hdr_.msg_namelen = 0;
hdr_.msg_iov = iov;
hdr_.msg_iovlen = iov_len;
hdr_.msg_flags = 0;
hdr_.msg_control = nullptr;
hdr_.msg_controllen = 0;
}
void QuicMsgHdr::SetPeerAddress(const QuicSocketAddress& peer_address) {
QUICHE_DCHECK(peer_address.IsInitialized());
raw_peer_address_ = peer_address.generic_address();
hdr_.msg_name = &raw_peer_address_;
hdr_.msg_namelen = raw_peer_address_.ss_family == AF_INET
? sizeof(sockaddr_in)
: sizeof(sockaddr_in6);
}
void QuicMsgHdr::SetIpInNextCmsg(const QuicIpAddress& self_address) {
if (!self_address.IsInitialized()) {
return;
}
if (self_address.IsIPv4()) {
QuicLinuxSocketUtils::SetIpInfoInCmsgData(
self_address, GetNextCmsgData<in_pktinfo>(IPPROTO_IP, IP_PKTINFO));
} else {
QuicLinuxSocketUtils::SetIpInfoInCmsgData(
self_address, GetNextCmsgData<in6_pktinfo>(IPPROTO_IPV6, IPV6_PKTINFO));
}
}
void* QuicMsgHdr::GetNextCmsgDataInternal(int cmsg_level, int cmsg_type,
size_t data_size) {
hdr_.msg_controllen += CMSG_SPACE(data_size);
QUICHE_DCHECK_LE(hdr_.msg_controllen, cbuf_size_);
if (cmsg_ == nullptr) {
QUICHE_DCHECK_EQ(nullptr, hdr_.msg_control);
memset(cbuf_, 0, cbuf_size_);
hdr_.msg_control = cbuf_;
cmsg_ = CMSG_FIRSTHDR(&hdr_);
} else {
QUICHE_DCHECK_NE(nullptr, hdr_.msg_control);
cmsg_ = CMSG_NXTHDR(&hdr_, cmsg_);
}
QUICHE_DCHECK_NE(nullptr, cmsg_) << "Insufficient control buffer space";
cmsg_->cmsg_len = CMSG_LEN(data_size);
cmsg_->cmsg_level = cmsg_level;
cmsg_->cmsg_type = cmsg_type;
return CMSG_DATA(cmsg_);
}
void QuicMMsgHdr::InitOneHeader(int i, const BufferedWrite& buffered_write) {
mmsghdr* mhdr = GetMMsgHdr(i);
msghdr* hdr = &mhdr->msg_hdr;
iovec* iov = GetIov(i);
iov->iov_base = const_cast<char*>(buffered_write.buffer);
iov->iov_len = buffered_write.buf_len;
hdr->msg_iov = iov;
hdr->msg_iovlen = 1;
hdr->msg_control = nullptr;
hdr->msg_controllen = 0;
QUICHE_DCHECK(buffered_write.peer_address.IsInitialized());
sockaddr_storage* peer_address_storage = GetPeerAddressStorage(i);
*peer_address_storage = buffered_write.peer_address.generic_address();
hdr->msg_name = peer_address_storage;
hdr->msg_namelen = peer_address_storage->ss_family == AF_INET
? sizeof(sockaddr_in)
: sizeof(sockaddr_in6);
}
void QuicMMsgHdr::SetIpInNextCmsg(int i, const QuicIpAddress& self_address) {
if (!self_address.IsInitialized()) {
return;
}
if (self_address.IsIPv4()) {
QuicLinuxSocketUtils::SetIpInfoInCmsgData(
self_address, GetNextCmsgData<in_pktinfo>(i, IPPROTO_IP, IP_PKTINFO));
} else {
QuicLinuxSocketUtils::SetIpInfoInCmsgData(
self_address,
GetNextCmsgData<in6_pktinfo>(i, IPPROTO_IPV6, IPV6_PKTINFO));
}
}
void* QuicMMsgHdr::GetNextCmsgDataInternal(int i, int cmsg_level, int cmsg_type,
size_t data_size) {
mmsghdr* mhdr = GetMMsgHdr(i);
msghdr* hdr = &mhdr->msg_hdr;
cmsghdr*& cmsg = *GetCmsgHdr(i);
hdr->msg_controllen += CMSG_SPACE(data_size);
QUICHE_DCHECK_LE(hdr->msg_controllen, cbuf_size_);
if (cmsg == nullptr) {
QUICHE_DCHECK_EQ(nullptr, hdr->msg_control);
hdr->msg_control = GetCbuf(i);
cmsg = CMSG_FIRSTHDR(hdr);
} else {
QUICHE_DCHECK_NE(nullptr, hdr->msg_control);
cmsg = CMSG_NXTHDR(hdr, cmsg);
}
QUICHE_DCHECK_NE(nullptr, cmsg) << "Insufficient control buffer space";
cmsg->cmsg_len = CMSG_LEN(data_size);
cmsg->cmsg_level = cmsg_level;
cmsg->cmsg_type = cmsg_type;
return CMSG_DATA(cmsg);
}
int QuicMMsgHdr::num_bytes_sent(int num_packets_sent) {
QUICHE_DCHECK_LE(0, num_packets_sent);
QUICHE_DCHECK_LE(num_packets_sent, num_msgs_);
int bytes_sent = 0;
iovec* iov = GetIov(0);
for (int i = 0; i < num_packets_sent; ++i) {
bytes_sent += iov[i].iov_len;
}
return bytes_sent;
}
int QuicLinuxSocketUtils::GetUDPSegmentSize(int fd) {
int optval;
socklen_t optlen = sizeof(optval);
int rc = getsockopt(fd, SOL_UDP, UDP_SEGMENT, &optval, &optlen);
if (rc < 0) {
QUIC_LOG_EVERY_N_SEC(INFO, 10)
<< "getsockopt(UDP_SEGMENT) failed: " << strerror(errno);
return -1;
}
QUIC_LOG_EVERY_N_SEC(INFO, 10)
<< "getsockopt(UDP_SEGMENT) returned segment size: " << optval;
return optval;
}
bool QuicLinuxSocketUtils::EnableReleaseTime(int fd, clockid_t clockid) {
struct LinuxSockTxTime {
clockid_t clockid;
uint32_t flags;
};
LinuxSockTxTime so_txtime_val{clockid, 0};
if (setsockopt(fd, SOL_SOCKET, SO_TXTIME, &so_txtime_val,
sizeof(so_txtime_val)) != 0) {
QUIC_LOG_EVERY_N_SEC(INFO, 10)
<< "setsockopt(SOL_SOCKET,SO_TXTIME) failed: " << strerror(errno);
return false;
}
return true;
}
bool QuicLinuxSocketUtils::GetTtlFromMsghdr(struct msghdr* hdr, int* ttl) {
if (hdr->msg_controllen > 0) {
struct cmsghdr* cmsg;
for (cmsg = CMSG_FIRSTHDR(hdr); cmsg != nullptr;
cmsg = CMSG_NXTHDR(hdr, cmsg)) {
if ((cmsg->cmsg_level == IPPROTO_IP && cmsg->cmsg_type == IP_TTL) ||
(cmsg->cmsg_level == IPPROTO_IPV6 &&
cmsg->cmsg_type == IPV6_HOPLIMIT)) {
*ttl = *(reinterpret_cast<int*>(CMSG_DATA(cmsg)));
return true;
}
}
}
return false;
}
void QuicLinuxSocketUtils::SetIpInfoInCmsgData(
const QuicIpAddress& self_address, void* cmsg_data) {
QUICHE_DCHECK(self_address.IsInitialized());
const std::string& address_str = self_address.ToPackedString();
if (self_address.IsIPv4()) {
in_pktinfo* pktinfo = static_cast<in_pktinfo*>(cmsg_data);
pktinfo->ipi_ifindex = 0;
memcpy(&pktinfo->ipi_spec_dst, address_str.c_str(), address_str.length());
} else if (self_address.IsIPv6()) {
in6_pktinfo* pktinfo = static_cast<in6_pktinfo*>(cmsg_data);
memcpy(&pktinfo->ipi6_addr, address_str.c_str(), address_str.length());
} else {
QUIC_BUG(quic_bug_10598_1) << "Unrecognized IPAddress";
}
}
size_t QuicLinuxSocketUtils::SetIpInfoInCmsg(const QuicIpAddress& self_address,
cmsghdr* cmsg) {
std::string address_string;
if (self_address.IsIPv4()) {
cmsg->cmsg_len = CMSG_LEN(sizeof(in_pktinfo));
cmsg->cmsg_level = IPPROTO_IP;
cmsg->cmsg_type = IP_PKTINFO;
in_pktinfo* pktinfo = reinterpret_cast<in_pktinfo*>(CMSG_DATA(cmsg));
memset(pktinfo, 0, sizeof(in_pktinfo));
pktinfo->ipi_ifindex = 0;
address_string = self_address.ToPackedString();
memcpy(&pktinfo->ipi_spec_dst, address_string.c_str(),
address_string.length());
return sizeof(in_pktinfo);
} else if (self_address.IsIPv6()) {
cmsg->cmsg_len = CMSG_LEN(sizeof(in6_pktinfo));
cmsg->cmsg_level = IPPROTO_IPV6;
cmsg->cmsg_type = IPV6_PKTINFO;
in6_pktinfo* pktinfo = reinterpret_cast<in6_pktinfo*>(CMSG_DATA(cmsg));
memset(pktinfo, 0, sizeof(in6_pktinfo));
address_string = self_address.ToPackedString();
memcpy(&pktinfo->ipi6_addr, address_string.c_str(),
address_string.length());
return sizeof(in6_pktinfo);
} else {
QUIC_BUG(quic_bug_10598_2) << "Unrecognized IPAddress";
return 0;
}
}
WriteResult QuicLinuxSocketUtils::WritePacket(int fd, const QuicMsgHdr& hdr) {
int rc;
do {
rc = GetGlobalSyscallWrapper()->Sendmsg(fd, hdr.hdr(), 0);
} while (rc < 0 && errno == EINTR);
if (rc >= 0) {
return WriteResult(WRITE_STATUS_OK, rc);
}
return WriteResult((errno == EAGAIN || errno == EWOULDBLOCK)
? WRITE_STATUS_BLOCKED
: WRITE_STATUS_ERROR,
errno);
}
WriteResult QuicLinuxSocketUtils::WriteMultiplePackets(int fd,
QuicMMsgHdr* mhdr,
int* num_packets_sent) {
*num_packets_sent = 0;
if (mhdr->num_msgs() <= 0) {
return WriteResult(WRITE_STATUS_ERROR, EINVAL);
}
int rc;
do {
rc = GetGlobalSyscallWrapper()->Sendmmsg(fd, mhdr->mhdr(), mhdr->num_msgs(),
0);
} while (rc < 0 && errno == EINTR);
if (rc > 0) {
*num_packets_sent = rc;
return WriteResult(WRITE_STATUS_OK, mhdr->num_bytes_sent(rc));
} else if (rc == 0) {
QUIC_BUG(quic_bug_10598_3)
<< "sendmmsg returned 0, returning WRITE_STATUS_ERROR. errno: "
<< errno;
errno = EIO;
}
return WriteResult((errno == EAGAIN || errno == EWOULDBLOCK)
? WRITE_STATUS_BLOCKED
: WRITE_STATUS_ERROR,
errno);
}
} | #include "quiche/quic/core/quic_linux_socket_utils.h"
#include <netinet/in.h>
#include <stdint.h>
#include <cstddef>
#include <sstream>
#include <string>
#include <vector>
#include "quiche/quic/platform/api/quic_test.h"
#include "quiche/quic/test_tools/quic_mock_syscall_wrapper.h"
#include "quiche/common/quiche_circular_deque.h"
using testing::_;
using testing::InSequence;
using testing::Invoke;
namespace quic {
namespace test {
namespace {
class QuicLinuxSocketUtilsTest : public QuicTest {
protected:
WriteResult TestWriteMultiplePackets(
int fd,
const quiche::QuicheCircularDeque<BufferedWrite>::const_iterator& first,
const quiche::QuicheCircularDeque<BufferedWrite>::const_iterator& last,
int* num_packets_sent) {
QuicMMsgHdr mhdr(
first, last, kCmsgSpaceForIp,
[](QuicMMsgHdr* mhdr, int i, const BufferedWrite& buffered_write) {
mhdr->SetIpInNextCmsg(i, buffered_write.self_address);
});
WriteResult res =
QuicLinuxSocketUtils::WriteMultiplePackets(fd, &mhdr, num_packets_sent);
return res;
}
MockQuicSyscallWrapper mock_syscalls_;
ScopedGlobalSyscallWrapperOverride syscall_override_{&mock_syscalls_};
};
void CheckIpAndTtlInCbuf(msghdr* hdr, const void* cbuf,
const QuicIpAddress& self_addr, int ttl) {
const bool is_ipv4 = self_addr.IsIPv4();
const size_t ip_cmsg_space = is_ipv4 ? kCmsgSpaceForIpv4 : kCmsgSpaceForIpv6;
EXPECT_EQ(cbuf, hdr->msg_control);
EXPECT_EQ(ip_cmsg_space + CMSG_SPACE(sizeof(uint16_t)), hdr->msg_controllen);
cmsghdr* cmsg = CMSG_FIRSTHDR(hdr);
EXPECT_EQ(cmsg->cmsg_len, is_ipv4 ? CMSG_LEN(sizeof(in_pktinfo))
: CMSG_LEN(sizeof(in6_pktinfo)));
EXPECT_EQ(cmsg->cmsg_level, is_ipv4 ? IPPROTO_IP : IPPROTO_IPV6);
EXPECT_EQ(cmsg->cmsg_type, is_ipv4 ? IP_PKTINFO : IPV6_PKTINFO);
const std::string& self_addr_str = self_addr.ToPackedString();
if (is_ipv4) {
in_pktinfo* pktinfo = reinterpret_cast<in_pktinfo*>(CMSG_DATA(cmsg));
EXPECT_EQ(0, memcmp(&pktinfo->ipi_spec_dst, self_addr_str.c_str(),
self_addr_str.length()));
} else {
in6_pktinfo* pktinfo = reinterpret_cast<in6_pktinfo*>(CMSG_DATA(cmsg));
EXPECT_EQ(0, memcmp(&pktinfo->ipi6_addr, self_addr_str.c_str(),
self_addr_str.length()));
}
cmsg = CMSG_NXTHDR(hdr, cmsg);
EXPECT_EQ(cmsg->cmsg_len, CMSG_LEN(sizeof(int)));
EXPECT_EQ(cmsg->cmsg_level, is_ipv4 ? IPPROTO_IP : IPPROTO_IPV6);
EXPECT_EQ(cmsg->cmsg_type, is_ipv4 ? IP_TTL : IPV6_HOPLIMIT);
EXPECT_EQ(ttl, *reinterpret_cast<int*>(CMSG_DATA(cmsg)));
EXPECT_EQ(nullptr, CMSG_NXTHDR(hdr, cmsg));
}
void CheckMsghdrWithoutCbuf(const msghdr* hdr, const void* buffer,
size_t buf_len,
const QuicSocketAddress& peer_addr) {
EXPECT_EQ(
peer_addr.host().IsIPv4() ? sizeof(sockaddr_in) : sizeof(sockaddr_in6),
hdr->msg_namelen);
sockaddr_storage peer_generic_addr = peer_addr.generic_address();
EXPECT_EQ(0, memcmp(hdr->msg_name, &peer_generic_addr, hdr->msg_namelen));
EXPECT_EQ(1u, hdr->msg_iovlen);
EXPECT_EQ(buffer, hdr->msg_iov->iov_base);
EXPECT_EQ(buf_len, hdr->msg_iov->iov_len);
EXPECT_EQ(0, hdr->msg_flags);
EXPECT_EQ(nullptr, hdr->msg_control);
EXPECT_EQ(0u, hdr->msg_controllen);
}
void CheckIpAndGsoSizeInCbuf(msghdr* hdr, const void* cbuf,
const QuicIpAddress& self_addr,
uint16_t gso_size) {
const bool is_ipv4 = self_addr.IsIPv4();
const size_t ip_cmsg_space = is_ipv4 ? kCmsgSpaceForIpv4 : kCmsgSpaceForIpv6;
EXPECT_EQ(cbuf, hdr->msg_control);
EXPECT_EQ(ip_cmsg_space + CMSG_SPACE(sizeof(uint16_t)), hdr->msg_controllen);
cmsghdr* cmsg = CMSG_FIRSTHDR(hdr);
EXPECT_EQ(cmsg->cmsg_len, is_ipv4 ? CMSG_LEN(sizeof(in_pktinfo))
: CMSG_LEN(sizeof(in6_pktinfo)));
EXPECT_EQ(cmsg->cmsg_level, is_ipv4 ? IPPROTO_IP : IPPROTO_IPV6);
EXPECT_EQ(cmsg->cmsg_type, is_ipv4 ? IP_PKTINFO : IPV6_PKTINFO);
const std::string& self_addr_str = self_addr.ToPackedString();
if (is_ipv4) {
in_pktinfo* pktinfo = reinterpret_cast<in_pktinfo*>(CMSG_DATA(cmsg));
EXPECT_EQ(0, memcmp(&pktinfo->ipi_spec_dst, self_addr_str.c_str(),
self_addr_str.length()));
} else {
in6_pktinfo* pktinfo = reinterpret_cast<in6_pktinfo*>(CMSG_DATA(cmsg));
EXPECT_EQ(0, memcmp(&pktinfo->ipi6_addr, self_addr_str.c_str(),
self_addr_str.length()));
}
cmsg = CMSG_NXTHDR(hdr, cmsg);
EXPECT_EQ(cmsg->cmsg_len, CMSG_LEN(sizeof(uint16_t)));
EXPECT_EQ(cmsg->cmsg_level, SOL_UDP);
EXPECT_EQ(cmsg->cmsg_type, UDP_SEGMENT);
EXPECT_EQ(gso_size, *reinterpret_cast<uint16_t*>(CMSG_DATA(cmsg)));
EXPECT_EQ(nullptr, CMSG_NXTHDR(hdr, cmsg));
}
TEST_F(QuicLinuxSocketUtilsTest, QuicMsgHdr) {
QuicSocketAddress peer_addr(QuicIpAddress::Loopback4(), 1234);
char packet_buf[1024];
iovec iov{packet_buf, sizeof(packet_buf)};
{
QuicMsgHdr quic_hdr(&iov, 1, nullptr, 0);
quic_hdr.SetPeerAddress(peer_addr);
CheckMsghdrWithoutCbuf(quic_hdr.hdr(), packet_buf, sizeof(packet_buf),
peer_addr);
}
for (bool is_ipv4 : {true, false}) {
QuicIpAddress self_addr =
is_ipv4 ? QuicIpAddress::Loopback4() : QuicIpAddress::Loopback6();
alignas(cmsghdr) char cbuf[kCmsgSpaceForIp + kCmsgSpaceForTTL];
QuicMsgHdr quic_hdr(&iov, 1, cbuf, sizeof(cbuf));
quic_hdr.SetPeerAddress(peer_addr);
msghdr* hdr = const_cast<msghdr*>(quic_hdr.hdr());
EXPECT_EQ(nullptr, hdr->msg_control);
EXPECT_EQ(0u, hdr->msg_controllen);
quic_hdr.SetIpInNextCmsg(self_addr);
EXPECT_EQ(cbuf, hdr->msg_control);
const size_t ip_cmsg_space =
is_ipv4 ? kCmsgSpaceForIpv4 : kCmsgSpaceForIpv6;
EXPECT_EQ(ip_cmsg_space, hdr->msg_controllen);
if (is_ipv4) {
*quic_hdr.GetNextCmsgData<int>(IPPROTO_IP, IP_TTL) = 32;
} else {
*quic_hdr.GetNextCmsgData<int>(IPPROTO_IPV6, IPV6_HOPLIMIT) = 32;
}
CheckIpAndTtlInCbuf(hdr, cbuf, self_addr, 32);
}
}
TEST_F(QuicLinuxSocketUtilsTest, QuicMMsgHdr) {
quiche::QuicheCircularDeque<BufferedWrite> buffered_writes;
char packet_buf1[1024];
char packet_buf2[512];
buffered_writes.emplace_back(
packet_buf1, sizeof(packet_buf1), QuicIpAddress::Loopback4(),
QuicSocketAddress(QuicIpAddress::Loopback4(), 4));
buffered_writes.emplace_back(
packet_buf2, sizeof(packet_buf2), QuicIpAddress::Loopback6(),
QuicSocketAddress(QuicIpAddress::Loopback6(), 6));
QuicMMsgHdr quic_mhdr_without_cbuf(buffered_writes.begin(),
buffered_writes.end(), 0);
for (size_t i = 0; i < buffered_writes.size(); ++i) {
const BufferedWrite& bw = buffered_writes[i];
CheckMsghdrWithoutCbuf(&quic_mhdr_without_cbuf.mhdr()[i].msg_hdr, bw.buffer,
bw.buf_len, bw.peer_address);
}
QuicMMsgHdr quic_mhdr_with_cbuf(
buffered_writes.begin(), buffered_writes.end(),
kCmsgSpaceForIp + kCmsgSpaceForSegmentSize,
[](QuicMMsgHdr* mhdr, int i, const BufferedWrite& buffered_write) {
mhdr->SetIpInNextCmsg(i, buffered_write.self_address);
*mhdr->GetNextCmsgData<uint16_t>(i, SOL_UDP, UDP_SEGMENT) = 1300;
});
for (size_t i = 0; i < buffered_writes.size(); ++i) {
const BufferedWrite& bw = buffered_writes[i];
msghdr* hdr = &quic_mhdr_with_cbuf.mhdr()[i].msg_hdr;
CheckIpAndGsoSizeInCbuf(hdr, hdr->msg_control, bw.self_address, 1300);
}
}
TEST_F(QuicLinuxSocketUtilsTest, WriteMultiplePackets_NoPacketsToSend) {
int num_packets_sent;
quiche::QuicheCircularDeque<BufferedWrite> buffered_writes;
EXPECT_CALL(mock_syscalls_, Sendmmsg(_, _, _, _)).Times(0);
EXPECT_EQ(WriteResult(WRITE_STATUS_ERROR, EINVAL),
TestWriteMultiplePackets(1, buffered_writes.begin(),
buffered_writes.end(), &num_packets_sent));
}
TEST_F(QuicLinuxSocketUtilsTest, WriteMultiplePackets_WriteBlocked) {
int num_packets_sent;
quiche::QuicheCircularDeque<BufferedWrite> buffered_writes;
buffered_writes.emplace_back(nullptr, 0, QuicIpAddress(),
QuicSocketAddress(QuicIpAddress::Any4(), 0));
EXPECT_CALL(mock_syscalls_, Sendmmsg(_, _, _, _))
.WillOnce(Invoke([](int , mmsghdr* ,
unsigned int , int ) {
errno = EWOULDBLOCK;
return -1;
}));
EXPECT_EQ(WriteResult(WRITE_STATUS_BLOCKED, EWOULDBLOCK),
TestWriteMultiplePackets(1, buffered_writes.begin(),
buffered_writes.end(), &num_packets_sent));
EXPECT_EQ(0, num_packets_sent);
}
TEST_F(QuicLinuxSocketUtilsTest, WriteMultiplePackets_WriteError) {
int num_packets_sent;
quiche::QuicheCircularDeque<BufferedWrite> buffered_writes;
buffered_writes.emplace_back(nullptr, 0, QuicIpAddress(),
QuicSocketAddress(QuicIpAddress::Any4(), 0));
EXPECT_CALL(mock_syscalls_, Sendmmsg(_, _, _, _))
.WillOnce(Invoke([](int , mmsghdr* ,
unsigned int , int ) {
errno = EPERM;
return -1;
}));
EXPECT_EQ(WriteResult(WRITE_STATUS_ERROR, EPERM),
TestWriteMultiplePackets(1, buffered_writes.begin(),
buffered_writes.end(), &num_packets_sent));
EXPECT_EQ(0, num_packets_sent);
}
TEST_F(QuicLinuxSocketUtilsTest, WriteMultiplePackets_WriteSuccess) {
int num_packets_sent;
quiche::QuicheCircularDeque<BufferedWrite> buffered_writes;
const int kNumBufferedWrites = 10;
static_assert(kNumBufferedWrites < 256, "Must be less than 256");
std::vector<std::string> buffer_holder;
for (int i = 0; i < kNumBufferedWrites; ++i) {
size_t buf_len = (i + 1) * 2;
std::ostringstream buffer_ostream;
while (buffer_ostream.str().length() < buf_len) {
buffer_ostream << i;
}
buffer_holder.push_back(buffer_ostream.str().substr(0, buf_len - 1) + '$');
buffered_writes.emplace_back(buffer_holder.back().data(), buf_len,
QuicIpAddress(),
QuicSocketAddress(QuicIpAddress::Any4(), 0));
if (i != 0) {
ASSERT_TRUE(buffered_writes.back().self_address.FromString("127.0.0.1"));
}
std::ostringstream peer_ip_ostream;
QuicIpAddress peer_ip_address;
peer_ip_ostream << "127.0.1." << i + 1;
ASSERT_TRUE(peer_ip_address.FromString(peer_ip_ostream.str()));
buffered_writes.back().peer_address =
QuicSocketAddress(peer_ip_address, i + 1);
}
InSequence s;
for (int expected_num_packets_sent : {1, 2, 3, 10}) {
SCOPED_TRACE(testing::Message()
<< "expected_num_packets_sent=" << expected_num_packets_sent);
EXPECT_CALL(mock_syscalls_, Sendmmsg(_, _, _, _))
.WillOnce(Invoke([&](int , mmsghdr* msgvec, unsigned int vlen,
int ) {
EXPECT_LE(static_cast<unsigned int>(expected_num_packets_sent), vlen);
for (unsigned int i = 0; i < vlen; ++i) {
const BufferedWrite& buffered_write = buffered_writes[i];
const msghdr& hdr = msgvec[i].msg_hdr;
EXPECT_EQ(1u, hdr.msg_iovlen);
EXPECT_EQ(buffered_write.buffer, hdr.msg_iov->iov_base);
EXPECT_EQ(buffered_write.buf_len, hdr.msg_iov->iov_len);
sockaddr_storage expected_peer_address =
buffered_write.peer_address.generic_address();
EXPECT_EQ(0, memcmp(&expected_peer_address, hdr.msg_name,
sizeof(sockaddr_storage)));
EXPECT_EQ(buffered_write.self_address.IsInitialized(),
hdr.msg_control != nullptr);
}
return expected_num_packets_sent;
}))
.RetiresOnSaturation();
int expected_bytes_written = 0;
for (auto it = buffered_writes.cbegin();
it != buffered_writes.cbegin() + expected_num_packets_sent; ++it) {
expected_bytes_written += it->buf_len;
}
EXPECT_EQ(
WriteResult(WRITE_STATUS_OK, expected_bytes_written),
TestWriteMultiplePackets(1, buffered_writes.cbegin(),
buffered_writes.cend(), &num_packets_sent));
EXPECT_EQ(expected_num_packets_sent, num_packets_sent);
}
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_linux_socket_utils.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_linux_socket_utils_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
5611789e-150e-4d79-9881-878f6039e44c | cpp | google/quiche | quic_stream_send_buffer | quiche/quic/core/quic_stream_send_buffer.cc | quiche/quic/core/quic_stream_send_buffer_test.cc | #include "quiche/quic/core/quic_stream_send_buffer.h"
#include <algorithm>
#include <utility>
#include "quiche/quic/core/quic_data_writer.h"
#include "quiche/quic/core/quic_interval.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_mem_slice.h"
namespace quic {
namespace {
struct CompareOffset {
bool operator()(const BufferedSlice& slice, QuicStreamOffset offset) const {
return slice.offset + slice.slice.length() < offset;
}
};
}
BufferedSlice::BufferedSlice(quiche::QuicheMemSlice mem_slice,
QuicStreamOffset offset)
: slice(std::move(mem_slice)), offset(offset) {}
BufferedSlice::BufferedSlice(BufferedSlice&& other) = default;
BufferedSlice& BufferedSlice::operator=(BufferedSlice&& other) = default;
BufferedSlice::~BufferedSlice() {}
QuicInterval<std::size_t> BufferedSlice::interval() const {
const std::size_t length = slice.length();
return QuicInterval<std::size_t>(offset, offset + length);
}
bool StreamPendingRetransmission::operator==(
const StreamPendingRetransmission& other) const {
return offset == other.offset && length == other.length;
}
QuicStreamSendBuffer::QuicStreamSendBuffer(
quiche::QuicheBufferAllocator* allocator)
: current_end_offset_(0),
stream_offset_(0),
allocator_(allocator),
stream_bytes_written_(0),
stream_bytes_outstanding_(0),
write_index_(-1) {}
QuicStreamSendBuffer::~QuicStreamSendBuffer() {}
void QuicStreamSendBuffer::SaveStreamData(absl::string_view data) {
QUICHE_DCHECK(!data.empty());
const QuicByteCount max_data_slice_size =
GetQuicFlag(quic_send_buffer_max_data_slice_size);
while (!data.empty()) {
auto slice_len = std::min<absl::string_view::size_type>(
data.length(), max_data_slice_size);
auto buffer =
quiche::QuicheBuffer::Copy(allocator_, data.substr(0, slice_len));
SaveMemSlice(quiche::QuicheMemSlice(std::move(buffer)));
data = data.substr(slice_len);
}
}
void QuicStreamSendBuffer::SaveMemSlice(quiche::QuicheMemSlice slice) {
QUIC_DVLOG(2) << "Save slice offset " << stream_offset_ << " length "
<< slice.length();
if (slice.empty()) {
QUIC_BUG(quic_bug_10853_1) << "Try to save empty MemSlice to send buffer.";
return;
}
size_t length = slice.length();
if (interval_deque_.Empty()) {
const QuicStreamOffset end = stream_offset_ + length;
current_end_offset_ = std::max(current_end_offset_, end);
}
BufferedSlice bs = BufferedSlice(std::move(slice), stream_offset_);
interval_deque_.PushBack(std::move(bs));
stream_offset_ += length;
}
QuicByteCount QuicStreamSendBuffer::SaveMemSliceSpan(
absl::Span<quiche::QuicheMemSlice> span) {
QuicByteCount total = 0;
for (quiche::QuicheMemSlice& slice : span) {
if (slice.length() == 0) {
continue;
}
total += slice.length();
SaveMemSlice(std::move(slice));
}
return total;
}
void QuicStreamSendBuffer::OnStreamDataConsumed(size_t bytes_consumed) {
stream_bytes_written_ += bytes_consumed;
stream_bytes_outstanding_ += bytes_consumed;
}
bool QuicStreamSendBuffer::WriteStreamData(QuicStreamOffset offset,
QuicByteCount data_length,
QuicDataWriter* writer) {
QUIC_BUG_IF(quic_bug_12823_1, current_end_offset_ < offset)
<< "Tried to write data out of sequence. last_offset_end:"
<< current_end_offset_ << ", offset:" << offset;
for (auto slice_it = interval_deque_.DataAt(offset);
slice_it != interval_deque_.DataEnd(); ++slice_it) {
if (data_length == 0 || offset < slice_it->offset) {
break;
}
QuicByteCount slice_offset = offset - slice_it->offset;
QuicByteCount available_bytes_in_slice =
slice_it->slice.length() - slice_offset;
QuicByteCount copy_length = std::min(data_length, available_bytes_in_slice);
if (!writer->WriteBytes(slice_it->slice.data() + slice_offset,
copy_length)) {
QUIC_BUG(quic_bug_10853_2) << "Writer fails to write.";
return false;
}
offset += copy_length;
data_length -= copy_length;
const QuicStreamOffset new_end =
slice_it->offset + slice_it->slice.length();
current_end_offset_ = std::max(current_end_offset_, new_end);
}
return data_length == 0;
}
bool QuicStreamSendBuffer::OnStreamDataAcked(
QuicStreamOffset offset, QuicByteCount data_length,
QuicByteCount* newly_acked_length) {
*newly_acked_length = 0;
if (data_length == 0) {
return true;
}
if (bytes_acked_.Empty() || offset >= bytes_acked_.rbegin()->max() ||
bytes_acked_.IsDisjoint(
QuicInterval<QuicStreamOffset>(offset, offset + data_length))) {
if (stream_bytes_outstanding_ < data_length) {
return false;
}
bytes_acked_.AddOptimizedForAppend(offset, offset + data_length);
*newly_acked_length = data_length;
stream_bytes_outstanding_ -= data_length;
pending_retransmissions_.Difference(offset, offset + data_length);
if (!FreeMemSlices(offset, offset + data_length)) {
return false;
}
CleanUpBufferedSlices();
return true;
}
if (bytes_acked_.Contains(offset, offset + data_length)) {
return true;
}
QuicIntervalSet<QuicStreamOffset> newly_acked(offset, offset + data_length);
newly_acked.Difference(bytes_acked_);
for (const auto& interval : newly_acked) {
*newly_acked_length += (interval.max() - interval.min());
}
if (stream_bytes_outstanding_ < *newly_acked_length) {
return false;
}
stream_bytes_outstanding_ -= *newly_acked_length;
bytes_acked_.Add(offset, offset + data_length);
pending_retransmissions_.Difference(offset, offset + data_length);
if (newly_acked.Empty()) {
return true;
}
if (!FreeMemSlices(newly_acked.begin()->min(), newly_acked.rbegin()->max())) {
return false;
}
CleanUpBufferedSlices();
return true;
}
void QuicStreamSendBuffer::OnStreamDataLost(QuicStreamOffset offset,
QuicByteCount data_length) {
if (data_length == 0) {
return;
}
QuicIntervalSet<QuicStreamOffset> bytes_lost(offset, offset + data_length);
bytes_lost.Difference(bytes_acked_);
if (bytes_lost.Empty()) {
return;
}
for (const auto& lost : bytes_lost) {
pending_retransmissions_.Add(lost.min(), lost.max());
}
}
void QuicStreamSendBuffer::OnStreamDataRetransmitted(
QuicStreamOffset offset, QuicByteCount data_length) {
if (data_length == 0) {
return;
}
pending_retransmissions_.Difference(offset, offset + data_length);
}
bool QuicStreamSendBuffer::HasPendingRetransmission() const {
return !pending_retransmissions_.Empty();
}
StreamPendingRetransmission QuicStreamSendBuffer::NextPendingRetransmission()
const {
if (HasPendingRetransmission()) {
const auto pending = pending_retransmissions_.begin();
return {pending->min(), pending->max() - pending->min()};
}
QUIC_BUG(quic_bug_10853_3)
<< "NextPendingRetransmission is called unexpected with no "
"pending retransmissions.";
return {0, 0};
}
bool QuicStreamSendBuffer::FreeMemSlices(QuicStreamOffset start,
QuicStreamOffset end) {
auto it = interval_deque_.DataBegin();
if (it == interval_deque_.DataEnd() || it->slice.empty()) {
QUIC_BUG(quic_bug_10853_4)
<< "Trying to ack stream data [" << start << ", " << end << "), "
<< (it == interval_deque_.DataEnd()
? "and there is no outstanding data."
: "and the first slice is empty.");
return false;
}
if (!it->interval().Contains(start)) {
it = std::lower_bound(interval_deque_.DataBegin(),
interval_deque_.DataEnd(), start, CompareOffset());
}
if (it == interval_deque_.DataEnd() || it->slice.empty()) {
QUIC_BUG(quic_bug_10853_5)
<< "Offset " << start << " with iterator offset: " << it->offset
<< (it == interval_deque_.DataEnd() ? " does not exist."
: " has already been acked.");
return false;
}
for (; it != interval_deque_.DataEnd(); ++it) {
if (it->offset >= end) {
break;
}
if (!it->slice.empty() &&
bytes_acked_.Contains(it->offset, it->offset + it->slice.length())) {
it->slice.Reset();
}
}
return true;
}
void QuicStreamSendBuffer::CleanUpBufferedSlices() {
while (!interval_deque_.Empty() &&
interval_deque_.DataBegin()->slice.empty()) {
QUIC_BUG_IF(quic_bug_12823_2,
interval_deque_.DataBegin()->offset > current_end_offset_)
<< "Fail to pop front from interval_deque_. Front element contained "
"a slice whose data has not all be written. Front offset "
<< interval_deque_.DataBegin()->offset << " length "
<< interval_deque_.DataBegin()->slice.length();
interval_deque_.PopFront();
}
}
bool QuicStreamSendBuffer::IsStreamDataOutstanding(
QuicStreamOffset offset, QuicByteCount data_length) const {
return data_length > 0 &&
!bytes_acked_.Contains(offset, offset + data_length);
}
size_t QuicStreamSendBuffer::size() const { return interval_deque_.Size(); }
} | #include "quiche/quic/core/quic_stream_send_buffer.h"
#include <string>
#include <utility>
#include <vector>
#include "absl/strings/string_view.h"
#include "quiche/quic/core/quic_data_writer.h"
#include "quiche/quic/core/quic_utils.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_stream_send_buffer_peer.h"
#include "quiche/quic/test_tools/quic_test_utils.h"
#include "quiche/common/simple_buffer_allocator.h"
namespace quic {
namespace test {
namespace {
class QuicStreamSendBufferTest : public QuicTest {
public:
QuicStreamSendBufferTest() : send_buffer_(&allocator_) {
EXPECT_EQ(0u, send_buffer_.size());
EXPECT_EQ(0u, send_buffer_.stream_bytes_written());
EXPECT_EQ(0u, send_buffer_.stream_bytes_outstanding());
EXPECT_EQ(0u, QuicStreamSendBufferPeer::EndOffset(&send_buffer_));
std::string data1 = absl::StrCat(
std::string(1536, 'a'), std::string(256, 'b'), std::string(256, 'c'));
quiche::QuicheBuffer buffer1(&allocator_, 1024);
memset(buffer1.data(), 'c', buffer1.size());
quiche::QuicheMemSlice slice1(std::move(buffer1));
quiche::QuicheBuffer buffer2(&allocator_, 768);
memset(buffer2.data(), 'd', buffer2.size());
quiche::QuicheMemSlice slice2(std::move(buffer2));
SetQuicFlag(quic_send_buffer_max_data_slice_size, 1024);
send_buffer_.SaveStreamData(data1);
send_buffer_.SaveMemSlice(std::move(slice1));
EXPECT_TRUE(slice1.empty());
send_buffer_.SaveMemSlice(std::move(slice2));
EXPECT_TRUE(slice2.empty());
EXPECT_EQ(4u, send_buffer_.size());
}
void WriteAllData() {
char buf[4000];
QuicDataWriter writer(4000, buf, quiche::HOST_BYTE_ORDER);
send_buffer_.WriteStreamData(0, 3840u, &writer);
send_buffer_.OnStreamDataConsumed(3840u);
EXPECT_EQ(3840u, send_buffer_.stream_bytes_written());
EXPECT_EQ(3840u, send_buffer_.stream_bytes_outstanding());
}
quiche::SimpleBufferAllocator allocator_;
QuicStreamSendBuffer send_buffer_;
};
TEST_F(QuicStreamSendBufferTest, CopyDataToBuffer) {
char buf[4000];
QuicDataWriter writer(4000, buf, quiche::HOST_BYTE_ORDER);
std::string copy1(1024, 'a');
std::string copy2 =
std::string(512, 'a') + std::string(256, 'b') + std::string(256, 'c');
std::string copy3(1024, 'c');
std::string copy4(768, 'd');
ASSERT_TRUE(send_buffer_.WriteStreamData(0, 1024, &writer));
EXPECT_EQ(copy1, absl::string_view(buf, 1024));
ASSERT_TRUE(send_buffer_.WriteStreamData(1024, 1024, &writer));
EXPECT_EQ(copy2, absl::string_view(buf + 1024, 1024));
ASSERT_TRUE(send_buffer_.WriteStreamData(2048, 1024, &writer));
EXPECT_EQ(copy3, absl::string_view(buf + 2048, 1024));
ASSERT_TRUE(send_buffer_.WriteStreamData(3072, 768, &writer));
EXPECT_EQ(copy4, absl::string_view(buf + 3072, 768));
QuicDataWriter writer2(4000, buf, quiche::HOST_BYTE_ORDER);
std::string copy5 =
std::string(536, 'a') + std::string(256, 'b') + std::string(232, 'c');
ASSERT_TRUE(send_buffer_.WriteStreamData(1000, 1024, &writer2));
EXPECT_EQ(copy5, absl::string_view(buf, 1024));
ASSERT_TRUE(send_buffer_.WriteStreamData(2500, 1024, &writer2));
std::string copy6 = std::string(572, 'c') + std::string(452, 'd');
EXPECT_EQ(copy6, absl::string_view(buf + 1024, 1024));
QuicDataWriter writer3(4000, buf, quiche::HOST_BYTE_ORDER);
EXPECT_FALSE(send_buffer_.WriteStreamData(3000, 1024, &writer3));
EXPECT_QUIC_BUG(send_buffer_.WriteStreamData(0, 4000, &writer3),
"Writer fails to write.");
send_buffer_.OnStreamDataConsumed(3840);
EXPECT_EQ(3840u, send_buffer_.stream_bytes_written());
EXPECT_EQ(3840u, send_buffer_.stream_bytes_outstanding());
}
TEST_F(QuicStreamSendBufferTest,
WriteStreamDataContainsBothRetransmissionAndNewData) {
std::string copy1(1024, 'a');
std::string copy2 =
std::string(512, 'a') + std::string(256, 'b') + std::string(256, 'c');
std::string copy3 = std::string(1024, 'c') + std::string(100, 'd');
char buf[6000];
QuicDataWriter writer(6000, buf, quiche::HOST_BYTE_ORDER);
EXPECT_EQ(0, QuicStreamSendBufferPeer::write_index(&send_buffer_));
ASSERT_TRUE(send_buffer_.WriteStreamData(0, 1024, &writer));
EXPECT_EQ(copy1, absl::string_view(buf, 1024));
EXPECT_EQ(1, QuicStreamSendBufferPeer::write_index(&send_buffer_));
ASSERT_TRUE(send_buffer_.WriteStreamData(0, 2048, &writer));
EXPECT_EQ(copy1 + copy2, absl::string_view(buf + 1024, 2048));
EXPECT_EQ(2048u, QuicStreamSendBufferPeer::EndOffset(&send_buffer_));
ASSERT_TRUE(send_buffer_.WriteStreamData(2048, 50, &writer));
EXPECT_EQ(std::string(50, 'c'), absl::string_view(buf + 1024 + 2048, 50));
EXPECT_EQ(3072u, QuicStreamSendBufferPeer::EndOffset(&send_buffer_));
ASSERT_TRUE(send_buffer_.WriteStreamData(2048, 1124, &writer));
EXPECT_EQ(copy3, absl::string_view(buf + 1024 + 2048 + 50, 1124));
EXPECT_EQ(3840u, QuicStreamSendBufferPeer::EndOffset(&send_buffer_));
}
TEST_F(QuicStreamSendBufferTest, RemoveStreamFrame) {
WriteAllData();
QuicByteCount newly_acked_length;
EXPECT_TRUE(send_buffer_.OnStreamDataAcked(1024, 1024, &newly_acked_length));
EXPECT_EQ(1024u, newly_acked_length);
EXPECT_EQ(4u, send_buffer_.size());
EXPECT_TRUE(send_buffer_.OnStreamDataAcked(2048, 1024, &newly_acked_length));
EXPECT_EQ(1024u, newly_acked_length);
EXPECT_EQ(4u, send_buffer_.size());
EXPECT_TRUE(send_buffer_.OnStreamDataAcked(0, 1024, &newly_acked_length));
EXPECT_EQ(1024u, newly_acked_length);
EXPECT_EQ(1u, send_buffer_.size());
EXPECT_TRUE(send_buffer_.OnStreamDataAcked(3072, 768, &newly_acked_length));
EXPECT_EQ(768u, newly_acked_length);
EXPECT_EQ(0u, send_buffer_.size());
}
TEST_F(QuicStreamSendBufferTest, RemoveStreamFrameAcrossBoundries) {
WriteAllData();
QuicByteCount newly_acked_length;
EXPECT_TRUE(send_buffer_.OnStreamDataAcked(2024, 576, &newly_acked_length));
EXPECT_EQ(576u, newly_acked_length);
EXPECT_EQ(4u, send_buffer_.size());
EXPECT_TRUE(send_buffer_.OnStreamDataAcked(0, 1000, &newly_acked_length));
EXPECT_EQ(1000u, newly_acked_length);
EXPECT_EQ(4u, send_buffer_.size());
EXPECT_TRUE(send_buffer_.OnStreamDataAcked(1000, 1024, &newly_acked_length));
EXPECT_EQ(1024u, newly_acked_length);
EXPECT_EQ(2u, send_buffer_.size());
EXPECT_TRUE(send_buffer_.OnStreamDataAcked(2600, 1024, &newly_acked_length));
EXPECT_EQ(1024u, newly_acked_length);
EXPECT_EQ(1u, send_buffer_.size());
EXPECT_TRUE(send_buffer_.OnStreamDataAcked(3624, 216, &newly_acked_length));
EXPECT_EQ(216u, newly_acked_length);
EXPECT_EQ(0u, send_buffer_.size());
}
TEST_F(QuicStreamSendBufferTest, AckStreamDataMultipleTimes) {
WriteAllData();
QuicByteCount newly_acked_length;
EXPECT_TRUE(send_buffer_.OnStreamDataAcked(100, 1500, &newly_acked_length));
EXPECT_EQ(1500u, newly_acked_length);
EXPECT_EQ(4u, send_buffer_.size());
EXPECT_TRUE(send_buffer_.OnStreamDataAcked(2000, 500, &newly_acked_length));
EXPECT_EQ(500u, newly_acked_length);
EXPECT_EQ(4u, send_buffer_.size());
EXPECT_TRUE(send_buffer_.OnStreamDataAcked(0, 2600, &newly_acked_length));
EXPECT_EQ(600u, newly_acked_length);
EXPECT_EQ(2u, send_buffer_.size());
EXPECT_TRUE(send_buffer_.OnStreamDataAcked(2200, 1640, &newly_acked_length));
EXPECT_EQ(1240u, newly_acked_length);
EXPECT_EQ(0u, send_buffer_.size());
EXPECT_FALSE(send_buffer_.OnStreamDataAcked(4000, 100, &newly_acked_length));
}
TEST_F(QuicStreamSendBufferTest, AckStreamDataOutOfOrder) {
WriteAllData();
QuicByteCount newly_acked_length;
EXPECT_TRUE(send_buffer_.OnStreamDataAcked(500, 1000, &newly_acked_length));
EXPECT_EQ(1000u, newly_acked_length);
EXPECT_EQ(4u, send_buffer_.size());
EXPECT_EQ(3840u, QuicStreamSendBufferPeer::TotalLength(&send_buffer_));
EXPECT_TRUE(send_buffer_.OnStreamDataAcked(1200, 1000, &newly_acked_length));
EXPECT_EQ(700u, newly_acked_length);
EXPECT_EQ(4u, send_buffer_.size());
EXPECT_EQ(2816u, QuicStreamSendBufferPeer::TotalLength(&send_buffer_));
EXPECT_TRUE(send_buffer_.OnStreamDataAcked(2000, 1840, &newly_acked_length));
EXPECT_EQ(1640u, newly_acked_length);
EXPECT_EQ(4u, send_buffer_.size());
EXPECT_EQ(1024u, QuicStreamSendBufferPeer::TotalLength(&send_buffer_));
EXPECT_TRUE(send_buffer_.OnStreamDataAcked(0, 1000, &newly_acked_length));
EXPECT_EQ(500u, newly_acked_length);
EXPECT_EQ(0u, send_buffer_.size());
EXPECT_EQ(0u, QuicStreamSendBufferPeer::TotalLength(&send_buffer_));
}
TEST_F(QuicStreamSendBufferTest, PendingRetransmission) {
WriteAllData();
EXPECT_TRUE(send_buffer_.IsStreamDataOutstanding(0, 3840));
EXPECT_FALSE(send_buffer_.HasPendingRetransmission());
send_buffer_.OnStreamDataLost(0, 1200);
send_buffer_.OnStreamDataLost(1500, 500);
EXPECT_TRUE(send_buffer_.HasPendingRetransmission());
EXPECT_EQ(StreamPendingRetransmission(0, 1200),
send_buffer_.NextPendingRetransmission());
send_buffer_.OnStreamDataRetransmitted(0, 500);
EXPECT_TRUE(send_buffer_.IsStreamDataOutstanding(0, 500));
EXPECT_EQ(StreamPendingRetransmission(500, 700),
send_buffer_.NextPendingRetransmission());
QuicByteCount newly_acked_length = 0;
EXPECT_TRUE(send_buffer_.OnStreamDataAcked(500, 700, &newly_acked_length));
EXPECT_FALSE(send_buffer_.IsStreamDataOutstanding(500, 700));
EXPECT_TRUE(send_buffer_.HasPendingRetransmission());
EXPECT_EQ(StreamPendingRetransmission(1500, 500),
send_buffer_.NextPendingRetransmission());
send_buffer_.OnStreamDataRetransmitted(1500, 500);
EXPECT_FALSE(send_buffer_.HasPendingRetransmission());
send_buffer_.OnStreamDataLost(200, 600);
EXPECT_TRUE(send_buffer_.HasPendingRetransmission());
EXPECT_EQ(StreamPendingRetransmission(200, 300),
send_buffer_.NextPendingRetransmission());
EXPECT_FALSE(send_buffer_.IsStreamDataOutstanding(100, 0));
EXPECT_TRUE(send_buffer_.IsStreamDataOutstanding(400, 800));
}
TEST_F(QuicStreamSendBufferTest, EndOffset) {
char buf[4000];
QuicDataWriter writer(4000, buf, quiche::HOST_BYTE_ORDER);
EXPECT_EQ(1024u, QuicStreamSendBufferPeer::EndOffset(&send_buffer_));
ASSERT_TRUE(send_buffer_.WriteStreamData(0, 1024, &writer));
EXPECT_EQ(1024u, QuicStreamSendBufferPeer::EndOffset(&send_buffer_));
ASSERT_TRUE(send_buffer_.WriteStreamData(1024, 512, &writer));
EXPECT_EQ(2048u, QuicStreamSendBufferPeer::EndOffset(&send_buffer_));
send_buffer_.OnStreamDataConsumed(1024);
QuicByteCount newly_acked_length;
EXPECT_TRUE(send_buffer_.OnStreamDataAcked(0, 1024, &newly_acked_length));
EXPECT_EQ(2048u, QuicStreamSendBufferPeer::EndOffset(&send_buffer_));
ASSERT_TRUE(
send_buffer_.WriteStreamData(1024 + 512, 3840 - 1024 - 512, &writer));
EXPECT_EQ(3840u, QuicStreamSendBufferPeer::EndOffset(&send_buffer_));
quiche::QuicheBuffer buffer(&allocator_, 60);
memset(buffer.data(), 'e', buffer.size());
quiche::QuicheMemSlice slice(std::move(buffer));
send_buffer_.SaveMemSlice(std::move(slice));
EXPECT_EQ(3840u, QuicStreamSendBufferPeer::EndOffset(&send_buffer_));
}
TEST_F(QuicStreamSendBufferTest, SaveMemSliceSpan) {
quiche::SimpleBufferAllocator allocator;
QuicStreamSendBuffer send_buffer(&allocator);
std::string data(1024, 'a');
std::vector<quiche::QuicheMemSlice> buffers;
for (size_t i = 0; i < 10; ++i) {
buffers.push_back(MemSliceFromString(data));
}
EXPECT_EQ(10 * 1024u, send_buffer.SaveMemSliceSpan(absl::MakeSpan(buffers)));
EXPECT_EQ(10u, send_buffer.size());
}
TEST_F(QuicStreamSendBufferTest, SaveEmptyMemSliceSpan) {
quiche::SimpleBufferAllocator allocator;
QuicStreamSendBuffer send_buffer(&allocator);
std::string data(1024, 'a');
std::vector<quiche::QuicheMemSlice> buffers;
for (size_t i = 0; i < 10; ++i) {
buffers.push_back(MemSliceFromString(data));
}
EXPECT_EQ(10 * 1024u, send_buffer.SaveMemSliceSpan(absl::MakeSpan(buffers)));
EXPECT_EQ(10u, send_buffer.size());
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_stream_send_buffer.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_stream_send_buffer_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
589b93b3-2eb7-49ee-946c-2062dc9b29b0 | cpp | google/quiche | legacy_quic_stream_id_manager | quiche/quic/core/legacy_quic_stream_id_manager.cc | quiche/quic/core/legacy_quic_stream_id_manager_test.cc | #include "quiche/quic/core/legacy_quic_stream_id_manager.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"
namespace quic {
LegacyQuicStreamIdManager::LegacyQuicStreamIdManager(
Perspective perspective, QuicTransportVersion transport_version,
size_t max_open_outgoing_streams, size_t max_open_incoming_streams)
: perspective_(perspective),
transport_version_(transport_version),
max_open_outgoing_streams_(max_open_outgoing_streams),
max_open_incoming_streams_(max_open_incoming_streams),
next_outgoing_stream_id_(QuicUtils::GetFirstBidirectionalStreamId(
transport_version_, perspective_)),
largest_peer_created_stream_id_(
perspective_ == Perspective::IS_SERVER
? (QuicVersionUsesCryptoFrames(transport_version_)
? QuicUtils::GetInvalidStreamId(transport_version_)
: QuicUtils::GetCryptoStreamId(transport_version_))
: QuicUtils::GetInvalidStreamId(transport_version_)),
num_open_incoming_streams_(0),
num_open_outgoing_streams_(0) {}
LegacyQuicStreamIdManager::~LegacyQuicStreamIdManager() {}
bool LegacyQuicStreamIdManager::CanOpenNextOutgoingStream() const {
QUICHE_DCHECK_LE(num_open_outgoing_streams_, max_open_outgoing_streams_);
QUIC_DLOG_IF(INFO, num_open_outgoing_streams_ == max_open_outgoing_streams_)
<< "Failed to create a new outgoing stream. "
<< "Already " << num_open_outgoing_streams_ << " open.";
return num_open_outgoing_streams_ < max_open_outgoing_streams_;
}
bool LegacyQuicStreamIdManager::CanOpenIncomingStream() const {
return num_open_incoming_streams_ < max_open_incoming_streams_;
}
bool LegacyQuicStreamIdManager::MaybeIncreaseLargestPeerStreamId(
const QuicStreamId stream_id) {
available_streams_.erase(stream_id);
if (largest_peer_created_stream_id_ !=
QuicUtils::GetInvalidStreamId(transport_version_) &&
stream_id <= largest_peer_created_stream_id_) {
return true;
}
size_t additional_available_streams =
(stream_id - largest_peer_created_stream_id_) / 2 - 1;
if (largest_peer_created_stream_id_ ==
QuicUtils::GetInvalidStreamId(transport_version_)) {
additional_available_streams = (stream_id + 1) / 2 - 1;
}
size_t new_num_available_streams =
GetNumAvailableStreams() + additional_available_streams;
if (new_num_available_streams > MaxAvailableStreams()) {
QUIC_DLOG(INFO) << perspective_
<< "Failed to create a new incoming stream with id:"
<< stream_id << ". There are already "
<< GetNumAvailableStreams()
<< " streams available, which would become "
<< new_num_available_streams << ", which exceeds the limit "
<< MaxAvailableStreams() << ".";
return false;
}
QuicStreamId first_available_stream = largest_peer_created_stream_id_ + 2;
if (largest_peer_created_stream_id_ ==
QuicUtils::GetInvalidStreamId(transport_version_)) {
first_available_stream = QuicUtils::GetFirstBidirectionalStreamId(
transport_version_, QuicUtils::InvertPerspective(perspective_));
}
for (QuicStreamId id = first_available_stream; id < stream_id; id += 2) {
available_streams_.insert(id);
}
largest_peer_created_stream_id_ = stream_id;
return true;
}
QuicStreamId LegacyQuicStreamIdManager::GetNextOutgoingStreamId() {
QuicStreamId id = next_outgoing_stream_id_;
next_outgoing_stream_id_ += 2;
return id;
}
void LegacyQuicStreamIdManager::ActivateStream(bool is_incoming) {
if (is_incoming) {
++num_open_incoming_streams_;
return;
}
++num_open_outgoing_streams_;
}
void LegacyQuicStreamIdManager::OnStreamClosed(bool is_incoming) {
if (is_incoming) {
QUIC_BUG_IF(quic_bug_12720_1, num_open_incoming_streams_ == 0);
--num_open_incoming_streams_;
return;
}
QUIC_BUG_IF(quic_bug_12720_2, num_open_outgoing_streams_ == 0);
--num_open_outgoing_streams_;
}
bool LegacyQuicStreamIdManager::IsAvailableStream(QuicStreamId id) const {
if (!IsIncomingStream(id)) {
return id >= next_outgoing_stream_id_;
}
return largest_peer_created_stream_id_ ==
QuicUtils::GetInvalidStreamId(transport_version_) ||
id > largest_peer_created_stream_id_ ||
available_streams_.contains(id);
}
bool LegacyQuicStreamIdManager::IsIncomingStream(QuicStreamId id) const {
return id % 2 != next_outgoing_stream_id_ % 2;
}
size_t LegacyQuicStreamIdManager::GetNumAvailableStreams() const {
return available_streams_.size();
}
size_t LegacyQuicStreamIdManager::MaxAvailableStreams() const {
return max_open_incoming_streams_ * kMaxAvailableStreamsMultiplier;
}
} | #include "quiche/quic/core/legacy_quic_stream_id_manager.h"
#include <string>
#include <utility>
#include <vector>
#include "absl/strings/str_cat.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_test.h"
#include "quiche/quic/test_tools/quic_session_peer.h"
#include "quiche/quic/test_tools/quic_test_utils.h"
namespace quic {
namespace test {
namespace {
using testing::_;
using testing::StrictMock;
struct TestParams {
TestParams(ParsedQuicVersion version, Perspective perspective)
: version(version), perspective(perspective) {}
ParsedQuicVersion version;
Perspective perspective;
};
std::string PrintToString(const TestParams& p) {
return absl::StrCat(
ParsedQuicVersionToString(p.version),
(p.perspective == Perspective::IS_CLIENT ? "Client" : "Server"));
}
std::vector<TestParams> GetTestParams() {
std::vector<TestParams> params;
for (ParsedQuicVersion version : AllSupportedVersions()) {
for (auto perspective : {Perspective::IS_CLIENT, Perspective::IS_SERVER}) {
if (!VersionHasIetfQuicFrames(version.transport_version)) {
params.push_back(TestParams(version, perspective));
}
}
}
return params;
}
class LegacyQuicStreamIdManagerTest : public QuicTestWithParam<TestParams> {
public:
LegacyQuicStreamIdManagerTest()
: manager_(GetParam().perspective, GetParam().version.transport_version,
kDefaultMaxStreamsPerConnection,
kDefaultMaxStreamsPerConnection) {}
protected:
QuicStreamId GetNthPeerInitiatedId(int n) {
if (GetParam().perspective == Perspective::IS_SERVER) {
return QuicUtils::GetFirstBidirectionalStreamId(
GetParam().version.transport_version, Perspective::IS_CLIENT) +
2 * n;
} else {
return 2 + 2 * n;
}
}
LegacyQuicStreamIdManager manager_;
};
INSTANTIATE_TEST_SUITE_P(Tests, LegacyQuicStreamIdManagerTest,
::testing::ValuesIn(GetTestParams()),
::testing::PrintToStringParamName());
TEST_P(LegacyQuicStreamIdManagerTest, CanOpenNextOutgoingStream) {
for (size_t i = 0; i < manager_.max_open_outgoing_streams() - 1; ++i) {
manager_.ActivateStream(false);
}
EXPECT_TRUE(manager_.CanOpenNextOutgoingStream());
manager_.ActivateStream(false);
EXPECT_FALSE(manager_.CanOpenNextOutgoingStream());
}
TEST_P(LegacyQuicStreamIdManagerTest, CanOpenIncomingStream) {
for (size_t i = 0; i < manager_.max_open_incoming_streams() - 1; ++i) {
manager_.ActivateStream(true);
}
EXPECT_TRUE(manager_.CanOpenIncomingStream());
manager_.ActivateStream(true);
EXPECT_FALSE(manager_.CanOpenIncomingStream());
}
TEST_P(LegacyQuicStreamIdManagerTest, AvailableStreams) {
ASSERT_TRUE(
manager_.MaybeIncreaseLargestPeerStreamId(GetNthPeerInitiatedId(3)));
EXPECT_TRUE(manager_.IsAvailableStream(GetNthPeerInitiatedId(1)));
EXPECT_TRUE(manager_.IsAvailableStream(GetNthPeerInitiatedId(2)));
ASSERT_TRUE(
manager_.MaybeIncreaseLargestPeerStreamId(GetNthPeerInitiatedId(2)));
ASSERT_TRUE(
manager_.MaybeIncreaseLargestPeerStreamId(GetNthPeerInitiatedId(1)));
}
TEST_P(LegacyQuicStreamIdManagerTest, MaxAvailableStreams) {
const size_t kMaxStreamsForTest = 10;
const size_t kAvailableStreamLimit = manager_.MaxAvailableStreams();
EXPECT_EQ(
manager_.max_open_incoming_streams() * kMaxAvailableStreamsMultiplier,
manager_.MaxAvailableStreams());
EXPECT_LE(10 * kMaxStreamsForTest, kAvailableStreamLimit);
EXPECT_TRUE(
manager_.MaybeIncreaseLargestPeerStreamId(GetNthPeerInitiatedId(0)));
const int kLimitingStreamId =
GetNthPeerInitiatedId(kAvailableStreamLimit + 1);
EXPECT_TRUE(manager_.MaybeIncreaseLargestPeerStreamId(kLimitingStreamId));
EXPECT_FALSE(
manager_.MaybeIncreaseLargestPeerStreamId(kLimitingStreamId + 2 * 2));
}
TEST_P(LegacyQuicStreamIdManagerTest, MaximumAvailableOpenedStreams) {
QuicStreamId stream_id = GetNthPeerInitiatedId(0);
EXPECT_TRUE(manager_.MaybeIncreaseLargestPeerStreamId(stream_id));
EXPECT_TRUE(manager_.MaybeIncreaseLargestPeerStreamId(
stream_id + 2 * (manager_.max_open_incoming_streams() - 1)));
}
TEST_P(LegacyQuicStreamIdManagerTest, TooManyAvailableStreams) {
QuicStreamId stream_id = GetNthPeerInitiatedId(0);
EXPECT_TRUE(manager_.MaybeIncreaseLargestPeerStreamId(stream_id));
QuicStreamId stream_id2 =
GetNthPeerInitiatedId(2 * manager_.MaxAvailableStreams() + 4);
EXPECT_FALSE(manager_.MaybeIncreaseLargestPeerStreamId(stream_id2));
}
TEST_P(LegacyQuicStreamIdManagerTest, ManyAvailableStreams) {
manager_.set_max_open_incoming_streams(200);
QuicStreamId stream_id = GetNthPeerInitiatedId(0);
EXPECT_TRUE(manager_.MaybeIncreaseLargestPeerStreamId(stream_id));
EXPECT_TRUE(
manager_.MaybeIncreaseLargestPeerStreamId(GetNthPeerInitiatedId(199)));
}
TEST_P(LegacyQuicStreamIdManagerTest,
TestMaxIncomingAndOutgoingStreamsAllowed) {
EXPECT_EQ(manager_.max_open_incoming_streams(),
kDefaultMaxStreamsPerConnection);
EXPECT_EQ(manager_.max_open_outgoing_streams(),
kDefaultMaxStreamsPerConnection);
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/legacy_quic_stream_id_manager.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/legacy_quic_stream_id_manager_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
75df00ce-02fb-44c3-99d2-636453365693 | cpp | google/quiche | quic_connection_id_manager | quiche/quic/core/quic_connection_id_manager.cc | quiche/quic/core/quic_connection_id_manager_test.cc | #include "quiche/quic/core/quic_connection_id_manager.h"
#include <algorithm>
#include <cstdio>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "quiche/quic/core/quic_clock.h"
#include "quiche/quic/core/quic_connection_id.h"
#include "quiche/quic/core/quic_error_codes.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"
#include "quiche/common/platform/api/quiche_logging.h"
namespace quic {
QuicConnectionIdData::QuicConnectionIdData(
const QuicConnectionId& connection_id, uint64_t sequence_number,
const StatelessResetToken& stateless_reset_token)
: connection_id(connection_id),
sequence_number(sequence_number),
stateless_reset_token(stateless_reset_token) {}
namespace {
class RetirePeerIssuedConnectionIdAlarm
: public QuicAlarm::DelegateWithContext {
public:
explicit RetirePeerIssuedConnectionIdAlarm(
QuicConnectionIdManagerVisitorInterface* visitor,
QuicConnectionContext* context)
: QuicAlarm::DelegateWithContext(context), visitor_(visitor) {}
RetirePeerIssuedConnectionIdAlarm(const RetirePeerIssuedConnectionIdAlarm&) =
delete;
RetirePeerIssuedConnectionIdAlarm& operator=(
const RetirePeerIssuedConnectionIdAlarm&) = delete;
void OnAlarm() override { visitor_->OnPeerIssuedConnectionIdRetired(); }
private:
QuicConnectionIdManagerVisitorInterface* visitor_;
};
std::vector<QuicConnectionIdData>::const_iterator FindConnectionIdData(
const std::vector<QuicConnectionIdData>& cid_data_vector,
const QuicConnectionId& cid) {
return std::find_if(cid_data_vector.begin(), cid_data_vector.end(),
[&cid](const QuicConnectionIdData& cid_data) {
return cid == cid_data.connection_id;
});
}
std::vector<QuicConnectionIdData>::iterator FindConnectionIdData(
std::vector<QuicConnectionIdData>* cid_data_vector,
const QuicConnectionId& cid) {
return std::find_if(cid_data_vector->begin(), cid_data_vector->end(),
[&cid](const QuicConnectionIdData& cid_data) {
return cid == cid_data.connection_id;
});
}
}
QuicPeerIssuedConnectionIdManager::QuicPeerIssuedConnectionIdManager(
size_t active_connection_id_limit,
const QuicConnectionId& initial_peer_issued_connection_id,
const QuicClock* clock, QuicAlarmFactory* alarm_factory,
QuicConnectionIdManagerVisitorInterface* visitor,
QuicConnectionContext* context)
: active_connection_id_limit_(active_connection_id_limit),
clock_(clock),
retire_connection_id_alarm_(alarm_factory->CreateAlarm(
new RetirePeerIssuedConnectionIdAlarm(visitor, context))) {
QUICHE_DCHECK_GE(active_connection_id_limit_, 2u);
QUICHE_DCHECK(!initial_peer_issued_connection_id.IsEmpty());
active_connection_id_data_.emplace_back<const QuicConnectionId&, uint64_t,
const StatelessResetToken&>(
initial_peer_issued_connection_id,
0u, {});
recent_new_connection_id_sequence_numbers_.Add(0u, 1u);
}
QuicPeerIssuedConnectionIdManager::~QuicPeerIssuedConnectionIdManager() {
retire_connection_id_alarm_->Cancel();
}
bool QuicPeerIssuedConnectionIdManager::IsConnectionIdNew(
const QuicNewConnectionIdFrame& frame) {
auto is_old_connection_id = [&frame](const QuicConnectionIdData& cid_data) {
return cid_data.connection_id == frame.connection_id;
};
if (std::any_of(active_connection_id_data_.begin(),
active_connection_id_data_.end(), is_old_connection_id)) {
return false;
}
if (std::any_of(unused_connection_id_data_.begin(),
unused_connection_id_data_.end(), is_old_connection_id)) {
return false;
}
if (std::any_of(to_be_retired_connection_id_data_.begin(),
to_be_retired_connection_id_data_.end(),
is_old_connection_id)) {
return false;
}
return true;
}
void QuicPeerIssuedConnectionIdManager::PrepareToRetireConnectionIdPriorTo(
uint64_t retire_prior_to,
std::vector<QuicConnectionIdData>* cid_data_vector) {
auto it2 = cid_data_vector->begin();
for (auto it = cid_data_vector->begin(); it != cid_data_vector->end(); ++it) {
if (it->sequence_number >= retire_prior_to) {
*it2++ = *it;
} else {
to_be_retired_connection_id_data_.push_back(*it);
if (!retire_connection_id_alarm_->IsSet()) {
retire_connection_id_alarm_->Set(clock_->ApproximateNow());
}
}
}
cid_data_vector->erase(it2, cid_data_vector->end());
}
QuicErrorCode QuicPeerIssuedConnectionIdManager::OnNewConnectionIdFrame(
const QuicNewConnectionIdFrame& frame, std::string* error_detail,
bool* is_duplicate_frame) {
if (recent_new_connection_id_sequence_numbers_.Contains(
frame.sequence_number)) {
*is_duplicate_frame = true;
return QUIC_NO_ERROR;
}
if (!IsConnectionIdNew(frame)) {
*error_detail =
"Received a NEW_CONNECTION_ID frame that reuses a previously seen Id.";
return IETF_QUIC_PROTOCOL_VIOLATION;
}
recent_new_connection_id_sequence_numbers_.AddOptimizedForAppend(
frame.sequence_number, frame.sequence_number + 1);
if (recent_new_connection_id_sequence_numbers_.Size() >
kMaxNumConnectionIdSequenceNumberIntervals) {
*error_detail =
"Too many disjoint connection Id sequence number intervals.";
return IETF_QUIC_PROTOCOL_VIOLATION;
}
if (frame.sequence_number < max_new_connection_id_frame_retire_prior_to_) {
to_be_retired_connection_id_data_.emplace_back(frame.connection_id,
frame.sequence_number,
frame.stateless_reset_token);
if (!retire_connection_id_alarm_->IsSet()) {
retire_connection_id_alarm_->Set(clock_->ApproximateNow());
}
return QUIC_NO_ERROR;
}
if (frame.retire_prior_to > max_new_connection_id_frame_retire_prior_to_) {
max_new_connection_id_frame_retire_prior_to_ = frame.retire_prior_to;
PrepareToRetireConnectionIdPriorTo(frame.retire_prior_to,
&active_connection_id_data_);
PrepareToRetireConnectionIdPriorTo(frame.retire_prior_to,
&unused_connection_id_data_);
}
if (active_connection_id_data_.size() + unused_connection_id_data_.size() >=
active_connection_id_limit_) {
*error_detail = "Peer provides more connection IDs than the limit.";
return QUIC_CONNECTION_ID_LIMIT_ERROR;
}
unused_connection_id_data_.emplace_back(
frame.connection_id, frame.sequence_number, frame.stateless_reset_token);
return QUIC_NO_ERROR;
}
const QuicConnectionIdData*
QuicPeerIssuedConnectionIdManager::ConsumeOneUnusedConnectionId() {
if (unused_connection_id_data_.empty()) {
return nullptr;
}
active_connection_id_data_.push_back(unused_connection_id_data_.back());
unused_connection_id_data_.pop_back();
return &active_connection_id_data_.back();
}
void QuicPeerIssuedConnectionIdManager::PrepareToRetireActiveConnectionId(
const QuicConnectionId& cid) {
auto it = FindConnectionIdData(active_connection_id_data_, cid);
if (it == active_connection_id_data_.end()) {
return;
}
to_be_retired_connection_id_data_.push_back(*it);
active_connection_id_data_.erase(it);
if (!retire_connection_id_alarm_->IsSet()) {
retire_connection_id_alarm_->Set(clock_->ApproximateNow());
}
}
void QuicPeerIssuedConnectionIdManager::MaybeRetireUnusedConnectionIds(
const std::vector<QuicConnectionId>& active_connection_ids_on_path) {
std::vector<QuicConnectionId> cids_to_retire;
for (const auto& cid_data : active_connection_id_data_) {
if (std::find(active_connection_ids_on_path.begin(),
active_connection_ids_on_path.end(),
cid_data.connection_id) ==
active_connection_ids_on_path.end()) {
cids_to_retire.push_back(cid_data.connection_id);
}
}
for (const auto& cid : cids_to_retire) {
PrepareToRetireActiveConnectionId(cid);
}
}
bool QuicPeerIssuedConnectionIdManager::IsConnectionIdActive(
const QuicConnectionId& cid) const {
return FindConnectionIdData(active_connection_id_data_, cid) !=
active_connection_id_data_.end();
}
std::vector<uint64_t> QuicPeerIssuedConnectionIdManager::
ConsumeToBeRetiredConnectionIdSequenceNumbers() {
std::vector<uint64_t> result;
for (auto const& cid_data : to_be_retired_connection_id_data_) {
result.push_back(cid_data.sequence_number);
}
to_be_retired_connection_id_data_.clear();
return result;
}
void QuicPeerIssuedConnectionIdManager::ReplaceConnectionId(
const QuicConnectionId& old_connection_id,
const QuicConnectionId& new_connection_id) {
auto it1 =
FindConnectionIdData(&active_connection_id_data_, old_connection_id);
if (it1 != active_connection_id_data_.end()) {
it1->connection_id = new_connection_id;
return;
}
auto it2 = FindConnectionIdData(&to_be_retired_connection_id_data_,
old_connection_id);
if (it2 != to_be_retired_connection_id_data_.end()) {
it2->connection_id = new_connection_id;
}
}
namespace {
class RetireSelfIssuedConnectionIdAlarmDelegate
: public QuicAlarm::DelegateWithContext {
public:
explicit RetireSelfIssuedConnectionIdAlarmDelegate(
QuicSelfIssuedConnectionIdManager* connection_id_manager,
QuicConnectionContext* context)
: QuicAlarm::DelegateWithContext(context),
connection_id_manager_(connection_id_manager) {}
RetireSelfIssuedConnectionIdAlarmDelegate(
const RetireSelfIssuedConnectionIdAlarmDelegate&) = delete;
RetireSelfIssuedConnectionIdAlarmDelegate& operator=(
const RetireSelfIssuedConnectionIdAlarmDelegate&) = delete;
void OnAlarm() override { connection_id_manager_->RetireConnectionId(); }
private:
QuicSelfIssuedConnectionIdManager* connection_id_manager_;
};
}
QuicSelfIssuedConnectionIdManager::QuicSelfIssuedConnectionIdManager(
size_t active_connection_id_limit,
const QuicConnectionId& initial_connection_id, const QuicClock* clock,
QuicAlarmFactory* alarm_factory,
QuicConnectionIdManagerVisitorInterface* visitor,
QuicConnectionContext* context, ConnectionIdGeneratorInterface& generator)
: active_connection_id_limit_(active_connection_id_limit),
clock_(clock),
visitor_(visitor),
retire_connection_id_alarm_(alarm_factory->CreateAlarm(
new RetireSelfIssuedConnectionIdAlarmDelegate(this, context))),
last_connection_id_(initial_connection_id),
next_connection_id_sequence_number_(1u),
last_connection_id_consumed_by_self_sequence_number_(0u),
connection_id_generator_(generator) {
active_connection_ids_.emplace_back(initial_connection_id, 0u);
}
QuicSelfIssuedConnectionIdManager::~QuicSelfIssuedConnectionIdManager() {
retire_connection_id_alarm_->Cancel();
}
std::optional<QuicNewConnectionIdFrame>
QuicSelfIssuedConnectionIdManager::MaybeIssueNewConnectionId() {
std::optional<QuicConnectionId> new_cid =
connection_id_generator_.GenerateNextConnectionId(last_connection_id_);
if (!new_cid.has_value()) {
return {};
}
if (!visitor_->MaybeReserveConnectionId(*new_cid)) {
return {};
}
QuicNewConnectionIdFrame frame;
frame.connection_id = *new_cid;
frame.sequence_number = next_connection_id_sequence_number_++;
frame.stateless_reset_token =
QuicUtils::GenerateStatelessResetToken(frame.connection_id);
active_connection_ids_.emplace_back(frame.connection_id,
frame.sequence_number);
frame.retire_prior_to = active_connection_ids_.front().second;
last_connection_id_ = frame.connection_id;
return frame;
}
std::optional<QuicNewConnectionIdFrame> QuicSelfIssuedConnectionIdManager::
MaybeIssueNewConnectionIdForPreferredAddress() {
std::optional<QuicNewConnectionIdFrame> frame = MaybeIssueNewConnectionId();
QUICHE_DCHECK(!frame.has_value() || (frame->sequence_number == 1u));
return frame;
}
QuicErrorCode QuicSelfIssuedConnectionIdManager::OnRetireConnectionIdFrame(
const QuicRetireConnectionIdFrame& frame, QuicTime::Delta pto_delay,
std::string* error_detail) {
QUICHE_DCHECK(!active_connection_ids_.empty());
if (frame.sequence_number >= next_connection_id_sequence_number_) {
*error_detail = "To be retired connecton ID is never issued.";
return IETF_QUIC_PROTOCOL_VIOLATION;
}
auto it =
std::find_if(active_connection_ids_.begin(), active_connection_ids_.end(),
[&frame](const std::pair<QuicConnectionId, uint64_t>& p) {
return p.second == frame.sequence_number;
});
if (it == active_connection_ids_.end()) {
return QUIC_NO_ERROR;
}
if (to_be_retired_connection_ids_.size() + active_connection_ids_.size() >=
kMaxNumConnectonIdsInUse) {
*error_detail = "There are too many connection IDs in use.";
return QUIC_TOO_MANY_CONNECTION_ID_WAITING_TO_RETIRE;
}
QuicTime retirement_time = clock_->ApproximateNow() + 3 * pto_delay;
if (!to_be_retired_connection_ids_.empty()) {
retirement_time =
std::max(retirement_time, to_be_retired_connection_ids_.back().second);
}
to_be_retired_connection_ids_.emplace_back(it->first, retirement_time);
if (!retire_connection_id_alarm_->IsSet()) {
retire_connection_id_alarm_->Set(retirement_time);
}
active_connection_ids_.erase(it);
MaybeSendNewConnectionIds();
return QUIC_NO_ERROR;
}
std::vector<QuicConnectionId>
QuicSelfIssuedConnectionIdManager::GetUnretiredConnectionIds() const {
std::vector<QuicConnectionId> unretired_ids;
for (const auto& cid_pair : to_be_retired_connection_ids_) {
unretired_ids.push_back(cid_pair.first);
}
for (const auto& cid_pair : active_connection_ids_) {
unretired_ids.push_back(cid_pair.first);
}
return unretired_ids;
}
QuicConnectionId QuicSelfIssuedConnectionIdManager::GetOneActiveConnectionId()
const {
QUICHE_DCHECK(!active_connection_ids_.empty());
return active_connection_ids_.front().first;
}
void QuicSelfIssuedConnectionIdManager::RetireConnectionId() {
if (to_be_retired_connection_ids_.empty()) {
QUIC_BUG(quic_bug_12420_1)
<< "retire_connection_id_alarm fired but there is no connection ID "
"to be retired.";
return;
}
QuicTime now = clock_->ApproximateNow();
auto it = to_be_retired_connection_ids_.begin();
do {
visitor_->OnSelfIssuedConnectionIdRetired(it->first);
++it;
} while (it != to_be_retired_connection_ids_.end() && it->second <= now);
to_be_retired_connection_ids_.erase(to_be_retired_connection_ids_.begin(),
it);
if (!to_be_retired_connection_ids_.empty()) {
retire_connection_id_alarm_->Set(
to_be_retired_connection_ids_.front().second);
}
}
void QuicSelfIssuedConnectionIdManager::MaybeSendNewConnectionIds() {
while (active_connection_ids_.size() < active_connection_id_limit_) {
std::optional<QuicNewConnectionIdFrame> frame = MaybeIssueNewConnectionId();
if (!frame.has_value()) {
break;
}
if (!visitor_->SendNewConnectionId(*frame)) {
break;
}
}
}
bool QuicSelfIssuedConnectionIdManager::HasConnectionIdToConsume() const {
for (const auto& active_cid_data : active_connection_ids_) {
if (active_cid_data.second >
last_connection_id_consumed_by_self_sequence_number_) {
return true;
}
}
return false;
}
std::optional<QuicConnectionId>
QuicSelfIssuedConnectionIdManager::ConsumeOneConnectionId() {
for (const auto& active_cid_data : active_connection_ids_) {
if (active_cid_data.second >
last_connection_id_consumed_by_self_sequence_number_) {
last_connection_id_consumed_by_self_sequence_number_ =
active_cid_data.second;
return active_cid_data.first;
}
}
return std::nullopt;
}
bool QuicSelfIssuedConnectionIdManager::IsConnectionIdInUse(
const QuicConnectionId& cid) const {
for (const auto& active_cid_data : active_connection_ids_) {
if (active_cid_data.first == cid) {
return true;
}
}
for (const auto& to_be_retired_cid_data : to_be_retired_connection_ids_) {
if (to_be_retired_cid_data.first == cid) {
return true;
}
}
return false;
}
} | #include "quiche/quic/core/quic_connection_id_manager.h"
#include <cstddef>
#include <optional>
#include <string>
#include <vector>
#include "quiche/quic/core/frames/quic_retire_connection_id_frame.h"
#include "quiche/quic/core/quic_connection_id.h"
#include "quiche/quic/core/quic_error_codes.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"
#include "quiche/quic/test_tools/mock_connection_id_generator.h"
#include "quiche/quic/test_tools/quic_connection_id_manager_peer.h"
#include "quiche/quic/test_tools/quic_test_utils.h"
namespace quic::test {
namespace {
using ::quic::test::IsError;
using ::quic::test::IsQuicNoError;
using ::quic::test::QuicConnectionIdManagerPeer;
using ::quic::test::TestConnectionId;
using ::testing::_;
using ::testing::ElementsAre;
using ::testing::IsNull;
using ::testing::Return;
using ::testing::StrictMock;
class TestPeerIssuedConnectionIdManagerVisitor
: public QuicConnectionIdManagerVisitorInterface {
public:
void SetPeerIssuedConnectionIdManager(
QuicPeerIssuedConnectionIdManager* peer_issued_connection_id_manager) {
peer_issued_connection_id_manager_ = peer_issued_connection_id_manager;
}
void OnPeerIssuedConnectionIdRetired() override {
if (!peer_issued_connection_id_manager_->IsConnectionIdActive(
current_peer_issued_connection_id_)) {
current_peer_issued_connection_id_ =
peer_issued_connection_id_manager_->ConsumeOneUnusedConnectionId()
->connection_id;
}
most_recent_retired_connection_id_sequence_numbers_ =
peer_issued_connection_id_manager_
->ConsumeToBeRetiredConnectionIdSequenceNumbers();
}
const std::vector<uint64_t>&
most_recent_retired_connection_id_sequence_numbers() {
return most_recent_retired_connection_id_sequence_numbers_;
}
void SetCurrentPeerConnectionId(QuicConnectionId cid) {
current_peer_issued_connection_id_ = cid;
}
const QuicConnectionId& GetCurrentPeerConnectionId() {
return current_peer_issued_connection_id_;
}
bool SendNewConnectionId(const QuicNewConnectionIdFrame& ) override {
return false;
}
bool MaybeReserveConnectionId(const QuicConnectionId&) override {
return false;
}
void OnSelfIssuedConnectionIdRetired(
const QuicConnectionId& ) override {}
private:
QuicPeerIssuedConnectionIdManager* peer_issued_connection_id_manager_ =
nullptr;
QuicConnectionId current_peer_issued_connection_id_;
std::vector<uint64_t> most_recent_retired_connection_id_sequence_numbers_;
};
class QuicPeerIssuedConnectionIdManagerTest : public QuicTest {
public:
QuicPeerIssuedConnectionIdManagerTest()
: peer_issued_cid_manager_(
2, initial_connection_id_, &clock_,
&alarm_factory_, &cid_manager_visitor_, nullptr) {
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
cid_manager_visitor_.SetPeerIssuedConnectionIdManager(
&peer_issued_cid_manager_);
cid_manager_visitor_.SetCurrentPeerConnectionId(initial_connection_id_);
retire_peer_issued_cid_alarm_ =
QuicConnectionIdManagerPeer::GetRetirePeerIssuedConnectionIdAlarm(
&peer_issued_cid_manager_);
}
protected:
MockClock clock_;
test::MockAlarmFactory alarm_factory_;
TestPeerIssuedConnectionIdManagerVisitor cid_manager_visitor_;
QuicConnectionId initial_connection_id_ = TestConnectionId(0);
QuicPeerIssuedConnectionIdManager peer_issued_cid_manager_;
QuicAlarm* retire_peer_issued_cid_alarm_ = nullptr;
std::string error_details_;
bool duplicate_frame_ = false;
};
TEST_F(QuicPeerIssuedConnectionIdManagerTest,
ConnectionIdSequenceWhenMigrationSucceed) {
{
QuicNewConnectionIdFrame frame;
frame.connection_id = TestConnectionId(1);
frame.sequence_number = 1u;
frame.retire_prior_to = 0u;
frame.stateless_reset_token =
QuicUtils::GenerateStatelessResetToken(frame.connection_id);
ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame(
frame, &error_details_, &duplicate_frame_),
IsQuicNoError());
const QuicConnectionIdData* aternative_connection_id_data =
peer_issued_cid_manager_.ConsumeOneUnusedConnectionId();
ASSERT_THAT(aternative_connection_id_data, testing::NotNull());
EXPECT_EQ(aternative_connection_id_data->connection_id,
TestConnectionId(1));
EXPECT_EQ(aternative_connection_id_data->stateless_reset_token,
frame.stateless_reset_token);
peer_issued_cid_manager_.MaybeRetireUnusedConnectionIds(
{TestConnectionId(1)});
cid_manager_visitor_.SetCurrentPeerConnectionId(TestConnectionId(1));
ASSERT_TRUE(retire_peer_issued_cid_alarm_->IsSet());
alarm_factory_.FireAlarm(retire_peer_issued_cid_alarm_);
EXPECT_THAT(cid_manager_visitor_
.most_recent_retired_connection_id_sequence_numbers(),
ElementsAre(0u));
}
{
QuicNewConnectionIdFrame frame;
frame.connection_id = TestConnectionId(2);
frame.sequence_number = 2u;
frame.retire_prior_to = 1u;
frame.stateless_reset_token =
QuicUtils::GenerateStatelessResetToken(frame.connection_id);
ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame(
frame, &error_details_, &duplicate_frame_),
IsQuicNoError());
peer_issued_cid_manager_.ConsumeOneUnusedConnectionId();
peer_issued_cid_manager_.MaybeRetireUnusedConnectionIds(
{TestConnectionId(2)});
cid_manager_visitor_.SetCurrentPeerConnectionId(TestConnectionId(2));
ASSERT_TRUE(retire_peer_issued_cid_alarm_->IsSet());
alarm_factory_.FireAlarm(retire_peer_issued_cid_alarm_);
EXPECT_THAT(cid_manager_visitor_
.most_recent_retired_connection_id_sequence_numbers(),
ElementsAre(1u));
}
{
QuicNewConnectionIdFrame frame;
frame.connection_id = TestConnectionId(3);
frame.sequence_number = 3u;
frame.retire_prior_to = 2u;
frame.stateless_reset_token =
QuicUtils::GenerateStatelessResetToken(frame.connection_id);
ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame(
frame, &error_details_, &duplicate_frame_),
IsQuicNoError());
peer_issued_cid_manager_.ConsumeOneUnusedConnectionId();
peer_issued_cid_manager_.MaybeRetireUnusedConnectionIds(
{TestConnectionId(3)});
cid_manager_visitor_.SetCurrentPeerConnectionId(TestConnectionId(3));
ASSERT_TRUE(retire_peer_issued_cid_alarm_->IsSet());
alarm_factory_.FireAlarm(retire_peer_issued_cid_alarm_);
EXPECT_THAT(cid_manager_visitor_
.most_recent_retired_connection_id_sequence_numbers(),
ElementsAre(2u));
}
{
QuicNewConnectionIdFrame frame;
frame.connection_id = TestConnectionId(4);
frame.sequence_number = 4u;
frame.retire_prior_to = 3u;
frame.stateless_reset_token =
QuicUtils::GenerateStatelessResetToken(frame.connection_id);
ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame(
frame, &error_details_, &duplicate_frame_),
IsQuicNoError());
}
}
TEST_F(QuicPeerIssuedConnectionIdManagerTest,
ConnectionIdSequenceWhenMigrationFail) {
{
QuicNewConnectionIdFrame frame;
frame.connection_id = TestConnectionId(1);
frame.sequence_number = 1u;
frame.retire_prior_to = 0u;
frame.stateless_reset_token =
QuicUtils::GenerateStatelessResetToken(frame.connection_id);
ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame(
frame, &error_details_, &duplicate_frame_),
IsQuicNoError());
peer_issued_cid_manager_.ConsumeOneUnusedConnectionId();
peer_issued_cid_manager_.MaybeRetireUnusedConnectionIds(
{initial_connection_id_});
ASSERT_TRUE(retire_peer_issued_cid_alarm_->IsSet());
alarm_factory_.FireAlarm(retire_peer_issued_cid_alarm_);
EXPECT_THAT(cid_manager_visitor_
.most_recent_retired_connection_id_sequence_numbers(),
ElementsAre(1u));
}
{
QuicNewConnectionIdFrame frame;
frame.connection_id = TestConnectionId(2);
frame.sequence_number = 2u;
frame.retire_prior_to = 0u;
frame.stateless_reset_token =
QuicUtils::GenerateStatelessResetToken(frame.connection_id);
ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame(
frame, &error_details_, &duplicate_frame_),
IsQuicNoError());
peer_issued_cid_manager_.ConsumeOneUnusedConnectionId();
peer_issued_cid_manager_.MaybeRetireUnusedConnectionIds(
{initial_connection_id_});
ASSERT_TRUE(retire_peer_issued_cid_alarm_->IsSet());
alarm_factory_.FireAlarm(retire_peer_issued_cid_alarm_);
EXPECT_THAT(cid_manager_visitor_
.most_recent_retired_connection_id_sequence_numbers(),
ElementsAre(2u));
}
{
QuicNewConnectionIdFrame frame;
frame.connection_id = TestConnectionId(3);
frame.sequence_number = 3u;
frame.retire_prior_to = 0u;
frame.stateless_reset_token =
QuicUtils::GenerateStatelessResetToken(frame.connection_id);
ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame(
frame, &error_details_, &duplicate_frame_),
IsQuicNoError());
peer_issued_cid_manager_.ConsumeOneUnusedConnectionId();
peer_issued_cid_manager_.MaybeRetireUnusedConnectionIds(
{TestConnectionId(3)});
cid_manager_visitor_.SetCurrentPeerConnectionId(TestConnectionId(3));
ASSERT_TRUE(retire_peer_issued_cid_alarm_->IsSet());
alarm_factory_.FireAlarm(retire_peer_issued_cid_alarm_);
EXPECT_THAT(cid_manager_visitor_
.most_recent_retired_connection_id_sequence_numbers(),
ElementsAre(0u));
}
{
QuicNewConnectionIdFrame frame;
frame.connection_id = TestConnectionId(4);
frame.sequence_number = 4u;
frame.retire_prior_to = 3u;
frame.stateless_reset_token =
QuicUtils::GenerateStatelessResetToken(frame.connection_id);
EXPECT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame(
frame, &error_details_, &duplicate_frame_),
IsQuicNoError());
EXPECT_FALSE(retire_peer_issued_cid_alarm_->IsSet());
}
}
TEST_F(QuicPeerIssuedConnectionIdManagerTest,
ReceivesNewConnectionIdOutOfOrder) {
{
QuicNewConnectionIdFrame frame;
frame.connection_id = TestConnectionId(1);
frame.sequence_number = 1u;
frame.retire_prior_to = 0u;
frame.stateless_reset_token =
QuicUtils::GenerateStatelessResetToken(frame.connection_id);
ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame(
frame, &error_details_, &duplicate_frame_),
IsQuicNoError());
peer_issued_cid_manager_.ConsumeOneUnusedConnectionId();
}
{
QuicNewConnectionIdFrame frame;
frame.connection_id = TestConnectionId(3);
frame.sequence_number = 3u;
frame.retire_prior_to = 2u;
frame.stateless_reset_token =
QuicUtils::GenerateStatelessResetToken(frame.connection_id);
ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame(
frame, &error_details_, &duplicate_frame_),
IsQuicNoError());
}
{
QuicNewConnectionIdFrame frame;
frame.connection_id = TestConnectionId(2);
frame.sequence_number = 2u;
frame.retire_prior_to = 1u;
frame.stateless_reset_token =
QuicUtils::GenerateStatelessResetToken(frame.connection_id);
ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame(
frame, &error_details_, &duplicate_frame_),
IsQuicNoError());
}
{
EXPECT_FALSE(
peer_issued_cid_manager_.IsConnectionIdActive(TestConnectionId(0)));
EXPECT_FALSE(
peer_issued_cid_manager_.IsConnectionIdActive(TestConnectionId(1)));
ASSERT_TRUE(retire_peer_issued_cid_alarm_->IsSet());
alarm_factory_.FireAlarm(retire_peer_issued_cid_alarm_);
EXPECT_THAT(cid_manager_visitor_
.most_recent_retired_connection_id_sequence_numbers(),
ElementsAre(0u, 1u));
EXPECT_EQ(cid_manager_visitor_.GetCurrentPeerConnectionId(),
TestConnectionId(2));
EXPECT_EQ(
peer_issued_cid_manager_.ConsumeOneUnusedConnectionId()->connection_id,
TestConnectionId(3));
}
}
TEST_F(QuicPeerIssuedConnectionIdManagerTest,
VisitedNewConnectionIdFrameIsIgnored) {
QuicNewConnectionIdFrame frame;
frame.connection_id = TestConnectionId(1);
frame.sequence_number = 1u;
frame.retire_prior_to = 0u;
frame.stateless_reset_token =
QuicUtils::GenerateStatelessResetToken(frame.connection_id);
ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame(
frame, &error_details_, &duplicate_frame_),
IsQuicNoError());
peer_issued_cid_manager_.ConsumeOneUnusedConnectionId();
peer_issued_cid_manager_.MaybeRetireUnusedConnectionIds(
{initial_connection_id_});
ASSERT_TRUE(retire_peer_issued_cid_alarm_->IsSet());
alarm_factory_.FireAlarm(retire_peer_issued_cid_alarm_);
EXPECT_THAT(
cid_manager_visitor_.most_recent_retired_connection_id_sequence_numbers(),
ElementsAre(1u));
ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame(
frame, &error_details_, &duplicate_frame_),
IsQuicNoError());
EXPECT_EQ(true, duplicate_frame_);
EXPECT_THAT(peer_issued_cid_manager_.ConsumeOneUnusedConnectionId(),
testing::IsNull());
}
TEST_F(QuicPeerIssuedConnectionIdManagerTest,
ErrorWhenActiveConnectionIdLimitExceeded) {
{
QuicNewConnectionIdFrame frame;
frame.connection_id = TestConnectionId(1);
frame.sequence_number = 1u;
frame.retire_prior_to = 0u;
frame.stateless_reset_token =
QuicUtils::GenerateStatelessResetToken(frame.connection_id);
ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame(
frame, &error_details_, &duplicate_frame_),
IsQuicNoError());
}
{
QuicNewConnectionIdFrame frame;
frame.connection_id = TestConnectionId(2);
frame.sequence_number = 2u;
frame.retire_prior_to = 0u;
frame.stateless_reset_token =
QuicUtils::GenerateStatelessResetToken(frame.connection_id);
ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame(
frame, &error_details_, &duplicate_frame_),
IsError(QUIC_CONNECTION_ID_LIMIT_ERROR));
}
}
TEST_F(QuicPeerIssuedConnectionIdManagerTest,
ErrorWhenTheSameConnectionIdIsSeenWithDifferentSequenceNumbers) {
{
QuicNewConnectionIdFrame frame;
frame.connection_id = TestConnectionId(1);
frame.sequence_number = 1u;
frame.retire_prior_to = 0u;
frame.stateless_reset_token =
QuicUtils::GenerateStatelessResetToken(frame.connection_id);
ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame(
frame, &error_details_, &duplicate_frame_),
IsQuicNoError());
}
{
QuicNewConnectionIdFrame frame;
frame.connection_id = TestConnectionId(1);
frame.sequence_number = 2u;
frame.retire_prior_to = 1u;
frame.stateless_reset_token =
QuicUtils::GenerateStatelessResetToken(TestConnectionId(2));
ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame(
frame, &error_details_, &duplicate_frame_),
IsError(IETF_QUIC_PROTOCOL_VIOLATION));
}
}
TEST_F(QuicPeerIssuedConnectionIdManagerTest,
NewConnectionIdFrameWithTheSameSequenceNumberIsIgnored) {
{
QuicNewConnectionIdFrame frame;
frame.connection_id = TestConnectionId(1);
frame.sequence_number = 1u;
frame.retire_prior_to = 0u;
frame.stateless_reset_token =
QuicUtils::GenerateStatelessResetToken(frame.connection_id);
ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame(
frame, &error_details_, &duplicate_frame_),
IsQuicNoError());
}
{
QuicNewConnectionIdFrame frame;
frame.connection_id = TestConnectionId(2);
frame.sequence_number = 1u;
frame.retire_prior_to = 0u;
frame.stateless_reset_token =
QuicUtils::GenerateStatelessResetToken(TestConnectionId(2));
EXPECT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame(
frame, &error_details_, &duplicate_frame_),
IsQuicNoError());
EXPECT_EQ(true, duplicate_frame_);
EXPECT_EQ(
peer_issued_cid_manager_.ConsumeOneUnusedConnectionId()->connection_id,
TestConnectionId(1));
EXPECT_THAT(peer_issued_cid_manager_.ConsumeOneUnusedConnectionId(),
IsNull());
}
}
TEST_F(QuicPeerIssuedConnectionIdManagerTest,
ErrorWhenThereAreTooManyGapsInIssuedConnectionIdSequenceNumbers) {
for (int i = 2; i <= 38; i += 2) {
QuicNewConnectionIdFrame frame;
frame.connection_id = TestConnectionId(i);
frame.sequence_number = i;
frame.retire_prior_to = i;
frame.stateless_reset_token =
QuicUtils::GenerateStatelessResetToken(frame.connection_id);
ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame(
frame, &error_details_, &duplicate_frame_),
IsQuicNoError());
}
QuicNewConnectionIdFrame frame;
frame.connection_id = TestConnectionId(40);
frame.sequence_number = 40u;
frame.retire_prior_to = 40u;
frame.stateless_reset_token =
QuicUtils::GenerateStatelessResetToken(frame.connection_id);
ASSERT_THAT(peer_issued_cid_manager_.OnNewConnectionIdFrame(
frame, &error_details_, &duplicate_frame_),
IsError(IETF_QUIC_PROTOCOL_VIOLATION));
}
TEST_F(QuicPeerIssuedConnectionIdManagerTest, ReplaceConnectionId) {
ASSERT_TRUE(
peer_issued_cid_manager_.IsConnectionIdActive(initial_connection_id_));
peer_issued_cid_manager_.ReplaceConnectionId(initial_connection_id_,
TestConnectionId(1));
EXPECT_FALSE(
peer_issued_cid_manager_.IsConnectionIdActive(initial_connection_id_));
EXPECT_TRUE(
peer_issued_cid_manager_.IsConnectionIdActive(TestConnectionId(1)));
}
class TestSelfIssuedConnectionIdManagerVisitor
: public QuicConnectionIdManagerVisitorInterface {
public:
void OnPeerIssuedConnectionIdRetired() override {}
MOCK_METHOD(bool, SendNewConnectionId,
(const QuicNewConnectionIdFrame& frame), (override));
MOCK_METHOD(bool, MaybeReserveConnectionId,
(const QuicConnectionId& connection_id), (override));
MOCK_METHOD(void, OnSelfIssuedConnectionIdRetired,
(const QuicConnectionId& connection_id), (override));
};
class QuicSelfIssuedConnectionIdManagerTest : public QuicTest {
public:
QuicSelfIssuedConnectionIdManagerTest()
: cid_manager_( 2, initial_connection_id_,
&clock_, &alarm_factory_, &cid_manager_visitor_,
nullptr, connection_id_generator_) {
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
retire_self_issued_cid_alarm_ =
QuicConnectionIdManagerPeer::GetRetireSelfIssuedConnectionIdAlarm(
&cid_manager_);
}
protected:
QuicConnectionId CheckGenerate(QuicConnectionId old_cid) {
QuicConnectionId new_cid = old_cid;
(*new_cid.mutable_data())++;
EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(old_cid))
.WillOnce(Return(new_cid));
return new_cid;
}
MockClock clock_;
test::MockAlarmFactory alarm_factory_;
TestSelfIssuedConnectionIdManagerVisitor cid_manager_visitor_;
QuicConnectionId initial_connection_id_ = TestConnectionId(0);
StrictMock<QuicSelfIssuedConnectionIdManager> cid_manager_;
QuicAlarm* retire_self_issued_cid_alarm_ = nullptr;
std::string error_details_;
QuicTime::Delta pto_delay_ = QuicTime::Delta::FromMilliseconds(10);
MockConnectionIdGenerator connection_id_generator_;
};
MATCHER_P3(ExpectedNewConnectionIdFrame, connection_id, sequence_number,
retire_prior_to, "") {
return (arg.connection_id == connection_id) &&
(arg.sequence_number == sequence_number) &&
(arg.retire_prior_to == retire_prior_to);
}
TEST_F(QuicSelfIssuedConnectionIdManagerTest,
RetireSelfIssuedConnectionIdInOrder) {
QuicConnectionId cid0 = initial_connection_id_;
QuicConnectionId cid1 = CheckGenerate(cid0);
QuicConnectionId cid2 = CheckGenerate(cid1);
QuicConnectionId cid3 = CheckGenerate(cid2);
QuicConnectionId cid4 = CheckGenerate(cid3);
QuicConnectionId cid5 = CheckGenerate(cid4);
EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(cid1))
.WillOnce(Return(true));
EXPECT_CALL(cid_manager_visitor_,
SendNewConnectionId(ExpectedNewConnectionIdFrame(cid1, 1u, 0u)))
.WillOnce(Return(true));
cid_manager_.MaybeSendNewConnectionIds();
{
EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(cid2))
.WillOnce(Return(true));
EXPECT_CALL(cid_manager_visitor_,
SendNewConnectionId(ExpectedNewConnectionIdFrame(cid2, 2u, 1u)))
.WillOnce(Return(true));
QuicRetireConnectionIdFrame retire_cid_frame;
retire_cid_frame.sequence_number = 0u;
ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame(
retire_cid_frame, pto_delay_, &error_details_),
IsQuicNoError());
}
{
EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(cid3))
.WillOnce(Return(true));
EXPECT_CALL(cid_manager_visitor_,
SendNewConnectionId(ExpectedNewConnectionIdFrame(cid3, 3u, 2u)))
.WillOnce(Return(true));
QuicRetireConnectionIdFrame retire_cid_frame;
retire_cid_frame.sequence_number = 1u;
ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame(
retire_cid_frame, pto_delay_, &error_details_),
IsQuicNoError());
}
{
EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(cid4))
.WillOnce(Return(true));
EXPECT_CALL(cid_manager_visitor_,
SendNewConnectionId(ExpectedNewConnectionIdFrame(cid4, 4u, 3u)))
.WillOnce(Return(true));
QuicRetireConnectionIdFrame retire_cid_frame;
retire_cid_frame.sequence_number = 2u;
ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame(
retire_cid_frame, pto_delay_, &error_details_),
IsQuicNoError());
}
{
EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(cid5))
.WillOnce(Return(true));
EXPECT_CALL(cid_manager_visitor_,
SendNewConnectionId(ExpectedNewConnectionIdFrame(cid5, 5u, 4u)))
.WillOnce(Return(true));
QuicRetireConnectionIdFrame retire_cid_frame;
retire_cid_frame.sequence_number = 3u;
ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame(
retire_cid_frame, pto_delay_, &error_details_),
IsQuicNoError());
}
}
TEST_F(QuicSelfIssuedConnectionIdManagerTest,
RetireSelfIssuedConnectionIdOutOfOrder) {
QuicConnectionId cid0 = initial_connection_id_;
QuicConnectionId cid1 = CheckGenerate(cid0);
QuicConnectionId cid2 = CheckGenerate(cid1);
QuicConnectionId cid3 = CheckGenerate(cid2);
QuicConnectionId cid4 = CheckGenerate(cid3);
EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(cid1))
.WillOnce(Return(true));
EXPECT_CALL(cid_manager_visitor_,
SendNewConnectionId(ExpectedNewConnectionIdFrame(cid1, 1u, 0u)))
.WillOnce(Return(true));
cid_manager_.MaybeSendNewConnectionIds();
{
EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(cid2))
.WillOnce(Return(true));
EXPECT_CALL(cid_manager_visitor_,
SendNewConnectionId(ExpectedNewConnectionIdFrame(cid2, 2u, 0u)))
.WillOnce(Return(true));
QuicRetireConnectionIdFrame retire_cid_frame;
retire_cid_frame.sequence_number = 1u;
ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame(
retire_cid_frame, pto_delay_, &error_details_),
IsQuicNoError());
}
{
QuicRetireConnectionIdFrame retire_cid_frame;
retire_cid_frame.sequence_number = 1u;
ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame(
retire_cid_frame, pto_delay_, &error_details_),
IsQuicNoError());
}
{
EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(cid3))
.WillOnce(Return(true));
EXPECT_CALL(cid_manager_visitor_,
SendNewConnectionId(ExpectedNewConnectionIdFrame(cid3, 3u, 2u)))
.WillOnce(Return(true));
QuicRetireConnectionIdFrame retire_cid_frame;
retire_cid_frame.sequence_number = 0u;
ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame(
retire_cid_frame, pto_delay_, &error_details_),
IsQuicNoError());
}
{
EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(cid4))
.WillOnce(Return(true));
EXPECT_CALL(cid_manager_visitor_,
SendNewConnectionId(ExpectedNewConnectionIdFrame(cid4, 4u, 2u)))
.WillOnce(Return(true));
QuicRetireConnectionIdFrame retire_cid_frame;
retire_cid_frame.sequence_number = 3u;
ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame(
retire_cid_frame, pto_delay_, &error_details_),
IsQuicNoError());
}
{
QuicRetireConnectionIdFrame retire_cid_frame;
retire_cid_frame.sequence_number = 0u;
ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame(
retire_cid_frame, pto_delay_, &error_details_),
IsQuicNoError());
}
}
TEST_F(QuicSelfIssuedConnectionIdManagerTest,
ScheduleConnectionIdRetirementOneAtATime) {
QuicConnectionId cid0 = initial_connection_id_;
QuicConnectionId cid1 = CheckGenerate(cid0);
QuicConnectionId cid2 = CheckGenerate(cid1);
QuicConnectionId cid3 = CheckGenerate(cid2);
EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(_))
.Times(3)
.WillRepeatedly(Return(true));
EXPECT_CALL(cid_manager_visitor_, SendNewConnectionId(_))
.Times(3)
.WillRepeatedly(Return(true));
QuicTime::Delta connection_id_expire_timeout = 3 * pto_delay_;
QuicRetireConnectionIdFrame retire_cid_frame;
cid_manager_.MaybeSendNewConnectionIds();
retire_cid_frame.sequence_number = 0u;
ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame(
retire_cid_frame, pto_delay_, &error_details_),
IsQuicNoError());
EXPECT_THAT(cid_manager_.GetUnretiredConnectionIds(),
ElementsAre(cid0, cid1, cid2));
EXPECT_TRUE(retire_self_issued_cid_alarm_->IsSet());
EXPECT_EQ(retire_self_issued_cid_alarm_->deadline(),
clock_.ApproximateNow() + connection_id_expire_timeout);
EXPECT_CALL(cid_manager_visitor_, OnSelfIssuedConnectionIdRetired(cid0));
clock_.AdvanceTime(connection_id_expire_timeout);
alarm_factory_.FireAlarm(retire_self_issued_cid_alarm_);
EXPECT_THAT(cid_manager_.GetUnretiredConnectionIds(),
ElementsAre(cid1, cid2));
EXPECT_FALSE(retire_self_issued_cid_alarm_->IsSet());
retire_cid_frame.sequence_number = 1u;
ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame(
retire_cid_frame, pto_delay_, &error_details_),
IsQuicNoError());
EXPECT_THAT(cid_manager_.GetUnretiredConnectionIds(),
ElementsAre(cid1, cid2, cid3));
EXPECT_TRUE(retire_self_issued_cid_alarm_->IsSet());
EXPECT_EQ(retire_self_issued_cid_alarm_->deadline(),
clock_.ApproximateNow() + connection_id_expire_timeout);
EXPECT_CALL(cid_manager_visitor_, OnSelfIssuedConnectionIdRetired(cid1));
clock_.AdvanceTime(connection_id_expire_timeout);
alarm_factory_.FireAlarm(retire_self_issued_cid_alarm_);
EXPECT_THAT(cid_manager_.GetUnretiredConnectionIds(),
ElementsAre(cid2, cid3));
EXPECT_FALSE(retire_self_issued_cid_alarm_->IsSet());
}
TEST_F(QuicSelfIssuedConnectionIdManagerTest,
ScheduleMultipleConnectionIdRetirement) {
QuicConnectionId cid0 = initial_connection_id_;
QuicConnectionId cid1 = CheckGenerate(cid0);
QuicConnectionId cid2 = CheckGenerate(cid1);
QuicConnectionId cid3 = CheckGenerate(cid2);
EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(_))
.Times(3)
.WillRepeatedly(Return(true));
EXPECT_CALL(cid_manager_visitor_, SendNewConnectionId(_))
.Times(3)
.WillRepeatedly(Return(true));
QuicTime::Delta connection_id_expire_timeout = 3 * pto_delay_;
QuicRetireConnectionIdFrame retire_cid_frame;
cid_manager_.MaybeSendNewConnectionIds();
retire_cid_frame.sequence_number = 0u;
ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame(
retire_cid_frame, pto_delay_, &error_details_),
IsQuicNoError());
clock_.AdvanceTime(connection_id_expire_timeout * 0.25);
retire_cid_frame.sequence_number = 1u;
ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame(
retire_cid_frame, pto_delay_, &error_details_),
IsQuicNoError());
EXPECT_THAT(cid_manager_.GetUnretiredConnectionIds(),
ElementsAre(cid0, cid1, cid2, cid3));
EXPECT_TRUE(retire_self_issued_cid_alarm_->IsSet());
EXPECT_EQ(retire_self_issued_cid_alarm_->deadline(),
clock_.ApproximateNow() + connection_id_expire_timeout * 0.75);
EXPECT_CALL(cid_manager_visitor_, OnSelfIssuedConnectionIdRetired(cid0));
clock_.AdvanceTime(connection_id_expire_timeout * 0.75);
alarm_factory_.FireAlarm(retire_self_issued_cid_alarm_);
EXPECT_THAT(cid_manager_.GetUnretiredConnectionIds(),
ElementsAre(cid1, cid2, cid3));
EXPECT_TRUE(retire_self_issued_cid_alarm_->IsSet());
EXPECT_EQ(retire_self_issued_cid_alarm_->deadline(),
clock_.ApproximateNow() + connection_id_expire_timeout * 0.25);
EXPECT_CALL(cid_manager_visitor_, OnSelfIssuedConnectionIdRetired(cid1));
clock_.AdvanceTime(connection_id_expire_timeout * 0.25);
alarm_factory_.FireAlarm(retire_self_issued_cid_alarm_);
EXPECT_THAT(cid_manager_.GetUnretiredConnectionIds(),
ElementsAre(cid2, cid3));
EXPECT_FALSE(retire_self_issued_cid_alarm_->IsSet());
}
TEST_F(QuicSelfIssuedConnectionIdManagerTest,
AllExpiredConnectionIdsAreRetiredInOneBatch) {
QuicConnectionId cid0 = initial_connection_id_;
QuicConnectionId cid1 = CheckGenerate(cid0);
QuicConnectionId cid2 = CheckGenerate(cid1);
QuicConnectionId cid3 = CheckGenerate(cid2);
QuicConnectionId cid;
EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(_))
.Times(3)
.WillRepeatedly(Return(true));
EXPECT_CALL(cid_manager_visitor_, SendNewConnectionId(_))
.Times(3)
.WillRepeatedly(Return(true));
QuicTime::Delta connection_id_expire_timeout = 3 * pto_delay_;
QuicRetireConnectionIdFrame retire_cid_frame;
EXPECT_TRUE(cid_manager_.IsConnectionIdInUse(cid0));
EXPECT_FALSE(cid_manager_.HasConnectionIdToConsume());
EXPECT_FALSE(cid_manager_.ConsumeOneConnectionId().has_value());
cid_manager_.MaybeSendNewConnectionIds();
EXPECT_TRUE(cid_manager_.IsConnectionIdInUse(cid1));
EXPECT_TRUE(cid_manager_.HasConnectionIdToConsume());
cid = *cid_manager_.ConsumeOneConnectionId();
EXPECT_EQ(cid1, cid);
EXPECT_FALSE(cid_manager_.HasConnectionIdToConsume());
retire_cid_frame.sequence_number = 0u;
cid_manager_.OnRetireConnectionIdFrame(retire_cid_frame, pto_delay_,
&error_details_);
EXPECT_TRUE(cid_manager_.IsConnectionIdInUse(cid0));
EXPECT_TRUE(cid_manager_.IsConnectionIdInUse(cid1));
EXPECT_TRUE(cid_manager_.IsConnectionIdInUse(cid2));
EXPECT_TRUE(cid_manager_.HasConnectionIdToConsume());
cid = *cid_manager_.ConsumeOneConnectionId();
EXPECT_EQ(cid2, cid);
EXPECT_FALSE(cid_manager_.HasConnectionIdToConsume());
clock_.AdvanceTime(connection_id_expire_timeout * 0.1);
retire_cid_frame.sequence_number = 1u;
cid_manager_.OnRetireConnectionIdFrame(retire_cid_frame, pto_delay_,
&error_details_);
{
clock_.AdvanceTime(connection_id_expire_timeout);
testing::InSequence s;
EXPECT_CALL(cid_manager_visitor_, OnSelfIssuedConnectionIdRetired(cid0));
EXPECT_CALL(cid_manager_visitor_, OnSelfIssuedConnectionIdRetired(cid1));
alarm_factory_.FireAlarm(retire_self_issued_cid_alarm_);
EXPECT_FALSE(cid_manager_.IsConnectionIdInUse(cid0));
EXPECT_FALSE(cid_manager_.IsConnectionIdInUse(cid1));
EXPECT_TRUE(cid_manager_.IsConnectionIdInUse(cid2));
EXPECT_THAT(cid_manager_.GetUnretiredConnectionIds(),
ElementsAre(cid2, cid3));
EXPECT_FALSE(retire_self_issued_cid_alarm_->IsSet());
}
}
TEST_F(QuicSelfIssuedConnectionIdManagerTest,
ErrorWhenRetireConnectionIdNeverIssued) {
QuicConnectionId cid0 = initial_connection_id_;
QuicConnectionId cid1 = CheckGenerate(cid0);
EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(_))
.WillOnce(Return(true));
EXPECT_CALL(cid_manager_visitor_, SendNewConnectionId(_))
.WillOnce(Return(true));
cid_manager_.MaybeSendNewConnectionIds();
QuicRetireConnectionIdFrame retire_cid_frame;
retire_cid_frame.sequence_number = 2u;
ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame(
retire_cid_frame, pto_delay_, &error_details_),
IsError(IETF_QUIC_PROTOCOL_VIOLATION));
}
TEST_F(QuicSelfIssuedConnectionIdManagerTest,
ErrorWhenTooManyConnectionIdWaitingToBeRetired) {
QuicConnectionId last_connection_id = CheckGenerate(initial_connection_id_);
EXPECT_CALL(cid_manager_visitor_,
MaybeReserveConnectionId(last_connection_id))
.WillOnce(Return(true));
EXPECT_CALL(cid_manager_visitor_, SendNewConnectionId(_))
.WillOnce(Return(true));
cid_manager_.MaybeSendNewConnectionIds();
for (int i = 0; i < 8; ++i) {
last_connection_id = CheckGenerate(last_connection_id);
EXPECT_CALL(cid_manager_visitor_,
MaybeReserveConnectionId(last_connection_id))
.WillOnce(Return(true));
EXPECT_CALL(cid_manager_visitor_, SendNewConnectionId(_));
QuicRetireConnectionIdFrame retire_cid_frame;
retire_cid_frame.sequence_number = i;
ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame(
retire_cid_frame, pto_delay_, &error_details_),
IsQuicNoError());
}
QuicRetireConnectionIdFrame retire_cid_frame;
retire_cid_frame.sequence_number = 8u;
ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame(
retire_cid_frame, pto_delay_, &error_details_),
IsError(QUIC_TOO_MANY_CONNECTION_ID_WAITING_TO_RETIRE));
}
TEST_F(QuicSelfIssuedConnectionIdManagerTest, CannotIssueNewCidDueToVisitor) {
QuicConnectionId cid0 = initial_connection_id_;
QuicConnectionId cid1 = CheckGenerate(cid0);
EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(cid1))
.WillOnce(Return(false));
EXPECT_CALL(cid_manager_visitor_, SendNewConnectionId(_)).Times(0);
cid_manager_.MaybeSendNewConnectionIds();
}
TEST_F(QuicSelfIssuedConnectionIdManagerTest,
CannotIssueNewCidUponRetireConnectionIdDueToVisitor) {
QuicConnectionId cid0 = initial_connection_id_;
QuicConnectionId cid1 = CheckGenerate(cid0);
QuicConnectionId cid2 = CheckGenerate(cid1);
EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(cid1))
.WillOnce(Return(true));
EXPECT_CALL(cid_manager_visitor_, SendNewConnectionId(_))
.WillOnce(Return(true));
cid_manager_.MaybeSendNewConnectionIds();
EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(cid2))
.WillOnce(Return(false));
EXPECT_CALL(cid_manager_visitor_, SendNewConnectionId(_)).Times(0);
QuicRetireConnectionIdFrame retire_cid_frame;
retire_cid_frame.sequence_number = 1;
ASSERT_THAT(cid_manager_.OnRetireConnectionIdFrame(
retire_cid_frame, pto_delay_, &error_details_),
IsQuicNoError());
}
TEST_F(QuicSelfIssuedConnectionIdManagerTest,
DoNotIssueConnectionIdVoluntarilyIfOneHasIssuedForPerferredAddress) {
QuicConnectionId cid0 = initial_connection_id_;
QuicConnectionId cid1 = CheckGenerate(cid0);
EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(cid1))
.WillOnce(Return(true));
std::optional<QuicNewConnectionIdFrame> new_cid_frame =
cid_manager_.MaybeIssueNewConnectionIdForPreferredAddress();
ASSERT_TRUE(new_cid_frame.has_value());
ASSERT_THAT(*new_cid_frame, ExpectedNewConnectionIdFrame(cid1, 1u, 0u));
EXPECT_THAT(cid_manager_.GetUnretiredConnectionIds(),
ElementsAre(cid0, cid1));
EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(_)).Times(0);
EXPECT_CALL(cid_manager_visitor_, SendNewConnectionId(_)).Times(0);
cid_manager_.MaybeSendNewConnectionIds();
}
TEST_F(QuicSelfIssuedConnectionIdManagerTest,
RetireConnectionIdAfterConnectionIdCollisionIsFine) {
QuicConnectionId cid0 = initial_connection_id_;
QuicConnectionId cid1 = CheckGenerate(cid0);
EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(cid1))
.WillOnce(Return(true));
EXPECT_CALL(cid_manager_visitor_, SendNewConnectionId(_))
.WillOnce(Return(true));
cid_manager_.MaybeSendNewConnectionIds();
QuicRetireConnectionIdFrame retire_cid_frame(0,
1);
QuicConnectionId cid2 = CheckGenerate(cid1);
EXPECT_CALL(cid_manager_visitor_, MaybeReserveConnectionId(cid2))
.WillOnce(Return(false));
std::string error_details;
EXPECT_EQ(
cid_manager_.OnRetireConnectionIdFrame(
retire_cid_frame, QuicTime::Delta::FromSeconds(1), &error_details),
QUIC_NO_ERROR)
<< error_details;
EXPECT_EQ(
cid_manager_.OnRetireConnectionIdFrame(
retire_cid_frame, QuicTime::Delta::FromSeconds(1), &error_details),
QUIC_NO_ERROR)
<< error_details;
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_connection_id_manager.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_connection_id_manager_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
2b37f4eb-1743-4a71-a5fa-9e6fbb0fbcc1 | cpp | google/quiche | quic_alarm | quiche/quic/core/quic_alarm.cc | quiche/quic/core/quic_alarm_test.cc | #include "quiche/quic/core/quic_alarm.h"
#include <atomic>
#include <cstdlib>
#include <utility>
#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_stack_trace.h"
namespace quic {
QuicAlarm::QuicAlarm(QuicArenaScopedPtr<Delegate> delegate)
: delegate_(std::move(delegate)), deadline_(QuicTime::Zero()) {}
QuicAlarm::~QuicAlarm() {
if (IsSet()) {
QUIC_CODE_COUNT(quic_alarm_not_cancelled_in_dtor);
}
}
void QuicAlarm::Set(QuicTime new_deadline) {
QUICHE_DCHECK(!IsSet());
QUICHE_DCHECK(new_deadline.IsInitialized());
if (IsPermanentlyCancelled()) {
QUIC_BUG(quic_alarm_illegal_set)
<< "Set called after alarm is permanently cancelled. new_deadline:"
<< new_deadline;
return;
}
deadline_ = new_deadline;
SetImpl();
}
void QuicAlarm::CancelInternal(bool permanent) {
if (IsSet()) {
deadline_ = QuicTime::Zero();
CancelImpl();
}
if (permanent) {
delegate_.reset();
}
}
bool QuicAlarm::IsPermanentlyCancelled() const { return delegate_ == nullptr; }
void QuicAlarm::Update(QuicTime new_deadline, QuicTime::Delta granularity) {
if (IsPermanentlyCancelled()) {
QUIC_BUG(quic_alarm_illegal_update)
<< "Update called after alarm is permanently cancelled. new_deadline:"
<< new_deadline << ", granularity:" << granularity;
return;
}
if (!new_deadline.IsInitialized()) {
Cancel();
return;
}
if (std::abs((new_deadline - deadline_).ToMicroseconds()) <
granularity.ToMicroseconds()) {
return;
}
const bool was_set = IsSet();
deadline_ = new_deadline;
if (was_set) {
UpdateImpl();
} else {
SetImpl();
}
}
bool QuicAlarm::IsSet() const { return deadline_.IsInitialized(); }
void QuicAlarm::Fire() {
if (!IsSet()) {
return;
}
deadline_ = QuicTime::Zero();
if (!IsPermanentlyCancelled()) {
QuicConnectionContextSwitcher context_switcher(
delegate_->GetConnectionContext());
delegate_->OnAlarm();
}
}
void QuicAlarm::UpdateImpl() {
const QuicTime new_deadline = deadline_;
deadline_ = QuicTime::Zero();
CancelImpl();
deadline_ = new_deadline;
SetImpl();
}
} | #include "quiche/quic/core/quic_alarm.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "quiche/quic/core/quic_connection_context.h"
#include "quiche/quic/platform/api/quic_expect_bug.h"
#include "quiche/quic/platform/api/quic_test.h"
using testing::ElementsAre;
using testing::Invoke;
using testing::Return;
namespace quic {
namespace test {
namespace {
class TraceCollector : public QuicConnectionTracer {
public:
~TraceCollector() override = default;
void PrintLiteral(const char* literal) override { trace_.push_back(literal); }
void PrintString(absl::string_view s) override {
trace_.push_back(std::string(s));
}
const std::vector<std::string>& trace() const { return trace_; }
private:
std::vector<std::string> trace_;
};
class MockDelegate : public QuicAlarm::Delegate {
public:
MOCK_METHOD(QuicConnectionContext*, GetConnectionContext, (), (override));
MOCK_METHOD(void, OnAlarm, (), (override));
};
class DestructiveDelegate : public QuicAlarm::DelegateWithoutContext {
public:
DestructiveDelegate() : alarm_(nullptr) {}
void set_alarm(QuicAlarm* alarm) { alarm_ = alarm; }
void OnAlarm() override {
QUICHE_DCHECK(alarm_);
delete alarm_;
}
private:
QuicAlarm* alarm_;
};
class TestAlarm : public QuicAlarm {
public:
explicit TestAlarm(QuicAlarm::Delegate* delegate)
: QuicAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate>(delegate)) {}
bool scheduled() const { return scheduled_; }
void FireAlarm() {
scheduled_ = false;
Fire();
}
protected:
void SetImpl() override {
QUICHE_DCHECK(deadline().IsInitialized());
scheduled_ = true;
}
void CancelImpl() override {
QUICHE_DCHECK(!deadline().IsInitialized());
scheduled_ = false;
}
private:
bool scheduled_;
};
class DestructiveAlarm : public QuicAlarm {
public:
explicit DestructiveAlarm(DestructiveDelegate* delegate)
: QuicAlarm(QuicArenaScopedPtr<DestructiveDelegate>(delegate)) {}
void FireAlarm() { Fire(); }
protected:
void SetImpl() override {}
void CancelImpl() override {}
};
class QuicAlarmTest : public QuicTest {
public:
QuicAlarmTest()
: delegate_(new MockDelegate()),
alarm_(delegate_),
deadline_(QuicTime::Zero() + QuicTime::Delta::FromSeconds(7)),
deadline2_(QuicTime::Zero() + QuicTime::Delta::FromSeconds(14)),
new_deadline_(QuicTime::Zero()) {}
void ResetAlarm() { alarm_.Set(new_deadline_); }
MockDelegate* delegate_;
TestAlarm alarm_;
QuicTime deadline_;
QuicTime deadline2_;
QuicTime new_deadline_;
};
TEST_F(QuicAlarmTest, IsSet) { EXPECT_FALSE(alarm_.IsSet()); }
TEST_F(QuicAlarmTest, Set) {
QuicTime deadline = QuicTime::Zero() + QuicTime::Delta::FromSeconds(7);
alarm_.Set(deadline);
EXPECT_TRUE(alarm_.IsSet());
EXPECT_TRUE(alarm_.scheduled());
EXPECT_EQ(deadline, alarm_.deadline());
}
TEST_F(QuicAlarmTest, Cancel) {
QuicTime deadline = QuicTime::Zero() + QuicTime::Delta::FromSeconds(7);
alarm_.Set(deadline);
alarm_.Cancel();
EXPECT_FALSE(alarm_.IsSet());
EXPECT_FALSE(alarm_.scheduled());
EXPECT_EQ(QuicTime::Zero(), alarm_.deadline());
}
TEST_F(QuicAlarmTest, PermanentCancel) {
QuicTime deadline = QuicTime::Zero() + QuicTime::Delta::FromSeconds(7);
alarm_.Set(deadline);
alarm_.PermanentCancel();
EXPECT_FALSE(alarm_.IsSet());
EXPECT_FALSE(alarm_.scheduled());
EXPECT_EQ(QuicTime::Zero(), alarm_.deadline());
EXPECT_QUIC_BUG(alarm_.Set(deadline),
"Set called after alarm is permanently cancelled");
EXPECT_TRUE(alarm_.IsPermanentlyCancelled());
EXPECT_FALSE(alarm_.IsSet());
EXPECT_FALSE(alarm_.scheduled());
EXPECT_EQ(QuicTime::Zero(), alarm_.deadline());
EXPECT_QUIC_BUG(alarm_.Update(deadline, QuicTime::Delta::Zero()),
"Update called after alarm is permanently cancelled");
EXPECT_TRUE(alarm_.IsPermanentlyCancelled());
EXPECT_FALSE(alarm_.IsSet());
EXPECT_FALSE(alarm_.scheduled());
EXPECT_EQ(QuicTime::Zero(), alarm_.deadline());
}
TEST_F(QuicAlarmTest, Update) {
QuicTime deadline = QuicTime::Zero() + QuicTime::Delta::FromSeconds(7);
alarm_.Set(deadline);
QuicTime new_deadline = QuicTime::Zero() + QuicTime::Delta::FromSeconds(8);
alarm_.Update(new_deadline, QuicTime::Delta::Zero());
EXPECT_TRUE(alarm_.IsSet());
EXPECT_TRUE(alarm_.scheduled());
EXPECT_EQ(new_deadline, alarm_.deadline());
}
TEST_F(QuicAlarmTest, UpdateWithZero) {
QuicTime deadline = QuicTime::Zero() + QuicTime::Delta::FromSeconds(7);
alarm_.Set(deadline);
alarm_.Update(QuicTime::Zero(), QuicTime::Delta::Zero());
EXPECT_FALSE(alarm_.IsSet());
EXPECT_FALSE(alarm_.scheduled());
EXPECT_EQ(QuicTime::Zero(), alarm_.deadline());
}
TEST_F(QuicAlarmTest, Fire) {
QuicTime deadline = QuicTime::Zero() + QuicTime::Delta::FromSeconds(7);
alarm_.Set(deadline);
EXPECT_CALL(*delegate_, OnAlarm());
alarm_.FireAlarm();
EXPECT_FALSE(alarm_.IsSet());
EXPECT_FALSE(alarm_.scheduled());
EXPECT_EQ(QuicTime::Zero(), alarm_.deadline());
}
TEST_F(QuicAlarmTest, FireAndResetViaSet) {
alarm_.Set(deadline_);
new_deadline_ = deadline2_;
EXPECT_CALL(*delegate_, OnAlarm())
.WillOnce(Invoke(this, &QuicAlarmTest::ResetAlarm));
alarm_.FireAlarm();
EXPECT_TRUE(alarm_.IsSet());
EXPECT_TRUE(alarm_.scheduled());
EXPECT_EQ(deadline2_, alarm_.deadline());
}
TEST_F(QuicAlarmTest, FireDestroysAlarm) {
DestructiveDelegate* delegate(new DestructiveDelegate);
DestructiveAlarm* alarm = new DestructiveAlarm(delegate);
delegate->set_alarm(alarm);
QuicTime deadline = QuicTime::Zero() + QuicTime::Delta::FromSeconds(7);
alarm->Set(deadline);
alarm->FireAlarm();
}
TEST_F(QuicAlarmTest, NullAlarmContext) {
QuicTime deadline = QuicTime::Zero() + QuicTime::Delta::FromSeconds(7);
alarm_.Set(deadline);
EXPECT_CALL(*delegate_, GetConnectionContext()).WillOnce(Return(nullptr));
EXPECT_CALL(*delegate_, OnAlarm()).WillOnce(Invoke([] {
QUIC_TRACELITERAL("Alarm fired.");
}));
alarm_.FireAlarm();
}
TEST_F(QuicAlarmTest, AlarmContextWithNullTracer) {
QuicConnectionContext context;
ASSERT_EQ(context.tracer, nullptr);
QuicTime deadline = QuicTime::Zero() + QuicTime::Delta::FromSeconds(7);
alarm_.Set(deadline);
EXPECT_CALL(*delegate_, GetConnectionContext()).WillOnce(Return(&context));
EXPECT_CALL(*delegate_, OnAlarm()).WillOnce(Invoke([] {
QUIC_TRACELITERAL("Alarm fired.");
}));
alarm_.FireAlarm();
}
TEST_F(QuicAlarmTest, AlarmContextWithTracer) {
QuicConnectionContext context;
std::unique_ptr<TraceCollector> tracer = std::make_unique<TraceCollector>();
const TraceCollector& tracer_ref = *tracer;
context.tracer = std::move(tracer);
QuicTime deadline = QuicTime::Zero() + QuicTime::Delta::FromSeconds(7);
alarm_.Set(deadline);
EXPECT_CALL(*delegate_, GetConnectionContext()).WillOnce(Return(&context));
EXPECT_CALL(*delegate_, OnAlarm()).WillOnce(Invoke([] {
QUIC_TRACELITERAL("Alarm fired.");
}));
QUIC_TRACELITERAL("Should not be collected before alarm.");
alarm_.FireAlarm();
QUIC_TRACELITERAL("Should not be collected after alarm.");
EXPECT_THAT(tracer_ref.trace(), ElementsAre("Alarm fired."));
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_alarm.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_alarm_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
3700447d-c783-4304-81d0-298c510d58bf | cpp | google/quiche | quic_packets | quiche/quic/core/quic_packets.cc | quiche/quic/core/quic_packets_test.cc | #include "quiche/quic/core/quic_packets.h"
#include <algorithm>
#include <memory>
#include <ostream>
#include <string>
#include <utility>
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.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/core/quic_versions.h"
#include "quiche/quic/platform/api/quic_flags.h"
namespace quic {
QuicConnectionId GetServerConnectionIdAsRecipient(
const QuicPacketHeader& header, Perspective perspective) {
if (perspective == Perspective::IS_SERVER) {
return header.destination_connection_id;
}
return header.source_connection_id;
}
QuicConnectionId GetClientConnectionIdAsRecipient(
const QuicPacketHeader& header, Perspective perspective) {
if (perspective == Perspective::IS_CLIENT) {
return header.destination_connection_id;
}
return header.source_connection_id;
}
QuicConnectionId GetServerConnectionIdAsSender(const QuicPacketHeader& header,
Perspective perspective) {
if (perspective == Perspective::IS_CLIENT) {
return header.destination_connection_id;
}
return header.source_connection_id;
}
QuicConnectionIdIncluded GetServerConnectionIdIncludedAsSender(
const QuicPacketHeader& header, Perspective perspective) {
if (perspective == Perspective::IS_CLIENT) {
return header.destination_connection_id_included;
}
return header.source_connection_id_included;
}
QuicConnectionId GetClientConnectionIdAsSender(const QuicPacketHeader& header,
Perspective perspective) {
if (perspective == Perspective::IS_CLIENT) {
return header.source_connection_id;
}
return header.destination_connection_id;
}
QuicConnectionIdIncluded GetClientConnectionIdIncludedAsSender(
const QuicPacketHeader& header, Perspective perspective) {
if (perspective == Perspective::IS_CLIENT) {
return header.source_connection_id_included;
}
return header.destination_connection_id_included;
}
uint8_t GetIncludedConnectionIdLength(
QuicConnectionId connection_id,
QuicConnectionIdIncluded connection_id_included) {
QUICHE_DCHECK(connection_id_included == CONNECTION_ID_PRESENT ||
connection_id_included == CONNECTION_ID_ABSENT);
return connection_id_included == CONNECTION_ID_PRESENT
? connection_id.length()
: 0;
}
uint8_t GetIncludedDestinationConnectionIdLength(
const QuicPacketHeader& header) {
return GetIncludedConnectionIdLength(
header.destination_connection_id,
header.destination_connection_id_included);
}
uint8_t GetIncludedSourceConnectionIdLength(const QuicPacketHeader& header) {
return GetIncludedConnectionIdLength(header.source_connection_id,
header.source_connection_id_included);
}
size_t GetPacketHeaderSize(QuicTransportVersion version,
const QuicPacketHeader& header) {
return GetPacketHeaderSize(
version, GetIncludedDestinationConnectionIdLength(header),
GetIncludedSourceConnectionIdLength(header), header.version_flag,
header.nonce != nullptr, header.packet_number_length,
header.retry_token_length_length, header.retry_token.length(),
header.length_length);
}
size_t GetPacketHeaderSize(
QuicTransportVersion version, uint8_t destination_connection_id_length,
uint8_t source_connection_id_length, bool include_version,
bool include_diversification_nonce,
QuicPacketNumberLength packet_number_length,
quiche::QuicheVariableLengthIntegerLength retry_token_length_length,
QuicByteCount retry_token_length,
quiche::QuicheVariableLengthIntegerLength length_length) {
if (include_version) {
size_t size = kPacketHeaderTypeSize + kConnectionIdLengthSize +
destination_connection_id_length +
source_connection_id_length + packet_number_length +
kQuicVersionSize;
if (include_diversification_nonce) {
size += kDiversificationNonceSize;
}
if (VersionHasLengthPrefixedConnectionIds(version)) {
size += kConnectionIdLengthSize;
}
QUICHE_DCHECK(
QuicVersionHasLongHeaderLengths(version) ||
retry_token_length_length + retry_token_length + length_length == 0);
if (QuicVersionHasLongHeaderLengths(version)) {
size += retry_token_length_length + retry_token_length + length_length;
}
return size;
}
return kPacketHeaderTypeSize + destination_connection_id_length +
packet_number_length;
}
size_t GetStartOfEncryptedData(QuicTransportVersion version,
const QuicPacketHeader& header) {
return GetPacketHeaderSize(version, header);
}
size_t GetStartOfEncryptedData(
QuicTransportVersion version, uint8_t destination_connection_id_length,
uint8_t source_connection_id_length, bool include_version,
bool include_diversification_nonce,
QuicPacketNumberLength packet_number_length,
quiche::QuicheVariableLengthIntegerLength retry_token_length_length,
QuicByteCount retry_token_length,
quiche::QuicheVariableLengthIntegerLength length_length) {
return GetPacketHeaderSize(
version, destination_connection_id_length, source_connection_id_length,
include_version, include_diversification_nonce, packet_number_length,
retry_token_length_length, retry_token_length, length_length);
}
QuicPacketHeader::QuicPacketHeader()
: destination_connection_id(EmptyQuicConnectionId()),
destination_connection_id_included(CONNECTION_ID_PRESENT),
source_connection_id(EmptyQuicConnectionId()),
source_connection_id_included(CONNECTION_ID_ABSENT),
reset_flag(false),
version_flag(false),
has_possible_stateless_reset_token(false),
packet_number_length(PACKET_4BYTE_PACKET_NUMBER),
type_byte(0),
version(UnsupportedQuicVersion()),
nonce(nullptr),
form(GOOGLE_QUIC_PACKET),
long_packet_type(INITIAL),
possible_stateless_reset_token({}),
retry_token_length_length(quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0),
retry_token(absl::string_view()),
length_length(quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0),
remaining_packet_length(0) {}
QuicPacketHeader::QuicPacketHeader(const QuicPacketHeader& other) = default;
QuicPacketHeader::~QuicPacketHeader() {}
QuicPacketHeader& QuicPacketHeader::operator=(const QuicPacketHeader& other) =
default;
QuicPublicResetPacket::QuicPublicResetPacket()
: connection_id(EmptyQuicConnectionId()), nonce_proof(0) {}
QuicPublicResetPacket::QuicPublicResetPacket(QuicConnectionId connection_id)
: connection_id(connection_id), nonce_proof(0) {}
QuicVersionNegotiationPacket::QuicVersionNegotiationPacket()
: connection_id(EmptyQuicConnectionId()) {}
QuicVersionNegotiationPacket::QuicVersionNegotiationPacket(
QuicConnectionId connection_id)
: connection_id(connection_id) {}
QuicVersionNegotiationPacket::QuicVersionNegotiationPacket(
const QuicVersionNegotiationPacket& other) = default;
QuicVersionNegotiationPacket::~QuicVersionNegotiationPacket() {}
QuicIetfStatelessResetPacket::QuicIetfStatelessResetPacket()
: stateless_reset_token({}) {}
QuicIetfStatelessResetPacket::QuicIetfStatelessResetPacket(
const QuicPacketHeader& header, StatelessResetToken token)
: header(header), stateless_reset_token(token) {}
QuicIetfStatelessResetPacket::QuicIetfStatelessResetPacket(
const QuicIetfStatelessResetPacket& other) = default;
QuicIetfStatelessResetPacket::~QuicIetfStatelessResetPacket() {}
std::ostream& operator<<(std::ostream& os, const QuicPacketHeader& header) {
os << "{ destination_connection_id: " << header.destination_connection_id
<< " ("
<< (header.destination_connection_id_included == CONNECTION_ID_PRESENT
? "present"
: "absent")
<< "), source_connection_id: " << header.source_connection_id << " ("
<< (header.source_connection_id_included == CONNECTION_ID_PRESENT
? "present"
: "absent")
<< "), packet_number_length: "
<< static_cast<int>(header.packet_number_length)
<< ", reset_flag: " << header.reset_flag
<< ", version_flag: " << header.version_flag;
if (header.version_flag) {
os << ", version: " << ParsedQuicVersionToString(header.version);
if (header.long_packet_type != INVALID_PACKET_TYPE) {
os << ", long_packet_type: "
<< QuicUtils::QuicLongHeaderTypetoString(header.long_packet_type);
}
if (header.retry_token_length_length !=
quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0) {
os << ", retry_token_length_length: "
<< static_cast<int>(header.retry_token_length_length);
}
if (header.retry_token.length() != 0) {
os << ", retry_token_length: " << header.retry_token.length();
}
if (header.length_length != quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0) {
os << ", length_length: " << static_cast<int>(header.length_length);
}
if (header.remaining_packet_length != 0) {
os << ", remaining_packet_length: " << header.remaining_packet_length;
}
}
if (header.nonce != nullptr) {
os << ", diversification_nonce: "
<< absl::BytesToHexString(
absl::string_view(header.nonce->data(), header.nonce->size()));
}
os << ", packet_number: " << header.packet_number << " }\n";
return os;
}
QuicData::QuicData(const char* buffer, size_t length)
: buffer_(buffer), length_(length), owns_buffer_(false) {}
QuicData::QuicData(const char* buffer, size_t length, bool owns_buffer)
: buffer_(buffer), length_(length), owns_buffer_(owns_buffer) {}
QuicData::QuicData(absl::string_view packet_data)
: buffer_(packet_data.data()),
length_(packet_data.length()),
owns_buffer_(false) {}
QuicData::~QuicData() {
if (owns_buffer_) {
delete[] const_cast<char*>(buffer_);
}
}
QuicPacket::QuicPacket(
char* buffer, size_t length, bool owns_buffer,
uint8_t destination_connection_id_length,
uint8_t source_connection_id_length, bool includes_version,
bool includes_diversification_nonce,
QuicPacketNumberLength packet_number_length,
quiche::QuicheVariableLengthIntegerLength retry_token_length_length,
QuicByteCount retry_token_length,
quiche::QuicheVariableLengthIntegerLength length_length)
: QuicData(buffer, length, owns_buffer),
buffer_(buffer),
destination_connection_id_length_(destination_connection_id_length),
source_connection_id_length_(source_connection_id_length),
includes_version_(includes_version),
includes_diversification_nonce_(includes_diversification_nonce),
packet_number_length_(packet_number_length),
retry_token_length_length_(retry_token_length_length),
retry_token_length_(retry_token_length),
length_length_(length_length) {}
QuicPacket::QuicPacket(QuicTransportVersion , char* buffer,
size_t length, bool owns_buffer,
const QuicPacketHeader& header)
: QuicPacket(buffer, length, owns_buffer,
GetIncludedDestinationConnectionIdLength(header),
GetIncludedSourceConnectionIdLength(header),
header.version_flag, header.nonce != nullptr,
header.packet_number_length, header.retry_token_length_length,
header.retry_token.length(), header.length_length) {}
QuicEncryptedPacket::QuicEncryptedPacket(const char* buffer, size_t length)
: QuicData(buffer, length) {}
QuicEncryptedPacket::QuicEncryptedPacket(const char* buffer, size_t length,
bool owns_buffer)
: QuicData(buffer, length, owns_buffer) {}
QuicEncryptedPacket::QuicEncryptedPacket(absl::string_view data)
: QuicData(data) {}
std::unique_ptr<QuicEncryptedPacket> QuicEncryptedPacket::Clone() const {
char* buffer = new char[this->length()];
std::copy(this->data(), this->data() + this->length(), buffer);
return std::make_unique<QuicEncryptedPacket>(buffer, this->length(), true);
}
std::ostream& operator<<(std::ostream& os, const QuicEncryptedPacket& s) {
os << s.length() << "-byte data";
return os;
}
QuicReceivedPacket::QuicReceivedPacket(const char* buffer, size_t length,
QuicTime receipt_time)
: QuicReceivedPacket(buffer, length, receipt_time,
false ) {}
QuicReceivedPacket::QuicReceivedPacket(const char* buffer, size_t length,
QuicTime receipt_time, bool owns_buffer)
: QuicReceivedPacket(buffer, length, receipt_time, owns_buffer, 0 ,
true ) {}
QuicReceivedPacket::QuicReceivedPacket(const char* buffer, size_t length,
QuicTime receipt_time, bool owns_buffer,
int ttl, bool ttl_valid)
: quic::QuicReceivedPacket(buffer, length, receipt_time, owns_buffer, ttl,
ttl_valid, nullptr ,
0 ,
false , ECN_NOT_ECT) {}
QuicReceivedPacket::QuicReceivedPacket(const char* buffer, size_t length,
QuicTime receipt_time, bool owns_buffer,
int ttl, bool ttl_valid,
char* packet_headers,
size_t headers_length,
bool owns_header_buffer)
: quic::QuicReceivedPacket(buffer, length, receipt_time, owns_buffer, ttl,
ttl_valid, packet_headers, headers_length,
owns_header_buffer, ECN_NOT_ECT) {}
QuicReceivedPacket::QuicReceivedPacket(
const char* buffer, size_t length, QuicTime receipt_time, bool owns_buffer,
int ttl, bool ttl_valid, char* packet_headers, size_t headers_length,
bool owns_header_buffer, QuicEcnCodepoint ecn_codepoint)
: QuicEncryptedPacket(buffer, length, owns_buffer),
receipt_time_(receipt_time),
ttl_(ttl_valid ? ttl : -1),
packet_headers_(packet_headers),
headers_length_(headers_length),
owns_header_buffer_(owns_header_buffer),
ecn_codepoint_(ecn_codepoint) {}
QuicReceivedPacket::~QuicReceivedPacket() {
if (owns_header_buffer_) {
delete[] static_cast<char*>(packet_headers_);
}
}
std::unique_ptr<QuicReceivedPacket> QuicReceivedPacket::Clone() const {
char* buffer = new char[this->length()];
memcpy(buffer, this->data(), this->length());
if (this->packet_headers()) {
char* headers_buffer = new char[this->headers_length()];
memcpy(headers_buffer, this->packet_headers(), this->headers_length());
return std::make_unique<QuicReceivedPacket>(
buffer, this->length(), receipt_time(), true, ttl(), ttl() >= 0,
headers_buffer, this->headers_length(), true, this->ecn_codepoint());
}
return std::make_unique<QuicReceivedPacket>(
buffer, this->length(), receipt_time(), true, ttl(), ttl() >= 0, nullptr,
0, false, this->ecn_codepoint());
}
std::ostream& operator<<(std::ostream& os, const QuicReceivedPacket& s) {
os << s.length() << "-byte data";
return os;
}
absl::string_view QuicPacket::AssociatedData(
QuicTransportVersion version) const {
return absl::string_view(
data(),
GetStartOfEncryptedData(version, destination_connection_id_length_,
source_connection_id_length_, includes_version_,
includes_diversification_nonce_,
packet_number_length_, retry_token_length_length_,
retry_token_length_, length_length_));
}
absl::string_view QuicPacket::Plaintext(QuicTransportVersion version) const {
const size_t start_of_encrypted_data = GetStartOfEncryptedData(
version, destination_connection_id_length_, source_connection_id_length_,
includes_version_, includes_diversification_nonce_, packet_number_length_,
retry_token_length_length_, retry_token_length_, length_length_);
return absl::string_view(data() + start_of_encrypted_data,
length() - start_of_encrypted_data);
}
SerializedPacket::SerializedPacket(QuicPacketNumber packet_number,
QuicPacketNumberLength packet_number_length,
const char* encrypted_buffer,
QuicPacketLength encrypted_length,
bool has_ack, bool has_stop_waiting)
: encrypted_buffer(encrypted_buffer),
encrypted_length(encrypted_length),
has_crypto_handshake(NOT_HANDSHAKE),
packet_number(packet_number),
packet_number_length(packet_number_length),
encryption_level(ENCRYPTION_INITIAL),
has_ack(has_ack),
has_stop_waiting(has_stop_waiting),
transmission_type(NOT_RETRANSMISSION),
has_ack_frame_copy(false),
has_ack_frequency(false),
has_message(false),
fate(SEND_TO_WRITER) {}
SerializedPacket::SerializedPacket(SerializedPacket&& other)
: has_crypto_handshake(other.has_crypto_handshake),
packet_number(other.packet_number),
packet_number_length(other.packet_number_length),
encryption_level(other.encryption_level),
has_ack(other.has_ack),
has_stop_waiting(other.has_stop_waiting),
has_ack_ecn(other.has_ack_ecn),
transmission_type(other.transmission_type),
largest_acked(other.largest_acked),
has_ack_frame_copy(other.has_ack_frame_copy),
has_ack_frequency(other.has_ack_frequency),
has_message(other.has_message),
fate(other.fate),
peer_address(other.peer_address),
bytes_not_retransmitted(other.bytes_not_retransmitted),
initial_header(other.initial_header) {
if (this != &other) {
if (release_encrypted_buffer && encrypted_buffer != nullptr) {
release_encrypted_buffer(encrypted_buffer);
}
encrypted_buffer = other.encrypted_buffer;
encrypted_length = other.encrypted_length;
release_encrypted_buffer = std::move(other.release_encrypted_buffer);
other.release_encrypted_buffer = nullptr;
retransmittable_frames.swap(other.retransmittable_frames);
nonretransmittable_frames.swap(other.nonretransmittable_frames);
}
}
SerializedPacket::~SerializedPacket() {
if (release_encrypted_buffer && encrypted_buffer != nullptr) {
release_encrypted_buffer(encrypted_buffer);
}
if (!retransmittable_frames.empty()) {
DeleteFrames(&retransmittable_frames);
}
for (auto& frame : nonretransmittable_frames) {
if (!has_ack_frame_copy && frame.type == ACK_FRAME) {
continue;
}
DeleteFrame(&frame);
}
}
SerializedPacket* CopySerializedPacket(const SerializedPacket& serialized,
quiche::QuicheBufferAllocator* allocator,
bool copy_buffer) {
SerializedPacket* copy = new SerializedPacket(
serialized.packet_number, serialized.packet_number_length,
serialized.encrypted_buffer, serialized.encrypted_length,
serialized.has_ack, serialized.has_stop_waiting);
copy->has_crypto_handshake = serialized.has_crypto_handshake;
copy->encryption_level = serialized.encryption_level;
copy->transmission_type = serialized.transmission_type;
copy->largest_acked = serialized.largest_acked;
copy->has_ack_frequency = serialized.has_ack_frequency;
copy->has_message = serialized.has_message;
copy->fate = serialized.fate;
copy->peer_address = serialized.peer_address;
copy->bytes_not_retransmitted = serialized.bytes_not_retransmitted;
copy->initial_header = serialized.initial_header;
copy->has_ack_ecn = serialized.has_ack_ecn;
if (copy_buffer) {
copy->encrypted_buffer = CopyBuffer(serialized);
copy->release_encrypted_buffer = [](const char* p) { delete[] p; };
}
copy->retransmittable_frames =
CopyQuicFrames(allocator, serialized.retransmittable_frames);
QUICHE_DCHECK(copy->nonretransmittable_frames.empty());
for (const auto& frame : serialized.nonretransmittable_frames) {
if (frame.type == ACK_FRAME) {
copy->has_ack_frame_copy = true;
}
copy->nonretransmittable_frames.push_back(CopyQuicFrame(allocator, frame));
}
return copy;
}
char* CopyBuffer(const SerializedPacket& packet) {
return CopyBuffer(packet.encrypted_buffer, packet.encrypted_length);
}
char* CopyBuffer(const char* encrypted_buffer,
QuicPacketLength encrypted_length) {
char* dst_buffer = new char[encrypted_length];
memcpy(dst_buffer, encrypted_buffer, encrypted_length);
return dst_buffer;
}
ReceivedPacketInfo::ReceivedPacketInfo(const QuicSocketAddress& self_address,
const QuicSocketAddress& peer_address,
const QuicReceivedPacket& packet)
: self_address(self_address),
peer_address(peer_address),
packet(packet),
form(GOOGLE_QUIC_PACKET),
long_packet_type(INVALID_PACKET_TYPE),
version_flag(false),
use_length_prefix(false),
version_label(0),
version(ParsedQuicVersion::Unsupported()),
destination_connection_id(EmptyQuicConnectionId()),
source_connection_id(EmptyQuicConnectionId()) {}
ReceivedPacketInfo::~ReceivedPacketInfo() {}
std::string ReceivedPacketInfo::ToString() const {
std::string output =
absl::StrCat("{ self_address: ", self_address.ToString(),
", peer_address: ", peer_address.ToString(),
", packet_length: ", packet.length(),
", header_format: ", form, ", version_flag: ", version_flag);
if (version_flag) {
absl::StrAppend(&output, ", version: ", ParsedQuicVersionToString(version));
}
absl::StrAppend(
&output,
", destination_connection_id: ", destination_connection_id.ToString(),
", source_connection_id: ", source_connection_id.ToString(), " }\n");
return output;
}
std::ostream& operator<<(std::ostream& os,
const ReceivedPacketInfo& packet_info) {
os << packet_info.ToString();
return os;
}
bool QuicPacketHeader::operator==(const QuicPacketHeader& other) const {
return destination_connection_id == other.destination_connection_id &&
destination_connection_id_included ==
other.destination_connection_id_included &&
source_connection_id == other.source_connection_id &&
source_connection_id_included == other.source_connection_id_included &&
reset_flag == other.reset_flag && version_flag == other.version_flag &&
has_possible_stateless_reset_token ==
other.has_possible_stateless_reset_token &&
packet_number_length == other.packet_number_length &&
type_byte == other.type_byte && version == other.version &&
nonce == other.nonce &&
((!packet_number.IsInitialized() &&
!other.packet_number.IsInitialized()) ||
(packet_number.IsInitialized() &&
other.packet_number.IsInitialized() &&
packet_number == other.packet_number)) &&
form == other.form && long_packet_type == other.long_packet_type &&
possible_stateless_reset_token ==
other.possible_stateless_reset_token &&
retry_token_length_length == other.retry_token_length_length &&
retry_token == other.retry_token &&
length_length == other.length_length &&
remaining_packet_length == other.remaining_packet_length;
}
bool QuicPacketHeader::operator!=(const QuicPacketHeader& other) const {
return !operator==(other);
}
} | #include "quiche/quic/core/quic_packets.h"
#include <memory>
#include <string>
#include "absl/memory/memory.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_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 {
QuicPacketHeader CreateFakePacketHeader() {
QuicPacketHeader header;
header.destination_connection_id = TestConnectionId(1);
header.destination_connection_id_included = CONNECTION_ID_PRESENT;
header.source_connection_id = TestConnectionId(2);
header.source_connection_id_included = CONNECTION_ID_ABSENT;
return header;
}
class QuicPacketsTest : public QuicTest {};
TEST_F(QuicPacketsTest, GetServerConnectionIdAsRecipient) {
QuicPacketHeader header = CreateFakePacketHeader();
EXPECT_EQ(TestConnectionId(1),
GetServerConnectionIdAsRecipient(header, Perspective::IS_SERVER));
EXPECT_EQ(TestConnectionId(2),
GetServerConnectionIdAsRecipient(header, Perspective::IS_CLIENT));
}
TEST_F(QuicPacketsTest, GetServerConnectionIdAsSender) {
QuicPacketHeader header = CreateFakePacketHeader();
EXPECT_EQ(TestConnectionId(2),
GetServerConnectionIdAsSender(header, Perspective::IS_SERVER));
EXPECT_EQ(TestConnectionId(1),
GetServerConnectionIdAsSender(header, Perspective::IS_CLIENT));
}
TEST_F(QuicPacketsTest, GetServerConnectionIdIncludedAsSender) {
QuicPacketHeader header = CreateFakePacketHeader();
EXPECT_EQ(CONNECTION_ID_ABSENT, GetServerConnectionIdIncludedAsSender(
header, Perspective::IS_SERVER));
EXPECT_EQ(CONNECTION_ID_PRESENT, GetServerConnectionIdIncludedAsSender(
header, Perspective::IS_CLIENT));
}
TEST_F(QuicPacketsTest, GetClientConnectionIdIncludedAsSender) {
QuicPacketHeader header = CreateFakePacketHeader();
EXPECT_EQ(CONNECTION_ID_PRESENT, GetClientConnectionIdIncludedAsSender(
header, Perspective::IS_SERVER));
EXPECT_EQ(CONNECTION_ID_ABSENT, GetClientConnectionIdIncludedAsSender(
header, Perspective::IS_CLIENT));
}
TEST_F(QuicPacketsTest, GetClientConnectionIdAsRecipient) {
QuicPacketHeader header = CreateFakePacketHeader();
EXPECT_EQ(TestConnectionId(2),
GetClientConnectionIdAsRecipient(header, Perspective::IS_SERVER));
EXPECT_EQ(TestConnectionId(1),
GetClientConnectionIdAsRecipient(header, Perspective::IS_CLIENT));
}
TEST_F(QuicPacketsTest, GetClientConnectionIdAsSender) {
QuicPacketHeader header = CreateFakePacketHeader();
EXPECT_EQ(TestConnectionId(1),
GetClientConnectionIdAsSender(header, Perspective::IS_SERVER));
EXPECT_EQ(TestConnectionId(2),
GetClientConnectionIdAsSender(header, Perspective::IS_CLIENT));
}
TEST_F(QuicPacketsTest, CopyQuicPacketHeader) {
QuicPacketHeader header;
QuicPacketHeader header2 = CreateFakePacketHeader();
EXPECT_NE(header, header2);
QuicPacketHeader header3(header2);
EXPECT_EQ(header2, header3);
}
TEST_F(QuicPacketsTest, CopySerializedPacket) {
std::string buffer(1000, 'a');
quiche::SimpleBufferAllocator allocator;
SerializedPacket packet(QuicPacketNumber(1), PACKET_1BYTE_PACKET_NUMBER,
buffer.data(), buffer.length(), false,
false);
packet.retransmittable_frames.push_back(QuicFrame(QuicWindowUpdateFrame()));
packet.retransmittable_frames.push_back(QuicFrame(QuicStreamFrame()));
QuicAckFrame ack_frame(InitAckFrame(1));
packet.nonretransmittable_frames.push_back(QuicFrame(&ack_frame));
packet.nonretransmittable_frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
std::unique_ptr<SerializedPacket> copy = absl::WrapUnique<SerializedPacket>(
CopySerializedPacket(packet, &allocator, true));
EXPECT_EQ(quic::QuicPacketNumber(1), copy->packet_number);
EXPECT_EQ(PACKET_1BYTE_PACKET_NUMBER, copy->packet_number_length);
ASSERT_EQ(2u, copy->retransmittable_frames.size());
EXPECT_EQ(WINDOW_UPDATE_FRAME, copy->retransmittable_frames[0].type);
EXPECT_EQ(STREAM_FRAME, copy->retransmittable_frames[1].type);
ASSERT_EQ(2u, copy->nonretransmittable_frames.size());
EXPECT_EQ(ACK_FRAME, copy->nonretransmittable_frames[0].type);
EXPECT_EQ(PADDING_FRAME, copy->nonretransmittable_frames[1].type);
EXPECT_EQ(1000u, copy->encrypted_length);
quiche::test::CompareCharArraysWithHexError(
"encrypted_buffer", copy->encrypted_buffer, copy->encrypted_length,
packet.encrypted_buffer, packet.encrypted_length);
std::unique_ptr<SerializedPacket> copy2 = absl::WrapUnique<SerializedPacket>(
CopySerializedPacket(packet, &allocator, false));
EXPECT_EQ(packet.encrypted_buffer, copy2->encrypted_buffer);
EXPECT_EQ(1000u, copy2->encrypted_length);
}
TEST_F(QuicPacketsTest, CloneReceivedPacket) {
char header[4] = "bar";
QuicReceivedPacket packet("foo", 3, QuicTime::Zero(), false, 0, true, header,
sizeof(header) - 1, false,
QuicEcnCodepoint::ECN_ECT1);
std::unique_ptr<QuicReceivedPacket> copy = packet.Clone();
EXPECT_EQ(packet.ecn_codepoint(), copy->ecn_codepoint());
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_packets.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_packets_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
12d35529-f1f7-471b-bef8-c74ef2f32ec8 | cpp | google/quiche | quic_config | quiche/quic/core/quic_config.cc | quiche/quic/core/quic_config_test.cc | #include "quiche/quic/core/quic_config.h"
#include <algorithm>
#include <cstring>
#include <limits>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include "absl/base/attributes.h"
#include "absl/strings/string_view.h"
#include "quiche/quic/core/crypto/crypto_handshake_message.h"
#include "quiche/quic/core/crypto/crypto_protocol.h"
#include "quiche/quic/core/quic_connection_id.h"
#include "quiche/quic/core/quic_constants.h"
#include "quiche/quic/core/quic_socket_address_coder.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/quic/platform/api/quic_socket_address.h"
namespace quic {
QuicErrorCode ReadUint32(const CryptoHandshakeMessage& msg, QuicTag tag,
QuicConfigPresence presence, uint32_t default_value,
uint32_t* out, std::string* error_details) {
QUICHE_DCHECK(error_details != nullptr);
QuicErrorCode error = msg.GetUint32(tag, out);
switch (error) {
case QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND:
if (presence == PRESENCE_REQUIRED) {
*error_details = "Missing " + QuicTagToString(tag);
break;
}
error = QUIC_NO_ERROR;
*out = default_value;
break;
case QUIC_NO_ERROR:
break;
default:
*error_details = "Bad " + QuicTagToString(tag);
break;
}
return error;
}
QuicConfigValue::QuicConfigValue(QuicTag tag, QuicConfigPresence presence)
: tag_(tag), presence_(presence) {}
QuicConfigValue::~QuicConfigValue() {}
QuicFixedUint32::QuicFixedUint32(QuicTag tag, QuicConfigPresence presence)
: QuicConfigValue(tag, presence),
has_send_value_(false),
has_receive_value_(false) {}
QuicFixedUint32::~QuicFixedUint32() {}
bool QuicFixedUint32::HasSendValue() const { return has_send_value_; }
uint32_t QuicFixedUint32::GetSendValue() const {
QUIC_BUG_IF(quic_bug_12743_1, !has_send_value_)
<< "No send value to get for tag:" << QuicTagToString(tag_);
return send_value_;
}
void QuicFixedUint32::SetSendValue(uint32_t value) {
has_send_value_ = true;
send_value_ = value;
}
bool QuicFixedUint32::HasReceivedValue() const { return has_receive_value_; }
uint32_t QuicFixedUint32::GetReceivedValue() const {
QUIC_BUG_IF(quic_bug_12743_2, !has_receive_value_)
<< "No receive value to get for tag:" << QuicTagToString(tag_);
return receive_value_;
}
void QuicFixedUint32::SetReceivedValue(uint32_t value) {
has_receive_value_ = true;
receive_value_ = value;
}
void QuicFixedUint32::ToHandshakeMessage(CryptoHandshakeMessage* out) const {
if (tag_ == 0) {
QUIC_BUG(quic_bug_12743_3)
<< "This parameter does not support writing to CryptoHandshakeMessage";
return;
}
if (has_send_value_) {
out->SetValue(tag_, send_value_);
}
}
QuicErrorCode QuicFixedUint32::ProcessPeerHello(
const CryptoHandshakeMessage& peer_hello, HelloType ,
std::string* error_details) {
QUICHE_DCHECK(error_details != nullptr);
if (tag_ == 0) {
*error_details =
"This parameter does not support reading from CryptoHandshakeMessage";
QUIC_BUG(quic_bug_10575_1) << *error_details;
return QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND;
}
QuicErrorCode error = peer_hello.GetUint32(tag_, &receive_value_);
switch (error) {
case QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND:
if (presence_ == PRESENCE_OPTIONAL) {
return QUIC_NO_ERROR;
}
*error_details = "Missing " + QuicTagToString(tag_);
break;
case QUIC_NO_ERROR:
has_receive_value_ = true;
break;
default:
*error_details = "Bad " + QuicTagToString(tag_);
break;
}
return error;
}
QuicFixedUint62::QuicFixedUint62(QuicTag name, QuicConfigPresence presence)
: QuicConfigValue(name, presence),
has_send_value_(false),
has_receive_value_(false) {}
QuicFixedUint62::~QuicFixedUint62() {}
bool QuicFixedUint62::HasSendValue() const { return has_send_value_; }
uint64_t QuicFixedUint62::GetSendValue() const {
if (!has_send_value_) {
QUIC_BUG(quic_bug_10575_2)
<< "No send value to get for tag:" << QuicTagToString(tag_);
return 0;
}
return send_value_;
}
void QuicFixedUint62::SetSendValue(uint64_t value) {
if (value > quiche::kVarInt62MaxValue) {
QUIC_BUG(quic_bug_10575_3) << "QuicFixedUint62 invalid value " << value;
value = quiche::kVarInt62MaxValue;
}
has_send_value_ = true;
send_value_ = value;
}
bool QuicFixedUint62::HasReceivedValue() const { return has_receive_value_; }
uint64_t QuicFixedUint62::GetReceivedValue() const {
if (!has_receive_value_) {
QUIC_BUG(quic_bug_10575_4)
<< "No receive value to get for tag:" << QuicTagToString(tag_);
return 0;
}
return receive_value_;
}
void QuicFixedUint62::SetReceivedValue(uint64_t value) {
has_receive_value_ = true;
receive_value_ = value;
}
void QuicFixedUint62::ToHandshakeMessage(CryptoHandshakeMessage* out) const {
if (!has_send_value_) {
return;
}
uint32_t send_value32;
if (send_value_ > std::numeric_limits<uint32_t>::max()) {
QUIC_BUG(quic_bug_10575_5) << "Attempting to send " << send_value_
<< " for tag:" << QuicTagToString(tag_);
send_value32 = std::numeric_limits<uint32_t>::max();
} else {
send_value32 = static_cast<uint32_t>(send_value_);
}
out->SetValue(tag_, send_value32);
}
QuicErrorCode QuicFixedUint62::ProcessPeerHello(
const CryptoHandshakeMessage& peer_hello, HelloType ,
std::string* error_details) {
QUICHE_DCHECK(error_details != nullptr);
uint32_t receive_value32;
QuicErrorCode error = peer_hello.GetUint32(tag_, &receive_value32);
receive_value_ = receive_value32;
switch (error) {
case QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND:
if (presence_ == PRESENCE_OPTIONAL) {
return QUIC_NO_ERROR;
}
*error_details = "Missing " + QuicTagToString(tag_);
break;
case QUIC_NO_ERROR:
has_receive_value_ = true;
break;
default:
*error_details = "Bad " + QuicTagToString(tag_);
break;
}
return error;
}
QuicFixedStatelessResetToken::QuicFixedStatelessResetToken(
QuicTag tag, QuicConfigPresence presence)
: QuicConfigValue(tag, presence),
has_send_value_(false),
has_receive_value_(false) {}
QuicFixedStatelessResetToken::~QuicFixedStatelessResetToken() {}
bool QuicFixedStatelessResetToken::HasSendValue() const {
return has_send_value_;
}
const StatelessResetToken& QuicFixedStatelessResetToken::GetSendValue() const {
QUIC_BUG_IF(quic_bug_12743_4, !has_send_value_)
<< "No send value to get for tag:" << QuicTagToString(tag_);
return send_value_;
}
void QuicFixedStatelessResetToken::SetSendValue(
const StatelessResetToken& value) {
has_send_value_ = true;
send_value_ = value;
}
bool QuicFixedStatelessResetToken::HasReceivedValue() const {
return has_receive_value_;
}
const StatelessResetToken& QuicFixedStatelessResetToken::GetReceivedValue()
const {
QUIC_BUG_IF(quic_bug_12743_5, !has_receive_value_)
<< "No receive value to get for tag:" << QuicTagToString(tag_);
return receive_value_;
}
void QuicFixedStatelessResetToken::SetReceivedValue(
const StatelessResetToken& value) {
has_receive_value_ = true;
receive_value_ = value;
}
void QuicFixedStatelessResetToken::ToHandshakeMessage(
CryptoHandshakeMessage* out) const {
if (has_send_value_) {
out->SetValue(tag_, send_value_);
}
}
QuicErrorCode QuicFixedStatelessResetToken::ProcessPeerHello(
const CryptoHandshakeMessage& peer_hello, HelloType ,
std::string* error_details) {
QUICHE_DCHECK(error_details != nullptr);
QuicErrorCode error =
peer_hello.GetStatelessResetToken(tag_, &receive_value_);
switch (error) {
case QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND:
if (presence_ == PRESENCE_OPTIONAL) {
return QUIC_NO_ERROR;
}
*error_details = "Missing " + QuicTagToString(tag_);
break;
case QUIC_NO_ERROR:
has_receive_value_ = true;
break;
default:
*error_details = "Bad " + QuicTagToString(tag_);
break;
}
return error;
}
QuicFixedTagVector::QuicFixedTagVector(QuicTag name,
QuicConfigPresence presence)
: QuicConfigValue(name, presence),
has_send_values_(false),
has_receive_values_(false) {}
QuicFixedTagVector::QuicFixedTagVector(const QuicFixedTagVector& other) =
default;
QuicFixedTagVector::~QuicFixedTagVector() {}
bool QuicFixedTagVector::HasSendValues() const { return has_send_values_; }
const QuicTagVector& QuicFixedTagVector::GetSendValues() const {
QUIC_BUG_IF(quic_bug_12743_6, !has_send_values_)
<< "No send values to get for tag:" << QuicTagToString(tag_);
return send_values_;
}
void QuicFixedTagVector::SetSendValues(const QuicTagVector& values) {
has_send_values_ = true;
send_values_ = values;
}
bool QuicFixedTagVector::HasReceivedValues() const {
return has_receive_values_;
}
const QuicTagVector& QuicFixedTagVector::GetReceivedValues() const {
QUIC_BUG_IF(quic_bug_12743_7, !has_receive_values_)
<< "No receive value to get for tag:" << QuicTagToString(tag_);
return receive_values_;
}
void QuicFixedTagVector::SetReceivedValues(const QuicTagVector& values) {
has_receive_values_ = true;
receive_values_ = values;
}
void QuicFixedTagVector::ToHandshakeMessage(CryptoHandshakeMessage* out) const {
if (has_send_values_) {
out->SetVector(tag_, send_values_);
}
}
QuicErrorCode QuicFixedTagVector::ProcessPeerHello(
const CryptoHandshakeMessage& peer_hello, HelloType ,
std::string* error_details) {
QUICHE_DCHECK(error_details != nullptr);
QuicTagVector values;
QuicErrorCode error = peer_hello.GetTaglist(tag_, &values);
switch (error) {
case QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND:
if (presence_ == PRESENCE_OPTIONAL) {
return QUIC_NO_ERROR;
}
*error_details = "Missing " + QuicTagToString(tag_);
break;
case QUIC_NO_ERROR:
QUIC_DVLOG(1) << "Received Connection Option tags from receiver.";
has_receive_values_ = true;
receive_values_.insert(receive_values_.end(), values.begin(),
values.end());
break;
default:
*error_details = "Bad " + QuicTagToString(tag_);
break;
}
return error;
}
QuicFixedSocketAddress::QuicFixedSocketAddress(QuicTag tag,
QuicConfigPresence presence)
: QuicConfigValue(tag, presence),
has_send_value_(false),
has_receive_value_(false) {}
QuicFixedSocketAddress::~QuicFixedSocketAddress() {}
bool QuicFixedSocketAddress::HasSendValue() const { return has_send_value_; }
const QuicSocketAddress& QuicFixedSocketAddress::GetSendValue() const {
QUIC_BUG_IF(quic_bug_12743_8, !has_send_value_)
<< "No send value to get for tag:" << QuicTagToString(tag_);
return send_value_;
}
void QuicFixedSocketAddress::SetSendValue(const QuicSocketAddress& value) {
has_send_value_ = true;
send_value_ = value;
}
void QuicFixedSocketAddress::ClearSendValue() {
has_send_value_ = false;
send_value_ = QuicSocketAddress();
}
bool QuicFixedSocketAddress::HasReceivedValue() const {
return has_receive_value_;
}
const QuicSocketAddress& QuicFixedSocketAddress::GetReceivedValue() const {
QUIC_BUG_IF(quic_bug_12743_9, !has_receive_value_)
<< "No receive value to get for tag:" << QuicTagToString(tag_);
return receive_value_;
}
void QuicFixedSocketAddress::SetReceivedValue(const QuicSocketAddress& value) {
has_receive_value_ = true;
receive_value_ = value;
}
void QuicFixedSocketAddress::ToHandshakeMessage(
CryptoHandshakeMessage* out) const {
if (has_send_value_) {
QuicSocketAddressCoder address_coder(send_value_);
out->SetStringPiece(tag_, address_coder.Encode());
}
}
QuicErrorCode QuicFixedSocketAddress::ProcessPeerHello(
const CryptoHandshakeMessage& peer_hello, HelloType ,
std::string* error_details) {
absl::string_view address;
if (!peer_hello.GetStringPiece(tag_, &address)) {
if (presence_ == PRESENCE_REQUIRED) {
*error_details = "Missing " + QuicTagToString(tag_);
return QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND;
}
} else {
QuicSocketAddressCoder address_coder;
if (address_coder.Decode(address.data(), address.length())) {
SetReceivedValue(
QuicSocketAddress(address_coder.ip(), address_coder.port()));
}
}
return QUIC_NO_ERROR;
}
QuicConfig::QuicConfig()
: negotiated_(false),
max_time_before_crypto_handshake_(QuicTime::Delta::Zero()),
max_idle_time_before_crypto_handshake_(QuicTime::Delta::Zero()),
max_undecryptable_packets_(0),
connection_options_(kCOPT, PRESENCE_OPTIONAL),
client_connection_options_(kCLOP, PRESENCE_OPTIONAL),
max_idle_timeout_to_send_(QuicTime::Delta::Infinite()),
max_bidirectional_streams_(kMIBS, PRESENCE_REQUIRED),
max_unidirectional_streams_(kMIUS, PRESENCE_OPTIONAL),
bytes_for_connection_id_(kTCID, PRESENCE_OPTIONAL),
initial_round_trip_time_us_(kIRTT, PRESENCE_OPTIONAL),
initial_max_stream_data_bytes_incoming_bidirectional_(0,
PRESENCE_OPTIONAL),
initial_max_stream_data_bytes_outgoing_bidirectional_(0,
PRESENCE_OPTIONAL),
initial_max_stream_data_bytes_unidirectional_(0, PRESENCE_OPTIONAL),
initial_stream_flow_control_window_bytes_(kSFCW, PRESENCE_OPTIONAL),
initial_session_flow_control_window_bytes_(kCFCW, PRESENCE_OPTIONAL),
connection_migration_disabled_(kNCMR, PRESENCE_OPTIONAL),
alternate_server_address_ipv6_(kASAD, PRESENCE_OPTIONAL),
alternate_server_address_ipv4_(kASAD, PRESENCE_OPTIONAL),
stateless_reset_token_(kSRST, PRESENCE_OPTIONAL),
max_ack_delay_ms_(kMAD, PRESENCE_OPTIONAL),
min_ack_delay_ms_(0, PRESENCE_OPTIONAL),
ack_delay_exponent_(kADE, PRESENCE_OPTIONAL),
max_udp_payload_size_(0, PRESENCE_OPTIONAL),
max_datagram_frame_size_(0, PRESENCE_OPTIONAL),
active_connection_id_limit_(0, PRESENCE_OPTIONAL) {
SetDefaults();
}
QuicConfig::QuicConfig(const QuicConfig& other) = default;
QuicConfig::~QuicConfig() {}
bool QuicConfig::SetInitialReceivedConnectionOptions(
const QuicTagVector& tags) {
if (HasReceivedConnectionOptions()) {
return false;
}
connection_options_.SetReceivedValues(tags);
return true;
}
void QuicConfig::SetConnectionOptionsToSend(
const QuicTagVector& connection_options) {
connection_options_.SetSendValues(connection_options);
}
void QuicConfig::AddConnectionOptionsToSend(
const QuicTagVector& connection_options) {
if (!connection_options_.HasSendValues()) {
SetConnectionOptionsToSend(connection_options);
return;
}
const QuicTagVector& existing_connection_options = SendConnectionOptions();
QuicTagVector connection_options_to_send;
connection_options_to_send.reserve(existing_connection_options.size() +
connection_options.size());
connection_options_to_send.assign(existing_connection_options.begin(),
existing_connection_options.end());
connection_options_to_send.insert(connection_options_to_send.end(),
connection_options.begin(),
connection_options.end());
SetConnectionOptionsToSend(connection_options_to_send);
}
void QuicConfig::SetGoogleHandshakeMessageToSend(std::string message) {
google_handshake_message_to_send_ = std::move(message);
}
const std::optional<std::string>&
QuicConfig::GetReceivedGoogleHandshakeMessage() const {
return received_google_handshake_message_;
}
bool QuicConfig::HasReceivedConnectionOptions() const {
return connection_options_.HasReceivedValues();
}
const QuicTagVector& QuicConfig::ReceivedConnectionOptions() const {
return connection_options_.GetReceivedValues();
}
bool QuicConfig::HasSendConnectionOptions() const {
return connection_options_.HasSendValues();
}
const QuicTagVector& QuicConfig::SendConnectionOptions() const {
return connection_options_.GetSendValues();
}
bool QuicConfig::HasClientSentConnectionOption(QuicTag tag,
Perspective perspective) const {
if (perspective == Perspective::IS_SERVER) {
if (HasReceivedConnectionOptions() &&
ContainsQuicTag(ReceivedConnectionOptions(), tag)) {
return true;
}
} else if (HasSendConnectionOptions() &&
ContainsQuicTag(SendConnectionOptions(), tag)) {
return true;
}
return false;
}
void QuicConfig::SetClientConnectionOptions(
const QuicTagVector& client_connection_options) {
client_connection_options_.SetSendValues(client_connection_options);
}
bool QuicConfig::HasClientRequestedIndependentOption(
QuicTag tag, Perspective perspective) const {
if (perspective == Perspective::IS_SERVER) {
return (HasReceivedConnectionOptions() &&
ContainsQuicTag(ReceivedConnectionOptions(), tag));
}
return (client_connection_options_.HasSendValues() &&
ContainsQuicTag(client_connection_options_.GetSendValues(), tag));
}
const QuicTagVector& QuicConfig::ClientRequestedIndependentOptions(
Perspective perspective) const {
static const QuicTagVector* no_options = new QuicTagVector;
if (perspective == Perspective::IS_SERVER) {
return HasReceivedConnectionOptions() ? ReceivedConnectionOptions()
: *no_options;
}
return client_connection_options_.HasSendValues()
? client_connection_options_.GetSendValues()
: *no_options;
}
void QuicConfig::SetIdleNetworkTimeout(QuicTime::Delta idle_network_timeout) {
if (idle_network_timeout.ToMicroseconds() <= 0) {
QUIC_BUG(quic_bug_10575_6)
<< "Invalid idle network timeout " << idle_network_timeout;
return;
}
max_idle_timeout_to_send_ = idle_network_timeout;
}
QuicTime::Delta QuicConfig::IdleNetworkTimeout() const {
if (!received_max_idle_timeout_.has_value()) {
return max_idle_timeout_to_send_;
}
return *received_max_idle_timeout_;
}
void QuicConfig::SetMaxBidirectionalStreamsToSend(uint32_t max_streams) {
max_bidirectional_streams_.SetSendValue(max_streams);
}
uint32_t QuicConfig::GetMaxBidirectionalStreamsToSend() const {
return max_bidirectional_streams_.GetSendValue();
}
bool QuicConfig::HasReceivedMaxBidirectionalStreams() const {
return max_bidirectional_streams_.HasReceivedValue();
}
uint32_t QuicConfig::ReceivedMaxBidirectionalStreams() const {
return max_bidirectional_streams_.GetReceivedValue();
}
void QuicConfig::SetMaxUnidirectionalStreamsToSend(uint32_t max_streams) {
max_unidirectional_streams_.SetSendValue(max_streams);
}
uint32_t QuicConfig::GetMaxUnidirectionalStreamsToSend() const {
return max_unidirectional_streams_.GetSendValue();
}
bool QuicConfig::HasReceivedMaxUnidirectionalStreams() const {
return max_unidirectional_streams_.HasReceivedValue();
}
uint32_t QuicConfig::ReceivedMaxUnidirectionalStreams() const {
return max_unidirectional_streams_.GetReceivedValue();
}
void QuicConfig::SetMaxAckDelayToSendMs(uint32_t max_ack_delay_ms) {
max_ack_delay_ms_.SetSendValue(max_ack_delay_ms);
}
uint32_t QuicConfig::GetMaxAckDelayToSendMs() const {
return max_ack_delay_ms_.GetSendValue();
}
bool QuicConfig::HasReceivedMaxAckDelayMs() const {
return max_ack_delay_ms_.HasReceivedValue();
}
uint32_t QuicConfig::ReceivedMaxAckDelayMs() const {
return max_ack_delay_ms_.GetReceivedValue();
}
void QuicConfig::SetMinAckDelayMs(uint32_t min_ack_delay_ms) {
min_ack_delay_ms_.SetSendValue(min_ack_delay_ms);
}
uint32_t QuicConfig::GetMinAckDelayToSendMs() const {
return min_ack_delay_ms_.GetSendValue();
}
bool QuicConfig::HasReceivedMinAckDelayMs() const {
return min_ack_delay_ms_.HasReceivedValue();
}
uint32_t QuicConfig::ReceivedMinAckDelayMs() const {
return min_ack_delay_ms_.GetReceivedValue();
}
void QuicConfig::SetAckDelayExponentToSend(uint32_t exponent) {
ack_delay_exponent_.SetSendValue(exponent);
}
uint32_t QuicConfig::GetAckDelayExponentToSend() const {
return ack_delay_exponent_.GetSendValue();
}
bool QuicConfig::HasReceivedAckDelayExponent() const {
return ack_delay_exponent_.HasReceivedValue();
}
uint32_t QuicConfig::ReceivedAckDelayExponent() const {
return ack_delay_exponent_.GetReceivedValue();
}
void QuicConfig::SetMaxPacketSizeToSend(uint64_t max_udp_payload_size) {
max_udp_payload_size_.SetSendValue(max_udp_payload_size);
}
uint64_t QuicConfig::GetMaxPacketSizeToSend() const {
return max_udp_payload_size_.GetSendValue();
}
bool QuicConfig::HasReceivedMaxPacketSize() const {
return max_udp_payload_size_.HasReceivedValue();
}
uint64_t QuicConfig::ReceivedMaxPacketSize() const {
return max_udp_payload_size_.GetReceivedValue();
}
void QuicConfig::SetMaxDatagramFrameSizeToSend(
uint64_t max_datagram_frame_size) {
max_datagram_frame_size_.SetSendValue(max_datagram_frame_size);
}
uint64_t QuicConfig::GetMaxDatagramFrameSizeToSend() const {
return max_datagram_frame_size_.GetSendValue();
}
bool QuicConfig::HasReceivedMaxDatagramFrameSize() const {
return max_datagram_frame_size_.HasReceivedValue();
}
uint64_t QuicConfig::ReceivedMaxDatagramFrameSize() const {
return max_datagram_frame_size_.GetReceivedValue();
}
void QuicConfig::SetActiveConnectionIdLimitToSend(
uint64_t active_connection_id_limit) {
active_connection_id_limit_.SetSendValue(active_connection_id_limit);
}
uint64_t QuicConfig::GetActiveConnectionIdLimitToSend() const {
return active_connection_id_limit_.GetSendValue();
}
bool QuicConfig::HasReceivedActiveConnectionIdLimit() const {
return active_connection_id_limit_.HasReceivedValue();
}
uint64_t QuicConfig::ReceivedActiveConnectionIdLimit() const {
return active_connection_id_limit_.GetReceivedValue();
}
bool QuicConfig::HasSetBytesForConnectionIdToSend() const {
return bytes_for_connection_id_.HasSendValue();
}
void QuicConfig::SetBytesForConnectionIdToSend(uint32_t bytes) {
bytes_for_connection_id_.SetSendValue(bytes);
}
bool QuicConfig::HasReceivedBytesForConnectionId() const {
return bytes_for_connection_id_.HasReceivedValue();
}
uint32_t QuicConfig::ReceivedBytesForConnectionId() const {
return bytes_for_connection_id_.GetReceivedValue();
}
void QuicConfig::SetInitialRoundTripTimeUsToSend(uint64_t rtt) {
initial_round_trip_time_us_.SetSendValue(rtt);
}
bool QuicConfig::HasReceivedInitialRoundTripTimeUs() const {
return initial_round_trip_time_us_.HasReceivedValue();
}
uint64_t QuicConfig::ReceivedInitialRoundTripTimeUs() const {
return initial_round_trip_time_us_.GetReceivedValue();
}
bool QuicConfig::HasInitialRoundTripTimeUsToSend() const {
return initial_round_trip_time_us_.HasSendValue();
}
uint64_t QuicConfig::GetInitialRoundTripTimeUsToSend() const {
return initial_round_trip_time_us_.GetSendValue();
}
void QuicConfig::SetInitialStreamFlowControlWindowToSend(
uint64_t window_bytes) {
if (window_bytes < kMinimumFlowControlSendWindow) {
QUIC_BUG(quic_bug_10575_7)
<< "Initial stream flow control receive window (" << window_bytes
<< ") cannot be set lower than minimum ("
<< kMinimumFlowControlSendWindow << ").";
window_bytes = kMinimumFlowControlSendWindow;
}
initial_stream_flow_control_window_bytes_.SetSendValue(window_bytes);
}
uint64_t QuicConfig::GetInitialStreamFlowControlWindowToSend() const {
return initial_stream_flow_control_window_bytes_.GetSendValue();
}
bool QuicConfig::HasReceivedInitialStreamFlowControlWindowBytes() const {
return initial_stream_flow_control_window_bytes_.HasReceivedValue();
}
uint64_t QuicConfig::ReceivedInitialStreamFlowControlWindowBytes() const {
return initial_stream_flow_control_window_bytes_.GetReceivedValue();
}
void QuicConfig::SetInitialMaxStreamDataBytesIncomingBidirectionalToSend(
uint64_t window_bytes) {
initial_max_stream_data_bytes_incoming_bidirectional_.SetSendValue(
window_bytes);
}
uint64_t QuicConfig::GetInitialMaxStreamDataBytesIncomingBidirectionalToSend()
const {
if (initial_max_stream_data_bytes_incoming_bidirectional_.HasSendValue()) {
return initial_max_stream_data_bytes_incoming_bidirectional_.GetSendValue();
}
return initial_stream_flow_control_window_bytes_.GetSendValue();
}
bool QuicConfig::HasReceivedInitialMaxStreamDataBytesIncomingBidirectional()
const {
return initial_max_stream_data_bytes_incoming_bidirectional_
.HasReceivedValue();
}
uint64_t QuicConfig::ReceivedInitialMaxStreamDataBytesIncomingBidirectional()
const {
return initial_max_stream_data_bytes_incoming_bidirectional_
.GetReceivedValue();
}
void QuicConfig::SetInitialMaxStreamDataBytesOutgoingBidirectionalToSend(
uint64_t window_bytes) {
initial_max_stream_data_bytes_outgoing_bidirectional_.SetSendValue(
window_bytes);
}
uint64_t QuicConfig::GetInitialMaxStreamDataBytesOutgoingBidirectionalToSend()
const {
if (initial_max_stream_data_bytes_outgoing_bidirectional_.HasSendValue()) {
return initial_max_stream_data_bytes_outgoing_bidirectional_.GetSendValue();
}
return initial_stream_flow_control_window_bytes_.GetSendValue();
}
bool QuicConfig::HasReceivedInitialMaxStreamDataBytesOutgoingBidirectional()
const {
return initial_max_stream_data_bytes_outgoing_bidirectional_
.HasReceivedValue();
}
uint64_t QuicConfig::ReceivedInitialMaxStreamDataBytesOutgoingBidirectional()
const {
return initial_max_stream_data_bytes_outgoing_bidirectional_
.GetReceivedValue();
}
void QuicConfig::SetInitialMaxStreamDataBytesUnidirectionalToSend(
uint64_t window_bytes) {
initial_max_stream_data_bytes_unidirectional_.SetSendValue(window_bytes);
}
uint64_t QuicConfig::GetInitialMaxStreamDataBytesUnidirectionalToSend() const {
if (initial_max_stream_data_bytes_unidirectional_.HasSendValue()) {
return initial_max_stream_data_bytes_unidirectional_.GetSendValue();
}
return initial_stream_flow_control_window_bytes_.GetSendValue();
}
bool QuicConfig::HasReceivedInitialMaxStreamDataBytesUnidirectional() const {
return initial_max_stream_data_bytes_unidirectional_.HasReceivedValue();
}
uint64_t QuicConfig::ReceivedInitialMaxStreamDataBytesUnidirectional() const {
return initial_max_stream_data_bytes_unidirectional_.GetReceivedValue();
}
void QuicConfig::SetInitialSessionFlowControlWindowToSend(
uint64_t window_bytes) {
if (window_bytes < kMinimumFlowControlSendWindow) {
QUIC_BUG(quic_bug_10575_8)
<< "Initial session flow control receive window (" << window_bytes
<< ") cannot be set lower than default ("
<< kMinimumFlowControlSendWindow << ").";
window_bytes = kMinimumFlowControlSendWindow;
}
initial_session_flow_control_window_bytes_.SetSendValue(window_bytes);
}
uint64_t QuicConfig::GetInitialSessionFlowControlWindowToSend() const {
return initial_session_flow_control_window_bytes_.GetSendValue();
}
bool QuicConfig::HasReceivedInitialSessionFlowControlWindowBytes() const {
return initial_session_flow_control_window_bytes_.HasReceivedValue();
}
uint64_t QuicConfig::ReceivedInitialSessionFlowControlWindowBytes() const {
return initial_session_flow_control_window_bytes_.GetReceivedValue();
}
void QuicConfig::SetDisableConnectionMigration() {
connection_migration_disabled_.SetSendValue(1);
}
bool QuicConfig::DisableConnectionMigration() const {
return connection_migration_disabled_.HasReceivedValue();
}
void QuicConfig::SetIPv6AlternateServerAddressToSend(
const QuicSocketAddress& alternate_server_address_ipv6) {
if (!alternate_server_address_ipv6.Normalized().host().IsIPv6()) {
QUIC_BUG(quic_bug_10575_9)
<< "Cannot use SetIPv6AlternateServerAddressToSend with "
<< alternate_server_address_ipv6;
return;
}
alternate_server_address_ipv6_.SetSendValue(alternate_server_address_ipv6);
}
bool QuicConfig::HasReceivedIPv6AlternateServerAddress() const {
return alternate_server_address_ipv6_.HasReceivedValue();
}
const QuicSocketAddress& QuicConfig::ReceivedIPv6AlternateServerAddress()
const {
return alternate_server_address_ipv6_.GetReceivedValue();
}
void QuicConfig::SetIPv4AlternateServerAddressToSend(
const QuicSocketAddress& alternate_server_address_ipv4) {
if (!alternate_server_address_ipv4.host().IsIPv4()) {
QUIC_BUG(quic_bug_10575_11)
<< "Cannot use SetIPv4AlternateServerAddressToSend with "
<< alternate_server_address_ipv4;
return;
}
alternate_server_address_ipv4_.SetSendValue(alternate_server_address_ipv4);
}
bool QuicConfig::HasReceivedIPv4AlternateServerAddress() const {
return alternate_server_address_ipv4_.HasReceivedValue();
}
const QuicSocketAddress& QuicConfig::ReceivedIPv4AlternateServerAddress()
const {
return alternate_server_address_ipv4_.GetReceivedValue();
}
void QuicConfig::SetPreferredAddressConnectionIdAndTokenToSend(
const QuicConnectionId& connection_id,
const StatelessResetToken& stateless_reset_token) {
if ((!alternate_server_address_ipv4_.HasSendValue() &&
!alternate_server_address_ipv6_.HasSendValue()) ||
preferred_address_connection_id_and_token_.has_value()) {
QUIC_BUG(quic_bug_10575_17)
<< "Can not send connection ID and token for preferred address";
return;
}
preferred_address_connection_id_and_token_ =
std::make_pair(connection_id, stateless_reset_token);
}
bool QuicConfig::HasReceivedPreferredAddressConnectionIdAndToken() const {
return (HasReceivedIPv6AlternateServerAddress() ||
HasReceivedIPv4AlternateServerAddress()) &&
preferred_address_connection_id_and_token_.has_value();
}
const std::pair<QuicConnectionId, StatelessResetToken>&
QuicConfig::ReceivedPreferredAddressConnectionIdAndToken() const {
QUICHE_DCHECK(HasReceivedPreferredAddressConnectionIdAndToken());
return *preferred_address_connection_id_and_token_;
}
void QuicConfig::SetOriginalConnectionIdToSend(
const QuicConnectionId& original_destination_connection_id) {
original_destination_connection_id_to_send_ =
original_destination_connection_id;
}
bool QuicConfig::HasReceivedOriginalConnectionId() const {
return received_original_destination_connection_id_.has_value();
}
QuicConnectionId QuicConfig::ReceivedOriginalConnectionId() const {
if (!HasReceivedOriginalConnectionId()) {
QUIC_BUG(quic_bug_10575_13) << "No received original connection ID";
return EmptyQuicConnectionId();
}
return *received_original_destination_connection_id_;
}
void QuicConfig::SetInitialSourceConnectionIdToSend(
const QuicConnectionId& initial_source_connection_id) {
initial_source_connection_id_to_send_ = initial_source_connection_id;
}
bool QuicConfig::HasReceivedInitialSourceConnectionId() const {
return received_initial_source_connection_id_.has_value();
}
QuicConnectionId QuicConfig::ReceivedInitialSourceConnectionId() const {
if (!HasReceivedInitialSourceConnectionId()) {
QUIC_BUG(quic_bug_10575_14) << "No received initial source connection ID";
return EmptyQuicConnectionId();
}
return *received_initial_source_connection_id_;
}
void QuicConfig::SetRetrySourceConnectionIdToSend(
const QuicConnectionId& retry_source_connection_id) {
retry_source_connection_id_to_send_ = retry_source_connection_id;
}
bool QuicConfig::HasReceivedRetrySourceConnectionId() const {
return received_retry_source_connection_id_.has_value();
}
QuicConnectionId QuicConfig::ReceivedRetrySourceConnectionId() const {
if (!HasReceivedRetrySourceConnectionId()) {
QUIC_BUG(quic_bug_10575_15) << "No received retry source connection ID";
return EmptyQuicConnectionId();
}
return *received_retry_source_connection_id_;
}
void QuicConfig::SetStatelessResetTokenToSend(
const StatelessResetToken& stateless_reset_token) {
stateless_reset_token_.SetSendValue(stateless_reset_token);
}
bool QuicConfig::HasStatelessResetTokenToSend() const {
return stateless_reset_token_.HasSendValue();
}
bool QuicConfig::HasReceivedStatelessResetToken() const {
return stateless_reset_token_.HasReceivedValue();
}
const StatelessResetToken& QuicConfig::ReceivedStatelessResetToken() const {
return stateless_reset_token_.GetReceivedValue();
}
bool QuicConfig::negotiated() const { return negotiated_; }
void QuicConfig::SetCreateSessionTagIndicators(QuicTagVector tags) {
create_session_tag_indicators_ = std::move(tags);
}
const QuicTagVector& QuicConfig::create_session_tag_indicators() const {
return create_session_tag_indicators_;
}
void QuicConfig::SetDefaults() {
SetIdleNetworkTimeout(QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
SetMaxBidirectionalStreamsToSend(kDefaultMaxStreamsPerConnection);
SetMaxUnidirectionalStreamsToSend(kDefaultMaxStreamsPerConnection);
max_time_before_crypto_handshake_ =
QuicTime::Delta::FromSeconds(kMaxTimeForCryptoHandshakeSecs);
max_idle_time_before_crypto_handshake_ =
QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs);
max_undecryptable_packets_ = kDefaultMaxUndecryptablePackets;
SetInitialStreamFlowControlWindowToSend(kMinimumFlowControlSendWindow);
SetInitialSessionFlowControlWindowToSend(kMinimumFlowControlSendWindow);
SetMaxAckDelayToSendMs(GetDefaultDelayedAckTimeMs());
SetAckDelayExponentToSend(kDefaultAckDelayExponent);
SetMaxPacketSizeToSend(kMaxIncomingPacketSize);
SetMaxDatagramFrameSizeToSend(kMaxAcceptedDatagramFrameSize);
SetReliableStreamReset(false);
}
void QuicConfig::ToHandshakeMessage(
CryptoHandshakeMessage* out, QuicTransportVersion transport_version) const {
QuicFixedUint32 max_idle_timeout_seconds(kICSL, PRESENCE_REQUIRED);
uint32_t max_idle_timeout_to_send_seconds =
max_idle_timeout_to_send_.ToSeconds();
if (received_max_idle_timeout_.has_value() &&
received_max_idle_timeout_->ToSeconds() <
max_idle_timeout_to_send_seconds) {
max_idle_timeout_to_send_seconds = received_max_idle_timeout_->ToSeconds();
}
max_idle_timeout_seconds.SetSendValue(max_idle_timeout_to_send_seconds);
max_idle_timeout_seconds.ToHandshakeMessage(out);
max_bidirectional_streams_.ToHandshakeMessage(out);
if (VersionHasIetfQuicFrames(transport_version)) {
max_unidirectional_streams_.ToHandshakeMessage(out);
ack_delay_exponent_.ToHandshakeMessage(out);
}
if (max_ack_delay_ms_.GetSendValue() != GetDefaultDelayedAckTimeMs()) {
max_ack_delay_ms_.ToHandshakeMessage(out);
}
bytes_for_connection_id_.ToHandshakeMessage(out);
initial_round_trip_time_us_.ToHandshakeMessage(out);
initial_stream_flow_control_window_bytes_.ToHandshakeMessage(out);
initial_session_flow_control_window_bytes_.ToHandshakeMessage(out);
connection_migration_disabled_.ToHandshakeMessage(out);
connection_options_.ToHandshakeMessage(out);
if (alternate_server_address_ipv6_.HasSendValue()) {
alternate_server_address_ipv6_.ToHandshakeMessage(out);
} else {
alternate_server_address_ipv4_.ToHandshakeMessage(out);
}
stateless_reset_token_.ToHandshakeMessage(out);
}
QuicErrorCode QuicConfig::ProcessPeerHello(
const CryptoHandshakeMessage& peer_hello, HelloType hello_type,
std::string* error_details) {
QUICHE_DCHECK(error_details != nullptr);
QuicErrorCode error = QUIC_NO_ERROR;
if (error == QUIC_NO_ERROR) {
QuicFixedUint32 max_idle_timeout_seconds(kICSL, PRESENCE_REQUIRED);
error = max_idle_timeout_seconds.ProcessPeerHello(peer_hello, hello_type,
error_details);
if (error == QUIC_NO_ERROR) {
if (max_idle_timeout_seconds.GetReceivedValue() >
max_idle_timeout_to_send_.ToSeconds()) {
if (hello_type == SERVER) {
error = QUIC_INVALID_NEGOTIATED_VALUE;
*error_details =
"Invalid value received for " + QuicTagToString(kICSL);
}
} else {
received_max_idle_timeout_ = QuicTime::Delta::FromSeconds(
max_idle_timeout_seconds.GetReceivedValue());
}
}
}
if (error == QUIC_NO_ERROR) {
error = max_bidirectional_streams_.ProcessPeerHello(peer_hello, hello_type,
error_details);
}
if (error == QUIC_NO_ERROR) {
error = max_unidirectional_streams_.ProcessPeerHello(peer_hello, hello_type,
error_details);
}
if (error == QUIC_NO_ERROR) {
error = bytes_for_connection_id_.ProcessPeerHello(peer_hello, hello_type,
error_details);
}
if (error == QUIC_NO_ERROR) {
error = initial_round_trip_time_us_.ProcessPeerHello(peer_hello, hello_type,
error_details);
}
if (error == QUIC_NO_ERROR) {
error = initial_stream_flow_control_window_bytes_.ProcessPeerHello(
peer_hello, hello_type, error_details);
}
if (error == QUIC_NO_ERROR) {
error = initial_session_flow_control_window_bytes_.ProcessPeerHello(
peer_hello, hello_type, error_details);
}
if (error == QUIC_NO_ERROR) {
error = connection_migration_disabled_.ProcessPeerHello(
peer_hello, hello_type, error_details);
}
if (error == QUIC_NO_ERROR) {
error = connection_options_.ProcessPeerHello(peer_hello, hello_type,
error_details);
}
if (error == QUIC_NO_ERROR) {
QuicFixedSocketAddress alternate_server_address(kASAD, PRESENCE_OPTIONAL);
error = alternate_server_address.ProcessPeerHello(peer_hello, hello_type,
error_details);
if (error == QUIC_NO_ERROR && alternate_server_address.HasReceivedValue()) {
const QuicSocketAddress& received_address =
alternate_server_address.GetReceivedValue();
if (received_address.host().IsIPv6()) {
alternate_server_address_ipv6_.SetReceivedValue(received_address);
} else if (received_address.host().IsIPv4()) {
alternate_server_address_ipv4_.SetReceivedValue(received_address);
}
}
}
if (error == QUIC_NO_ERROR) {
error = stateless_reset_token_.ProcessPeerHello(peer_hello, hello_type,
error_details);
}
if (error == QUIC_NO_ERROR) {
error = max_ack_delay_ms_.ProcessPeerHello(peer_hello, hello_type,
error_details);
}
if (error == QUIC_NO_ERROR) {
error = ack_delay_exponent_.ProcessPeerHello(peer_hello, hello_type,
error_details);
}
if (error == QUIC_NO_ERROR) {
negotiated_ = true;
}
return error;
}
bool QuicConfig::FillTransportParameters(TransportParameters* params) const {
if (original_destination_connection_id_to_send_.has_value()) {
params->original_destination_connection_id =
*original_destination_connection_id_to_send_;
}
params->max_idle_timeout_ms.set_value(
max_idle_timeout_to_send_.ToMilliseconds());
if (stateless_reset_token_.HasSendValue()) {
StatelessResetToken stateless_reset_token =
stateless_reset_token_.GetSendValue();
params->stateless_reset_token.assign(
reinterpret_cast<const char*>(&stateless_reset_token),
reinterpret_cast<const char*>(&stateless_reset_token) +
sizeof(stateless_reset_token));
}
params->max_udp_payload_size.set_value(GetMaxPacketSizeToSend());
params->max_datagram_frame_size.set_value(GetMaxDatagramFrameSizeToSend());
params->initial_max_data.set_value(
GetInitialSessionFlowControlWindowToSend());
params->initial_max_stream_data_bidi_local.set_value(
GetInitialMaxStreamDataBytesOutgoingBidirectionalToSend());
params->initial_max_stream_data_bidi_remote.set_value(
GetInitialMaxStreamDataBytesIncomingBidirectionalToSend());
params->initial_max_stream_data_uni.set_value(
GetInitialMaxStreamDataBytesUnidirectionalToSend());
params->initial_max_streams_bidi.set_value(
GetMaxBidirectionalStreamsToSend());
params->initial_max_streams_uni.set_value(
GetMaxUnidirectionalStreamsToSend());
params->max_ack_delay.set_value(GetMaxAckDelayToSendMs());
if (min_ack_delay_ms_.HasSendValue()) {
params->min_ack_delay_us.set_value(min_ack_delay_ms_.GetSendValue() *
kNumMicrosPerMilli);
}
params->ack_delay_exponent.set_value(GetAckDelayExponentToSend());
params->disable_active_migration =
connection_migration_disabled_.HasSendValue() &&
connection_migration_disabled_.GetSendValue() != 0;
if (alternate_server_address_ipv6_.HasSendValue() ||
alternate_server_address_ipv4_.HasSendValue()) {
TransportParameters::PreferredAddress preferred_address;
if (alternate_server_address_ipv6_.HasSendValue()) {
preferred_address.ipv6_socket_address =
alternate_server_address_ipv6_.GetSendValue();
}
if (alternate_server_address_ipv4_.HasSendValue()) {
preferred_address.ipv4_socket_address =
alternate_server_address_ipv4_.GetSendValue();
}
if (preferred_address_connection_id_and_token_) {
preferred_address.connection_id =
preferred_address_connection_id_and_token_->first;
auto* begin = reinterpret_cast<const char*>(
&preferred_address_connection_id_and_token_->second);
auto* end =
begin + sizeof(preferred_address_connection_id_and_token_->second);
preferred_address.stateless_reset_token.assign(begin, end);
}
params->preferred_address =
std::make_unique<TransportParameters::PreferredAddress>(
preferred_address);
}
if (active_connection_id_limit_.HasSendValue()) {
params->active_connection_id_limit.set_value(
active_connection_id_limit_.GetSendValue());
}
if (initial_source_connection_id_to_send_.has_value()) {
params->initial_source_connection_id =
*initial_source_connection_id_to_send_;
}
if (retry_source_connection_id_to_send_.has_value()) {
params->retry_source_connection_id = *retry_source_connection_id_to_send_;
}
if (initial_round_trip_time_us_.HasSendValue()) {
params->initial_round_trip_time_us.set_value(
initial_round_trip_time_us_.GetSendValue());
}
if (connection_options_.HasSendValues() &&
!connection_options_.GetSendValues().empty()) {
params->google_connection_options = connection_options_.GetSendValues();
}
if (google_handshake_message_to_send_.has_value()) {
params->google_handshake_message = google_handshake_message_to_send_;
}
params->reliable_stream_reset = reliable_stream_reset_;
params->custom_parameters = custom_transport_parameters_to_send_;
return true;
}
QuicErrorCode QuicConfig::ProcessTransportParameters(
const TransportParameters& params, bool is_resumption,
std::string* error_details) {
if (!is_resumption && params.original_destination_connection_id.has_value()) {
received_original_destination_connection_id_ =
*params.original_destination_connection_id;
}
if (params.max_idle_timeout_ms.value() > 0 &&
params.max_idle_timeout_ms.value() <
static_cast<uint64_t>(max_idle_timeout_to_send_.ToMilliseconds())) {
received_max_idle_timeout_ =
QuicTime::Delta::FromMilliseconds(params.max_idle_timeout_ms.value());
}
if (!is_resumption && !params.stateless_reset_token.empty()) {
StatelessResetToken stateless_reset_token;
if (params.stateless_reset_token.size() != sizeof(stateless_reset_token)) {
QUIC_BUG(quic_bug_10575_16) << "Bad stateless reset token length "
<< params.stateless_reset_token.size();
*error_details = "Bad stateless reset token length";
return QUIC_INTERNAL_ERROR;
}
memcpy(&stateless_reset_token, params.stateless_reset_token.data(),
params.stateless_reset_token.size());
stateless_reset_token_.SetReceivedValue(stateless_reset_token);
}
if (params.max_udp_payload_size.IsValid()) {
max_udp_payload_size_.SetReceivedValue(params.max_udp_payload_size.value());
}
if (params.max_datagram_frame_size.IsValid()) {
max_datagram_frame_size_.SetReceivedValue(
params.max_datagram_frame_size.value());
}
initial_session_flow_control_window_bytes_.SetReceivedValue(
params.initial_max_data.value());
max_bidirectional_streams_.SetReceivedValue(
std::min<uint64_t>(params.initial_max_streams_bidi.value(),
std::numeric_limits<uint32_t>::max()));
max_unidirectional_streams_.SetReceivedValue(
std::min<uint64_t>(params.initial_max_streams_uni.value(),
std::numeric_limits<uint32_t>::max()));
initial_max_stream_data_bytes_incoming_bidirectional_.SetReceivedValue(
params.initial_max_stream_data_bidi_local.value());
initial_max_stream_data_bytes_outgoing_bidirectional_.SetReceivedValue(
params.initial_max_stream_data_bidi_remote.value());
initial_max_stream_data_bytes_unidirectional_.SetReceivedValue(
params.initial_max_stream_data_uni.value());
if (!is_resumption) {
max_ack_delay_ms_.SetReceivedValue(params.max_ack_delay.value());
if (params.ack_delay_exponent.IsValid()) {
ack_delay_exponent_.SetReceivedValue(params.ack_delay_exponent.value());
}
if (params.preferred_address != nullptr) {
if (params.preferred_address->ipv6_socket_address.port() != 0) {
alternate_server_address_ipv6_.SetReceivedValue(
params.preferred_address->ipv6_socket_address);
}
if (params.preferred_address->ipv4_socket_address.port() != 0) {
alternate_server_address_ipv4_.SetReceivedValue(
params.preferred_address->ipv4_socket_address);
}
if (!params.preferred_address->connection_id.IsEmpty()) {
preferred_address_connection_id_and_token_ = std::make_pair(
params.preferred_address->connection_id,
*reinterpret_cast<const StatelessResetToken*>(
¶ms.preferred_address->stateless_reset_token.front()));
}
}
if (params.min_ack_delay_us.value() != 0) {
if (params.min_ack_delay_us.value() >
params.max_ack_delay.value() * kNumMicrosPerMilli) {
*error_details = "MinAckDelay is greater than MaxAckDelay.";
return IETF_QUIC_PROTOCOL_VIOLATION;
}
min_ack_delay_ms_.SetReceivedValue(params.min_ack_delay_us.value() /
kNumMicrosPerMilli);
}
}
if (params.disable_active_migration) {
connection_migration_disabled_.SetReceivedValue(1u);
}
active_connection_id_limit_.SetReceivedValue(
params.active_connection_id_limit.value());
if (!is_resumption) {
if (params.initial_source_connection_id.has_value()) {
received_initial_source_connection_id_ =
*params.initial_source_connection_id;
}
if (params.retry_source_connection_id.has_value()) {
received_retry_source_connection_id_ = *params.retry_source_connection_id;
}
}
if (params.initial_round_trip_time_us.value() > 0) {
initial_round_trip_time_us_.SetReceivedValue(
params.initial_round_trip_time_us.value());
}
if (params.google_connection_options.has_value()) {
connection_options_.SetReceivedValues(*params.google_connection_options);
}
if (params.google_handshake_message.has_value()) {
received_google_handshake_message_ = params.google_handshake_message;
}
received_custom_transport_parameters_ = params.custom_parameters;
if (reliable_stream_reset_) {
reliable_stream_reset_ = params.reliable_stream_reset;
}
if (!is_resumption) {
negotiated_ = true;
}
*error_details = "";
return QUIC_NO_ERROR;
}
void QuicConfig::ClearGoogleHandshakeMessage() {
google_handshake_message_to_send_.reset();
received_google_handshake_message_.reset();
}
std::optional<QuicSocketAddress> QuicConfig::GetPreferredAddressToSend(
quiche::IpAddressFamily address_family) const {
if (alternate_server_address_ipv6_.HasSendValue() &&
address_family == quiche::IpAddressFamily::IP_V6) {
return alternate_server_address_ipv6_.GetSendValue();
}
if (alternate_server_address_ipv4_.HasSendValue() &&
address_family == quiche::IpAddressFamily::IP_V4) {
return alternate_server_address_ipv4_.GetSendValue();
}
return std::nullopt;
}
void QuicConfig::SetIPv4AlternateServerAddressForDNat(
const QuicSocketAddress& alternate_server_address_ipv4_to_send,
const QuicSocketAddress& mapped_alternate_server_address_ipv4) {
SetIPv4AlternateServerAddressToSend(alternate_server_address_ipv4_to_send);
mapped_alternate_server_address_ipv4_ = mapped_alternate_server_address_ipv4;
}
void QuicConfig::SetIPv6AlternateServerAddressForDNat(
const QuicSocketAddress& alternate_server_address_ipv6_to_send,
const QuicSocketAddress& mapped_alternate_server_address_ipv6) {
SetIPv6AlternateServerAddressToSend(alternate_server_address_ipv6_to_send);
mapped_alternate_server_address_ipv6_ = mapped_alternate_server_address_ipv6;
}
std::optional<QuicSocketAddress> QuicConfig::GetMappedAlternativeServerAddress(
quiche::IpAddressFamily address_family) const {
if (mapped_alternate_server_address_ipv6_.has_value() &&
address_family == quiche::IpAddressFamily::IP_V6) {
return *mapped_alternate_server_address_ipv6_;
}
if (mapped_alternate_server_address_ipv4_.has_value() &&
address_family == quiche::IpAddressFamily::IP_V4) {
return *mapped_alternate_server_address_ipv4_;
}
return GetPreferredAddressToSend(address_family);
}
void QuicConfig::ClearAlternateServerAddressToSend(
quiche::IpAddressFamily address_family) {
if (address_family == quiche::IpAddressFamily::IP_V4) {
alternate_server_address_ipv4_.ClearSendValue();
} else if (address_family == quiche::IpAddressFamily::IP_V6) {
alternate_server_address_ipv6_.ClearSendValue();
}
}
bool QuicConfig::SupportsServerPreferredAddress(Perspective perspective) const {
return HasClientSentConnectionOption(kSPAD, perspective) ||
GetQuicFlag(quic_always_support_server_preferred_address);
}
void QuicConfig::SetReliableStreamReset(bool reliable_stream_reset) {
reliable_stream_reset_ = reliable_stream_reset;
}
bool QuicConfig::SupportsReliableStreamReset() const {
return reliable_stream_reset_;
}
} | #include "quiche/quic/core/quic_config.h"
#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/crypto/transport_parameters.h"
#include "quiche/quic/core/quic_constants.h"
#include "quiche/quic/core/quic_packets.h"
#include "quiche/quic/core/quic_time.h"
#include "quiche/quic/core/quic_utils.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_config_peer.h"
#include "quiche/quic/test_tools/quic_test_utils.h"
namespace quic {
namespace test {
namespace {
class QuicConfigTest : public QuicTestWithParam<ParsedQuicVersion> {
public:
QuicConfigTest() : version_(GetParam()) {}
protected:
ParsedQuicVersion version_;
QuicConfig config_;
};
INSTANTIATE_TEST_SUITE_P(QuicConfigTests, QuicConfigTest,
::testing::ValuesIn(AllSupportedVersions()),
::testing::PrintToStringParamName());
TEST_P(QuicConfigTest, SetDefaults) {
EXPECT_EQ(kMinimumFlowControlSendWindow,
config_.GetInitialStreamFlowControlWindowToSend());
EXPECT_EQ(kMinimumFlowControlSendWindow,
config_.GetInitialMaxStreamDataBytesIncomingBidirectionalToSend());
EXPECT_EQ(kMinimumFlowControlSendWindow,
config_.GetInitialMaxStreamDataBytesOutgoingBidirectionalToSend());
EXPECT_EQ(kMinimumFlowControlSendWindow,
config_.GetInitialMaxStreamDataBytesUnidirectionalToSend());
EXPECT_FALSE(config_.HasReceivedInitialStreamFlowControlWindowBytes());
EXPECT_FALSE(
config_.HasReceivedInitialMaxStreamDataBytesIncomingBidirectional());
EXPECT_FALSE(
config_.HasReceivedInitialMaxStreamDataBytesOutgoingBidirectional());
EXPECT_FALSE(config_.HasReceivedInitialMaxStreamDataBytesUnidirectional());
EXPECT_EQ(kMaxIncomingPacketSize, config_.GetMaxPacketSizeToSend());
EXPECT_FALSE(config_.HasReceivedMaxPacketSize());
}
TEST_P(QuicConfigTest, AutoSetIetfFlowControl) {
EXPECT_EQ(kMinimumFlowControlSendWindow,
config_.GetInitialStreamFlowControlWindowToSend());
EXPECT_EQ(kMinimumFlowControlSendWindow,
config_.GetInitialMaxStreamDataBytesIncomingBidirectionalToSend());
EXPECT_EQ(kMinimumFlowControlSendWindow,
config_.GetInitialMaxStreamDataBytesOutgoingBidirectionalToSend());
EXPECT_EQ(kMinimumFlowControlSendWindow,
config_.GetInitialMaxStreamDataBytesUnidirectionalToSend());
static const uint32_t kTestWindowSize = 1234567;
config_.SetInitialStreamFlowControlWindowToSend(kTestWindowSize);
EXPECT_EQ(kTestWindowSize, config_.GetInitialStreamFlowControlWindowToSend());
EXPECT_EQ(kTestWindowSize,
config_.GetInitialMaxStreamDataBytesIncomingBidirectionalToSend());
EXPECT_EQ(kTestWindowSize,
config_.GetInitialMaxStreamDataBytesOutgoingBidirectionalToSend());
EXPECT_EQ(kTestWindowSize,
config_.GetInitialMaxStreamDataBytesUnidirectionalToSend());
static const uint32_t kTestWindowSizeTwo = 2345678;
config_.SetInitialMaxStreamDataBytesIncomingBidirectionalToSend(
kTestWindowSizeTwo);
EXPECT_EQ(kTestWindowSize, config_.GetInitialStreamFlowControlWindowToSend());
EXPECT_EQ(kTestWindowSizeTwo,
config_.GetInitialMaxStreamDataBytesIncomingBidirectionalToSend());
EXPECT_EQ(kTestWindowSize,
config_.GetInitialMaxStreamDataBytesOutgoingBidirectionalToSend());
EXPECT_EQ(kTestWindowSize,
config_.GetInitialMaxStreamDataBytesUnidirectionalToSend());
}
TEST_P(QuicConfigTest, ToHandshakeMessage) {
if (version_.UsesTls()) {
return;
}
config_.SetInitialStreamFlowControlWindowToSend(
kInitialStreamFlowControlWindowForTest);
config_.SetInitialSessionFlowControlWindowToSend(
kInitialSessionFlowControlWindowForTest);
config_.SetIdleNetworkTimeout(QuicTime::Delta::FromSeconds(5));
CryptoHandshakeMessage msg;
config_.ToHandshakeMessage(&msg, version_.transport_version);
uint32_t value;
QuicErrorCode error = msg.GetUint32(kICSL, &value);
EXPECT_THAT(error, IsQuicNoError());
EXPECT_EQ(5u, value);
error = msg.GetUint32(kSFCW, &value);
EXPECT_THAT(error, IsQuicNoError());
EXPECT_EQ(kInitialStreamFlowControlWindowForTest, value);
error = msg.GetUint32(kCFCW, &value);
EXPECT_THAT(error, IsQuicNoError());
EXPECT_EQ(kInitialSessionFlowControlWindowForTest, value);
}
TEST_P(QuicConfigTest, ProcessClientHello) {
if (version_.UsesTls()) {
return;
}
const uint32_t kTestMaxAckDelayMs =
static_cast<uint32_t>(GetDefaultDelayedAckTimeMs() + 1);
QuicConfig client_config;
QuicTagVector cgst;
cgst.push_back(kQBIC);
client_config.SetIdleNetworkTimeout(
QuicTime::Delta::FromSeconds(2 * kMaximumIdleTimeoutSecs));
client_config.SetInitialRoundTripTimeUsToSend(10 * kNumMicrosPerMilli);
client_config.SetInitialStreamFlowControlWindowToSend(
2 * kInitialStreamFlowControlWindowForTest);
client_config.SetInitialSessionFlowControlWindowToSend(
2 * kInitialSessionFlowControlWindowForTest);
QuicTagVector copt;
copt.push_back(kTBBR);
client_config.SetConnectionOptionsToSend(copt);
client_config.SetMaxAckDelayToSendMs(kTestMaxAckDelayMs);
CryptoHandshakeMessage msg;
client_config.ToHandshakeMessage(&msg, version_.transport_version);
std::string error_details;
QuicTagVector initial_received_options;
initial_received_options.push_back(kIW50);
EXPECT_TRUE(
config_.SetInitialReceivedConnectionOptions(initial_received_options));
EXPECT_FALSE(
config_.SetInitialReceivedConnectionOptions(initial_received_options))
<< "You can only set initial options once.";
const QuicErrorCode error =
config_.ProcessPeerHello(msg, CLIENT, &error_details);
EXPECT_FALSE(
config_.SetInitialReceivedConnectionOptions(initial_received_options))
<< "You cannot set initial options after the hello.";
EXPECT_THAT(error, IsQuicNoError());
EXPECT_TRUE(config_.negotiated());
EXPECT_EQ(QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs),
config_.IdleNetworkTimeout());
EXPECT_EQ(10 * kNumMicrosPerMilli, config_.ReceivedInitialRoundTripTimeUs());
EXPECT_TRUE(config_.HasReceivedConnectionOptions());
EXPECT_EQ(2u, config_.ReceivedConnectionOptions().size());
EXPECT_EQ(config_.ReceivedConnectionOptions()[0], kIW50);
EXPECT_EQ(config_.ReceivedConnectionOptions()[1], kTBBR);
EXPECT_EQ(config_.ReceivedInitialStreamFlowControlWindowBytes(),
2 * kInitialStreamFlowControlWindowForTest);
EXPECT_EQ(config_.ReceivedInitialSessionFlowControlWindowBytes(),
2 * kInitialSessionFlowControlWindowForTest);
EXPECT_TRUE(config_.HasReceivedMaxAckDelayMs());
EXPECT_EQ(kTestMaxAckDelayMs, config_.ReceivedMaxAckDelayMs());
EXPECT_FALSE(
config_.HasReceivedInitialMaxStreamDataBytesIncomingBidirectional());
EXPECT_FALSE(
config_.HasReceivedInitialMaxStreamDataBytesOutgoingBidirectional());
EXPECT_FALSE(config_.HasReceivedInitialMaxStreamDataBytesUnidirectional());
}
TEST_P(QuicConfigTest, ProcessServerHello) {
if (version_.UsesTls()) {
return;
}
QuicIpAddress host;
host.FromString("127.0.3.1");
const QuicSocketAddress kTestServerAddress = QuicSocketAddress(host, 1234);
const StatelessResetToken kTestStatelessResetToken{
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f};
const uint32_t kTestMaxAckDelayMs =
static_cast<uint32_t>(GetDefaultDelayedAckTimeMs() + 1);
QuicConfig server_config;
QuicTagVector cgst;
cgst.push_back(kQBIC);
server_config.SetIdleNetworkTimeout(
QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs / 2));
server_config.SetInitialRoundTripTimeUsToSend(10 * kNumMicrosPerMilli);
server_config.SetInitialStreamFlowControlWindowToSend(
2 * kInitialStreamFlowControlWindowForTest);
server_config.SetInitialSessionFlowControlWindowToSend(
2 * kInitialSessionFlowControlWindowForTest);
server_config.SetIPv4AlternateServerAddressToSend(kTestServerAddress);
server_config.SetStatelessResetTokenToSend(kTestStatelessResetToken);
server_config.SetMaxAckDelayToSendMs(kTestMaxAckDelayMs);
CryptoHandshakeMessage msg;
server_config.ToHandshakeMessage(&msg, version_.transport_version);
std::string error_details;
const QuicErrorCode error =
config_.ProcessPeerHello(msg, SERVER, &error_details);
EXPECT_THAT(error, IsQuicNoError());
EXPECT_TRUE(config_.negotiated());
EXPECT_EQ(QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs / 2),
config_.IdleNetworkTimeout());
EXPECT_EQ(10 * kNumMicrosPerMilli, config_.ReceivedInitialRoundTripTimeUs());
EXPECT_EQ(config_.ReceivedInitialStreamFlowControlWindowBytes(),
2 * kInitialStreamFlowControlWindowForTest);
EXPECT_EQ(config_.ReceivedInitialSessionFlowControlWindowBytes(),
2 * kInitialSessionFlowControlWindowForTest);
EXPECT_TRUE(config_.HasReceivedIPv4AlternateServerAddress());
EXPECT_EQ(kTestServerAddress, config_.ReceivedIPv4AlternateServerAddress());
EXPECT_FALSE(config_.HasReceivedIPv6AlternateServerAddress());
EXPECT_TRUE(config_.HasReceivedStatelessResetToken());
EXPECT_EQ(kTestStatelessResetToken, config_.ReceivedStatelessResetToken());
EXPECT_TRUE(config_.HasReceivedMaxAckDelayMs());
EXPECT_EQ(kTestMaxAckDelayMs, config_.ReceivedMaxAckDelayMs());
EXPECT_FALSE(
config_.HasReceivedInitialMaxStreamDataBytesIncomingBidirectional());
EXPECT_FALSE(
config_.HasReceivedInitialMaxStreamDataBytesOutgoingBidirectional());
EXPECT_FALSE(config_.HasReceivedInitialMaxStreamDataBytesUnidirectional());
}
TEST_P(QuicConfigTest, MissingOptionalValuesInCHLO) {
if (version_.UsesTls()) {
return;
}
CryptoHandshakeMessage msg;
msg.SetValue(kICSL, 1);
msg.SetValue(kICSL, 1);
msg.SetValue(kMIBS, 1);
std::string error_details;
const QuicErrorCode error =
config_.ProcessPeerHello(msg, CLIENT, &error_details);
EXPECT_THAT(error, IsQuicNoError());
EXPECT_TRUE(config_.negotiated());
}
TEST_P(QuicConfigTest, MissingOptionalValuesInSHLO) {
if (version_.UsesTls()) {
return;
}
CryptoHandshakeMessage msg;
msg.SetValue(kICSL, 1);
msg.SetValue(kMIBS, 1);
std::string error_details;
const QuicErrorCode error =
config_.ProcessPeerHello(msg, SERVER, &error_details);
EXPECT_THAT(error, IsQuicNoError());
EXPECT_TRUE(config_.negotiated());
}
TEST_P(QuicConfigTest, MissingValueInCHLO) {
if (version_.UsesTls()) {
return;
}
CryptoHandshakeMessage msg;
std::string error_details;
const QuicErrorCode error =
config_.ProcessPeerHello(msg, CLIENT, &error_details);
EXPECT_THAT(error, IsError(QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND));
}
TEST_P(QuicConfigTest, MissingValueInSHLO) {
if (version_.UsesTls()) {
return;
}
CryptoHandshakeMessage msg;
std::string error_details;
const QuicErrorCode error =
config_.ProcessPeerHello(msg, SERVER, &error_details);
EXPECT_THAT(error, IsError(QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND));
}
TEST_P(QuicConfigTest, OutOfBoundSHLO) {
if (version_.UsesTls()) {
return;
}
QuicConfig server_config;
server_config.SetIdleNetworkTimeout(
QuicTime::Delta::FromSeconds(2 * kMaximumIdleTimeoutSecs));
CryptoHandshakeMessage msg;
server_config.ToHandshakeMessage(&msg, version_.transport_version);
std::string error_details;
const QuicErrorCode error =
config_.ProcessPeerHello(msg, SERVER, &error_details);
EXPECT_THAT(error, IsError(QUIC_INVALID_NEGOTIATED_VALUE));
}
TEST_P(QuicConfigTest, InvalidFlowControlWindow) {
QuicConfig config;
const uint64_t kInvalidWindow = kMinimumFlowControlSendWindow - 1;
EXPECT_QUIC_BUG(
config.SetInitialStreamFlowControlWindowToSend(kInvalidWindow),
"Initial stream flow control receive window");
EXPECT_EQ(kMinimumFlowControlSendWindow,
config.GetInitialStreamFlowControlWindowToSend());
}
TEST_P(QuicConfigTest, HasClientSentConnectionOption) {
if (version_.UsesTls()) {
return;
}
QuicConfig client_config;
QuicTagVector copt;
copt.push_back(kTBBR);
client_config.SetConnectionOptionsToSend(copt);
EXPECT_TRUE(client_config.HasClientSentConnectionOption(
kTBBR, Perspective::IS_CLIENT));
CryptoHandshakeMessage msg;
client_config.ToHandshakeMessage(&msg, version_.transport_version);
std::string error_details;
const QuicErrorCode error =
config_.ProcessPeerHello(msg, CLIENT, &error_details);
EXPECT_THAT(error, IsQuicNoError());
EXPECT_TRUE(config_.negotiated());
EXPECT_TRUE(config_.HasReceivedConnectionOptions());
EXPECT_EQ(1u, config_.ReceivedConnectionOptions().size());
EXPECT_TRUE(
config_.HasClientSentConnectionOption(kTBBR, Perspective::IS_SERVER));
}
TEST_P(QuicConfigTest, DontSendClientConnectionOptions) {
if (version_.UsesTls()) {
return;
}
QuicConfig client_config;
QuicTagVector copt;
copt.push_back(kTBBR);
client_config.SetClientConnectionOptions(copt);
CryptoHandshakeMessage msg;
client_config.ToHandshakeMessage(&msg, version_.transport_version);
std::string error_details;
const QuicErrorCode error =
config_.ProcessPeerHello(msg, CLIENT, &error_details);
EXPECT_THAT(error, IsQuicNoError());
EXPECT_TRUE(config_.negotiated());
EXPECT_FALSE(config_.HasReceivedConnectionOptions());
}
TEST_P(QuicConfigTest, HasClientRequestedIndependentOption) {
if (version_.UsesTls()) {
return;
}
QuicConfig client_config;
QuicTagVector client_opt;
client_opt.push_back(kRENO);
QuicTagVector copt;
copt.push_back(kTBBR);
client_config.SetClientConnectionOptions(client_opt);
client_config.SetConnectionOptionsToSend(copt);
EXPECT_TRUE(client_config.HasClientSentConnectionOption(
kTBBR, Perspective::IS_CLIENT));
EXPECT_TRUE(client_config.HasClientRequestedIndependentOption(
kRENO, Perspective::IS_CLIENT));
EXPECT_FALSE(client_config.HasClientRequestedIndependentOption(
kTBBR, Perspective::IS_CLIENT));
CryptoHandshakeMessage msg;
client_config.ToHandshakeMessage(&msg, version_.transport_version);
std::string error_details;
const QuicErrorCode error =
config_.ProcessPeerHello(msg, CLIENT, &error_details);
EXPECT_THAT(error, IsQuicNoError());
EXPECT_TRUE(config_.negotiated());
EXPECT_TRUE(config_.HasReceivedConnectionOptions());
EXPECT_EQ(1u, config_.ReceivedConnectionOptions().size());
EXPECT_FALSE(config_.HasClientRequestedIndependentOption(
kRENO, Perspective::IS_SERVER));
EXPECT_TRUE(config_.HasClientRequestedIndependentOption(
kTBBR, Perspective::IS_SERVER));
}
TEST_P(QuicConfigTest, IncomingLargeIdleTimeoutTransportParameter) {
if (!version_.UsesTls()) {
return;
}
config_.SetIdleNetworkTimeout(quic::QuicTime::Delta::FromSeconds(60));
TransportParameters params;
params.max_idle_timeout_ms.set_value(120000);
std::string error_details = "foobar";
EXPECT_THAT(config_.ProcessTransportParameters(
params, false, &error_details),
IsQuicNoError());
EXPECT_EQ("", error_details);
EXPECT_EQ(quic::QuicTime::Delta::FromSeconds(60),
config_.IdleNetworkTimeout());
}
TEST_P(QuicConfigTest, ReceivedInvalidMinAckDelayInTransportParameter) {
if (!version_.UsesTls()) {
return;
}
TransportParameters params;
params.max_ack_delay.set_value(25 );
params.min_ack_delay_us.set_value(25 * kNumMicrosPerMilli + 1);
std::string error_details = "foobar";
EXPECT_THAT(config_.ProcessTransportParameters(
params, false, &error_details),
IsError(IETF_QUIC_PROTOCOL_VIOLATION));
EXPECT_EQ("MinAckDelay is greater than MaxAckDelay.", error_details);
params.max_ack_delay.set_value(25 );
params.min_ack_delay_us.set_value(25 * kNumMicrosPerMilli);
EXPECT_THAT(config_.ProcessTransportParameters(
params, false, &error_details),
IsQuicNoError());
EXPECT_TRUE(error_details.empty());
}
TEST_P(QuicConfigTest, FillTransportParams) {
if (!version_.UsesTls()) {
return;
}
const std::string kFakeGoogleHandshakeMessage = "Fake handshake message";
config_.SetInitialMaxStreamDataBytesIncomingBidirectionalToSend(
2 * kMinimumFlowControlSendWindow);
config_.SetInitialMaxStreamDataBytesOutgoingBidirectionalToSend(
3 * kMinimumFlowControlSendWindow);
config_.SetInitialMaxStreamDataBytesUnidirectionalToSend(
4 * kMinimumFlowControlSendWindow);
config_.SetMaxPacketSizeToSend(kMaxPacketSizeForTest);
config_.SetMaxDatagramFrameSizeToSend(kMaxDatagramFrameSizeForTest);
config_.SetActiveConnectionIdLimitToSend(kActiveConnectionIdLimitForTest);
config_.SetOriginalConnectionIdToSend(TestConnectionId(0x1111));
config_.SetInitialSourceConnectionIdToSend(TestConnectionId(0x2222));
config_.SetRetrySourceConnectionIdToSend(TestConnectionId(0x3333));
config_.SetMinAckDelayMs(kDefaultMinAckDelayTimeMs);
config_.SetGoogleHandshakeMessageToSend(kFakeGoogleHandshakeMessage);
config_.SetReliableStreamReset(true);
QuicIpAddress host;
host.FromString("127.0.3.1");
QuicSocketAddress kTestServerAddress = QuicSocketAddress(host, 1234);
QuicConnectionId new_connection_id = TestConnectionId(5);
StatelessResetToken new_stateless_reset_token =
QuicUtils::GenerateStatelessResetToken(new_connection_id);
config_.SetIPv4AlternateServerAddressToSend(kTestServerAddress);
QuicSocketAddress kTestServerAddressV6 =
QuicSocketAddress(QuicIpAddress::Any6(), 1234);
config_.SetIPv6AlternateServerAddressToSend(kTestServerAddressV6);
config_.SetPreferredAddressConnectionIdAndTokenToSend(
new_connection_id, new_stateless_reset_token);
config_.ClearAlternateServerAddressToSend(quiche::IpAddressFamily::IP_V6);
EXPECT_TRUE(config_.GetPreferredAddressToSend(quiche::IpAddressFamily::IP_V4)
.has_value());
EXPECT_FALSE(config_.GetPreferredAddressToSend(quiche::IpAddressFamily::IP_V6)
.has_value());
TransportParameters params;
config_.FillTransportParameters(¶ms);
EXPECT_EQ(2 * kMinimumFlowControlSendWindow,
params.initial_max_stream_data_bidi_remote.value());
EXPECT_EQ(3 * kMinimumFlowControlSendWindow,
params.initial_max_stream_data_bidi_local.value());
EXPECT_EQ(4 * kMinimumFlowControlSendWindow,
params.initial_max_stream_data_uni.value());
EXPECT_EQ(static_cast<uint64_t>(kMaximumIdleTimeoutSecs * 1000),
params.max_idle_timeout_ms.value());
EXPECT_EQ(kMaxPacketSizeForTest, params.max_udp_payload_size.value());
EXPECT_EQ(kMaxDatagramFrameSizeForTest,
params.max_datagram_frame_size.value());
EXPECT_EQ(kActiveConnectionIdLimitForTest,
params.active_connection_id_limit.value());
ASSERT_TRUE(params.original_destination_connection_id.has_value());
EXPECT_EQ(TestConnectionId(0x1111),
params.original_destination_connection_id.value());
ASSERT_TRUE(params.initial_source_connection_id.has_value());
EXPECT_EQ(TestConnectionId(0x2222),
params.initial_source_connection_id.value());
ASSERT_TRUE(params.retry_source_connection_id.has_value());
EXPECT_EQ(TestConnectionId(0x3333),
params.retry_source_connection_id.value());
EXPECT_EQ(
static_cast<uint64_t>(kDefaultMinAckDelayTimeMs) * kNumMicrosPerMilli,
params.min_ack_delay_us.value());
EXPECT_EQ(params.preferred_address->ipv4_socket_address, kTestServerAddress);
EXPECT_EQ(params.preferred_address->ipv6_socket_address,
QuicSocketAddress(QuicIpAddress::Any6(), 0));
EXPECT_EQ(*reinterpret_cast<StatelessResetToken*>(
¶ms.preferred_address->stateless_reset_token.front()),
new_stateless_reset_token);
EXPECT_EQ(kFakeGoogleHandshakeMessage, params.google_handshake_message);
EXPECT_TRUE(params.reliable_stream_reset);
}
TEST_P(QuicConfigTest, DNATPreferredAddress) {
QuicIpAddress host_v4;
host_v4.FromString("127.0.3.1");
QuicSocketAddress server_address_v4 = QuicSocketAddress(host_v4, 1234);
QuicSocketAddress expected_server_address_v4 =
QuicSocketAddress(host_v4, 1235);
QuicIpAddress host_v6;
host_v6.FromString("2001:db8:0::1");
QuicSocketAddress server_address_v6 = QuicSocketAddress(host_v6, 1234);
QuicSocketAddress expected_server_address_v6 =
QuicSocketAddress(host_v6, 1235);
config_.SetIPv4AlternateServerAddressForDNat(server_address_v4,
expected_server_address_v4);
config_.SetIPv6AlternateServerAddressForDNat(server_address_v6,
expected_server_address_v6);
EXPECT_EQ(server_address_v4,
config_.GetPreferredAddressToSend(quiche::IpAddressFamily::IP_V4));
EXPECT_EQ(server_address_v6,
config_.GetPreferredAddressToSend(quiche::IpAddressFamily::IP_V6));
EXPECT_EQ(expected_server_address_v4,
config_.GetMappedAlternativeServerAddress(
quiche::IpAddressFamily::IP_V4));
EXPECT_EQ(expected_server_address_v6,
config_.GetMappedAlternativeServerAddress(
quiche::IpAddressFamily::IP_V6));
}
TEST_P(QuicConfigTest, FillTransportParamsNoV4PreferredAddress) {
if (!version_.UsesTls()) {
return;
}
QuicIpAddress host;
host.FromString("127.0.3.1");
QuicSocketAddress kTestServerAddress = QuicSocketAddress(host, 1234);
QuicConnectionId new_connection_id = TestConnectionId(5);
StatelessResetToken new_stateless_reset_token =
QuicUtils::GenerateStatelessResetToken(new_connection_id);
config_.SetIPv4AlternateServerAddressToSend(kTestServerAddress);
QuicSocketAddress kTestServerAddressV6 =
QuicSocketAddress(QuicIpAddress::Any6(), 1234);
config_.SetIPv6AlternateServerAddressToSend(kTestServerAddressV6);
config_.SetPreferredAddressConnectionIdAndTokenToSend(
new_connection_id, new_stateless_reset_token);
config_.ClearAlternateServerAddressToSend(quiche::IpAddressFamily::IP_V4);
EXPECT_FALSE(config_.GetPreferredAddressToSend(quiche::IpAddressFamily::IP_V4)
.has_value());
config_.ClearAlternateServerAddressToSend(quiche::IpAddressFamily::IP_V4);
TransportParameters params;
config_.FillTransportParameters(¶ms);
EXPECT_EQ(params.preferred_address->ipv4_socket_address,
QuicSocketAddress(QuicIpAddress::Any4(), 0));
EXPECT_EQ(params.preferred_address->ipv6_socket_address,
kTestServerAddressV6);
}
TEST_P(QuicConfigTest, SupportsServerPreferredAddress) {
SetQuicFlag(quic_always_support_server_preferred_address, true);
EXPECT_TRUE(config_.SupportsServerPreferredAddress(Perspective::IS_CLIENT));
EXPECT_TRUE(config_.SupportsServerPreferredAddress(Perspective::IS_SERVER));
SetQuicFlag(quic_always_support_server_preferred_address, false);
EXPECT_FALSE(config_.SupportsServerPreferredAddress(Perspective::IS_CLIENT));
EXPECT_FALSE(config_.SupportsServerPreferredAddress(Perspective::IS_SERVER));
QuicTagVector copt;
copt.push_back(kSPAD);
config_.SetConnectionOptionsToSend(copt);
EXPECT_TRUE(config_.SupportsServerPreferredAddress(Perspective::IS_CLIENT));
EXPECT_FALSE(config_.SupportsServerPreferredAddress(Perspective::IS_SERVER));
config_.SetInitialReceivedConnectionOptions(copt);
EXPECT_TRUE(config_.SupportsServerPreferredAddress(Perspective::IS_CLIENT));
EXPECT_TRUE(config_.SupportsServerPreferredAddress(Perspective::IS_SERVER));
}
TEST_P(QuicConfigTest, AddConnectionOptionsToSend) {
QuicTagVector copt;
copt.push_back(kNOIP);
copt.push_back(kFPPE);
config_.AddConnectionOptionsToSend(copt);
ASSERT_TRUE(config_.HasSendConnectionOptions());
EXPECT_TRUE(quic::ContainsQuicTag(config_.SendConnectionOptions(), kNOIP));
EXPECT_TRUE(quic::ContainsQuicTag(config_.SendConnectionOptions(), kFPPE));
copt.clear();
copt.push_back(kSPAD);
copt.push_back(kSPA2);
config_.AddConnectionOptionsToSend(copt);
ASSERT_EQ(4, config_.SendConnectionOptions().size());
EXPECT_TRUE(quic::ContainsQuicTag(config_.SendConnectionOptions(), kNOIP));
EXPECT_TRUE(quic::ContainsQuicTag(config_.SendConnectionOptions(), kFPPE));
EXPECT_TRUE(quic::ContainsQuicTag(config_.SendConnectionOptions(), kSPAD));
EXPECT_TRUE(quic::ContainsQuicTag(config_.SendConnectionOptions(), kSPA2));
}
TEST_P(QuicConfigTest, ProcessTransportParametersServer) {
if (!version_.UsesTls()) {
return;
}
const std::string kFakeGoogleHandshakeMessage = "Fake handshake message";
TransportParameters params;
params.initial_max_stream_data_bidi_local.set_value(
2 * kMinimumFlowControlSendWindow);
params.initial_max_stream_data_bidi_remote.set_value(
3 * kMinimumFlowControlSendWindow);
params.initial_max_stream_data_uni.set_value(4 *
kMinimumFlowControlSendWindow);
params.max_udp_payload_size.set_value(kMaxPacketSizeForTest);
params.max_datagram_frame_size.set_value(kMaxDatagramFrameSizeForTest);
params.initial_max_streams_bidi.set_value(kDefaultMaxStreamsPerConnection);
params.stateless_reset_token = CreateStatelessResetTokenForTest();
params.max_ack_delay.set_value(kMaxAckDelayForTest);
params.min_ack_delay_us.set_value(kMinAckDelayUsForTest);
params.ack_delay_exponent.set_value(kAckDelayExponentForTest);
params.active_connection_id_limit.set_value(kActiveConnectionIdLimitForTest);
params.original_destination_connection_id = TestConnectionId(0x1111);
params.initial_source_connection_id = TestConnectionId(0x2222);
params.retry_source_connection_id = TestConnectionId(0x3333);
params.google_handshake_message = kFakeGoogleHandshakeMessage;
std::string error_details;
EXPECT_THAT(config_.ProcessTransportParameters(
params, true, &error_details),
IsQuicNoError())
<< error_details;
EXPECT_FALSE(config_.negotiated());
ASSERT_TRUE(
config_.HasReceivedInitialMaxStreamDataBytesIncomingBidirectional());
EXPECT_EQ(2 * kMinimumFlowControlSendWindow,
config_.ReceivedInitialMaxStreamDataBytesIncomingBidirectional());
ASSERT_TRUE(
config_.HasReceivedInitialMaxStreamDataBytesOutgoingBidirectional());
EXPECT_EQ(3 * kMinimumFlowControlSendWindow,
config_.ReceivedInitialMaxStreamDataBytesOutgoingBidirectional());
ASSERT_TRUE(config_.HasReceivedInitialMaxStreamDataBytesUnidirectional());
EXPECT_EQ(4 * kMinimumFlowControlSendWindow,
config_.ReceivedInitialMaxStreamDataBytesUnidirectional());
ASSERT_TRUE(config_.HasReceivedMaxPacketSize());
EXPECT_EQ(kMaxPacketSizeForTest, config_.ReceivedMaxPacketSize());
ASSERT_TRUE(config_.HasReceivedMaxDatagramFrameSize());
EXPECT_EQ(kMaxDatagramFrameSizeForTest,
config_.ReceivedMaxDatagramFrameSize());
ASSERT_TRUE(config_.HasReceivedMaxBidirectionalStreams());
EXPECT_EQ(kDefaultMaxStreamsPerConnection,
config_.ReceivedMaxBidirectionalStreams());
EXPECT_FALSE(config_.DisableConnectionMigration());
EXPECT_FALSE(config_.HasReceivedStatelessResetToken());
EXPECT_FALSE(config_.HasReceivedMaxAckDelayMs());
EXPECT_FALSE(config_.HasReceivedAckDelayExponent());
EXPECT_FALSE(config_.HasReceivedMinAckDelayMs());
EXPECT_FALSE(config_.HasReceivedOriginalConnectionId());
EXPECT_FALSE(config_.HasReceivedInitialSourceConnectionId());
EXPECT_FALSE(config_.HasReceivedRetrySourceConnectionId());
params.initial_max_stream_data_bidi_local.set_value(
2 * kMinimumFlowControlSendWindow + 1);
params.initial_max_stream_data_bidi_remote.set_value(
4 * kMinimumFlowControlSendWindow);
params.initial_max_stream_data_uni.set_value(5 *
kMinimumFlowControlSendWindow);
params.max_udp_payload_size.set_value(2 * kMaxPacketSizeForTest);
params.max_datagram_frame_size.set_value(2 * kMaxDatagramFrameSizeForTest);
params.initial_max_streams_bidi.set_value(2 *
kDefaultMaxStreamsPerConnection);
params.disable_active_migration = true;
EXPECT_THAT(config_.ProcessTransportParameters(
params, false, &error_details),
IsQuicNoError())
<< error_details;
EXPECT_TRUE(config_.negotiated());
ASSERT_TRUE(
config_.HasReceivedInitialMaxStreamDataBytesIncomingBidirectional());
EXPECT_EQ(2 * kMinimumFlowControlSendWindow + 1,
config_.ReceivedInitialMaxStreamDataBytesIncomingBidirectional());
ASSERT_TRUE(
config_.HasReceivedInitialMaxStreamDataBytesOutgoingBidirectional());
EXPECT_EQ(4 * kMinimumFlowControlSendWindow,
config_.ReceivedInitialMaxStreamDataBytesOutgoingBidirectional());
ASSERT_TRUE(config_.HasReceivedInitialMaxStreamDataBytesUnidirectional());
EXPECT_EQ(5 * kMinimumFlowControlSendWindow,
config_.ReceivedInitialMaxStreamDataBytesUnidirectional());
ASSERT_TRUE(config_.HasReceivedMaxPacketSize());
EXPECT_EQ(2 * kMaxPacketSizeForTest, config_.ReceivedMaxPacketSize());
ASSERT_TRUE(config_.HasReceivedMaxDatagramFrameSize());
EXPECT_EQ(2 * kMaxDatagramFrameSizeForTest,
config_.ReceivedMaxDatagramFrameSize());
ASSERT_TRUE(config_.HasReceivedMaxBidirectionalStreams());
EXPECT_EQ(2 * kDefaultMaxStreamsPerConnection,
config_.ReceivedMaxBidirectionalStreams());
EXPECT_TRUE(config_.DisableConnectionMigration());
ASSERT_TRUE(config_.HasReceivedStatelessResetToken());
ASSERT_TRUE(config_.HasReceivedMaxAckDelayMs());
EXPECT_EQ(config_.ReceivedMaxAckDelayMs(), kMaxAckDelayForTest);
ASSERT_TRUE(config_.HasReceivedMinAckDelayMs());
EXPECT_EQ(config_.ReceivedMinAckDelayMs(),
kMinAckDelayUsForTest / kNumMicrosPerMilli);
ASSERT_TRUE(config_.HasReceivedAckDelayExponent());
EXPECT_EQ(config_.ReceivedAckDelayExponent(), kAckDelayExponentForTest);
ASSERT_TRUE(config_.HasReceivedActiveConnectionIdLimit());
EXPECT_EQ(config_.ReceivedActiveConnectionIdLimit(),
kActiveConnectionIdLimitForTest);
ASSERT_TRUE(config_.HasReceivedOriginalConnectionId());
EXPECT_EQ(config_.ReceivedOriginalConnectionId(), TestConnectionId(0x1111));
ASSERT_TRUE(config_.HasReceivedInitialSourceConnectionId());
EXPECT_EQ(config_.ReceivedInitialSourceConnectionId(),
TestConnectionId(0x2222));
ASSERT_TRUE(config_.HasReceivedRetrySourceConnectionId());
EXPECT_EQ(config_.ReceivedRetrySourceConnectionId(),
TestConnectionId(0x3333));
EXPECT_EQ(kFakeGoogleHandshakeMessage,
config_.GetReceivedGoogleHandshakeMessage());
}
TEST_P(QuicConfigTest, DisableMigrationTransportParameter) {
if (!version_.UsesTls()) {
return;
}
TransportParameters params;
params.disable_active_migration = true;
std::string error_details;
EXPECT_THAT(config_.ProcessTransportParameters(
params, false, &error_details),
IsQuicNoError());
EXPECT_TRUE(config_.DisableConnectionMigration());
}
TEST_P(QuicConfigTest, SendPreferredIPv4Address) {
if (!version_.UsesTls()) {
return;
}
EXPECT_FALSE(config_.HasReceivedPreferredAddressConnectionIdAndToken());
TransportParameters params;
QuicIpAddress host;
host.FromString("::ffff:192.0.2.128");
QuicSocketAddress kTestServerAddress = QuicSocketAddress(host, 1234);
QuicConnectionId new_connection_id = TestConnectionId(5);
StatelessResetToken new_stateless_reset_token =
QuicUtils::GenerateStatelessResetToken(new_connection_id);
auto preferred_address =
std::make_unique<TransportParameters::PreferredAddress>();
preferred_address->ipv6_socket_address = kTestServerAddress;
preferred_address->connection_id = new_connection_id;
preferred_address->stateless_reset_token.assign(
reinterpret_cast<const char*>(&new_stateless_reset_token),
reinterpret_cast<const char*>(&new_stateless_reset_token) +
sizeof(new_stateless_reset_token));
params.preferred_address = std::move(preferred_address);
std::string error_details;
EXPECT_THAT(config_.ProcessTransportParameters(
params, false, &error_details),
IsQuicNoError());
EXPECT_TRUE(config_.HasReceivedIPv6AlternateServerAddress());
EXPECT_EQ(config_.ReceivedIPv6AlternateServerAddress(), kTestServerAddress);
EXPECT_TRUE(config_.HasReceivedPreferredAddressConnectionIdAndToken());
const std::pair<QuicConnectionId, StatelessResetToken>&
preferred_address_connection_id_and_token =
config_.ReceivedPreferredAddressConnectionIdAndToken();
EXPECT_EQ(preferred_address_connection_id_and_token.first, new_connection_id);
EXPECT_EQ(preferred_address_connection_id_and_token.second,
new_stateless_reset_token);
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_config.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_config_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
b8b2ea9d-441c-403b-a467-54034bd1807f | cpp | google/quiche | quic_sent_packet_manager | quiche/quic/core/quic_sent_packet_manager.cc | quiche/quic/core/quic_sent_packet_manager_test.cc | #include "quiche/quic/core/quic_sent_packet_manager.h"
#include <algorithm>
#include <cstddef>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "quiche/quic/core/congestion_control/general_loss_algorithm.h"
#include "quiche/quic/core/congestion_control/pacing_sender.h"
#include "quiche/quic/core/congestion_control/send_algorithm_interface.h"
#include "quiche/quic/core/crypto/crypto_protocol.h"
#include "quiche/quic/core/frames/quic_ack_frequency_frame.h"
#include "quiche/quic/core/proto/cached_network_parameters_proto.h"
#include "quiche/quic/core/quic_connection_stats.h"
#include "quiche/quic/core/quic_constants.h"
#include "quiche/quic/core/quic_packet_number.h"
#include "quiche/quic/core/quic_transmission_info.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/print_elements.h"
namespace quic {
namespace {
static const int64_t kDefaultRetransmissionTimeMs = 500;
static const int64_t kMinHandshakeTimeoutMs = 10;
static const size_t kDefaultMaxTailLossProbes = 2;
static const float kPtoMultiplierWithoutRttSamples = 3;
inline bool ShouldForceRetransmission(TransmissionType transmission_type) {
return transmission_type == HANDSHAKE_RETRANSMISSION ||
transmission_type == PTO_RETRANSMISSION;
}
static const uint32_t kConservativeUnpacedBurst = 2;
static const uint32_t kNumProbeTimeoutsForPathDegradingDelay = 4;
}
#define ENDPOINT \
(unacked_packets_.perspective() == Perspective::IS_SERVER ? "Server: " \
: "Client: ")
QuicSentPacketManager::QuicSentPacketManager(
Perspective perspective, const QuicClock* clock, QuicRandom* random,
QuicConnectionStats* stats, CongestionControlType congestion_control_type)
: unacked_packets_(perspective),
clock_(clock),
random_(random),
stats_(stats),
debug_delegate_(nullptr),
network_change_visitor_(nullptr),
initial_congestion_window_(kInitialCongestionWindow),
loss_algorithm_(&uber_loss_algorithm_),
consecutive_crypto_retransmission_count_(0),
pending_timer_transmission_count_(0),
using_pacing_(false),
conservative_handshake_retransmits_(false),
largest_mtu_acked_(0),
handshake_finished_(false),
peer_max_ack_delay_(
QuicTime::Delta::FromMilliseconds(kDefaultPeerDelayedAckTimeMs)),
rtt_updated_(false),
acked_packets_iter_(last_ack_frame_.packets.rbegin()),
consecutive_pto_count_(0),
handshake_mode_disabled_(false),
handshake_packet_acked_(false),
zero_rtt_packet_acked_(false),
one_rtt_packet_acked_(false),
num_ptos_for_path_degrading_(kNumProbeTimeoutsForPathDegradingDelay),
ignore_pings_(false),
ignore_ack_delay_(false) {
SetSendAlgorithm(congestion_control_type);
}
QuicSentPacketManager::~QuicSentPacketManager() {}
void QuicSentPacketManager::SetFromConfig(const QuicConfig& config) {
const Perspective perspective = unacked_packets_.perspective();
if (config.HasReceivedInitialRoundTripTimeUs() &&
config.ReceivedInitialRoundTripTimeUs() > 0) {
if (!config.HasClientSentConnectionOption(kNRTT, perspective)) {
SetInitialRtt(QuicTime::Delta::FromMicroseconds(
config.ReceivedInitialRoundTripTimeUs()),
false);
}
} else if (config.HasInitialRoundTripTimeUsToSend() &&
config.GetInitialRoundTripTimeUsToSend() > 0) {
SetInitialRtt(QuicTime::Delta::FromMicroseconds(
config.GetInitialRoundTripTimeUsToSend()),
false);
}
if (config.HasReceivedMaxAckDelayMs()) {
peer_max_ack_delay_ =
QuicTime::Delta::FromMilliseconds(config.ReceivedMaxAckDelayMs());
}
if (GetQuicReloadableFlag(quic_can_send_ack_frequency) &&
perspective == Perspective::IS_SERVER) {
if (config.HasReceivedMinAckDelayMs()) {
peer_min_ack_delay_ =
QuicTime::Delta::FromMilliseconds(config.ReceivedMinAckDelayMs());
}
if (config.HasClientSentConnectionOption(kAFF1, perspective)) {
use_smoothed_rtt_in_ack_delay_ = true;
}
}
if (config.HasClientSentConnectionOption(kMAD0, perspective)) {
ignore_ack_delay_ = true;
}
if (config.HasClientRequestedIndependentOption(kTBBR, perspective)) {
SetSendAlgorithm(kBBR);
}
if (GetQuicReloadableFlag(quic_allow_client_enabled_bbr_v2) &&
config.HasClientRequestedIndependentOption(kB2ON, perspective)) {
QUIC_RELOADABLE_FLAG_COUNT(quic_allow_client_enabled_bbr_v2);
SetSendAlgorithm(kBBRv2);
}
if (config.HasClientRequestedIndependentOption(kRENO, perspective)) {
SetSendAlgorithm(kRenoBytes);
} else if (config.HasClientRequestedIndependentOption(kBYTE, perspective) ||
(GetQuicReloadableFlag(quic_default_to_bbr) &&
config.HasClientRequestedIndependentOption(kQBIC, perspective))) {
SetSendAlgorithm(kCubicBytes);
}
if (config.HasClientRequestedIndependentOption(kIW03, perspective)) {
initial_congestion_window_ = 3;
send_algorithm_->SetInitialCongestionWindowInPackets(3);
}
if (config.HasClientRequestedIndependentOption(kIW10, perspective)) {
initial_congestion_window_ = 10;
send_algorithm_->SetInitialCongestionWindowInPackets(10);
}
if (config.HasClientRequestedIndependentOption(kIW20, perspective)) {
initial_congestion_window_ = 20;
send_algorithm_->SetInitialCongestionWindowInPackets(20);
}
if (config.HasClientRequestedIndependentOption(kIW50, perspective)) {
initial_congestion_window_ = 50;
send_algorithm_->SetInitialCongestionWindowInPackets(50);
}
if (config.HasClientRequestedIndependentOption(kBWS5, perspective)) {
initial_congestion_window_ = 10;
send_algorithm_->SetInitialCongestionWindowInPackets(10);
}
if (config.HasClientRequestedIndependentOption(kIGNP, perspective)) {
ignore_pings_ = true;
}
using_pacing_ = !GetQuicFlag(quic_disable_pacing_for_perf_tests);
if (config.HasClientRequestedIndependentOption(kILD0, perspective)) {
uber_loss_algorithm_.SetReorderingShift(kDefaultIetfLossDelayShift);
uber_loss_algorithm_.DisableAdaptiveReorderingThreshold();
}
if (config.HasClientRequestedIndependentOption(kILD1, perspective)) {
uber_loss_algorithm_.SetReorderingShift(kDefaultLossDelayShift);
uber_loss_algorithm_.DisableAdaptiveReorderingThreshold();
}
if (config.HasClientRequestedIndependentOption(kILD2, perspective)) {
uber_loss_algorithm_.EnableAdaptiveReorderingThreshold();
uber_loss_algorithm_.SetReorderingShift(kDefaultIetfLossDelayShift);
}
if (config.HasClientRequestedIndependentOption(kILD3, perspective)) {
uber_loss_algorithm_.SetReorderingShift(kDefaultLossDelayShift);
uber_loss_algorithm_.EnableAdaptiveReorderingThreshold();
}
if (config.HasClientRequestedIndependentOption(kILD4, perspective)) {
uber_loss_algorithm_.SetReorderingShift(kDefaultLossDelayShift);
uber_loss_algorithm_.EnableAdaptiveReorderingThreshold();
uber_loss_algorithm_.EnableAdaptiveTimeThreshold();
}
if (config.HasClientRequestedIndependentOption(kRUNT, perspective)) {
uber_loss_algorithm_.DisablePacketThresholdForRuntPackets();
}
if (config.HasClientSentConnectionOption(kCONH, perspective)) {
conservative_handshake_retransmits_ = true;
}
if (config.HasClientSentConnectionOption(kRNIB, perspective)) {
pacing_sender_.set_remove_non_initial_burst();
}
send_algorithm_->SetFromConfig(config, perspective);
loss_algorithm_->SetFromConfig(config, perspective);
if (network_change_visitor_ != nullptr) {
network_change_visitor_->OnCongestionChange();
}
if (debug_delegate_ != nullptr) {
DebugDelegate::SendParameters parameters;
parameters.congestion_control_type =
send_algorithm_->GetCongestionControlType();
parameters.use_pacing = using_pacing_;
parameters.initial_congestion_window = initial_congestion_window_;
debug_delegate_->OnConfigProcessed(parameters);
}
}
void QuicSentPacketManager::ApplyConnectionOptions(
const QuicTagVector& connection_options) {
std::optional<CongestionControlType> cc_type;
if (ContainsQuicTag(connection_options, kB2ON)) {
cc_type = kBBRv2;
} else if (ContainsQuicTag(connection_options, kTBBR)) {
cc_type = kBBR;
} else if (ContainsQuicTag(connection_options, kRENO)) {
cc_type = kRenoBytes;
} else if (ContainsQuicTag(connection_options, kQBIC)) {
cc_type = kCubicBytes;
}
if (cc_type.has_value()) {
SetSendAlgorithm(*cc_type);
}
send_algorithm_->ApplyConnectionOptions(connection_options);
}
void QuicSentPacketManager::ResumeConnectionState(
const CachedNetworkParameters& cached_network_params,
bool max_bandwidth_resumption) {
QuicBandwidth bandwidth = QuicBandwidth::FromBytesPerSecond(
max_bandwidth_resumption
? cached_network_params.max_bandwidth_estimate_bytes_per_second()
: cached_network_params.bandwidth_estimate_bytes_per_second());
QuicTime::Delta rtt =
QuicTime::Delta::FromMilliseconds(cached_network_params.min_rtt_ms());
SendAlgorithmInterface::NetworkParams params(
bandwidth, rtt, false);
params.is_rtt_trusted = true;
AdjustNetworkParameters(params);
}
void QuicSentPacketManager::AdjustNetworkParameters(
const SendAlgorithmInterface::NetworkParams& params) {
const QuicBandwidth& bandwidth = params.bandwidth;
const QuicTime::Delta& rtt = params.rtt;
if (!rtt.IsZero()) {
if (params.is_rtt_trusted) {
SetInitialRtt(rtt, true);
} else if (rtt_stats_.initial_rtt() ==
QuicTime::Delta::FromMilliseconds(kInitialRttMs)) {
SetInitialRtt(rtt, false);
}
}
const QuicByteCount old_cwnd = send_algorithm_->GetCongestionWindow();
if (GetQuicReloadableFlag(quic_conservative_bursts) && using_pacing_ &&
!bandwidth.IsZero()) {
QUIC_RELOADABLE_FLAG_COUNT(quic_conservative_bursts);
pacing_sender_.SetBurstTokens(kConservativeUnpacedBurst);
}
send_algorithm_->AdjustNetworkParameters(params);
if (debug_delegate_ != nullptr) {
debug_delegate_->OnAdjustNetworkParameters(
bandwidth, rtt.IsZero() ? rtt_stats_.MinOrInitialRtt() : rtt, old_cwnd,
send_algorithm_->GetCongestionWindow());
}
}
void QuicSentPacketManager::SetLossDetectionTuner(
std::unique_ptr<LossDetectionTunerInterface> tuner) {
uber_loss_algorithm_.SetLossDetectionTuner(std::move(tuner));
}
void QuicSentPacketManager::OnConfigNegotiated() {
loss_algorithm_->OnConfigNegotiated();
}
void QuicSentPacketManager::OnConnectionClosed() {
loss_algorithm_->OnConnectionClosed();
}
void QuicSentPacketManager::SetHandshakeConfirmed() {
if (!handshake_finished_) {
handshake_finished_ = true;
NeuterHandshakePackets();
}
}
void QuicSentPacketManager::PostProcessNewlyAckedPackets(
QuicPacketNumber ack_packet_number, EncryptionLevel ack_decrypted_level,
const QuicAckFrame& ack_frame, QuicTime ack_receive_time, bool rtt_updated,
QuicByteCount prior_bytes_in_flight,
std::optional<QuicEcnCounts> ecn_counts) {
unacked_packets_.NotifyAggregatedStreamFrameAcked(
last_ack_frame_.ack_delay_time);
InvokeLossDetection(ack_receive_time);
MaybeInvokeCongestionEvent(
rtt_updated, prior_bytes_in_flight, ack_receive_time, ecn_counts,
peer_ack_ecn_counts_[QuicUtils::GetPacketNumberSpace(
ack_decrypted_level)]);
unacked_packets_.RemoveObsoletePackets();
sustained_bandwidth_recorder_.RecordEstimate(
send_algorithm_->InRecovery(), send_algorithm_->InSlowStart(),
send_algorithm_->BandwidthEstimate(), ack_receive_time, clock_->WallNow(),
rtt_stats_.smoothed_rtt());
if (rtt_updated) {
if (consecutive_pto_count_ >
stats_->max_consecutive_rto_with_forward_progress) {
stats_->max_consecutive_rto_with_forward_progress =
consecutive_pto_count_;
}
consecutive_pto_count_ = 0;
consecutive_crypto_retransmission_count_ = 0;
}
if (debug_delegate_ != nullptr) {
debug_delegate_->OnIncomingAck(
ack_packet_number, ack_decrypted_level, ack_frame, ack_receive_time,
LargestAcked(ack_frame), rtt_updated, GetLeastUnacked());
}
last_ack_frame_.packets.RemoveUpTo(unacked_packets_.GetLeastUnacked());
last_ack_frame_.received_packet_times.clear();
}
void QuicSentPacketManager::MaybeInvokeCongestionEvent(
bool rtt_updated, QuicByteCount prior_in_flight, QuicTime event_time,
std::optional<QuicEcnCounts> ecn_counts,
const QuicEcnCounts& previous_counts) {
if (!rtt_updated && packets_acked_.empty() && packets_lost_.empty()) {
return;
}
const bool overshooting_detected =
stats_->overshooting_detected_with_network_parameters_adjusted;
QuicPacketCount newly_acked_ect = 0, newly_acked_ce = 0;
if (ecn_counts.has_value()) {
QUICHE_DCHECK(GetQuicRestartFlag(quic_support_ect1));
newly_acked_ect = ecn_counts->ect1 - previous_counts.ect1;
if (newly_acked_ect == 0) {
newly_acked_ect = ecn_counts->ect0 - previous_counts.ect0;
} else {
QUIC_BUG_IF(quic_bug_518619343_04,
ecn_counts->ect0 - previous_counts.ect0)
<< "Sent ECT(0) and ECT(1) newly acked in the same ACK.";
}
newly_acked_ce = ecn_counts->ce - previous_counts.ce;
}
if (using_pacing_) {
pacing_sender_.OnCongestionEvent(rtt_updated, prior_in_flight, event_time,
packets_acked_, packets_lost_,
newly_acked_ect, newly_acked_ce);
} else {
send_algorithm_->OnCongestionEvent(rtt_updated, prior_in_flight, event_time,
packets_acked_, packets_lost_,
newly_acked_ect, newly_acked_ce);
}
if (debug_delegate_ != nullptr && !overshooting_detected &&
stats_->overshooting_detected_with_network_parameters_adjusted) {
debug_delegate_->OnOvershootingDetected();
}
packets_acked_.clear();
packets_lost_.clear();
if (network_change_visitor_ != nullptr) {
network_change_visitor_->OnCongestionChange();
}
}
void QuicSentPacketManager::MarkInitialPacketsForRetransmission() {
if (unacked_packets_.empty()) {
return;
}
QuicPacketNumber packet_number = unacked_packets_.GetLeastUnacked();
QuicPacketNumber largest_sent_packet = unacked_packets_.largest_sent_packet();
for (; packet_number <= largest_sent_packet; ++packet_number) {
QuicTransmissionInfo* transmission_info =
unacked_packets_.GetMutableTransmissionInfo(packet_number);
if (transmission_info->encryption_level == ENCRYPTION_INITIAL) {
if (transmission_info->in_flight) {
unacked_packets_.RemoveFromInFlight(transmission_info);
}
if (unacked_packets_.HasRetransmittableFrames(*transmission_info)) {
MarkForRetransmission(packet_number, ALL_INITIAL_RETRANSMISSION);
}
}
}
}
void QuicSentPacketManager::MarkZeroRttPacketsForRetransmission() {
if (unacked_packets_.empty()) {
return;
}
QuicPacketNumber packet_number = unacked_packets_.GetLeastUnacked();
QuicPacketNumber largest_sent_packet = unacked_packets_.largest_sent_packet();
for (; packet_number <= largest_sent_packet; ++packet_number) {
QuicTransmissionInfo* transmission_info =
unacked_packets_.GetMutableTransmissionInfo(packet_number);
if (transmission_info->encryption_level == ENCRYPTION_ZERO_RTT) {
if (transmission_info->in_flight) {
unacked_packets_.RemoveFromInFlight(transmission_info);
}
if (unacked_packets_.HasRetransmittableFrames(*transmission_info)) {
MarkForRetransmission(packet_number, ALL_ZERO_RTT_RETRANSMISSION);
}
}
}
}
void QuicSentPacketManager::NeuterUnencryptedPackets() {
for (QuicPacketNumber packet_number :
unacked_packets_.NeuterUnencryptedPackets()) {
send_algorithm_->OnPacketNeutered(packet_number);
}
if (handshake_mode_disabled_) {
consecutive_pto_count_ = 0;
uber_loss_algorithm_.ResetLossDetection(INITIAL_DATA);
}
}
void QuicSentPacketManager::NeuterHandshakePackets() {
for (QuicPacketNumber packet_number :
unacked_packets_.NeuterHandshakePackets()) {
send_algorithm_->OnPacketNeutered(packet_number);
}
if (handshake_mode_disabled_) {
consecutive_pto_count_ = 0;
uber_loss_algorithm_.ResetLossDetection(HANDSHAKE_DATA);
}
}
bool QuicSentPacketManager::ShouldAddMaxAckDelay(
PacketNumberSpace space) const {
return !supports_multiple_packet_number_spaces() || space == APPLICATION_DATA;
}
QuicTime QuicSentPacketManager::GetEarliestPacketSentTimeForPto(
PacketNumberSpace* packet_number_space) const {
QUICHE_DCHECK(supports_multiple_packet_number_spaces());
QuicTime earliest_sent_time = QuicTime::Zero();
for (int8_t i = 0; i < NUM_PACKET_NUMBER_SPACES; ++i) {
const QuicTime sent_time = unacked_packets_.GetLastInFlightPacketSentTime(
static_cast<PacketNumberSpace>(i));
if (!handshake_finished_ && i == APPLICATION_DATA) {
continue;
}
if (!sent_time.IsInitialized() || (earliest_sent_time.IsInitialized() &&
earliest_sent_time <= sent_time)) {
continue;
}
earliest_sent_time = sent_time;
*packet_number_space = static_cast<PacketNumberSpace>(i);
}
return earliest_sent_time;
}
void QuicSentPacketManager::MarkForRetransmission(
QuicPacketNumber packet_number, TransmissionType transmission_type) {
QuicTransmissionInfo* transmission_info =
unacked_packets_.GetMutableTransmissionInfo(packet_number);
QUIC_BUG_IF(quic_bug_12552_2, transmission_type != LOSS_RETRANSMISSION &&
!unacked_packets_.HasRetransmittableFrames(
*transmission_info))
<< "packet number " << packet_number
<< " transmission_type: " << transmission_type << " transmission_info "
<< transmission_info->DebugString();
if (ShouldForceRetransmission(transmission_type)) {
if (!unacked_packets_.RetransmitFrames(
QuicFrames(transmission_info->retransmittable_frames),
transmission_type)) {
QUIC_CODE_COUNT(quic_retransmit_frames_failed);
return;
}
QUIC_CODE_COUNT(quic_retransmit_frames_succeeded);
} else {
unacked_packets_.NotifyFramesLost(*transmission_info, transmission_type);
if (!transmission_info->retransmittable_frames.empty()) {
if (transmission_type == LOSS_RETRANSMISSION) {
transmission_info->first_sent_after_loss =
unacked_packets_.largest_sent_packet() + 1;
} else {
transmission_info->first_sent_after_loss.Clear();
}
}
}
transmission_info =
unacked_packets_.GetMutableTransmissionInfo(packet_number);
transmission_info->state =
QuicUtils::RetransmissionTypeToPacketState(transmission_type);
}
void QuicSentPacketManager::RecordOneSpuriousRetransmission(
const QuicTransmissionInfo& info) {
stats_->bytes_spuriously_retransmitted += info.bytes_sent;
++stats_->packets_spuriously_retransmitted;
if (debug_delegate_ != nullptr) {
debug_delegate_->OnSpuriousPacketRetransmission(info.transmission_type,
info.bytes_sent);
}
}
void QuicSentPacketManager::MarkPacketHandled(QuicPacketNumber packet_number,
QuicTransmissionInfo* info,
QuicTime ack_receive_time,
QuicTime::Delta ack_delay_time,
QuicTime receive_timestamp) {
if (info->has_ack_frequency) {
for (const auto& frame : info->retransmittable_frames) {
if (frame.type == ACK_FREQUENCY_FRAME) {
OnAckFrequencyFrameAcked(*frame.ack_frequency_frame);
}
}
}
if (info->transmission_type == NOT_RETRANSMISSION) {
unacked_packets_.MaybeAggregateAckedStreamFrame(*info, ack_delay_time,
receive_timestamp);
} else {
unacked_packets_.NotifyAggregatedStreamFrameAcked(ack_delay_time);
const bool new_data_acked = unacked_packets_.NotifyFramesAcked(
*info, ack_delay_time, receive_timestamp);
if (!new_data_acked && info->transmission_type != NOT_RETRANSMISSION) {
QUIC_DVLOG(1) << "Detect spurious retransmitted packet " << packet_number
<< " transmission type: " << info->transmission_type;
RecordOneSpuriousRetransmission(*info);
}
}
if (info->state == LOST) {
const PacketNumberSpace packet_number_space =
unacked_packets_.GetPacketNumberSpace(info->encryption_level);
const QuicPacketNumber previous_largest_acked =
supports_multiple_packet_number_spaces()
? unacked_packets_.GetLargestAckedOfPacketNumberSpace(
packet_number_space)
: unacked_packets_.largest_acked();
QUIC_DVLOG(1) << "Packet " << packet_number
<< " was detected lost spuriously, "
"previous_largest_acked: "
<< previous_largest_acked;
loss_algorithm_->SpuriousLossDetected(unacked_packets_, rtt_stats_,
ack_receive_time, packet_number,
previous_largest_acked);
++stats_->packet_spuriously_detected_lost;
}
if (network_change_visitor_ != nullptr &&
info->bytes_sent > largest_mtu_acked_) {
largest_mtu_acked_ = info->bytes_sent;
network_change_visitor_->OnPathMtuIncreased(largest_mtu_acked_);
}
unacked_packets_.RemoveFromInFlight(info);
unacked_packets_.RemoveRetransmittability(info);
info->state = ACKED;
}
bool QuicSentPacketManager::CanSendAckFrequency() const {
return !peer_min_ack_delay_.IsInfinite() && handshake_finished_;
}
QuicAckFrequencyFrame QuicSentPacketManager::GetUpdatedAckFrequencyFrame()
const {
QuicAckFrequencyFrame frame;
if (!CanSendAckFrequency()) {
QUIC_BUG(quic_bug_10750_1)
<< "New AckFrequencyFrame is created while it shouldn't.";
return frame;
}
QUIC_RELOADABLE_FLAG_COUNT_N(quic_can_send_ack_frequency, 1, 3);
frame.packet_tolerance = kMaxRetransmittablePacketsBeforeAck;
auto rtt = use_smoothed_rtt_in_ack_delay_ ? rtt_stats_.SmoothedOrInitialRtt()
: rtt_stats_.MinOrInitialRtt();
frame.max_ack_delay = rtt * kPeerAckDecimationDelay;
frame.max_ack_delay = std::max(frame.max_ack_delay, peer_min_ack_delay_);
frame.max_ack_delay =
std::max(frame.max_ack_delay,
QuicTime::Delta::FromMilliseconds(kDefaultMinAckDelayTimeMs));
return frame;
}
void QuicSentPacketManager::RecordEcnMarkingSent(QuicEcnCodepoint ecn_codepoint,
EncryptionLevel level) {
PacketNumberSpace space = QuicUtils::GetPacketNumberSpace(level);
switch (ecn_codepoint) {
case ECN_NOT_ECT:
break;
case ECN_ECT0:
++ect0_packets_sent_[space];
break;
case ECN_ECT1:
++ect1_packets_sent_[space];
break;
case ECN_CE:
++ect0_packets_sent_[space];
++ect1_packets_sent_[space];
break;
}
}
bool QuicSentPacketManager::OnPacketSent(
SerializedPacket* mutable_packet, QuicTime sent_time,
TransmissionType transmission_type,
HasRetransmittableData has_retransmittable_data, bool measure_rtt,
QuicEcnCodepoint ecn_codepoint) {
const SerializedPacket& packet = *mutable_packet;
QuicPacketNumber packet_number = packet.packet_number;
QUICHE_DCHECK_LE(FirstSendingPacketNumber(), packet_number);
QUICHE_DCHECK(!unacked_packets_.IsUnacked(packet_number));
QUIC_BUG_IF(quic_bug_10750_2, packet.encrypted_length == 0)
<< "Cannot send empty packets.";
if (pending_timer_transmission_count_ > 0) {
--pending_timer_transmission_count_;
}
bool in_flight = has_retransmittable_data == HAS_RETRANSMITTABLE_DATA;
if (ignore_pings_ && mutable_packet->retransmittable_frames.size() == 1 &&
mutable_packet->retransmittable_frames[0].type == PING_FRAME) {
in_flight = false;
measure_rtt = false;
}
if (using_pacing_) {
pacing_sender_.OnPacketSent(sent_time, unacked_packets_.bytes_in_flight(),
packet_number, packet.encrypted_length,
has_retransmittable_data);
} else {
send_algorithm_->OnPacketSent(sent_time, unacked_packets_.bytes_in_flight(),
packet_number, packet.encrypted_length,
has_retransmittable_data);
}
if (packet.has_message) {
for (auto& frame : mutable_packet->retransmittable_frames) {
if (frame.type == MESSAGE_FRAME) {
frame.message_frame->message_data.clear();
frame.message_frame->message_length = 0;
}
}
}
if (packet.has_ack_frequency) {
for (const auto& frame : packet.retransmittable_frames) {
if (frame.type == ACK_FREQUENCY_FRAME) {
OnAckFrequencyFrameSent(*frame.ack_frequency_frame);
}
}
}
RecordEcnMarkingSent(ecn_codepoint, packet.encryption_level);
unacked_packets_.AddSentPacket(mutable_packet, transmission_type, sent_time,
in_flight, measure_rtt, ecn_codepoint);
return in_flight;
}
const QuicTransmissionInfo& QuicSentPacketManager::AddDispatcherSentPacket(
const DispatcherSentPacket& packet) {
QUIC_DVLOG(1) << "QuicSPM: Adding dispatcher sent packet "
<< packet.packet_number << ", size: " << packet.bytes_sent
<< ", sent_time: " << packet.sent_time
<< ", largest_acked: " << packet.largest_acked;
if (using_pacing_) {
pacing_sender_.OnPacketSent(
packet.sent_time, unacked_packets_.bytes_in_flight(),
packet.packet_number, packet.bytes_sent, NO_RETRANSMITTABLE_DATA);
} else {
send_algorithm_->OnPacketSent(
packet.sent_time, unacked_packets_.bytes_in_flight(),
packet.packet_number, packet.bytes_sent, NO_RETRANSMITTABLE_DATA);
}
return unacked_packets_.AddDispatcherSentPacket(packet);
}
QuicSentPacketManager::RetransmissionTimeoutMode
QuicSentPacketManager::OnRetransmissionTimeout() {
QUICHE_DCHECK(unacked_packets_.HasInFlightPackets() ||
(handshake_mode_disabled_ && !handshake_finished_));
QUICHE_DCHECK_EQ(0u, pending_timer_transmission_count_);
switch (GetRetransmissionMode()) {
case HANDSHAKE_MODE:
QUICHE_DCHECK(!handshake_mode_disabled_);
++stats_->crypto_retransmit_count;
RetransmitCryptoPackets();
return HANDSHAKE_MODE;
case LOSS_MODE: {
++stats_->loss_timeout_count;
QuicByteCount prior_in_flight = unacked_packets_.bytes_in_flight();
const QuicTime now = clock_->Now();
InvokeLossDetection(now);
MaybeInvokeCongestionEvent(false, prior_in_flight, now,
std::optional<QuicEcnCounts>(),
peer_ack_ecn_counts_[APPLICATION_DATA]);
return LOSS_MODE;
}
case PTO_MODE:
QUIC_DVLOG(1) << ENDPOINT << "PTO mode";
++stats_->pto_count;
if (handshake_mode_disabled_ && !handshake_finished_) {
++stats_->crypto_retransmit_count;
}
++consecutive_pto_count_;
pending_timer_transmission_count_ = 1;
return PTO_MODE;
}
QUIC_BUG(quic_bug_10750_3)
<< "Unknown retransmission mode " << GetRetransmissionMode();
return GetRetransmissionMode();
}
void QuicSentPacketManager::RetransmitCryptoPackets() {
QUICHE_DCHECK_EQ(HANDSHAKE_MODE, GetRetransmissionMode());
++consecutive_crypto_retransmission_count_;
bool packet_retransmitted = false;
std::vector<QuicPacketNumber> crypto_retransmissions;
if (!unacked_packets_.empty()) {
QuicPacketNumber packet_number = unacked_packets_.GetLeastUnacked();
QuicPacketNumber largest_sent_packet =
unacked_packets_.largest_sent_packet();
for (; packet_number <= largest_sent_packet; ++packet_number) {
QuicTransmissionInfo* transmission_info =
unacked_packets_.GetMutableTransmissionInfo(packet_number);
if (!transmission_info->in_flight ||
transmission_info->state != OUTSTANDING ||
!transmission_info->has_crypto_handshake ||
!unacked_packets_.HasRetransmittableFrames(*transmission_info)) {
continue;
}
packet_retransmitted = true;
crypto_retransmissions.push_back(packet_number);
++pending_timer_transmission_count_;
}
}
QUICHE_DCHECK(packet_retransmitted)
<< "No crypto packets found to retransmit.";
for (QuicPacketNumber retransmission : crypto_retransmissions) {
MarkForRetransmission(retransmission, HANDSHAKE_RETRANSMISSION);
}
}
bool QuicSentPacketManager::MaybeRetransmitOldestPacket(TransmissionType type) {
if (!unacked_packets_.empty()) {
QuicPacketNumber packet_number = unacked_packets_.GetLeastUnacked();
QuicPacketNumber largest_sent_packet =
unacked_packets_.largest_sent_packet();
for (; packet_number <= largest_sent_packet; ++packet_number) {
QuicTransmissionInfo* transmission_info =
unacked_packets_.GetMutableTransmissionInfo(packet_number);
if (!transmission_info->in_flight ||
transmission_info->state != OUTSTANDING ||
!unacked_packets_.HasRetransmittableFrames(*transmission_info)) {
continue;
}
MarkForRetransmission(packet_number, type);
return true;
}
}
QUIC_DVLOG(1)
<< "No retransmittable packets, so RetransmitOldestPacket failed.";
return false;
}
void QuicSentPacketManager::MaybeSendProbePacket() {
if (pending_timer_transmission_count_ == 0) {
return;
}
PacketNumberSpace packet_number_space;
if (supports_multiple_packet_number_spaces()) {
if (!GetEarliestPacketSentTimeForPto(&packet_number_space)
.IsInitialized()) {
QUIC_BUG_IF(quic_earliest_sent_time_not_initialized,
unacked_packets_.perspective() == Perspective::IS_SERVER)
<< "earliest_sent_time not initialized when trying to send PTO "
"retransmissions";
return;
}
}
std::vector<QuicPacketNumber> probing_packets;
if (!unacked_packets_.empty()) {
QuicPacketNumber packet_number = unacked_packets_.GetLeastUnacked();
QuicPacketNumber largest_sent_packet =
unacked_packets_.largest_sent_packet();
for (; packet_number <= largest_sent_packet; ++packet_number) {
QuicTransmissionInfo* transmission_info =
unacked_packets_.GetMutableTransmissionInfo(packet_number);
if (transmission_info->state == OUTSTANDING &&
unacked_packets_.HasRetransmittableFrames(*transmission_info) &&
(!supports_multiple_packet_number_spaces() ||
unacked_packets_.GetPacketNumberSpace(
transmission_info->encryption_level) == packet_number_space)) {
QUICHE_DCHECK(transmission_info->in_flight);
probing_packets.push_back(packet_number);
if (probing_packets.size() == pending_timer_transmission_count_) {
break;
}
}
}
}
for (QuicPacketNumber retransmission : probing_packets) {
QUIC_DVLOG(1) << ENDPOINT << "Marking " << retransmission
<< " for probing retransmission";
MarkForRetransmission(retransmission, PTO_RETRANSMISSION);
}
}
void QuicSentPacketManager::EnableIetfPtoAndLossDetection() {
handshake_mode_disabled_ = true;
}
void QuicSentPacketManager::RetransmitDataOfSpaceIfAny(
PacketNumberSpace space) {
QUICHE_DCHECK(supports_multiple_packet_number_spaces());
if (!unacked_packets_.GetLastInFlightPacketSentTime(space).IsInitialized()) {
return;
}
if (unacked_packets_.empty()) {
return;
}
QuicPacketNumber packet_number = unacked_packets_.GetLeastUnacked();
QuicPacketNumber largest_sent_packet = unacked_packets_.largest_sent_packet();
for (; packet_number <= largest_sent_packet; ++packet_number) {
QuicTransmissionInfo* transmission_info =
unacked_packets_.GetMutableTransmissionInfo(packet_number);
if (transmission_info->state == OUTSTANDING &&
unacked_packets_.HasRetransmittableFrames(*transmission_info) &&
unacked_packets_.GetPacketNumberSpace(
transmission_info->encryption_level) == space) {
QUICHE_DCHECK(transmission_info->in_flight);
if (pending_timer_transmission_count_ == 0) {
pending_timer_transmission_count_ = 1;
}
MarkForRetransmission(packet_number, PTO_RETRANSMISSION);
return;
}
}
}
QuicSentPacketManager::RetransmissionTimeoutMode
QuicSentPacketManager::GetRetransmissionMode() const {
QUICHE_DCHECK(unacked_packets_.HasInFlightPackets() ||
(handshake_mode_disabled_ && !handshake_finished_));
if (!handshake_mode_disabled_ && !handshake_finished_ &&
unacked_packets_.HasPendingCryptoPackets()) {
return HANDSHAKE_MODE;
}
if (loss_algorithm_->GetLossTimeout() != QuicTime::Zero()) {
return LOSS_MODE;
}
return PTO_MODE;
}
void QuicSentPacketManager::InvokeLossDetection(QuicTime time) {
if (!packets_acked_.empty()) {
QUICHE_DCHECK_LE(packets_acked_.front().packet_number,
packets_acked_.back().packet_number);
largest_newly_acked_ = packets_acked_.back().packet_number;
}
LossDetectionInterface::DetectionStats detection_stats =
loss_algorithm_->DetectLosses(unacked_packets_, time, rtt_stats_,
largest_newly_acked_, packets_acked_,
&packets_lost_);
if (detection_stats.sent_packets_max_sequence_reordering >
stats_->sent_packets_max_sequence_reordering) {
stats_->sent_packets_max_sequence_reordering =
detection_stats.sent_packets_max_sequence_reordering;
}
stats_->sent_packets_num_borderline_time_reorderings +=
detection_stats.sent_packets_num_borderline_time_reorderings;
stats_->total_loss_detection_response_time +=
detection_stats.total_loss_detection_response_time;
for (const LostPacket& packet : packets_lost_) {
QuicTransmissionInfo* info =
unacked_packets_.GetMutableTransmissionInfo(packet.packet_number);
++stats_->packets_lost;
if (debug_delegate_ != nullptr) {
debug_delegate_->OnPacketLoss(packet.packet_number,
info->encryption_level, LOSS_RETRANSMISSION,
time);
}
unacked_packets_.RemoveFromInFlight(info);
MarkForRetransmission(packet.packet_number, LOSS_RETRANSMISSION);
}
}
bool QuicSentPacketManager::MaybeUpdateRTT(QuicPacketNumber largest_acked,
QuicTime::Delta ack_delay_time,
QuicTime ack_receive_time) {
if (!unacked_packets_.IsUnacked(largest_acked)) {
return false;
}
const QuicTransmissionInfo& transmission_info =
unacked_packets_.GetTransmissionInfo(largest_acked);
if (transmission_info.sent_time == QuicTime::Zero()) {
QUIC_BUG(quic_bug_10750_4)
<< "Acked packet has zero sent time, largest_acked:" << largest_acked;
return false;
}
if (transmission_info.state == NOT_CONTRIBUTING_RTT) {
return false;
}
if (transmission_info.sent_time > ack_receive_time) {
QUIC_CODE_COUNT(quic_receive_acked_before_sending);
}
QuicTime::Delta send_delta = ack_receive_time - transmission_info.sent_time;
const bool min_rtt_available = !rtt_stats_.min_rtt().IsZero();
rtt_stats_.UpdateRtt(send_delta, ack_delay_time, ack_receive_time);
if (!min_rtt_available && !rtt_stats_.min_rtt().IsZero()) {
loss_algorithm_->OnMinRttAvailable();
}
return true;
}
QuicTime::Delta QuicSentPacketManager::TimeUntilSend(QuicTime now) const {
if (pending_timer_transmission_count_ > 0) {
return QuicTime::Delta::Zero();
}
if (using_pacing_) {
return pacing_sender_.TimeUntilSend(now,
unacked_packets_.bytes_in_flight());
}
return send_algorithm_->CanSend(unacked_packets_.bytes_in_flight())
? QuicTime::Delta::Zero()
: QuicTime::Delta::Infinite();
}
const QuicTime QuicSentPacketManager::GetRetransmissionTime() const {
if (!unacked_packets_.HasInFlightPackets() &&
PeerCompletedAddressValidation()) {
return QuicTime::Zero();
}
if (pending_timer_transmission_count_ > 0) {
return QuicTime::Zero();
}
switch (GetRetransmissionMode()) {
case HANDSHAKE_MODE:
return unacked_packets_.GetLastCryptoPacketSentTime() +
GetCryptoRetransmissionDelay();
case LOSS_MODE:
return loss_algorithm_->GetLossTimeout();
case PTO_MODE: {
if (!supports_multiple_packet_number_spaces()) {
if (unacked_packets_.HasInFlightPackets() &&
consecutive_pto_count_ == 0) {
return std::max(
clock_->ApproximateNow(),
std::max(unacked_packets_.GetFirstInFlightTransmissionInfo()
->sent_time +
GetProbeTimeoutDelay(NUM_PACKET_NUMBER_SPACES),
unacked_packets_.GetLastInFlightPacketSentTime() +
kFirstPtoSrttMultiplier *
rtt_stats_.SmoothedOrInitialRtt()));
}
return std::max(clock_->ApproximateNow(),
unacked_packets_.GetLastInFlightPacketSentTime() +
GetProbeTimeoutDelay(NUM_PACKET_NUMBER_SPACES));
}
PacketNumberSpace packet_number_space = NUM_PACKET_NUMBER_SPACES;
QuicTime earliest_right_edge =
GetEarliestPacketSentTimeForPto(&packet_number_space);
if (!earliest_right_edge.IsInitialized()) {
earliest_right_edge = clock_->ApproximateNow();
}
if (packet_number_space == APPLICATION_DATA &&
consecutive_pto_count_ == 0) {
const QuicTransmissionInfo* first_application_info =
unacked_packets_.GetFirstInFlightTransmissionInfoOfSpace(
APPLICATION_DATA);
if (first_application_info != nullptr) {
return std::max(
clock_->ApproximateNow(),
std::max(
first_application_info->sent_time +
GetProbeTimeoutDelay(packet_number_space),
earliest_right_edge + kFirstPtoSrttMultiplier *
rtt_stats_.SmoothedOrInitialRtt()));
}
}
return std::max(
clock_->ApproximateNow(),
earliest_right_edge + GetProbeTimeoutDelay(packet_number_space));
}
}
QUICHE_DCHECK(false);
return QuicTime::Zero();
}
const QuicTime::Delta QuicSentPacketManager::GetPathDegradingDelay() const {
QUICHE_DCHECK_GT(num_ptos_for_path_degrading_, 0);
return num_ptos_for_path_degrading_ * GetPtoDelay();
}
const QuicTime::Delta QuicSentPacketManager::GetNetworkBlackholeDelay(
int8_t num_rtos_for_blackhole_detection) const {
return GetNConsecutiveRetransmissionTimeoutDelay(
kDefaultMaxTailLossProbes + num_rtos_for_blackhole_detection);
}
QuicTime::Delta QuicSentPacketManager::GetMtuReductionDelay(
int8_t num_rtos_for_blackhole_detection) const {
return GetNetworkBlackholeDelay(num_rtos_for_blackhole_detection / 2);
}
const QuicTime::Delta QuicSentPacketManager::GetCryptoRetransmissionDelay()
const {
QuicTime::Delta srtt = rtt_stats_.SmoothedOrInitialRtt();
int64_t delay_ms;
if (conservative_handshake_retransmits_) {
delay_ms = std::max(peer_max_ack_delay_.ToMilliseconds(),
static_cast<int64_t>(2 * srtt.ToMilliseconds()));
} else {
delay_ms = std::max(kMinHandshakeTimeoutMs,
static_cast<int64_t>(1.5 * srtt.ToMilliseconds()));
}
return QuicTime::Delta::FromMilliseconds(
delay_ms << consecutive_crypto_retransmission_count_);
}
const QuicTime::Delta QuicSentPacketManager::GetProbeTimeoutDelay(
PacketNumberSpace space) const {
if (rtt_stats_.smoothed_rtt().IsZero()) {
QUIC_BUG_IF(quic_bug_12552_6, rtt_stats_.initial_rtt().IsZero());
return std::max(kPtoMultiplierWithoutRttSamples * rtt_stats_.initial_rtt(),
QuicTime::Delta::FromMilliseconds(kMinHandshakeTimeoutMs)) *
(1 << consecutive_pto_count_);
}
QuicTime::Delta pto_delay =
rtt_stats_.smoothed_rtt() +
std::max(kPtoRttvarMultiplier * rtt_stats_.mean_deviation(),
kAlarmGranularity) +
(ShouldAddMaxAckDelay(space) ? peer_max_ack_delay_
: QuicTime::Delta::Zero());
return pto_delay * (1 << consecutive_pto_count_);
}
QuicTime::Delta QuicSentPacketManager::GetSlowStartDuration() const {
if (send_algorithm_->GetCongestionControlType() == kBBR ||
send_algorithm_->GetCongestionControlType() == kBBRv2) {
return stats_->slowstart_duration.GetTotalElapsedTime(
clock_->ApproximateNow());
}
return QuicTime::Delta::Infinite();
}
QuicByteCount QuicSentPacketManager::GetAvailableCongestionWindowInBytes()
const {
QuicByteCount congestion_window = GetCongestionWindowInBytes();
QuicByteCount bytes_in_flight = GetBytesInFlight();
return congestion_window - std::min(congestion_window, bytes_in_flight);
}
std::string QuicSentPacketManager::GetDebugState() const {
return send_algorithm_->GetDebugState();
}
void QuicSentPacketManager::SetSendAlgorithm(
CongestionControlType congestion_control_type) {
if (send_algorithm_ &&
send_algorithm_->GetCongestionControlType() == congestion_control_type) {
return;
}
SetSendAlgorithm(SendAlgorithmInterface::Create(
clock_, &rtt_stats_, &unacked_packets_, congestion_control_type, random_,
stats_, initial_congestion_window_, send_algorithm_.get()));
}
void QuicSentPacketManager::SetSendAlgorithm(
SendAlgorithmInterface* send_algorithm) {
if (debug_delegate_ != nullptr && send_algorithm != nullptr) {
debug_delegate_->OnSendAlgorithmChanged(
send_algorithm->GetCongestionControlType());
}
send_algorithm_.reset(send_algorithm);
pacing_sender_.set_sender(send_algorithm);
}
std::unique_ptr<SendAlgorithmInterface>
QuicSentPacketManager::OnConnectionMigration(bool reset_send_algorithm) {
consecutive_pto_count_ = 0;
rtt_stats_.OnConnectionMigration();
if (!reset_send_algorithm) {
send_algorithm_->OnConnectionMigration();
return nullptr;
}
std::unique_ptr<SendAlgorithmInterface> old_send_algorithm =
std::move(send_algorithm_);
SetSendAlgorithm(old_send_algorithm->GetCongestionControlType());
QuicPacketNumber packet_number = unacked_packets_.GetLeastUnacked();
for (auto it = unacked_packets_.begin(); it != unacked_packets_.end();
++it, ++packet_number) {
if (it->in_flight) {
unacked_packets_.RemoveFromInFlight(packet_number);
if (unacked_packets_.HasRetransmittableFrames(packet_number)) {
MarkForRetransmission(packet_number, PATH_RETRANSMISSION);
QUICHE_DCHECK_EQ(it->state, NOT_CONTRIBUTING_RTT);
}
}
it->state = NOT_CONTRIBUTING_RTT;
}
return old_send_algorithm;
}
void QuicSentPacketManager::OnAckFrameStart(QuicPacketNumber largest_acked,
QuicTime::Delta ack_delay_time,
QuicTime ack_receive_time) {
QUICHE_DCHECK(packets_acked_.empty());
QUICHE_DCHECK_LE(largest_acked, unacked_packets_.largest_sent_packet());
if (!supports_multiple_packet_number_spaces() || handshake_finished_) {
if (ack_delay_time > peer_max_ack_delay()) {
ack_delay_time = peer_max_ack_delay();
}
if (ignore_ack_delay_) {
ack_delay_time = QuicTime::Delta::Zero();
}
}
rtt_updated_ =
MaybeUpdateRTT(largest_acked, ack_delay_time, ack_receive_time);
last_ack_frame_.ack_delay_time = ack_delay_time;
acked_packets_iter_ = last_ack_frame_.packets.rbegin();
}
void QuicSentPacketManager::OnAckRange(QuicPacketNumber start,
QuicPacketNumber end) {
if (!last_ack_frame_.largest_acked.IsInitialized() ||
end > last_ack_frame_.largest_acked + 1) {
unacked_packets_.IncreaseLargestAcked(end - 1);
last_ack_frame_.largest_acked = end - 1;
}
QuicPacketNumber least_unacked = unacked_packets_.GetLeastUnacked();
if (least_unacked.IsInitialized() && end <= least_unacked) {
return;
}
start = std::max(start, least_unacked);
do {
QuicPacketNumber newly_acked_start = start;
if (acked_packets_iter_ != last_ack_frame_.packets.rend()) {
newly_acked_start = std::max(start, acked_packets_iter_->max());
}
for (QuicPacketNumber acked = end - 1; acked >= newly_acked_start;
--acked) {
packets_acked_.push_back(AckedPacket(acked, 0, QuicTime::Zero()));
if (acked == FirstSendingPacketNumber()) {
break;
}
}
if (acked_packets_iter_ == last_ack_frame_.packets.rend() ||
start > acked_packets_iter_->min()) {
return;
}
end = std::min(end, acked_packets_iter_->min());
++acked_packets_iter_;
} while (start < end);
}
void QuicSentPacketManager::OnAckTimestamp(QuicPacketNumber packet_number,
QuicTime timestamp) {
last_ack_frame_.received_packet_times.push_back({packet_number, timestamp});
for (AckedPacket& packet : packets_acked_) {
if (packet.packet_number == packet_number) {
packet.receive_timestamp = timestamp;
return;
}
}
}
bool QuicSentPacketManager::IsEcnFeedbackValid(
PacketNumberSpace space, const std::optional<QuicEcnCounts>& ecn_counts,
QuicPacketCount newly_acked_ect0, QuicPacketCount newly_acked_ect1) {
if (!ecn_counts.has_value()) {
if (newly_acked_ect0 > 0 || newly_acked_ect1 > 0) {
QUIC_DVLOG(1) << ENDPOINT
<< "ECN packets acknowledged, no counts reported.";
return false;
}
return true;
}
if (ecn_counts->ect0 < peer_ack_ecn_counts_[space].ect0 ||
ecn_counts->ect1 < peer_ack_ecn_counts_[space].ect1 ||
ecn_counts->ce < peer_ack_ecn_counts_[space].ce) {
QUIC_DVLOG(1) << ENDPOINT << "Reported ECN count declined.";
return false;
}
if (ecn_counts->ect0 > ect0_packets_sent_[space] ||
ecn_counts->ect1 > ect1_packets_sent_[space] ||
(ecn_counts->ect0 + ecn_counts->ect1 + ecn_counts->ce >
ect0_packets_sent_[space] + ect1_packets_sent_[space])) {
QUIC_DVLOG(1) << ENDPOINT << "Reported ECT + CE exceeds packets sent:"
<< " reported " << ecn_counts->ToString() << " , ECT(0) sent "
<< ect0_packets_sent_[space] << " , ECT(1) sent "
<< ect1_packets_sent_[space];
return false;
}
if ((newly_acked_ect0 >
(ecn_counts->ect0 + ecn_counts->ce - peer_ack_ecn_counts_[space].ect0 +
peer_ack_ecn_counts_[space].ce)) ||
(newly_acked_ect1 >
(ecn_counts->ect1 + ecn_counts->ce - peer_ack_ecn_counts_[space].ect1 +
peer_ack_ecn_counts_[space].ce))) {
QUIC_DVLOG(1) << ENDPOINT
<< "Peer acked packet but did not report the ECN mark: "
<< " New ECN counts: " << ecn_counts->ToString()
<< " Old ECN counts: "
<< peer_ack_ecn_counts_[space].ToString()
<< " Newly acked ECT(0) : " << newly_acked_ect0
<< " Newly acked ECT(1) : " << newly_acked_ect1;
return false;
}
return true;
}
AckResult QuicSentPacketManager::OnAckFrameEnd(
QuicTime ack_receive_time, QuicPacketNumber ack_packet_number,
EncryptionLevel ack_decrypted_level,
const std::optional<QuicEcnCounts>& ecn_counts) {
QuicByteCount prior_bytes_in_flight = unacked_packets_.bytes_in_flight();
QuicPacketCount newly_acked_ect0 = 0;
QuicPacketCount newly_acked_ect1 = 0;
PacketNumberSpace acked_packet_number_space =
QuicUtils::GetPacketNumberSpace(ack_decrypted_level);
QuicPacketNumber old_largest_acked =
unacked_packets_.GetLargestAckedOfPacketNumberSpace(
acked_packet_number_space);
std::reverse(packets_acked_.begin(), packets_acked_.end());
for (AckedPacket& acked_packet : packets_acked_) {
QuicTransmissionInfo* info =
unacked_packets_.GetMutableTransmissionInfo(acked_packet.packet_number);
if (!QuicUtils::IsAckable(info->state)) {
if (info->state == ACKED) {
QUIC_BUG(quic_bug_10750_5)
<< "Trying to ack an already acked packet: "
<< acked_packet.packet_number
<< ", last_ack_frame_: " << last_ack_frame_
<< ", least_unacked: " << unacked_packets_.GetLeastUnacked()
<< ", packets_acked_: " << quiche::PrintElements(packets_acked_);
} else {
QUIC_PEER_BUG(quic_peer_bug_10750_6)
<< "Received " << ack_decrypted_level
<< " ack for unackable packet: " << acked_packet.packet_number
<< " with state: "
<< QuicUtils::SentPacketStateToString(info->state);
if (supports_multiple_packet_number_spaces()) {
if (info->state == NEVER_SENT) {
return UNSENT_PACKETS_ACKED;
}
return UNACKABLE_PACKETS_ACKED;
}
}
continue;
}
QUIC_DVLOG(1) << ENDPOINT << "Got an " << ack_decrypted_level
<< " ack for packet " << acked_packet.packet_number
<< " , state: "
<< QuicUtils::SentPacketStateToString(info->state);
const PacketNumberSpace packet_number_space =
unacked_packets_.GetPacketNumberSpace(info->encryption_level);
if (supports_multiple_packet_number_spaces() &&
QuicUtils::GetPacketNumberSpace(ack_decrypted_level) !=
packet_number_space) {
return PACKETS_ACKED_IN_WRONG_PACKET_NUMBER_SPACE;
}
last_ack_frame_.packets.Add(acked_packet.packet_number);
if (info->encryption_level == ENCRYPTION_HANDSHAKE) {
handshake_packet_acked_ = true;
} else if (info->encryption_level == ENCRYPTION_ZERO_RTT) {
zero_rtt_packet_acked_ = true;
} else if (info->encryption_level == ENCRYPTION_FORWARD_SECURE) {
one_rtt_packet_acked_ = true;
}
largest_packet_peer_knows_is_acked_.UpdateMax(info->largest_acked);
if (supports_multiple_packet_number_spaces()) {
largest_packets_peer_knows_is_acked_[packet_number_space].UpdateMax(
info->largest_acked);
}
if (info->in_flight) {
acked_packet.bytes_acked = info->bytes_sent;
} else {
acked_packet.spurious_loss = (info->state == LOST);
largest_newly_acked_ = acked_packet.packet_number;
}
switch (info->ecn_codepoint) {
case ECN_NOT_ECT:
break;
case ECN_CE:
break;
case ECN_ECT0:
++newly_acked_ect0;
if (info->in_flight) {
network_change_visitor_->OnInFlightEcnPacketAcked();
}
break;
case ECN_ECT1:
++newly_acked_ect1;
if (info->in_flight) {
network_change_visitor_->OnInFlightEcnPacketAcked();
}
break;
}
unacked_packets_.MaybeUpdateLargestAckedOfPacketNumberSpace(
packet_number_space, acked_packet.packet_number);
MarkPacketHandled(acked_packet.packet_number, info, ack_receive_time,
last_ack_frame_.ack_delay_time,
acked_packet.receive_timestamp);
}
std::optional<QuicEcnCounts> valid_ecn_counts;
if (GetQuicRestartFlag(quic_support_ect1)) {
QUIC_RESTART_FLAG_COUNT_N(quic_support_ect1, 1, 9);
if (IsEcnFeedbackValid(acked_packet_number_space, ecn_counts,
newly_acked_ect0, newly_acked_ect1)) {
valid_ecn_counts = ecn_counts;
} else if (!old_largest_acked.IsInitialized() ||
old_largest_acked <
unacked_packets_.GetLargestAckedOfPacketNumberSpace(
acked_packet_number_space)) {
network_change_visitor_->OnInvalidEcnFeedback();
}
}
const bool acked_new_packet = !packets_acked_.empty();
PostProcessNewlyAckedPackets(ack_packet_number, ack_decrypted_level,
last_ack_frame_, ack_receive_time, rtt_updated_,
prior_bytes_in_flight, valid_ecn_counts);
if (valid_ecn_counts.has_value()) {
peer_ack_ecn_counts_[acked_packet_number_space] = *valid_ecn_counts;
}
return acked_new_packet ? PACKETS_NEWLY_ACKED : NO_PACKETS_NEWLY_ACKED;
}
void QuicSentPacketManager::SetDebugDelegate(DebugDelegate* debug_delegate) {
debug_delegate_ = debug_delegate;
}
void QuicSentPacketManager::OnApplicationLimited() {
if (using_pacing_) {
pacing_sender_.OnApplicationLimited();
}
send_algorithm_->OnApplicationLimited(unacked_packets_.bytes_in_flight());
if (debug_delegate_ != nullptr) {
debug_delegate_->OnApplicationLimited();
}
}
NextReleaseTimeResult QuicSentPacketManager::GetNextReleaseTime() const {
if (!using_pacing_) {
return {QuicTime::Zero(), false};
}
return pacing_sender_.GetNextReleaseTime();
}
void QuicSentPacketManager::SetInitialRtt(QuicTime::Delta rtt, bool trusted) {
const QuicTime::Delta min_rtt = QuicTime::Delta::FromMicroseconds(
trusted ? kMinTrustedInitialRoundTripTimeUs
: kMinUntrustedInitialRoundTripTimeUs);
QuicTime::Delta max_rtt =
QuicTime::Delta::FromMicroseconds(kMaxInitialRoundTripTimeUs);
rtt_stats_.set_initial_rtt(std::max(min_rtt, std::min(max_rtt, rtt)));
}
void QuicSentPacketManager::EnableMultiplePacketNumberSpacesSupport() {
EnableIetfPtoAndLossDetection();
unacked_packets_.EnableMultiplePacketNumberSpacesSupport();
}
QuicPacketNumber QuicSentPacketManager::GetLargestAckedPacket(
EncryptionLevel decrypted_packet_level) const {
QUICHE_DCHECK(supports_multiple_packet_number_spaces());
return unacked_packets_.GetLargestAckedOfPacketNumberSpace(
QuicUtils::GetPacketNumberSpace(decrypted_packet_level));
}
QuicPacketNumber QuicSentPacketManager::GetLeastPacketAwaitedByPeer(
EncryptionLevel encryption_level) const {
QuicPacketNumber largest_acked;
if (supports_multiple_packet_number_spaces()) {
largest_acked = GetLargestAckedPacket(encryption_level);
} else {
largest_acked = GetLargestObserved();
}
if (!largest_acked.IsInitialized()) {
return FirstSendingPacketNumber();
}
QuicPacketNumber least_awaited = largest_acked + 1;
QuicPacketNumber least_unacked = GetLeastUnacked();
if (least_unacked.IsInitialized() && least_unacked < least_awaited) {
least_awaited = least_unacked;
}
return least_awaited;
}
QuicPacketNumber QuicSentPacketManager::GetLargestPacketPeerKnowsIsAcked(
EncryptionLevel decrypted_packet_level) const {
QUICHE_DCHECK(supports_multiple_packet_number_spaces());
return largest_packets_peer_knows_is_acked_[QuicUtils::GetPacketNumberSpace(
decrypted_packet_level)];
}
QuicTime::Delta
QuicSentPacketManager::GetNConsecutiveRetransmissionTimeoutDelay(
int num_timeouts) const {
QuicTime::Delta total_delay = QuicTime::Delta::Zero();
const QuicTime::Delta srtt = rtt_stats_.SmoothedOrInitialRtt();
int num_tlps =
std::min(num_timeouts, static_cast<int>(kDefaultMaxTailLossProbes));
num_timeouts -= num_tlps;
if (num_tlps > 0) {
const QuicTime::Delta tlp_delay = std::max(
2 * srtt,
unacked_packets_.HasMultipleInFlightPackets()
? QuicTime::Delta::FromMilliseconds(kMinTailLossProbeTimeoutMs)
: (1.5 * srtt +
(QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs) *
0.5)));
total_delay = total_delay + num_tlps * tlp_delay;
}
if (num_timeouts == 0) {
return total_delay;
}
const QuicTime::Delta retransmission_delay =
rtt_stats_.smoothed_rtt().IsZero()
? QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs)
: std::max(
srtt + 4 * rtt_stats_.mean_deviation(),
QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs));
total_delay = total_delay + ((1 << num_timeouts) - 1) * retransmission_delay;
return total_delay;
}
bool QuicSentPacketManager::PeerCompletedAddressValidation() const {
if (unacked_packets_.perspective() == Perspective::IS_SERVER ||
!handshake_mode_disabled_) {
return true;
}
return handshake_finished_ || handshake_packet_acked_;
}
bool QuicSentPacketManager::IsLessThanThreePTOs(QuicTime::Delta timeout) const {
return timeout < 3 * GetPtoDelay();
}
QuicTime::Delta QuicSentPacketManager::GetPtoDelay() const {
return GetProbeTimeoutDelay(APPLICATION_DATA);
}
void QuicSentPacketManager::OnAckFrequencyFrameSent(
const QuicAckFrequencyFrame& ack_frequency_frame) {
in_use_sent_ack_delays_.emplace_back(ack_frequency_frame.max_ack_delay,
ack_frequency_frame.sequence_number);
if (ack_frequency_frame.max_ack_delay > peer_max_ack_delay_) {
peer_max_ack_delay_ = ack_frequency_frame.max_ack_delay;
}
}
void QuicSentPacketManager::OnAckFrequencyFrameAcked(
const QuicAckFrequencyFrame& ack_frequency_frame) {
int stale_entry_count = 0;
for (auto it = in_use_sent_ack_delays_.cbegin();
it != in_use_sent_ack_delays_.cend(); ++it) {
if (it->second < ack_frequency_frame.sequence_number) {
++stale_entry_count;
} else {
break;
}
}
if (stale_entry_count > 0) {
in_use_sent_ack_delays_.pop_front_n(stale_entry_count);
}
if (in_use_sent_ack_delays_.empty()) {
QUIC_BUG(quic_bug_10750_7) << "in_use_sent_ack_delays_ is empty.";
return;
}
peer_max_ack_delay_ = std::max_element(in_use_sent_ack_delays_.cbegin(),
in_use_sent_ack_delays_.cend())
->first;
}
#undef ENDPOINT
} | #include "quiche/quic/core/quic_sent_packet_manager.h"
#include <algorithm>
#include <memory>
#include <optional>
#include <utility>
#include <vector>
#include "absl/base/macros.h"
#include "absl/strings/string_view.h"
#include "quiche/quic/core/frames/quic_ack_frequency_frame.h"
#include "quiche/quic/core/quic_time.h"
#include "quiche/quic/core/quic_types.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_config_peer.h"
#include "quiche/quic/test_tools/quic_sent_packet_manager_peer.h"
#include "quiche/quic/test_tools/quic_test_utils.h"
#include "quiche/common/platform/api/quiche_mem_slice.h"
using testing::_;
using testing::AnyNumber;
using testing::Invoke;
using testing::InvokeWithoutArgs;
using testing::IsEmpty;
using testing::Not;
using testing::Pointwise;
using testing::Return;
using testing::StrictMock;
using testing::WithArgs;
namespace quic {
namespace test {
namespace {
const uint32_t kDefaultLength = 1000;
const QuicStreamId kStreamId = 7;
const std::optional<QuicEcnCounts> kEmptyCounts = std::nullopt;
MATCHER(PacketNumberEq, "") {
return std::get<0>(arg).packet_number == QuicPacketNumber(std::get<1>(arg));
}
class MockDebugDelegate : public QuicSentPacketManager::DebugDelegate {
public:
MOCK_METHOD(void, OnSpuriousPacketRetransmission,
(TransmissionType transmission_type, QuicByteCount byte_size),
(override));
MOCK_METHOD(void, OnPacketLoss,
(QuicPacketNumber lost_packet_number,
EncryptionLevel encryption_level,
TransmissionType transmission_type, QuicTime detection_time),
(override));
};
class QuicSentPacketManagerTest : public QuicTest {
public:
bool RetransmitCryptoPacket(uint64_t packet_number) {
EXPECT_CALL(
*send_algorithm_,
OnPacketSent(_, BytesInFlight(), QuicPacketNumber(packet_number),
kDefaultLength, HAS_RETRANSMITTABLE_DATA));
SerializedPacket packet(CreatePacket(packet_number, false));
packet.retransmittable_frames.push_back(
QuicFrame(QuicStreamFrame(1, false, 0, absl::string_view())));
packet.has_crypto_handshake = IS_HANDSHAKE;
manager_.OnPacketSent(&packet, clock_.Now(), HANDSHAKE_RETRANSMISSION,
HAS_RETRANSMITTABLE_DATA, true, ECN_NOT_ECT);
return true;
}
bool RetransmitDataPacket(uint64_t packet_number, TransmissionType type,
EncryptionLevel level) {
EXPECT_CALL(
*send_algorithm_,
OnPacketSent(_, BytesInFlight(), QuicPacketNumber(packet_number),
kDefaultLength, HAS_RETRANSMITTABLE_DATA));
SerializedPacket packet(CreatePacket(packet_number, true));
packet.encryption_level = level;
manager_.OnPacketSent(&packet, clock_.Now(), type, HAS_RETRANSMITTABLE_DATA,
true, ECN_NOT_ECT);
return true;
}
bool RetransmitDataPacket(uint64_t packet_number, TransmissionType type) {
return RetransmitDataPacket(packet_number, type, ENCRYPTION_INITIAL);
}
protected:
const CongestionControlType kInitialCongestionControlType = kCubicBytes;
QuicSentPacketManagerTest()
: manager_(Perspective::IS_SERVER, &clock_, QuicRandom::GetInstance(),
&stats_, kInitialCongestionControlType),
send_algorithm_(new StrictMock<MockSendAlgorithm>),
network_change_visitor_(new StrictMock<MockNetworkChangeVisitor>) {
QuicSentPacketManagerPeer::SetSendAlgorithm(&manager_, send_algorithm_);
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1000));
manager_.SetNetworkChangeVisitor(network_change_visitor_.get());
manager_.SetSessionNotifier(¬ifier_);
EXPECT_CALL(*send_algorithm_, GetCongestionControlType())
.WillRepeatedly(Return(kInitialCongestionControlType));
EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
.Times(AnyNumber())
.WillRepeatedly(Return(QuicBandwidth::Zero()));
EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
EXPECT_CALL(*send_algorithm_, OnPacketNeutered(_)).Times(AnyNumber());
EXPECT_CALL(*network_change_visitor_, OnPathMtuIncreased(1000))
.Times(AnyNumber());
EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(true));
EXPECT_CALL(notifier_, HasUnackedCryptoData())
.WillRepeatedly(Return(false));
EXPECT_CALL(notifier_, OnStreamFrameRetransmitted(_)).Times(AnyNumber());
EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).WillRepeatedly(Return(true));
}
~QuicSentPacketManagerTest() override {}
QuicByteCount BytesInFlight() { return manager_.GetBytesInFlight(); }
void VerifyUnackedPackets(uint64_t* packets, size_t num_packets) {
if (num_packets == 0) {
EXPECT_TRUE(manager_.unacked_packets().empty());
EXPECT_EQ(0u, QuicSentPacketManagerPeer::GetNumRetransmittablePackets(
&manager_));
return;
}
EXPECT_FALSE(manager_.unacked_packets().empty());
EXPECT_EQ(QuicPacketNumber(packets[0]), manager_.GetLeastUnacked());
for (size_t i = 0; i < num_packets; ++i) {
EXPECT_TRUE(
manager_.unacked_packets().IsUnacked(QuicPacketNumber(packets[i])))
<< packets[i];
}
}
void VerifyRetransmittablePackets(uint64_t* packets, size_t num_packets) {
EXPECT_EQ(
num_packets,
QuicSentPacketManagerPeer::GetNumRetransmittablePackets(&manager_));
for (size_t i = 0; i < num_packets; ++i) {
EXPECT_TRUE(QuicSentPacketManagerPeer::HasRetransmittableFrames(
&manager_, packets[i]))
<< " packets[" << i << "]:" << packets[i];
}
}
void ExpectAck(uint64_t largest_observed) {
EXPECT_CALL(
*send_algorithm_,
OnCongestionEvent(true, _, _,
Pointwise(PacketNumberEq(), {largest_observed}),
IsEmpty(), _, _));
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
}
void ExpectUpdatedRtt(uint64_t ) {
EXPECT_CALL(*send_algorithm_,
OnCongestionEvent(true, _, _, IsEmpty(), IsEmpty(), _, _));
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
}
void ExpectAckAndLoss(bool rtt_updated, uint64_t largest_observed,
uint64_t lost_packet) {
EXPECT_CALL(
*send_algorithm_,
OnCongestionEvent(rtt_updated, _, _,
Pointwise(PacketNumberEq(), {largest_observed}),
Pointwise(PacketNumberEq(), {lost_packet}), _, _));
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
}
void ExpectAcksAndLosses(bool rtt_updated, uint64_t* packets_acked,
size_t num_packets_acked, uint64_t* packets_lost,
size_t num_packets_lost) {
std::vector<QuicPacketNumber> ack_vector;
for (size_t i = 0; i < num_packets_acked; ++i) {
ack_vector.push_back(QuicPacketNumber(packets_acked[i]));
}
std::vector<QuicPacketNumber> lost_vector;
for (size_t i = 0; i < num_packets_lost; ++i) {
lost_vector.push_back(QuicPacketNumber(packets_lost[i]));
}
EXPECT_CALL(*send_algorithm_,
OnCongestionEvent(
rtt_updated, _, _, Pointwise(PacketNumberEq(), ack_vector),
Pointwise(PacketNumberEq(), lost_vector), _, _));
EXPECT_CALL(*network_change_visitor_, OnCongestionChange())
.Times(AnyNumber());
}
void RetransmitAndSendPacket(uint64_t old_packet_number,
uint64_t new_packet_number) {
RetransmitAndSendPacket(old_packet_number, new_packet_number,
PTO_RETRANSMISSION);
}
void RetransmitAndSendPacket(uint64_t old_packet_number,
uint64_t new_packet_number,
TransmissionType transmission_type) {
bool is_lost = false;
if (transmission_type == HANDSHAKE_RETRANSMISSION ||
transmission_type == PTO_RETRANSMISSION) {
EXPECT_CALL(notifier_, RetransmitFrames(_, _))
.WillOnce(WithArgs<1>(
Invoke([this, new_packet_number](TransmissionType type) {
return RetransmitDataPacket(new_packet_number, type);
})));
} else {
EXPECT_CALL(notifier_, OnFrameLost(_)).Times(1);
is_lost = true;
}
QuicSentPacketManagerPeer::MarkForRetransmission(
&manager_, old_packet_number, transmission_type);
if (!is_lost) {
return;
}
EXPECT_CALL(
*send_algorithm_,
OnPacketSent(_, BytesInFlight(), QuicPacketNumber(new_packet_number),
kDefaultLength, HAS_RETRANSMITTABLE_DATA));
SerializedPacket packet(CreatePacket(new_packet_number, true));
manager_.OnPacketSent(&packet, clock_.Now(), transmission_type,
HAS_RETRANSMITTABLE_DATA, true, ECN_NOT_ECT);
}
SerializedPacket CreateDataPacket(uint64_t packet_number) {
return CreatePacket(packet_number, true);
}
SerializedPacket CreatePacket(uint64_t packet_number, bool retransmittable) {
SerializedPacket packet(QuicPacketNumber(packet_number),
PACKET_4BYTE_PACKET_NUMBER, nullptr, kDefaultLength,
false, false);
if (retransmittable) {
packet.retransmittable_frames.push_back(
QuicFrame(QuicStreamFrame(kStreamId, false, 0, absl::string_view())));
}
return packet;
}
SerializedPacket CreatePingPacket(uint64_t packet_number) {
SerializedPacket packet(QuicPacketNumber(packet_number),
PACKET_4BYTE_PACKET_NUMBER, nullptr, kDefaultLength,
false, false);
packet.retransmittable_frames.push_back(QuicFrame(QuicPingFrame()));
return packet;
}
void SendDataPacket(uint64_t packet_number) {
SendDataPacket(packet_number, ENCRYPTION_INITIAL, ECN_NOT_ECT);
}
void SendDataPacket(uint64_t packet_number,
EncryptionLevel encryption_level) {
SendDataPacket(packet_number, encryption_level, ECN_NOT_ECT);
}
void SendDataPacket(uint64_t packet_number, EncryptionLevel encryption_level,
QuicEcnCodepoint ecn_codepoint) {
EXPECT_CALL(*send_algorithm_,
OnPacketSent(_, BytesInFlight(),
QuicPacketNumber(packet_number), _, _));
SerializedPacket packet(CreateDataPacket(packet_number));
packet.encryption_level = encryption_level;
manager_.OnPacketSent(&packet, clock_.Now(), NOT_RETRANSMISSION,
HAS_RETRANSMITTABLE_DATA, true, ecn_codepoint);
}
void SendPingPacket(uint64_t packet_number,
EncryptionLevel encryption_level) {
EXPECT_CALL(*send_algorithm_,
OnPacketSent(_, BytesInFlight(),
QuicPacketNumber(packet_number), _, _));
SerializedPacket packet(CreatePingPacket(packet_number));
packet.encryption_level = encryption_level;
manager_.OnPacketSent(&packet, clock_.Now(), NOT_RETRANSMISSION,
HAS_RETRANSMITTABLE_DATA, true, ECN_NOT_ECT);
}
void SendCryptoPacket(uint64_t packet_number) {
EXPECT_CALL(
*send_algorithm_,
OnPacketSent(_, BytesInFlight(), QuicPacketNumber(packet_number),
kDefaultLength, HAS_RETRANSMITTABLE_DATA));
SerializedPacket packet(CreatePacket(packet_number, false));
packet.retransmittable_frames.push_back(
QuicFrame(QuicStreamFrame(1, false, 0, absl::string_view())));
packet.has_crypto_handshake = IS_HANDSHAKE;
manager_.OnPacketSent(&packet, clock_.Now(), NOT_RETRANSMISSION,
HAS_RETRANSMITTABLE_DATA, true, ECN_NOT_ECT);
EXPECT_CALL(notifier_, HasUnackedCryptoData()).WillRepeatedly(Return(true));
}
void SendAckPacket(uint64_t packet_number, uint64_t largest_acked) {
SendAckPacket(packet_number, largest_acked, ENCRYPTION_INITIAL);
}
void SendAckPacket(uint64_t packet_number, uint64_t largest_acked,
EncryptionLevel level) {
EXPECT_CALL(
*send_algorithm_,
OnPacketSent(_, BytesInFlight(), QuicPacketNumber(packet_number),
kDefaultLength, NO_RETRANSMITTABLE_DATA));
SerializedPacket packet(CreatePacket(packet_number, false));
packet.largest_acked = QuicPacketNumber(largest_acked);
packet.encryption_level = level;
manager_.OnPacketSent(&packet, clock_.Now(), NOT_RETRANSMISSION,
NO_RETRANSMITTABLE_DATA, true, ECN_NOT_ECT);
}
quiche::SimpleBufferAllocator allocator_;
QuicSentPacketManager manager_;
MockClock clock_;
QuicConnectionStats stats_;
MockSendAlgorithm* send_algorithm_;
std::unique_ptr<MockNetworkChangeVisitor> network_change_visitor_;
StrictMock<MockSessionNotifier> notifier_;
};
TEST_F(QuicSentPacketManagerTest, IsUnacked) {
VerifyUnackedPackets(nullptr, 0);
SendDataPacket(1);
uint64_t unacked[] = {1};
VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked));
uint64_t retransmittable[] = {1};
VerifyRetransmittablePackets(retransmittable,
ABSL_ARRAYSIZE(retransmittable));
}
TEST_F(QuicSentPacketManagerTest, IsUnAckedRetransmit) {
SendDataPacket(1);
RetransmitAndSendPacket(1, 2);
EXPECT_TRUE(QuicSentPacketManagerPeer::IsRetransmission(&manager_, 2));
uint64_t unacked[] = {1, 2};
VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked));
std::vector<uint64_t> retransmittable = {1, 2};
VerifyRetransmittablePackets(&retransmittable[0], retransmittable.size());
}
TEST_F(QuicSentPacketManagerTest, RetransmitThenAck) {
SendDataPacket(1);
RetransmitAndSendPacket(1, 2);
ExpectAck(2);
manager_.OnAckFrameStart(QuicPacketNumber(2), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(2), QuicPacketNumber(3));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(false));
uint64_t unacked[] = {1};
VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked));
EXPECT_TRUE(manager_.HasInFlightPackets());
VerifyRetransmittablePackets(nullptr, 0);
}
TEST_F(QuicSentPacketManagerTest, RetransmitThenAckBeforeSend) {
SendDataPacket(1);
EXPECT_CALL(notifier_, RetransmitFrames(_, _))
.WillOnce(WithArgs<1>(Invoke([this](TransmissionType type) {
return RetransmitDataPacket(2, type);
})));
QuicSentPacketManagerPeer::MarkForRetransmission(&manager_, 1,
PTO_RETRANSMISSION);
ExpectAck(1);
manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(false));
uint64_t unacked[] = {2};
VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked));
VerifyRetransmittablePackets(nullptr, 0);
EXPECT_EQ(0u, stats_.packets_spuriously_retransmitted);
}
TEST_F(QuicSentPacketManagerTest, RetransmitThenStopRetransmittingBeforeSend) {
SendDataPacket(1);
EXPECT_CALL(notifier_, RetransmitFrames(_, _)).WillRepeatedly(Return(true));
QuicSentPacketManagerPeer::MarkForRetransmission(&manager_, 1,
PTO_RETRANSMISSION);
EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(false));
uint64_t unacked[] = {1};
VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked));
VerifyRetransmittablePackets(nullptr, 0);
EXPECT_EQ(0u, stats_.packets_spuriously_retransmitted);
}
TEST_F(QuicSentPacketManagerTest, RetransmitThenAckPrevious) {
SendDataPacket(1);
RetransmitAndSendPacket(1, 2);
QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(15);
clock_.AdvanceTime(rtt);
ExpectAck(1);
manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(false));
uint64_t unacked[] = {2};
VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked));
EXPECT_TRUE(manager_.HasInFlightPackets());
VerifyRetransmittablePackets(nullptr, 0);
EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).WillOnce(Return(false));
ExpectAck(2);
manager_.OnAckFrameStart(QuicPacketNumber(2), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(3));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(2),
ENCRYPTION_INITIAL, kEmptyCounts));
EXPECT_EQ(1u, stats_.packets_spuriously_retransmitted);
}
TEST_F(QuicSentPacketManagerTest, RetransmitThenAckPreviousThenNackRetransmit) {
SendDataPacket(1);
RetransmitAndSendPacket(1, 2);
QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(15);
clock_.AdvanceTime(rtt);
ExpectAck(1);
manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
SendDataPacket(3);
SendDataPacket(4);
SendDataPacket(5);
clock_.AdvanceTime(rtt);
EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(false));
EXPECT_CALL(notifier_, OnFrameLost(_)).Times(1);
ExpectAckAndLoss(true, 3, 2);
manager_.OnAckFrameStart(QuicPacketNumber(3), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(3), QuicPacketNumber(4));
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(2),
ENCRYPTION_INITIAL, kEmptyCounts));
ExpectAck(4);
manager_.OnAckFrameStart(QuicPacketNumber(4), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(3), QuicPacketNumber(5));
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(3),
ENCRYPTION_INITIAL, kEmptyCounts));
ExpectAck(5);
manager_.OnAckFrameStart(QuicPacketNumber(5), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(3), QuicPacketNumber(6));
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(4),
ENCRYPTION_INITIAL, kEmptyCounts));
uint64_t unacked[] = {2};
VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked));
EXPECT_FALSE(manager_.HasInFlightPackets());
VerifyRetransmittablePackets(nullptr, 0);
EXPECT_EQ(QuicTime::Zero(), manager_.GetRetransmissionTime());
}
TEST_F(QuicSentPacketManagerTest,
DISABLED_RetransmitTwiceThenAckPreviousBeforeSend) {
SendDataPacket(1);
RetransmitAndSendPacket(1, 2);
EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
manager_.OnRetransmissionTimeout();
ExpectUpdatedRtt(1);
manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
uint64_t unacked[] = {2};
VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked));
EXPECT_FALSE(manager_.HasInFlightPackets());
VerifyRetransmittablePackets(nullptr, 0);
EXPECT_EQ(QuicTime::Zero(), manager_.GetRetransmissionTime());
}
TEST_F(QuicSentPacketManagerTest, RetransmitTwiceThenAckFirst) {
StrictMock<MockDebugDelegate> debug_delegate;
EXPECT_CALL(debug_delegate, OnSpuriousPacketRetransmission(PTO_RETRANSMISSION,
kDefaultLength))
.Times(1);
manager_.SetDebugDelegate(&debug_delegate);
SendDataPacket(1);
RetransmitAndSendPacket(1, 2);
RetransmitAndSendPacket(2, 3);
QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(15);
clock_.AdvanceTime(rtt);
ExpectAck(1);
manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
EXPECT_CALL(notifier_, IsFrameOutstanding(_))
.Times(2)
.WillRepeatedly(Return(false));
uint64_t unacked[] = {2, 3};
VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked));
EXPECT_TRUE(manager_.HasInFlightPackets());
VerifyRetransmittablePackets(nullptr, 0);
SendDataPacket(4);
EXPECT_CALL(notifier_, OnFrameAcked(_, _, _))
.WillOnce(Return(false))
.WillRepeatedly(Return(true));
uint64_t acked[] = {3, 4};
ExpectAcksAndLosses(true, acked, ABSL_ARRAYSIZE(acked), nullptr, 0);
manager_.OnAckFrameStart(QuicPacketNumber(4), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(3), QuicPacketNumber(5));
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(2),
ENCRYPTION_INITIAL, kEmptyCounts));
uint64_t unacked2[] = {2};
VerifyUnackedPackets(unacked2, ABSL_ARRAYSIZE(unacked2));
EXPECT_TRUE(manager_.HasInFlightPackets());
SendDataPacket(5);
ExpectAckAndLoss(true, 5, 2);
EXPECT_CALL(debug_delegate,
OnPacketLoss(QuicPacketNumber(2), _, LOSS_RETRANSMISSION, _));
EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(false));
EXPECT_CALL(notifier_, OnFrameLost(_)).Times(1);
manager_.OnAckFrameStart(QuicPacketNumber(5), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(3), QuicPacketNumber(6));
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(3),
ENCRYPTION_INITIAL, kEmptyCounts));
uint64_t unacked3[] = {2};
VerifyUnackedPackets(unacked3, ABSL_ARRAYSIZE(unacked3));
EXPECT_FALSE(manager_.HasInFlightPackets());
EXPECT_EQ(1u, stats_.packets_spuriously_retransmitted);
EXPECT_EQ(1u, stats_.packets_lost);
EXPECT_LT(0.0, stats_.total_loss_detection_response_time);
EXPECT_LE(1u, stats_.sent_packets_max_sequence_reordering);
}
TEST_F(QuicSentPacketManagerTest, AckOriginalTransmission) {
auto loss_algorithm = std::make_unique<MockLossAlgorithm>();
QuicSentPacketManagerPeer::SetLossAlgorithm(&manager_, loss_algorithm.get());
SendDataPacket(1);
RetransmitAndSendPacket(1, 2);
{
ExpectAck(1);
EXPECT_CALL(*loss_algorithm, DetectLosses(_, _, _, _, _, _));
manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
}
SendDataPacket(3);
SendDataPacket(4);
{
ExpectAck(4);
EXPECT_CALL(*loss_algorithm, DetectLosses(_, _, _, _, _, _));
manager_.OnAckFrameStart(QuicPacketNumber(4), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(4), QuicPacketNumber(5));
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(2),
ENCRYPTION_INITIAL, kEmptyCounts));
RetransmitAndSendPacket(3, 5, LOSS_RETRANSMISSION);
}
{
uint64_t acked[] = {3};
ExpectAcksAndLosses(false, acked, ABSL_ARRAYSIZE(acked), nullptr, 0);
EXPECT_CALL(*loss_algorithm, DetectLosses(_, _, _, _, _, _));
EXPECT_CALL(*loss_algorithm,
SpuriousLossDetected(_, _, _, QuicPacketNumber(3),
QuicPacketNumber(4)));
manager_.OnAckFrameStart(QuicPacketNumber(4), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(3), QuicPacketNumber(5));
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(0u, stats_.packet_spuriously_detected_lost);
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(3),
ENCRYPTION_INITIAL, kEmptyCounts));
EXPECT_EQ(1u, stats_.packet_spuriously_detected_lost);
ExpectAck(5);
EXPECT_CALL(*loss_algorithm, DetectLosses(_, _, _, _, _, _));
EXPECT_CALL(notifier_, OnFrameAcked(_, _, _)).WillOnce(Return(false));
manager_.OnAckFrameStart(QuicPacketNumber(5), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(3), QuicPacketNumber(6));
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(4),
ENCRYPTION_INITIAL, kEmptyCounts));
}
}
TEST_F(QuicSentPacketManagerTest, GetLeastUnacked) {
EXPECT_EQ(QuicPacketNumber(1u), manager_.GetLeastUnacked());
}
TEST_F(QuicSentPacketManagerTest, GetLeastUnackedUnacked) {
SendDataPacket(1);
EXPECT_EQ(QuicPacketNumber(1u), manager_.GetLeastUnacked());
}
TEST_F(QuicSentPacketManagerTest, AckAckAndUpdateRtt) {
EXPECT_FALSE(manager_.largest_packet_peer_knows_is_acked().IsInitialized());
SendDataPacket(1);
SendAckPacket(2, 1);
uint64_t acked[] = {1, 2};
ExpectAcksAndLosses(true, acked, ABSL_ARRAYSIZE(acked), nullptr, 0);
manager_.OnAckFrameStart(QuicPacketNumber(2),
QuicTime::Delta::FromMilliseconds(5), clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(3));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
EXPECT_EQ(QuicPacketNumber(1), manager_.largest_packet_peer_knows_is_acked());
SendAckPacket(3, 3);
uint64_t acked2[] = {3};
ExpectAcksAndLosses(true, acked2, ABSL_ARRAYSIZE(acked2), nullptr, 0);
manager_.OnAckFrameStart(QuicPacketNumber(3), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(4));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(2),
ENCRYPTION_INITIAL, kEmptyCounts));
EXPECT_EQ(QuicPacketNumber(3u),
manager_.largest_packet_peer_knows_is_acked());
}
TEST_F(QuicSentPacketManagerTest, Rtt) {
QuicTime::Delta expected_rtt = QuicTime::Delta::FromMilliseconds(20);
SendDataPacket(1);
clock_.AdvanceTime(expected_rtt);
ExpectAck(1);
manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
EXPECT_EQ(expected_rtt, manager_.GetRttStats()->latest_rtt());
}
TEST_F(QuicSentPacketManagerTest, RttWithInvalidDelta) {
QuicTime::Delta expected_rtt = QuicTime::Delta::FromMilliseconds(10);
SendDataPacket(1);
clock_.AdvanceTime(expected_rtt);
ExpectAck(1);
manager_.OnAckFrameStart(QuicPacketNumber(1),
QuicTime::Delta::FromMilliseconds(11), clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
EXPECT_EQ(expected_rtt, manager_.GetRttStats()->latest_rtt());
}
TEST_F(QuicSentPacketManagerTest, RttWithInfiniteDelta) {
QuicTime::Delta expected_rtt = QuicTime::Delta::FromMilliseconds(10);
SendDataPacket(1);
clock_.AdvanceTime(expected_rtt);
ExpectAck(1);
manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
EXPECT_EQ(expected_rtt, manager_.GetRttStats()->latest_rtt());
}
TEST_F(QuicSentPacketManagerTest, RttWithDeltaExceedingLimit) {
RttStats* rtt_stats = const_cast<RttStats*>(manager_.GetRttStats());
rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(10),
QuicTime::Delta::Zero(), QuicTime::Zero());
QuicTime::Delta send_delta = QuicTime::Delta::FromMilliseconds(100);
QuicTime::Delta ack_delay =
QuicTime::Delta::FromMilliseconds(5) + manager_.peer_max_ack_delay();
ASSERT_GT(send_delta - rtt_stats->min_rtt(), ack_delay);
SendDataPacket(1);
clock_.AdvanceTime(send_delta);
ExpectAck(1);
manager_.OnAckFrameStart(QuicPacketNumber(1), ack_delay, clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_FORWARD_SECURE, kEmptyCounts));
QuicTime::Delta expected_rtt_sample =
send_delta - manager_.peer_max_ack_delay();
EXPECT_EQ(expected_rtt_sample, manager_.GetRttStats()->latest_rtt());
}
TEST_F(QuicSentPacketManagerTest, RttZeroDelta) {
QuicTime::Delta expected_rtt = QuicTime::Delta::FromMilliseconds(10);
SendDataPacket(1);
clock_.AdvanceTime(expected_rtt);
ExpectAck(1);
manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Zero(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
EXPECT_EQ(expected_rtt, manager_.GetRttStats()->latest_rtt());
}
TEST_F(QuicSentPacketManagerTest, CryptoHandshakeTimeout) {
const size_t kNumSentCryptoPackets = 2;
for (size_t i = 1; i <= kNumSentCryptoPackets; ++i) {
SendCryptoPacket(i);
}
const size_t kNumSentDataPackets = 3;
for (size_t i = 1; i <= kNumSentDataPackets; ++i) {
SendDataPacket(kNumSentCryptoPackets + i);
}
EXPECT_TRUE(manager_.HasUnackedCryptoPackets());
EXPECT_EQ(5 * kDefaultLength, manager_.GetBytesInFlight());
EXPECT_CALL(notifier_, RetransmitFrames(_, _))
.Times(2)
.WillOnce(
InvokeWithoutArgs([this]() { return RetransmitCryptoPacket(6); }))
.WillOnce(
InvokeWithoutArgs([this]() { return RetransmitCryptoPacket(7); }));
manager_.OnRetransmissionTimeout();
EXPECT_EQ(7 * kDefaultLength, manager_.GetBytesInFlight());
EXPECT_TRUE(manager_.HasUnackedCryptoPackets());
EXPECT_CALL(notifier_, RetransmitFrames(_, _))
.Times(2)
.WillOnce(
InvokeWithoutArgs([this]() { return RetransmitCryptoPacket(8); }))
.WillOnce(
InvokeWithoutArgs([this]() { return RetransmitCryptoPacket(9); }));
manager_.OnRetransmissionTimeout();
EXPECT_EQ(9 * kDefaultLength, manager_.GetBytesInFlight());
EXPECT_TRUE(manager_.HasUnackedCryptoPackets());
uint64_t acked[] = {3, 4, 5, 8, 9};
uint64_t lost[] = {1, 2, 6};
ExpectAcksAndLosses(true, acked, ABSL_ARRAYSIZE(acked), lost,
ABSL_ARRAYSIZE(lost));
EXPECT_CALL(notifier_, OnFrameLost(_)).Times(3);
EXPECT_CALL(notifier_, HasUnackedCryptoData()).WillRepeatedly(Return(false));
manager_.OnAckFrameStart(QuicPacketNumber(9), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(8), QuicPacketNumber(10));
manager_.OnAckRange(QuicPacketNumber(3), QuicPacketNumber(6));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
EXPECT_FALSE(manager_.HasUnackedCryptoPackets());
}
TEST_F(QuicSentPacketManagerTest, CryptoHandshakeSpuriousRetransmission) {
SendCryptoPacket(1);
EXPECT_TRUE(manager_.HasUnackedCryptoPackets());
EXPECT_CALL(notifier_, RetransmitFrames(_, _))
.WillOnce(
InvokeWithoutArgs([this]() { return RetransmitCryptoPacket(2); }));
manager_.OnRetransmissionTimeout();
EXPECT_CALL(notifier_, RetransmitFrames(_, _))
.WillOnce(
InvokeWithoutArgs([this]() { return RetransmitCryptoPacket(3); }));
manager_.OnRetransmissionTimeout();
uint64_t acked[] = {2};
ExpectAcksAndLosses(true, acked, ABSL_ARRAYSIZE(acked), nullptr, 0);
EXPECT_CALL(notifier_, HasUnackedCryptoData()).WillRepeatedly(Return(false));
EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(false));
manager_.OnAckFrameStart(QuicPacketNumber(2), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(2), QuicPacketNumber(3));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
EXPECT_FALSE(manager_.HasUnackedCryptoPackets());
uint64_t unacked[] = {1, 3};
VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked));
}
TEST_F(QuicSentPacketManagerTest, CryptoHandshakeTimeoutUnsentDataPacket) {
const size_t kNumSentCryptoPackets = 2;
for (size_t i = 1; i <= kNumSentCryptoPackets; ++i) {
SendCryptoPacket(i);
}
SendDataPacket(3);
EXPECT_TRUE(manager_.HasUnackedCryptoPackets());
EXPECT_CALL(notifier_, RetransmitFrames(_, _))
.Times(2)
.WillOnce(
InvokeWithoutArgs([this]() { return RetransmitCryptoPacket(4); }))
.WillOnce(
InvokeWithoutArgs([this]() { return RetransmitCryptoPacket(5); }));
manager_.OnRetransmissionTimeout();
EXPECT_TRUE(manager_.HasUnackedCryptoPackets());
}
TEST_F(QuicSentPacketManagerTest,
CryptoHandshakeRetransmissionThenNeuterAndAck) {
SendCryptoPacket(1);
EXPECT_TRUE(manager_.HasUnackedCryptoPackets());
EXPECT_CALL(notifier_, RetransmitFrames(_, _))
.WillOnce(
InvokeWithoutArgs([this]() { return RetransmitCryptoPacket(2); }));
manager_.OnRetransmissionTimeout();
EXPECT_TRUE(manager_.HasUnackedCryptoPackets());
EXPECT_CALL(notifier_, RetransmitFrames(_, _))
.WillOnce(
InvokeWithoutArgs([this]() { return RetransmitCryptoPacket(3); }));
manager_.OnRetransmissionTimeout();
EXPECT_TRUE(manager_.HasUnackedCryptoPackets());
EXPECT_CALL(notifier_, HasUnackedCryptoData()).WillRepeatedly(Return(false));
EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(false));
manager_.NeuterUnencryptedPackets();
EXPECT_FALSE(manager_.HasUnackedCryptoPackets());
uint64_t unacked[] = {1, 2, 3};
VerifyUnackedPackets(unacked, ABSL_ARRAYSIZE(unacked));
VerifyRetransmittablePackets(nullptr, 0);
EXPECT_FALSE(manager_.HasUnackedCryptoPackets());
EXPECT_FALSE(manager_.HasInFlightPackets());
uint64_t acked[] = {3};
ExpectAcksAndLosses(true, acked, ABSL_ARRAYSIZE(acked), nullptr, 0);
manager_.OnAckFrameStart(QuicPacketNumber(3), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(3), QuicPacketNumber(4));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
VerifyUnackedPackets(nullptr, 0);
VerifyRetransmittablePackets(nullptr, 0);
}
TEST_F(QuicSentPacketManagerTest, GetTransmissionTime) {
EXPECT_EQ(QuicTime::Zero(), manager_.GetRetransmissionTime());
}
TEST_F(QuicSentPacketManagerTest, GetTransmissionTimeCryptoHandshake) {
QuicTime crypto_packet_send_time = clock_.Now();
SendCryptoPacket(1);
RttStats* rtt_stats = const_cast<RttStats*>(manager_.GetRttStats());
rtt_stats->set_initial_rtt(QuicTime::Delta::FromMilliseconds(1));
EXPECT_EQ(clock_.Now() + QuicTime::Delta::FromMilliseconds(10),
manager_.GetRetransmissionTime());
rtt_stats->set_initial_rtt(QuicTime::Delta::FromMilliseconds(100));
QuicTime::Delta srtt = rtt_stats->initial_rtt();
QuicTime expected_time = clock_.Now() + 1.5 * srtt;
EXPECT_EQ(expected_time, manager_.GetRetransmissionTime());
clock_.AdvanceTime(1.5 * srtt);
EXPECT_CALL(notifier_, RetransmitFrames(_, _))
.WillOnce(
InvokeWithoutArgs([this]() { return RetransmitCryptoPacket(2); }));
crypto_packet_send_time = clock_.Now();
manager_.OnRetransmissionTimeout();
expected_time = crypto_packet_send_time + srtt * 2 * 1.5;
EXPECT_EQ(expected_time, manager_.GetRetransmissionTime());
clock_.AdvanceTime(2 * 1.5 * srtt);
EXPECT_CALL(notifier_, RetransmitFrames(_, _))
.WillOnce(
InvokeWithoutArgs([this]() { return RetransmitCryptoPacket(3); }));
crypto_packet_send_time = clock_.Now();
manager_.OnRetransmissionTimeout();
expected_time = crypto_packet_send_time + srtt * 4 * 1.5;
EXPECT_EQ(expected_time, manager_.GetRetransmissionTime());
}
TEST_F(QuicSentPacketManagerTest,
GetConservativeTransmissionTimeCryptoHandshake) {
QuicConfig config;
QuicTagVector options;
options.push_back(kCONH);
QuicConfigPeer::SetReceivedConnectionOptions(&config, options);
EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
manager_.SetFromConfig(config);
EXPECT_CALL(*send_algorithm_, PacingRate(_))
.WillRepeatedly(Return(QuicBandwidth::Zero()));
EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
.WillRepeatedly(Return(10 * kDefaultTCPMSS));
QuicTime crypto_packet_send_time = clock_.Now();
SendCryptoPacket(1);
RttStats* rtt_stats = const_cast<RttStats*>(manager_.GetRttStats());
rtt_stats->set_initial_rtt(QuicTime::Delta::FromMilliseconds(1));
EXPECT_EQ(clock_.Now() + QuicTime::Delta::FromMilliseconds(25),
manager_.GetRetransmissionTime());
rtt_stats->set_initial_rtt(QuicTime::Delta::FromMilliseconds(100));
QuicTime::Delta srtt = rtt_stats->initial_rtt();
QuicTime expected_time = clock_.Now() + 2 * srtt;
EXPECT_EQ(expected_time, manager_.GetRetransmissionTime());
clock_.AdvanceTime(2 * srtt);
EXPECT_CALL(notifier_, RetransmitFrames(_, _))
.WillOnce(
InvokeWithoutArgs([this]() { return RetransmitCryptoPacket(2); }));
crypto_packet_send_time = clock_.Now();
manager_.OnRetransmissionTimeout();
expected_time = crypto_packet_send_time + srtt * 2 * 2;
EXPECT_EQ(expected_time, manager_.GetRetransmissionTime());
}
TEST_F(QuicSentPacketManagerTest, GetLossDelay) {
auto loss_algorithm = std::make_unique<MockLossAlgorithm>();
QuicSentPacketManagerPeer::SetLossAlgorithm(&manager_, loss_algorithm.get());
EXPECT_CALL(*loss_algorithm, GetLossTimeout())
.WillRepeatedly(Return(QuicTime::Zero()));
SendDataPacket(1);
SendDataPacket(2);
ExpectAck(2);
EXPECT_CALL(*loss_algorithm, DetectLosses(_, _, _, _, _, _));
manager_.OnAckFrameStart(QuicPacketNumber(2), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(2), QuicPacketNumber(3));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
QuicTime timeout(clock_.Now() + QuicTime::Delta::FromMilliseconds(10));
EXPECT_CALL(*loss_algorithm, GetLossTimeout())
.WillRepeatedly(Return(timeout));
EXPECT_EQ(timeout, manager_.GetRetransmissionTime());
EXPECT_CALL(*loss_algorithm, DetectLosses(_, _, _, _, _, _));
manager_.OnRetransmissionTimeout();
}
TEST_F(QuicSentPacketManagerTest, NegotiateIetfLossDetectionFromOptions) {
EXPECT_TRUE(
QuicSentPacketManagerPeer::AdaptiveReorderingThresholdEnabled(&manager_));
EXPECT_FALSE(
QuicSentPacketManagerPeer::AdaptiveTimeThresholdEnabled(&manager_));
EXPECT_EQ(kDefaultLossDelayShift,
QuicSentPacketManagerPeer::GetReorderingShift(&manager_));
QuicConfig config;
QuicTagVector options;
options.push_back(kILD0);
QuicConfigPeer::SetReceivedConnectionOptions(&config, options);
EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
manager_.SetFromConfig(config);
EXPECT_EQ(3, QuicSentPacketManagerPeer::GetReorderingShift(&manager_));
EXPECT_FALSE(
QuicSentPacketManagerPeer::AdaptiveReorderingThresholdEnabled(&manager_));
}
TEST_F(QuicSentPacketManagerTest,
NegotiateIetfLossDetectionOneFourthRttFromOptions) {
EXPECT_TRUE(
QuicSentPacketManagerPeer::AdaptiveReorderingThresholdEnabled(&manager_));
EXPECT_FALSE(
QuicSentPacketManagerPeer::AdaptiveTimeThresholdEnabled(&manager_));
EXPECT_EQ(kDefaultLossDelayShift,
QuicSentPacketManagerPeer::GetReorderingShift(&manager_));
QuicConfig config;
QuicTagVector options;
options.push_back(kILD1);
QuicConfigPeer::SetReceivedConnectionOptions(&config, options);
EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
manager_.SetFromConfig(config);
EXPECT_EQ(kDefaultLossDelayShift,
QuicSentPacketManagerPeer::GetReorderingShift(&manager_));
EXPECT_FALSE(
QuicSentPacketManagerPeer::AdaptiveReorderingThresholdEnabled(&manager_));
}
TEST_F(QuicSentPacketManagerTest,
NegotiateIetfLossDetectionAdaptiveReorderingThreshold) {
EXPECT_TRUE(
QuicSentPacketManagerPeer::AdaptiveReorderingThresholdEnabled(&manager_));
EXPECT_FALSE(
QuicSentPacketManagerPeer::AdaptiveTimeThresholdEnabled(&manager_));
EXPECT_EQ(kDefaultLossDelayShift,
QuicSentPacketManagerPeer::GetReorderingShift(&manager_));
QuicConfig config;
QuicTagVector options;
options.push_back(kILD2);
QuicConfigPeer::SetReceivedConnectionOptions(&config, options);
EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
manager_.SetFromConfig(config);
EXPECT_EQ(3, QuicSentPacketManagerPeer::GetReorderingShift(&manager_));
EXPECT_TRUE(
QuicSentPacketManagerPeer::AdaptiveReorderingThresholdEnabled(&manager_));
}
TEST_F(QuicSentPacketManagerTest,
NegotiateIetfLossDetectionAdaptiveReorderingThreshold2) {
EXPECT_TRUE(
QuicSentPacketManagerPeer::AdaptiveReorderingThresholdEnabled(&manager_));
EXPECT_FALSE(
QuicSentPacketManagerPeer::AdaptiveTimeThresholdEnabled(&manager_));
EXPECT_EQ(kDefaultLossDelayShift,
QuicSentPacketManagerPeer::GetReorderingShift(&manager_));
QuicConfig config;
QuicTagVector options;
options.push_back(kILD3);
QuicConfigPeer::SetReceivedConnectionOptions(&config, options);
EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
manager_.SetFromConfig(config);
EXPECT_EQ(kDefaultLossDelayShift,
QuicSentPacketManagerPeer::GetReorderingShift(&manager_));
EXPECT_TRUE(
QuicSentPacketManagerPeer::AdaptiveReorderingThresholdEnabled(&manager_));
}
TEST_F(QuicSentPacketManagerTest,
NegotiateIetfLossDetectionAdaptiveReorderingAndTimeThreshold) {
EXPECT_TRUE(
QuicSentPacketManagerPeer::AdaptiveReorderingThresholdEnabled(&manager_));
EXPECT_FALSE(
QuicSentPacketManagerPeer::AdaptiveTimeThresholdEnabled(&manager_));
EXPECT_EQ(kDefaultLossDelayShift,
QuicSentPacketManagerPeer::GetReorderingShift(&manager_));
QuicConfig config;
QuicTagVector options;
options.push_back(kILD4);
QuicConfigPeer::SetReceivedConnectionOptions(&config, options);
EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
manager_.SetFromConfig(config);
EXPECT_EQ(kDefaultLossDelayShift,
QuicSentPacketManagerPeer::GetReorderingShift(&manager_));
EXPECT_TRUE(
QuicSentPacketManagerPeer::AdaptiveReorderingThresholdEnabled(&manager_));
EXPECT_TRUE(
QuicSentPacketManagerPeer::AdaptiveTimeThresholdEnabled(&manager_));
}
TEST_F(QuicSentPacketManagerTest, NegotiateCongestionControlFromOptions) {
QuicConfig config;
QuicTagVector options;
options.push_back(kRENO);
QuicConfigPeer::SetReceivedConnectionOptions(&config, options);
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
manager_.SetFromConfig(config);
EXPECT_EQ(kRenoBytes, QuicSentPacketManagerPeer::GetSendAlgorithm(manager_)
->GetCongestionControlType());
options.clear();
options.push_back(kTBBR);
QuicConfigPeer::SetReceivedConnectionOptions(&config, options);
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
manager_.SetFromConfig(config);
EXPECT_EQ(kBBR, QuicSentPacketManagerPeer::GetSendAlgorithm(manager_)
->GetCongestionControlType());
options.clear();
options.push_back(kBYTE);
QuicConfigPeer::SetReceivedConnectionOptions(&config, options);
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
manager_.SetFromConfig(config);
EXPECT_EQ(kCubicBytes, QuicSentPacketManagerPeer::GetSendAlgorithm(manager_)
->GetCongestionControlType());
options.clear();
options.push_back(kRENO);
options.push_back(kBYTE);
QuicConfigPeer::SetReceivedConnectionOptions(&config, options);
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
manager_.SetFromConfig(config);
EXPECT_EQ(kRenoBytes, QuicSentPacketManagerPeer::GetSendAlgorithm(manager_)
->GetCongestionControlType());
}
TEST_F(QuicSentPacketManagerTest, NegotiateClientCongestionControlFromOptions) {
QuicConfig config;
QuicTagVector options;
const SendAlgorithmInterface* mock_sender =
QuicSentPacketManagerPeer::GetSendAlgorithm(manager_);
options.push_back(kRENO);
config.SetClientConnectionOptions(options);
EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
manager_.SetFromConfig(config);
EXPECT_EQ(mock_sender, QuicSentPacketManagerPeer::GetSendAlgorithm(manager_));
QuicSentPacketManagerPeer::SetPerspective(&manager_, Perspective::IS_CLIENT);
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
manager_.SetFromConfig(config);
EXPECT_EQ(kRenoBytes, QuicSentPacketManagerPeer::GetSendAlgorithm(manager_)
->GetCongestionControlType());
options.clear();
options.push_back(kTBBR);
config.SetClientConnectionOptions(options);
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
manager_.SetFromConfig(config);
EXPECT_EQ(kBBR, QuicSentPacketManagerPeer::GetSendAlgorithm(manager_)
->GetCongestionControlType());
options.clear();
options.push_back(kBYTE);
config.SetClientConnectionOptions(options);
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
manager_.SetFromConfig(config);
EXPECT_EQ(kCubicBytes, QuicSentPacketManagerPeer::GetSendAlgorithm(manager_)
->GetCongestionControlType());
options.clear();
options.push_back(kRENO);
options.push_back(kBYTE);
config.SetClientConnectionOptions(options);
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
manager_.SetFromConfig(config);
EXPECT_EQ(kRenoBytes, QuicSentPacketManagerPeer::GetSendAlgorithm(manager_)
->GetCongestionControlType());
}
TEST_F(QuicSentPacketManagerTest, UseInitialRoundTripTimeToSend) {
QuicTime::Delta initial_rtt = QuicTime::Delta::FromMilliseconds(325);
EXPECT_NE(initial_rtt, manager_.GetRttStats()->smoothed_rtt());
QuicConfig config;
config.SetInitialRoundTripTimeUsToSend(initial_rtt.ToMicroseconds());
EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
manager_.SetFromConfig(config);
EXPECT_EQ(QuicTime::Delta::Zero(), manager_.GetRttStats()->smoothed_rtt());
EXPECT_EQ(initial_rtt, manager_.GetRttStats()->initial_rtt());
}
TEST_F(QuicSentPacketManagerTest, ResumeConnectionState) {
const QuicTime::Delta kRtt = QuicTime::Delta::FromMilliseconds(123);
CachedNetworkParameters cached_network_params;
cached_network_params.set_min_rtt_ms(kRtt.ToMilliseconds());
SendAlgorithmInterface::NetworkParams params;
params.bandwidth = QuicBandwidth::Zero();
params.allow_cwnd_to_decrease = false;
params.rtt = kRtt;
params.is_rtt_trusted = true;
EXPECT_CALL(*send_algorithm_, AdjustNetworkParameters(params));
EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
.Times(testing::AnyNumber());
manager_.ResumeConnectionState(cached_network_params, false);
EXPECT_EQ(kRtt, manager_.GetRttStats()->initial_rtt());
}
TEST_F(QuicSentPacketManagerTest, ConnectionMigrationUnspecifiedChange) {
RttStats* rtt_stats = const_cast<RttStats*>(manager_.GetRttStats());
QuicTime::Delta default_init_rtt = rtt_stats->initial_rtt();
rtt_stats->set_initial_rtt(default_init_rtt * 2);
EXPECT_EQ(2 * default_init_rtt, rtt_stats->initial_rtt());
QuicSentPacketManagerPeer::SetConsecutivePtoCount(&manager_, 1);
EXPECT_EQ(1u, manager_.GetConsecutivePtoCount());
EXPECT_CALL(*send_algorithm_, OnConnectionMigration());
EXPECT_EQ(nullptr,
manager_.OnConnectionMigration(false));
EXPECT_EQ(default_init_rtt, rtt_stats->initial_rtt());
EXPECT_EQ(0u, manager_.GetConsecutivePtoCount());
}
TEST_F(QuicSentPacketManagerTest,
ConnectionMigrationUnspecifiedChangeResetSendAlgorithm) {
auto loss_algorithm = std::make_unique<MockLossAlgorithm>();
QuicSentPacketManagerPeer::SetLossAlgorithm(&manager_, loss_algorithm.get());
RttStats* rtt_stats = const_cast<RttStats*>(manager_.GetRttStats());
QuicTime::Delta default_init_rtt = rtt_stats->initial_rtt();
rtt_stats->set_initial_rtt(default_init_rtt * 2);
EXPECT_EQ(2 * default_init_rtt, rtt_stats->initial_rtt());
QuicSentPacketManagerPeer::SetConsecutivePtoCount(&manager_, 1);
EXPECT_EQ(1u, manager_.GetConsecutivePtoCount());
SendDataPacket(1, ENCRYPTION_FORWARD_SECURE);
RttStats old_rtt_stats;
old_rtt_stats.CloneFrom(*manager_.GetRttStats());
EXPECT_CALL(notifier_, OnFrameLost(_));
std::unique_ptr<SendAlgorithmInterface> old_send_algorithm =
manager_.OnConnectionMigration(true);
EXPECT_NE(old_send_algorithm.get(), manager_.GetSendAlgorithm());
EXPECT_EQ(old_send_algorithm->GetCongestionControlType(),
manager_.GetSendAlgorithm()->GetCongestionControlType());
EXPECT_EQ(default_init_rtt, rtt_stats->initial_rtt());
EXPECT_EQ(0u, manager_.GetConsecutivePtoCount());
EXPECT_EQ(0u, BytesInFlight());
manager_.SetSendAlgorithm(old_send_algorithm.release());
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
RetransmitDataPacket(2, LOSS_RETRANSMISSION, ENCRYPTION_FORWARD_SECURE);
EXPECT_EQ(kDefaultLength, BytesInFlight());
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
EXPECT_CALL(
*send_algorithm_,
OnCongestionEvent(false, kDefaultLength, _, _, _, _, _))
.WillOnce(testing::WithArg<3>(
Invoke([](const AckedPacketVector& acked_packets) {
EXPECT_EQ(1u, acked_packets.size());
EXPECT_EQ(QuicPacketNumber(1), acked_packets[0].packet_number);
EXPECT_EQ(0u, acked_packets[0].bytes_acked);
})));
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_CALL(*loss_algorithm, DetectLosses(_, _, _, _, _, _));
EXPECT_CALL(*loss_algorithm, SpuriousLossDetected(_, _, _, _, _)).Times(0u);
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_FORWARD_SECURE, kEmptyCounts));
EXPECT_TRUE(manager_.GetRttStats()->latest_rtt().IsZero());
manager_.OnAckFrameStart(QuicPacketNumber(2), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(2), QuicPacketNumber(3));
EXPECT_CALL(*loss_algorithm, DetectLosses(_, _, _, _, _, _));
EXPECT_CALL(
*send_algorithm_,
OnCongestionEvent(true, kDefaultLength, _, _, _, _, _))
.WillOnce(testing::WithArg<3>(
Invoke([](const AckedPacketVector& acked_packets) {
EXPECT_EQ(1u, acked_packets.size());
EXPECT_EQ(QuicPacketNumber(2), acked_packets[0].packet_number);
EXPECT_EQ(kDefaultLength, acked_packets[0].bytes_acked);
})));
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(2),
ENCRYPTION_FORWARD_SECURE, kEmptyCounts));
EXPECT_EQ(0u, BytesInFlight());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10),
manager_.GetRttStats()->latest_rtt());
SendDataPacket(3, ENCRYPTION_FORWARD_SECURE);
EXPECT_CALL(*loss_algorithm, GetLossTimeout())
.WillOnce(Return(clock_.Now() + QuicTime::Delta::FromMilliseconds(10)));
EXPECT_CALL(*loss_algorithm, DetectLosses(_, _, _, _, _, _))
.WillOnce(WithArgs<5>(Invoke([](LostPacketVector* packet_lost) {
packet_lost->emplace_back(QuicPacketNumber(3u), kDefaultLength);
return LossDetectionInterface::DetectionStats();
})));
EXPECT_CALL(notifier_, OnFrameLost(_));
EXPECT_CALL(*send_algorithm_,
OnCongestionEvent(false, kDefaultLength, _, _, _, _, _));
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
manager_.OnRetransmissionTimeout();
EXPECT_EQ(0u, BytesInFlight());
old_send_algorithm =
manager_.OnConnectionMigration(true);
EXPECT_NE(old_send_algorithm.get(), manager_.GetSendAlgorithm());
EXPECT_EQ(old_send_algorithm->GetCongestionControlType(),
manager_.GetSendAlgorithm()->GetCongestionControlType());
EXPECT_EQ(default_init_rtt, rtt_stats->initial_rtt());
EXPECT_EQ(0u, manager_.GetConsecutivePtoCount());
EXPECT_EQ(0u, BytesInFlight());
EXPECT_TRUE(manager_.GetRttStats()->latest_rtt().IsZero());
manager_.SetSendAlgorithm(old_send_algorithm.release());
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(30));
manager_.OnAckFrameStart(QuicPacketNumber(3), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(3), QuicPacketNumber(4));
EXPECT_CALL(*loss_algorithm, DetectLosses(_, _, _, _, _, _));
EXPECT_CALL(*loss_algorithm, SpuriousLossDetected(_, _, _, _, _)).Times(0u);
EXPECT_CALL(*send_algorithm_,
OnCongestionEvent(false, 0, _, _, _, _, _));
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(3),
ENCRYPTION_FORWARD_SECURE, kEmptyCounts));
EXPECT_EQ(0u, BytesInFlight());
EXPECT_TRUE(manager_.GetRttStats()->latest_rtt().IsZero());
SendDataPacket(4, ENCRYPTION_FORWARD_SECURE);
EXPECT_CALL(*loss_algorithm, GetLossTimeout())
.WillOnce(Return(clock_.Now() + QuicTime::Delta::FromMilliseconds(10)));
EXPECT_CALL(*loss_algorithm, DetectLosses(_, _, _, _, _, _))
.WillOnce(WithArgs<5>(Invoke([](LostPacketVector* packet_lost) {
packet_lost->emplace_back(QuicPacketNumber(4u), kDefaultLength);
return LossDetectionInterface::DetectionStats();
})));
EXPECT_CALL(notifier_, OnFrameLost(_));
EXPECT_CALL(*send_algorithm_,
OnCongestionEvent(false, kDefaultLength, _, _, _, _, _));
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
manager_.OnRetransmissionTimeout();
EXPECT_EQ(0u, BytesInFlight());
RetransmitDataPacket(5, LOSS_RETRANSMISSION, ENCRYPTION_FORWARD_SECURE);
EXPECT_EQ(kDefaultLength, BytesInFlight());
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(30));
manager_.OnAckFrameStart(QuicPacketNumber(4), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(4), QuicPacketNumber(5));
EXPECT_CALL(*loss_algorithm, DetectLosses(_, _, _, _, _, _));
EXPECT_CALL(*loss_algorithm, SpuriousLossDetected(_, _, _, _, _));
EXPECT_CALL(
*send_algorithm_,
OnCongestionEvent(true, kDefaultLength, _, _, _, _, _));
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
EXPECT_CALL(notifier_, OnFrameAcked(_, _, _));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(3),
ENCRYPTION_FORWARD_SECURE, kEmptyCounts));
EXPECT_EQ(kDefaultLength, BytesInFlight());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(30),
manager_.GetRttStats()->latest_rtt());
EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillOnce(Return(false));
EXPECT_CALL(notifier_, OnFrameLost(_)).Times(0u);
old_send_algorithm =
manager_.OnConnectionMigration(true);
EXPECT_EQ(default_init_rtt, rtt_stats->initial_rtt());
EXPECT_EQ(0u, manager_.GetConsecutivePtoCount());
EXPECT_EQ(0u, BytesInFlight());
EXPECT_TRUE(manager_.GetRttStats()->latest_rtt().IsZero());
manager_.SetSendAlgorithm(old_send_algorithm.release());
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
manager_.OnAckFrameStart(QuicPacketNumber(5), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(5), QuicPacketNumber(6));
EXPECT_CALL(*loss_algorithm, DetectLosses(_, _, _, _, _, _));
EXPECT_CALL(*loss_algorithm, SpuriousLossDetected(_, _, _, _, _)).Times(0u);
EXPECT_CALL(*send_algorithm_,
OnCongestionEvent(false, 0, _, _, _, _, _));
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
EXPECT_CALL(notifier_, OnFrameAcked(_, _, _));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(3),
ENCRYPTION_FORWARD_SECURE, kEmptyCounts));
EXPECT_EQ(0u, BytesInFlight());
EXPECT_TRUE(manager_.GetRttStats()->latest_rtt().IsZero());
}
TEST_F(QuicSentPacketManagerTest, PathMtuIncreased) {
EXPECT_CALL(*send_algorithm_,
OnPacketSent(_, BytesInFlight(), QuicPacketNumber(1), _, _));
SerializedPacket packet(QuicPacketNumber(1), PACKET_4BYTE_PACKET_NUMBER,
nullptr, kDefaultLength + 100, false, false);
manager_.OnPacketSent(&packet, clock_.Now(), NOT_RETRANSMISSION,
HAS_RETRANSMITTABLE_DATA, true, ECN_NOT_ECT);
ExpectAck(1);
EXPECT_CALL(*network_change_visitor_,
OnPathMtuIncreased(kDefaultLength + 100));
QuicAckFrame ack_frame = InitAckFrame(1);
manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
}
TEST_F(QuicSentPacketManagerTest, OnAckRangeSlowPath) {
for (size_t i = 1; i <= 20; ++i) {
SendDataPacket(i);
}
uint64_t acked1[] = {5, 6, 10, 11, 15, 16};
uint64_t lost1[] = {1, 2, 3, 4, 7, 8, 9, 12, 13};
ExpectAcksAndLosses(true, acked1, ABSL_ARRAYSIZE(acked1), lost1,
ABSL_ARRAYSIZE(lost1));
EXPECT_CALL(notifier_, OnFrameLost(_)).Times(AnyNumber());
manager_.OnAckFrameStart(QuicPacketNumber(16), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(15), QuicPacketNumber(17));
manager_.OnAckRange(QuicPacketNumber(10), QuicPacketNumber(12));
manager_.OnAckRange(QuicPacketNumber(5), QuicPacketNumber(7));
manager_.OnAckRange(QuicPacketNumber(4), QuicPacketNumber(4));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
uint64_t acked2[] = {4, 7, 9, 12, 14, 17, 18, 19, 20};
ExpectAcksAndLosses(true, acked2, ABSL_ARRAYSIZE(acked2), nullptr, 0);
manager_.OnAckFrameStart(QuicPacketNumber(20), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(14), QuicPacketNumber(21));
manager_.OnAckRange(QuicPacketNumber(9), QuicPacketNumber(13));
manager_.OnAckRange(QuicPacketNumber(4), QuicPacketNumber(8));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(2),
ENCRYPTION_INITIAL, kEmptyCounts));
}
TEST_F(QuicSentPacketManagerTest, TolerateReneging) {
for (size_t i = 1; i <= 20; ++i) {
SendDataPacket(i);
}
uint64_t acked1[] = {5, 6, 10, 11, 15, 16};
uint64_t lost1[] = {1, 2, 3, 4, 7, 8, 9, 12, 13};
ExpectAcksAndLosses(true, acked1, ABSL_ARRAYSIZE(acked1), lost1,
ABSL_ARRAYSIZE(lost1));
EXPECT_CALL(notifier_, OnFrameLost(_)).Times(AnyNumber());
manager_.OnAckFrameStart(QuicPacketNumber(16), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(15), QuicPacketNumber(17));
manager_.OnAckRange(QuicPacketNumber(10), QuicPacketNumber(12));
manager_.OnAckRange(QuicPacketNumber(5), QuicPacketNumber(7));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
uint64_t acked2[] = {4, 7, 9, 12};
ExpectAcksAndLosses(true, acked2, ABSL_ARRAYSIZE(acked2), nullptr, 0);
manager_.OnAckFrameStart(QuicPacketNumber(12), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(9), QuicPacketNumber(13));
manager_.OnAckRange(QuicPacketNumber(4), QuicPacketNumber(8));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(2),
ENCRYPTION_INITIAL, kEmptyCounts));
EXPECT_EQ(QuicPacketNumber(16), manager_.GetLargestObserved());
}
TEST_F(QuicSentPacketManagerTest, MultiplePacketNumberSpaces) {
manager_.EnableMultiplePacketNumberSpacesSupport();
const QuicUnackedPacketMap* unacked_packets =
QuicSentPacketManagerPeer::GetUnackedPacketMap(&manager_);
EXPECT_FALSE(
unacked_packets
->GetLargestSentRetransmittableOfPacketNumberSpace(INITIAL_DATA)
.IsInitialized());
EXPECT_FALSE(
manager_.GetLargestAckedPacket(ENCRYPTION_INITIAL).IsInitialized());
SendDataPacket(1, ENCRYPTION_INITIAL);
EXPECT_EQ(QuicPacketNumber(1),
unacked_packets->GetLargestSentRetransmittableOfPacketNumberSpace(
INITIAL_DATA));
EXPECT_FALSE(
unacked_packets
->GetLargestSentRetransmittableOfPacketNumberSpace(HANDSHAKE_DATA)
.IsInitialized());
ExpectAck(1);
manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
EXPECT_EQ(QuicPacketNumber(1),
manager_.GetLargestAckedPacket(ENCRYPTION_INITIAL));
EXPECT_FALSE(
manager_.GetLargestAckedPacket(ENCRYPTION_HANDSHAKE).IsInitialized());
SendDataPacket(2, ENCRYPTION_HANDSHAKE);
SendDataPacket(3, ENCRYPTION_HANDSHAKE);
EXPECT_EQ(QuicPacketNumber(1),
unacked_packets->GetLargestSentRetransmittableOfPacketNumberSpace(
INITIAL_DATA));
EXPECT_EQ(QuicPacketNumber(3),
unacked_packets->GetLargestSentRetransmittableOfPacketNumberSpace(
HANDSHAKE_DATA));
EXPECT_FALSE(
unacked_packets
->GetLargestSentRetransmittableOfPacketNumberSpace(APPLICATION_DATA)
.IsInitialized());
ExpectAck(2);
manager_.OnAckFrameStart(QuicPacketNumber(2), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(2), QuicPacketNumber(3));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(2),
ENCRYPTION_HANDSHAKE, kEmptyCounts));
EXPECT_EQ(QuicPacketNumber(2),
manager_.GetLargestAckedPacket(ENCRYPTION_HANDSHAKE));
EXPECT_FALSE(
manager_.GetLargestAckedPacket(ENCRYPTION_ZERO_RTT).IsInitialized());
ExpectAck(3);
manager_.OnAckFrameStart(QuicPacketNumber(3), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(2), QuicPacketNumber(4));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(3),
ENCRYPTION_HANDSHAKE, kEmptyCounts));
EXPECT_EQ(QuicPacketNumber(3),
manager_.GetLargestAckedPacket(ENCRYPTION_HANDSHAKE));
EXPECT_FALSE(
manager_.GetLargestAckedPacket(ENCRYPTION_ZERO_RTT).IsInitialized());
SendDataPacket(4, ENCRYPTION_ZERO_RTT);
SendDataPacket(5, ENCRYPTION_ZERO_RTT);
EXPECT_EQ(QuicPacketNumber(1),
unacked_packets->GetLargestSentRetransmittableOfPacketNumberSpace(
INITIAL_DATA));
EXPECT_EQ(QuicPacketNumber(3),
unacked_packets->GetLargestSentRetransmittableOfPacketNumberSpace(
HANDSHAKE_DATA));
EXPECT_EQ(QuicPacketNumber(5),
unacked_packets->GetLargestSentRetransmittableOfPacketNumberSpace(
APPLICATION_DATA));
ExpectAck(5);
manager_.OnAckFrameStart(QuicPacketNumber(5), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(5), QuicPacketNumber(6));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(4),
ENCRYPTION_FORWARD_SECURE, kEmptyCounts));
EXPECT_EQ(QuicPacketNumber(3),
manager_.GetLargestAckedPacket(ENCRYPTION_HANDSHAKE));
EXPECT_EQ(QuicPacketNumber(5),
manager_.GetLargestAckedPacket(ENCRYPTION_ZERO_RTT));
EXPECT_EQ(QuicPacketNumber(5),
manager_.GetLargestAckedPacket(ENCRYPTION_FORWARD_SECURE));
SendDataPacket(6, ENCRYPTION_FORWARD_SECURE);
SendDataPacket(7, ENCRYPTION_FORWARD_SECURE);
SendDataPacket(8, ENCRYPTION_FORWARD_SECURE);
EXPECT_EQ(QuicPacketNumber(1),
unacked_packets->GetLargestSentRetransmittableOfPacketNumberSpace(
INITIAL_DATA));
EXPECT_EQ(QuicPacketNumber(3),
unacked_packets->GetLargestSentRetransmittableOfPacketNumberSpace(
HANDSHAKE_DATA));
EXPECT_EQ(QuicPacketNumber(8),
unacked_packets->GetLargestSentRetransmittableOfPacketNumberSpace(
APPLICATION_DATA));
uint64_t acked[] = {4, 6, 7, 8};
ExpectAcksAndLosses(true, acked, ABSL_ARRAYSIZE(acked), nullptr, 0);
manager_.OnAckFrameStart(QuicPacketNumber(8), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(4), QuicPacketNumber(9));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(5),
ENCRYPTION_FORWARD_SECURE, kEmptyCounts));
EXPECT_EQ(QuicPacketNumber(3),
manager_.GetLargestAckedPacket(ENCRYPTION_HANDSHAKE));
EXPECT_EQ(QuicPacketNumber(8),
manager_.GetLargestAckedPacket(ENCRYPTION_ZERO_RTT));
EXPECT_EQ(QuicPacketNumber(8),
manager_.GetLargestAckedPacket(ENCRYPTION_FORWARD_SECURE));
}
TEST_F(QuicSentPacketManagerTest, PacketsGetAckedInWrongPacketNumberSpace) {
manager_.EnableMultiplePacketNumberSpacesSupport();
SendDataPacket(1, ENCRYPTION_INITIAL);
SendDataPacket(2, ENCRYPTION_HANDSHAKE);
SendDataPacket(3, ENCRYPTION_HANDSHAKE);
manager_.OnAckFrameStart(QuicPacketNumber(3), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(4));
EXPECT_EQ(PACKETS_ACKED_IN_WRONG_PACKET_NUMBER_SPACE,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
}
TEST_F(QuicSentPacketManagerTest, PacketsGetAckedInWrongPacketNumberSpace2) {
manager_.EnableMultiplePacketNumberSpacesSupport();
SendDataPacket(1, ENCRYPTION_INITIAL);
SendDataPacket(2, ENCRYPTION_HANDSHAKE);
SendDataPacket(3, ENCRYPTION_HANDSHAKE);
manager_.OnAckFrameStart(QuicPacketNumber(3), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(4));
EXPECT_EQ(PACKETS_ACKED_IN_WRONG_PACKET_NUMBER_SPACE,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_HANDSHAKE, kEmptyCounts));
}
TEST_F(QuicSentPacketManagerTest,
ToleratePacketsGetAckedInWrongPacketNumberSpace) {
manager_.EnableMultiplePacketNumberSpacesSupport();
SendDataPacket(1, ENCRYPTION_INITIAL);
ExpectAck(1);
manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
SendDataPacket(2, ENCRYPTION_HANDSHAKE);
SendDataPacket(3, ENCRYPTION_HANDSHAKE);
uint64_t acked[] = {2, 3};
ExpectAcksAndLosses(true, acked, ABSL_ARRAYSIZE(acked), nullptr, 0);
manager_.OnAckFrameStart(QuicPacketNumber(3), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(4));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(2),
ENCRYPTION_HANDSHAKE, kEmptyCounts));
}
TEST_F(QuicSentPacketManagerTest, ComputingProbeTimeout) {
EXPECT_CALL(*send_algorithm_, PacingRate(_))
.WillRepeatedly(Return(QuicBandwidth::Zero()));
EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
.WillRepeatedly(Return(10 * kDefaultTCPMSS));
RttStats* rtt_stats = const_cast<RttStats*>(manager_.GetRttStats());
rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(100),
QuicTime::Delta::Zero(), QuicTime::Zero());
QuicTime::Delta srtt = rtt_stats->smoothed_rtt();
SendDataPacket(1, ENCRYPTION_FORWARD_SECURE);
QuicTime::Delta expected_pto_delay =
srtt + kPtoRttvarMultiplier * rtt_stats->mean_deviation() +
QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs());
QuicTime packet1_sent_time = clock_.Now();
EXPECT_EQ(clock_.Now() + expected_pto_delay,
manager_.GetRetransmissionTime());
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
SendDataPacket(2, ENCRYPTION_FORWARD_SECURE);
QuicTime deadline = packet1_sent_time + expected_pto_delay;
EXPECT_EQ(deadline, manager_.GetRetransmissionTime());
EXPECT_EQ(0u, stats_.pto_count);
clock_.AdvanceTime(deadline - clock_.Now());
manager_.OnRetransmissionTimeout();
EXPECT_EQ(QuicTime::Delta::Zero(), manager_.TimeUntilSend(clock_.Now()));
EXPECT_EQ(1u, stats_.pto_count);
EXPECT_EQ(0u, stats_.max_consecutive_rto_with_forward_progress);
EXPECT_CALL(notifier_, RetransmitFrames(_, _))
.WillOnce(WithArgs<1>(Invoke([this](TransmissionType type) {
return RetransmitDataPacket(3, type, ENCRYPTION_FORWARD_SECURE);
})));
manager_.MaybeSendProbePacket();
QuicTime sent_time = clock_.Now();
EXPECT_EQ(sent_time + expected_pto_delay * 2,
manager_.GetRetransmissionTime());
uint64_t acked[] = {1, 2};
ExpectAcksAndLosses(true, acked, ABSL_ARRAYSIZE(acked), nullptr, 0);
manager_.OnAckFrameStart(QuicPacketNumber(2), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(3));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_FORWARD_SECURE, kEmptyCounts));
expected_pto_delay =
rtt_stats->SmoothedOrInitialRtt() +
std::max(kPtoRttvarMultiplier * rtt_stats->mean_deviation(),
QuicTime::Delta::FromMilliseconds(1)) +
QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs());
EXPECT_EQ(sent_time + expected_pto_delay, manager_.GetRetransmissionTime());
EXPECT_EQ(1u, stats_.max_consecutive_rto_with_forward_progress);
}
TEST_F(QuicSentPacketManagerTest, SendOneProbePacket) {
EXPECT_CALL(*send_algorithm_, PacingRate(_))
.WillRepeatedly(Return(QuicBandwidth::Zero()));
EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
.WillRepeatedly(Return(10 * kDefaultTCPMSS));
SendDataPacket(1, ENCRYPTION_FORWARD_SECURE);
QuicTime packet1_sent_time = clock_.Now();
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
SendDataPacket(2, ENCRYPTION_FORWARD_SECURE);
RttStats* rtt_stats = const_cast<RttStats*>(manager_.GetRttStats());
rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(100),
QuicTime::Delta::Zero(), QuicTime::Zero());
QuicTime::Delta srtt = rtt_stats->smoothed_rtt();
QuicTime::Delta expected_pto_delay =
srtt + kPtoRttvarMultiplier * rtt_stats->mean_deviation() +
QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs());
QuicTime deadline = packet1_sent_time + expected_pto_delay;
EXPECT_EQ(deadline, manager_.GetRetransmissionTime());
clock_.AdvanceTime(deadline - clock_.Now());
manager_.OnRetransmissionTimeout();
EXPECT_EQ(QuicTime::Delta::Zero(), manager_.TimeUntilSend(clock_.Now()));
EXPECT_CALL(notifier_, RetransmitFrames(_, _))
.WillOnce(WithArgs<1>(Invoke([this](TransmissionType type) {
return RetransmitDataPacket(3, type, ENCRYPTION_FORWARD_SECURE);
})));
manager_.MaybeSendProbePacket();
}
TEST_F(QuicSentPacketManagerTest, DisableHandshakeModeClient) {
QuicSentPacketManagerPeer::SetPerspective(&manager_, Perspective::IS_CLIENT);
manager_.EnableMultiplePacketNumberSpacesSupport();
SendCryptoPacket(1);
EXPECT_NE(QuicTime::Zero(), manager_.GetRetransmissionTime());
ExpectAck(1);
manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
EXPECT_EQ(0u, manager_.GetBytesInFlight());
EXPECT_NE(QuicTime::Zero(), manager_.GetRetransmissionTime());
EXPECT_EQ(QuicSentPacketManager::PTO_MODE,
manager_.OnRetransmissionTimeout());
SendDataPacket(2, ENCRYPTION_HANDSHAKE);
ExpectAck(2);
manager_.OnAckFrameStart(QuicPacketNumber(2), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(2), QuicPacketNumber(3));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(2),
ENCRYPTION_HANDSHAKE, kEmptyCounts));
EXPECT_EQ(QuicTime::Zero(), manager_.GetRetransmissionTime());
}
TEST_F(QuicSentPacketManagerTest, DisableHandshakeModeServer) {
manager_.EnableIetfPtoAndLossDetection();
SendCryptoPacket(1);
EXPECT_NE(QuicTime::Zero(), manager_.GetRetransmissionTime());
ExpectAck(1);
manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
EXPECT_EQ(0u, manager_.GetBytesInFlight());
EXPECT_EQ(QuicTime::Zero(), manager_.GetRetransmissionTime());
}
TEST_F(QuicSentPacketManagerTest, PtoTimeoutRttVarMultiple) {
EXPECT_CALL(*send_algorithm_, PacingRate(_))
.WillRepeatedly(Return(QuicBandwidth::Zero()));
EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
.WillRepeatedly(Return(10 * kDefaultTCPMSS));
RttStats* rtt_stats = const_cast<RttStats*>(manager_.GetRttStats());
rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(100),
QuicTime::Delta::Zero(), QuicTime::Zero());
QuicTime::Delta srtt = rtt_stats->smoothed_rtt();
SendDataPacket(1, ENCRYPTION_FORWARD_SECURE);
QuicTime::Delta expected_pto_delay =
srtt + kPtoRttvarMultiplier * rtt_stats->mean_deviation() +
QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs());
EXPECT_EQ(clock_.Now() + expected_pto_delay,
manager_.GetRetransmissionTime());
}
TEST_F(QuicSentPacketManagerTest, IW10ForUpAndDown) {
QuicConfig config;
QuicTagVector options;
options.push_back(kBWS5);
QuicConfigPeer::SetReceivedConnectionOptions(&config, options);
EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
EXPECT_CALL(*send_algorithm_, SetInitialCongestionWindowInPackets(10));
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
manager_.SetFromConfig(config);
EXPECT_EQ(10u, manager_.initial_congestion_window());
}
TEST_F(QuicSentPacketManagerTest, ClientMultiplePacketNumberSpacePtoTimeout) {
manager_.EnableMultiplePacketNumberSpacesSupport();
EXPECT_CALL(*send_algorithm_, PacingRate(_))
.WillRepeatedly(Return(QuicBandwidth::Zero()));
EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
.WillRepeatedly(Return(10 * kDefaultTCPMSS));
RttStats* rtt_stats = const_cast<RttStats*>(manager_.GetRttStats());
rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(100),
QuicTime::Delta::Zero(), QuicTime::Zero());
QuicTime::Delta srtt = rtt_stats->smoothed_rtt();
QuicSentPacketManagerPeer::SetPerspective(&manager_, Perspective::IS_CLIENT);
SendDataPacket(1, ENCRYPTION_INITIAL);
QuicTime::Delta expected_pto_delay =
srtt + kPtoRttvarMultiplier * rtt_stats->mean_deviation() +
QuicTime::Delta::Zero();
EXPECT_EQ(clock_.Now() + expected_pto_delay,
manager_.GetRetransmissionTime());
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(false));
manager_.NeuterUnencryptedPackets();
EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(true));
SendDataPacket(2, ENCRYPTION_HANDSHAKE);
EXPECT_EQ(clock_.Now() + expected_pto_delay,
manager_.GetRetransmissionTime());
clock_.AdvanceTime(expected_pto_delay);
manager_.OnRetransmissionTimeout();
EXPECT_EQ(QuicTime::Delta::Zero(), manager_.TimeUntilSend(clock_.Now()));
EXPECT_EQ(1u, stats_.pto_count);
EXPECT_EQ(1u, stats_.crypto_retransmit_count);
EXPECT_CALL(notifier_, RetransmitFrames(_, _))
.WillOnce(WithArgs<1>(Invoke([this](TransmissionType type) {
return RetransmitDataPacket(3, type, ENCRYPTION_HANDSHAKE);
})));
manager_.MaybeSendProbePacket();
const QuicTime packet3_sent_time = clock_.Now();
EXPECT_EQ(packet3_sent_time + expected_pto_delay * 2,
manager_.GetRetransmissionTime());
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
SendDataPacket(4, ENCRYPTION_ZERO_RTT);
const QuicTime packet4_sent_time = clock_.Now();
EXPECT_EQ(packet3_sent_time + expected_pto_delay * 2,
manager_.GetRetransmissionTime());
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
SendDataPacket(5, ENCRYPTION_HANDSHAKE);
const QuicTime packet5_sent_time = clock_.Now();
EXPECT_EQ(clock_.Now() + expected_pto_delay * 2,
manager_.GetRetransmissionTime());
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
SendDataPacket(6, ENCRYPTION_FORWARD_SECURE);
EXPECT_EQ(packet5_sent_time + expected_pto_delay * 2,
manager_.GetRetransmissionTime());
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
const QuicTime packet7_sent_time = clock_.Now();
SendDataPacket(7, ENCRYPTION_HANDSHAKE);
expected_pto_delay =
srtt + kPtoRttvarMultiplier * rtt_stats->mean_deviation();
EXPECT_EQ(packet7_sent_time + expected_pto_delay * 2,
manager_.GetRetransmissionTime());
manager_.SetHandshakeConfirmed();
expected_pto_delay =
srtt + kPtoRttvarMultiplier * rtt_stats->mean_deviation() +
QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs());
EXPECT_EQ(packet4_sent_time + expected_pto_delay,
manager_.GetRetransmissionTime());
}
TEST_F(QuicSentPacketManagerTest, ServerMultiplePacketNumberSpacePtoTimeout) {
manager_.EnableMultiplePacketNumberSpacesSupport();
EXPECT_CALL(*send_algorithm_, PacingRate(_))
.WillRepeatedly(Return(QuicBandwidth::Zero()));
EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
.WillRepeatedly(Return(10 * kDefaultTCPMSS));
RttStats* rtt_stats = const_cast<RttStats*>(manager_.GetRttStats());
rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(100),
QuicTime::Delta::Zero(), QuicTime::Zero());
QuicTime::Delta srtt = rtt_stats->smoothed_rtt();
SendDataPacket(1, ENCRYPTION_INITIAL);
const QuicTime packet1_sent_time = clock_.Now();
QuicTime::Delta expected_pto_delay =
srtt + kPtoRttvarMultiplier * rtt_stats->mean_deviation() +
QuicTime::Delta::Zero();
EXPECT_EQ(packet1_sent_time + expected_pto_delay,
manager_.GetRetransmissionTime());
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
SendDataPacket(2, ENCRYPTION_HANDSHAKE);
const QuicTime packet2_sent_time = clock_.Now();
EXPECT_EQ(packet1_sent_time + expected_pto_delay,
manager_.GetRetransmissionTime());
EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(false));
manager_.NeuterUnencryptedPackets();
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
SendDataPacket(3, ENCRYPTION_FORWARD_SECURE);
const QuicTime packet3_sent_time = clock_.Now();
EXPECT_EQ(packet2_sent_time + expected_pto_delay,
manager_.GetRetransmissionTime());
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
SendDataPacket(4, ENCRYPTION_HANDSHAKE);
EXPECT_EQ(clock_.Now() + expected_pto_delay,
manager_.GetRetransmissionTime());
manager_.SetHandshakeConfirmed();
expected_pto_delay =
srtt + kPtoRttvarMultiplier * rtt_stats->mean_deviation() +
QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs());
EXPECT_EQ(packet3_sent_time + expected_pto_delay,
manager_.GetRetransmissionTime());
}
TEST_F(QuicSentPacketManagerTest, ComputingProbeTimeoutByLeftEdge) {
EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
EXPECT_CALL(*send_algorithm_, PacingRate(_))
.WillRepeatedly(Return(QuicBandwidth::Zero()));
EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
.WillRepeatedly(Return(10 * kDefaultTCPMSS));
RttStats* rtt_stats = const_cast<RttStats*>(manager_.GetRttStats());
rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(100),
QuicTime::Delta::Zero(), QuicTime::Zero());
QuicTime::Delta srtt = rtt_stats->smoothed_rtt();
SendDataPacket(1, ENCRYPTION_FORWARD_SECURE);
QuicTime::Delta expected_pto_delay =
srtt + kPtoRttvarMultiplier * rtt_stats->mean_deviation() +
QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs());
const QuicTime packet1_sent_time = clock_.Now();
EXPECT_EQ(packet1_sent_time + expected_pto_delay,
manager_.GetRetransmissionTime());
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
SendDataPacket(2, ENCRYPTION_FORWARD_SECURE);
EXPECT_EQ(packet1_sent_time + expected_pto_delay,
manager_.GetRetransmissionTime());
EXPECT_EQ(0u, stats_.pto_count);
clock_.AdvanceTime(expected_pto_delay);
manager_.OnRetransmissionTimeout();
EXPECT_EQ(QuicTime::Delta::Zero(), manager_.TimeUntilSend(clock_.Now()));
EXPECT_EQ(1u, stats_.pto_count);
EXPECT_CALL(notifier_, RetransmitFrames(_, _))
.WillOnce(WithArgs<1>(Invoke([this](TransmissionType type) {
return RetransmitDataPacket(3, type, ENCRYPTION_FORWARD_SECURE);
})));
manager_.MaybeSendProbePacket();
QuicTime packet3_sent_time = clock_.Now();
EXPECT_EQ(packet3_sent_time + expected_pto_delay * 2,
manager_.GetRetransmissionTime());
uint64_t acked[] = {1, 2};
ExpectAcksAndLosses(true, acked, ABSL_ARRAYSIZE(acked), nullptr, 0);
manager_.OnAckFrameStart(QuicPacketNumber(2), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(3));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_FORWARD_SECURE, kEmptyCounts));
expected_pto_delay =
rtt_stats->SmoothedOrInitialRtt() +
std::max(kPtoRttvarMultiplier * rtt_stats->mean_deviation(),
QuicTime::Delta::FromMilliseconds(1)) +
QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs());
EXPECT_EQ(packet3_sent_time + expected_pto_delay,
manager_.GetRetransmissionTime());
}
TEST_F(QuicSentPacketManagerTest, ComputingProbeTimeoutByLeftEdge2) {
EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
EXPECT_CALL(*send_algorithm_, PacingRate(_))
.WillRepeatedly(Return(QuicBandwidth::Zero()));
EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
.WillRepeatedly(Return(10 * kDefaultTCPMSS));
RttStats* rtt_stats = const_cast<RttStats*>(manager_.GetRttStats());
rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(100),
QuicTime::Delta::Zero(), QuicTime::Zero());
QuicTime::Delta srtt = rtt_stats->smoothed_rtt();
SendDataPacket(1, ENCRYPTION_FORWARD_SECURE);
QuicTime::Delta expected_pto_delay =
srtt + kPtoRttvarMultiplier * rtt_stats->mean_deviation() +
QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs());
const QuicTime packet1_sent_time = clock_.Now();
EXPECT_EQ(packet1_sent_time + expected_pto_delay,
manager_.GetRetransmissionTime());
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(
expected_pto_delay.ToMilliseconds() - 10));
SendDataPacket(2, ENCRYPTION_FORWARD_SECURE);
expected_pto_delay = kFirstPtoSrttMultiplier * rtt_stats->smoothed_rtt();
EXPECT_EQ(clock_.Now() + expected_pto_delay,
manager_.GetRetransmissionTime());
EXPECT_EQ(0u, stats_.pto_count);
clock_.AdvanceTime(expected_pto_delay);
manager_.OnRetransmissionTimeout();
EXPECT_EQ(QuicTime::Delta::Zero(), manager_.TimeUntilSend(clock_.Now()));
EXPECT_EQ(1u, stats_.pto_count);
EXPECT_CALL(notifier_, RetransmitFrames(_, _))
.WillOnce(WithArgs<1>(Invoke([this](TransmissionType type) {
return RetransmitDataPacket(3, type, ENCRYPTION_FORWARD_SECURE);
})));
manager_.MaybeSendProbePacket();
expected_pto_delay =
srtt + kPtoRttvarMultiplier * rtt_stats->mean_deviation() +
QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs());
QuicTime packet3_sent_time = clock_.Now();
EXPECT_EQ(packet3_sent_time + expected_pto_delay * 2,
manager_.GetRetransmissionTime());
uint64_t acked[] = {1, 2};
ExpectAcksAndLosses(true, acked, ABSL_ARRAYSIZE(acked), nullptr, 0);
manager_.OnAckFrameStart(QuicPacketNumber(2), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(3));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_FORWARD_SECURE, kEmptyCounts));
expected_pto_delay =
rtt_stats->SmoothedOrInitialRtt() +
std::max(kPtoRttvarMultiplier * rtt_stats->mean_deviation(),
QuicTime::Delta::FromMilliseconds(1)) +
QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs());
EXPECT_EQ(packet3_sent_time + expected_pto_delay,
manager_.GetRetransmissionTime());
}
TEST_F(QuicSentPacketManagerTest,
ComputingProbeTimeoutByLeftEdgeMultiplePacketNumberSpaces) {
manager_.EnableMultiplePacketNumberSpacesSupport();
EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
EXPECT_CALL(*send_algorithm_, PacingRate(_))
.WillRepeatedly(Return(QuicBandwidth::Zero()));
EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
.WillRepeatedly(Return(10 * kDefaultTCPMSS));
RttStats* rtt_stats = const_cast<RttStats*>(manager_.GetRttStats());
rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(100),
QuicTime::Delta::Zero(), QuicTime::Zero());
QuicTime::Delta srtt = rtt_stats->smoothed_rtt();
SendDataPacket(1, ENCRYPTION_INITIAL);
const QuicTime packet1_sent_time = clock_.Now();
QuicTime::Delta expected_pto_delay =
srtt + kPtoRttvarMultiplier * rtt_stats->mean_deviation() +
QuicTime::Delta::Zero();
EXPECT_EQ(packet1_sent_time + expected_pto_delay,
manager_.GetRetransmissionTime());
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
SendDataPacket(2, ENCRYPTION_HANDSHAKE);
const QuicTime packet2_sent_time = clock_.Now();
EXPECT_EQ(packet1_sent_time + expected_pto_delay,
manager_.GetRetransmissionTime());
EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(false));
manager_.NeuterUnencryptedPackets();
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
SendDataPacket(3, ENCRYPTION_FORWARD_SECURE);
const QuicTime packet3_sent_time = clock_.Now();
EXPECT_EQ(packet2_sent_time + expected_pto_delay,
manager_.GetRetransmissionTime());
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
SendDataPacket(4, ENCRYPTION_HANDSHAKE);
EXPECT_EQ(clock_.Now() + expected_pto_delay,
manager_.GetRetransmissionTime());
manager_.SetHandshakeConfirmed();
expected_pto_delay =
srtt + kPtoRttvarMultiplier * rtt_stats->mean_deviation() +
QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs());
EXPECT_EQ(packet3_sent_time + expected_pto_delay,
manager_.GetRetransmissionTime());
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
SendDataPacket(5, ENCRYPTION_FORWARD_SECURE);
EXPECT_EQ(packet3_sent_time + expected_pto_delay,
manager_.GetRetransmissionTime());
}
TEST_F(QuicSentPacketManagerTest,
ComputingProbeTimeoutByLeftEdge2MultiplePacketNumberSpaces) {
manager_.EnableMultiplePacketNumberSpacesSupport();
EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
EXPECT_CALL(*send_algorithm_, PacingRate(_))
.WillRepeatedly(Return(QuicBandwidth::Zero()));
EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
.WillRepeatedly(Return(10 * kDefaultTCPMSS));
RttStats* rtt_stats = const_cast<RttStats*>(manager_.GetRttStats());
rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(100),
QuicTime::Delta::Zero(), QuicTime::Zero());
QuicTime::Delta srtt = rtt_stats->smoothed_rtt();
SendDataPacket(1, ENCRYPTION_INITIAL);
const QuicTime packet1_sent_time = clock_.Now();
QuicTime::Delta expected_pto_delay =
srtt + kPtoRttvarMultiplier * rtt_stats->mean_deviation() +
QuicTime::Delta::Zero();
EXPECT_EQ(packet1_sent_time + expected_pto_delay,
manager_.GetRetransmissionTime());
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
SendDataPacket(2, ENCRYPTION_HANDSHAKE);
const QuicTime packet2_sent_time = clock_.Now();
EXPECT_EQ(packet1_sent_time + expected_pto_delay,
manager_.GetRetransmissionTime());
EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(false));
manager_.NeuterUnencryptedPackets();
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
SendDataPacket(3, ENCRYPTION_FORWARD_SECURE);
const QuicTime packet3_sent_time = clock_.Now();
EXPECT_EQ(packet2_sent_time + expected_pto_delay,
manager_.GetRetransmissionTime());
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
SendDataPacket(4, ENCRYPTION_HANDSHAKE);
EXPECT_EQ(clock_.Now() + expected_pto_delay,
manager_.GetRetransmissionTime());
manager_.SetHandshakeConfirmed();
expected_pto_delay =
srtt + kPtoRttvarMultiplier * rtt_stats->mean_deviation() +
QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs());
EXPECT_EQ(packet3_sent_time + expected_pto_delay,
manager_.GetRetransmissionTime());
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(
expected_pto_delay.ToMilliseconds() - 10));
SendDataPacket(5, ENCRYPTION_FORWARD_SECURE);
EXPECT_EQ(clock_.Now() + kFirstPtoSrttMultiplier * rtt_stats->smoothed_rtt(),
manager_.GetRetransmissionTime());
}
TEST_F(QuicSentPacketManagerTest, SetHandshakeConfirmed) {
QuicSentPacketManagerPeer::SetPerspective(&manager_, Perspective::IS_CLIENT);
manager_.EnableMultiplePacketNumberSpacesSupport();
SendDataPacket(1, ENCRYPTION_INITIAL);
SendDataPacket(2, ENCRYPTION_HANDSHAKE);
EXPECT_CALL(notifier_, OnFrameAcked(_, _, _))
.WillOnce(
Invoke([](const QuicFrame& , QuicTime::Delta ack_delay_time,
QuicTime receive_timestamp) {
EXPECT_TRUE(ack_delay_time.IsZero());
EXPECT_EQ(receive_timestamp, QuicTime::Zero());
return true;
}));
EXPECT_CALL(*send_algorithm_, OnPacketNeutered(QuicPacketNumber(2))).Times(1);
manager_.SetHandshakeConfirmed();
}
TEST_F(QuicSentPacketManagerTest, NeuterUnencryptedPackets) {
SendCryptoPacket(1);
SendPingPacket(2, ENCRYPTION_INITIAL);
EXPECT_CALL(notifier_, OnFrameAcked(_, _, _))
.Times(2)
.WillOnce(Return(false))
.WillOnce(Return(true));
EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(false));
EXPECT_CALL(*send_algorithm_, OnPacketNeutered(QuicPacketNumber(1))).Times(1);
manager_.NeuterUnencryptedPackets();
}
TEST_F(QuicSentPacketManagerTest, MarkInitialPacketsForRetransmission) {
SendCryptoPacket(1);
SendPingPacket(2, ENCRYPTION_HANDSHAKE);
EXPECT_CALL(notifier_, OnFrameLost(_)).Times(1);
manager_.MarkInitialPacketsForRetransmission();
}
TEST_F(QuicSentPacketManagerTest, NoPacketThresholdDetectionForRuntPackets) {
EXPECT_TRUE(
QuicSentPacketManagerPeer::UsePacketThresholdForRuntPackets(&manager_));
QuicConfig config;
QuicTagVector options;
options.push_back(kRUNT);
QuicConfigPeer::SetReceivedConnectionOptions(&config, options);
EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
manager_.SetFromConfig(config);
EXPECT_FALSE(
QuicSentPacketManagerPeer::UsePacketThresholdForRuntPackets(&manager_));
}
TEST_F(QuicSentPacketManagerTest, GetPathDegradingDelayDefaultPTO) {
QuicSentPacketManagerPeer::SetPerspective(&manager_, Perspective::IS_CLIENT);
QuicTime::Delta expected_delay = 4 * manager_.GetPtoDelay();
EXPECT_EQ(expected_delay, manager_.GetPathDegradingDelay());
}
TEST_F(QuicSentPacketManagerTest, ClientsIgnorePings) {
QuicSentPacketManagerPeer::SetPerspective(&manager_, Perspective::IS_CLIENT);
QuicConfig client_config;
QuicTagVector options;
QuicTagVector client_options;
client_options.push_back(kIGNP);
client_config.SetConnectionOptionsToSend(options);
client_config.SetClientConnectionOptions(client_options);
EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
manager_.SetFromConfig(client_config);
EXPECT_CALL(*send_algorithm_, PacingRate(_))
.WillRepeatedly(Return(QuicBandwidth::Zero()));
EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
.WillRepeatedly(Return(10 * kDefaultTCPMSS));
EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
SendPingPacket(1, ENCRYPTION_INITIAL);
EXPECT_EQ(QuicTime::Zero(), manager_.GetRetransmissionTime());
SendDataPacket(2, ENCRYPTION_INITIAL);
EXPECT_NE(QuicTime::Zero(), manager_.GetRetransmissionTime());
uint64_t acked[] = {1};
ExpectAcksAndLosses(false, acked, ABSL_ARRAYSIZE(acked),
nullptr, 0);
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(90));
manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
RttStats* rtt_stats = const_cast<RttStats*>(manager_.GetRttStats());
EXPECT_TRUE(rtt_stats->smoothed_rtt().IsZero());
ExpectAck(2);
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
manager_.OnAckFrameStart(QuicPacketNumber(2), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(3));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(2),
ENCRYPTION_INITIAL, kEmptyCounts));
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(100), rtt_stats->smoothed_rtt());
}
TEST_F(QuicSentPacketManagerTest, ExponentialBackoffWithNoRttMeasurement) {
QuicSentPacketManagerPeer::SetPerspective(&manager_, Perspective::IS_CLIENT);
manager_.EnableMultiplePacketNumberSpacesSupport();
RttStats* rtt_stats = const_cast<RttStats*>(manager_.GetRttStats());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(kInitialRttMs),
rtt_stats->initial_rtt());
EXPECT_TRUE(rtt_stats->smoothed_rtt().IsZero());
SendCryptoPacket(1);
QuicTime::Delta expected_pto_delay =
QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs);
EXPECT_EQ(clock_.Now() + expected_pto_delay,
manager_.GetRetransmissionTime());
clock_.AdvanceTime(expected_pto_delay);
manager_.OnRetransmissionTimeout();
EXPECT_CALL(notifier_, RetransmitFrames(_, _))
.WillOnce(
WithArgs<1>(Invoke([this]() { return RetransmitCryptoPacket(3); })));
manager_.MaybeSendProbePacket();
EXPECT_EQ(clock_.Now() + 2 * expected_pto_delay,
manager_.GetRetransmissionTime());
}
TEST_F(QuicSentPacketManagerTest, PtoDelayWithTinyInitialRtt) {
manager_.EnableMultiplePacketNumberSpacesSupport();
RttStats* rtt_stats = const_cast<RttStats*>(manager_.GetRttStats());
rtt_stats->set_initial_rtt(QuicTime::Delta::FromMicroseconds(1));
EXPECT_EQ(QuicTime::Delta::FromMicroseconds(1), rtt_stats->initial_rtt());
EXPECT_TRUE(rtt_stats->smoothed_rtt().IsZero());
SendCryptoPacket(1);
QuicTime::Delta expected_pto_delay = QuicTime::Delta::FromMilliseconds(10);
EXPECT_EQ(clock_.Now() + expected_pto_delay,
manager_.GetRetransmissionTime());
clock_.AdvanceTime(expected_pto_delay);
manager_.OnRetransmissionTimeout();
EXPECT_CALL(notifier_, RetransmitFrames(_, _))
.WillOnce(
WithArgs<1>(Invoke([this]() { return RetransmitCryptoPacket(3); })));
manager_.MaybeSendProbePacket();
EXPECT_EQ(clock_.Now() + 2 * expected_pto_delay,
manager_.GetRetransmissionTime());
}
TEST_F(QuicSentPacketManagerTest, HandshakeAckCausesInitialKeyDropping) {
manager_.EnableMultiplePacketNumberSpacesSupport();
QuicSentPacketManagerPeer::SetPerspective(&manager_, Perspective::IS_CLIENT);
SendDataPacket(1, ENCRYPTION_INITIAL);
QuicTime::Delta expected_pto_delay =
QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs);
EXPECT_EQ(clock_.Now() + expected_pto_delay,
manager_.GetRetransmissionTime());
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
SendAckPacket(2, 1, ENCRYPTION_HANDSHAKE);
EXPECT_CALL(notifier_, HasUnackedCryptoData()).WillRepeatedly(Return(false));
EXPECT_CALL(notifier_, IsFrameOutstanding(_)).WillRepeatedly(Return(false));
manager_.NeuterUnencryptedPackets();
EXPECT_FALSE(manager_.HasInFlightPackets());
EXPECT_EQ(clock_.Now() + expected_pto_delay,
manager_.GetRetransmissionTime());
clock_.AdvanceTime(expected_pto_delay);
manager_.OnRetransmissionTimeout();
EXPECT_CALL(notifier_, RetransmitFrames(_, _)).Times(0);
manager_.MaybeSendProbePacket();
}
TEST_F(QuicSentPacketManagerTest, ClearLastInflightPacketsSentTime) {
manager_.EnableMultiplePacketNumberSpacesSupport();
EXPECT_CALL(*send_algorithm_, PacingRate(_))
.WillRepeatedly(Return(QuicBandwidth::Zero()));
EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
.WillRepeatedly(Return(10 * kDefaultTCPMSS));
SendDataPacket(1, ENCRYPTION_INITIAL);
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
SendDataPacket(2, ENCRYPTION_HANDSHAKE);
SendDataPacket(3, ENCRYPTION_HANDSHAKE);
SendDataPacket(4, ENCRYPTION_HANDSHAKE);
const QuicTime packet2_sent_time = clock_.Now();
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
SendDataPacket(5, ENCRYPTION_FORWARD_SECURE);
ExpectAck(1);
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(90));
manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
RttStats* rtt_stats = const_cast<RttStats*>(manager_.GetRttStats());
const QuicTime::Delta pto_delay =
rtt_stats->smoothed_rtt() +
kPtoRttvarMultiplier * rtt_stats->mean_deviation() +
QuicTime::Delta::Zero();
EXPECT_EQ(packet2_sent_time + pto_delay, manager_.GetRetransmissionTime());
}
TEST_F(QuicSentPacketManagerTest, MaybeRetransmitInitialData) {
manager_.EnableMultiplePacketNumberSpacesSupport();
EXPECT_CALL(*send_algorithm_, PacingRate(_))
.WillRepeatedly(Return(QuicBandwidth::Zero()));
EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
.WillRepeatedly(Return(10 * kDefaultTCPMSS));
RttStats* rtt_stats = const_cast<RttStats*>(manager_.GetRttStats());
rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(100),
QuicTime::Delta::Zero(), QuicTime::Zero());
QuicTime::Delta srtt = rtt_stats->smoothed_rtt();
SendDataPacket(1, ENCRYPTION_INITIAL);
QuicTime packet1_sent_time = clock_.Now();
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
SendDataPacket(2, ENCRYPTION_HANDSHAKE);
QuicTime packet2_sent_time = clock_.Now();
SendDataPacket(3, ENCRYPTION_HANDSHAKE);
QuicTime::Delta expected_pto_delay =
srtt + kPtoRttvarMultiplier * rtt_stats->mean_deviation() +
QuicTime::Delta::Zero();
EXPECT_EQ(packet1_sent_time + expected_pto_delay,
manager_.GetRetransmissionTime());
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
EXPECT_CALL(notifier_, RetransmitFrames(_, _))
.WillOnce(WithArgs<1>(Invoke([this](TransmissionType type) {
return RetransmitDataPacket(4, type, ENCRYPTION_INITIAL);
})));
manager_.RetransmitDataOfSpaceIfAny(INITIAL_DATA);
EXPECT_EQ(packet2_sent_time + expected_pto_delay,
manager_.GetRetransmissionTime());
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
EXPECT_CALL(notifier_, RetransmitFrames(_, _))
.WillOnce(WithArgs<1>(Invoke([this](TransmissionType type) {
return RetransmitDataPacket(5, type, ENCRYPTION_INITIAL);
})));
manager_.RetransmitDataOfSpaceIfAny(INITIAL_DATA);
EXPECT_EQ(packet2_sent_time + expected_pto_delay,
manager_.GetRetransmissionTime());
}
TEST_F(QuicSentPacketManagerTest, SendPathChallengeAndGetAck) {
QuicPacketNumber packet_number(1);
EXPECT_CALL(*send_algorithm_,
OnPacketSent(_, BytesInFlight(), packet_number, _, _));
SerializedPacket packet(packet_number, PACKET_4BYTE_PACKET_NUMBER, nullptr,
kDefaultLength, false, false);
QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
packet.nonretransmittable_frames.push_back(
QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
packet.encryption_level = ENCRYPTION_FORWARD_SECURE;
manager_.OnPacketSent(&packet, clock_.Now(), NOT_RETRANSMISSION,
NO_RETRANSMITTABLE_DATA, false, ECN_NOT_ECT);
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
EXPECT_CALL(
*send_algorithm_,
OnCongestionEvent(false, _, _,
Pointwise(PacketNumberEq(), {1}), IsEmpty(), _, _));
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_FORWARD_SECURE, kEmptyCounts));
}
SerializedPacket MakePacketWithAckFrequencyFrame(
int packet_number, int ack_frequency_sequence_number,
QuicTime::Delta max_ack_delay) {
auto* ack_frequency_frame = new QuicAckFrequencyFrame();
ack_frequency_frame->max_ack_delay = max_ack_delay;
ack_frequency_frame->sequence_number = ack_frequency_sequence_number;
SerializedPacket packet(QuicPacketNumber(packet_number),
PACKET_4BYTE_PACKET_NUMBER, nullptr, kDefaultLength,
false,
false);
packet.retransmittable_frames.push_back(QuicFrame(ack_frequency_frame));
packet.has_ack_frequency = true;
packet.encryption_level = ENCRYPTION_FORWARD_SECURE;
return packet;
}
TEST_F(QuicSentPacketManagerTest,
PeerMaxAckDelayUpdatedFromAckFrequencyFrameOneAtATime) {
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
.Times(AnyNumber());
EXPECT_CALL(*network_change_visitor_, OnCongestionChange())
.Times(AnyNumber());
auto initial_peer_max_ack_delay = manager_.peer_max_ack_delay();
auto one_ms = QuicTime::Delta::FromMilliseconds(1);
auto plus_1_ms_delay = initial_peer_max_ack_delay + one_ms;
auto minus_1_ms_delay = initial_peer_max_ack_delay - one_ms;
SerializedPacket packet1 = MakePacketWithAckFrequencyFrame(
1, 1,
plus_1_ms_delay);
manager_.OnPacketSent(&packet1, clock_.Now(), NOT_RETRANSMISSION,
HAS_RETRANSMITTABLE_DATA, true,
ECN_NOT_ECT);
EXPECT_EQ(manager_.peer_max_ack_delay(), plus_1_ms_delay);
manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_FORWARD_SECURE, kEmptyCounts);
EXPECT_EQ(manager_.peer_max_ack_delay(), plus_1_ms_delay);
SerializedPacket packet2 = MakePacketWithAckFrequencyFrame(
2, 2,
minus_1_ms_delay);
manager_.OnPacketSent(&packet2, clock_.Now(), NOT_RETRANSMISSION,
HAS_RETRANSMITTABLE_DATA, true,
ECN_NOT_ECT);
EXPECT_EQ(manager_.peer_max_ack_delay(), plus_1_ms_delay);
manager_.OnAckFrameStart(QuicPacketNumber(2), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(2), QuicPacketNumber(3));
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(2),
ENCRYPTION_FORWARD_SECURE, kEmptyCounts);
EXPECT_EQ(manager_.peer_max_ack_delay(), minus_1_ms_delay);
}
TEST_F(QuicSentPacketManagerTest,
PeerMaxAckDelayUpdatedFromInOrderAckFrequencyFrames) {
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
.Times(AnyNumber());
EXPECT_CALL(*network_change_visitor_, OnCongestionChange())
.Times(AnyNumber());
auto initial_peer_max_ack_delay = manager_.peer_max_ack_delay();
auto one_ms = QuicTime::Delta::FromMilliseconds(1);
auto extra_1_ms = initial_peer_max_ack_delay + one_ms;
auto extra_2_ms = initial_peer_max_ack_delay + 2 * one_ms;
auto extra_3_ms = initial_peer_max_ack_delay + 3 * one_ms;
SerializedPacket packet1 = MakePacketWithAckFrequencyFrame(
1, 1, extra_1_ms);
SerializedPacket packet2 = MakePacketWithAckFrequencyFrame(
2, 2, extra_3_ms);
SerializedPacket packet3 = MakePacketWithAckFrequencyFrame(
3, 3, extra_2_ms);
manager_.OnPacketSent(&packet1, clock_.Now(), NOT_RETRANSMISSION,
HAS_RETRANSMITTABLE_DATA, true,
ECN_NOT_ECT);
EXPECT_EQ(manager_.peer_max_ack_delay(), extra_1_ms);
manager_.OnPacketSent(&packet2, clock_.Now(), NOT_RETRANSMISSION,
HAS_RETRANSMITTABLE_DATA, true,
ECN_NOT_ECT);
EXPECT_EQ(manager_.peer_max_ack_delay(), extra_3_ms);
manager_.OnPacketSent(&packet3, clock_.Now(), NOT_RETRANSMISSION,
HAS_RETRANSMITTABLE_DATA, true,
ECN_NOT_ECT);
EXPECT_EQ(manager_.peer_max_ack_delay(), extra_3_ms);
manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_FORWARD_SECURE, kEmptyCounts);
EXPECT_EQ(manager_.peer_max_ack_delay(), extra_3_ms);
manager_.OnAckFrameStart(QuicPacketNumber(2), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(3));
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_FORWARD_SECURE, kEmptyCounts);
EXPECT_EQ(manager_.peer_max_ack_delay(), extra_3_ms);
manager_.OnAckFrameStart(QuicPacketNumber(3), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(4));
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_FORWARD_SECURE, kEmptyCounts);
EXPECT_EQ(manager_.peer_max_ack_delay(), extra_2_ms);
}
TEST_F(QuicSentPacketManagerTest,
PeerMaxAckDelayUpdatedFromOutOfOrderAckedAckFrequencyFrames) {
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
.Times(AnyNumber());
EXPECT_CALL(*network_change_visitor_, OnCongestionChange())
.Times(AnyNumber());
auto initial_peer_max_ack_delay = manager_.peer_max_ack_delay();
auto one_ms = QuicTime::Delta::FromMilliseconds(1);
auto extra_1_ms = initial_peer_max_ack_delay + one_ms;
auto extra_2_ms = initial_peer_max_ack_delay + 2 * one_ms;
auto extra_3_ms = initial_peer_max_ack_delay + 3 * one_ms;
auto extra_4_ms = initial_peer_max_ack_delay + 4 * one_ms;
SerializedPacket packet1 = MakePacketWithAckFrequencyFrame(
1, 1, extra_4_ms);
SerializedPacket packet2 = MakePacketWithAckFrequencyFrame(
2, 2, extra_3_ms);
SerializedPacket packet3 = MakePacketWithAckFrequencyFrame(
3, 3, extra_2_ms);
SerializedPacket packet4 = MakePacketWithAckFrequencyFrame(
4, 4, extra_1_ms);
manager_.OnPacketSent(&packet1, clock_.Now(), NOT_RETRANSMISSION,
HAS_RETRANSMITTABLE_DATA, true,
ECN_NOT_ECT);
manager_.OnPacketSent(&packet2, clock_.Now(), NOT_RETRANSMISSION,
HAS_RETRANSMITTABLE_DATA, true,
ECN_NOT_ECT);
manager_.OnPacketSent(&packet3, clock_.Now(), NOT_RETRANSMISSION,
HAS_RETRANSMITTABLE_DATA, true,
ECN_NOT_ECT);
manager_.OnPacketSent(&packet4, clock_.Now(), NOT_RETRANSMISSION,
NO_RETRANSMITTABLE_DATA, true,
ECN_NOT_ECT);
EXPECT_EQ(manager_.peer_max_ack_delay(), extra_4_ms);
manager_.OnAckFrameStart(QuicPacketNumber(3), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(3), QuicPacketNumber(4));
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_FORWARD_SECURE, kEmptyCounts);
EXPECT_EQ(manager_.peer_max_ack_delay(), extra_2_ms);
manager_.OnAckFrameStart(QuicPacketNumber(3), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(3), QuicPacketNumber(4));
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_FORWARD_SECURE, kEmptyCounts);
EXPECT_EQ(manager_.peer_max_ack_delay(), extra_2_ms);
manager_.OnAckFrameStart(QuicPacketNumber(3), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(4));
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_FORWARD_SECURE, kEmptyCounts);
EXPECT_EQ(manager_.peer_max_ack_delay(), extra_2_ms);
manager_.OnAckFrameStart(QuicPacketNumber(4), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(5));
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_FORWARD_SECURE, kEmptyCounts);
EXPECT_EQ(manager_.peer_max_ack_delay(), extra_1_ms);
}
TEST_F(QuicSentPacketManagerTest, ClearDataInMessageFrameAfterPacketSent) {
EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QuicMessageFrame* message_frame = nullptr;
{
quiche::QuicheMemSlice slice(quiche::QuicheBuffer(&allocator_, 1024));
message_frame = new QuicMessageFrame(1, std::move(slice));
EXPECT_FALSE(message_frame->message_data.empty());
EXPECT_EQ(message_frame->message_length, 1024);
SerializedPacket packet(QuicPacketNumber(1), PACKET_4BYTE_PACKET_NUMBER,
nullptr, kDefaultLength,
false,
false);
packet.encryption_level = ENCRYPTION_FORWARD_SECURE;
packet.retransmittable_frames.push_back(QuicFrame(message_frame));
packet.has_message = true;
manager_.OnPacketSent(&packet, clock_.Now(), NOT_RETRANSMISSION,
HAS_RETRANSMITTABLE_DATA, true,
ECN_NOT_ECT);
}
EXPECT_TRUE(message_frame->message_data.empty());
EXPECT_EQ(message_frame->message_length, 0);
}
TEST_F(QuicSentPacketManagerTest, BuildAckFrequencyFrame) {
SetQuicReloadableFlag(quic_can_send_ack_frequency, true);
EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
QuicConfig config;
QuicConfigPeer::SetReceivedMinAckDelayMs(&config, 1);
manager_.SetFromConfig(config);
manager_.SetHandshakeConfirmed();
auto* rtt_stats = const_cast<RttStats*>(manager_.GetRttStats());
rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(80),
QuicTime::Delta::Zero(),
QuicTime::Zero());
rtt_stats->UpdateRtt(
QuicTime::Delta::FromMilliseconds(160),
QuicTime::Delta::Zero(),
QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(24));
auto frame = manager_.GetUpdatedAckFrequencyFrame();
EXPECT_EQ(frame.max_ack_delay,
std::max(rtt_stats->min_rtt() * 0.25,
QuicTime::Delta::FromMilliseconds(1u)));
EXPECT_EQ(frame.packet_tolerance, 10u);
}
TEST_F(QuicSentPacketManagerTest, SmoothedRttIgnoreAckDelay) {
QuicConfig config;
QuicTagVector options;
options.push_back(kMAD0);
QuicConfigPeer::SetReceivedConnectionOptions(&config, options);
EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
.WillRepeatedly(Return(10 * kDefaultTCPMSS));
manager_.SetFromConfig(config);
SendDataPacket(1);
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(300));
ExpectAck(1);
manager_.OnAckFrameStart(QuicPacketNumber(1),
QuicTime::Delta::FromMilliseconds(100),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(300),
manager_.GetRttStats()->latest_rtt());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(300),
manager_.GetRttStats()->smoothed_rtt());
SendDataPacket(2);
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(300));
ExpectAck(2);
manager_.OnAckFrameStart(QuicPacketNumber(2),
QuicTime::Delta::FromMilliseconds(100),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(2), QuicPacketNumber(3));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(2),
ENCRYPTION_INITIAL, kEmptyCounts));
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(300),
manager_.GetRttStats()->latest_rtt());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(300),
manager_.GetRttStats()->smoothed_rtt());
SendDataPacket(3);
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(300));
ExpectAck(3);
manager_.OnAckFrameStart(QuicPacketNumber(3),
QuicTime::Delta::FromMilliseconds(50), clock_.Now());
manager_.OnAckRange(QuicPacketNumber(3), QuicPacketNumber(4));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(3),
ENCRYPTION_INITIAL, kEmptyCounts));
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(300),
manager_.GetRttStats()->latest_rtt());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(300),
manager_.GetRttStats()->smoothed_rtt());
SendDataPacket(4);
clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(200));
ExpectAck(4);
manager_.OnAckFrameStart(QuicPacketNumber(4),
QuicTime::Delta::FromMilliseconds(300),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(4), QuicPacketNumber(5));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(4),
ENCRYPTION_INITIAL, kEmptyCounts));
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200),
manager_.GetRttStats()->latest_rtt());
EXPECT_EQ(QuicTime::Delta::FromMicroseconds(287500),
manager_.GetRttStats()->smoothed_rtt());
}
TEST_F(QuicSentPacketManagerTest, IgnorePeerMaxAckDelayDuringHandshake) {
manager_.EnableMultiplePacketNumberSpacesSupport();
const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(100);
SendDataPacket(1, ENCRYPTION_INITIAL);
SendDataPacket(2, ENCRYPTION_HANDSHAKE);
clock_.AdvanceTime(kTestRTT);
ExpectAck(1);
manager_.OnAckFrameStart(QuicPacketNumber(1), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_INITIAL, kEmptyCounts));
EXPECT_EQ(kTestRTT, manager_.GetRttStats()->latest_rtt());
const QuicTime::Delta queuing_delay = QuicTime::Delta::FromMilliseconds(50);
clock_.AdvanceTime(queuing_delay);
ExpectAck(2);
manager_.OnAckFrameStart(QuicPacketNumber(2), queuing_delay, clock_.Now());
manager_.OnAckRange(QuicPacketNumber(2), QuicPacketNumber(3));
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(2),
ENCRYPTION_HANDSHAKE, kEmptyCounts));
EXPECT_EQ(kTestRTT, manager_.GetRttStats()->latest_rtt());
}
TEST_F(QuicSentPacketManagerTest, BuildAckFrequencyFrameWithSRTT) {
SetQuicReloadableFlag(quic_can_send_ack_frequency, true);
EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
EXPECT_CALL(*network_change_visitor_, OnCongestionChange());
QuicConfig config;
QuicConfigPeer::SetReceivedMinAckDelayMs(&config, 1);
QuicTagVector quic_tag_vector;
quic_tag_vector.push_back(kAFF1);
QuicConfigPeer::SetReceivedConnectionOptions(&config, quic_tag_vector);
manager_.SetFromConfig(config);
manager_.SetHandshakeConfirmed();
auto* rtt_stats = const_cast<RttStats*>(manager_.GetRttStats());
rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(80),
QuicTime::Delta::Zero(),
QuicTime::Zero());
rtt_stats->UpdateRtt(
QuicTime::Delta::FromMilliseconds(160),
QuicTime::Delta::Zero(),
QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(24));
auto frame = manager_.GetUpdatedAckFrequencyFrame();
EXPECT_EQ(frame.max_ack_delay,
std::max(rtt_stats->SmoothedOrInitialRtt() * 0.25,
QuicTime::Delta::FromMilliseconds(1u)));
}
TEST_F(QuicSentPacketManagerTest, SetInitialRtt) {
manager_.SetInitialRtt(
QuicTime::Delta::FromMicroseconds(kMaxInitialRoundTripTimeUs + 1), false);
EXPECT_EQ(manager_.GetRttStats()->initial_rtt().ToMicroseconds(),
kMaxInitialRoundTripTimeUs);
manager_.SetInitialRtt(
QuicTime::Delta::FromMicroseconds(kMaxInitialRoundTripTimeUs + 1), true);
EXPECT_EQ(manager_.GetRttStats()->initial_rtt().ToMicroseconds(),
kMaxInitialRoundTripTimeUs);
EXPECT_GT(kMinUntrustedInitialRoundTripTimeUs,
kMinTrustedInitialRoundTripTimeUs);
manager_.SetInitialRtt(QuicTime::Delta::FromMicroseconds(
kMinUntrustedInitialRoundTripTimeUs - 1),
false);
EXPECT_EQ(manager_.GetRttStats()->initial_rtt().ToMicroseconds(),
kMinUntrustedInitialRoundTripTimeUs);
manager_.SetInitialRtt(QuicTime::Delta::FromMicroseconds(
kMinUntrustedInitialRoundTripTimeUs - 1),
true);
EXPECT_EQ(manager_.GetRttStats()->initial_rtt().ToMicroseconds(),
kMinUntrustedInitialRoundTripTimeUs - 1);
manager_.SetInitialRtt(
QuicTime::Delta::FromMicroseconds(kMinTrustedInitialRoundTripTimeUs - 1),
true);
EXPECT_EQ(manager_.GetRttStats()->initial_rtt().ToMicroseconds(),
kMinTrustedInitialRoundTripTimeUs);
}
TEST_F(QuicSentPacketManagerTest, GetAvailableCongestionWindow) {
SendDataPacket(1);
EXPECT_EQ(kDefaultLength, manager_.GetBytesInFlight());
EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
.WillOnce(Return(kDefaultLength + 10));
EXPECT_EQ(10u, manager_.GetAvailableCongestionWindowInBytes());
EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
.WillOnce(Return(kDefaultLength));
EXPECT_EQ(0u, manager_.GetAvailableCongestionWindowInBytes());
EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
.WillOnce(Return(kDefaultLength - 10));
EXPECT_EQ(0u, manager_.GetAvailableCongestionWindowInBytes());
}
TEST_F(QuicSentPacketManagerTest, EcnCountsAreStored) {
if (!GetQuicRestartFlag(quic_support_ect1)) {
return;
}
std::optional<QuicEcnCounts> ecn_counts1, ecn_counts2, ecn_counts3;
ecn_counts1 = {1, 0, 3};
ecn_counts2 = {0, 3, 1};
ecn_counts3 = {0, 2, 0};
SendDataPacket(1, ENCRYPTION_INITIAL, ECN_ECT0);
SendDataPacket(2, ENCRYPTION_INITIAL, ECN_ECT0);
SendDataPacket(3, ENCRYPTION_INITIAL, ECN_ECT0);
SendDataPacket(4, ENCRYPTION_INITIAL, ECN_ECT0);
SendDataPacket(5, ENCRYPTION_HANDSHAKE, ECN_ECT1);
SendDataPacket(6, ENCRYPTION_HANDSHAKE, ECN_ECT1);
SendDataPacket(7, ENCRYPTION_HANDSHAKE, ECN_ECT1);
SendDataPacket(8, ENCRYPTION_HANDSHAKE, ECN_ECT1);
SendDataPacket(9, ENCRYPTION_FORWARD_SECURE, ECN_ECT1);
SendDataPacket(10, ENCRYPTION_FORWARD_SECURE, ECN_ECT1);
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1), ENCRYPTION_INITIAL,
ecn_counts1);
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(2),
ENCRYPTION_HANDSHAKE, ecn_counts2);
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(3),
ENCRYPTION_FORWARD_SECURE, ecn_counts3);
EXPECT_EQ(
*QuicSentPacketManagerPeer::GetPeerEcnCounts(&manager_, INITIAL_DATA),
ecn_counts1);
EXPECT_EQ(
*QuicSentPacketManagerPeer::GetPeerEcnCounts(&manager_, HANDSHAKE_DATA),
ecn_counts2);
EXPECT_EQ(
*QuicSentPacketManagerPeer::GetPeerEcnCounts(&manager_, APPLICATION_DATA),
ecn_counts3);
}
TEST_F(QuicSentPacketManagerTest, EcnCountsReceived) {
if (!GetQuicRestartFlag(quic_support_ect1)) {
return;
}
for (uint64_t i = 1; i <= 3; ++i) {
SendDataPacket(i, ENCRYPTION_FORWARD_SECURE, ECN_ECT1);
}
EXPECT_CALL(*network_change_visitor_, OnInFlightEcnPacketAcked()).Times(2);
manager_.OnAckFrameStart(QuicPacketNumber(3), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(2), QuicPacketNumber(4));
EXPECT_CALL(*send_algorithm_,
OnCongestionEvent(_, _, _, Pointwise(PacketNumberEq(), {2, 3}),
IsEmpty(), 2, 1))
.Times(1);
EXPECT_CALL(*network_change_visitor_, OnCongestionChange()).Times(1);
std::optional<QuicEcnCounts> ecn_counts = QuicEcnCounts();
ecn_counts->ect1 = QuicPacketCount(2);
ecn_counts->ce = QuicPacketCount(1);
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_FORWARD_SECURE, ecn_counts));
}
TEST_F(QuicSentPacketManagerTest, PeerDecrementsEcnCounts) {
if (!GetQuicRestartFlag(quic_support_ect1)) {
return;
}
for (uint64_t i = 1; i <= 5; ++i) {
SendDataPacket(i, ENCRYPTION_FORWARD_SECURE, ECN_ECT1);
}
EXPECT_CALL(*network_change_visitor_, OnInFlightEcnPacketAcked()).Times(3);
manager_.OnAckFrameStart(QuicPacketNumber(3), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(4));
EXPECT_CALL(*send_algorithm_,
OnCongestionEvent(_, _, _, Pointwise(PacketNumberEq(), {1, 2, 3}),
IsEmpty(), 2, 1))
.Times(1);
EXPECT_CALL(*network_change_visitor_, OnCongestionChange()).Times(1);
std::optional<QuicEcnCounts> ecn_counts = QuicEcnCounts();
ecn_counts->ect1 = QuicPacketCount(2);
ecn_counts->ce = QuicPacketCount(1);
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_FORWARD_SECURE, ecn_counts));
EXPECT_CALL(*network_change_visitor_, OnInFlightEcnPacketAcked()).Times(1);
manager_.OnAckFrameStart(QuicPacketNumber(4), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(4), QuicPacketNumber(5));
EXPECT_CALL(*network_change_visitor_, OnInvalidEcnFeedback());
EXPECT_CALL(*send_algorithm_,
OnCongestionEvent(_, _, _, Pointwise(PacketNumberEq(), {4}),
IsEmpty(), 0, 0))
.Times(1);
EXPECT_CALL(*network_change_visitor_, OnCongestionChange()).Times(1);
ecn_counts = QuicEcnCounts();
ecn_counts->ect1 = QuicPacketCount(3);
ecn_counts->ce = QuicPacketCount(0);
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(2),
ENCRYPTION_FORWARD_SECURE, ecn_counts));
}
TEST_F(QuicSentPacketManagerTest, TooManyEcnCountsReported) {
if (!GetQuicRestartFlag(quic_support_ect1)) {
return;
}
for (uint64_t i = 1; i <= 3; ++i) {
SendDataPacket(i, ENCRYPTION_FORWARD_SECURE, ECN_ECT1);
}
EXPECT_CALL(*network_change_visitor_, OnInFlightEcnPacketAcked()).Times(2);
manager_.OnAckFrameStart(QuicPacketNumber(3), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(2), QuicPacketNumber(4));
std::optional<QuicEcnCounts> ecn_counts = QuicEcnCounts();
ecn_counts->ect1 = QuicPacketCount(3);
ecn_counts->ce = QuicPacketCount(1);
EXPECT_CALL(*network_change_visitor_, OnInvalidEcnFeedback());
EXPECT_CALL(*send_algorithm_,
OnCongestionEvent(_, _, _, Pointwise(PacketNumberEq(), {2, 3}),
IsEmpty(), 0, 0))
.Times(1);
EXPECT_CALL(*network_change_visitor_, OnCongestionChange()).Times(1);
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_FORWARD_SECURE, ecn_counts));
}
TEST_F(QuicSentPacketManagerTest, PeerReportsWrongCodepoint) {
if (!GetQuicRestartFlag(quic_support_ect1)) {
return;
}
for (uint64_t i = 1; i <= 3; ++i) {
SendDataPacket(i, ENCRYPTION_FORWARD_SECURE, ECN_ECT1);
}
EXPECT_CALL(*network_change_visitor_, OnInFlightEcnPacketAcked()).Times(2);
manager_.OnAckFrameStart(QuicPacketNumber(3), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(2), QuicPacketNumber(4));
std::optional<QuicEcnCounts> ecn_counts = QuicEcnCounts();
ecn_counts->ect0 = QuicPacketCount(2);
ecn_counts->ce = QuicPacketCount(1);
EXPECT_CALL(*network_change_visitor_, OnInvalidEcnFeedback());
EXPECT_CALL(*send_algorithm_,
OnCongestionEvent(_, _, _, Pointwise(PacketNumberEq(), {2, 3}),
IsEmpty(), 0, 0))
.Times(1);
EXPECT_CALL(*network_change_visitor_, OnCongestionChange()).Times(1);
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_FORWARD_SECURE, ecn_counts));
}
TEST_F(QuicSentPacketManagerTest, TooFewEcnCountsReported) {
if (!GetQuicRestartFlag(quic_support_ect1)) {
return;
}
for (uint64_t i = 1; i <= 3; ++i) {
SendDataPacket(i, ENCRYPTION_FORWARD_SECURE, ECN_ECT1);
}
EXPECT_CALL(*network_change_visitor_, OnInFlightEcnPacketAcked()).Times(2);
manager_.OnAckFrameStart(QuicPacketNumber(3), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(2), QuicPacketNumber(4));
EXPECT_CALL(*network_change_visitor_, OnInvalidEcnFeedback());
EXPECT_CALL(*send_algorithm_,
OnCongestionEvent(_, _, _, Pointwise(PacketNumberEq(), {2, 3}),
IsEmpty(), 0, 0))
.Times(1);
EXPECT_CALL(*network_change_visitor_, OnCongestionChange()).Times(1);
std::optional<QuicEcnCounts> ecn_counts = QuicEcnCounts();
ecn_counts->ect1 = QuicPacketCount(1);
ecn_counts->ce = QuicPacketCount(0);
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_FORWARD_SECURE, ecn_counts));
}
TEST_F(QuicSentPacketManagerTest,
EcnCountsNotValidatedIfLargestAckedUnchanged) {
if (!GetQuicRestartFlag(quic_support_ect1)) {
return;
}
for (uint64_t i = 1; i <= 3; ++i) {
SendDataPacket(i, ENCRYPTION_FORWARD_SECURE, ECN_ECT1);
}
EXPECT_CALL(*network_change_visitor_, OnInFlightEcnPacketAcked()).Times(2);
manager_.OnAckFrameStart(QuicPacketNumber(3), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(2), QuicPacketNumber(4));
EXPECT_CALL(*send_algorithm_,
OnCongestionEvent(_, _, _, Pointwise(PacketNumberEq(), {2, 3}),
IsEmpty(), 2, 1))
.Times(1);
EXPECT_CALL(*network_change_visitor_, OnCongestionChange()).Times(1);
std::optional<QuicEcnCounts> ecn_counts = QuicEcnCounts();
ecn_counts->ect1 = QuicPacketCount(2);
ecn_counts->ce = QuicPacketCount(1);
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_FORWARD_SECURE, ecn_counts));
EXPECT_CALL(*network_change_visitor_, OnInFlightEcnPacketAcked()).Times(1);
manager_.OnAckFrameStart(QuicPacketNumber(3), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(1), QuicPacketNumber(4));
EXPECT_CALL(*send_algorithm_,
OnCongestionEvent(_, _, _, Pointwise(PacketNumberEq(), {1}),
IsEmpty(), 0, 0))
.Times(1);
EXPECT_CALL(*network_change_visitor_, OnCongestionChange()).Times(1);
ecn_counts = QuicEcnCounts();
ecn_counts->ect1 = QuicPacketCount(2);
ecn_counts->ce = QuicPacketCount(0);
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(2),
ENCRYPTION_FORWARD_SECURE, ecn_counts));
}
TEST_F(QuicSentPacketManagerTest, EcnAckedButNoMarksReported) {
if (!GetQuicRestartFlag(quic_support_ect1)) {
return;
}
for (uint64_t i = 1; i <= 3; ++i) {
SendDataPacket(i, ENCRYPTION_FORWARD_SECURE, ECN_ECT1);
}
EXPECT_CALL(*network_change_visitor_, OnInFlightEcnPacketAcked()).Times(2);
manager_.OnAckFrameStart(QuicPacketNumber(3), QuicTime::Delta::Infinite(),
clock_.Now());
manager_.OnAckRange(QuicPacketNumber(2), QuicPacketNumber(4));
EXPECT_CALL(*network_change_visitor_, OnInvalidEcnFeedback());
EXPECT_CALL(*send_algorithm_,
OnCongestionEvent(_, _, _, Pointwise(PacketNumberEq(), {2, 3}),
IsEmpty(), 0, 0))
.Times(1);
EXPECT_CALL(*network_change_visitor_, OnCongestionChange()).Times(1);
std::optional<QuicEcnCounts> ecn_counts = std::nullopt;
EXPECT_EQ(PACKETS_NEWLY_ACKED,
manager_.OnAckFrameEnd(clock_.Now(), QuicPacketNumber(1),
ENCRYPTION_FORWARD_SECURE, ecn_counts));
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_sent_packet_manager.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_sent_packet_manager_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
fa41cd86-bce6-4de3-bb3a-e3c3aaae27ec | cpp | google/quiche | tls_client_handshaker | quiche/quic/core/tls_client_handshaker.cc | quiche/quic/core/tls_client_handshaker_test.cc | #include "quiche/quic/core/tls_client_handshaker.h"
#include <algorithm>
#include <cstring>
#include <limits>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "openssl/ssl.h"
#include "quiche/quic/core/crypto/quic_crypto_client_config.h"
#include "quiche/quic/core/crypto/quic_encrypter.h"
#include "quiche/quic/core/crypto/transport_parameters.h"
#include "quiche/quic/core/quic_session.h"
#include "quiche/quic/core/quic_types.h"
#include "quiche/quic/platform/api/quic_flags.h"
#include "quiche/quic/platform/api/quic_hostname_utils.h"
#include "quiche/common/quiche_text_utils.h"
namespace quic {
TlsClientHandshaker::TlsClientHandshaker(
const QuicServerId& server_id, QuicCryptoStream* stream,
QuicSession* session, std::unique_ptr<ProofVerifyContext> verify_context,
QuicCryptoClientConfig* crypto_config,
QuicCryptoClientStream::ProofHandler* proof_handler,
bool has_application_state)
: TlsHandshaker(stream, session),
session_(session),
server_id_(server_id),
proof_verifier_(crypto_config->proof_verifier()),
verify_context_(std::move(verify_context)),
proof_handler_(proof_handler),
session_cache_(crypto_config->session_cache()),
user_agent_id_(crypto_config->user_agent_id()),
pre_shared_key_(crypto_config->pre_shared_key()),
crypto_negotiated_params_(new QuicCryptoNegotiatedParameters),
has_application_state_(has_application_state),
tls_connection_(crypto_config->ssl_ctx(), this, session->GetSSLConfig()) {
if (crypto_config->tls_signature_algorithms().has_value()) {
SSL_set1_sigalgs_list(ssl(),
crypto_config->tls_signature_algorithms()->c_str());
}
if (crypto_config->proof_source() != nullptr) {
std::shared_ptr<const ClientProofSource::CertAndKey> cert_and_key =
crypto_config->proof_source()->GetCertAndKey(server_id.host());
if (cert_and_key != nullptr) {
QUIC_DVLOG(1) << "Setting client cert and key for " << server_id.host();
tls_connection_.SetCertChain(cert_and_key->chain->ToCryptoBuffers().value,
cert_and_key->private_key.private_key());
}
}
#if BORINGSSL_API_VERSION >= 22
if (!crypto_config->preferred_groups().empty()) {
SSL_set1_group_ids(ssl(), crypto_config->preferred_groups().data(),
crypto_config->preferred_groups().size());
}
#endif
#if BORINGSSL_API_VERSION >= 27
SSL_set_alps_use_new_codepoint(ssl(),
crypto_config->alps_use_new_codepoint());
#endif
}
TlsClientHandshaker::~TlsClientHandshaker() {}
bool TlsClientHandshaker::CryptoConnect() {
if (!pre_shared_key_.empty()) {
std::string error_details =
"QUIC client pre-shared keys not yet supported with TLS";
QUIC_BUG(quic_bug_10576_1) << error_details;
CloseConnection(QUIC_HANDSHAKE_FAILED, error_details);
return false;
}
int use_legacy_extension = 0;
if (session()->version().UsesLegacyTlsExtension()) {
use_legacy_extension = 1;
}
SSL_set_quic_use_legacy_codepoint(ssl(), use_legacy_extension);
#if BORINGSSL_API_VERSION >= 16
SSL_set_permute_extensions(ssl(), true);
#endif
SSL_set_connect_state(ssl());
const bool allow_invalid_sni_for_test =
GetQuicFlag(quic_client_allow_invalid_sni_for_test);
if (QUIC_DLOG_INFO_IS_ON() &&
!QuicHostnameUtils::IsValidSNI(server_id_.host())) {
QUIC_DLOG(INFO) << "Client configured with invalid hostname \""
<< server_id_.host() << "\", "
<< (allow_invalid_sni_for_test
? "sending it anyway for test."
: "not sending as SNI.");
}
if (!server_id_.host().empty() &&
(QuicHostnameUtils::IsValidSNI(server_id_.host()) ||
allow_invalid_sni_for_test) &&
SSL_set_tlsext_host_name(ssl(), server_id_.host().c_str()) != 1) {
return false;
}
if (!SetAlpn()) {
CloseConnection(QUIC_HANDSHAKE_FAILED, "Client failed to set ALPN");
return false;
}
if (!SetTransportParameters()) {
CloseConnection(QUIC_HANDSHAKE_FAILED,
"Client failed to set Transport Parameters");
return false;
}
if (session_cache_) {
cached_state_ = session_cache_->Lookup(
server_id_, session()->GetClock()->WallNow(), SSL_get_SSL_CTX(ssl()));
}
if (cached_state_) {
SSL_set_session(ssl(), cached_state_->tls_session.get());
if (!cached_state_->token.empty()) {
session()->SetSourceAddressTokenToSend(cached_state_->token);
}
}
SSL_set_enable_ech_grease(ssl(),
tls_connection_.ssl_config().ech_grease_enabled);
if (!tls_connection_.ssl_config().ech_config_list.empty() &&
!SSL_set1_ech_config_list(
ssl(),
reinterpret_cast<const uint8_t*>(
tls_connection_.ssl_config().ech_config_list.data()),
tls_connection_.ssl_config().ech_config_list.size())) {
CloseConnection(QUIC_HANDSHAKE_FAILED,
"Client failed to set ECHConfigList");
return false;
}
AdvanceHandshake();
return session()->connection()->connected();
}
bool TlsClientHandshaker::PrepareZeroRttConfig(
QuicResumptionState* cached_state) {
std::string error_details;
if (!cached_state->transport_params ||
handshaker_delegate()->ProcessTransportParameters(
*(cached_state->transport_params),
true, &error_details) != QUIC_NO_ERROR) {
QUIC_BUG(quic_bug_10576_2)
<< "Unable to parse cached transport parameters.";
CloseConnection(QUIC_HANDSHAKE_FAILED,
"Client failed to parse cached Transport Parameters.");
return false;
}
session()->connection()->OnTransportParametersResumed(
*(cached_state->transport_params));
session()->OnConfigNegotiated();
if (has_application_state_) {
if (!cached_state->application_state ||
!session()->ResumeApplicationState(
cached_state->application_state.get())) {
QUIC_BUG(quic_bug_10576_3) << "Unable to parse cached application state.";
CloseConnection(QUIC_HANDSHAKE_FAILED,
"Client failed to parse cached application state.");
return false;
}
}
return true;
}
static bool IsValidAlpn(const std::string& alpn_string) {
return alpn_string.length() <= std::numeric_limits<uint8_t>::max();
}
bool TlsClientHandshaker::SetAlpn() {
std::vector<std::string> alpns = session()->GetAlpnsToOffer();
if (alpns.empty()) {
if (allow_empty_alpn_for_tests_) {
return true;
}
QUIC_BUG(quic_bug_10576_4) << "ALPN missing";
return false;
}
if (!std::all_of(alpns.begin(), alpns.end(), IsValidAlpn)) {
QUIC_BUG(quic_bug_10576_5) << "ALPN too long";
return false;
}
uint8_t alpn[1024];
QuicDataWriter alpn_writer(sizeof(alpn), reinterpret_cast<char*>(alpn));
bool success = true;
for (const std::string& alpn_string : alpns) {
success = success && alpn_writer.WriteUInt8(alpn_string.size()) &&
alpn_writer.WriteStringPiece(alpn_string);
}
success =
success && (SSL_set_alpn_protos(ssl(), alpn, alpn_writer.length()) == 0);
if (!success) {
QUIC_BUG(quic_bug_10576_6)
<< "Failed to set ALPN: "
<< quiche::QuicheTextUtils::HexDump(
absl::string_view(alpn_writer.data(), alpn_writer.length()));
return false;
}
for (const std::string& alpn_string : alpns) {
for (const ParsedQuicVersion& version : session()->supported_versions()) {
if (!version.UsesHttp3() || AlpnForVersion(version) != alpn_string) {
continue;
}
if (SSL_add_application_settings(
ssl(), reinterpret_cast<const uint8_t*>(alpn_string.data()),
alpn_string.size(), nullptr, 0) != 1) {
QUIC_BUG(quic_bug_10576_7) << "Failed to enable ALPS.";
return false;
}
break;
}
}
QUIC_DLOG(INFO) << "Client using ALPN: '" << alpns[0] << "'";
return true;
}
bool TlsClientHandshaker::SetTransportParameters() {
TransportParameters params;
params.perspective = Perspective::IS_CLIENT;
params.legacy_version_information =
TransportParameters::LegacyVersionInformation();
params.legacy_version_information->version =
CreateQuicVersionLabel(session()->supported_versions().front());
params.version_information = TransportParameters::VersionInformation();
const QuicVersionLabel version = CreateQuicVersionLabel(session()->version());
params.version_information->chosen_version = version;
params.version_information->other_versions.push_back(version);
if (!handshaker_delegate()->FillTransportParameters(¶ms)) {
return false;
}
session()->connection()->OnTransportParametersSent(params);
std::vector<uint8_t> param_bytes;
return SerializeTransportParameters(params, ¶m_bytes) &&
SSL_set_quic_transport_params(ssl(), param_bytes.data(),
param_bytes.size()) == 1;
}
bool TlsClientHandshaker::ProcessTransportParameters(
std::string* error_details) {
received_transport_params_ = std::make_unique<TransportParameters>();
const uint8_t* param_bytes;
size_t param_bytes_len;
SSL_get_peer_quic_transport_params(ssl(), ¶m_bytes, ¶m_bytes_len);
if (param_bytes_len == 0) {
*error_details = "Server's transport parameters are missing";
return false;
}
std::string parse_error_details;
if (!ParseTransportParameters(
session()->connection()->version(), Perspective::IS_SERVER,
param_bytes, param_bytes_len, received_transport_params_.get(),
&parse_error_details)) {
QUICHE_DCHECK(!parse_error_details.empty());
*error_details =
"Unable to parse server's transport parameters: " + parse_error_details;
return false;
}
session()->connection()->OnTransportParametersReceived(
*received_transport_params_);
if (received_transport_params_->legacy_version_information.has_value()) {
if (received_transport_params_->legacy_version_information->version !=
CreateQuicVersionLabel(session()->connection()->version())) {
*error_details = "Version mismatch detected";
return false;
}
if (CryptoUtils::ValidateServerHelloVersions(
received_transport_params_->legacy_version_information
->supported_versions,
session()->connection()->server_supported_versions(),
error_details) != QUIC_NO_ERROR) {
QUICHE_DCHECK(!error_details->empty());
return false;
}
}
if (received_transport_params_->version_information.has_value()) {
if (!CryptoUtils::ValidateChosenVersion(
received_transport_params_->version_information->chosen_version,
session()->version(), error_details)) {
QUICHE_DCHECK(!error_details->empty());
return false;
}
if (!CryptoUtils::CryptoUtils::ValidateServerVersions(
received_transport_params_->version_information->other_versions,
session()->version(),
session()->client_original_supported_versions(), error_details)) {
QUICHE_DCHECK(!error_details->empty());
return false;
}
}
if (handshaker_delegate()->ProcessTransportParameters(
*received_transport_params_, false,
error_details) != QUIC_NO_ERROR) {
QUICHE_DCHECK(!error_details->empty());
return false;
}
session()->OnConfigNegotiated();
if (is_connection_closed()) {
*error_details =
"Session closed the connection when parsing negotiated config.";
return false;
}
return true;
}
int TlsClientHandshaker::num_sent_client_hellos() const { return 0; }
bool TlsClientHandshaker::ResumptionAttempted() const {
QUIC_BUG_IF(quic_tls_client_resumption_attempted, !encryption_established_);
return cached_state_ != nullptr;
}
bool TlsClientHandshaker::IsResumption() const {
QUIC_BUG_IF(quic_bug_12736_1, !one_rtt_keys_available());
return SSL_session_reused(ssl()) == 1;
}
bool TlsClientHandshaker::EarlyDataAccepted() const {
QUIC_BUG_IF(quic_bug_12736_2, !one_rtt_keys_available());
return SSL_early_data_accepted(ssl()) == 1;
}
ssl_early_data_reason_t TlsClientHandshaker::EarlyDataReason() const {
return TlsHandshaker::EarlyDataReason();
}
bool TlsClientHandshaker::ReceivedInchoateReject() const {
QUIC_BUG_IF(quic_bug_12736_3, !one_rtt_keys_available());
return false;
}
int TlsClientHandshaker::num_scup_messages_received() const {
return 0;
}
std::string TlsClientHandshaker::chlo_hash() const { return ""; }
bool TlsClientHandshaker::ExportKeyingMaterial(absl::string_view label,
absl::string_view context,
size_t result_len,
std::string* result) {
return ExportKeyingMaterialForLabel(label, context, result_len, result);
}
bool TlsClientHandshaker::encryption_established() const {
return encryption_established_;
}
bool TlsClientHandshaker::IsCryptoFrameExpectedForEncryptionLevel(
EncryptionLevel level) const {
return level != ENCRYPTION_ZERO_RTT;
}
EncryptionLevel TlsClientHandshaker::GetEncryptionLevelToSendCryptoDataOfSpace(
PacketNumberSpace space) const {
switch (space) {
case INITIAL_DATA:
return ENCRYPTION_INITIAL;
case HANDSHAKE_DATA:
return ENCRYPTION_HANDSHAKE;
default:
QUICHE_DCHECK(false);
return NUM_ENCRYPTION_LEVELS;
}
}
bool TlsClientHandshaker::one_rtt_keys_available() const {
return state_ >= HANDSHAKE_COMPLETE;
}
const QuicCryptoNegotiatedParameters&
TlsClientHandshaker::crypto_negotiated_params() const {
return *crypto_negotiated_params_;
}
CryptoMessageParser* TlsClientHandshaker::crypto_message_parser() {
return TlsHandshaker::crypto_message_parser();
}
HandshakeState TlsClientHandshaker::GetHandshakeState() const { return state_; }
size_t TlsClientHandshaker::BufferSizeLimitForLevel(
EncryptionLevel level) const {
return TlsHandshaker::BufferSizeLimitForLevel(level);
}
std::unique_ptr<QuicDecrypter>
TlsClientHandshaker::AdvanceKeysAndCreateCurrentOneRttDecrypter() {
return TlsHandshaker::AdvanceKeysAndCreateCurrentOneRttDecrypter();
}
std::unique_ptr<QuicEncrypter>
TlsClientHandshaker::CreateCurrentOneRttEncrypter() {
return TlsHandshaker::CreateCurrentOneRttEncrypter();
}
void TlsClientHandshaker::OnOneRttPacketAcknowledged() {
OnHandshakeConfirmed();
}
void TlsClientHandshaker::OnHandshakePacketSent() {
if (initial_keys_dropped_) {
return;
}
initial_keys_dropped_ = true;
handshaker_delegate()->DiscardOldEncryptionKey(ENCRYPTION_INITIAL);
handshaker_delegate()->DiscardOldDecryptionKey(ENCRYPTION_INITIAL);
}
void TlsClientHandshaker::OnConnectionClosed(QuicErrorCode error,
ConnectionCloseSource source) {
TlsHandshaker::OnConnectionClosed(error, source);
}
void TlsClientHandshaker::OnHandshakeDoneReceived() {
if (!one_rtt_keys_available()) {
CloseConnection(QUIC_HANDSHAKE_FAILED,
"Unexpected handshake done received");
return;
}
OnHandshakeConfirmed();
}
void TlsClientHandshaker::OnNewTokenReceived(absl::string_view token) {
if (token.empty()) {
return;
}
if (session_cache_ != nullptr) {
session_cache_->OnNewTokenReceived(server_id_, token);
}
}
void TlsClientHandshaker::SetWriteSecret(
EncryptionLevel level, const SSL_CIPHER* cipher,
absl::Span<const uint8_t> write_secret) {
if (is_connection_closed()) {
return;
}
if (level == ENCRYPTION_FORWARD_SECURE || level == ENCRYPTION_ZERO_RTT) {
encryption_established_ = true;
}
TlsHandshaker::SetWriteSecret(level, cipher, write_secret);
if (level == ENCRYPTION_FORWARD_SECURE) {
handshaker_delegate()->DiscardOldEncryptionKey(ENCRYPTION_ZERO_RTT);
}
}
void TlsClientHandshaker::OnHandshakeConfirmed() {
QUICHE_DCHECK(one_rtt_keys_available());
if (state_ >= HANDSHAKE_CONFIRMED) {
return;
}
state_ = HANDSHAKE_CONFIRMED;
handshaker_delegate()->OnTlsHandshakeConfirmed();
handshaker_delegate()->DiscardOldEncryptionKey(ENCRYPTION_HANDSHAKE);
handshaker_delegate()->DiscardOldDecryptionKey(ENCRYPTION_HANDSHAKE);
}
QuicAsyncStatus TlsClientHandshaker::VerifyCertChain(
const std::vector<std::string>& certs, std::string* error_details,
std::unique_ptr<ProofVerifyDetails>* details, uint8_t* out_alert,
std::unique_ptr<ProofVerifierCallback> callback) {
const uint8_t* ocsp_response_raw;
size_t ocsp_response_len;
SSL_get0_ocsp_response(ssl(), &ocsp_response_raw, &ocsp_response_len);
std::string ocsp_response(reinterpret_cast<const char*>(ocsp_response_raw),
ocsp_response_len);
const uint8_t* sct_list_raw;
size_t sct_list_len;
SSL_get0_signed_cert_timestamp_list(ssl(), &sct_list_raw, &sct_list_len);
std::string sct_list(reinterpret_cast<const char*>(sct_list_raw),
sct_list_len);
return proof_verifier_->VerifyCertChain(
server_id_.host(), server_id_.port(), certs, ocsp_response, sct_list,
verify_context_.get(), error_details, details, out_alert,
std::move(callback));
}
void TlsClientHandshaker::OnProofVerifyDetailsAvailable(
const ProofVerifyDetails& verify_details) {
proof_handler_->OnProofVerifyDetailsAvailable(verify_details);
}
void TlsClientHandshaker::FinishHandshake() {
FillNegotiatedParams();
QUICHE_CHECK(!SSL_in_early_data(ssl()));
QUIC_DLOG(INFO) << "Client: handshake finished";
std::string error_details;
if (!ProcessTransportParameters(&error_details)) {
QUICHE_DCHECK(!error_details.empty());
CloseConnection(QUIC_HANDSHAKE_FAILED, error_details);
return;
}
const uint8_t* alpn_data = nullptr;
unsigned alpn_length = 0;
SSL_get0_alpn_selected(ssl(), &alpn_data, &alpn_length);
if (alpn_length == 0) {
QUIC_DLOG(ERROR) << "Client: server did not select ALPN";
CloseConnection(QUIC_HANDSHAKE_FAILED, "Server did not select ALPN");
return;
}
std::string received_alpn_string(reinterpret_cast<const char*>(alpn_data),
alpn_length);
std::vector<std::string> offered_alpns = session()->GetAlpnsToOffer();
if (std::find(offered_alpns.begin(), offered_alpns.end(),
received_alpn_string) == offered_alpns.end()) {
QUIC_LOG(ERROR) << "Client: received mismatched ALPN '"
<< received_alpn_string;
CloseConnection(QUIC_HANDSHAKE_FAILED, "Client received mismatched ALPN");
return;
}
session()->OnAlpnSelected(received_alpn_string);
QUIC_DLOG(INFO) << "Client: server selected ALPN: '" << received_alpn_string
<< "'";
const uint8_t* alps_data;
size_t alps_length;
SSL_get0_peer_application_settings(ssl(), &alps_data, &alps_length);
if (alps_length > 0) {
auto error = session()->OnAlpsData(alps_data, alps_length);
if (error.has_value()) {
CloseConnection(QUIC_HANDSHAKE_FAILED,
absl::StrCat("Error processing ALPS data: ", *error));
return;
}
}
state_ = HANDSHAKE_COMPLETE;
handshaker_delegate()->OnTlsHandshakeComplete();
}
void TlsClientHandshaker::OnEnterEarlyData() {
QUICHE_DCHECK(SSL_in_early_data(ssl()));
FillNegotiatedParams();
PrepareZeroRttConfig(cached_state_.get());
}
void TlsClientHandshaker::FillNegotiatedParams() {
const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl());
if (cipher) {
crypto_negotiated_params_->cipher_suite =
SSL_CIPHER_get_protocol_id(cipher);
}
crypto_negotiated_params_->key_exchange_group = SSL_get_curve_id(ssl());
crypto_negotiated_params_->peer_signature_algorithm =
SSL_get_peer_signature_algorithm(ssl());
crypto_negotiated_params_->encrypted_client_hello = SSL_ech_accepted(ssl());
}
void TlsClientHandshaker::ProcessPostHandshakeMessage() {
int rv = SSL_process_quic_post_handshake(ssl());
if (rv != 1) {
CloseConnection(QUIC_HANDSHAKE_FAILED, "Unexpected post-handshake data");
}
}
bool TlsClientHandshaker::ShouldCloseConnectionOnUnexpectedError(
int ssl_error) {
if (ssl_error != SSL_ERROR_EARLY_DATA_REJECTED) {
return true;
}
HandleZeroRttReject();
return false;
}
void TlsClientHandshaker::HandleZeroRttReject() {
QUIC_DLOG(INFO) << "0-RTT handshake attempted but was rejected by the server";
QUICHE_DCHECK(session_cache_);
encryption_established_ = false;
handshaker_delegate()->OnZeroRttRejected(EarlyDataReason());
SSL_reset_early_data_reject(ssl());
session_cache_->ClearEarlyData(server_id_);
AdvanceHandshake();
}
void TlsClientHandshaker::InsertSession(bssl::UniquePtr<SSL_SESSION> session) {
if (!received_transport_params_) {
QUIC_BUG(quic_bug_10576_8) << "Transport parameters isn't received";
return;
}
if (session_cache_ == nullptr) {
QUIC_DVLOG(1) << "No session cache, not inserting a session";
return;
}
if (has_application_state_ && !received_application_state_) {
if (cached_tls_sessions_[0] != nullptr) {
cached_tls_sessions_[1] = std::move(cached_tls_sessions_[0]);
}
cached_tls_sessions_[0] = std::move(session);
return;
}
session_cache_->Insert(server_id_, std::move(session),
*received_transport_params_,
received_application_state_.get());
}
void TlsClientHandshaker::WriteMessage(EncryptionLevel level,
absl::string_view data) {
if (level == ENCRYPTION_HANDSHAKE && state_ < HANDSHAKE_PROCESSED) {
state_ = HANDSHAKE_PROCESSED;
}
TlsHandshaker::WriteMessage(level, data);
}
void TlsClientHandshaker::SetServerApplicationStateForResumption(
std::unique_ptr<ApplicationState> application_state) {
QUICHE_DCHECK(one_rtt_keys_available());
received_application_state_ = std::move(application_state);
if (session_cache_ != nullptr && cached_tls_sessions_[0] != nullptr) {
if (cached_tls_sessions_[1] != nullptr) {
session_cache_->Insert(server_id_, std::move(cached_tls_sessions_[1]),
*received_transport_params_,
received_application_state_.get());
}
session_cache_->Insert(server_id_, std::move(cached_tls_sessions_[0]),
*received_transport_params_,
received_application_state_.get());
}
}
} | #include <algorithm>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "absl/base/macros.h"
#include "openssl/hpke.h"
#include "openssl/ssl.h"
#include "quiche/quic/core/crypto/quic_decrypter.h"
#include "quiche/quic/core/crypto/quic_encrypter.h"
#include "quiche/quic/core/quic_error_codes.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_expect_bug.h"
#include "quiche/quic/platform/api/quic_flags.h"
#include "quiche/quic/platform/api/quic_test.h"
#include "quiche/quic/test_tools/crypto_test_utils.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_session_peer.h"
#include "quiche/quic/test_tools/quic_test_utils.h"
#include "quiche/quic/test_tools/simple_session_cache.h"
#include "quiche/quic/tools/fake_proof_verifier.h"
#include "quiche/common/test_tools/quiche_test_utils.h"
using testing::_;
using testing::HasSubstr;
namespace quic {
namespace test {
namespace {
constexpr char kServerHostname[] = "test.example.com";
constexpr uint16_t kServerPort = 443;
class TestProofVerifier : public ProofVerifier {
public:
TestProofVerifier()
: verifier_(crypto_test_utils::ProofVerifierForTesting()) {}
QuicAsyncStatus VerifyProof(
const std::string& hostname, const uint16_t port,
const std::string& server_config, QuicTransportVersion quic_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 {
return verifier_->VerifyProof(
hostname, port, server_config, quic_version, chlo_hash, certs, cert_sct,
signature, context, error_details, details, std::move(callback));
}
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 {
if (!active_) {
return verifier_->VerifyCertChain(
hostname, port, certs, ocsp_response, cert_sct, context,
error_details, details, out_alert, std::move(callback));
}
pending_ops_.push_back(std::make_unique<VerifyChainPendingOp>(
hostname, port, certs, ocsp_response, cert_sct, context, error_details,
details, out_alert, std::move(callback), verifier_.get()));
return QUIC_PENDING;
}
std::unique_ptr<ProofVerifyContext> CreateDefaultContext() override {
return nullptr;
}
void Activate() { active_ = true; }
size_t NumPendingCallbacks() const { return pending_ops_.size(); }
void InvokePendingCallback(size_t n) {
ASSERT_GT(NumPendingCallbacks(), n);
pending_ops_[n]->Run();
auto it = pending_ops_.begin() + n;
pending_ops_.erase(it);
}
private:
class FailingProofVerifierCallback : public ProofVerifierCallback {
public:
void Run(bool , const std::string& ,
std::unique_ptr<ProofVerifyDetails>* ) override {
FAIL();
}
};
class VerifyChainPendingOp {
public:
VerifyChainPendingOp(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,
ProofVerifier* delegate)
: hostname_(hostname),
port_(port),
certs_(certs),
ocsp_response_(ocsp_response),
cert_sct_(cert_sct),
context_(context),
error_details_(error_details),
details_(details),
out_alert_(out_alert),
callback_(std::move(callback)),
delegate_(delegate) {}
void Run() {
QuicAsyncStatus status = delegate_->VerifyCertChain(
hostname_, port_, certs_, ocsp_response_, cert_sct_, context_,
error_details_, details_, out_alert_,
std::make_unique<FailingProofVerifierCallback>());
ASSERT_NE(status, QUIC_PENDING);
callback_->Run(status == QUIC_SUCCESS, *error_details_, details_);
}
private:
std::string hostname_;
const uint16_t port_;
std::vector<std::string> certs_;
std::string ocsp_response_;
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_;
ProofVerifier* delegate_;
};
std::unique_ptr<ProofVerifier> verifier_;
bool active_ = false;
std::vector<std::unique_ptr<VerifyChainPendingOp>> pending_ops_;
};
class TlsClientHandshakerTest : public QuicTestWithParam<ParsedQuicVersion> {
public:
TlsClientHandshakerTest()
: supported_versions_({GetParam()}),
server_id_(kServerHostname, kServerPort),
server_compressed_certs_cache_(
QuicCompressedCertsCache::kQuicCompressedCertsCacheSize) {
crypto_config_ = std::make_unique<QuicCryptoClientConfig>(
std::make_unique<TestProofVerifier>(),
std::make_unique<test::SimpleSessionCache>());
server_crypto_config_ = crypto_test_utils::CryptoServerConfigForTesting();
CreateConnection();
}
void CreateSession() {
session_ = std::make_unique<TestQuicSpdyClientSession>(
connection_, DefaultQuicConfig(), supported_versions_, server_id_,
crypto_config_.get(), ssl_config_);
EXPECT_CALL(*session_, GetAlpnsToOffer())
.WillRepeatedly(testing::Return(std::vector<std::string>(
{AlpnForVersion(connection_->version())})));
}
void CreateConnection() {
connection_ =
new PacketSavingConnection(&client_helper_, &alarm_factory_,
Perspective::IS_CLIENT, supported_versions_);
connection_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
CreateSession();
}
void CompleteCryptoHandshake() {
CompleteCryptoHandshakeWithServerALPN(
AlpnForVersion(connection_->version()));
}
void CompleteCryptoHandshakeWithServerALPN(const std::string& alpn) {
EXPECT_CALL(*connection_, SendCryptoData(_, _, _))
.Times(testing::AnyNumber());
stream()->CryptoConnect();
QuicConfig config;
crypto_test_utils::HandshakeWithFakeServer(
&config, server_crypto_config_.get(), &server_helper_, &alarm_factory_,
connection_, stream(), alpn);
}
QuicCryptoClientStream* stream() {
return session_->GetMutableCryptoStream();
}
QuicCryptoServerStreamBase* server_stream() {
return server_session_->GetMutableCryptoStream();
}
void InitializeFakeServer() {
TestQuicSpdyServerSession* server_session = nullptr;
CreateServerSessionForTest(
server_id_, QuicTime::Delta::FromSeconds(100000), supported_versions_,
&server_helper_, &alarm_factory_, server_crypto_config_.get(),
&server_compressed_certs_cache_, &server_connection_, &server_session);
server_session_.reset(server_session);
std::string alpn = AlpnForVersion(connection_->version());
EXPECT_CALL(*server_session_, SelectAlpn(_))
.WillRepeatedly([alpn](const std::vector<absl::string_view>& alpns) {
return std::find(alpns.cbegin(), alpns.cend(), alpn);
});
}
static bssl::UniquePtr<SSL_ECH_KEYS> MakeTestEchKeys(
const char* public_name, size_t max_name_len,
std::string* ech_config_list) {
bssl::ScopedEVP_HPKE_KEY key;
if (!EVP_HPKE_KEY_generate(key.get(), EVP_hpke_x25519_hkdf_sha256())) {
return nullptr;
}
uint8_t* ech_config;
size_t ech_config_len;
if (!SSL_marshal_ech_config(&ech_config, &ech_config_len,
1, key.get(), public_name,
max_name_len)) {
return nullptr;
}
bssl::UniquePtr<uint8_t> scoped_ech_config(ech_config);
uint8_t* ech_config_list_raw;
size_t ech_config_list_len;
bssl::UniquePtr<SSL_ECH_KEYS> keys(SSL_ECH_KEYS_new());
if (!keys ||
!SSL_ECH_KEYS_add(keys.get(), 1, ech_config,
ech_config_len, key.get()) ||
!SSL_ECH_KEYS_marshal_retry_configs(keys.get(), &ech_config_list_raw,
&ech_config_list_len)) {
return nullptr;
}
bssl::UniquePtr<uint8_t> scoped_ech_config_list(ech_config_list_raw);
ech_config_list->assign(ech_config_list_raw,
ech_config_list_raw + ech_config_list_len);
return keys;
}
MockQuicConnectionHelper server_helper_;
MockQuicConnectionHelper client_helper_;
MockAlarmFactory alarm_factory_;
PacketSavingConnection* connection_;
ParsedQuicVersionVector supported_versions_;
std::unique_ptr<TestQuicSpdyClientSession> session_;
QuicServerId server_id_;
CryptoHandshakeMessage message_;
std::unique_ptr<QuicCryptoClientConfig> crypto_config_;
std::optional<QuicSSLConfig> ssl_config_;
std::unique_ptr<QuicCryptoServerConfig> server_crypto_config_;
PacketSavingConnection* server_connection_;
std::unique_ptr<TestQuicSpdyServerSession> server_session_;
QuicCompressedCertsCache server_compressed_certs_cache_;
};
INSTANTIATE_TEST_SUITE_P(TlsHandshakerTests, TlsClientHandshakerTest,
::testing::ValuesIn(AllSupportedVersionsWithTls()),
::testing::PrintToStringParamName());
TEST_P(TlsClientHandshakerTest, NotInitiallyConnected) {
EXPECT_FALSE(stream()->encryption_established());
EXPECT_FALSE(stream()->one_rtt_keys_available());
}
TEST_P(TlsClientHandshakerTest, ConnectedAfterHandshake) {
CompleteCryptoHandshake();
EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
EXPECT_TRUE(stream()->encryption_established());
EXPECT_TRUE(stream()->one_rtt_keys_available());
EXPECT_FALSE(stream()->IsResumption());
}
TEST_P(TlsClientHandshakerTest, ConnectionClosedOnTlsError) {
stream()->CryptoConnect();
EXPECT_CALL(*connection_, CloseConnection(QUIC_HANDSHAKE_FAILED, _, _, _));
char bogus_handshake_message[] = {
2,
0, 0, 0,
};
stream()->crypto_message_parser()->ProcessInput(
absl::string_view(bogus_handshake_message,
ABSL_ARRAYSIZE(bogus_handshake_message)),
ENCRYPTION_INITIAL);
EXPECT_FALSE(stream()->one_rtt_keys_available());
}
TEST_P(TlsClientHandshakerTest, ProofVerifyDetailsAvailableAfterHandshake) {
EXPECT_CALL(*session_, OnProofVerifyDetailsAvailable(testing::_));
stream()->CryptoConnect();
QuicConfig config;
crypto_test_utils::HandshakeWithFakeServer(
&config, server_crypto_config_.get(), &server_helper_, &alarm_factory_,
connection_, stream(), AlpnForVersion(connection_->version()));
EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
EXPECT_TRUE(stream()->encryption_established());
EXPECT_TRUE(stream()->one_rtt_keys_available());
}
TEST_P(TlsClientHandshakerTest, HandshakeWithAsyncProofVerifier) {
InitializeFakeServer();
TestProofVerifier* proof_verifier =
static_cast<TestProofVerifier*>(crypto_config_->proof_verifier());
proof_verifier->Activate();
stream()->CryptoConnect();
std::pair<size_t, size_t> moved_message_counts =
crypto_test_utils::AdvanceHandshake(
connection_, stream(), 0, server_connection_, server_stream(), 0);
ASSERT_EQ(proof_verifier->NumPendingCallbacks(), 1u);
proof_verifier->InvokePendingCallback(0);
crypto_test_utils::AdvanceHandshake(
connection_, stream(), moved_message_counts.first, server_connection_,
server_stream(), moved_message_counts.second);
EXPECT_TRUE(stream()->encryption_established());
EXPECT_TRUE(stream()->one_rtt_keys_available());
}
TEST_P(TlsClientHandshakerTest, Resumption) {
SSL_CTX_set_early_data_enabled(server_crypto_config_->ssl_ctx(), false);
CompleteCryptoHandshake();
EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
EXPECT_TRUE(stream()->encryption_established());
EXPECT_TRUE(stream()->one_rtt_keys_available());
EXPECT_FALSE(stream()->ResumptionAttempted());
EXPECT_FALSE(stream()->IsResumption());
CreateConnection();
CompleteCryptoHandshake();
EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
EXPECT_TRUE(stream()->encryption_established());
EXPECT_TRUE(stream()->one_rtt_keys_available());
EXPECT_TRUE(stream()->ResumptionAttempted());
EXPECT_TRUE(stream()->IsResumption());
}
TEST_P(TlsClientHandshakerTest, ResumptionRejection) {
SSL_CTX_set_early_data_enabled(server_crypto_config_->ssl_ctx(), false);
CompleteCryptoHandshake();
EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
EXPECT_TRUE(stream()->encryption_established());
EXPECT_TRUE(stream()->one_rtt_keys_available());
EXPECT_FALSE(stream()->ResumptionAttempted());
EXPECT_FALSE(stream()->IsResumption());
SSL_CTX_set_options(server_crypto_config_->ssl_ctx(), SSL_OP_NO_TICKET);
CreateConnection();
CompleteCryptoHandshake();
EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
EXPECT_TRUE(stream()->encryption_established());
EXPECT_TRUE(stream()->one_rtt_keys_available());
EXPECT_TRUE(stream()->ResumptionAttempted());
EXPECT_FALSE(stream()->IsResumption());
EXPECT_FALSE(stream()->EarlyDataAccepted());
EXPECT_EQ(stream()->EarlyDataReason(),
ssl_early_data_unsupported_for_session);
}
TEST_P(TlsClientHandshakerTest, ZeroRttResumption) {
CompleteCryptoHandshake();
EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
EXPECT_TRUE(stream()->encryption_established());
EXPECT_TRUE(stream()->one_rtt_keys_available());
EXPECT_FALSE(stream()->IsResumption());
CreateConnection();
EXPECT_CALL(*session_, OnConfigNegotiated()).Times(2);
EXPECT_CALL(*connection_, SendCryptoData(_, _, _))
.Times(testing::AnyNumber());
stream()->CryptoConnect();
EXPECT_TRUE(stream()->encryption_established());
EXPECT_NE(stream()->crypto_negotiated_params().cipher_suite, 0);
EXPECT_NE(stream()->crypto_negotiated_params().key_exchange_group, 0);
EXPECT_NE(stream()->crypto_negotiated_params().peer_signature_algorithm, 0);
QuicConfig config;
crypto_test_utils::HandshakeWithFakeServer(
&config, server_crypto_config_.get(), &server_helper_, &alarm_factory_,
connection_, stream(), AlpnForVersion(connection_->version()));
EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
EXPECT_TRUE(stream()->encryption_established());
EXPECT_TRUE(stream()->one_rtt_keys_available());
EXPECT_TRUE(stream()->IsResumption());
EXPECT_TRUE(stream()->EarlyDataAccepted());
EXPECT_EQ(stream()->EarlyDataReason(), ssl_early_data_accepted);
}
TEST_P(TlsClientHandshakerTest, ZeroRttResumptionWithAyncProofVerifier) {
CompleteCryptoHandshake();
EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
EXPECT_TRUE(stream()->encryption_established());
EXPECT_TRUE(stream()->one_rtt_keys_available());
EXPECT_FALSE(stream()->IsResumption());
CreateConnection();
InitializeFakeServer();
EXPECT_CALL(*session_, OnConfigNegotiated());
EXPECT_CALL(*connection_, SendCryptoData(_, _, _))
.Times(testing::AnyNumber());
TestProofVerifier* proof_verifier =
static_cast<TestProofVerifier*>(crypto_config_->proof_verifier());
proof_verifier->Activate();
stream()->CryptoConnect();
ASSERT_EQ(proof_verifier->NumPendingCallbacks(), 1u);
crypto_test_utils::AdvanceHandshake(connection_, stream(), 0,
server_connection_, server_stream(), 0);
EXPECT_FALSE(stream()->one_rtt_keys_available());
EXPECT_FALSE(server_stream()->one_rtt_keys_available());
proof_verifier->InvokePendingCallback(0);
QuicFramer* framer = QuicConnectionPeer::GetFramer(connection_);
EXPECT_NE(nullptr,
QuicFramerPeer::GetEncrypter(framer, ENCRYPTION_HANDSHAKE));
}
TEST_P(TlsClientHandshakerTest, ZeroRttRejection) {
CompleteCryptoHandshake();
EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
EXPECT_TRUE(stream()->encryption_established());
EXPECT_TRUE(stream()->one_rtt_keys_available());
EXPECT_FALSE(stream()->IsResumption());
SSL_CTX_set_early_data_enabled(server_crypto_config_->ssl_ctx(), false);
CreateConnection();
EXPECT_CALL(*session_, OnConfigNegotiated()).Times(2);
EXPECT_CALL(*connection_,
OnPacketSent(ENCRYPTION_INITIAL, NOT_RETRANSMISSION));
if (VersionUsesHttp3(session_->transport_version())) {
EXPECT_CALL(*connection_,
OnPacketSent(ENCRYPTION_ZERO_RTT, NOT_RETRANSMISSION));
}
EXPECT_CALL(*connection_,
OnPacketSent(ENCRYPTION_HANDSHAKE, NOT_RETRANSMISSION));
if (VersionUsesHttp3(session_->transport_version())) {
EXPECT_CALL(*connection_,
OnPacketSent(ENCRYPTION_FORWARD_SECURE, LOSS_RETRANSMISSION));
}
CompleteCryptoHandshake();
QuicFramer* framer = QuicConnectionPeer::GetFramer(connection_);
EXPECT_EQ(nullptr, QuicFramerPeer::GetEncrypter(framer, ENCRYPTION_ZERO_RTT));
EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
EXPECT_TRUE(stream()->encryption_established());
EXPECT_TRUE(stream()->one_rtt_keys_available());
EXPECT_TRUE(stream()->IsResumption());
EXPECT_FALSE(stream()->EarlyDataAccepted());
EXPECT_EQ(stream()->EarlyDataReason(), ssl_early_data_peer_declined);
}
TEST_P(TlsClientHandshakerTest, ZeroRttAndResumptionRejection) {
CompleteCryptoHandshake();
EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
EXPECT_TRUE(stream()->encryption_established());
EXPECT_TRUE(stream()->one_rtt_keys_available());
EXPECT_FALSE(stream()->IsResumption());
SSL_CTX_set_options(server_crypto_config_->ssl_ctx(), SSL_OP_NO_TICKET);
CreateConnection();
EXPECT_CALL(*session_, OnConfigNegotiated()).Times(2);
EXPECT_CALL(*connection_,
OnPacketSent(ENCRYPTION_INITIAL, NOT_RETRANSMISSION));
if (VersionUsesHttp3(session_->transport_version())) {
EXPECT_CALL(*connection_,
OnPacketSent(ENCRYPTION_ZERO_RTT, NOT_RETRANSMISSION));
}
EXPECT_CALL(*connection_,
OnPacketSent(ENCRYPTION_HANDSHAKE, NOT_RETRANSMISSION));
if (VersionUsesHttp3(session_->transport_version())) {
EXPECT_CALL(*connection_,
OnPacketSent(ENCRYPTION_FORWARD_SECURE, LOSS_RETRANSMISSION));
}
CompleteCryptoHandshake();
QuicFramer* framer = QuicConnectionPeer::GetFramer(connection_);
EXPECT_EQ(nullptr, QuicFramerPeer::GetEncrypter(framer, ENCRYPTION_ZERO_RTT));
EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
EXPECT_TRUE(stream()->encryption_established());
EXPECT_TRUE(stream()->one_rtt_keys_available());
EXPECT_FALSE(stream()->IsResumption());
EXPECT_FALSE(stream()->EarlyDataAccepted());
EXPECT_EQ(stream()->EarlyDataReason(), ssl_early_data_session_not_resumed);
}
TEST_P(TlsClientHandshakerTest, ClientSendsNoSNI) {
server_id_ = QuicServerId("", 443);
crypto_config_.reset(new QuicCryptoClientConfig(
std::make_unique<FakeProofVerifier>(), nullptr));
CreateConnection();
InitializeFakeServer();
stream()->CryptoConnect();
crypto_test_utils::CommunicateHandshakeMessages(
connection_, stream(), server_connection_, server_stream());
EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
EXPECT_TRUE(stream()->encryption_established());
EXPECT_TRUE(stream()->one_rtt_keys_available());
EXPECT_EQ(server_stream()->crypto_negotiated_params().sni, "");
}
TEST_P(TlsClientHandshakerTest, ClientSendingTooManyALPNs) {
std::string long_alpn(250, 'A');
EXPECT_QUIC_BUG(
{
EXPECT_CALL(*session_, GetAlpnsToOffer())
.WillOnce(testing::Return(std::vector<std::string>({
long_alpn + "1",
long_alpn + "2",
long_alpn + "3",
long_alpn + "4",
long_alpn + "5",
long_alpn + "6",
long_alpn + "7",
long_alpn + "8",
})));
stream()->CryptoConnect();
},
"Failed to set ALPN");
}
TEST_P(TlsClientHandshakerTest, ServerRequiresCustomALPN) {
InitializeFakeServer();
const std::string kTestAlpn = "An ALPN That Client Did Not Offer";
EXPECT_CALL(*server_session_, SelectAlpn(_))
.WillOnce([kTestAlpn](const std::vector<absl::string_view>& alpns) {
return std::find(alpns.cbegin(), alpns.cend(), kTestAlpn);
});
EXPECT_CALL(
*server_connection_,
CloseConnection(
QUIC_HANDSHAKE_FAILED,
static_cast<QuicIetfTransportErrorCodes>(CRYPTO_ERROR_FIRST + 120),
HasSubstr("TLS handshake failure (ENCRYPTION_INITIAL) 120: "
"no application protocol"),
_));
stream()->CryptoConnect();
crypto_test_utils::AdvanceHandshake(connection_, stream(), 0,
server_connection_, server_stream(), 0);
EXPECT_FALSE(stream()->one_rtt_keys_available());
EXPECT_FALSE(server_stream()->one_rtt_keys_available());
EXPECT_FALSE(stream()->encryption_established());
EXPECT_FALSE(server_stream()->encryption_established());
}
TEST_P(TlsClientHandshakerTest, ZeroRTTNotAttemptedOnALPNChange) {
CompleteCryptoHandshake();
EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
EXPECT_TRUE(stream()->encryption_established());
EXPECT_TRUE(stream()->one_rtt_keys_available());
EXPECT_FALSE(stream()->IsResumption());
CreateConnection();
const std::string kTestAlpn = "Test ALPN";
EXPECT_CALL(*session_, GetAlpnsToOffer())
.WillRepeatedly(testing::Return(std::vector<std::string>({kTestAlpn})));
EXPECT_CALL(*session_, OnConfigNegotiated()).Times(1);
CompleteCryptoHandshakeWithServerALPN(kTestAlpn);
EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
EXPECT_TRUE(stream()->encryption_established());
EXPECT_TRUE(stream()->one_rtt_keys_available());
EXPECT_FALSE(stream()->EarlyDataAccepted());
EXPECT_EQ(stream()->EarlyDataReason(), ssl_early_data_alpn_mismatch);
}
TEST_P(TlsClientHandshakerTest, InvalidSNI) {
server_id_ = QuicServerId("invalid!.example.com", 443);
crypto_config_.reset(new QuicCryptoClientConfig(
std::make_unique<FakeProofVerifier>(), nullptr));
CreateConnection();
InitializeFakeServer();
stream()->CryptoConnect();
crypto_test_utils::CommunicateHandshakeMessages(
connection_, stream(), server_connection_, server_stream());
EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
EXPECT_TRUE(stream()->encryption_established());
EXPECT_TRUE(stream()->one_rtt_keys_available());
EXPECT_EQ(server_stream()->crypto_negotiated_params().sni, "");
}
TEST_P(TlsClientHandshakerTest, BadTransportParams) {
if (!connection_->version().UsesHttp3()) {
return;
}
CompleteCryptoHandshake();
CreateConnection();
stream()->CryptoConnect();
auto* id_manager = QuicSessionPeer::ietf_streamid_manager(session_.get());
EXPECT_EQ(kDefaultMaxStreamsPerConnection,
id_manager->max_outgoing_bidirectional_streams());
QuicConfig config;
config.SetMaxBidirectionalStreamsToSend(
config.GetMaxBidirectionalStreamsToSend() - 1);
EXPECT_CALL(*connection_,
CloseConnection(QUIC_ZERO_RTT_REJECTION_LIMIT_REDUCED, _, _))
.WillOnce(testing::Invoke(connection_,
&MockQuicConnection::ReallyCloseConnection));
EXPECT_CALL(*connection_, CloseConnection(QUIC_HANDSHAKE_FAILED, _, _));
crypto_test_utils::HandshakeWithFakeServer(
&config, server_crypto_config_.get(), &server_helper_, &alarm_factory_,
connection_, stream(), AlpnForVersion(connection_->version()));
}
TEST_P(TlsClientHandshakerTest, ECH) {
ssl_config_.emplace();
bssl::UniquePtr<SSL_ECH_KEYS> ech_keys =
MakeTestEchKeys("public-name.example", 64,
&ssl_config_->ech_config_list);
ASSERT_TRUE(ech_keys);
ASSERT_TRUE(
SSL_CTX_set1_ech_keys(server_crypto_config_->ssl_ctx(), ech_keys.get()));
CreateConnection();
CompleteCryptoHandshake();
EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
EXPECT_TRUE(stream()->encryption_established());
EXPECT_TRUE(stream()->one_rtt_keys_available());
EXPECT_TRUE(stream()->crypto_negotiated_params().encrypted_client_hello);
}
TEST_P(TlsClientHandshakerTest, ECHWithConfigAndGREASE) {
ssl_config_.emplace();
bssl::UniquePtr<SSL_ECH_KEYS> ech_keys =
MakeTestEchKeys("public-name.example", 64,
&ssl_config_->ech_config_list);
ASSERT_TRUE(ech_keys);
ssl_config_->ech_grease_enabled = true;
ASSERT_TRUE(
SSL_CTX_set1_ech_keys(server_crypto_config_->ssl_ctx(), ech_keys.get()));
CreateConnection();
CompleteCryptoHandshake();
EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
EXPECT_TRUE(stream()->encryption_established());
EXPECT_TRUE(stream()->one_rtt_keys_available());
EXPECT_TRUE(stream()->crypto_negotiated_params().encrypted_client_hello);
}
TEST_P(TlsClientHandshakerTest, ECHInvalidConfig) {
ssl_config_.emplace();
ssl_config_->ech_config_list = "invalid config";
CreateConnection();
EXPECT_CALL(*connection_, CloseConnection(QUIC_HANDSHAKE_FAILED, _, _));
stream()->CryptoConnect();
}
TEST_P(TlsClientHandshakerTest, ECHWrongKeys) {
ssl_config_.emplace();
bssl::UniquePtr<SSL_ECH_KEYS> ech_keys1 =
MakeTestEchKeys("public-name.example", 64,
&ssl_config_->ech_config_list);
ASSERT_TRUE(ech_keys1);
std::string ech_config_list2;
bssl::UniquePtr<SSL_ECH_KEYS> ech_keys2 = MakeTestEchKeys(
"public-name.example", 64, &ech_config_list2);
ASSERT_TRUE(ech_keys2);
ASSERT_TRUE(
SSL_CTX_set1_ech_keys(server_crypto_config_->ssl_ctx(), ech_keys2.get()));
CreateConnection();
EXPECT_CALL(*connection_,
CloseConnection(QUIC_HANDSHAKE_FAILED,
static_cast<QuicIetfTransportErrorCodes>(
CRYPTO_ERROR_FIRST + SSL_AD_ECH_REQUIRED),
_, _))
.WillOnce(testing::Invoke(connection_,
&MockQuicConnection::ReallyCloseConnection4));
CompleteCryptoHandshake();
}
TEST_P(TlsClientHandshakerTest, ECHGrease) {
ssl_config_.emplace();
ssl_config_->ech_grease_enabled = true;
CreateConnection();
static bool callback_ran;
callback_ran = false;
SSL_CTX_set_dos_protection_cb(
server_crypto_config_->ssl_ctx(),
[](const SSL_CLIENT_HELLO* client_hello) -> int {
const uint8_t* data;
size_t len;
EXPECT_TRUE(SSL_early_callback_ctx_extension_get(
client_hello, TLSEXT_TYPE_encrypted_client_hello, &data, &len));
callback_ran = true;
return 1;
});
CompleteCryptoHandshake();
EXPECT_TRUE(callback_ran);
EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
EXPECT_TRUE(stream()->encryption_established());
EXPECT_TRUE(stream()->one_rtt_keys_available());
EXPECT_FALSE(stream()->crypto_negotiated_params().encrypted_client_hello);
}
#if BORINGSSL_API_VERSION >= 22
TEST_P(TlsClientHandshakerTest, EnableKyber) {
crypto_config_->set_preferred_groups({SSL_GROUP_X25519_KYBER768_DRAFT00});
server_crypto_config_->set_preferred_groups(
{SSL_GROUP_X25519_KYBER768_DRAFT00, SSL_GROUP_X25519, SSL_GROUP_SECP256R1,
SSL_GROUP_SECP384R1});
CreateConnection();
CompleteCryptoHandshake();
EXPECT_TRUE(stream()->encryption_established());
EXPECT_TRUE(stream()->one_rtt_keys_available());
EXPECT_EQ(SSL_GROUP_X25519_KYBER768_DRAFT00,
SSL_get_group_id(stream()->GetSsl()));
}
#endif
#if BORINGSSL_API_VERSION >= 27
TEST_P(TlsClientHandshakerTest, EnableClientAlpsUseNewCodepoint) {
for (bool server_allow_alps_new_codepoint : {true, false}) {
SCOPED_TRACE(absl::StrCat("Test allows alps new codepoint:",
server_allow_alps_new_codepoint));
crypto_config_->set_alps_use_new_codepoint(true);
SetQuicReloadableFlag(quic_gfe_allow_alps_new_codepoint,
server_allow_alps_new_codepoint);
CreateConnection();
static bool callback_ran;
callback_ran = false;
SSL_CTX_set_dos_protection_cb(
server_crypto_config_->ssl_ctx(),
[](const SSL_CLIENT_HELLO* client_hello) -> int {
const uint8_t* data;
size_t len;
EXPECT_TRUE(SSL_early_callback_ctx_extension_get(
client_hello, TLSEXT_TYPE_application_settings, &data, &len));
callback_ran = true;
return 1;
});
CompleteCryptoHandshake();
EXPECT_EQ(PROTOCOL_TLS1_3, stream()->handshake_protocol());
EXPECT_TRUE(callback_ran);
}
}
#endif
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/tls_client_handshaker.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/tls_client_handshaker_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
496b588b-9d15-443d-9b70-61c9b5967273 | cpp | google/quiche | deterministic_connection_id_generator | quiche/quic/core/deterministic_connection_id_generator.cc | quiche/quic/core/deterministic_connection_id_generator_test.cc | #include "quiche/quic/core/deterministic_connection_id_generator.h"
#include <optional>
#include "quiche/quic/core/quic_utils.h"
#include "quiche/quic/platform/api/quic_bug_tracker.h"
#include "quiche/quic/platform/api/quic_logging.h"
namespace quic {
DeterministicConnectionIdGenerator::DeterministicConnectionIdGenerator(
uint8_t expected_connection_id_length)
: expected_connection_id_length_(expected_connection_id_length) {
if (expected_connection_id_length_ >
kQuicMaxConnectionIdWithLengthPrefixLength) {
QUIC_BUG(quic_bug_465151159_01)
<< "Issuing connection IDs longer than allowed in RFC9000";
}
}
std::optional<QuicConnectionId>
DeterministicConnectionIdGenerator::GenerateNextConnectionId(
const QuicConnectionId& original) {
if (expected_connection_id_length_ == 0) {
return EmptyQuicConnectionId();
}
const uint64_t connection_id_hash64 = QuicUtils::FNV1a_64_Hash(
absl::string_view(original.data(), original.length()));
if (expected_connection_id_length_ <= sizeof(uint64_t)) {
return QuicConnectionId(
reinterpret_cast<const char*>(&connection_id_hash64),
expected_connection_id_length_);
}
char new_connection_id_data[255] = {};
const absl::uint128 connection_id_hash128 = QuicUtils::FNV1a_128_Hash(
absl::string_view(original.data(), original.length()));
static_assert(sizeof(connection_id_hash64) + sizeof(connection_id_hash128) <=
sizeof(new_connection_id_data),
"bad size");
memcpy(new_connection_id_data, &connection_id_hash64,
sizeof(connection_id_hash64));
memcpy(new_connection_id_data + sizeof(connection_id_hash64),
&connection_id_hash128, sizeof(connection_id_hash128));
return QuicConnectionId(new_connection_id_data,
expected_connection_id_length_);
}
std::optional<QuicConnectionId>
DeterministicConnectionIdGenerator::MaybeReplaceConnectionId(
const QuicConnectionId& original, const ParsedQuicVersion& version) {
if (original.length() == expected_connection_id_length_) {
return std::optional<QuicConnectionId>();
}
QUICHE_DCHECK(version.AllowsVariableLengthConnectionIds());
std::optional<QuicConnectionId> new_connection_id =
GenerateNextConnectionId(original);
if (!new_connection_id.has_value()) {
QUIC_BUG(unset_next_connection_id);
return std::nullopt;
}
QUICHE_DCHECK_EQ(
*new_connection_id,
static_cast<QuicConnectionId>(*GenerateNextConnectionId(original)));
QUICHE_DCHECK_EQ(expected_connection_id_length_, new_connection_id->length());
QUIC_DLOG(INFO) << "Replacing incoming connection ID " << original << " with "
<< *new_connection_id;
return new_connection_id;
}
} | #include "quiche/quic/core/deterministic_connection_id_generator.h"
#include <optional>
#include <ostream>
#include <vector>
#include "quiche/quic/platform/api/quic_test.h"
#include "quiche/quic/test_tools/quic_test_utils.h"
namespace quic {
namespace test {
namespace {
struct TestParams {
TestParams(int connection_id_length)
: connection_id_length_(connection_id_length) {}
TestParams() : TestParams(kQuicDefaultConnectionIdLength) {}
friend std::ostream& operator<<(std::ostream& os, const TestParams& p) {
os << "{ connection ID length: " << p.connection_id_length_ << " }";
return os;
}
int connection_id_length_;
};
std::vector<struct TestParams> GetTestParams() {
std::vector<struct TestParams> params;
std::vector<int> connection_id_lengths{7, 8, 9, 16, 20};
for (int connection_id_length : connection_id_lengths) {
params.push_back(TestParams(connection_id_length));
}
return params;
}
class DeterministicConnectionIdGeneratorTest
: public QuicTestWithParam<TestParams> {
public:
DeterministicConnectionIdGeneratorTest()
: connection_id_length_(GetParam().connection_id_length_),
generator_(DeterministicConnectionIdGenerator(connection_id_length_)),
version_(ParsedQuicVersion::RFCv1()) {}
protected:
int connection_id_length_;
DeterministicConnectionIdGenerator generator_;
ParsedQuicVersion version_;
};
INSTANTIATE_TEST_SUITE_P(DeterministicConnectionIdGeneratorTests,
DeterministicConnectionIdGeneratorTest,
::testing::ValuesIn(GetTestParams()));
TEST_P(DeterministicConnectionIdGeneratorTest,
NextConnectionIdIsDeterministic) {
QuicConnectionId connection_id64a = TestConnectionId(33);
QuicConnectionId connection_id64b = TestConnectionId(33);
EXPECT_EQ(connection_id64a, connection_id64b);
EXPECT_EQ(*generator_.GenerateNextConnectionId(connection_id64a),
*generator_.GenerateNextConnectionId(connection_id64b));
QuicConnectionId connection_id72a = TestConnectionIdNineBytesLong(42);
QuicConnectionId connection_id72b = TestConnectionIdNineBytesLong(42);
EXPECT_EQ(connection_id72a, connection_id72b);
EXPECT_EQ(*generator_.GenerateNextConnectionId(connection_id72a),
*generator_.GenerateNextConnectionId(connection_id72b));
}
TEST_P(DeterministicConnectionIdGeneratorTest,
NextConnectionIdLengthIsCorrect) {
const char connection_id_bytes[255] = {};
for (uint8_t i = 0; i < sizeof(connection_id_bytes) - 1; ++i) {
QuicConnectionId connection_id(connection_id_bytes, i);
std::optional<QuicConnectionId> replacement_connection_id =
generator_.GenerateNextConnectionId(connection_id);
ASSERT_TRUE(replacement_connection_id.has_value());
EXPECT_EQ(connection_id_length_, replacement_connection_id->length());
}
}
TEST_P(DeterministicConnectionIdGeneratorTest, NextConnectionIdHasEntropy) {
for (uint64_t i = 0; i < 256; ++i) {
QuicConnectionId connection_id_i = TestConnectionId(i);
std::optional<QuicConnectionId> new_i =
generator_.GenerateNextConnectionId(connection_id_i);
ASSERT_TRUE(new_i.has_value());
EXPECT_NE(connection_id_i, *new_i);
for (uint64_t j = i + 1; j <= 256; ++j) {
QuicConnectionId connection_id_j = TestConnectionId(j);
EXPECT_NE(connection_id_i, connection_id_j);
std::optional<QuicConnectionId> new_j =
generator_.GenerateNextConnectionId(connection_id_j);
ASSERT_TRUE(new_j.has_value());
EXPECT_NE(*new_i, *new_j);
}
}
}
TEST_P(DeterministicConnectionIdGeneratorTest,
OnlyReplaceConnectionIdWithWrongLength) {
const char connection_id_input[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14};
for (int i = 0; i < kQuicMaxConnectionIdWithLengthPrefixLength; i++) {
QuicConnectionId input = QuicConnectionId(connection_id_input, i);
std::optional<QuicConnectionId> output =
generator_.MaybeReplaceConnectionId(input, version_);
if (i == connection_id_length_) {
EXPECT_FALSE(output.has_value());
} else {
ASSERT_TRUE(output.has_value());
EXPECT_EQ(*output, generator_.GenerateNextConnectionId(input));
}
}
}
TEST_P(DeterministicConnectionIdGeneratorTest, ReturnLength) {
EXPECT_EQ(generator_.ConnectionIdLength(0x01), connection_id_length_);
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/deterministic_connection_id_generator.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/deterministic_connection_id_generator_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
502bbc76-326a-4964-b6e3-52d5d77be96a | cpp | google/quiche | quic_datagram_queue | quiche/quic/core/quic_datagram_queue.cc | quiche/quic/core/quic_datagram_queue_test.cc | #include "quiche/quic/core/quic_datagram_queue.h"
#include <algorithm>
#include <memory>
#include <optional>
#include <utility>
#include "absl/types/span.h"
#include "quiche/quic/core/quic_constants.h"
#include "quiche/quic/core/quic_session.h"
#include "quiche/quic/core/quic_time.h"
#include "quiche/quic/core/quic_types.h"
namespace quic {
constexpr float kExpiryInMinRtts = 1.25;
constexpr float kMinPacingWindows = 4;
QuicDatagramQueue::QuicDatagramQueue(QuicSession* session)
: QuicDatagramQueue(session, nullptr) {}
QuicDatagramQueue::QuicDatagramQueue(QuicSession* session,
std::unique_ptr<Observer> observer)
: session_(session),
clock_(session->connection()->clock()),
observer_(std::move(observer)) {}
MessageStatus QuicDatagramQueue::SendOrQueueDatagram(
quiche::QuicheMemSlice datagram) {
if (queue_.empty()) {
MessageResult result = session_->SendMessage(absl::MakeSpan(&datagram, 1),
force_flush_);
if (result.status != MESSAGE_STATUS_BLOCKED) {
if (observer_) {
observer_->OnDatagramProcessed(result.status);
}
return result.status;
}
}
queue_.emplace_back(Datagram{std::move(datagram),
clock_->ApproximateNow() + GetMaxTimeInQueue()});
return MESSAGE_STATUS_BLOCKED;
}
std::optional<MessageStatus> QuicDatagramQueue::TrySendingNextDatagram() {
RemoveExpiredDatagrams();
if (queue_.empty()) {
return std::nullopt;
}
MessageResult result =
session_->SendMessage(absl::MakeSpan(&queue_.front().datagram, 1));
if (result.status != MESSAGE_STATUS_BLOCKED) {
queue_.pop_front();
if (observer_) {
observer_->OnDatagramProcessed(result.status);
}
}
return result.status;
}
size_t QuicDatagramQueue::SendDatagrams() {
size_t num_datagrams = 0;
for (;;) {
std::optional<MessageStatus> status = TrySendingNextDatagram();
if (!status.has_value()) {
break;
}
if (*status == MESSAGE_STATUS_BLOCKED) {
break;
}
num_datagrams++;
}
return num_datagrams;
}
QuicTime::Delta QuicDatagramQueue::GetMaxTimeInQueue() const {
if (!max_time_in_queue_.IsZero()) {
return max_time_in_queue_;
}
const QuicTime::Delta min_rtt =
session_->connection()->sent_packet_manager().GetRttStats()->min_rtt();
return std::max(kExpiryInMinRtts * min_rtt,
kMinPacingWindows * kAlarmGranularity);
}
void QuicDatagramQueue::RemoveExpiredDatagrams() {
QuicTime now = clock_->ApproximateNow();
while (!queue_.empty() && queue_.front().expiry <= now) {
++expired_datagram_count_;
queue_.pop_front();
if (observer_) {
observer_->OnDatagramProcessed(std::nullopt);
}
}
}
} | #include "quiche/quic/core/quic_datagram_queue.h"
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "absl/strings/string_view.h"
#include "quiche/quic/core/crypto/null_encrypter.h"
#include "quiche/quic/core/quic_time.h"
#include "quiche/quic/core/quic_types.h"
#include "quiche/quic/platform/api/quic_test.h"
#include "quiche/quic/test_tools/quic_test_utils.h"
#include "quiche/common/platform/api/quiche_mem_slice.h"
#include "quiche/common/platform/api/quiche_reference_counted.h"
#include "quiche/common/quiche_buffer_allocator.h"
namespace quic {
namespace test {
namespace {
using testing::_;
using testing::ElementsAre;
using testing::Return;
class EstablishedCryptoStream : public MockQuicCryptoStream {
public:
using MockQuicCryptoStream::MockQuicCryptoStream;
bool encryption_established() const override { return true; }
};
class QuicDatagramQueueObserver final : public QuicDatagramQueue::Observer {
public:
class Context : public quiche::QuicheReferenceCounted {
public:
std::vector<std::optional<MessageStatus>> statuses;
};
QuicDatagramQueueObserver() : context_(new Context()) {}
QuicDatagramQueueObserver(const QuicDatagramQueueObserver&) = delete;
QuicDatagramQueueObserver& operator=(const QuicDatagramQueueObserver&) =
delete;
void OnDatagramProcessed(std::optional<MessageStatus> status) override {
context_->statuses.push_back(std::move(status));
}
const quiche::QuicheReferenceCountedPointer<Context>& context() {
return context_;
}
private:
quiche::QuicheReferenceCountedPointer<Context> context_;
};
class QuicDatagramQueueTestBase : public QuicTest {
protected:
QuicDatagramQueueTestBase()
: connection_(new MockQuicConnection(&helper_, &alarm_factory_,
Perspective::IS_CLIENT)),
session_(connection_) {
session_.SetCryptoStream(new EstablishedCryptoStream(&session_));
connection_->SetEncrypter(
ENCRYPTION_FORWARD_SECURE,
std::make_unique<NullEncrypter>(connection_->perspective()));
}
~QuicDatagramQueueTestBase() = default;
quiche::QuicheMemSlice CreateMemSlice(absl::string_view data) {
return quiche::QuicheMemSlice(quiche::QuicheBuffer::Copy(
helper_.GetStreamSendBufferAllocator(), data));
}
MockQuicConnectionHelper helper_;
MockAlarmFactory alarm_factory_;
MockQuicConnection* connection_;
MockQuicSession session_;
};
class QuicDatagramQueueTest : public QuicDatagramQueueTestBase {
public:
QuicDatagramQueueTest() : queue_(&session_) {}
protected:
QuicDatagramQueue queue_;
};
TEST_F(QuicDatagramQueueTest, SendDatagramImmediately) {
EXPECT_CALL(*connection_, SendMessage(_, _, _))
.WillOnce(Return(MESSAGE_STATUS_SUCCESS));
MessageStatus status = queue_.SendOrQueueDatagram(CreateMemSlice("test"));
EXPECT_EQ(MESSAGE_STATUS_SUCCESS, status);
EXPECT_EQ(0u, queue_.queue_size());
}
TEST_F(QuicDatagramQueueTest, SendDatagramAfterBuffering) {
EXPECT_CALL(*connection_, SendMessage(_, _, _))
.WillOnce(Return(MESSAGE_STATUS_BLOCKED));
MessageStatus initial_status =
queue_.SendOrQueueDatagram(CreateMemSlice("test"));
EXPECT_EQ(MESSAGE_STATUS_BLOCKED, initial_status);
EXPECT_EQ(1u, queue_.queue_size());
EXPECT_CALL(*connection_, SendMessage(_, _, _))
.WillOnce(Return(MESSAGE_STATUS_BLOCKED));
std::optional<MessageStatus> status = queue_.TrySendingNextDatagram();
ASSERT_TRUE(status.has_value());
EXPECT_EQ(MESSAGE_STATUS_BLOCKED, *status);
EXPECT_EQ(1u, queue_.queue_size());
EXPECT_CALL(*connection_, SendMessage(_, _, _))
.WillOnce(Return(MESSAGE_STATUS_SUCCESS));
status = queue_.TrySendingNextDatagram();
ASSERT_TRUE(status.has_value());
EXPECT_EQ(MESSAGE_STATUS_SUCCESS, *status);
EXPECT_EQ(0u, queue_.queue_size());
}
TEST_F(QuicDatagramQueueTest, EmptyBuffer) {
std::optional<MessageStatus> status = queue_.TrySendingNextDatagram();
EXPECT_FALSE(status.has_value());
size_t num_messages = queue_.SendDatagrams();
EXPECT_EQ(0u, num_messages);
}
TEST_F(QuicDatagramQueueTest, MultipleDatagrams) {
EXPECT_CALL(*connection_, SendMessage(_, _, _))
.WillOnce(Return(MESSAGE_STATUS_BLOCKED));
queue_.SendOrQueueDatagram(CreateMemSlice("a"));
queue_.SendOrQueueDatagram(CreateMemSlice("b"));
queue_.SendOrQueueDatagram(CreateMemSlice("c"));
queue_.SendOrQueueDatagram(CreateMemSlice("d"));
queue_.SendOrQueueDatagram(CreateMemSlice("e"));
EXPECT_CALL(*connection_, SendMessage(_, _, _))
.Times(5)
.WillRepeatedly(Return(MESSAGE_STATUS_SUCCESS));
size_t num_messages = queue_.SendDatagrams();
EXPECT_EQ(5u, num_messages);
}
TEST_F(QuicDatagramQueueTest, DefaultMaxTimeInQueue) {
EXPECT_EQ(QuicTime::Delta::Zero(),
connection_->sent_packet_manager().GetRttStats()->min_rtt());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(4), queue_.GetMaxTimeInQueue());
RttStats* stats =
const_cast<RttStats*>(connection_->sent_packet_manager().GetRttStats());
stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(100),
QuicTime::Delta::Zero(), helper_.GetClock()->Now());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(125), queue_.GetMaxTimeInQueue());
}
TEST_F(QuicDatagramQueueTest, Expiry) {
constexpr QuicTime::Delta expiry = QuicTime::Delta::FromMilliseconds(100);
queue_.SetMaxTimeInQueue(expiry);
EXPECT_CALL(*connection_, SendMessage(_, _, _))
.WillOnce(Return(MESSAGE_STATUS_BLOCKED));
queue_.SendOrQueueDatagram(CreateMemSlice("a"));
helper_.AdvanceTime(0.6 * expiry);
queue_.SendOrQueueDatagram(CreateMemSlice("b"));
helper_.AdvanceTime(0.6 * expiry);
queue_.SendOrQueueDatagram(CreateMemSlice("c"));
std::vector<std::string> messages;
EXPECT_CALL(*connection_, SendMessage(_, _, _))
.WillRepeatedly([&messages](QuicMessageId ,
absl::Span<quiche::QuicheMemSlice> message,
bool ) {
messages.push_back(std::string(message[0].AsStringView()));
return MESSAGE_STATUS_SUCCESS;
});
EXPECT_EQ(2u, queue_.SendDatagrams());
EXPECT_THAT(messages, ElementsAre("b", "c"));
}
TEST_F(QuicDatagramQueueTest, ExpireAll) {
constexpr QuicTime::Delta expiry = QuicTime::Delta::FromMilliseconds(100);
queue_.SetMaxTimeInQueue(expiry);
EXPECT_CALL(*connection_, SendMessage(_, _, _))
.WillOnce(Return(MESSAGE_STATUS_BLOCKED));
queue_.SendOrQueueDatagram(CreateMemSlice("a"));
queue_.SendOrQueueDatagram(CreateMemSlice("b"));
queue_.SendOrQueueDatagram(CreateMemSlice("c"));
helper_.AdvanceTime(100 * expiry);
EXPECT_CALL(*connection_, SendMessage(_, _, _)).Times(0);
EXPECT_EQ(0u, queue_.SendDatagrams());
}
class QuicDatagramQueueWithObserverTest : public QuicDatagramQueueTestBase {
public:
QuicDatagramQueueWithObserverTest()
: observer_(std::make_unique<QuicDatagramQueueObserver>()),
context_(observer_->context()),
queue_(&session_, std::move(observer_)) {}
protected:
std::unique_ptr<QuicDatagramQueueObserver> observer_;
quiche::QuicheReferenceCountedPointer<QuicDatagramQueueObserver::Context>
context_;
QuicDatagramQueue queue_;
};
TEST_F(QuicDatagramQueueWithObserverTest, ObserveSuccessImmediately) {
EXPECT_TRUE(context_->statuses.empty());
EXPECT_CALL(*connection_, SendMessage(_, _, _))
.WillOnce(Return(MESSAGE_STATUS_SUCCESS));
EXPECT_EQ(MESSAGE_STATUS_SUCCESS,
queue_.SendOrQueueDatagram(CreateMemSlice("a")));
EXPECT_THAT(context_->statuses, ElementsAre(MESSAGE_STATUS_SUCCESS));
}
TEST_F(QuicDatagramQueueWithObserverTest, ObserveFailureImmediately) {
EXPECT_TRUE(context_->statuses.empty());
EXPECT_CALL(*connection_, SendMessage(_, _, _))
.WillOnce(Return(MESSAGE_STATUS_TOO_LARGE));
EXPECT_EQ(MESSAGE_STATUS_TOO_LARGE,
queue_.SendOrQueueDatagram(CreateMemSlice("a")));
EXPECT_THAT(context_->statuses, ElementsAre(MESSAGE_STATUS_TOO_LARGE));
}
TEST_F(QuicDatagramQueueWithObserverTest, BlockingShouldNotBeObserved) {
EXPECT_TRUE(context_->statuses.empty());
EXPECT_CALL(*connection_, SendMessage(_, _, _))
.WillRepeatedly(Return(MESSAGE_STATUS_BLOCKED));
EXPECT_EQ(MESSAGE_STATUS_BLOCKED,
queue_.SendOrQueueDatagram(CreateMemSlice("a")));
EXPECT_EQ(0u, queue_.SendDatagrams());
EXPECT_TRUE(context_->statuses.empty());
}
TEST_F(QuicDatagramQueueWithObserverTest, ObserveSuccessAfterBuffering) {
EXPECT_TRUE(context_->statuses.empty());
EXPECT_CALL(*connection_, SendMessage(_, _, _))
.WillOnce(Return(MESSAGE_STATUS_BLOCKED));
EXPECT_EQ(MESSAGE_STATUS_BLOCKED,
queue_.SendOrQueueDatagram(CreateMemSlice("a")));
EXPECT_TRUE(context_->statuses.empty());
EXPECT_CALL(*connection_, SendMessage(_, _, _))
.WillOnce(Return(MESSAGE_STATUS_SUCCESS));
EXPECT_EQ(1u, queue_.SendDatagrams());
EXPECT_THAT(context_->statuses, ElementsAre(MESSAGE_STATUS_SUCCESS));
}
TEST_F(QuicDatagramQueueWithObserverTest, ObserveExpiry) {
constexpr QuicTime::Delta expiry = QuicTime::Delta::FromMilliseconds(100);
queue_.SetMaxTimeInQueue(expiry);
EXPECT_TRUE(context_->statuses.empty());
EXPECT_CALL(*connection_, SendMessage(_, _, _))
.WillOnce(Return(MESSAGE_STATUS_BLOCKED));
EXPECT_EQ(MESSAGE_STATUS_BLOCKED,
queue_.SendOrQueueDatagram(CreateMemSlice("a")));
EXPECT_TRUE(context_->statuses.empty());
EXPECT_CALL(*connection_, SendMessage(_, _, _)).Times(0);
helper_.AdvanceTime(100 * expiry);
EXPECT_TRUE(context_->statuses.empty());
EXPECT_EQ(0u, queue_.SendDatagrams());
EXPECT_THAT(context_->statuses, ElementsAre(std::nullopt));
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_datagram_queue.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_datagram_queue_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
8a9d037e-3b07-40e2-a833-78cd5a534886 | cpp | google/quiche | quic_error_codes | quiche/quic/core/quic_error_codes.cc | quiche/quic/core/quic_error_codes_test.cc | #include "quiche/quic/core/quic_error_codes.h"
#include <cstdint>
#include <cstring>
#include <ostream>
#include <string>
#include "absl/strings/str_cat.h"
#include "openssl/ssl.h"
#include "quiche/quic/platform/api/quic_logging.h"
namespace quic {
#define RETURN_STRING_LITERAL(x) \
case x: \
return #x;
const char* QuicRstStreamErrorCodeToString(QuicRstStreamErrorCode error) {
switch (error) {
RETURN_STRING_LITERAL(QUIC_STREAM_NO_ERROR);
RETURN_STRING_LITERAL(QUIC_ERROR_PROCESSING_STREAM);
RETURN_STRING_LITERAL(QUIC_MULTIPLE_TERMINATION_OFFSETS);
RETURN_STRING_LITERAL(QUIC_BAD_APPLICATION_PAYLOAD);
RETURN_STRING_LITERAL(QUIC_STREAM_CONNECTION_ERROR);
RETURN_STRING_LITERAL(QUIC_STREAM_PEER_GOING_AWAY);
RETURN_STRING_LITERAL(QUIC_STREAM_CANCELLED);
RETURN_STRING_LITERAL(QUIC_RST_ACKNOWLEDGEMENT);
RETURN_STRING_LITERAL(QUIC_REFUSED_STREAM);
RETURN_STRING_LITERAL(QUIC_INVALID_PROMISE_URL);
RETURN_STRING_LITERAL(QUIC_UNAUTHORIZED_PROMISE_URL);
RETURN_STRING_LITERAL(QUIC_DUPLICATE_PROMISE_URL);
RETURN_STRING_LITERAL(QUIC_PROMISE_VARY_MISMATCH);
RETURN_STRING_LITERAL(QUIC_INVALID_PROMISE_METHOD);
RETURN_STRING_LITERAL(QUIC_PUSH_STREAM_TIMED_OUT);
RETURN_STRING_LITERAL(QUIC_HEADERS_TOO_LARGE);
RETURN_STRING_LITERAL(QUIC_STREAM_TTL_EXPIRED);
RETURN_STRING_LITERAL(QUIC_DATA_AFTER_CLOSE_OFFSET);
RETURN_STRING_LITERAL(QUIC_STREAM_GENERAL_PROTOCOL_ERROR);
RETURN_STRING_LITERAL(QUIC_STREAM_INTERNAL_ERROR);
RETURN_STRING_LITERAL(QUIC_STREAM_STREAM_CREATION_ERROR);
RETURN_STRING_LITERAL(QUIC_STREAM_CLOSED_CRITICAL_STREAM);
RETURN_STRING_LITERAL(QUIC_STREAM_FRAME_UNEXPECTED);
RETURN_STRING_LITERAL(QUIC_STREAM_FRAME_ERROR);
RETURN_STRING_LITERAL(QUIC_STREAM_EXCESSIVE_LOAD);
RETURN_STRING_LITERAL(QUIC_STREAM_ID_ERROR);
RETURN_STRING_LITERAL(QUIC_STREAM_SETTINGS_ERROR);
RETURN_STRING_LITERAL(QUIC_STREAM_MISSING_SETTINGS);
RETURN_STRING_LITERAL(QUIC_STREAM_REQUEST_REJECTED);
RETURN_STRING_LITERAL(QUIC_STREAM_REQUEST_INCOMPLETE);
RETURN_STRING_LITERAL(QUIC_STREAM_CONNECT_ERROR);
RETURN_STRING_LITERAL(QUIC_STREAM_VERSION_FALLBACK);
RETURN_STRING_LITERAL(QUIC_STREAM_DECOMPRESSION_FAILED);
RETURN_STRING_LITERAL(QUIC_STREAM_ENCODER_STREAM_ERROR);
RETURN_STRING_LITERAL(QUIC_STREAM_DECODER_STREAM_ERROR);
RETURN_STRING_LITERAL(QUIC_STREAM_UNKNOWN_APPLICATION_ERROR_CODE);
RETURN_STRING_LITERAL(QUIC_STREAM_WEBTRANSPORT_SESSION_GONE);
RETURN_STRING_LITERAL(
QUIC_STREAM_WEBTRANSPORT_BUFFERED_STREAMS_LIMIT_EXCEEDED);
RETURN_STRING_LITERAL(QUIC_APPLICATION_DONE_WITH_STREAM);
RETURN_STRING_LITERAL(QUIC_STREAM_LAST_ERROR);
}
return "INVALID_RST_STREAM_ERROR_CODE";
}
const char* QuicErrorCodeToString(QuicErrorCode error) {
switch (error) {
RETURN_STRING_LITERAL(QUIC_NO_ERROR);
RETURN_STRING_LITERAL(QUIC_INTERNAL_ERROR);
RETURN_STRING_LITERAL(QUIC_STREAM_DATA_AFTER_TERMINATION);
RETURN_STRING_LITERAL(QUIC_INVALID_PACKET_HEADER);
RETURN_STRING_LITERAL(QUIC_INVALID_FRAME_DATA);
RETURN_STRING_LITERAL(QUIC_MISSING_PAYLOAD);
RETURN_STRING_LITERAL(QUIC_INVALID_FEC_DATA);
RETURN_STRING_LITERAL(QUIC_INVALID_STREAM_DATA);
RETURN_STRING_LITERAL(QUIC_OVERLAPPING_STREAM_DATA);
RETURN_STRING_LITERAL(QUIC_UNENCRYPTED_STREAM_DATA);
RETURN_STRING_LITERAL(QUIC_INVALID_RST_STREAM_DATA);
RETURN_STRING_LITERAL(QUIC_INVALID_CONNECTION_CLOSE_DATA);
RETURN_STRING_LITERAL(QUIC_INVALID_GOAWAY_DATA);
RETURN_STRING_LITERAL(QUIC_INVALID_WINDOW_UPDATE_DATA);
RETURN_STRING_LITERAL(QUIC_INVALID_BLOCKED_DATA);
RETURN_STRING_LITERAL(QUIC_INVALID_STOP_WAITING_DATA);
RETURN_STRING_LITERAL(QUIC_INVALID_PATH_CLOSE_DATA);
RETURN_STRING_LITERAL(QUIC_INVALID_ACK_DATA);
RETURN_STRING_LITERAL(QUIC_INVALID_VERSION_NEGOTIATION_PACKET);
RETURN_STRING_LITERAL(QUIC_INVALID_PUBLIC_RST_PACKET);
RETURN_STRING_LITERAL(QUIC_DECRYPTION_FAILURE);
RETURN_STRING_LITERAL(QUIC_ENCRYPTION_FAILURE);
RETURN_STRING_LITERAL(QUIC_PACKET_TOO_LARGE);
RETURN_STRING_LITERAL(QUIC_PEER_GOING_AWAY);
RETURN_STRING_LITERAL(QUIC_HANDSHAKE_FAILED);
RETURN_STRING_LITERAL(QUIC_HANDSHAKE_FAILED_PACKETS_BUFFERED_TOO_LONG);
RETURN_STRING_LITERAL(QUIC_HANDSHAKE_FAILED_INVALID_HOSTNAME);
RETURN_STRING_LITERAL(QUIC_CRYPTO_TAGS_OUT_OF_ORDER);
RETURN_STRING_LITERAL(QUIC_CRYPTO_TOO_MANY_ENTRIES);
RETURN_STRING_LITERAL(QUIC_CRYPTO_TOO_MANY_REJECTS);
RETURN_STRING_LITERAL(QUIC_CRYPTO_INVALID_VALUE_LENGTH)
RETURN_STRING_LITERAL(QUIC_CRYPTO_MESSAGE_AFTER_HANDSHAKE_COMPLETE);
RETURN_STRING_LITERAL(QUIC_CRYPTO_INTERNAL_ERROR);
RETURN_STRING_LITERAL(QUIC_CRYPTO_VERSION_NOT_SUPPORTED);
RETURN_STRING_LITERAL(QUIC_CRYPTO_NO_SUPPORT);
RETURN_STRING_LITERAL(QUIC_INVALID_CRYPTO_MESSAGE_TYPE);
RETURN_STRING_LITERAL(QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER);
RETURN_STRING_LITERAL(QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND);
RETURN_STRING_LITERAL(QUIC_CRYPTO_MESSAGE_PARAMETER_NO_OVERLAP);
RETURN_STRING_LITERAL(QUIC_CRYPTO_MESSAGE_INDEX_NOT_FOUND);
RETURN_STRING_LITERAL(QUIC_UNSUPPORTED_PROOF_DEMAND);
RETURN_STRING_LITERAL(QUIC_INVALID_STREAM_ID);
RETURN_STRING_LITERAL(QUIC_INVALID_PRIORITY);
RETURN_STRING_LITERAL(QUIC_TOO_MANY_OPEN_STREAMS);
RETURN_STRING_LITERAL(QUIC_PUBLIC_RESET);
RETURN_STRING_LITERAL(QUIC_INVALID_VERSION);
RETURN_STRING_LITERAL(QUIC_PACKET_WRONG_VERSION);
RETURN_STRING_LITERAL(QUIC_INVALID_0RTT_PACKET_NUMBER_OUT_OF_ORDER);
RETURN_STRING_LITERAL(QUIC_INVALID_HEADER_ID);
RETURN_STRING_LITERAL(QUIC_INVALID_NEGOTIATED_VALUE);
RETURN_STRING_LITERAL(QUIC_DECOMPRESSION_FAILURE);
RETURN_STRING_LITERAL(QUIC_NETWORK_IDLE_TIMEOUT);
RETURN_STRING_LITERAL(QUIC_HANDSHAKE_TIMEOUT);
RETURN_STRING_LITERAL(QUIC_ERROR_MIGRATING_ADDRESS);
RETURN_STRING_LITERAL(QUIC_ERROR_MIGRATING_PORT);
RETURN_STRING_LITERAL(QUIC_PACKET_WRITE_ERROR);
RETURN_STRING_LITERAL(QUIC_PACKET_READ_ERROR);
RETURN_STRING_LITERAL(QUIC_EMPTY_STREAM_FRAME_NO_FIN);
RETURN_STRING_LITERAL(QUIC_INVALID_HEADERS_STREAM_DATA);
RETURN_STRING_LITERAL(QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE);
RETURN_STRING_LITERAL(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA);
RETURN_STRING_LITERAL(QUIC_FLOW_CONTROL_SENT_TOO_MUCH_DATA);
RETURN_STRING_LITERAL(QUIC_FLOW_CONTROL_INVALID_WINDOW);
RETURN_STRING_LITERAL(QUIC_CONNECTION_IP_POOLED);
RETURN_STRING_LITERAL(QUIC_PROOF_INVALID);
RETURN_STRING_LITERAL(QUIC_CRYPTO_DUPLICATE_TAG);
RETURN_STRING_LITERAL(QUIC_CRYPTO_ENCRYPTION_LEVEL_INCORRECT);
RETURN_STRING_LITERAL(QUIC_CRYPTO_SERVER_CONFIG_EXPIRED);
RETURN_STRING_LITERAL(QUIC_INVALID_CHANNEL_ID_SIGNATURE);
RETURN_STRING_LITERAL(QUIC_CRYPTO_SYMMETRIC_KEY_SETUP_FAILED);
RETURN_STRING_LITERAL(QUIC_CRYPTO_MESSAGE_WHILE_VALIDATING_CLIENT_HELLO);
RETURN_STRING_LITERAL(QUIC_CRYPTO_UPDATE_BEFORE_HANDSHAKE_COMPLETE);
RETURN_STRING_LITERAL(QUIC_VERSION_NEGOTIATION_MISMATCH);
RETURN_STRING_LITERAL(QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS);
RETURN_STRING_LITERAL(QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS);
RETURN_STRING_LITERAL(QUIC_CONNECTION_CANCELLED);
RETURN_STRING_LITERAL(QUIC_BAD_PACKET_LOSS_RATE);
RETURN_STRING_LITERAL(QUIC_PUBLIC_RESETS_POST_HANDSHAKE);
RETURN_STRING_LITERAL(QUIC_FAILED_TO_SERIALIZE_PACKET);
RETURN_STRING_LITERAL(QUIC_TOO_MANY_AVAILABLE_STREAMS);
RETURN_STRING_LITERAL(QUIC_UNENCRYPTED_FEC_DATA);
RETURN_STRING_LITERAL(QUIC_BAD_MULTIPATH_FLAG);
RETURN_STRING_LITERAL(QUIC_IP_ADDRESS_CHANGED);
RETURN_STRING_LITERAL(QUIC_CONNECTION_MIGRATION_NO_MIGRATABLE_STREAMS);
RETURN_STRING_LITERAL(QUIC_CONNECTION_MIGRATION_TOO_MANY_CHANGES);
RETURN_STRING_LITERAL(QUIC_CONNECTION_MIGRATION_NO_NEW_NETWORK);
RETURN_STRING_LITERAL(QUIC_CONNECTION_MIGRATION_NON_MIGRATABLE_STREAM);
RETURN_STRING_LITERAL(QUIC_TOO_MANY_RTOS);
RETURN_STRING_LITERAL(QUIC_ATTEMPT_TO_SEND_UNENCRYPTED_STREAM_DATA);
RETURN_STRING_LITERAL(QUIC_MAYBE_CORRUPTED_MEMORY);
RETURN_STRING_LITERAL(QUIC_CRYPTO_CHLO_TOO_LARGE);
RETURN_STRING_LITERAL(QUIC_MULTIPATH_PATH_DOES_NOT_EXIST);
RETURN_STRING_LITERAL(QUIC_MULTIPATH_PATH_NOT_ACTIVE);
RETURN_STRING_LITERAL(QUIC_TOO_MANY_STREAM_DATA_INTERVALS);
RETURN_STRING_LITERAL(QUIC_STREAM_SEQUENCER_INVALID_STATE);
RETURN_STRING_LITERAL(QUIC_TOO_MANY_SESSIONS_ON_SERVER);
RETURN_STRING_LITERAL(QUIC_STREAM_LENGTH_OVERFLOW);
RETURN_STRING_LITERAL(QUIC_CONNECTION_MIGRATION_DISABLED_BY_CONFIG);
RETURN_STRING_LITERAL(QUIC_CONNECTION_MIGRATION_INTERNAL_ERROR);
RETURN_STRING_LITERAL(QUIC_INVALID_MAX_DATA_FRAME_DATA);
RETURN_STRING_LITERAL(QUIC_INVALID_MAX_STREAM_DATA_FRAME_DATA);
RETURN_STRING_LITERAL(QUIC_INVALID_STREAM_BLOCKED_DATA);
RETURN_STRING_LITERAL(QUIC_MAX_STREAMS_DATA);
RETURN_STRING_LITERAL(QUIC_STREAMS_BLOCKED_DATA);
RETURN_STRING_LITERAL(QUIC_INVALID_NEW_CONNECTION_ID_DATA);
RETURN_STRING_LITERAL(QUIC_INVALID_RETIRE_CONNECTION_ID_DATA);
RETURN_STRING_LITERAL(QUIC_CONNECTION_ID_LIMIT_ERROR);
RETURN_STRING_LITERAL(QUIC_TOO_MANY_CONNECTION_ID_WAITING_TO_RETIRE);
RETURN_STRING_LITERAL(QUIC_INVALID_STOP_SENDING_FRAME_DATA);
RETURN_STRING_LITERAL(QUIC_INVALID_PATH_CHALLENGE_DATA);
RETURN_STRING_LITERAL(QUIC_INVALID_PATH_RESPONSE_DATA);
RETURN_STRING_LITERAL(QUIC_CONNECTION_MIGRATION_HANDSHAKE_UNCONFIRMED);
RETURN_STRING_LITERAL(QUIC_PEER_PORT_CHANGE_HANDSHAKE_UNCONFIRMED);
RETURN_STRING_LITERAL(QUIC_INVALID_MESSAGE_DATA);
RETURN_STRING_LITERAL(IETF_QUIC_PROTOCOL_VIOLATION);
RETURN_STRING_LITERAL(QUIC_INVALID_NEW_TOKEN);
RETURN_STRING_LITERAL(QUIC_DATA_RECEIVED_ON_WRITE_UNIDIRECTIONAL_STREAM);
RETURN_STRING_LITERAL(QUIC_TRY_TO_WRITE_DATA_ON_READ_UNIDIRECTIONAL_STREAM);
RETURN_STRING_LITERAL(QUIC_STREAMS_BLOCKED_ERROR);
RETURN_STRING_LITERAL(QUIC_MAX_STREAMS_ERROR);
RETURN_STRING_LITERAL(QUIC_HTTP_DECODER_ERROR);
RETURN_STRING_LITERAL(QUIC_STALE_CONNECTION_CANCELLED);
RETURN_STRING_LITERAL(QUIC_IETF_GQUIC_ERROR_MISSING);
RETURN_STRING_LITERAL(
QUIC_WINDOW_UPDATE_RECEIVED_ON_READ_UNIDIRECTIONAL_STREAM);
RETURN_STRING_LITERAL(QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES);
RETURN_STRING_LITERAL(QUIC_TRANSPORT_INVALID_CLIENT_INDICATION);
RETURN_STRING_LITERAL(QUIC_QPACK_DECOMPRESSION_FAILED);
RETURN_STRING_LITERAL(QUIC_QPACK_ENCODER_STREAM_ERROR);
RETURN_STRING_LITERAL(QUIC_QPACK_DECODER_STREAM_ERROR);
RETURN_STRING_LITERAL(QUIC_QPACK_ENCODER_STREAM_INTEGER_TOO_LARGE);
RETURN_STRING_LITERAL(QUIC_QPACK_ENCODER_STREAM_STRING_LITERAL_TOO_LONG);
RETURN_STRING_LITERAL(QUIC_QPACK_ENCODER_STREAM_HUFFMAN_ENCODING_ERROR);
RETURN_STRING_LITERAL(QUIC_QPACK_ENCODER_STREAM_INVALID_STATIC_ENTRY);
RETURN_STRING_LITERAL(QUIC_QPACK_ENCODER_STREAM_ERROR_INSERTING_STATIC);
RETURN_STRING_LITERAL(
QUIC_QPACK_ENCODER_STREAM_INSERTION_INVALID_RELATIVE_INDEX);
RETURN_STRING_LITERAL(
QUIC_QPACK_ENCODER_STREAM_INSERTION_DYNAMIC_ENTRY_NOT_FOUND);
RETURN_STRING_LITERAL(QUIC_QPACK_ENCODER_STREAM_ERROR_INSERTING_DYNAMIC);
RETURN_STRING_LITERAL(QUIC_QPACK_ENCODER_STREAM_ERROR_INSERTING_LITERAL);
RETURN_STRING_LITERAL(
QUIC_QPACK_ENCODER_STREAM_DUPLICATE_INVALID_RELATIVE_INDEX);
RETURN_STRING_LITERAL(
QUIC_QPACK_ENCODER_STREAM_DUPLICATE_DYNAMIC_ENTRY_NOT_FOUND);
RETURN_STRING_LITERAL(QUIC_QPACK_ENCODER_STREAM_SET_DYNAMIC_TABLE_CAPACITY);
RETURN_STRING_LITERAL(QUIC_QPACK_DECODER_STREAM_INTEGER_TOO_LARGE);
RETURN_STRING_LITERAL(QUIC_QPACK_DECODER_STREAM_INVALID_ZERO_INCREMENT);
RETURN_STRING_LITERAL(QUIC_QPACK_DECODER_STREAM_INCREMENT_OVERFLOW);
RETURN_STRING_LITERAL(QUIC_QPACK_DECODER_STREAM_IMPOSSIBLE_INSERT_COUNT);
RETURN_STRING_LITERAL(QUIC_QPACK_DECODER_STREAM_INCORRECT_ACKNOWLEDGEMENT);
RETURN_STRING_LITERAL(QUIC_STREAM_DATA_BEYOND_CLOSE_OFFSET);
RETURN_STRING_LITERAL(QUIC_STREAM_MULTIPLE_OFFSET);
RETURN_STRING_LITERAL(QUIC_HTTP_FRAME_TOO_LARGE);
RETURN_STRING_LITERAL(QUIC_HTTP_FRAME_ERROR);
RETURN_STRING_LITERAL(QUIC_HTTP_FRAME_UNEXPECTED_ON_SPDY_STREAM);
RETURN_STRING_LITERAL(QUIC_HTTP_FRAME_UNEXPECTED_ON_CONTROL_STREAM);
RETURN_STRING_LITERAL(QUIC_HTTP_INVALID_FRAME_SEQUENCE_ON_SPDY_STREAM);
RETURN_STRING_LITERAL(QUIC_HTTP_INVALID_FRAME_SEQUENCE_ON_CONTROL_STREAM);
RETURN_STRING_LITERAL(QUIC_HTTP_DUPLICATE_UNIDIRECTIONAL_STREAM);
RETURN_STRING_LITERAL(QUIC_HTTP_SERVER_INITIATED_BIDIRECTIONAL_STREAM);
RETURN_STRING_LITERAL(QUIC_HTTP_STREAM_WRONG_DIRECTION);
RETURN_STRING_LITERAL(QUIC_HTTP_CLOSED_CRITICAL_STREAM);
RETURN_STRING_LITERAL(QUIC_HTTP_MISSING_SETTINGS_FRAME);
RETURN_STRING_LITERAL(QUIC_HTTP_DUPLICATE_SETTING_IDENTIFIER);
RETURN_STRING_LITERAL(QUIC_HTTP_INVALID_MAX_PUSH_ID);
RETURN_STRING_LITERAL(QUIC_HTTP_STREAM_LIMIT_TOO_LOW);
RETURN_STRING_LITERAL(QUIC_HTTP_ZERO_RTT_RESUMPTION_SETTINGS_MISMATCH);
RETURN_STRING_LITERAL(QUIC_HTTP_ZERO_RTT_REJECTION_SETTINGS_MISMATCH);
RETURN_STRING_LITERAL(QUIC_HTTP_GOAWAY_INVALID_STREAM_ID);
RETURN_STRING_LITERAL(QUIC_HTTP_GOAWAY_ID_LARGER_THAN_PREVIOUS);
RETURN_STRING_LITERAL(QUIC_HTTP_RECEIVE_SPDY_SETTING);
RETURN_STRING_LITERAL(QUIC_HTTP_RECEIVE_SPDY_FRAME);
RETURN_STRING_LITERAL(QUIC_HTTP_RECEIVE_SERVER_PUSH);
RETURN_STRING_LITERAL(QUIC_HTTP_INVALID_SETTING_VALUE);
RETURN_STRING_LITERAL(QUIC_HPACK_INDEX_VARINT_ERROR);
RETURN_STRING_LITERAL(QUIC_HPACK_NAME_LENGTH_VARINT_ERROR);
RETURN_STRING_LITERAL(QUIC_HPACK_VALUE_LENGTH_VARINT_ERROR);
RETURN_STRING_LITERAL(QUIC_HPACK_NAME_TOO_LONG);
RETURN_STRING_LITERAL(QUIC_HPACK_VALUE_TOO_LONG);
RETURN_STRING_LITERAL(QUIC_HPACK_NAME_HUFFMAN_ERROR);
RETURN_STRING_LITERAL(QUIC_HPACK_VALUE_HUFFMAN_ERROR);
RETURN_STRING_LITERAL(QUIC_HPACK_MISSING_DYNAMIC_TABLE_SIZE_UPDATE);
RETURN_STRING_LITERAL(QUIC_HPACK_INVALID_INDEX);
RETURN_STRING_LITERAL(QUIC_HPACK_INVALID_NAME_INDEX);
RETURN_STRING_LITERAL(QUIC_HPACK_DYNAMIC_TABLE_SIZE_UPDATE_NOT_ALLOWED);
RETURN_STRING_LITERAL(
QUIC_HPACK_INITIAL_TABLE_SIZE_UPDATE_IS_ABOVE_LOW_WATER_MARK);
RETURN_STRING_LITERAL(
QUIC_HPACK_TABLE_SIZE_UPDATE_IS_ABOVE_ACKNOWLEDGED_SETTING);
RETURN_STRING_LITERAL(QUIC_HPACK_TRUNCATED_BLOCK);
RETURN_STRING_LITERAL(QUIC_HPACK_FRAGMENT_TOO_LONG);
RETURN_STRING_LITERAL(QUIC_HPACK_COMPRESSED_HEADER_SIZE_EXCEEDS_LIMIT);
RETURN_STRING_LITERAL(QUIC_ZERO_RTT_UNRETRANSMITTABLE);
RETURN_STRING_LITERAL(QUIC_ZERO_RTT_REJECTION_LIMIT_REDUCED);
RETURN_STRING_LITERAL(QUIC_ZERO_RTT_RESUMPTION_LIMIT_REDUCED);
RETURN_STRING_LITERAL(QUIC_SILENT_IDLE_TIMEOUT);
RETURN_STRING_LITERAL(QUIC_MISSING_WRITE_KEYS);
RETURN_STRING_LITERAL(QUIC_KEY_UPDATE_ERROR);
RETURN_STRING_LITERAL(QUIC_AEAD_LIMIT_REACHED);
RETURN_STRING_LITERAL(QUIC_MAX_AGE_TIMEOUT);
RETURN_STRING_LITERAL(QUIC_INVALID_PRIORITY_UPDATE);
RETURN_STRING_LITERAL(QUIC_TLS_BAD_CERTIFICATE);
RETURN_STRING_LITERAL(QUIC_TLS_UNSUPPORTED_CERTIFICATE);
RETURN_STRING_LITERAL(QUIC_TLS_CERTIFICATE_REVOKED);
RETURN_STRING_LITERAL(QUIC_TLS_CERTIFICATE_EXPIRED);
RETURN_STRING_LITERAL(QUIC_TLS_CERTIFICATE_UNKNOWN);
RETURN_STRING_LITERAL(QUIC_TLS_INTERNAL_ERROR);
RETURN_STRING_LITERAL(QUIC_TLS_UNRECOGNIZED_NAME);
RETURN_STRING_LITERAL(QUIC_TLS_CERTIFICATE_REQUIRED);
RETURN_STRING_LITERAL(QUIC_INVALID_CHARACTER_IN_FIELD_VALUE);
RETURN_STRING_LITERAL(QUIC_TLS_UNEXPECTED_KEYING_MATERIAL_EXPORT_LABEL);
RETURN_STRING_LITERAL(QUIC_TLS_KEYING_MATERIAL_EXPORTS_MISMATCH);
RETURN_STRING_LITERAL(QUIC_TLS_KEYING_MATERIAL_EXPORT_NOT_AVAILABLE);
RETURN_STRING_LITERAL(QUIC_UNEXPECTED_DATA_BEFORE_ENCRYPTION_ESTABLISHED);
RETURN_STRING_LITERAL(QUIC_SERVER_UNHEALTHY);
RETURN_STRING_LITERAL(QUIC_CLIENT_LOST_NETWORK_ACCESS);
RETURN_STRING_LITERAL(QUIC_LAST_ERROR);
}
return "INVALID_ERROR_CODE";
}
std::string QuicIetfTransportErrorCodeString(QuicIetfTransportErrorCodes c) {
if (c >= CRYPTO_ERROR_FIRST && c <= CRYPTO_ERROR_LAST) {
const int tls_error = static_cast<int>(c - CRYPTO_ERROR_FIRST);
const char* tls_error_description = SSL_alert_desc_string_long(tls_error);
if (strcmp("unknown", tls_error_description) != 0) {
return absl::StrCat("CRYPTO_ERROR(", tls_error_description, ")");
}
return absl::StrCat("CRYPTO_ERROR(unknown(", tls_error, "))");
}
switch (c) {
RETURN_STRING_LITERAL(NO_IETF_QUIC_ERROR);
RETURN_STRING_LITERAL(INTERNAL_ERROR);
RETURN_STRING_LITERAL(SERVER_BUSY_ERROR);
RETURN_STRING_LITERAL(FLOW_CONTROL_ERROR);
RETURN_STRING_LITERAL(STREAM_LIMIT_ERROR);
RETURN_STRING_LITERAL(STREAM_STATE_ERROR);
RETURN_STRING_LITERAL(FINAL_SIZE_ERROR);
RETURN_STRING_LITERAL(FRAME_ENCODING_ERROR);
RETURN_STRING_LITERAL(TRANSPORT_PARAMETER_ERROR);
RETURN_STRING_LITERAL(CONNECTION_ID_LIMIT_ERROR);
RETURN_STRING_LITERAL(PROTOCOL_VIOLATION);
RETURN_STRING_LITERAL(INVALID_TOKEN);
RETURN_STRING_LITERAL(CRYPTO_BUFFER_EXCEEDED);
RETURN_STRING_LITERAL(KEY_UPDATE_ERROR);
RETURN_STRING_LITERAL(AEAD_LIMIT_REACHED);
case CRYPTO_ERROR_FIRST:
case CRYPTO_ERROR_LAST:
QUICHE_DCHECK(false) << "Unexpected error " << static_cast<uint64_t>(c);
break;
}
return absl::StrCat("Unknown(", static_cast<uint64_t>(c), ")");
}
std::ostream& operator<<(std::ostream& os,
const QuicIetfTransportErrorCodes& c) {
os << QuicIetfTransportErrorCodeString(c);
return os;
}
QuicErrorCodeToIetfMapping QuicErrorCodeToTransportErrorCode(
QuicErrorCode error) {
switch (error) {
case QUIC_NO_ERROR:
return {true, static_cast<uint64_t>(NO_IETF_QUIC_ERROR)};
case QUIC_INTERNAL_ERROR:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_STREAM_DATA_AFTER_TERMINATION:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_INVALID_PACKET_HEADER:
return {true, static_cast<uint64_t>(FRAME_ENCODING_ERROR)};
case QUIC_INVALID_FRAME_DATA:
return {true, static_cast<uint64_t>(FRAME_ENCODING_ERROR)};
case QUIC_MISSING_PAYLOAD:
return {true, static_cast<uint64_t>(FRAME_ENCODING_ERROR)};
case QUIC_INVALID_FEC_DATA:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_INVALID_STREAM_DATA:
return {true, static_cast<uint64_t>(FRAME_ENCODING_ERROR)};
case QUIC_OVERLAPPING_STREAM_DATA:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_UNENCRYPTED_STREAM_DATA:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_ATTEMPT_TO_SEND_UNENCRYPTED_STREAM_DATA:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_MAYBE_CORRUPTED_MEMORY:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_UNENCRYPTED_FEC_DATA:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_INVALID_RST_STREAM_DATA:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_INVALID_CONNECTION_CLOSE_DATA:
return {true, static_cast<uint64_t>(FRAME_ENCODING_ERROR)};
case QUIC_INVALID_GOAWAY_DATA:
return {true, static_cast<uint64_t>(FRAME_ENCODING_ERROR)};
case QUIC_INVALID_WINDOW_UPDATE_DATA:
return {true, static_cast<uint64_t>(FRAME_ENCODING_ERROR)};
case QUIC_INVALID_BLOCKED_DATA:
return {true, static_cast<uint64_t>(FRAME_ENCODING_ERROR)};
case QUIC_INVALID_STOP_WAITING_DATA:
return {true, static_cast<uint64_t>(FRAME_ENCODING_ERROR)};
case QUIC_INVALID_PATH_CLOSE_DATA:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_INVALID_ACK_DATA:
return {true, static_cast<uint64_t>(FRAME_ENCODING_ERROR)};
case QUIC_INVALID_MESSAGE_DATA:
return {true, static_cast<uint64_t>(FRAME_ENCODING_ERROR)};
case QUIC_INVALID_VERSION_NEGOTIATION_PACKET:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_INVALID_PUBLIC_RST_PACKET:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_DECRYPTION_FAILURE:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_ENCRYPTION_FAILURE:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_PACKET_TOO_LARGE:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_PEER_GOING_AWAY:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_INVALID_STREAM_ID:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_INVALID_PRIORITY:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_TOO_MANY_OPEN_STREAMS:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_TOO_MANY_AVAILABLE_STREAMS:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_PUBLIC_RESET:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_INVALID_VERSION:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_PACKET_WRONG_VERSION:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_INVALID_0RTT_PACKET_NUMBER_OUT_OF_ORDER:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_INVALID_HEADER_ID:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_INVALID_NEGOTIATED_VALUE:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_DECOMPRESSION_FAILURE:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_NETWORK_IDLE_TIMEOUT:
return {true, static_cast<uint64_t>(NO_IETF_QUIC_ERROR)};
case QUIC_SILENT_IDLE_TIMEOUT:
return {true, static_cast<uint64_t>(NO_IETF_QUIC_ERROR)};
case QUIC_HANDSHAKE_TIMEOUT:
return {true, static_cast<uint64_t>(NO_IETF_QUIC_ERROR)};
case QUIC_ERROR_MIGRATING_ADDRESS:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_ERROR_MIGRATING_PORT:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_PACKET_WRITE_ERROR:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_PACKET_READ_ERROR:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_EMPTY_STREAM_FRAME_NO_FIN:
return {true, static_cast<uint64_t>(FRAME_ENCODING_ERROR)};
case QUIC_INVALID_HEADERS_STREAM_DATA:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA:
return {true, static_cast<uint64_t>(FLOW_CONTROL_ERROR)};
case QUIC_FLOW_CONTROL_SENT_TOO_MUCH_DATA:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_FLOW_CONTROL_INVALID_WINDOW:
return {true, static_cast<uint64_t>(FLOW_CONTROL_ERROR)};
case QUIC_CONNECTION_IP_POOLED:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_TOO_MANY_OUTSTANDING_RECEIVED_PACKETS:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_CONNECTION_CANCELLED:
return {true, static_cast<uint64_t>(NO_IETF_QUIC_ERROR)};
case QUIC_BAD_PACKET_LOSS_RATE:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_PUBLIC_RESETS_POST_HANDSHAKE:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_FAILED_TO_SERIALIZE_PACKET:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_TOO_MANY_RTOS:
return {true, static_cast<uint64_t>(NO_IETF_QUIC_ERROR)};
case QUIC_HANDSHAKE_FAILED:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_CRYPTO_TAGS_OUT_OF_ORDER:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_CRYPTO_TOO_MANY_ENTRIES:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_CRYPTO_INVALID_VALUE_LENGTH:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_CRYPTO_MESSAGE_AFTER_HANDSHAKE_COMPLETE:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_INVALID_CRYPTO_MESSAGE_TYPE:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_INVALID_CHANNEL_ID_SIGNATURE:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_CRYPTO_MESSAGE_PARAMETER_NO_OVERLAP:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_CRYPTO_MESSAGE_INDEX_NOT_FOUND:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_UNSUPPORTED_PROOF_DEMAND:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_CRYPTO_INTERNAL_ERROR:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_CRYPTO_VERSION_NOT_SUPPORTED:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_CRYPTO_NO_SUPPORT:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_CRYPTO_TOO_MANY_REJECTS:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_PROOF_INVALID:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_CRYPTO_DUPLICATE_TAG:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_CRYPTO_ENCRYPTION_LEVEL_INCORRECT:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_CRYPTO_SERVER_CONFIG_EXPIRED:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_CRYPTO_SYMMETRIC_KEY_SETUP_FAILED:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_CRYPTO_MESSAGE_WHILE_VALIDATING_CLIENT_HELLO:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_CRYPTO_UPDATE_BEFORE_HANDSHAKE_COMPLETE:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_CRYPTO_CHLO_TOO_LARGE:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_VERSION_NEGOTIATION_MISMATCH:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_BAD_MULTIPATH_FLAG:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_MULTIPATH_PATH_DOES_NOT_EXIST:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_MULTIPATH_PATH_NOT_ACTIVE:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_IP_ADDRESS_CHANGED:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_CONNECTION_MIGRATION_NO_MIGRATABLE_STREAMS:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_CONNECTION_MIGRATION_TOO_MANY_CHANGES:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_CONNECTION_MIGRATION_NO_NEW_NETWORK:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_CONNECTION_MIGRATION_NON_MIGRATABLE_STREAM:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_CONNECTION_MIGRATION_DISABLED_BY_CONFIG:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_CONNECTION_MIGRATION_INTERNAL_ERROR:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_CONNECTION_MIGRATION_HANDSHAKE_UNCONFIRMED:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_PEER_PORT_CHANGE_HANDSHAKE_UNCONFIRMED:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_TOO_MANY_STREAM_DATA_INTERVALS:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_STREAM_SEQUENCER_INVALID_STATE:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_TOO_MANY_SESSIONS_ON_SERVER:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_STREAM_LENGTH_OVERFLOW:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_INVALID_MAX_DATA_FRAME_DATA:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_INVALID_MAX_STREAM_DATA_FRAME_DATA:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_MAX_STREAMS_DATA:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_STREAMS_BLOCKED_DATA:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_INVALID_STREAM_BLOCKED_DATA:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_INVALID_NEW_CONNECTION_ID_DATA:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_INVALID_STOP_SENDING_FRAME_DATA:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_INVALID_PATH_CHALLENGE_DATA:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_INVALID_PATH_RESPONSE_DATA:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case IETF_QUIC_PROTOCOL_VIOLATION:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_INVALID_NEW_TOKEN:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_DATA_RECEIVED_ON_WRITE_UNIDIRECTIONAL_STREAM:
return {true, static_cast<uint64_t>(STREAM_STATE_ERROR)};
case QUIC_TRY_TO_WRITE_DATA_ON_READ_UNIDIRECTIONAL_STREAM:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_INVALID_RETIRE_CONNECTION_ID_DATA:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_STREAMS_BLOCKED_ERROR:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_MAX_STREAMS_ERROR:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_HTTP_DECODER_ERROR:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_STALE_CONNECTION_CANCELLED:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_IETF_GQUIC_ERROR_MISSING:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_WINDOW_UPDATE_RECEIVED_ON_READ_UNIDIRECTIONAL_STREAM:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_TRANSPORT_INVALID_CLIENT_INDICATION:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_QPACK_DECOMPRESSION_FAILED:
return {false, static_cast<uint64_t>(
QuicHttpQpackErrorCode::DECOMPRESSION_FAILED)};
case QUIC_QPACK_ENCODER_STREAM_ERROR:
return {false, static_cast<uint64_t>(
QuicHttpQpackErrorCode::ENCODER_STREAM_ERROR)};
case QUIC_QPACK_DECODER_STREAM_ERROR:
return {false, static_cast<uint64_t>(
QuicHttpQpackErrorCode::DECODER_STREAM_ERROR)};
case QUIC_QPACK_ENCODER_STREAM_INTEGER_TOO_LARGE:
return {false, static_cast<uint64_t>(
QuicHttpQpackErrorCode::ENCODER_STREAM_ERROR)};
case QUIC_QPACK_ENCODER_STREAM_STRING_LITERAL_TOO_LONG:
return {false, static_cast<uint64_t>(
QuicHttpQpackErrorCode::ENCODER_STREAM_ERROR)};
case QUIC_QPACK_ENCODER_STREAM_HUFFMAN_ENCODING_ERROR:
return {false, static_cast<uint64_t>(
QuicHttpQpackErrorCode::ENCODER_STREAM_ERROR)};
case QUIC_QPACK_ENCODER_STREAM_INVALID_STATIC_ENTRY:
return {false, static_cast<uint64_t>(
QuicHttpQpackErrorCode::ENCODER_STREAM_ERROR)};
case QUIC_QPACK_ENCODER_STREAM_ERROR_INSERTING_STATIC:
return {false, static_cast<uint64_t>(
QuicHttpQpackErrorCode::ENCODER_STREAM_ERROR)};
case QUIC_QPACK_ENCODER_STREAM_INSERTION_INVALID_RELATIVE_INDEX:
return {false, static_cast<uint64_t>(
QuicHttpQpackErrorCode::ENCODER_STREAM_ERROR)};
case QUIC_QPACK_ENCODER_STREAM_INSERTION_DYNAMIC_ENTRY_NOT_FOUND:
return {false, static_cast<uint64_t>(
QuicHttpQpackErrorCode::ENCODER_STREAM_ERROR)};
case QUIC_QPACK_ENCODER_STREAM_ERROR_INSERTING_DYNAMIC:
return {false, static_cast<uint64_t>(
QuicHttpQpackErrorCode::ENCODER_STREAM_ERROR)};
case QUIC_QPACK_ENCODER_STREAM_ERROR_INSERTING_LITERAL:
return {false, static_cast<uint64_t>(
QuicHttpQpackErrorCode::ENCODER_STREAM_ERROR)};
case QUIC_QPACK_ENCODER_STREAM_DUPLICATE_INVALID_RELATIVE_INDEX:
return {false, static_cast<uint64_t>(
QuicHttpQpackErrorCode::ENCODER_STREAM_ERROR)};
case QUIC_QPACK_ENCODER_STREAM_DUPLICATE_DYNAMIC_ENTRY_NOT_FOUND:
return {false, static_cast<uint64_t>(
QuicHttpQpackErrorCode::ENCODER_STREAM_ERROR)};
case QUIC_QPACK_ENCODER_STREAM_SET_DYNAMIC_TABLE_CAPACITY:
return {false, static_cast<uint64_t>(
QuicHttpQpackErrorCode::ENCODER_STREAM_ERROR)};
case QUIC_QPACK_DECODER_STREAM_INTEGER_TOO_LARGE:
return {false, static_cast<uint64_t>(
QuicHttpQpackErrorCode::DECODER_STREAM_ERROR)};
case QUIC_QPACK_DECODER_STREAM_INVALID_ZERO_INCREMENT:
return {false, static_cast<uint64_t>(
QuicHttpQpackErrorCode::DECODER_STREAM_ERROR)};
case QUIC_QPACK_DECODER_STREAM_INCREMENT_OVERFLOW:
return {false, static_cast<uint64_t>(
QuicHttpQpackErrorCode::DECODER_STREAM_ERROR)};
case QUIC_QPACK_DECODER_STREAM_IMPOSSIBLE_INSERT_COUNT:
return {false, static_cast<uint64_t>(
QuicHttpQpackErrorCode::DECODER_STREAM_ERROR)};
case QUIC_QPACK_DECODER_STREAM_INCORRECT_ACKNOWLEDGEMENT:
return {false, static_cast<uint64_t>(
QuicHttpQpackErrorCode::DECODER_STREAM_ERROR)};
case QUIC_STREAM_DATA_BEYOND_CLOSE_OFFSET:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_STREAM_MULTIPLE_OFFSET:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_HTTP_FRAME_TOO_LARGE:
return {false, static_cast<uint64_t>(QuicHttp3ErrorCode::EXCESSIVE_LOAD)};
case QUIC_HTTP_FRAME_ERROR:
return {false, static_cast<uint64_t>(QuicHttp3ErrorCode::FRAME_ERROR)};
case QUIC_HTTP_FRAME_UNEXPECTED_ON_SPDY_STREAM:
return {false,
static_cast<uint64_t>(QuicHttp3ErrorCode::FRAME_UNEXPECTED)};
case QUIC_HTTP_FRAME_UNEXPECTED_ON_CONTROL_STREAM:
return {false,
static_cast<uint64_t>(QuicHttp3ErrorCode::FRAME_UNEXPECTED)};
case QUIC_HTTP_INVALID_FRAME_SEQUENCE_ON_SPDY_STREAM:
return {false,
static_cast<uint64_t>(QuicHttp3ErrorCode::FRAME_UNEXPECTED)};
case QUIC_HTTP_INVALID_FRAME_SEQUENCE_ON_CONTROL_STREAM:
return {false,
static_cast<uint64_t>(QuicHttp3ErrorCode::FRAME_UNEXPECTED)};
case QUIC_HTTP_DUPLICATE_UNIDIRECTIONAL_STREAM:
return {false,
static_cast<uint64_t>(QuicHttp3ErrorCode::STREAM_CREATION_ERROR)};
case QUIC_HTTP_SERVER_INITIATED_BIDIRECTIONAL_STREAM:
return {false,
static_cast<uint64_t>(QuicHttp3ErrorCode::STREAM_CREATION_ERROR)};
case QUIC_HTTP_STREAM_WRONG_DIRECTION:
return {true, static_cast<uint64_t>(STREAM_STATE_ERROR)};
case QUIC_HTTP_CLOSED_CRITICAL_STREAM:
return {false, static_cast<uint64_t>(
QuicHttp3ErrorCode::CLOSED_CRITICAL_STREAM)};
case QUIC_HTTP_MISSING_SETTINGS_FRAME:
return {false,
static_cast<uint64_t>(QuicHttp3ErrorCode::MISSING_SETTINGS)};
case QUIC_HTTP_DUPLICATE_SETTING_IDENTIFIER:
return {false, static_cast<uint64_t>(QuicHttp3ErrorCode::SETTINGS_ERROR)};
case QUIC_HTTP_INVALID_MAX_PUSH_ID:
return {false, static_cast<uint64_t>(QuicHttp3ErrorCode::ID_ERROR)};
case QUIC_HTTP_STREAM_LIMIT_TOO_LOW:
return {false, static_cast<uint64_t>(
QuicHttp3ErrorCode::GENERAL_PROTOCOL_ERROR)};
case QUIC_HTTP_RECEIVE_SERVER_PUSH:
return {false, static_cast<uint64_t>(
QuicHttp3ErrorCode::GENERAL_PROTOCOL_ERROR)};
case QUIC_HTTP_ZERO_RTT_RESUMPTION_SETTINGS_MISMATCH:
return {false, static_cast<uint64_t>(QuicHttp3ErrorCode::SETTINGS_ERROR)};
case QUIC_HTTP_ZERO_RTT_REJECTION_SETTINGS_MISMATCH:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_HTTP_GOAWAY_INVALID_STREAM_ID:
return {false, static_cast<uint64_t>(QuicHttp3ErrorCode::ID_ERROR)};
case QUIC_HTTP_GOAWAY_ID_LARGER_THAN_PREVIOUS:
return {false, static_cast<uint64_t>(QuicHttp3ErrorCode::ID_ERROR)};
case QUIC_HTTP_RECEIVE_SPDY_SETTING:
return {false, static_cast<uint64_t>(QuicHttp3ErrorCode::SETTINGS_ERROR)};
case QUIC_HTTP_INVALID_SETTING_VALUE:
return {false, static_cast<uint64_t>(QuicHttp3ErrorCode::SETTINGS_ERROR)};
case QUIC_HTTP_RECEIVE_SPDY_FRAME:
return {false,
static_cast<uint64_t>(QuicHttp3ErrorCode::FRAME_UNEXPECTED)};
case QUIC_HPACK_INDEX_VARINT_ERROR:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_HPACK_NAME_LENGTH_VARINT_ERROR:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_HPACK_VALUE_LENGTH_VARINT_ERROR:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_HPACK_NAME_TOO_LONG:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_HPACK_VALUE_TOO_LONG:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_HPACK_NAME_HUFFMAN_ERROR:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_HPACK_VALUE_HUFFMAN_ERROR:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_HPACK_MISSING_DYNAMIC_TABLE_SIZE_UPDATE:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_HPACK_INVALID_INDEX:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_HPACK_INVALID_NAME_INDEX:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_HPACK_DYNAMIC_TABLE_SIZE_UPDATE_NOT_ALLOWED:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_HPACK_INITIAL_TABLE_SIZE_UPDATE_IS_ABOVE_LOW_WATER_MARK:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_HPACK_TABLE_SIZE_UPDATE_IS_ABOVE_ACKNOWLEDGED_SETTING:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_HPACK_TRUNCATED_BLOCK:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_HPACK_FRAGMENT_TOO_LONG:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_HPACK_COMPRESSED_HEADER_SIZE_EXCEEDS_LIMIT:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_ZERO_RTT_UNRETRANSMITTABLE:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_ZERO_RTT_REJECTION_LIMIT_REDUCED:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_ZERO_RTT_RESUMPTION_LIMIT_REDUCED:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_MISSING_WRITE_KEYS:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_KEY_UPDATE_ERROR:
return {true, static_cast<uint64_t>(KEY_UPDATE_ERROR)};
case QUIC_AEAD_LIMIT_REACHED:
return {true, static_cast<uint64_t>(AEAD_LIMIT_REACHED)};
case QUIC_MAX_AGE_TIMEOUT:
return {false, static_cast<uint64_t>(QuicHttp3ErrorCode::INTERNAL_ERROR)};
case QUIC_INVALID_PRIORITY_UPDATE:
return {false, static_cast<uint64_t>(
QuicHttp3ErrorCode::GENERAL_PROTOCOL_ERROR)};
case QUIC_TLS_BAD_CERTIFICATE:
return {true, static_cast<uint64_t>(CRYPTO_ERROR_FIRST +
SSL_AD_BAD_CERTIFICATE)};
case QUIC_TLS_UNSUPPORTED_CERTIFICATE:
return {true, static_cast<uint64_t>(CRYPTO_ERROR_FIRST +
SSL_AD_UNSUPPORTED_CERTIFICATE)};
case QUIC_TLS_CERTIFICATE_REVOKED:
return {true, static_cast<uint64_t>(CRYPTO_ERROR_FIRST +
SSL_AD_CERTIFICATE_REVOKED)};
case QUIC_TLS_CERTIFICATE_EXPIRED:
return {true, static_cast<uint64_t>(CRYPTO_ERROR_FIRST +
SSL_AD_CERTIFICATE_EXPIRED)};
case QUIC_TLS_CERTIFICATE_UNKNOWN:
return {true, static_cast<uint64_t>(CRYPTO_ERROR_FIRST +
SSL_AD_CERTIFICATE_UNKNOWN)};
case QUIC_TLS_INTERNAL_ERROR:
return {true, static_cast<uint64_t>(CRYPTO_ERROR_FIRST +
SSL_AD_INTERNAL_ERROR)};
case QUIC_TLS_UNRECOGNIZED_NAME:
return {true, static_cast<uint64_t>(CRYPTO_ERROR_FIRST +
SSL_AD_UNRECOGNIZED_NAME)};
case QUIC_TLS_CERTIFICATE_REQUIRED:
return {true, static_cast<uint64_t>(CRYPTO_ERROR_FIRST +
SSL_AD_CERTIFICATE_REQUIRED)};
case QUIC_CONNECTION_ID_LIMIT_ERROR:
return {true, static_cast<uint64_t>(CONNECTION_ID_LIMIT_ERROR)};
case QUIC_TOO_MANY_CONNECTION_ID_WAITING_TO_RETIRE:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_INVALID_CHARACTER_IN_FIELD_VALUE:
return {false, static_cast<uint64_t>(QuicHttp3ErrorCode::MESSAGE_ERROR)};
case QUIC_TLS_UNEXPECTED_KEYING_MATERIAL_EXPORT_LABEL:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_TLS_KEYING_MATERIAL_EXPORTS_MISMATCH:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_TLS_KEYING_MATERIAL_EXPORT_NOT_AVAILABLE:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_UNEXPECTED_DATA_BEFORE_ENCRYPTION_ESTABLISHED:
return {true, static_cast<uint64_t>(PROTOCOL_VIOLATION)};
case QUIC_SERVER_UNHEALTHY:
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
case QUIC_HANDSHAKE_FAILED_PACKETS_BUFFERED_TOO_LONG:
return {true, static_cast<uint64_t>(NO_IETF_QUIC_ERROR)};
case QUIC_CLIENT_LOST_NETWORK_ACCESS:
return {true, static_cast<uint64_t>(NO_IETF_QUIC_ERROR)};
case QUIC_HANDSHAKE_FAILED_INVALID_HOSTNAME:
return {true, static_cast<uint64_t>(NO_IETF_QUIC_ERROR)};
case QUIC_LAST_ERROR:
return {false, static_cast<uint64_t>(QUIC_LAST_ERROR)};
}
return {true, static_cast<uint64_t>(INTERNAL_ERROR)};
}
QuicErrorCode TlsAlertToQuicErrorCode(uint8_t desc) {
switch (desc) {
case SSL_AD_BAD_CERTIFICATE:
return QUIC_TLS_BAD_CERTIFICATE;
case SSL_AD_UNSUPPORTED_CERTIFICATE:
return QUIC_TLS_UNSUPPORTED_CERTIFICATE;
case SSL_AD_CERTIFICATE_REVOKED:
return QUIC_TLS_CERTIFICATE_REVOKED;
case SSL_AD_CERTIFICATE_EXPIRED:
return QUIC_TLS_CERTIFICATE_EXPIRED;
case SSL_AD_CERTIFICATE_UNKNOWN:
return QUIC_TLS_CERTIFICATE_UNKNOWN;
case SSL_AD_INTERNAL_ERROR:
return QUIC_TLS_INTERNAL_ERROR;
case SSL_AD_UNRECOGNIZED_NAME:
return QUIC_TLS_UNRECOGNIZED_NAME;
case SSL_AD_CERTIFICATE_REQUIRED:
return QUIC_TLS_CERTIFICATE_REQUIRED;
default:
return QUIC_HANDSHAKE_FAILED;
}
}
uint64_t RstStreamErrorCodeToIetfResetStreamErrorCode(
QuicRstStreamErrorCode rst_stream_error_code) {
switch (rst_stream_error_code) {
case QUIC_STREAM_NO_ERROR:
return static_cast<uint64_t>(QuicHttp3ErrorCode::HTTP3_NO_ERROR);
case QUIC_ERROR_PROCESSING_STREAM:
return static_cast<uint64_t>(QuicHttp3ErrorCode::GENERAL_PROTOCOL_ERROR);
case QUIC_MULTIPLE_TERMINATION_OFFSETS:
return static_cast<uint64_t>(QuicHttp3ErrorCode::GENERAL_PROTOCOL_ERROR);
case QUIC_BAD_APPLICATION_PAYLOAD:
return static_cast<uint64_t>(QuicHttp3ErrorCode::GENERAL_PROTOCOL_ERROR);
case QUIC_STREAM_CONNECTION_ERROR:
return static_cast<uint64_t>(QuicHttp3ErrorCode::INTERNAL_ERROR);
case QUIC_STREAM_PEER_GOING_AWAY:
return static_cast<uint64_t>(QuicHttp3ErrorCode::GENERAL_PROTOCOL_ERROR);
case QUIC_STREAM_CANCELLED:
return static_cast<uint64_t>(QuicHttp3ErrorCode::REQUEST_CANCELLED);
case QUIC_RST_ACKNOWLEDGEMENT:
return static_cast<uint64_t>(QuicHttp3ErrorCode::HTTP3_NO_ERROR);
case QUIC_REFUSED_STREAM:
return static_cast<uint64_t>(QuicHttp3ErrorCode::ID_ERROR);
case QUIC_INVALID_PROMISE_URL:
return static_cast<uint64_t>(QuicHttp3ErrorCode::STREAM_CREATION_ERROR);
case QUIC_UNAUTHORIZED_PROMISE_URL:
return static_cast<uint64_t>(QuicHttp3ErrorCode::STREAM_CREATION_ERROR);
case QUIC_DUPLICATE_PROMISE_URL:
return static_cast<uint64_t>(QuicHttp3ErrorCode::STREAM_CREATION_ERROR);
case QUIC_PROMISE_VARY_MISMATCH:
return static_cast<uint64_t>(QuicHttp3ErrorCode::REQUEST_CANCELLED);
case QUIC_INVALID_PROMISE_METHOD:
return static_cast<uint64_t>(QuicHttp3ErrorCode::STREAM_CREATION_ERROR);
case QUIC_PUSH_STREAM_TIMED_OUT:
return static_cast<uint64_t>(QuicHttp3ErrorCode::REQUEST_CANCELLED);
case QUIC_HEADERS_TOO_LARGE:
return static_cast<uint64_t>(QuicHttp3ErrorCode::EXCESSIVE_LOAD);
case QUIC_STREAM_TTL_EXPIRED:
return static_cast<uint64_t>(QuicHttp3ErrorCode::REQUEST_CANCELLED);
case QUIC_DATA_AFTER_CLOSE_OFFSET:
return static_cast<uint64_t>(QuicHttp3ErrorCode::GENERAL_PROTOCOL_ERROR);
case QUIC_STREAM_GENERAL_PROTOCOL_ERROR:
return static_cast<uint64_t>(QuicHttp3ErrorCode::GENERAL_PROTOCOL_ERROR);
case QUIC_STREAM_INTERNAL_ERROR:
return static_cast<uint64_t>(QuicHttp3ErrorCode::INTERNAL_ERROR);
case QUIC_STREAM_STREAM_CREATION_ERROR:
return static_cast<uint64_t>(QuicHttp3ErrorCode::STREAM_CREATION_ERROR);
case QUIC_STREAM_CLOSED_CRITICAL_STREAM:
return static_cast<uint64_t>(QuicHttp3ErrorCode::CLOSED_CRITICAL_STREAM);
case QUIC_STREAM_FRAME_UNEXPECTED:
return static_cast<uint64_t>(QuicHttp3ErrorCode::FRAME_UNEXPECTED);
case QUIC_STREAM_FRAME_ERROR:
return static_cast<uint64_t>(QuicHttp3ErrorCode::FRAME_ERROR);
case QUIC_STREAM_EXCESSIVE_LOAD:
return static_cast<uint64_t>(QuicHttp3ErrorCode::EXCESSIVE_LOAD);
case QUIC_STREAM_ID_ERROR:
return static_cast<uint64_t>(QuicHttp3ErrorCode::ID_ERROR);
case QUIC_STREAM_SETTINGS_ERROR:
return static_cast<uint64_t>(QuicHttp3ErrorCode::SETTINGS_ERROR);
case QUIC_STREAM_MISSING_SETTINGS:
return static_cast<uint64_t>(QuicHttp3ErrorCode::MISSING_SETTINGS);
case QUIC_STREAM_REQUEST_REJECTED:
return static_cast<uint64_t>(QuicHttp3ErrorCode::REQUEST_REJECTED);
case QUIC_STREAM_REQUEST_INCOMPLETE:
return static_cast<uint64_t>(QuicHttp3ErrorCode::REQUEST_INCOMPLETE);
case QUIC_STREAM_CONNECT_ERROR:
return static_cast<uint64_t>(QuicHttp3ErrorCode::CONNECT_ERROR);
case QUIC_STREAM_VERSION_FALLBACK:
return static_cast<uint64_t>(QuicHttp3ErrorCode::VERSION_FALLBACK);
case QUIC_STREAM_DECOMPRESSION_FAILED:
return static_cast<uint64_t>(
QuicHttpQpackErrorCode::DECOMPRESSION_FAILED);
case QUIC_STREAM_ENCODER_STREAM_ERROR:
return static_cast<uint64_t>(
QuicHttpQpackErrorCode::ENCODER_STREAM_ERROR);
case QUIC_STREAM_DECODER_STREAM_ERROR:
return static_cast<uint64_t>(
QuicHttpQpackErrorCode::DECODER_STREAM_ERROR);
case QUIC_STREAM_UNKNOWN_APPLICATION_ERROR_CODE:
return static_cast<uint64_t>(QuicHttp3ErrorCode::INTERNAL_ERROR);
case QUIC_STREAM_WEBTRANSPORT_SESSION_GONE:
return static_cast<uint64_t>(QuicHttp3ErrorCode::CONNECT_ERROR);
case QUIC_STREAM_WEBTRANSPORT_BUFFERED_STREAMS_LIMIT_EXCEEDED:
return static_cast<uint64_t>(QuicHttp3ErrorCode::CONNECT_ERROR);
case QUIC_APPLICATION_DONE_WITH_STREAM:
return static_cast<uint64_t>(QuicHttp3ErrorCode::GENERAL_PROTOCOL_ERROR);
case QUIC_STREAM_LAST_ERROR:
return static_cast<uint64_t>(QuicHttp3ErrorCode::INTERNAL_ERROR);
}
return static_cast<uint64_t>(QuicHttp3ErrorCode::INTERNAL_ERROR);
}
QuicRstStreamErrorCode IetfResetStreamErrorCodeToRstStreamErrorCode(
uint64_t ietf_error_code) {
switch (ietf_error_code) {
case static_cast<uint64_t>(QuicHttp3ErrorCode::HTTP3_NO_ERROR):
return QUIC_STREAM_NO_ERROR;
case static_cast<uint64_t>(QuicHttp3ErrorCode::GENERAL_PROTOCOL_ERROR):
return QUIC_STREAM_GENERAL_PROTOCOL_ERROR;
case static_cast<uint64_t>(QuicHttp3ErrorCode::INTERNAL_ERROR):
return QUIC_STREAM_INTERNAL_ERROR;
case static_cast<uint64_t>(QuicHttp3ErrorCode::STREAM_CREATION_ERROR):
return QUIC_STREAM_STREAM_CREATION_ERROR;
case static_cast<uint64_t>(QuicHttp3ErrorCode::CLOSED_CRITICAL_STREAM):
return QUIC_STREAM_CLOSED_CRITICAL_STREAM;
case static_cast<uint64_t>(QuicHttp3ErrorCode::FRAME_UNEXPECTED):
return QUIC_STREAM_FRAME_UNEXPECTED;
case static_cast<uint64_t>(QuicHttp3ErrorCode::FRAME_ERROR):
return QUIC_STREAM_FRAME_ERROR;
case static_cast<uint64_t>(QuicHttp3ErrorCode::EXCESSIVE_LOAD):
return QUIC_STREAM_EXCESSIVE_LOAD;
case static_cast<uint64_t>(QuicHttp3ErrorCode::ID_ERROR):
return QUIC_STREAM_ID_ERROR;
case static_cast<uint64_t>(QuicHttp3ErrorCode::SETTINGS_ERROR):
return QUIC_STREAM_SETTINGS_ERROR;
case static_cast<uint64_t>(QuicHttp3ErrorCode::MISSING_SETTINGS):
return QUIC_STREAM_MISSING_SETTINGS;
case static_cast<uint64_t>(QuicHttp3ErrorCode::REQUEST_REJECTED):
return QUIC_STREAM_REQUEST_REJECTED;
case static_cast<uint64_t>(QuicHttp3ErrorCode::REQUEST_CANCELLED):
return QUIC_STREAM_CANCELLED;
case static_cast<uint64_t>(QuicHttp3ErrorCode::REQUEST_INCOMPLETE):
return QUIC_STREAM_REQUEST_INCOMPLETE;
case static_cast<uint64_t>(QuicHttp3ErrorCode::CONNECT_ERROR):
return QUIC_STREAM_CONNECT_ERROR;
case static_cast<uint64_t>(QuicHttp3ErrorCode::VERSION_FALLBACK):
return QUIC_STREAM_VERSION_FALLBACK;
case static_cast<uint64_t>(QuicHttpQpackErrorCode::DECOMPRESSION_FAILED):
return QUIC_STREAM_DECOMPRESSION_FAILED;
case static_cast<uint64_t>(QuicHttpQpackErrorCode::ENCODER_STREAM_ERROR):
return QUIC_STREAM_ENCODER_STREAM_ERROR;
case static_cast<uint64_t>(QuicHttpQpackErrorCode::DECODER_STREAM_ERROR):
return QUIC_STREAM_DECODER_STREAM_ERROR;
}
return QUIC_STREAM_UNKNOWN_APPLICATION_ERROR_CODE;
}
QuicResetStreamError QuicResetStreamError::FromInternal(
QuicRstStreamErrorCode code) {
return QuicResetStreamError(
code, RstStreamErrorCodeToIetfResetStreamErrorCode(code));
}
QuicResetStreamError QuicResetStreamError::FromIetf(uint64_t code) {
return QuicResetStreamError(
IetfResetStreamErrorCodeToRstStreamErrorCode(code), code);
}
QuicResetStreamError QuicResetStreamError::FromIetf(QuicHttp3ErrorCode code) {
return FromIetf(static_cast<uint64_t>(code));
}
QuicResetStreamError QuicResetStreamError::FromIetf(
QuicHttpQpackErrorCode code) {
return FromIetf(static_cast<uint64_t>(code));
}
#undef RETURN_STRING_LITERAL
} | #include "quiche/quic/core/quic_error_codes.h"
#include <cstdint>
#include <string>
#include "openssl/ssl.h"
#include "quiche/quic/platform/api/quic_test.h"
namespace quic {
namespace test {
namespace {
using QuicErrorCodesTest = QuicTest;
TEST_F(QuicErrorCodesTest, QuicErrorCodeToString) {
EXPECT_STREQ("QUIC_NO_ERROR", QuicErrorCodeToString(QUIC_NO_ERROR));
}
TEST_F(QuicErrorCodesTest, QuicIetfTransportErrorCodeString) {
EXPECT_EQ("CRYPTO_ERROR(missing extension)",
QuicIetfTransportErrorCodeString(
static_cast<quic::QuicIetfTransportErrorCodes>(
CRYPTO_ERROR_FIRST + SSL_AD_MISSING_EXTENSION)));
EXPECT_EQ("NO_IETF_QUIC_ERROR",
QuicIetfTransportErrorCodeString(NO_IETF_QUIC_ERROR));
EXPECT_EQ("INTERNAL_ERROR", QuicIetfTransportErrorCodeString(INTERNAL_ERROR));
EXPECT_EQ("SERVER_BUSY_ERROR",
QuicIetfTransportErrorCodeString(SERVER_BUSY_ERROR));
EXPECT_EQ("FLOW_CONTROL_ERROR",
QuicIetfTransportErrorCodeString(FLOW_CONTROL_ERROR));
EXPECT_EQ("STREAM_LIMIT_ERROR",
QuicIetfTransportErrorCodeString(STREAM_LIMIT_ERROR));
EXPECT_EQ("STREAM_STATE_ERROR",
QuicIetfTransportErrorCodeString(STREAM_STATE_ERROR));
EXPECT_EQ("FINAL_SIZE_ERROR",
QuicIetfTransportErrorCodeString(FINAL_SIZE_ERROR));
EXPECT_EQ("FRAME_ENCODING_ERROR",
QuicIetfTransportErrorCodeString(FRAME_ENCODING_ERROR));
EXPECT_EQ("TRANSPORT_PARAMETER_ERROR",
QuicIetfTransportErrorCodeString(TRANSPORT_PARAMETER_ERROR));
EXPECT_EQ("CONNECTION_ID_LIMIT_ERROR",
QuicIetfTransportErrorCodeString(CONNECTION_ID_LIMIT_ERROR));
EXPECT_EQ("PROTOCOL_VIOLATION",
QuicIetfTransportErrorCodeString(PROTOCOL_VIOLATION));
EXPECT_EQ("INVALID_TOKEN", QuicIetfTransportErrorCodeString(INVALID_TOKEN));
EXPECT_EQ("CRYPTO_BUFFER_EXCEEDED",
QuicIetfTransportErrorCodeString(CRYPTO_BUFFER_EXCEEDED));
EXPECT_EQ("KEY_UPDATE_ERROR",
QuicIetfTransportErrorCodeString(KEY_UPDATE_ERROR));
EXPECT_EQ("AEAD_LIMIT_REACHED",
QuicIetfTransportErrorCodeString(AEAD_LIMIT_REACHED));
EXPECT_EQ("Unknown(1024)",
QuicIetfTransportErrorCodeString(
static_cast<quic::QuicIetfTransportErrorCodes>(0x400)));
}
TEST_F(QuicErrorCodesTest, QuicErrorCodeToTransportErrorCode) {
for (uint32_t internal_error_code = 0; internal_error_code < QUIC_LAST_ERROR;
++internal_error_code) {
std::string internal_error_code_string =
QuicErrorCodeToString(static_cast<QuicErrorCode>(internal_error_code));
if (internal_error_code_string == "INVALID_ERROR_CODE") {
continue;
}
QuicErrorCodeToIetfMapping ietf_error_code =
QuicErrorCodeToTransportErrorCode(
static_cast<QuicErrorCode>(internal_error_code));
if (ietf_error_code.is_transport_close) {
QuicIetfTransportErrorCodes transport_error_code =
static_cast<QuicIetfTransportErrorCodes>(ietf_error_code.error_code);
bool is_transport_crypto_error_code =
transport_error_code >= 0x100 && transport_error_code <= 0x1ff;
if (is_transport_crypto_error_code) {
EXPECT_EQ(
internal_error_code,
TlsAlertToQuicErrorCode(transport_error_code - CRYPTO_ERROR_FIRST));
}
bool is_valid_transport_error_code =
transport_error_code <= 0x0f || is_transport_crypto_error_code;
EXPECT_TRUE(is_valid_transport_error_code) << internal_error_code_string;
} else {
uint64_t application_error_code = ietf_error_code.error_code;
bool is_valid_http3_error_code =
application_error_code >= 0x100 && application_error_code <= 0x110;
bool is_valid_qpack_error_code =
application_error_code >= 0x200 && application_error_code <= 0x202;
EXPECT_TRUE(is_valid_http3_error_code || is_valid_qpack_error_code)
<< internal_error_code_string;
}
}
}
using QuicRstErrorCodesTest = QuicTest;
TEST_F(QuicRstErrorCodesTest, QuicRstStreamErrorCodeToString) {
EXPECT_STREQ("QUIC_BAD_APPLICATION_PAYLOAD",
QuicRstStreamErrorCodeToString(QUIC_BAD_APPLICATION_PAYLOAD));
}
TEST_F(QuicRstErrorCodesTest,
IetfResetStreamErrorCodeToRstStreamErrorCodeAndBack) {
for (uint64_t wire_code :
{static_cast<uint64_t>(QuicHttp3ErrorCode::HTTP3_NO_ERROR),
static_cast<uint64_t>(QuicHttp3ErrorCode::GENERAL_PROTOCOL_ERROR),
static_cast<uint64_t>(QuicHttp3ErrorCode::INTERNAL_ERROR),
static_cast<uint64_t>(QuicHttp3ErrorCode::STREAM_CREATION_ERROR),
static_cast<uint64_t>(QuicHttp3ErrorCode::CLOSED_CRITICAL_STREAM),
static_cast<uint64_t>(QuicHttp3ErrorCode::FRAME_UNEXPECTED),
static_cast<uint64_t>(QuicHttp3ErrorCode::FRAME_ERROR),
static_cast<uint64_t>(QuicHttp3ErrorCode::EXCESSIVE_LOAD),
static_cast<uint64_t>(QuicHttp3ErrorCode::ID_ERROR),
static_cast<uint64_t>(QuicHttp3ErrorCode::SETTINGS_ERROR),
static_cast<uint64_t>(QuicHttp3ErrorCode::MISSING_SETTINGS),
static_cast<uint64_t>(QuicHttp3ErrorCode::REQUEST_REJECTED),
static_cast<uint64_t>(QuicHttp3ErrorCode::REQUEST_CANCELLED),
static_cast<uint64_t>(QuicHttp3ErrorCode::REQUEST_INCOMPLETE),
static_cast<uint64_t>(QuicHttp3ErrorCode::CONNECT_ERROR),
static_cast<uint64_t>(QuicHttp3ErrorCode::VERSION_FALLBACK),
static_cast<uint64_t>(QuicHttpQpackErrorCode::DECOMPRESSION_FAILED),
static_cast<uint64_t>(QuicHttpQpackErrorCode::ENCODER_STREAM_ERROR),
static_cast<uint64_t>(QuicHttpQpackErrorCode::DECODER_STREAM_ERROR)}) {
QuicRstStreamErrorCode rst_stream_error_code =
IetfResetStreamErrorCodeToRstStreamErrorCode(wire_code);
EXPECT_EQ(wire_code, RstStreamErrorCodeToIetfResetStreamErrorCode(
rst_stream_error_code));
}
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_error_codes.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_error_codes_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
86c445d1-3acf-4a4e-b997-db710d49539f | cpp | google/quiche | quic_socket_address_coder | quiche/quic/core/quic_socket_address_coder.cc | quiche/quic/core/quic_socket_address_coder_test.cc | #include "quiche/quic/core/quic_socket_address_coder.h"
#include <cstring>
#include <string>
#include <vector>
#include "quiche/quic/platform/api/quic_ip_address_family.h"
namespace quic {
namespace {
const uint16_t kIPv4 = 2;
const uint16_t kIPv6 = 10;
}
QuicSocketAddressCoder::QuicSocketAddressCoder() {}
QuicSocketAddressCoder::QuicSocketAddressCoder(const QuicSocketAddress& address)
: address_(address) {}
QuicSocketAddressCoder::~QuicSocketAddressCoder() {}
std::string QuicSocketAddressCoder::Encode() const {
std::string serialized;
uint16_t address_family;
switch (address_.host().address_family()) {
case IpAddressFamily::IP_V4:
address_family = kIPv4;
break;
case IpAddressFamily::IP_V6:
address_family = kIPv6;
break;
default:
return serialized;
}
serialized.append(reinterpret_cast<const char*>(&address_family),
sizeof(address_family));
serialized.append(address_.host().ToPackedString());
uint16_t port = address_.port();
serialized.append(reinterpret_cast<const char*>(&port), sizeof(port));
return serialized;
}
bool QuicSocketAddressCoder::Decode(const char* data, size_t length) {
uint16_t address_family;
if (length < sizeof(address_family)) {
return false;
}
memcpy(&address_family, data, sizeof(address_family));
data += sizeof(address_family);
length -= sizeof(address_family);
size_t ip_length;
switch (address_family) {
case kIPv4:
ip_length = QuicIpAddress::kIPv4AddressSize;
break;
case kIPv6:
ip_length = QuicIpAddress::kIPv6AddressSize;
break;
default:
return false;
}
if (length < ip_length) {
return false;
}
std::vector<uint8_t> ip(ip_length);
memcpy(&ip[0], data, ip_length);
data += ip_length;
length -= ip_length;
uint16_t port;
if (length != sizeof(port)) {
return false;
}
memcpy(&port, data, length);
QuicIpAddress ip_address;
ip_address.FromPackedString(reinterpret_cast<const char*>(&ip[0]), ip_length);
address_ = QuicSocketAddress(ip_address, port);
return true;
}
} | #include "quiche/quic/core/quic_socket_address_coder.h"
#include <string>
#include "absl/base/macros.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_test.h"
namespace quic {
namespace test {
class QuicSocketAddressCoderTest : public QuicTest {};
TEST_F(QuicSocketAddressCoderTest, EncodeIPv4) {
QuicIpAddress ip;
ip.FromString("4.31.198.44");
QuicSocketAddressCoder coder(QuicSocketAddress(ip, 0x1234));
std::string serialized = coder.Encode();
std::string expected("\x02\x00\x04\x1f\xc6\x2c\x34\x12", 8);
EXPECT_EQ(expected, serialized);
}
TEST_F(QuicSocketAddressCoderTest, EncodeIPv6) {
QuicIpAddress ip;
ip.FromString("2001:700:300:1800::f");
QuicSocketAddressCoder coder(QuicSocketAddress(ip, 0x5678));
std::string serialized = coder.Encode();
std::string expected(
"\x0a\x00"
"\x20\x01\x07\x00\x03\x00\x18\x00"
"\x00\x00\x00\x00\x00\x00\x00\x0f"
"\x78\x56",
20);
EXPECT_EQ(expected, serialized);
}
TEST_F(QuicSocketAddressCoderTest, DecodeIPv4) {
std::string serialized("\x02\x00\x04\x1f\xc6\x2c\x34\x12", 8);
QuicSocketAddressCoder coder;
ASSERT_TRUE(coder.Decode(serialized.data(), serialized.length()));
EXPECT_EQ(IpAddressFamily::IP_V4, coder.ip().address_family());
std::string expected_addr("\x04\x1f\xc6\x2c");
EXPECT_EQ(expected_addr, coder.ip().ToPackedString());
EXPECT_EQ(0x1234, coder.port());
}
TEST_F(QuicSocketAddressCoderTest, DecodeIPv6) {
std::string serialized(
"\x0a\x00"
"\x20\x01\x07\x00\x03\x00\x18\x00"
"\x00\x00\x00\x00\x00\x00\x00\x0f"
"\x78\x56",
20);
QuicSocketAddressCoder coder;
ASSERT_TRUE(coder.Decode(serialized.data(), serialized.length()));
EXPECT_EQ(IpAddressFamily::IP_V6, coder.ip().address_family());
std::string expected_addr(
"\x20\x01\x07\x00\x03\x00\x18\x00"
"\x00\x00\x00\x00\x00\x00\x00\x0f",
16);
EXPECT_EQ(expected_addr, coder.ip().ToPackedString());
EXPECT_EQ(0x5678, coder.port());
}
TEST_F(QuicSocketAddressCoderTest, DecodeBad) {
std::string serialized(
"\x0a\x00"
"\x20\x01\x07\x00\x03\x00\x18\x00"
"\x00\x00\x00\x00\x00\x00\x00\x0f"
"\x78\x56",
20);
QuicSocketAddressCoder coder;
EXPECT_TRUE(coder.Decode(serialized.data(), serialized.length()));
serialized.push_back('\0');
EXPECT_FALSE(coder.Decode(serialized.data(), serialized.length()));
serialized.resize(20);
EXPECT_TRUE(coder.Decode(serialized.data(), serialized.length()));
serialized[0] = '\x03';
EXPECT_FALSE(coder.Decode(serialized.data(), serialized.length()));
serialized[0] = '\x0a';
EXPECT_TRUE(coder.Decode(serialized.data(), serialized.length()));
size_t len = serialized.length();
for (size_t i = 0; i < len; i++) {
ASSERT_FALSE(serialized.empty());
serialized.erase(serialized.length() - 1);
EXPECT_FALSE(coder.Decode(serialized.data(), serialized.length()));
}
EXPECT_TRUE(serialized.empty());
}
TEST_F(QuicSocketAddressCoderTest, EncodeAndDecode) {
struct {
const char* ip_literal;
uint16_t port;
} test_case[] = {
{"93.184.216.119", 0x1234},
{"199.204.44.194", 80},
{"149.20.4.69", 443},
{"127.0.0.1", 8080},
{"2001:700:300:1800::", 0x5678},
{"::1", 65534},
};
for (size_t i = 0; i < ABSL_ARRAYSIZE(test_case); i++) {
QuicIpAddress ip;
ASSERT_TRUE(ip.FromString(test_case[i].ip_literal));
QuicSocketAddressCoder encoder(QuicSocketAddress(ip, test_case[i].port));
std::string serialized = encoder.Encode();
QuicSocketAddressCoder decoder;
ASSERT_TRUE(decoder.Decode(serialized.data(), serialized.length()));
EXPECT_EQ(encoder.ip(), decoder.ip());
EXPECT_EQ(encoder.port(), decoder.port());
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_socket_address_coder.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_socket_address_coder_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
c52c1cca-1aa8-4857-935d-25c61d856f28 | cpp | google/quiche | quic_connection_context | quiche/quic/core/quic_connection_context.cc | quiche/quic/core/quic_connection_context_test.cc | #include "quiche/quic/core/quic_connection_context.h"
#include "absl/base/attributes.h"
namespace quic {
namespace {
ABSL_CONST_INIT thread_local QuicConnectionContext* current_context = nullptr;
}
QuicConnectionContext* QuicConnectionContext::Current() {
return current_context;
}
QuicConnectionContextSwitcher::QuicConnectionContextSwitcher(
QuicConnectionContext* new_context)
: old_context_(QuicConnectionContext::Current()) {
current_context = new_context;
if (new_context && new_context->listener) {
new_context->listener->Activate();
}
}
QuicConnectionContextSwitcher::~QuicConnectionContextSwitcher() {
QuicConnectionContext* current = QuicConnectionContext::Current();
if (current && current->listener) {
current->listener->Deactivate();
}
current_context = old_context_;
}
} | #include "quiche/quic/core/quic_connection_context.h"
#include <memory>
#include <string>
#include <vector>
#include "quiche/quic/platform/api/quic_test.h"
#include "quiche/quic/platform/api/quic_thread.h"
using testing::ElementsAre;
namespace quic::test {
namespace {
class TraceCollector : public QuicConnectionTracer {
public:
~TraceCollector() override = default;
void PrintLiteral(const char* literal) override { trace_.push_back(literal); }
void PrintString(absl::string_view s) override {
trace_.push_back(std::string(s));
}
const std::vector<std::string>& trace() const { return trace_; }
private:
std::vector<std::string> trace_;
};
struct FakeConnection {
FakeConnection() { context.tracer = std::make_unique<TraceCollector>(); }
const std::vector<std::string>& trace() const {
return static_cast<const TraceCollector*>(context.tracer.get())->trace();
}
QuicConnectionContext context;
};
void SimpleSwitch() {
FakeConnection connection;
EXPECT_EQ(QuicConnectionContext::Current(), nullptr);
QUIC_TRACELITERAL("before switch: literal");
QUIC_TRACESTRING(std::string("before switch: string"));
QUIC_TRACEPRINTF("%s: %s", "before switch", "printf");
{
QuicConnectionContextSwitcher switcher(&connection.context);
QUIC_TRACELITERAL("literal");
QUIC_TRACESTRING(std::string("string"));
QUIC_TRACEPRINTF("%s", "printf");
}
EXPECT_EQ(QuicConnectionContext::Current(), nullptr);
QUIC_TRACELITERAL("after switch: literal");
QUIC_TRACESTRING(std::string("after switch: string"));
QUIC_TRACEPRINTF("%s: %s", "after switch", "printf");
EXPECT_THAT(connection.trace(), ElementsAre("literal", "string", "printf"));
}
void NestedSwitch() {
FakeConnection outer, inner;
{
QuicConnectionContextSwitcher switcher(&outer.context);
QUIC_TRACELITERAL("outer literal 0");
QUIC_TRACESTRING(std::string("outer string 0"));
QUIC_TRACEPRINTF("%s %s %d", "outer", "printf", 0);
{
QuicConnectionContextSwitcher nested_switcher(&inner.context);
QUIC_TRACELITERAL("inner literal");
QUIC_TRACESTRING(std::string("inner string"));
QUIC_TRACEPRINTF("%s %s", "inner", "printf");
}
QUIC_TRACELITERAL("outer literal 1");
QUIC_TRACESTRING(std::string("outer string 1"));
QUIC_TRACEPRINTF("%s %s %d", "outer", "printf", 1);
}
EXPECT_THAT(outer.trace(), ElementsAre("outer literal 0", "outer string 0",
"outer printf 0", "outer literal 1",
"outer string 1", "outer printf 1"));
EXPECT_THAT(inner.trace(),
ElementsAre("inner literal", "inner string", "inner printf"));
}
void AlternatingSwitch() {
FakeConnection zero, one, two;
for (int i = 0; i < 15; ++i) {
FakeConnection* connection =
((i % 3) == 0) ? &zero : (((i % 3) == 1) ? &one : &two);
QuicConnectionContextSwitcher switcher(&connection->context);
QUIC_TRACEPRINTF("%d", i);
}
EXPECT_THAT(zero.trace(), ElementsAre("0", "3", "6", "9", "12"));
EXPECT_THAT(one.trace(), ElementsAre("1", "4", "7", "10", "13"));
EXPECT_THAT(two.trace(), ElementsAre("2", "5", "8", "11", "14"));
}
typedef void (*ThreadFunction)();
template <ThreadFunction func>
class TestThread : public QuicThread {
public:
TestThread() : QuicThread("TestThread") {}
~TestThread() override = default;
protected:
void Run() override { func(); }
};
template <ThreadFunction func>
void RunInThreads(size_t n_threads) {
using ThreadType = TestThread<func>;
std::vector<ThreadType> threads(n_threads);
for (ThreadType& t : threads) {
t.Start();
}
for (ThreadType& t : threads) {
t.Join();
}
}
class QuicConnectionContextTest : public QuicTest {
protected:
};
TEST_F(QuicConnectionContextTest, NullTracerOK) {
FakeConnection connection;
std::unique_ptr<QuicConnectionTracer> tracer;
{
QuicConnectionContextSwitcher switcher(&connection.context);
QUIC_TRACELITERAL("msg 1 recorded");
}
connection.context.tracer.swap(tracer);
{
QuicConnectionContextSwitcher switcher(&connection.context);
QUIC_TRACELITERAL("msg 2 ignored");
}
EXPECT_THAT(static_cast<TraceCollector*>(tracer.get())->trace(),
ElementsAre("msg 1 recorded"));
}
TEST_F(QuicConnectionContextTest, TestSimpleSwitch) {
RunInThreads<SimpleSwitch>(10);
}
TEST_F(QuicConnectionContextTest, TestNestedSwitch) {
RunInThreads<NestedSwitch>(10);
}
TEST_F(QuicConnectionContextTest, TestAlternatingSwitch) {
RunInThreads<AlternatingSwitch>(10);
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_connection_context.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_connection_context_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
bc60f86c-e41b-41b2-8fdf-d424fb530694 | cpp | google/quiche | quic_blocked_writer_list | quiche/quic/core/quic_blocked_writer_list.cc | quiche/quic/core/quic_blocked_writer_list_test.cc | #include "quiche/quic/core/quic_blocked_writer_list.h"
#include <utility>
#include "quiche/quic/platform/api/quic_bug_tracker.h"
#include "quiche/quic/platform/api/quic_flag_utils.h"
namespace quic {
void QuicBlockedWriterList::Add(QuicBlockedWriterInterface& blocked_writer) {
if (!blocked_writer.IsWriterBlocked()) {
QUIC_BUG(quic_bug_12724_4)
<< "Tried to add writer into blocked list when it shouldn't be added";
return;
}
write_blocked_list_.insert(std::make_pair(&blocked_writer, true));
}
bool QuicBlockedWriterList::Empty() const {
return write_blocked_list_.empty();
}
bool QuicBlockedWriterList::Remove(QuicBlockedWriterInterface& blocked_writer) {
return write_blocked_list_.erase(&blocked_writer) != 0;
}
void QuicBlockedWriterList::OnWriterUnblocked() {
const size_t num_blocked_writers_before = write_blocked_list_.size();
WriteBlockedList temp_list;
temp_list.swap(write_blocked_list_);
QUICHE_DCHECK(write_blocked_list_.empty());
while (!temp_list.empty()) {
QuicBlockedWriterInterface* blocked_writer = temp_list.begin()->first;
temp_list.erase(temp_list.begin());
blocked_writer->OnBlockedWriterCanWrite();
}
const size_t num_blocked_writers_after = write_blocked_list_.size();
if (num_blocked_writers_after != 0) {
if (num_blocked_writers_before == num_blocked_writers_after) {
QUIC_CODE_COUNT(quic_zero_progress_on_can_write);
} else {
QUIC_CODE_COUNT(quic_blocked_again_on_can_write);
}
}
}
} | #include "quiche/quic/core/quic_blocked_writer_list.h"
#include "quiche/quic/core/quic_blocked_writer_interface.h"
#include "quiche/quic/platform/api/quic_test.h"
namespace quic {
using testing::Invoke;
using testing::Return;
namespace {
class TestWriter : public QuicBlockedWriterInterface {
public:
~TestWriter() override = default;
MOCK_METHOD(void, OnBlockedWriterCanWrite, ());
MOCK_METHOD(bool, IsWriterBlocked, (), (const));
};
}
TEST(QuicBlockedWriterList, Empty) {
QuicBlockedWriterList list;
EXPECT_TRUE(list.Empty());
}
TEST(QuicBlockedWriterList, NotEmpty) {
QuicBlockedWriterList list;
testing::StrictMock<TestWriter> writer1;
EXPECT_CALL(writer1, IsWriterBlocked()).WillOnce(Return(true));
list.Add(writer1);
EXPECT_FALSE(list.Empty());
list.Remove(writer1);
EXPECT_TRUE(list.Empty());
}
TEST(QuicBlockedWriterList, OnWriterUnblocked) {
QuicBlockedWriterList list;
testing::StrictMock<TestWriter> writer1;
EXPECT_CALL(writer1, IsWriterBlocked()).WillOnce(Return(true));
list.Add(writer1);
EXPECT_CALL(writer1, OnBlockedWriterCanWrite());
list.OnWriterUnblocked();
EXPECT_TRUE(list.Empty());
}
TEST(QuicBlockedWriterList, OnWriterUnblockedInOrder) {
QuicBlockedWriterList list;
testing::StrictMock<TestWriter> writer1;
testing::StrictMock<TestWriter> writer2;
testing::StrictMock<TestWriter> writer3;
EXPECT_CALL(writer1, IsWriterBlocked()).WillOnce(Return(true));
EXPECT_CALL(writer2, IsWriterBlocked()).WillOnce(Return(true));
EXPECT_CALL(writer3, IsWriterBlocked()).WillOnce(Return(true));
list.Add(writer1);
list.Add(writer2);
list.Add(writer3);
testing::InSequence s;
EXPECT_CALL(writer1, OnBlockedWriterCanWrite());
EXPECT_CALL(writer2, OnBlockedWriterCanWrite());
EXPECT_CALL(writer3, OnBlockedWriterCanWrite());
list.OnWriterUnblocked();
EXPECT_TRUE(list.Empty());
}
TEST(QuicBlockedWriterList, OnWriterUnblockedInOrderAfterReinsertion) {
QuicBlockedWriterList list;
testing::StrictMock<TestWriter> writer1;
testing::StrictMock<TestWriter> writer2;
testing::StrictMock<TestWriter> writer3;
EXPECT_CALL(writer1, IsWriterBlocked()).WillOnce(Return(true));
EXPECT_CALL(writer2, IsWriterBlocked()).WillOnce(Return(true));
EXPECT_CALL(writer3, IsWriterBlocked()).WillOnce(Return(true));
list.Add(writer1);
list.Add(writer2);
list.Add(writer3);
EXPECT_CALL(writer1, IsWriterBlocked()).WillOnce(Return(true));
list.Add(writer1);
testing::InSequence s;
EXPECT_CALL(writer1, OnBlockedWriterCanWrite());
EXPECT_CALL(writer2, OnBlockedWriterCanWrite());
EXPECT_CALL(writer3, OnBlockedWriterCanWrite());
list.OnWriterUnblocked();
EXPECT_TRUE(list.Empty());
}
TEST(QuicBlockedWriterList, OnWriterUnblockedThenBlocked) {
QuicBlockedWriterList list;
testing::StrictMock<TestWriter> writer1;
testing::StrictMock<TestWriter> writer2;
testing::StrictMock<TestWriter> writer3;
EXPECT_CALL(writer1, IsWriterBlocked()).WillOnce(Return(true));
EXPECT_CALL(writer2, IsWriterBlocked()).WillOnce(Return(true));
EXPECT_CALL(writer3, IsWriterBlocked()).WillOnce(Return(true));
list.Add(writer1);
list.Add(writer2);
list.Add(writer3);
EXPECT_CALL(writer1, OnBlockedWriterCanWrite());
EXPECT_CALL(writer2, IsWriterBlocked()).WillOnce(Return(true));
EXPECT_CALL(writer2, OnBlockedWriterCanWrite()).WillOnce(Invoke([&]() {
list.Add(writer2);
}));
EXPECT_CALL(writer3, OnBlockedWriterCanWrite());
list.OnWriterUnblocked();
EXPECT_FALSE(list.Empty());
EXPECT_CALL(writer2, OnBlockedWriterCanWrite());
list.OnWriterUnblocked();
EXPECT_TRUE(list.Empty());
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_blocked_writer_list.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_blocked_writer_list_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
0b50e74e-6281-418c-afaa-2bc9ca84c7fd | 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 | #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::CachedState& other) {
QUICHE_DCHECK(server_config_.empty());
QUICHE_DCHECK(!server_config_valid_);
server_config_ = other.server_config_;
source_address_token_ = other.source_address_token_;
certs_ = other.certs_;
cert_sct_ = other.cert_sct_;
chlo_hash_ = other.chlo_hash_;
server_config_sig_ = other.server_config_sig_;
server_config_valid_ = other.server_config_valid_;
expiration_time_ = other.expiration_time_;
if (other.proof_verify_details_ != nullptr) {
proof_verify_details_.reset(other.proof_verify_details_->Clone());
}
++generation_counter_;
}
void QuicCryptoClientConfig::SetDefaults() {
kexs = {kC255, kP256};
if (EVP_has_aes_hardware() == 1) {
aead = {kAESG, kCC20};
} else {
aead = {kCC20, kAESG};
}
}
QuicCryptoClientConfig::CachedState* QuicCryptoClientConfig::LookupOrCreate(
const QuicServerId& server_id) {
auto it = cached_states_.find(server_id);
if (it != cached_states_.end()) {
return it->second.get();
}
CachedState* cached = new CachedState;
cached_states_.insert(std::make_pair(server_id, absl::WrapUnique(cached)));
bool cache_populated = PopulateFromCanonicalConfig(server_id, cached);
QUIC_CLIENT_HISTOGRAM_BOOL(
"QuicCryptoClientConfig.PopulatedFromCanonicalConfig", cache_populated,
"");
return cached;
}
void QuicCryptoClientConfig::ClearCachedStates(const ServerIdFilter& filter) {
for (auto it = cached_states_.begin(); it != cached_states_.end(); ++it) {
if (filter.Matches(it->first)) it->second->Clear();
}
}
void QuicCryptoClientConfig::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 {
out->set_tag(kCHLO);
out->set_minimum_size(1);
if (QuicHostnameUtils::IsValidSNI(server_id.host())) {
out->SetStringPiece(kSNI, server_id.host());
}
out->SetVersion(kVER, preferred_version);
if (!user_agent_id_.empty()) {
out->SetStringPiece(kUAID, user_agent_id_);
}
if (!alpn_.empty()) {
out->SetStringPiece(kALPN, alpn_);
}
const CryptoHandshakeMessage* scfg = cached->GetServerConfig();
if (scfg != nullptr) {
absl::string_view scid;
if (scfg->GetStringPiece(kSCID, &scid)) {
out->SetStringPiece(kSCID, scid);
}
}
if (!cached->source_address_token().empty()) {
out->SetStringPiece(kSourceAddressTokenTag, cached->source_address_token());
}
if (!demand_x509_proof) {
return;
}
char proof_nonce[32];
rand->RandBytes(proof_nonce, ABSL_ARRAYSIZE(proof_nonce));
out->SetStringPiece(
kNONP, absl::string_view(proof_nonce, ABSL_ARRAYSIZE(proof_nonce)));
out->SetVector(kPDMD, QuicTagVector{kX509});
out->SetStringPiece(kCertificateSCTTag, "");
const std::vector<std::string>& certs = cached->certs();
out_params->cached_certs = certs;
if (!certs.empty()) {
std::vector<uint64_t> hashes;
hashes.reserve(certs.size());
for (auto i = certs.begin(); i != certs.end(); ++i) {
hashes.push_back(QuicUtils::FNV1a_64_Hash(*i));
}
out->SetVector(kCCRT, hashes);
}
}
QuicErrorCode QuicCryptoClientConfig::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 {
QUICHE_DCHECK(error_details != nullptr);
QUIC_BUG_IF(quic_bug_12943_2,
!QuicUtils::IsConnectionIdValidForVersion(
connection_id, preferred_version.transport_version))
<< "FillClientHello: attempted to use connection ID " << connection_id
<< " which is invalid with version " << preferred_version;
FillInchoateClientHello(server_id, preferred_version, cached, rand,
true, out_params, out);
out->set_minimum_size(1);
const CryptoHandshakeMessage* scfg = cached->GetServerConfig();
if (!scfg) {
*error_details = "Handshake not ready";
return QUIC_CRYPTO_INTERNAL_ERROR;
}
absl::string_view scid;
if (!scfg->GetStringPiece(kSCID, &scid)) {
*error_details = "SCFG missing SCID";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
out->SetStringPiece(kSCID, scid);
out->SetStringPiece(kCertificateSCTTag, "");
QuicTagVector their_aeads;
QuicTagVector their_key_exchanges;
if (scfg->GetTaglist(kAEAD, &their_aeads) != QUIC_NO_ERROR ||
scfg->GetTaglist(kKEXS, &their_key_exchanges) != QUIC_NO_ERROR) {
*error_details = "Missing AEAD or KEXS";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
size_t key_exchange_index;
if (!FindMutualQuicTag(aead, their_aeads, &out_params->aead, nullptr) ||
!FindMutualQuicTag(kexs, their_key_exchanges, &out_params->key_exchange,
&key_exchange_index)) {
*error_details = "Unsupported AEAD or KEXS";
return QUIC_CRYPTO_NO_SUPPORT;
}
out->SetVector(kAEAD, QuicTagVector{out_params->aead});
out->SetVector(kKEXS, QuicTagVector{out_params->key_exchange});
absl::string_view public_value;
if (scfg->GetNthValue24(kPUBS, key_exchange_index, &public_value) !=
QUIC_NO_ERROR) {
*error_details = "Missing public value";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
absl::string_view orbit;
if (!scfg->GetStringPiece(kORBT, &orbit) || orbit.size() != kOrbitSize) {
*error_details = "SCFG missing OBIT";
return QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND;
}
CryptoUtils::GenerateNonce(now, rand, orbit, &out_params->client_nonce);
out->SetStringPiece(kNONC, out_params->client_nonce);
if (!out_params->server_nonce.empty()) {
out->SetStringPiece(kServerNonceTag, out_params->server_nonce);
}
switch (out_params->key_exchange) {
case kC255:
out_params->client_key_exchange = Curve25519KeyExchange::New(
Curve25519KeyExchange::NewPrivateKey(rand));
break;
case kP256:
out_params->client_key_exchange =
P256KeyExchange::New(P256KeyExchange::NewPrivateKey());
break;
default:
QUICHE_DCHECK(false);
*error_details = "Configured to support an unknown key exchange";
return QUIC_CRYPTO_INTERNAL_ERROR;
}
if (!out_params->client_key_exchange->CalculateSharedKeySync(
public_value, &out_params->initial_premaster_secret)) {
*error_details = "Key exchange failure";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
out->SetStringPiece(kPUBS, out_params->client_key_exchange->public_value());
const std::vector<std::string>& certs = cached->certs();
if (certs.empty()) {
*error_details = "No certs to calculate XLCT";
return QUIC_CRYPTO_INTERNAL_ERROR;
}
out->SetValue(kXLCT, CryptoUtils::ComputeLeafCertHash(certs[0]));
out_params->hkdf_input_suffix.clear();
out_params->hkdf_input_suffix.append(connection_id.data(),
connection_id.length());
const QuicData& client_hello_serialized = out->GetSerialized();
out_params->hkdf_input_suffix.append(client_hello_serialized.data(),
client_hello_serialized.length());
out_params->hkdf_input_suffix.append(cached->server_config());
if (certs.empty()) {
*error_details = "No certs found to include in KDF";
return QUIC_CRYPTO_INTERNAL_ERROR;
}
out_params->hkdf_input_suffix.append(certs[0]);
std::string hkdf_input;
const size_t label_len = strlen(QuicCryptoConfig::kInitialLabel) + 1;
hkdf_input.reserve(label_len + out_params->hkdf_input_suffix.size());
hkdf_input.append(QuicCryptoConfig::kInitialLabel, label_len);
hkdf_input.append(out_params->hkdf_input_suffix);
std::string* subkey_secret = &out_params->initial_subkey_secret;
if (!CryptoUtils::DeriveKeys(
actual_version, out_params->initial_premaster_secret,
out_params->aead, out_params->client_nonce, out_params->server_nonce,
pre_shared_key_, hkdf_input, Perspective::IS_CLIENT,
CryptoUtils::Diversification::Pending(),
&out_params->initial_crypters, subkey_secret)) {
*error_details = "Symmetric key setup failed";
return QUIC_CRYPTO_SYMMETRIC_KEY_SETUP_FAILED;
}
return QUIC_NO_ERROR;
}
QuicErrorCode QuicCryptoClientConfig::CacheNewServerConfig(
const CryptoHandshakeMessage& message, QuicWallTime now,
QuicTransportVersion , absl::string_view chlo_hash,
const std::vector<std::string>& cached_certs, CachedState* cached,
std::string* error_details) {
QUICHE_DCHECK(error_details != nullptr);
absl::string_view scfg;
if (!message.GetStringPiece(kSCFG, &scfg)) {
*error_details = "Missing SCFG";
return QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND;
}
QuicWallTime expiration_time = QuicWallTime::Zero();
uint64_t expiry_seconds;
if (message.GetUint64(kSTTL, &expiry_seconds) == QUIC_NO_ERROR) {
expiration_time = now.Add(QuicTime::Delta::FromSeconds(
std::min(expiry_seconds, kNumSecondsPerWeek)));
}
CachedState::ServerConfigState state =
cached->SetServerConfig(scfg, now, expiration_time, error_details);
if (state == CachedState::SERVER_CONFIG_EXPIRED) {
return QUIC_CRYPTO_SERVER_CONFIG_EXPIRED;
}
if (state != CachedState::SERVER_CONFIG_VALID) {
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
absl::string_view token;
if (message.GetStringPiece(kSourceAddressTokenTag, &token)) {
cached->set_source_address_token(token);
}
absl::string_view proof, cert_bytes, cert_sct;
bool has_proof = message.GetStringPiece(kPROF, &proof);
bool has_cert = message.GetStringPiece(kCertificateTag, &cert_bytes);
if (has_proof && has_cert) {
std::vector<std::string> certs;
if (!CertCompressor::DecompressChain(cert_bytes, cached_certs, &certs)) {
*error_details = "Certificate data invalid";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
message.GetStringPiece(kCertificateSCTTag, &cert_sct);
cached->SetProof(certs, cert_sct, chlo_hash, proof);
} else {
cached->ClearProof();
if (has_proof && !has_cert) {
*error_details = "Certificate missing";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
if (!has_proof && has_cert) {
*error_details = "Proof missing";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
}
return QUIC_NO_ERROR;
}
QuicErrorCode QuicCryptoClientConfig::ProcessRejection(
const CryptoHandshakeMessage& rej, QuicWallTime now,
const QuicTransportVersion version, absl::string_view chlo_hash,
CachedState* cached,
quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters>
out_params,
std::string* error_details) {
QUICHE_DCHECK(error_details != nullptr);
if (rej.tag() != kREJ) {
*error_details = "Message is not REJ";
return QUIC_CRYPTO_INTERNAL_ERROR;
}
QuicErrorCode error =
CacheNewServerConfig(rej, now, version, chlo_hash,
out_params->cached_certs, cached, error_details);
if (error != QUIC_NO_ERROR) {
return error;
}
absl::string_view nonce;
if (rej.GetStringPiece(kServerNonceTag, &nonce)) {
out_params->server_nonce = std::string(nonce);
}
return QUIC_NO_ERROR;
}
QuicErrorCode QuicCryptoClientConfig::ProcessServerHello(
const CryptoHandshakeMessage& server_hello,
QuicConnectionId , ParsedQuicVersion version,
const ParsedQuicVersionVector& negotiated_versions, CachedState* cached,
quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters>
out_params,
std::string* error_details) {
QUICHE_DCHECK(error_details != nullptr);
QuicErrorCode valid = CryptoUtils::ValidateServerHello(
server_hello, negotiated_versions, error_details);
if (valid != QUIC_NO_ERROR) {
return valid;
}
absl::string_view token;
if (server_hello.GetStringPiece(kSourceAddressTokenTag, &token)) {
cached->set_source_address_token(token);
}
absl::string_view shlo_nonce;
if (!server_hello.GetStringPiece(kServerNonceTag, &shlo_nonce)) {
*error_details = "server hello missing server nonce";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
absl::string_view public_value;
if (!server_hello.GetStringPiece(kPUBS, &public_value)) {
*error_details = "server hello missing forward secure public value";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
if (!out_params->client_key_exchange->CalculateSharedKeySync(
public_value, &out_params->forward_secure_premaster_secret)) {
*error_details = "Key exchange failure";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
std::string hkdf_input;
const size_t label_len = strlen(QuicCryptoConfig::kForwardSecureLabel) + 1;
hkdf_input.reserve(label_len + out_params->hkdf_input_suffix.size());
hkdf_input.append(QuicCryptoConfig::kForwardSecureLabel, label_len);
hkdf_input.append(out_params->hkdf_input_suffix);
if (!CryptoUtils::DeriveKeys(
version, out_params->forward_secure_premaster_secret,
out_params->aead, out_params->client_nonce,
shlo_nonce.empty() ? out_params->server_nonce : shlo_nonce,
pre_shared_key_, hkdf_input, Perspective::IS_CLIENT,
CryptoUtils::Diversification::Never(),
&out_params->forward_secure_crypters, &out_params->subkey_secret)) {
*error_details = "Symmetric key setup failed";
return QUIC_CRYPTO_SYMMETRIC_KEY_SETUP_FAILED;
}
return QUIC_NO_ERROR;
}
QuicErrorCode QuicCryptoClientConfig::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) {
QUICHE_DCHECK(error_details != nullptr);
if (server_config_update.tag() != kSCUP) {
*error_details = "ServerConfigUpdate must have kSCUP tag.";
return QUIC_INVALID_CRYPTO_MESSAGE_TYPE;
}
return CacheNewServerConfig(server_config_update, now, version, chlo_hash,
out_params->cached_certs, cached, error_details);
}
ProofVerifier* QuicCryptoClientConfig::proof_verifier() const {
return proof_verifier_.get();
}
SessionCache* QuicCryptoClientConfig::session_cache() const {
return session_cache_.get();
}
void QuicCryptoClientConfig::set_session_cache(
std::shared_ptr<SessionCache> session_cache) {
session_cache_ = std::move(session_cache);
}
ClientProofSource* QuicCryptoClientConfig::proof_source() const {
return proof_source_.get();
}
void QuicCryptoClientConfig::set_proof_source(
std::unique_ptr<ClientProofSource> proof_source) {
proof_source_ = std::move(proof_source);
}
SSL_CTX* QuicCryptoClientConfig::ssl_ctx() const { return ssl_ctx_.get(); }
void QuicCryptoClientConfig::InitializeFrom(
const QuicServerId& server_id, const QuicServerId& canonical_server_id,
QuicCryptoClientConfig* canonical_crypto_config) {
CachedState* canonical_cached =
canonical_crypto_config->LookupOrCreate(canonical_server_id);
if (!canonical_cached->proof_valid()) {
return;
}
CachedState* cached = LookupOrCreate(server_id);
cached->InitializeFrom(*canonical_cached);
}
void QuicCryptoClientConfig::AddCanonicalSuffix(const std::string& suffix) {
canonical_suffixes_.push_back(suffix);
}
bool QuicCryptoClientConfig::PopulateFromCanonicalConfig(
const QuicServerId& server_id, CachedState* cached) {
QUICHE_DCHECK(cached->IsEmpty());
size_t i = 0;
for (; i < canonical_suffixes_.size(); ++i) {
if (absl::EndsWithIgnoreCase(server_id.host(), canonical_suffixes_[i])) {
break;
}
}
if (i == canonical_suffixes_.size()) {
return false;
}
QuicServerId suffix_server_id(canonical_suffixes_[i], server_id.port());
auto it = canonical_server_map_.lower_bound(suffix_server_id);
if (it == canonical_server_map_.end() || it->first != suffix_server_id) {
canonical_server_map_.insert(
it, std::make_pair(std::move(suffix_server_id), std::move(server_id)));
return false;
}
const QuicServerId& canonical_server_id = it->second;
CachedState* canonical_state = cached_states_[canonical_server_id].get();
if (!canonical_state->proof_valid()) {
return false;
}
it->second = server_id;
cached->InitializeFrom(*canonical_state);
return true;
}
} | #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);
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);
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);
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);
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);
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);
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);
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);
QuicCryptoClientConfig::CachedState* state =
config.LookupOrCreate(canonical_server_id);
state->set_source_address_token("TOKEN");
state->SetProofValid();
QuicServerId other_server_id("mail.google.com", 443);
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);
QuicServerId canonical_id2("mail.google.com", 443);
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);
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);
QuicServerId canonical_id2("mail.google.com", 443);
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), 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);
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);
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);
QuicCryptoClientConfig::CachedState* state3 =
config.LookupOrCreate(canonical_server_id3);
EXPECT_TRUE(state3->IsEmpty());
const CryptoHandshakeMessage* const scfg3 = state3->GetServerConfig();
EXPECT_FALSE(scfg3);
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/quic_crypto_client_config.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/quic_crypto_client_config_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
8867b303-3760-4c6a-ae22-deb8039dc228 | cpp | google/quiche | null_decrypter | quiche/quic/core/crypto/null_decrypter.cc | quiche/quic/core/crypto/null_decrypter_test.cc | #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));
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/null_decrypter.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/null_decrypter_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
cd769502-6740-472a-af2d-ee4ccea984ff | cpp | google/quiche | curve25519_key_exchange | quiche/quic/core/crypto/curve25519_key_exchange.cc | quiche/quic/core/crypto/curve25519_key_exchange_test.cc | #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());
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/curve25519_key_exchange.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/curve25519_key_exchange_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
e59aac71-cf2e-45a8-bde2-70dce5b93419 | 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 | #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());
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/chacha20_poly1305_tls_decrypter.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/chacha20_poly1305_tls_decrypter_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
d53c5340-f9f2-4631-8d81-c1a41da52e9d | cpp | google/quiche | crypto_secret_boxer | quiche/quic/core/crypto/crypto_secret_boxer.cc | quiche/quic/core/crypto/crypto_secret_boxer_test.cc | #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"
#include "quiche/common/platform/api/quiche_mutex.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));
}
quiche::QuicheWriterMutexLock 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;
{
quiche::QuicheReaderMutexLock 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;
{
quiche::QuicheReaderMutexLock 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));
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/crypto_secret_boxer.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/crypto_secret_boxer_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
e3abe368-daaa-479e-a903-fb97f4bc69c4 | 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 | #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());
}
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/aes_128_gcm_12_decrypter.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/aes_128_gcm_12_decrypter_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
4e41776b-5e87-46af-94e5-a93ae9fe3691 | cpp | google/quiche | crypto_utils | quiche/quic/core/crypto/crypto_utils.cc | quiche/quic/core/crypto/crypto_utils_test.cc | #include "quiche/quic/core/crypto/crypto_utils.h"
#include <algorithm>
#include <cstddef>
#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/err.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);
switch (diversification.mode()) {
case Diversification::NEVER: {
if (perspective == Perspective::IS_SERVER) {
if (!crypters->encrypter->SetKey(hkdf.server_write_key()) ||
!crypters->encrypter->SetNoncePrefixOrIV(version,
hkdf.server_write_iv()) ||
!crypters->encrypter->SetHeaderProtectionKey(
hkdf.server_hp_key()) ||
!crypters->decrypter->SetKey(hkdf.client_write_key()) ||
!crypters->decrypter->SetNoncePrefixOrIV(version,
hkdf.client_write_iv()) ||
!crypters->decrypter->SetHeaderProtectionKey(
hkdf.client_hp_key())) {
return false;
}
} else {
if (!crypters->encrypter->SetKey(hkdf.client_write_key()) ||
!crypters->encrypter->SetNoncePrefixOrIV(version,
hkdf.client_write_iv()) ||
!crypters->encrypter->SetHeaderProtectionKey(
hkdf.client_hp_key()) ||
!crypters->decrypter->SetKey(hkdf.server_write_key()) ||
!crypters->decrypter->SetNoncePrefixOrIV(version,
hkdf.server_write_iv()) ||
!crypters->decrypter->SetHeaderProtectionKey(
hkdf.server_hp_key())) {
return false;
}
}
break;
}
case Diversification::PENDING: {
if (perspective == Perspective::IS_SERVER) {
QUIC_BUG(quic_bug_10699_8)
<< "Pending diversification is only for clients.";
return false;
}
if (!crypters->encrypter->SetKey(hkdf.client_write_key()) ||
!crypters->encrypter->SetNoncePrefixOrIV(version,
hkdf.client_write_iv()) ||
!crypters->encrypter->SetHeaderProtectionKey(hkdf.client_hp_key()) ||
!crypters->decrypter->SetPreliminaryKey(hkdf.server_write_key()) ||
!crypters->decrypter->SetNoncePrefixOrIV(version,
hkdf.server_write_iv()) ||
!crypters->decrypter->SetHeaderProtectionKey(hkdf.server_hp_key())) {
return false;
}
break;
}
case Diversification::NOW: {
if (perspective == Perspective::IS_CLIENT) {
QUIC_BUG(quic_bug_10699_9)
<< "Immediate diversification is only for servers.";
return false;
}
std::string key, nonce_prefix;
QuicDecrypter::DiversifyPreliminaryKey(
hkdf.server_write_key(), hkdf.server_write_iv(),
*diversification.nonce(), key_bytes, nonce_prefix_bytes, &key,
&nonce_prefix);
if (!crypters->decrypter->SetKey(hkdf.client_write_key()) ||
!crypters->decrypter->SetNoncePrefixOrIV(version,
hkdf.client_write_iv()) ||
!crypters->decrypter->SetHeaderProtectionKey(hkdf.client_hp_key()) ||
!crypters->encrypter->SetKey(key) ||
!crypters->encrypter->SetNoncePrefixOrIV(version, nonce_prefix) ||
!crypters->encrypter->SetHeaderProtectionKey(hkdf.server_hp_key())) {
return false;
}
break;
}
default:
QUICHE_DCHECK(false);
}
if (subkey_secret != nullptr) {
*subkey_secret = std::string(hkdf.subkey_secret());
}
return true;
}
uint64_t CryptoUtils::ComputeLeafCertHash(absl::string_view cert) {
return QuicUtils::FNV1a_64_Hash(cert);
}
QuicErrorCode CryptoUtils::ValidateServerHello(
const CryptoHandshakeMessage& server_hello,
const ParsedQuicVersionVector& negotiated_versions,
std::string* error_details) {
QUICHE_DCHECK(error_details != nullptr);
if (server_hello.tag() != kSHLO) {
*error_details = "Bad tag";
return QUIC_INVALID_CRYPTO_MESSAGE_TYPE;
}
QuicVersionLabelVector supported_version_labels;
if (server_hello.GetVersionLabelList(kVER, &supported_version_labels) !=
QUIC_NO_ERROR) {
*error_details = "server hello missing version list";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
return ValidateServerHelloVersions(supported_version_labels,
negotiated_versions, error_details);
}
QuicErrorCode CryptoUtils::ValidateServerHelloVersions(
const QuicVersionLabelVector& server_versions,
const ParsedQuicVersionVector& negotiated_versions,
std::string* error_details) {
if (!negotiated_versions.empty()) {
bool mismatch = server_versions.size() != negotiated_versions.size();
for (size_t i = 0; i < server_versions.size() && !mismatch; ++i) {
mismatch =
server_versions[i] != CreateQuicVersionLabel(negotiated_versions[i]);
}
if (mismatch) {
*error_details = absl::StrCat(
"Downgrade attack detected: ServerVersions(", server_versions.size(),
")[", QuicVersionLabelVectorToString(server_versions, ",", 30),
"] NegotiatedVersions(", negotiated_versions.size(), ")[",
ParsedQuicVersionVectorToString(negotiated_versions, ",", 30), "]");
return QUIC_VERSION_NEGOTIATION_MISMATCH;
}
}
return QUIC_NO_ERROR;
}
QuicErrorCode CryptoUtils::ValidateClientHello(
const CryptoHandshakeMessage& client_hello, ParsedQuicVersion version,
const ParsedQuicVersionVector& supported_versions,
std::string* error_details) {
if (client_hello.tag() != kCHLO) {
*error_details = "Bad tag";
return QUIC_INVALID_CRYPTO_MESSAGE_TYPE;
}
QuicVersionLabel client_version_label;
if (client_hello.GetVersionLabel(kVER, &client_version_label) !=
QUIC_NO_ERROR) {
*error_details = "client hello missing version list";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
return ValidateClientHelloVersion(client_version_label, version,
supported_versions, error_details);
}
QuicErrorCode CryptoUtils::ValidateClientHelloVersion(
QuicVersionLabel client_version, ParsedQuicVersion connection_version,
const ParsedQuicVersionVector& supported_versions,
std::string* error_details) {
if (client_version != CreateQuicVersionLabel(connection_version)) {
for (size_t i = 0; i < supported_versions.size(); ++i) {
if (client_version == CreateQuicVersionLabel(supported_versions[i])) {
*error_details = absl::StrCat(
"Downgrade attack detected: ClientVersion[",
QuicVersionLabelToString(client_version), "] ConnectionVersion[",
ParsedQuicVersionToString(connection_version),
"] SupportedVersions(", supported_versions.size(), ")[",
ParsedQuicVersionVectorToString(supported_versions, ",", 30), "]");
return QUIC_VERSION_NEGOTIATION_MISMATCH;
}
}
}
return QUIC_NO_ERROR;
}
bool CryptoUtils::ValidateChosenVersion(
const QuicVersionLabel& version_information_chosen_version,
const ParsedQuicVersion& session_version, std::string* error_details) {
if (version_information_chosen_version !=
CreateQuicVersionLabel(session_version)) {
*error_details = absl::StrCat(
"Detected version mismatch: version_information contained ",
QuicVersionLabelToString(version_information_chosen_version),
" instead of ", ParsedQuicVersionToString(session_version));
return false;
}
return true;
}
bool CryptoUtils::ValidateServerVersions(
const QuicVersionLabelVector& version_information_other_versions,
const ParsedQuicVersion& session_version,
const ParsedQuicVersionVector& client_original_supported_versions,
std::string* error_details) {
if (client_original_supported_versions.empty()) {
return true;
}
ParsedQuicVersionVector parsed_other_versions =
ParseQuicVersionLabelVector(version_information_other_versions);
ParsedQuicVersion expected_version = ParsedQuicVersion::Unsupported();
for (const ParsedQuicVersion& client_version :
client_original_supported_versions) {
if (std::find(parsed_other_versions.begin(), parsed_other_versions.end(),
client_version) != parsed_other_versions.end()) {
expected_version = client_version;
break;
}
}
if (expected_version != session_version) {
*error_details = absl::StrCat(
"Downgrade attack detected: used ",
ParsedQuicVersionToString(session_version), " but ServerVersions(",
version_information_other_versions.size(), ")[",
QuicVersionLabelVectorToString(version_information_other_versions, ",",
30),
"] ClientOriginalVersions(", client_original_supported_versions.size(),
")[",
ParsedQuicVersionVectorToString(client_original_supported_versions, ",",
30),
"]");
return false;
}
return true;
}
#define RETURN_STRING_LITERAL(x) \
case x: \
return #x
const char* CryptoUtils::HandshakeFailureReasonToString(
HandshakeFailureReason reason) {
switch (reason) {
RETURN_STRING_LITERAL(HANDSHAKE_OK);
RETURN_STRING_LITERAL(CLIENT_NONCE_UNKNOWN_FAILURE);
RETURN_STRING_LITERAL(CLIENT_NONCE_INVALID_FAILURE);
RETURN_STRING_LITERAL(CLIENT_NONCE_NOT_UNIQUE_FAILURE);
RETURN_STRING_LITERAL(CLIENT_NONCE_INVALID_ORBIT_FAILURE);
RETURN_STRING_LITERAL(CLIENT_NONCE_INVALID_TIME_FAILURE);
RETURN_STRING_LITERAL(CLIENT_NONCE_STRIKE_REGISTER_TIMEOUT);
RETURN_STRING_LITERAL(CLIENT_NONCE_STRIKE_REGISTER_FAILURE);
RETURN_STRING_LITERAL(SERVER_NONCE_DECRYPTION_FAILURE);
RETURN_STRING_LITERAL(SERVER_NONCE_INVALID_FAILURE);
RETURN_STRING_LITERAL(SERVER_NONCE_NOT_UNIQUE_FAILURE);
RETURN_STRING_LITERAL(SERVER_NONCE_INVALID_TIME_FAILURE);
RETURN_STRING_LITERAL(SERVER_NONCE_REQUIRED_FAILURE);
RETURN_STRING_LITERAL(SERVER_CONFIG_INCHOATE_HELLO_FAILURE);
RETURN_STRING_LITERAL(SERVER_CONFIG_UNKNOWN_CONFIG_FAILURE);
RETURN_STRING_LITERAL(SOURCE_ADDRESS_TOKEN_INVALID_FAILURE);
RETURN_STRING_LITERAL(SOURCE_ADDRESS_TOKEN_DECRYPTION_FAILURE);
RETURN_STRING_LITERAL(SOURCE_ADDRESS_TOKEN_PARSE_FAILURE);
RETURN_STRING_LITERAL(SOURCE_ADDRESS_TOKEN_DIFFERENT_IP_ADDRESS_FAILURE);
RETURN_STRING_LITERAL(SOURCE_ADDRESS_TOKEN_CLOCK_SKEW_FAILURE);
RETURN_STRING_LITERAL(SOURCE_ADDRESS_TOKEN_EXPIRED_FAILURE);
RETURN_STRING_LITERAL(INVALID_EXPECTED_LEAF_CERTIFICATE);
RETURN_STRING_LITERAL(MAX_FAILURE_REASON);
}
return "INVALID_HANDSHAKE_FAILURE_REASON";
}
#undef RETURN_STRING_LITERAL
std::string CryptoUtils::EarlyDataReasonToString(
ssl_early_data_reason_t reason) {
const char* reason_string = SSL_early_data_reason_string(reason);
if (reason_string != nullptr) {
return std::string("ssl_early_data_") + reason_string;
}
QUIC_BUG_IF(quic_bug_12871_3,
reason < 0 || reason > ssl_early_data_reason_max_value)
<< "Unknown ssl_early_data_reason_t " << reason;
return "unknown ssl_early_data_reason_t";
}
std::string CryptoUtils::HashHandshakeMessage(
const CryptoHandshakeMessage& message, Perspective ) {
std::string output;
const QuicData& serialized = message.GetSerialized();
uint8_t digest[SHA256_DIGEST_LENGTH];
SHA256(reinterpret_cast<const uint8_t*>(serialized.data()),
serialized.length(), digest);
output.assign(reinterpret_cast<const char*>(digest), sizeof(digest));
return output;
}
bool CryptoUtils::GetSSLCapabilities(const SSL* ssl,
bssl::UniquePtr<uint8_t>* capabilities,
size_t* capabilities_len) {
uint8_t* buffer;
bssl::ScopedCBB cbb;
if (!CBB_init(cbb.get(), 128) ||
!SSL_serialize_capabilities(ssl, cbb.get()) ||
!CBB_finish(cbb.get(), &buffer, capabilities_len)) {
return false;
}
*capabilities = bssl::UniquePtr<uint8_t>(buffer);
return true;
}
std::optional<std::string> CryptoUtils::GenerateProofPayloadToBeSigned(
absl::string_view chlo_hash, absl::string_view server_config) {
size_t payload_size = sizeof(kProofSignatureLabel) + sizeof(uint32_t) +
chlo_hash.size() + server_config.size();
std::string payload;
payload.resize(payload_size);
QuicDataWriter payload_writer(payload_size, payload.data(),
quiche::Endianness::HOST_BYTE_ORDER);
bool success = payload_writer.WriteBytes(kProofSignatureLabel,
sizeof(kProofSignatureLabel)) &&
payload_writer.WriteUInt32(chlo_hash.size()) &&
payload_writer.WriteStringPiece(chlo_hash) &&
payload_writer.WriteStringPiece(server_config);
if (!success) {
return std::nullopt;
}
return payload;
}
std::string CryptoUtils::GetSSLErrorStack() {
std::string result;
const char* file;
const char* data;
int line;
int flags;
int packed_error = ERR_get_error_line_data(&file, &line, &data, &flags);
if (packed_error != 0) {
char buffer[ERR_ERROR_STRING_BUF_LEN];
while (packed_error != 0) {
ERR_error_string_n(packed_error, buffer, sizeof(buffer));
absl::StrAppendFormat(&result, "[%s:%d] %s", PosixBasename(file), line,
buffer);
if (data && (flags & ERR_TXT_STRING)) {
absl::StrAppendFormat(&result, "(%s)", data);
}
packed_error = ERR_get_error_line_data(&file, &line, &data, &flags);
if (packed_error != 0) {
absl::StrAppend(&result, ", ");
}
}
}
return result;
}
} | #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/str_cat.h"
#include "absl/strings/string_view.h"
#include "openssl/err.h"
#include "openssl/ssl.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 {
using ::testing::AllOf;
using ::testing::HasSubstr;
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);
}
}
TEST_F(CryptoUtilsTest, GetSSLErrorStack) {
ERR_clear_error();
const int line = (OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SSL_VERSION), __LINE__);
std::string error_location = absl::StrCat("crypto_utils_test.cc:", line);
EXPECT_THAT(CryptoUtils::GetSSLErrorStack(),
AllOf(HasSubstr(error_location), HasSubstr("WRONG_SSL_VERSION")));
EXPECT_TRUE(CryptoUtils::GetSSLErrorStack().empty());
ERR_clear_error();
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/crypto_utils.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/crypto_utils_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
8ae863ea-b859-4a67-abeb-3bdd5ff08373 | cpp | google/quiche | chacha20_poly1305_encrypter | quiche/quic/core/crypto/chacha20_poly1305_encrypter.cc | quiche/quic/core/crypto/chacha20_poly1305_encrypter_test.cc | #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));
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/chacha20_poly1305_encrypter.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/chacha20_poly1305_encrypter_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
7104f0ae-7ea6-4577-a737-6eb9c8a9195e | cpp | google/quiche | proof_source_x509 | quiche/quic/core/crypto/proof_source_x509.cc | quiche/quic/core/crypto/proof_source_x509_test.cc | #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>());
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/proof_source_x509.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/proof_source_x509_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
ddb4901f-a53e-485f-a2f2-dea58d05ec89 | cpp | google/quiche | p256_key_exchange | quiche/quic/core/crypto/p256_key_exchange.cc | quiche/quic/core/crypto/p256_key_exchange_test.cc | #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());
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/p256_key_exchange.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/p256_key_exchange_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
57f098d9-da3c-4ce4-a0e2-5b4d75de77da | cpp | google/quiche | quic_hkdf | quiche/quic/core/crypto/quic_hkdf.cc | quiche/quic/core/crypto/quic_hkdf_test.cc | #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()));
}
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/quic_hkdf.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/quic_hkdf_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
c4c7ef74-e75d-4082-85ad-b20b4f359d7d | cpp | google/quiche | cert_compressor | quiche/quic/core/crypto/cert_compressor.cc | quiche/quic/core/crypto/cert_compressor_test.cc | #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));
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/cert_compressor.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/cert_compressor_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
94d65507-653b-432e-949d-172867d6e0b4 | 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 | #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());
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/aes_256_gcm_decrypter.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/aes_256_gcm_decrypter_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
bcacdd99-1c10-474c-bf53-07e8abaf672b | 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 | #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());
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/aes_128_gcm_decrypter.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/aes_128_gcm_decrypter_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
a807a51e-59a8-4aa7-8b7c-9ed30daf3d07 | cpp | google/quiche | transport_parameters | quiche/quic/core/crypto/transport_parameters.cc | quiche/quic/core/crypto/transport_parameters_test.cc | #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,
kReliableStreamReset = 0x17F7586D2CB571,
};
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";
case TransportParameters::kReliableStreamReset:
return "reliable_stream_reset";
}
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:
case TransportParameters::kReliableStreamReset:
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 (reliable_stream_reset) {
rv += " " + TransportParameterIdToString(kReliableStreamReset);
}
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),
active_connection_id_limit(kActiveConnectionIdLimit,
kDefaultActiveConnectionIdLimitTransportParam,
kMinActiveConnectionIdLimitTransportParam,
quiche::kVarInt62MaxValue),
max_datagram_frame_size(kMaxDatagramFrameSize),
reliable_stream_reset(false),
initial_round_trip_time_us(kInitialRoundTripTime)
{}
TransportParameters::TransportParameters(const TransportParameters& other)
: perspective(other.perspective),
legacy_version_information(other.legacy_version_information),
version_information(other.version_information),
original_destination_connection_id(
other.original_destination_connection_id),
max_idle_timeout_ms(other.max_idle_timeout_ms),
stateless_reset_token(other.stateless_reset_token),
max_udp_payload_size(other.max_udp_payload_size),
initial_max_data(other.initial_max_data),
initial_max_stream_data_bidi_local(
other.initial_max_stream_data_bidi_local),
initial_max_stream_data_bidi_remote(
other.initial_max_stream_data_bidi_remote),
initial_max_stream_data_uni(other.initial_max_stream_data_uni),
initial_max_streams_bidi(other.initial_max_streams_bidi),
initial_max_streams_uni(other.initial_max_streams_uni),
ack_delay_exponent(other.ack_delay_exponent),
max_ack_delay(other.max_ack_delay),
min_ack_delay_us(other.min_ack_delay_us),
disable_active_migration(other.disable_active_migration),
active_connection_id_limit(other.active_connection_id_limit),
initial_source_connection_id(other.initial_source_connection_id),
retry_source_connection_id(other.retry_source_connection_id),
max_datagram_frame_size(other.max_datagram_frame_size),
reliable_stream_reset(other.reliable_stream_reset),
initial_round_trip_time_us(other.initial_round_trip_time_us),
google_handshake_message(other.google_handshake_message),
google_connection_options(other.google_connection_options),
custom_parameters(other.custom_parameters) {
if (other.preferred_address) {
preferred_address = std::make_unique<TransportParameters::PreferredAddress>(
*other.preferred_address);
}
}
bool TransportParameters::operator==(const TransportParameters& rhs) const {
if (!(perspective == rhs.perspective &&
legacy_version_information == rhs.legacy_version_information &&
version_information == rhs.version_information &&
original_destination_connection_id ==
rhs.original_destination_connection_id &&
max_idle_timeout_ms.value() == rhs.max_idle_timeout_ms.value() &&
stateless_reset_token == rhs.stateless_reset_token &&
max_udp_payload_size.value() == rhs.max_udp_payload_size.value() &&
initial_max_data.value() == rhs.initial_max_data.value() &&
initial_max_stream_data_bidi_local.value() ==
rhs.initial_max_stream_data_bidi_local.value() &&
initial_max_stream_data_bidi_remote.value() ==
rhs.initial_max_stream_data_bidi_remote.value() &&
initial_max_stream_data_uni.value() ==
rhs.initial_max_stream_data_uni.value() &&
initial_max_streams_bidi.value() ==
rhs.initial_max_streams_bidi.value() &&
initial_max_streams_uni.value() ==
rhs.initial_max_streams_uni.value() &&
ack_delay_exponent.value() == rhs.ack_delay_exponent.value() &&
max_ack_delay.value() == rhs.max_ack_delay.value() &&
min_ack_delay_us.value() == rhs.min_ack_delay_us.value() &&
disable_active_migration == rhs.disable_active_migration &&
active_connection_id_limit.value() ==
rhs.active_connection_id_limit.value() &&
initial_source_connection_id == rhs.initial_source_connection_id &&
retry_source_connection_id == rhs.retry_source_connection_id &&
max_datagram_frame_size.value() ==
rhs.max_datagram_frame_size.value() &&
reliable_stream_reset == rhs.reliable_stream_reset &&
initial_round_trip_time_us.value() ==
rhs.initial_round_trip_time_us.value() &&
google_handshake_message == rhs.google_handshake_message &&
google_connection_options == rhs.google_connection_options &&
custom_parameters == rhs.custom_parameters)) {
return false;
}
if ((!preferred_address && rhs.preferred_address) ||
(preferred_address && !rhs.preferred_address)) {
return false;
}
if (preferred_address && rhs.preferred_address &&
*preferred_address != *rhs.preferred_address) {
return false;
}
return true;
}
bool TransportParameters::operator!=(const TransportParameters& rhs) const {
return !(*this == rhs);
}
bool TransportParameters::AreValid(std::string* error_details) const {
QUICHE_DCHECK(perspective == Perspective::IS_CLIENT ||
perspective == Perspective::IS_SERVER);
if (perspective == Perspective::IS_CLIENT && !stateless_reset_token.empty()) {
*error_details = "Client cannot send stateless reset token";
return false;
}
if (perspective == Perspective::IS_CLIENT &&
original_destination_connection_id.has_value()) {
*error_details = "Client cannot send original_destination_connection_id";
return false;
}
if (!stateless_reset_token.empty() &&
stateless_reset_token.size() != kStatelessResetTokenLength) {
*error_details = absl::StrCat("Stateless reset token has bad length ",
stateless_reset_token.size());
return false;
}
if (perspective == Perspective::IS_CLIENT && preferred_address) {
*error_details = "Client cannot send preferred address";
return false;
}
if (preferred_address && preferred_address->stateless_reset_token.size() !=
kStatelessResetTokenLength) {
*error_details =
absl::StrCat("Preferred address stateless reset token has bad length ",
preferred_address->stateless_reset_token.size());
return false;
}
if (preferred_address &&
(!preferred_address->ipv4_socket_address.host().IsIPv4() ||
!preferred_address->ipv6_socket_address.host().IsIPv6())) {
QUIC_BUG(quic_bug_10743_4) << "Preferred address family failure";
*error_details = "Internal preferred address family failure";
return false;
}
if (perspective == Perspective::IS_CLIENT &&
retry_source_connection_id.has_value()) {
*error_details = "Client cannot send retry_source_connection_id";
return false;
}
for (const auto& kv : custom_parameters) {
if (TransportParameterIdIsKnown(kv.first)) {
*error_details = absl::StrCat("Using custom_parameters with known ID ",
TransportParameterIdToString(kv.first),
" is not allowed");
return false;
}
}
if (perspective == Perspective::IS_SERVER &&
google_handshake_message.has_value()) {
*error_details = "Server cannot send google_handshake_message";
return false;
}
if (perspective == Perspective::IS_SERVER &&
initial_round_trip_time_us.value() > 0) {
*error_details = "Server cannot send initial round trip time";
return false;
}
if (version_information.has_value()) {
const QuicVersionLabel& chosen_version =
version_information->chosen_version;
const QuicVersionLabelVector& other_versions =
version_information->other_versions;
if (chosen_version == 0) {
*error_details = "Invalid chosen version";
return false;
}
if (perspective == Perspective::IS_CLIENT &&
std::find(other_versions.begin(), other_versions.end(),
chosen_version) == other_versions.end()) {
*error_details = "Client chosen version not in other versions";
return false;
}
}
const bool ok =
max_idle_timeout_ms.IsValid() && max_udp_payload_size.IsValid() &&
initial_max_data.IsValid() &&
initial_max_stream_data_bidi_local.IsValid() &&
initial_max_stream_data_bidi_remote.IsValid() &&
initial_max_stream_data_uni.IsValid() &&
initial_max_streams_bidi.IsValid() && initial_max_streams_uni.IsValid() &&
ack_delay_exponent.IsValid() && max_ack_delay.IsValid() &&
min_ack_delay_us.IsValid() && active_connection_id_limit.IsValid() &&
max_datagram_frame_size.IsValid() && initial_round_trip_time_us.IsValid();
if (!ok) {
*error_details = "Invalid transport parameters " + this->ToString();
}
return ok;
}
TransportParameters::~TransportParameters() = default;
bool SerializeTransportParameters(const TransportParameters& in,
std::vector<uint8_t>* out) {
std::string error_details;
if (!in.AreValid(&error_details)) {
QUIC_BUG(invalid transport parameters)
<< "Not serializing invalid transport parameters: " << error_details;
return false;
}
if (!in.legacy_version_information.has_value() ||
in.legacy_version_information->version == 0 ||
(in.perspective == Perspective::IS_SERVER &&
in.legacy_version_information->supported_versions.empty())) {
QUIC_BUG(missing versions) << "Refusing to serialize without versions";
return false;
}
TransportParameters::ParameterMap custom_parameters = in.custom_parameters;
for (const auto& kv : custom_parameters) {
if (kv.first % 31 == 27) {
QUIC_BUG(custom_parameters with GREASE)
<< "Serializing custom_parameters with GREASE ID " << kv.first
<< " is not allowed";
return false;
}
}
static constexpr size_t kMaxGreaseLength = 16;
static constexpr size_t kTypeAndValueLength = 2 * sizeof(uint64_t);
static constexpr size_t kIntegerParameterLength =
kTypeAndValueLength + sizeof(uint64_t);
static constexpr size_t kStatelessResetParameterLength =
kTypeAndValueLength + 16 ;
static constexpr size_t kConnectionIdParameterLength =
kTypeAndValueLength + 255 ;
static constexpr size_t kPreferredAddressParameterLength =
kTypeAndValueLength + 4 + 2 +
16 + 1 +
255 + 16 ;
static constexpr size_t kKnownTransportParamLength =
kConnectionIdParameterLength +
kIntegerParameterLength +
kStatelessResetParameterLength +
kIntegerParameterLength +
kIntegerParameterLength +
kIntegerParameterLength +
kIntegerParameterLength +
kIntegerParameterLength +
kIntegerParameterLength +
kIntegerParameterLength +
kIntegerParameterLength +
kIntegerParameterLength +
kIntegerParameterLength +
kTypeAndValueLength +
kPreferredAddressParameterLength +
kIntegerParameterLength +
kConnectionIdParameterLength +
kConnectionIdParameterLength +
kIntegerParameterLength +
kTypeAndValueLength +
kIntegerParameterLength +
kTypeAndValueLength +
kTypeAndValueLength +
kTypeAndValueLength;
std::vector<TransportParameters::TransportParameterId> parameter_ids = {
TransportParameters::kOriginalDestinationConnectionId,
TransportParameters::kMaxIdleTimeout,
TransportParameters::kStatelessResetToken,
TransportParameters::kMaxPacketSize,
TransportParameters::kInitialMaxData,
TransportParameters::kInitialMaxStreamDataBidiLocal,
TransportParameters::kInitialMaxStreamDataBidiRemote,
TransportParameters::kInitialMaxStreamDataUni,
TransportParameters::kInitialMaxStreamsBidi,
TransportParameters::kInitialMaxStreamsUni,
TransportParameters::kAckDelayExponent,
TransportParameters::kMaxAckDelay,
TransportParameters::kMinAckDelay,
TransportParameters::kActiveConnectionIdLimit,
TransportParameters::kMaxDatagramFrameSize,
TransportParameters::kReliableStreamReset,
TransportParameters::kGoogleHandshakeMessage,
TransportParameters::kInitialRoundTripTime,
TransportParameters::kDisableActiveMigration,
TransportParameters::kPreferredAddress,
TransportParameters::kInitialSourceConnectionId,
TransportParameters::kRetrySourceConnectionId,
TransportParameters::kGoogleConnectionOptions,
TransportParameters::kGoogleQuicVersion,
TransportParameters::kVersionInformation,
};
size_t max_transport_param_length = kKnownTransportParamLength;
if (in.google_connection_options.has_value()) {
max_transport_param_length +=
in.google_connection_options->size() * sizeof(QuicTag);
}
if (in.legacy_version_information.has_value()) {
max_transport_param_length +=
sizeof(in.legacy_version_information->version) +
1 +
in.legacy_version_information->supported_versions.size() *
sizeof(QuicVersionLabel);
}
if (in.version_information.has_value()) {
max_transport_param_length +=
sizeof(in.version_information->chosen_version) +
(in.version_information->other_versions.size() + 1) *
sizeof(QuicVersionLabel);
}
if (in.google_handshake_message.has_value()) {
max_transport_param_length += in.google_handshake_message->length();
}
QuicRandom* random = QuicRandom::GetInstance();
uint64_t grease_id64 = random->RandUint64() % ((1ULL << 62) - 31);
grease_id64 = (grease_id64 / 31) * 31 + 27;
TransportParameters::TransportParameterId grease_id =
static_cast<TransportParameters::TransportParameterId>(grease_id64);
const size_t grease_length = random->RandUint64() % kMaxGreaseLength;
QUICHE_DCHECK_GE(kMaxGreaseLength, grease_length);
char grease_contents[kMaxGreaseLength];
random->RandBytes(grease_contents, grease_length);
custom_parameters[grease_id] = std::string(grease_contents, grease_length);
for (const auto& kv : custom_parameters) {
max_transport_param_length += kTypeAndValueLength + kv.second.length();
parameter_ids.push_back(kv.first);
}
for (size_t i = parameter_ids.size() - 1; i > 0; i--) {
std::swap(parameter_ids[i],
parameter_ids[random->InsecureRandUint64() % (i + 1)]);
}
out->resize(max_transport_param_length);
QuicDataWriter writer(out->size(), reinterpret_cast<char*>(out->data()));
for (TransportParameters::TransportParameterId parameter_id : parameter_ids) {
switch (parameter_id) {
case TransportParameters::kOriginalDestinationConnectionId: {
if (in.original_destination_connection_id.has_value()) {
QUICHE_DCHECK_EQ(Perspective::IS_SERVER, in.perspective);
QuicConnectionId original_destination_connection_id =
*in.original_destination_connection_id;
if (!writer.WriteVarInt62(
TransportParameters::kOriginalDestinationConnectionId) ||
!writer.WriteStringPieceVarInt62(absl::string_view(
original_destination_connection_id.data(),
original_destination_connection_id.length()))) {
QUIC_BUG(Failed to write original_destination_connection_id)
<< "Failed to write original_destination_connection_id "
<< original_destination_connection_id << " for " << in;
return false;
}
}
} break;
case TransportParameters::kMaxIdleTimeout: {
if (!in.max_idle_timeout_ms.Write(&writer)) {
QUIC_BUG(Failed to write idle_timeout)
<< "Failed to write idle_timeout for " << in;
return false;
}
} break;
case TransportParameters::kStatelessResetToken: {
if (!in.stateless_reset_token.empty()) {
QUICHE_DCHECK_EQ(kStatelessResetTokenLength,
in.stateless_reset_token.size());
QUICHE_DCHECK_EQ(Perspective::IS_SERVER, in.perspective);
if (!writer.WriteVarInt62(
TransportParameters::kStatelessResetToken) ||
!writer.WriteStringPieceVarInt62(
absl::string_view(reinterpret_cast<const char*>(
in.stateless_reset_token.data()),
in.stateless_reset_token.size()))) {
QUIC_BUG(Failed to write stateless_reset_token)
<< "Failed to write stateless_reset_token of length "
<< in.stateless_reset_token.size() << " for " << in;
return false;
}
}
} break;
case TransportParameters::kMaxPacketSize: {
if (!in.max_udp_payload_size.Write(&writer)) {
QUIC_BUG(Failed to write max_udp_payload_size)
<< "Failed to write max_udp_payload_size for " << in;
return false;
}
} break;
case TransportParameters::kInitialMaxData: {
if (!in.initial_max_data.Write(&writer)) {
QUIC_BUG(Failed to write initial_max_data)
<< "Failed to write initial_max_data for " << in;
return false;
}
} break;
case TransportParameters::kInitialMaxStreamDataBidiLocal: {
if (!in.initial_max_stream_data_bidi_local.Write(&writer)) {
QUIC_BUG(Failed to write initial_max_stream_data_bidi_local)
<< "Failed to write initial_max_stream_data_bidi_local for "
<< in;
return false;
}
} break;
case TransportParameters::kInitialMaxStreamDataBidiRemote: {
if (!in.initial_max_stream_data_bidi_remote.Write(&writer)) {
QUIC_BUG(Failed to write initial_max_stream_data_bidi_remote)
<< "Failed to write initial_max_stream_data_bidi_remote for "
<< in;
return false;
}
} break;
case TransportParameters::kInitialMaxStreamDataUni: {
if (!in.initial_max_stream_data_uni.Write(&writer)) {
QUIC_BUG(Failed to write initial_max_stream_data_uni)
<< "Failed to write initial_max_stream_data_uni for " << in;
return false;
}
} break;
case TransportParameters::kInitialMaxStreamsBidi: {
if (!in.initial_max_streams_bidi.Write(&writer)) {
QUIC_BUG(Failed to write initial_max_streams_bidi)
<< "Failed to write initial_max_streams_bidi for " << in;
return false;
}
} break;
case TransportParameters::kInitialMaxStreamsUni: {
if (!in.initial_max_streams_uni.Write(&writer)) {
QUIC_BUG(Failed to write initial_max_streams_uni)
<< "Failed to write initial_max_streams_uni for " << in;
return false;
}
} break;
case TransportParameters::kAckDelayExponent: {
if (!in.ack_delay_exponent.Write(&writer)) {
QUIC_BUG(Failed to write ack_delay_exponent)
<< "Failed to write ack_delay_exponent for " << in;
return false;
}
} break;
case TransportParameters::kMaxAckDelay: {
if (!in.max_ack_delay.Write(&writer)) {
QUIC_BUG(Failed to write max_ack_delay)
<< "Failed to write max_ack_delay for " << in;
return false;
}
} break;
case TransportParameters::kMinAckDelay: {
if (!in.min_ack_delay_us.Write(&writer)) {
QUIC_BUG(Failed to write min_ack_delay_us)
<< "Failed to write min_ack_delay_us for " << in;
return false;
}
} break;
case TransportParameters::kActiveConnectionIdLimit: {
if (!in.active_connection_id_limit.Write(&writer)) {
QUIC_BUG(Failed to write active_connection_id_limit)
<< "Failed to write active_connection_id_limit for " << in;
return false;
}
} break;
case TransportParameters::kMaxDatagramFrameSize: {
if (!in.max_datagram_frame_size.Write(&writer)) {
QUIC_BUG(Failed to write max_datagram_frame_size)
<< "Failed to write max_datagram_frame_size for " << in;
return false;
}
} break;
case TransportParameters::kGoogleHandshakeMessage: {
if (in.google_handshake_message.has_value()) {
if (!writer.WriteVarInt62(
TransportParameters::kGoogleHandshakeMessage) ||
!writer.WriteStringPieceVarInt62(*in.google_handshake_message)) {
QUIC_BUG(Failed to write google_handshake_message)
<< "Failed to write google_handshake_message: "
<< *in.google_handshake_message << " for " << in;
return false;
}
}
} break;
case TransportParameters::kInitialRoundTripTime: {
if (!in.initial_round_trip_time_us.Write(&writer)) {
QUIC_BUG(Failed to write initial_round_trip_time_us)
<< "Failed to write initial_round_trip_time_us for " << in;
return false;
}
} break;
case TransportParameters::kDisableActiveMigration: {
if (in.disable_active_migration) {
if (!writer.WriteVarInt62(
TransportParameters::kDisableActiveMigration) ||
!writer.WriteVarInt62( 0)) {
QUIC_BUG(Failed to write disable_active_migration)
<< "Failed to write disable_active_migration for " << in;
return false;
}
}
} break;
case TransportParameters::kReliableStreamReset: {
if (in.reliable_stream_reset) {
if (!writer.WriteVarInt62(
TransportParameters::kReliableStreamReset) ||
!writer.WriteVarInt62( 0)) {
QUIC_BUG(Failed to write reliable_stream_reset)
<< "Failed to write reliable_stream_reset for " << in;
return false;
}
}
} break;
case TransportParameters::kPreferredAddress: {
if (in.preferred_address) {
std::string v4_address_bytes =
in.preferred_address->ipv4_socket_address.host().ToPackedString();
std::string v6_address_bytes =
in.preferred_address->ipv6_socket_address.host().ToPackedString();
if (v4_address_bytes.length() != 4 ||
v6_address_bytes.length() != 16 ||
in.preferred_address->stateless_reset_token.size() !=
kStatelessResetTokenLength) {
QUIC_BUG(quic_bug_10743_12)
<< "Bad lengths " << *in.preferred_address;
return false;
}
const uint64_t preferred_address_length =
v4_address_bytes.length() + sizeof(uint16_t) +
v6_address_bytes.length() + sizeof(uint16_t) +
sizeof(uint8_t) +
in.preferred_address->connection_id.length() +
in.preferred_address->stateless_reset_token.size();
if (!writer.WriteVarInt62(TransportParameters::kPreferredAddress) ||
!writer.WriteVarInt62(
preferred_address_length) ||
!writer.WriteStringPiece(v4_address_bytes) ||
!writer.WriteUInt16(
in.preferred_address->ipv4_socket_address.port()) ||
!writer.WriteStringPiece(v6_address_bytes) ||
!writer.WriteUInt16(
in.preferred_address->ipv6_socket_address.port()) ||
!writer.WriteUInt8(
in.preferred_address->connection_id.length()) ||
!writer.WriteBytes(
in.preferred_address->connection_id.data(),
in.preferred_address->connection_id.length()) ||
!writer.WriteBytes(
in.preferred_address->stateless_reset_token.data(),
in.preferred_address->stateless_reset_token.size())) {
QUIC_BUG(Failed to write preferred_address)
<< "Failed to write preferred_address for " << in;
return false;
}
}
} break;
case TransportParameters::kInitialSourceConnectionId: {
if (in.initial_source_connection_id.has_value()) {
QuicConnectionId initial_source_connection_id =
*in.initial_source_connection_id;
if (!writer.WriteVarInt62(
TransportParameters::kInitialSourceConnectionId) ||
!writer.WriteStringPieceVarInt62(
absl::string_view(initial_source_connection_id.data(),
initial_source_connection_id.length()))) {
QUIC_BUG(Failed to write initial_source_connection_id)
<< "Failed to write initial_source_connection_id "
<< initial_source_connection_id << " for " << in;
return false;
}
}
} break;
case TransportParameters::kRetrySourceConnectionId: {
if (in.retry_source_connection_id.has_value()) {
QUICHE_DCHECK_EQ(Perspective::IS_SERVER, in.perspective);
QuicConnectionId retry_source_connection_id =
*in.retry_source_connection_id;
if (!writer.WriteVarInt62(
TransportParameters::kRetrySourceConnectionId) ||
!writer.WriteStringPieceVarInt62(
absl::string_view(retry_source_connection_id.data(),
retry_source_connection_id.length()))) {
QUIC_BUG(Failed to write retry_source_connection_id)
<< "Failed to write retry_source_connection_id "
<< retry_source_connection_id << " for " << in;
return false;
}
}
} break;
case TransportParameters::kGoogleConnectionOptions: {
if (in.google_connection_options.has_value()) {
static_assert(sizeof(in.google_connection_options->front()) == 4,
"bad size");
uint64_t connection_options_length =
in.google_connection_options->size() * 4;
if (!writer.WriteVarInt62(
TransportParameters::kGoogleConnectionOptions) ||
!writer.WriteVarInt62(
connection_options_length)) {
QUIC_BUG(Failed to write google_connection_options)
<< "Failed to write google_connection_options of length "
<< connection_options_length << " for " << in;
return false;
}
for (const QuicTag& connection_option :
*in.google_connection_options) {
if (!writer.WriteTag(connection_option)) {
QUIC_BUG(Failed to write google_connection_option)
<< "Failed to write google_connection_option "
<< QuicTagToString(connection_option) << " for " << in;
return false;
}
}
}
} break;
case TransportParameters::kGoogleQuicVersion: {
if (!in.legacy_version_information.has_value()) {
break;
}
static_assert(sizeof(QuicVersionLabel) == sizeof(uint32_t),
"bad length");
uint64_t google_version_length =
sizeof(in.legacy_version_information->version);
if (in.perspective == Perspective::IS_SERVER) {
google_version_length +=
sizeof(uint8_t) +
sizeof(QuicVersionLabel) *
in.legacy_version_information->supported_versions.size();
}
if (!writer.WriteVarInt62(TransportParameters::kGoogleQuicVersion) ||
!writer.WriteVarInt62(
google_version_length) ||
!writer.WriteUInt32(in.legacy_version_information->version)) {
QUIC_BUG(Failed to write Google version extension)
<< "Failed to write Google version extension for " << in;
return false;
}
if (in.perspective == Perspective::IS_SERVER) {
if (!writer.WriteUInt8(
sizeof(QuicVersionLabel) *
in.legacy_version_information->supported_versions.size())) {
QUIC_BUG(Failed to write versions length)
<< "Failed to write versions length for " << in;
return false;
}
for (QuicVersionLabel version_label :
in.legacy_version_information->supported_versions) {
if (!writer.WriteUInt32(version_label)) {
QUIC_BUG(Failed to write supported version)
<< "Failed to write supported version for " << in;
return false;
}
}
}
} break;
case TransportParameters::kVersionInformation: {
if (!in.version_information.has_value()) {
break;
}
static_assert(sizeof(QuicVersionLabel) == sizeof(uint32_t),
"bad length");
QuicVersionLabelVector other_versions =
in.version_information->other_versions;
const size_t grease_index =
random->InsecureRandUint64() % (other_versions.size() + 1);
other_versions.insert(
other_versions.begin() + grease_index,
CreateQuicVersionLabel(QuicVersionReservedForNegotiation()));
const uint64_t version_information_length =
sizeof(in.version_information->chosen_version) +
sizeof(QuicVersionLabel) * other_versions.size();
if (!writer.WriteVarInt62(TransportParameters::kVersionInformation) ||
!writer.WriteVarInt62(
version_information_length) ||
!writer.WriteUInt32(in.version_information->chosen_version)) {
QUIC_BUG(Failed to write chosen version)
<< "Failed to write chosen version for " << in;
return false;
}
for (QuicVersionLabel version_label : other_versions) {
if (!writer.WriteUInt32(version_label)) {
QUIC_BUG(Failed to write other version)
<< "Failed to write other version for " << in;
return false;
}
}
} break;
default: {
auto it = custom_parameters.find(parameter_id);
if (it == custom_parameters.end()) {
QUIC_BUG(Unknown parameter) << "Unknown parameter " << parameter_id;
return false;
}
if (!writer.WriteVarInt62(parameter_id) ||
!writer.WriteStringPieceVarInt62(it->second)) {
QUIC_BUG(Failed to write custom parameter)
<< "Failed to write custom parameter " << parameter_id;
return false;
}
} break;
}
}
out->resize(writer.length());
QUIC_DLOG(INFO) << "Serialized " << in << " as " << writer.length()
<< " bytes";
return true;
}
bool ParseTransportParameters(ParsedQuicVersion version,
Perspective perspective, const uint8_t* in,
size_t in_len, TransportParameters* out,
std::string* error_details) {
out->perspective = perspective;
QuicDataReader reader(reinterpret_cast<const char*>(in), in_len);
while (!reader.IsDoneReading()) {
uint64_t param_id64;
if (!reader.ReadVarInt62(¶m_id64)) {
*error_details = "Failed to parse transport parameter ID";
return false;
}
TransportParameters::TransportParameterId param_id =
static_cast<TransportParameters::TransportParameterId>(param_id64);
absl::string_view value;
if (!reader.ReadStringPieceVarInt62(&value)) {
*error_details =
"Failed to read length and value of transport parameter " +
TransportParameterIdToString(param_id);
return false;
}
QuicDataReader value_reader(value);
bool parse_success = true;
switch (param_id) {
case TransportParameters::kOriginalDestinationConnectionId: {
if (out->original_destination_connection_id.has_value()) {
*error_details =
"Received a second original_destination_connection_id";
return false;
}
const size_t connection_id_length = value_reader.BytesRemaining();
if (!QuicUtils::IsConnectionIdLengthValidForVersion(
connection_id_length, version.transport_version)) {
*error_details = absl::StrCat(
"Received original_destination_connection_id of invalid length ",
connection_id_length);
return false;
}
QuicConnectionId original_destination_connection_id;
if (!value_reader.ReadConnectionId(&original_destination_connection_id,
connection_id_length)) {
*error_details = "Failed to read original_destination_connection_id";
return false;
}
out->original_destination_connection_id =
original_destination_connection_id;
} break;
case TransportParameters::kMaxIdleTimeout:
parse_success =
out->max_idle_timeout_ms.Read(&value_reader, error_details);
break;
case TransportParameters::kStatelessResetToken: {
if (!out->stateless_reset_token.empty()) {
*error_details = "Received a second stateless_reset_token";
return false;
}
absl::string_view stateless_reset_token =
value_reader.ReadRemainingPayload();
if (stateless_reset_token.length() != kStatelessResetTokenLength) {
*error_details =
absl::StrCat("Received stateless_reset_token of invalid length ",
stateless_reset_token.length());
return false;
}
out->stateless_reset_token.assign(
stateless_reset_token.data(),
stateless_reset_token.data() + stateless_reset_token.length());
} break;
case TransportParameters::kMaxPacketSize:
parse_success =
out->max_udp_payload_size.Read(&value_reader, error_details);
break;
case TransportParameters::kInitialMaxData:
parse_success =
out->initial_max_data.Read(&value_reader, error_details);
break;
case TransportParameters::kInitialMaxStreamDataBidiLocal:
parse_success = out->initial_max_stream_data_bidi_local.Read(
&value_reader, error_details);
break;
case TransportParameters::kInitialMaxStreamDataBidiRemote:
parse_success = out->initial_max_stream_data_bidi_remote.Read(
&value_reader, error_details);
break;
case TransportParameters::kInitialMaxStreamDataUni:
parse_success =
out->initial_max_stream_data_uni.Read(&value_reader, error_details);
break;
case TransportParameters::kInitialMaxStreamsBidi:
parse_success =
out->initial_max_streams_bidi.Read(&value_reader, error_details);
break;
case TransportParameters::kInitialMaxStreamsUni:
parse_success =
out->initial_max_streams_uni.Read(&value_reader, error_details);
break;
case TransportParameters::kAckDelayExponent:
parse_success =
out->ack_delay_exponent.Read(&value_reader, error_details);
break;
case TransportParameters::kMaxAckDelay:
parse_success = out->max_ack_delay.Read(&value_reader, error_details);
break;
case TransportParameters::kDisableActiveMigration:
if (out->disable_active_migration) {
*error_details = "Received a second disable_active_migration";
return false;
}
out->disable_active_migration = true;
break;
case TransportParameters::kPreferredAddress: {
TransportParameters::PreferredAddress preferred_address;
uint16_t ipv4_port, ipv6_port;
in_addr ipv4_address;
in6_addr ipv6_address;
preferred_address.stateless_reset_token.resize(
kStatelessResetTokenLength);
if (!value_reader.ReadBytes(&ipv4_address, sizeof(ipv4_address)) ||
!value_reader.ReadUInt16(&ipv4_port) ||
!value_reader.ReadBytes(&ipv6_address, sizeof(ipv6_address)) ||
!value_reader.ReadUInt16(&ipv6_port) ||
!value_reader.ReadLengthPrefixedConnectionId(
&preferred_address.connection_id) ||
!value_reader.ReadBytes(&preferred_address.stateless_reset_token[0],
kStatelessResetTokenLength)) {
*error_details = "Failed to read preferred_address";
return false;
}
preferred_address.ipv4_socket_address =
QuicSocketAddress(QuicIpAddress(ipv4_address), ipv4_port);
preferred_address.ipv6_socket_address =
QuicSocketAddress(QuicIpAddress(ipv6_address), ipv6_port);
if (!preferred_address.ipv4_socket_address.host().IsIPv4() ||
!preferred_address.ipv6_socket_address.host().IsIPv6()) {
*error_details = "Received preferred_address of bad families " +
preferred_address.ToString();
return false;
}
if (!QuicUtils::IsConnectionIdValidForVersion(
preferred_address.connection_id, version.transport_version)) {
*error_details = "Received invalid preferred_address connection ID " +
preferred_address.ToString();
return false;
}
out->preferred_address =
std::make_unique<TransportParameters::PreferredAddress>(
preferred_address);
} break;
case TransportParameters::kActiveConnectionIdLimit:
parse_success =
out->active_connection_id_limit.Read(&value_reader, error_details);
break;
case TransportParameters::kInitialSourceConnectionId: {
if (out->initial_source_connection_id.has_value()) {
*error_details = "Received a second initial_source_connection_id";
return false;
}
const size_t connection_id_length = value_reader.BytesRemaining();
if (!QuicUtils::IsConnectionIdLengthValidForVersion(
connection_id_length, version.transport_version)) {
*error_details = absl::StrCat(
"Received initial_source_connection_id of invalid length ",
connection_id_length);
return false;
}
QuicConnectionId initial_source_connection_id;
if (!value_reader.ReadConnectionId(&initial_source_connection_id,
connection_id_length)) {
*error_details = "Failed to read initial_source_connection_id";
return false;
}
out->initial_source_connection_id = initial_source_connection_id;
} break;
case TransportParameters::kRetrySourceConnectionId: {
if (out->retry_source_connection_id.has_value()) {
*error_details = "Received a second retry_source_connection_id";
return false;
}
const size_t connection_id_length = value_reader.BytesRemaining();
if (!QuicUtils::IsConnectionIdLengthValidForVersion(
connection_id_length, version.transport_version)) {
*error_details = absl::StrCat(
"Received retry_source_connection_id of invalid length ",
connection_id_length);
return false;
}
QuicConnectionId retry_source_connection_id;
if (!value_reader.ReadConnectionId(&retry_source_connection_id,
connection_id_length)) {
*error_details = "Failed to read retry_source_connection_id";
return false;
}
out->retry_source_connection_id = retry_source_connection_id;
} break;
case TransportParameters::kMaxDatagramFrameSize:
parse_success =
out->max_datagram_frame_size.Read(&value_reader, error_details);
break;
case TransportParameters::kGoogleHandshakeMessage:
if (out->google_handshake_message.has_value()) {
*error_details = "Received a second google_handshake_message";
return false;
}
out->google_handshake_message =
std::string(value_reader.ReadRemainingPayload());
break;
case TransportParameters::kInitialRoundTripTime:
parse_success =
out->initial_round_trip_time_us.Read(&value_reader, error_details);
break;
case TransportParameters::kReliableStreamReset:
if (out->reliable_stream_reset) {
*error_details = "Received a second reliable_stream_reset";
return false;
}
out->reliable_stream_reset = true;
break;
case TransportParameters::kGoogleConnectionOptions: {
if (out->google_connection_options.has_value()) {
*error_details = "Received a second google_connection_options";
return false;
}
out->google_connection_options = QuicTagVector{};
while (!value_reader.IsDoneReading()) {
QuicTag connection_option;
if (!value_reader.ReadTag(&connection_option)) {
*error_details = "Failed to read a google_connection_options";
return false;
}
out->google_connection_options->push_back(connection_option);
}
} break;
case TransportParameters::kGoogleQuicVersion: {
if (!out->legacy_version_information.has_value()) {
out->legacy_version_information =
TransportParameters::LegacyVersionInformation();
}
if (!value_reader.ReadUInt32(
&out->legacy_version_information->version)) {
*error_details = "Failed to read Google version extension version";
return false;
}
if (perspective == Perspective::IS_SERVER) {
uint8_t versions_length;
if (!value_reader.ReadUInt8(&versions_length)) {
*error_details = "Failed to parse Google supported versions length";
return false;
}
const uint8_t num_versions = versions_length / sizeof(uint32_t);
for (uint8_t i = 0; i < num_versions; ++i) {
QuicVersionLabel parsed_version;
if (!value_reader.ReadUInt32(&parsed_version)) {
*error_details = "Failed to parse Google supported version";
return false;
}
out->legacy_version_information->supported_versions.push_back(
parsed_version);
}
}
} break;
case TransportParameters::kVersionInformation: {
if (out->version_information.has_value()) {
*error_details = "Received a second version_information";
return false;
}
out->version_information = TransportParameters::VersionInformation();
if (!value_reader.ReadUInt32(
&out->version_information->chosen_version)) {
*error_details = "Failed to read chosen version";
return false;
}
while (!value_reader.IsDoneReading()) {
QuicVersionLabel other_version;
if (!value_reader.ReadUInt32(&other_version)) {
*error_details = "Failed to parse other version";
return false;
}
out->version_information->other_versions.push_back(other_version);
}
} break;
case TransportParameters::kMinAckDelay:
parse_success =
out->min_ack_delay_us.Read(&value_reader, error_details);
break;
default:
if (out->custom_parameters.find(param_id) !=
out->custom_parameters.end()) {
*error_details = "Received a second unknown parameter" +
TransportParameterIdToString(param_id);
return false;
}
out->custom_parameters[param_id] =
std::string(value_reader.ReadRemainingPayload());
break;
}
if (!parse_success) {
QUICHE_DCHECK(!error_details->empty());
return false;
}
if (!value_reader.IsDoneReading()) {
*error_details = absl::StrCat(
"Received unexpected ", value_reader.BytesRemaining(),
" bytes after parsing ", TransportParameterIdToString(param_id));
return false;
}
}
if (!out->AreValid(error_details)) {
QUICHE_DCHECK(!error_details->empty());
return false;
}
QUIC_DLOG(INFO) << "Parsed transport parameters " << *out << " from "
<< in_len << " bytes";
return true;
}
namespace {
bool DigestUpdateIntegerParam(
EVP_MD_CTX* hash_ctx, const TransportParameters::IntegerParameter& param) {
uint64_t value = param.value();
return EVP_DigestUpdate(hash_ctx, &value, sizeof(value));
}
}
bool SerializeTransportParametersForTicket(
const TransportParameters& in, const std::vector<uint8_t>& application_data,
std::vector<uint8_t>* out) {
std::string error_details;
if (!in.AreValid(&error_details)) {
QUIC_BUG(quic_bug_10743_26)
<< "Not serializing invalid transport parameters: " << error_details;
return false;
}
out->resize(SHA256_DIGEST_LENGTH + 1);
const uint8_t serialization_version = 0;
(*out)[0] = serialization_version;
bssl::ScopedEVP_MD_CTX hash_ctx;
uint64_t app_data_len = application_data.size();
const uint64_t parameter_version = 0;
if (!EVP_DigestInit(hash_ctx.get(), EVP_sha256()) ||
!EVP_DigestUpdate(hash_ctx.get(), &app_data_len, sizeof(app_data_len)) ||
!EVP_DigestUpdate(hash_ctx.get(), application_data.data(),
application_data.size()) ||
!EVP_DigestUpdate(hash_ctx.get(), ¶meter_version,
sizeof(parameter_version))) {
QUIC_BUG(quic_bug_10743_27)
<< "Unexpected failure of EVP_Digest functions when hashing "
"Transport Parameters for ticket";
return false;
}
if (!DigestUpdateIntegerParam(hash_ctx.get(), in.initial_max_data) ||
!DigestUpdateIntegerParam(hash_ctx.get(),
in.initial_max_stream_data_bidi_local) ||
!DigestUpdateIntegerParam(hash_ctx.get(),
in.initial_max_stream_data_bidi_remote) ||
!DigestUpdateIntegerParam(hash_ctx.get(),
in.initial_max_stream_data_uni) ||
!DigestUpdateIntegerParam(hash_ctx.get(), in.initial_max_streams_bidi) ||
!DigestUpdateIntegerParam(hash_ctx.get(), in.initial_max_streams_uni) ||
!DigestUpdateIntegerParam(hash_ctx.get(),
in.active_connection_id_limit)) {
QUIC_BUG(quic_bug_10743_28)
<< "Unexpected failure of EVP_Digest functions when hashing "
"Transport Parameters for ticket";
return false;
}
uint8_t disable_active_migration = in.disable_active_migration ? 1 : 0;
uint8_t reliable_stream_reset = in.reliable_stream_reset ? 1 : 0;
if (!EVP_DigestUpdate(hash_ctx.get(), &disable_active_migration,
sizeof(disable_active_migration)) ||
(reliable_stream_reset &&
!EVP_DigestUpdate(hash_ctx.get(), "ResetStreamAt", 13)) ||
!EVP_DigestFinal(hash_ctx.get(), out->data() + 1, nullptr)) {
QUIC_BUG(quic_bug_10743_29)
<< "Unexpected failure of EVP_Digest functions when hashing "
"Transport Parameters for ticket";
return false;
}
return true;
}
void DegreaseTransportParameters(TransportParameters& parameters) {
for (auto it = parameters.custom_parameters.begin();
it != parameters.custom_parameters.end();
) {
if (it->first % 31 == 27) {
parameters.custom_parameters.erase(it++);
} else {
++it;
}
}
if (parameters.version_information.has_value()) {
QuicVersionLabelVector clean_versions;
for (QuicVersionLabel version :
parameters.version_information->other_versions) {
if ((version & kReservedVersionMask) != kReservedVersionBits) {
clean_versions.push_back(version);
}
}
parameters.version_information->other_versions = std::move(clean_versions);
}
}
} | #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 bool kFakeReliableStreamReset = 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;
orig_params.reliable_stream_reset = true;
new_params.reliable_stream_reset = 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.reliable_stream_reset = kFakeReliableStreamReset;
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.reliable_stream_reset = kFakeReliableStreamReset;
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.reliable_stream_reset = kFakeReliableStreamReset;
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,
0xc0, 0x17, 0xf7, 0x58, 0x6d, 0x2c, 0xb5, 0x71,
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(kFakeReliableStreamReset, new_params.reliable_stream_reset);
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,
0xc0, 0x17, 0xf7, 0x58, 0x6d, 0x2c, 0xb5, 0x71,
0x00,
0x0d,
0x31,
0x41, 0x42, 0x43, 0x44,
0x48, 0x84,
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f,
0x63, 0x36,
0x08,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBE, 0xEF,
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F,
0x0e,
0x01,
0x34,
0x0f,
0x08,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x23, 0x45,
0x10,
0x08,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x98, 0x76,
0x71, 0x28,
0x0c,
'A', 'L', 'P', 'N',
'E', 'F', 'G', 0x00,
'H', 'I', 'J', 0xff,
0x80, 0x00, 0x47, 0x52,
0x0d,
0x01, 0x23, 0x45, 0x67,
0x08,
0x01, 0x23, 0x45, 0x67,
0x89, 0xab, 0xcd, 0xef,
0x80, 0xFF, 0x73, 0xDB,
0x0C,
0x01, 0x23, 0x45, 0x67,
0x01, 0x23, 0x45, 0x67,
0x89, 0xab, 0xcd, 0xef,
};
const uint8_t* server_params =
reinterpret_cast<const uint8_t*>(kServerParams);
size_t server_params_length = ABSL_ARRAYSIZE(kServerParams);
TransportParameters new_params;
std::string error_details;
ASSERT_TRUE(ParseTransportParameters(version_, Perspective::IS_SERVER,
server_params, server_params_length,
&new_params, &error_details))
<< error_details;
EXPECT_TRUE(error_details.empty());
EXPECT_EQ(Perspective::IS_SERVER, new_params.perspective);
ASSERT_TRUE(new_params.legacy_version_information.has_value());
EXPECT_EQ(kFakeVersionLabel,
new_params.legacy_version_information.value().version);
ASSERT_EQ(
2u,
new_params.legacy_version_information.value().supported_versions.size());
EXPECT_EQ(
kFakeVersionLabel,
new_params.legacy_version_information.value().supported_versions[0]);
EXPECT_EQ(
kFakeVersionLabel2,
new_params.legacy_version_information.value().supported_versions[1]);
ASSERT_TRUE(new_params.version_information.has_value());
EXPECT_EQ(new_params.version_information.value(),
CreateFakeVersionInformation());
ASSERT_TRUE(new_params.original_destination_connection_id.has_value());
EXPECT_EQ(CreateFakeOriginalDestinationConnectionId(),
new_params.original_destination_connection_id.value());
EXPECT_EQ(kFakeIdleTimeoutMilliseconds,
new_params.max_idle_timeout_ms.value());
EXPECT_EQ(CreateStatelessResetTokenForTest(),
new_params.stateless_reset_token);
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(kFakeReliableStreamReset, new_params.reliable_stream_reset);
ASSERT_NE(nullptr, new_params.preferred_address.get());
EXPECT_EQ(CreateFakeV4SocketAddress(),
new_params.preferred_address->ipv4_socket_address);
EXPECT_EQ(CreateFakeV6SocketAddress(),
new_params.preferred_address->ipv6_socket_address);
EXPECT_EQ(CreateFakePreferredConnectionId(),
new_params.preferred_address->connection_id);
EXPECT_EQ(CreateFakePreferredStatelessResetToken(),
new_params.preferred_address->stateless_reset_token);
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());
ASSERT_TRUE(new_params.retry_source_connection_id.has_value());
EXPECT_EQ(CreateFakeRetrySourceConnectionId(),
new_params.retry_source_connection_id.value());
ASSERT_TRUE(new_params.google_connection_options.has_value());
EXPECT_EQ(CreateFakeGoogleConnectionOptions(),
new_params.google_connection_options.value());
}
TEST_P(TransportParametersTest, ParseServerParametersRepeated) {
const uint8_t kServerParamsRepeated[] = {
0x00,
0x08,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0x37,
0x01,
0x02,
0x6e, 0xec,
0x02,
0x10,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
0x01,
0x02,
0x6e, 0xec,
};
const uint8_t* server_params =
reinterpret_cast<const uint8_t*>(kServerParamsRepeated);
size_t server_params_length = ABSL_ARRAYSIZE(kServerParamsRepeated);
TransportParameters out_params;
std::string error_details;
EXPECT_FALSE(ParseTransportParameters(version_, Perspective::IS_SERVER,
server_params, server_params_length,
&out_params, &error_details));
EXPECT_EQ(error_details, "Received a second max_idle_timeout");
}
TEST_P(TransportParametersTest,
ParseServerParametersEmptyOriginalConnectionId) {
const uint8_t kServerParamsEmptyOriginalConnectionId[] = {
0x00,
0x00,
0x01,
0x02,
0x6e, 0xec,
0x02,
0x10,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
};
const uint8_t* server_params =
reinterpret_cast<const uint8_t*>(kServerParamsEmptyOriginalConnectionId);
size_t server_params_length =
ABSL_ARRAYSIZE(kServerParamsEmptyOriginalConnectionId);
TransportParameters out_params;
std::string error_details;
ASSERT_TRUE(ParseTransportParameters(version_, Perspective::IS_SERVER,
server_params, server_params_length,
&out_params, &error_details))
<< error_details;
ASSERT_TRUE(out_params.original_destination_connection_id.has_value());
EXPECT_EQ(out_params.original_destination_connection_id.value(),
EmptyQuicConnectionId());
}
TEST_P(TransportParametersTest, VeryLongCustomParameter) {
std::string custom_value(70000, '?');
TransportParameters orig_params;
orig_params.perspective = Perspective::IS_CLIENT;
orig_params.legacy_version_information =
CreateFakeLegacyVersionInformationClient();
orig_params.custom_parameters[kCustomParameter1] = custom_value;
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, SerializationOrderIsRandom) {
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.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.reliable_stream_reset = kFakeReliableStreamReset;
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);
orig_params.google_connection_options = CreateFakeGoogleConnectionOptions();
orig_params.custom_parameters[kCustomParameter1] = kCustomParameter1Value;
orig_params.custom_parameters[kCustomParameter2] = kCustomParameter2Value;
std::vector<uint8_t> first_serialized;
ASSERT_TRUE(SerializeTransportParameters(orig_params, &first_serialized));
for (int i = 0; i < 1000; i++) {
std::vector<uint8_t> serialized;
ASSERT_TRUE(SerializeTransportParameters(orig_params, &serialized));
if (serialized != first_serialized) {
return;
}
}
}
TEST_P(TransportParametersTest, Degrease) {
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.reliable_stream_reset = kFakeReliableStreamReset;
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());
EXPECT_NE(new_params, orig_params);
DegreaseTransportParameters(new_params);
EXPECT_EQ(new_params, orig_params);
}
class TransportParametersTicketSerializationTest : public QuicTest {
protected:
void SetUp() override {
original_params_.perspective = Perspective::IS_SERVER;
original_params_.legacy_version_information =
CreateFakeLegacyVersionInformationServer();
original_params_.original_destination_connection_id =
CreateFakeOriginalDestinationConnectionId();
original_params_.max_idle_timeout_ms.set_value(
kFakeIdleTimeoutMilliseconds);
original_params_.stateless_reset_token = CreateStatelessResetTokenForTest();
original_params_.max_udp_payload_size.set_value(kMaxPacketSizeForTest);
original_params_.initial_max_data.set_value(kFakeInitialMaxData);
original_params_.initial_max_stream_data_bidi_local.set_value(
kFakeInitialMaxStreamDataBidiLocal);
original_params_.initial_max_stream_data_bidi_remote.set_value(
kFakeInitialMaxStreamDataBidiRemote);
original_params_.initial_max_stream_data_uni.set_value(
kFakeInitialMaxStreamDataUni);
original_params_.initial_max_streams_bidi.set_value(
kFakeInitialMaxStreamsBidi);
original_params_.initial_max_streams_uni.set_value(
kFakeInitialMaxStreamsUni);
original_params_.ack_delay_exponent.set_value(kAckDelayExponentForTest);
original_params_.max_ack_delay.set_value(kMaxAckDelayForTest);
original_params_.min_ack_delay_us.set_value(kMinAckDelayUsForTest);
original_params_.disable_active_migration = kFakeDisableMigration;
original_params_.reliable_stream_reset = kFakeReliableStreamReset;
original_params_.preferred_address = CreateFakePreferredAddress();
original_params_.active_connection_id_limit.set_value(
kActiveConnectionIdLimitForTest);
original_params_.initial_source_connection_id =
CreateFakeInitialSourceConnectionId();
original_params_.retry_source_connection_id =
CreateFakeRetrySourceConnectionId();
original_params_.google_connection_options =
CreateFakeGoogleConnectionOptions();
ASSERT_TRUE(SerializeTransportParametersForTicket(
original_params_, application_state_, &original_serialized_params_));
}
TransportParameters original_params_;
std::vector<uint8_t> application_state_ = {0, 1};
std::vector<uint8_t> original_serialized_params_;
};
TEST_F(TransportParametersTicketSerializationTest,
StatelessResetTokenDoesntChangeOutput) {
TransportParameters new_params = original_params_;
new_params.stateless_reset_token = CreateFakePreferredStatelessResetToken();
EXPECT_NE(new_params, original_params_);
std::vector<uint8_t> serialized;
ASSERT_TRUE(SerializeTransportParametersForTicket(
new_params, application_state_, &serialized));
EXPECT_EQ(original_serialized_params_, serialized);
}
TEST_F(TransportParametersTicketSerializationTest,
ConnectionIDDoesntChangeOutput) {
TransportParameters new_params = original_params_;
new_params.original_destination_connection_id = TestConnectionId(0xCAFE);
EXPECT_NE(new_params, original_params_);
std::vector<uint8_t> serialized;
ASSERT_TRUE(SerializeTransportParametersForTicket(
new_params, application_state_, &serialized));
EXPECT_EQ(original_serialized_params_, serialized);
}
TEST_F(TransportParametersTicketSerializationTest, StreamLimitChangesOutput) {
TransportParameters new_params = original_params_;
new_params.initial_max_stream_data_bidi_local.set_value(
kFakeInitialMaxStreamDataBidiLocal + 1);
EXPECT_NE(new_params, original_params_);
std::vector<uint8_t> serialized;
ASSERT_TRUE(SerializeTransportParametersForTicket(
new_params, application_state_, &serialized));
EXPECT_NE(original_serialized_params_, serialized);
}
TEST_F(TransportParametersTicketSerializationTest,
ApplicationStateChangesOutput) {
std::vector<uint8_t> new_application_state = {0};
EXPECT_NE(new_application_state, application_state_);
std::vector<uint8_t> serialized;
ASSERT_TRUE(SerializeTransportParametersForTicket(
original_params_, new_application_state, &serialized));
EXPECT_NE(original_serialized_params_, serialized);
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/transport_parameters.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/transport_parameters_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
a3142451-cf72-41ab-8269-ae2f5d405d40 | cpp | google/quiche | certificate_util | quiche/quic/core/crypto/certificate_util.cc | quiche/quic/core/crypto/certificate_util_test.cc | #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));
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/certificate_util.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/certificate_util_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
0ededd8e-de7b-4c1d-bda1-bcfd77a634ba | cpp | google/quiche | crypto_handshake_message | quiche/quic/core/crypto/crypto_handshake_message.cc | quiche/quic/core/crypto/crypto_handshake_message_test.cc | #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));
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/crypto_handshake_message.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/crypto_handshake_message_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
c3df8637-01b3-4e20-ace3-b31228f0bd1f | cpp | google/quiche | client_proof_source | quiche/quic/core/crypto/client_proof_source.cc | quiche/quic/core/crypto/client_proof_source_test.cc | #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);
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/client_proof_source.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/client_proof_source_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
535afe38-1169-49f7-af7c-0d9f4af30529 | cpp | google/quiche | chacha20_poly1305_decrypter | quiche/quic/core/crypto/chacha20_poly1305_decrypter.cc | quiche/quic/core/crypto/chacha20_poly1305_decrypter_test.cc | #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());
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/chacha20_poly1305_decrypter.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/chacha20_poly1305_decrypter_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
00a55dbb-ab9f-464d-a180-889b68767656 | 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 | #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));
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/aes_128_gcm_12_encrypter.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/aes_128_gcm_12_encrypter_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
487f752b-f305-4937-9f9c-1fd877b6d512 | 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 | #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());
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/chacha20_poly1305_tls_encrypter.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/chacha20_poly1305_tls_encrypter_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
bbf401b8-740f-4cd0-9b82-b7205cea4db8 | cpp | google/quiche | null_encrypter | quiche/quic/core/crypto/null_encrypter.cc | quiche/quic/core/crypto/null_encrypter_test.cc | #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));
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/null_encrypter.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/null_encrypter_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
e7b0f0bb-323d-400b-9b81-1cbad95102df | cpp | google/quiche | channel_id | quiche/quic/core/crypto/channel_id.cc | quiche/quic/core/crypto/channel_id_test.cc | #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));
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/channel_id.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/channel_id_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
044f3244-444c-4c46-bd49-7ff09be2cf0e | 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 | #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());
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/aes_128_gcm_encrypter.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/aes_128_gcm_encrypter_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
3beedbbb-f1a8-4a93-bcca-28005e3b2a6e | 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 | #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"}));
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/web_transport_fingerprint_proof_verifier.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/web_transport_fingerprint_proof_verifier_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
e7d29cc8-d376-428f-885c-1b55d95cf820 | 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 | #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));
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/quic_compressed_certs_cache.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/quic_compressed_certs_cache_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
e7cfed3b-83f7-4d25-964a-912339d32c32 | 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 | #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());
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/aes_256_gcm_encrypter.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/aes_256_gcm_encrypter_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
5fe37cdb-4572-49d7-8a2a-00bf0f3af8ef | 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 | #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());
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/quic_client_session_cache.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/quic_client_session_cache_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
213a7c82-6f11-4429-9428-dd1bc9636c7c | cpp | google/quiche | certificate_view | quiche/quic/core/crypto/certificate_view.cc | quiche/quic/core/crypto/certificate_view_test.cc | #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, ¬_before, ¬_before_tag) ||
!CBS_get_any_asn1(&validity, ¬_after, ¬_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);
}
}
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/certificate_view.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/certificate_view_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
fb25460a-918c-4ca3-b138-5b2aa44d6b57 | cpp | google/quiche | crypto_framer | quiche/quic/core/crypto/crypto_framer.cc | quiche/quic/core/crypto/crypto_framer_test.cc | #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_);
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/crypto_framer.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/crypto_framer_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
1b8bdcc1-21e7-4a3e-8266-111b382e0bdf | 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 | #include "quiche/quic/core/crypto/quic_crypto_server_config.h"
#include <algorithm>
#include <cstdlib>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "absl/base/attributes.h"
#include "absl/strings/escaping.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "openssl/sha.h"
#include "openssl/ssl.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/cert_compressor.h"
#include "quiche/quic/core/crypto/certificate_view.h"
#include "quiche/quic/core/crypto/chacha20_poly1305_encrypter.h"
#include "quiche/quic/core/crypto/channel_id.h"
#include "quiche/quic/core/crypto/crypto_framer.h"
#include "quiche/quic/core/crypto/crypto_handshake_message.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_source.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/crypto/tls_server_connection.h"
#include "quiche/quic/core/proto/crypto_server_config_proto.h"
#include "quiche/quic/core/proto/source_address_token_proto.h"
#include "quiche/quic/core/quic_clock.h"
#include "quiche/quic/core/quic_connection_context.h"
#include "quiche/quic/core/quic_packets.h"
#include "quiche/quic/core/quic_socket_address_coder.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_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_testvalue.h"
#include "quiche/common/platform/api/quiche_reference_counted.h"
namespace quic {
namespace {
const size_t kMultiplier = 3;
const int kMaxTokenAddresses = 4;
std::string DeriveSourceAddressTokenKey(
absl::string_view source_address_token_secret) {
QuicHKDF hkdf(source_address_token_secret, absl::string_view() ,
"QUIC source address token key",
CryptoSecretBoxer::GetKeySize(), 0 ,
0 );
return std::string(hkdf.server_write_key());
}
class DefaultKeyExchangeSource : public KeyExchangeSource {
public:
DefaultKeyExchangeSource() = default;
~DefaultKeyExchangeSource() override = default;
std::unique_ptr<AsynchronousKeyExchange> Create(
std::string , bool , QuicTag type,
absl::string_view private_key) override {
if (private_key.empty()) {
QUIC_LOG(WARNING) << "Server config contains key exchange method without "
"corresponding private key of type "
<< QuicTagToString(type);
return nullptr;
}
std::unique_ptr<SynchronousKeyExchange> ka =
CreateLocalSynchronousKeyExchange(type, private_key);
if (!ka) {
QUIC_LOG(WARNING) << "Failed to create key exchange method of type "
<< QuicTagToString(type);
}
return ka;
}
};
bool ClientDemandsX509Proof(const CryptoHandshakeMessage& client_hello) {
QuicTagVector their_proof_demands;
if (client_hello.GetTaglist(kPDMD, &their_proof_demands) != QUIC_NO_ERROR) {
return false;
}
for (const QuicTag tag : their_proof_demands) {
if (tag == kX509) {
return true;
}
}
return false;
}
std::string FormatCryptoHandshakeMessageForTrace(
const CryptoHandshakeMessage* message) {
if (message == nullptr) {
return "<null message>";
}
std::string s = QuicTagToString(message->tag());
if (const auto it = message->tag_value_map().find(kRREJ);
it != message->tag_value_map().end()) {
const std::string& value = it->second;
if (value.size() % sizeof(uint32_t) == 0) {
absl::StrAppend(&s, " RREJ:[");
for (size_t j = 0; j < value.size(); j += sizeof(uint32_t)) {
uint32_t reason;
memcpy(&reason, value.data() + j, sizeof(reason));
if (j > 0) {
absl::StrAppend(&s, ",");
}
absl::StrAppend(&s, CryptoUtils::HandshakeFailureReasonToString(
static_cast<HandshakeFailureReason>(reason)));
}
absl::StrAppend(&s, "]");
} else {
absl::StrAppendFormat(&s, " RREJ:[unexpected length:%u]", value.size());
}
}
return s;
}
}
std::unique_ptr<KeyExchangeSource> KeyExchangeSource::Default() {
return std::make_unique<DefaultKeyExchangeSource>();
}
class ValidateClientHelloHelper {
public:
ValidateClientHelloHelper(
quiche::QuicheReferenceCountedPointer<
ValidateClientHelloResultCallback::Result>
result,
std::unique_ptr<ValidateClientHelloResultCallback>* done_cb)
: result_(std::move(result)), done_cb_(done_cb) {}
ValidateClientHelloHelper(const ValidateClientHelloHelper&) = delete;
ValidateClientHelloHelper& operator=(const ValidateClientHelloHelper&) =
delete;
~ValidateClientHelloHelper() {
QUIC_BUG_IF(quic_bug_12963_1, done_cb_ != nullptr)
<< "Deleting ValidateClientHelloHelper with a pending callback.";
}
void ValidationComplete(
QuicErrorCode error_code, const char* error_details,
std::unique_ptr<ProofSource::Details> proof_source_details) {
result_->error_code = error_code;
result_->error_details = error_details;
(*done_cb_)->Run(std::move(result_), std::move(proof_source_details));
DetachCallback();
}
void DetachCallback() {
QUIC_BUG_IF(quic_bug_10630_1, done_cb_ == nullptr)
<< "Callback already detached.";
done_cb_ = nullptr;
}
private:
quiche::QuicheReferenceCountedPointer<
ValidateClientHelloResultCallback::Result>
result_;
std::unique_ptr<ValidateClientHelloResultCallback>* done_cb_;
};
const char QuicCryptoServerConfig::TESTING[] = "secret string for testing";
ClientHelloInfo::ClientHelloInfo(const QuicIpAddress& in_client_ip,
QuicWallTime in_now)
: client_ip(in_client_ip), now(in_now), valid_source_address_token(false) {}
ClientHelloInfo::ClientHelloInfo(const ClientHelloInfo& other) = default;
ClientHelloInfo::~ClientHelloInfo() {}
PrimaryConfigChangedCallback::PrimaryConfigChangedCallback() {}
PrimaryConfigChangedCallback::~PrimaryConfigChangedCallback() {}
ValidateClientHelloResultCallback::Result::Result(
const CryptoHandshakeMessage& in_client_hello, QuicIpAddress in_client_ip,
QuicWallTime in_now)
: client_hello(in_client_hello),
info(in_client_ip, in_now),
error_code(QUIC_NO_ERROR) {}
ValidateClientHelloResultCallback::Result::~Result() {}
ValidateClientHelloResultCallback::ValidateClientHelloResultCallback() {}
ValidateClientHelloResultCallback::~ValidateClientHelloResultCallback() {}
ProcessClientHelloResultCallback::ProcessClientHelloResultCallback() {}
ProcessClientHelloResultCallback::~ProcessClientHelloResultCallback() {}
QuicCryptoServerConfig::ConfigOptions::ConfigOptions()
: expiry_time(QuicWallTime::Zero()),
channel_id_enabled(false),
p256(false) {}
QuicCryptoServerConfig::ConfigOptions::ConfigOptions(
const ConfigOptions& other) = default;
QuicCryptoServerConfig::ConfigOptions::~ConfigOptions() {}
QuicCryptoServerConfig::ProcessClientHelloContext::
~ProcessClientHelloContext() {
if (done_cb_ != nullptr) {
QUIC_LOG(WARNING)
<< "Deleting ProcessClientHelloContext with a pending callback.";
}
}
void QuicCryptoServerConfig::ProcessClientHelloContext::Fail(
QuicErrorCode error, const std::string& error_details) {
QUIC_TRACEPRINTF("ProcessClientHello failed: error=%s, details=%s",
QuicErrorCodeToString(error), error_details);
done_cb_->Run(error, error_details, nullptr, nullptr, nullptr);
done_cb_ = nullptr;
}
void QuicCryptoServerConfig::ProcessClientHelloContext::Succeed(
std::unique_ptr<CryptoHandshakeMessage> message,
std::unique_ptr<DiversificationNonce> diversification_nonce,
std::unique_ptr<ProofSource::Details> proof_source_details) {
QUIC_TRACEPRINTF("ProcessClientHello succeeded: %s",
FormatCryptoHandshakeMessageForTrace(message.get()));
done_cb_->Run(QUIC_NO_ERROR, std::string(), std::move(message),
std::move(diversification_nonce),
std::move(proof_source_details));
done_cb_ = nullptr;
}
QuicCryptoServerConfig::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)
: replay_protection_(true),
chlo_multiplier_(kMultiplier),
configs_lock_(),
primary_config_(nullptr),
next_config_promotion_time_(QuicWallTime::Zero()),
proof_source_(std::move(proof_source)),
key_exchange_source_(std::move(key_exchange_source)),
ssl_ctx_(TlsServerConnection::CreateSslCtx(proof_source_.get())),
source_address_token_future_secs_(3600),
source_address_token_lifetime_secs_(86400),
enable_serving_sct_(false),
rejection_observer_(nullptr),
pad_rej_(true),
pad_shlo_(true),
validate_chlo_size_(true),
validate_source_address_token_(true) {
QUICHE_DCHECK(proof_source_.get());
source_address_token_boxer_.SetKeys(
{DeriveSourceAddressTokenKey(source_address_token_secret)});
server_nonce_entropy->RandBytes(server_nonce_orbit_,
sizeof(server_nonce_orbit_));
const size_t key_size = server_nonce_boxer_.GetKeySize();
std::unique_ptr<uint8_t[]> key_bytes(new uint8_t[key_size]);
server_nonce_entropy->RandBytes(key_bytes.get(), key_size);
server_nonce_boxer_.SetKeys(
{std::string(reinterpret_cast<char*>(key_bytes.get()), key_size)});
}
QuicCryptoServerConfig::~QuicCryptoServerConfig() {}
QuicServerConfigProtobuf QuicCryptoServerConfig::GenerateConfig(
QuicRandom* rand, const QuicClock* clock, const ConfigOptions& options) {
CryptoHandshakeMessage msg;
const std::string curve25519_private_key =
Curve25519KeyExchange::NewPrivateKey(rand);
std::unique_ptr<Curve25519KeyExchange> curve25519 =
Curve25519KeyExchange::New(curve25519_private_key);
absl::string_view curve25519_public_value = curve25519->public_value();
std::string encoded_public_values;
QUICHE_DCHECK_LT(curve25519_public_value.size(), (1U << 24));
encoded_public_values.push_back(
static_cast<char>(curve25519_public_value.size()));
encoded_public_values.push_back(
static_cast<char>(curve25519_public_value.size() >> 8));
encoded_public_values.push_back(
static_cast<char>(curve25519_public_value.size() >> 16));
encoded_public_values.append(curve25519_public_value.data(),
curve25519_public_value.size());
std::string p256_private_key;
if (options.p256) {
p256_private_key = P256KeyExchange::NewPrivateKey();
std::unique_ptr<P256KeyExchange> p256(
P256KeyExchange::New(p256_private_key));
absl::string_view p256_public_value = p256->public_value();
QUICHE_DCHECK_LT(p256_public_value.size(), (1U << 24));
encoded_public_values.push_back(
static_cast<char>(p256_public_value.size()));
encoded_public_values.push_back(
static_cast<char>(p256_public_value.size() >> 8));
encoded_public_values.push_back(
static_cast<char>(p256_public_value.size() >> 16));
encoded_public_values.append(p256_public_value.data(),
p256_public_value.size());
}
msg.set_tag(kSCFG);
if (options.p256) {
msg.SetVector(kKEXS, QuicTagVector{kC255, kP256});
} else {
msg.SetVector(kKEXS, QuicTagVector{kC255});
}
msg.SetVector(kAEAD, QuicTagVector{kAESG, kCC20});
msg.SetStringPiece(kPUBS, encoded_public_values);
if (options.expiry_time.IsZero()) {
const QuicWallTime now = clock->WallNow();
const QuicWallTime expiry = now.Add(QuicTime::Delta::FromSeconds(
60 * 60 * 24 * 180 ));
const uint64_t expiry_seconds = expiry.ToUNIXSeconds();
msg.SetValue(kEXPY, expiry_seconds);
} else {
msg.SetValue(kEXPY, options.expiry_time.ToUNIXSeconds());
}
char orbit_bytes[kOrbitSize];
if (options.orbit.size() == sizeof(orbit_bytes)) {
memcpy(orbit_bytes, options.orbit.data(), sizeof(orbit_bytes));
} else {
QUICHE_DCHECK(options.orbit.empty());
rand->RandBytes(orbit_bytes, sizeof(orbit_bytes));
}
msg.SetStringPiece(kORBT,
absl::string_view(orbit_bytes, sizeof(orbit_bytes)));
if (options.channel_id_enabled) {
msg.SetVector(kPDMD, QuicTagVector{kCHID});
}
if (options.id.empty()) {
std::unique_ptr<QuicData> serialized =
CryptoFramer::ConstructHandshakeMessage(msg);
uint8_t scid_bytes[SHA256_DIGEST_LENGTH];
SHA256(reinterpret_cast<const uint8_t*>(serialized->data()),
serialized->length(), scid_bytes);
static_assert(16 <= SHA256_DIGEST_LENGTH, "SCID length too high.");
msg.SetStringPiece(
kSCID,
absl::string_view(reinterpret_cast<const char*>(scid_bytes), 16));
} else {
msg.SetStringPiece(kSCID, options.id);
}
std::unique_ptr<QuicData> serialized =
CryptoFramer::ConstructHandshakeMessage(msg);
QuicServerConfigProtobuf config;
config.set_config(std::string(serialized->AsStringPiece()));
QuicServerConfigProtobuf::PrivateKey* curve25519_key = config.add_key();
curve25519_key->set_tag(kC255);
curve25519_key->set_private_key(curve25519_private_key);
if (options.p256) {
QuicServerConfigProtobuf::PrivateKey* p256_key = config.add_key();
p256_key->set_tag(kP256);
p256_key->set_private_key(p256_private_key);
}
return config;
}
std::unique_ptr<CryptoHandshakeMessage> QuicCryptoServerConfig::AddConfig(
const QuicServerConfigProtobuf& protobuf, const QuicWallTime now) {
std::unique_ptr<CryptoHandshakeMessage> msg =
CryptoFramer::ParseMessage(protobuf.config());
if (!msg) {
QUIC_LOG(WARNING) << "Failed to parse server config message";
return nullptr;
}
quiche::QuicheReferenceCountedPointer<Config> config =
ParseConfigProtobuf(protobuf, false);
if (!config) {
QUIC_LOG(WARNING) << "Failed to parse server config message";
return nullptr;
}
{
quiche::QuicheWriterMutexLock locked(&configs_lock_);
if (configs_.find(config->id) != configs_.end()) {
QUIC_LOG(WARNING) << "Failed to add config because another with the same "
"server config id already exists: "
<< absl::BytesToHexString(config->id);
return nullptr;
}
configs_[config->id] = config;
SelectNewPrimaryConfig(now);
QUICHE_DCHECK(primary_config_.get());
QUICHE_DCHECK_EQ(configs_.find(primary_config_->id)->second.get(),
primary_config_.get());
}
return msg;
}
std::unique_ptr<CryptoHandshakeMessage>
QuicCryptoServerConfig::AddDefaultConfig(QuicRandom* rand,
const QuicClock* clock,
const ConfigOptions& options) {
return AddConfig(GenerateConfig(rand, clock, options), clock->WallNow());
}
bool QuicCryptoServerConfig::SetConfigs(
const std::vector<QuicServerConfigProtobuf>& protobufs,
const QuicServerConfigProtobuf* fallback_protobuf, const QuicWallTime now) {
std::vector<quiche::QuicheReferenceCountedPointer<Config>> parsed_configs;
for (auto& protobuf : protobufs) {
quiche::QuicheReferenceCountedPointer<Config> config =
ParseConfigProtobuf(protobuf, false);
if (!config) {
QUIC_LOG(WARNING) << "Rejecting QUIC configs because of above errors";
return false;
}
parsed_configs.push_back(config);
}
quiche::QuicheReferenceCountedPointer<Config> fallback_config;
if (fallback_protobuf != nullptr) {
fallback_config =
ParseConfigProtobuf(*fallback_protobuf, true);
if (!fallback_config) {
QUIC_LOG(WARNING) << "Rejecting QUIC configs because of above errors";
return false;
}
QUIC_LOG(INFO) << "Fallback config has scid "
<< absl::BytesToHexString(fallback_config->id);
parsed_configs.push_back(fallback_config);
} else {
QUIC_LOG(INFO) << "No fallback config provided";
}
if (parsed_configs.empty()) {
QUIC_LOG(WARNING)
<< "Rejecting QUIC configs because new config list is empty.";
return false;
}
QUIC_LOG(INFO) << "Updating configs:";
quiche::QuicheWriterMutexLock locked(&configs_lock_);
ConfigMap new_configs;
for (const quiche::QuicheReferenceCountedPointer<Config>& config :
parsed_configs) {
auto it = configs_.find(config->id);
if (it != configs_.end()) {
QUIC_LOG(INFO) << "Keeping scid: " << absl::BytesToHexString(config->id)
<< " orbit: "
<< absl::BytesToHexString(absl::string_view(
reinterpret_cast<const char*>(config->orbit),
kOrbitSize))
<< " new primary_time "
<< config->primary_time.ToUNIXSeconds()
<< " old primary_time "
<< it->second->primary_time.ToUNIXSeconds()
<< " new priority " << config->priority << " old priority "
<< it->second->priority;
it->second->primary_time = config->primary_time;
it->second->priority = config->priority;
new_configs.insert(*it);
} else {
QUIC_LOG(INFO) << "Adding scid: " << absl::BytesToHexString(config->id)
<< " orbit: "
<< absl::BytesToHexString(absl::string_view(
reinterpret_cast<const char*>(config->orbit),
kOrbitSize))
<< " primary_time " << config->primary_time.ToUNIXSeconds()
<< " priority " << config->priority;
new_configs.emplace(config->id, config);
}
}
configs_ = std::move(new_configs);
fallback_config_ = fallback_config;
SelectNewPrimaryConfig(now);
QUICHE_DCHECK(primary_config_.get());
QUICHE_DCHECK_EQ(configs_.find(primary_config_->id)->second.get(),
primary_config_.get());
return true;
}
void QuicCryptoServerConfig::SetSourceAddressTokenKeys(
const std::vector<std::string>& keys) {
source_address_token_boxer_.SetKeys(keys);
}
std::vector<std::string> QuicCryptoServerConfig::GetConfigIds() const {
quiche::QuicheReaderMutexLock locked(&configs_lock_);
std::vector<std::string> scids;
for (auto it = configs_.begin(); it != configs_.end(); ++it) {
scids.push_back(it->first);
}
return scids;
}
void QuicCryptoServerConfig::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 {
const QuicWallTime now(clock->WallNow());
quiche::QuicheReferenceCountedPointer<
ValidateClientHelloResultCallback::Result>
result(new ValidateClientHelloResultCallback::Result(
client_hello, client_address.host(), now));
absl::string_view requested_scid;
client_hello.GetStringPiece(kSCID, &requested_scid);
Configs configs;
if (!GetCurrentConfigs(now, requested_scid,
nullptr, &configs)) {
result->error_code = QUIC_CRYPTO_INTERNAL_ERROR;
result->error_details = "No configurations loaded";
}
signed_config->config = configs.primary;
if (result->error_code == QUIC_NO_ERROR) {
signed_config->chain = nullptr;
signed_config->proof.signature = "";
signed_config->proof.leaf_cert_scts = "";
EvaluateClientHello(server_address, client_address, version, configs,
result, std::move(done_cb));
} else {
done_cb->Run(result, nullptr);
}
}
class QuicCryptoServerConfig::ProcessClientHelloCallback
: public ProofSource::Callback {
public:
ProcessClientHelloCallback(const QuicCryptoServerConfig* config,
std::unique_ptr<ProcessClientHelloContext> context,
const Configs& configs)
: config_(config), context_(std::move(context)), configs_(configs) {}
void Run(
bool ok,
const quiche::QuicheReferenceCountedPointer<ProofSource::Chain>& chain,
const QuicCryptoProof& proof,
std::unique_ptr<ProofSource::Details> details) override {
if (ok) {
context_->signed_config()->chain = chain;
context_->signed_config()->proof = proof;
}
config_->ProcessClientHelloAfterGetProof(!ok, std::move(details),
std::move(context_), configs_);
}
private:
const QuicCryptoServerConfig* config_;
std::unique_ptr<ProcessClientHelloContext> context_;
const Configs configs_;
};
class QuicCryptoServerConfig::ProcessClientHelloAfterGetProofCallback
: public AsynchronousKeyExchange::Callback {
public:
ProcessClientHelloAfterGetProofCallback(
const QuicCryptoServerConfig* config,
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)
: config_(config),
proof_source_details_(std::move(proof_source_details)),
key_exchange_type_(key_exchange_type),
out_(std::move(out)),
public_value_(public_value),
context_(std::move(context)),
configs_(configs) {}
void Run(bool ok) override {
config_->ProcessClientHelloAfterCalculateSharedKeys(
!ok, std::move(proof_source_details_), key_exchange_type_,
std::move(out_), public_value_, std::move(context_), configs_);
}
private:
const QuicCryptoServerConfig* config_;
std::unique_ptr<ProofSource::Details> proof_source_details_;
const QuicTag key_exchange_type_;
std::unique_ptr<CryptoHandshakeMessage> out_;
const std::string public_value_;
std::unique_ptr<ProcessClientHelloContext> context_;
const Configs configs_;
std::unique_ptr<ProcessClientHelloResultCallback> done_cb_;
};
class QuicCryptoServerConfig::SendRejectWithFallbackConfigCallback
: public ProofSource::Callback {
public:
SendRejectWithFallbackConfigCallback(
const QuicCryptoServerConfig* config,
std::unique_ptr<ProcessClientHelloContext> context,
quiche::QuicheReferenceCountedPointer<Config> fallback_config)
: config_(config),
context_(std::move(context)),
fallback_config_(fallback_config) {}
void Run(
bool ok,
const quiche::QuicheReferenceCountedPointer<ProofSource::Chain>& chain,
const QuicCryptoProof& proof,
std::unique_ptr<ProofSource::Details> details) override {
if (ok) {
context_->signed_config()->chain = chain;
context_->signed_config()->proof = proof;
}
config_->SendRejectWithFallbackConfigAfterGetProof(
!ok, std::move(details), std::move(context_), fallback_config_);
}
private:
const QuicCryptoServerConfig* config_;
std::unique_ptr<ProcessClientHelloContext> context_;
quiche::QuicheReferenceCountedPointer<Config> fallback_config_;
};
void QuicCryptoServerConfig::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 {
QUICHE_DCHECK(done_cb);
auto context = std::make_unique<ProcessClientHelloContext>(
validate_chlo_result, reject_only, connection_id, server_address,
client_address, version, supported_versions, clock, rand,
compressed_certs_cache, params, signed_config, total_framing_overhead,
chlo_packet_size, std::move(done_cb));
std::string error_details;
QuicErrorCode valid = CryptoUtils::ValidateClientHello(
context->client_hello(), context->version(),
context->supported_versions(), &error_details);
if (valid != QUIC_NO_ERROR) {
context->Fail(valid, error_details);
return;
}
absl::string_view requested_scid;
context->client_hello().GetStringPiece(kSCID, &requested_scid);
Configs configs;
if (!GetCurrentConfigs(context->clock()->WallNow(), requested_scid,
signed_config->config, &configs)) {
context->Fail(QUIC_CRYPTO_INTERNAL_ERROR, "No configurations loaded");
return;
}
if (context->validate_chlo_result()->error_code != QUIC_NO_ERROR) {
context->Fail(context->validate_chlo_result()->error_code,
context->validate_chlo_result()->error_details);
return;
}
if (!ClientDemandsX509Proof(context->client_hello())) {
context->Fail(QUIC_UNSUPPORTED_PROOF_DEMAND, "Missing or invalid PDMD");
return;
}
if (!context->signed_config()->chain) {
const std::string chlo_hash = CryptoUtils::HashHandshakeMessage(
context->client_hello(), Perspective::IS_SERVER);
const QuicSocketAddress context_server_address = context->server_address();
const std::string sni = std::string(context->info().sni);
const QuicTransportVersion transport_version = context->transport_version();
auto cb = std::make_unique<ProcessClientHelloCallback>(
this, std::move(context), configs);
QUICHE_DCHECK(proof_source_.get());
proof_source_->GetProof(context_server_address, client_address, sni,
configs.primary->serialized, transport_version,
chlo_hash, std::move(cb));
return;
}
ProcessClientHelloAfterGetProof(
false, nullptr,
std::move(context), configs);
}
void QuicCryptoServerConfig::ProcessClientHelloAfterGetProof(
bool found_error,
std::unique_ptr<ProofSource::Details> proof_source_details,
std::unique_ptr<ProcessClientHelloContext> context,
const Configs& configs) const {
QUIC_BUG_IF(quic_bug_12963_2,
!QuicUtils::IsConnectionIdValidForVersion(
context->connection_id(), context->transport_version()))
<< "ProcessClientHelloAfterGetProof: attempted to use connection ID "
<< context->connection_id() << " which is invalid with version "
<< context->version();
if (context->info().reject_reasons.empty()) {
if (!context->signed_config() || !context->signed_config()->chain) {
context->validate_chlo_result()->info.reject_reasons.push_back(
SERVER_CONFIG_UNKNOWN_CONFIG_FAILURE);
} else if (!ValidateExpectedLeafCertificate(
context->client_hello(),
context->signed_config()->chain->certs)) {
context->validate_chlo_result()->info.reject_reasons.push_back(
INVALID_EXPECTED_LEAF_CERTIFICATE);
}
}
if (found_error) {
context->Fail(QUIC_HANDSHAKE_FAILED, "Failed to get proof");
return;
}
auto out_diversification_nonce = std::make_unique<DiversificationNonce>();
absl::string_view cert_sct;
if (context->client_hello().GetStringPiece(kCertificateSCTTag, &cert_sct) &&
cert_sct.empty()) {
context->params()->sct_supported_by_client = true;
}
auto out = std::make_unique<CryptoHandshakeMessage>();
if (!context->info().reject_reasons.empty() || !configs.requested) {
BuildRejectionAndRecordStats(*context, *configs.primary,
context->info().reject_reasons, out.get());
context->Succeed(std::move(out), std::move(out_diversification_nonce),
std::move(proof_source_details));
return;
}
if (context->reject_only()) {
context->Succeed(std::move(out), std::move(out_diversification_nonce),
std::move(proof_source_details));
return;
}
QuicTagVector their_aeads;
QuicTagVector their_key_exchanges;
if (context->client_hello().GetTaglist(kAEAD, &their_aeads) !=
QUIC_NO_ERROR ||
context->client_hello().GetTaglist(kKEXS, &their_key_exchanges) !=
QUIC_NO_ERROR ||
their_aeads.size() != 1 || their_key_exchanges.size() != 1) {
context->Fail(QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER,
"Missing or invalid AEAD or KEXS");
return;
}
size_t key_exchange_index;
if (!FindMutualQuicTag(configs.requested->aead, their_aeads,
&context->params()->aead, nullptr) ||
!FindMutualQuicTag(configs.requested->kexs, their_key_exchanges,
&context->params()->key_exchange,
&key_exchange_index)) {
context->Fail(QUIC_CRYPTO_NO_SUPPORT, "Unsupported AEAD or KEXS");
return;
}
absl::string_view public_value;
if (!context->client_hello().GetStringPiece(kPUBS, &public_value)) {
context->Fail(QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER,
"Missing public value");
return;
}
AdjustTestValue("quic::QuicCryptoServerConfig::public_value_adjust",
&public_value);
const AsynchronousKeyExchange* key_exchange =
configs.requested->key_exchanges[key_exchange_index].get();
std::string* initial_premaster_secret =
&context->params()->initial_premaster_secret;
auto cb = std::make_unique<ProcessClientHelloAfterGetProofCallback>(
this, std::move(proof_source_details), key_exchange->type(),
std::move(out), public_value, std::move(context), configs);
key_exchange->CalculateSharedKeyAsync(public_value, initial_premaster_secret,
std::move(cb));
}
void QuicCryptoServerConfig::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 {
QUIC_BUG_IF(quic_bug_12963_3,
!QuicUtils::IsConnectionIdValidForVersion(
context->connection_id(), context->transport_version()))
<< "ProcessClientHelloAfterCalculateSharedKeys:"
" attempted to use connection ID "
<< context->connection_id() << " which is invalid with version "
<< context->version();
if (found_error) {
if (configs.fallback == nullptr ||
context->signed_config()->config == configs.fallback) {
context->Fail(QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER,
"Failed to calculate shared key");
} else {
SendRejectWithFallbackConfig(std::move(context), configs.fallback);
}
return;
}
if (!context->info().sni.empty()) {
context->params()->sni =
QuicHostnameUtils::NormalizeHostname(context->info().sni);
}
std::string hkdf_suffix;
const QuicData& client_hello_serialized =
context->client_hello().GetSerialized();
hkdf_suffix.reserve(context->connection_id().length() +
client_hello_serialized.length() +
configs.requested->serialized.size());
hkdf_suffix.append(context->connection_id().data(),
context->connection_id().length());
hkdf_suffix.append(client_hello_serialized.data(),
client_hello_serialized.length());
hkdf_suffix.append(configs.requested->serialized);
QUICHE_DCHECK(proof_source_.get());
if (context->signed_config()->chain->certs.empty()) {
context->Fail(QUIC_CRYPTO_INTERNAL_ERROR, "Failed to get certs");
return;
}
hkdf_suffix.append(context->signed_config()->chain->certs[0]);
absl::string_view cetv_ciphertext;
if (configs.requested->channel_id_enabled &&
context->client_hello().GetStringPiece(kCETV, &cetv_ciphertext)) {
CryptoHandshakeMessage client_hello_copy(context->client_hello());
client_hello_copy.Erase(kCETV);
client_hello_copy.Erase(kPAD);
const QuicData& client_hello_copy_serialized =
client_hello_copy.GetSerialized();
std::string hkdf_input;
hkdf_input.append(QuicCryptoConfig::kCETVLabel,
strlen(QuicCryptoConfig::kCETVLabel) + 1);
hkdf_input.append(context->connection_id().data(),
context->connection_id().length());
hkdf_input.append(client_hello_copy_serialized.data(),
client_hello_copy_serialized.length());
hkdf_input.append(configs.requested->serialized);
CrypterPair crypters;
if (!CryptoUtils::DeriveKeys(
context->version(), context->params()->initial_premaster_secret,
context->params()->aead, context->info().client_nonce,
context->info().server_nonce, pre_shared_key_, hkdf_input,
Perspective::IS_SERVER, CryptoUtils::Diversification::Never(),
&crypters, nullptr )) {
context->Fail(QUIC_CRYPTO_SYMMETRIC_KEY_SETUP_FAILED,
"Symmetric key setup failed");
return;
}
char plaintext[kMaxOutgoingPacketSize];
size_t plaintext_length = 0;
const bool success = crypters.decrypter->DecryptPacket(
0 , absl::string_view() ,
cetv_ciphertext, plaintext, &plaintext_length, kMaxOutgoingPacketSize);
if (!success) {
context->Fail(QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER,
"CETV decryption failure");
return;
}
std::unique_ptr<CryptoHandshakeMessage> cetv(CryptoFramer::ParseMessage(
absl::string_view(plaintext, plaintext_length)));
if (!cetv) {
context->Fail(QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER, "CETV parse error");
return;
}
absl::string_view key, signature;
if (cetv->GetStringPiece(kCIDK, &key) &&
cetv->GetStringPiece(kCIDS, &signature)) {
if (!ChannelIDVerifier::Verify(key, hkdf_input, signature)) {
context->Fail(QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER,
"ChannelID signature failure");
return;
}
context->params()->channel_id = std::string(key);
}
}
std::string hkdf_input;
size_t label_len = strlen(QuicCryptoConfig::kInitialLabel) + 1;
hkdf_input.reserve(label_len + hkdf_suffix.size());
hkdf_input.append(QuicCryptoConfig::kInitialLabel, label_len);
hkdf_input.append(hkdf_suffix);
auto out_diversification_nonce = std::make_unique<DiversificationNonce>();
context->rand()->RandBytes(out_diversification_nonce->data(),
out_diversification_nonce->size());
CryptoUtils::Diversification diversification =
CryptoUtils::Diversification::Now(out_diversification_nonce.get());
if (!CryptoUtils::DeriveKeys(
context->version(), context->params()->initial_premaster_secret,
context->params()->aead, context->info().client_nonce,
context->info().server_nonce, pre_shared_key_, hkdf_input,
Perspective::IS_SERVER, diversification,
&context->params()->initial_crypters,
&context->params()->initial_subkey_secret)) {
context->Fail(QUIC_CRYPTO_SYMMETRIC_KEY_SETUP_FAILED,
"Symmetric key setup failed");
return;
}
std::string forward_secure_public_value;
std::unique_ptr<SynchronousKeyExchange> forward_secure_key_exchange =
CreateLocalSynchronousKeyExchange(key_exchange_type, context->rand());
if (!forward_secure_key_exchange) {
QUIC_DLOG(WARNING) << "Failed to create keypair";
context->Fail(QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER,
"Failed to create keypair");
return;
}
forward_secure_public_value =
std::string(forward_secure_key_exchange->public_value());
if (!forward_secure_key_exchange->CalculateSharedKeySync(
public_value, &context->params()->forward_secure_premaster_secret)) {
context->Fail(QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER,
"Invalid public value");
return;
}
std::string forward_secure_hkdf_input;
label_len = strlen(QuicCryptoConfig::kForwardSecureLabel) + 1;
forward_secure_hkdf_input.reserve(label_len + hkdf_suffix.size());
forward_secure_hkdf_input.append(QuicCryptoConfig::kForwardSecureLabel,
label_len);
forward_secure_hkdf_input.append(hkdf_suffix);
std::string shlo_nonce;
shlo_nonce = NewServerNonce(context->rand(), context->info().now);
out->SetStringPiece(kServerNonceTag, shlo_nonce);
if (!CryptoUtils::DeriveKeys(
context->version(),
context->params()->forward_secure_premaster_secret,
context->params()->aead, context->info().client_nonce,
shlo_nonce.empty() ? context->info().server_nonce : shlo_nonce,
pre_shared_key_, forward_secure_hkdf_input, Perspective::IS_SERVER,
CryptoUtils::Diversification::Never(),
&context->params()->forward_secure_crypters,
&context->params()->subkey_secret)) {
context->Fail(QUIC_CRYPTO_SYMMETRIC_KEY_SETUP_FAILED,
"Symmetric key setup failed");
return;
}
out->set_tag(kSHLO);
out->SetVersionVector(kVER, context->supported_versions());
out->SetStringPiece(
kSourceAddressTokenTag,
NewSourceAddressToken(*configs.requested->source_address_token_boxer,
context->info().source_address_tokens,
context->client_address().host(), context->rand(),
context->info().now, nullptr));
QuicSocketAddressCoder address_coder(context->client_address());
out->SetStringPiece(kCADR, address_coder.Encode());
out->SetStringPiece(kPUBS, forward_secure_public_value);
context->Succeed(std::move(out), std::move(out_diversification_nonce),
std::move(proof_source_details));
}
void QuicCryptoServerConfig::SendRejectWithFallbackConfig(
std::unique_ptr<ProcessClientHelloContext> context,
quiche::QuicheReferenceCountedPointer<Config> fallback_config) const {
const std::string chlo_hash = CryptoUtils::HashHandshakeMessage(
context->client_hello(), Perspective::IS_SERVER);
const QuicSocketAddress server_address = context->server_address();
const std::string sni(context->info().sni);
const QuicTransportVersion transport_version = context->transport_version();
const QuicSocketAddress& client_address = context->client_address();
auto cb = std::make_unique<SendRejectWithFallbackConfigCallback>(
this, std::move(context), fallback_config);
proof_source_->GetProof(server_address, client_address, sni,
fallback_config->serialized, transport_version,
chlo_hash, std::move(cb));
}
void QuicCryptoServerConfig::SendRejectWithFallbackConfigAfterGetProof(
bool found_error,
std::unique_ptr<ProofSource::Details> proof_source_details,
std::unique_ptr<ProcessClientHelloContext> context,
quiche::QuicheReferenceCountedPointer<Config> fallback_config) const {
if (found_error) {
context->Fail(QUIC_HANDSHAKE_FAILED, "Failed to get proof");
return;
}
auto out = std::make_unique<CryptoHandshakeMessage>();
BuildRejectionAndRecordStats(*context, *fallback_config,
{SERVER_CONFIG_UNKNOWN_CONFIG_FAILURE},
out.get());
context->Succeed(std::move(out), std::make_unique<DiversificationNonce>(),
std::move(proof_source_details));
}
quiche::QuicheReferenceCountedPointer<QuicCryptoServerConfig::Config>
QuicCryptoServerConfig::GetConfigWithScid(
absl::string_view requested_scid) const {
configs_lock_.AssertReaderHeld();
if (!requested_scid.empty()) {
auto it = configs_.find((std::string(requested_scid)));
if (it != configs_.end()) {
return quiche::QuicheReferenceCountedPointer<Config>(it->second);
}
}
return quiche::QuicheReferenceCountedPointer<Config>();
}
bool QuicCryptoServerConfig::GetCurrentConfigs(
const QuicWallTime& now, absl::string_view requested_scid,
quiche::QuicheReferenceCountedPointer<Config> old_primary_config,
Configs* configs) const {
quiche::QuicheReaderMutexLock locked(&configs_lock_);
if (!primary_config_) {
return false;
}
if (IsNextConfigReady(now)) {
configs_lock_.ReaderUnlock();
configs_lock_.WriterLock();
SelectNewPrimaryConfig(now);
QUICHE_DCHECK(primary_config_.get());
QUICHE_DCHECK_EQ(configs_.find(primary_config_->id)->second.get(),
primary_config_.get());
configs_lock_.WriterUnlock();
configs_lock_.ReaderLock();
}
if (old_primary_config != nullptr) {
configs->primary = old_primary_config;
} else {
configs->primary = primary_config_;
}
configs->requested = GetConfigWithScid(requested_scid);
configs->fallback = fallback_config_;
return true;
}
bool QuicCryptoServerConfig::ConfigPrimaryTimeLessThan(
const quiche::QuicheReferenceCountedPointer<Config>& a,
const quiche::QuicheReferenceCountedPointer<Config>& b) {
if (a->primary_time.IsBefore(b->primary_time) ||
b->primary_time.IsBefore(a->primary_time)) {
return a->primary_time.IsBefore(b->primary_time);
} else if (a->priority != b->priority) {
return a->priority < b->priority;
} else {
return a->id < b->id;
}
}
void QuicCryptoServerConfig::SelectNewPrimaryConfig(
const QuicWallTime now) const {
std::vector<quiche::QuicheReferenceCountedPointer<Config>> configs;
configs.reserve(configs_.size());
for (auto it = configs_.begin(); it != configs_.end(); ++it) {
configs.push_back(it->second);
}
if (configs.empty()) {
if (primary_config_ != nullptr) {
QUIC_BUG(quic_bug_10630_2)
<< "No valid QUIC server config. Keeping the current config.";
} else {
QUIC_BUG(quic_bug_10630_3) << "No valid QUIC server config.";
}
return;
}
std::sort(configs.begin(), configs.end(), ConfigPrimaryTimeLessThan);
quiche::QuicheReferenceCountedPointer<Config> best_candidate = configs[0];
for (size_t i = 0; i < configs.size(); ++i) {
const quiche::QuicheReferenceCountedPointer<Config> config(configs[i]);
if (!config->primary_time.IsAfter(now)) {
if (config->primary_time.IsAfter(best_candidate->primary_time)) {
best_candidate = config;
}
continue;
}
quiche::QuicheReferenceCountedPointer<Config> new_primary = best_candidate;
if (i == 0) {
if (configs.size() > 1) {
next_config_promotion_time_ = configs[1]->primary_time;
} else {
next_config_promotion_time_ = QuicWallTime::Zero();
}
} else {
next_config_promotion_time_ = config->primary_time;
}
if (primary_config_) {
primary_config_->is_primary = false;
}
primary_config_ = new_primary;
new_primary->is_primary = true;
QUIC_DLOG(INFO) << "New primary config. orbit: "
<< absl::BytesToHexString(
absl::string_view(reinterpret_cast<const char*>(
primary_config_->orbit),
kOrbitSize));
if (primary_config_changed_cb_ != nullptr) {
primary_config_changed_cb_->Run(primary_config_->id);
}
return;
}
quiche::QuicheReferenceCountedPointer<Config> new_primary = best_candidate;
if (primary_config_) {
primary_config_->is_primary = false;
}
primary_config_ = new_primary;
new_primary->is_primary = true;
QUIC_DLOG(INFO) << "New primary config. orbit: "
<< absl::BytesToHexString(absl::string_view(
reinterpret_cast<const char*>(primary_config_->orbit),
kOrbitSize))
<< " scid: " << absl::BytesToHexString(primary_config_->id);
next_config_promotion_time_ = QuicWallTime::Zero();
if (primary_config_changed_cb_ != nullptr) {
primary_config_changed_cb_->Run(primary_config_->id);
}
}
void QuicCryptoServerConfig::EvaluateClientHello(
const QuicSocketAddress& ,
const QuicSocketAddress& ,
QuicTransportVersion , const Configs& configs,
quiche::QuicheReferenceCountedPointer<
ValidateClientHelloResultCallback::Result>
client_hello_state,
std::unique_ptr<ValidateClientHelloResultCallback> done_cb) const {
ValidateClientHelloHelper helper(client_hello_state, &done_cb);
const CryptoHandshakeMessage& client_hello = client_hello_state->client_hello;
ClientHelloInfo* info = &(client_hello_state->info);
if (client_hello.GetStringPiece(kSNI, &info->sni) &&
!QuicHostnameUtils::IsValidSNI(info->sni)) {
helper.ValidationComplete(QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER,
"Invalid SNI name", nullptr);
return;
}
client_hello.GetStringPiece(kUAID, &info->user_agent_id);
HandshakeFailureReason source_address_token_error = MAX_FAILURE_REASON;
if (validate_source_address_token_) {
absl::string_view srct;
if (client_hello.GetStringPiece(kSourceAddressTokenTag, &srct)) {
Config& config =
configs.requested != nullptr ? *configs.requested : *configs.primary;
source_address_token_error =
ParseSourceAddressToken(*config.source_address_token_boxer, srct,
info->source_address_tokens);
if (source_address_token_error == HANDSHAKE_OK) {
source_address_token_error = ValidateSourceAddressTokens(
info->source_address_tokens, info->client_ip, info->now,
&client_hello_state->cached_network_params);
}
info->valid_source_address_token =
(source_address_token_error == HANDSHAKE_OK);
} else {
source_address_token_error = SOURCE_ADDRESS_TOKEN_INVALID_FAILURE;
}
} else {
source_address_token_error = HANDSHAKE_OK;
info->valid_source_address_token = true;
}
if (!configs.requested) {
absl::string_view requested_scid;
if (client_hello.GetStringPiece(kSCID, &requested_scid)) {
info->reject_reasons.push_back(SERVER_CONFIG_UNKNOWN_CONFIG_FAILURE);
} else {
info->reject_reasons.push_back(SERVER_CONFIG_INCHOATE_HELLO_FAILURE);
}
helper.ValidationComplete(QUIC_NO_ERROR, "", nullptr);
return;
}
if (!client_hello.GetStringPiece(kNONC, &info->client_nonce)) {
info->reject_reasons.push_back(SERVER_CONFIG_INCHOATE_HELLO_FAILURE);
helper.ValidationComplete(QUIC_NO_ERROR, "", nullptr);
return;
}
if (source_address_token_error != HANDSHAKE_OK) {
info->reject_reasons.push_back(source_address_token_error);
}
if (info->client_nonce.size() != kNonceSize) {
info->reject_reasons.push_back(CLIENT_NONCE_INVALID_FAILURE);
QUIC_LOG_FIRST_N(ERROR, 2)
<< "Invalid client nonce: " << client_hello.DebugString();
QUIC_DLOG(INFO) << "Invalid client nonce.";
}
client_hello.GetStringPiece(kServerNonceTag, &info->server_nonce);
if (GetQuicReloadableFlag(quic_require_handshake_confirmation) &&
info->server_nonce.empty()) {
QUIC_RELOADABLE_FLAG_COUNT(quic_require_handshake_confirmation);
info->reject_reasons.push_back(SERVER_NONCE_REQUIRED_FAILURE);
}
helper.ValidationComplete(QUIC_NO_ERROR, "",
std::unique_ptr<ProofSource::Details>());
}
void QuicCryptoServerConfig::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 {
std::string serialized;
std::string source_address_token;
{
quiche::QuicheReaderMutexLock locked(&configs_lock_);
serialized = primary_config_->serialized;
source_address_token = NewSourceAddressToken(
*primary_config_->source_address_token_boxer,
previous_source_address_tokens, client_address.host(), rand,
clock->WallNow(), cached_network_params);
}
CryptoHandshakeMessage message;
message.set_tag(kSCUP);
message.SetStringPiece(kSCFG, serialized);
message.SetStringPiece(kSourceAddressTokenTag, source_address_token);
auto proof_source_cb =
std::make_unique<BuildServerConfigUpdateMessageProofSourceCallback>(
this, compressed_certs_cache, params, std::move(message),
std::move(cb));
proof_source_->GetProof(server_address, client_address, params.sni,
serialized, version, chlo_hash,
std::move(proof_source_cb));
}
QuicCryptoServerConfig::BuildServerConfigUpdateMessageProofSourceCallback::
~BuildServerConfigUpdateMessageProofSourceCallback() {}
QuicCryptoServerConfig::BuildServerConfigUpdateMessageProofSourceCallback::
BuildServerConfigUpdateMessageProofSourceCallback(
const QuicCryptoServerConfig* config,
QuicCompressedCertsCache* compressed_certs_cache,
const QuicCryptoNegotiatedParameters& params,
CryptoHandshakeMessage message,
std::unique_ptr<BuildServerConfigUpdateMessageResultCallback> cb)
: config_(config),
compressed_certs_cache_(compressed_certs_cache),
client_cached_cert_hashes_(params.client_cached_cert_hashes),
sct_supported_by_client_(params.sct_supported_by_client),
sni_(params.sni),
message_(std::move(message)),
cb_(std::move(cb)) {}
void QuicCryptoServerConfig::BuildServerConfigUpdateMessageProofSourceCallback::
Run(bool ok,
const quiche::QuicheReferenceCountedPointer<ProofSource::Chain>& chain,
const QuicCryptoProof& proof,
std::unique_ptr<ProofSource::Details> details) {
config_->FinishBuildServerConfigUpdateMessage(
compressed_certs_cache_, client_cached_cert_hashes_,
sct_supported_by_client_, sni_, ok, chain, proof.signature,
proof.leaf_cert_scts, std::move(details), std::move(message_),
std::move(cb_));
}
void QuicCryptoServerConfig::FinishBuildServerConfigUpdateMessage(
QuicCompressedCertsCache* compressed_certs_cache,
const std::string& client_cached_cert_hashes, bool sct_supported_by_client,
const std::string& sni, bool ok,
const quiche::QuicheReferenceCountedPointer<ProofSource::Chain>& chain,
const std::string& signature, const std::string& leaf_cert_sct,
std::unique_ptr<ProofSource::Details> ,
CryptoHandshakeMessage message,
std::unique_ptr<BuildServerConfigUpdateMessageResultCallback> cb) const {
if (!ok) {
cb->Run(false, message);
return;
}
const std::string compressed =
CompressChain(compressed_certs_cache, chain, client_cached_cert_hashes);
message.SetStringPiece(kCertificateTag, compressed);
message.SetStringPiece(kPROF, signature);
if (sct_supported_by_client && enable_serving_sct_) {
if (leaf_cert_sct.empty()) {
QUIC_LOG_EVERY_N_SEC(WARNING, 60)
<< "SCT is expected but it is empty. SNI: " << sni;
} else {
message.SetStringPiece(kCertificateSCTTag, leaf_cert_sct);
}
}
cb->Run(true, message);
}
void QuicCryptoServerConfig::BuildRejectionAndRecordStats(
const ProcessClientHelloContext& context, const Config& config,
const std::vector<uint32_t>& reject_reasons,
CryptoHandshakeMessage* out) const {
BuildRejection(context, config, reject_reasons, out);
if (rejection_observer_ != nullptr) {
rejection_observer_->OnRejectionBuilt(reject_reasons, out);
}
}
void QuicCryptoServerConfig::BuildRejection(
const ProcessClientHelloContext& context, const Config& config,
const std::vector<uint32_t>& reject_reasons,
CryptoHandshakeMessage* out) const {
const QuicWallTime now = context.clock()->WallNow();
out->set_tag(kREJ);
out->SetStringPiece(kSCFG, config.serialized);
out->SetStringPiece(
kSourceAddressTokenTag,
NewSourceAddressToken(
*config.source_address_token_boxer,
context.info().source_address_tokens, context.info().client_ip,
context.rand(), context.info().now,
&context.validate_chlo_result()->cached_network_params));
out->SetValue(kSTTL, config.expiry_time.AbsoluteDifference(now).ToSeconds());
if (replay_protection_) {
out->SetStringPiece(kServerNonceTag,
NewServerNonce(context.rand(), context.info().now));
}
QUICHE_DCHECK_LT(0u, reject_reasons.size());
out->SetVector(kRREJ, reject_reasons);
if (!ClientDemandsX509Proof(context.client_hello())) {
QUIC_BUG(quic_bug_10630_4)
<< "x509 certificates not supported in proof demand";
return;
}
absl::string_view client_cached_cert_hashes;
if (context.client_hello().GetStringPiece(kCCRT,
&client_cached_cert_hashes)) {
context.params()->client_cached_cert_hashes =
std::string(client_cached_cert_hashes);
} else {
context.params()->client_cached_cert_hashes.clear();
}
const std::string compressed = CompressChain(
context.compressed_certs_cache(), context.signed_config()->chain,
context.params()->client_cached_cert_hashes);
QUICHE_DCHECK_GT(context.chlo_packet_size(), context.client_hello().size());
const size_t kREJOverheadBytes = 166;
const size_t max_unverified_size =
chlo_multiplier_ *
(context.chlo_packet_size() - context.total_framing_overhead()) -
kREJOverheadBytes;
static_assert(kClientHelloMinimumSize * kMultiplier >= kREJOverheadBytes,
"overhead calculation may underflow");
bool should_return_sct =
context.params()->sct_supported_by_client && enable_serving_sct_;
const std::string& cert_sct = context.signed_config()->proof.leaf_cert_scts;
const size_t sct_size = should_return_sct ? cert_sct.size() : 0;
const size_t total_size = context.signed_config()->proof.signature.size() +
compressed.size() + sct_size;
if (context.info().valid_source_address_token ||
total_size < max_unverified_size) {
out->SetStringPiece(kCertificateTag, compressed);
out->SetStringPiece(kPROF, context.signed_config()->proof.signature);
if (should_return_sct) {
if (cert_sct.empty()) {
const std::vector<std::string>& certs =
context.signed_config()->chain->certs;
std::string ca_subject;
if (!certs.empty()) {
std::unique_ptr<CertificateView> view =
CertificateView::ParseSingleCertificate(certs[0]);
if (view != nullptr) {
std::optional<std::string> maybe_ca_subject =
view->GetHumanReadableSubject();
if (maybe_ca_subject.has_value()) {
ca_subject = *maybe_ca_subject;
}
}
}
QUIC_LOG_EVERY_N_SEC(WARNING, 60)
<< "SCT is expected but it is empty. sni: '"
<< context.params()->sni << "' cert subject: '" << ca_subject
<< "'";
} else {
out->SetStringPiece(kCertificateSCTTag, cert_sct);
}
}
} else {
QUIC_LOG_EVERY_N_SEC(WARNING, 60)
<< "Sending inchoate REJ for hostname: " << context.info().sni
<< " signature: " << context.signed_config()->proof.signature.size()
<< " cert: " << compressed.size() << " sct:" << sct_size
<< " total: " << total_size << " max: " << max_unverified_size;
}
}
std::string QuicCryptoServerConfig::CompressChain(
QuicCompressedCertsCache* compressed_certs_cache,
const quiche::QuicheReferenceCountedPointer<ProofSource::Chain>& chain,
const std::string& client_cached_cert_hashes) {
QUICHE_DCHECK(compressed_certs_cache);
const std::string* cached_value = compressed_certs_cache->GetCompressedCert(
chain, client_cached_cert_hashes);
if (cached_value) {
return *cached_value;
}
std::string compressed =
CertCompressor::CompressChain(chain->certs, client_cached_cert_hashes);
compressed_certs_cache->Insert(chain, client_cached_cert_hashes, compressed);
return compressed;
}
quiche::QuicheReferenceCountedPointer<QuicCryptoServerConfig::Config>
QuicCryptoServerConfig::ParseConfigProtobuf(
const QuicServerConfigProtobuf& protobuf, bool is_fallback) const {
std::unique_ptr<CryptoHandshakeMessage> msg =
CryptoFramer::ParseMessage(protobuf.config());
if (!msg) {
QUIC_LOG(WARNING) << "Failed to parse server config message";
return nullptr;
}
if (msg->tag() != kSCFG) {
QUIC_LOG(WARNING) << "Server config message has tag " << msg->tag()
<< ", but expected " << kSCFG;
return nullptr;
}
quiche::QuicheReferenceCountedPointer<Config> config(new Config);
config->serialized = protobuf.config();
config->source_address_token_boxer = &source_address_token_boxer_;
if (protobuf.has_primary_time()) {
config->primary_time =
QuicWallTime::FromUNIXSeconds(protobuf.primary_time());
}
config->priority = protobuf.priority();
absl::string_view scid;
if (!msg->GetStringPiece(kSCID, &scid)) {
QUIC_LOG(WARNING) << "Server config message is missing SCID";
return nullptr;
}
if (scid.empty()) {
QUIC_LOG(WARNING) << "Server config message contains an empty SCID";
return nullptr;
}
config->id = std::string(scid);
if (msg->GetTaglist(kAEAD, &config->aead) != QUIC_NO_ERROR) {
QUIC_LOG(WARNING) << "Server config message is missing AEAD";
return nullptr;
}
QuicTagVector kexs_tags;
if (msg->GetTaglist(kKEXS, &kexs_tags) != QUIC_NO_ERROR) {
QUIC_LOG(WARNING) << "Server config message is missing KEXS";
return nullptr;
}
absl::string_view orbit;
if (!msg->GetStringPiece(kORBT, &orbit)) {
QUIC_LOG(WARNING) << "Server config message is missing ORBT";
return nullptr;
}
if (orbit.size() != kOrbitSize) {
QUIC_LOG(WARNING) << "Orbit value in server config is the wrong length."
" Got "
<< orbit.size() << " want " << kOrbitSize;
return nullptr;
}
static_assert(sizeof(config->orbit) == kOrbitSize, "incorrect orbit size");
memcpy(config->orbit, orbit.data(), sizeof(config->orbit));
QuicTagVector proof_demand_tags;
if (msg->GetTaglist(kPDMD, &proof_demand_tags) == QUIC_NO_ERROR) {
for (QuicTag tag : proof_demand_tags) {
if (tag == kCHID) {
config->channel_id_enabled = true;
break;
}
}
}
for (size_t i = 0; i < kexs_tags.size(); i++) {
const QuicTag tag = kexs_tags[i];
std::string private_key;
config->kexs.push_back(tag);
for (int j = 0; j < protobuf.key_size(); j++) {
const QuicServerConfigProtobuf::PrivateKey& key = protobuf.key(i);
if (key.tag() == tag) {
private_key = key.private_key();
break;
}
}
std::unique_ptr<AsynchronousKeyExchange> ka =
key_exchange_source_->Create(config->id, is_fallback, tag, private_key);
if (!ka) {
return nullptr;
}
for (const auto& key_exchange : config->key_exchanges) {
if (key_exchange->type() == tag) {
QUIC_LOG(WARNING) << "Duplicate key exchange in config: " << tag;
return nullptr;
}
}
config->key_exchanges.push_back(std::move(ka));
}
uint64_t expiry_seconds;
if (msg->GetUint64(kEXPY, &expiry_seconds) != QUIC_NO_ERROR) {
QUIC_LOG(WARNING) << "Server config message is missing EXPY";
return nullptr;
}
config->expiry_time = QuicWallTime::FromUNIXSeconds(expiry_seconds);
return config;
}
void QuicCryptoServerConfig::set_replay_protection(bool on) {
replay_protection_ = on;
}
void QuicCryptoServerConfig::set_chlo_multiplier(size_t multiplier) {
chlo_multiplier_ = multiplier;
}
void QuicCryptoServerConfig::set_source_address_token_future_secs(
uint32_t future_secs) {
source_address_token_future_secs_ = future_secs;
}
void QuicCryptoServerConfig::set_source_address_token_lifetime_secs(
uint32_t lifetime_secs) {
source_address_token_lifetime_secs_ = lifetime_secs;
}
void QuicCryptoServerConfig::set_enable_serving_sct(bool enable_serving_sct) {
enable_serving_sct_ = enable_serving_sct;
}
void QuicCryptoServerConfig::AcquirePrimaryConfigChangedCb(
std::unique_ptr<PrimaryConfigChangedCallback> cb) {
quiche::QuicheWriterMutexLock locked(&configs_lock_);
primary_config_changed_cb_ = std::move(cb);
}
std::string QuicCryptoServerConfig::NewSourceAddressToken(
const CryptoSecretBoxer& crypto_secret_boxer,
const SourceAddressTokens& previous_tokens, const QuicIpAddress& ip,
QuicRandom* rand, QuicWallTime now,
const CachedNetworkParameters* cached_network_params) const {
SourceAddressTokens source_address_tokens;
SourceAddressToken* source_address_token = source_address_tokens.add_tokens();
source_address_token->set_ip(ip.DualStacked().ToPackedString());
source_address_token->set_timestamp(now.ToUNIXSeconds());
if (cached_network_params != nullptr) {
*(source_address_token->mutable_cached_network_parameters()) =
*cached_network_params;
}
for (const SourceAddressToken& token : previous_tokens.tokens()) {
if (source_address_tokens.tokens_size() > kMaxTokenAddresses) {
break;
}
if (token.ip() == source_address_token->ip()) {
continue;
}
if (ValidateSourceAddressTokenTimestamp(token, now) != HANDSHAKE_OK) {
continue;
}
*(source_address_tokens.add_tokens()) = token;
}
return crypto_secret_boxer.Box(rand,
source_address_tokens.SerializeAsString());
}
int QuicCryptoServerConfig::NumberOfConfigs() const {
quiche::QuicheReaderMutexLock locked(&configs_lock_);
return configs_.size();
}
ProofSource* QuicCryptoServerConfig::proof_source() const {
return proof_source_.get();
}
SSL_CTX* QuicCryptoServerConfig::ssl_ctx() const { return ssl_ctx_.get(); }
HandshakeFailureReason QuicCryptoServerConfig::ParseSourceAddressToken(
const CryptoSecretBoxer& crypto_secret_boxer, absl::string_view token,
SourceAddressTokens& tokens) const {
std::string storage;
absl::string_view plaintext;
if (!crypto_secret_boxer.Unbox(token, &storage, &plaintext)) {
return SOURCE_ADDRESS_TOKEN_DECRYPTION_FAILURE;
}
if (!tokens.ParseFromArray(plaintext.data(), plaintext.size())) {
SourceAddressToken old_source_token;
if (!old_source_token.ParseFromArray(plaintext.data(), plaintext.size())) {
return SOURCE_ADDRESS_TOKEN_PARSE_FAILURE;
}
*tokens.add_tokens() = old_source_token;
}
return HANDSHAKE_OK;
}
HandshakeFailureReason QuicCryptoServerConfig::ValidateSourceAddressTokens(
const SourceAddressTokens& source_address_tokens, const QuicIpAddress& ip,
QuicWallTime now, CachedNetworkParameters* cached_network_params) const {
HandshakeFailureReason reason =
SOURCE_ADDRESS_TOKEN_DIFFERENT_IP_ADDRESS_FAILURE;
for (const SourceAddressToken& token : source_address_tokens.tokens()) {
reason = ValidateSingleSourceAddressToken(token, ip, now);
if (reason == HANDSHAKE_OK) {
if (cached_network_params != nullptr &&
token.has_cached_network_parameters()) {
*cached_network_params = token.cached_network_parameters();
}
break;
}
}
return reason;
}
HandshakeFailureReason QuicCryptoServerConfig::ValidateSingleSourceAddressToken(
const SourceAddressToken& source_address_token, const QuicIpAddress& ip,
QuicWallTime now) const {
if (source_address_token.ip() != ip.DualStacked().ToPackedString()) {
return SOURCE_ADDRESS_TOKEN_DIFFERENT_IP_ADDRESS_FAILURE;
}
return ValidateSourceAddressTokenTimestamp(source_address_token, now);
}
HandshakeFailureReason
QuicCryptoServerConfig::ValidateSourceAddressTokenTimestamp(
const SourceAddressToken& source_address_token, QuicWallTime now) const {
const QuicWallTime timestamp(
QuicWallTime::FromUNIXSeconds(source_address_token.timestamp()));
const QuicTime::Delta delta(now.AbsoluteDifference(timestamp));
if (now.IsBefore(timestamp) &&
delta.ToSeconds() > source_address_token_future_secs_) {
return SOURCE_ADDRESS_TOKEN_CLOCK_SKEW_FAILURE;
}
if (now.IsAfter(timestamp) &&
delta.ToSeconds() > source_address_token_lifetime_secs_) {
return SOURCE_ADDRESS_TOKEN_EXPIRED_FAILURE;
}
return HANDSHAKE_OK;
}
static const size_t kServerNoncePlaintextSize =
4 + 20 ;
std::string QuicCryptoServerConfig::NewServerNonce(QuicRandom* rand,
QuicWallTime now) const {
const uint32_t timestamp = static_cast<uint32_t>(now.ToUNIXSeconds());
uint8_t server_nonce[kServerNoncePlaintextSize];
static_assert(sizeof(server_nonce) > sizeof(timestamp), "nonce too small");
server_nonce[0] = static_cast<uint8_t>(timestamp >> 24);
server_nonce[1] = static_cast<uint8_t>(timestamp >> 16);
server_nonce[2] = static_cast<uint8_t>(timestamp >> 8);
server_nonce[3] = static_cast<uint8_t>(timestamp);
rand->RandBytes(&server_nonce[sizeof(timestamp)],
sizeof(server_nonce) - sizeof(timestamp));
return server_nonce_boxer_.Box(
rand, absl::string_view(reinterpret_cast<char*>(server_nonce),
sizeof(server_nonce)));
}
bool QuicCryptoServerConfig::ValidateExpectedLeafCertificate(
const CryptoHandshakeMessage& client_hello,
const std::vector<std::string>& certs) const {
if (certs.empty()) {
return false;
}
uint64_t hash_from_client;
if (client_hello.GetUint64(kXLCT, &hash_from_client) != QUIC_NO_ERROR) {
return false;
}
return CryptoUtils::ComputeLeafCertHash(certs[0]) == hash_from_client;
}
bool QuicCryptoServerConfig::IsNextConfigReady(QuicWallTime now) const {
return !next_config_promotion_time_.IsZero() &&
!next_config_promotion_time_.IsAfter(now);
}
QuicCryptoServerConfig::Config::Config()
: channel_id_enabled(false),
is_primary(false),
primary_time(QuicWallTime::Zero()),
expiry_time(QuicWallTime::Zero()),
priority(0),
source_address_token_boxer(nullptr) {}
QuicCryptoServerConfig::Config::~Config() {}
QuicSignedServerConfig::QuicSignedServerConfig() {}
QuicSignedServerConfig::~QuicSignedServerConfig() {}
} | #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}});
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/quic_crypto_server_config.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/crypto/quic_crypto_server_config_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
c480f536-28b4-4184-bf64-e20358674619 | 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 | #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);
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/batch_writer/quic_gso_batch_writer.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/batch_writer/quic_gso_batch_writer_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
798a4ba8-37d2-48c9-aa40-dfb68e7f290c | 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 | #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);
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/batch_writer/quic_batch_writer_buffer.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/batch_writer/quic_batch_writer_buffer_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
b9a823c3-0c38-48fc-9bee-8aaf1bede3f6 | 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 | #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 {
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/batch_writer/quic_sendmmsg_batch_writer.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/batch_writer/quic_sendmmsg_batch_writer_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
cb674ea6-6720-4736-b815-049e514ec55d | cpp | google/quiche | socket | quiche/quic/core/io/socket.cc | quiche/quic/core/io/socket_test.cc | #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));
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/io/socket.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/io/socket_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
67499580-6a0a-4546-a683-3cbca4e07781 | 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 | #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()));
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/io/event_loop_connecting_client_socket.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/io/event_loop_connecting_client_socket_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
c4be7536-a004-445e-9ae3-3c93ab000533 | 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 | #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);
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/io/quic_poll_event_loop.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/io/quic_poll_event_loop_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
142edbef-bb7f-49ca-8044-b0c2a9bdfa53 | cpp | google/quiche | spdy_utils | quiche/quic/core/http/spdy_utils.cc | quiche/quic/core/http/spdy_utils_test.cc | #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/http2/core/spdy_protocol.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"
using quiche::HttpHeaderBlock;
namespace quic {
bool SpdyUtils::ExtractContentLengthFromHeaders(int64_t* content_length,
HttpHeaderBlock* 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,
HttpHeaderBlock* 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,
HttpHeaderBlock* 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,
HttpHeaderBlock* 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 quiche::HttpHeaderBlock;
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) {
auto headers = std::make_unique<QuicHeaderList>();
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;
HttpHeaderBlock 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;
HttpHeaderBlock 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;
HttpHeaderBlock 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;
HttpHeaderBlock 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;
HttpHeaderBlock 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;
HttpHeaderBlock 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;
HttpHeaderBlock 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;
HttpHeaderBlock 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;
HttpHeaderBlock 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;
HttpHeaderBlock 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;
HttpHeaderBlock 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;
HttpHeaderBlock 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;
HttpHeaderBlock block;
EXPECT_FALSE(SpdyUtils::CopyAndValidateTrailers(
trailers, kExpectFinalByteOffset, &final_byte_offset, &block));
}
TEST_F(CopyAndValidateTrailers,
EmptyTrailerListWithFinalByteOffsetNotExpected) {
QuicHeaderList trailers;
size_t final_byte_offset = 0;
HttpHeaderBlock 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;
HttpHeaderBlock 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;
HttpHeaderBlock 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;
HttpHeaderBlock 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;
HttpHeaderBlock 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;
HttpHeaderBlock 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;
HttpHeaderBlock 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;
HttpHeaderBlock 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:
HttpHeaderBlock 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:
HttpHeaderBlock 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) {
HttpHeaderBlock 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()));
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/spdy_utils.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/spdy_utils_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
d5247d11-dec1-4e23-8082-84562476de33 | cpp | google/quiche | metadata_decoder | quiche/quic/core/http/metadata_decoder.cc | quiche/quic/core/http/metadata_decoder_test.cc | #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(quiche::HttpHeaderBlock& headers) {
quic::NoopDecoderStreamErrorDelegate delegate;
quic::QpackEncoder encoder(&delegate, quic::HuffmanEncoding::kDisabled,
quic::CookieCrumbling::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) {
quiche::HttpHeaderBlock 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) {
quiche::HttpHeaderBlock 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());
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/metadata_decoder.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/metadata_decoder_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
05bd352c-f36c-4288-87f4-8cca088e06e7 | 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 | #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/common/http/http_header_block.h"
using quiche::HttpHeaderBlock;
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), 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), 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.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.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.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),
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));
} else {
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_INTERNAL_ERROR,
"Server rejected 0-RTT, aborting because new stream "
"limit 0 is less than current open streams: 1",
_))
.WillOnce(testing::Invoke(connection_,
&MockQuicConnection::ReallyCloseConnection));
}
EXPECT_CALL(*connection_, CloseConnection(QUIC_HANDSHAKE_FAILED, _, _));
crypto_test_utils::HandshakeWithFakeServer(
&config, server_crypto_config_.get(), &helper_, &alarm_factory_,
connection_, crypto_stream_, AlpnForVersion(connection_->version()));
}
TEST_P(QuicSpdyClientSessionTest,
ZeroRttRejectReducesStreamFlowControlTooMuch) {
if (session_->version().UsesQuicCrypto()) {
return;
}
CompleteFirstConnection();
CreateConnection();
QuicConfig config = DefaultQuicConfig();
config.SetInitialMaxStreamDataBytesIncomingBidirectionalToSend(2);
config.SetInitialMaxStreamDataBytesUnidirectionalToSend(1);
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);
stream->WriteOrBufferData("hello", true, nullptr);
if (session_->version().UsesHttp3()) {
EXPECT_CALL(*connection_, CloseConnection(_, _, _))
.WillOnce(testing::Invoke(connection_,
&MockQuicConnection::ReallyCloseConnection));
EXPECT_CALL(*connection_,
CloseConnection(QUIC_ZERO_RTT_UNRETRANSMITTABLE, _, _))
.WillOnce(testing::Invoke(connection_,
&MockQuicConnection::ReallyCloseConnection))
.RetiresOnSaturation();
} else {
EXPECT_CALL(*connection_,
CloseConnection(
QUIC_ZERO_RTT_UNRETRANSMITTABLE,
"Server rejected 0-RTT, aborting because new stream max "
"data 2 for stream 3 is less than currently used: 5",
_))
.Times(1)
.WillOnce(testing::Invoke(connection_,
&MockQuicConnection::ReallyCloseConnection));
}
EXPECT_CALL(*connection_, CloseConnection(QUIC_HANDSHAKE_FAILED, _, _));
crypto_test_utils::HandshakeWithFakeServer(
&config, server_crypto_config_.get(), &helper_, &alarm_factory_,
connection_, crypto_stream_, AlpnForVersion(connection_->version()));
}
TEST_P(QuicSpdyClientSessionTest,
ZeroRttRejectReducesSessionFlowControlTooMuch) {
if (session_->version().UsesQuicCrypto()) {
return;
}
CompleteFirstConnection();
CreateConnection();
QuicSentPacketManager* sent_packet_manager =
QuicConnectionPeer::GetSentPacketManager(connection_);
sent_packet_manager->SetSendAlgorithm(kCubicBytes);
QuicSentPacketManagerPeer::GetPacingSender(sent_packet_manager)
->SetBurstTokens(20);
QuicConfig config = DefaultQuicConfig();
config.SetInitialSessionFlowControlWindowToSend(
kMinimumFlowControlSendWindow);
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);
std::string data_to_send(kMinimumFlowControlSendWindow + 1, 'x');
stream->WriteOrBufferData(data_to_send, true, nullptr);
EXPECT_CALL(*connection_,
CloseConnection(QUIC_ZERO_RTT_UNRETRANSMITTABLE, _, _))
.WillOnce(testing::Invoke(connection_,
&MockQuicConnection::ReallyCloseConnection));
EXPECT_CALL(*connection_, CloseConnection(QUIC_HANDSHAKE_FAILED, _, _));
crypto_test_utils::HandshakeWithFakeServer(
&config, server_crypto_config_.get(), &helper_, &alarm_factory_,
connection_, crypto_stream_, AlpnForVersion(connection_->version()));
}
TEST_P(QuicSpdyClientSessionTest, BadSettingsInZeroRttResumption) {
if (!session_->version().UsesHttp3()) {
return;
}
CompleteFirstConnection();
CreateConnection();
CompleteCryptoHandshake();
EXPECT_TRUE(session_->GetCryptoStream()->EarlyDataAccepted());
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_HTTP_ZERO_RTT_RESUMPTION_SETTINGS_MISMATCH, _, _))
.WillOnce(testing::Invoke(connection_,
&MockQuicConnection::ReallyCloseConnection));
SettingsFrame settings;
settings.values[SETTINGS_QPACK_MAX_TABLE_CAPACITY] = 1;
settings.values[SETTINGS_MAX_FIELD_SECTION_SIZE] = 5;
settings.values[256] = 4;
session_->OnSettingsFrame(settings);
}
TEST_P(QuicSpdyClientSessionTest, BadSettingsInZeroRttRejection) {
if (!session_->version().UsesHttp3()) {
return;
}
CompleteFirstConnection();
CreateConnection();
SSL_CTX_set_early_data_enabled(server_crypto_config_->ssl_ctx(), false);
session_->CryptoConnect();
EXPECT_TRUE(session_->IsEncryptionEstablished());
QuicConfig config = DefaultQuicConfig();
crypto_test_utils::HandshakeWithFakeServer(
&config, server_crypto_config_.get(), &helper_, &alarm_factory_,
connection_, crypto_stream_, AlpnForVersion(connection_->version()));
EXPECT_FALSE(session_->GetCryptoStream()->EarlyDataAccepted());
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_HTTP_ZERO_RTT_REJECTION_SETTINGS_MISMATCH, _, _))
.WillOnce(testing::Invoke(connection_,
&MockQuicConnection::ReallyCloseConnection));
SettingsFrame settings;
settings.values[SETTINGS_QPACK_MAX_TABLE_CAPACITY] = 2;
settings.values[SETTINGS_MAX_FIELD_SECTION_SIZE] = 4;
settings.values[256] = 4;
session_->OnSettingsFrame(settings);
}
TEST_P(QuicSpdyClientSessionTest, ServerAcceptsZeroRttButOmitSetting) {
if (!session_->version().UsesHttp3()) {
return;
}
CompleteFirstConnection();
CreateConnection();
CompleteCryptoHandshake();
EXPECT_TRUE(session_->GetMutableCryptoStream()->EarlyDataAccepted());
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_HTTP_ZERO_RTT_RESUMPTION_SETTINGS_MISMATCH, _, _))
.WillOnce(testing::Invoke(connection_,
&MockQuicConnection::ReallyCloseConnection));
SettingsFrame settings;
settings.values[SETTINGS_QPACK_MAX_TABLE_CAPACITY] = 1;
settings.values[256] = 4;
session_->OnSettingsFrame(settings);
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/quic_spdy_client_session.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/quic_spdy_client_session_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
70fc085d-109b-4714-b8b0-16c42530fb57 | cpp | google/quiche | quic_spdy_stream | quiche/quic/core/http/quic_spdy_stream.cc | quiche/quic/core/http/quic_spdy_stream_test.cc | #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/core/spdy_protocol.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"
using ::quiche::Capsule;
using ::quiche::CapsuleType;
using ::quiche::HttpHeaderBlock;
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 OnOriginFrameStart(QuicByteCount ) override {
CloseConnectionOnWrongFrame("ORIGIN");
return false;
}
bool OnOriginFrame(const OriginFrame& ) override {
CloseConnectionOnWrongFrame("ORIGIN");
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(
HttpHeaderBlock header_block, bool fin,
quiche::QuicheReferenceCountedPointer<QuicAckListenerInterface>
ack_listener) {
if (!AssertNotWebTransportDataStream("writing headers")) {
return 0;
}
QuicConnection::ScopedPacketFlusher flusher(spdy_session_->connection());
MaybeProcessSentWebTransportHeaders(header_block);
if (web_transport_ != nullptr &&
spdy_session_->perspective() == Perspective::IS_SERVER &&
spdy_session_->SupportedWebTransportVersion() ==
WebTransportHttp3Version::kDraft02) {
header_block["sec-webtransport-http3-draft"] = "draft02";
}
size_t bytes_written =
WriteHeadersImpl(std::move(header_block), fin, std::move(ack_listener));
if (!VersionUsesHttp3(transport_version()) && fin) {
SetFinSent();
CloseWriteSide();
}
if (web_transport_ != nullptr &&
session()->perspective() == Perspective::IS_CLIENT) {
WriteGreaseCapsule();
if (spdy_session_->http_datagram_support() ==
HttpDatagramSupport::kDraft04) {
uint64_t capsule_type = 0xff37a2;
constexpr unsigned char capsule_data[4] = {
0x80, 0xff, 0x7c, 0x00,
};
WriteCapsule(Capsule::Unknown(
capsule_type,
absl::string_view(reinterpret_cast<const char*>(capsule_data),
sizeof(capsule_data))));
WriteGreaseCapsule();
}
}
if (connect_ip_visitor_ != nullptr) {
connect_ip_visitor_->OnHeadersWritten();
}
return bytes_written;
}
void QuicSpdyStream::WriteOrBufferBody(absl::string_view data, bool fin) {
if (!AssertNotWebTransportDataStream("writing body data")) {
return;
}
if (!VersionUsesHttp3(transport_version()) || data.length() == 0) {
WriteOrBufferData(data, fin, nullptr);
return;
}
QuicConnection::ScopedPacketFlusher flusher(spdy_session_->connection());
const bool success =
WriteDataFrameHeader(data.length(), true);
QUICHE_DCHECK(success);
QUIC_DVLOG(1) << ENDPOINT << "Stream " << id()
<< " is writing DATA frame payload of length " << data.length()
<< " with fin " << fin;
WriteOrBufferData(data, fin, nullptr);
}
size_t QuicSpdyStream::WriteTrailers(
HttpHeaderBlock trailer_block,
quiche::QuicheReferenceCountedPointer<QuicAckListenerInterface>
ack_listener) {
if (fin_sent()) {
QUIC_BUG(quic_bug_10410_1)
<< "Trailers cannot be sent after a FIN, on stream " << id();
return 0;
}
if (!VersionUsesHttp3(transport_version())) {
const QuicStreamOffset final_offset =
stream_bytes_written() + BufferedDataBytes();
QUIC_DVLOG(1) << ENDPOINT << "Inserting trailer: (" << kFinalOffsetHeaderKey
<< ", " << final_offset << ")";
trailer_block.insert(
std::make_pair(kFinalOffsetHeaderKey, absl::StrCat(final_offset)));
}
const bool kFin = true;
size_t bytes_written =
WriteHeadersImpl(std::move(trailer_block), kFin, std::move(ack_listener));
if (!VersionUsesHttp3(transport_version())) {
SetFinSent();
if (BufferedDataBytes() == 0) {
CloseWriteSide();
}
}
return bytes_written;
}
QuicConsumedData QuicSpdyStream::WritevBody(const struct iovec* iov, int count,
bool fin) {
quiche::QuicheMemSliceStorage storage(
iov, count,
session()->connection()->helper()->GetStreamSendBufferAllocator(),
GetQuicFlag(quic_send_buffer_max_data_slice_size));
return WriteBodySlices(storage.ToSpan(), fin);
}
bool QuicSpdyStream::WriteDataFrameHeader(QuicByteCount data_length,
bool force_write) {
QUICHE_DCHECK(VersionUsesHttp3(transport_version()));
QUICHE_DCHECK_GT(data_length, 0u);
quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader(
data_length,
spdy_session_->connection()->helper()->GetStreamSendBufferAllocator());
const bool can_write = CanWriteNewDataAfterData(header.size());
if (!can_write && !force_write) {
return false;
}
if (spdy_session_->debug_visitor()) {
spdy_session_->debug_visitor()->OnDataFrameSent(id(), data_length);
}
unacked_frame_headers_offsets_.Add(
send_buffer().stream_offset(),
send_buffer().stream_offset() + header.size());
QUIC_DVLOG(1) << ENDPOINT << "Stream " << id()
<< " is writing DATA frame header of length " << header.size();
if (can_write) {
quiche::QuicheMemSlice header_slice(std::move(header));
WriteMemSlices(absl::MakeSpan(&header_slice, 1), false);
} else {
QUICHE_DCHECK(force_write);
WriteOrBufferData(header.AsStringView(), false, nullptr);
}
return true;
}
QuicConsumedData QuicSpdyStream::WriteBodySlices(
absl::Span<quiche::QuicheMemSlice> slices, bool fin) {
if (!VersionUsesHttp3(transport_version()) || slices.empty()) {
return WriteMemSlices(slices, fin);
}
QuicConnection::ScopedPacketFlusher flusher(spdy_session_->connection());
const QuicByteCount data_size = MemSliceSpanTotalSize(slices);
if (!WriteDataFrameHeader(data_size, false)) {
return {0, false};
}
QUIC_DVLOG(1) << ENDPOINT << "Stream " << id()
<< " is writing DATA frame payload of length " << data_size;
return WriteMemSlices(slices, fin);
}
size_t QuicSpdyStream::Readv(const struct iovec* iov, size_t iov_len) {
QUICHE_DCHECK(FinishedReadingHeaders());
if (!VersionUsesHttp3(transport_version())) {
return sequencer()->Readv(iov, iov_len);
}
size_t bytes_read = 0;
sequencer()->MarkConsumed(body_manager_.ReadBody(iov, iov_len, &bytes_read));
return bytes_read;
}
int QuicSpdyStream::GetReadableRegions(iovec* iov, size_t iov_len) const {
QUICHE_DCHECK(FinishedReadingHeaders());
if (!VersionUsesHttp3(transport_version())) {
return sequencer()->GetReadableRegions(iov, iov_len);
}
return body_manager_.PeekBody(iov, iov_len);
}
void QuicSpdyStream::MarkConsumed(size_t num_bytes) {
QUICHE_DCHECK(FinishedReadingHeaders());
if (!VersionUsesHttp3(transport_version())) {
sequencer()->MarkConsumed(num_bytes);
return;
}
sequencer()->MarkConsumed(body_manager_.OnBodyConsumed(num_bytes));
}
bool QuicSpdyStream::IsDoneReading() const {
bool done_reading_headers = FinishedReadingHeaders();
bool done_reading_body = sequencer()->IsClosed();
bool done_reading_trailers = FinishedReadingTrailers();
return done_reading_headers && done_reading_body && done_reading_trailers;
}
bool QuicSpdyStream::HasBytesToRead() const {
if (!VersionUsesHttp3(transport_version())) {
return sequencer()->HasBytesToRead();
}
return body_manager_.HasBytesToRead();
}
QuicByteCount QuicSpdyStream::ReadableBytes() const {
if (!VersionUsesHttp3(transport_version())) {
return sequencer()->ReadableBytes();
}
return body_manager_.ReadableBytes();
}
void QuicSpdyStream::MarkTrailersConsumed() { trailers_consumed_ = true; }
uint64_t QuicSpdyStream::total_body_bytes_read() const {
if (VersionUsesHttp3(transport_version())) {
return body_manager_.total_body_bytes_received();
}
return sequencer()->NumBytesConsumed();
}
void QuicSpdyStream::ConsumeHeaderList() {
header_list_.Clear();
if (!FinishedReadingHeaders()) {
return;
}
if (!VersionUsesHttp3(transport_version())) {
sequencer()->SetUnblocked();
return;
}
if (body_manager_.HasBytesToRead()) {
HandleBodyAvailable();
return;
}
if (sequencer()->IsClosed() &&
!on_body_available_called_because_sequencer_is_closed_) {
on_body_available_called_because_sequencer_is_closed_ = true;
HandleBodyAvailable();
}
}
void QuicSpdyStream::OnStreamHeadersPriority(
const spdy::SpdyStreamPrecedence& precedence) {
QUICHE_DCHECK_EQ(Perspective::IS_SERVER,
session()->connection()->perspective());
SetPriority(QuicStreamPriority(HttpStreamPriority{
precedence.spdy3_priority(), HttpStreamPriority::kDefaultIncremental}));
}
void QuicSpdyStream::OnStreamHeaderList(bool fin, size_t frame_len,
const QuicHeaderList& header_list) {
if (!spdy_session()->user_agent_id().has_value()) {
std::string uaid;
for (const auto& kv : header_list) {
if (quiche::QuicheTextUtils::ToLower(kv.first) == kUserAgentHeaderName) {
uaid = kv.second;
break;
}
}
spdy_session()->SetUserAgentId(std::move(uaid));
}
if ((VersionUsesHttp3(transport_version()) &&
header_list_size_limit_exceeded_) ||
(!VersionUsesHttp3(transport_version()) && header_list.empty())) {
OnHeadersTooLarge();
if (IsDoneReading()) {
return;
}
}
if (!NextHeaderIsTrailer()) {
OnInitialHeadersComplete(fin, frame_len, header_list);
} else {
OnTrailingHeadersComplete(fin, frame_len, header_list);
}
}
void QuicSpdyStream::OnHeadersDecoded(QuicHeaderList headers,
bool header_list_size_limit_exceeded) {
header_list_size_limit_exceeded_ = header_list_size_limit_exceeded;
qpack_decoded_headers_accumulator_.reset();
QuicSpdySession::LogHeaderCompressionRatioHistogram(
true,
false, headers.compressed_header_bytes(),
headers.uncompressed_header_bytes());
header_decoding_delay_ = QuicTime::Delta::Zero();
if (blocked_on_decoding_headers_) {
const QuicTime now = session()->GetClock()->ApproximateNow();
if (!header_block_received_time_.IsInitialized() ||
now < header_block_received_time_) {
QUICHE_BUG(QuicSpdyStream_time_flows_backwards);
} else {
header_decoding_delay_ = now - header_block_received_time_;
}
}
Http3DebugVisitor* const debug_visitor = spdy_session()->debug_visitor();
if (debug_visitor) {
debug_visitor->OnHeadersDecoded(id(), headers);
}
OnStreamHeaderList( false, headers_payload_length_, headers);
if (blocked_on_decoding_headers_) {
blocked_on_decoding_headers_ = false;
OnDataAvailable();
}
}
void QuicSpdyStream::OnHeaderDecodingError(QuicErrorCode error_code,
absl::string_view error_message) {
qpack_decoded_headers_accumulator_.reset();
std::string connection_close_error_message = absl::StrCat(
"Error decoding ", headers_decompressed_ ? "trailers" : "headers",
" on stream ", id(), ": ", error_message);
OnUnrecoverableError(error_code, connection_close_error_message);
}
void QuicSpdyStream::MaybeSendPriorityUpdateFrame() {
if (!VersionUsesHttp3(transport_version()) ||
session()->perspective() != Perspective::IS_CLIENT) {
return;
}
if (priority().type() != QuicPriorityType::kHttp) {
return;
}
if (last_sent_priority_ == priority()) {
return;
}
last_sent_priority_ = priority();
spdy_session_->WriteHttp3PriorityUpdate(id(), priority().http());
}
void QuicSpdyStream::OnHeadersTooLarge() { Reset(QUIC_HEADERS_TOO_LARGE); }
void QuicSpdyStream::OnInitialHeadersComplete(
bool fin, size_t , const QuicHeaderList& header_list) {
headers_decompressed_ = true;
header_list_ = header_list;
bool header_too_large = VersionUsesHttp3(transport_version())
? header_list_size_limit_exceeded_
: header_list.empty();
if (!AreHeaderFieldValuesValid(header_list)) {
OnInvalidHeaders();
return;
}
if (!header_too_large && !ValidateReceivedHeaders(header_list)) {
QUIC_CODE_COUNT_N(quic_validate_request_header, 1, 2);
QUICHE_DCHECK(!invalid_request_details().empty())
<< "ValidatedRequestHeaders() returns false without populating "
"invalid_request_details_";
if (GetQuicReloadableFlag(quic_act_upon_invalid_header)) {
QUIC_RELOADABLE_FLAG_COUNT(quic_act_upon_invalid_header);
OnInvalidHeaders();
return;
}
}
QUIC_CODE_COUNT_N(quic_validate_request_header, 2, 2);
if (!header_too_large) {
MaybeProcessReceivedWebTransportHeaders();
}
if (VersionUsesHttp3(transport_version())) {
if (fin) {
OnStreamFrame(QuicStreamFrame(id(), true,
highest_received_byte_offset(),
absl::string_view()));
}
return;
}
if (fin && !rst_sent()) {
OnStreamFrame(
QuicStreamFrame(id(), fin, 0, absl::string_view()));
}
if (FinishedReadingHeaders()) {
sequencer()->SetUnblocked();
}
}
bool QuicSpdyStream::CopyAndValidateTrailers(
const QuicHeaderList& header_list, bool expect_final_byte_offset,
size_t* final_byte_offset, quiche::HttpHeaderBlock* trailers) {
return SpdyUtils::CopyAndValidateTrailers(
header_list, expect_final_byte_offset, final_byte_offset, trailers);
}
void QuicSpdyStream::OnTrailingHeadersComplete(
bool fin, size_t , const QuicHeaderList& header_list) {
QUICHE_DCHECK(!trailers_decompressed_);
if (!VersionUsesHttp3(transport_version()) && fin_received()) {
QUIC_DLOG(INFO) << ENDPOINT
<< "Received Trailers after FIN, on stream: " << id();
stream_delegate()->OnStreamError(QUIC_INVALID_HEADERS_STREAM_DATA,
"Trailers after fin");
return;
}
if (!VersionUsesHttp3(transport_version()) && !fin) {
QUIC_DLOG(INFO) << ENDPOINT
<< "Trailers must have FIN set, on stream: " << id();
stream_delegate()->OnStreamError(QUIC_INVALID_HEADERS_STREAM_DATA,
"Fin missing from trailers");
return;
}
size_t final_byte_offset = 0;
const bool expect_final_byte_offset = !VersionUsesHttp3(transport_version());
if (!CopyAndValidateTrailers(header_list, expect_final_byte_offset,
&final_byte_offset, &received_trailers_)) {
QUIC_DLOG(ERROR) << ENDPOINT << "Trailers for stream " << id()
<< " are malformed.";
stream_delegate()->OnStreamError(QUIC_INVALID_HEADERS_STREAM_DATA,
"Trailers are malformed");
return;
}
trailers_decompressed_ = true;
if (fin) {
const QuicStreamOffset offset = VersionUsesHttp3(transport_version())
? highest_received_byte_offset()
: final_byte_offset;
OnStreamFrame(QuicStreamFrame(id(), fin, offset, absl::string_view()));
}
}
void QuicSpdyStream::RegisterMetadataVisitor(MetadataVisitor* visitor) {
metadata_visitor_ = visitor;
}
void QuicSpdyStream::UnregisterMetadataVisitor() {
metadata_visitor_ = nullptr;
}
void QuicSpdyStream::OnPriorityFrame(
const spdy::SpdyStreamPrecedence& precedence) {
QUICHE_DCHECK_EQ(Perspective::IS_SERVER,
session()->connection()->perspective());
SetPriority(QuicStreamPriority(HttpStreamPriority{
precedence.spdy3_priority(), HttpStreamPriority::kDefaultIncremental}));
}
void QuicSpdyStream::OnStreamReset(const QuicRstStreamFrame& frame) {
if (web_transport_data_ != nullptr) {
WebTransportStreamVisitor* webtransport_visitor =
web_transport_data_->adapter.visitor();
if (webtransport_visitor != nullptr) {
webtransport_visitor->OnResetStreamReceived(
Http3ErrorToWebTransportOrDefault(frame.ietf_error_code));
}
QuicStream::OnStreamReset(frame);
return;
}
if (VersionUsesHttp3(transport_version()) && !fin_received() &&
spdy_session_->qpack_decoder()) {
spdy_session_->qpack_decoder()->OnStreamReset(id());
qpack_decoded_headers_accumulator_.reset();
}
if (VersionUsesHttp3(transport_version()) ||
frame.error_code != QUIC_STREAM_NO_ERROR) {
QuicStream::OnStreamReset(frame);
return;
}
QUIC_DVLOG(1) << ENDPOINT
<< "Received QUIC_STREAM_NO_ERROR, not discarding response";
set_rst_received(true);
MaybeIncreaseHighestReceivedOffset(frame.byte_offset);
set_stream_error(frame.error());
CloseWriteSide();
}
void QuicSpdyStream::ResetWithError(QuicResetStreamError error) {
if (VersionUsesHttp3(transport_version()) && !fin_received() &&
spdy_session_->qpack_decoder() && web_transport_data_ == nullptr) {
spdy_session_->qpack_decoder()->OnStreamReset(id());
qpack_decoded_headers_accumulator_.reset();
}
QuicStream::ResetWithError(error);
}
bool QuicSpdyStream::OnStopSending(QuicResetStreamError error) {
if (web_transport_data_ != nullptr) {
WebTransportStreamVisitor* visitor = web_transport_data_->adapter.visitor();
if (visitor != nullptr) {
visitor->OnStopSendingReceived(
Http3ErrorToWebTransportOrDefault(error.ietf_application_code()));
}
}
return QuicStream::OnStopSending(error);
}
void QuicSpdyStream::OnWriteSideInDataRecvdState() {
if (web_transport_data_ != nullptr) {
WebTransportStreamVisitor* visitor = web_transport_data_->adapter.visitor();
if (visitor != nullptr) {
visitor->OnWriteSideInDataRecvdState();
}
}
QuicStream::OnWriteSideInDataRecvdState();
}
void QuicSpdyStream::OnDataAvailable() {
if (!VersionUsesHttp3(transport_version())) {
QUICHE_DCHECK(FinishedReadingHeaders());
}
if (!VersionUsesHttp3(transport_version())) {
HandleBodyAvailable();
return;
}
if (web_transport_data_ != nullptr) {
web_transport_data_->adapter.OnDataAvailable();
return;
}
if (!spdy_session()->ShouldProcessIncomingRequests()) {
spdy_session()->OnStreamWaitingForClientSettings(id());
return;
}
if (is_decoder_processing_input_) {
return;
}
if (blocked_on_decoding_headers_) {
return;
}
if (spdy_session_->SupportsWebTransport()) {
decoder_.EnableWebTransportStreamParsing();
}
iovec iov;
while (session()->connection()->connected() && !reading_stopped() &&
decoder_.error() == QUIC_NO_ERROR) {
QUICHE_DCHECK_GE(sequencer_offset_, sequencer()->NumBytesConsumed());
if (!sequencer()->PeekRegion(sequencer_offset_, &iov)) {
break;
}
QUICHE_DCHECK(!sequencer()->IsClosed());
is_decoder_processing_input_ = true;
QuicByteCount processed_bytes = decoder_.ProcessInput(
reinterpret_cast<const char*>(iov.iov_base), iov.iov_len);
is_decoder_processing_input_ = false;
if (!session()->connection()->connected()) {
return;
}
sequencer_offset_ += processed_bytes;
if (blocked_on_decoding_headers_) {
return;
}
if (web_transport_data_ != nullptr) {
return;
}
}
if (!FinishedReadingHeaders()) {
return;
}
if (body_manager_.HasBytesToRead()) {
HandleBodyAvailable();
return;
}
if (sequencer()->IsClosed() &&
!on_body_available_called_because_sequencer_is_closed_) {
on_body_available_called_because_sequencer_is_closed_ = true;
HandleBodyAvailable();
}
}
void QuicSpdyStream::OnClose() {
QuicStream::OnClose();
qpack_decoded_headers_accumulator_.reset();
if (visitor_) {
Visitor* visitor = visitor_;
visitor_ = nullptr;
visitor->OnClose(this);
}
if (web_transport_ != nullptr) {
web_transport_->OnConnectStreamClosing();
}
if (web_transport_data_ != nullptr) {
WebTransportHttp3* web_transport =
spdy_session_->GetWebTransportSession(web_transport_data_->session_id);
if (web_transport == nullptr) {
QUIC_DLOG(WARNING) << ENDPOINT << "WebTransport stream " << id()
<< " attempted to notify parent session "
<< web_transport_data_->session_id
<< ", but the session could not be found.";
return;
}
web_transport->OnStreamClosed(id());
}
}
void QuicSpdyStream::OnCanWrite() {
QuicStream::OnCanWrite();
if (!HasBufferedData() && fin_sent()) {
CloseWriteSide();
}
}
bool QuicSpdyStream::FinishedReadingHeaders() const {
return headers_decompressed_ && header_list_.empty();
}
bool QuicSpdyStream::ParseHeaderStatusCode(const HttpHeaderBlock& header,
int* status_code) {
HttpHeaderBlock::const_iterator it = header.find(spdy::kHttp2StatusHeader);
if (it == header.end()) {
return false;
}
const absl::string_view status(it->second);
return ParseHeaderStatusCode(status, status_code);
}
bool QuicSpdyStream::ParseHeaderStatusCode(absl::string_view status,
int* status_code) {
if (status.size() != 3) {
return false;
}
if (status[0] < '1' || status[0] > '5') {
return false;
}
if (!isdigit(status[1]) || !isdigit(status[2])) {
return false;
}
return absl::SimpleAtoi(status, status_code);
}
bool QuicSpdyStream::FinishedReadingTrailers() const {
if (!fin_received()) {
return false;
} else if (!trailers_decompressed_) {
return true;
} else {
return trailers_consumed_;
}
}
bool QuicSpdyStream::OnDataFrameStart(QuicByteCount header_length,
QuicByteCount payload_length) {
QUICHE_DCHECK(VersionUsesHttp3(transport_version()));
if (spdy_session_->debug_visitor()) {
spdy_session_->debug_visitor()->OnDataFrameReceived(id(), payload_length);
}
if (!headers_decompressed_ || trailers_decompressed_) {
QUICHE_LOG(INFO) << ENDPOINT << "stream_id: " << id()
<< ", headers_decompressed: "
<< (headers_decompressed_ ? "true" : "false")
<< ", trailers_decompressed: "
<< (trailers_decompressed_ ? "true" : "false")
<< ", NumBytesConsumed: "
<< sequencer()->NumBytesConsumed()
<< ", total_body_bytes_received: "
<< body_manager_.total_body_bytes_received()
<< ", header_length: " << header_length
<< ", payload_length: " << payload_length;
stream_delegate()->OnStreamError(
QUIC_HTTP_INVALID_FRAME_SEQUENCE_ON_SPDY_STREAM,
"Unexpected DATA frame received.");
return false;
}
sequencer()->MarkConsumed(body_manager_.OnNonBody(header_length));
return true;
}
bool QuicSpdyStream::OnDataFramePayload(absl::string_view payload) {
QUICHE_DCHECK(VersionUsesHttp3(transport_version()));
body_manager_.OnBody(payload);
return true;
}
bool QuicSpdyStream::OnDataFrameEnd() {
QUICHE_DCHECK(VersionUsesHttp3(transport_version()));
QUIC_DVLOG(1) << ENDPOINT
<< "Reaches the end of a data frame. Total bytes received are "
<< body_manager_.total_body_bytes_received();
return true;
}
bool QuicSpdyStream::OnStreamFrameAcked(QuicStreamOffset offset,
QuicByteCount data_length,
bool fin_acked,
QuicTime::Delta ack_delay_time,
QuicTime receive_timestamp,
QuicByteCount* newly_acked_length) {
const bool new_data_acked = QuicStream::OnStreamFrameAcked(
offset, data_length, fin_acked, ack_delay_time, receive_timestamp,
newly_acked_length);
const QuicByteCount newly_acked_header_length =
GetNumFrameHeadersInInterval(offset, data_length);
QUICHE_DCHECK_LE(newly_acked_header_length, *newly_acked_length);
unacked_frame_headers_offsets_.Difference(offset, offset + data_length);
if (ack_listener_ != nullptr && new_data_acked) {
ack_listener_->OnPacketAcked(
*newly_acked_length - newly_acked_header_length, ack_delay_time);
}
return new_data_acked;
}
void QuicSpdyStream::OnStreamFrameRetransmitted(QuicStreamOffset offset,
QuicByteCount data_length,
bool fin_retransmitted) {
QuicStream::OnStreamFrameRetransmitted(offset, data_length,
fin_retransmitted);
const QuicByteCount retransmitted_header_length =
GetNumFrameHeadersInInterval(offset, data_length);
QUICHE_DCHECK_LE(retransmitted_header_length, data_length);
if (ack_listener_ != nullptr) {
ack_listener_->OnPacketRetransmitted(data_length -
retransmitted_header_length);
}
}
QuicByteCount QuicSpdyStream::GetNumFrameHeadersInInterval(
QuicStreamOffset offset, QuicByteCount data_length) const {
QuicByteCount header_acked_length = 0;
QuicIntervalSet<QuicStreamOffset> newly_acked(offset, offset + data_length);
newly_acked.Intersection(unacked_frame_headers_offsets_);
for (const auto& interval : newly_acked) {
header_acked_length += interval.Length();
}
return header_acked_length;
}
bool QuicSpdyStream::OnHeadersFrameStart(QuicByteCount header_length,
QuicByteCount payload_length) {
QUICHE_DCHECK(VersionUsesHttp3(transport_version()));
QUICHE_DCHECK(!qpack_decoded_headers_accumulator_);
if (spdy_session_->debug_visitor()) {
spdy_session_->debug_visitor()->OnHeadersFrameReceived(id(),
payload_length);
}
headers_payload_length_ = payload_length;
if (trailers_decompressed_) {
QUICHE_LOG(INFO) << ENDPOINT << "stream_id: " << id()
<< ", headers_decompressed: "
<< (headers_decompressed_ ? "true" : "false")
<< ", NumBytesConsumed: "
<< sequencer()->NumBytesConsumed()
<< ", total_body_bytes_received: "
<< body_manager_.total_body_bytes_received();
stream_delegate()->OnStreamError(
QUIC_HTTP_INVALID_FRAME_SEQUENCE_ON_SPDY_STREAM,
"HEADERS frame received after trailing HEADERS.");
return false;
}
sequencer()->MarkConsumed(body_manager_.OnNonBody(header_length));
qpack_decoded_headers_accumulator_ =
std::make_unique<QpackDecodedHeadersAccumulator>(
id(), spdy_session_->qpack_decoder(), this,
spdy_session_->max_inbound_header_list_size());
return true;
}
bool QuicSpdyStream::OnHeadersFramePayload(absl::string_view payload) {
QUICHE_DCHECK(VersionUsesHttp3(transport_version()));
if (!qpack_decoded_headers_accumulator_) {
QUIC_BUG(b215142466_OnHeadersFramePayload);
OnHeaderDecodingError(QUIC_INTERNAL_ERROR,
"qpack_decoded_headers_accumulator_ is nullptr");
return false;
}
qpack_decoded_headers_accumulator_->Decode(payload);
if (!qpack_decoded_headers_accumulator_) {
return false;
}
sequencer()->MarkConsumed(body_manager_.OnNonBody(payload.size()));
return true;
}
bool QuicSpdyStream::OnHeadersFrameEnd() {
QUICHE_DCHECK(VersionUsesHttp3(transport_version()));
if (!qpack_decoded_headers_accumulator_) {
QUIC_BUG(b215142466_OnHeadersFrameEnd);
OnHeaderDecodingError(QUIC_INTERNAL_ERROR,
"qpack_decoded_headers_accumulator_ is nullptr");
return false;
}
qpack_decoded_headers_accumulator_->EndHeaderBlock();
if (qpack_decoded_headers_accumulator_) {
blocked_on_decoding_headers_ = true;
header_block_received_time_ = session()->GetClock()->ApproximateNow();
return false;
}
return !sequencer()->IsClosed() && !reading_stopped();
}
void QuicSpdyStream::OnWebTransportStreamFrameType(
QuicByteCount header_length, WebTransportSessionId session_id) {
QUIC_DVLOG(1) << ENDPOINT << " Received WEBTRANSPORT_STREAM on stream "
<< id() << " for session " << session_id;
QuicStreamOffset offset = sequencer()->NumBytesConsumed();
sequencer()->MarkConsumed(header_length);
std::optional<WebTransportHttp3Version> version =
spdy_session_->SupportedWebTransportVersion();
QUICHE_DCHECK(version.has_value());
if (version == WebTransportHttp3Version::kDraft02) {
if (headers_payload_length_ > 0 || headers_decompressed_) {
std::string error =
absl::StrCat("Stream ", id(),
" attempted to convert itself into a WebTransport data "
"stream, but it already has HTTP data on it");
QUIC_PEER_BUG(WEBTRANSPORT_STREAM received on HTTP request)
<< ENDPOINT << error;
OnUnrecoverableError(QUIC_HTTP_INVALID_FRAME_SEQUENCE_ON_SPDY_STREAM,
error);
return;
}
} else {
if (offset > 0) {
std::string error =
absl::StrCat("Stream ", id(),
" received WEBTRANSPORT_STREAM at a non-zero offset");
QUIC_DLOG(ERROR) << ENDPOINT << error;
OnUnrecoverableError(QUIC_HTTP_INVALID_FRAME_SEQUENCE_ON_SPDY_STREAM,
error);
return;
}
}
if (QuicUtils::IsOutgoingStreamId(spdy_session_->version(), id(),
spdy_session_->perspective())) {
std::string error = absl::StrCat(
"Stream ", id(),
" attempted to convert itself into a WebTransport data stream, but "
"only the initiator of the stream can do that");
QUIC_PEER_BUG(WEBTRANSPORT_STREAM received on outgoing request)
<< ENDPOINT << error;
OnUnrecoverableError(QUIC_HTTP_INVALID_FRAME_SEQUENCE_ON_SPDY_STREAM,
error);
return;
}
QUICHE_DCHECK(web_transport_ == nullptr);
web_transport_data_ =
std::make_unique<WebTransportDataStream>(this, session_id);
spdy_session_->AssociateIncomingWebTransportStreamWithSession(session_id,
id());
}
bool QuicSpdyStream::OnMetadataFrameStart(QuicByteCount header_length,
QuicByteCount payload_length) {
if (metadata_visitor_ == nullptr) {
return OnUnknownFrameStart(
static_cast<uint64_t>(quic::HttpFrameType::METADATA), header_length,
payload_length);
}
QUIC_BUG_IF(Invalid METADATA state, metadata_decoder_ != nullptr);
constexpr size_t kMaxMetadataBlockSize = 1 << 20;
metadata_decoder_ = std::make_unique<MetadataDecoder>(
id(), kMaxMetadataBlockSize, header_length, payload_length);
QUIC_DVLOG(1) << ENDPOINT << "Consuming " << header_length
<< " byte long frame header of METADATA.";
sequencer()->MarkConsumed(body_manager_.OnNonBody(header_length));
return true;
}
bool QuicSpdyStream::OnMetadataFramePayload(absl::string_view payload) {
if (metadata_visitor_ == nullptr) {
return OnUnknownFramePayload(payload);
}
if (!metadata_decoder_->Decode(payload)) {
OnUnrecoverableError(QUIC_DECOMPRESSION_FAILURE,
metadata_decoder_->error_message());
return false;
}
QUIC_DVLOG(1) << ENDPOINT << "Consuming " << payload.size()
<< " bytes of payload of METADATA.";
sequencer()->MarkConsumed(body_manager_.OnNonBody(payload.size()));
return true;
}
bool QuicSpdyStream::OnMetadataFrameEnd() {
if (metadata_visitor_ == nullptr) {
return OnUnknownFrameEnd();
}
if (!metadata_decoder_->EndHeaderBlock()) {
OnUnrecoverableError(QUIC_DECOMPRESSION_FAILURE,
metadata_decoder_->error_message());
return false;
}
metadata_visitor_->OnMetadataComplete(metadata_decoder_->frame_len(),
metadata_decoder_->headers());
metadata_decoder_.reset();
return !sequencer()->IsClosed() && !reading_stopped();
}
bool QuicSpdyStream::OnUnknownFrameStart(uint64_t frame_type,
QuicByteCount header_length,
QuicByteCount payload_length) {
if (spdy_session_->debug_visitor()) {
spdy_session_->debug_visitor()->OnUnknownFrameReceived(id(), frame_type,
payload_length);
}
spdy_session_->OnUnknownFrameStart(id(), frame_type, header_length,
payload_length);
QUIC_DVLOG(1) << ENDPOINT << "Consuming " << header_length
<< " byte long frame header of frame of unknown type "
<< frame_type << ".";
sequencer()->MarkConsumed(body_manager_.OnNonBody(header_length));
return true;
}
bool QuicSpdyStream::OnUnknownFramePayload(absl::string_view payload) {
spdy_session_->OnUnknownFramePayload(id(), payload);
QUIC_DVLOG(1) << ENDPOINT << "Consuming " << payload.size()
<< " bytes of payload of frame of unknown type.";
sequencer()->MarkConsumed(body_manager_.OnNonBody(payload.size()));
return true;
}
bool QuicSpdyStream::OnUnknownFrameEnd() { return true; }
size_t QuicSpdyStream::WriteHeadersImpl(
quiche::HttpHeaderBlock header_block, bool fin,
quiche::QuicheReferenceCountedPointer<QuicAckListenerInterface>
ack_listener) {
if (!VersionUsesHttp3(transport_version())) {
return spdy_session_->WriteHeadersOnHeadersStream(
id(), std::move(header_block), fin,
spdy::SpdyStreamPrecedence(priority().http().urgency),
std::move(ack_listener));
}
QuicByteCount encoder_stream_sent_byte_count;
std::string encoded_headers =
spdy_session_->qpack_encoder()->EncodeHeaderList(
id(), header_block, &encoder_stream_sent_byte_count);
if (spdy_session_->debug_visitor()) {
spdy_session_->debug_visitor()->OnHeadersFrameSent(id(), header_block);
}
std::string headers_frame_header =
HttpEncoder::SerializeHeadersFrameHeader(encoded_headers.size());
unacked_frame_headers_offsets_.Add(
send_buffer().stream_offset(),
send_buffer().stream_offset() + headers_frame_header.length());
QUIC_DVLOG(1) << ENDPOINT << "Stream " << id()
<< " is writing HEADERS frame header of length "
<< headers_frame_header.length() << ", and payload of length "
<< encoded_headers.length() << " with fin " << fin;
WriteOrBufferData(absl::StrCat(headers_frame_header, encoded_headers), fin,
nullptr);
QuicSpdySession::LogHeaderCompressionRatioHistogram(
true,
true,
encoded_headers.size() + encoder_stream_sent_byte_count,
header_block.TotalBytesUsed());
return encoded_headers.size();
}
bool QuicSpdyStream::CanWriteNewBodyData(QuicByteCount write_size) const {
QUICHE_DCHECK_NE(0u, write_size);
if (!VersionUsesHttp3(transport_version())) {
return CanWriteNewData();
}
return CanWriteNewDataAfterData(
HttpEncoder::GetDataFrameHeaderLength(write_size));
}
void QuicSpdyStream::MaybeProcessReceivedWebTransportHeaders() {
if (!spdy_session_->SupportsWebTransport()) {
return;
}
if (session()->perspective() != Perspective::IS_SERVER) {
return;
}
QUICHE_DCHECK(IsValidWebTransportSessionId(id(), version()));
std::string method;
std::string protocol;
for (const auto& [header_name, header_value] : header_list_) {
if (header_name == ":method") {
if (!method.empty() || header_value.empty()) {
return;
}
method = header_value;
}
if (header_name == ":protocol") {
if (!protocol.empty() || header_value.empty()) {
return;
}
protocol = header_value;
}
if (header_name == "datagram-flow-id") {
QUIC_DLOG(ERROR) << ENDPOINT
<< "Rejecting WebTransport due to unexpected "
"Datagram-Flow-Id header";
return;
}
}
if (method != "CONNECT" || protocol != "webtransport") {
return;
}
web_transport_ =
std::make_unique<WebTransportHttp3>(spdy_session_, this, id());
}
void QuicSpdyStream::MaybeProcessSentWebTransportHeaders(
quiche::HttpHeaderBlock& headers) {
if (!spdy_session_->SupportsWebTransport()) {
return;
}
if (session()->perspective() != Perspective::IS_CLIENT) {
return;
}
QUICHE_DCHECK(IsValidWebTransportSessionId(id(), version()));
const auto method_it = headers.find(":method");
const auto protocol_it = headers.find(":protocol");
if (method_it == headers.end() || protocol_it == headers.end()) {
return;
}
if (method_it->second != "CONNECT" && protocol_it->second != "webtransport") {
return;
}
if (spdy_session_->SupportedWebTransportVersion() ==
WebTransportHttp3Version::kDraft02) {
headers["sec-webtransport-http3-draft02"] = "1";
}
web_transport_ =
std::make_unique<WebTransportHttp3>(spdy_session_, this, id());
}
void QuicSpdyStream::OnCanWriteNewData() {
if (web_transport_data_ != nullptr) {
web_transport_data_->adapter.OnCanWriteNewData();
}
}
bool QuicSpdyStream::AssertNotWebTransportDataStream(
absl::string_view operation) {
if (web_transport_data_ != nullptr) {
QUIC_BUG(Invalid operation on WebTransport stream)
<< "Attempted to " << operation << " on WebTransport data stream "
<< id() << " associated with session "
<< web_transport_data_->session_id;
OnUnrecoverableError(QUIC_INTERNAL_ERROR,
absl::StrCat("Attempted to ", operation,
" on WebTransport data stream"));
return false;
}
return true;
}
void QuicSpdyStream::ConvertToWebTransportDataStream(
WebTransportSessionId session_id) {
if (send_buffer().stream_offset() != 0) {
QUIC_BUG(Sending WEBTRANSPORT_STREAM when data already sent)
<< "Attempted to send a WEBTRANSPORT_STREAM frame when other data has "
"already been sent on the stream.";
OnUnrecoverableError(QUIC_INTERNAL_ERROR,
"Attempted to send a WEBTRANSPORT_STREAM frame when "
"other data has already been sent on the stream.");
return;
}
std::string header =
HttpEncoder::SerializeWebTransportStreamFrameHeader(session_id);
if (header.empty()) {
QUIC_BUG(Failed to serialize WEBTRANSPORT_STREAM)
<< "Failed to serialize a WEBTRANSPORT_STREAM frame.";
OnUnrecoverableError(QUIC_INTERNAL_ERROR,
"Failed to serialize a WEBTRANSPORT_STREAM frame.");
return;
}
WriteOrBufferData(header, false, nullptr);
web_transport_data_ =
std::make_unique<WebTransportDataStream>(this, session_id);
QUIC_DVLOG(1) << ENDPOINT << "Successfully opened WebTransport data stream "
<< id() << " for session " << session_id;
}
QuicSpdyStream::WebTransportDataStream::WebTransportDataStream(
QuicSpdyStream* stream, WebTransportSessionId session_id)
: session_id(session_id),
adapter(stream->spdy_session_, stream, stream->sequencer(), session_id) {}
void QuicSpdyStream::HandleReceivedDatagram(absl::string_view payload) {
if (datagram_visitor_ == nullptr) {
QUIC_DLOG(ERROR) << ENDPOINT << "Received datagram without any visitor";
return;
}
datagram_visitor_->OnHttp3Datagram(id(), payload);
}
bool QuicSpdyStream::OnCapsule(const Capsule& capsule) {
QUIC_DLOG(INFO) << ENDPOINT << "Stream " << id() << " received capsule "
<< capsule;
if (!headers_decompressed_) {
QUIC_PEER_BUG(capsule before headers)
<< ENDPOINT << "Stream " << id() << " received capsule " << capsule
<< " before headers";
return false;
}
if (web_transport_ != nullptr && web_transport_->close_received()) {
QUIC_PEER_BUG(capsule after close)
<< ENDPOINT << "Stream " << id() << " received capsule " << capsule
<< " after CLOSE_WEBTRANSPORT_SESSION.";
return false;
}
switch (capsule.capsule_type()) {
case CapsuleType::DATAGRAM:
HandleReceivedDatagram(capsule.datagram_capsule().http_datagram_payload);
return true;
case CapsuleType::LEGACY_DATAGRAM:
HandleReceivedDatagram(
capsule.legacy_datagram_capsule().http_datagram_payload);
return true;
case CapsuleType::LEGACY_DATAGRAM_WITHOUT_CONTEXT:
HandleReceivedDatagram(capsule.legacy_datagram_without_context_capsule()
.http_datagram_payload);
return true;
case CapsuleType::CLOSE_WEBTRANSPORT_SESSION:
if (web_transport_ == nullptr) {
QUIC_DLOG(ERROR) << ENDPOINT << "Received capsule " << capsule
<< " for a non-WebTransport stream.";
return false;
}
web_transport_->OnCloseReceived(
capsule.close_web_transport_session_capsule().error_code,
capsule.close_web_transport_session_capsule().error_message);
return true;
case CapsuleType::DRAIN_WEBTRANSPORT_SESSION:
if (web_transport_ == nullptr) {
QUIC_DLOG(ERROR) << ENDPOINT << "Received capsule " << capsule
<< " for a non-WebTransport stream.";
return false;
}
web_transport_->OnDrainSessionReceived();
return true;
case CapsuleType::ADDRESS_ASSIGN:
if (connect_ip_visitor_ == nullptr) {
return true;
}
return connect_ip_visitor_->OnAddressAssignCapsule(
capsule.address_assign_capsule());
case CapsuleType::ADDRESS_REQUEST:
if (connect_ip_visitor_ == nullptr) {
return true;
}
return connect_ip_visitor_->OnAddressRequestCapsule(
capsule.address_request_capsule());
case CapsuleType::ROUTE_ADVERTISEMENT:
if (connect_ip_visitor_ == nullptr) {
return true;
}
return connect_ip_visitor_->OnRouteAdvertisementCapsule(
capsule.route_advertisement_capsule());
case CapsuleType::WT_RESET_STREAM:
case CapsuleType::WT_STOP_SENDING:
case CapsuleType::WT_STREAM:
case CapsuleType::WT_STREAM_WITH_FIN:
case CapsuleType::WT_MAX_STREAM_DATA:
case CapsuleType::WT_MAX_STREAMS_BIDI:
case CapsuleType::WT_MAX_STREAMS_UNIDI:
return true;
}
if (datagram_visitor_) {
datagram_visitor_->OnUnknownCapsule(id(), capsule.unknown_capsule());
}
return true;
}
void QuicSpdyStream::OnCapsuleParseFailure(absl::string_view error_message) {
QUIC_DLOG(ERROR) << ENDPOINT << "Capsule parse failure: " << error_message;
Reset(QUIC_BAD_APPLICATION_PAYLOAD);
}
void QuicSpdyStream::WriteCapsule(const Capsule& capsule, bool fin) {
QUIC_DLOG(INFO) << ENDPOINT << "Stream " << id() << " sending capsule "
<< capsule;
quiche::QuicheBuffer serialized_capsule = SerializeCapsule(
capsule,
spdy_session_->connection()->helper()->GetStreamSendBufferAllocator());
QUICHE_DCHECK_GT(serialized_capsule.size(), 0u);
WriteOrBufferBody(serialized_capsule.AsStringView(), fin);
}
void QuicSpdyStream::WriteGreaseCapsule() {
QuicRandom* random = spdy_session_->connection()->random_generator();
uint64_t type = random->InsecureRandUint64() >> 4;
type = (type / 41) * 41 + 23;
QUICHE_DCHECK_EQ((type - 23) % 41, 0u);
constexpr size_t kMaxLength = 64;
size_t length = random->InsecureRandUint64() % kMaxLength;
std::string bytes(length, '\0');
random->InsecureRandBytes(&bytes[0], bytes.size());
Capsule capsule = Capsule::Unknown(type, bytes);
WriteCapsule(capsule, false);
}
MessageStatus QuicSpdyStream::SendHttp3Datagram(absl::string_view payload) {
return spdy_session_->SendHttp3Datagram(id(), payload);
}
void QuicSpdyStream::RegisterHttp3DatagramVisitor(
Http3DatagramVisitor* visitor) {
if (visitor == nullptr) {
QUIC_BUG(null datagram visitor)
<< ENDPOINT << "Null datagram visitor for stream ID " << id();
return;
}
QUIC_DLOG(INFO) << ENDPOINT << "Registering datagram visitor with stream ID "
<< id();
if (datagram_visitor_ != nullptr) {
QUIC_BUG(h3 datagram double registration)
<< ENDPOINT
<< "Attempted to doubly register HTTP/3 datagram with stream ID "
<< id();
return;
}
datagram_visitor_ = visitor;
QUICHE_DCHECK(!capsule_parser_);
capsule_parser_ = std::make_unique<quiche::CapsuleParser>(this);
}
void QuicSpdyStream::UnregisterHttp3DatagramVisitor() {
if (datagram_visitor_ == nullptr) {
QUIC_BUG(datagram visitor empty during unregistration)
<< ENDPOINT << "Cannot unregister datagram visitor for stream ID "
<< id();
return;
}
QUIC_DLOG(INFO) << ENDPOINT << "Unregistering datagram visitor for stream ID "
<< id();
datagram_visitor_ = nullptr;
}
void QuicSpdyStream::ReplaceHttp3DatagramVisitor(
Http3DatagramVisitor* visitor) {
QUIC_BUG_IF(h3 datagram unknown move, datagram_visitor_ == nullptr)
<< "Attempted to move missing datagram visitor on HTTP/3 stream ID "
<< id();
datagram_visitor_ = visitor;
}
void QuicSpdyStream::RegisterConnectIpVisitor(ConnectIpVisitor* visitor) {
if (visitor == nullptr) {
QUIC_BUG(null connect - ip visitor)
<< ENDPOINT << "Null connect-ip visitor for stream ID " << id();
return;
}
QUIC_DLOG(INFO) << ENDPOINT
<< "Registering CONNECT-IP visitor with stream ID " << id();
if (connect_ip_visitor_ != nullptr) {
QUIC_BUG(connect - ip double registration)
<< ENDPOINT << "Attempted to doubly register CONNECT-IP with stream ID "
<< id();
return;
}
connect_ip_visitor_ = visitor;
}
void QuicSpdyStream::UnregisterConnectIpVisitor() {
if (connect_ip_visitor_ == nullptr) {
QUIC_BUG(connect - ip visitor empty during unregistration)
<< ENDPOINT << "Cannot unregister CONNECT-IP visitor for stream ID "
<< id();
return;
}
QUIC_DLOG(INFO) << ENDPOINT
<< "Unregistering CONNECT-IP visitor for stream ID " << id();
connect_ip_visitor_ = nullptr;
}
void QuicSpdyStream::ReplaceConnectIpVisitor(ConnectIpVisitor* visitor) {
QUIC_BUG_IF(connect - ip unknown move, connect_ip_visitor_ == nullptr)
<< "Attempted to move missing CONNECT-IP visitor on HTTP/3 stream ID "
<< id();
connect_ip_visitor_ = visitor;
}
void QuicSpdyStream::SetMaxDatagramTimeInQueue(
QuicTime::Delta max_time_in_queue) {
spdy_session_->SetMaxDatagramTimeInQueueForStreamId(id(), max_time_in_queue);
}
void QuicSpdyStream::OnDatagramReceived(QuicDataReader* reader) {
if (!headers_decompressed_) {
QUIC_DLOG(INFO) << "Dropping datagram received before headers on stream ID "
<< id();
return;
}
HandleReceivedDatagram(reader->ReadRemainingPayload());
}
QuicByteCount QuicSpdyStream::GetMaxDatagramSize() const {
QuicByteCount prefix_size = 0;
switch (spdy_session_->http_datagram_support()) {
case HttpDatagramSupport::kDraft04:
case HttpDatagramSupport::kRfc:
prefix_size =
QuicDataWriter::GetVarInt62Len(id() / kHttpDatagramStreamIdDivisor);
break;
case HttpDatagramSupport::kNone:
case HttpDatagramSupport::kRfcAndDraft04:
QUIC_BUG(GetMaxDatagramSize called with no datagram support)
<< "GetMaxDatagramSize() called when no HTTP/3 datagram support has "
"been negotiated. Support value: "
<< spdy_session_->http_datagram_support();
break;
}
if (prefix_size == 0) {
prefix_size = 8;
}
QuicByteCount max_datagram_size =
session()->GetGuaranteedLargestMessagePayload();
if (max_datagram_size < prefix_size) {
QUIC_BUG(max_datagram_size smaller than prefix_size)
<< "GetGuaranteedLargestMessagePayload() returned a datagram size that "
"is not sufficient to fit stream ID into it.";
return 0;
}
return max_datagram_size - prefix_size;
}
void QuicSpdyStream::HandleBodyAvailable() {
if (!capsule_parser_ || !uses_capsules()) {
OnBodyAvailable();
return;
}
while (body_manager_.HasBytesToRead()) {
iovec iov;
int num_iov = GetReadableRegions(&iov, 1);
if (num_iov == 0) {
break;
}
if (!capsule_parser_->IngestCapsuleFragment(absl::string_view(
reinterpret_cast<const char*>(iov.iov_base), iov.iov_len))) {
break;
}
MarkConsumed(iov.iov_len);
}
if (sequencer()->IsClosed()) {
capsule_parser_->ErrorIfThereIsRemainingBufferedData();
if (web_transport_ != nullptr) {
web_transport_->OnConnectStreamFinReceived();
}
OnFinRead();
}
}
namespace {
bool IsValidHeaderName(absl::string_view name) {
if (name.empty()) {
return true;
}
if (name[0] == ':') {
name.remove_prefix(1);
}
return http2::adapter::HeaderValidator::IsValidHeaderName(name);
}
}
bool QuicSpdyStream::ValidateReceivedHeaders(
const QuicHeaderList& header_list) {
bool force_fail_validation = false;
AdjustTestValue("quic::QuicSpdyStream::request_header_validation_adjust",
&force_fail_validation);
if (force_fail_validation) {
invalid_request_details_ =
"request_header_validation_adjust force failed the validation.";
QUIC_DLOG(ERROR) << invalid_request_details_;
return false;
}
bool is_response = false;
for (const std::pair<std::string, std::string>& pair : header_list) {
const std::string& name = pair.first;
if (!IsValidHeaderName(name)) {
invalid_request_details_ =
absl::StrCat("Invalid character in header name ", name);
QUIC_DLOG(ERROR) << invalid_request_details_;
return false;
}
if (name == ":status") {
is_response = !pair.second.empty();
}
if (name == "host") {
if (GetQuicReloadableFlag(quic_allow_host_in_request2)) {
QUICHE_RELOADABLE_FLAG_COUNT_N(quic_allow_host_in_request2, 1, 3);
continue;
}
if (is_response) {
continue;
}
}
if (http2::GetInvalidHttp2HeaderSet().contains(name)) {
invalid_request_details_ = absl::StrCat(name, " header is not allowed");
QUIC_DLOG(ERROR) << invalid_request_details_;
return false;
}
}
return true;
}
void QuicSpdyStream::set_invalid_request_details(
std::string invalid_request_details) {
QUIC_BUG_IF(
empty invalid request detail,
!invalid_request_details_.empty() || invalid_request_details.empty());
invalid_request_details_ = std::move(invalid_request_details);
}
bool QuicSpdyStream::AreHeaderFieldValuesValid(
const QuicHeaderList& header_list) const {
if (!VersionUsesHttp3(transport_version())) {
return true;
}
for (const std::pair<std::string, std::string>& pair : header_list) {
const std::string& value = pair.second;
for (const auto c : value) {
if (c == '\0' || c == '\n' || c == '\r') {
return false;
}
}
}
return true;
}
void QuicSpdyStream::StopReading() {
QuicStream::StopReading();
if (GetQuicReloadableFlag(
quic_stop_reading_also_stops_header_decompression) &&
VersionUsesHttp3(transport_version()) && !fin_received() &&
spdy_session_->qpack_decoder()) {
QUIC_RELOADABLE_FLAG_COUNT(
quic_stop_reading_also_stops_header_decompression);
spdy_session_->qpack_decoder()->OnStreamReset(id());
qpack_decoded_headers_accumulator_.reset();
}
}
void QuicSpdyStream::OnInvalidHeaders() { Reset(QUIC_BAD_APPLICATION_PAYLOAD); }
void QuicSpdyStream::CloseReadSide() {
QuicStream::CloseReadSide();
body_manager_.Clear();
}
#undef ENDPOINT
} | #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/qpack/value_splitting_header_list.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::HttpHeaderBlock;
using quiche::IpAddressRange;
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(
quiche::HttpHeaderBlock 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 quiche::HttpHeaderBlock& 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_;
quiche::HttpHeaderBlock 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) {
HttpHeaderBlock 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 HttpHeaderBlock& header) {
NoopQpackStreamSenderDelegate encoder_stream_sender_delegate;
auto qpack_encoder = std::make_unique<QpackEncoder>(
session_.get(), HuffmanEncoding::kEnabled, CookieCrumbling::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 HttpHeaderBlock& 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 HttpHeaderBlock& 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_;
HttpHeaderBlock 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));
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_->ConsumeHeaderList();
char buffer[2048];
char buffer2[2048];
struct iovec vec[2];
vec[0].iov_base = buffer;
vec[0].iov_len = ABSL_ARRAYSIZE(buffer);
vec[1].iov_base = buffer2;
vec[1].iov_len = ABSL_ARRAYSIZE(buffer2);
size_t bytes_read = stream_->Readv(vec, 2);
EXPECT_EQ(2048u * 2, bytes_read);
EXPECT_EQ(body.substr(0, 2048), std::string(buffer, 2048));
EXPECT_EQ(body.substr(2048, 2048), std::string(buffer2, 2048));
}
TEST_P(QuicSpdyStreamTest, ProcessHeadersAndBodyMarkConsumed) {
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();
struct iovec vec;
EXPECT_EQ(1, stream_->GetReadableRegions(&vec, 1));
EXPECT_EQ(body.length(), vec.iov_len);
EXPECT_EQ(body, std::string(static_cast<char*>(vec.iov_base), vec.iov_len));
stream_->MarkConsumed(body.length());
EXPECT_EQ(data.length(), QuicStreamPeer::bytes_consumed(stream_));
}
TEST_P(QuicSpdyStreamTest, ProcessHeadersAndConsumeMultipleBody) {
Initialize(!kShouldProcessData);
std::string body1 = "this is body 1";
std::string data1 = UsesHttp3() ? DataFrame(body1) : body1;
std::string body2 = "body 2";
std::string data2 = UsesHttp3() ? DataFrame(body2) : body2;
ProcessHeaders(false, headers_);
QuicStreamFrame frame1(GetNthClientInitiatedBidirectionalId(0), false, 0,
absl::string_view(data1));
QuicStreamFrame frame2(GetNthClientInitiatedBidirectionalId(0), false,
data1.length(), absl::string_view(data2));
stream_->OnStreamFrame(frame1);
stream_->OnStreamFrame(frame2);
stream_->ConsumeHeaderList();
stream_->MarkConsumed(body1.length() + body2.length());
EXPECT_EQ(data1.length() + data2.length(),
QuicStreamPeer::bytes_consumed(stream_));
}
TEST_P(QuicSpdyStreamTest, ProcessHeadersAndBodyIncrementalReadv) {
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[1];
struct iovec vec;
vec.iov_base = buffer;
vec.iov_len = ABSL_ARRAYSIZE(buffer);
for (size_t i = 0; i < body.length(); ++i) {
size_t bytes_read = stream_->Readv(&vec, 1);
ASSERT_EQ(1u, bytes_read);
EXPECT_EQ(body.data()[i], buffer[0]);
}
}
TEST_P(QuicSpdyStreamTest, ProcessHeadersUsingReadvWithMultipleIovecs) {
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 buffer1[1];
char buffer2[1];
struct iovec vec[2];
vec[0].iov_base = buffer1;
vec[0].iov_len = ABSL_ARRAYSIZE(buffer1);
vec[1].iov_base = buffer2;
vec[1].iov_len = ABSL_ARRAYSIZE(buffer2);
for (size_t i = 0; i < body.length(); i += 2) {
size_t bytes_read = stream_->Readv(vec, 2);
ASSERT_EQ(2u, bytes_read) << i;
ASSERT_EQ(body.data()[i], buffer1[0]) << i;
ASSERT_EQ(body.data()[i + 1], buffer2[0]) << i;
}
}
TEST_P(QuicSpdyStreamTest, StreamFlowControlBlocked) {
Initialize(kShouldProcessData);
testing::InSequence seq;
const uint64_t kWindow = 36;
QuicStreamPeer::SetSendWindowOffset(stream_, kWindow);
EXPECT_EQ(kWindow, QuicStreamPeer::SendWindowOffset(stream_));
const uint64_t kOverflow = 15;
std::string body(kWindow + kOverflow, 'a');
const uint64_t kHeaderLength = UsesHttp3() ? 2 : 0;
if (UsesHttp3()) {
EXPECT_CALL(*session_, WritevData(_, kHeaderLength, _, NO_FIN, _, _));
}
EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _))
.WillOnce(Return(QuicConsumedData(kWindow - kHeaderLength, true)));
EXPECT_CALL(*session_, SendBlocked(_, _));
EXPECT_CALL(*connection_, SendControlFrame(_));
stream_->WriteOrBufferBody(body, false);
EXPECT_EQ(0u, QuicStreamPeer::SendWindowSize(stream_));
EXPECT_EQ(kOverflow + kHeaderLength, stream_->BufferedDataBytes());
}
TEST_P(QuicSpdyStreamTest, StreamFlowControlNoWindowUpdateIfNotConsumed) {
Initialize(!kShouldProcessData);
EXPECT_CALL(*session_, SendWindowUpdate(_, _)).Times(0);
const uint64_t kWindow = 36;
QuicStreamPeer::SetReceiveWindowOffset(stream_, kWindow);
QuicStreamPeer::SetMaxReceiveWindow(stream_, kWindow);
std::string body(kWindow / 3, 'a');
QuicByteCount header_length = 0;
std::string data;
if (UsesHttp3()) {
quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader(
body.length(), quiche::SimpleBufferAllocator::Get());
data = absl::StrCat(header.AsStringView(), body);
header_length = header.size();
} else {
data = body;
}
ProcessHeaders(false, headers_);
QuicStreamFrame frame1(GetNthClientInitiatedBidirectionalId(0), false, 0,
absl::string_view(data));
stream_->OnStreamFrame(frame1);
EXPECT_EQ(kWindow - (kWindow / 3) - header_length,
QuicStreamPeer::ReceiveWindowSize(stream_));
QuicStreamFrame frame2(GetNthClientInitiatedBidirectionalId(0), false,
kWindow / 3 + header_length, absl::string_view(data));
stream_->OnStreamFrame(frame2);
EXPECT_EQ(kWindow - (2 * kWindow / 3) - 2 * header_length,
QuicStreamPeer::ReceiveWindowSize(stream_));
}
TEST_P(QuicSpdyStreamTest, StreamFlowControlWindowUpdate) {
Initialize(kShouldProcessData);
const uint64_t kWindow = 36;
QuicStreamPeer::SetReceiveWindowOffset(stream_, kWindow);
QuicStreamPeer::SetMaxReceiveWindow(stream_, kWindow);
std::string body(kWindow / 3, 'a');
QuicByteCount header_length = 0;
std::string data;
if (UsesHttp3()) {
quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader(
body.length(), quiche::SimpleBufferAllocator::Get());
data = absl::StrCat(header.AsStringView(), body);
header_length = header.size();
} else {
data = body;
}
ProcessHeaders(false, headers_);
stream_->ConsumeHeaderList();
QuicStreamFrame frame1(GetNthClientInitiatedBidirectionalId(0), false, 0,
absl::string_view(data));
stream_->OnStreamFrame(frame1);
EXPECT_EQ(kWindow - (kWindow / 3) - header_length,
QuicStreamPeer::ReceiveWindowSize(stream_));
QuicStreamFrame frame2(GetNthClientInitiatedBidirectionalId(0), false,
kWindow / 3 + header_length, absl::string_view(data));
EXPECT_CALL(*session_, SendWindowUpdate(_, _));
EXPECT_CALL(*connection_, SendControlFrame(_));
stream_->OnStreamFrame(frame2);
EXPECT_EQ(kWindow, QuicStreamPeer::ReceiveWindowSize(stream_));
}
TEST_P(QuicSpdyStreamTest, ConnectionFlowControlWindowUpdate) {
Initialize(kShouldProcessData);
const uint64_t kWindow = 36;
QuicStreamPeer::SetReceiveWindowOffset(stream_, kWindow);
QuicStreamPeer::SetMaxReceiveWindow(stream_, kWindow);
QuicStreamPeer::SetReceiveWindowOffset(stream2_, kWindow);
QuicStreamPeer::SetMaxReceiveWindow(stream2_, kWindow);
QuicFlowControllerPeer::SetReceiveWindowOffset(session_->flow_controller(),
kWindow);
QuicFlowControllerPeer::SetMaxReceiveWindow(session_->flow_controller(),
kWindow);
auto headers = AsHeaderList(headers_);
stream_->OnStreamHeaderList(false, headers.uncompressed_header_bytes(),
headers);
stream_->ConsumeHeaderList();
stream2_->OnStreamHeaderList(false, headers.uncompressed_header_bytes(),
headers);
stream2_->ConsumeHeaderList();
QuicByteCount header_length = 0;
std::string body;
std::string data;
std::string data2;
std::string body2(1, 'a');
if (UsesHttp3()) {
body = std::string(kWindow / 4 - 2, 'a');
quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader(
body.length(), quiche::SimpleBufferAllocator::Get());
data = absl::StrCat(header.AsStringView(), body);
header_length = header.size();
quiche::QuicheBuffer header2 = HttpEncoder::SerializeDataFrameHeader(
body.length(), quiche::SimpleBufferAllocator::Get());
data2 = absl::StrCat(header2.AsStringView(), body2);
} else {
body = std::string(kWindow / 4, 'a');
data = body;
data2 = body2;
}
QuicStreamFrame frame1(GetNthClientInitiatedBidirectionalId(0), false, 0,
absl::string_view(data));
stream_->OnStreamFrame(frame1);
QuicStreamFrame frame2(GetNthClientInitiatedBidirectionalId(1), false, 0,
absl::string_view(data));
stream2_->OnStreamFrame(frame2);
EXPECT_CALL(*session_, SendWindowUpdate(_, _));
EXPECT_CALL(*connection_, SendControlFrame(_));
QuicStreamFrame frame3(GetNthClientInitiatedBidirectionalId(0), false,
body.length() + header_length,
absl::string_view(data2));
stream_->OnStreamFrame(frame3);
}
TEST_P(QuicSpdyStreamTest, StreamFlowControlViolation) {
Initialize(!kShouldProcessData);
const uint64_t kWindow = 50;
QuicStreamPeer::SetReceiveWindowOffset(stream_, kWindow);
ProcessHeaders(false, headers_);
std::string body(kWindow + 1, 'a');
std::string data = UsesHttp3() ? DataFrame(body) : body;
QuicStreamFrame frame(GetNthClientInitiatedBidirectionalId(0), false, 0,
absl::string_view(data));
EXPECT_CALL(*connection_,
CloseConnection(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, _, _));
stream_->OnStreamFrame(frame);
}
TEST_P(QuicSpdyStreamTest, TestHandlingQuicRstStreamNoError) {
Initialize(kShouldProcessData);
ProcessHeaders(false, headers_);
EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)).Times(AnyNumber());
stream_->OnStreamReset(QuicRstStreamFrame(
kInvalidControlFrameId, stream_->id(), QUIC_STREAM_NO_ERROR, 0));
if (UsesHttp3()) {
EXPECT_TRUE(stream_->read_side_closed());
EXPECT_FALSE(stream_->write_side_closed());
} else {
EXPECT_TRUE(stream_->write_side_closed());
EXPECT_FALSE(stream_->reading_stopped());
}
}
TEST_P(QuicSpdyStreamTest, ConnectionFlowControlViolation) {
Initialize(!kShouldProcessData);
const uint64_t kStreamWindow = 50;
const uint64_t kConnectionWindow = 10;
QuicStreamPeer::SetReceiveWindowOffset(stream_, kStreamWindow);
QuicFlowControllerPeer::SetReceiveWindowOffset(session_->flow_controller(),
kConnectionWindow);
ProcessHeaders(false, headers_);
std::string body(kConnectionWindow + 1, 'a');
std::string data = UsesHttp3() ? DataFrame(body) : body;
EXPECT_LT(data.size(), kStreamWindow);
QuicStreamFrame frame(GetNthClientInitiatedBidirectionalId(0), false, 0,
absl::string_view(data));
EXPECT_CALL(*connection_,
CloseConnection(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, _, _));
stream_->OnStreamFrame(frame);
}
TEST_P(QuicSpdyStreamTest, StreamFlowControlFinNotBlocked) {
Initialize(kShouldProcessData);
QuicStreamPeer::SetReceiveWindowOffset(stream_, 0);
std::string body = "";
bool fin = true;
EXPECT_CALL(*session_,
SendBlocked(GetNthClientInitiatedBidirectionalId(0), _))
.Times(0);
EXPECT_CALL(*session_, WritevData(_, 0, _, FIN, _, _));
stream_->WriteOrBufferBody(body, fin);
}
TEST_P(QuicSpdyStreamTest, ReceivingTrailersViaHeaderList) {
Initialize(kShouldProcessData);
size_t total_bytes = 0;
QuicHeaderList headers;
for (const auto& p : headers_) {
headers.OnHeader(p.first, p.second);
total_bytes += p.first.size() + p.second.size();
}
stream_->OnStreamHeadersPriority(
spdy::SpdyStreamPrecedence(kV3HighestPriority));
stream_->OnStreamHeaderList(false, total_bytes, headers);
stream_->ConsumeHeaderList();
HttpHeaderBlock trailers_block;
trailers_block["key1"] = "value1";
trailers_block["key2"] = "value2";
trailers_block["key3"] = "value3";
HttpHeaderBlock trailers_block_with_final_offset = trailers_block.Clone();
if (!UsesHttp3()) {
trailers_block_with_final_offset[kFinalOffsetHeaderKey] = "0";
}
total_bytes = 0;
QuicHeaderList trailers;
for (const auto& p : trailers_block_with_final_offset) {
trailers.OnHeader(p.first, p.second);
total_bytes += p.first.size() + p.second.size();
}
stream_->OnStreamHeaderList(true, total_bytes, trailers);
EXPECT_TRUE(stream_->trailers_decompressed());
EXPECT_EQ(trailers_block, stream_->received_trailers());
EXPECT_FALSE(stream_->IsDoneReading());
stream_->MarkTrailersConsumed();
EXPECT_TRUE(stream_->IsDoneReading());
}
TEST_P(QuicSpdyStreamTest, ReceivingTrailersWithOffset) {
if (UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
QuicHeaderList headers = ProcessHeaders(false, headers_);
stream_->ConsumeHeaderList();
const std::string body = "this is the body";
std::string data = UsesHttp3() ? DataFrame(body) : body;
HttpHeaderBlock trailers_block;
trailers_block["key1"] = "value1";
trailers_block["key2"] = "value2";
trailers_block["key3"] = "value3";
trailers_block[kFinalOffsetHeaderKey] = absl::StrCat(data.size());
QuicHeaderList trailers = ProcessHeaders(true, trailers_block);
EXPECT_TRUE(stream_->trailers_decompressed());
trailers_block.erase(kFinalOffsetHeaderKey);
EXPECT_EQ(trailers_block, stream_->received_trailers());
stream_->MarkTrailersConsumed();
EXPECT_TRUE(stream_->FinishedReadingTrailers());
EXPECT_FALSE(stream_->IsDoneReading());
QuicStreamFrame frame(GetNthClientInitiatedBidirectionalId(0), false,
0, data);
stream_->OnStreamFrame(frame);
EXPECT_EQ(body, stream_->data());
EXPECT_TRUE(stream_->IsDoneReading());
}
TEST_P(QuicSpdyStreamTest, ReceivingTrailersWithoutOffset) {
if (UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
ProcessHeaders(false, headers_);
stream_->ConsumeHeaderList();
HttpHeaderBlock trailers_block;
trailers_block["key1"] = "value1";
trailers_block["key2"] = "value2";
trailers_block["key3"] = "value3";
auto trailers = AsHeaderList(trailers_block);
EXPECT_EQ("", trailers_block[kFinalOffsetHeaderKey].as_string());
EXPECT_CALL(*connection_,
CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA, _, _))
.Times(1);
stream_->OnStreamHeaderList(true,
trailers.uncompressed_header_bytes(), trailers);
}
TEST_P(QuicSpdyStreamTest, ReceivingTrailersWithoutFin) {
if (UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
auto headers = AsHeaderList(headers_);
stream_->OnStreamHeaderList(false,
headers.uncompressed_header_bytes(), headers);
stream_->ConsumeHeaderList();
HttpHeaderBlock trailers_block;
trailers_block["foo"] = "bar";
auto trailers = AsHeaderList(trailers_block);
EXPECT_CALL(*connection_,
CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA, _, _))
.Times(1);
stream_->OnStreamHeaderList(false,
trailers.uncompressed_header_bytes(), trailers);
}
TEST_P(QuicSpdyStreamTest, ReceivingTrailersAfterHeadersWithFin) {
Initialize(kShouldProcessData);
if (UsesHttp3()) {
return;
}
ProcessHeaders(true, headers_);
stream_->ConsumeHeaderList();
HttpHeaderBlock trailers_block;
trailers_block["foo"] = "bar";
EXPECT_CALL(*connection_,
CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA, _, _))
.Times(1);
ProcessHeaders(true, trailers_block);
}
TEST_P(QuicSpdyStreamTest, ReceivingTrailersAfterBodyWithFin) {
if (UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
ProcessHeaders(false, headers_);
stream_->ConsumeHeaderList();
QuicStreamFrame frame(GetNthClientInitiatedBidirectionalId(0), true,
0, "body");
stream_->OnStreamFrame(frame);
HttpHeaderBlock trailers_block;
trailers_block["foo"] = "bar";
EXPECT_CALL(*connection_,
CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA, _, _))
.Times(1);
ProcessHeaders(true, trailers_block);
}
TEST_P(QuicSpdyStreamTest, ClosingStreamWithNoTrailers) {
Initialize(kShouldProcessData);
auto h = AsHeaderList(headers_);
stream_->OnStreamHeaderList(false, h.uncompressed_header_bytes(), h);
stream_->ConsumeHeaderList();
std::string body(1024, 'x');
std::string data = UsesHttp3() ? DataFrame(body) : body;
QuicStreamFrame frame(GetNthClientInitiatedBidirectionalId(0), true,
0, data);
stream_->OnStreamFrame(frame);
EXPECT_TRUE(stream_->IsDoneReading());
}
TEST_P(QuicSpdyStreamTest, WritingTrailersSendsAFin) {
Initialize(kShouldProcessData);
if (UsesHttp3()) {
EXPECT_CALL(*session_, WritevData(stream_->id(), _, _, _, _, _)).Times(2);
}
EXPECT_CALL(*stream_, WriteHeadersMock(false));
stream_->WriteHeaders(HttpHeaderBlock(), false, nullptr);
HttpHeaderBlock trailers;
trailers["trailer key"] = "trailer value";
EXPECT_CALL(*stream_, WriteHeadersMock(true));
stream_->WriteTrailers(std::move(trailers), nullptr);
EXPECT_TRUE(stream_->fin_sent());
}
TEST_P(QuicSpdyStreamTest, DoNotSendPriorityUpdateWithDefaultUrgency) {
if (!UsesHttp3()) {
return;
}
InitializeWithPerspective(kShouldProcessData, Perspective::IS_CLIENT);
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
EXPECT_CALL(*session_, WritevData(stream_->id(), _, _, _, _, _)).Times(2);
auto send_control_stream =
QuicSpdySessionPeer::GetSendControlStream(session_.get());
EXPECT_CALL(*session_, WritevData(send_control_stream->id(), _, _, _, _, _))
.Times(0);
EXPECT_CALL(*stream_, WriteHeadersMock(false));
EXPECT_CALL(debug_visitor, OnHeadersFrameSent(stream_->id(), _));
stream_->WriteHeaders(HttpHeaderBlock(), false, nullptr);
HttpHeaderBlock trailers;
trailers["trailer key"] = "trailer value";
EXPECT_CALL(*stream_, WriteHeadersMock(true));
EXPECT_CALL(debug_visitor, OnHeadersFrameSent(stream_->id(), _));
stream_->WriteTrailers(std::move(trailers), nullptr);
EXPECT_TRUE(stream_->fin_sent());
}
TEST_P(QuicSpdyStreamTest, ChangePriority) {
if (!UsesHttp3()) {
return;
}
InitializeWithPerspective(kShouldProcessData, Perspective::IS_CLIENT);
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
EXPECT_CALL(*session_, WritevData(stream_->id(), _, _, _, _, _)).Times(1);
EXPECT_CALL(*stream_, WriteHeadersMock(false));
EXPECT_CALL(debug_visitor, OnHeadersFrameSent(stream_->id(), _));
stream_->WriteHeaders(HttpHeaderBlock(), false, nullptr);
testing::Mock::VerifyAndClearExpectations(&debug_visitor);
auto send_control_stream =
QuicSpdySessionPeer::GetSendControlStream(session_.get());
EXPECT_CALL(*session_, WritevData(send_control_stream->id(), _, _, _, _, _));
PriorityUpdateFrame priority_update1{stream_->id(), "u=0"};
EXPECT_CALL(debug_visitor, OnPriorityUpdateFrameSent(priority_update1));
const HttpStreamPriority priority1{kV3HighestPriority,
HttpStreamPriority::kDefaultIncremental};
stream_->SetPriority(QuicStreamPriority(priority1));
testing::Mock::VerifyAndClearExpectations(&debug_visitor);
EXPECT_CALL(*session_, WritevData(send_control_stream->id(), _, _, _, _, _));
PriorityUpdateFrame priority_update2{stream_->id(), "u=2, i"};
EXPECT_CALL(debug_visitor, OnPriorityUpdateFrameSent(priority_update2));
const HttpStreamPriority priority2{2, true};
stream_->SetPriority(QuicStreamPriority(priority2));
testing::Mock::VerifyAndClearExpectations(&debug_visitor);
stream_->SetPriority(QuicStreamPriority(priority2));
}
TEST_P(QuicSpdyStreamTest, ChangePriorityBeforeWritingHeaders) {
if (!UsesHttp3()) {
return;
}
InitializeWithPerspective(kShouldProcessData, Perspective::IS_CLIENT);
auto send_control_stream =
QuicSpdySessionPeer::GetSendControlStream(session_.get());
EXPECT_CALL(*session_, WritevData(send_control_stream->id(), _, _, _, _, _));
stream_->SetPriority(QuicStreamPriority(HttpStreamPriority{
kV3HighestPriority, HttpStreamPriority::kDefaultIncremental}));
testing::Mock::VerifyAndClearExpectations(session_.get());
EXPECT_CALL(*session_, WritevData(stream_->id(), _, _, _, _, _)).Times(1);
EXPECT_CALL(*stream_, WriteHeadersMock(true));
stream_->WriteHeaders(HttpHeaderBlock(), true, nullptr);
}
TEST_P(QuicSpdyStreamTest, WritingTrailersFinalOffset) {
Initialize(kShouldProcessData);
if (UsesHttp3()) {
EXPECT_CALL(*session_, WritevData(stream_->id(), _, _, _, _, _)).Times(1);
}
EXPECT_CALL(*stream_, WriteHeadersMock(false));
stream_->WriteHeaders(HttpHeaderBlock(), false, nullptr);
EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)).Times(AtLeast(1));
std::string body(1024, 'x');
QuicByteCount header_length = 0;
if (UsesHttp3()) {
header_length = HttpEncoder::SerializeDataFrameHeader(
body.length(), quiche::SimpleBufferAllocator::Get())
.size();
}
stream_->WriteOrBufferBody(body, false);
HttpHeaderBlock trailers;
trailers["trailer key"] = "trailer value";
HttpHeaderBlock expected_trailers(trailers.Clone());
if (!UsesHttp3()) {
expected_trailers[kFinalOffsetHeaderKey] =
absl::StrCat(body.length() + header_length);
}
EXPECT_CALL(*stream_, WriteHeadersMock(true));
stream_->WriteTrailers(std::move(trailers), nullptr);
EXPECT_EQ(expected_trailers, stream_->saved_headers());
}
TEST_P(QuicSpdyStreamTest, WritingTrailersClosesWriteSide) {
Initialize(kShouldProcessData);
EXPECT_CALL(*session_, WritevData(stream_->id(), _, _, _, _, _))
.Times(AtLeast(1));
EXPECT_CALL(*stream_, WriteHeadersMock(false));
stream_->WriteHeaders(HttpHeaderBlock(), false, nullptr);
const int kBodySize = 1 * 1024;
stream_->WriteOrBufferBody(std::string(kBodySize, 'x'), false);
EXPECT_EQ(0u, stream_->BufferedDataBytes());
EXPECT_CALL(*stream_, WriteHeadersMock(true));
stream_->WriteTrailers(HttpHeaderBlock(), nullptr);
EXPECT_TRUE(stream_->write_side_closed());
}
TEST_P(QuicSpdyStreamTest, WritingTrailersWithQueuedBytes) {
if (UsesHttp3()) {
return;
}
testing::InSequence seq;
Initialize(kShouldProcessData);
EXPECT_CALL(*stream_, WriteHeadersMock(false));
stream_->WriteHeaders(HttpHeaderBlock(), false, nullptr);
const int kBodySize = 1 * 1024;
if (UsesHttp3()) {
EXPECT_CALL(*session_, WritevData(_, 3, _, NO_FIN, _, _));
}
EXPECT_CALL(*session_, WritevData(_, kBodySize, _, NO_FIN, _, _))
.WillOnce(Return(QuicConsumedData(kBodySize - 1, false)));
stream_->WriteOrBufferBody(std::string(kBodySize, 'x'), false);
EXPECT_EQ(1u, stream_->BufferedDataBytes());
EXPECT_CALL(*stream_, WriteHeadersMock(true));
stream_->WriteTrailers(HttpHeaderBlock(), nullptr);
EXPECT_TRUE(stream_->fin_sent());
EXPECT_FALSE(stream_->write_side_closed());
EXPECT_CALL(*session_, WritevData(_, 1, _, NO_FIN, _, _));
stream_->OnCanWrite();
EXPECT_TRUE(stream_->write_side_closed());
}
TEST_P(QuicSpdyStreamTest, WritingTrailersAfterFIN) {
if (UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
EXPECT_CALL(*stream_, WriteHeadersMock(true));
stream_->WriteHeaders(HttpHeaderBlock(), true, nullptr);
EXPECT_TRUE(stream_->fin_sent());
EXPECT_QUIC_BUG(stream_->WriteTrailers(HttpHeaderBlock(), nullptr),
"Trailers cannot be sent after a FIN");
}
TEST_P(QuicSpdyStreamTest, HeaderStreamNotiferCorrespondingSpdyStream) {
if (UsesHttp3()) {
return;
}
const char kHeader1[] = "Header1";
const char kHeader2[] = "Header2";
const char kBody1[] = "Test1";
const char kBody2[] = "Test2";
Initialize(kShouldProcessData);
EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)).Times(AtLeast(1));
testing::InSequence s;
quiche::QuicheReferenceCountedPointer<MockAckListener> ack_listener1(
new MockAckListener());
quiche::QuicheReferenceCountedPointer<MockAckListener> ack_listener2(
new MockAckListener());
stream_->set_ack_listener(ack_listener1);
stream2_->set_ack_listener(ack_listener2);
session_->headers_stream()->WriteOrBufferData(kHeader1, false, ack_listener1);
stream_->WriteOrBufferBody(kBody1, true);
session_->headers_stream()->WriteOrBufferData(kHeader2, false, ack_listener2);
stream2_->WriteOrBufferBody(kBody2, false);
QuicStreamFrame frame1(
QuicUtils::GetHeadersStreamId(connection_->transport_version()), false, 0,
kHeader1);
std::string data1 = UsesHttp3() ? DataFrame(kBody1) : kBody1;
QuicStreamFrame frame2(stream_->id(), true, 0, data1);
QuicStreamFrame frame3(
QuicUtils::GetHeadersStreamId(connection_->transport_version()), false, 7,
kHeader2);
std::string data2 = UsesHttp3() ? DataFrame(kBody2) : kBody2;
QuicStreamFrame frame4(stream2_->id(), false, 0, data2);
EXPECT_CALL(*ack_listener1, OnPacketRetransmitted(7));
session_->OnStreamFrameRetransmitted(frame1);
EXPECT_CALL(*ack_listener1, OnPacketAcked(7, _));
EXPECT_TRUE(session_->OnFrameAcked(QuicFrame(frame1), QuicTime::Delta::Zero(),
QuicTime::Zero()));
EXPECT_CALL(*ack_listener1, OnPacketAcked(5, _));
EXPECT_TRUE(session_->OnFrameAcked(QuicFrame(frame2), QuicTime::Delta::Zero(),
QuicTime::Zero()));
EXPECT_CALL(*ack_listener2, OnPacketAcked(7, _));
EXPECT_TRUE(session_->OnFrameAcked(QuicFrame(frame3), QuicTime::Delta::Zero(),
QuicTime::Zero()));
EXPECT_CALL(*ack_listener2, OnPacketAcked(5, _));
EXPECT_TRUE(session_->OnFrameAcked(QuicFrame(frame4), QuicTime::Delta::Zero(),
QuicTime::Zero()));
}
TEST_P(QuicSpdyStreamTest, OnPriorityFrame) {
Initialize(kShouldProcessData);
stream_->OnPriorityFrame(spdy::SpdyStreamPrecedence(kV3HighestPriority));
EXPECT_EQ(QuicStreamPriority(HttpStreamPriority{
kV3HighestPriority, HttpStreamPriority::kDefaultIncremental}),
stream_->priority());
}
TEST_P(QuicSpdyStreamTest, OnPriorityFrameAfterSendingData) {
Initialize(kShouldProcessData);
testing::InSequence seq;
if (UsesHttp3()) {
EXPECT_CALL(*session_, WritevData(_, 2, _, NO_FIN, _, _));
}
EXPECT_CALL(*session_, WritevData(_, 4, _, FIN, _, _));
stream_->WriteOrBufferBody("data", true);
stream_->OnPriorityFrame(spdy::SpdyStreamPrecedence(kV3HighestPriority));
EXPECT_EQ(QuicStreamPriority(HttpStreamPriority{
kV3HighestPriority, HttpStreamPriority::kDefaultIncremental}),
stream_->priority());
}
TEST_P(QuicSpdyStreamTest, SetPriorityBeforeUpdateStreamPriority) {
MockQuicConnection* connection = new StrictMock<MockQuicConnection>(
&helper_, &alarm_factory_, Perspective::IS_SERVER,
SupportedVersions(GetParam()));
std::unique_ptr<TestMockUpdateStreamSession> session(
new StrictMock<TestMockUpdateStreamSession>(connection));
auto stream =
new StrictMock<TestStream>(GetNthClientInitiatedBidirectionalStreamId(
session->transport_version(), 0),
session.get(),
true);
session->ActivateStream(absl::WrapUnique(stream));
session->SetExpectedStream(stream);
session->SetExpectedPriority(HttpStreamPriority{kV3HighestPriority});
stream->SetPriority(
QuicStreamPriority(HttpStreamPriority{kV3HighestPriority}));
session->SetExpectedPriority(HttpStreamPriority{kV3LowestPriority});
stream->SetPriority(
QuicStreamPriority(HttpStreamPriority{kV3LowestPriority}));
}
TEST_P(QuicSpdyStreamTest, StreamWaitsForAcks) {
Initialize(kShouldProcessData);
quiche::QuicheReferenceCountedPointer<MockAckListener> mock_ack_listener(
new StrictMock<MockAckListener>);
stream_->set_ack_listener(mock_ack_listener);
EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)).Times(AtLeast(1));
EXPECT_FALSE(stream_->IsWaitingForAcks());
EXPECT_EQ(0u, QuicStreamPeer::SendBuffer(stream_).size());
stream_->WriteOrBufferData("FooAndBar", false, nullptr);
EXPECT_EQ(1u, QuicStreamPeer::SendBuffer(stream_).size());
EXPECT_TRUE(stream_->IsWaitingForAcks());
EXPECT_CALL(*mock_ack_listener, OnPacketAcked(9, _));
QuicByteCount newly_acked_length = 0;
EXPECT_TRUE(stream_->OnStreamFrameAcked(0, 9, false, QuicTime::Delta::Zero(),
QuicTime::Zero(),
&newly_acked_length));
EXPECT_FALSE(stream_->IsWaitingForAcks());
EXPECT_EQ(0u, QuicStreamPeer::SendBuffer(stream_).size());
stream_->WriteOrBufferData("FooAndBar", false, nullptr);
EXPECT_TRUE(stream_->IsWaitingForAcks());
EXPECT_EQ(1u, QuicStreamPeer::SendBuffer(stream_).size());
stream_->WriteOrBufferData("", true, nullptr);
EXPECT_EQ(1u, QuicStreamPeer::SendBuffer(stream_).size());
EXPECT_CALL(*mock_ack_listener, OnPacketRetransmitted(9));
stream_->OnStreamFrameRetransmitted(9, 9, false);
EXPECT_CALL(*mock_ack_listener, OnPacketAcked(9, _));
EXPECT_TRUE(stream_->OnStreamFrameAcked(9, 9, false, QuicTime::Delta::Zero(),
QuicTime::Zero(),
&newly_acked_length));
EXPECT_TRUE(stream_->IsWaitingForAcks());
EXPECT_EQ(0u, QuicStreamPeer::SendBuffer(stream_).size());
EXPECT_CALL(*mock_ack_listener, OnPacketAcked(0, _));
EXPECT_TRUE(stream_->OnStreamFrameAcked(18, 0, true, QuicTime::Delta::Zero(),
QuicTime::Zero(),
&newly_acked_length));
EXPECT_FALSE(stream_->IsWaitingForAcks());
EXPECT_EQ(0u, QuicStreamPeer::SendBuffer(stream_).size());
}
TEST_P(QuicSpdyStreamTest, StreamDataGetAckedMultipleTimes) {
Initialize(kShouldProcessData);
quiche::QuicheReferenceCountedPointer<MockAckListener> mock_ack_listener(
new StrictMock<MockAckListener>);
stream_->set_ack_listener(mock_ack_listener);
EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)).Times(AtLeast(1));
stream_->WriteOrBufferData("FooAndBar", false, nullptr);
stream_->WriteOrBufferData("FooAndBar", false, nullptr);
stream_->WriteOrBufferData("FooAndBar", true, nullptr);
QuicByteCount newly_acked_length = 0;
EXPECT_CALL(*mock_ack_listener, OnPacketAcked(9, _));
EXPECT_TRUE(stream_->OnStreamFrameAcked(0, 9, false, QuicTime::Delta::Zero(),
QuicTime::Zero(),
&newly_acked_length));
EXPECT_EQ(2u, QuicStreamPeer::SendBuffer(stream_).size());
EXPECT_CALL(*mock_ack_listener, OnPacketAcked(13, _));
EXPECT_TRUE(stream_->OnStreamFrameAcked(5, 17, false, QuicTime::Delta::Zero(),
QuicTime::Zero(),
&newly_acked_length));
EXPECT_EQ(1u, QuicStreamPeer::SendBuffer(stream_).size());
EXPECT_CALL(*mock_ack_listener, OnPacketAcked(4, _));
EXPECT_TRUE(stream_->OnStreamFrameAcked(18, 8, false, QuicTime::Delta::Zero(),
QuicTime::Zero(),
&newly_acked_length));
EXPECT_EQ(1u, QuicStreamPeer::SendBuffer(stream_).size());
EXPECT_TRUE(stream_->IsWaitingForAcks());
EXPECT_CALL(*mock_ack_listener, OnPacketAcked(1, _));
EXPECT_TRUE(stream_->OnStreamFrameAcked(26, 1, false, QuicTime::Delta::Zero(),
QuicTime::Zero(),
&newly_acked_length));
EXPECT_EQ(0u, QuicStreamPeer::SendBuffer(stream_).size());
EXPECT_TRUE(stream_->IsWaitingForAcks());
EXPECT_CALL(*mock_ack_listener, OnPacketAcked(0, _));
EXPECT_TRUE(stream_->OnStreamFrameAcked(27, 0, true, QuicTime::Delta::Zero(),
QuicTime::Zero(),
&newly_acked_length));
EXPECT_EQ(0u, QuicStreamPeer::SendBuffer(stream_).size());
EXPECT_FALSE(stream_->IsWaitingForAcks());
EXPECT_CALL(*mock_ack_listener, OnPacketAcked(_, _)).Times(0);
EXPECT_FALSE(
stream_->OnStreamFrameAcked(10, 17, true, QuicTime::Delta::Zero(),
QuicTime::Zero(), &newly_acked_length));
EXPECT_EQ(0u, QuicStreamPeer::SendBuffer(stream_).size());
EXPECT_FALSE(stream_->IsWaitingForAcks());
}
TEST_P(QuicSpdyStreamTest, HeadersAckNotReportedWriteOrBufferBody) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
quiche::QuicheReferenceCountedPointer<MockAckListener> mock_ack_listener(
new StrictMock<MockAckListener>);
stream_->set_ack_listener(mock_ack_listener);
std::string body = "Test1";
std::string body2(100, 'x');
EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)).Times(AtLeast(1));
stream_->WriteOrBufferBody(body, false);
stream_->WriteOrBufferBody(body2, true);
quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader(
body.length(), quiche::SimpleBufferAllocator::Get());
quiche::QuicheBuffer header2 = HttpEncoder::SerializeDataFrameHeader(
body2.length(), quiche::SimpleBufferAllocator::Get());
EXPECT_CALL(*mock_ack_listener, OnPacketAcked(body.length(), _));
QuicStreamFrame frame(stream_->id(), false, 0,
absl::StrCat(header.AsStringView(), body));
EXPECT_TRUE(session_->OnFrameAcked(QuicFrame(frame), QuicTime::Delta::Zero(),
QuicTime::Zero()));
EXPECT_CALL(*mock_ack_listener, OnPacketAcked(0, _));
QuicStreamFrame frame2(stream_->id(), false, header.size() + body.length(),
header2.AsStringView());
EXPECT_TRUE(session_->OnFrameAcked(QuicFrame(frame2), QuicTime::Delta::Zero(),
QuicTime::Zero()));
EXPECT_CALL(*mock_ack_listener, OnPacketAcked(body2.length(), _));
QuicStreamFrame frame3(stream_->id(), true,
header.size() + body.length() + header2.size(), body2);
EXPECT_TRUE(session_->OnFrameAcked(QuicFrame(frame3), QuicTime::Delta::Zero(),
QuicTime::Zero()));
EXPECT_TRUE(
QuicSpdyStreamPeer::unacked_frame_headers_offsets(stream_).Empty());
}
TEST_P(QuicSpdyStreamTest, HeadersAckNotReportedWriteBodySlices) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
quiche::QuicheReferenceCountedPointer<MockAckListener> mock_ack_listener(
new StrictMock<MockAckListener>);
stream_->set_ack_listener(mock_ack_listener);
std::string body1 = "Test1";
std::string body2(100, 'x');
struct iovec body1_iov = {const_cast<char*>(body1.data()), body1.length()};
struct iovec body2_iov = {const_cast<char*>(body2.data()), body2.length()};
quiche::QuicheMemSliceStorage storage(
&body1_iov, 1, helper_.GetStreamSendBufferAllocator(), 1024);
quiche::QuicheMemSliceStorage storage2(
&body2_iov, 1, helper_.GetStreamSendBufferAllocator(), 1024);
EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)).Times(AtLeast(1));
stream_->WriteBodySlices(storage.ToSpan(), false);
stream_->WriteBodySlices(storage2.ToSpan(), true);
std::string data1 = DataFrame(body1);
std::string data2 = DataFrame(body2);
EXPECT_CALL(*mock_ack_listener,
OnPacketAcked(body1.length() + body2.length(), _));
QuicStreamFrame frame(stream_->id(), true, 0, data1 + data2);
EXPECT_TRUE(session_->OnFrameAcked(QuicFrame(frame), QuicTime::Delta::Zero(),
QuicTime::Zero()));
EXPECT_TRUE(
QuicSpdyStreamPeer::unacked_frame_headers_offsets(stream_).Empty());
}
TEST_P(QuicSpdyStreamTest, HeaderBytesNotReportedOnRetransmission) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
quiche::QuicheReferenceCountedPointer<MockAckListener> mock_ack_listener(
new StrictMock<MockAckListener>);
stream_->set_ack_listener(mock_ack_listener);
std::string body1 = "Test1";
std::string body2(100, 'x');
EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)).Times(AtLeast(1));
stream_->WriteOrBufferBody(body1, false);
stream_->WriteOrBufferBody(body2, true);
std::string data1 = DataFrame(body1);
std::string data2 = DataFrame(body2);
EXPECT_CALL(*mock_ack_listener, OnPacketRetransmitted(body1.length()));
QuicStreamFrame frame(stream_->id(), false, 0, data1);
session_->OnStreamFrameRetransmitted(frame);
EXPECT_CALL(*mock_ack_listener, OnPacketRetransmitted(body2.length()));
QuicStreamFrame frame2(stream_->id(), true, data1.length(), data2);
session_->OnStreamFrameRetransmitted(frame2);
EXPECT_FALSE(
QuicSpdyStreamPeer::unacked_frame_headers_offsets(stream_).Empty());
}
TEST_P(QuicSpdyStreamTest, HeadersFrameOnRequestStream) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
std::string headers = HeadersFrame({std::make_pair("foo", "bar")});
std::string data = DataFrame(kDataFramePayload);
std::string trailers =
HeadersFrame({std::make_pair("custom-key", "custom-value")});
std::string stream_frame_payload = absl::StrCat(headers, data, trailers);
QuicStreamFrame frame(stream_->id(), false, 0, stream_frame_payload);
stream_->OnStreamFrame(frame);
EXPECT_THAT(stream_->header_list(), ElementsAre(Pair("foo", "bar")));
EXPECT_EQ("", stream_->data());
stream_->ConsumeHeaderList();
EXPECT_EQ(kDataFramePayload, stream_->data());
EXPECT_THAT(stream_->received_trailers(),
ElementsAre(Pair("custom-key", "custom-value")));
}
TEST_P(QuicSpdyStreamTest, ProcessBodyAfterTrailers) {
if (!UsesHttp3()) {
return;
}
Initialize(!kShouldProcessData);
std::string headers = HeadersFrame({std::make_pair("foo", "bar")});
std::string data = DataFrame(kDataFramePayload);
HttpHeaderBlock trailers_block;
trailers_block["key1"] = std::string(10000, 'x');
std::string trailers = HeadersFrame(trailers_block);
std::string stream_frame_payload = absl::StrCat(headers, data, trailers);
QuicStreamFrame frame(stream_->id(), false, 0, stream_frame_payload);
stream_->OnStreamFrame(frame);
stream_->ConsumeHeaderList();
stream_->MarkTrailersConsumed();
EXPECT_TRUE(stream_->trailers_decompressed());
EXPECT_EQ(trailers_block, stream_->received_trailers());
EXPECT_TRUE(stream_->HasBytesToRead());
char buffer[2048];
struct iovec vec;
vec.iov_base = buffer;
vec.iov_len = ABSL_ARRAYSIZE(buffer);
size_t bytes_read = stream_->Readv(&vec, 1);
EXPECT_EQ(kDataFramePayload, absl::string_view(buffer, bytes_read));
EXPECT_FALSE(stream_->HasBytesToRead());
}
TEST_P(QuicSpdyStreamTest, MalformedHeadersStopHttpDecoder) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
testing::InSequence s;
connection_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
std::string headers_bytes;
ASSERT_TRUE(absl::HexStringToBytes("00002a94e7036261", &headers_bytes));
std::string headers = HeadersFrame(headers_bytes);
std::string data = DataFrame(kDataFramePayload);
std::string stream_frame_payload = absl::StrCat(headers, data);
QuicStreamFrame frame(stream_->id(), false, 0, stream_frame_payload);
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_QPACK_DECOMPRESSION_FAILED,
MatchesRegex("Error decoding headers on stream \\d+: "
"Incomplete header block."),
_))
.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, DoNotMarkConsumedAfterQpackDecodingError) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
connection_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
{
testing::InSequence s;
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_QPACK_DECOMPRESSION_FAILED,
MatchesRegex("Error decoding headers on stream \\d+: "
"Invalid relative index."),
_))
.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(stream_->id(), _, _));
EXPECT_CALL(*session_, MaybeSendRstStreamFrame(stream2_->id(), _, _));
std::string headers_bytes;
ASSERT_TRUE(absl::HexStringToBytes("000080", &headers_bytes));
std::string headers = HeadersFrame(headers_bytes);
QuicStreamFrame frame(stream_->id(), false, 0, headers);
stream_->OnStreamFrame(frame);
}
TEST_P(QuicSpdyStreamTest, ImmediateHeaderDecodingWithDynamicTableEntries) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
testing::InSequence s;
session_->qpack_decoder()->OnSetDynamicTableCapacity(1024);
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
session_->qpack_decoder()->OnInsertWithoutNameReference("foo", "bar");
EXPECT_EQ(std::nullopt, stream_->header_decoding_delay());
std::string encoded_headers;
ASSERT_TRUE(absl::HexStringToBytes("020080", &encoded_headers));
std::string headers = HeadersFrame(encoded_headers);
EXPECT_CALL(debug_visitor,
OnHeadersFrameReceived(stream_->id(), encoded_headers.length()));
EXPECT_CALL(debug_visitor, OnHeadersDecoded(stream_->id(), _));
stream_->OnStreamFrame(QuicStreamFrame(stream_->id(), false, 0, headers));
EXPECT_TRUE(stream_->headers_decompressed());
EXPECT_THAT(stream_->header_list(), ElementsAre(Pair("foo", "bar")));
stream_->ConsumeHeaderList();
EXPECT_THAT(stream_->header_decoding_delay(),
Optional(QuicTime::Delta::Zero()));
std::string data = DataFrame(kDataFramePayload);
EXPECT_CALL(debug_visitor,
OnDataFrameReceived(stream_->id(), kDataFramePayload.length()));
stream_->OnStreamFrame(QuicStreamFrame(stream_->id(), false,
headers.length(), data));
EXPECT_EQ(kDataFramePayload, stream_->data());
session_->qpack_decoder()->OnInsertWithoutNameReference("trailing", "foobar");
std::string encoded_trailers;
ASSERT_TRUE(absl::HexStringToBytes("030080", &encoded_trailers));
std::string trailers = HeadersFrame(encoded_trailers);
EXPECT_CALL(debug_visitor,
OnHeadersFrameReceived(stream_->id(), encoded_trailers.length()));
EXPECT_CALL(debug_visitor, OnHeadersDecoded(stream_->id(), _));
stream_->OnStreamFrame(QuicStreamFrame(stream_->id(), true,
headers.length() + data.length(),
trailers));
EXPECT_TRUE(stream_->trailers_decompressed());
EXPECT_THAT(stream_->received_trailers(),
ElementsAre(Pair("trailing", "foobar")));
stream_->MarkTrailersConsumed();
}
TEST_P(QuicSpdyStreamTest, BlockedHeaderDecoding) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
testing::InSequence s;
session_->qpack_decoder()->OnSetDynamicTableCapacity(1024);
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
std::string encoded_headers;
ASSERT_TRUE(absl::HexStringToBytes("020080", &encoded_headers));
std::string headers = HeadersFrame(encoded_headers);
EXPECT_CALL(debug_visitor,
OnHeadersFrameReceived(stream_->id(), encoded_headers.length()));
stream_->OnStreamFrame(QuicStreamFrame(stream_->id(), false, 0, headers));
EXPECT_FALSE(stream_->headers_decompressed());
EXPECT_EQ(std::nullopt, stream_->header_decoding_delay());
EXPECT_CALL(debug_visitor, OnHeadersDecoded(stream_->id(), _));
const QuicTime::Delta delay = QuicTime::Delta::FromSeconds(1);
helper_.GetClock()->AdvanceTime(delay);
session_->qpack_decoder()->OnInsertWithoutNameReference("foo", "bar");
EXPECT_TRUE(stream_->headers_decompressed());
EXPECT_THAT(stream_->header_list(), ElementsAre(Pair("foo", "bar")));
stream_->ConsumeHeaderList();
EXPECT_THAT(stream_->header_decoding_delay(), Optional(delay));
std::string data = DataFrame(kDataFramePayload);
EXPECT_CALL(debug_visitor,
OnDataFrameReceived(stream_->id(), kDataFramePayload.length()));
stream_->OnStreamFrame(QuicStreamFrame(stream_->id(), false,
headers.length(), data));
EXPECT_EQ(kDataFramePayload, stream_->data());
std::string encoded_trailers;
ASSERT_TRUE(absl::HexStringToBytes("030080", &encoded_trailers));
std::string trailers = HeadersFrame(encoded_trailers);
EXPECT_CALL(debug_visitor,
OnHeadersFrameReceived(stream_->id(), encoded_trailers.length()));
stream_->OnStreamFrame(QuicStreamFrame(stream_->id(), true,
headers.length() + data.length(),
trailers));
EXPECT_FALSE(stream_->trailers_decompressed());
EXPECT_CALL(debug_visitor, OnHeadersDecoded(stream_->id(), _));
session_->qpack_decoder()->OnInsertWithoutNameReference("trailing", "foobar");
EXPECT_TRUE(stream_->trailers_decompressed());
EXPECT_THAT(stream_->received_trailers(),
ElementsAre(Pair("trailing", "foobar")));
stream_->MarkTrailersConsumed();
}
TEST_P(QuicSpdyStreamTest, BlockedHeaderDecodingAndStopReading) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
testing::InSequence s;
session_->qpack_decoder()->OnSetDynamicTableCapacity(1024);
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
std::string encoded_headers;
ASSERT_TRUE(absl::HexStringToBytes("020080", &encoded_headers));
std::string headers = HeadersFrame(encoded_headers);
EXPECT_CALL(debug_visitor,
OnHeadersFrameReceived(stream_->id(), encoded_headers.length()));
stream_->OnStreamFrame(QuicStreamFrame(stream_->id(), false, 0, headers));
EXPECT_FALSE(stream_->headers_decompressed());
if (GetQuicReloadableFlag(
quic_stop_reading_also_stops_header_decompression)) {
EXPECT_CALL(debug_visitor, OnHeadersDecoded(stream_->id(), _)).Times(0);
}
stream_->StopReading();
if (!GetQuicReloadableFlag(
quic_stop_reading_also_stops_header_decompression)) {
EXPECT_CALL(debug_visitor, OnHeadersDecoded(stream_->id(), _));
}
session_->qpack_decoder()->OnInsertWithoutNameReference("foo", "bar");
EXPECT_NE(
GetQuicReloadableFlag(quic_stop_reading_also_stops_header_decompression),
stream_->headers_decompressed());
}
TEST_P(QuicSpdyStreamTest, AsyncErrorDecodingHeaders) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
session_->qpack_decoder()->OnSetDynamicTableCapacity(1024);
std::string headers_bytes;
ASSERT_TRUE(absl::HexStringToBytes("030081", &headers_bytes));
std::string headers = HeadersFrame(headers_bytes);
stream_->OnStreamFrame(QuicStreamFrame(stream_->id(), false, 0, headers));
EXPECT_FALSE(stream_->headers_decompressed());
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_QPACK_DECOMPRESSION_FAILED,
MatchesRegex("Error decoding headers on stream \\d+: "
"Required Insert Count too large."),
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET));
session_->qpack_decoder()->OnInsertWithoutNameReference("foo", "bar");
session_->qpack_decoder()->OnInsertWithoutNameReference("foo", "bar");
}
TEST_P(QuicSpdyStreamTest, BlockedHeaderDecodingUnblockedWithBufferedError) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
session_->qpack_decoder()->OnSetDynamicTableCapacity(1024);
std::string headers_bytes;
ASSERT_TRUE(absl::HexStringToBytes("020082", &headers_bytes));
std::string headers = HeadersFrame(headers_bytes);
stream_->OnStreamFrame(QuicStreamFrame(stream_->id(), false, 0, headers));
EXPECT_FALSE(stream_->headers_decompressed());
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_QPACK_DECOMPRESSION_FAILED,
MatchesRegex("Error decoding headers on stream \\d+: "
"Invalid relative index."),
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET));
session_->qpack_decoder()->OnInsertWithoutNameReference("foo", "bar");
}
TEST_P(QuicSpdyStreamTest, AsyncErrorDecodingTrailers) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
testing::InSequence s;
session_->qpack_decoder()->OnSetDynamicTableCapacity(1024);
std::string headers_bytes;
ASSERT_TRUE(absl::HexStringToBytes("020080", &headers_bytes));
std::string headers = HeadersFrame(headers_bytes);
stream_->OnStreamFrame(QuicStreamFrame(stream_->id(), false, 0, headers));
EXPECT_FALSE(stream_->headers_decompressed());
session_->qpack_decoder()->OnInsertWithoutNameReference("foo", "bar");
EXPECT_TRUE(stream_->headers_decompressed());
EXPECT_THAT(stream_->header_list(), ElementsAre(Pair("foo", "bar")));
stream_->ConsumeHeaderList();
std::string data = DataFrame(kDataFramePayload);
stream_->OnStreamFrame(QuicStreamFrame(stream_->id(), false,
headers.length(), data));
EXPECT_EQ(kDataFramePayload, stream_->data());
std::string trailers_bytes;
ASSERT_TRUE(absl::HexStringToBytes("030081", &trailers_bytes));
std::string trailers = HeadersFrame(trailers_bytes);
stream_->OnStreamFrame(QuicStreamFrame(stream_->id(), true,
headers.length() + data.length(),
trailers));
EXPECT_FALSE(stream_->trailers_decompressed());
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_QPACK_DECOMPRESSION_FAILED,
MatchesRegex("Error decoding trailers on stream \\d+: "
"Required Insert Count too large."),
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET));
session_->qpack_decoder()->OnInsertWithoutNameReference("trailing", "foobar");
}
TEST_P(QuicSpdyStreamTest, HeaderDecodingUnblockedAfterStreamClosed) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
testing::InSequence s;
session_->qpack_decoder()->OnSetDynamicTableCapacity(1024);
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
std::string encoded_headers;
ASSERT_TRUE(absl::HexStringToBytes("020080", &encoded_headers));
std::string headers = HeadersFrame(encoded_headers);
EXPECT_CALL(debug_visitor,
OnHeadersFrameReceived(stream_->id(), encoded_headers.length()));
stream_->OnStreamFrame(QuicStreamFrame(stream_->id(), false, 0, headers));
EXPECT_FALSE(stream_->headers_decompressed());
EXPECT_CALL(*session_, MaybeSendStopSendingFrame(
stream_->id(), QuicResetStreamError::FromInternal(
QUIC_STREAM_CANCELLED)));
EXPECT_CALL(
*session_,
MaybeSendRstStreamFrame(
stream_->id(),
QuicResetStreamError::FromInternal(QUIC_STREAM_CANCELLED), _));
stream_->Reset(QUIC_STREAM_CANCELLED);
session_->qpack_decoder()->OnInsertWithoutNameReference("foo", "bar");
EXPECT_FALSE(stream_->headers_decompressed());
}
TEST_P(QuicSpdyStreamTest, HeaderDecodingUnblockedAfterResetReceived) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
testing::InSequence s;
session_->qpack_decoder()->OnSetDynamicTableCapacity(1024);
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
std::string encoded_headers;
ASSERT_TRUE(absl::HexStringToBytes("020080", &encoded_headers));
std::string headers = HeadersFrame(encoded_headers);
EXPECT_CALL(debug_visitor,
OnHeadersFrameReceived(stream_->id(), encoded_headers.length()));
stream_->OnStreamFrame(QuicStreamFrame(stream_->id(), false, 0, headers));
EXPECT_FALSE(stream_->headers_decompressed());
stream_->OnStreamReset(QuicRstStreamFrame(
kInvalidControlFrameId, stream_->id(), QUIC_STREAM_CANCELLED, 0));
session_->qpack_decoder()->OnInsertWithoutNameReference("foo", "bar");
EXPECT_FALSE(stream_->headers_decompressed());
}
class QuicSpdyStreamIncrementalConsumptionTest : public QuicSpdyStreamTest {
protected:
QuicSpdyStreamIncrementalConsumptionTest() : offset_(0), consumed_bytes_(0) {}
~QuicSpdyStreamIncrementalConsumptionTest() override = default;
void OnStreamFrame(absl::string_view payload) {
QuicStreamFrame frame(stream_->id(), false, offset_, payload);
stream_->OnStreamFrame(frame);
offset_ += payload.size();
}
QuicStreamOffset NewlyConsumedBytes() {
QuicStreamOffset previously_consumed_bytes = consumed_bytes_;
consumed_bytes_ = stream_->sequencer()->NumBytesConsumed();
return consumed_bytes_ - previously_consumed_bytes;
}
std::string ReadFromStream(QuicByteCount size) {
std::string buffer;
buffer.resize(size);
struct iovec vec;
vec.iov_base = const_cast<char*>(buffer.data());
vec.iov_len = size;
size_t bytes_read = stream_->Readv(&vec, 1);
EXPECT_EQ(bytes_read, size);
return buffer;
}
private:
QuicStreamOffset offset_;
QuicStreamOffset consumed_bytes_;
};
INSTANTIATE_TEST_SUITE_P(Tests, QuicSpdyStreamIncrementalConsumptionTest,
::testing::ValuesIn(AllSupportedVersions()),
::testing::PrintToStringParamName());
TEST_P(QuicSpdyStreamIncrementalConsumptionTest, OnlyKnownFrames) {
if (!UsesHttp3()) {
return;
}
Initialize(!kShouldProcessData);
std::string headers = HeadersFrame({std::make_pair("foo", "bar")});
OnStreamFrame(absl::string_view(headers).substr(0, headers.size() - 1));
EXPECT_EQ(headers.size() - 1, NewlyConsumedBytes());
OnStreamFrame(absl::string_view(headers).substr(headers.size() - 1));
EXPECT_EQ(1u, NewlyConsumedBytes());
EXPECT_THAT(stream_->header_list(), ElementsAre(Pair("foo", "bar")));
stream_->ConsumeHeaderList();
absl::string_view data_payload(kDataFramePayload);
std::string data_frame = DataFrame(data_payload);
QuicByteCount data_frame_header_length =
data_frame.size() - data_payload.size();
OnStreamFrame(data_frame);
EXPECT_EQ(data_frame_header_length, NewlyConsumedBytes());
EXPECT_EQ(data_payload.substr(0, data_payload.size() - 1),
ReadFromStream(data_payload.size() - 1));
EXPECT_EQ(data_payload.size() - 1, NewlyConsumedBytes());
std::string trailers =
HeadersFrame({std::make_pair("custom-key", "custom-value")});
OnStreamFrame(absl::string_view(trailers).substr(0, trailers.size() - 1));
EXPECT_EQ(0u, NewlyConsumedBytes());
EXPECT_EQ(data_payload.substr(data_payload.size() - 1), ReadFromStream(1));
EXPECT_EQ(1 + trailers.size() - 1, NewlyConsumedBytes());
OnStreamFrame(absl::string_view(trailers).substr(trailers.size() - 1));
EXPECT_EQ(1u, NewlyConsumedBytes());
EXPECT_THAT(stream_->received_trailers(),
ElementsAre(Pair("custom-key", "custom-value")));
}
TEST_P(QuicSpdyStreamIncrementalConsumptionTest, ReceiveUnknownFrame) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
EXPECT_CALL(debug_visitor,
OnUnknownFrameReceived(stream_->id(), 0x21,
3));
std::string unknown_frame = UnknownFrame(0x21, "foo");
OnStreamFrame(unknown_frame);
}
TEST_P(QuicSpdyStreamIncrementalConsumptionTest,
ReceiveUnsupportedMetadataFrame) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
quiche::HttpHeaderBlock headers;
headers.AppendValueOrAddHeader("key1", "val1");
headers.AppendValueOrAddHeader("key2", "val2");
NoopDecoderStreamErrorDelegate delegate;
QpackEncoder qpack_encoder(&delegate, HuffmanEncoding::kDisabled,
CookieCrumbling::kEnabled);
std::string metadata_frame_payload = qpack_encoder.EncodeHeaderList(
stream_->id(), headers,
nullptr);
std::string metadata_frame_header =
HttpEncoder::SerializeMetadataFrameHeader(metadata_frame_payload.size());
std::string metadata_frame = metadata_frame_header + metadata_frame_payload;
EXPECT_CALL(debug_visitor,
OnUnknownFrameReceived(
stream_->id(), 0x4d,
metadata_frame_payload.length()));
OnStreamFrame(metadata_frame);
}
class MockMetadataVisitor : public QuicSpdyStream::MetadataVisitor {
public:
~MockMetadataVisitor() override = default;
MOCK_METHOD(void, OnMetadataComplete,
(size_t frame_len, const QuicHeaderList& header_list),
(override));
};
TEST_P(QuicSpdyStreamIncrementalConsumptionTest, ReceiveMetadataFrame) {
if (!UsesHttp3()) {
return;
}
StrictMock<MockMetadataVisitor> metadata_visitor;
Initialize(kShouldProcessData);
stream_->RegisterMetadataVisitor(&metadata_visitor);
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
quiche::HttpHeaderBlock headers;
headers.AppendValueOrAddHeader("key1", "val1");
headers.AppendValueOrAddHeader("key2", "val2");
NoopDecoderStreamErrorDelegate delegate;
QpackEncoder qpack_encoder(&delegate, HuffmanEncoding::kDisabled,
CookieCrumbling::kEnabled);
std::string metadata_frame_payload = qpack_encoder.EncodeHeaderList(
stream_->id(), headers,
nullptr);
std::string metadata_frame_header =
HttpEncoder::SerializeMetadataFrameHeader(metadata_frame_payload.size());
std::string metadata_frame = metadata_frame_header + metadata_frame_payload;
EXPECT_CALL(metadata_visitor, OnMetadataComplete(metadata_frame.size(), _))
.WillOnce(testing::WithArgs<1>(
Invoke([&headers](const QuicHeaderList& header_list) {
quiche::HttpHeaderBlock actual_headers;
for (const auto& header : header_list) {
actual_headers.AppendValueOrAddHeader(header.first,
header.second);
}
EXPECT_EQ(headers, actual_headers);
})));
OnStreamFrame(metadata_frame);
}
TEST_P(QuicSpdyStreamIncrementalConsumptionTest,
ResetDuringMultipleMetadataFrames) {
if (!UsesHttp3()) {
return;
}
StrictMock<MockMetadataVisitor> metadata_visitor;
Initialize(kShouldProcessData);
stream_->RegisterMetadataVisitor(&metadata_visitor);
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
quiche::HttpHeaderBlock headers;
headers.AppendValueOrAddHeader("key1", "val1");
headers.AppendValueOrAddHeader("key2", "val2");
NoopDecoderStreamErrorDelegate delegate;
QpackEncoder qpack_encoder(&delegate, HuffmanEncoding::kDisabled,
CookieCrumbling::kEnabled);
std::string metadata_frame_payload = qpack_encoder.EncodeHeaderList(
stream_->id(), headers,
nullptr);
std::string metadata_frame_header =
HttpEncoder::SerializeMetadataFrameHeader(metadata_frame_payload.size());
std::string metadata_frame = metadata_frame_header + metadata_frame_payload;
EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)).Times(AnyNumber());
EXPECT_CALL(*session_, MaybeSendStopSendingFrame(_, _));
EXPECT_CALL(*session_, MaybeSendRstStreamFrame(_, _, _));
EXPECT_CALL(metadata_visitor, OnMetadataComplete(metadata_frame.size(), _))
.WillOnce(testing::WithArgs<1>(
Invoke([&headers, this](const QuicHeaderList& header_list) {
quiche::HttpHeaderBlock actual_headers;
for (const auto& header : header_list) {
actual_headers.AppendValueOrAddHeader(header.first,
header.second);
}
EXPECT_EQ(headers, actual_headers);
stream_->Reset(QUIC_STREAM_CANCELLED);
})));
std::string data = metadata_frame + metadata_frame;
OnStreamFrame(data);
}
TEST_P(QuicSpdyStreamIncrementalConsumptionTest, UnknownFramesInterleaved) {
if (!UsesHttp3()) {
return;
}
Initialize(!kShouldProcessData);
std::string unknown_frame1 = UnknownFrame(0x21, "foo");
OnStreamFrame(unknown_frame1);
EXPECT_EQ(unknown_frame1.size(), NewlyConsumedBytes());
std::string headers = HeadersFrame({std::make_pair("foo", "bar")});
OnStreamFrame(absl::string_view(headers).substr(0, headers.size() - 1));
EXPECT_EQ(headers.size() - 1, NewlyConsumedBytes());
OnStreamFrame(absl::string_view(headers).substr(headers.size() - 1));
EXPECT_EQ(1u, NewlyConsumedBytes());
EXPECT_THAT(stream_->header_list(), ElementsAre(Pair("foo", "bar")));
stream_->ConsumeHeaderList();
std::string unknown_frame2 = UnknownFrame(0x3a, "");
OnStreamFrame(unknown_frame2);
EXPECT_EQ(unknown_frame2.size(), NewlyConsumedBytes());
absl::string_view data_payload(kDataFramePayload);
std::string data_frame = DataFrame(data_payload);
QuicByteCount data_frame_header_length =
data_frame.size() - data_payload.size();
OnStreamFrame(data_frame);
EXPECT_EQ(data_frame_header_length, NewlyConsumedBytes());
std::string unknown_frame3 = UnknownFrame(0x39, "bar");
OnStreamFrame(unknown_frame3);
EXPECT_EQ(0u, NewlyConsumedBytes());
EXPECT_EQ(data_payload.substr(0, data_payload.size() - 1),
ReadFromStream(data_payload.size() - 1));
EXPECT_EQ(data_payload.size() - 1, NewlyConsumedBytes());
std::string trailers =
HeadersFrame({std::make_pair("custom-key", "custom-value")});
OnStreamFrame(absl::string_view(trailers).substr(0, trailers.size() - 1));
EXPECT_EQ(0u, NewlyConsumedBytes());
EXPECT_EQ(data_payload.substr(data_payload.size() - 1), ReadFromStream(1));
EXPECT_EQ(1 + unknown_frame3.size() + trailers.size() - 1,
NewlyConsumedBytes());
OnStreamFrame(absl::string_view(trailers).substr(trailers.size() - 1));
EXPECT_EQ(1u, NewlyConsumedBytes());
EXPECT_THAT(stream_->received_trailers(),
ElementsAre(Pair("custom-key", "custom-value")));
std::string unknown_frame4 = UnknownFrame(0x40, "");
OnStreamFrame(unknown_frame4);
EXPECT_EQ(unknown_frame4.size(), NewlyConsumedBytes());
}
TEST_P(QuicSpdyStreamTest, DataBeforeHeaders) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_HTTP_INVALID_FRAME_SEQUENCE_ON_SPDY_STREAM,
"Unexpected DATA frame received.",
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET))
.WillOnce(InvokeWithoutArgs([this]() { stream_->StopReading(); }));
std::string data = DataFrame(kDataFramePayload);
stream_->OnStreamFrame(QuicStreamFrame(stream_->id(), false, 0, data));
}
TEST_P(QuicSpdyStreamTest, TrailersAfterTrailers) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
std::string headers = HeadersFrame({std::make_pair("foo", "bar")});
QuicStreamOffset offset = 0;
stream_->OnStreamFrame(
QuicStreamFrame(stream_->id(), false, offset, headers));
offset += headers.size();
EXPECT_THAT(stream_->header_list(), ElementsAre(Pair("foo", "bar")));
stream_->ConsumeHeaderList();
std::string data = DataFrame(kDataFramePayload);
stream_->OnStreamFrame(QuicStreamFrame(stream_->id(), false, offset, data));
offset += data.size();
EXPECT_EQ(kDataFramePayload, stream_->data());
std::string trailers1 =
HeadersFrame({std::make_pair("custom-key", "custom-value")});
stream_->OnStreamFrame(
QuicStreamFrame(stream_->id(), false, offset, trailers1));
offset += trailers1.size();
EXPECT_TRUE(stream_->trailers_decompressed());
EXPECT_THAT(stream_->received_trailers(),
ElementsAre(Pair("custom-key", "custom-value")));
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_HTTP_INVALID_FRAME_SEQUENCE_ON_SPDY_STREAM,
"HEADERS frame received after trailing HEADERS.",
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET))
.WillOnce(InvokeWithoutArgs([this]() { stream_->StopReading(); }));
std::string trailers2 = HeadersFrame(HttpHeaderBlock());
stream_->OnStreamFrame(
QuicStreamFrame(stream_->id(), false, offset, trailers2));
}
TEST_P(QuicSpdyStreamTest, DataAfterTrailers) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
std::string headers = HeadersFrame({std::make_pair("foo", "bar")});
QuicStreamOffset offset = 0;
stream_->OnStreamFrame(
QuicStreamFrame(stream_->id(), false, offset, headers));
offset += headers.size();
EXPECT_THAT(stream_->header_list(), ElementsAre(Pair("foo", "bar")));
stream_->ConsumeHeaderList();
std::string data1 = DataFrame(kDataFramePayload);
stream_->OnStreamFrame(QuicStreamFrame(stream_->id(), false, offset, data1));
offset += data1.size();
EXPECT_EQ(kDataFramePayload, stream_->data());
std::string trailers =
HeadersFrame({std::make_pair("custom-key", "custom-value")});
stream_->OnStreamFrame(
QuicStreamFrame(stream_->id(), false, offset, trailers));
offset += trailers.size();
EXPECT_THAT(stream_->received_trailers(),
ElementsAre(Pair("custom-key", "custom-value")));
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_HTTP_INVALID_FRAME_SEQUENCE_ON_SPDY_STREAM,
"Unexpected DATA frame received.",
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET))
.WillOnce(InvokeWithoutArgs([this]() { stream_->StopReading(); }));
std::string data2 = DataFrame("This payload should not be processed.");
stream_->OnStreamFrame(QuicStreamFrame(stream_->id(), false, offset, data2));
}
TEST_P(QuicSpdyStreamTest, StopProcessingIfConnectionClosed) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
std::string settings;
ASSERT_TRUE(absl::HexStringToBytes("0400", &settings));
std::string headers = HeadersFrame({std::make_pair("foo", "bar")});
std::string frames = absl::StrCat(settings, headers);
EXPECT_EQ(0u, stream_->sequencer()->NumBytesConsumed());
EXPECT_CALL(*connection_,
CloseConnection(QUIC_HTTP_FRAME_UNEXPECTED_ON_SPDY_STREAM, _, _))
.WillOnce(
Invoke(connection_, &MockQuicConnection::ReallyCloseConnection));
EXPECT_CALL(*connection_, SendConnectionClosePacket(_, _, _));
EXPECT_CALL(*session_, OnConnectionClosed(_, _));
stream_->OnStreamFrame(QuicStreamFrame(stream_->id(), false,
0, frames));
EXPECT_EQ(0u, stream_->sequencer()->NumBytesConsumed());
}
TEST_P(QuicSpdyStreamTest, StreamCancellationWhenStreamReset) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
EXPECT_CALL(*session_, MaybeSendStopSendingFrame(
stream_->id(), QuicResetStreamError::FromInternal(
QUIC_STREAM_CANCELLED)));
EXPECT_CALL(
*session_,
MaybeSendRstStreamFrame(
stream_->id(),
QuicResetStreamError::FromInternal(QUIC_STREAM_CANCELLED), _));
stream_->Reset(QUIC_STREAM_CANCELLED);
}
TEST_P(QuicSpdyStreamTest, StreamCancellationOnResetReceived) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
stream_->OnStreamReset(QuicRstStreamFrame(
kInvalidControlFrameId, stream_->id(), QUIC_STREAM_CANCELLED, 0));
}
TEST_P(QuicSpdyStreamTest, WriteHeadersReturnValue) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
testing::InSequence s;
session_->OnSetting(SETTINGS_QPACK_MAX_TABLE_CAPACITY, 1024);
session_->OnSetting(SETTINGS_QPACK_BLOCKED_STREAMS, 1);
EXPECT_CALL(*stream_, WriteHeadersMock(true));
QpackSendStream* encoder_stream =
QuicSpdySessionPeer::GetQpackEncoderSendStream(session_.get());
EXPECT_CALL(*session_, WritevData(encoder_stream->id(), _, _, _, _, _))
.Times(AnyNumber());
size_t bytes_written = 0;
EXPECT_CALL(*session_,
WritevData(stream_->id(), _, 0, _, _, _))
.WillOnce(
DoAll(SaveArg<1>(&bytes_written),
Invoke(session_.get(), &MockQuicSpdySession::ConsumeData)));
HttpHeaderBlock request_headers;
request_headers["foo"] = "bar";
size_t write_headers_return_value =
stream_->WriteHeaders(std::move(request_headers), true, nullptr);
EXPECT_TRUE(stream_->fin_sent());
EXPECT_GT(bytes_written, write_headers_return_value);
}
TEST_P(QuicSpdyStreamTest, TwoResetStreamFrames) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)).Times(AnyNumber());
QuicRstStreamFrame rst_frame1(kInvalidControlFrameId, stream_->id(),
QUIC_STREAM_CANCELLED, 0);
stream_->OnStreamReset(rst_frame1);
EXPECT_TRUE(stream_->read_side_closed());
EXPECT_FALSE(stream_->write_side_closed());
QuicRstStreamFrame rst_frame2(kInvalidControlFrameId, stream_->id(),
QUIC_STREAM_NO_ERROR, 0);
stream_->OnStreamReset(rst_frame2);
EXPECT_TRUE(stream_->read_side_closed());
EXPECT_FALSE(stream_->write_side_closed());
}
TEST_P(QuicSpdyStreamTest, ProcessOutgoingWebTransportHeaders) {
if (!UsesHttp3()) {
return;
}
InitializeWithPerspective(kShouldProcessData, Perspective::IS_CLIENT);
session_->set_local_http_datagram_support(HttpDatagramSupport::kRfc);
session_->EnableWebTransport();
session_->OnSetting(SETTINGS_ENABLE_CONNECT_PROTOCOL, 1);
QuicSpdySessionPeer::EnableWebTransport(session_.get());
QuicSpdySessionPeer::SetHttpDatagramSupport(session_.get(),
HttpDatagramSupport::kRfc);
EXPECT_CALL(*stream_, WriteHeadersMock(false));
EXPECT_CALL(*session_, WritevData(stream_->id(), _, _, _, _, _))
.Times(AnyNumber());
quiche::HttpHeaderBlock headers;
headers[":method"] = "CONNECT";
headers[":protocol"] = "webtransport";
stream_->WriteHeaders(std::move(headers), false, nullptr);
ASSERT_TRUE(stream_->web_transport() != nullptr);
EXPECT_EQ(stream_->id(), stream_->web_transport()->id());
}
TEST_P(QuicSpdyStreamTest, ProcessIncomingWebTransportHeaders) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
session_->set_local_http_datagram_support(HttpDatagramSupport::kRfc);
session_->EnableWebTransport();
QuicSpdySessionPeer::EnableWebTransport(session_.get());
QuicSpdySessionPeer::SetHttpDatagramSupport(session_.get(),
HttpDatagramSupport::kRfc);
headers_[":method"] = "CONNECT";
headers_[":protocol"] = "webtransport";
stream_->OnStreamHeadersPriority(
spdy::SpdyStreamPrecedence(kV3HighestPriority));
ProcessHeaders(false, headers_);
EXPECT_EQ("", stream_->data());
EXPECT_FALSE(stream_->header_list().empty());
EXPECT_FALSE(stream_->IsDoneReading());
ASSERT_TRUE(stream_->web_transport() != nullptr);
EXPECT_EQ(stream_->id(), stream_->web_transport()->id());
}
TEST_P(QuicSpdyStreamTest, IncomingWebTransportStreamWhenUnsupported) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
session_->set_local_http_datagram_support(HttpDatagramSupport::kRfc);
session_->EnableWebTransport();
session_->OnSettingsFrame(SettingsFrame());
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
std::string webtransport_stream_frame;
ASSERT_TRUE(
absl::HexStringToBytes("40410400000000", &webtransport_stream_frame));
QuicStreamFrame stream_frame(stream_->id(), false,
0, webtransport_stream_frame);
EXPECT_CALL(debug_visitor, OnUnknownFrameReceived(stream_->id(), 0x41, 4));
stream_->OnStreamFrame(stream_frame);
EXPECT_TRUE(stream_->web_transport_stream() == nullptr);
}
TEST_P(QuicSpdyStreamTest, IncomingWebTransportStream) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
session_->set_local_http_datagram_support(HttpDatagramSupport::kRfc);
session_->EnableWebTransport();
SettingsFrame settings;
settings.values[SETTINGS_WEBTRANS_MAX_SESSIONS_DRAFT07] = 10;
settings.values[SETTINGS_H3_DATAGRAM] = 1;
session_->OnSettingsFrame(settings);
std::string webtransport_stream_frame;
ASSERT_TRUE(absl::HexStringToBytes("404110", &webtransport_stream_frame));
QuicStreamFrame stream_frame(stream_->id(), false,
0, webtransport_stream_frame);
EXPECT_CALL(*session_, CreateIncomingStream(0x10));
stream_->OnStreamFrame(stream_frame);
EXPECT_TRUE(stream_->web_transport_stream() != nullptr);
}
TEST_P(QuicSpdyStreamTest, IncomingWebTransportStreamWithPaddingDraft02) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
session_->set_local_http_datagram_support(HttpDatagramSupport::kRfc);
session_->EnableWebTransport();
SettingsFrame settings;
settings.values[SETTINGS_WEBTRANS_DRAFT00] = 1;
settings.values[SETTINGS_H3_DATAGRAM] = 1;
session_->OnSettingsFrame(settings);
std::string webtransport_stream_frame;
ASSERT_TRUE(absl::HexStringToBytes("2100404110", &webtransport_stream_frame));
QuicStreamFrame stream_frame(stream_->id(), false,
0, webtransport_stream_frame);
EXPECT_CALL(*session_, CreateIncomingStream(0x10));
stream_->OnStreamFrame(stream_frame);
EXPECT_TRUE(stream_->web_transport_stream() != nullptr);
}
TEST_P(QuicSpdyStreamTest, IncomingWebTransportStreamWithPaddingDraft07) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
session_->set_local_http_datagram_support(HttpDatagramSupport::kRfc);
session_->EnableWebTransport();
SettingsFrame settings;
settings.values[SETTINGS_WEBTRANS_MAX_SESSIONS_DRAFT07] = 10;
settings.values[SETTINGS_H3_DATAGRAM] = 1;
session_->OnSettingsFrame(settings);
std::string webtransport_stream_frame;
ASSERT_TRUE(absl::HexStringToBytes("2100404110", &webtransport_stream_frame));
QuicStreamFrame stream_frame(stream_->id(), false,
0, webtransport_stream_frame);
EXPECT_CALL(*connection_,
CloseConnection(QUIC_HTTP_INVALID_FRAME_SEQUENCE_ON_SPDY_STREAM,
HasSubstr("non-zero offset"), _));
stream_->OnStreamFrame(stream_frame);
EXPECT_TRUE(stream_->web_transport_stream() == nullptr);
}
TEST_P(QuicSpdyStreamTest, ReceiveHttpDatagram) {
if (!UsesHttp3()) {
return;
}
InitializeWithPerspective(kShouldProcessData, Perspective::IS_CLIENT);
session_->set_local_http_datagram_support(HttpDatagramSupport::kRfc);
QuicSpdySessionPeer::SetHttpDatagramSupport(session_.get(),
HttpDatagramSupport::kRfc);
headers_[":method"] = "CONNECT";
headers_[":protocol"] = "webtransport";
ProcessHeaders(false, headers_);
SavingHttp3DatagramVisitor h3_datagram_visitor;
ASSERT_EQ(QuicDataWriter::GetVarInt62Len(stream_->id()), 1);
std::array<char, 256> datagram;
datagram[0] = stream_->id();
for (size_t i = 1; i < datagram.size(); i++) {
datagram[i] = i;
}
stream_->RegisterHttp3DatagramVisitor(&h3_datagram_visitor);
session_->OnMessageReceived(
absl::string_view(datagram.data(), datagram.size()));
EXPECT_THAT(
h3_datagram_visitor.received_h3_datagrams(),
ElementsAre(SavingHttp3DatagramVisitor::SavedHttp3Datagram{
stream_->id(), std::string(&datagram[1], datagram.size() - 1)}));
SavingHttp3DatagramVisitor h3_datagram_visitor2;
stream_->ReplaceHttp3DatagramVisitor(&h3_datagram_visitor2);
EXPECT_TRUE(h3_datagram_visitor2.received_h3_datagrams().empty());
session_->OnMessageReceived(
absl::string_view(datagram.data(), datagram.size()));
EXPECT_THAT(
h3_datagram_visitor2.received_h3_datagrams(),
ElementsAre(SavingHttp3DatagramVisitor::SavedHttp3Datagram{
stream_->id(), std::string(&datagram[1], datagram.size() - 1)}));
stream_->UnregisterHttp3DatagramVisitor();
}
TEST_P(QuicSpdyStreamTest, SendHttpDatagram) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
session_->set_local_http_datagram_support(HttpDatagramSupport::kRfc);
QuicSpdySessionPeer::SetHttpDatagramSupport(session_.get(),
HttpDatagramSupport::kRfc);
std::string http_datagram_payload = {1, 2, 3, 4, 5, 6};
EXPECT_CALL(*connection_, SendMessage(1, _, false))
.WillOnce(Return(MESSAGE_STATUS_SUCCESS));
EXPECT_EQ(stream_->SendHttp3Datagram(http_datagram_payload),
MESSAGE_STATUS_SUCCESS);
}
TEST_P(QuicSpdyStreamTest, SendHttpDatagramWithoutLocalSupport) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
session_->set_local_http_datagram_support(HttpDatagramSupport::kNone);
std::string http_datagram_payload = {1, 2, 3, 4, 5, 6};
EXPECT_QUIC_BUG(stream_->SendHttp3Datagram(http_datagram_payload),
"Cannot send HTTP Datagram when disabled locally");
}
TEST_P(QuicSpdyStreamTest, SendHttpDatagramBeforeReceivingSettings) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
session_->set_local_http_datagram_support(HttpDatagramSupport::kRfc);
std::string http_datagram_payload = {1, 2, 3, 4, 5, 6};
EXPECT_EQ(stream_->SendHttp3Datagram(http_datagram_payload),
MESSAGE_STATUS_SETTINGS_NOT_RECEIVED);
}
TEST_P(QuicSpdyStreamTest, SendHttpDatagramWithoutPeerSupport) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
session_->set_local_http_datagram_support(HttpDatagramSupport::kRfc);
SettingsFrame settings;
settings.values[SETTINGS_H3_DATAGRAM] = 0;
session_->OnSettingsFrame(settings);
std::string http_datagram_payload = {1, 2, 3, 4, 5, 6};
EXPECT_EQ(stream_->SendHttp3Datagram(http_datagram_payload),
MESSAGE_STATUS_UNSUPPORTED);
}
TEST_P(QuicSpdyStreamTest, GetMaxDatagramSize) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
session_->set_local_http_datagram_support(HttpDatagramSupport::kRfc);
QuicSpdySessionPeer::SetHttpDatagramSupport(session_.get(),
HttpDatagramSupport::kRfc);
EXPECT_GT(stream_->GetMaxDatagramSize(), 512u);
}
TEST_P(QuicSpdyStreamTest, Capsules) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
session_->set_local_http_datagram_support(HttpDatagramSupport::kRfc);
QuicSpdySessionPeer::SetHttpDatagramSupport(session_.get(),
HttpDatagramSupport::kRfc);
SavingHttp3DatagramVisitor h3_datagram_visitor;
stream_->RegisterHttp3DatagramVisitor(&h3_datagram_visitor);
SavingConnectIpVisitor connect_ip_visitor;
stream_->RegisterConnectIpVisitor(&connect_ip_visitor);
headers_[":method"] = "CONNECT";
headers_[":protocol"] = "fake-capsule-protocol";
ProcessHeaders(false, headers_);
std::string http_datagram_payload = {1, 2, 3, 4, 5, 6};
stream_->OnCapsule(Capsule::Datagram(http_datagram_payload));
EXPECT_THAT(h3_datagram_visitor.received_h3_datagrams(),
ElementsAre(SavingHttp3DatagramVisitor::SavedHttp3Datagram{
stream_->id(), http_datagram_payload}));
quiche::PrefixWithId ip_prefix_with_id;
ip_prefix_with_id.request_id = 1;
quiche::QuicheIpAddress ip_address;
ip_address.FromString("::");
ip_prefix_with_id.ip_prefix =
quiche::QuicheIpPrefix(ip_address, 96);
Capsule address_assign_capsule = Capsule::AddressAssign();
address_assign_capsule.address_assign_capsule().assigned_addresses.push_back(
ip_prefix_with_id);
stream_->OnCapsule(address_assign_capsule);
EXPECT_THAT(connect_ip_visitor.received_address_assign_capsules(),
ElementsAre(address_assign_capsule.address_assign_capsule()));
Capsule address_request_capsule = Capsule::AddressRequest();
address_request_capsule.address_request_capsule()
.requested_addresses.push_back(ip_prefix_with_id);
stream_->OnCapsule(address_request_capsule);
EXPECT_THAT(connect_ip_visitor.received_address_request_capsules(),
ElementsAre(address_request_capsule.address_request_capsule()));
Capsule route_advertisement_capsule = Capsule::RouteAdvertisement();
IpAddressRange ip_address_range;
ip_address_range.start_ip_address.FromString("192.0.2.24");
ip_address_range.end_ip_address.FromString("192.0.2.42");
ip_address_range.ip_protocol = 0;
route_advertisement_capsule.route_advertisement_capsule()
.ip_address_ranges.push_back(ip_address_range);
stream_->OnCapsule(route_advertisement_capsule);
EXPECT_THAT(
connect_ip_visitor.received_route_advertisement_capsules(),
ElementsAre(route_advertisement_capsule.route_advertisement_capsule()));
uint64_t capsule_type = 0x17u;
std::string capsule_payload = {1, 2, 3, 4};
Capsule unknown_capsule = Capsule::Unknown(capsule_type, capsule_payload);
stream_->OnCapsule(unknown_capsule);
EXPECT_THAT(h3_datagram_visitor.received_unknown_capsules(),
ElementsAre(SavingHttp3DatagramVisitor::SavedUnknownCapsule{
stream_->id(), capsule_type, capsule_payload}));
stream_->UnregisterHttp3DatagramVisitor();
stream_->UnregisterConnectIpVisitor();
}
TEST_P(QuicSpdyStreamTest,
QUIC_TEST_DISABLED_IN_CHROME(HeadersAccumulatorNullptr)) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
std::string headers = HeadersFrame({std::make_pair("foo", "bar")});
stream_->OnStreamFrame(QuicStreamFrame(stream_->id(), false, 0, headers));
stream_->OnHeadersDecoded({}, false);
EXPECT_QUIC_BUG(
{
EXPECT_CALL(*connection_, CloseConnection(_, _, _));
EXPECT_FALSE(QuicSpdyStreamPeer::OnHeadersFrameEnd(stream_));
},
"b215142466_OnHeadersFrameEnd");
}
TEST_P(QuicSpdyStreamTest, ReadAfterReset) {
if (!UsesHttp3()) {
return;
}
Initialize(!kShouldProcessData);
ProcessHeaders(false, headers_);
stream_->ConsumeHeaderList();
std::string data_frame = DataFrame(kDataFramePayload);
QuicStreamFrame frame(stream_->id(), false, 0, data_frame);
stream_->OnStreamFrame(frame);
stream_->OnStreamReset(QuicRstStreamFrame(
kInvalidControlFrameId, stream_->id(), QUIC_STREAM_NO_ERROR, 0));
char buffer[100];
struct iovec vec;
vec.iov_base = buffer;
vec.iov_len = ABSL_ARRAYSIZE(buffer);
size_t bytes_read = stream_->Readv(&vec, 1);
EXPECT_EQ(0u, bytes_read);
}
TEST_P(QuicSpdyStreamTest, ColonDisallowedInHeaderName) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
headers_["foo:bar"] = "invalid";
EXPECT_FALSE(stream_->ValidateReceivedHeaders(AsHeaderList(headers_)));
EXPECT_EQ("Invalid character in header name foo:bar",
stream_->invalid_request_details());
}
TEST_P(QuicSpdyStreamTest, HostHeaderInRequest) {
if (!UsesHttp3()) {
return;
}
Initialize(kShouldProcessData);
headers_["host"] = "foo";
if (GetQuicReloadableFlag(quic_allow_host_in_request2)) {
EXPECT_TRUE(stream_->ValidateReceivedHeaders(AsHeaderList(headers_)));
} else {
EXPECT_FALSE(stream_->ValidateReceivedHeaders(AsHeaderList(headers_)));
EXPECT_EQ("host header is not allowed", stream_->invalid_request_details());
}
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/quic_spdy_stream.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/quic_spdy_stream_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
9ba49551-4fc5-4137-807f-a64223fef3f8 | 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 | #include "quiche/quic/core/http/quic_spdy_server_stream_base.h"
#include <optional>
#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/platform/api/quiche_flag_utils.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;
std::optional<std::string> authority;
std::optional<std::string> host;
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") {
authority = pair.second;
} 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;
} else if (pair.first == "host") {
host = pair.second;
}
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 (GetQuicReloadableFlag(quic_allow_host_in_request2)) {
QUICHE_RELOADABLE_FLAG_COUNT_N(quic_allow_host_in_request2, 2, 3);
if (host && (!authority || *authority != *host)) {
QUIC_CODE_COUNT(http3_host_header_does_not_match_authority);
set_invalid_request_details("Host header does not match authority");
return false;
}
}
if (is_extended_connect) {
if (saw_scheme && saw_path && 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 && 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/core/qpack/value_splitting_header_list.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/common/http/http_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.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.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.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.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.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.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.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.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.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.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.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, HostHeaderWithoutAuthority) {
SetQuicReloadableFlag(quic_act_upon_invalid_header, true);
SetQuicReloadableFlag(quic_allow_host_in_request2, true);
QuicHeaderList header_list;
header_list.OnHeader("host", "www.google.com:4433");
header_list.OnHeader(":scheme", "http");
header_list.OnHeader(":method", "POST");
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, HostHeaderWitDifferentAuthority) {
SetQuicReloadableFlag(quic_act_upon_invalid_header, true);
SetQuicReloadableFlag(quic_allow_host_in_request2, true);
QuicHeaderList header_list;
header_list.OnHeader(":authority", "www.google.com:4433");
header_list.OnHeader(":scheme", "http");
header_list.OnHeader(":method", "POST");
header_list.OnHeader(":path", "/path");
header_list.OnHeader("host", "mail.google.com:4433");
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, ValidHostHeader) {
SetQuicReloadableFlag(quic_act_upon_invalid_header, true);
SetQuicReloadableFlag(quic_allow_host_in_request2, true);
QuicHeaderList header_list;
header_list.OnHeader(":authority", "www.google.com:4433");
header_list.OnHeader(":scheme", "http");
header_list.OnHeader(":method", "POST");
header_list.OnHeader(":path", "/path");
header_list.OnHeader("host", "www.google.com:4433");
header_list.OnHeaderBlockEnd(128, 128);
stream_->OnStreamHeaderList(false, 0, header_list);
EXPECT_FALSE(stream_->rst_sent());
}
TEST_F(QuicSpdyServerStreamBaseTest, EmptyHeaders) {
SetQuicReloadableFlag(quic_act_upon_invalid_header, true);
quiche::HttpHeaderBlock 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,
CookieCrumbling::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());
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/quic_spdy_server_stream_base.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/quic_spdy_server_stream_base_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
e6a53ecf-262f-4a73-8681-729d61a7cb24 | cpp | google/quiche | http_encoder | quiche/quic/core/http/http_encoder.cc | quiche/quic/core/http/http_encoder_test.cc | #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::SerializeOriginFrame(const OriginFrame& origin) {
QuicByteCount payload_length = 0;
for (const std::string& entry : origin.origins) {
constexpr QuicByteCount kLengthFieldOverhead = 2;
payload_length += kLengthFieldOverhead + entry.size();
}
QuicByteCount total_length =
GetTotalLength(payload_length, HttpFrameType::ORIGIN);
std::string frame;
frame.resize(total_length);
QuicDataWriter writer(total_length, frame.data());
if (!WriteFrameHeader(payload_length, HttpFrameType::ORIGIN, &writer)) {
QUIC_DLOG(ERROR) << "Http encoder failed to serialize ORIGIN frame header.";
return {};
}
for (const std::string& entry : origin.origins) {
if (!writer.WriteStringPiece16(entry)) {
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, SerializeEmptyOriginFrame) {
OriginFrame frame;
uint8_t expected[] = {0x0C,
0x00};
std::string output = HttpEncoder::SerializeOriginFrame(frame);
quiche::test::CompareCharArraysWithHexError(
"ORIGIN", output.data(), output.length(),
reinterpret_cast<char*>(expected), ABSL_ARRAYSIZE(expected));
}
TEST(HttpEncoderTest, SerializeOriginFrame) {
OriginFrame frame;
frame.origins = {"foo", "bar"};
uint8_t expected[] = {0x0C,
0x0A,
0x00, 0x003,
0x66, 0x6f, 0x6f,
0x00, 0x003,
0x62, 0x61, 0x72};
std::string output = HttpEncoder::SerializeOriginFrame(frame);
quiche::test::CompareCharArraysWithHexError(
"ORIGIN", output.data(), output.length(),
reinterpret_cast<char*>(expected), ABSL_ARRAYSIZE(expected));
}
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));
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/http_encoder.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/http_encoder_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
a9d6e50b-861a-4c55-b233-20860fc7a291 | cpp | google/quiche | web_transport_http3 | quiche/quic/core/http/web_transport_http3.cc | quiche/quic/core/http/web_transport_http3_test.cc | #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 quiche::HttpHeaderBlock& 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));
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/web_transport_http3.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/web_transport_http3_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
a18745e0-7850-49be-a0f1-f376124d5507 | 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 | #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));
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/quic_spdy_stream_body_manager.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/quic_spdy_stream_body_manager_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
716754ad-2df8-41c0-9550-49ab9b1acfa3 | cpp | google/quiche | quic_header_list | quiche/quic/core/http/quic_header_list.cc | quiche/quic/core/http/quic_header_list_test.cc | #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 {
void QuicHeaderList::OnHeader(absl::string_view name, absl::string_view value) {
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;
}
void QuicHeaderList::Clear() {
header_list_.clear();
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, 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", "")));
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/quic_header_list.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/quic_header_list_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
9bb9b7ea-bdbc-4d32-b3c2-c473b5a052e4 | cpp | google/quiche | quic_headers_stream | quiche/quic/core/http/quic_headers_stream.cc | quiche/quic/core/http/quic_headers_stream_test.cc | #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/http2/core/http2_frame_decoder_adapter.h"
#include "quiche/http2/core/recording_headers_handler.h"
#include "quiche/http2/core/spdy_alt_svc_wire_format.h"
#include "quiche/http2/core/spdy_protocol.h"
#include "quiche/http2/test_tools/spdy_test_utils.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/http/http_header_block.h"
#include "quiche/common/quiche_endian.h"
using quiche::HttpHeaderBlock;
using spdy::ERROR_CODE_PROTOCOL_ERROR;
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_;
HttpHeaderBlock 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, false, QuicTime::Delta::Zero(), QuicTime::Zero(),
&newly_acked_length));
EXPECT_EQ(12u, newly_acked_length);
EXPECT_CALL(*ack_listener1, OnPacketAcked(14, _));
EXPECT_CALL(*ack_listener2, OnPacketAcked(3, _));
EXPECT_TRUE(headers_stream_->OnStreamFrameAcked(
0, 17, false, QuicTime::Delta::Zero(), QuicTime::Zero(),
&newly_acked_length));
EXPECT_EQ(17u, newly_acked_length);
}
TEST_P(QuicHeadersStreamTest, HeadersGetAckedMultipleTimes) {
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);
QuicByteCount newly_acked_length = 0;
EXPECT_CALL(*ack_listener2, OnPacketAcked(5, _));
EXPECT_TRUE(headers_stream_->OnStreamFrameAcked(
15, 5, false, QuicTime::Delta::Zero(), QuicTime::Zero(),
&newly_acked_length));
EXPECT_EQ(5u, newly_acked_length);
EXPECT_CALL(*ack_listener1, OnPacketAcked(9, _));
EXPECT_CALL(*ack_listener2, OnPacketAcked(1, _));
EXPECT_CALL(*ack_listener2, OnPacketAcked(1, _));
EXPECT_CALL(*ack_listener3, OnPacketAcked(4, _));
EXPECT_TRUE(headers_stream_->OnStreamFrameAcked(
5, 20, false, QuicTime::Delta::Zero(), QuicTime::Zero(),
&newly_acked_length));
EXPECT_EQ(15u, newly_acked_length);
EXPECT_FALSE(headers_stream_->OnStreamFrameAcked(
10, 7, false, QuicTime::Delta::Zero(), QuicTime::Zero(),
&newly_acked_length));
EXPECT_EQ(0u, newly_acked_length);
EXPECT_CALL(*ack_listener1, OnPacketAcked(5, _));
EXPECT_TRUE(headers_stream_->OnStreamFrameAcked(
0, 12, false, QuicTime::Delta::Zero(), QuicTime::Zero(),
&newly_acked_length));
EXPECT_EQ(5u, newly_acked_length);
EXPECT_CALL(*ack_listener3, OnPacketAcked(3, _));
EXPECT_CALL(*ack_listener2, OnPacketAcked(7, _));
EXPECT_CALL(*ack_listener3, OnPacketAcked(7, _));
EXPECT_TRUE(headers_stream_->OnStreamFrameAcked(
22, 20, false, QuicTime::Delta::Zero(), QuicTime::Zero(),
&newly_acked_length));
EXPECT_EQ(17u, newly_acked_length);
}
TEST_P(QuicHeadersStreamTest, CloseOnPushPromiseToServer) {
if (perspective() == Perspective::IS_CLIENT) {
return;
}
QuicStreamId promised_id = 1;
SpdyPushPromiseIR push_promise(client_id_1_, promised_id, headers_.Clone());
SpdySerializedFrame frame = framer_->SerializeFrame(push_promise);
stream_frame_.data_buffer = frame.data();
stream_frame_.data_length = frame.size();
EXPECT_CALL(session_, OnStreamHeaderList(_, _, _, _));
EXPECT_CALL(*connection_, CloseConnection(QUIC_INVALID_HEADERS_STREAM_DATA,
"PUSH_PROMISE not supported.", _));
headers_stream_->OnStreamFrame(stream_frame_);
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/quic_headers_stream.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/quic_headers_stream_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
3ca819db-f581-4313-a4d9-73d5fb37ee7c | 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 | #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),
origin_frame_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::MaybeSendOriginFrame(
std::vector<std::string> origins) {
if (origins.empty() || origin_frame_sent_) {
return;
}
OriginFrame frame;
frame.origins = std::move(origins);
QUIC_DVLOG(1) << "Control stream " << id() << " is writing origin frame "
<< frame;
WriteOrBufferData(HttpEncoder::SerializeOriginFrame(frame), false,
nullptr);
origin_frame_sent_ = true;
}
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, SendOriginFrameOnce) {
Initialize();
std::vector<std::string> origins = {"a", "b", "c"};
EXPECT_CALL(session_, WritevData(send_control_stream_->id(), _, _, _, _, _))
.Times(1);
send_control_stream_->MaybeSendOriginFrame(origins);
send_control_stream_->MaybeSendOriginFrame(origins);
}
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);
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/quic_send_control_stream.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/quic_send_control_stream_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
6857c23b-75e7-41e2-917d-67f9283e7e56 | cpp | google/quiche | http_decoder | quiche/quic/core/http/http_decoder.cc | quiche/quic/core/http/http_decoder_test.cc | #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_(""),
enable_origin_frame_(GetQuicReloadableFlag(enable_h3_origin_frame)) {
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(¤t_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(¤t_frame_type_);
QUICHE_DCHECK(success);
}
if (decoded_frame_types_.size() < 10) {
decoded_frame_types_.push_back(current_frame_type_);
}
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(¤t_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(¤t_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;
case static_cast<uint64_t>(HttpFrameType::METADATA):
continue_processing =
visitor_->OnMetadataFrameStart(header_length, current_frame_length_);
break;
default:
if (enable_origin_frame_ &&
current_frame_type_ == static_cast<uint64_t>(HttpFrameType::ORIGIN)) {
QUIC_CODE_COUNT_N(enable_h3_origin_frame, 1, 2);
continue_processing = visitor_->OnOriginFrameStart(header_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::ORIGIN):
if (enable_origin_frame_) {
QUIC_CODE_COUNT_N(enable_h3_origin_frame, 2, 2);
return true;
}
return false;
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;
}
case 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;
}
default: {
if (enable_origin_frame_ &&
current_frame_type_ == static_cast<uint64_t>(HttpFrameType::ORIGIN)) {
QUICHE_NOTREACHED();
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;
}
case static_cast<uint64_t>(HttpFrameType::METADATA): {
continue_processing = visitor_->OnMetadataFrameEnd();
break;
}
default:
if (enable_origin_frame_ &&
current_frame_type_ == static_cast<uint64_t>(HttpFrameType::ORIGIN)) {
QUICHE_NOTREACHED();
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::ORIGIN): {
OriginFrame frame;
if (!ParseOriginFrame(reader, frame)) {
return false;
}
return visitor_->OnOriginFrame(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<QuicByteCount>(
remaining_length_field_length_, reader.BytesRemaining());
bool success =
reader.ReadBytes(length_buffer_.data() + current_length_field_length_ -
remaining_length_field_length_,
bytes_to_read);
QUICHE_DCHECK(success);
remaining_length_field_length_ -= bytes_to_read;
}
void HttpDecoder::BufferFrameType(QuicDataReader& reader) {
QuicByteCount bytes_to_read = std::min<QuicByteCount>(
remaining_type_field_length_, reader.BytesRemaining());
bool success =
reader.ReadBytes(type_buffer_.data() + current_type_field_length_ -
remaining_type_field_length_,
bytes_to_read);
QUICHE_DCHECK(success);
remaining_type_field_length_ -= bytes_to_read;
}
void HttpDecoder::RaiseError(QuicErrorCode error, std::string error_detail) {
state_ = STATE_ERROR;
error_ = error;
error_detail_ = std::move(error_detail);
visitor_->OnError(this);
}
bool HttpDecoder::ParseSettingsFrame(QuicDataReader& reader,
SettingsFrame& frame) {
while (!reader.IsDoneReading()) {
uint64_t id;
if (!reader.ReadVarInt62(&id)) {
RaiseError(QUIC_HTTP_FRAME_ERROR, "Unable to read setting identifier.");
return false;
}
uint64_t content;
if (!reader.ReadVarInt62(&content)) {
RaiseError(QUIC_HTTP_FRAME_ERROR, "Unable to read setting value.");
return false;
}
auto result = frame.values.insert({id, content});
if (!result.second) {
RaiseError(QUIC_HTTP_DUPLICATE_SETTING_IDENTIFIER,
"Duplicate setting identifier.");
return false;
}
}
return true;
}
bool HttpDecoder::ParsePriorityUpdateFrame(QuicDataReader& reader,
PriorityUpdateFrame& frame) {
if (!reader.ReadVarInt62(&frame.prioritized_element_id)) {
RaiseError(QUIC_HTTP_FRAME_ERROR, "Unable to read prioritized element id.");
return false;
}
absl::string_view priority_field_value = reader.ReadRemainingPayload();
frame.priority_field_value =
std::string(priority_field_value.data(), priority_field_value.size());
return true;
}
bool HttpDecoder::ParseOriginFrame(QuicDataReader& reader, OriginFrame& frame) {
QUICHE_DCHECK(enable_origin_frame_);
while (!reader.IsDoneReading()) {
absl::string_view origin;
if (!reader.ReadStringPiece16(&origin)) {
RaiseError(QUIC_HTTP_FRAME_ERROR, "Unable to read ORIGIN origin.");
return false;
}
frame.origins.push_back(std::string(origin));
}
return true;
}
bool HttpDecoder::ParseAcceptChFrame(QuicDataReader& reader,
AcceptChFrame& frame) {
absl::string_view origin;
absl::string_view value;
while (!reader.IsDoneReading()) {
if (!reader.ReadStringPieceVarInt62(&origin)) {
RaiseError(QUIC_HTTP_FRAME_ERROR, "Unable to read ACCEPT_CH origin.");
return false;
}
if (!reader.ReadStringPieceVarInt62(&value)) {
RaiseError(QUIC_HTTP_FRAME_ERROR, "Unable to read ACCEPT_CH value.");
return false;
}
frame.entries.push_back({std::string(origin.data(), origin.size()),
std::string(value.data(), value.size())});
}
return true;
}
QuicByteCount HttpDecoder::MaxFrameLength(uint64_t frame_type) {
QUICHE_DCHECK(IsFrameBuffered());
switch (frame_type) {
case static_cast<uint64_t>(HttpFrameType::SETTINGS):
return kPayloadLengthLimit;
case static_cast<uint64_t>(HttpFrameType::GOAWAY):
return quiche::VARIABLE_LENGTH_INTEGER_LENGTH_8;
case static_cast<uint64_t>(HttpFrameType::MAX_PUSH_ID):
return quiche::VARIABLE_LENGTH_INTEGER_LENGTH_8;
case static_cast<uint64_t>(HttpFrameType::PRIORITY_UPDATE_REQUEST_STREAM):
return kPayloadLengthLimit;
case static_cast<uint64_t>(HttpFrameType::ACCEPT_CH):
return kPayloadLengthLimit;
case static_cast<uint64_t>(HttpFrameType::ORIGIN):
return kPayloadLengthLimit;
default:
QUICHE_NOTREACHED();
return 0;
}
}
std::string HttpDecoder::DebugString() const {
return absl::StrCat(
"HttpDecoder:", "\n state: ", state_, "\n error: ", error_,
"\n current_frame_type: ", current_frame_type_,
"\n current_length_field_length: ", current_length_field_length_,
"\n remaining_length_field_length: ", remaining_length_field_length_,
"\n current_frame_length: ", current_frame_length_,
"\n remaining_frame_length: ", remaining_frame_length_,
"\n current_type_field_length: ", current_type_field_length_,
"\n remaining_type_field_length: ", remaining_type_field_length_);
}
} | #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::ElementsAre;
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_, OnOriginFrameStart(_)).WillByDefault(Return(true));
ON_CALL(visitor_, OnOriginFrame(_)).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_THAT(decoder_.decoded_frame_types(), ElementsAre(4));
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_THAT(decoder_.decoded_frame_types(), ElementsAre(4, 4));
EXPECT_CALL(visitor_, OnSettingsFrameStart(2));
EXPECT_CALL(visitor_, OnSettingsFrame(frame));
ProcessInputCharByChar(input);
EXPECT_THAT(decoder_.error(), IsQuicNoError());
EXPECT_EQ("", decoder_.error_detail());
EXPECT_THAT(decoder_.decoded_frame_types(), ElementsAre(4, 4, 4));
}
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",
&input));
EXPECT_CALL(visitor_, OnError(&decoder_));
EXPECT_EQ(input.size(), ProcessInput(input));
EXPECT_THAT(decoder_.error(), IsError(QUIC_HTTP_FRAME_ERROR));
EXPECT_EQ("Unable to read GOAWAY ID.", decoder_.error_detail());
}
TEST_F(HttpDecoderTest, EmptyMaxPushIdFrame) {
std::string input;
ASSERT_TRUE(
absl::HexStringToBytes("0d"
"00",
&input));
EXPECT_CALL(visitor_, OnError(&decoder_));
EXPECT_EQ(input.size(), ProcessInput(input));
EXPECT_THAT(decoder_.error(), IsError(QUIC_HTTP_FRAME_ERROR));
EXPECT_EQ("Unable to read MAX_PUSH_ID push_id.", decoder_.error_detail());
}
TEST_F(HttpDecoderTest, LargeStreamIdInGoAway) {
GoAwayFrame frame;
frame.id = 1ull << 60;
std::string goaway = HttpEncoder::SerializeGoAwayFrame(frame);
EXPECT_CALL(visitor_, OnGoAwayFrame(frame));
EXPECT_GT(goaway.length(), 0u);
EXPECT_EQ(goaway.length(),
decoder_.ProcessInput(goaway.data(), goaway.length()));
EXPECT_THAT(decoder_.error(), IsQuicNoError());
EXPECT_EQ("", decoder_.error_detail());
}
TEST_F(HttpDecoderTest, ObsoletePriorityUpdateFrame) {
const QuicByteCount header_length = 2;
const QuicByteCount payload_length = 3;
InSequence s;
std::string input;
ASSERT_TRUE(
absl::HexStringToBytes("0f"
"03"
"666f6f",
&input));
EXPECT_CALL(visitor_,
OnUnknownFrameStart(0x0f, header_length, payload_length));
EXPECT_CALL(visitor_, OnUnknownFramePayload(Eq("foo")));
EXPECT_CALL(visitor_, OnUnknownFrameEnd()).WillOnce(Return(false));
EXPECT_EQ(header_length + payload_length,
ProcessInputWithGarbageAppended(input));
EXPECT_THAT(decoder_.error(), IsQuicNoError());
EXPECT_EQ("", decoder_.error_detail());
EXPECT_CALL(visitor_,
OnUnknownFrameStart(0x0f, header_length, payload_length));
EXPECT_CALL(visitor_, OnUnknownFramePayload(Eq("f")));
EXPECT_CALL(visitor_, OnUnknownFramePayload(Eq("o")));
EXPECT_CALL(visitor_, OnUnknownFramePayload(Eq("o")));
EXPECT_CALL(visitor_, OnUnknownFrameEnd());
ProcessInputCharByChar(input);
EXPECT_THAT(decoder_.error(), IsQuicNoError());
EXPECT_EQ("", decoder_.error_detail());
}
TEST_F(HttpDecoderTest, PriorityUpdateFrame) {
InSequence s;
std::string input1;
ASSERT_TRUE(
absl::HexStringToBytes("800f0700"
"01"
"03",
&input1));
PriorityUpdateFrame priority_update1;
priority_update1.prioritized_element_id = 0x03;
EXPECT_CALL(visitor_, OnPriorityUpdateFrameStart(5)).WillOnce(Return(false));
absl::string_view remaining_input(input1);
QuicByteCount processed_bytes =
ProcessInputWithGarbageAppended(remaining_input);
EXPECT_EQ(5u, processed_bytes);
remaining_input = remaining_input.substr(processed_bytes);
EXPECT_CALL(visitor_, OnPriorityUpdateFrame(priority_update1))
.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_, OnPriorityUpdateFrameStart(5));
EXPECT_CALL(visitor_, OnPriorityUpdateFrame(priority_update1));
EXPECT_EQ(input1.size(), ProcessInput(input1));
EXPECT_THAT(decoder_.error(), IsQuicNoError());
EXPECT_EQ("", decoder_.error_detail());
EXPECT_CALL(visitor_, OnPriorityUpdateFrameStart(5));
EXPECT_CALL(visitor_, OnPriorityUpdateFrame(priority_update1));
ProcessInputCharByChar(input1);
EXPECT_THAT(decoder_.error(), IsQuicNoError());
EXPECT_EQ("", decoder_.error_detail());
std::string input2;
ASSERT_TRUE(
absl::HexStringToBytes("800f0700"
"04"
"05"
"666f6f",
&input2));
PriorityUpdateFrame priority_update2;
priority_update2.prioritized_element_id = 0x05;
priority_update2.priority_field_value = "foo";
EXPECT_CALL(visitor_, OnPriorityUpdateFrameStart(5)).WillOnce(Return(false));
remaining_input = input2;
processed_bytes = ProcessInputWithGarbageAppended(remaining_input);
EXPECT_EQ(5u, processed_bytes);
remaining_input = remaining_input.substr(processed_bytes);
EXPECT_CALL(visitor_, OnPriorityUpdateFrame(priority_update2))
.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_, OnPriorityUpdateFrameStart(5));
EXPECT_CALL(visitor_, OnPriorityUpdateFrame(priority_update2));
EXPECT_EQ(input2.size(), ProcessInput(input2));
EXPECT_THAT(decoder_.error(), IsQuicNoError());
EXPECT_EQ("", decoder_.error_detail());
EXPECT_CALL(visitor_, OnPriorityUpdateFrameStart(5));
EXPECT_CALL(visitor_, OnPriorityUpdateFrame(priority_update2));
ProcessInputCharByChar(input2);
EXPECT_THAT(decoder_.error(), IsQuicNoError());
EXPECT_EQ("", decoder_.error_detail());
}
TEST_F(HttpDecoderTest, CorruptPriorityUpdateFrame) {
std::string payload;
ASSERT_TRUE(absl::HexStringToBytes("4005",
&payload));
struct {
size_t payload_length;
const char* const error_message;
} kTestData[] = {
{0, "Unable to read prioritized element id."},
{1, "Unable to read prioritized element id."},
};
for (const auto& test_data : kTestData) {
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("800f0700",
&input));
input.push_back(test_data.payload_length);
size_t header_length = input.size();
input.append(payload.data(), test_data.payload_length);
HttpDecoder decoder(&visitor_);
EXPECT_CALL(visitor_, OnPriorityUpdateFrameStart(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, AcceptChFrame) {
InSequence s;
std::string input1;
ASSERT_TRUE(
absl::HexStringToBytes("4089"
"00",
&input1));
AcceptChFrame accept_ch1;
EXPECT_CALL(visitor_, OnAcceptChFrameStart(3)).WillOnce(Return(false));
absl::string_view remaining_input(input1);
QuicByteCount processed_bytes =
ProcessInputWithGarbageAppended(remaining_input);
EXPECT_EQ(3u, processed_bytes);
remaining_input = remaining_input.substr(processed_bytes);
EXPECT_CALL(visitor_, OnAcceptChFrame(accept_ch1)).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_, OnAcceptChFrameStart(3));
EXPECT_CALL(visitor_, OnAcceptChFrame(accept_ch1));
EXPECT_EQ(input1.size(), ProcessInput(input1));
EXPECT_THAT(decoder_.error(), IsQuicNoError());
EXPECT_EQ("", decoder_.error_detail());
EXPECT_CALL(visitor_, OnAcceptChFrameStart(3));
EXPECT_CALL(visitor_, OnAcceptChFrame(accept_ch1));
ProcessInputCharByChar(input1);
EXPECT_THAT(decoder_.error(), IsQuicNoError());
EXPECT_EQ("", decoder_.error_detail());
std::string input2;
ASSERT_TRUE(
absl::HexStringToBytes("4089"
"08"
"03"
"666f6f"
"03"
"626172",
&input2));
AcceptChFrame accept_ch2;
accept_ch2.entries.push_back({"foo", "bar"});
EXPECT_CALL(visitor_, OnAcceptChFrameStart(3)).WillOnce(Return(false));
remaining_input = input2;
processed_bytes = ProcessInputWithGarbageAppended(remaining_input);
EXPECT_EQ(3u, processed_bytes);
remaining_input = remaining_input.substr(processed_bytes);
EXPECT_CALL(visitor_, OnAcceptChFrame(accept_ch2)).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_, OnAcceptChFrameStart(3));
EXPECT_CALL(visitor_, OnAcceptChFrame(accept_ch2));
EXPECT_EQ(input2.size(), ProcessInput(input2));
EXPECT_THAT(decoder_.error(), IsQuicNoError());
EXPECT_EQ("", decoder_.error_detail());
EXPECT_CALL(visitor_, OnAcceptChFrameStart(3));
EXPECT_CALL(visitor_, OnAcceptChFrame(accept_ch2));
ProcessInputCharByChar(input2);
EXPECT_THAT(decoder_.error(), IsQuicNoError());
EXPECT_EQ("", decoder_.error_detail());
}
TEST_F(HttpDecoderTest, OriginFrame) {
if (!GetQuicReloadableFlag(enable_h3_origin_frame)) {
return;
}
InSequence s;
std::string input1;
ASSERT_TRUE(
absl::HexStringToBytes("0C"
"00",
&input1));
OriginFrame origin1;
EXPECT_CALL(visitor_, OnOriginFrameStart(2)).WillOnce(Return(false));
absl::string_view remaining_input(input1);
QuicByteCount processed_bytes =
ProcessInputWithGarbageAppended(remaining_input);
EXPECT_EQ(2u, processed_bytes);
remaining_input = remaining_input.substr(processed_bytes);
EXPECT_CALL(visitor_, OnOriginFrame(origin1)).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_, OnOriginFrameStart(2));
EXPECT_CALL(visitor_, OnOriginFrame(origin1));
EXPECT_EQ(input1.size(), ProcessInput(input1));
EXPECT_THAT(decoder_.error(), IsQuicNoError());
EXPECT_EQ("", decoder_.error_detail());
EXPECT_CALL(visitor_, OnOriginFrameStart(2));
EXPECT_CALL(visitor_, OnOriginFrame(origin1));
ProcessInputCharByChar(input1);
EXPECT_THAT(decoder_.error(), IsQuicNoError());
EXPECT_EQ("", decoder_.error_detail());
std::string input2;
ASSERT_TRUE(
absl::HexStringToBytes("0C"
"0A"
"0003"
"666f6f"
"0003"
"626172",
&input2));
ASSERT_EQ(12, input2.length());
OriginFrame origin2;
origin2.origins = {"foo", "bar"};
EXPECT_CALL(visitor_, OnOriginFrameStart(2)).WillOnce(Return(false));
remaining_input = input2;
processed_bytes = ProcessInputWithGarbageAppended(remaining_input);
EXPECT_EQ(2u, processed_bytes);
remaining_input = remaining_input.substr(processed_bytes);
EXPECT_CALL(visitor_, OnOriginFrame(origin2)).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_, OnOriginFrameStart(2));
EXPECT_CALL(visitor_, OnOriginFrame(origin2));
EXPECT_EQ(input2.size(), ProcessInput(input2));
EXPECT_THAT(decoder_.error(), IsQuicNoError());
EXPECT_EQ("", decoder_.error_detail());
EXPECT_CALL(visitor_, OnOriginFrameStart(2));
EXPECT_CALL(visitor_, OnOriginFrame(origin2));
ProcessInputCharByChar(input2);
EXPECT_THAT(decoder_.error(), IsQuicNoError());
EXPECT_EQ("", decoder_.error_detail());
}
TEST_F(HttpDecoderTest, OriginFrameDisabled) {
if (GetQuicReloadableFlag(enable_h3_origin_frame)) {
return;
}
InSequence s;
std::string input1;
ASSERT_TRUE(
absl::HexStringToBytes("0C"
"00",
&input1));
EXPECT_CALL(visitor_, OnUnknownFrameStart(0x0C, 2, 0));
EXPECT_CALL(visitor_, OnUnknownFrameEnd());
EXPECT_EQ(ProcessInput(input1), input1.size());
std::string input2;
ASSERT_TRUE(
absl::HexStringToBytes("0C"
"0A"
"0003"
"666f6f"
"0003"
"626172",
&input2));
EXPECT_CALL(visitor_, OnUnknownFrameStart(0x0C, 2, input2.size() - 2));
EXPECT_CALL(visitor_, OnUnknownFramePayload(input2.substr(2)));
EXPECT_CALL(visitor_, OnUnknownFrameEnd());
EXPECT_EQ(ProcessInput(input2), input2.size());
}
TEST_F(HttpDecoderTest, WebTransportStreamDisabled) {
InSequence s;
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("40414104", &input));
EXPECT_CALL(visitor_, OnUnknownFrameStart(0x41, input.size(), 0x104));
EXPECT_EQ(ProcessInput(input), input.size());
}
TEST(HttpDecoderTestNoFixture, WebTransportStream) {
testing::StrictMock<MockHttpDecoderVisitor> visitor;
HttpDecoder decoder(&visitor);
decoder.EnableWebTransportStreamParsing();
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("40414104ffffffff", &input));
EXPECT_CALL(visitor, OnWebTransportStreamFrameType(4, 0x104));
QuicByteCount bytes = decoder.ProcessInput(input.data(), input.size());
EXPECT_EQ(bytes, 4u);
}
TEST(HttpDecoderTestNoFixture, WebTransportStreamError) {
testing::StrictMock<MockHttpDecoderVisitor> visitor;
HttpDecoder decoder(&visitor);
decoder.EnableWebTransportStreamParsing();
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("404100", &input));
EXPECT_CALL(visitor, OnWebTransportStreamFrameType(_, _));
decoder.ProcessInput(input.data(), input.size());
EXPECT_QUIC_BUG(
{
EXPECT_CALL(visitor, OnError(_));
decoder.ProcessInput(input.data(), input.size());
},
"HttpDecoder called after an indefinite-length frame");
}
TEST_F(HttpDecoderTest, DecodeSettings) {
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;
SettingsFrame out;
EXPECT_TRUE(HttpDecoder::DecodeSettings(input.data(), input.size(), &out));
EXPECT_EQ(frame, out);
ASSERT_TRUE(
absl::HexStringToBytes("0D"
"01"
"01",
&input));
EXPECT_FALSE(HttpDecoder::DecodeSettings(input.data(), input.size(), &out));
ASSERT_TRUE(absl::HexStringToBytes(
"04"
"01"
"42",
&input));
EXPECT_FALSE(HttpDecoder::DecodeSettings(input.data(), input.size(), &out));
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/http_decoder.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/http_decoder_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
ee3ece70-e829-41e9-bae8-db8fc2bcc5f5 | 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 | #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/http2/core/spdy_protocol.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"
using quiche::HttpHeaderBlock;
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,
quiche::HttpHeaderBlock& 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(HttpHeaderBlock 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 quiche::HttpHeaderBlock;
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),
&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_;
HttpHeaderBlock 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);
HttpHeaderBlock 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();
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/quic_spdy_client_stream.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/quic_spdy_client_stream_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
733b7e61-92a1-4d61-82c3-b4d67223cfbb | 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 | #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::IsBandwidthResumptionEnabled(session_.get()));
}
TEST_P(QuicServerSessionBaseTest, NoBandwidthResumptionByDefault) {
EXPECT_FALSE(
QuicServerSessionBasePeer::IsBandwidthResumptionEnabled(session_.get()));
connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
session_->OnConfigNegotiated();
EXPECT_FALSE(
QuicServerSessionBasePeer::IsBandwidthResumptionEnabled(session_.get()));
}
TEST_P(QuicServerSessionBaseTest, OpenStreamLimitPerEventLoop) {
if (!VersionHasIetfQuicFrames(transport_version())) {
return;
}
MockTlsServerHandshaker* crypto_stream =
new MockTlsServerHandshaker(session_.get(), &crypto_config_);
QuicServerSessionBasePeer::SetCryptoStream(session_.get(), crypto_stream);
EXPECT_CALL(*crypto_stream, encryption_established())
.WillRepeatedly(testing::Return(true));
connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
session_->OnConfigNegotiated();
size_t i = 0u;
QuicStreamFrame data(GetNthClientInitiatedBidirectionalId(i), false, 0,
kStreamData);
session_->OnStreamFrame(data);
EXPECT_EQ(1u, session_->GetNumActiveStreams());
++i;
QuicAlarm* alarm = QuicSessionPeer::GetStreamCountResetAlarm(session_.get());
EXPECT_TRUE(alarm->IsSet());
alarm_factory_.FireAlarm(alarm);
QuicStreamId control_stream_id =
GetNthClientInitiatedUnidirectionalStreamId(transport_version(), 3);
QuicStreamFrame data1(control_stream_id, false, 1, "aaaa");
session_->OnStreamFrame(data1);
EXPECT_EQ(1u, session_->pending_streams_size());
for (; i < 10u; ++i) {
QuicStreamFrame more_data(GetNthClientInitiatedBidirectionalId(i), false, 0,
kStreamData);
session_->OnStreamFrame(more_data);
}
EXPECT_EQ(5u, session_->GetNumActiveStreams());
EXPECT_EQ(6u, session_->pending_streams_size());
EXPECT_EQ(
GetNthClientInitiatedBidirectionalId(i - 1),
QuicSessionPeer::GetLargestPeerCreatedStreamId(session_.get(), false));
helper_.GetClock()->AdvanceTime(QuicTime::Delta::FromMicroseconds(100));
EXPECT_TRUE(alarm->IsSet());
alarm_factory_.FireAlarm(alarm);
EXPECT_EQ(9u, session_->GetNumActiveStreams());
EXPECT_EQ(2u, session_->pending_streams_size());
EXPECT_EQ(nullptr, session_->GetActiveStream(control_stream_id));
EXPECT_EQ(nullptr, session_->GetActiveStream(
GetNthClientInitiatedBidirectionalId(i - 1)));
EXPECT_CALL(*connection_, CloseConnection(QUIC_INVALID_STREAM_ID, _, _));
QuicStreamFrame bad_stream(GetNthClientInitiatedBidirectionalId(i), false, 0,
kStreamData);
session_->OnStreamFrame(bad_stream);
}
class StreamMemberLifetimeTest : public QuicServerSessionBaseTest {
public:
StreamMemberLifetimeTest()
: QuicServerSessionBaseTest(
std::unique_ptr<FakeProofSource>(new FakeProofSource())),
crypto_config_peer_(&crypto_config_) {
GetFakeProofSource()->Activate();
}
FakeProofSource* GetFakeProofSource() const {
return static_cast<FakeProofSource*>(crypto_config_peer_.GetProofSource());
}
private:
QuicCryptoServerConfigPeer crypto_config_peer_;
};
INSTANTIATE_TEST_SUITE_P(StreamMemberLifetimeTests, StreamMemberLifetimeTest,
::testing::ValuesIn(AllSupportedVersions()),
::testing::PrintToStringParamName());
TEST_P(StreamMemberLifetimeTest, Basic) {
if (version().handshake_protocol == PROTOCOL_TLS1_3) {
return;
}
const QuicClock* clock = helper_.GetClock();
CryptoHandshakeMessage chlo = crypto_test_utils::GenerateDefaultInchoateCHLO(
clock, transport_version(), &crypto_config_);
chlo.SetVector(kCOPT, QuicTagVector{kREJ});
std::vector<ParsedQuicVersion> packet_version_list = {version()};
std::unique_ptr<QuicEncryptedPacket> packet(ConstructEncryptedPacket(
TestConnectionId(1), EmptyQuicConnectionId(), true, false, 1,
std::string(chlo.GetSerialized().AsStringPiece()), CONNECTION_ID_PRESENT,
CONNECTION_ID_ABSENT, PACKET_4BYTE_PACKET_NUMBER, &packet_version_list));
EXPECT_CALL(stream_helper_, CanAcceptClientHello(_, _, _, _, _))
.WillOnce(testing::Return(true));
QuicConnectionPeer::SetCurrentPacket(session_->connection(),
packet->AsStringPiece());
QuicCryptoServerStreamBase* crypto_stream =
const_cast<QuicCryptoServerStreamBase*>(session_->crypto_stream());
crypto_test_utils::SendHandshakeMessageToStream(crypto_stream, chlo,
Perspective::IS_CLIENT);
ASSERT_EQ(GetFakeProofSource()->NumPendingCallbacks(), 1);
session_.reset();
GetFakeProofSource()->InvokePendingCallback(0);
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/quic_server_session_base.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/quic_server_session_base_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
08aabd66-003a-4e32-bd14-891d13de3ca4 | 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 | #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::OnOriginFrameStart(
QuicByteCount ) {
return ValidateFrameType(HttpFrameType::ORIGIN);
}
bool QuicReceiveControlStream::OnOriginFrame(const OriginFrame& frame) {
QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, spdy_session()->perspective());
if (spdy_session()->debug_visitor()) {
spdy_session()->debug_visitor()->OnOriginFrameReceived(frame);
}
spdy_session()->OnOriginFrame(frame);
return false;
}
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 &&
((GetQuicReloadableFlag(enable_h3_origin_frame) &&
frame_type == HttpFrameType::ORIGIN) ||
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, ReceiveOriginFrame) {
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 origin_frame;
ASSERT_TRUE(
absl::HexStringToBytes("0C"
"00",
&origin_frame));
if (GetQuicReloadableFlag(enable_h3_origin_frame)) {
if (perspective() == Perspective::IS_CLIENT) {
EXPECT_CALL(debug_visitor, OnOriginFrameReceived(_));
} else {
EXPECT_CALL(*connection_,
CloseConnection(
QUIC_HTTP_FRAME_UNEXPECTED_ON_CONTROL_STREAM,
"Invalid frame type 12 received on control stream.", _))
.WillOnce(
Invoke(connection_, &MockQuicConnection::ReallyCloseConnection));
EXPECT_CALL(*connection_, SendConnectionClosePacket(_, _, _));
EXPECT_CALL(session_, OnConnectionClosed(_, _));
}
} else {
EXPECT_CALL(debug_visitor,
OnUnknownFrameReceived(id, 0x0c,
0));
}
receive_control_stream_->OnStreamFrame(
QuicStreamFrame(id, false, offset, origin_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));
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/quic_receive_control_stream.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/quic_receive_control_stream_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
ec3a6617-a451-44bc-8bdd-d99c7dc86203 | cpp | google/quiche | quic_spdy_session | quiche/quic/core/http/quic_spdy_session.cc | quiche/quic/core/http/quic_spdy_session_test.cc | #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/http2/core/http2_frame_decoder_adapter.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 "quiche/quic/platform/api/quic_logging.h"
#include "quiche/quic/platform/api/quic_stack_trace.h"
#include "quiche/common/platform/api/quiche_mem_slice.h"
using http2::Http2DecoderAdapter;
using quiche::HttpHeaderBlock;
using spdy::Http2WeightToSpdy3Priority;
using spdy::Spdy3PriorityToHttp2Weight;
using spdy::SpdyErrorCode;
using spdy::SpdyFramer;
using spdy::SpdyFramerDebugVisitorInterface;
using spdy::SpdyFramerVisitorInterface;
using spdy::SpdyFrameType;
using spdy::SpdyHeadersHandlerInterface;
using spdy::SpdyHeadersIR;
using spdy::SpdyPingId;
using spdy::SpdyPriority;
using spdy::SpdyPriorityIR;
using spdy::SpdySerializedFrame;
using spdy::SpdySettingsId;
using spdy::SpdyStreamId;
namespace quic {
ABSL_CONST_INIT const size_t kMaxUnassociatedWebTransportStreams = 24;
namespace {
constexpr uint64_t kHpackEncoderDynamicTableSizeLimit = 16384;
constexpr QuicStreamCount kDefaultMaxWebTransportSessions = 16;
#define ENDPOINT \
(perspective() == Perspective::IS_SERVER ? "Server: " : "Client: ")
class AlpsFrameDecoder : public HttpDecoder::Visitor {
public:
explicit AlpsFrameDecoder(QuicSpdySession* session) : session_(session) {}
~AlpsFrameDecoder() override = default;
void OnError(HttpDecoder* ) override {}
bool OnMaxPushIdFrame() override {
error_detail_ = "MAX_PUSH_ID frame forbidden";
return false;
}
bool OnGoAwayFrame(const GoAwayFrame& ) override {
error_detail_ = "GOAWAY frame forbidden";
return false;
}
bool OnSettingsFrameStart(QuicByteCount ) override {
return true;
}
bool OnSettingsFrame(const SettingsFrame& frame) override {
if (settings_frame_received_via_alps_) {
error_detail_ = "multiple SETTINGS frames";
return false;
}
settings_frame_received_via_alps_ = true;
error_detail_ = session_->OnSettingsFrameViaAlps(frame);
return !error_detail_;
}
bool OnDataFrameStart(QuicByteCount , QuicByteCount
) override {
error_detail_ = "DATA frame forbidden";
return false;
}
bool OnDataFramePayload(absl::string_view ) override {
QUICHE_NOTREACHED();
return false;
}
bool OnDataFrameEnd() override {
QUICHE_NOTREACHED();
return false;
}
bool OnHeadersFrameStart(QuicByteCount ,
QuicByteCount ) override {
error_detail_ = "HEADERS frame forbidden";
return false;
}
bool OnHeadersFramePayload(absl::string_view ) override {
QUICHE_NOTREACHED();
return false;
}
bool OnHeadersFrameEnd() override {
QUICHE_NOTREACHED();
return false;
}
bool OnPriorityUpdateFrameStart(QuicByteCount ) override {
error_detail_ = "PRIORITY_UPDATE frame forbidden";
return false;
}
bool OnPriorityUpdateFrame(const PriorityUpdateFrame& ) override {
QUICHE_NOTREACHED();
return false;
}
bool OnAcceptChFrameStart(QuicByteCount ) override {
return true;
}
bool OnAcceptChFrame(const AcceptChFrame& frame) override {
session_->OnAcceptChFrameReceivedViaAlps(frame);
return true;
}
bool OnOriginFrameStart(QuicByteCount ) override {
QUICHE_NOTREACHED();
return true;
}
bool OnOriginFrame(const OriginFrame& ) override { return true; }
void OnWebTransportStreamFrameType(
QuicByteCount ,
WebTransportSessionId ) override {
QUICHE_NOTREACHED();
}
bool OnMetadataFrameStart(QuicByteCount ,
QuicByteCount ) override {
error_detail_ = "METADATA frame forbidden";
return false;
}
bool OnMetadataFramePayload(absl::string_view ) override {
QUICHE_NOTREACHED();
return false;
}
bool OnMetadataFrameEnd() override {
QUICHE_NOTREACHED();
return false;
}
bool OnUnknownFrameStart(uint64_t ,
QuicByteCount
,
QuicByteCount ) override {
return true;
}
bool OnUnknownFramePayload(absl::string_view ) override {
return true;
}
bool OnUnknownFrameEnd() override { return true; }
const std::optional<std::string>& error_detail() const {
return error_detail_;
}
private:
QuicSpdySession* const session_;
std::optional<std::string> error_detail_;
bool settings_frame_received_via_alps_ = false;
};
uint64_t GetDefaultQpackMaximumDynamicTableCapacity(Perspective perspective) {
if (perspective == Perspective::IS_SERVER &&
GetQuicFlag(quic_server_disable_qpack_dynamic_table)) {
return 0;
}
return kDefaultQpackMaxDynamicTableCapacity;
}
class SizeLimitingHeaderList : public spdy::SpdyHeadersHandlerInterface {
public:
~SizeLimitingHeaderList() override = default;
void OnHeaderBlockStart() override {
QUIC_BUG_IF(quic_bug_12518_1, current_header_list_size_ != 0)
<< "OnHeaderBlockStart called more than once!";
}
void OnHeader(absl::string_view name, absl::string_view value) override {
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_.OnHeader(name, value);
}
}
void OnHeaderBlockEnd(size_t uncompressed_header_bytes,
size_t compressed_header_bytes) override {
header_list_.OnHeaderBlockEnd(uncompressed_header_bytes,
compressed_header_bytes);
if (current_header_list_size_ > max_header_list_size_) {
Clear();
}
}
void set_max_header_list_size(size_t max_header_list_size) {
max_header_list_size_ = max_header_list_size;
}
void Clear() {
header_list_.Clear();
current_header_list_size_ = 0;
}
const QuicHeaderList& header_list() const { return header_list_; }
private:
QuicHeaderList header_list_;
size_t max_header_list_size_ = std::numeric_limits<size_t>::max();
size_t current_header_list_size_ = 0;
};
}
class QuicSpdySession::SpdyFramerVisitor
: public SpdyFramerVisitorInterface,
public SpdyFramerDebugVisitorInterface {
public:
explicit SpdyFramerVisitor(QuicSpdySession* session) : session_(session) {}
SpdyFramerVisitor(const SpdyFramerVisitor&) = delete;
SpdyFramerVisitor& operator=(const SpdyFramerVisitor&) = delete;
SpdyHeadersHandlerInterface* OnHeaderFrameStart(
SpdyStreamId ) override {
QUICHE_DCHECK(!VersionUsesHttp3(session_->transport_version()));
return &header_list_;
}
void OnHeaderFrameEnd(SpdyStreamId ) override {
QUICHE_DCHECK(!VersionUsesHttp3(session_->transport_version()));
LogHeaderCompressionRatioHistogram(
false,
false,
header_list_.header_list().compressed_header_bytes(),
header_list_.header_list().uncompressed_header_bytes());
if (session_->IsConnected() && !expecting_pushed_headers_) {
session_->OnHeaderList(header_list_.header_list());
}
expecting_pushed_headers_ = false;
header_list_.Clear();
}
void OnStreamFrameData(SpdyStreamId , const char* ,
size_t ) override {
QUICHE_DCHECK(!VersionUsesHttp3(session_->transport_version()));
CloseConnection("SPDY DATA frame received.",
QUIC_INVALID_HEADERS_STREAM_DATA);
}
void OnStreamEnd(SpdyStreamId ) override {
}
void OnStreamPadding(SpdyStreamId , size_t ) override {
CloseConnection("SPDY frame padding received.",
QUIC_INVALID_HEADERS_STREAM_DATA);
}
void OnError(Http2DecoderAdapter::SpdyFramerError error,
std::string detailed_error) override {
QuicErrorCode code;
switch (error) {
case Http2DecoderAdapter::SpdyFramerError::SPDY_HPACK_INDEX_VARINT_ERROR:
code = QUIC_HPACK_INDEX_VARINT_ERROR;
break;
case Http2DecoderAdapter::SpdyFramerError::
SPDY_HPACK_NAME_LENGTH_VARINT_ERROR:
code = QUIC_HPACK_NAME_LENGTH_VARINT_ERROR;
break;
case Http2DecoderAdapter::SpdyFramerError::
SPDY_HPACK_VALUE_LENGTH_VARINT_ERROR:
code = QUIC_HPACK_VALUE_LENGTH_VARINT_ERROR;
break;
case Http2DecoderAdapter::SpdyFramerError::SPDY_HPACK_NAME_TOO_LONG:
code = QUIC_HPACK_NAME_TOO_LONG;
break;
case Http2DecoderAdapter::SpdyFramerError::SPDY_HPACK_VALUE_TOO_LONG:
code = QUIC_HPACK_VALUE_TOO_LONG;
break;
case Http2DecoderAdapter::SpdyFramerError::SPDY_HPACK_NAME_HUFFMAN_ERROR:
code = QUIC_HPACK_NAME_HUFFMAN_ERROR;
break;
case Http2DecoderAdapter::SpdyFramerError::SPDY_HPACK_VALUE_HUFFMAN_ERROR:
code = QUIC_HPACK_VALUE_HUFFMAN_ERROR;
break;
case Http2DecoderAdapter::SpdyFramerError::
SPDY_HPACK_MISSING_DYNAMIC_TABLE_SIZE_UPDATE:
code = QUIC_HPACK_MISSING_DYNAMIC_TABLE_SIZE_UPDATE;
break;
case Http2DecoderAdapter::SpdyFramerError::SPDY_HPACK_INVALID_INDEX:
code = QUIC_HPACK_INVALID_INDEX;
break;
case Http2DecoderAdapter::SpdyFramerError::SPDY_HPACK_INVALID_NAME_INDEX:
code = QUIC_HPACK_INVALID_NAME_INDEX;
break;
case Http2DecoderAdapter::SpdyFramerError::
SPDY_HPACK_DYNAMIC_TABLE_SIZE_UPDATE_NOT_ALLOWED:
code = QUIC_HPACK_DYNAMIC_TABLE_SIZE_UPDATE_NOT_ALLOWED;
break;
case Http2DecoderAdapter::SpdyFramerError::
SPDY_HPACK_INITIAL_DYNAMIC_TABLE_SIZE_UPDATE_IS_ABOVE_LOW_WATER_MARK:
code = QUIC_HPACK_INITIAL_TABLE_SIZE_UPDATE_IS_ABOVE_LOW_WATER_MARK;
break;
case Http2DecoderAdapter::SpdyFramerError::
SPDY_HPACK_DYNAMIC_TABLE_SIZE_UPDATE_IS_ABOVE_ACKNOWLEDGED_SETTING:
code = QUIC_HPACK_TABLE_SIZE_UPDATE_IS_ABOVE_ACKNOWLEDGED_SETTING;
break;
case Http2DecoderAdapter::SpdyFramerError::SPDY_HPACK_TRUNCATED_BLOCK:
code = QUIC_HPACK_TRUNCATED_BLOCK;
break;
case Http2DecoderAdapter::SpdyFramerError::SPDY_HPACK_FRAGMENT_TOO_LONG:
code = QUIC_HPACK_FRAGMENT_TOO_LONG;
break;
case Http2DecoderAdapter::SpdyFramerError::
SPDY_HPACK_COMPRESSED_HEADER_SIZE_EXCEEDS_LIMIT:
code = QUIC_HPACK_COMPRESSED_HEADER_SIZE_EXCEEDS_LIMIT;
break;
case Http2DecoderAdapter::SpdyFramerError::SPDY_DECOMPRESS_FAILURE:
code = QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE;
break;
default:
code = QUIC_INVALID_HEADERS_STREAM_DATA;
}
CloseConnection(
absl::StrCat("SPDY framing error: ", detailed_error,
Http2DecoderAdapter::SpdyFramerErrorToString(error)),
code);
}
void OnDataFrameHeader(SpdyStreamId , size_t ,
bool ) override {
QUICHE_DCHECK(!VersionUsesHttp3(session_->transport_version()));
CloseConnection("SPDY DATA frame received.",
QUIC_INVALID_HEADERS_STREAM_DATA);
}
void OnRstStream(SpdyStreamId ,
SpdyErrorCode ) override {
CloseConnection("SPDY RST_STREAM frame received.",
QUIC_INVALID_HEADERS_STREAM_DATA);
}
void OnSetting(SpdySettingsId id, uint32_t value) override {
QUICHE_DCHECK(!VersionUsesHttp3(session_->transport_version()));
session_->OnSetting(id, value);
}
void OnSettingsEnd() override {
QUICHE_DCHECK(!VersionUsesHttp3(session_->transport_version()));
}
void OnPing(SpdyPingId , bool ) override {
CloseConnection("SPDY PING frame received.",
QUIC_INVALID_HEADERS_STREAM_DATA);
}
void OnGoAway(SpdyStreamId ,
SpdyErrorCode ) override {
CloseConnection("SPDY GOAWAY frame received.",
QUIC_INVALID_HEADERS_STREAM_DATA);
}
void OnHeaders(SpdyStreamId stream_id, size_t ,
bool has_priority, int weight,
SpdyStreamId , bool ,
bool fin, bool ) override {
if (!session_->IsConnected()) {
return;
}
if (VersionUsesHttp3(session_->transport_version())) {
CloseConnection("HEADERS frame not allowed on headers stream.",
QUIC_INVALID_HEADERS_STREAM_DATA);
return;
}
QUIC_BUG_IF(quic_bug_12477_1,
session_->destruction_indicator() != 123456789)
<< "QuicSpdyStream use after free. "
<< session_->destruction_indicator() << QuicStackTrace();
SpdyPriority priority =
has_priority ? Http2WeightToSpdy3Priority(weight) : 0;
session_->OnHeaders(stream_id, has_priority,
spdy::SpdyStreamPrecedence(priority), fin);
}
void OnWindowUpdate(SpdyStreamId ,
int ) override {
CloseConnection("SPDY WINDOW_UPDATE frame received.",
QUIC_INVALID_HEADERS_STREAM_DATA);
}
void OnPushPromise(SpdyStreamId ,
SpdyStreamId promised_stream_id, bool ) override {
QUICHE_DCHECK(!VersionUsesHttp3(session_->transport_version()));
if (session_->perspective() != Perspective::IS_CLIENT) {
CloseConnection("PUSH_PROMISE not supported.",
QUIC_INVALID_HEADERS_STREAM_DATA);
return;
}
session_->MaybeSendRstStreamFrame(
promised_stream_id,
QuicResetStreamError::FromInternal(QUIC_REFUSED_STREAM),
0);
QUICHE_DCHECK(!expecting_pushed_headers_);
expecting_pushed_headers_ = true;
}
void OnContinuation(SpdyStreamId , size_t ,
bool ) override {}
void OnPriority(SpdyStreamId stream_id, SpdyStreamId ,
int weight, bool ) override {
QUICHE_DCHECK(!VersionUsesHttp3(session_->transport_version()));
if (!session_->IsConnected()) {
return;
}
SpdyPriority priority = Http2WeightToSpdy3Priority(weight);
session_->OnPriority(stream_id, spdy::SpdyStreamPrecedence(priority));
}
void OnPriorityUpdate(SpdyStreamId ,
absl::string_view ) override {}
bool OnUnknownFrame(SpdyStreamId ,
uint8_t ) override {
CloseConnection("Unknown frame type received.",
QUIC_INVALID_HEADERS_STREAM_DATA);
return false;
}
void OnUnknownFrameStart(SpdyStreamId , size_t ,
uint8_t , uint8_t ) override {}
void OnUnknownFramePayload(SpdyStreamId ,
absl::string_view ) override {}
void OnSendCompressedFrame(SpdyStreamId , SpdyFrameType ,
size_t payload_len, size_t frame_len) override {
if (payload_len == 0) {
QUIC_BUG(quic_bug_10360_1) << "Zero payload length.";
return;
}
int compression_pct = 100 - (100 * frame_len) / payload_len;
QUIC_DVLOG(1) << "Net.QuicHpackCompressionPercentage: " << compression_pct;
}
void OnReceiveCompressedFrame(SpdyStreamId ,
SpdyFrameType ,
size_t frame_len) override {
if (session_->IsConnected()) {
session_->OnCompressedFrameSize(frame_len);
}
}
void set_max_header_list_size(size_t max_header_list_size) {
header_list_.set_max_header_list_size(max_header_list_size);
}
private:
void CloseConnection(const std::string& details, QuicErrorCode code) {
if (session_->IsConnected()) {
session_->CloseConnectionWithDetails(code, details);
}
}
QuicSpdySession* session_;
SizeLimitingHeaderList header_list_;
bool expecting_pushed_headers_ = false;
};
Http3DebugVisitor::Http3DebugVisitor() {}
Http3DebugVisitor::~Http3DebugVisitor() {}
QuicSpdySession::QuicSpdySession(
QuicConnection* connection, QuicSession::Visitor* visitor,
const QuicConfig& config, const ParsedQuicVersionVector& supported_versions)
: QuicSession(connection, visitor, config, supported_versions,
VersionUsesHttp3(connection->transport_version())
? static_cast<QuicStreamCount>(
kHttp3StaticUnidirectionalStreamCount)
: 0u,
std::make_unique<DatagramObserver>(this)),
send_control_stream_(nullptr),
receive_control_stream_(nullptr),
qpack_encoder_receive_stream_(nullptr),
qpack_decoder_receive_stream_(nullptr),
qpack_encoder_send_stream_(nullptr),
qpack_decoder_send_stream_(nullptr),
qpack_maximum_dynamic_table_capacity_(
GetDefaultQpackMaximumDynamicTableCapacity(perspective())),
qpack_maximum_blocked_streams_(kDefaultMaximumBlockedStreams),
max_inbound_header_list_size_(kDefaultMaxUncompressedHeaderSize),
max_outbound_header_list_size_(std::numeric_limits<size_t>::max()),
stream_id_(
QuicUtils::GetInvalidStreamId(connection->transport_version())),
frame_len_(0),
fin_(false),
spdy_framer_(SpdyFramer::ENABLE_COMPRESSION),
spdy_framer_visitor_(new SpdyFramerVisitor(this)),
debug_visitor_(nullptr),
destruction_indicator_(123456789),
allow_extended_connect_(perspective() == Perspective::IS_SERVER &&
VersionUsesHttp3(transport_version())),
force_buffer_requests_until_settings_(false) {
h2_deframer_.set_visitor(spdy_framer_visitor_.get());
h2_deframer_.set_debug_visitor(spdy_framer_visitor_.get());
spdy_framer_.set_debug_visitor(spdy_framer_visitor_.get());
}
QuicSpdySession::~QuicSpdySession() {
QUIC_BUG_IF(quic_bug_12477_2, destruction_indicator_ != 123456789)
<< "QuicSpdySession use after free. " << destruction_indicator_
<< QuicStackTrace();
destruction_indicator_ = 987654321;
}
void QuicSpdySession::Initialize() {
QuicSession::Initialize();
FillSettingsFrame();
if (!VersionUsesHttp3(transport_version())) {
if (perspective() == Perspective::IS_SERVER) {
set_largest_peer_created_stream_id(
QuicUtils::GetHeadersStreamId(transport_version()));
} else {
QuicStreamId headers_stream_id = GetNextOutgoingBidirectionalStreamId();
QUICHE_DCHECK_EQ(headers_stream_id,
QuicUtils::GetHeadersStreamId(transport_version()));
}
auto headers_stream = std::make_unique<QuicHeadersStream>((this));
QUICHE_DCHECK_EQ(QuicUtils::GetHeadersStreamId(transport_version()),
headers_stream->id());
headers_stream_ = headers_stream.get();
ActivateStream(std::move(headers_stream));
} else {
qpack_encoder_ = std::make_unique<QpackEncoder>(this, huffman_encoding_,
cookie_crumbling_);
qpack_decoder_ =
std::make_unique<QpackDecoder>(qpack_maximum_dynamic_table_capacity_,
qpack_maximum_blocked_streams_, this);
MaybeInitializeHttp3UnidirectionalStreams();
}
spdy_framer_visitor_->set_max_header_list_size(max_inbound_header_list_size_);
h2_deframer_.GetHpackDecoder().set_max_decode_buffer_size_bytes(
2 * max_inbound_header_list_size_);
}
void QuicSpdySession::FillSettingsFrame() {
settings_.values[SETTINGS_QPACK_MAX_TABLE_CAPACITY] =
qpack_maximum_dynamic_table_capacity_;
settings_.values[SETTINGS_QPACK_BLOCKED_STREAMS] =
qpack_maximum_blocked_streams_;
settings_.values[SETTINGS_MAX_FIELD_SECTION_SIZE] =
max_inbound_header_list_size_;
if (version().UsesHttp3()) {
switch (LocalHttpDatagramSupport()) {
case HttpDatagramSupport::kNone:
break;
case HttpDatagramSupport::kDraft04:
settings_.values[SETTINGS_H3_DATAGRAM_DRAFT04] = 1;
break;
case HttpDatagramSupport::kRfc:
settings_.values[SETTINGS_H3_DATAGRAM] = 1;
break;
case HttpDatagramSupport::kRfcAndDraft04:
settings_.values[SETTINGS_H3_DATAGRAM] = 1;
settings_.values[SETTINGS_H3_DATAGRAM_DRAFT04] = 1;
break;
}
}
if (WillNegotiateWebTransport()) {
WebTransportHttp3VersionSet versions =
LocallySupportedWebTransportVersions();
if (versions.IsSet(WebTransportHttp3Version::kDraft02)) {
settings_.values[SETTINGS_WEBTRANS_DRAFT00] = 1;
}
if (versions.IsSet(WebTransportHttp3Version::kDraft07)) {
QUICHE_BUG_IF(
WT_enabled_extended_connect_disabled,
perspective() == Perspective::IS_SERVER && !allow_extended_connect())
<< "WebTransport enabled, but extended CONNECT is not";
settings_.values[SETTINGS_WEBTRANS_MAX_SESSIONS_DRAFT07] =
kDefaultMaxWebTransportSessions;
}
}
if (allow_extended_connect()) {
settings_.values[SETTINGS_ENABLE_CONNECT_PROTOCOL] = 1;
}
}
void QuicSpdySession::OnDecoderStreamError(QuicErrorCode error_code,
absl::string_view error_message) {
QUICHE_DCHECK(VersionUsesHttp3(transport_version()));
CloseConnectionWithDetails(
error_code, absl::StrCat("Decoder stream error: ", error_message));
}
void QuicSpdySession::OnEncoderStreamError(QuicErrorCode error_code,
absl::string_view error_message) {
QUICHE_DCHECK(VersionUsesHttp3(transport_version()));
CloseConnectionWithDetails(
error_code, absl::StrCat("Encoder stream error: ", error_message));
}
void QuicSpdySession::OnStreamHeadersPriority(
QuicStreamId stream_id, const spdy::SpdyStreamPrecedence& precedence) {
QuicSpdyStream* stream = GetOrCreateSpdyDataStream(stream_id);
if (!stream) {
return;
}
stream->OnStreamHeadersPriority(precedence);
}
void QuicSpdySession::OnStreamHeaderList(QuicStreamId stream_id, bool fin,
size_t frame_len,
const QuicHeaderList& header_list) {
if (IsStaticStream(stream_id)) {
connection()->CloseConnection(
QUIC_INVALID_HEADERS_STREAM_DATA, "stream is static",
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
return;
}
QuicSpdyStream* stream = GetOrCreateSpdyDataStream(stream_id);
if (stream == nullptr) {
size_t final_byte_offset = 0;
for (const auto& header : header_list) {
const std::string& header_key = header.first;
const std::string& header_value = header.second;
if (header_key == kFinalOffsetHeaderKey) {
if (!absl::SimpleAtoi(header_value, &final_byte_offset)) {
connection()->CloseConnection(
QUIC_INVALID_HEADERS_STREAM_DATA,
"Trailers are malformed (no final offset)",
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
return;
}
QUIC_DVLOG(1) << ENDPOINT
<< "Received final byte offset in trailers for stream "
<< stream_id << ", which no longer exists.";
OnFinalByteOffsetReceived(stream_id, final_byte_offset);
}
}
return;
}
stream->OnStreamHeaderList(fin, frame_len, header_list);
}
void QuicSpdySession::OnPriorityFrame(
QuicStreamId stream_id, const spdy::SpdyStreamPrecedence& precedence) {
QuicSpdyStream* stream = GetOrCreateSpdyDataStream(stream_id);
if (!stream) {
return;
}
stream->OnPriorityFrame(precedence);
}
bool QuicSpdySession::OnPriorityUpdateForRequestStream(
QuicStreamId stream_id, HttpStreamPriority priority) {
if (perspective() == Perspective::IS_CLIENT ||
!QuicUtils::IsBidirectionalStreamId(stream_id, version()) ||
!QuicUtils::IsClientInitiatedStreamId(transport_version(), stream_id)) {
return true;
}
QuicStreamCount advertised_max_incoming_bidirectional_streams =
GetAdvertisedMaxIncomingBidirectionalStreams();
if (advertised_max_incoming_bidirectional_streams == 0 ||
stream_id > QuicUtils::GetFirstBidirectionalStreamId(
transport_version(), Perspective::IS_CLIENT) +
QuicUtils::StreamIdDelta(transport_version()) *
(advertised_max_incoming_bidirectional_streams - 1)) {
connection()->CloseConnection(
QUIC_INVALID_STREAM_ID,
"PRIORITY_UPDATE frame received for invalid stream.",
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
return false;
}
if (MaybeSetStreamPriority(stream_id, QuicStreamPriority(priority))) {
return true;
}
if (IsClosedStream(stream_id)) {
return true;
}
buffered_stream_priorities_[stream_id] = priority;
if (buffered_stream_priorities_.size() >
10 * max_open_incoming_bidirectional_streams()) {
std::string error_message =
absl::StrCat("Too many stream priority values buffered: ",
buffered_stream_priorities_.size(),
", which should not exceed the incoming stream limit of ",
max_open_incoming_bidirectional_streams());
QUIC_BUG(quic_bug_10360_2) << error_message;
connection()->CloseConnection(
QUIC_INTERNAL_ERROR, error_message,
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
return false;
}
return true;
}
size_t QuicSpdySession::ProcessHeaderData(const struct iovec& iov) {
QUIC_BUG_IF(quic_bug_12477_4, destruction_indicator_ != 123456789)
<< "QuicSpdyStream use after free. " << destruction_indicator_
<< QuicStackTrace();
return h2_deframer_.ProcessInput(static_cast<char*>(iov.iov_base),
iov.iov_len);
}
size_t QuicSpdySession::WriteHeadersOnHeadersStream(
QuicStreamId id, HttpHeaderBlock headers, bool fin,
const spdy::SpdyStreamPrecedence& precedence,
quiche::QuicheReferenceCountedPointer<QuicAckListenerInterface>
ack_listener) {
QUICHE_DCHECK(!VersionUsesHttp3(transport_version()));
return WriteHeadersOnHeadersStreamImpl(
id, std::move(headers), fin,
0,
Spdy3PriorityToHttp2Weight(precedence.spdy3_priority()),
false, std::move(ack_listener));
}
size_t QuicSpdySession::WritePriority(QuicStreamId stream_id,
QuicStreamId parent_stream_id, int weight,
bool exclusive) {
QUICHE_DCHECK(!VersionUsesHttp3(transport_version()));
SpdyPriorityIR priority_frame(stream_id, parent_stream_id, weight, exclusive);
SpdySerializedFrame frame(spdy_framer_.SerializeFrame(priority_frame));
headers_stream()->WriteOrBufferData(
absl::string_view(frame.data(), frame.size()), false, nullptr);
return frame.size();
}
void QuicSpdySession::WriteHttp3PriorityUpdate(QuicStreamId stream_id,
HttpStreamPriority priority) {
QUICHE_DCHECK(VersionUsesHttp3(transport_version()));
send_control_stream_->WritePriorityUpdate(stream_id, priority);
}
void QuicSpdySession::OnHttp3GoAway(uint64_t id) {
QUIC_BUG_IF(quic_bug_12477_5, !version().UsesHttp3())
<< "HTTP/3 GOAWAY received on version " << version();
if (last_received_http3_goaway_id_.has_value() &&
id > *last_received_http3_goaway_id_) {
CloseConnectionWithDetails(
QUIC_HTTP_GOAWAY_ID_LARGER_THAN_PREVIOUS,
absl::StrCat("GOAWAY received with ID ", id,
" greater than previously received ID ",
*last_received_http3_goaway_id_));
return;
}
last_received_http3_goaway_id_ = id;
if (perspective() == Perspective::IS_SERVER) {
return;
}
QuicStreamId stream_id = static_cast<QuicStreamId>(id);
if (!QuicUtils::IsBidirectionalStreamId(stream_id, version()) ||
IsIncomingStream(stream_id)) {
CloseConnectionWithDetails(QUIC_HTTP_GOAWAY_INVALID_STREAM_ID,
"GOAWAY with invalid stream ID");
return;
}
if (SupportsWebTransport()) {
PerformActionOnActiveStreams([](QuicStream* stream) {
if (!QuicUtils::IsBidirectionalStreamId(stream->id(),
stream->version()) ||
!QuicUtils::IsClientInitiatedStreamId(
stream->version().transport_version, stream->id())) {
return true;
}
QuicSpdyStream* spdy_stream = static_cast<QuicSpdyStream*>(stream);
WebTransportHttp3* web_transport = spdy_stream->web_transport();
if (web_transport == nullptr) {
return true;
}
web_transport->OnGoAwayReceived();
return true;
});
}
}
bool QuicSpdySession::OnStreamsBlockedFrame(
const QuicStreamsBlockedFrame& frame) {
if (!QuicSession::OnStreamsBlockedFrame(frame)) {
return false;
}
if (perspective() == Perspective::IS_SERVER &&
frame.stream_count >= QuicUtils::GetMaxStreamCount()) {
QUICHE_DCHECK_EQ(frame.stream_count, QuicUtils::GetMaxStreamCount());
SendHttp3GoAway(QUIC_PEER_GOING_AWAY, "stream count too large");
}
return true;
}
void QuicSpdySession::SendHttp3GoAway(QuicErrorCode error_code,
const std::string& reason) {
QUICHE_DCHECK(VersionUsesHttp3(transport_version()));
if (!IsEncryptionEstablished()) {
QUIC_CODE_COUNT(quic_h3_goaway_before_encryption_established);
connection()->CloseConnection(
error_code, reason,
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
return;
}
ietf_streamid_manager().StopIncreasingIncomingMaxStreams();
QuicStreamId stream_id =
QuicUtils::GetMaxClientInitiatedBidirectionalStreamId(
transport_version());
if (last_sent_http3_goaway_id_.has_value() &&
*last_sent_http3_goaway_id_ <= stream_id) {
return;
}
send_control_stream_->SendGoAway(stream_id);
last_sent_http3_goaway_id_ = stream_id;
}
void QuicSpdySession::SendInitialData() {
if (!VersionUsesHttp3(transport_version())) {
return;
}
QuicConnection::ScopedPacketFlusher flusher(connection());
send_control_stream_->MaybeSendSettingsFrame();
SendInitialDataAfterSettings();
}
bool QuicSpdySession::CheckStreamWriteBlocked(QuicStream* stream) const {
if (qpack_decoder_send_stream_ != nullptr &&
stream->id() == qpack_decoder_send_stream_->id()) {
return true;
}
return QuicSession::CheckStreamWriteBlocked(stream);
}
QpackEncoder* QuicSpdySession::qpack_encoder() {
QUICHE_DCHECK(VersionUsesHttp3(transport_version()));
return qpack_encoder_.get();
}
QpackDecoder* QuicSpdySession::qpack_decoder() {
QUICHE_DCHECK(VersionUsesHttp3(transport_version()));
return qpack_decoder_.get();
}
void QuicSpdySession::OnStreamCreated(QuicSpdyStream* stream) {
auto it = buffered_stream_priorities_.find(stream->id());
if (it == buffered_stream_priorities_.end()) {
return;
}
stream->SetPriority(QuicStreamPriority(it->second));
buffered_stream_priorities_.erase(it);
}
QuicSpdyStream* QuicSpdySession::GetOrCreateSpdyDataStream(
const QuicStreamId stream_id) {
QuicStream* stream = GetOrCreateStream(stream_id);
if (stream && stream->is_static()) {
QUIC_BUG(quic_bug_10360_5)
<< "GetOrCreateSpdyDataStream returns static stream " << stream_id
<< " in version " << transport_version() << "\n"
<< QuicStackTrace();
connection()->CloseConnection(
QUIC_INVALID_STREAM_ID,
absl::StrCat("stream ", stream_id, " is static"),
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
return nullptr;
}
return static_cast<QuicSpdyStream*>(stream);
}
void QuicSpdySession::OnNewEncryptionKeyAvailable(
EncryptionLevel level, std::unique_ptr<QuicEncrypter> encrypter) {
QuicSession::OnNewEncryptionKeyAvailable(level, std::move(encrypter));
if (IsEncryptionEstablished()) {
SendInitialData();
}
}
bool QuicSpdySession::ShouldNegotiateWebTransport() const {
return LocallySupportedWebTransportVersions().Any();
}
WebTransportHttp3VersionSet
QuicSpdySession::LocallySupportedWebTransportVersions() const {
return WebTransportHttp3VersionSet();
}
bool QuicSpdySession::WillNegotiateWebTransport() {
return LocalHttpDatagramSupport() != HttpDatagramSupport::kNone &&
version().UsesHttp3() && ShouldNegotiateWebTransport();
}
bool QuicSpdySession::ShouldKeepConnectionAlive() const {
QUICHE_DCHECK(VersionUsesHttp3(transport_version()) ||
0u == pending_streams_size());
return GetNumActiveStreams() + pending_streams_size() > 0;
}
bool QuicSpdySession::UsesPendingStreamForFrame(QuicFrameType type,
QuicStreamId stream_id) const {
return VersionUsesHttp3(transport_version()) &&
(type == STREAM_FRAME || type == RST_STREAM_FRAME) &&
QuicUtils::GetStreamType(stream_id, perspective(),
IsIncomingStream(stream_id),
version()) == READ_UNIDIRECTIONAL;
}
size_t QuicSpdySession::WriteHeadersOnHeadersStreamImpl(
QuicStreamId id, quiche::HttpHeaderBlock headers, bool fin,
QuicStreamId parent_stream_id, int weight, bool exclusive,
quiche::QuicheReferenceCountedPointer<QuicAckListenerInterface>
ack_listener) {
QUICHE_DCHECK(!VersionUsesHttp3(transport_version()));
const QuicByteCount uncompressed_size = headers.TotalBytesUsed();
SpdyHeadersIR headers_frame(id, std::move(headers));
headers_frame.set_fin(fin);
if (perspective() == Perspective::IS_CLIENT) {
headers_frame.set_has_priority(true);
headers_frame.set_parent_stream_id(parent_stream_id);
headers_frame.set_weight(weight);
headers_frame.set_exclusive(exclusive);
}
SpdySerializedFrame frame(spdy_framer_.SerializeFrame(headers_frame));
headers_stream()->WriteOrBufferData(
absl::string_view(frame.data(), frame.size()), false,
std::move(ack_listener));
QuicByteCount compressed_size = frame.size();
compressed_size -= spdy::kFrameHeaderSize;
if (perspective() == Perspective::IS_CLIENT) {
compressed_size -= 5;
}
LogHeaderCompressionRatioHistogram(
false,
true, compressed_size, uncompressed_size);
return frame.size();
}
bool QuicSpdySession::ResumeApplicationState(ApplicationState* cached_state) {
QUICHE_DCHECK_EQ(perspective(), Perspective::IS_CLIENT);
QUICHE_DCHECK(VersionUsesHttp3(transport_version()));
SettingsFrame out;
if (!HttpDecoder::DecodeSettings(
reinterpret_cast<char*>(cached_state->data()), cached_state->size(),
&out)) {
return false;
}
if (debug_visitor_ != nullptr) {
debug_visitor_->OnSettingsFrameResumed(out);
}
QUICHE_DCHECK(streams_waiting_for_settings_.empty());
for (const auto& setting : out.values) {
OnSetting(setting.first, setting.second);
}
return true;
}
std::optional<std::string> QuicSpdySession::OnAlpsData(const uint8_t* alps_data,
size_t alps_length) {
AlpsFrameDecoder alps_frame_decoder(this);
HttpDecoder decoder(&alps_frame_decoder);
decoder.ProcessInput(reinterpret_cast<const char*>(alps_data), alps_length);
if (alps_frame_decoder.error_detail()) {
return alps_frame_decoder.error_detail();
}
if (decoder.error() != QUIC_NO_ERROR) {
return decoder.error_detail();
}
if (!decoder.AtFrameBoundary()) {
return "incomplete HTTP/3 frame";
}
return std::nullopt;
}
void QuicSpdySession::OnAcceptChFrameReceivedViaAlps(
const AcceptChFrame& frame) {
if (debug_visitor_) {
debug_visitor_->OnAcceptChFrameReceivedViaAlps(frame);
}
}
bool QuicSpdySession::OnSettingsFrame(const SettingsFrame& frame) {
QUICHE_DCHECK(VersionUsesHttp3(transport_version()));
if (debug_visitor_ != nullptr) {
debug_visitor_->OnSettingsFrameReceived(frame);
}
for (const auto& setting : frame.values) {
if (!OnSetting(setting.first, setting.second)) {
return false;
}
}
if (!ValidateWebTransportSettingsConsistency()) {
return false;
}
QUICHE_DCHECK(!settings_received_);
settings_received_ = true;
for (QuicStreamId stream_id : streams_waiting_for_settings_) {
QUICHE_RELOADABLE_FLAG_COUNT_N(quic_block_until_settings_received_copt, 4,
4);
QUICHE_DCHECK(ShouldBufferRequestsUntilSettings());
QuicSpdyStream* stream = GetOrCreateSpdyDataStream(stream_id);
if (stream == nullptr) {
continue;
}
stream->OnDataAvailable();
}
streams_waiting_for_settings_.clear();
return true;
}
bool QuicSpdySession::ValidateWebTransportSettingsConsistency() {
std::optional<WebTransportHttp3Version> version =
NegotiatedWebTransportVersion();
if (!version.has_value() || *version == WebTransportHttp3Version::kDraft02) {
return true;
}
if (!allow_extended_connect_) {
CloseConnectionWithDetails(
QUIC_HTTP_INVALID_SETTING_VALUE,
"Negotiated use of WebTransport over HTTP/3 (draft-07 or later), but "
"failed to negotiate extended CONNECT");
return false;
}
if (http_datagram_support_ == HttpDatagramSupport::kDraft04) {
CloseConnectionWithDetails(
QUIC_HTTP_INVALID_SETTING_VALUE,
"WebTransport over HTTP/3 version draft-07 and beyond requires the "
"RFC version of HTTP datagrams");
return false;
}
if (http_datagram_support_ != HttpDatagramSupport::kRfc) {
CloseConnectionWithDetails(
QUIC_HTTP_INVALID_SETTING_VALUE,
"WebTransport over HTTP/3 requires HTTP datagrams support");
return false;
}
return true;
}
std::optional<std::string> QuicSpdySession::OnSettingsFrameViaAlps(
const SettingsFrame& frame) {
QUICHE_DCHECK(VersionUsesHttp3(transport_version()));
if (debug_visitor_ != nullptr) {
debug_visitor_->OnSettingsFrameReceivedViaAlps(frame);
}
for (const auto& setting : frame.values) {
if (!OnSetting(setting.first, setting.second)) {
return "error parsing setting";
}
}
return std::nullopt;
}
bool QuicSpdySession::VerifySettingIsZeroOrOne(uint64_t id, uint64_t value) {
if (value == 0 || value == 1) {
return true;
}
std::string error_details = absl::StrCat(
"Received ",
H3SettingsToString(static_cast<Http3AndQpackSettingsIdentifiers>(id)),
" with invalid value ", value);
QUIC_PEER_BUG(bad received setting) << ENDPOINT << error_details;
CloseConnectionWithDetails(QUIC_HTTP_INVALID_SETTING_VALUE, error_details);
return false;
}
bool QuicSpdySession::OnSetting(uint64_t id, uint64_t value) {
if (VersionUsesHttp3(transport_version())) {
switch (id) {
case SETTINGS_QPACK_MAX_TABLE_CAPACITY: {
QUIC_DVLOG(1)
<< ENDPOINT
<< "SETTINGS_QPACK_MAX_TABLE_CAPACITY received with value "
<< value;
if (!qpack_encoder_->SetMaximumDynamicTableCapacity(value)) {
CloseConnectionWithDetails(
was_zero_rtt_rejected()
? QUIC_HTTP_ZERO_RTT_REJECTION_SETTINGS_MISMATCH
: QUIC_HTTP_ZERO_RTT_RESUMPTION_SETTINGS_MISMATCH,
absl::StrCat(was_zero_rtt_rejected()
? "Server rejected 0-RTT, aborting because "
: "",
"Server sent an SETTINGS_QPACK_MAX_TABLE_CAPACITY: ",
value, " while current value is: ",
qpack_encoder_->MaximumDynamicTableCapacity()));
return false;
}
qpack_encoder_->SetDynamicTableCapacity(
std::min(value, qpack_maximum_dynamic_table_capacity_));
break;
}
case SETTINGS_MAX_FIELD_SECTION_SIZE:
QUIC_DVLOG(1) << ENDPOINT
<< "SETTINGS_MAX_FIELD_SECTION_SIZE received with value "
<< value;
if (max_outbound_header_list_size_ !=
std::numeric_limits<size_t>::max() &&
max_outbound_header_list_size_ > value) {
CloseConnectionWithDetails(
was_zero_rtt_rejected()
? QUIC_HTTP_ZERO_RTT_REJECTION_SETTINGS_MISMATCH
: QUIC_HTTP_ZERO_RTT_RESUMPTION_SETTINGS_MISMATCH,
absl::StrCat(was_zero_rtt_rejected()
? "Server rejected 0-RTT, aborting because "
: "",
"Server sent an SETTINGS_MAX_FIELD_SECTION_SIZE: ",
value, " which reduces current value: ",
max_outbound_header_list_size_));
return false;
}
max_outbound_header_list_size_ = value;
break;
case SETTINGS_QPACK_BLOCKED_STREAMS: {
QUIC_DVLOG(1) << ENDPOINT
<< "SETTINGS_QPACK_BLOCKED_STREAMS received with value "
<< value;
if (!qpack_encoder_->SetMaximumBlockedStreams(value)) {
CloseConnectionWithDetails(
was_zero_rtt_rejected()
? QUIC_HTTP_ZERO_RTT_REJECTION_SETTINGS_MISMATCH
: QUIC_HTTP_ZERO_RTT_RESUMPTION_SETTINGS_MISMATCH,
absl::StrCat(was_zero_rtt_rejected()
? "Server rejected 0-RTT, aborting because "
: "",
"Server sent an SETTINGS_QPACK_BLOCKED_STREAMS: ",
value, " which reduces current value: ",
qpack_encoder_->maximum_blocked_streams()));
return false;
}
break;
}
case SETTINGS_ENABLE_CONNECT_PROTOCOL: {
QUIC_DVLOG(1) << ENDPOINT
<< "SETTINGS_ENABLE_CONNECT_PROTOCOL received with value "
<< value;
if (!VerifySettingIsZeroOrOne(id, value)) {
return false;
}
if (perspective() == Perspective::IS_CLIENT) {
allow_extended_connect_ = value != 0;
}
break;
}
case spdy::SETTINGS_ENABLE_PUSH:
ABSL_FALLTHROUGH_INTENDED;
case spdy::SETTINGS_MAX_CONCURRENT_STREAMS:
ABSL_FALLTHROUGH_INTENDED;
case spdy::SETTINGS_INITIAL_WINDOW_SIZE:
ABSL_FALLTHROUGH_INTENDED;
case spdy::SETTINGS_MAX_FRAME_SIZE:
CloseConnectionWithDetails(
QUIC_HTTP_RECEIVE_SPDY_SETTING,
absl::StrCat("received HTTP/2 specific setting in HTTP/3 session: ",
id));
return false;
case SETTINGS_H3_DATAGRAM_DRAFT04: {
HttpDatagramSupport local_http_datagram_support =
LocalHttpDatagramSupport();
if (local_http_datagram_support != HttpDatagramSupport::kDraft04 &&
local_http_datagram_support !=
HttpDatagramSupport::kRfcAndDraft04) {
break;
}
QUIC_DVLOG(1) << ENDPOINT
<< "SETTINGS_H3_DATAGRAM_DRAFT04 received with value "
<< value;
if (!version().UsesHttp3()) {
break;
}
if (!VerifySettingIsZeroOrOne(id, value)) {
return false;
}
if (value && http_datagram_support_ != HttpDatagramSupport::kRfc) {
http_datagram_support_ = HttpDatagramSupport::kDraft04;
}
break;
}
case SETTINGS_H3_DATAGRAM: {
HttpDatagramSupport local_http_datagram_support =
LocalHttpDatagramSupport();
if (local_http_datagram_support != HttpDatagramSupport::kRfc &&
local_http_datagram_support !=
HttpDatagramSupport::kRfcAndDraft04) {
break;
}
QUIC_DVLOG(1) << ENDPOINT << "SETTINGS_H3_DATAGRAM received with value "
<< value;
if (!version().UsesHttp3()) {
break;
}
if (!VerifySettingIsZeroOrOne(id, value)) {
return false;
}
if (value) {
http_datagram_support_ = HttpDatagramSupport::kRfc;
}
break;
}
case SETTINGS_WEBTRANS_DRAFT00:
if (!WillNegotiateWebTransport()) {
break;
}
QUIC_DVLOG(1) << ENDPOINT
<< "SETTINGS_ENABLE_WEBTRANSPORT(02) received with value "
<< value;
if (!VerifySettingIsZeroOrOne(id, value)) {
return false;
}
if (value == 1) {
peer_web_transport_versions_.Set(WebTransportHttp3Version::kDraft02);
if (perspective() == Perspective::IS_CLIENT) {
allow_extended_connect_ = true;
}
}
break;
case SETTINGS_WEBTRANS_MAX_SESSIONS_DRAFT07:
if (!WillNegotiateWebTransport()) {
break;
}
QUIC_DVLOG(1)
<< ENDPOINT
<< "SETTINGS_WEBTRANS_MAX_SESSIONS_DRAFT07 received with value "
<< value;
if (value > 0) {
peer_web_transport_versions_.Set(WebTransportHttp3Version::kDraft07);
if (perspective() == Perspective::IS_CLIENT) {
max_webtransport_sessions_[WebTransportHttp3Version::kDraft07] =
value;
}
}
break;
default:
QUIC_DVLOG(1) << ENDPOINT << "Unknown setting identifier " << id
<< " received with value " << value;
break;
}
return true;
}
switch (id) {
case spdy::SETTINGS_HEADER_TABLE_SIZE:
QUIC_DVLOG(1) << ENDPOINT
<< "SETTINGS_HEADER_TABLE_SIZE received with value "
<< value;
spdy_framer_.UpdateHeaderEncoderTableSize(
std::min<uint64_t>(value, kHpackEncoderDynamicTableSizeLimit));
break;
case spdy::SETTINGS_ENABLE_PUSH:
if (perspective() == Perspective::IS_SERVER) {
if (value > 1) {
QUIC_DLOG(ERROR) << ENDPOINT << "Invalid value " << value
<< " received for SETTINGS_ENABLE_PUSH.";
if (IsConnected()) {
CloseConnectionWithDetails(
QUIC_INVALID_HEADERS_STREAM_DATA,
absl::StrCat("Invalid value for SETTINGS_ENABLE_PUSH: ",
value));
}
return true;
}
QUIC_DVLOG(1) << ENDPOINT << "SETTINGS_ENABLE_PUSH received with value "
<< value << ", ignoring.";
break;
} else {
QUIC_DLOG(ERROR)
<< ENDPOINT
<< "Invalid SETTINGS_ENABLE_PUSH received by client with value "
<< value;
if (IsConnected()) {
CloseConnectionWithDetails(
QUIC_INVALID_HEADERS_STREAM_DATA,
absl::StrCat("Unsupported field of HTTP/2 SETTINGS frame: ", id));
}
}
break;
case spdy::SETTINGS_MAX_HEADER_LIST_SIZE:
QUIC_DVLOG(1) << ENDPOINT
<< "SETTINGS_MAX_HEADER_LIST_SIZE received with value "
<< value;
max_outbound_header_list_size_ = value;
break;
default:
QUIC_DLOG(ERROR) << ENDPOINT << "Unknown setting identifier " << id
<< " received with value " << value;
if (IsConnected()) {
CloseConnectionWithDetails(
QUIC_INVALID_HEADERS_STREAM_DATA,
absl::StrCat("Unsupported field of HTTP/2 SETTINGS frame: ", id));
}
}
return true;
}
bool QuicSpdySession::ShouldReleaseHeadersStreamSequencerBuffer() {
return false;
}
void QuicSpdySession::OnHeaders(SpdyStreamId stream_id, bool has_priority,
const spdy::SpdyStreamPrecedence& precedence,
bool fin) {
if (has_priority) {
if (perspective() == Perspective::IS_CLIENT) {
CloseConnectionWithDetails(QUIC_INVALID_HEADERS_STREAM_DATA,
"Server must not send priorities.");
return;
}
OnStreamHeadersPriority(stream_id, precedence);
} else {
if (perspective() == Perspective::IS_SERVER) {
CloseConnectionWithDetails(QUIC_INVALID_HEADERS_STREAM_DATA,
"Client must send priorities.");
return;
}
}
QUICHE_DCHECK_EQ(QuicUtils::GetInvalidStreamId(transport_version()),
stream_id_);
stream_id_ = stream_id;
fin_ = fin;
}
void QuicSpdySession::OnPriority(SpdyStreamId stream_id,
const spdy::SpdyStreamPrecedence& precedence) {
if (perspective() == Perspective::IS_CLIENT) {
CloseConnectionWithDetails(QUIC_INVALID_HEADERS_STREAM_DATA,
"Server must not send PRIORITY frames.");
return;
}
OnPriorityFrame(stream_id, precedence);
}
void QuicSpdySession::OnHeaderList(const QuicHeaderList& header_list) {
QUIC_DVLOG(1) << ENDPOINT << "Received header list for stream " << stream_id_
<< ": " << header_list.DebugString();
QUICHE_DCHECK(!VersionUsesHttp3(transport_version()));
OnStreamHeaderList(stream_id_, fin_, frame_len_, header_list);
stream_id_ = QuicUtils::GetInvalidStreamId(transport_version());
fin_ = false;
frame_len_ = 0;
}
void QuicSpdySession::OnCompressedFrameSize(size_t frame_len) {
frame_len_ += frame_len;
}
void QuicSpdySession::CloseConnectionWithDetails(QuicErrorCode error,
const std::string& details) {
connection()->CloseConnection(
error, details, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
}
bool QuicSpdySession::HasActiveRequestStreams() const {
return GetNumActiveStreams() + num_draining_streams() > 0;
}
QuicStream* QuicSpdySession::ProcessReadUnidirectionalPendingStream(
PendingStream* pending) {
struct iovec iov;
if (!pending->sequencer()->GetReadableRegion(&iov)) {
return nullptr;
}
QuicDataReader reader(static_cast<char*>(iov.iov_base), iov.iov_len);
uint8_t stream_type_length = reader.PeekVarInt62Length();
uint64_t stream_type = 0;
if (!reader.ReadVarInt62(&stream_type)) {
if (pending->sequencer()->NumBytesBuffered() ==
pending->sequencer()->close_offset()) {
pending->MarkConsumed(pending->sequencer()->close_offset());
}
return nullptr;
}
pending->MarkConsumed(stream_type_length);
switch (stream_type) {
case kControlStream: {
if (receive_control_stream_) {
CloseConnectionOnDuplicateHttp3UnidirectionalStreams("Control");
return nullptr;
}
auto receive_stream =
std::make_unique<QuicReceiveControlStream>(pending, this);
receive_control_stream_ = receive_stream.get();
ActivateStream(std::move(receive_stream));
QUIC_DVLOG(1) << ENDPOINT << "Receive Control stream is created";
if (debug_visitor_ != nullptr) {
debug_visitor_->OnPeerControlStreamCreated(
receive_control_stream_->id());
}
return receive_control_stream_;
}
case kServerPushStream: {
CloseConnectionWithDetails(QUIC_HTTP_RECEIVE_SERVER_PUSH,
"Received server push stream");
return nullptr;
}
case kQpackEncoderStream: {
if (qpack_encoder_receive_stream_) {
CloseConnectionOnDuplicateHttp3UnidirectionalStreams("QPACK encoder");
return nullptr;
}
auto encoder_receive = std::make_unique<QpackReceiveStream>(
pending, this, qpack_decoder_->encoder_stream_receiver());
qpack_encoder_receive_stream_ = encoder_receive.get();
ActivateStream(std::move(encoder_receive));
QUIC_DVLOG(1) << ENDPOINT << "Receive QPACK Encoder stream is created";
if (debug_visitor_ != nullptr) {
debug_visitor_->OnPeerQpackEncoderStreamCreated(
qpack_encoder_receive_stream_->id());
}
return qpack_encoder_receive_stream_;
}
case kQpackDecoderStream: {
if (qpack_decoder_receive_stream_) {
CloseConnectionOnDuplicateHttp3UnidirectionalStreams("QPACK decoder");
return nullptr;
}
auto decoder_receive = std::make_unique<QpackReceiveStream>(
pending, this, qpack_encoder_->decoder_stream_receiver());
qpack_decoder_receive_stream_ = decoder_receive.get();
ActivateStream(std::move(decoder_receive));
QUIC_DVLOG(1) << ENDPOINT << "Receive QPACK Decoder stream is created";
if (debug_visitor_ != nullptr) {
debug_visitor_->OnPeerQpackDecoderStreamCreated(
qpack_decoder_receive_stream_->id());
}
return qpack_decoder_receive_stream_;
}
case kWebTransportUnidirectionalStream: {
if (!WillNegotiateWebTransport()) {
break;
}
QUIC_DVLOG(1) << ENDPOINT << "Created an incoming WebTransport stream "
<< pending->id();
auto stream_owned =
std::make_unique<WebTransportHttp3UnidirectionalStream>(pending,
this);
WebTransportHttp3UnidirectionalStream* stream = stream_owned.get();
ActivateStream(std::move(stream_owned));
return stream;
}
default:
break;
}
MaybeSendStopSendingFrame(
pending->id(),
QuicResetStreamError::FromInternal(QUIC_STREAM_STREAM_CREATION_ERROR));
pending->StopReading();
return nullptr;
}
void QuicSpdySession::MaybeInitializeHttp3UnidirectionalStreams() {
QUICHE_DCHECK(VersionUsesHttp3(transport_version()));
if (!send_control_stream_ && CanOpenNextOutgoingUnidirectionalStream()) {
auto send_control = std::make_unique<QuicSendControlStream>(
GetNextOutgoingUnidirectionalStreamId(), this, settings_);
send_control_stream_ = send_control.get();
ActivateStream(std::move(send_control));
if (debug_visitor_) {
debug_visitor_->OnControlStreamCreated(send_control_stream_->id());
}
}
if (!qpack_decoder_send_stream_ &&
CanOpenNextOutgoingUnidirectionalStream()) {
auto decoder_send = std::make_unique<QpackSendStream>(
GetNextOutgoingUnidirectionalStreamId(), this, kQpackDecoderStream);
qpack_decoder_send_stream_ = decoder_send.get();
ActivateStream(std::move(decoder_send));
qpack_decoder_->set_qpack_stream_sender_delegate(
qpack_decoder_send_stream_);
if (debug_visitor_) {
debug_visitor_->OnQpackDecoderStreamCreated(
qpack_decoder_send_stream_->id());
}
}
if (!qpack_encoder_send_stream_ &&
CanOpenNextOutgoingUnidirectionalStream()) {
auto encoder_send = std::make_unique<QpackSendStream>(
GetNextOutgoingUnidirectionalStreamId(), this, kQpackEncoderStream);
qpack_encoder_send_stream_ = encoder_send.get();
ActivateStream(std::move(encoder_send));
qpack_encoder_->set_qpack_stream_sender_delegate(
qpack_encoder_send_stream_);
if (debug_visitor_) {
debug_visitor_->OnQpackEncoderStreamCreated(
qpack_encoder_send_stream_->id());
}
}
}
void QuicSpdySession::BeforeConnectionCloseSent() {
if (!VersionUsesHttp3(transport_version()) || !IsEncryptionEstablished()) {
return;
}
QUICHE_DCHECK_EQ(perspective(), Perspective::IS_SERVER);
QuicStreamId stream_id =
GetLargestPeerCreatedStreamId( false);
if (stream_id == QuicUtils::GetInvalidStreamId(transport_version())) {
stream_id = 0;
} else {
stream_id += QuicUtils::StreamIdDelta(transport_version());
}
if (last_sent_http3_goaway_id_.has_value() &&
*last_sent_http3_goaway_id_ <= stream_id) {
return;
}
send_control_stream_->SendGoAway(stream_id);
last_sent_http3_goaway_id_ = stream_id;
}
void QuicSpdySession::MaybeBundleOpportunistically() {
if (qpack_decoder_ != nullptr) {
qpack_decoder_->FlushDecoderStream();
}
}
void QuicSpdySession::OnCanCreateNewOutgoingStream(bool unidirectional) {
if (unidirectional && VersionUsesHttp3(transport_version())) {
MaybeInitializeHttp3UnidirectionalStreams();
}
}
bool QuicSpdySession::goaway_received() const {
return VersionUsesHttp3(transport_version())
? last_received_http3_goaway_id_.has_value()
: transport_goaway_received();
}
bool QuicSpdySession::goaway_sent() const {
return VersionUsesHttp3(transport_version())
? last_sent_http3_goaway_id_.has_value()
: transport_goaway_sent();
}
void QuicSpdySession::CloseConnectionOnDuplicateHttp3UnidirectionalStreams(
absl::string_view type) {
QUIC_PEER_BUG(quic_peer_bug_10360_9) << absl::StrCat(
"Received a duplicate ", type, " stream: Closing connection.");
CloseConnectionWithDetails(QUIC_HTTP_DUPLICATE_UNIDIRECTIONAL_STREAM,
absl::StrCat(type, " stream is received twice."));
}
void QuicSpdySession::LogHeaderCompressionRatioHistogram(
bool using_qpack, bool is_sent, QuicByteCount compressed,
QuicByteCount uncompressed) {
if (compressed <= 0 || uncompressed <= 0) {
return;
}
int ratio = 100 * (compressed) / (uncompressed);
if (ratio < 1) {
ratio = 1;
} else if (ratio > 200) {
ratio = 200;
}
if (using_qpack) {
if (is_sent) {
QUIC_HISTOGRAM_COUNTS("QuicSession.HeaderCompressionRatioQpackSent",
ratio, 1, 200, 200,
"Header compression ratio as percentage for sent "
"headers using QPACK.");
} else {
QUIC_HISTOGRAM_COUNTS("QuicSession.HeaderCompressionRatioQpackReceived",
ratio, 1, 200, 200,
"Header compression ratio as percentage for "
"received headers using QPACK.");
}
} else {
if (is_sent) {
QUIC_HISTOGRAM_COUNTS("QuicSession.HeaderCompressionRatioHpackSent",
ratio, 1, 200, 200,
"Header compression ratio as percentage for sent "
"headers using HPACK.");
} else {
QUIC_HISTOGRAM_COUNTS("QuicSession.HeaderCompressionRatioHpackReceived",
ratio, 1, 200, 200,
"Header compression ratio as percentage for "
"received headers using HPACK.");
}
}
}
MessageStatus QuicSpdySession::SendHttp3Datagram(QuicStreamId stream_id,
absl::string_view payload) {
if (!SupportsH3Datagram()) {
if (LocalHttpDatagramSupport() == HttpDatagramSupport::kNone) {
QUIC_BUG(http datagram disabled locally)
<< "Cannot send HTTP Datagram when disabled locally";
return MESSAGE_STATUS_UNSUPPORTED;
} else if (!settings_received_) {
QUIC_DLOG(INFO)
<< "Refusing to send HTTP Datagram before SETTINGS received";
return MESSAGE_STATUS_SETTINGS_NOT_RECEIVED;
} else {
QUIC_DLOG(INFO) << "Refusing to send HTTP Datagram without peer support";
return MESSAGE_STATUS_UNSUPPORTED;
}
}
uint64_t stream_id_to_write = stream_id / kHttpDatagramStreamIdDivisor;
size_t slice_length =
QuicDataWriter::GetVarInt62Len(stream_id_to_write) + payload.length();
quiche::QuicheBuffer buffer(
connection()->helper()->GetStreamSendBufferAllocator(), slice_length);
QuicDataWriter writer(slice_length, buffer.data());
if (!writer.WriteVarInt62(stream_id_to_write)) {
QUIC_BUG(h3 datagram stream ID write fail)
<< "Failed to write HTTP/3 datagram stream ID";
return MESSAGE_STATUS_INTERNAL_ERROR;
}
if (!writer.WriteBytes(payload.data(), payload.length())) {
QUIC_BUG(h3 datagram payload write fail)
<< "Failed to write HTTP/3 datagram payload";
return MESSAGE_STATUS_INTERNAL_ERROR;
}
quiche::QuicheMemSlice slice(std::move(buffer));
return datagram_queue()->SendOrQueueDatagram(std::move(slice));
}
void QuicSpdySession::SetMaxDatagramTimeInQueueForStreamId(
QuicStreamId , QuicTime::Delta max_time_in_queue) {
datagram_queue()->SetMaxTimeInQueue(max_time_in_queue);
}
void QuicSpdySession::OnMessageReceived(absl::string_view message) {
QuicSession::OnMessageReceived(message);
if (!SupportsH3Datagram()) {
QUIC_DLOG(INFO) << "Ignoring unexpected received HTTP/3 datagram";
return;
}
QuicDataReader reader(message);
uint64_t stream_id64;
if (!reader.ReadVarInt62(&stream_id64)) {
QUIC_DLOG(ERROR) << "Failed to parse stream ID in received HTTP/3 datagram";
return;
}
if (stream_id64 >
std::numeric_limits<QuicStreamId>::max() / kHttpDatagramStreamIdDivisor) {
CloseConnectionWithDetails(
QUIC_HTTP_FRAME_ERROR,
absl::StrCat("Received HTTP Datagram with invalid quarter stream ID ",
stream_id64));
return;
}
stream_id64 *= kHttpDatagramStreamIdDivisor;
QuicStreamId stream_id = static_cast<QuicStreamId>(stream_id64);
QuicSpdyStream* stream =
static_cast<QuicSpdyStream*>(GetActiveStream(stream_id));
if (stream == nullptr) {
QUIC_DLOG(INFO) << "Received HTTP/3 datagram for unknown stream ID "
<< stream_id;
return;
}
stream->OnDatagramReceived(&reader);
}
bool QuicSpdySession::SupportsWebTransport() {
return WillNegotiateWebTransport() && SupportsH3Datagram() &&
NegotiatedWebTransportVersion().has_value() && allow_extended_connect_;
}
std::optional<WebTransportHttp3Version>
QuicSpdySession::SupportedWebTransportVersion() {
if (!SupportsWebTransport()) {
return std::nullopt;
}
return NegotiatedWebTransportVersion();
}
bool QuicSpdySession::SupportsH3Datagram() const {
return http_datagram_support_ != HttpDatagramSupport::kNone;
}
WebTransportHttp3* QuicSpdySession::GetWebTransportSession(
WebTransportSessionId id) {
if (!SupportsWebTransport()) {
return nullptr;
}
if (!IsValidWebTransportSessionId(id, version())) {
return nullptr;
}
QuicSpdyStream* connect_stream = GetOrCreateSpdyDataStream(id);
if (connect_stream == nullptr) {
return nullptr;
}
return connect_stream->web_transport();
}
bool QuicSpdySession::ShouldProcessIncomingRequests() {
if (!ShouldBufferRequestsUntilSettings()) {
return true;
}
QUICHE_RELOADABLE_FLAG_COUNT_N(quic_block_until_settings_received_copt, 2, 4);
return settings_received_;
}
void QuicSpdySession::OnStreamWaitingForClientSettings(QuicStreamId id) {
QUICHE_DCHECK(ShouldBufferRequestsUntilSettings());
QUICHE_DCHECK(QuicUtils::IsBidirectionalStreamId(id, version()));
QUICHE_RELOADABLE_FLAG_COUNT_N(quic_block_until_settings_received_copt, 3, 4);
streams_waiting_for_settings_.insert(id);
}
void QuicSpdySession::AssociateIncomingWebTransportStreamWithSession(
WebTransportSessionId session_id, QuicStreamId stream_id) {
if (QuicUtils::IsOutgoingStreamId(version(), stream_id, perspective())) {
QUIC_BUG(AssociateIncomingWebTransportStreamWithSession got outgoing stream)
<< ENDPOINT
<< "AssociateIncomingWebTransportStreamWithSession() got an outgoing "
"stream ID: "
<< stream_id;
return;
}
WebTransportHttp3* session = GetWebTransportSession(session_id);
if (session != nullptr) {
QUIC_DVLOG(1) << ENDPOINT
<< "Successfully associated incoming WebTransport stream "
<< stream_id << " with session ID " << session_id;
session->AssociateStream(stream_id);
return;
}
while (buffered_streams_.size() >= kMaxUnassociatedWebTransportStreams) {
QUIC_DVLOG(1) << ENDPOINT << "Removing stream "
<< buffered_streams_.front().stream_id
<< " from buffered streams as the queue is full.";
ResetStream(buffered_streams_.front().stream_id,
QUIC_STREAM_WEBTRANSPORT_BUFFERED_STREAMS_LIMIT_EXCEEDED);
buffered_streams_.pop_front();
}
QUIC_DVLOG(1) << ENDPOINT << "Received a WebTransport stream " << stream_id
<< " for session ID " << session_id
<< " but cannot associate it; buffering instead.";
buffered_streams_.push_back(
BufferedWebTransportStream{session_id, stream_id});
}
void QuicSpdySession::ProcessBufferedWebTransportStreamsForSession(
WebTransportHttp3* session) {
const WebTransportSessionId session_id = session->id();
QUIC_DVLOG(1) << "Processing buffered WebTransport streams for "
<< session_id;
auto it = buffered_streams_.begin();
while (it != buffered_streams_.end()) {
if (it->session_id == session_id) {
QUIC_DVLOG(1) << "Unbuffered and associated WebTransport stream "
<< it->stream_id << " with session " << it->session_id;
session->AssociateStream(it->stream_id);
it = buffered_streams_.erase(it);
} else {
it++;
}
}
}
WebTransportHttp3UnidirectionalStream*
QuicSpdySession::CreateOutgoingUnidirectionalWebTransportStream(
WebTransportHttp3* session) {
if (!CanOpenNextOutgoingUnidirectionalStream()) {
return nullptr;
}
QuicStreamId stream_id = GetNextOutgoingUnidirectionalStreamId();
auto stream_owned = std::make_unique<WebTransportHttp3UnidirectionalStream>(
stream_id, this, session->id());
WebTransportHttp3UnidirectionalStream* stream = stream_owned.get();
ActivateStream(std::move(stream_owned));
stream->WritePreamble();
session->AssociateStream(stream_id);
return stream;
}
QuicSpdyStream* QuicSpdySession::CreateOutgoingBidirectionalWebTransportStream(
WebTransportHttp3* session) {
QuicSpdyStream* stream = CreateOutgoingBidirectionalStream();
if (stream == nullptr) {
return nullptr;
}
QuicStreamId stream_id = stream->id();
stream->ConvertToWebTransportDataStream(session->id());
if (stream->web_transport_stream() == nullptr) {
return nullptr;
}
session->AssociateStream(stream_id);
return stream;
}
void QuicSpdySession::OnDatagramProcessed(
std::optional<MessageStatus> ) {
}
void QuicSpdySession::DatagramObserver::OnDatagramProcessed(
std::optional<MessageStatus> status) {
session_->OnDatagramProcessed(status);
}
HttpDatagramSupport QuicSpdySession::LocalHttpDatagramSupport() {
return HttpDatagramSupport::kRfc;
}
std::string HttpDatagramSupportToString(
HttpDatagramSupport http_datagram_support) {
switch (http_datagram_support) {
case HttpDatagramSupport::kNone:
return "None";
case HttpDatagramSupport::kDraft04:
return "Draft04";
case HttpDatagramSupport::kRfc:
return "Rfc";
case HttpDatagramSupport::kRfcAndDraft04:
return "RfcAndDraft04";
}
return absl::StrCat("Unknown(", static_cast<int>(http_datagram_support), ")");
}
std::ostream& operator<<(std::ostream& os,
const HttpDatagramSupport& http_datagram_support) {
os << HttpDatagramSupportToString(http_datagram_support);
return os;
}
void QuicSpdySession::set_allow_extended_connect(bool allow_extended_connect) {
QUIC_BUG_IF(extended connect wrong version,
!VersionUsesHttp3(transport_version()))
<< "Try to enable/disable extended CONNECT in Google QUIC";
QUIC_BUG_IF(extended connect on client,
perspective() == Perspective::IS_CLIENT)
<< "Enabling/disabling extended CONNECT on the client side has no effect";
if (ShouldNegotiateWebTransport()) {
QUIC_BUG_IF(disable extended connect, !allow_extended_connect)
<< "Disabling extended CONNECT with web transport enabled has no "
"effect.";
return;
}
allow_extended_connect_ = allow_extended_connect;
}
void QuicSpdySession::OnConfigNegotiated() {
QuicSession::OnConfigNegotiated();
if (GetQuicReloadableFlag(quic_block_until_settings_received_copt) &&
perspective() == Perspective::IS_SERVER &&
config()->HasClientSentConnectionOption(kBSUS, Perspective::IS_SERVER)) {
QUICHE_RELOADABLE_FLAG_COUNT_N(quic_block_until_settings_received_copt, 1,
4);
force_buffer_requests_until_settings_ = true;
}
}
#undef ENDPOINT
} | #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/http2/core/spdy_framer.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"
using quiche::HttpHeaderBlock;
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.OnHeader(":method", "CONNECT");
headers.OnHeader(":protocol", "webtransport");
stream->OnStreamHeaderList(true, 0, headers);
WebTransportHttp3* web_transport =
session_->GetWebTransportSession(session_id);
ASSERT_TRUE(web_transport != nullptr);
quiche::HttpHeaderBlock 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_, WritePacket(_, _, _, _, _, _))
.WillRepeatedly(Return(WriteResult(WRITE_STATUS_OK, 0)));
TestStream* stream2 = session_->CreateOutgoingBidirectionalStream();
QuicStreamId closed_stream_id = stream2->id();
EXPECT_CALL(*connection_, SendControlFrame(_));
EXPECT_CALL(*connection_, OnStreamReset(closed_stream_id, _));
stream2->Reset(QUIC_BAD_APPLICATION_PAYLOAD);
std::string msg =
absl::StrCat("Marking unknown stream ", closed_stream_id, " blocked.");
EXPECT_QUIC_BUG(session_->MarkConnectionLevelWriteBlocked(closed_stream_id),
msg);
}
TEST_P(QuicSpdySessionTestServer, TooLargeStreamBlocked) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
QuicSessionPeer::SetMaxOpenIncomingBidirectionalStreams(
static_cast<QuicSession*>(&*session_), QuicUtils::GetMaxStreamCount());
QuicStreamsBlockedFrame frame;
frame.stream_count = QuicUtils::GetMaxStreamCount();
EXPECT_CALL(*writer_, WritePacket(_, _, _, _, _, _))
.WillOnce(Return(WriteResult(WRITE_STATUS_OK, 0)));
EXPECT_CALL(debug_visitor, OnGoAwayFrameSent(_));
session_->OnStreamsBlockedFrame(frame);
}
TEST_P(QuicSpdySessionTestServer, OnCanWriteBundlesStreams) {
Initialize();
CompleteHandshake();
MockSendAlgorithm* send_algorithm = new StrictMock<MockSendAlgorithm>;
QuicConnectionPeer::SetSendAlgorithm(session_->connection(), send_algorithm);
TestStream* stream2 = session_->CreateOutgoingBidirectionalStream();
TestStream* stream4 = session_->CreateOutgoingBidirectionalStream();
TestStream* stream6 = session_->CreateOutgoingBidirectionalStream();
session_->MarkConnectionLevelWriteBlocked(stream2->id());
session_->MarkConnectionLevelWriteBlocked(stream6->id());
session_->MarkConnectionLevelWriteBlocked(stream4->id());
EXPECT_CALL(*send_algorithm, CanSend(_)).WillRepeatedly(Return(true));
EXPECT_CALL(*send_algorithm, GetCongestionWindow())
.WillRepeatedly(Return(kMaxOutgoingPacketSize * 10));
EXPECT_CALL(*send_algorithm, InRecovery()).WillRepeatedly(Return(false));
EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() {
session_->SendStreamData(stream2);
}));
EXPECT_CALL(*stream4, OnCanWrite()).WillOnce(Invoke([this, stream4]() {
session_->SendStreamData(stream4);
}));
EXPECT_CALL(*stream6, OnCanWrite()).WillOnce(Invoke([this, stream6]() {
session_->SendStreamData(stream6);
}));
EXPECT_CALL(*writer_, WritePacket(_, _, _, _, _, _))
.WillOnce(Return(WriteResult(WRITE_STATUS_OK, 0)));
EXPECT_CALL(*send_algorithm, OnPacketSent(_, _, _, _, _));
EXPECT_CALL(*send_algorithm, OnApplicationLimited(_));
session_->OnCanWrite();
EXPECT_FALSE(session_->WillingAndAbleToWrite());
}
TEST_P(QuicSpdySessionTestServer, OnCanWriteCongestionControlBlocks) {
Initialize();
CompleteHandshake();
session_->set_writev_consumes_all_data(true);
InSequence s;
MockSendAlgorithm* send_algorithm = new StrictMock<MockSendAlgorithm>;
QuicConnectionPeer::SetSendAlgorithm(session_->connection(), send_algorithm);
TestStream* stream2 = session_->CreateOutgoingBidirectionalStream();
TestStream* stream4 = session_->CreateOutgoingBidirectionalStream();
TestStream* stream6 = session_->CreateOutgoingBidirectionalStream();
session_->MarkConnectionLevelWriteBlocked(stream2->id());
session_->MarkConnectionLevelWriteBlocked(stream6->id());
session_->MarkConnectionLevelWriteBlocked(stream4->id());
EXPECT_CALL(*send_algorithm, CanSend(_)).WillOnce(Return(true));
EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() {
session_->SendStreamData(stream2);
}));
EXPECT_CALL(*send_algorithm, GetCongestionWindow()).Times(AnyNumber());
EXPECT_CALL(*send_algorithm, CanSend(_)).WillOnce(Return(true));
EXPECT_CALL(*stream6, OnCanWrite()).WillOnce(Invoke([this, stream6]() {
session_->SendStreamData(stream6);
}));
EXPECT_CALL(*send_algorithm, CanSend(_)).WillOnce(Return(false));
session_->OnCanWrite();
EXPECT_TRUE(session_->WillingAndAbleToWrite());
EXPECT_CALL(*send_algorithm, CanSend(_)).WillOnce(Return(false));
session_->OnCanWrite();
EXPECT_TRUE(session_->WillingAndAbleToWrite());
EXPECT_CALL(*send_algorithm, CanSend(_)).WillOnce(Return(true));
EXPECT_CALL(*stream4, OnCanWrite()).WillOnce(Invoke([this, stream4]() {
session_->SendStreamData(stream4);
}));
EXPECT_CALL(*send_algorithm, OnApplicationLimited(_));
session_->OnCanWrite();
EXPECT_FALSE(session_->WillingAndAbleToWrite());
}
TEST_P(QuicSpdySessionTestServer, OnCanWriteWriterBlocks) {
Initialize();
CompleteHandshake();
MockSendAlgorithm* send_algorithm = new StrictMock<MockSendAlgorithm>;
QuicConnectionPeer::SetSendAlgorithm(session_->connection(), send_algorithm);
EXPECT_CALL(*send_algorithm, CanSend(_)).WillRepeatedly(Return(true));
EXPECT_CALL(*writer_, IsWriteBlocked()).WillRepeatedly(Return(true));
EXPECT_CALL(*writer_, WritePacket(_, _, _, _, _, _)).Times(0);
TestStream* stream2 = session_->CreateOutgoingBidirectionalStream();
session_->MarkConnectionLevelWriteBlocked(stream2->id());
EXPECT_CALL(*stream2, OnCanWrite()).Times(0);
EXPECT_CALL(*send_algorithm, OnApplicationLimited(_)).Times(0);
session_->OnCanWrite();
EXPECT_TRUE(session_->WillingAndAbleToWrite());
}
TEST_P(QuicSpdySessionTestServer, BufferedHandshake) {
Initialize();
if (QuicVersionUsesCryptoFrames(transport_version())) {
return;
}
session_->set_writev_consumes_all_data(true);
EXPECT_FALSE(session_->HasPendingHandshake());
TestStream* stream2 = session_->CreateOutgoingBidirectionalStream();
session_->MarkConnectionLevelWriteBlocked(stream2->id());
EXPECT_FALSE(session_->HasPendingHandshake());
TestStream* stream3 = session_->CreateOutgoingBidirectionalStream();
session_->MarkConnectionLevelWriteBlocked(stream3->id());
EXPECT_FALSE(session_->HasPendingHandshake());
session_->MarkConnectionLevelWriteBlocked(
QuicUtils::GetCryptoStreamId(transport_version()));
EXPECT_TRUE(session_->HasPendingHandshake());
TestStream* stream4 = session_->CreateOutgoingBidirectionalStream();
session_->MarkConnectionLevelWriteBlocked(stream4->id());
EXPECT_TRUE(session_->HasPendingHandshake());
InSequence s;
TestCryptoStream* crypto_stream = session_->GetMutableCryptoStream();
EXPECT_CALL(*crypto_stream, OnCanWrite());
EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() {
session_->SendStreamData(stream2);
}));
EXPECT_CALL(*stream3, OnCanWrite()).WillOnce(Invoke([this, stream3]() {
session_->SendStreamData(stream3);
}));
EXPECT_CALL(*stream4, OnCanWrite()).WillOnce(Invoke([this, stream4]() {
session_->SendStreamData(stream4);
session_->MarkConnectionLevelWriteBlocked(stream4->id());
}));
session_->OnCanWrite();
EXPECT_TRUE(session_->WillingAndAbleToWrite());
EXPECT_FALSE(session_->HasPendingHandshake());
}
TEST_P(QuicSpdySessionTestServer, OnCanWriteWithClosedStream) {
Initialize();
CompleteHandshake();
session_->set_writev_consumes_all_data(true);
TestStream* stream2 = session_->CreateOutgoingBidirectionalStream();
TestStream* stream4 = session_->CreateOutgoingBidirectionalStream();
TestStream* stream6 = session_->CreateOutgoingBidirectionalStream();
session_->MarkConnectionLevelWriteBlocked(stream2->id());
session_->MarkConnectionLevelWriteBlocked(stream6->id());
session_->MarkConnectionLevelWriteBlocked(stream4->id());
CloseStream(stream6->id());
InSequence s;
EXPECT_CALL(*connection_, SendControlFrame(_))
.WillRepeatedly(Invoke(&ClearControlFrame));
EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() {
session_->SendStreamData(stream2);
}));
EXPECT_CALL(*stream4, OnCanWrite()).WillOnce(Invoke([this, stream4]() {
session_->SendStreamData(stream4);
}));
session_->OnCanWrite();
EXPECT_FALSE(session_->WillingAndAbleToWrite());
}
TEST_P(QuicSpdySessionTestServer,
OnCanWriteLimitsNumWritesIfFlowControlBlocked) {
Initialize();
CompleteHandshake();
MockSendAlgorithm* send_algorithm = new StrictMock<MockSendAlgorithm>;
QuicConnectionPeer::SetSendAlgorithm(session_->connection(), send_algorithm);
EXPECT_CALL(*send_algorithm, CanSend(_)).WillRepeatedly(Return(true));
QuicFlowControllerPeer::SetSendWindowOffset(session_->flow_controller(), 0);
EXPECT_TRUE(session_->flow_controller()->IsBlocked());
EXPECT_TRUE(session_->IsConnectionFlowControlBlocked());
EXPECT_FALSE(session_->IsStreamFlowControlBlocked());
if (!QuicVersionUsesCryptoFrames(transport_version())) {
session_->MarkConnectionLevelWriteBlocked(
QuicUtils::GetCryptoStreamId(transport_version()));
}
TestStream* stream = session_->CreateOutgoingBidirectionalStream();
session_->MarkConnectionLevelWriteBlocked(stream->id());
EXPECT_CALL(*stream, OnCanWrite()).Times(0);
if (!QuicVersionUsesCryptoFrames(transport_version())) {
TestCryptoStream* crypto_stream = session_->GetMutableCryptoStream();
EXPECT_CALL(*crypto_stream, OnCanWrite());
}
if (!VersionUsesHttp3(transport_version())) {
TestHeadersStream* headers_stream;
QuicSpdySessionPeer::SetHeadersStream(&*session_, nullptr);
headers_stream = new TestHeadersStream(&*session_);
QuicSpdySessionPeer::SetHeadersStream(&*session_, headers_stream);
session_->MarkConnectionLevelWriteBlocked(
QuicUtils::GetHeadersStreamId(transport_version()));
EXPECT_CALL(*headers_stream, OnCanWrite());
}
EXPECT_CALL(*send_algorithm, OnApplicationLimited(_));
session_->OnCanWrite();
EXPECT_FALSE(session_->WillingAndAbleToWrite());
}
TEST_P(QuicSpdySessionTestServer, SendGoAway) {
Initialize();
CompleteHandshake();
if (VersionHasIetfQuicFrames(transport_version())) {
return;
}
connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
EXPECT_CALL(*writer_, WritePacket(_, _, _, _, _, _))
.WillOnce(Return(WriteResult(WRITE_STATUS_OK, 0)));
EXPECT_CALL(*connection_, SendControlFrame(_))
.WillOnce(
Invoke(connection_, &MockQuicConnection::ReallySendControlFrame));
session_->SendGoAway(QUIC_PEER_GOING_AWAY, "Going Away.");
EXPECT_TRUE(session_->goaway_sent());
const QuicStreamId kTestStreamId = 5u;
EXPECT_CALL(*connection_, SendControlFrame(_)).Times(0);
EXPECT_CALL(*connection_,
OnStreamReset(kTestStreamId, QUIC_STREAM_PEER_GOING_AWAY))
.Times(0);
EXPECT_TRUE(session_->GetOrCreateStream(kTestStreamId));
}
TEST_P(QuicSpdySessionTestServer, SendGoAwayWithoutEncryption) {
Initialize();
if (VersionHasIetfQuicFrames(transport_version())) {
return;
}
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_PEER_GOING_AWAY, "Going Away.",
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET));
EXPECT_CALL(*connection_, SendControlFrame(_)).Times(0);
session_->SendGoAway(QUIC_PEER_GOING_AWAY, "Going Away.");
EXPECT_FALSE(session_->goaway_sent());
}
TEST_P(QuicSpdySessionTestServer, SendHttp3GoAway) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
EXPECT_CALL(*writer_, WritePacket(_, _, _, _, _, _))
.WillOnce(Return(WriteResult(WRITE_STATUS_OK, 0)));
EXPECT_CALL(debug_visitor, OnGoAwayFrameSent( 0xfffffffc));
session_->SendHttp3GoAway(QUIC_PEER_GOING_AWAY, "Goaway");
EXPECT_TRUE(session_->goaway_sent());
const QuicStreamId kTestStreamId =
GetNthClientInitiatedBidirectionalStreamId(transport_version(), 0);
EXPECT_CALL(*connection_, OnStreamReset(kTestStreamId, _)).Times(0);
EXPECT_TRUE(session_->GetOrCreateStream(kTestStreamId));
session_->SendHttp3GoAway(QUIC_PEER_GOING_AWAY, "Goaway");
}
TEST_P(QuicSpdySessionTestServer, SendHttp3GoAwayAndNoMoreMaxStreams) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
EXPECT_CALL(*writer_, WritePacket(_, _, _, _, _, _))
.WillOnce(Return(WriteResult(WRITE_STATUS_OK, 0)));
EXPECT_CALL(debug_visitor, OnGoAwayFrameSent( 0xfffffffc));
session_->SendHttp3GoAway(QUIC_PEER_GOING_AWAY, "Goaway");
EXPECT_TRUE(session_->goaway_sent());
EXPECT_CALL(*connection_, SendControlFrame(_)).Times(0);
const QuicStreamCount max_streams =
QuicSessionPeer::ietf_streamid_manager(&*session_)
->max_incoming_bidirectional_streams();
for (QuicStreamCount i = 0; i < max_streams; ++i) {
QuicStreamId stream_id = StreamCountToId(
i + 1,
Perspective::IS_CLIENT,
true);
EXPECT_NE(nullptr, session_->GetOrCreateStream(stream_id));
CloseStream(stream_id);
QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream_id,
QUIC_STREAM_CANCELLED,
0);
session_->OnRstStream(rst_frame);
}
EXPECT_EQ(max_streams, QuicSessionPeer::ietf_streamid_manager(&*session_)
->max_incoming_bidirectional_streams());
}
TEST_P(QuicSpdySessionTestServer, SendHttp3GoAwayWithoutEncryption) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_PEER_GOING_AWAY, "Goaway",
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET));
session_->SendHttp3GoAway(QUIC_PEER_GOING_AWAY, "Goaway");
EXPECT_FALSE(session_->goaway_sent());
}
TEST_P(QuicSpdySessionTestServer, SendHttp3GoAwayAfterStreamIsCreated) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
const QuicStreamId kTestStreamId =
GetNthClientInitiatedBidirectionalStreamId(transport_version(), 0);
EXPECT_TRUE(session_->GetOrCreateStream(kTestStreamId));
EXPECT_CALL(*writer_, WritePacket(_, _, _, _, _, _))
.WillOnce(Return(WriteResult(WRITE_STATUS_OK, 0)));
EXPECT_CALL(debug_visitor, OnGoAwayFrameSent( 0xfffffffc));
session_->SendHttp3GoAway(QUIC_PEER_GOING_AWAY, "Goaway");
EXPECT_TRUE(session_->goaway_sent());
session_->SendHttp3GoAway(QUIC_PEER_GOING_AWAY, "Goaway");
}
TEST_P(QuicSpdySessionTestServer, DoNotSendGoAwayTwice) {
Initialize();
CompleteHandshake();
if (VersionHasIetfQuicFrames(transport_version())) {
return;
}
EXPECT_CALL(*connection_, SendControlFrame(_))
.WillOnce(Invoke(&ClearControlFrame));
session_->SendGoAway(QUIC_PEER_GOING_AWAY, "Going Away.");
EXPECT_TRUE(session_->goaway_sent());
session_->SendGoAway(QUIC_PEER_GOING_AWAY, "Going Away.");
}
TEST_P(QuicSpdySessionTestServer, InvalidGoAway) {
Initialize();
if (VersionHasIetfQuicFrames(transport_version())) {
return;
}
QuicGoAwayFrame go_away(kInvalidControlFrameId, QUIC_PEER_GOING_AWAY,
session_->next_outgoing_bidirectional_stream_id(),
"");
session_->OnGoAway(go_away);
}
TEST_P(QuicSpdySessionTestServer, Http3GoAwayLargerIdThanBefore) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
EXPECT_FALSE(session_->goaway_received());
session_->OnHttp3GoAway( 0);
EXPECT_TRUE(session_->goaway_received());
EXPECT_CALL(
*connection_,
CloseConnection(
QUIC_HTTP_GOAWAY_ID_LARGER_THAN_PREVIOUS,
"GOAWAY received with ID 1 greater than previously received ID 0",
_));
session_->OnHttp3GoAway( 1);
}
TEST_P(QuicSpdySessionTestServer, ServerReplyToConnecitivityProbe) {
Initialize();
if (VersionHasIetfQuicFrames(transport_version()) ||
GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
return;
}
connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QuicSocketAddress old_peer_address =
QuicSocketAddress(QuicIpAddress::Loopback4(), kTestPort);
EXPECT_EQ(old_peer_address, session_->peer_address());
QuicSocketAddress new_peer_address =
QuicSocketAddress(QuicIpAddress::Loopback4(), kTestPort + 1);
EXPECT_CALL(*connection_,
SendConnectivityProbingPacket(nullptr, new_peer_address));
session_->OnPacketReceived(session_->self_address(), new_peer_address,
true);
EXPECT_EQ(old_peer_address, session_->peer_address());
}
TEST_P(QuicSpdySessionTestServer, IncreasedTimeoutAfterCryptoHandshake) {
Initialize();
EXPECT_EQ(kInitialIdleTimeoutSecs + 3,
QuicConnectionPeer::GetNetworkTimeout(connection_).ToSeconds());
CompleteHandshake();
EXPECT_EQ(kMaximumIdleTimeoutSecs + 3,
QuicConnectionPeer::GetNetworkTimeout(connection_).ToSeconds());
}
TEST_P(QuicSpdySessionTestServer, RstStreamBeforeHeadersDecompressed) {
Initialize();
CompleteHandshake();
QuicStreamFrame data1(GetNthClientInitiatedBidirectionalId(0), false, 0,
absl::string_view("HT"));
session_->OnStreamFrame(data1);
EXPECT_EQ(1u, QuicSessionPeer::GetNumOpenDynamicStreams(&*session_));
if (!VersionHasIetfQuicFrames(transport_version())) {
EXPECT_CALL(*connection_,
OnStreamReset(GetNthClientInitiatedBidirectionalId(0), _));
}
EXPECT_CALL(*connection_, SendControlFrame(_));
QuicRstStreamFrame rst1(kInvalidControlFrameId,
GetNthClientInitiatedBidirectionalId(0),
QUIC_ERROR_PROCESSING_STREAM, 0);
session_->OnRstStream(rst1);
if (VersionHasIetfQuicFrames(transport_version())) {
QuicStopSendingFrame stop_sending(kInvalidControlFrameId,
GetNthClientInitiatedBidirectionalId(0),
QUIC_ERROR_PROCESSING_STREAM);
EXPECT_CALL(*connection_,
OnStreamReset(GetNthClientInitiatedBidirectionalId(0),
QUIC_ERROR_PROCESSING_STREAM));
session_->OnStopSendingFrame(stop_sending);
}
EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(&*session_));
EXPECT_TRUE(connection_->connected());
}
TEST_P(QuicSpdySessionTestServer, OnStreamFrameFinStaticStreamId) {
Initialize();
QuicStreamId id;
if (VersionUsesHttp3(transport_version())) {
CompleteHandshake();
id = GetNthClientInitiatedUnidirectionalStreamId(transport_version(), 3);
char type[] = {kControlStream};
QuicStreamFrame data1(id, false, 0, absl::string_view(type, 1));
session_->OnStreamFrame(data1);
} else {
id = QuicUtils::GetHeadersStreamId(transport_version());
}
QuicStreamFrame data1(id, true, 0, absl::string_view("HT"));
EXPECT_CALL(*connection_,
CloseConnection(
QUIC_INVALID_STREAM_ID, "Attempt to close a static stream",
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET));
session_->OnStreamFrame(data1);
}
TEST_P(QuicSpdySessionTestServer, OnRstStreamStaticStreamId) {
Initialize();
QuicStreamId id;
QuicErrorCode expected_error;
std::string error_message;
if (VersionUsesHttp3(transport_version())) {
CompleteHandshake();
id = GetNthClientInitiatedUnidirectionalStreamId(transport_version(), 3);
char type[] = {kControlStream};
QuicStreamFrame data1(id, false, 0, absl::string_view(type, 1));
session_->OnStreamFrame(data1);
expected_error = QUIC_HTTP_CLOSED_CRITICAL_STREAM;
error_message = "RESET_STREAM received for receive control stream";
} else {
id = QuicUtils::GetHeadersStreamId(transport_version());
expected_error = QUIC_INVALID_STREAM_ID;
error_message = "Attempt to reset headers stream";
}
QuicRstStreamFrame rst1(kInvalidControlFrameId, id,
QUIC_ERROR_PROCESSING_STREAM, 0);
EXPECT_CALL(
*connection_,
CloseConnection(expected_error, error_message,
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET));
session_->OnRstStream(rst1);
}
TEST_P(QuicSpdySessionTestServer, OnStreamFrameInvalidStreamId) {
Initialize();
QuicStreamFrame data1(QuicUtils::GetInvalidStreamId(transport_version()),
true, 0, absl::string_view("HT"));
EXPECT_CALL(*connection_,
CloseConnection(
QUIC_INVALID_STREAM_ID, "Received data for an invalid stream",
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET));
session_->OnStreamFrame(data1);
}
TEST_P(QuicSpdySessionTestServer, OnRstStreamInvalidStreamId) {
Initialize();
QuicRstStreamFrame rst1(kInvalidControlFrameId,
QuicUtils::GetInvalidStreamId(transport_version()),
QUIC_ERROR_PROCESSING_STREAM, 0);
EXPECT_CALL(*connection_,
CloseConnection(
QUIC_INVALID_STREAM_ID, "Received data for an invalid stream",
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET));
session_->OnRstStream(rst1);
}
TEST_P(QuicSpdySessionTestServer, HandshakeUnblocksFlowControlBlockedStream) {
Initialize();
if (connection_->version().handshake_protocol == PROTOCOL_TLS1_3) {
return;
}
session_->GetMutableCryptoStream()->EstablishZeroRttEncryption();
session_->set_writev_consumes_all_data(true);
TestStream* stream2 = session_->CreateOutgoingBidirectionalStream();
std::string body(kMinimumFlowControlSendWindow, '.');
EXPECT_FALSE(stream2->IsFlowControlBlocked());
EXPECT_FALSE(session_->IsConnectionFlowControlBlocked());
EXPECT_FALSE(session_->IsStreamFlowControlBlocked());
EXPECT_CALL(*connection_, SendControlFrame(_)).Times(AtLeast(1));
stream2->WriteOrBufferBody(body, false);
EXPECT_TRUE(stream2->IsFlowControlBlocked());
EXPECT_TRUE(session_->IsConnectionFlowControlBlocked());
EXPECT_TRUE(session_->IsStreamFlowControlBlocked());
CompleteHandshake();
EXPECT_TRUE(QuicSessionPeer::IsStreamWriteBlocked(&*session_, stream2->id()));
EXPECT_FALSE(stream2->IsFlowControlBlocked());
EXPECT_FALSE(session_->IsConnectionFlowControlBlocked());
EXPECT_FALSE(session_->IsStreamFlowControlBlocked());
}
#if !defined(OS_IOS)
TEST_P(QuicSpdySessionTestServer,
HandshakeUnblocksFlowControlBlockedHeadersStream) {
Initialize();
if (QuicVersionUsesCryptoFrames(transport_version())) {
return;
}
if (VersionUsesHttp3(transport_version())) {
return;
}
session_->GetMutableCryptoStream()->EstablishZeroRttEncryption();
session_->set_writev_consumes_all_data(true);
TestCryptoStream* crypto_stream = session_->GetMutableCryptoStream();
EXPECT_FALSE(crypto_stream->IsFlowControlBlocked());
EXPECT_FALSE(session_->IsConnectionFlowControlBlocked());
EXPECT_FALSE(session_->IsStreamFlowControlBlocked());
QuicHeadersStream* headers_stream =
QuicSpdySessionPeer::GetHeadersStream(&*session_);
EXPECT_FALSE(headers_stream->IsFlowControlBlocked());
EXPECT_FALSE(session_->IsConnectionFlowControlBlocked());
EXPECT_FALSE(session_->IsStreamFlowControlBlocked());
QuicStreamId stream_id = 5;
EXPECT_CALL(*connection_, SendControlFrame(_))
.WillOnce(Invoke(&ClearControlFrame));
HttpHeaderBlock headers;
SimpleRandom random;
while (!headers_stream->IsFlowControlBlocked() && stream_id < 2000) {
EXPECT_FALSE(session_->IsConnectionFlowControlBlocked());
EXPECT_FALSE(session_->IsStreamFlowControlBlocked());
headers["header"] = absl::StrCat(random.RandUint64(), random.RandUint64(),
random.RandUint64());
session_->WriteHeadersOnHeadersStream(stream_id, headers.Clone(), true,
spdy::SpdyStreamPrecedence(0),
nullptr);
stream_id += IdDelta();
}
session_->WriteHeadersOnHeadersStream(stream_id, std::move(headers), true,
spdy::SpdyStreamPrecedence(0), nullptr);
EXPECT_TRUE(headers_stream->HasBufferedData());
EXPECT_TRUE(headers_stream->IsFlowControlBlocked());
EXPECT_FALSE(crypto_stream->IsFlowControlBlocked());
EXPECT_FALSE(session_->IsConnectionFlowControlBlocked());
EXPECT_TRUE(session_->IsStreamFlowControlBlocked());
EXPECT_FALSE(session_->HasDataToWrite());
CompleteHandshake();
EXPECT_FALSE(headers_stream->IsFlowControlBlocked());
EXPECT_FALSE(session_->IsConnectionFlowControlBlocked());
EXPECT_FALSE(session_->IsStreamFlowControlBlocked());
EXPECT_TRUE(headers_stream->HasBufferedData());
EXPECT_TRUE(QuicSessionPeer::IsStreamWriteBlocked(
&*session_, QuicUtils::GetHeadersStreamId(transport_version())));
}
#endif
TEST_P(QuicSpdySessionTestServer,
ConnectionFlowControlAccountingRstOutOfOrder) {
Initialize();
EXPECT_CALL(*connection_, SendControlFrame(_))
.WillRepeatedly(Invoke(&ClearControlFrame));
CompleteHandshake();
TestStream* stream = session_->CreateOutgoingBidirectionalStream();
const QuicStreamOffset kByteOffset =
1 + kInitialSessionFlowControlWindowForTest / 2;
if (!VersionHasIetfQuicFrames(transport_version())) {
EXPECT_CALL(*connection_, OnStreamReset(stream->id(), _));
EXPECT_CALL(*connection_, SendControlFrame(_));
}
QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream->id(),
QUIC_STREAM_CANCELLED, kByteOffset);
session_->OnRstStream(rst_frame);
if (VersionHasIetfQuicFrames(transport_version())) {
QuicStopSendingFrame stop_sending(kInvalidControlFrameId, stream->id(),
QUIC_STREAM_CANCELLED);
EXPECT_CALL(*connection_,
OnStreamReset(stream->id(), QUIC_STREAM_CANCELLED));
EXPECT_CALL(*connection_, SendControlFrame(_));
session_->OnStopSendingFrame(stop_sending);
}
EXPECT_EQ(kByteOffset, session_->flow_controller()->bytes_consumed());
}
TEST_P(QuicSpdySessionTestServer, InvalidStreamFlowControlWindowInHandshake) {
Initialize();
if (GetParam().handshake_protocol == PROTOCOL_TLS1_3) {
return;
}
const uint32_t kInvalidWindow = kMinimumFlowControlSendWindow - 1;
QuicConfigPeer::SetReceivedInitialStreamFlowControlWindow(session_->config(),
kInvalidWindow);
EXPECT_CALL(*connection_,
CloseConnection(QUIC_FLOW_CONTROL_INVALID_WINDOW, _, _));
session_->OnConfigNegotiated();
}
TEST_P(QuicSpdySessionTestServer, TooLowUnidirectionalStreamLimitHttp3) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
session_->GetMutableCryptoStream()->EstablishZeroRttEncryption();
QuicConfigPeer::SetReceivedMaxUnidirectionalStreams(session_->config(), 2u);
connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
EXPECT_CALL(
*connection_,
CloseConnection(
_, "new unidirectional limit 2 decreases the current limit: 3", _));
session_->OnConfigNegotiated();
}
TEST_P(QuicSpdySessionTestServer, CustomFlowControlWindow) {
Initialize();
QuicTagVector copt;
copt.push_back(kIFW7);
QuicConfigPeer::SetReceivedConnectionOptions(session_->config(), copt);
connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
session_->OnConfigNegotiated();
EXPECT_EQ(192 * 1024u, QuicFlowControllerPeer::ReceiveWindowSize(
session_->flow_controller()));
}
TEST_P(QuicSpdySessionTestServer, WindowUpdateUnblocksHeadersStream) {
Initialize();
if (VersionUsesHttp3(transport_version())) {
return;
}
QuicHeadersStream* headers_stream =
QuicSpdySessionPeer::GetHeadersStream(&*session_);
QuicStreamPeer::SetSendWindowOffset(headers_stream, 0);
EXPECT_TRUE(headers_stream->IsFlowControlBlocked());
EXPECT_FALSE(session_->IsConnectionFlowControlBlocked());
EXPECT_TRUE(session_->IsStreamFlowControlBlocked());
QuicWindowUpdateFrame window_update_frame(kInvalidControlFrameId,
headers_stream->id(),
2 * kMinimumFlowControlSendWindow);
session_->OnWindowUpdateFrame(window_update_frame);
EXPECT_FALSE(headers_stream->IsFlowControlBlocked());
EXPECT_FALSE(session_->IsConnectionFlowControlBlocked());
EXPECT_FALSE(session_->IsStreamFlowControlBlocked());
}
TEST_P(QuicSpdySessionTestServer,
TooManyUnfinishedStreamsCauseServerRejectStream) {
Initialize();
CompleteHandshake();
const QuicStreamId kMaxStreams = 5;
if (VersionHasIetfQuicFrames(transport_version())) {
QuicSessionPeer::SetMaxOpenIncomingBidirectionalStreams(&*session_,
kMaxStreams);
} else {
QuicSessionPeer::SetMaxOpenIncomingStreams(&*session_, kMaxStreams);
}
const QuicStreamId kFirstStreamId = GetNthClientInitiatedBidirectionalId(0);
const QuicStreamId kFinalStreamId =
GetNthClientInitiatedBidirectionalId(kMaxStreams);
const QuicStreamId kNextId = QuicUtils::StreamIdDelta(transport_version());
for (QuicStreamId i = kFirstStreamId; i < kFinalStreamId; i += kNextId) {
QuicStreamFrame data1(i, false, 0, absl::string_view("HT"));
session_->OnStreamFrame(data1);
CloseStream(i);
}
if (!VersionHasIetfQuicFrames(transport_version())) {
EXPECT_CALL(*connection_, SendControlFrame(_)).Times(1);
EXPECT_CALL(*connection_,
OnStreamReset(kFinalStreamId, QUIC_REFUSED_STREAM))
.Times(1);
} else {
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_INVALID_STREAM_ID,
testing::MatchesRegex(
"Stream id \\d+ would exceed stream count limit 5"),
_));
}
QuicStreamFrame data1(kFinalStreamId, false, 0, absl::string_view("HT"));
session_->OnStreamFrame(data1);
}
TEST_P(QuicSpdySessionTestServer, DrainingStreamsDoNotCountAsOpened) {
Initialize();
CompleteHandshake();
if (VersionHasIetfQuicFrames(transport_version())) {
QuicSessionPeer::set_is_configured(&*session_, true);
EXPECT_CALL(*connection_, SendControlFrame(_)).Times(1);
} else {
EXPECT_CALL(*connection_, SendControlFrame(_)).Times(0);
}
EXPECT_CALL(*connection_, OnStreamReset(_, QUIC_REFUSED_STREAM)).Times(0);
const QuicStreamId kMaxStreams = 5;
if (VersionHasIetfQuicFrames(transport_version())) {
QuicSessionPeer::SetMaxOpenIncomingBidirectionalStreams(&*session_,
kMaxStreams);
} else {
QuicSessionPeer::SetMaxOpenIncomingStreams(&*session_, kMaxStreams);
}
const QuicStreamId kFirstStreamId = GetNthClientInitiatedBidirectionalId(0);
const QuicStreamId kFinalStreamId =
GetNthClientInitiatedBidirectionalId(kMaxStreams + 1);
for (QuicStreamId i = kFirstStreamId; i < kFinalStreamId; i += IdDelta()) {
QuicStreamFrame data1(i, true, 0, absl::string_view("HT"));
session_->OnStreamFrame(data1);
EXPECT_EQ(1u, QuicSessionPeer::GetNumOpenDynamicStreams(&*session_));
session_->StreamDraining(i, false);
EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(&*session_));
}
}
class QuicSpdySessionTestClient : public QuicSpdySessionTestBase {
protected:
QuicSpdySessionTestClient()
: QuicSpdySessionTestBase(Perspective::IS_CLIENT, false) {}
};
INSTANTIATE_TEST_SUITE_P(Tests, QuicSpdySessionTestClient,
::testing::ValuesIn(AllSupportedVersions()),
::testing::PrintToStringParamName());
TEST_P(QuicSpdySessionTestClient, UsesPendingStreamsForFrame) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
EXPECT_TRUE(session_->UsesPendingStreamForFrame(
STREAM_FRAME, QuicUtils::GetFirstUnidirectionalStreamId(
transport_version(), Perspective::IS_SERVER)));
EXPECT_TRUE(session_->UsesPendingStreamForFrame(
RST_STREAM_FRAME, QuicUtils::GetFirstUnidirectionalStreamId(
transport_version(), Perspective::IS_SERVER)));
EXPECT_FALSE(session_->UsesPendingStreamForFrame(
RST_STREAM_FRAME, QuicUtils::GetFirstUnidirectionalStreamId(
transport_version(), Perspective::IS_CLIENT)));
EXPECT_FALSE(session_->UsesPendingStreamForFrame(
STOP_SENDING_FRAME, QuicUtils::GetFirstUnidirectionalStreamId(
transport_version(), Perspective::IS_SERVER)));
EXPECT_FALSE(session_->UsesPendingStreamForFrame(
RST_STREAM_FRAME, QuicUtils::GetFirstBidirectionalStreamId(
transport_version(), Perspective::IS_SERVER)));
}
TEST_P(QuicSpdySessionTestClient, BadStreamFramePendingStream) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(&*session_));
QuicStreamId stream_id1 =
GetNthServerInitiatedUnidirectionalStreamId(transport_version(), 0);
QuicStreamFrame data1(stream_id1, false, 0, 0);
session_->OnStreamFrame(data1);
}
TEST_P(QuicSpdySessionTestClient, PendingStreamKeepsConnectionAlive) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
QuicStreamId stream_id = QuicUtils::GetFirstUnidirectionalStreamId(
transport_version(), Perspective::IS_SERVER);
QuicStreamFrame frame(stream_id, false, 1, "test");
EXPECT_FALSE(session_->ShouldKeepConnectionAlive());
session_->OnStreamFrame(frame);
EXPECT_TRUE(QuicSessionPeer::GetPendingStream(&*session_, stream_id));
EXPECT_TRUE(session_->ShouldKeepConnectionAlive());
}
TEST_P(QuicSpdySessionTestClient, AvailableStreamsClient) {
Initialize();
ASSERT_TRUE(session_->GetOrCreateStream(
GetNthServerInitiatedBidirectionalId(2)) != nullptr);
EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable(
&*session_, GetNthServerInitiatedBidirectionalId(0)));
EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable(
&*session_, GetNthServerInitiatedBidirectionalId(1)));
ASSERT_TRUE(session_->GetOrCreateStream(
GetNthServerInitiatedBidirectionalId(0)) != nullptr);
ASSERT_TRUE(session_->GetOrCreateStream(
GetNthServerInitiatedBidirectionalId(1)) != nullptr);
EXPECT_FALSE(QuicSessionPeer::IsStreamAvailable(
&*session_, GetNthClientInitiatedBidirectionalId(0)));
}
TEST_P(QuicSpdySessionTestClient, TooLargeHeadersMustNotCauseWriteAfterReset) {
Initialize();
if (VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
TestStream* stream = session_->CreateOutgoingBidirectionalStream();
EXPECT_CALL(*writer_, WritePacket(_, _, _, _, _, _))
.WillOnce(Return(WriteResult(WRITE_STATUS_OK, 0)));
stream->WriteHeaders(HttpHeaderBlock(), true, nullptr);
QuicHeaderList headers;
EXPECT_CALL(*connection_, SendControlFrame(_));
EXPECT_CALL(*connection_,
OnStreamReset(stream->id(), QUIC_HEADERS_TOO_LARGE));
stream->OnStreamHeaderList( true,
headers.uncompressed_header_bytes(), headers);
}
TEST_P(QuicSpdySessionTestClient, RecordFinAfterReadSideClosed) {
Initialize();
CompleteHandshake();
TestStream* stream = session_->CreateOutgoingBidirectionalStream();
QuicStreamId stream_id = stream->id();
QuicStreamPeer::CloseReadSide(stream);
QuicStreamFrame frame(stream_id, true, 0, absl::string_view());
session_->OnStreamFrame(frame);
EXPECT_TRUE(stream->fin_received());
EXPECT_CALL(*connection_, SendControlFrame(_));
EXPECT_CALL(*connection_, OnStreamReset(stream->id(), _));
stream->Reset(QUIC_STREAM_CANCELLED);
EXPECT_TRUE(QuicStreamPeer::read_side_closed(stream));
EXPECT_TRUE(connection_->connected());
EXPECT_TRUE(QuicSessionPeer::IsStreamClosed(&*session_, stream_id));
EXPECT_FALSE(QuicSessionPeer::IsStreamCreated(&*session_, stream_id));
EXPECT_EQ(
0u,
QuicSessionPeer::GetLocallyClosedStreamsHighestOffset(&*session_).size());
}
TEST_P(QuicSpdySessionTestClient, WritePriority) {
Initialize();
if (VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
TestHeadersStream* headers_stream;
QuicSpdySessionPeer::SetHeadersStream(&*session_, nullptr);
headers_stream = new TestHeadersStream(&*session_);
QuicSpdySessionPeer::SetHeadersStream(&*session_, headers_stream);
EXPECT_CALL(*writer_, IsWriteBlocked()).WillRepeatedly(Return(true));
const QuicStreamId id = 4;
const QuicStreamId parent_stream_id = 9;
const SpdyPriority priority = kV3HighestPriority;
const bool exclusive = true;
session_->WritePriority(id, parent_stream_id,
Spdy3PriorityToHttp2Weight(priority), exclusive);
QuicStreamSendBuffer& send_buffer =
QuicStreamPeer::SendBuffer(headers_stream);
ASSERT_EQ(1u, send_buffer.size());
SpdyPriorityIR priority_frame(
id, parent_stream_id, Spdy3PriorityToHttp2Weight(priority), exclusive);
SpdyFramer spdy_framer(SpdyFramer::ENABLE_COMPRESSION);
SpdySerializedFrame frame = spdy_framer.SerializeFrame(priority_frame);
const quiche::QuicheMemSlice& slice =
QuicStreamSendBufferPeer::CurrentWriteSlice(&send_buffer)->slice;
EXPECT_EQ(absl::string_view(frame.data(), frame.size()),
absl::string_view(slice.data(), slice.length()));
}
TEST_P(QuicSpdySessionTestClient, Http3ServerPush) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(&*session_));
std::string frame_type1;
ASSERT_TRUE(absl::HexStringToBytes("01", &frame_type1));
QuicStreamId stream_id1 =
GetNthServerInitiatedUnidirectionalStreamId(transport_version(), 0);
EXPECT_CALL(*connection_,
CloseConnection(QUIC_HTTP_RECEIVE_SERVER_PUSH, _, _))
.Times(1);
session_->OnStreamFrame(QuicStreamFrame(stream_id1, false,
0, frame_type1));
}
TEST_P(QuicSpdySessionTestClient, Http3ServerPushOutofOrderFrame) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(&*session_));
std::string frame_type;
ASSERT_TRUE(absl::HexStringToBytes("01", &frame_type));
std::string push_id;
ASSERT_TRUE(absl::HexStringToBytes("4000", &push_id));
QuicStreamId stream_id =
GetNthServerInitiatedUnidirectionalStreamId(transport_version(), 0);
QuicStreamFrame data1(stream_id,
false, 0, frame_type);
QuicStreamFrame data2(stream_id,
false, frame_type.size(),
push_id);
session_->OnStreamFrame(data2);
EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(&*session_));
EXPECT_CALL(*connection_,
CloseConnection(QUIC_HTTP_RECEIVE_SERVER_PUSH, _, _))
.Times(1);
session_->OnStreamFrame(data1);
}
TEST_P(QuicSpdySessionTestClient, ServerDisableQpackDynamicTable) {
SetQuicFlag(quic_server_disable_qpack_dynamic_table, true);
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
QuicStreamId stream_id =
GetNthServerInitiatedUnidirectionalStreamId(transport_version(), 3);
char type[] = {kControlStream};
QuicStreamFrame data1(stream_id, false, 0, absl::string_view(type, 1));
session_->OnStreamFrame(data1);
EXPECT_EQ(stream_id,
QuicSpdySessionPeer::GetReceiveControlStream(&*session_)->id());
const uint64_t capacity = 512;
SettingsFrame settings;
settings.values[SETTINGS_QPACK_MAX_TABLE_CAPACITY] = capacity;
std::string data = HttpEncoder::SerializeSettingsFrame(settings);
QuicStreamFrame frame(stream_id, false, 1, data);
session_->OnStreamFrame(frame);
QpackEncoder* qpack_encoder = session_->qpack_encoder();
EXPECT_EQ(capacity, qpack_encoder->MaximumDynamicTableCapacity());
QpackEncoderHeaderTable* encoder_header_table =
QpackEncoderPeer::header_table(qpack_encoder);
EXPECT_EQ(capacity, encoder_header_table->dynamic_table_capacity());
EXPECT_EQ(capacity, encoder_header_table->maximum_dynamic_table_capacity());
SettingsFrame outgoing_settings = session_->settings();
EXPECT_EQ(kDefaultQpackMaxDynamicTableCapacity,
outgoing_settings.values[SETTINGS_QPACK_MAX_TABLE_CAPACITY]);
}
TEST_P(QuicSpdySessionTestClient, DisableQpackDynamicTable) {
SetQuicFlag(quic_server_disable_qpack_dynamic_table, false);
qpack_maximum_dynamic_table_capacity_ = 0;
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
QuicStreamId stream_id =
GetNthServerInitiatedUnidirectionalStreamId(transport_version(), 3);
char type[] = {kControlStream};
QuicStreamFrame data1(stream_id, false, 0, absl::string_view(type, 1));
session_->OnStreamFrame(data1);
EXPECT_EQ(stream_id,
QuicSpdySessionPeer::GetReceiveControlStream(&*session_)->id());
const uint64_t capacity = 512;
SettingsFrame settings;
settings.values[SETTINGS_QPACK_MAX_TABLE_CAPACITY] = capacity;
std::string data = HttpEncoder::SerializeSettingsFrame(settings);
QuicStreamFrame frame(stream_id, false, 1, data);
session_->OnStreamFrame(frame);
QpackEncoder* qpack_encoder = session_->qpack_encoder();
EXPECT_EQ(capacity, qpack_encoder->MaximumDynamicTableCapacity());
QpackEncoderHeaderTable* encoder_header_table =
QpackEncoderPeer::header_table(qpack_encoder);
EXPECT_EQ(0, encoder_header_table->dynamic_table_capacity());
EXPECT_EQ(capacity, encoder_header_table->maximum_dynamic_table_capacity());
SettingsFrame outgoing_settings = session_->settings();
EXPECT_EQ(0, outgoing_settings.values[SETTINGS_QPACK_MAX_TABLE_CAPACITY]);
}
TEST_P(QuicSpdySessionTestServer, OnStreamFrameLost) {
Initialize();
CompleteHandshake();
InSequence s;
MockSendAlgorithm* send_algorithm = new StrictMock<MockSendAlgorithm>;
QuicConnectionPeer::SetSendAlgorithm(session_->connection(), send_algorithm);
TestCryptoStream* crypto_stream = session_->GetMutableCryptoStream();
TestStream* stream2 = session_->CreateOutgoingBidirectionalStream();
TestStream* stream4 = session_->CreateOutgoingBidirectionalStream();
QuicStreamFrame frame2(stream2->id(), false, 0, 9);
QuicStreamFrame frame3(stream4->id(), false, 0, 9);
EXPECT_CALL(*stream4, HasPendingRetransmission()).WillOnce(Return(true));
if (!QuicVersionUsesCryptoFrames(transport_version())) {
EXPECT_CALL(*crypto_stream, HasPendingRetransmission())
.WillOnce(Return(true));
}
EXPECT_CALL(*stream2, HasPendingRetransmission()).WillOnce(Return(true));
session_->OnFrameLost(QuicFrame(frame3));
if (!QuicVersionUsesCryptoFrames(transport_version())) {
QuicStreamFrame frame1(QuicUtils::GetCryptoStreamId(transport_version()),
false, 0, 1300);
session_->OnFrameLost(QuicFrame(frame1));
} else {
QuicCryptoFrame crypto_frame(ENCRYPTION_INITIAL, 0, 1300);
session_->OnFrameLost(QuicFrame(&crypto_frame));
}
session_->OnFrameLost(QuicFrame(frame2));
EXPECT_TRUE(session_->WillingAndAbleToWrite());
session_->MarkConnectionLevelWriteBlocked(stream2->id());
session_->MarkConnectionLevelWriteBlocked(stream4->id());
EXPECT_CALL(*send_algorithm, CanSend(_)).Times(0);
if (!QuicVersionUsesCryptoFrames(transport_version())) {
EXPECT_CALL(*crypto_stream, OnCanWrite());
EXPECT_CALL(*crypto_stream, HasPendingRetransmission())
.WillOnce(Return(false));
}
EXPECT_CALL(*send_algorithm, CanSend(_)).WillOnce(Return(true));
EXPECT_CALL(*stream4, OnCanWrite());
EXPECT_CALL(*stream4, HasPendingRetransmission()).WillOnce(Return(false));
EXPECT_CALL(*send_algorithm, CanSend(_)).WillRepeatedly(Return(false));
session_->OnCanWrite();
EXPECT_TRUE(session_->WillingAndAbleToWrite());
EXPECT_CALL(*send_algorithm, CanSend(_)).WillOnce(Return(true));
EXPECT_CALL(*stream2, OnCanWrite());
EXPECT_CALL(*stream2, HasPendingRetransmission()).WillOnce(Return(false));
EXPECT_CALL(*send_algorithm, CanSend(_)).WillOnce(Return(true));
EXPECT_CALL(*stream2, OnCanWrite());
EXPECT_CALL(*send_algorithm, CanSend(_)).WillOnce(Return(true));
EXPECT_CALL(*stream4, OnCanWrite());
EXPECT_CALL(*send_algorithm, OnApplicationLimited(_));
session_->OnCanWrite();
EXPECT_FALSE(session_->WillingAndAbleToWrite());
}
TEST_P(QuicSpdySessionTestServer, DonotRetransmitDataOfClosedStreams) {
Initialize();
CompleteHandshake();
NoopQpackStreamSenderDelegate qpack_stream_sender_delegate;
if (VersionUsesHttp3(transport_version())) {
session_->qpack_decoder()->set_qpack_stream_sender_delegate(
&qpack_stream_sender_delegate);
}
InSequence s;
TestStream* stream2 = session_->CreateOutgoingBidirectionalStream();
TestStream* stream4 = session_->CreateOutgoingBidirectionalStream();
TestStream* stream6 = session_->CreateOutgoingBidirectionalStream();
QuicStreamFrame frame1(stream2->id(), false, 0, 9);
QuicStreamFrame frame2(stream4->id(), false, 0, 9);
QuicStreamFrame frame3(stream6->id(), false, 0, 9);
EXPECT_CALL(*stream6, HasPendingRetransmission()).WillOnce(Return(true));
EXPECT_CALL(*stream4, HasPendingRetransmission()).WillOnce(Return(true));
EXPECT_CALL(*stream2, HasPendingRetransmission()).WillOnce(Return(true));
session_->OnFrameLost(QuicFrame(frame3));
session_->OnFrameLost(QuicFrame(frame2));
session_->OnFrameLost(QuicFrame(frame1));
session_->MarkConnectionLevelWriteBlocked(stream2->id());
session_->MarkConnectionLevelWriteBlocked(stream4->id());
session_->MarkConnectionLevelWriteBlocked(stream6->id());
EXPECT_CALL(*connection_, SendControlFrame(_));
EXPECT_CALL(*connection_, OnStreamReset(stream4->id(), _));
stream4->Reset(QUIC_STREAM_CANCELLED);
EXPECT_CALL(*stream6, OnCanWrite());
EXPECT_CALL(*stream6, HasPendingRetransmission()).WillOnce(Return(false));
EXPECT_CALL(*stream2, OnCanWrite());
EXPECT_CALL(*stream2, HasPendingRetransmission()).WillOnce(Return(false));
EXPECT_CALL(*connection_, SendControlFrame(_))
.WillRepeatedly(Invoke(&ClearControlFrame));
EXPECT_CALL(*stream2, OnCanWrite());
EXPECT_CALL(*stream6, OnCanWrite());
session_->OnCanWrite();
}
TEST_P(QuicSpdySessionTestServer, RetransmitFrames) {
Initialize();
CompleteHandshake();
MockSendAlgorithm* send_algorithm = new StrictMock<MockSendAlgorithm>;
QuicConnectionPeer::SetSendAlgorithm(session_->connection(), send_algorithm);
InSequence s;
TestStream* stream2 = session_->CreateOutgoingBidirectionalStream();
TestStream* stream4 = session_->CreateOutgoingBidirectionalStream();
TestStream* stream6 = session_->CreateOutgoingBidirectionalStream();
EXPECT_CALL(*connection_, SendControlFrame(_))
.WillOnce(Invoke(&ClearControlFrame));
session_->SendWindowUpdate(stream2->id(), 9);
QuicStreamFrame frame1(stream2->id(), false, 0, 9);
QuicStreamFrame frame2(stream4->id(), false, 0, 9);
QuicStreamFrame frame3(stream6->id(), false, 0, 9);
QuicWindowUpdateFrame window_update(1, stream2->id(), 9);
QuicFrames frames;
frames.push_back(QuicFrame(frame1));
frames.push_back(QuicFrame(window_update));
frames.push_back(QuicFrame(frame2));
frames.push_back(QuicFrame(frame3));
EXPECT_FALSE(session_->WillingAndAbleToWrite());
EXPECT_CALL(*stream2, RetransmitStreamData(_, _, _, _))
.WillOnce(Return(true));
EXPECT_CALL(*connection_, SendControlFrame(_))
.WillOnce(Invoke(&ClearControlFrame));
EXPECT_CALL(*stream4, RetransmitStreamData(_, _, _, _))
.WillOnce(Return(true));
EXPECT_CALL(*stream6, RetransmitStreamData(_, _, _, _))
.WillOnce(Return(true));
EXPECT_CALL(*send_algorithm, OnApplicationLimited(_));
session_->RetransmitFrames(frames, PTO_RETRANSMISSION);
}
TEST_P(QuicSpdySessionTestServer, OnPriorityFrame) {
Initialize();
QuicStreamId stream_id = GetNthClientInitiatedBidirectionalId(0);
TestStream* stream = session_->CreateIncomingStream(stream_id);
session_->OnPriorityFrame(stream_id,
spdy::SpdyStreamPrecedence(kV3HighestPriority));
EXPECT_EQ((QuicStreamPriority(HttpStreamPriority{
kV3HighestPriority, HttpStreamPriority::kDefaultIncremental})),
stream->priority());
}
TEST_P(QuicSpdySessionTestServer, OnPriorityUpdateFrame) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
EXPECT_CALL(debug_visitor, OnSettingsFrameSent(_));
CompleteHandshake();
QuicStreamId receive_control_stream_id =
GetNthClientInitiatedUnidirectionalStreamId(transport_version(), 3);
char type[] = {kControlStream};
absl::string_view stream_type(type, 1);
QuicStreamOffset offset = 0;
QuicStreamFrame data1(receive_control_stream_id, false, offset, stream_type);
offset += stream_type.length();
EXPECT_CALL(debug_visitor,
OnPeerControlStreamCreated(receive_control_stream_id));
session_->OnStreamFrame(data1);
EXPECT_EQ(receive_control_stream_id,
QuicSpdySessionPeer::GetReceiveControlStream(&*session_)->id());
std::string serialized_settings = HttpEncoder::SerializeSettingsFrame({});
QuicStreamFrame data2(receive_control_stream_id, false, offset,
serialized_settings);
offset += serialized_settings.length();
EXPECT_CALL(debug_visitor, OnSettingsFrameReceived(_));
session_->OnStreamFrame(data2);
const QuicStreamId stream_id1 = GetNthClientInitiatedBidirectionalId(0);
PriorityUpdateFrame priority_update1{stream_id1, "u=2"};
std::string serialized_priority_update1 =
HttpEncoder::SerializePriorityUpdateFrame(priority_update1);
QuicStreamFrame data3(receive_control_stream_id,
false, offset, serialized_priority_update1);
offset += serialized_priority_update1.size();
TestStream* stream1 = session_->CreateIncomingStream(stream_id1);
EXPECT_EQ(QuicStreamPriority(
HttpStreamPriority{HttpStreamPriority::kDefaultUrgency,
HttpStreamPriority::kDefaultIncremental}),
stream1->priority());
EXPECT_CALL(debug_visitor, OnPriorityUpdateFrameReceived(priority_update1));
session_->OnStreamFrame(data3);
EXPECT_EQ(QuicStreamPriority(HttpStreamPriority{
2u, HttpStreamPriority::kDefaultIncremental}),
stream1->priority());
const QuicStreamId stream_id2 = GetNthClientInitiatedBidirectionalId(1);
PriorityUpdateFrame priority_update2{stream_id2, "u=5, i"};
std::string serialized_priority_update2 =
HttpEncoder::SerializePriorityUpdateFrame(priority_update2);
QuicStreamFrame stream_frame3(receive_control_stream_id,
false, offset,
serialized_priority_update2);
EXPECT_CALL(debug_visitor, OnPriorityUpdateFrameReceived(priority_update2));
session_->OnStreamFrame(stream_frame3);
TestStream* stream2 = session_->CreateIncomingStream(stream_id2);
EXPECT_EQ(QuicStreamPriority(HttpStreamPriority{5u, true}),
stream2->priority());
}
TEST_P(QuicSpdySessionTestServer, OnInvalidPriorityUpdateFrame) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
QuicStreamId receive_control_stream_id =
GetNthClientInitiatedUnidirectionalStreamId(transport_version(), 3);
char type[] = {kControlStream};
absl::string_view stream_type(type, 1);
QuicStreamOffset offset = 0;
QuicStreamFrame data1(receive_control_stream_id, false, offset, stream_type);
offset += stream_type.length();
EXPECT_CALL(debug_visitor,
OnPeerControlStreamCreated(receive_control_stream_id));
session_->OnStreamFrame(data1);
EXPECT_EQ(receive_control_stream_id,
QuicSpdySessionPeer::GetReceiveControlStream(&*session_)->id());
std::string serialized_settings = HttpEncoder::SerializeSettingsFrame({});
QuicStreamFrame data2(receive_control_stream_id, false, offset,
serialized_settings);
offset += serialized_settings.length();
EXPECT_CALL(debug_visitor, OnSettingsFrameReceived(_));
session_->OnStreamFrame(data2);
const QuicStreamId stream_id = GetNthClientInitiatedBidirectionalId(0);
PriorityUpdateFrame priority_update{stream_id, "00"};
EXPECT_CALL(debug_visitor, OnPriorityUpdateFrameReceived(priority_update));
EXPECT_CALL(*connection_,
CloseConnection(QUIC_INVALID_PRIORITY_UPDATE,
"Invalid PRIORITY_UPDATE frame payload.", _));
std::string serialized_priority_update =
HttpEncoder::SerializePriorityUpdateFrame(priority_update);
QuicStreamFrame data3(receive_control_stream_id,
false, offset, serialized_priority_update);
session_->OnStreamFrame(data3);
}
TEST_P(QuicSpdySessionTestServer, OnPriorityUpdateFrameOutOfBoundsUrgency) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
QuicStreamId receive_control_stream_id =
GetNthClientInitiatedUnidirectionalStreamId(transport_version(), 3);
char type[] = {kControlStream};
absl::string_view stream_type(type, 1);
QuicStreamOffset offset = 0;
QuicStreamFrame data1(receive_control_stream_id, false, offset, stream_type);
offset += stream_type.length();
EXPECT_CALL(debug_visitor,
OnPeerControlStreamCreated(receive_control_stream_id));
session_->OnStreamFrame(data1);
EXPECT_EQ(receive_control_stream_id,
QuicSpdySessionPeer::GetReceiveControlStream(&*session_)->id());
std::string serialized_settings = HttpEncoder::SerializeSettingsFrame({});
QuicStreamFrame data2(receive_control_stream_id, false, offset,
serialized_settings);
offset += serialized_settings.length();
EXPECT_CALL(debug_visitor, OnSettingsFrameReceived(_));
session_->OnStreamFrame(data2);
const QuicStreamId stream_id = GetNthClientInitiatedBidirectionalId(0);
PriorityUpdateFrame priority_update{stream_id, "u=9"};
EXPECT_CALL(debug_visitor, OnPriorityUpdateFrameReceived(priority_update));
EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0);
std::string serialized_priority_update =
HttpEncoder::SerializePriorityUpdateFrame(priority_update);
QuicStreamFrame data3(receive_control_stream_id,
false, offset, serialized_priority_update);
session_->OnStreamFrame(data3);
}
TEST_P(QuicSpdySessionTestServer, SimplePendingStreamType) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
char input[] = {0x04,
'a', 'b', 'c'};
absl::string_view payload(input, ABSL_ARRAYSIZE(input));
QuicStreamId stream_id = QuicUtils::GetFirstUnidirectionalStreamId(
transport_version(), Perspective::IS_CLIENT);
for (bool fin : {true, false}) {
QuicStreamFrame frame(stream_id, fin, 0, payload);
EXPECT_CALL(*connection_, SendControlFrame(_))
.WillOnce(Invoke([stream_id](const QuicFrame& frame) {
EXPECT_EQ(STOP_SENDING_FRAME, frame.type);
const QuicStopSendingFrame& stop_sending = frame.stop_sending_frame;
EXPECT_EQ(stream_id, stop_sending.stream_id);
EXPECT_EQ(QUIC_STREAM_STREAM_CREATION_ERROR, stop_sending.error_code);
EXPECT_EQ(
static_cast<uint64_t>(QuicHttp3ErrorCode::STREAM_CREATION_ERROR),
stop_sending.ietf_error_code);
return ClearControlFrame(frame);
}));
session_->OnStreamFrame(frame);
PendingStream* pending =
QuicSessionPeer::GetPendingStream(&*session_, stream_id);
if (fin) {
EXPECT_FALSE(pending);
} else {
ASSERT_TRUE(pending);
EXPECT_TRUE(pending->sequencer()->ignore_read_data());
}
stream_id += QuicUtils::StreamIdDelta(transport_version());
}
}
TEST_P(QuicSpdySessionTestServer, SimplePendingStreamTypeOutOfOrderDelivery) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
char input[] = {0x04,
'a', 'b', 'c'};
absl::string_view payload(input, ABSL_ARRAYSIZE(input));
QuicStreamId stream_id = QuicUtils::GetFirstUnidirectionalStreamId(
transport_version(), Perspective::IS_CLIENT);
for (bool fin : {true, false}) {
QuicStreamFrame frame1(stream_id, false, 0,
payload.substr(0, 1));
QuicStreamFrame frame2(stream_id, fin, 1, payload.substr(1));
session_->OnStreamFrame(frame2);
EXPECT_CALL(*connection_, SendControlFrame(_))
.WillOnce(Invoke(&VerifyAndClearStopSendingFrame));
session_->OnStreamFrame(frame1);
PendingStream* pending =
QuicSessionPeer::GetPendingStream(&*session_, stream_id);
if (fin) {
EXPECT_FALSE(pending);
} else {
ASSERT_TRUE(pending);
EXPECT_TRUE(pending->sequencer()->ignore_read_data());
}
stream_id += QuicUtils::StreamIdDelta(transport_version());
}
}
TEST_P(QuicSpdySessionTestServer,
MultipleBytesPendingStreamTypeOutOfOrderDelivery) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
char input[] = {0x41, 0x00,
'a', 'b', 'c'};
absl::string_view payload(input, ABSL_ARRAYSIZE(input));
QuicStreamId stream_id = QuicUtils::GetFirstUnidirectionalStreamId(
transport_version(), Perspective::IS_CLIENT);
for (bool fin : {true, false}) {
QuicStreamFrame frame1(stream_id, false, 0,
payload.substr(0, 1));
QuicStreamFrame frame2(stream_id, false, 1,
payload.substr(1, 1));
QuicStreamFrame frame3(stream_id, fin, 2, payload.substr(2));
session_->OnStreamFrame(frame3);
session_->OnStreamFrame(frame1);
EXPECT_CALL(*connection_, SendControlFrame(_))
.WillOnce(Invoke(&VerifyAndClearStopSendingFrame));
session_->OnStreamFrame(frame2);
PendingStream* pending =
QuicSessionPeer::GetPendingStream(&*session_, stream_id);
if (fin) {
EXPECT_FALSE(pending);
} else {
ASSERT_TRUE(pending);
EXPECT_TRUE(pending->sequencer()->ignore_read_data());
}
stream_id += QuicUtils::StreamIdDelta(transport_version());
}
}
TEST_P(QuicSpdySessionTestServer, ReceiveControlStream) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
QuicStreamId stream_id =
GetNthClientInitiatedUnidirectionalStreamId(transport_version(), 3);
char type[] = {kControlStream};
QuicStreamFrame data1(stream_id, false, 0, absl::string_view(type, 1));
EXPECT_CALL(debug_visitor, OnPeerControlStreamCreated(stream_id));
session_->OnStreamFrame(data1);
EXPECT_EQ(stream_id,
QuicSpdySessionPeer::GetReceiveControlStream(&*session_)->id());
SettingsFrame settings;
settings.values[SETTINGS_QPACK_MAX_TABLE_CAPACITY] = 512;
settings.values[SETTINGS_MAX_FIELD_SECTION_SIZE] = 5;
settings.values[SETTINGS_QPACK_BLOCKED_STREAMS] = 42;
std::string data = HttpEncoder::SerializeSettingsFrame(settings);
QuicStreamFrame frame(stream_id, false, 1, data);
QpackEncoder* qpack_encoder = session_->qpack_encoder();
QpackEncoderHeaderTable* header_table =
QpackEncoderPeer::header_table(qpack_encoder);
EXPECT_NE(512u, header_table->maximum_dynamic_table_capacity());
EXPECT_NE(5u, session_->max_outbound_header_list_size());
EXPECT_NE(42u, QpackEncoderPeer::maximum_blocked_streams(qpack_encoder));
EXPECT_CALL(debug_visitor, OnSettingsFrameReceived(settings));
session_->OnStreamFrame(frame);
EXPECT_EQ(512u, header_table->maximum_dynamic_table_capacity());
EXPECT_EQ(5u, session_->max_outbound_header_list_size());
EXPECT_EQ(42u, QpackEncoderPeer::maximum_blocked_streams(qpack_encoder));
}
TEST_P(QuicSpdySessionTestServer, ServerDisableQpackDynamicTable) {
SetQuicFlag(quic_server_disable_qpack_dynamic_table, true);
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
QuicStreamId stream_id =
GetNthClientInitiatedUnidirectionalStreamId(transport_version(), 3);
char type[] = {kControlStream};
QuicStreamFrame data1(stream_id, false, 0, absl::string_view(type, 1));
session_->OnStreamFrame(data1);
EXPECT_EQ(stream_id,
QuicSpdySessionPeer::GetReceiveControlStream(&*session_)->id());
const uint64_t capacity = 512;
SettingsFrame settings;
settings.values[SETTINGS_QPACK_MAX_TABLE_CAPACITY] = capacity;
std::string data = HttpEncoder::SerializeSettingsFrame(settings);
QuicStreamFrame frame(stream_id, false, 1, data);
session_->OnStreamFrame(frame);
QpackEncoder* qpack_encoder = session_->qpack_encoder();
EXPECT_EQ(capacity, qpack_encoder->MaximumDynamicTableCapacity());
QpackEncoderHeaderTable* encoder_header_table =
QpackEncoderPeer::header_table(qpack_encoder);
EXPECT_EQ(capacity, encoder_header_table->maximum_dynamic_table_capacity());
EXPECT_EQ(0, encoder_header_table->dynamic_table_capacity());
SettingsFrame outgoing_settings = session_->settings();
EXPECT_EQ(0, outgoing_settings.values[SETTINGS_QPACK_MAX_TABLE_CAPACITY]);
}
TEST_P(QuicSpdySessionTestServer, DisableQpackDynamicTable) {
SetQuicFlag(quic_server_disable_qpack_dynamic_table, false);
qpack_maximum_dynamic_table_capacity_ = 0;
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
QuicStreamId stream_id =
GetNthClientInitiatedUnidirectionalStreamId(transport_version(), 3);
char type[] = {kControlStream};
QuicStreamFrame data1(stream_id, false, 0, absl::string_view(type, 1));
session_->OnStreamFrame(data1);
EXPECT_EQ(stream_id,
QuicSpdySessionPeer::GetReceiveControlStream(&*session_)->id());
const uint64_t capacity = 512;
SettingsFrame settings;
settings.values[SETTINGS_QPACK_MAX_TABLE_CAPACITY] = capacity;
std::string data = HttpEncoder::SerializeSettingsFrame(settings);
QuicStreamFrame frame(stream_id, false, 1, data);
session_->OnStreamFrame(frame);
QpackEncoder* qpack_encoder = session_->qpack_encoder();
EXPECT_EQ(capacity, qpack_encoder->MaximumDynamicTableCapacity());
QpackEncoderHeaderTable* encoder_header_table =
QpackEncoderPeer::header_table(qpack_encoder);
EXPECT_EQ(capacity, encoder_header_table->maximum_dynamic_table_capacity());
EXPECT_EQ(0, encoder_header_table->dynamic_table_capacity());
SettingsFrame outgoing_settings = session_->settings();
EXPECT_EQ(0, outgoing_settings.values[SETTINGS_QPACK_MAX_TABLE_CAPACITY]);
}
TEST_P(QuicSpdySessionTestServer, ReceiveControlStreamOutOfOrderDelivery) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
QuicStreamId stream_id =
GetNthClientInitiatedUnidirectionalStreamId(transport_version(), 3);
char type[] = {kControlStream};
SettingsFrame settings;
settings.values[10] = 2;
settings.values[SETTINGS_MAX_FIELD_SECTION_SIZE] = 5;
std::string data = HttpEncoder::SerializeSettingsFrame(settings);
QuicStreamFrame data1(stream_id, false, 1, data);
QuicStreamFrame data2(stream_id, false, 0, absl::string_view(type, 1));
session_->OnStreamFrame(data1);
EXPECT_NE(5u, session_->max_outbound_header_list_size());
session_->OnStreamFrame(data2);
EXPECT_EQ(5u, session_->max_outbound_header_list_size());
}
TEST_P(QuicSpdySessionTestServer, StreamClosedWhileHeaderDecodingBlocked) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
session_->qpack_decoder()->OnSetDynamicTableCapacity(1024);
QuicStreamId stream_id = GetNthClientInitiatedBidirectionalId(0);
TestStream* stream = session_->CreateIncomingStream(stream_id);
std::string headers_frame_payload;
ASSERT_TRUE(absl::HexStringToBytes("020080", &headers_frame_payload));
std::string headers_frame_header =
HttpEncoder::SerializeHeadersFrameHeader(headers_frame_payload.length());
std::string headers_frame =
absl::StrCat(headers_frame_header, headers_frame_payload);
stream->OnStreamFrame(QuicStreamFrame(stream_id, false, 0, headers_frame));
EXPECT_FALSE(stream->headers_decompressed());
CloseStream(stream_id);
session_->CleanUpClosedStreams();
session_->qpack_decoder()->OnInsertWithoutNameReference("foo", "bar");
}
TEST_P(QuicSpdySessionTestServer, SessionDestroyedWhileHeaderDecodingBlocked) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
session_->qpack_decoder()->OnSetDynamicTableCapacity(1024);
QuicStreamId stream_id = GetNthClientInitiatedBidirectionalId(0);
TestStream* stream = session_->CreateIncomingStream(stream_id);
std::string headers_frame_payload;
ASSERT_TRUE(absl::HexStringToBytes("020080", &headers_frame_payload));
std::string headers_frame_header =
HttpEncoder::SerializeHeadersFrameHeader(headers_frame_payload.length());
std::string headers_frame =
absl::StrCat(headers_frame_header, headers_frame_payload);
stream->OnStreamFrame(QuicStreamFrame(stream_id, false, 0, headers_frame));
EXPECT_FALSE(stream->headers_decompressed());
}
TEST_P(QuicSpdySessionTestClient, ResetAfterInvalidIncomingStreamType) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
const QuicStreamId stream_id =
GetNthServerInitiatedUnidirectionalStreamId(transport_version(), 0);
ASSERT_TRUE(session_->UsesPendingStreamForFrame(STREAM_FRAME, stream_id));
std::string payload;
ASSERT_TRUE(absl::HexStringToBytes("3f01", &payload));
QuicStreamFrame frame(stream_id, false, 0,
payload);
EXPECT_CALL(*connection_, SendControlFrame(_))
.WillOnce(Invoke(&VerifyAndClearStopSendingFrame));
session_->OnStreamFrame(frame);
EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(&*session_));
PendingStream* pending =
QuicSessionPeer::GetPendingStream(&*session_, stream_id);
ASSERT_TRUE(pending);
EXPECT_TRUE(pending->sequencer()->ignore_read_data());
session_->OnStreamFrame(frame);
QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream_id,
QUIC_STREAM_CANCELLED,
payload.size());
session_->OnRstStream(rst_frame);
EXPECT_FALSE(QuicSessionPeer::GetPendingStream(&*session_, stream_id));
}
TEST_P(QuicSpdySessionTestClient, FinAfterInvalidIncomingStreamType) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
const QuicStreamId stream_id =
GetNthServerInitiatedUnidirectionalStreamId(transport_version(), 0);
ASSERT_TRUE(session_->UsesPendingStreamForFrame(STREAM_FRAME, stream_id));
std::string payload;
ASSERT_TRUE(absl::HexStringToBytes("3f01", &payload));
QuicStreamFrame frame(stream_id, false, 0,
payload);
EXPECT_CALL(*connection_, SendControlFrame(_))
.WillOnce(Invoke(&VerifyAndClearStopSendingFrame));
session_->OnStreamFrame(frame);
PendingStream* pending =
QuicSessionPeer::GetPendingStream(&*session_, stream_id);
EXPECT_TRUE(pending);
EXPECT_TRUE(pending->sequencer()->ignore_read_data());
session_->OnStreamFrame(frame);
session_->OnStreamFrame(QuicStreamFrame(stream_id, true,
payload.size(), ""));
EXPECT_FALSE(QuicSessionPeer::GetPendingStream(&*session_, stream_id));
}
TEST_P(QuicSpdySessionTestClient, ResetInMiddleOfStreamType) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
const QuicStreamId stream_id =
GetNthServerInitiatedUnidirectionalStreamId(transport_version(), 0);
ASSERT_TRUE(session_->UsesPendingStreamForFrame(STREAM_FRAME, stream_id));
std::string payload;
ASSERT_TRUE(absl::HexStringToBytes("40", &payload));
QuicStreamFrame frame(stream_id, false, 0,
payload);
session_->OnStreamFrame(frame);
EXPECT_TRUE(QuicSessionPeer::GetPendingStream(&*session_, stream_id));
QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream_id,
QUIC_STREAM_CANCELLED,
payload.size());
session_->OnRstStream(rst_frame);
EXPECT_FALSE(QuicSessionPeer::GetPendingStream(&*session_, stream_id));
}
TEST_P(QuicSpdySessionTestClient, FinInMiddleOfStreamType) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
const QuicStreamId stream_id =
GetNthServerInitiatedUnidirectionalStreamId(transport_version(), 0);
ASSERT_TRUE(session_->UsesPendingStreamForFrame(STREAM_FRAME, stream_id));
std::string payload;
ASSERT_TRUE(absl::HexStringToBytes("40", &payload));
QuicStreamFrame frame(stream_id, true, 0, payload);
session_->OnStreamFrame(frame);
EXPECT_FALSE(QuicSessionPeer::GetPendingStream(&*session_, stream_id));
}
TEST_P(QuicSpdySessionTestClient, DuplicateHttp3UnidirectionalStreams) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
QuicStreamId id1 =
GetNthServerInitiatedUnidirectionalStreamId(transport_version(), 0);
char type1[] = {kControlStream};
QuicStreamFrame data1(id1, false, 0, absl::string_view(type1, 1));
EXPECT_CALL(debug_visitor, OnPeerControlStreamCreated(id1));
session_->OnStreamFrame(data1);
QuicStreamId id2 =
GetNthServerInitiatedUnidirectionalStreamId(transport_version(), 1);
QuicStreamFrame data2(id2, false, 0, absl::string_view(type1, 1));
EXPECT_CALL(debug_visitor, OnPeerControlStreamCreated(id2)).Times(0);
EXPECT_QUIC_PEER_BUG(
{
EXPECT_CALL(*connection_,
CloseConnection(QUIC_HTTP_DUPLICATE_UNIDIRECTIONAL_STREAM,
"Control stream is received twice.", _));
session_->OnStreamFrame(data2);
},
"Received a duplicate Control stream: Closing connection.");
QuicStreamId id3 =
GetNthServerInitiatedUnidirectionalStreamId(transport_version(), 2);
char type2[]{kQpackEncoderStream};
QuicStreamFrame data3(id3, false, 0, absl::string_view(type2, 1));
EXPECT_CALL(debug_visitor, OnPeerQpackEncoderStreamCreated(id3));
session_->OnStreamFrame(data3);
QuicStreamId id4 =
GetNthServerInitiatedUnidirectionalStreamId(transport_version(), 3);
QuicStreamFrame data4(id4, false, 0, absl::string_view(type2, 1));
EXPECT_CALL(debug_visitor, OnPeerQpackEncoderStreamCreated(id4)).Times(0);
EXPECT_QUIC_PEER_BUG(
{
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_HTTP_DUPLICATE_UNIDIRECTIONAL_STREAM,
"QPACK encoder stream is received twice.", _));
session_->OnStreamFrame(data4);
},
"Received a duplicate QPACK encoder stream: Closing connection.");
QuicStreamId id5 =
GetNthServerInitiatedUnidirectionalStreamId(transport_version(), 4);
char type3[]{kQpackDecoderStream};
QuicStreamFrame data5(id5, false, 0, absl::string_view(type3, 1));
EXPECT_CALL(debug_visitor, OnPeerQpackDecoderStreamCreated(id5));
session_->OnStreamFrame(data5);
QuicStreamId id6 =
GetNthServerInitiatedUnidirectionalStreamId(transport_version(), 5);
QuicStreamFrame data6(id6, false, 0, absl::string_view(type3, 1));
EXPECT_CALL(debug_visitor, OnPeerQpackDecoderStreamCreated(id6)).Times(0);
EXPECT_QUIC_PEER_BUG(
{
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_HTTP_DUPLICATE_UNIDIRECTIONAL_STREAM,
"QPACK decoder stream is received twice.", _));
session_->OnStreamFrame(data6);
},
"Received a duplicate QPACK decoder stream: Closing connection.");
}
TEST_P(QuicSpdySessionTestClient, EncoderStreamError) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
std::string data;
ASSERT_TRUE(
absl::HexStringToBytes("02"
"00",
&data));
QuicStreamId stream_id =
GetNthServerInitiatedUnidirectionalStreamId(transport_version(), 0);
QuicStreamFrame frame(stream_id, false, 0, data);
EXPECT_CALL(*connection_,
CloseConnection(
QUIC_QPACK_ENCODER_STREAM_DUPLICATE_INVALID_RELATIVE_INDEX,
"Encoder stream error: Invalid relative index.", _));
session_->OnStreamFrame(frame);
}
TEST_P(QuicSpdySessionTestClient, DecoderStreamError) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
std::string data;
ASSERT_TRUE(absl::HexStringToBytes(
"03"
"00",
&data));
QuicStreamId stream_id =
GetNthServerInitiatedUnidirectionalStreamId(transport_version(), 0);
QuicStreamFrame frame(stream_id, false, 0, data);
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_QPACK_DECODER_STREAM_INVALID_ZERO_INCREMENT,
"Decoder stream error: Invalid increment value 0.", _));
session_->OnStreamFrame(frame);
}
TEST_P(QuicSpdySessionTestClient, InvalidHttp3GoAway) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
EXPECT_CALL(*connection_,
CloseConnection(QUIC_HTTP_GOAWAY_INVALID_STREAM_ID,
"GOAWAY with invalid stream ID", _));
QuicStreamId stream_id =
GetNthServerInitiatedUnidirectionalStreamId(transport_version(), 0);
session_->OnHttp3GoAway(stream_id);
}
TEST_P(QuicSpdySessionTestClient, Http3GoAwayLargerIdThanBefore) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
EXPECT_FALSE(session_->goaway_received());
QuicStreamId stream_id1 =
GetNthClientInitiatedBidirectionalStreamId(transport_version(), 0);
session_->OnHttp3GoAway(stream_id1);
EXPECT_TRUE(session_->goaway_received());
EXPECT_CALL(
*connection_,
CloseConnection(
QUIC_HTTP_GOAWAY_ID_LARGER_THAN_PREVIOUS,
"GOAWAY received with ID 4 greater than previously received ID 0",
_));
QuicStreamId stream_id2 =
GetNthClientInitiatedBidirectionalStreamId(transport_version(), 1);
session_->OnHttp3GoAway(stream_id2);
}
TEST_P(QuicSpdySessionTestClient, CloseConnectionOnCancelPush) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
QuicStreamId receive_control_stream_id =
GetNthServerInitiatedUnidirectionalStreamId(transport_version(), 3);
char type[] = {kControlStream};
absl::string_view stream_type(type, 1);
QuicStreamOffset offset = 0;
QuicStreamFrame data1(receive_control_stream_id, false, offset,
stream_type);
offset += stream_type.length();
EXPECT_CALL(debug_visitor,
OnPeerControlStreamCreated(receive_control_stream_id));
session_->OnStreamFrame(data1);
EXPECT_EQ(receive_control_stream_id,
QuicSpdySessionPeer::GetReceiveControlStream(&*session_)->id());
std::string serialized_settings = HttpEncoder::SerializeSettingsFrame({});
QuicStreamFrame data2(receive_control_stream_id, false, offset,
serialized_settings);
offset += serialized_settings.length();
EXPECT_CALL(debug_visitor, OnSettingsFrameReceived(_));
session_->OnStreamFrame(data2);
std::string cancel_push_frame;
ASSERT_TRUE(
absl::HexStringToBytes("03"
"01"
"00",
&cancel_push_frame));
QuicStreamFrame data3(receive_control_stream_id, false, offset,
cancel_push_frame);
EXPECT_CALL(*connection_, CloseConnection(QUIC_HTTP_FRAME_ERROR,
"CANCEL_PUSH frame received.", _))
.WillOnce(
Invoke(connection_, &MockQuicConnection::ReallyCloseConnection));
EXPECT_CALL(*connection_,
SendConnectionClosePacket(QUIC_HTTP_FRAME_ERROR, _,
"CANCEL_PUSH frame received."));
session_->OnStreamFrame(data3);
}
TEST_P(QuicSpdySessionTestServer, OnSetting) {
Initialize();
CompleteHandshake();
if (VersionUsesHttp3(transport_version())) {
EXPECT_EQ(std::numeric_limits<size_t>::max(),
session_->max_outbound_header_list_size());
session_->OnSetting(SETTINGS_MAX_FIELD_SECTION_SIZE, 5);
EXPECT_EQ(5u, session_->max_outbound_header_list_size());
EXPECT_CALL(*writer_, WritePacket(_, _, _, _, _, _))
.WillRepeatedly(Return(WriteResult(WRITE_STATUS_OK, 0)));
QpackEncoder* qpack_encoder = session_->qpack_encoder();
EXPECT_EQ(0u, QpackEncoderPeer::maximum_blocked_streams(qpack_encoder));
session_->OnSetting(SETTINGS_QPACK_BLOCKED_STREAMS, 12);
EXPECT_EQ(12u, QpackEncoderPeer::maximum_blocked_streams(qpack_encoder));
QpackEncoderHeaderTable* header_table =
QpackEncoderPeer::header_table(qpack_encoder);
EXPECT_EQ(0u, header_table->maximum_dynamic_table_capacity());
session_->OnSetting(SETTINGS_QPACK_MAX_TABLE_CAPACITY, 37);
EXPECT_EQ(37u, header_table->maximum_dynamic_table_capacity());
return;
}
EXPECT_EQ(std::numeric_limits<size_t>::max(),
session_->max_outbound_header_list_size());
session_->OnSetting(SETTINGS_MAX_FIELD_SECTION_SIZE, 5);
EXPECT_EQ(5u, session_->max_outbound_header_list_size());
spdy::HpackEncoder* hpack_encoder =
QuicSpdySessionPeer::GetSpdyFramer(&*session_)->GetHpackEncoder();
EXPECT_EQ(4096u, hpack_encoder->CurrentHeaderTableSizeSetting());
session_->OnSetting(spdy::SETTINGS_HEADER_TABLE_SIZE, 59);
EXPECT_EQ(59u, hpack_encoder->CurrentHeaderTableSizeSetting());
}
TEST_P(QuicSpdySessionTestServer, FineGrainedHpackErrorCodes) {
Initialize();
if (VersionUsesHttp3(transport_version())) {
return;
}
QuicStreamId request_stream_id = 5;
session_->CreateIncomingStream(request_stream_id);
std::string headers_frame;
ASSERT_TRUE(
absl::HexStringToBytes("000006"
"01"
"24"
"00000005"
"00000000"
"10"
"fe",
&headers_frame));
QuicStreamId headers_stream_id =
QuicUtils::GetHeadersStreamId(transport_version());
QuicStreamFrame data(headers_stream_id, false, 0, headers_frame);
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_HPACK_INVALID_INDEX,
"SPDY framing error: HPACK_INVALID_INDEX",
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET));
session_->OnStreamFrame(data);
}
TEST_P(QuicSpdySessionTestServer, PeerClosesCriticalReceiveStream) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
struct {
char type;
const char* error_details;
} kTestData[] = {
{kControlStream, "RESET_STREAM received for receive control stream"},
{kQpackEncoderStream, "RESET_STREAM received for QPACK receive stream"},
{kQpackDecoderStream, "RESET_STREAM received for QPACK receive stream"},
};
for (size_t i = 0; i < ABSL_ARRAYSIZE(kTestData); ++i) {
QuicStreamId stream_id =
GetNthClientInitiatedUnidirectionalStreamId(transport_version(), i + 1);
const QuicByteCount data_length = 1;
QuicStreamFrame data(stream_id, false, 0,
absl::string_view(&kTestData[i].type, data_length));
session_->OnStreamFrame(data);
EXPECT_CALL(*connection_, CloseConnection(QUIC_HTTP_CLOSED_CRITICAL_STREAM,
kTestData[i].error_details, _));
QuicRstStreamFrame rst(kInvalidControlFrameId, stream_id,
QUIC_STREAM_CANCELLED, data_length);
session_->OnRstStream(rst);
}
}
TEST_P(QuicSpdySessionTestServer,
H3ControlStreamsLimitedByConnectionFlowControl) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
QuicFlowControllerPeer::SetSendWindowOffset(session_->flow_controller(), 0);
EXPECT_TRUE(session_->IsConnectionFlowControlBlocked());
QuicSendControlStream* send_control_stream =
QuicSpdySessionPeer::GetSendControlStream(&*session_);
session_->MarkConnectionLevelWriteBlocked(send_control_stream->id());
EXPECT_FALSE(session_->WillingAndAbleToWrite());
}
TEST_P(QuicSpdySessionTestServer, PeerClosesCriticalSendStream) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
QuicSendControlStream* control_stream =
QuicSpdySessionPeer::GetSendControlStream(&*session_);
ASSERT_TRUE(control_stream);
QuicStopSendingFrame stop_sending_control_stream(
kInvalidControlFrameId, control_stream->id(), QUIC_STREAM_CANCELLED);
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_HTTP_CLOSED_CRITICAL_STREAM,
"STOP_SENDING received for send control stream", _));
session_->OnStopSendingFrame(stop_sending_control_stream);
QpackSendStream* decoder_stream =
QuicSpdySessionPeer::GetQpackDecoderSendStream(&*session_);
ASSERT_TRUE(decoder_stream);
QuicStopSendingFrame stop_sending_decoder_stream(
kInvalidControlFrameId, decoder_stream->id(), QUIC_STREAM_CANCELLED);
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_HTTP_CLOSED_CRITICAL_STREAM,
"STOP_SENDING received for QPACK send stream", _));
session_->OnStopSendingFrame(stop_sending_decoder_stream);
QpackSendStream* encoder_stream =
QuicSpdySessionPeer::GetQpackEncoderSendStream(&*session_);
ASSERT_TRUE(encoder_stream);
QuicStopSendingFrame stop_sending_encoder_stream(
kInvalidControlFrameId, encoder_stream->id(), QUIC_STREAM_CANCELLED);
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_HTTP_CLOSED_CRITICAL_STREAM,
"STOP_SENDING received for QPACK send stream", _));
session_->OnStopSendingFrame(stop_sending_encoder_stream);
}
TEST_P(QuicSpdySessionTestServer, CloseConnectionOnCancelPush) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
QuicStreamId receive_control_stream_id =
GetNthClientInitiatedUnidirectionalStreamId(transport_version(), 3);
char type[] = {kControlStream};
absl::string_view stream_type(type, 1);
QuicStreamOffset offset = 0;
QuicStreamFrame data1(receive_control_stream_id, false, offset,
stream_type);
offset += stream_type.length();
EXPECT_CALL(debug_visitor,
OnPeerControlStreamCreated(receive_control_stream_id));
session_->OnStreamFrame(data1);
EXPECT_EQ(receive_control_stream_id,
QuicSpdySessionPeer::GetReceiveControlStream(&*session_)->id());
std::string serialized_settings = HttpEncoder::SerializeSettingsFrame({});
QuicStreamFrame data2(receive_control_stream_id, false, offset,
serialized_settings);
offset += serialized_settings.length();
EXPECT_CALL(debug_visitor, OnSettingsFrameReceived(_));
session_->OnStreamFrame(data2);
std::string cancel_push_frame;
ASSERT_TRUE(
absl::HexStringToBytes("03"
"01"
"00",
&cancel_push_frame));
QuicStreamFrame data3(receive_control_stream_id, false, offset,
cancel_push_frame);
EXPECT_CALL(*connection_, CloseConnection(QUIC_HTTP_FRAME_ERROR,
"CANCEL_PUSH frame received.", _))
.WillOnce(
Invoke(connection_, &MockQuicConnection::ReallyCloseConnection));
EXPECT_CALL(*connection_,
SendConnectionClosePacket(QUIC_HTTP_FRAME_ERROR, _,
"CANCEL_PUSH frame received."));
session_->OnStreamFrame(data3);
}
TEST_P(QuicSpdySessionTestServer, Http3GoAwayWhenClosingConnection) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
EXPECT_CALL(debug_visitor, OnSettingsFrameSent(_));
CompleteHandshake();
QuicStreamId stream_id = GetNthClientInitiatedBidirectionalId(0);
const QuicByteCount headers_payload_length = 10;
std::string headers_frame_header =
HttpEncoder::SerializeHeadersFrameHeader(headers_payload_length);
EXPECT_CALL(debug_visitor,
OnHeadersFrameReceived(stream_id, headers_payload_length));
session_->OnStreamFrame(
QuicStreamFrame(stream_id, false, 0, headers_frame_header));
EXPECT_EQ(stream_id, QuicSessionPeer::GetLargestPeerCreatedStreamId(
&*session_, false));
EXPECT_CALL(debug_visitor,
OnGoAwayFrameSent(stream_id +
QuicUtils::StreamIdDelta(transport_version())));
EXPECT_CALL(*writer_, WritePacket(_, _, _, _, _, _))
.WillRepeatedly(Return(WriteResult(WRITE_STATUS_OK, 0)));
EXPECT_CALL(*connection_, CloseConnection(QUIC_NO_ERROR, _, _))
.WillOnce(
Invoke(connection_, &MockQuicConnection::ReallyCloseConnection));
EXPECT_CALL(*connection_, SendConnectionClosePacket(QUIC_NO_ERROR, _, _))
.WillOnce(Invoke(connection_,
&MockQuicConnection::ReallySendConnectionClosePacket));
connection_->CloseConnection(
QUIC_NO_ERROR, "closing connection",
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
}
TEST_P(QuicSpdySessionTestClient, DoNotSendInitialMaxPushIdIfNotSet) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
InSequence s;
EXPECT_CALL(debug_visitor, OnSettingsFrameSent(_));
CompleteHandshake();
}
TEST_P(QuicSpdySessionTestClient, ReceiveSpdySettingInHttp3) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
SettingsFrame frame;
frame.values[SETTINGS_MAX_FIELD_SECTION_SIZE] = 5;
frame.values[spdy::SETTINGS_INITIAL_WINDOW_SIZE] = 100;
CompleteHandshake();
EXPECT_CALL(*connection_,
CloseConnection(QUIC_HTTP_RECEIVE_SPDY_SETTING, _, _));
session_->OnSettingsFrame(frame);
}
TEST_P(QuicSpdySessionTestClient, ReceiveAcceptChFrame) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
QuicStreamId receive_control_stream_id =
GetNthServerInitiatedUnidirectionalStreamId(transport_version(), 3);
char type[] = {kControlStream};
absl::string_view stream_type(type, 1);
QuicStreamOffset offset = 0;
QuicStreamFrame data1(receive_control_stream_id, false, offset,
stream_type);
offset += stream_type.length();
EXPECT_CALL(debug_visitor,
OnPeerControlStreamCreated(receive_control_stream_id));
session_->OnStreamFrame(data1);
EXPECT_EQ(receive_control_stream_id,
QuicSpdySessionPeer::GetReceiveControlStream(&*session_)->id());
std::string serialized_settings = HttpEncoder::SerializeSettingsFrame({});
QuicStreamFrame data2(receive_control_stream_id, false, offset,
serialized_settings);
offset += serialized_settings.length();
EXPECT_CALL(debug_visitor, OnSettingsFrameReceived(_));
session_->OnStreamFrame(data2);
AcceptChFrame accept_ch;
accept_ch.entries.push_back({"foo", "bar"});
std::string accept_ch_frame = HttpEncoder::SerializeAcceptChFrame(accept_ch);
QuicStreamFrame data3(receive_control_stream_id, false, offset,
accept_ch_frame);
EXPECT_CALL(debug_visitor, OnAcceptChFrameReceived(accept_ch));
EXPECT_CALL(*session_, OnAcceptChFrame(accept_ch));
session_->OnStreamFrame(data3);
}
TEST_P(QuicSpdySessionTestClient, AcceptChViaAlps) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
std::string serialized_accept_ch_frame;
ASSERT_TRUE(
absl::HexStringToBytes("4089"
"08"
"03"
"666f6f"
"03"
"626172",
&serialized_accept_ch_frame));
AcceptChFrame expected_accept_ch_frame{{{"foo", "bar"}}};
EXPECT_CALL(debug_visitor,
OnAcceptChFrameReceivedViaAlps(expected_accept_ch_frame));
auto error = session_->OnAlpsData(
reinterpret_cast<const uint8_t*>(serialized_accept_ch_frame.data()),
serialized_accept_ch_frame.size());
EXPECT_FALSE(error);
}
TEST_P(QuicSpdySessionTestClient, AlpsForbiddenFrame) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
std::string forbidden_frame;
ASSERT_TRUE(
absl::HexStringToBytes("00"
"03"
"66666f",
&forbidden_frame));
auto error = session_->OnAlpsData(
reinterpret_cast<const uint8_t*>(forbidden_frame.data()),
forbidden_frame.size());
ASSERT_TRUE(error);
EXPECT_EQ("DATA frame forbidden", error.value());
}
TEST_P(QuicSpdySessionTestClient, AlpsIncompleteFrame) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
std::string incomplete_frame;
ASSERT_TRUE(
absl::HexStringToBytes("04"
"03",
&incomplete_frame));
auto error = session_->OnAlpsData(
reinterpret_cast<const uint8_t*>(incomplete_frame.data()),
incomplete_frame.size());
ASSERT_TRUE(error);
EXPECT_EQ("incomplete HTTP/3 frame", error.value());
}
TEST_P(QuicSpdySessionTestClient, SettingsViaAlpsThenOnControlStream) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
QpackEncoder* qpack_encoder = session_->qpack_encoder();
EXPECT_EQ(0u, qpack_encoder->MaximumDynamicTableCapacity());
EXPECT_EQ(0u, qpack_encoder->maximum_blocked_streams());
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
std::string serialized_settings_frame1;
ASSERT_TRUE(
absl::HexStringToBytes("04"
"05"
"01"
"4400"
"07"
"20",
&serialized_settings_frame1));
SettingsFrame expected_settings_frame1{
{{SETTINGS_QPACK_MAX_TABLE_CAPACITY, 1024},
{SETTINGS_QPACK_BLOCKED_STREAMS, 32}}};
EXPECT_CALL(debug_visitor,
OnSettingsFrameReceivedViaAlps(expected_settings_frame1));
auto error = session_->OnAlpsData(
reinterpret_cast<const uint8_t*>(serialized_settings_frame1.data()),
serialized_settings_frame1.size());
EXPECT_FALSE(error);
EXPECT_EQ(1024u, qpack_encoder->MaximumDynamicTableCapacity());
EXPECT_EQ(32u, qpack_encoder->maximum_blocked_streams());
const QuicStreamId control_stream_id =
GetNthServerInitiatedUnidirectionalStreamId(transport_version(), 0);
EXPECT_CALL(debug_visitor, OnPeerControlStreamCreated(control_stream_id));
std::string stream_type;
ASSERT_TRUE(absl::HexStringToBytes("00", &stream_type));
session_->OnStreamFrame(QuicStreamFrame(control_stream_id, false,
0, stream_type));
SettingsFrame expected_settings_frame2{
{{SETTINGS_QPACK_MAX_TABLE_CAPACITY, 1024},
{SETTINGS_QPACK_BLOCKED_STREAMS, 48}}};
EXPECT_CALL(debug_visitor, OnSettingsFrameReceived(expected_settings_frame2));
std::string serialized_settings_frame2;
ASSERT_TRUE(
absl::HexStringToBytes("04"
"05"
"01"
"4400"
"07"
"30",
&serialized_settings_frame2));
session_->OnStreamFrame(QuicStreamFrame(control_stream_id, false,
stream_type.length(),
serialized_settings_frame2));
EXPECT_EQ(1024u, qpack_encoder->MaximumDynamicTableCapacity());
EXPECT_EQ(48u, qpack_encoder->maximum_blocked_streams());
}
TEST_P(QuicSpdySessionTestClient,
SettingsViaAlpsConflictsSettingsViaControlStream) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
CompleteHandshake();
QpackEncoder* qpack_encoder = session_->qpack_encoder();
EXPECT_EQ(0u, qpack_encoder->MaximumDynamicTableCapacity());
std::string serialized_settings_frame1;
ASSERT_TRUE(
absl::HexStringToBytes("04"
"03"
"01"
"4400",
&serialized_settings_frame1));
auto error = session_->OnAlpsData(
reinterpret_cast<const uint8_t*>(serialized_settings_frame1.data()),
serialized_settings_frame1.size());
EXPECT_FALSE(error);
EXPECT_EQ(1024u, qpack_encoder->MaximumDynamicTableCapacity());
const QuicStreamId control_stream_id =
GetNthServerInitiatedUnidirectionalStreamId(transport_version(), 0);
std::string stream_type;
ASSERT_TRUE(absl::HexStringToBytes("00", &stream_type));
session_->OnStreamFrame(QuicStreamFrame(control_stream_id, false,
0, stream_type));
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_HTTP_ZERO_RTT_RESUMPTION_SETTINGS_MISMATCH,
"Server sent an SETTINGS_QPACK_MAX_TABLE_CAPACITY: "
"32 while current value is: 1024",
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET));
std::string serialized_settings_frame2;
ASSERT_TRUE(
absl::HexStringToBytes("04"
"02"
"01"
"20",
&serialized_settings_frame2));
session_->OnStreamFrame(QuicStreamFrame(control_stream_id, false,
stream_type.length(),
serialized_settings_frame2));
}
TEST_P(QuicSpdySessionTestClient, AlpsTwoSettingsFrame) {
Initialize();
if (!VersionUsesHttp3(transport_version())) {
return;
}
std::string banned_frame;
ASSERT_TRUE(
absl::HexStringToBytes("04"
"00"
"04"
"00",
&banned_frame));
auto error = session_->OnAlpsData(
reinterpret_cast<const uint8_t*>(banned_frame.data()),
banned_frame.size());
ASSERT_TRUE(error);
EXPECT_EQ("multiple SETTINGS frames", error.value());
}
void QuicSpdySessionTestBase::TestHttpDatagramSetting(
HttpDatagramSupport local_support, HttpDatagramSupport remote_support,
HttpDatagramSupport expected_support, bool expected_datagram_supported) {
if (!version().UsesHttp3()) {
return;
}
CompleteHandshake();
session_->set_local_http_datagram_support(local_support);
EXPECT_FALSE(session_->SupportsH3Datagram());
EXPECT_EQ(session_->http_datagram_support(), HttpDatagramSupport::kNone);
SettingsFrame settings;
switch (remote_support) {
case HttpDatagramSupport::kNone:
break;
case HttpDatagramSupport::kDraft04:
settings.values[SETTINGS_H3_DATAGRAM_DRAFT04] = 1;
break;
case HttpDatagramSupport::kRfc:
settings.values[SETTINGS_H3_DATAGRAM] = 1;
break;
case HttpDatagramSupport::kRfcAndDraft04:
settings.values[SETTINGS_H3_DATAGRAM] = 1;
settings.values[SETTINGS_H3_DATAGRAM_DRAFT04] = 1;
break;
}
std::string data = std::string(1, kControlStream) +
HttpEncoder::SerializeSettingsFrame(settings);
QuicStreamId stream_id =
GetNthServerInitiatedUnidirectionalStreamId(transport_version(), 3);
QuicStreamFrame frame(stream_id, false, 0, data);
StrictMock<MockHttp3DebugVisitor> debug_visitor;
session_->set_debug_visitor(&debug_visitor);
EXPECT_CALL(debug_visitor, OnPeerControlStreamCreated(stream_id));
EXPECT_CALL(debug_visitor, OnSettingsFrameReceived(settings));
session_->OnStreamFrame(frame);
EXPECT_EQ(session_->http_datagram_support(), expected_support);
EXPECT_EQ(session_->SupportsH3Datagram(), expected_datagram_supported);
}
TEST_P(QuicSpdySessionTestClient, HttpDatagramSettingLocal04Remote04) {
Initialize();
TestHttpDatagramSetting(
HttpDatagramSupport::kDraft04,
HttpDatagramSupport::kDraft04,
HttpDatagramSupport::kDraft04,
true);
}
TEST_P(QuicSpdySessionTestClient, HttpDatagramSettingLocal04Remote09) {
Initialize();
TestHttpDatagramSetting(
HttpDatagramSupport::kDraft04,
HttpDatagramSupport::kRfc,
HttpDatagramSupport::kNone,
false);
}
TEST_P(QuicSpdySessionTestClient, HttpDatagramSettingLocal04Remote04And09) {
Initialize();
TestHttpDatagramSetting(
HttpDatagramSupport::kDraft04,
HttpDatagramSupport::kRfcAndDraft04,
HttpDatagramSupport::kDraft04,
true);
}
TEST_P(QuicSpdySessionTestClient, HttpDatagramSettingLocal09Remote04) {
Initialize();
TestHttpDatagramSetting(
HttpDatagramSupport::kRfc,
HttpDatagramSupport::kDraft04,
HttpDatagramSupport::kNone,
false);
}
TEST_P(QuicSpdySessionTestClient, HttpDatagramSettingLocal09Remote09) {
Initialize();
TestHttpDatagramSetting(
HttpDatagramSupport::kRfc,
HttpDatagramSupport::kRfc,
HttpDatagramSupport::kRfc,
true);
}
TEST_P(QuicSpdySessionTestClient, HttpDatagramSettingLocal09Remote04And09) {
Initialize();
TestHttpDatagramSetting(
HttpDatagramSupport::kRfc,
HttpDatagramSupport::kRfcAndDraft04,
HttpDatagramSupport::kRfc,
true);
}
TEST_P(QuicSpdySessionTestClient, HttpDatagramSettingLocal04And09Remote04) {
Initialize();
TestHttpDatagramSetting(
HttpDatagramSupport::kRfcAndDraft04,
HttpDatagramSupport::kDraft04,
HttpDatagramSupport::kDraft04,
true);
}
TEST_P(QuicSpdySessionTestClient, HttpDatagramSettingLocal04And09Remote09) {
Initialize();
TestHttpDatagramSetting(
HttpDatagramSupport::kRfcAndDraft04,
HttpDatagramSupport::kRfc,
HttpDatagramSupport::kRfc,
true);
}
TEST_P(QuicSpdySessionTestClient,
HttpDatagramSettingLocal04And09Remote04And09) {
Initialize();
TestHttpDatagramSetting(
HttpDatagramSupport::kRfcAndDraft04,
HttpDatagramSupport::kRfcAndDraft04,
HttpDatagramSupport::kRfc,
true);
}
TEST_P(QuicSpdySessionTestClient, WebTransportSettingDraft02OnlyBothSides) {
Initialize();
if (!version().UsesHttp3()) {
return;
}
session_->set_local_http_datagram_support(
HttpDatagramSupport::kRfcAndDraft04);
session_->set_locally_supported_web_transport_versions(
WebTransportHttp3VersionSet({WebTransportHttp3Version::kDraft02}));
EXPECT_FALSE(session_->SupportsWebTransport());
CompleteHandshake();
ReceiveWebTransportSettings(
WebTransportHttp3VersionSet({WebTransportHttp3Version::kDraft02}));
EXPECT_TRUE(session_->ShouldProcessIncomingRequests());
EXPECT_TRUE(session_->SupportsWebTransport());
EXPECT_EQ(session_->SupportedWebTransportVersion(),
WebTransportHttp3Version::kDraft02);
}
TEST_P(QuicSpdySessionTestClient, WebTransportSettingDraft07OnlyBothSides) {
Initialize();
if (!version().UsesHttp3()) {
return;
}
session_->set_local_http_datagram_support(
HttpDatagramSupport::kRfcAndDraft04);
session_->set_locally_supported_web_transport_versions(
WebTransportHttp3VersionSet({WebTransportHttp3Version::kDraft07}));
EXPECT_FALSE(session_->SupportsWebTransport());
CompleteHandshake();
ReceiveWebTransportSettings(
WebTransportHttp3VersionSet({WebTransportHttp3Version::kDraft07}));
EXPECT_TRUE(session_->ShouldProcessIncomingRequests());
EXPECT_TRUE(session_->SupportsWebTransport());
EXPECT_EQ(session_->SupportedWebTransportVersion(),
WebTransportHttp3Version::kDraft07);
}
TEST_P(QuicSpdySessionTestClient, WebTransportSettingBothDraftsBothSides) {
Initialize();
if (!version().UsesHttp3()) {
return;
}
session_->set_local_http_datagram_support(
HttpDatagramSupport::kRfcAndDraft04);
session_->set_locally_supported_web_transport_versions(
WebTransportHttp3VersionSet({WebTransportHttp3Version::kDraft02,
WebTransportHttp3Version::kDraft07}));
EXPECT_FALSE(session_->SupportsWebTransport());
CompleteHandshake();
ReceiveWebTransportSettings(
WebTransportHttp3VersionSet({WebTransportHttp3Version::kDraft02,
WebTransportHttp3Version::kDraft07}));
EXPECT_TRUE(session_->ShouldProcessIncomingRequests());
EXPECT_TRUE(session_->SupportsWebTransport());
EXPECT_EQ(session_->SupportedWebTransportVersion(),
WebTransportHttp3Version::kDraft07);
}
TEST_P(QuicSpdySessionTestClient, WebTransportSettingVersionMismatch) {
Initialize();
if (!version().UsesHttp3()) {
return;
}
session_->set_local_http_datagram_support(
HttpDatagramSupport::kRfcAndDraft04);
session_->set_locally_supported_web_transport_versions(
WebTransportHttp3VersionSet({WebTransportHttp3Version::kDraft07}));
EXPECT_FALSE(session_->SupportsWebTransport());
CompleteHandshake();
ReceiveWebTransportSettings(
WebTransportHttp3VersionSet({WebTransportHttp3Version::kDraft02}));
EXPECT_FALSE(session_->SupportsWebTransport());
EXPECT_EQ(session_->SupportedWebTransportVersion(), std::nullopt);
}
TEST_P(QuicSpdySessionTestClient, WebTransportSettingSetToZero) {
Initialize();
if (!version().UsesHttp3()) {
return;
}
session_->set_local_http_datagram_support(
HttpDatagramSupport::kRfcAndDraft04);
session_->set_supports_webtransport(true);
EXPECT_FALSE(session_->SupportsWebTransport());
StrictMock<MockHttp3DebugVisitor> debug_visitor;
EXPECT_CALL(debug_visitor, OnSettingsFrameSent(_));
session_->set_debug_visitor(&debug_visitor);
CompleteHandshake();
SettingsFrame server_settings;
server_settings.values[SETTINGS_H3_DATAGRAM_DRAFT04] = 1;
server_settings.values[SETTINGS_WEBTRANS_DRAFT00] = 0;
std::string data = std::string(1, kControlStream) +
HttpEncoder::SerializeSettingsFrame(server_settings);
QuicStreamId stream_id =
GetNthServerInitiatedUnidirectionalStreamId(transport_version(), 3);
QuicStreamFrame frame(stream_id, false, 0, data);
EXPECT_CALL(debug_visitor, OnPeerControlStreamCreated(stream_id));
EXPECT_CALL(debug_visitor, OnSettingsFrameReceived(server_settings));
session_->OnStreamFrame(frame);
EXPECT_FALSE(session_->SupportsWebTransport());
}
TEST_P(QuicSpdySessionTestServer, WebTransportSetting) {
Initialize();
if (!version().UsesHttp3()) {
return;
}
session_->set_local_http_datagram_support(
HttpDatagramSupport::kRfcAndDraft04);
session_->set_supports_webtransport(true);
EXPECT_FALSE(session_->SupportsWebTransport());
EXPECT_FALSE(session_->ShouldProcessIncomingRequests());
CompleteHandshake();
ReceiveWebTransportSettings();
EXPECT_TRUE(session_->SupportsWebTransport());
EXPECT_TRUE(session_->ShouldProcessIncomingRequests());
}
TEST_P(QuicSpdySessionTestServer, BufferingIncomingStreams) {
Initialize();
if (!version().UsesHttp3()) {
return;
}
session_->set_local_http_datagram_support(
HttpDatagramSupport::kRfcAndDraft04);
session_->set_supports_webtransport(true);
CompleteHandshake();
QuicStreamId session_id =
GetNthClientInitiatedBidirectionalStreamId(transport_version(), 1);
QuicStreamId data_stream_id =
GetNthClientInitiatedUnidirectionalStreamId(transport_version(), 4);
ReceiveWebTransportUnidirectionalStream(session_id, data_stream_id);
ReceiveWebTransportSettings();
ReceiveWebTransportSession(session_id);
WebTransportHttp3* web_transport =
session_->GetWebTransportSession(session_id);
ASSERT_TRUE(web_transport != nullptr);
EXPECT_EQ(web_transport->NumberOfAssociatedStreams(), 1u);
EXPECT_CALL(*connection_, SendControlFrame(_))
.WillRepeatedly(Invoke(&ClearControlFrame));
EXPECT_CALL(*connection_, OnStreamReset(session_id, _));
EXPECT_CALL(
*connection_,
OnStreamReset(data_stream_id, QUIC_STREAM_WEBTRANSPORT_SESSION_GONE));
session_->ResetStream(session_id, QUIC_STREAM_INTERNAL_ERROR);
}
TEST_P(QuicSpdySessionTestServer, BufferingIncomingStreamsLimit) {
Initialize();
if (!version().UsesHttp3()) {
return;
}
session_->set_local_http_datagram_support(
HttpDatagramSupport::kRfcAndDraft04);
session_->set_supports_webtransport(true);
CompleteHandshake();
QuicStreamId session_id =
GetNthClientInitiatedBidirectionalStreamId(transport_version(), 1);
const int streams_to_send = kMaxUnassociatedWebTransportStreams + 4;
EXPECT_CALL(*connection_, SendControlFrame(_))
.WillRepeatedly(Invoke(&ClearControlFrame));
EXPECT_CALL(*connection_,
OnStreamReset(
_, QUIC_STREAM_WEBTRANSPORT_BUFFERED_STREAMS_LIMIT_EXCEEDED))
.Times(4);
for (int i = 0; i < streams_to_send; i++) {
QuicStreamId data_stream_id =
GetNthClientInitiatedUnidirectionalStreamId(transport_version(), 4 + i);
ReceiveWebTransportUnidirectionalStream(session_id, data_stream_id);
}
ReceiveWebTransportSettings();
ReceiveWebTransportSession(session_id);
WebTransportHttp3* web_transport =
session_->GetWebTransportSession(session_id);
ASSERT_TRUE(web_transport != nullptr);
EXPECT_EQ(web_transport->NumberOfAssociatedStreams(),
kMaxUnassociatedWebTransportStreams);
EXPECT_CALL(*connection_, SendControlFrame(_))
.WillRepeatedly(Invoke(&ClearControlFrame));
EXPECT_CALL(*connection_, OnStreamReset(_, _))
.Times(kMaxUnassociatedWebTransportStreams + 1);
session_->ResetStream(session_id, QUIC_STREAM_INTERNAL_ERROR);
}
TEST_P(QuicSpdySessionTestServer, BufferingIncomingStreamsWithFin) {
Initialize();
if (!version().UsesHttp3()) {
return;
}
CompleteHandshake();
const UberQuicStreamIdManager& stream_id_manager =
*QuicSessionPeer::ietf_streamid_manager(&*session_);
const QuicStreamId initial_advertized_max_streams =
stream_id_manager.advertised_max_incoming_unidirectional_streams();
const size_t num_streams_to_open =
session_->max_open_incoming_unidirectional_streams();
EXPECT_CALL(*connection_, SendControlFrame(_)).Times(testing::AnyNumber());
for (size_t i = 0; i < num_streams_to_open; i++) {
const QuicStreamId stream_id =
GetNthClientInitiatedUnidirectionalStreamId(transport_version(), 4 + i);
QuicStreamFrame frame(stream_id, true, 0, "");
session_->OnStreamFrame(frame);
}
EXPECT_LT(initial_advertized_max_streams,
stream_id_manager.advertised_max_incoming_unidirectional_streams());
EXPECT_EQ(0, session_->pending_streams_size());
}
TEST_P(QuicSpdySessionTestServer, ResetOutgoingWebTransportStreams) {
Initialize();
if (!version().UsesHttp3()) {
return;
}
session_->set_local_http_datagram_support(
HttpDatagramSupport::kRfcAndDraft04);
session_->set_supports_webtransport(true);
CompleteHandshake();
QuicStreamId session_id =
GetNthClientInitiatedBidirectionalStreamId(transport_version(), 1);
ReceiveWebTransportSettings();
ReceiveWebTransportSession(session_id);
WebTransportHttp3* web_transport =
session_->GetWebTransportSession(session_id);
ASSERT_TRUE(web_transport != nullptr);
session_->set_writev_consumes_all_data(true);
EXPECT_TRUE(web_transport->CanOpenNextOutgoingUnidirectionalStream());
EXPECT_EQ(web_transport->NumberOfAssociatedStreams(), 0u);
WebTransportStream* stream =
web_transport->OpenOutgoingUnidirectionalStream();
EXPECT_EQ(web_transport->NumberOfAssociatedStreams(), 1u);
ASSERT_TRUE(stream != nullptr);
QuicStreamId stream_id = stream->GetStreamId();
EXPECT_CALL(*connection_, SendControlFrame(_))
.WillRepeatedly(Invoke(&ClearControlFrame));
EXPECT_CALL(*connection_, OnStreamReset(session_id, _));
EXPECT_CALL(*connection_,
OnStreamReset(stream_id, QUIC_STREAM_WEBTRANSPORT_SESSION_GONE));
session_->ResetStream(session_id, QUIC_STREAM_INTERNAL_ERROR);
EXPECT_EQ(web_transport->NumberOfAssociatedStreams(), 0u);
}
TEST_P(QuicSpdySessionTestClient, WebTransportWithoutExtendedConnect) {
Initialize();
if (!version().UsesHttp3()) {
return;
}
SetQuicReloadableFlag(quic_act_upon_invalid_header, true);
session_->set_local_http_datagram_support(
HttpDatagramSupport::kRfcAndDraft04);
session_->set_supports_webtransport(true);
EXPECT_FALSE(session_->SupportsWebTransport());
CompleteHandshake();
SettingsFrame settings;
settings.values[SETTINGS_H3_DATAGRAM_DRAFT04] = 1;
settings.values[SETTINGS_WEBTRANS_DRAFT00] = 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);
EXPECT_TRUE(session_->SupportsWebTransport());
}
TEST_P(QuicSpdySessionTestClient, LimitEncoderDynamicTableSize) {
Initialize();
if (version().UsesHttp3()) {
return;
}
CompleteHandshake();
QuicSpdySessionPeer::SetHeadersStream(&*session_, nullptr);
TestHeadersStream* headers_stream =
new StrictMock<TestHeadersStream>(&*session_);
QuicSpdySessionPeer::SetHeadersStream(&*session_, headers_stream);
session_->MarkConnectionLevelWriteBlocked(headers_stream->id());
session_->OnSetting(spdy::SETTINGS_HEADER_TABLE_SIZE, 1024 * 1024 * 1024);
TestStream* stream = session_->CreateOutgoingBidirectionalStream();
EXPECT_CALL(*writer_, IsWriteBlocked()).WillRepeatedly(Return(true));
HttpHeaderBlock headers;
headers[":method"] = "GET";
stream->WriteHeaders(std::move(headers), true, nullptr);
EXPECT_TRUE(headers_stream->HasBufferedData());
QuicStreamSendBuffer& send_buffer =
QuicStreamPeer::SendBuffer(headers_stream);
ASSERT_EQ(1u, send_buffer.size());
const quiche::QuicheMemSlice& slice =
QuicStreamSendBufferPeer::CurrentWriteSlice(&send_buffer)->slice;
absl::string_view stream_data(slice.data(), slice.length());
std::string expected_stream_data_1;
ASSERT_TRUE(
absl::HexStringToBytes("000009"
"01"
"25",
&expected_stream_data_1));
EXPECT_EQ(expected_stream_data_1, stream_data.substr(0, 5));
stream_data.remove_prefix(5);
stream_data.remove_prefix(4);
std::string expected_stream_data_2;
ASSERT_TRUE(
absl::HexStringToBytes("00000000"
"92",
&expected_stream_data_2));
EXPECT_EQ(expected_stream_data_2, stream_data.substr(0, 5));
stream_data.remove_prefix(5);
std::string expected_stream_data_3;
ASSERT_TRUE(absl::HexStringToBytes(
"3fe17f"
"82",
&expected_stream_data_3));
EXPECT_EQ(expected_stream_data_3, stream_data);
}
class QuicSpdySessionTestServerNoExtendedConnect
: public QuicSpdySessionTestBase {
public:
QuicSpdySessionTestServerNoExtendedConnect()
: QuicSpdySessionTestBase(Perspective::IS_SERVER, false) {}
};
INSTANTIATE_TEST_SUITE_P(Tests, QuicSpdySessionTestServerNoExtendedConnect,
::testing::ValuesIn(AllSupportedVersions()),
::testing::PrintToStringParamName());
TEST_P(QuicSpdySessionTestServerNoExtendedConnect,
WebTransportSettingNoEffect) {
Initialize();
if (!version().UsesHttp3()) {
return;
}
EXPECT_FALSE(session_->SupportsWebTransport());
EXPECT_TRUE(session_->ShouldProcessIncomingRequests());
CompleteHandshake();
ReceiveWebTransportSettings();
EXPECT_FALSE(session_->allow_extended_connect());
EXPECT_FALSE(session_->SupportsWebTransport());
EXPECT_TRUE(session_->ShouldProcessIncomingRequests());
}
TEST_P(QuicSpdySessionTestServerNoExtendedConnect, BadExtendedConnectSetting) {
Initialize();
if (!version().UsesHttp3()) {
return;
}
SetQuicReloadableFlag(quic_act_upon_invalid_header, true);
EXPECT_FALSE(session_->SupportsWebTransport());
EXPECT_TRUE(session_->ShouldProcessIncomingRequests());
CompleteHandshake();
SettingsFrame settings;
settings.values[SETTINGS_ENABLE_CONNECT_PROTOCOL] = 2;
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);
EXPECT_QUIC_PEER_BUG(
{
EXPECT_CALL(*connection_,
CloseConnection(QUIC_HTTP_INVALID_SETTING_VALUE, _, _));
session_->OnStreamFrame(frame);
},
"Received SETTINGS_ENABLE_CONNECT_PROTOCOL with invalid value");
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/quic_spdy_session.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/http/quic_spdy_session_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
958a6d63-f8ba-40c9-a13d-4ece1b593b74 | cpp | google/quiche | qpack_encoder_stream_receiver | quiche/quic/core/qpack/qpack_encoder_stream_receiver.cc | quiche/quic/core/qpack/qpack_encoder_stream_receiver_test.cc | #include "quiche/quic/core/qpack/qpack_encoder_stream_receiver.h"
#include "absl/strings/string_view.h"
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/quic/core/qpack/qpack_instructions.h"
#include "quiche/quic/platform/api/quic_logging.h"
namespace quic {
QpackEncoderStreamReceiver::QpackEncoderStreamReceiver(Delegate* delegate)
: instruction_decoder_(QpackEncoderStreamLanguage(), this),
delegate_(delegate),
error_detected_(false) {
QUICHE_DCHECK(delegate_);
}
void QpackEncoderStreamReceiver::Decode(absl::string_view data) {
if (data.empty() || error_detected_) {
return;
}
instruction_decoder_.Decode(data);
}
bool QpackEncoderStreamReceiver::OnInstructionDecoded(
const QpackInstruction* instruction) {
if (instruction == InsertWithNameReferenceInstruction()) {
delegate_->OnInsertWithNameReference(instruction_decoder_.s_bit(),
instruction_decoder_.varint(),
instruction_decoder_.value());
return true;
}
if (instruction == InsertWithoutNameReferenceInstruction()) {
delegate_->OnInsertWithoutNameReference(instruction_decoder_.name(),
instruction_decoder_.value());
return true;
}
if (instruction == DuplicateInstruction()) {
delegate_->OnDuplicate(instruction_decoder_.varint());
return true;
}
QUICHE_DCHECK_EQ(instruction, SetDynamicTableCapacityInstruction());
delegate_->OnSetDynamicTableCapacity(instruction_decoder_.varint());
return true;
}
void QpackEncoderStreamReceiver::OnInstructionDecodingError(
QpackInstructionDecoder::ErrorCode error_code,
absl::string_view error_message) {
QUICHE_DCHECK(!error_detected_);
error_detected_ = true;
QuicErrorCode quic_error_code;
switch (error_code) {
case QpackInstructionDecoder::ErrorCode::INTEGER_TOO_LARGE:
quic_error_code = QUIC_QPACK_ENCODER_STREAM_INTEGER_TOO_LARGE;
break;
case QpackInstructionDecoder::ErrorCode::STRING_LITERAL_TOO_LONG:
quic_error_code = QUIC_QPACK_ENCODER_STREAM_STRING_LITERAL_TOO_LONG;
break;
case QpackInstructionDecoder::ErrorCode::HUFFMAN_ENCODING_ERROR:
quic_error_code = QUIC_QPACK_ENCODER_STREAM_HUFFMAN_ENCODING_ERROR;
break;
default:
quic_error_code = QUIC_INTERNAL_ERROR;
}
delegate_->OnErrorDetected(quic_error_code, error_message);
}
} | #include "quiche/quic/core/qpack/qpack_encoder_stream_receiver.h"
#include <string>
#include "absl/strings/escaping.h"
#include "absl/strings/string_view.h"
#include "quiche/quic/platform/api/quic_test.h"
using testing::Eq;
using testing::StrictMock;
namespace quic {
namespace test {
namespace {
class MockDelegate : public QpackEncoderStreamReceiver::Delegate {
public:
~MockDelegate() override = default;
MOCK_METHOD(void, OnInsertWithNameReference,
(bool is_static, uint64_t name_index, absl::string_view value),
(override));
MOCK_METHOD(void, OnInsertWithoutNameReference,
(absl::string_view name, absl::string_view value), (override));
MOCK_METHOD(void, OnDuplicate, (uint64_t index), (override));
MOCK_METHOD(void, OnSetDynamicTableCapacity, (uint64_t capacity), (override));
MOCK_METHOD(void, OnErrorDetected,
(QuicErrorCode error_code, absl::string_view error_message),
(override));
};
class QpackEncoderStreamReceiverTest : public QuicTest {
protected:
QpackEncoderStreamReceiverTest() : stream_(&delegate_) {}
~QpackEncoderStreamReceiverTest() override = default;
void Decode(absl::string_view data) { stream_.Decode(data); }
StrictMock<MockDelegate>* delegate() { return &delegate_; }
private:
QpackEncoderStreamReceiver stream_;
StrictMock<MockDelegate> delegate_;
};
TEST_F(QpackEncoderStreamReceiverTest, InsertWithNameReference) {
EXPECT_CALL(*delegate(), OnInsertWithNameReference(true, 5, Eq("")));
EXPECT_CALL(*delegate(), OnInsertWithNameReference(true, 2, Eq("foo")));
EXPECT_CALL(*delegate(), OnInsertWithNameReference(false, 137, Eq("bar")));
EXPECT_CALL(*delegate(),
OnInsertWithNameReference(false, 42, Eq(std::string(127, 'Z'))));
std::string encoded_data;
ASSERT_TRUE(absl::HexStringToBytes(
"c500"
"c28294e7"
"bf4a03626172"
"aa7f005a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a"
"5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a"
"5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a"
"5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a",
&encoded_data));
Decode(encoded_data);
}
TEST_F(QpackEncoderStreamReceiverTest, InsertWithNameReferenceIndexTooLarge) {
EXPECT_CALL(*delegate(),
OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_INTEGER_TOO_LARGE,
Eq("Encoded integer too large.")));
std::string encoded_data;
ASSERT_TRUE(
absl::HexStringToBytes("bfffffffffffffffffffffff", &encoded_data));
Decode(encoded_data);
}
TEST_F(QpackEncoderStreamReceiverTest, InsertWithNameReferenceValueTooLong) {
EXPECT_CALL(*delegate(),
OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_INTEGER_TOO_LARGE,
Eq("Encoded integer too large.")));
std::string encoded_data;
ASSERT_TRUE(
absl::HexStringToBytes("c57fffffffffffffffffffff", &encoded_data));
Decode(encoded_data);
}
TEST_F(QpackEncoderStreamReceiverTest, InsertWithoutNameReference) {
EXPECT_CALL(*delegate(), OnInsertWithoutNameReference(Eq(""), Eq("")));
EXPECT_CALL(*delegate(), OnInsertWithoutNameReference(Eq("bar"), Eq("bar")));
EXPECT_CALL(*delegate(), OnInsertWithoutNameReference(Eq("foo"), Eq("foo")));
EXPECT_CALL(*delegate(),
OnInsertWithoutNameReference(Eq(std::string(31, 'Z')),
Eq(std::string(127, 'Z'))));
std::string encoded_data;
ASSERT_TRUE(absl::HexStringToBytes(
"4000"
"4362617203626172"
"6294e78294e7"
"5f005a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a7f005a"
"5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a"
"5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a"
"5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a"
"5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a",
&encoded_data));
Decode(encoded_data);
}
TEST_F(QpackEncoderStreamReceiverTest,
InsertWithoutNameReferenceNameTooLongForVarintDecoder) {
EXPECT_CALL(*delegate(),
OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_INTEGER_TOO_LARGE,
Eq("Encoded integer too large.")));
std::string encoded_data;
ASSERT_TRUE(absl::HexStringToBytes("5fffffffffffffffffffff", &encoded_data));
Decode(encoded_data);
}
TEST_F(QpackEncoderStreamReceiverTest,
InsertWithoutNameReferenceNameExceedsLimit) {
EXPECT_CALL(*delegate(),
OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_STRING_LITERAL_TOO_LONG,
Eq("String literal too long.")));
std::string encoded_data;
ASSERT_TRUE(absl::HexStringToBytes("5fffff7f", &encoded_data));
Decode(encoded_data);
}
TEST_F(QpackEncoderStreamReceiverTest,
InsertWithoutNameReferenceValueTooLongForVarintDecoder) {
EXPECT_CALL(*delegate(),
OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_INTEGER_TOO_LARGE,
Eq("Encoded integer too large.")));
std::string encoded_data;
ASSERT_TRUE(
absl::HexStringToBytes("436261727fffffffffffffffffffff", &encoded_data));
Decode(encoded_data);
}
TEST_F(QpackEncoderStreamReceiverTest,
InsertWithoutNameReferenceValueExceedsLimit) {
EXPECT_CALL(*delegate(),
OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_STRING_LITERAL_TOO_LONG,
Eq("String literal too long.")));
std::string encoded_data;
ASSERT_TRUE(absl::HexStringToBytes("436261727fffff7f", &encoded_data));
Decode(encoded_data);
}
TEST_F(QpackEncoderStreamReceiverTest, Duplicate) {
EXPECT_CALL(*delegate(), OnDuplicate(17));
EXPECT_CALL(*delegate(), OnDuplicate(500));
std::string encoded_data;
ASSERT_TRUE(absl::HexStringToBytes("111fd503", &encoded_data));
Decode(encoded_data);
}
TEST_F(QpackEncoderStreamReceiverTest, DuplicateIndexTooLarge) {
EXPECT_CALL(*delegate(),
OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_INTEGER_TOO_LARGE,
Eq("Encoded integer too large.")));
std::string encoded_data;
ASSERT_TRUE(absl::HexStringToBytes("1fffffffffffffffffffff", &encoded_data));
Decode(encoded_data);
}
TEST_F(QpackEncoderStreamReceiverTest, SetDynamicTableCapacity) {
EXPECT_CALL(*delegate(), OnSetDynamicTableCapacity(17));
EXPECT_CALL(*delegate(), OnSetDynamicTableCapacity(500));
std::string encoded_data;
ASSERT_TRUE(absl::HexStringToBytes("313fd503", &encoded_data));
Decode(encoded_data);
}
TEST_F(QpackEncoderStreamReceiverTest, SetDynamicTableCapacityTooLarge) {
EXPECT_CALL(*delegate(),
OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_INTEGER_TOO_LARGE,
Eq("Encoded integer too large.")));
std::string encoded_data;
ASSERT_TRUE(absl::HexStringToBytes("3fffffffffffffffffffff", &encoded_data));
Decode(encoded_data);
}
TEST_F(QpackEncoderStreamReceiverTest, InvalidHuffmanEncoding) {
EXPECT_CALL(*delegate(),
OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_HUFFMAN_ENCODING_ERROR,
Eq("Error in Huffman-encoded string.")));
std::string encoded_data;
ASSERT_TRUE(absl::HexStringToBytes("c281ff", &encoded_data));
Decode(encoded_data);
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_encoder_stream_receiver.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_encoder_stream_receiver_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
adeb99e1-0e4c-4bf7-a55d-129ccd6739eb | 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 | #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());
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_encoder_stream_sender.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_encoder_stream_sender_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
8cfd8b81-c908-4911-ac60-3c75d154cc47 | cpp | google/quiche | qpack_decoder | quiche/quic/core/qpack/qpack_decoder.cc | quiche/quic/core/qpack/qpack_decoder_test.cc | #include "quiche/quic/core/qpack/qpack_decoder.h"
#include <memory>
#include <utility>
#include "absl/strings/string_view.h"
#include "quiche/quic/core/qpack/qpack_index_conversions.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 {
QpackDecoder::QpackDecoder(
uint64_t maximum_dynamic_table_capacity, uint64_t maximum_blocked_streams,
EncoderStreamErrorDelegate* encoder_stream_error_delegate)
: encoder_stream_error_delegate_(encoder_stream_error_delegate),
encoder_stream_receiver_(this),
maximum_blocked_streams_(maximum_blocked_streams),
known_received_count_(0) {
QUICHE_DCHECK(encoder_stream_error_delegate_);
header_table_.SetMaximumDynamicTableCapacity(maximum_dynamic_table_capacity);
}
QpackDecoder::~QpackDecoder() {}
void QpackDecoder::OnStreamReset(QuicStreamId stream_id) {
if (header_table_.maximum_dynamic_table_capacity() > 0) {
decoder_stream_sender_.SendStreamCancellation(stream_id);
}
}
bool QpackDecoder::OnStreamBlocked(QuicStreamId stream_id) {
auto result = blocked_streams_.insert(stream_id);
QUICHE_DCHECK(result.second);
return blocked_streams_.size() <= maximum_blocked_streams_;
}
void QpackDecoder::OnStreamUnblocked(QuicStreamId stream_id) {
size_t result = blocked_streams_.erase(stream_id);
QUICHE_DCHECK_EQ(1u, result);
}
void QpackDecoder::OnDecodingCompleted(QuicStreamId stream_id,
uint64_t required_insert_count) {
if (required_insert_count > 0) {
decoder_stream_sender_.SendHeaderAcknowledgement(stream_id);
if (known_received_count_ < required_insert_count) {
known_received_count_ = required_insert_count;
}
}
if (known_received_count_ < header_table_.inserted_entry_count()) {
decoder_stream_sender_.SendInsertCountIncrement(
header_table_.inserted_entry_count() - known_received_count_);
known_received_count_ = header_table_.inserted_entry_count();
}
}
void QpackDecoder::OnInsertWithNameReference(bool is_static,
uint64_t name_index,
absl::string_view value) {
if (is_static) {
auto entry = header_table_.LookupEntry( true, name_index);
if (!entry) {
OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_INVALID_STATIC_ENTRY,
"Invalid static table entry.");
return;
}
if (!header_table_.EntryFitsDynamicTableCapacity(entry->name(), value)) {
OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_ERROR_INSERTING_STATIC,
"Error inserting entry with name reference.");
return;
}
header_table_.InsertEntry(entry->name(), value);
return;
}
uint64_t absolute_index;
if (!QpackEncoderStreamRelativeIndexToAbsoluteIndex(
name_index, header_table_.inserted_entry_count(), &absolute_index)) {
OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_INSERTION_INVALID_RELATIVE_INDEX,
"Invalid relative index.");
return;
}
const QpackEntry* entry =
header_table_.LookupEntry( false, absolute_index);
if (!entry) {
OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_INSERTION_DYNAMIC_ENTRY_NOT_FOUND,
"Dynamic table entry not found.");
return;
}
if (!header_table_.EntryFitsDynamicTableCapacity(entry->name(), value)) {
OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_ERROR_INSERTING_DYNAMIC,
"Error inserting entry with name reference.");
return;
}
header_table_.InsertEntry(entry->name(), value);
}
void QpackDecoder::OnInsertWithoutNameReference(absl::string_view name,
absl::string_view value) {
if (!header_table_.EntryFitsDynamicTableCapacity(name, value)) {
OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_ERROR_INSERTING_LITERAL,
"Error inserting literal entry.");
return;
}
header_table_.InsertEntry(name, value);
}
void QpackDecoder::OnDuplicate(uint64_t index) {
uint64_t absolute_index;
if (!QpackEncoderStreamRelativeIndexToAbsoluteIndex(
index, header_table_.inserted_entry_count(), &absolute_index)) {
OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_DUPLICATE_INVALID_RELATIVE_INDEX,
"Invalid relative index.");
return;
}
const QpackEntry* entry =
header_table_.LookupEntry( false, absolute_index);
if (!entry) {
OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_DUPLICATE_DYNAMIC_ENTRY_NOT_FOUND,
"Dynamic table entry not found.");
return;
}
if (!header_table_.EntryFitsDynamicTableCapacity(entry->name(),
entry->value())) {
OnErrorDetected(QUIC_INTERNAL_ERROR, "Error inserting duplicate entry.");
return;
}
header_table_.InsertEntry(entry->name(), entry->value());
}
void QpackDecoder::OnSetDynamicTableCapacity(uint64_t capacity) {
if (!header_table_.SetDynamicTableCapacity(capacity)) {
OnErrorDetected(QUIC_QPACK_ENCODER_STREAM_SET_DYNAMIC_TABLE_CAPACITY,
"Error updating dynamic table capacity.");
}
}
void QpackDecoder::OnErrorDetected(QuicErrorCode error_code,
absl::string_view error_message) {
encoder_stream_error_delegate_->OnEncoderStreamError(error_code,
error_message);
}
std::unique_ptr<QpackProgressiveDecoder> QpackDecoder::CreateProgressiveDecoder(
QuicStreamId stream_id,
QpackProgressiveDecoder::HeadersHandlerInterface* handler) {
return std::make_unique<QpackProgressiveDecoder>(stream_id, this, this,
&header_table_, handler);
}
void QpackDecoder::FlushDecoderStream() { decoder_stream_sender_.Flush(); }
} | #include "quiche/quic/core/qpack/qpack_decoder.h"
#include <algorithm>
#include <memory>
#include <string>
#include "absl/strings/escaping.h"
#include "absl/strings/string_view.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/qpack/qpack_decoder_test_utils.h"
#include "quiche/quic/test_tools/qpack/qpack_test_utils.h"
using ::testing::_;
using ::testing::Eq;
using ::testing::Invoke;
using ::testing::Mock;
using ::testing::Sequence;
using ::testing::StrictMock;
using ::testing::Values;
namespace quic {
namespace test {
namespace {
const char* const kHeaderAcknowledgement = "\x81";
const uint64_t kMaximumDynamicTableCapacity = 1024;
const uint64_t kMaximumBlockedStreams = 1;
class QpackDecoderTest : public QuicTestWithParam<FragmentMode> {
protected:
QpackDecoderTest()
: qpack_decoder_(kMaximumDynamicTableCapacity, kMaximumBlockedStreams,
&encoder_stream_error_delegate_),
fragment_mode_(GetParam()) {
qpack_decoder_.set_qpack_stream_sender_delegate(
&decoder_stream_sender_delegate_);
}
~QpackDecoderTest() override = default;
void SetUp() override {
ON_CALL(handler_, OnDecodingErrorDetected(_, _))
.WillByDefault(Invoke([this](QuicErrorCode ,
absl::string_view ) {
progressive_decoder_.reset();
}));
}
void DecodeEncoderStreamData(absl::string_view data) {
qpack_decoder_.encoder_stream_receiver()->Decode(data);
}
std::unique_ptr<QpackProgressiveDecoder> CreateProgressiveDecoder(
QuicStreamId stream_id) {
return qpack_decoder_.CreateProgressiveDecoder(stream_id, &handler_);
}
void FlushDecoderStream() { qpack_decoder_.FlushDecoderStream(); }
void StartDecoding() {
progressive_decoder_ = CreateProgressiveDecoder( 1);
}
void DecodeData(absl::string_view data) {
auto fragment_size_generator =
FragmentModeToFragmentSizeGenerator(fragment_mode_);
while (progressive_decoder_ && !data.empty()) {
size_t fragment_size = std::min(fragment_size_generator(), data.size());
progressive_decoder_->Decode(data.substr(0, fragment_size));
data = data.substr(fragment_size);
}
}
void EndDecoding() {
if (progressive_decoder_) {
progressive_decoder_->EndHeaderBlock();
}
}
void DecodeHeaderBlock(absl::string_view data) {
StartDecoding();
DecodeData(data);
EndDecoding();
}
StrictMock<MockEncoderStreamErrorDelegate> encoder_stream_error_delegate_;
StrictMock<MockQpackStreamSenderDelegate> decoder_stream_sender_delegate_;
StrictMock<MockHeadersHandler> handler_;
private:
QpackDecoder qpack_decoder_;
const FragmentMode fragment_mode_;
std::unique_ptr<QpackProgressiveDecoder> progressive_decoder_;
};
INSTANTIATE_TEST_SUITE_P(All, QpackDecoderTest,
Values(FragmentMode::kSingleChunk,
FragmentMode::kOctetByOctet));
TEST_P(QpackDecoderTest, NoPrefix) {
EXPECT_CALL(handler_,
OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Incomplete header data prefix.")));
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("00", &input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, InvalidPrefix) {
StartDecoding();
EXPECT_CALL(handler_,
OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Encoded integer too large.")));
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("ffffffffffffffffffffffffffff", &input));
DecodeData(input);
}
TEST_P(QpackDecoderTest, EmptyHeaderBlock) {
EXPECT_CALL(handler_, OnDecodingCompleted());
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("0000", &input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, LiteralEntryEmptyName) {
EXPECT_CALL(handler_, OnHeaderDecoded(Eq(""), Eq("foo")));
EXPECT_CALL(handler_, OnDecodingCompleted());
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("00002003666f6f", &input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, LiteralEntryEmptyValue) {
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("")));
EXPECT_CALL(handler_, OnDecodingCompleted());
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("000023666f6f00", &input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, LiteralEntryEmptyNameAndValue) {
EXPECT_CALL(handler_, OnHeaderDecoded(Eq(""), Eq("")));
EXPECT_CALL(handler_, OnDecodingCompleted());
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("00002000", &input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, SimpleLiteralEntry) {
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("bar")));
EXPECT_CALL(handler_, OnDecodingCompleted());
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("000023666f6f03626172", &input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, MultipleLiteralEntries) {
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("bar")));
std::string str(127, 'a');
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foobaar"), absl::string_view(str)));
EXPECT_CALL(handler_, OnDecodingCompleted());
std::string input;
ASSERT_TRUE(absl::HexStringToBytes(
"0000"
"23666f6f03626172"
"2700666f6f62616172"
"7f0061616161616161"
"616161616161616161"
"6161616161616161616161616161616161616161616161616161616161616161616161"
"6161616161616161616161616161616161616161616161616161616161616161616161"
"6161616161616161616161616161616161616161616161616161616161616161616161"
"616161616161",
&input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, NameLenTooLargeForVarintDecoder) {
EXPECT_CALL(handler_,
OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Encoded integer too large.")));
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("000027ffffffffffffffffffff", &input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, NameLenExceedsLimit) {
EXPECT_CALL(handler_,
OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("String literal too long.")));
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("000027ffff7f", &input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, ValueLenTooLargeForVarintDecoder) {
EXPECT_CALL(handler_,
OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Encoded integer too large.")));
std::string input;
ASSERT_TRUE(
absl::HexStringToBytes("000023666f6f7fffffffffffffffffffff", &input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, ValueLenExceedsLimit) {
EXPECT_CALL(handler_,
OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("String literal too long.")));
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("000023666f6f7fffff7f", &input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, LineFeedInValue) {
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("ba\nr")));
EXPECT_CALL(handler_, OnDecodingCompleted());
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("000023666f6f0462610a72", &input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, IncompleteHeaderBlock) {
EXPECT_CALL(handler_,
OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Incomplete header block.")));
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("00002366", &input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, HuffmanSimple) {
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("custom-key"), Eq("custom-value")));
EXPECT_CALL(handler_, OnDecodingCompleted());
std::string input;
ASSERT_TRUE(absl::HexStringToBytes(
"00002f0125a849e95ba97d7f8925a849e95bb8e8b4bf", &input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, AlternatingHuffmanNonHuffman) {
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("custom-key"), Eq("custom-value")))
.Times(4);
EXPECT_CALL(handler_, OnDecodingCompleted());
std::string input;
ASSERT_TRUE(absl::HexStringToBytes(
"0000"
"2f0125a849e95ba97d7f"
"8925a849e95bb8e8b4bf"
"2703637573746f6d2d6b6579"
"0c637573746f6d2d76616c7565"
"2f0125a849e95ba97d7f"
"0c637573746f6d2d76616c7565"
"2703637573746f6d2d6b6579"
"8925a849e95bb8e8b4bf",
&input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, HuffmanNameDoesNotHaveEOSPrefix) {
EXPECT_CALL(handler_,
OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Error in Huffman-encoded string.")));
std::string input;
ASSERT_TRUE(absl::HexStringToBytes(
"00002f0125a849e95ba97d7e8925a849e95bb8e8b4bf", &input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, HuffmanValueDoesNotHaveEOSPrefix) {
EXPECT_CALL(handler_,
OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Error in Huffman-encoded string.")));
std::string input;
ASSERT_TRUE(absl::HexStringToBytes(
"00002f0125a849e95ba97d7f8925a849e95bb8e8b4be", &input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, HuffmanNameEOSPrefixTooLong) {
EXPECT_CALL(handler_,
OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Error in Huffman-encoded string.")));
std::string input;
ASSERT_TRUE(absl::HexStringToBytes(
"00002f0225a849e95ba97d7fff8925a849e95bb8e8b4bf", &input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, HuffmanValueEOSPrefixTooLong) {
EXPECT_CALL(handler_,
OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Error in Huffman-encoded string.")));
std::string input;
ASSERT_TRUE(absl::HexStringToBytes(
"00002f0125a849e95ba97d7f8a25a849e95bb8e8b4bfff", &input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, StaticTable) {
EXPECT_CALL(handler_, OnHeaderDecoded(Eq(":method"), Eq("GET")));
EXPECT_CALL(handler_, OnHeaderDecoded(Eq(":method"), Eq("POST")));
EXPECT_CALL(handler_, OnHeaderDecoded(Eq(":method"), Eq("TRACE")));
EXPECT_CALL(handler_,
OnHeaderDecoded(Eq("accept-encoding"), Eq("gzip, deflate, br")));
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("accept-encoding"), Eq("compress")));
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("accept-encoding"), Eq("")));
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("location"), Eq("")));
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("location"), Eq("foo")));
EXPECT_CALL(handler_, OnDecodingCompleted());
std::string input;
ASSERT_TRUE(absl::HexStringToBytes(
"0000d1dfccd45f108621e9aec2a11f5c8294e75f000554524143455f1000", &input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, TooHighStaticTableIndex) {
EXPECT_CALL(handler_,
OnHeaderDecoded(Eq("x-frame-options"), Eq("sameorigin")));
EXPECT_CALL(handler_,
OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Static table entry not found.")));
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("0000ff23ff24", &input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, DynamicTable) {
std::string input;
ASSERT_TRUE(absl::HexStringToBytes(
"3fe107"
"6294e703626172"
"80035a5a5a"
"cf8294e7"
"01",
&input));
DecodeEncoderStreamData(input);
Sequence s;
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("bar"))).InSequence(s);
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("ZZZ"))).InSequence(s);
EXPECT_CALL(handler_, OnHeaderDecoded(Eq(":method"), Eq("foo")))
.InSequence(s);
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("ZZZ"))).InSequence(s);
EXPECT_CALL(handler_, OnHeaderDecoded(Eq(":method"), Eq("ZZ"))).InSequence(s);
EXPECT_CALL(handler_, OnDecodingCompleted()).InSequence(s);
EXPECT_CALL(decoder_stream_sender_delegate_,
WriteStreamData(Eq(kHeaderAcknowledgement)))
.InSequence(s);
ASSERT_TRUE(absl::HexStringToBytes(
"0500"
"83"
"82"
"81"
"80"
"41025a5a",
&input));
DecodeHeaderBlock(input);
FlushDecoderStream();
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("bar"))).InSequence(s);
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("ZZZ"))).InSequence(s);
EXPECT_CALL(handler_, OnHeaderDecoded(Eq(":method"), Eq("foo")))
.InSequence(s);
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("ZZZ"))).InSequence(s);
EXPECT_CALL(handler_, OnHeaderDecoded(Eq(":method"), Eq("ZZ"))).InSequence(s);
EXPECT_CALL(handler_, OnDecodingCompleted()).InSequence(s);
EXPECT_CALL(decoder_stream_sender_delegate_,
WriteStreamData(Eq(kHeaderAcknowledgement)))
.InSequence(s);
ASSERT_TRUE(absl::HexStringToBytes(
"0502"
"85"
"84"
"83"
"82"
"43025a5a",
&input));
DecodeHeaderBlock(input);
FlushDecoderStream();
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("bar"))).InSequence(s);
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("ZZZ"))).InSequence(s);
EXPECT_CALL(handler_, OnHeaderDecoded(Eq(":method"), Eq("foo")))
.InSequence(s);
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("ZZZ"))).InSequence(s);
EXPECT_CALL(handler_, OnHeaderDecoded(Eq(":method"), Eq("ZZ"))).InSequence(s);
EXPECT_CALL(handler_, OnDecodingCompleted()).InSequence(s);
EXPECT_CALL(decoder_stream_sender_delegate_,
WriteStreamData(Eq(kHeaderAcknowledgement)))
.InSequence(s);
ASSERT_TRUE(absl::HexStringToBytes(
"0582"
"80"
"10"
"11"
"12"
"01025a5a",
&input));
DecodeHeaderBlock(input);
FlushDecoderStream();
}
TEST_P(QpackDecoderTest, DecreasingDynamicTableCapacityEvictsEntries) {
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("3fe107", &input));
DecodeEncoderStreamData(input);
ASSERT_TRUE(absl::HexStringToBytes("6294e703626172", &input));
DecodeEncoderStreamData(input);
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("bar")));
EXPECT_CALL(handler_, OnDecodingCompleted());
EXPECT_CALL(decoder_stream_sender_delegate_,
WriteStreamData(Eq(kHeaderAcknowledgement)));
ASSERT_TRUE(absl::HexStringToBytes(
"0200"
"80",
&input));
DecodeHeaderBlock(input);
ASSERT_TRUE(absl::HexStringToBytes("3f01", &input));
DecodeEncoderStreamData(input);
EXPECT_CALL(handler_, OnDecodingErrorDetected(
QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Dynamic table entry already evicted.")));
ASSERT_TRUE(absl::HexStringToBytes(
"0200"
"80",
&input));
DecodeHeaderBlock(input);
FlushDecoderStream();
}
TEST_P(QpackDecoderTest, EncoderStreamErrorEntryTooLarge) {
std::string input;
EXPECT_CALL(
encoder_stream_error_delegate_,
OnEncoderStreamError(QUIC_QPACK_ENCODER_STREAM_ERROR_INSERTING_LITERAL,
Eq("Error inserting literal entry.")));
ASSERT_TRUE(absl::HexStringToBytes("3f03", &input));
DecodeEncoderStreamData(input);
ASSERT_TRUE(absl::HexStringToBytes("6294e703626172", &input));
DecodeEncoderStreamData(input);
}
TEST_P(QpackDecoderTest, EncoderStreamErrorInvalidStaticTableEntry) {
EXPECT_CALL(
encoder_stream_error_delegate_,
OnEncoderStreamError(QUIC_QPACK_ENCODER_STREAM_INVALID_STATIC_ENTRY,
Eq("Invalid static table entry.")));
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("ff2400", &input));
DecodeEncoderStreamData(input);
}
TEST_P(QpackDecoderTest, EncoderStreamErrorInvalidDynamicTableEntry) {
EXPECT_CALL(encoder_stream_error_delegate_,
OnEncoderStreamError(
QUIC_QPACK_ENCODER_STREAM_INSERTION_INVALID_RELATIVE_INDEX,
Eq("Invalid relative index.")));
std::string input;
ASSERT_TRUE(absl::HexStringToBytes(
"3fe107"
"6294e703626172"
"8100",
&input));
DecodeEncoderStreamData(input);
}
TEST_P(QpackDecoderTest, EncoderStreamErrorDuplicateInvalidEntry) {
EXPECT_CALL(encoder_stream_error_delegate_,
OnEncoderStreamError(
QUIC_QPACK_ENCODER_STREAM_DUPLICATE_INVALID_RELATIVE_INDEX,
Eq("Invalid relative index.")));
std::string input;
ASSERT_TRUE(absl::HexStringToBytes(
"3fe107"
"6294e703626172"
"01",
&input));
DecodeEncoderStreamData(input);
}
TEST_P(QpackDecoderTest, EncoderStreamErrorTooLargeInteger) {
EXPECT_CALL(encoder_stream_error_delegate_,
OnEncoderStreamError(QUIC_QPACK_ENCODER_STREAM_INTEGER_TOO_LARGE,
Eq("Encoded integer too large.")));
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("3fffffffffffffffffffff", &input));
DecodeEncoderStreamData(input);
}
TEST_P(QpackDecoderTest, InvalidDynamicEntryWhenBaseIsZero) {
EXPECT_CALL(handler_, OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Invalid relative index.")));
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("3fe107", &input));
DecodeEncoderStreamData(input);
ASSERT_TRUE(absl::HexStringToBytes("6294e703626172", &input));
DecodeEncoderStreamData(input);
ASSERT_TRUE(absl::HexStringToBytes(
"0280"
"80",
&input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, InvalidNegativeBase) {
EXPECT_CALL(handler_, OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Error calculating Base.")));
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("0281", &input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, InvalidDynamicEntryByRelativeIndex) {
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("3fe107", &input));
DecodeEncoderStreamData(input);
ASSERT_TRUE(absl::HexStringToBytes("6294e703626172", &input));
DecodeEncoderStreamData(input);
EXPECT_CALL(handler_, OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Invalid relative index.")));
ASSERT_TRUE(absl::HexStringToBytes(
"0200"
"81",
&input));
DecodeHeaderBlock(input);
EXPECT_CALL(handler_, OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Invalid relative index.")));
ASSERT_TRUE(absl::HexStringToBytes(
"0200"
"4100",
&input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, EvictedDynamicTableEntry) {
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("3f61", &input));
DecodeEncoderStreamData(input);
ASSERT_TRUE(absl::HexStringToBytes("6294e703626172", &input));
DecodeEncoderStreamData(input);
ASSERT_TRUE(absl::HexStringToBytes("00000000", &input));
DecodeEncoderStreamData(input);
EXPECT_CALL(handler_, OnDecodingErrorDetected(
QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Dynamic table entry already evicted.")));
ASSERT_TRUE(absl::HexStringToBytes(
"0500"
"82",
&input));
DecodeHeaderBlock(input);
EXPECT_CALL(handler_, OnDecodingErrorDetected(
QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Dynamic table entry already evicted.")));
ASSERT_TRUE(absl::HexStringToBytes(
"0500"
"4200",
&input));
DecodeHeaderBlock(input);
EXPECT_CALL(handler_, OnDecodingErrorDetected(
QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Dynamic table entry already evicted.")));
ASSERT_TRUE(absl::HexStringToBytes(
"0380"
"10",
&input));
DecodeHeaderBlock(input);
EXPECT_CALL(handler_, OnDecodingErrorDetected(
QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Dynamic table entry already evicted.")));
ASSERT_TRUE(absl::HexStringToBytes(
"0380"
"0000",
&input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, TableCapacityMustNotExceedMaximum) {
EXPECT_CALL(
encoder_stream_error_delegate_,
OnEncoderStreamError(QUIC_QPACK_ENCODER_STREAM_SET_DYNAMIC_TABLE_CAPACITY,
Eq("Error updating dynamic table capacity.")));
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("3fe10f", &input));
DecodeEncoderStreamData(input);
}
TEST_P(QpackDecoderTest, SetDynamicTableCapacity) {
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("3f61", &input));
DecodeEncoderStreamData(input);
}
TEST_P(QpackDecoderTest, InvalidEncodedRequiredInsertCount) {
EXPECT_CALL(handler_, OnDecodingErrorDetected(
QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Error decoding Required Insert Count.")));
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("4100", &input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, DataAfterInvalidEncodedRequiredInsertCount) {
EXPECT_CALL(handler_, OnDecodingErrorDetected(
QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Error decoding Required Insert Count.")));
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("410000", &input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, WrappedRequiredInsertCount) {
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("3fe107", &input));
DecodeEncoderStreamData(input);
ASSERT_TRUE(
absl::HexStringToBytes("6294e7"
"7fd903",
&input));
DecodeEncoderStreamData(input);
std::string header_value(600, 'Z');
DecodeEncoderStreamData(header_value);
DecodeEncoderStreamData(std::string(200, '\x00'));
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq(header_value)));
EXPECT_CALL(handler_, OnDecodingCompleted());
EXPECT_CALL(decoder_stream_sender_delegate_,
WriteStreamData(Eq(kHeaderAcknowledgement)));
ASSERT_TRUE(absl::HexStringToBytes(
"0a00"
"80",
&input));
DecodeHeaderBlock(input);
FlushDecoderStream();
}
TEST_P(QpackDecoderTest, NonZeroRequiredInsertCountButNoDynamicEntries) {
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("3fe107", &input));
DecodeEncoderStreamData(input);
ASSERT_TRUE(absl::HexStringToBytes("6294e703626172", &input));
DecodeEncoderStreamData(input);
EXPECT_CALL(handler_, OnHeaderDecoded(Eq(":method"), Eq("GET")));
EXPECT_CALL(handler_,
OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Required Insert Count too large.")));
ASSERT_TRUE(absl::HexStringToBytes(
"0200"
"d1",
&input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, AddressEntryNotAllowedByRequiredInsertCount) {
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("3fe107", &input));
DecodeEncoderStreamData(input);
ASSERT_TRUE(absl::HexStringToBytes("6294e703626172", &input));
DecodeEncoderStreamData(input);
EXPECT_CALL(
handler_,
OnDecodingErrorDetected(
QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Absolute Index must be smaller than Required Insert Count.")));
ASSERT_TRUE(absl::HexStringToBytes(
"0201"
"80",
&input));
DecodeHeaderBlock(input);
EXPECT_CALL(
handler_,
OnDecodingErrorDetected(
QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Absolute Index must be smaller than Required Insert Count.")));
ASSERT_TRUE(absl::HexStringToBytes(
"0201"
"4000",
&input));
DecodeHeaderBlock(input);
EXPECT_CALL(
handler_,
OnDecodingErrorDetected(
QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Absolute Index must be smaller than Required Insert Count.")));
ASSERT_TRUE(absl::HexStringToBytes(
"0200"
"10",
&input));
DecodeHeaderBlock(input);
EXPECT_CALL(
handler_,
OnDecodingErrorDetected(
QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Absolute Index must be smaller than Required Insert Count.")));
ASSERT_TRUE(absl::HexStringToBytes(
"0200"
"0000",
&input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, PromisedRequiredInsertCountLargerThanActual) {
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("3fe107", &input));
DecodeEncoderStreamData(input);
ASSERT_TRUE(absl::HexStringToBytes("6294e703626172", &input));
DecodeEncoderStreamData(input);
ASSERT_TRUE(absl::HexStringToBytes("00", &input));
DecodeEncoderStreamData(input);
DecodeEncoderStreamData(input);
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("bar")));
EXPECT_CALL(handler_,
OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Required Insert Count too large.")));
ASSERT_TRUE(absl::HexStringToBytes(
"0300"
"81",
&input));
DecodeHeaderBlock(input);
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("")));
EXPECT_CALL(handler_,
OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Required Insert Count too large.")));
ASSERT_TRUE(absl::HexStringToBytes(
"0300"
"4100",
&input));
DecodeHeaderBlock(input);
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("bar")));
EXPECT_CALL(handler_,
OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Required Insert Count too large.")));
ASSERT_TRUE(absl::HexStringToBytes(
"0481"
"10",
&input));
DecodeHeaderBlock(input);
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("")));
EXPECT_CALL(handler_,
OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Required Insert Count too large.")));
ASSERT_TRUE(absl::HexStringToBytes(
"0481"
"0000",
&input));
DecodeHeaderBlock(input);
}
TEST_P(QpackDecoderTest, BlockedDecoding) {
std::string input;
ASSERT_TRUE(absl::HexStringToBytes(
"0200"
"80",
&input));
DecodeHeaderBlock(input);
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("bar")));
EXPECT_CALL(handler_, OnDecodingCompleted());
EXPECT_CALL(decoder_stream_sender_delegate_,
WriteStreamData(Eq(kHeaderAcknowledgement)));
ASSERT_TRUE(absl::HexStringToBytes("3fe107", &input));
DecodeEncoderStreamData(input);
ASSERT_TRUE(absl::HexStringToBytes("6294e703626172", &input));
DecodeEncoderStreamData(input);
FlushDecoderStream();
}
TEST_P(QpackDecoderTest, BlockedDecodingUnblockedBeforeEndOfHeaderBlock) {
std::string input;
StartDecoding();
ASSERT_TRUE(absl::HexStringToBytes(
"0200"
"80"
"d1",
&input));
DecodeData(input);
ASSERT_TRUE(absl::HexStringToBytes("3fe107", &input));
DecodeEncoderStreamData(input);
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("bar")));
EXPECT_CALL(handler_, OnHeaderDecoded(Eq(":method"), Eq("GET")));
ASSERT_TRUE(absl::HexStringToBytes("6294e703626172", &input));
DecodeEncoderStreamData(input);
Mock::VerifyAndClearExpectations(&handler_);
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("bar")));
EXPECT_CALL(handler_, OnHeaderDecoded(Eq(":scheme"), Eq("https")));
ASSERT_TRUE(absl::HexStringToBytes(
"80"
"d7",
&input));
DecodeData(input);
Mock::VerifyAndClearExpectations(&handler_);
EXPECT_CALL(handler_, OnDecodingCompleted());
EXPECT_CALL(decoder_stream_sender_delegate_,
WriteStreamData(Eq(kHeaderAcknowledgement)));
EndDecoding();
FlushDecoderStream();
}
TEST_P(QpackDecoderTest,
BlockedDecodingUnblockedAndErrorBeforeEndOfHeaderBlock) {
std::string input;
StartDecoding();
ASSERT_TRUE(absl::HexStringToBytes(
"0200"
"80"
"81",
&input));
DecodeData(input);
ASSERT_TRUE(absl::HexStringToBytes("3fe107", &input));
DecodeEncoderStreamData(input);
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("bar")));
EXPECT_CALL(handler_, OnDecodingErrorDetected(QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Invalid relative index.")));
ASSERT_TRUE(absl::HexStringToBytes("6294e703626172", &input));
DecodeEncoderStreamData(input);
}
TEST_P(QpackDecoderTest, BlockedDecodingAndEvictedEntries) {
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("3f61", &input));
DecodeEncoderStreamData(input);
ASSERT_TRUE(absl::HexStringToBytes(
"0700"
"80",
&input));
DecodeHeaderBlock(input);
ASSERT_TRUE(absl::HexStringToBytes("6294e703626172", &input));
DecodeEncoderStreamData(input);
ASSERT_TRUE(absl::HexStringToBytes("00000000", &input));
DecodeEncoderStreamData(input);
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("baz")));
EXPECT_CALL(handler_, OnDecodingCompleted());
EXPECT_CALL(decoder_stream_sender_delegate_,
WriteStreamData(Eq(kHeaderAcknowledgement)));
ASSERT_TRUE(absl::HexStringToBytes("6294e70362617a", &input));
DecodeEncoderStreamData(input);
FlushDecoderStream();
}
TEST_P(QpackDecoderTest, TooManyBlockedStreams) {
std::string data;
ASSERT_TRUE(absl::HexStringToBytes("0200", &data));
auto progressive_decoder1 = CreateProgressiveDecoder( 1);
progressive_decoder1->Decode(data);
EXPECT_CALL(handler_,
OnDecodingErrorDetected(
QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Limit on number of blocked streams exceeded.")));
auto progressive_decoder2 = CreateProgressiveDecoder( 2);
progressive_decoder2->Decode(data);
}
TEST_P(QpackDecoderTest, InsertCountIncrement) {
std::string input;
ASSERT_TRUE(absl::HexStringToBytes(
"3fe107"
"6294e703626172"
"00",
&input));
DecodeEncoderStreamData(input);
EXPECT_CALL(handler_, OnHeaderDecoded(Eq("foo"), Eq("bar")));
EXPECT_CALL(handler_, OnDecodingCompleted());
std::string expected_data;
ASSERT_TRUE(absl::HexStringToBytes(
"81"
"01",
&expected_data));
EXPECT_CALL(decoder_stream_sender_delegate_,
WriteStreamData(Eq(expected_data)));
ASSERT_TRUE(absl::HexStringToBytes(
"0200"
"80",
&input));
DecodeHeaderBlock(input);
FlushDecoderStream();
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_decoder.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_decoder_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
e46b67d4-5a6d-455d-84c5-02a8b912636a | cpp | google/quiche | qpack_static_table | quiche/quic/core/qpack/qpack_static_table.cc | quiche/quic/core/qpack/qpack_static_table_test.cc | #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);
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_static_table.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_static_table_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
6be32d49-4f0d-4035-bcc7-0e47c6499953 | cpp | google/quiche | qpack_instruction_decoder | quiche/quic/core/qpack/qpack_instruction_decoder.cc | quiche/quic/core/qpack/qpack_instruction_decoder_test.cc | #include "quiche/quic/core/qpack/qpack_instruction_decoder.h"
#include <algorithm>
#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_logging.h"
namespace quic {
namespace {
const size_t kStringLiteralLengthLimit = 1024 * 1024;
}
QpackInstructionDecoder::QpackInstructionDecoder(const QpackLanguage* language,
Delegate* delegate)
: language_(language),
delegate_(delegate),
s_bit_(false),
varint_(0),
varint2_(0),
is_huffman_encoded_(false),
string_length_(0),
error_detected_(false),
state_(State::kStartInstruction) {}
bool QpackInstructionDecoder::Decode(absl::string_view data) {
QUICHE_DCHECK(!data.empty());
QUICHE_DCHECK(!error_detected_);
while (true) {
bool success = true;
size_t bytes_consumed = 0;
switch (state_) {
case State::kStartInstruction:
success = DoStartInstruction(data);
break;
case State::kStartField:
success = DoStartField();
break;
case State::kReadBit:
success = DoReadBit(data);
break;
case State::kVarintStart:
success = DoVarintStart(data, &bytes_consumed);
break;
case State::kVarintResume:
success = DoVarintResume(data, &bytes_consumed);
break;
case State::kVarintDone:
success = DoVarintDone();
break;
case State::kReadString:
success = DoReadString(data, &bytes_consumed);
break;
case State::kReadStringDone:
success = DoReadStringDone();
break;
}
if (!success) {
return false;
}
QUICHE_DCHECK(!error_detected_);
QUICHE_DCHECK_LE(bytes_consumed, data.size());
data = absl::string_view(data.data() + bytes_consumed,
data.size() - bytes_consumed);
if (data.empty() && (state_ != State::kStartField) &&
(state_ != State::kVarintDone) && (state_ != State::kReadStringDone)) {
return true;
}
}
}
bool QpackInstructionDecoder::AtInstructionBoundary() const {
return state_ == State::kStartInstruction;
}
bool QpackInstructionDecoder::DoStartInstruction(absl::string_view data) {
QUICHE_DCHECK(!data.empty());
instruction_ = LookupOpcode(data[0]);
field_ = instruction_->fields.begin();
state_ = State::kStartField;
return true;
}
bool QpackInstructionDecoder::DoStartField() {
if (field_ == instruction_->fields.end()) {
if (!delegate_->OnInstructionDecoded(instruction_)) {
return false;
}
state_ = State::kStartInstruction;
return true;
}
switch (field_->type) {
case QpackInstructionFieldType::kSbit:
case QpackInstructionFieldType::kName:
case QpackInstructionFieldType::kValue:
state_ = State::kReadBit;
return true;
case QpackInstructionFieldType::kVarint:
case QpackInstructionFieldType::kVarint2:
state_ = State::kVarintStart;
return true;
default:
QUIC_BUG(quic_bug_10767_1) << "Invalid field type.";
return false;
}
}
bool QpackInstructionDecoder::DoReadBit(absl::string_view data) {
QUICHE_DCHECK(!data.empty());
switch (field_->type) {
case QpackInstructionFieldType::kSbit: {
const uint8_t bitmask = field_->param;
s_bit_ = (data[0] & bitmask) == bitmask;
++field_;
state_ = State::kStartField;
return true;
}
case QpackInstructionFieldType::kName:
case QpackInstructionFieldType::kValue: {
const uint8_t prefix_length = field_->param;
QUICHE_DCHECK_GE(7, prefix_length);
const uint8_t bitmask = 1 << prefix_length;
is_huffman_encoded_ = (data[0] & bitmask) == bitmask;
state_ = State::kVarintStart;
return true;
}
default:
QUIC_BUG(quic_bug_10767_2) << "Invalid field type.";
return false;
}
}
bool QpackInstructionDecoder::DoVarintStart(absl::string_view data,
size_t* bytes_consumed) {
QUICHE_DCHECK(!data.empty());
QUICHE_DCHECK(field_->type == QpackInstructionFieldType::kVarint ||
field_->type == QpackInstructionFieldType::kVarint2 ||
field_->type == QpackInstructionFieldType::kName ||
field_->type == QpackInstructionFieldType::kValue);
http2::DecodeBuffer buffer(data.data() + 1, data.size() - 1);
http2::DecodeStatus status =
varint_decoder_.Start(data[0], field_->param, &buffer);
*bytes_consumed = 1 + buffer.Offset();
switch (status) {
case http2::DecodeStatus::kDecodeDone:
state_ = State::kVarintDone;
return true;
case http2::DecodeStatus::kDecodeInProgress:
state_ = State::kVarintResume;
return true;
case http2::DecodeStatus::kDecodeError:
OnError(ErrorCode::INTEGER_TOO_LARGE, "Encoded integer too large.");
return false;
default:
QUIC_BUG(quic_bug_10767_3) << "Unknown decode status " << status;
return false;
}
}
bool QpackInstructionDecoder::DoVarintResume(absl::string_view data,
size_t* bytes_consumed) {
QUICHE_DCHECK(!data.empty());
QUICHE_DCHECK(field_->type == QpackInstructionFieldType::kVarint ||
field_->type == QpackInstructionFieldType::kVarint2 ||
field_->type == QpackInstructionFieldType::kName ||
field_->type == QpackInstructionFieldType::kValue);
http2::DecodeBuffer buffer(data);
http2::DecodeStatus status = varint_decoder_.Resume(&buffer);
*bytes_consumed = buffer.Offset();
switch (status) {
case http2::DecodeStatus::kDecodeDone:
state_ = State::kVarintDone;
return true;
case http2::DecodeStatus::kDecodeInProgress:
QUICHE_DCHECK_EQ(*bytes_consumed, data.size());
QUICHE_DCHECK(buffer.Empty());
return true;
case http2::DecodeStatus::kDecodeError:
OnError(ErrorCode::INTEGER_TOO_LARGE, "Encoded integer too large.");
return false;
default:
QUIC_BUG(quic_bug_10767_4) << "Unknown decode status " << status;
return false;
}
}
bool QpackInstructionDecoder::DoVarintDone() {
QUICHE_DCHECK(field_->type == QpackInstructionFieldType::kVarint ||
field_->type == QpackInstructionFieldType::kVarint2 ||
field_->type == QpackInstructionFieldType::kName ||
field_->type == QpackInstructionFieldType::kValue);
if (field_->type == QpackInstructionFieldType::kVarint) {
varint_ = varint_decoder_.value();
++field_;
state_ = State::kStartField;
return true;
}
if (field_->type == QpackInstructionFieldType::kVarint2) {
varint2_ = varint_decoder_.value();
++field_;
state_ = State::kStartField;
return true;
}
string_length_ = varint_decoder_.value();
if (string_length_ > kStringLiteralLengthLimit) {
OnError(ErrorCode::STRING_LITERAL_TOO_LONG, "String literal too long.");
return false;
}
std::string* const string =
(field_->type == QpackInstructionFieldType::kName) ? &name_ : &value_;
string->clear();
if (string_length_ == 0) {
++field_;
state_ = State::kStartField;
return true;
}
string->reserve(string_length_);
state_ = State::kReadString;
return true;
}
bool QpackInstructionDecoder::DoReadString(absl::string_view data,
size_t* bytes_consumed) {
QUICHE_DCHECK(!data.empty());
QUICHE_DCHECK(field_->type == QpackInstructionFieldType::kName ||
field_->type == QpackInstructionFieldType::kValue);
std::string* const string =
(field_->type == QpackInstructionFieldType::kName) ? &name_ : &value_;
QUICHE_DCHECK_LT(string->size(), string_length_);
*bytes_consumed = std::min(string_length_ - string->size(), data.size());
string->append(data.data(), *bytes_consumed);
QUICHE_DCHECK_LE(string->size(), string_length_);
if (string->size() == string_length_) {
state_ = State::kReadStringDone;
}
return true;
}
bool QpackInstructionDecoder::DoReadStringDone() {
QUICHE_DCHECK(field_->type == QpackInstructionFieldType::kName ||
field_->type == QpackInstructionFieldType::kValue);
std::string* const string =
(field_->type == QpackInstructionFieldType::kName) ? &name_ : &value_;
QUICHE_DCHECK_EQ(string->size(), string_length_);
if (is_huffman_encoded_) {
huffman_decoder_.Reset();
std::string decoded_value;
huffman_decoder_.Decode(*string, &decoded_value);
if (!huffman_decoder_.InputProperlyTerminated()) {
OnError(ErrorCode::HUFFMAN_ENCODING_ERROR,
"Error in Huffman-encoded string.");
return false;
}
*string = std::move(decoded_value);
}
++field_;
state_ = State::kStartField;
return true;
}
const QpackInstruction* QpackInstructionDecoder::LookupOpcode(
uint8_t byte) const {
for (const auto* instruction : *language_) {
if ((byte & instruction->opcode.mask) == instruction->opcode.value) {
return instruction;
}
}
QUICHE_DCHECK(false);
return nullptr;
}
void QpackInstructionDecoder::OnError(ErrorCode error_code,
absl::string_view error_message) {
QUICHE_DCHECK(!error_detected_);
error_detected_ = true;
delegate_->OnInstructionDecodingError(error_code, error_message);
}
} | #include "quiche/quic/core/qpack/qpack_instruction_decoder.h"
#include <algorithm>
#include <memory>
#include <string>
#include "absl/strings/escaping.h"
#include "absl/strings/string_view.h"
#include "quiche/quic/core/qpack/qpack_instructions.h"
#include "quiche/quic/platform/api/quic_logging.h"
#include "quiche/quic/platform/api/quic_test.h"
#include "quiche/quic/test_tools/qpack/qpack_test_utils.h"
using ::testing::_;
using ::testing::Eq;
using ::testing::Expectation;
using ::testing::InvokeWithoutArgs;
using ::testing::Return;
using ::testing::StrictMock;
using ::testing::Values;
namespace quic {
namespace test {
namespace {
const QpackInstruction* TestInstruction1() {
static const QpackInstruction* const instruction =
new QpackInstruction{QpackInstructionOpcode{0x00, 0x80},
{{QpackInstructionFieldType::kSbit, 0x40},
{QpackInstructionFieldType::kVarint, 6},
{QpackInstructionFieldType::kVarint2, 8}}};
return instruction;
}
const QpackInstruction* TestInstruction2() {
static const QpackInstruction* const instruction =
new QpackInstruction{QpackInstructionOpcode{0x80, 0x80},
{{QpackInstructionFieldType::kName, 6},
{QpackInstructionFieldType::kValue, 7}}};
return instruction;
}
const QpackLanguage* TestLanguage() {
static const QpackLanguage* const language =
new QpackLanguage{TestInstruction1(), TestInstruction2()};
return language;
}
class MockDelegate : public QpackInstructionDecoder::Delegate {
public:
MockDelegate() {
ON_CALL(*this, OnInstructionDecoded(_)).WillByDefault(Return(true));
}
MockDelegate(const MockDelegate&) = delete;
MockDelegate& operator=(const MockDelegate&) = delete;
~MockDelegate() override = default;
MOCK_METHOD(bool, OnInstructionDecoded, (const QpackInstruction*),
(override));
MOCK_METHOD(void, OnInstructionDecodingError,
(QpackInstructionDecoder::ErrorCode error_code,
absl::string_view error_message),
(override));
};
class QpackInstructionDecoderTest : public QuicTestWithParam<FragmentMode> {
protected:
QpackInstructionDecoderTest()
: decoder_(std::make_unique<QpackInstructionDecoder>(TestLanguage(),
&delegate_)),
fragment_mode_(GetParam()) {}
~QpackInstructionDecoderTest() override = default;
void SetUp() override {
ON_CALL(delegate_, OnInstructionDecodingError(_, _))
.WillByDefault(InvokeWithoutArgs([this]() { decoder_.reset(); }));
}
void DecodeInstruction(absl::string_view data) {
EXPECT_TRUE(decoder_->AtInstructionBoundary());
FragmentSizeGenerator fragment_size_generator =
FragmentModeToFragmentSizeGenerator(fragment_mode_);
while (!data.empty()) {
size_t fragment_size = std::min(fragment_size_generator(), data.size());
bool success = decoder_->Decode(data.substr(0, fragment_size));
if (!decoder_) {
EXPECT_FALSE(success);
return;
}
EXPECT_TRUE(success);
data = data.substr(fragment_size);
if (!data.empty()) {
EXPECT_FALSE(decoder_->AtInstructionBoundary());
}
}
EXPECT_TRUE(decoder_->AtInstructionBoundary());
}
StrictMock<MockDelegate> delegate_;
std::unique_ptr<QpackInstructionDecoder> decoder_;
private:
const FragmentMode fragment_mode_;
};
INSTANTIATE_TEST_SUITE_P(All, QpackInstructionDecoderTest,
Values(FragmentMode::kSingleChunk,
FragmentMode::kOctetByOctet));
TEST_P(QpackInstructionDecoderTest, SBitAndVarint2) {
std::string encoded_data;
EXPECT_CALL(delegate_, OnInstructionDecoded(TestInstruction1()));
ASSERT_TRUE(absl::HexStringToBytes("7f01ff65", &encoded_data));
DecodeInstruction(encoded_data);
EXPECT_TRUE(decoder_->s_bit());
EXPECT_EQ(64u, decoder_->varint());
EXPECT_EQ(356u, decoder_->varint2());
EXPECT_CALL(delegate_, OnInstructionDecoded(TestInstruction1()));
ASSERT_TRUE(absl::HexStringToBytes("05c8", &encoded_data));
DecodeInstruction(encoded_data);
EXPECT_FALSE(decoder_->s_bit());
EXPECT_EQ(5u, decoder_->varint());
EXPECT_EQ(200u, decoder_->varint2());
}
TEST_P(QpackInstructionDecoderTest, NameAndValue) {
std::string encoded_data;
EXPECT_CALL(delegate_, OnInstructionDecoded(TestInstruction2()));
ASSERT_TRUE(absl::HexStringToBytes("83666f6f03626172", &encoded_data));
DecodeInstruction(encoded_data);
EXPECT_EQ("foo", decoder_->name());
EXPECT_EQ("bar", decoder_->value());
EXPECT_CALL(delegate_, OnInstructionDecoded(TestInstruction2()));
ASSERT_TRUE(absl::HexStringToBytes("8000", &encoded_data));
DecodeInstruction(encoded_data);
EXPECT_EQ("", decoder_->name());
EXPECT_EQ("", decoder_->value());
EXPECT_CALL(delegate_, OnInstructionDecoded(TestInstruction2()));
ASSERT_TRUE(absl::HexStringToBytes("c294e7838c767f", &encoded_data));
DecodeInstruction(encoded_data);
EXPECT_EQ("foo", decoder_->name());
EXPECT_EQ("bar", decoder_->value());
}
TEST_P(QpackInstructionDecoderTest, InvalidHuffmanEncoding) {
std::string encoded_data;
EXPECT_CALL(delegate_,
OnInstructionDecodingError(
QpackInstructionDecoder::ErrorCode::HUFFMAN_ENCODING_ERROR,
Eq("Error in Huffman-encoded string.")));
ASSERT_TRUE(absl::HexStringToBytes("c1ff", &encoded_data));
DecodeInstruction(encoded_data);
}
TEST_P(QpackInstructionDecoderTest, InvalidVarintEncoding) {
std::string encoded_data;
EXPECT_CALL(delegate_,
OnInstructionDecodingError(
QpackInstructionDecoder::ErrorCode::INTEGER_TOO_LARGE,
Eq("Encoded integer too large.")));
ASSERT_TRUE(absl::HexStringToBytes("ffffffffffffffffffffff", &encoded_data));
DecodeInstruction(encoded_data);
}
TEST_P(QpackInstructionDecoderTest, StringLiteralTooLong) {
std::string encoded_data;
EXPECT_CALL(delegate_,
OnInstructionDecodingError(
QpackInstructionDecoder::ErrorCode::STRING_LITERAL_TOO_LONG,
Eq("String literal too long.")));
ASSERT_TRUE(absl::HexStringToBytes("bfffff7f", &encoded_data));
DecodeInstruction(encoded_data);
}
TEST_P(QpackInstructionDecoderTest, DelegateSignalsError) {
Expectation first_call =
EXPECT_CALL(delegate_, OnInstructionDecoded(TestInstruction1()))
.WillOnce(InvokeWithoutArgs([this]() -> bool {
EXPECT_EQ(1u, decoder_->varint());
return true;
}));
EXPECT_CALL(delegate_, OnInstructionDecoded(TestInstruction1()))
.After(first_call)
.WillOnce(InvokeWithoutArgs([this]() -> bool {
EXPECT_EQ(2u, decoder_->varint());
return false;
}));
std::string encoded_data;
ASSERT_TRUE(absl::HexStringToBytes("01000200030004000500", &encoded_data));
EXPECT_FALSE(decoder_->Decode(encoded_data));
}
TEST_P(QpackInstructionDecoderTest, DelegateSignalsErrorAndDestroysDecoder) {
EXPECT_CALL(delegate_, OnInstructionDecoded(TestInstruction1()))
.WillOnce(InvokeWithoutArgs([this]() -> bool {
EXPECT_EQ(1u, decoder_->varint());
decoder_.reset();
return false;
}));
std::string encoded_data;
ASSERT_TRUE(absl::HexStringToBytes("0100", &encoded_data));
DecodeInstruction(encoded_data);
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_instruction_decoder.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_instruction_decoder_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
ddc5b0d0-1019-4b7a-97cc-3ae0acc9d1cb | cpp | google/quiche | qpack_decoded_headers_accumulator | quiche/quic/core/qpack/qpack_decoded_headers_accumulator.cc | quiche/quic/core/qpack/qpack_decoded_headers_accumulator_test.cc | #include "quiche/quic/core/qpack/qpack_decoded_headers_accumulator.h"
#include <utility>
#include "absl/strings/string_view.h"
#include "quiche/quic/core/qpack/qpack_decoder.h"
#include "quiche/quic/core/qpack/qpack_header_table.h"
#include "quiche/quic/platform/api/quic_bug_tracker.h"
#include "quiche/quic/platform/api/quic_flags.h"
namespace quic {
QpackDecodedHeadersAccumulator::QpackDecodedHeadersAccumulator(
QuicStreamId id, QpackDecoder* qpack_decoder, Visitor* visitor,
size_t max_header_list_size)
: decoder_(qpack_decoder->CreateProgressiveDecoder(id, this)),
visitor_(visitor),
max_header_list_size_(max_header_list_size),
uncompressed_header_bytes_including_overhead_(0),
uncompressed_header_bytes_without_overhead_(0),
compressed_header_bytes_(0),
header_list_size_limit_exceeded_(false),
headers_decoded_(false),
error_detected_(false) {}
void QpackDecodedHeadersAccumulator::OnHeaderDecoded(absl::string_view name,
absl::string_view value) {
QUICHE_DCHECK(!error_detected_);
uncompressed_header_bytes_without_overhead_ += name.size() + value.size();
if (header_list_size_limit_exceeded_) {
return;
}
uncompressed_header_bytes_including_overhead_ +=
name.size() + value.size() + kQpackEntrySizeOverhead;
const size_t uncompressed_header_bytes =
GetQuicFlag(quic_header_size_limit_includes_overhead)
? uncompressed_header_bytes_including_overhead_
: uncompressed_header_bytes_without_overhead_;
if (uncompressed_header_bytes > max_header_list_size_) {
header_list_size_limit_exceeded_ = true;
}
quic_header_list_.OnHeader(name, value);
}
void QpackDecodedHeadersAccumulator::OnDecodingCompleted() {
QUICHE_DCHECK(!headers_decoded_);
QUICHE_DCHECK(!error_detected_);
headers_decoded_ = true;
quic_header_list_.OnHeaderBlockEnd(
uncompressed_header_bytes_without_overhead_, compressed_header_bytes_);
visitor_->OnHeadersDecoded(std::move(quic_header_list_),
header_list_size_limit_exceeded_);
}
void QpackDecodedHeadersAccumulator::OnDecodingErrorDetected(
QuicErrorCode error_code, absl::string_view error_message) {
QUICHE_DCHECK(!error_detected_);
QUICHE_DCHECK(!headers_decoded_);
error_detected_ = true;
visitor_->OnHeaderDecodingError(error_code, error_message);
}
void QpackDecodedHeadersAccumulator::Decode(absl::string_view data) {
QUICHE_DCHECK(!error_detected_);
compressed_header_bytes_ += data.size();
decoder_->Decode(data);
}
void QpackDecodedHeadersAccumulator::EndHeaderBlock() {
QUICHE_DCHECK(!error_detected_);
QUICHE_DCHECK(!headers_decoded_);
if (!decoder_) {
QUIC_BUG(b215142466_EndHeaderBlock);
return;
}
decoder_->EndHeaderBlock();
}
} | #include "quiche/quic/core/qpack/qpack_decoded_headers_accumulator.h"
#include <cstring>
#include <string>
#include "absl/strings/escaping.h"
#include "absl/strings/string_view.h"
#include "quiche/quic/core/qpack/qpack_decoder.h"
#include "quiche/quic/platform/api/quic_test.h"
#include "quiche/quic/test_tools/qpack/qpack_test_utils.h"
using ::testing::_;
using ::testing::ElementsAre;
using ::testing::Eq;
using ::testing::Pair;
using ::testing::SaveArg;
using ::testing::StrictMock;
namespace quic {
namespace test {
namespace {
QuicStreamId kTestStreamId = 1;
const size_t kMaxHeaderListSize = 100;
const size_t kMaxDynamicTableCapacity = 100;
const uint64_t kMaximumBlockedStreams = 1;
const char* const kHeaderAcknowledgement = "\x81";
class MockVisitor : public QpackDecodedHeadersAccumulator::Visitor {
public:
~MockVisitor() override = default;
MOCK_METHOD(void, OnHeadersDecoded,
(QuicHeaderList headers, bool header_list_size_limit_exceeded),
(override));
MOCK_METHOD(void, OnHeaderDecodingError,
(QuicErrorCode error_code, absl::string_view error_message),
(override));
};
}
class QpackDecodedHeadersAccumulatorTest : public QuicTest {
protected:
QpackDecodedHeadersAccumulatorTest()
: qpack_decoder_(kMaxDynamicTableCapacity, kMaximumBlockedStreams,
&encoder_stream_error_delegate_),
accumulator_(kTestStreamId, &qpack_decoder_, &visitor_,
kMaxHeaderListSize) {
qpack_decoder_.set_qpack_stream_sender_delegate(
&decoder_stream_sender_delegate_);
}
NoopEncoderStreamErrorDelegate encoder_stream_error_delegate_;
StrictMock<MockQpackStreamSenderDelegate> decoder_stream_sender_delegate_;
QpackDecoder qpack_decoder_;
StrictMock<MockVisitor> visitor_;
QpackDecodedHeadersAccumulator accumulator_;
};
TEST_F(QpackDecodedHeadersAccumulatorTest, EmptyPayload) {
EXPECT_CALL(visitor_,
OnHeaderDecodingError(QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Incomplete header data prefix.")));
accumulator_.EndHeaderBlock();
}
TEST_F(QpackDecodedHeadersAccumulatorTest, TruncatedHeaderBlockPrefix) {
std::string encoded_data;
ASSERT_TRUE(absl::HexStringToBytes("00", &encoded_data));
accumulator_.Decode(encoded_data);
EXPECT_CALL(visitor_,
OnHeaderDecodingError(QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Incomplete header data prefix.")));
accumulator_.EndHeaderBlock();
}
TEST_F(QpackDecodedHeadersAccumulatorTest, EmptyHeaderList) {
std::string encoded_data;
ASSERT_TRUE(absl::HexStringToBytes("0000", &encoded_data));
accumulator_.Decode(encoded_data);
QuicHeaderList header_list;
EXPECT_CALL(visitor_, OnHeadersDecoded(_, false))
.WillOnce(SaveArg<0>(&header_list));
accumulator_.EndHeaderBlock();
EXPECT_EQ(0u, header_list.uncompressed_header_bytes());
EXPECT_EQ(encoded_data.size(), header_list.compressed_header_bytes());
EXPECT_TRUE(header_list.empty());
}
TEST_F(QpackDecodedHeadersAccumulatorTest, TruncatedPayload) {
std::string encoded_data;
ASSERT_TRUE(absl::HexStringToBytes("00002366", &encoded_data));
accumulator_.Decode(encoded_data);
EXPECT_CALL(visitor_, OnHeaderDecodingError(QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Incomplete header block.")));
accumulator_.EndHeaderBlock();
}
TEST_F(QpackDecodedHeadersAccumulatorTest, InvalidPayload) {
EXPECT_CALL(visitor_,
OnHeaderDecodingError(QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Static table entry not found.")));
std::string encoded_data;
ASSERT_TRUE(absl::HexStringToBytes("0000ff23ff24", &encoded_data));
accumulator_.Decode(encoded_data);
}
TEST_F(QpackDecodedHeadersAccumulatorTest, Success) {
std::string encoded_data;
ASSERT_TRUE(absl::HexStringToBytes("000023666f6f03626172", &encoded_data));
accumulator_.Decode(encoded_data);
QuicHeaderList header_list;
EXPECT_CALL(visitor_, OnHeadersDecoded(_, false))
.WillOnce(SaveArg<0>(&header_list));
accumulator_.EndHeaderBlock();
EXPECT_THAT(header_list, ElementsAre(Pair("foo", "bar")));
EXPECT_EQ(strlen("foo") + strlen("bar"),
header_list.uncompressed_header_bytes());
EXPECT_EQ(encoded_data.size(), header_list.compressed_header_bytes());
}
TEST_F(QpackDecodedHeadersAccumulatorTest, ExceedLimitThenSplitInstruction) {
std::string encoded_data;
ASSERT_TRUE(absl::HexStringToBytes(
"0000"
"26666f6f626172"
"7d61616161616161616161616161616161616161"
"616161616161616161616161616161616161616161616161616161616161616161616161"
"616161616161616161616161616161616161616161616161616161616161616161616161"
"61616161616161616161616161616161616161616161616161616161616161616161"
"ff",
&encoded_data));
accumulator_.Decode(encoded_data);
ASSERT_TRUE(absl::HexStringToBytes(
"0f",
&encoded_data));
accumulator_.Decode(encoded_data);
EXPECT_CALL(visitor_, OnHeadersDecoded(_, true));
accumulator_.EndHeaderBlock();
}
TEST_F(QpackDecodedHeadersAccumulatorTest, ExceedLimitBlocked) {
std::string encoded_data;
ASSERT_TRUE(absl::HexStringToBytes(
"0200"
"80"
"26666f6f626172"
"7d61616161616161616161616161616161616161"
"616161616161616161616161616161616161616161616161616161616161616161616161"
"616161616161616161616161616161616161616161616161616161616161616161616161"
"61616161616161616161616161616161616161616161616161616161616161616161",
&encoded_data));
accumulator_.Decode(encoded_data);
accumulator_.EndHeaderBlock();
qpack_decoder_.OnSetDynamicTableCapacity(kMaxDynamicTableCapacity);
EXPECT_CALL(decoder_stream_sender_delegate_,
WriteStreamData(Eq(kHeaderAcknowledgement)));
EXPECT_CALL(visitor_, OnHeadersDecoded(_, true));
qpack_decoder_.OnInsertWithoutNameReference("foo", "bar");
qpack_decoder_.FlushDecoderStream();
}
TEST_F(QpackDecodedHeadersAccumulatorTest, BlockedDecoding) {
std::string encoded_data;
ASSERT_TRUE(absl::HexStringToBytes("020080", &encoded_data));
accumulator_.Decode(encoded_data);
accumulator_.EndHeaderBlock();
qpack_decoder_.OnSetDynamicTableCapacity(kMaxDynamicTableCapacity);
EXPECT_CALL(decoder_stream_sender_delegate_,
WriteStreamData(Eq(kHeaderAcknowledgement)));
QuicHeaderList header_list;
EXPECT_CALL(visitor_, OnHeadersDecoded(_, false))
.WillOnce(SaveArg<0>(&header_list));
qpack_decoder_.OnInsertWithoutNameReference("foo", "bar");
EXPECT_THAT(header_list, ElementsAre(Pair("foo", "bar")));
EXPECT_EQ(strlen("foo") + strlen("bar"),
header_list.uncompressed_header_bytes());
EXPECT_EQ(encoded_data.size(), header_list.compressed_header_bytes());
qpack_decoder_.FlushDecoderStream();
}
TEST_F(QpackDecodedHeadersAccumulatorTest,
BlockedDecodingUnblockedBeforeEndOfHeaderBlock) {
std::string encoded_data;
ASSERT_TRUE(absl::HexStringToBytes("020080", &encoded_data));
accumulator_.Decode(encoded_data);
qpack_decoder_.OnSetDynamicTableCapacity(kMaxDynamicTableCapacity);
qpack_decoder_.OnInsertWithoutNameReference("foo", "bar");
EXPECT_CALL(decoder_stream_sender_delegate_,
WriteStreamData(Eq(kHeaderAcknowledgement)));
ASSERT_TRUE(absl::HexStringToBytes("80", &encoded_data));
accumulator_.Decode(encoded_data);
QuicHeaderList header_list;
EXPECT_CALL(visitor_, OnHeadersDecoded(_, false))
.WillOnce(SaveArg<0>(&header_list));
accumulator_.EndHeaderBlock();
EXPECT_THAT(header_list, ElementsAre(Pair("foo", "bar"), Pair("foo", "bar")));
qpack_decoder_.FlushDecoderStream();
}
TEST_F(QpackDecodedHeadersAccumulatorTest,
BlockedDecodingUnblockedAndErrorBeforeEndOfHeaderBlock) {
std::string encoded_data;
ASSERT_TRUE(absl::HexStringToBytes("0200", &encoded_data));
accumulator_.Decode(encoded_data);
ASSERT_TRUE(absl::HexStringToBytes("80", &encoded_data));
accumulator_.Decode(encoded_data);
ASSERT_TRUE(absl::HexStringToBytes("81", &encoded_data));
accumulator_.Decode(encoded_data);
qpack_decoder_.OnSetDynamicTableCapacity(kMaxDynamicTableCapacity);
EXPECT_CALL(visitor_, OnHeaderDecodingError(QUIC_QPACK_DECOMPRESSION_FAILED,
Eq("Invalid relative index.")));
qpack_decoder_.OnInsertWithoutNameReference("foo", "bar");
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_decoded_headers_accumulator.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_decoded_headers_accumulator_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
8048927d-21bf-46dd-b380-1c7f05f9afa0 | cpp | google/quiche | qpack_decoder_stream_receiver | quiche/quic/core/qpack/qpack_decoder_stream_receiver.cc | quiche/quic/core/qpack/qpack_decoder_stream_receiver_test.cc | #include "quiche/quic/core/qpack/qpack_decoder_stream_receiver.h"
#include "absl/strings/string_view.h"
#include "quiche/http2/decoder/decode_buffer.h"
#include "quiche/http2/decoder/decode_status.h"
#include "quiche/quic/core/qpack/qpack_instructions.h"
namespace quic {
QpackDecoderStreamReceiver::QpackDecoderStreamReceiver(Delegate* delegate)
: instruction_decoder_(QpackDecoderStreamLanguage(), this),
delegate_(delegate),
error_detected_(false) {
QUICHE_DCHECK(delegate_);
}
void QpackDecoderStreamReceiver::Decode(absl::string_view data) {
if (data.empty() || error_detected_) {
return;
}
instruction_decoder_.Decode(data);
}
bool QpackDecoderStreamReceiver::OnInstructionDecoded(
const QpackInstruction* instruction) {
if (instruction == InsertCountIncrementInstruction()) {
delegate_->OnInsertCountIncrement(instruction_decoder_.varint());
return true;
}
if (instruction == HeaderAcknowledgementInstruction()) {
delegate_->OnHeaderAcknowledgement(instruction_decoder_.varint());
return true;
}
QUICHE_DCHECK_EQ(instruction, StreamCancellationInstruction());
delegate_->OnStreamCancellation(instruction_decoder_.varint());
return true;
}
void QpackDecoderStreamReceiver::OnInstructionDecodingError(
QpackInstructionDecoder::ErrorCode error_code,
absl::string_view error_message) {
QUICHE_DCHECK(!error_detected_);
error_detected_ = true;
QuicErrorCode quic_error_code =
(error_code == QpackInstructionDecoder::ErrorCode::INTEGER_TOO_LARGE)
? QUIC_QPACK_DECODER_STREAM_INTEGER_TOO_LARGE
: QUIC_INTERNAL_ERROR;
delegate_->OnErrorDetected(quic_error_code, error_message);
}
} | #include "quiche/quic/core/qpack/qpack_decoder_stream_receiver.h"
#include <string>
#include "absl/strings/escaping.h"
#include "absl/strings/string_view.h"
#include "quiche/quic/platform/api/quic_test.h"
using testing::Eq;
using testing::StrictMock;
namespace quic {
namespace test {
namespace {
class MockDelegate : public QpackDecoderStreamReceiver::Delegate {
public:
~MockDelegate() override = default;
MOCK_METHOD(void, OnInsertCountIncrement, (uint64_t increment), (override));
MOCK_METHOD(void, OnHeaderAcknowledgement, (QuicStreamId stream_id),
(override));
MOCK_METHOD(void, OnStreamCancellation, (QuicStreamId stream_id), (override));
MOCK_METHOD(void, OnErrorDetected,
(QuicErrorCode error_code, absl::string_view error_message),
(override));
};
class QpackDecoderStreamReceiverTest : public QuicTest {
protected:
QpackDecoderStreamReceiverTest() : stream_(&delegate_) {}
~QpackDecoderStreamReceiverTest() override = default;
QpackDecoderStreamReceiver stream_;
StrictMock<MockDelegate> delegate_;
};
TEST_F(QpackDecoderStreamReceiverTest, InsertCountIncrement) {
std::string encoded_data;
EXPECT_CALL(delegate_, OnInsertCountIncrement(0));
ASSERT_TRUE(absl::HexStringToBytes("00", &encoded_data));
stream_.Decode(encoded_data);
EXPECT_CALL(delegate_, OnInsertCountIncrement(10));
ASSERT_TRUE(absl::HexStringToBytes("0a", &encoded_data));
stream_.Decode(encoded_data);
EXPECT_CALL(delegate_, OnInsertCountIncrement(63));
ASSERT_TRUE(absl::HexStringToBytes("3f00", &encoded_data));
stream_.Decode(encoded_data);
EXPECT_CALL(delegate_, OnInsertCountIncrement(200));
ASSERT_TRUE(absl::HexStringToBytes("3f8901", &encoded_data));
stream_.Decode(encoded_data);
EXPECT_CALL(delegate_,
OnErrorDetected(QUIC_QPACK_DECODER_STREAM_INTEGER_TOO_LARGE,
Eq("Encoded integer too large.")));
ASSERT_TRUE(absl::HexStringToBytes("3fffffffffffffffffffff", &encoded_data));
stream_.Decode(encoded_data);
}
TEST_F(QpackDecoderStreamReceiverTest, HeaderAcknowledgement) {
std::string encoded_data;
EXPECT_CALL(delegate_, OnHeaderAcknowledgement(0));
ASSERT_TRUE(absl::HexStringToBytes("80", &encoded_data));
stream_.Decode(encoded_data);
EXPECT_CALL(delegate_, OnHeaderAcknowledgement(37));
ASSERT_TRUE(absl::HexStringToBytes("a5", &encoded_data));
stream_.Decode(encoded_data);
EXPECT_CALL(delegate_, OnHeaderAcknowledgement(127));
ASSERT_TRUE(absl::HexStringToBytes("ff00", &encoded_data));
stream_.Decode(encoded_data);
EXPECT_CALL(delegate_, OnHeaderAcknowledgement(503));
ASSERT_TRUE(absl::HexStringToBytes("fff802", &encoded_data));
stream_.Decode(encoded_data);
EXPECT_CALL(delegate_,
OnErrorDetected(QUIC_QPACK_DECODER_STREAM_INTEGER_TOO_LARGE,
Eq("Encoded integer too large.")));
ASSERT_TRUE(absl::HexStringToBytes("ffffffffffffffffffffff", &encoded_data));
stream_.Decode(encoded_data);
}
TEST_F(QpackDecoderStreamReceiverTest, StreamCancellation) {
std::string encoded_data;
EXPECT_CALL(delegate_, OnStreamCancellation(0));
ASSERT_TRUE(absl::HexStringToBytes("40", &encoded_data));
stream_.Decode(encoded_data);
EXPECT_CALL(delegate_, OnStreamCancellation(19));
ASSERT_TRUE(absl::HexStringToBytes("53", &encoded_data));
stream_.Decode(encoded_data);
EXPECT_CALL(delegate_, OnStreamCancellation(63));
ASSERT_TRUE(absl::HexStringToBytes("7f00", &encoded_data));
stream_.Decode(encoded_data);
EXPECT_CALL(delegate_, OnStreamCancellation(110));
ASSERT_TRUE(absl::HexStringToBytes("7f2f", &encoded_data));
stream_.Decode(encoded_data);
EXPECT_CALL(delegate_,
OnErrorDetected(QUIC_QPACK_DECODER_STREAM_INTEGER_TOO_LARGE,
Eq("Encoded integer too large.")));
ASSERT_TRUE(absl::HexStringToBytes("7fffffffffffffffffffff", &encoded_data));
stream_.Decode(encoded_data);
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_decoder_stream_receiver.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_decoder_stream_receiver_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
ae67bc64-b853-4709-87f0-6b41af73742a | cpp | google/quiche | qpack_instruction_encoder | quiche/quic/core/qpack/qpack_instruction_encoder.cc | quiche/quic/core/qpack/qpack_instruction_encoder_test.cc | #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::HuffmanEncode(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"));
}
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_instruction_encoder.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_instruction_encoder_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
552ac37d-9222-4206-ba65-c3ddaa1f19e1 | cpp | google/quiche | qpack_blocking_manager | quiche/quic/core/qpack/qpack_blocking_manager.cc | quiche/quic/core/qpack/qpack_blocking_manager_test.cc | #include "quiche/quic/core/qpack/qpack_blocking_manager.h"
#include <limits>
#include <utility>
namespace quic {
QpackBlockingManager::QpackBlockingManager() : known_received_count_(0) {}
bool QpackBlockingManager::OnHeaderAcknowledgement(QuicStreamId stream_id) {
auto it = header_blocks_.find(stream_id);
if (it == header_blocks_.end()) {
return false;
}
QUICHE_DCHECK(!it->second.empty());
const IndexSet& indices = it->second.front();
QUICHE_DCHECK(!indices.empty());
const uint64_t required_index_count = RequiredInsertCount(indices);
if (known_received_count_ < required_index_count) {
known_received_count_ = required_index_count;
}
DecreaseReferenceCounts(indices);
it->second.pop_front();
if (it->second.empty()) {
header_blocks_.erase(it);
}
return true;
}
void QpackBlockingManager::OnStreamCancellation(QuicStreamId stream_id) {
auto it = header_blocks_.find(stream_id);
if (it == header_blocks_.end()) {
return;
}
for (const IndexSet& indices : it->second) {
DecreaseReferenceCounts(indices);
}
header_blocks_.erase(it);
}
bool QpackBlockingManager::OnInsertCountIncrement(uint64_t increment) {
if (increment >
std::numeric_limits<uint64_t>::max() - known_received_count_) {
return false;
}
known_received_count_ += increment;
return true;
}
void QpackBlockingManager::OnHeaderBlockSent(QuicStreamId stream_id,
IndexSet indices) {
QUICHE_DCHECK(!indices.empty());
IncreaseReferenceCounts(indices);
header_blocks_[stream_id].push_back(std::move(indices));
}
bool QpackBlockingManager::blocking_allowed_on_stream(
QuicStreamId stream_id, uint64_t maximum_blocked_streams) const {
if (header_blocks_.size() + 1 <= maximum_blocked_streams) {
return true;
}
if (maximum_blocked_streams == 0) {
return false;
}
uint64_t blocked_stream_count = 0;
for (const auto& header_blocks_for_stream : header_blocks_) {
for (const IndexSet& indices : header_blocks_for_stream.second) {
if (RequiredInsertCount(indices) > known_received_count_) {
if (header_blocks_for_stream.first == stream_id) {
return true;
}
++blocked_stream_count;
if (blocked_stream_count + 1 > maximum_blocked_streams) {
return false;
}
break;
}
}
}
return true;
}
uint64_t QpackBlockingManager::smallest_blocking_index() const {
return entry_reference_counts_.empty()
? std::numeric_limits<uint64_t>::max()
: entry_reference_counts_.begin()->first;
}
uint64_t QpackBlockingManager::RequiredInsertCount(const IndexSet& indices) {
return *indices.rbegin() + 1;
}
void QpackBlockingManager::IncreaseReferenceCounts(const IndexSet& indices) {
for (const uint64_t index : indices) {
auto it = entry_reference_counts_.lower_bound(index);
if (it != entry_reference_counts_.end() && it->first == index) {
++it->second;
} else {
entry_reference_counts_.insert(it, {index, 1});
}
}
}
void QpackBlockingManager::DecreaseReferenceCounts(const IndexSet& indices) {
for (const uint64_t index : indices) {
auto it = entry_reference_counts_.find(index);
QUICHE_DCHECK(it != entry_reference_counts_.end());
QUICHE_DCHECK_NE(0u, it->second);
if (it->second == 1) {
entry_reference_counts_.erase(it);
} else {
--it->second;
}
}
}
} | #include "quiche/quic/core/qpack/qpack_blocking_manager.h"
#include <limits>
#include "quiche/quic/platform/api/quic_test.h"
namespace quic {
namespace test {
class QpackBlockingManagerPeer {
public:
static bool stream_is_blocked(const QpackBlockingManager* manager,
QuicStreamId stream_id) {
for (const auto& header_blocks_for_stream : manager->header_blocks_) {
if (header_blocks_for_stream.first != stream_id) {
continue;
}
for (const auto& indices : header_blocks_for_stream.second) {
if (QpackBlockingManager::RequiredInsertCount(indices) >
manager->known_received_count_) {
return true;
}
}
}
return false;
}
};
namespace {
class QpackBlockingManagerTest : public QuicTest {
protected:
QpackBlockingManagerTest() = default;
~QpackBlockingManagerTest() override = default;
bool stream_is_blocked(QuicStreamId stream_id) const {
return QpackBlockingManagerPeer::stream_is_blocked(&manager_, stream_id);
}
QpackBlockingManager manager_;
};
TEST_F(QpackBlockingManagerTest, Empty) {
EXPECT_EQ(0u, manager_.known_received_count());
EXPECT_EQ(std::numeric_limits<uint64_t>::max(),
manager_.smallest_blocking_index());
EXPECT_FALSE(manager_.OnHeaderAcknowledgement(0));
EXPECT_FALSE(manager_.OnHeaderAcknowledgement(1));
}
TEST_F(QpackBlockingManagerTest, NotBlockedByInsertCountIncrement) {
EXPECT_TRUE(manager_.OnInsertCountIncrement(2));
manager_.OnHeaderBlockSent(0, {1, 0});
EXPECT_FALSE(stream_is_blocked(0));
}
TEST_F(QpackBlockingManagerTest, UnblockedByInsertCountIncrement) {
manager_.OnHeaderBlockSent(0, {1, 0});
EXPECT_TRUE(stream_is_blocked(0));
EXPECT_TRUE(manager_.OnInsertCountIncrement(2));
EXPECT_FALSE(stream_is_blocked(0));
}
TEST_F(QpackBlockingManagerTest, NotBlockedByHeaderAcknowledgement) {
manager_.OnHeaderBlockSent(0, {2, 1, 1});
EXPECT_TRUE(stream_is_blocked(0));
EXPECT_TRUE(manager_.OnHeaderAcknowledgement(0));
EXPECT_FALSE(stream_is_blocked(0));
manager_.OnHeaderBlockSent(1, {2, 2});
EXPECT_FALSE(stream_is_blocked(1));
}
TEST_F(QpackBlockingManagerTest, UnblockedByHeaderAcknowledgement) {
manager_.OnHeaderBlockSent(0, {2, 1, 1});
manager_.OnHeaderBlockSent(1, {2, 2});
EXPECT_TRUE(stream_is_blocked(0));
EXPECT_TRUE(stream_is_blocked(1));
EXPECT_TRUE(manager_.OnHeaderAcknowledgement(0));
EXPECT_FALSE(stream_is_blocked(0));
EXPECT_FALSE(stream_is_blocked(1));
}
TEST_F(QpackBlockingManagerTest, KnownReceivedCount) {
EXPECT_EQ(0u, manager_.known_received_count());
manager_.OnHeaderBlockSent(0, {0});
EXPECT_EQ(0u, manager_.known_received_count());
manager_.OnHeaderBlockSent(1, {1});
EXPECT_EQ(0u, manager_.known_received_count());
EXPECT_TRUE(manager_.OnHeaderAcknowledgement(0));
EXPECT_EQ(1u, manager_.known_received_count());
manager_.OnHeaderBlockSent(2, {5});
EXPECT_EQ(1u, manager_.known_received_count());
EXPECT_TRUE(manager_.OnHeaderAcknowledgement(1));
EXPECT_EQ(2u, manager_.known_received_count());
EXPECT_TRUE(manager_.OnInsertCountIncrement(2));
EXPECT_EQ(4u, manager_.known_received_count());
EXPECT_TRUE(manager_.OnHeaderAcknowledgement(2));
EXPECT_EQ(6u, manager_.known_received_count());
manager_.OnStreamCancellation(0);
EXPECT_EQ(6u, manager_.known_received_count());
manager_.OnHeaderBlockSent(0, {3});
EXPECT_EQ(6u, manager_.known_received_count());
EXPECT_TRUE(manager_.OnHeaderAcknowledgement(0));
EXPECT_EQ(6u, manager_.known_received_count());
manager_.OnHeaderBlockSent(1, {5});
EXPECT_EQ(6u, manager_.known_received_count());
EXPECT_TRUE(manager_.OnHeaderAcknowledgement(1));
EXPECT_EQ(6u, manager_.known_received_count());
}
TEST_F(QpackBlockingManagerTest, SmallestBlockingIndex) {
EXPECT_EQ(std::numeric_limits<uint64_t>::max(),
manager_.smallest_blocking_index());
manager_.OnHeaderBlockSent(0, {0});
EXPECT_EQ(0u, manager_.smallest_blocking_index());
manager_.OnHeaderBlockSent(1, {2});
EXPECT_EQ(0u, manager_.smallest_blocking_index());
EXPECT_TRUE(manager_.OnHeaderAcknowledgement(0));
EXPECT_EQ(2u, manager_.smallest_blocking_index());
manager_.OnHeaderBlockSent(1, {1});
EXPECT_EQ(1u, manager_.smallest_blocking_index());
EXPECT_TRUE(manager_.OnHeaderAcknowledgement(1));
EXPECT_EQ(1u, manager_.smallest_blocking_index());
EXPECT_TRUE(manager_.OnInsertCountIncrement(2));
EXPECT_EQ(1u, manager_.smallest_blocking_index());
manager_.OnStreamCancellation(1);
EXPECT_EQ(std::numeric_limits<uint64_t>::max(),
manager_.smallest_blocking_index());
}
TEST_F(QpackBlockingManagerTest, HeaderAcknowledgementsOnSingleStream) {
EXPECT_EQ(0u, manager_.known_received_count());
EXPECT_EQ(std::numeric_limits<uint64_t>::max(),
manager_.smallest_blocking_index());
manager_.OnHeaderBlockSent(0, {2, 1, 1});
EXPECT_EQ(0u, manager_.known_received_count());
EXPECT_TRUE(stream_is_blocked(0));
EXPECT_EQ(1u, manager_.smallest_blocking_index());
manager_.OnHeaderBlockSent(0, {1, 0});
EXPECT_EQ(0u, manager_.known_received_count());
EXPECT_TRUE(stream_is_blocked(0));
EXPECT_EQ(0u, manager_.smallest_blocking_index());
EXPECT_TRUE(manager_.OnHeaderAcknowledgement(0));
EXPECT_EQ(3u, manager_.known_received_count());
EXPECT_FALSE(stream_is_blocked(0));
EXPECT_EQ(0u, manager_.smallest_blocking_index());
manager_.OnHeaderBlockSent(0, {3});
EXPECT_EQ(3u, manager_.known_received_count());
EXPECT_TRUE(stream_is_blocked(0));
EXPECT_EQ(0u, manager_.smallest_blocking_index());
EXPECT_TRUE(manager_.OnHeaderAcknowledgement(0));
EXPECT_EQ(3u, manager_.known_received_count());
EXPECT_TRUE(stream_is_blocked(0));
EXPECT_EQ(3u, manager_.smallest_blocking_index());
EXPECT_TRUE(manager_.OnHeaderAcknowledgement(0));
EXPECT_EQ(4u, manager_.known_received_count());
EXPECT_FALSE(stream_is_blocked(0));
EXPECT_EQ(std::numeric_limits<uint64_t>::max(),
manager_.smallest_blocking_index());
EXPECT_FALSE(manager_.OnHeaderAcknowledgement(0));
}
TEST_F(QpackBlockingManagerTest, CancelStream) {
manager_.OnHeaderBlockSent(0, {3});
EXPECT_TRUE(stream_is_blocked(0));
EXPECT_EQ(3u, manager_.smallest_blocking_index());
manager_.OnHeaderBlockSent(0, {2});
EXPECT_TRUE(stream_is_blocked(0));
EXPECT_EQ(2u, manager_.smallest_blocking_index());
manager_.OnHeaderBlockSent(1, {4});
EXPECT_TRUE(stream_is_blocked(0));
EXPECT_TRUE(stream_is_blocked(1));
EXPECT_EQ(2u, manager_.smallest_blocking_index());
manager_.OnStreamCancellation(0);
EXPECT_FALSE(stream_is_blocked(0));
EXPECT_TRUE(stream_is_blocked(1));
EXPECT_EQ(4u, manager_.smallest_blocking_index());
manager_.OnStreamCancellation(1);
EXPECT_FALSE(stream_is_blocked(0));
EXPECT_FALSE(stream_is_blocked(1));
EXPECT_EQ(std::numeric_limits<uint64_t>::max(),
manager_.smallest_blocking_index());
}
TEST_F(QpackBlockingManagerTest, BlockingAllowedOnStream) {
const QuicStreamId kStreamId1 = 1;
const QuicStreamId kStreamId2 = 2;
const QuicStreamId kStreamId3 = 3;
EXPECT_FALSE(manager_.blocking_allowed_on_stream(kStreamId1, 0));
EXPECT_FALSE(manager_.blocking_allowed_on_stream(kStreamId2, 0));
EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId1, 1));
EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId2, 1));
manager_.OnHeaderBlockSent(kStreamId1, {0});
manager_.OnHeaderBlockSent(kStreamId1, {1});
EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId1, 1));
EXPECT_FALSE(manager_.blocking_allowed_on_stream(kStreamId2, 1));
EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId1, 2));
EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId2, 2));
manager_.OnHeaderBlockSent(kStreamId2, {2});
EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId1, 2));
EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId2, 2));
EXPECT_FALSE(manager_.blocking_allowed_on_stream(kStreamId3, 2));
EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId3, 3));
manager_.OnHeaderAcknowledgement(kStreamId1);
EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId1, 2));
EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId2, 2));
manager_.OnHeaderAcknowledgement(kStreamId1);
EXPECT_FALSE(manager_.blocking_allowed_on_stream(kStreamId1, 1));
EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId2, 1));
EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId1, 2));
EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId2, 2));
manager_.OnHeaderAcknowledgement(kStreamId2);
EXPECT_FALSE(manager_.blocking_allowed_on_stream(kStreamId1, 0));
EXPECT_FALSE(manager_.blocking_allowed_on_stream(kStreamId2, 0));
EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId1, 1));
EXPECT_TRUE(manager_.blocking_allowed_on_stream(kStreamId2, 1));
}
TEST_F(QpackBlockingManagerTest, InsertCountIncrementOverflow) {
EXPECT_TRUE(manager_.OnInsertCountIncrement(10));
EXPECT_EQ(10u, manager_.known_received_count());
EXPECT_FALSE(manager_.OnInsertCountIncrement(
std::numeric_limits<uint64_t>::max() - 5));
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_blocking_manager.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_blocking_manager_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
7d716e0e-d273-409d-bedb-bdd18c59e153 | cpp | google/quiche | qpack_encoder | quiche/quic/core/qpack/qpack_encoder.cc | quiche/quic/core/qpack/qpack_encoder_test.cc | #include "quiche/quic/core/qpack/qpack_encoder.h"
#include <algorithm>
#include <string>
#include <utility>
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "quiche/quic/core/qpack/qpack_index_conversions.h"
#include "quiche/quic/core/qpack/qpack_instruction_encoder.h"
#include "quiche/quic/core/qpack/qpack_required_insert_count.h"
#include "quiche/quic/core/qpack/value_splitting_header_list.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 float kDrainingFraction = 0.25;
}
QpackEncoder::QpackEncoder(
DecoderStreamErrorDelegate* decoder_stream_error_delegate,
HuffmanEncoding huffman_encoding, CookieCrumbling cookie_crumbling)
: huffman_encoding_(huffman_encoding),
cookie_crumbling_(cookie_crumbling),
decoder_stream_error_delegate_(decoder_stream_error_delegate),
decoder_stream_receiver_(this),
encoder_stream_sender_(huffman_encoding),
maximum_blocked_streams_(0),
header_list_count_(0) {
QUICHE_DCHECK(decoder_stream_error_delegate_);
}
QpackEncoder::~QpackEncoder() {}
QpackEncoder::Representation QpackEncoder::EncodeIndexedHeaderField(
bool is_static, uint64_t index,
QpackBlockingManager::IndexSet* referred_indices) {
if (!is_static) {
referred_indices->insert(index);
}
return Representation::IndexedHeaderField(is_static, index);
}
QpackEncoder::Representation
QpackEncoder::EncodeLiteralHeaderFieldWithNameReference(
bool is_static, uint64_t index, absl::string_view value,
QpackBlockingManager::IndexSet* referred_indices) {
if (!is_static) {
referred_indices->insert(index);
}
return Representation::LiteralHeaderFieldNameReference(is_static, index,
value);
}
QpackEncoder::Representation QpackEncoder::EncodeLiteralHeaderField(
absl::string_view name, absl::string_view value) {
return Representation::LiteralHeaderField(name, value);
}
QpackEncoder::Representations QpackEncoder::FirstPassEncode(
QuicStreamId stream_id, const quiche::HttpHeaderBlock& header_list,
QpackBlockingManager::IndexSet* referred_indices,
QuicByteCount* encoder_stream_sent_byte_count) {
const QuicByteCount initial_encoder_stream_buffered_byte_count =
encoder_stream_sender_.BufferedByteCount();
const bool can_write_to_encoder_stream = encoder_stream_sender_.CanWrite();
Representations representations;
representations.reserve(header_list.size());
const uint64_t known_received_count =
blocking_manager_.known_received_count();
uint64_t smallest_non_evictable_index = std::min(
blocking_manager_.smallest_blocking_index(), known_received_count);
const uint64_t draining_index =
header_table_.draining_index(kDrainingFraction);
const bool blocking_allowed = blocking_manager_.blocking_allowed_on_stream(
stream_id, maximum_blocked_streams_);
bool dynamic_table_insertion_blocked = false;
bool blocked_stream_limit_exhausted = false;
for (const auto& header :
ValueSplittingHeaderList(&header_list, cookie_crumbling_)) {
absl::string_view name = header.first;
absl::string_view value = header.second;
QpackEncoderHeaderTable::MatchResult match_result =
header_table_.FindHeaderField(name, value);
switch (match_result.match_type) {
case QpackEncoderHeaderTable::MatchType::kNameAndValue: {
if (match_result.is_static) {
representations.push_back(EncodeIndexedHeaderField(
match_result.is_static, match_result.index, referred_indices));
break;
}
if (match_result.index >= draining_index) {
if (!blocking_allowed && match_result.index >= known_received_count) {
blocked_stream_limit_exhausted = true;
} else {
representations.push_back(EncodeIndexedHeaderField(
match_result.is_static, match_result.index, referred_indices));
smallest_non_evictable_index =
std::min(smallest_non_evictable_index, match_result.index);
header_table_.set_dynamic_table_entry_referenced();
break;
}
} else {
if (!blocking_allowed) {
blocked_stream_limit_exhausted = true;
} else if (QpackEntry::Size(name, value) >
header_table_.MaxInsertSizeWithoutEvictingGivenEntry(
std::min(smallest_non_evictable_index,
match_result.index))) {
dynamic_table_insertion_blocked = true;
} else {
if (can_write_to_encoder_stream) {
encoder_stream_sender_.SendDuplicate(
QpackAbsoluteIndexToEncoderStreamRelativeIndex(
match_result.index,
header_table_.inserted_entry_count()));
uint64_t new_index = header_table_.InsertEntry(name, value);
representations.push_back(EncodeIndexedHeaderField(
match_result.is_static, new_index, referred_indices));
smallest_non_evictable_index =
std::min(smallest_non_evictable_index, match_result.index);
header_table_.set_dynamic_table_entry_referenced();
break;
}
}
}
QpackEncoderHeaderTable::MatchResult match_result_name_only =
header_table_.FindHeaderName(name);
if (match_result_name_only.match_type !=
QpackEncoderHeaderTable::MatchType::kName ||
(match_result_name_only.is_static == match_result.is_static &&
match_result_name_only.index == match_result.index)) {
representations.push_back(EncodeLiteralHeaderField(name, value));
break;
}
match_result = match_result_name_only;
ABSL_FALLTHROUGH_INTENDED;
}
case QpackEncoderHeaderTable::MatchType::kName: {
if (match_result.is_static) {
if (blocking_allowed &&
QpackEntry::Size(name, value) <=
header_table_.MaxInsertSizeWithoutEvictingGivenEntry(
smallest_non_evictable_index)) {
if (can_write_to_encoder_stream) {
encoder_stream_sender_.SendInsertWithNameReference(
match_result.is_static, match_result.index, value);
uint64_t new_index = header_table_.InsertEntry(name, value);
representations.push_back(EncodeIndexedHeaderField(
false, new_index, referred_indices));
smallest_non_evictable_index =
std::min<uint64_t>(smallest_non_evictable_index, new_index);
break;
}
}
representations.push_back(EncodeLiteralHeaderFieldWithNameReference(
match_result.is_static, match_result.index, value,
referred_indices));
break;
}
if (!blocking_allowed) {
blocked_stream_limit_exhausted = true;
} else if (QpackEntry::Size(name, value) >
header_table_.MaxInsertSizeWithoutEvictingGivenEntry(
std::min(smallest_non_evictable_index,
match_result.index))) {
dynamic_table_insertion_blocked = true;
} else {
if (can_write_to_encoder_stream) {
encoder_stream_sender_.SendInsertWithNameReference(
match_result.is_static,
QpackAbsoluteIndexToEncoderStreamRelativeIndex(
match_result.index, header_table_.inserted_entry_count()),
value);
uint64_t new_index = header_table_.InsertEntry(name, value);
representations.push_back(EncodeIndexedHeaderField(
match_result.is_static, new_index, referred_indices));
smallest_non_evictable_index =
std::min(smallest_non_evictable_index, match_result.index);
header_table_.set_dynamic_table_entry_referenced();
break;
}
}
if ((blocking_allowed || match_result.index < known_received_count) &&
match_result.index >= draining_index) {
representations.push_back(EncodeLiteralHeaderFieldWithNameReference(
match_result.is_static, match_result.index, value,
referred_indices));
smallest_non_evictable_index =
std::min(smallest_non_evictable_index, match_result.index);
header_table_.set_dynamic_table_entry_referenced();
break;
}
representations.push_back(EncodeLiteralHeaderField(name, value));
break;
}
case QpackEncoderHeaderTable::MatchType::kNoMatch: {
if (!blocking_allowed) {
blocked_stream_limit_exhausted = true;
} else if (QpackEntry::Size(name, value) >
header_table_.MaxInsertSizeWithoutEvictingGivenEntry(
smallest_non_evictable_index)) {
dynamic_table_insertion_blocked = true;
} else {
if (can_write_to_encoder_stream) {
encoder_stream_sender_.SendInsertWithoutNameReference(name, value);
uint64_t new_index = header_table_.InsertEntry(name, value);
representations.push_back(EncodeIndexedHeaderField(
false, new_index, referred_indices));
smallest_non_evictable_index =
std::min<uint64_t>(smallest_non_evictable_index, new_index);
break;
}
}
representations.push_back(EncodeLiteralHeaderField(name, value));
break;
}
}
}
const QuicByteCount encoder_stream_buffered_byte_count =
encoder_stream_sender_.BufferedByteCount();
QUICHE_DCHECK_GE(encoder_stream_buffered_byte_count,
initial_encoder_stream_buffered_byte_count);
if (encoder_stream_sent_byte_count) {
*encoder_stream_sent_byte_count =
encoder_stream_buffered_byte_count -
initial_encoder_stream_buffered_byte_count;
}
if (can_write_to_encoder_stream) {
encoder_stream_sender_.Flush();
} else {
QUICHE_DCHECK_EQ(encoder_stream_buffered_byte_count,
initial_encoder_stream_buffered_byte_count);
}
++header_list_count_;
if (dynamic_table_insertion_blocked) {
QUIC_HISTOGRAM_COUNTS(
"QuicSession.Qpack.HeaderListCountWhenInsertionBlocked",
header_list_count_, 1, 1000,
50,
"The ordinality of a header list within a connection during the "
"encoding of which at least one dynamic table insertion was "
"blocked.");
} else {
QUIC_HISTOGRAM_COUNTS(
"QuicSession.Qpack.HeaderListCountWhenInsertionNotBlocked",
header_list_count_, 1, 1000,
50,
"The ordinality of a header list within a connection during the "
"encoding of which no dynamic table insertion was blocked.");
}
if (blocked_stream_limit_exhausted) {
QUIC_HISTOGRAM_COUNTS(
"QuicSession.Qpack.HeaderListCountWhenBlockedStreamLimited",
header_list_count_, 1, 1000,
50,
"The ordinality of a header list within a connection during the "
"encoding of which unacknowledged dynamic table entries could not be "
"referenced due to the limit on the number of blocked streams.");
} else {
QUIC_HISTOGRAM_COUNTS(
"QuicSession.Qpack.HeaderListCountWhenNotBlockedStreamLimited",
header_list_count_, 1, 1000,
50,
"The ordinality of a header list within a connection during the "
"encoding of which the limit on the number of blocked streams did "
"not "
"prevent referencing unacknowledged dynamic table entries.");
}
return representations;
}
std::string QpackEncoder::SecondPassEncode(
QpackEncoder::Representations representations,
uint64_t required_insert_count) const {
QpackInstructionEncoder instruction_encoder(huffman_encoding_);
std::string encoded_headers;
instruction_encoder.Encode(
Representation::Prefix(QpackEncodeRequiredInsertCount(
required_insert_count, header_table_.max_entries())),
&encoded_headers);
const uint64_t base = required_insert_count;
for (auto& representation : representations) {
if ((representation.instruction() == QpackIndexedHeaderFieldInstruction() ||
representation.instruction() ==
QpackLiteralHeaderFieldNameReferenceInstruction()) &&
!representation.s_bit()) {
representation.set_varint(QpackAbsoluteIndexToRequestStreamRelativeIndex(
representation.varint(), base));
}
instruction_encoder.Encode(representation, &encoded_headers);
}
return encoded_headers;
}
std::string QpackEncoder::EncodeHeaderList(
QuicStreamId stream_id, const quiche::HttpHeaderBlock& header_list,
QuicByteCount* encoder_stream_sent_byte_count) {
QpackBlockingManager::IndexSet referred_indices;
Representations representations =
FirstPassEncode(stream_id, header_list, &referred_indices,
encoder_stream_sent_byte_count);
const uint64_t required_insert_count =
referred_indices.empty()
? 0
: QpackBlockingManager::RequiredInsertCount(referred_indices);
if (!referred_indices.empty()) {
blocking_manager_.OnHeaderBlockSent(stream_id, std::move(referred_indices));
}
return SecondPassEncode(std::move(representations), required_insert_count);
}
bool QpackEncoder::SetMaximumDynamicTableCapacity(
uint64_t maximum_dynamic_table_capacity) {
return header_table_.SetMaximumDynamicTableCapacity(
maximum_dynamic_table_capacity);
}
void QpackEncoder::SetDynamicTableCapacity(uint64_t dynamic_table_capacity) {
encoder_stream_sender_.SendSetDynamicTableCapacity(dynamic_table_capacity);
bool success = header_table_.SetDynamicTableCapacity(dynamic_table_capacity);
QUICHE_DCHECK(success);
}
bool QpackEncoder::SetMaximumBlockedStreams(uint64_t maximum_blocked_streams) {
if (maximum_blocked_streams < maximum_blocked_streams_) {
return false;
}
maximum_blocked_streams_ = maximum_blocked_streams;
return true;
}
void QpackEncoder::OnInsertCountIncrement(uint64_t increment) {
if (increment == 0) {
OnErrorDetected(QUIC_QPACK_DECODER_STREAM_INVALID_ZERO_INCREMENT,
"Invalid increment value 0.");
return;
}
if (!blocking_manager_.OnInsertCountIncrement(increment)) {
OnErrorDetected(QUIC_QPACK_DECODER_STREAM_INCREMENT_OVERFLOW,
"Insert Count Increment instruction causes overflow.");
}
if (blocking_manager_.known_received_count() >
header_table_.inserted_entry_count()) {
OnErrorDetected(QUIC_QPACK_DECODER_STREAM_IMPOSSIBLE_INSERT_COUNT,
absl::StrCat("Increment value ", increment,
" raises known received count to ",
blocking_manager_.known_received_count(),
" exceeding inserted entry count ",
header_table_.inserted_entry_count()));
}
}
void QpackEncoder::OnHeaderAcknowledgement(QuicStreamId stream_id) {
if (!blocking_manager_.OnHeaderAcknowledgement(stream_id)) {
OnErrorDetected(
QUIC_QPACK_DECODER_STREAM_INCORRECT_ACKNOWLEDGEMENT,
absl::StrCat("Header Acknowledgement received for stream ", stream_id,
" with no outstanding header blocks."));
}
}
void QpackEncoder::OnStreamCancellation(QuicStreamId stream_id) {
blocking_manager_.OnStreamCancellation(stream_id);
}
void QpackEncoder::OnErrorDetected(QuicErrorCode error_code,
absl::string_view error_message) {
decoder_stream_error_delegate_->OnDecoderStreamError(error_code,
error_message);
}
} | #include "quiche/quic/core/qpack/qpack_encoder.h"
#include <limits>
#include <string>
#include "absl/strings/escaping.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "quiche/quic/core/qpack/qpack_instruction_encoder.h"
#include "quiche/quic/core/qpack/value_splitting_header_list.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"
using ::testing::_;
using ::testing::Eq;
using ::testing::Return;
using ::testing::StrictMock;
namespace quic {
namespace test {
namespace {
constexpr uint64_t kTooManyBytesBuffered = 1024 * 1024;
std::string PrintToString(const testing::TestParamInfo<HuffmanEncoding>& info) {
switch (info.param) {
case HuffmanEncoding::kEnabled:
return "HuffmanEnabled";
case HuffmanEncoding::kDisabled:
return "HuffmanDisabled";
}
QUICHE_NOTREACHED();
return "InvalidValue";
}
class MockDecoderStreamErrorDelegate
: public QpackEncoder::DecoderStreamErrorDelegate {
public:
~MockDecoderStreamErrorDelegate() override = default;
MOCK_METHOD(void, OnDecoderStreamError,
(QuicErrorCode error_code, absl::string_view error_message),
(override));
};
class QpackEncoderTest : public QuicTestWithParam<HuffmanEncoding> {
protected:
QpackEncoderTest()
: huffman_encoding_(GetParam()),
encoder_(&decoder_stream_error_delegate_, huffman_encoding_,
CookieCrumbling::kEnabled),
encoder_stream_sent_byte_count_(0) {
encoder_.set_qpack_stream_sender_delegate(&encoder_stream_sender_delegate_);
encoder_.SetMaximumBlockedStreams(1);
}
~QpackEncoderTest() override = default;
bool HuffmanEnabled() const {
return huffman_encoding_ == HuffmanEncoding::kEnabled;
}
std::string Encode(const quiche::HttpHeaderBlock& header_list) {
return encoder_.EncodeHeaderList( 1, header_list,
&encoder_stream_sent_byte_count_);
}
const HuffmanEncoding huffman_encoding_;
StrictMock<MockDecoderStreamErrorDelegate> decoder_stream_error_delegate_;
StrictMock<MockQpackStreamSenderDelegate> encoder_stream_sender_delegate_;
QpackEncoder encoder_;
QuicByteCount encoder_stream_sent_byte_count_;
};
INSTANTIATE_TEST_SUITE_P(HuffmanEncoding, QpackEncoderTest,
::testing::ValuesIn({HuffmanEncoding::kEnabled,
HuffmanEncoding::kDisabled}),
PrintToString);
TEST_P(QpackEncoderTest, Empty) {
EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered())
.WillRepeatedly(Return(0));
quiche::HttpHeaderBlock header_list;
std::string output = Encode(header_list);
std::string expected_output;
ASSERT_TRUE(absl::HexStringToBytes("0000", &expected_output));
EXPECT_EQ(expected_output, output);
}
TEST_P(QpackEncoderTest, EmptyName) {
EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered())
.WillRepeatedly(Return(0));
quiche::HttpHeaderBlock header_list;
header_list[""] = "foo";
std::string output = Encode(header_list);
std::string expected_output;
if (HuffmanEnabled()) {
ASSERT_TRUE(absl::HexStringToBytes("0000208294e7", &expected_output));
} else {
ASSERT_TRUE(absl::HexStringToBytes("00002003666f6f", &expected_output));
}
EXPECT_EQ(expected_output, output);
}
TEST_P(QpackEncoderTest, EmptyValue) {
EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered())
.WillRepeatedly(Return(0));
quiche::HttpHeaderBlock header_list;
header_list["foo"] = "";
std::string output = Encode(header_list);
std::string expected_output;
if (HuffmanEnabled()) {
ASSERT_TRUE(absl::HexStringToBytes("00002a94e700", &expected_output));
} else {
ASSERT_TRUE(absl::HexStringToBytes("000023666f6f00", &expected_output));
}
EXPECT_EQ(expected_output, output);
}
TEST_P(QpackEncoderTest, EmptyNameAndValue) {
EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered())
.WillRepeatedly(Return(0));
quiche::HttpHeaderBlock header_list;
header_list[""] = "";
std::string output = Encode(header_list);
std::string expected_output;
ASSERT_TRUE(absl::HexStringToBytes("00002000", &expected_output));
EXPECT_EQ(expected_output, output);
}
TEST_P(QpackEncoderTest, Simple) {
EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered())
.WillRepeatedly(Return(0));
quiche::HttpHeaderBlock header_list;
header_list["foo"] = "bar";
std::string output = Encode(header_list);
std::string expected_output;
if (HuffmanEnabled()) {
ASSERT_TRUE(absl::HexStringToBytes("00002a94e703626172", &expected_output));
} else {
ASSERT_TRUE(
absl::HexStringToBytes("000023666f6f03626172", &expected_output));
}
EXPECT_EQ(expected_output, output);
}
TEST_P(QpackEncoderTest, Multiple) {
EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered())
.WillRepeatedly(Return(0));
quiche::HttpHeaderBlock header_list;
header_list["foo"] = "bar";
header_list["ZZZZZZZ"] = std::string(127, 'Z');
std::string output = Encode(header_list);
std::string expected_output_hex;
if (HuffmanEnabled()) {
expected_output_hex =
"0000"
"2a94e703626172";
} else {
expected_output_hex =
"0000"
"23666f6f03626172";
}
expected_output_hex +=
"27005a5a5a5a5a5a5a"
"7f005a5a5a5a5a5a5a"
"5a5a5a5a5a5a5a5a5a"
"5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a"
"5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a"
"5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a"
"5a5a5a5a5a5a5a5a5a";
std::string expected_output;
ASSERT_TRUE(absl::HexStringToBytes(expected_output_hex, &expected_output));
EXPECT_EQ(expected_output, output);
}
TEST_P(QpackEncoderTest, StaticTable) {
EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered())
.WillRepeatedly(Return(0));
{
quiche::HttpHeaderBlock header_list;
header_list[":method"] = "GET";
header_list["accept-encoding"] = "gzip, deflate, br";
header_list["location"] = "";
std::string output = Encode(header_list);
std::string expected_output;
ASSERT_TRUE(absl::HexStringToBytes("0000d1dfcc", &expected_output));
EXPECT_EQ(expected_output, output);
}
{
quiche::HttpHeaderBlock header_list;
header_list[":method"] = "POST";
header_list["accept-encoding"] = "compress";
header_list["location"] = "foo";
std::string output = Encode(header_list);
std::string expected_output;
if (HuffmanEnabled()) {
ASSERT_TRUE(absl::HexStringToBytes("0000d45f108621e9aec2a11f5c8294e7",
&expected_output));
} else {
ASSERT_TRUE(absl::HexStringToBytes(
"0000d45f1008636f6d70726573735c03666f6f", &expected_output));
}
EXPECT_EQ(expected_output, output);
}
{
quiche::HttpHeaderBlock header_list;
header_list[":method"] = "TRACE";
header_list["accept-encoding"] = "";
std::string output = Encode(header_list);
std::string expected_output;
ASSERT_TRUE(
absl::HexStringToBytes("00005f000554524143455f1000", &expected_output));
EXPECT_EQ(expected_output, output);
}
}
TEST_P(QpackEncoderTest, DecoderStreamError) {
EXPECT_CALL(decoder_stream_error_delegate_,
OnDecoderStreamError(QUIC_QPACK_DECODER_STREAM_INTEGER_TOO_LARGE,
Eq("Encoded integer too large.")));
QpackEncoder encoder(&decoder_stream_error_delegate_, huffman_encoding_,
CookieCrumbling::kEnabled);
encoder.set_qpack_stream_sender_delegate(&encoder_stream_sender_delegate_);
std::string input;
ASSERT_TRUE(absl::HexStringToBytes("ffffffffffffffffffffff", &input));
encoder.decoder_stream_receiver()->Decode(input);
}
TEST_P(QpackEncoderTest, SplitAlongNullCharacter) {
EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered())
.WillRepeatedly(Return(0));
quiche::HttpHeaderBlock header_list;
header_list["foo"] = absl::string_view("bar\0bar\0baz", 11);
std::string output = Encode(header_list);
std::string expected_output;
if (HuffmanEnabled()) {
ASSERT_TRUE(
absl::HexStringToBytes("0000"
"2a94e703626172"
"2a94e703626172"
"2a94e70362617a",
&expected_output));
} else {
ASSERT_TRUE(
absl::HexStringToBytes("0000"
"23666f6f03626172"
"23666f6f03626172"
"23666f6f0362617a",
&expected_output));
}
EXPECT_EQ(expected_output, output);
}
TEST_P(QpackEncoderTest, ZeroInsertCountIncrement) {
EXPECT_CALL(
decoder_stream_error_delegate_,
OnDecoderStreamError(QUIC_QPACK_DECODER_STREAM_INVALID_ZERO_INCREMENT,
Eq("Invalid increment value 0.")));
encoder_.OnInsertCountIncrement(0);
}
TEST_P(QpackEncoderTest, TooLargeInsertCountIncrement) {
EXPECT_CALL(
decoder_stream_error_delegate_,
OnDecoderStreamError(QUIC_QPACK_DECODER_STREAM_IMPOSSIBLE_INSERT_COUNT,
Eq("Increment value 1 raises known received count "
"to 1 exceeding inserted entry count 0")));
encoder_.OnInsertCountIncrement(1);
}
TEST_P(QpackEncoderTest, InsertCountIncrementOverflow) {
QpackEncoderHeaderTable* header_table =
QpackEncoderPeer::header_table(&encoder_);
header_table->SetMaximumDynamicTableCapacity(4096);
header_table->SetDynamicTableCapacity(4096);
header_table->InsertEntry("foo", "bar");
encoder_.OnInsertCountIncrement(1);
EXPECT_CALL(decoder_stream_error_delegate_,
OnDecoderStreamError(
QUIC_QPACK_DECODER_STREAM_INCREMENT_OVERFLOW,
Eq("Insert Count Increment instruction causes overflow.")));
encoder_.OnInsertCountIncrement(std::numeric_limits<uint64_t>::max());
}
TEST_P(QpackEncoderTest, InvalidHeaderAcknowledgement) {
EXPECT_CALL(
decoder_stream_error_delegate_,
OnDecoderStreamError(QUIC_QPACK_DECODER_STREAM_INCORRECT_ACKNOWLEDGEMENT,
Eq("Header Acknowledgement received for stream 0 "
"with no outstanding header blocks.")));
encoder_.OnHeaderAcknowledgement( 0);
}
TEST_P(QpackEncoderTest, DynamicTable) {
EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered())
.WillRepeatedly(Return(0));
encoder_.SetMaximumBlockedStreams(1);
encoder_.SetMaximumDynamicTableCapacity(4096);
encoder_.SetDynamicTableCapacity(4096);
quiche::HttpHeaderBlock header_list;
header_list["foo"] = "bar";
header_list.AppendValueOrAddHeader("foo",
"baz");
header_list["cookie"] = "baz";
std::string set_dyanamic_table_capacity;
ASSERT_TRUE(absl::HexStringToBytes("3fe11f", &set_dyanamic_table_capacity));
std::string insert_entries_hex;
if (HuffmanEnabled()) {
insert_entries_hex =
"62"
"94e7";
} else {
insert_entries_hex =
"43"
"666f6f";
}
insert_entries_hex +=
"03626172"
"80"
"0362617a"
"c5"
"0362617a";
std::string insert_entries;
ASSERT_TRUE(absl::HexStringToBytes(insert_entries_hex, &insert_entries));
EXPECT_CALL(encoder_stream_sender_delegate_,
WriteStreamData(Eq(
absl::StrCat(set_dyanamic_table_capacity, insert_entries))));
std::string expected_output;
ASSERT_TRUE(absl::HexStringToBytes(
"0400"
"828180",
&expected_output));
EXPECT_EQ(expected_output, Encode(header_list));
EXPECT_EQ(insert_entries.size(), encoder_stream_sent_byte_count_);
}
TEST_P(QpackEncoderTest, SmallDynamicTable) {
EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered())
.WillRepeatedly(Return(0));
encoder_.SetMaximumBlockedStreams(1);
encoder_.SetMaximumDynamicTableCapacity(QpackEntry::Size("foo", "bar"));
encoder_.SetDynamicTableCapacity(QpackEntry::Size("foo", "bar"));
quiche::HttpHeaderBlock header_list;
header_list["foo"] = "bar";
header_list.AppendValueOrAddHeader("foo",
"baz");
header_list["cookie"] = "baz";
header_list["bar"] = "baz";
std::string set_dyanamic_table_capacity;
ASSERT_TRUE(absl::HexStringToBytes("3f07", &set_dyanamic_table_capacity));
std::string insert_entry;
if (HuffmanEnabled()) {
ASSERT_TRUE(
absl::HexStringToBytes("62"
"94e7"
"03626172",
&insert_entry));
} else {
ASSERT_TRUE(
absl::HexStringToBytes("43"
"666f6f"
"03626172",
&insert_entry));
}
EXPECT_CALL(encoder_stream_sender_delegate_,
WriteStreamData(
Eq(absl::StrCat(set_dyanamic_table_capacity, insert_entry))));
std::string expected_output;
ASSERT_TRUE(
absl::HexStringToBytes("0200"
"80"
"40"
"0362617a"
"55"
"0362617a"
"23626172"
"0362617a",
&expected_output));
EXPECT_EQ(expected_output, Encode(header_list));
EXPECT_EQ(insert_entry.size(), encoder_stream_sent_byte_count_);
}
TEST_P(QpackEncoderTest, BlockedStream) {
EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered())
.WillRepeatedly(Return(0));
encoder_.SetMaximumBlockedStreams(1);
encoder_.SetMaximumDynamicTableCapacity(4096);
encoder_.SetDynamicTableCapacity(4096);
quiche::HttpHeaderBlock header_list1;
header_list1["foo"] = "bar";
std::string set_dyanamic_table_capacity;
ASSERT_TRUE(absl::HexStringToBytes("3fe11f", &set_dyanamic_table_capacity));
std::string insert_entry1;
if (HuffmanEnabled()) {
ASSERT_TRUE(
absl::HexStringToBytes("62"
"94e7"
"03626172",
&insert_entry1));
} else {
ASSERT_TRUE(
absl::HexStringToBytes("43"
"666f6f"
"03626172",
&insert_entry1));
}
EXPECT_CALL(encoder_stream_sender_delegate_,
WriteStreamData(Eq(
absl::StrCat(set_dyanamic_table_capacity, insert_entry1))));
std::string expected_output;
ASSERT_TRUE(
absl::HexStringToBytes("0200"
"80",
&expected_output));
EXPECT_EQ(expected_output,
encoder_.EncodeHeaderList( 1, header_list1,
&encoder_stream_sent_byte_count_));
EXPECT_EQ(insert_entry1.size(), encoder_stream_sent_byte_count_);
quiche::HttpHeaderBlock header_list2;
header_list2["foo"] = "bar";
header_list2.AppendValueOrAddHeader("foo",
"baz");
header_list2["cookie"] = "baz";
header_list2["bar"] = "baz";
std::string entries;
if (HuffmanEnabled()) {
ASSERT_TRUE(
absl::HexStringToBytes("0000"
"2a94e7"
"03626172"
"2a94e7"
"0362617a"
"55"
"0362617a"
"23626172"
"0362617a",
&entries));
} else {
ASSERT_TRUE(
absl::HexStringToBytes("0000"
"23666f6f"
"03626172"
"23666f6f"
"0362617a"
"55"
"0362617a"
"23626172"
"0362617a",
&entries));
}
EXPECT_EQ(entries,
encoder_.EncodeHeaderList( 2, header_list2,
&encoder_stream_sent_byte_count_));
EXPECT_EQ(0u, encoder_stream_sent_byte_count_);
encoder_.OnInsertCountIncrement(1);
std::string insert_entries;
ASSERT_TRUE(absl::HexStringToBytes(
"80"
"0362617a"
"c5"
"0362617a"
"43"
"626172"
"0362617a",
&insert_entries));
EXPECT_CALL(encoder_stream_sender_delegate_,
WriteStreamData(Eq(insert_entries)));
ASSERT_TRUE(
absl::HexStringToBytes("0500"
"83828180",
&expected_output));
EXPECT_EQ(expected_output,
encoder_.EncodeHeaderList( 3, header_list2,
&encoder_stream_sent_byte_count_));
EXPECT_EQ(insert_entries.size(), encoder_stream_sent_byte_count_);
std::string expected2;
if (HuffmanEnabled()) {
ASSERT_TRUE(
absl::HexStringToBytes("0200"
"80"
"2a94e7"
"0362617a"
"55"
"0362617a"
"23626172"
"0362617a",
&expected2));
} else {
ASSERT_TRUE(
absl::HexStringToBytes("0200"
"80"
"23666f6f"
"0362617a"
"55"
"0362617a"
"23626172"
"0362617a",
&expected2));
}
EXPECT_EQ(expected2,
encoder_.EncodeHeaderList( 4, header_list2,
&encoder_stream_sent_byte_count_));
EXPECT_EQ(0u, encoder_stream_sent_byte_count_);
encoder_.OnInsertCountIncrement(2);
std::string expected3;
ASSERT_TRUE(
absl::HexStringToBytes("0400"
"828180"
"23626172"
"0362617a",
&expected3));
EXPECT_EQ(expected3,
encoder_.EncodeHeaderList( 5, header_list2,
&encoder_stream_sent_byte_count_));
EXPECT_EQ(0u, encoder_stream_sent_byte_count_);
encoder_.OnHeaderAcknowledgement(3);
std::string expected4;
ASSERT_TRUE(
absl::HexStringToBytes("0500"
"83828180",
&expected4));
EXPECT_EQ(expected4,
encoder_.EncodeHeaderList( 6, header_list2,
&encoder_stream_sent_byte_count_));
EXPECT_EQ(0u, encoder_stream_sent_byte_count_);
}
TEST_P(QpackEncoderTest, Draining) {
EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered())
.WillRepeatedly(Return(0));
quiche::HttpHeaderBlock header_list1;
header_list1["one"] = "foo";
header_list1["two"] = "foo";
header_list1["three"] = "foo";
header_list1["four"] = "foo";
header_list1["five"] = "foo";
header_list1["six"] = "foo";
header_list1["seven"] = "foo";
header_list1["eight"] = "foo";
header_list1["nine"] = "foo";
header_list1["ten"] = "foo";
uint64_t maximum_dynamic_table_capacity = 0;
for (const auto& header_field : header_list1) {
maximum_dynamic_table_capacity +=
QpackEntry::Size(header_field.first, header_field.second);
}
maximum_dynamic_table_capacity += QpackEntry::Size("one", "foo");
encoder_.SetMaximumDynamicTableCapacity(maximum_dynamic_table_capacity);
encoder_.SetDynamicTableCapacity(maximum_dynamic_table_capacity);
EXPECT_CALL(encoder_stream_sender_delegate_, WriteStreamData(_));
std::string expected_output;
ASSERT_TRUE(
absl::HexStringToBytes("0b00"
"89888786858483828180",
&expected_output));
EXPECT_EQ(expected_output, Encode(header_list1));
quiche::HttpHeaderBlock header_list2;
header_list2["one"] = "foo";
ASSERT_TRUE(absl::HexStringToBytes("09", &expected_output));
EXPECT_CALL(encoder_stream_sender_delegate_,
WriteStreamData(Eq(expected_output)));
ASSERT_TRUE(
absl::HexStringToBytes("0c00"
"80",
&expected_output));
EXPECT_EQ(expected_output, Encode(header_list2));
quiche::HttpHeaderBlock header_list3;
header_list3.AppendValueOrAddHeader("two", "foo");
header_list3.AppendValueOrAddHeader("two", "bar");
std::string entries =
"0000"
"2374776f";
if (HuffmanEnabled()) {
entries += "8294e7";
} else {
entries += "03666f6f";
}
entries +=
"2374776f"
"03626172";
ASSERT_TRUE(absl::HexStringToBytes(entries, &expected_output));
EXPECT_EQ(expected_output, Encode(header_list3));
}
TEST_P(QpackEncoderTest, DynamicTableCapacityLessThanMaximum) {
encoder_.SetMaximumDynamicTableCapacity(1024);
encoder_.SetDynamicTableCapacity(30);
QpackEncoderHeaderTable* header_table =
QpackEncoderPeer::header_table(&encoder_);
EXPECT_EQ(1024u, header_table->maximum_dynamic_table_capacity());
EXPECT_EQ(30u, header_table->dynamic_table_capacity());
}
TEST_P(QpackEncoderTest, EncoderStreamWritesDisallowedThenAllowed) {
EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered())
.WillRepeatedly(Return(kTooManyBytesBuffered));
encoder_.SetMaximumBlockedStreams(1);
encoder_.SetMaximumDynamicTableCapacity(4096);
encoder_.SetDynamicTableCapacity(4096);
quiche::HttpHeaderBlock header_list1;
header_list1["foo"] = "bar";
header_list1.AppendValueOrAddHeader("foo", "baz");
header_list1["cookie"] = "baz";
std::string entries;
if (HuffmanEnabled()) {
ASSERT_TRUE(
absl::HexStringToBytes("0000"
"2a94e7"
"03626172"
"2a94e7"
"0362617a"
"55"
"0362617a",
&entries));
} else {
ASSERT_TRUE(
absl::HexStringToBytes("0000"
"23666f6f"
"03626172"
"23666f6f"
"0362617a"
"55"
"0362617a",
&entries));
}
EXPECT_EQ(entries, Encode(header_list1));
EXPECT_EQ(0u, encoder_stream_sent_byte_count_);
::testing::Mock::VerifyAndClearExpectations(&encoder_stream_sender_delegate_);
EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered())
.WillRepeatedly(Return(0));
quiche::HttpHeaderBlock header_list2;
header_list2["foo"] = "bar";
header_list2.AppendValueOrAddHeader("foo",
"baz");
header_list2["cookie"] = "baz";
std::string set_dyanamic_table_capacity;
ASSERT_TRUE(absl::HexStringToBytes("3fe11f", &set_dyanamic_table_capacity));
std::string insert_entries_hex;
if (HuffmanEnabled()) {
insert_entries_hex =
"62"
"94e7";
} else {
insert_entries_hex =
"43"
"666f6f";
}
insert_entries_hex +=
"03626172"
"80"
"0362617a"
"c5"
"0362617a";
std::string insert_entries;
ASSERT_TRUE(absl::HexStringToBytes(insert_entries_hex, &insert_entries));
EXPECT_CALL(encoder_stream_sender_delegate_,
WriteStreamData(Eq(
absl::StrCat(set_dyanamic_table_capacity, insert_entries))));
std::string expected_output;
ASSERT_TRUE(absl::HexStringToBytes(
"0400"
"828180",
&expected_output));
EXPECT_EQ(expected_output, Encode(header_list2));
EXPECT_EQ(insert_entries.size(), encoder_stream_sent_byte_count_);
}
TEST_P(QpackEncoderTest, EncoderStreamWritesAllowedThenDisallowed) {
EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered())
.WillRepeatedly(Return(0));
encoder_.SetMaximumBlockedStreams(1);
encoder_.SetMaximumDynamicTableCapacity(4096);
encoder_.SetDynamicTableCapacity(4096);
quiche::HttpHeaderBlock header_list1;
header_list1["foo"] = "bar";
header_list1.AppendValueOrAddHeader("foo",
"baz");
header_list1["cookie"] = "baz";
std::string set_dyanamic_table_capacity;
ASSERT_TRUE(absl::HexStringToBytes("3fe11f", &set_dyanamic_table_capacity));
std::string insert_entries_hex;
if (HuffmanEnabled()) {
insert_entries_hex =
"62"
"94e7";
} else {
insert_entries_hex =
"43"
"666f6f";
}
insert_entries_hex +=
"03626172"
"80"
"0362617a"
"c5"
"0362617a";
std::string insert_entries;
ASSERT_TRUE(absl::HexStringToBytes(insert_entries_hex, &insert_entries));
EXPECT_CALL(encoder_stream_sender_delegate_,
WriteStreamData(Eq(
absl::StrCat(set_dyanamic_table_capacity, insert_entries))));
std::string expected_output;
ASSERT_TRUE(absl::HexStringToBytes(
"0400"
"828180",
&expected_output));
EXPECT_EQ(expected_output, Encode(header_list1));
EXPECT_EQ(insert_entries.size(), encoder_stream_sent_byte_count_);
::testing::Mock::VerifyAndClearExpectations(&encoder_stream_sender_delegate_);
EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered())
.WillRepeatedly(Return(kTooManyBytesBuffered));
quiche::HttpHeaderBlock header_list2;
header_list2["foo"] = "bar";
header_list2["bar"] = "baz";
header_list2["cookie"] = "baz";
ASSERT_TRUE(
absl::HexStringToBytes("0400"
"82"
"23626172"
"0362617a"
"80",
&expected_output));
EXPECT_EQ(expected_output, Encode(header_list2));
EXPECT_EQ(0u, encoder_stream_sent_byte_count_);
}
TEST_P(QpackEncoderTest, UnackedEntryCannotBeEvicted) {
EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered())
.WillRepeatedly(Return(0));
encoder_.SetMaximumBlockedStreams(2);
encoder_.SetMaximumDynamicTableCapacity(40);
encoder_.SetDynamicTableCapacity(40);
QpackEncoderHeaderTable* header_table =
QpackEncoderPeer::header_table(&encoder_);
EXPECT_EQ(0u, header_table->inserted_entry_count());
EXPECT_EQ(0u, header_table->dropped_entry_count());
quiche::HttpHeaderBlock header_list1;
header_list1["foo"] = "bar";
std::string set_dyanamic_table_capacity;
ASSERT_TRUE(absl::HexStringToBytes("3f09", &set_dyanamic_table_capacity));
std::string insert_entries1;
if (HuffmanEnabled()) {
ASSERT_TRUE(
absl::HexStringToBytes("62"
"94e7"
"03626172",
&insert_entries1));
} else {
ASSERT_TRUE(
absl::HexStringToBytes("43"
"666f6f"
"03626172",
&insert_entries1));
}
EXPECT_CALL(encoder_stream_sender_delegate_,
WriteStreamData(Eq(
absl::StrCat(set_dyanamic_table_capacity, insert_entries1))));
std::string expected_output;
ASSERT_TRUE(
absl::HexStringToBytes("0200"
"80",
&expected_output));
EXPECT_EQ(expected_output,
encoder_.EncodeHeaderList( 1, header_list1,
&encoder_stream_sent_byte_count_));
EXPECT_EQ(1u, header_table->inserted_entry_count());
EXPECT_EQ(0u, header_table->dropped_entry_count());
encoder_.OnStreamCancellation( 1);
quiche::HttpHeaderBlock header_list2;
header_list2["bar"] = "baz";
ASSERT_TRUE(
absl::HexStringToBytes("0000"
"23626172"
"0362617a",
&expected_output));
EXPECT_EQ(expected_output,
encoder_.EncodeHeaderList( 2, header_list2,
&encoder_stream_sent_byte_count_));
EXPECT_EQ(1u, header_table->inserted_entry_count());
EXPECT_EQ(0u, header_table->dropped_entry_count());
}
TEST_P(QpackEncoderTest, UseStaticTableNameOnlyMatch) {
EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered())
.WillRepeatedly(Return(0));
encoder_.SetMaximumBlockedStreams(2);
encoder_.SetMaximumDynamicTableCapacity(4096);
encoder_.SetDynamicTableCapacity(4096);
quiche::HttpHeaderBlock header_list;
header_list[":method"] = "bar";
std::string set_dyanamic_table_capacity;
ASSERT_TRUE(absl::HexStringToBytes("3fe11f", &set_dyanamic_table_capacity));
std::string insert_entry1;
ASSERT_TRUE(
absl::HexStringToBytes("cf"
"03626172",
&insert_entry1));
EXPECT_CALL(encoder_stream_sender_delegate_,
WriteStreamData(Eq(
absl::StrCat(set_dyanamic_table_capacity, insert_entry1))));
std::string expected_output;
ASSERT_TRUE(
absl::HexStringToBytes("0200"
"80",
&expected_output));
EXPECT_EQ(expected_output,
encoder_.EncodeHeaderList( 1, header_list,
&encoder_stream_sent_byte_count_));
EXPECT_EQ(insert_entry1.size(), encoder_stream_sent_byte_count_);
EXPECT_EQ(expected_output,
encoder_.EncodeHeaderList( 2, header_list,
&encoder_stream_sent_byte_count_));
EXPECT_EQ(0u, encoder_stream_sent_byte_count_);
ASSERT_TRUE(
absl::HexStringToBytes("0000"
"5f00"
"03626172",
&expected_output));
EXPECT_EQ(expected_output,
encoder_.EncodeHeaderList( 3, header_list,
&encoder_stream_sent_byte_count_));
}
TEST_P(QpackEncoderTest, UseDynamicTableNameOnlyMatch) {
EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered())
.WillRepeatedly(Return(0));
quiche::HttpHeaderBlock header_list1;
header_list1["one"] = "foo";
header_list1["two"] = "foo";
header_list1["three"] = "foo";
header_list1["four"] = "foo";
header_list1["five"] = "foo";
header_list1["six"] = "foo";
header_list1["seven"] = "foo";
header_list1["eight"] = "foo";
header_list1["nine"] = "foo";
header_list1["ten"] = "foo";
uint64_t maximum_dynamic_table_capacity = 0;
for (const auto& header_field : header_list1) {
maximum_dynamic_table_capacity +=
QpackEntry::Size(header_field.first, header_field.second);
}
maximum_dynamic_table_capacity += QpackEntry::Size("one", "bar");
encoder_.SetMaximumDynamicTableCapacity(maximum_dynamic_table_capacity);
encoder_.SetDynamicTableCapacity(maximum_dynamic_table_capacity);
EXPECT_CALL(encoder_stream_sender_delegate_, WriteStreamData(_));
std::string expected_output;
ASSERT_TRUE(
absl::HexStringToBytes("0b00"
"89888786858483828180",
&expected_output));
EXPECT_EQ(expected_output, Encode(header_list1));
quiche::HttpHeaderBlock header_list2;
header_list2["one"] = "bar";
ASSERT_TRUE(absl::HexStringToBytes(
"89"
"03626172",
&expected_output));
EXPECT_CALL(encoder_stream_sender_delegate_,
WriteStreamData(Eq(expected_output)));
ASSERT_TRUE(
absl::HexStringToBytes("0c00"
"80",
&expected_output));
EXPECT_EQ(expected_output, Encode(header_list2));
quiche::HttpHeaderBlock header_list3;
header_list3["one"] = "foo";
if (HuffmanEnabled()) {
ASSERT_TRUE(
absl::HexStringToBytes("0c00"
"40"
"8294e7",
&expected_output));
} else {
ASSERT_TRUE(
absl::HexStringToBytes("0c00"
"40"
"03666f6f",
&expected_output));
}
EXPECT_EQ(expected_output, Encode(header_list3));
}
TEST_P(QpackEncoderTest, CookieCrumblingEnabledNoDynamicTable) {
EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered())
.WillRepeatedly(Return(0));
quiche::HttpHeaderBlock header_list;
header_list["cookie"] = "foo; bar";
std::string expected_output;
if (HuffmanEnabled()) {
ASSERT_TRUE(
absl::HexStringToBytes("0000"
"55"
"8294e7"
"55"
"03626172",
&expected_output));
} else {
ASSERT_TRUE(
absl::HexStringToBytes("0000"
"55"
"03666f6f"
"55"
"03626172",
&expected_output));
}
EXPECT_EQ(expected_output, Encode(header_list));
EXPECT_EQ(0u, encoder_stream_sent_byte_count_);
}
TEST_P(QpackEncoderTest, CookieCrumblingEnabledDynamicTable) {
EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered())
.WillRepeatedly(Return(0));
encoder_.SetMaximumBlockedStreams(1);
encoder_.SetMaximumDynamicTableCapacity(4096);
encoder_.SetDynamicTableCapacity(4096);
quiche::HttpHeaderBlock header_list;
header_list["cookie"] = "foo; bar";
std::string set_dyanamic_table_capacity;
ASSERT_TRUE(absl::HexStringToBytes("3fe11f", &set_dyanamic_table_capacity));
std::string insert_entries;
if (HuffmanEnabled()) {
ASSERT_TRUE(absl::HexStringToBytes(
"c5"
"8294e7"
"c5"
"03626172",
&insert_entries));
} else {
ASSERT_TRUE(absl::HexStringToBytes(
"c5"
"03666f6f"
"c5"
"03626172",
&insert_entries));
}
EXPECT_CALL(encoder_stream_sender_delegate_,
WriteStreamData(Eq(
absl::StrCat(set_dyanamic_table_capacity, insert_entries))));
std::string expected_output;
ASSERT_TRUE(
absl::HexStringToBytes("0300"
"81"
"80",
&expected_output));
EXPECT_EQ(expected_output, Encode(header_list));
EXPECT_EQ(insert_entries.size(), encoder_stream_sent_byte_count_);
}
TEST_P(QpackEncoderTest, CookieCrumblingDisabledNoDynamicTable) {
QpackEncoder encoder(&decoder_stream_error_delegate_, huffman_encoding_,
CookieCrumbling::kDisabled);
EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered())
.WillRepeatedly(Return(0));
quiche::HttpHeaderBlock header_list;
header_list["cookie"] = "foo; bar";
std::string expected_output;
if (HuffmanEnabled()) {
ASSERT_TRUE(absl::HexStringToBytes(
"0000"
"55"
"8694e7fb5231d9",
&expected_output));
} else {
ASSERT_TRUE(absl::HexStringToBytes(
"0000"
"55"
"08666f6f3b20626172",
&expected_output));
}
EXPECT_EQ(expected_output,
encoder.EncodeHeaderList( 1, header_list,
&encoder_stream_sent_byte_count_));
EXPECT_EQ(0u, encoder_stream_sent_byte_count_);
}
TEST_P(QpackEncoderTest, CookieCrumblingDisabledDynamicTable) {
QpackEncoder encoder(&decoder_stream_error_delegate_, huffman_encoding_,
CookieCrumbling::kDisabled);
encoder.SetMaximumBlockedStreams(1);
encoder.set_qpack_stream_sender_delegate(&encoder_stream_sender_delegate_);
EXPECT_CALL(encoder_stream_sender_delegate_, NumBytesBuffered())
.WillRepeatedly(Return(0));
encoder.SetMaximumBlockedStreams(1);
encoder.SetMaximumDynamicTableCapacity(4096);
encoder.SetDynamicTableCapacity(4096);
quiche::HttpHeaderBlock header_list;
header_list["cookie"] = "foo; bar";
std::string set_dyanamic_table_capacity;
ASSERT_TRUE(absl::HexStringToBytes("3fe11f", &set_dyanamic_table_capacity));
std::string insert_entries;
if (HuffmanEnabled()) {
ASSERT_TRUE(absl::HexStringToBytes(
"c5"
"8694e7fb5231d9",
&insert_entries));
} else {
ASSERT_TRUE(absl::HexStringToBytes(
"c5"
"08666f6f3b20626172",
&insert_entries));
}
EXPECT_CALL(encoder_stream_sender_delegate_,
WriteStreamData(Eq(
absl::StrCat(set_dyanamic_table_capacity, insert_entries))));
std::string expected_output;
ASSERT_TRUE(
absl::HexStringToBytes("0200"
"80",
&expected_output));
EXPECT_EQ(expected_output,
encoder.EncodeHeaderList( 1, header_list,
&encoder_stream_sent_byte_count_));
EXPECT_EQ(insert_entries.size(), encoder_stream_sent_byte_count_);
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_encoder.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_encoder_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
683091d0-4b5c-4f95-8c5d-18017a2e0324 | cpp | google/quiche | qpack_header_table | quiche/quic/core/qpack/qpack_header_table.cc | quiche/quic/core/qpack/qpack_header_table_test.cc | #include "quiche/quic/core/qpack/qpack_header_table.h"
#include <utility>
#include "absl/strings/string_view.h"
#include "quiche/quic/core/qpack/qpack_static_table.h"
#include "quiche/quic/platform/api/quic_logging.h"
#include "quiche/common/platform/api/quiche_logging.h"
namespace quic {
QpackEncoderHeaderTable::QpackEncoderHeaderTable()
: static_index_(ObtainQpackStaticTable().GetStaticIndex()),
static_name_index_(ObtainQpackStaticTable().GetStaticNameIndex()) {}
uint64_t QpackEncoderHeaderTable::InsertEntry(absl::string_view name,
absl::string_view value) {
const uint64_t index =
QpackHeaderTableBase<QpackEncoderDynamicTable>::InsertEntry(name, value);
name = dynamic_entries().back()->name();
value = dynamic_entries().back()->value();
auto index_result = dynamic_index_.insert(
std::make_pair(QpackLookupEntry{name, value}, index));
if (!index_result.second) {
QUICHE_DCHECK_GT(index, index_result.first->second);
dynamic_index_.erase(index_result.first);
auto result = dynamic_index_.insert(
std::make_pair(QpackLookupEntry{name, value}, index));
QUICHE_CHECK(result.second);
}
auto name_result = dynamic_name_index_.insert({name, index});
if (!name_result.second) {
QUICHE_DCHECK_GT(index, name_result.first->second);
dynamic_name_index_.erase(name_result.first);
auto result = dynamic_name_index_.insert({name, index});
QUICHE_CHECK(result.second);
}
return index;
}
QpackEncoderHeaderTable::MatchResult QpackEncoderHeaderTable::FindHeaderField(
absl::string_view name, absl::string_view value) const {
QpackLookupEntry query{name, value};
auto index_it = static_index_.find(query);
if (index_it != static_index_.end()) {
return { MatchType::kNameAndValue,
true,
index_it->second};
}
index_it = dynamic_index_.find(query);
if (index_it != dynamic_index_.end()) {
return { MatchType::kNameAndValue,
false,
index_it->second};
}
return FindHeaderName(name);
}
QpackEncoderHeaderTable::MatchResult QpackEncoderHeaderTable::FindHeaderName(
absl::string_view name) const {
auto name_index_it = static_name_index_.find(name);
if (name_index_it != static_name_index_.end()) {
return { MatchType::kName,
true,
name_index_it->second};
}
name_index_it = dynamic_name_index_.find(name);
if (name_index_it != dynamic_name_index_.end()) {
return { MatchType::kName,
false,
name_index_it->second};
}
return { MatchType::kNoMatch,
false,
0};
}
uint64_t QpackEncoderHeaderTable::MaxInsertSizeWithoutEvictingGivenEntry(
uint64_t index) const {
QUICHE_DCHECK_LE(dropped_entry_count(), index);
if (index > inserted_entry_count()) {
return dynamic_table_capacity();
}
uint64_t max_insert_size = dynamic_table_capacity() - dynamic_table_size();
uint64_t entry_index = dropped_entry_count();
for (const auto& entry : dynamic_entries()) {
if (entry_index >= index) {
break;
}
++entry_index;
max_insert_size += entry->Size();
}
return max_insert_size;
}
uint64_t QpackEncoderHeaderTable::draining_index(
float draining_fraction) const {
QUICHE_DCHECK_LE(0.0, draining_fraction);
QUICHE_DCHECK_LE(draining_fraction, 1.0);
const uint64_t required_space = draining_fraction * dynamic_table_capacity();
uint64_t space_above_draining_index =
dynamic_table_capacity() - dynamic_table_size();
if (dynamic_entries().empty() ||
space_above_draining_index >= required_space) {
return dropped_entry_count();
}
auto it = dynamic_entries().begin();
uint64_t entry_index = dropped_entry_count();
while (space_above_draining_index < required_space) {
space_above_draining_index += (*it)->Size();
++it;
++entry_index;
if (it == dynamic_entries().end()) {
return inserted_entry_count();
}
}
return entry_index;
}
void QpackEncoderHeaderTable::RemoveEntryFromEnd() {
const QpackEntry* const entry = dynamic_entries().front().get();
const uint64_t index = dropped_entry_count();
auto index_it = dynamic_index_.find({entry->name(), entry->value()});
if (index_it != dynamic_index_.end() && index_it->second == index) {
dynamic_index_.erase(index_it);
}
auto name_it = dynamic_name_index_.find(entry->name());
if (name_it != dynamic_name_index_.end() && name_it->second == index) {
dynamic_name_index_.erase(name_it);
}
QpackHeaderTableBase<QpackEncoderDynamicTable>::RemoveEntryFromEnd();
}
QpackDecoderHeaderTable::QpackDecoderHeaderTable()
: static_entries_(ObtainQpackStaticTable().GetStaticEntries()) {}
QpackDecoderHeaderTable::~QpackDecoderHeaderTable() {
for (auto& entry : observers_) {
entry.second->Cancel();
}
}
uint64_t QpackDecoderHeaderTable::InsertEntry(absl::string_view name,
absl::string_view value) {
const uint64_t index =
QpackHeaderTableBase<QpackDecoderDynamicTable>::InsertEntry(name, value);
while (!observers_.empty()) {
auto it = observers_.begin();
if (it->first > inserted_entry_count()) {
break;
}
Observer* observer = it->second;
observers_.erase(it);
observer->OnInsertCountReachedThreshold();
}
return index;
}
const QpackEntry* QpackDecoderHeaderTable::LookupEntry(bool is_static,
uint64_t index) const {
if (is_static) {
if (index >= static_entries_.size()) {
return nullptr;
}
return &static_entries_[index];
}
if (index < dropped_entry_count()) {
return nullptr;
}
index -= dropped_entry_count();
if (index >= dynamic_entries().size()) {
return nullptr;
}
return &dynamic_entries()[index];
}
void QpackDecoderHeaderTable::RegisterObserver(uint64_t required_insert_count,
Observer* observer) {
QUICHE_DCHECK_GT(required_insert_count, 0u);
observers_.insert({required_insert_count, observer});
}
void QpackDecoderHeaderTable::UnregisterObserver(uint64_t required_insert_count,
Observer* observer) {
auto it = observers_.lower_bound(required_insert_count);
while (it != observers_.end() && it->first == required_insert_count) {
if (it->second == observer) {
observers_.erase(it);
return;
}
++it;
}
QUICHE_NOTREACHED();
}
} | #include "quiche/quic/core/qpack/qpack_header_table.h"
#include <memory>
#include <tuple>
#include <utility>
#include "absl/base/macros.h"
#include "absl/strings/string_view.h"
#include "quiche/http2/hpack/hpack_entry.h"
#include "quiche/quic/core/qpack/qpack_static_table.h"
#include "quiche/quic/platform/api/quic_test.h"
namespace quic {
namespace test {
namespace {
using ::testing::_;
using ::testing::FieldsAre;
using ::testing::Mock;
using ::testing::StrictMock;
constexpr uint64_t kMaximumDynamicTableCapacityForTesting = 1024 * 1024;
constexpr bool kStaticEntry = true;
constexpr bool kDynamicEntry = false;
template <typename T>
class QpackHeaderTableTest : public QuicTest {
protected:
~QpackHeaderTableTest() override = default;
void SetUp() override {
ASSERT_TRUE(table_.SetMaximumDynamicTableCapacity(
kMaximumDynamicTableCapacityForTesting));
ASSERT_TRUE(
table_.SetDynamicTableCapacity(kMaximumDynamicTableCapacityForTesting));
}
bool EntryFitsDynamicTableCapacity(absl::string_view name,
absl::string_view value) const {
return table_.EntryFitsDynamicTableCapacity(name, value);
}
void InsertEntry(absl::string_view name, absl::string_view value) {
table_.InsertEntry(name, value);
}
bool SetDynamicTableCapacity(uint64_t capacity) {
return table_.SetDynamicTableCapacity(capacity);
}
uint64_t max_entries() const { return table_.max_entries(); }
uint64_t inserted_entry_count() const {
return table_.inserted_entry_count();
}
uint64_t dropped_entry_count() const { return table_.dropped_entry_count(); }
T table_;
};
using MyTypes =
::testing::Types<QpackEncoderHeaderTable, QpackDecoderHeaderTable>;
TYPED_TEST_SUITE(QpackHeaderTableTest, MyTypes);
TYPED_TEST(QpackHeaderTableTest, MaxEntries) {
TypeParam table1;
table1.SetMaximumDynamicTableCapacity(1024);
EXPECT_EQ(32u, table1.max_entries());
TypeParam table2;
table2.SetMaximumDynamicTableCapacity(500);
EXPECT_EQ(15u, table2.max_entries());
}
TYPED_TEST(QpackHeaderTableTest, SetDynamicTableCapacity) {
EXPECT_TRUE(this->SetDynamicTableCapacity(1024));
EXPECT_EQ(32u * 1024, this->max_entries());
EXPECT_TRUE(this->SetDynamicTableCapacity(500));
EXPECT_EQ(32u * 1024, this->max_entries());
EXPECT_FALSE(this->SetDynamicTableCapacity(
2 * kMaximumDynamicTableCapacityForTesting));
}
TYPED_TEST(QpackHeaderTableTest, EntryFitsDynamicTableCapacity) {
EXPECT_TRUE(this->SetDynamicTableCapacity(39));
EXPECT_TRUE(this->EntryFitsDynamicTableCapacity("foo", "bar"));
EXPECT_TRUE(this->EntryFitsDynamicTableCapacity("foo", "bar2"));
EXPECT_FALSE(this->EntryFitsDynamicTableCapacity("foo", "bar12"));
}
class QpackEncoderHeaderTableTest
: public QpackHeaderTableTest<QpackEncoderHeaderTable> {
protected:
enum MatchType { kNameAndValue, kName, kNoMatch };
~QpackEncoderHeaderTableTest() override = default;
std::tuple<MatchType, bool, uint64_t> FindHeaderField(
absl::string_view name, absl::string_view value) const {
QpackEncoderHeaderTable::MatchResult match_result =
table_.FindHeaderField(name, value);
return {static_cast<MatchType>(match_result.match_type),
match_result.is_static, match_result.index};
}
std::tuple<MatchType, bool, uint64_t> FindHeaderName(
absl::string_view name) const {
QpackEncoderHeaderTable::MatchResult match_result =
table_.FindHeaderName(name);
return {static_cast<MatchType>(match_result.match_type),
match_result.is_static, match_result.index};
}
uint64_t MaxInsertSizeWithoutEvictingGivenEntry(uint64_t index) const {
return table_.MaxInsertSizeWithoutEvictingGivenEntry(index);
}
uint64_t draining_index(float draining_fraction) const {
return table_.draining_index(draining_fraction);
}
};
TEST_F(QpackEncoderHeaderTableTest, FindStaticHeaderField) {
EXPECT_THAT(FindHeaderField(":method", "GET"),
FieldsAre(kNameAndValue, kStaticEntry, 17u));
EXPECT_THAT(FindHeaderField(":method", "POST"),
FieldsAre(kNameAndValue, kStaticEntry, 20u));
EXPECT_THAT(FindHeaderField(":method", "TRACE"),
FieldsAre(kName, kStaticEntry, 15u));
EXPECT_THAT(FindHeaderName(":method"), FieldsAre(kName, kStaticEntry, 15u));
EXPECT_THAT(FindHeaderField("accept-encoding", "gzip, deflate, br"),
FieldsAre(kNameAndValue, kStaticEntry, 31u));
EXPECT_THAT(FindHeaderField("accept-encoding", "compress"),
FieldsAre(kName, kStaticEntry, 31u));
EXPECT_THAT(FindHeaderField("accept-encoding", ""),
FieldsAre(kName, kStaticEntry, 31u));
EXPECT_THAT(FindHeaderName("accept-encoding"),
FieldsAre(kName, kStaticEntry, 31u));
EXPECT_THAT(FindHeaderField("location", ""),
FieldsAre(kNameAndValue, kStaticEntry, 12u));
EXPECT_THAT(FindHeaderField("location", "foo"),
FieldsAre(kName, kStaticEntry, 12u));
EXPECT_THAT(FindHeaderName("location"), FieldsAre(kName, kStaticEntry, 12u));
EXPECT_THAT(FindHeaderField("foo", ""), FieldsAre(kNoMatch, _, _));
EXPECT_THAT(FindHeaderField("foo", "bar"), FieldsAre(kNoMatch, _, _));
EXPECT_THAT(FindHeaderName("foo"), FieldsAre(kNoMatch, _, _));
}
TEST_F(QpackEncoderHeaderTableTest, FindDynamicHeaderField) {
EXPECT_THAT(FindHeaderField("foo", "bar"), FieldsAre(kNoMatch, _, _));
EXPECT_THAT(FindHeaderField("foo", "baz"), FieldsAre(kNoMatch, _, _));
EXPECT_THAT(FindHeaderName("foo"), FieldsAre(kNoMatch, _, _));
InsertEntry("foo", "bar");
EXPECT_THAT(FindHeaderField("foo", "bar"),
FieldsAre(kNameAndValue, kDynamicEntry, 0u));
EXPECT_THAT(FindHeaderField("foo", "baz"),
FieldsAre(kName, kDynamicEntry, 0u));
EXPECT_THAT(FindHeaderName("foo"), FieldsAre(kName, kDynamicEntry, 0u));
InsertEntry("foo", "bar");
EXPECT_THAT(FindHeaderField("foo", "bar"),
FieldsAre(kNameAndValue, kDynamicEntry, 1u));
EXPECT_THAT(FindHeaderField("foo", "baz"),
FieldsAre(kName, kDynamicEntry, 1u));
EXPECT_THAT(FindHeaderName("foo"), FieldsAre(kName, kDynamicEntry, 1u));
}
TEST_F(QpackEncoderHeaderTableTest, FindHeaderFieldPrefersStaticTable) {
InsertEntry(":method", "GET");
EXPECT_THAT(FindHeaderField(":method", "GET"),
FieldsAre(kNameAndValue, kStaticEntry, 17u));
EXPECT_THAT(FindHeaderField(":method", "TRACE"),
FieldsAre(kName, kStaticEntry, 15u));
EXPECT_THAT(FindHeaderName(":method"), FieldsAre(kName, kStaticEntry, 15u));
InsertEntry(":method", "TRACE");
EXPECT_THAT(FindHeaderField(":method", "TRACE"),
FieldsAre(kNameAndValue, kDynamicEntry, 1u));
}
TEST_F(QpackEncoderHeaderTableTest, EvictByInsertion) {
EXPECT_TRUE(SetDynamicTableCapacity(40));
InsertEntry("foo", "bar");
EXPECT_EQ(1u, inserted_entry_count());
EXPECT_EQ(0u, dropped_entry_count());
EXPECT_THAT(FindHeaderField("foo", "bar"),
FieldsAre(kNameAndValue, kDynamicEntry, 0u));
InsertEntry("baz", "qux");
EXPECT_EQ(2u, inserted_entry_count());
EXPECT_EQ(1u, dropped_entry_count());
EXPECT_THAT(FindHeaderField("foo", "bar"), FieldsAre(kNoMatch, _, _));
EXPECT_THAT(FindHeaderField("baz", "qux"),
FieldsAre(kNameAndValue, kDynamicEntry, 1u));
}
TEST_F(QpackEncoderHeaderTableTest, EvictByUpdateTableSize) {
InsertEntry("foo", "bar");
InsertEntry("baz", "qux");
EXPECT_EQ(2u, inserted_entry_count());
EXPECT_EQ(0u, dropped_entry_count());
EXPECT_THAT(FindHeaderField("foo", "bar"),
FieldsAre(kNameAndValue, kDynamicEntry, 0u));
EXPECT_THAT(FindHeaderField("baz", "qux"),
FieldsAre(kNameAndValue, kDynamicEntry, 1u));
EXPECT_TRUE(SetDynamicTableCapacity(40));
EXPECT_EQ(2u, inserted_entry_count());
EXPECT_EQ(1u, dropped_entry_count());
EXPECT_THAT(FindHeaderField("foo", "bar"), FieldsAre(kNoMatch, _, _));
EXPECT_THAT(FindHeaderField("baz", "qux"),
FieldsAre(kNameAndValue, kDynamicEntry, 1u));
EXPECT_TRUE(SetDynamicTableCapacity(20));
EXPECT_EQ(2u, inserted_entry_count());
EXPECT_EQ(2u, dropped_entry_count());
EXPECT_THAT(FindHeaderField("foo", "bar"), FieldsAre(kNoMatch, _, _));
EXPECT_THAT(FindHeaderField("baz", "qux"), FieldsAre(kNoMatch, _, _));
}
TEST_F(QpackEncoderHeaderTableTest, EvictOldestOfIdentical) {
EXPECT_TRUE(SetDynamicTableCapacity(80));
InsertEntry("foo", "bar");
InsertEntry("foo", "bar");
EXPECT_EQ(2u, inserted_entry_count());
EXPECT_EQ(0u, dropped_entry_count());
EXPECT_THAT(FindHeaderField("foo", "bar"),
FieldsAre(kNameAndValue, kDynamicEntry, 1u));
InsertEntry("baz", "qux");
EXPECT_EQ(3u, inserted_entry_count());
EXPECT_EQ(1u, dropped_entry_count());
EXPECT_THAT(FindHeaderField("foo", "bar"),
FieldsAre(kNameAndValue, kDynamicEntry, 1u));
EXPECT_THAT(FindHeaderField("baz", "qux"),
FieldsAre(kNameAndValue, kDynamicEntry, 2u));
}
TEST_F(QpackEncoderHeaderTableTest, EvictOldestOfSameName) {
EXPECT_TRUE(SetDynamicTableCapacity(80));
InsertEntry("foo", "bar");
InsertEntry("foo", "baz");
EXPECT_EQ(2u, inserted_entry_count());
EXPECT_EQ(0u, dropped_entry_count());
EXPECT_THAT(FindHeaderField("foo", "foo"),
FieldsAre(kName, kDynamicEntry, 1u));
InsertEntry("baz", "qux");
EXPECT_EQ(3u, inserted_entry_count());
EXPECT_EQ(1u, dropped_entry_count());
EXPECT_THAT(FindHeaderField("foo", "foo"),
FieldsAre(kName, kDynamicEntry, 1u));
EXPECT_THAT(FindHeaderField("baz", "qux"),
FieldsAre(kNameAndValue, kDynamicEntry, 2u));
}
TEST_F(QpackEncoderHeaderTableTest, MaxInsertSizeWithoutEvictingGivenEntry) {
const uint64_t dynamic_table_capacity = 100;
EXPECT_TRUE(SetDynamicTableCapacity(dynamic_table_capacity));
EXPECT_EQ(dynamic_table_capacity, MaxInsertSizeWithoutEvictingGivenEntry(0));
const uint64_t entry_size1 = QpackEntry::Size("foo", "bar");
InsertEntry("foo", "bar");
EXPECT_EQ(dynamic_table_capacity - entry_size1,
MaxInsertSizeWithoutEvictingGivenEntry(0));
EXPECT_EQ(dynamic_table_capacity, MaxInsertSizeWithoutEvictingGivenEntry(1));
const uint64_t entry_size2 = QpackEntry::Size("baz", "foobar");
InsertEntry("baz", "foobar");
EXPECT_EQ(dynamic_table_capacity, MaxInsertSizeWithoutEvictingGivenEntry(2));
EXPECT_EQ(dynamic_table_capacity - entry_size2,
MaxInsertSizeWithoutEvictingGivenEntry(1));
EXPECT_EQ(dynamic_table_capacity - entry_size2 - entry_size1,
MaxInsertSizeWithoutEvictingGivenEntry(0));
const uint64_t entry_size3 = QpackEntry::Size("last", "entry");
InsertEntry("last", "entry");
EXPECT_EQ(1u, dropped_entry_count());
EXPECT_EQ(dynamic_table_capacity, MaxInsertSizeWithoutEvictingGivenEntry(3));
EXPECT_EQ(dynamic_table_capacity - entry_size3,
MaxInsertSizeWithoutEvictingGivenEntry(2));
EXPECT_EQ(dynamic_table_capacity - entry_size3 - entry_size2,
MaxInsertSizeWithoutEvictingGivenEntry(1));
}
TEST_F(QpackEncoderHeaderTableTest, DrainingIndex) {
EXPECT_TRUE(SetDynamicTableCapacity(4 * QpackEntry::Size("foo", "bar")));
EXPECT_EQ(0u, draining_index(0.0));
EXPECT_EQ(0u, draining_index(1.0));
InsertEntry("foo", "bar");
EXPECT_EQ(0u, draining_index(0.0));
EXPECT_EQ(1u, draining_index(1.0));
InsertEntry("foo", "bar");
EXPECT_EQ(0u, draining_index(0.0));
EXPECT_EQ(0u, draining_index(0.5));
EXPECT_EQ(2u, draining_index(1.0));
InsertEntry("foo", "bar");
InsertEntry("foo", "bar");
EXPECT_EQ(0u, draining_index(0.0));
EXPECT_EQ(2u, draining_index(0.5));
EXPECT_EQ(4u, draining_index(1.0));
}
class MockObserver : public QpackDecoderHeaderTable::Observer {
public:
~MockObserver() override = default;
MOCK_METHOD(void, OnInsertCountReachedThreshold, (), (override));
MOCK_METHOD(void, Cancel, (), (override));
};
class QpackDecoderHeaderTableTest
: public QpackHeaderTableTest<QpackDecoderHeaderTable> {
protected:
~QpackDecoderHeaderTableTest() override = default;
void ExpectEntryAtIndex(bool is_static, uint64_t index,
absl::string_view expected_name,
absl::string_view expected_value) const {
const auto* entry = table_.LookupEntry(is_static, index);
ASSERT_TRUE(entry);
EXPECT_EQ(expected_name, entry->name());
EXPECT_EQ(expected_value, entry->value());
}
void ExpectNoEntryAtIndex(bool is_static, uint64_t index) const {
EXPECT_FALSE(table_.LookupEntry(is_static, index));
}
void RegisterObserver(uint64_t required_insert_count,
QpackDecoderHeaderTable::Observer* observer) {
table_.RegisterObserver(required_insert_count, observer);
}
void UnregisterObserver(uint64_t required_insert_count,
QpackDecoderHeaderTable::Observer* observer) {
table_.UnregisterObserver(required_insert_count, observer);
}
};
TEST_F(QpackDecoderHeaderTableTest, LookupStaticEntry) {
ExpectEntryAtIndex(kStaticEntry, 0, ":authority", "");
ExpectEntryAtIndex(kStaticEntry, 1, ":path", "/");
ExpectEntryAtIndex(kStaticEntry, 98, "x-frame-options", "sameorigin");
ASSERT_EQ(99u, QpackStaticTableVector().size());
ExpectNoEntryAtIndex(kStaticEntry, 99);
}
TEST_F(QpackDecoderHeaderTableTest, InsertAndLookupDynamicEntry) {
ExpectNoEntryAtIndex(kDynamicEntry, 0);
ExpectNoEntryAtIndex(kDynamicEntry, 1);
ExpectNoEntryAtIndex(kDynamicEntry, 2);
ExpectNoEntryAtIndex(kDynamicEntry, 3);
InsertEntry("foo", "bar");
ExpectEntryAtIndex(kDynamicEntry, 0, "foo", "bar");
ExpectNoEntryAtIndex(kDynamicEntry, 1);
ExpectNoEntryAtIndex(kDynamicEntry, 2);
ExpectNoEntryAtIndex(kDynamicEntry, 3);
InsertEntry("baz", "bing");
ExpectEntryAtIndex(kDynamicEntry, 0, "foo", "bar");
ExpectEntryAtIndex(kDynamicEntry, 1, "baz", "bing");
ExpectNoEntryAtIndex(kDynamicEntry, 2);
ExpectNoEntryAtIndex(kDynamicEntry, 3);
InsertEntry("baz", "bing");
ExpectEntryAtIndex(kDynamicEntry, 0, "foo", "bar");
ExpectEntryAtIndex(kDynamicEntry, 1, "baz", "bing");
ExpectEntryAtIndex(kDynamicEntry, 2, "baz", "bing");
ExpectNoEntryAtIndex(kDynamicEntry, 3);
}
TEST_F(QpackDecoderHeaderTableTest, EvictByInsertion) {
EXPECT_TRUE(SetDynamicTableCapacity(40));
InsertEntry("foo", "bar");
EXPECT_EQ(1u, inserted_entry_count());
EXPECT_EQ(0u, dropped_entry_count());
ExpectEntryAtIndex(kDynamicEntry, 0u, "foo", "bar");
InsertEntry("baz", "qux");
EXPECT_EQ(2u, inserted_entry_count());
EXPECT_EQ(1u, dropped_entry_count());
ExpectNoEntryAtIndex(kDynamicEntry, 0u);
ExpectEntryAtIndex(kDynamicEntry, 1u, "baz", "qux");
}
TEST_F(QpackDecoderHeaderTableTest, EvictByUpdateTableSize) {
ExpectNoEntryAtIndex(kDynamicEntry, 0u);
ExpectNoEntryAtIndex(kDynamicEntry, 1u);
InsertEntry("foo", "bar");
InsertEntry("baz", "qux");
EXPECT_EQ(2u, inserted_entry_count());
EXPECT_EQ(0u, dropped_entry_count());
ExpectEntryAtIndex(kDynamicEntry, 0u, "foo", "bar");
ExpectEntryAtIndex(kDynamicEntry, 1u, "baz", "qux");
EXPECT_TRUE(SetDynamicTableCapacity(40));
EXPECT_EQ(2u, inserted_entry_count());
EXPECT_EQ(1u, dropped_entry_count());
ExpectNoEntryAtIndex(kDynamicEntry, 0u);
ExpectEntryAtIndex(kDynamicEntry, 1u, "baz", "qux");
EXPECT_TRUE(SetDynamicTableCapacity(20));
EXPECT_EQ(2u, inserted_entry_count());
EXPECT_EQ(2u, dropped_entry_count());
ExpectNoEntryAtIndex(kDynamicEntry, 0u);
ExpectNoEntryAtIndex(kDynamicEntry, 1u);
}
TEST_F(QpackDecoderHeaderTableTest, EvictOldestOfIdentical) {
EXPECT_TRUE(SetDynamicTableCapacity(80));
InsertEntry("foo", "bar");
InsertEntry("foo", "bar");
EXPECT_EQ(2u, inserted_entry_count());
EXPECT_EQ(0u, dropped_entry_count());
ExpectEntryAtIndex(kDynamicEntry, 0u, "foo", "bar");
ExpectEntryAtIndex(kDynamicEntry, 1u, "foo", "bar");
ExpectNoEntryAtIndex(kDynamicEntry, 2u);
InsertEntry("baz", "qux");
EXPECT_EQ(3u, inserted_entry_count());
EXPECT_EQ(1u, dropped_entry_count());
ExpectNoEntryAtIndex(kDynamicEntry, 0u);
ExpectEntryAtIndex(kDynamicEntry, 1u, "foo", "bar");
ExpectEntryAtIndex(kDynamicEntry, 2u, "baz", "qux");
}
TEST_F(QpackDecoderHeaderTableTest, EvictOldestOfSameName) {
EXPECT_TRUE(SetDynamicTableCapacity(80));
InsertEntry("foo", "bar");
InsertEntry("foo", "baz");
EXPECT_EQ(2u, inserted_entry_count());
EXPECT_EQ(0u, dropped_entry_count());
ExpectEntryAtIndex(kDynamicEntry, 0u, "foo", "bar");
ExpectEntryAtIndex(kDynamicEntry, 1u, "foo", "baz");
ExpectNoEntryAtIndex(kDynamicEntry, 2u);
InsertEntry("baz", "qux");
EXPECT_EQ(3u, inserted_entry_count());
EXPECT_EQ(1u, dropped_entry_count());
ExpectNoEntryAtIndex(kDynamicEntry, 0u);
ExpectEntryAtIndex(kDynamicEntry, 1u, "foo", "baz");
ExpectEntryAtIndex(kDynamicEntry, 2u, "baz", "qux");
}
TEST_F(QpackDecoderHeaderTableTest, RegisterObserver) {
StrictMock<MockObserver> observer1;
RegisterObserver(1, &observer1);
EXPECT_CALL(observer1, OnInsertCountReachedThreshold);
InsertEntry("foo", "bar");
EXPECT_EQ(1u, inserted_entry_count());
Mock::VerifyAndClearExpectations(&observer1);
StrictMock<MockObserver> observer2;
StrictMock<MockObserver> observer3;
RegisterObserver(3, &observer3);
RegisterObserver(2, &observer2);
EXPECT_CALL(observer2, OnInsertCountReachedThreshold);
InsertEntry("foo", "bar");
EXPECT_EQ(2u, inserted_entry_count());
Mock::VerifyAndClearExpectations(&observer3);
EXPECT_CALL(observer3, OnInsertCountReachedThreshold);
InsertEntry("foo", "bar");
EXPECT_EQ(3u, inserted_entry_count());
Mock::VerifyAndClearExpectations(&observer2);
StrictMock<MockObserver> observer4;
StrictMock<MockObserver> observer5;
RegisterObserver(4, &observer4);
RegisterObserver(4, &observer5);
EXPECT_CALL(observer4, OnInsertCountReachedThreshold);
EXPECT_CALL(observer5, OnInsertCountReachedThreshold);
InsertEntry("foo", "bar");
EXPECT_EQ(4u, inserted_entry_count());
Mock::VerifyAndClearExpectations(&observer4);
Mock::VerifyAndClearExpectations(&observer5);
}
TEST_F(QpackDecoderHeaderTableTest, UnregisterObserver) {
StrictMock<MockObserver> observer1;
StrictMock<MockObserver> observer2;
StrictMock<MockObserver> observer3;
StrictMock<MockObserver> observer4;
RegisterObserver(1, &observer1);
RegisterObserver(2, &observer2);
RegisterObserver(2, &observer3);
RegisterObserver(3, &observer4);
UnregisterObserver(2, &observer3);
EXPECT_CALL(observer1, OnInsertCountReachedThreshold);
EXPECT_CALL(observer2, OnInsertCountReachedThreshold);
EXPECT_CALL(observer4, OnInsertCountReachedThreshold);
InsertEntry("foo", "bar");
InsertEntry("foo", "bar");
InsertEntry("foo", "bar");
EXPECT_EQ(3u, inserted_entry_count());
}
TEST_F(QpackDecoderHeaderTableTest, Cancel) {
StrictMock<MockObserver> observer;
auto table = std::make_unique<QpackDecoderHeaderTable>();
table->RegisterObserver(1, &observer);
EXPECT_CALL(observer, Cancel);
table.reset();
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_header_table.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_header_table_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
8abad779-4ab3-4f43-b6e2-670c1b292035 | cpp | google/quiche | value_splitting_header_list | quiche/quic/core/qpack/value_splitting_header_list.cc | quiche/quic/core/qpack/value_splitting_header_list_test.cc | #include "quiche/quic/core/qpack/value_splitting_header_list.h"
#include <utility>
#include "absl/strings/string_view.h"
#include "quiche/quic/platform/api/quic_logging.h"
namespace quic {
namespace {
const char kCookieKey[] = "cookie";
const char kCookieSeparator = ';';
const char kOptionalSpaceAfterCookieSeparator = ' ';
const char kNonCookieSeparator = '\0';
}
ValueSplittingHeaderList::const_iterator::const_iterator(
const quiche::HttpHeaderBlock* header_list,
quiche::HttpHeaderBlock::const_iterator header_list_iterator,
CookieCrumbling cookie_crumbling)
: header_list_(header_list),
header_list_iterator_(header_list_iterator),
cookie_crumbling_(cookie_crumbling),
value_start_(0) {
UpdateHeaderField();
}
bool ValueSplittingHeaderList::const_iterator::operator==(
const const_iterator& other) const {
return header_list_iterator_ == other.header_list_iterator_ &&
value_start_ == other.value_start_;
}
bool ValueSplittingHeaderList::const_iterator::operator!=(
const const_iterator& other) const {
return !(*this == other);
}
const ValueSplittingHeaderList::const_iterator&
ValueSplittingHeaderList::const_iterator::operator++() {
if (value_end_ == absl::string_view::npos) {
++header_list_iterator_;
value_start_ = 0;
} else {
value_start_ = value_end_ + 1;
}
UpdateHeaderField();
return *this;
}
const ValueSplittingHeaderList::value_type&
ValueSplittingHeaderList::const_iterator::operator*() const {
return header_field_;
}
const ValueSplittingHeaderList::value_type*
ValueSplittingHeaderList::const_iterator::operator->() const {
return &header_field_;
}
void ValueSplittingHeaderList::const_iterator::UpdateHeaderField() {
QUICHE_DCHECK(value_start_ != absl::string_view::npos);
if (header_list_iterator_ == header_list_->end()) {
return;
}
const absl::string_view name = header_list_iterator_->first;
const absl::string_view original_value = header_list_iterator_->second;
if (name == kCookieKey) {
if (cookie_crumbling_ == CookieCrumbling::kEnabled) {
value_end_ = original_value.find(kCookieSeparator, value_start_);
} else {
value_end_ = absl::string_view::npos;
}
} else {
value_end_ = original_value.find(kNonCookieSeparator, value_start_);
}
const absl::string_view value =
original_value.substr(value_start_, value_end_ - value_start_);
header_field_ = std::make_pair(name, value);
if (name == kCookieKey && value_end_ != absl::string_view::npos &&
value_end_ + 1 < original_value.size() &&
original_value[value_end_ + 1] == kOptionalSpaceAfterCookieSeparator) {
++value_end_;
}
}
ValueSplittingHeaderList::ValueSplittingHeaderList(
const quiche::HttpHeaderBlock* header_list,
CookieCrumbling cookie_crumbling)
: header_list_(header_list), cookie_crumbling_(cookie_crumbling) {
QUICHE_DCHECK(header_list_);
}
ValueSplittingHeaderList::const_iterator ValueSplittingHeaderList::begin()
const {
return const_iterator(header_list_, header_list_->begin(), cookie_crumbling_);
}
ValueSplittingHeaderList::const_iterator ValueSplittingHeaderList::end() const {
return const_iterator(header_list_, header_list_->end(), cookie_crumbling_);
}
} | #include "quiche/quic/core/qpack/value_splitting_header_list.h"
#include <vector>
#include "absl/base/macros.h"
#include "absl/strings/string_view.h"
#include "quiche/quic/platform/api/quic_test.h"
namespace quic {
namespace test {
namespace {
using ::testing::ElementsAre;
using ::testing::Pair;
TEST(ValueSplittingHeaderListTest, Comparison) {
quiche::HttpHeaderBlock block;
block["foo"] = absl::string_view("bar\0baz", 7);
block["baz"] = "qux";
block["cookie"] = "foo; bar";
ValueSplittingHeaderList headers(&block, CookieCrumbling::kEnabled);
ValueSplittingHeaderList::const_iterator it1 = headers.begin();
const int kEnd = 6;
for (int i = 0; i < kEnd; ++i) {
if (i == 0) {
EXPECT_TRUE(it1 == headers.begin());
EXPECT_TRUE(headers.begin() == it1);
EXPECT_FALSE(it1 != headers.begin());
EXPECT_FALSE(headers.begin() != it1);
} else {
EXPECT_FALSE(it1 == headers.begin());
EXPECT_FALSE(headers.begin() == it1);
EXPECT_TRUE(it1 != headers.begin());
EXPECT_TRUE(headers.begin() != it1);
}
if (i == kEnd - 1) {
EXPECT_TRUE(it1 == headers.end());
EXPECT_TRUE(headers.end() == it1);
EXPECT_FALSE(it1 != headers.end());
EXPECT_FALSE(headers.end() != it1);
} else {
EXPECT_FALSE(it1 == headers.end());
EXPECT_FALSE(headers.end() == it1);
EXPECT_TRUE(it1 != headers.end());
EXPECT_TRUE(headers.end() != it1);
}
ValueSplittingHeaderList::const_iterator it2 = headers.begin();
for (int j = 0; j < kEnd; ++j) {
if (i == j) {
EXPECT_TRUE(it1 == it2);
EXPECT_FALSE(it1 != it2);
} else {
EXPECT_FALSE(it1 == it2);
EXPECT_TRUE(it1 != it2);
}
if (j < kEnd - 1) {
ASSERT_NE(it2, headers.end());
++it2;
}
}
if (i < kEnd - 1) {
ASSERT_NE(it1, headers.end());
++it1;
}
}
}
TEST(ValueSplittingHeaderListTest, Empty) {
quiche::HttpHeaderBlock block;
ValueSplittingHeaderList headers(&block, CookieCrumbling::kEnabled);
EXPECT_THAT(headers, ElementsAre());
EXPECT_EQ(headers.begin(), headers.end());
}
TEST(ValueSplittingHeaderListTest, SplitNonCookie) {
struct {
const char* name;
absl::string_view value;
std::vector<absl::string_view> expected_values;
} kTestData[]{
{"foo", "", {""}},
{"foo", "bar", {"bar"}},
{"foo", {"bar\0baz", 7}, {"bar", "baz"}},
{"foo", {"\0", 1}, {"", ""}},
{"bar", {"foo\0", 4}, {"foo", ""}},
{"baz", {"\0bar", 4}, {"", "bar"}},
{"qux", {"\0foobar\0", 8}, {"", "foobar", ""}},
};
for (size_t i = 0; i < ABSL_ARRAYSIZE(kTestData); ++i) {
quiche::HttpHeaderBlock block;
block[kTestData[i].name] = kTestData[i].value;
{
ValueSplittingHeaderList headers(&block, CookieCrumbling::kEnabled);
auto it = headers.begin();
for (absl::string_view expected_value : kTestData[i].expected_values) {
ASSERT_NE(it, headers.end());
EXPECT_EQ(it->first, kTestData[i].name);
EXPECT_EQ(it->second, expected_value);
++it;
}
EXPECT_EQ(it, headers.end());
}
{
ValueSplittingHeaderList headers(&block, CookieCrumbling::kDisabled);
auto it = headers.begin();
for (absl::string_view expected_value : kTestData[i].expected_values) {
ASSERT_NE(it, headers.end());
EXPECT_EQ(it->first, kTestData[i].name);
EXPECT_EQ(it->second, expected_value);
++it;
}
EXPECT_EQ(it, headers.end());
}
}
}
TEST(ValueSplittingHeaderListTest, SplitCookie) {
struct {
const char* name;
absl::string_view value;
std::vector<absl::string_view> expected_values;
} kTestData[]{
{"cookie", "foo;bar", {"foo", "bar"}},
{"cookie", "foo; bar", {"foo", "bar"}},
{"cookie", ";", {"", ""}},
{"cookie", "foo;", {"foo", ""}},
{"cookie", ";bar", {"", "bar"}},
{"cookie", ";foobar;", {"", "foobar", ""}},
{"cookie", "; ", {"", ""}},
{"cookie", "foo; ", {"foo", ""}},
{"cookie", "; bar", {"", "bar"}},
{"cookie", "; foobar; ", {"", "foobar", ""}},
};
for (size_t i = 0; i < ABSL_ARRAYSIZE(kTestData); ++i) {
quiche::HttpHeaderBlock block;
block[kTestData[i].name] = kTestData[i].value;
{
ValueSplittingHeaderList headers(&block, CookieCrumbling::kEnabled);
auto it = headers.begin();
for (absl::string_view expected_value : kTestData[i].expected_values) {
ASSERT_NE(it, headers.end());
EXPECT_EQ(it->first, kTestData[i].name);
EXPECT_EQ(it->second, expected_value);
++it;
}
EXPECT_EQ(it, headers.end());
}
{
ValueSplittingHeaderList headers(&block, CookieCrumbling::kDisabled);
auto it = headers.begin();
ASSERT_NE(it, headers.end());
EXPECT_EQ(it->first, kTestData[i].name);
EXPECT_EQ(it->second, kTestData[i].value);
++it;
EXPECT_EQ(it, headers.end());
}
}
}
TEST(ValueSplittingHeaderListTest, MultipleFieldsCookieCrumblingEnabled) {
quiche::HttpHeaderBlock block;
block["foo"] = absl::string_view("bar\0baz\0", 8);
block["cookie"] = "foo; bar";
block["bar"] = absl::string_view("qux\0foo", 7);
ValueSplittingHeaderList headers(&block, CookieCrumbling::kEnabled);
EXPECT_THAT(headers, ElementsAre(Pair("foo", "bar"), Pair("foo", "baz"),
Pair("foo", ""), Pair("cookie", "foo"),
Pair("cookie", "bar"), Pair("bar", "qux"),
Pair("bar", "foo")));
}
TEST(ValueSplittingHeaderListTest, MultipleFieldsCookieCrumblingDisabled) {
quiche::HttpHeaderBlock block;
block["foo"] = absl::string_view("bar\0baz\0", 8);
block["cookie"] = "foo; bar";
block["bar"] = absl::string_view("qux\0foo", 7);
ValueSplittingHeaderList headers(&block, CookieCrumbling::kDisabled);
EXPECT_THAT(headers, ElementsAre(Pair("foo", "bar"), Pair("foo", "baz"),
Pair("foo", ""), Pair("cookie", "foo; bar"),
Pair("bar", "qux"), Pair("bar", "foo")));
}
TEST(ValueSplittingHeaderListTest, CookieStartsWithSpaceCrumblingEnabled) {
quiche::HttpHeaderBlock block;
block["foo"] = "bar";
block["cookie"] = " foo";
block["bar"] = "baz";
ValueSplittingHeaderList headers(&block, CookieCrumbling::kEnabled);
EXPECT_THAT(headers, ElementsAre(Pair("foo", "bar"), Pair("cookie", " foo"),
Pair("bar", "baz")));
}
TEST(ValueSplittingHeaderListTest, CookieStartsWithSpaceCrumblingDisabled) {
quiche::HttpHeaderBlock block;
block["foo"] = "bar";
block["cookie"] = " foo";
block["bar"] = "baz";
ValueSplittingHeaderList headers(&block, CookieCrumbling::kDisabled);
EXPECT_THAT(headers, ElementsAre(Pair("foo", "bar"), Pair("cookie", " foo"),
Pair("bar", "baz")));
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/value_splitting_header_list.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/value_splitting_header_list_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
0768de86-5d95-4ad5-9cf0-83216f58447b | cpp | google/quiche | qpack_receive_stream | quiche/quic/core/qpack/qpack_receive_stream.cc | quiche/quic/core/qpack/qpack_receive_stream_test.cc | #include "quiche/quic/core/qpack/qpack_receive_stream.h"
#include "absl/strings/string_view.h"
#include "quiche/quic/core/quic_session.h"
namespace quic {
QpackReceiveStream::QpackReceiveStream(PendingStream* pending,
QuicSession* session,
QpackStreamReceiver* receiver)
: QuicStream(pending, session, true), receiver_(receiver) {}
void QpackReceiveStream::OnStreamReset(const QuicRstStreamFrame& ) {
stream_delegate()->OnStreamError(
QUIC_HTTP_CLOSED_CRITICAL_STREAM,
"RESET_STREAM received for QPACK receive stream");
}
void QpackReceiveStream::OnDataAvailable() {
iovec iov;
while (!reading_stopped() && sequencer()->GetReadableRegion(&iov)) {
QUICHE_DCHECK(!sequencer()->IsClosed());
receiver_->Decode(absl::string_view(
reinterpret_cast<const char*>(iov.iov_base), iov.iov_len));
sequencer()->MarkConsumed(iov.iov_len);
}
}
} | #include "quiche/quic/core/qpack/qpack_receive_stream.h"
#include <vector>
#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_spdy_session_peer.h"
#include "quiche/quic/test_tools/quic_test_utils.h"
namespace quic {
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: version: "
<< ParsedQuicVersionToString(version)
<< ", perspective: " << perspective;
}
TestParams(const TestParams& other)
: version(other.version), perspective(other.perspective) {}
ParsedQuicVersion version;
Perspective perspective;
};
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 QpackReceiveStreamTest : public QuicTestWithParam<TestParams> {
public:
QpackReceiveStreamTest()
: 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[] = {0x03};
QuicStreamFrame data1(id, false, 0, absl::string_view(type, 1));
session_.OnStreamFrame(data1);
qpack_receive_stream_ =
QuicSpdySessionPeer::GetQpackDecoderReceiveStream(&session_);
}
Perspective perspective() const { return GetParam().perspective; }
MockQuicConnectionHelper helper_;
MockAlarmFactory alarm_factory_;
StrictMock<MockQuicConnection>* connection_;
StrictMock<MockQuicSpdySession> session_;
QpackReceiveStream* qpack_receive_stream_;
};
INSTANTIATE_TEST_SUITE_P(Tests, QpackReceiveStreamTest,
::testing::ValuesIn(GetTestParams()));
TEST_P(QpackReceiveStreamTest, ResetQpackReceiveStream) {
EXPECT_TRUE(qpack_receive_stream_->is_static());
QuicRstStreamFrame rst_frame(kInvalidControlFrameId,
qpack_receive_stream_->id(),
QUIC_STREAM_CANCELLED, 1234);
EXPECT_CALL(*connection_,
CloseConnection(QUIC_HTTP_CLOSED_CRITICAL_STREAM, _, _));
qpack_receive_stream_->OnStreamReset(rst_frame);
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_receive_stream.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_receive_stream_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
109f995c-94fb-4864-98ce-1f4d803594a6 | cpp | google/quiche | qpack_index_conversions | quiche/quic/core/qpack/qpack_index_conversions.cc | quiche/quic/core/qpack/qpack_index_conversions_test.cc | #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));
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_index_conversions.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_index_conversions_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
6511299d-fed9-47da-995d-cdf6bba91657 | 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 | #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;
}
std::string copy;
std::swap(copy, buffer_);
delegate_->WriteStreamData(copy);
}
} | #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();
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_decoder_stream_sender.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_decoder_stream_sender_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
0cabf035-1484-418d-8410-4cd1d9607b33 | cpp | google/quiche | qpack_send_stream | quiche/quic/core/qpack/qpack_send_stream.cc | quiche/quic/core/qpack/qpack_send_stream_test.cc | #include "quiche/quic/core/qpack/qpack_send_stream.h"
#include "absl/base/macros.h"
#include "absl/strings/string_view.h"
#include "quiche/quic/core/quic_session.h"
namespace quic {
QpackSendStream::QpackSendStream(QuicStreamId id, QuicSession* session,
uint64_t http3_stream_type)
: QuicStream(id, session, true, WRITE_UNIDIRECTIONAL),
http3_stream_type_(http3_stream_type),
stream_type_sent_(false) {}
void QpackSendStream::OnStreamReset(const QuicRstStreamFrame& ) {
QUIC_BUG(quic_bug_10805_1)
<< "OnStreamReset() called for write unidirectional stream.";
}
bool QpackSendStream::OnStopSending(QuicResetStreamError ) {
stream_delegate()->OnStreamError(
QUIC_HTTP_CLOSED_CRITICAL_STREAM,
"STOP_SENDING received for QPACK send stream");
return false;
}
void QpackSendStream::WriteStreamData(absl::string_view data) {
QuicConnection::ScopedPacketFlusher flusher(session()->connection());
MaybeSendStreamType();
WriteOrBufferData(data, false, nullptr);
}
uint64_t QpackSendStream::NumBytesBuffered() const {
return QuicStream::BufferedDataBytes();
}
void QpackSendStream::MaybeSendStreamType() {
if (!stream_type_sent_) {
char type[sizeof(http3_stream_type_)];
QuicDataWriter writer(ABSL_ARRAYSIZE(type), type);
writer.WriteVarInt62(http3_stream_type_);
WriteOrBufferData(absl::string_view(writer.data(), writer.length()), false,
nullptr);
stream_type_sent_ = true;
}
}
} | #include "quiche/quic/core/qpack/qpack_send_stream.h"
#include <memory>
#include <string>
#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/http_constants.h"
#include "quiche/quic/platform/api/quic_test.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_spdy_session_peer.h"
#include "quiche/quic/test_tools/quic_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: version: "
<< ParsedQuicVersionToString(version)
<< ", perspective: " << perspective;
}
TestParams(const TestParams& other)
: version(other.version), perspective(other.perspective) {}
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 QpackSendStreamTest : public QuicTestWithParam<TestParams> {
public:
QpackSendStreamTest()
: connection_(new StrictMock<MockQuicConnection>(
&helper_, &alarm_factory_, perspective(),
SupportedVersions(GetParam().version))),
session_(connection_) {
EXPECT_CALL(session_, OnCongestionWindowChange(_)).Times(AnyNumber());
session_.Initialize();
connection_->SetEncrypter(
ENCRYPTION_FORWARD_SECURE,
std::make_unique<NullEncrypter>(connection_->perspective()));
if (connection_->version().SupportsAntiAmplificationLimit()) {
QuicConnectionPeer::SetAddressValidated(connection_);
}
QuicConfigPeer::SetReceivedInitialSessionFlowControlWindow(
session_.config(), kMinimumFlowControlSendWindow);
QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesUnidirectional(
session_.config(), kMinimumFlowControlSendWindow);
QuicConfigPeer::SetReceivedMaxUnidirectionalStreams(session_.config(), 3);
session_.OnConfigNegotiated();
qpack_send_stream_ =
QuicSpdySessionPeer::GetQpackDecoderSendStream(&session_);
ON_CALL(session_, WritevData(_, _, _, _, _, _))
.WillByDefault(Invoke(&session_, &MockQuicSpdySession::ConsumeData));
}
Perspective perspective() const { return GetParam().perspective; }
MockQuicConnectionHelper helper_;
MockAlarmFactory alarm_factory_;
StrictMock<MockQuicConnection>* connection_;
StrictMock<MockQuicSpdySession> session_;
QpackSendStream* qpack_send_stream_;
};
INSTANTIATE_TEST_SUITE_P(Tests, QpackSendStreamTest,
::testing::ValuesIn(GetTestParams()),
::testing::PrintToStringParamName());
TEST_P(QpackSendStreamTest, WriteStreamTypeOnlyFirstTime) {
std::string data = "data";
EXPECT_CALL(session_, WritevData(_, 1, _, _, _, _));
EXPECT_CALL(session_, WritevData(_, data.length(), _, _, _, _));
qpack_send_stream_->WriteStreamData(absl::string_view(data));
EXPECT_CALL(session_, WritevData(_, data.length(), _, _, _, _));
qpack_send_stream_->WriteStreamData(absl::string_view(data));
EXPECT_CALL(session_, WritevData(_, _, _, _, _, _)).Times(0);
qpack_send_stream_->MaybeSendStreamType();
}
TEST_P(QpackSendStreamTest, StopSendingQpackStream) {
EXPECT_CALL(*connection_,
CloseConnection(QUIC_HTTP_CLOSED_CRITICAL_STREAM, _, _));
qpack_send_stream_->OnStopSending(
QuicResetStreamError::FromInternal(QUIC_STREAM_CANCELLED));
}
TEST_P(QpackSendStreamTest, ReceiveDataOnSendStream) {
QuicStreamFrame frame(qpack_send_stream_->id(), false, 0, "test");
EXPECT_CALL(
*connection_,
CloseConnection(QUIC_DATA_RECEIVED_ON_WRITE_UNIDIRECTIONAL_STREAM, _, _));
qpack_send_stream_->OnStreamFrame(frame);
}
TEST_P(QpackSendStreamTest, GetSendWindowSizeFromSession) {
EXPECT_NE(session_.GetFlowControlSendWindowSize(qpack_send_stream_->id()),
std::numeric_limits<QuicByteCount>::max());
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_send_stream.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_send_stream_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
6e8c1f82-a063-4a88-b2c7-c93d33ccf681 | cpp | google/quiche | qpack_required_insert_count | quiche/quic/core/qpack/qpack_required_insert_count.cc | quiche/quic/core/qpack/qpack_required_insert_count_test.cc | #include "quiche/quic/core/qpack/qpack_required_insert_count.h"
#include <limits>
#include "quiche/quic/platform/api/quic_logging.h"
namespace quic {
uint64_t QpackEncodeRequiredInsertCount(uint64_t required_insert_count,
uint64_t max_entries) {
if (required_insert_count == 0) {
return 0;
}
return required_insert_count % (2 * max_entries) + 1;
}
bool QpackDecodeRequiredInsertCount(uint64_t encoded_required_insert_count,
uint64_t max_entries,
uint64_t total_number_of_inserts,
uint64_t* required_insert_count) {
if (encoded_required_insert_count == 0) {
*required_insert_count = 0;
return true;
}
QUICHE_DCHECK_LE(max_entries, std::numeric_limits<uint64_t>::max() / 32);
if (encoded_required_insert_count > 2 * max_entries) {
return false;
}
*required_insert_count = encoded_required_insert_count - 1;
QUICHE_DCHECK_LT(*required_insert_count,
std::numeric_limits<uint64_t>::max() / 16);
uint64_t current_wrapped = total_number_of_inserts % (2 * max_entries);
QUICHE_DCHECK_LT(current_wrapped, std::numeric_limits<uint64_t>::max() / 16);
if (current_wrapped >= *required_insert_count + max_entries) {
*required_insert_count += 2 * max_entries;
} else if (current_wrapped + max_entries < *required_insert_count) {
current_wrapped += 2 * max_entries;
}
if (*required_insert_count >
std::numeric_limits<uint64_t>::max() - total_number_of_inserts) {
return false;
}
*required_insert_count += total_number_of_inserts;
if (current_wrapped >= *required_insert_count) {
return false;
}
*required_insert_count -= current_wrapped;
return true;
}
} | #include "quiche/quic/core/qpack/qpack_required_insert_count.h"
#include "absl/base/macros.h"
#include "quiche/quic/platform/api/quic_test.h"
namespace quic {
namespace test {
namespace {
TEST(QpackRequiredInsertCountTest, QpackEncodeRequiredInsertCount) {
EXPECT_EQ(0u, QpackEncodeRequiredInsertCount(0, 0));
EXPECT_EQ(0u, QpackEncodeRequiredInsertCount(0, 8));
EXPECT_EQ(0u, QpackEncodeRequiredInsertCount(0, 1024));
EXPECT_EQ(2u, QpackEncodeRequiredInsertCount(1, 8));
EXPECT_EQ(5u, QpackEncodeRequiredInsertCount(20, 8));
EXPECT_EQ(7u, QpackEncodeRequiredInsertCount(106, 10));
}
struct {
uint64_t required_insert_count;
uint64_t max_entries;
uint64_t total_number_of_inserts;
} kTestData[] = {
{0, 0, 0},
{0, 100, 0},
{0, 100, 500},
{15, 100, 25},
{20, 100, 10},
{90, 100, 110},
{234, 100, 180},
{5678, 100, 5701},
{401, 100, 500},
{600, 100, 500}};
TEST(QpackRequiredInsertCountTest, QpackDecodeRequiredInsertCount) {
for (size_t i = 0; i < ABSL_ARRAYSIZE(kTestData); ++i) {
const uint64_t required_insert_count = kTestData[i].required_insert_count;
const uint64_t max_entries = kTestData[i].max_entries;
const uint64_t total_number_of_inserts =
kTestData[i].total_number_of_inserts;
if (required_insert_count != 0) {
ASSERT_LT(0u, max_entries) << i;
ASSERT_LT(total_number_of_inserts, required_insert_count + max_entries)
<< i;
ASSERT_LE(required_insert_count, total_number_of_inserts + max_entries)
<< i;
}
uint64_t encoded_required_insert_count =
QpackEncodeRequiredInsertCount(required_insert_count, max_entries);
uint64_t decoded_required_insert_count = required_insert_count + 1;
EXPECT_TRUE(QpackDecodeRequiredInsertCount(
encoded_required_insert_count, max_entries, total_number_of_inserts,
&decoded_required_insert_count))
<< i;
EXPECT_EQ(decoded_required_insert_count, required_insert_count) << i;
}
}
struct {
uint64_t encoded_required_insert_count;
uint64_t max_entries;
uint64_t total_number_of_inserts;
} kInvalidTestData[] = {
{1, 0, 0},
{9, 0, 0},
{1, 10, 2},
{18, 10, 2},
{400, 100, 500},
{601, 100, 500}};
TEST(QpackRequiredInsertCountTest, DecodeRequiredInsertCountError) {
for (size_t i = 0; i < ABSL_ARRAYSIZE(kInvalidTestData); ++i) {
uint64_t decoded_required_insert_count = 0;
EXPECT_FALSE(QpackDecodeRequiredInsertCount(
kInvalidTestData[i].encoded_required_insert_count,
kInvalidTestData[i].max_entries,
kInvalidTestData[i].total_number_of_inserts,
&decoded_required_insert_count))
<< i;
}
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_required_insert_count.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/qpack/qpack_required_insert_count_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
5fd54df9-c8ba-413c-8b2b-4506dc2a7011 | cpp | google/quiche | prr_sender | quiche/quic/core/congestion_control/prr_sender.cc | quiche/quic/core/congestion_control/prr_sender_test.cc | #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;
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/prr_sender.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/prr_sender_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
da86d2eb-96f5-4b19-ab4a-2a58a81896a6 | cpp | google/quiche | bandwidth_sampler | quiche/quic/core/congestion_control/bandwidth_sampler.cc | quiche/quic/core/congestion_control/bandwidth_sampler_test.cc | #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_count);
return extra_bytes_acked;
}
BandwidthSampler::BandwidthSampler(
const QuicUnackedPacketMap* unacked_packet_map,
QuicRoundTripCount max_height_tracker_window_length)
: total_bytes_sent_(0),
total_bytes_acked_(0),
total_bytes_lost_(0),
total_bytes_neutered_(0),
total_bytes_sent_at_last_acked_packet_(0),
last_acked_packet_sent_time_(QuicTime::Zero()),
last_acked_packet_ack_time_(QuicTime::Zero()),
is_app_limited_(true),
connection_state_map_(),
max_tracked_packets_(GetQuicFlag(quic_max_tracked_packet_count)),
unacked_packet_map_(unacked_packet_map),
max_ack_height_tracker_(max_height_tracker_window_length),
total_bytes_acked_after_last_ack_event_(0),
overestimate_avoidance_(false),
limit_max_ack_height_tracker_by_send_rate_(false) {}
BandwidthSampler::BandwidthSampler(const BandwidthSampler& other)
: total_bytes_sent_(other.total_bytes_sent_),
total_bytes_acked_(other.total_bytes_acked_),
total_bytes_lost_(other.total_bytes_lost_),
total_bytes_neutered_(other.total_bytes_neutered_),
total_bytes_sent_at_last_acked_packet_(
other.total_bytes_sent_at_last_acked_packet_),
last_acked_packet_sent_time_(other.last_acked_packet_sent_time_),
last_acked_packet_ack_time_(other.last_acked_packet_ack_time_),
last_sent_packet_(other.last_sent_packet_),
last_acked_packet_(other.last_acked_packet_),
is_app_limited_(other.is_app_limited_),
end_of_app_limited_phase_(other.end_of_app_limited_phase_),
connection_state_map_(other.connection_state_map_),
recent_ack_points_(other.recent_ack_points_),
a0_candidates_(other.a0_candidates_),
max_tracked_packets_(other.max_tracked_packets_),
unacked_packet_map_(other.unacked_packet_map_),
max_ack_height_tracker_(other.max_ack_height_tracker_),
total_bytes_acked_after_last_ack_event_(
other.total_bytes_acked_after_last_ack_event_),
overestimate_avoidance_(other.overestimate_avoidance_),
limit_max_ack_height_tracker_by_send_rate_(
other.limit_max_ack_height_tracker_by_send_rate_) {}
void BandwidthSampler::EnableOverestimateAvoidance() {
if (overestimate_avoidance_) {
return;
}
overestimate_avoidance_ = true;
max_ack_height_tracker_.SetAckAggregationBandwidthThreshold(2.0);
}
BandwidthSampler::~BandwidthSampler() {}
void BandwidthSampler::OnPacketSent(
QuicTime sent_time, QuicPacketNumber packet_number, QuicByteCount bytes,
QuicByteCount bytes_in_flight,
HasRetransmittableData has_retransmittable_data) {
last_sent_packet_ = packet_number;
if (has_retransmittable_data != HAS_RETRANSMITTABLE_DATA) {
return;
}
total_bytes_sent_ += bytes;
if (bytes_in_flight == 0) {
last_acked_packet_ack_time_ = sent_time;
if (overestimate_avoidance_) {
recent_ack_points_.Clear();
recent_ack_points_.Update(sent_time, total_bytes_acked_);
a0_candidates_.clear();
a0_candidates_.push_back(recent_ack_points_.MostRecentPoint());
}
total_bytes_sent_at_last_acked_packet_ = total_bytes_sent_;
last_acked_packet_sent_time_ = sent_time;
}
if (!connection_state_map_.IsEmpty() &&
packet_number >
connection_state_map_.last_packet() + max_tracked_packets_) {
if (unacked_packet_map_ != nullptr && !unacked_packet_map_->empty()) {
QuicPacketNumber maybe_least_unacked =
unacked_packet_map_->GetLeastUnacked();
QUIC_BUG(quic_bug_10437_1)
<< "BandwidthSampler in-flight packet map has exceeded maximum "
"number of tracked packets("
<< max_tracked_packets_
<< "). First tracked: " << connection_state_map_.first_packet()
<< "; last tracked: " << connection_state_map_.last_packet()
<< "; entry_slots_used: " << connection_state_map_.entry_slots_used()
<< "; number_of_present_entries: "
<< connection_state_map_.number_of_present_entries()
<< "; packet number: " << packet_number
<< "; unacked_map: " << unacked_packet_map_->DebugString()
<< "; total_bytes_sent: " << total_bytes_sent_
<< "; total_bytes_acked: " << total_bytes_acked_
<< "; total_bytes_lost: " << total_bytes_lost_
<< "; total_bytes_neutered: " << total_bytes_neutered_
<< "; last_acked_packet_sent_time: " << last_acked_packet_sent_time_
<< "; total_bytes_sent_at_last_acked_packet: "
<< total_bytes_sent_at_last_acked_packet_
<< "; least_unacked_packet_info: "
<< (unacked_packet_map_->IsUnacked(maybe_least_unacked)
? unacked_packet_map_
->GetTransmissionInfo(maybe_least_unacked)
.DebugString()
: "n/a");
} else {
QUIC_BUG(quic_bug_10437_2)
<< "BandwidthSampler in-flight packet map has exceeded maximum "
"number of tracked packets.";
}
}
bool success = connection_state_map_.Emplace(packet_number, sent_time, bytes,
bytes_in_flight + bytes, *this);
QUIC_BUG_IF(quic_bug_10437_3, !success)
<< "BandwidthSampler failed to insert the packet "
"into the map, most likely because it's already "
"in it.";
}
void BandwidthSampler::OnPacketNeutered(QuicPacketNumber packet_number) {
connection_state_map_.Remove(
packet_number, [&](const ConnectionStateOnSentPacket& sent_packet) {
QUIC_CODE_COUNT(quic_bandwidth_sampler_packet_neutered);
total_bytes_neutered_ += sent_packet.size();
});
}
BandwidthSamplerInterface::CongestionEventSample
BandwidthSampler::OnCongestionEvent(QuicTime ack_time,
const AckedPacketVector& acked_packets,
const LostPacketVector& lost_packets,
QuicBandwidth max_bandwidth,
QuicBandwidth est_bandwidth_upper_bound,
QuicRoundTripCount round_trip_count) {
CongestionEventSample event_sample;
SendTimeState last_lost_packet_send_state;
for (const LostPacket& packet : lost_packets) {
SendTimeState send_state =
OnPacketLost(packet.packet_number, packet.bytes_lost);
if (send_state.is_valid) {
last_lost_packet_send_state = send_state;
}
}
if (acked_packets.empty()) {
event_sample.last_packet_send_state = last_lost_packet_send_state;
return event_sample;
}
SendTimeState last_acked_packet_send_state;
QuicBandwidth max_send_rate = QuicBandwidth::Zero();
for (const auto& packet : acked_packets) {
if (packet.spurious_loss) {
QUICHE_DCHECK_EQ(packet.bytes_acked, 0);
continue;
}
BandwidthSample sample =
OnPacketAcknowledged(ack_time, packet.packet_number);
if (!sample.state_at_send.is_valid) {
continue;
}
last_acked_packet_send_state = sample.state_at_send;
if (!sample.rtt.IsZero()) {
event_sample.sample_rtt = std::min(event_sample.sample_rtt, sample.rtt);
}
if (sample.bandwidth > event_sample.sample_max_bandwidth) {
event_sample.sample_max_bandwidth = sample.bandwidth;
event_sample.sample_is_app_limited = sample.state_at_send.is_app_limited;
}
if (!sample.send_rate.IsInfinite()) {
max_send_rate = std::max(max_send_rate, sample.send_rate);
}
const QuicByteCount inflight_sample =
total_bytes_acked() - last_acked_packet_send_state.total_bytes_acked;
if (inflight_sample > event_sample.sample_max_inflight) {
event_sample.sample_max_inflight = inflight_sample;
}
}
if (!last_lost_packet_send_state.is_valid) {
event_sample.last_packet_send_state = last_acked_packet_send_state;
} else if (!last_acked_packet_send_state.is_valid) {
event_sample.last_packet_send_state = last_lost_packet_send_state;
} else {
event_sample.last_packet_send_state =
lost_packets.back().packet_number > acked_packets.back().packet_number
? last_lost_packet_send_state
: last_acked_packet_send_state;
}
bool is_new_max_bandwidth = event_sample.sample_max_bandwidth > max_bandwidth;
max_bandwidth = std::max(max_bandwidth, event_sample.sample_max_bandwidth);
if (limit_max_ack_height_tracker_by_send_rate_) {
max_bandwidth = std::max(max_bandwidth, max_send_rate);
}
event_sample.extra_acked =
OnAckEventEnd(std::min(est_bandwidth_upper_bound, max_bandwidth),
is_new_max_bandwidth, round_trip_count);
return event_sample;
}
QuicByteCount BandwidthSampler::OnAckEventEnd(
QuicBandwidth bandwidth_estimate, bool is_new_max_bandwidth,
QuicRoundTripCount round_trip_count) {
const QuicByteCount newly_acked_bytes =
total_bytes_acked_ - total_bytes_acked_after_last_ack_event_;
if (newly_acked_bytes == 0) {
return 0;
}
total_bytes_acked_after_last_ack_event_ = total_bytes_acked_;
QuicByteCount extra_acked = max_ack_height_tracker_.Update(
bandwidth_estimate, is_new_max_bandwidth, round_trip_count,
last_sent_packet_, last_acked_packet_, last_acked_packet_ack_time_,
newly_acked_bytes);
if (overestimate_avoidance_ && extra_acked == 0) {
a0_candidates_.push_back(recent_ack_points_.LessRecentPoint());
QUIC_DVLOG(1) << "New a0_candidate:" << a0_candidates_.back();
}
return extra_acked;
}
BandwidthSample BandwidthSampler::OnPacketAcknowledged(
QuicTime ack_time, QuicPacketNumber packet_number) {
last_acked_packet_ = packet_number;
ConnectionStateOnSentPacket* sent_packet_pointer =
connection_state_map_.GetEntry(packet_number);
if (sent_packet_pointer == nullptr) {
return BandwidthSample();
}
BandwidthSample sample =
OnPacketAcknowledgedInner(ack_time, packet_number, *sent_packet_pointer);
return sample;
}
BandwidthSample BandwidthSampler::OnPacketAcknowledgedInner(
QuicTime ack_time, QuicPacketNumber packet_number,
const ConnectionStateOnSentPacket& sent_packet) {
total_bytes_acked_ += sent_packet.size();
total_bytes_sent_at_last_acked_packet_ =
sent_packet.send_time_state().total_bytes_sent;
last_acked_packet_sent_time_ = sent_packet.sent_time();
last_acked_packet_ack_time_ = ack_time;
if (overestimate_avoidance_) {
recent_ack_points_.Update(ack_time, total_bytes_acked_);
}
if (is_app_limited_) {
if (!end_of_app_limited_phase_.IsInitialized() ||
packet_number > end_of_app_limited_phase_) {
is_app_limited_ = false;
}
}
if (sent_packet.last_acked_packet_sent_time() == QuicTime::Zero()) {
QUIC_BUG(quic_bug_10437_4)
<< "sent_packet.last_acked_packet_sent_time is zero";
return BandwidthSample();
}
QuicBandwidth send_rate = QuicBandwidth::Infinite();
if (sent_packet.sent_time() > sent_packet.last_acked_packet_sent_time()) {
send_rate = QuicBandwidth::FromBytesAndTimeDelta(
sent_packet.send_time_state().total_bytes_sent -
sent_packet.total_bytes_sent_at_last_acked_packet(),
sent_packet.sent_time() - sent_packet.last_acked_packet_sent_time());
}
AckPoint a0;
if (overestimate_avoidance_ &&
ChooseA0Point(sent_packet.send_time_state().total_bytes_acked, &a0)) {
QUIC_DVLOG(2) << "Using a0 point: " << a0;
} else {
a0.ack_time = sent_packet.last_acked_packet_ack_time(),
a0.total_bytes_acked = sent_packet.send_time_state().total_bytes_acked;
}
if (ack_time <= a0.ack_time) {
if (a0.ack_time == sent_packet.sent_time()) {
QUIC_CODE_COUNT_N(quic_prev_ack_time_larger_than_current_ack_time, 1, 2);
} else {
QUIC_CODE_COUNT_N(quic_prev_ack_time_larger_than_current_ack_time, 2, 2);
}
QUIC_LOG_EVERY_N_SEC(ERROR, 60)
<< "Time of the previously acked packet:"
<< a0.ack_time.ToDebuggingValue()
<< " is larger than the ack time of the current packet:"
<< ack_time.ToDebuggingValue()
<< ". acked packet number:" << packet_number
<< ", total_bytes_acked_:" << total_bytes_acked_
<< ", overestimate_avoidance_:" << overestimate_avoidance_
<< ", sent_packet:" << sent_packet;
return BandwidthSample();
}
QuicBandwidth ack_rate = QuicBandwidth::FromBytesAndTimeDelta(
total_bytes_acked_ - a0.total_bytes_acked, ack_time - a0.ack_time);
BandwidthSample sample;
sample.bandwidth = std::min(send_rate, ack_rate);
sample.rtt = ack_time - sent_packet.sent_time();
sample.send_rate = send_rate;
SentPacketToSendTimeState(sent_packet, &sample.state_at_send);
if (sample.bandwidth.IsZero()) {
QUIC_LOG_EVERY_N_SEC(ERROR, 60)
<< "ack_rate: " << ack_rate << ", send_rate: " << send_rate
<< ". acked packet number:" << packet_number
<< ", overestimate_avoidance_:" << overestimate_avoidance_ << "a1:{"
<< total_bytes_acked_ << "@" << ack_time << "}, a0:{"
<< a0.total_bytes_acked << "@" << a0.ack_time
<< "}, sent_packet:" << sent_packet;
}
return sample;
}
bool BandwidthSampler::ChooseA0Point(QuicByteCount total_bytes_acked,
AckPoint* a0) {
if (a0_candidates_.empty()) {
QUIC_BUG(quic_bug_10437_5)
<< "No A0 point candicates. total_bytes_acked:" << total_bytes_acked;
return false;
}
if (a0_candidates_.size() == 1) {
*a0 = a0_candidates_.front();
return true;
}
for (size_t i = 1; i < a0_candidates_.size(); ++i) {
if (a0_candidates_[i].total_bytes_acked > total_bytes_acked) {
*a0 = a0_candidates_[i - 1];
if (i > 1) {
a0_candidates_.pop_front_n(i - 1);
}
return true;
}
}
*a0 = a0_candidates_.back();
a0_candidates_.pop_front_n(a0_candidates_.size() - 1);
return true;
}
SendTimeState BandwidthSampler::OnPacketLost(QuicPacketNumber packet_number,
QuicPacketLength bytes_lost) {
SendTimeState send_time_state;
total_bytes_lost_ += bytes_lost;
ConnectionStateOnSentPacket* sent_packet_pointer =
connection_state_map_.GetEntry(packet_number);
if (sent_packet_pointer != nullptr) {
SentPacketToSendTimeState(*sent_packet_pointer, &send_time_state);
}
return send_time_state;
}
void BandwidthSampler::SentPacketToSendTimeState(
const ConnectionStateOnSentPacket& sent_packet,
SendTimeState* send_time_state) const {
*send_time_state = sent_packet.send_time_state();
send_time_state->is_valid = true;
}
void BandwidthSampler::OnAppLimited() {
is_app_limited_ = true;
end_of_app_limited_phase_ = last_sent_packet_;
}
void BandwidthSampler::RemoveObsoletePackets(QuicPacketNumber least_unacked) {
connection_state_map_.RemoveUpTo(least_unacked);
}
QuicByteCount BandwidthSampler::total_bytes_sent() const {
return total_bytes_sent_;
}
QuicByteCount BandwidthSampler::total_bytes_acked() const {
return total_bytes_acked_;
}
QuicByteCount BandwidthSampler::total_bytes_lost() const {
return total_bytes_lost_;
}
QuicByteCount BandwidthSampler::total_bytes_neutered() const {
return total_bytes_neutered_;
}
bool BandwidthSampler::is_app_limited() const { return is_app_limited_; }
QuicPacketNumber BandwidthSampler::end_of_app_limited_phase() const {
return end_of_app_limited_phase_;
}
} | #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),
1000, true);
EXPECT_EQ(3u, tracker_.num_ack_aggregation_epochs());
} else {
AggregationEpisode(bandwidth_ * 2, QuicTime::Delta::FromMilliseconds(50),
1000, false);
EXPECT_EQ(2u, tracker_.num_ack_aggregation_epochs());
}
}
TEST_F(MaxAckHeightTrackerTest, SomewhatAggregatedSmallAcks) {
AggregationEpisode(bandwidth_ * 2, QuicTime::Delta::FromMilliseconds(50), 100,
true);
AggregationEpisode(bandwidth_ * 2, QuicTime::Delta::FromMilliseconds(50), 100,
true);
now_ = now_ - QuicTime::Delta::FromMilliseconds(1);
if (tracker_.ack_aggregation_bandwidth_threshold() > 1.1) {
AggregationEpisode(bandwidth_ * 2, QuicTime::Delta::FromMilliseconds(50),
100, true);
EXPECT_EQ(3u, tracker_.num_ack_aggregation_epochs());
} else {
AggregationEpisode(bandwidth_ * 2, QuicTime::Delta::FromMilliseconds(50),
100, false);
EXPECT_EQ(2u, tracker_.num_ack_aggregation_epochs());
}
}
TEST_F(MaxAckHeightTrackerTest, NotAggregated) {
AggregationEpisode(bandwidth_, QuicTime::Delta::FromMilliseconds(100), 100,
true);
EXPECT_LT(2u, tracker_.num_ack_aggregation_epochs());
}
TEST_F(MaxAckHeightTrackerTest, StartNewEpochAfterAFullRound) {
last_sent_packet_number_ = QuicPacketNumber(10);
AggregationEpisode(bandwidth_ * 2, QuicTime::Delta::FromMilliseconds(50), 100,
true);
last_acked_packet_number_ = QuicPacketNumber(11);
tracker_.Update(bandwidth_ * 0.1, true, RoundTripCount(),
last_sent_packet_number_, last_acked_packet_number_, now_,
100);
EXPECT_EQ(2u, tracker_.num_ack_aggregation_epochs());
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/bandwidth_sampler.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/bandwidth_sampler_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
e2c248dd-78ba-4aea-9008-7c08db0ced96 | cpp | google/quiche | rtt_stats | quiche/quic/core/congestion_control/rtt_stats.cc | quiche/quic/core/congestion_control/rtt_stats_test.cc | #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);
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/rtt_stats.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/rtt_stats_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
1d31f4c3-4a06-4301-8ccf-985a4a4f853b | 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 | #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());
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/tcp_cubic_sender_bytes.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/tcp_cubic_sender_bytes_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
e95d1719-3e34-4bae-9718-58f6b1e988a4 | 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 | #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());
}
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/general_loss_algorithm.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/general_loss_algorithm_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |
c8a7d82a-a08b-47e8-9784-ea74e8f613ab | cpp | google/quiche | bbr_sender | quiche/quic/core/congestion_control/bbr_sender.cc | quiche/quic/core/congestion_control/bbr_sender_test.cc | #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 = gain * bdp;
if (congestion_window == 0) {
congestion_window = gain * initial_congestion_window_;
}
return std::max(congestion_window, min_congestion_window_);
}
QuicByteCount BbrSender::ProbeRttCongestionWindow() const {
return min_congestion_window_;
}
void BbrSender::EnterStartupMode(QuicTime now) {
if (stats_) {
++stats_->slowstart_count;
stats_->slowstart_duration.Start(now);
}
mode_ = STARTUP;
pacing_gain_ = high_gain_;
congestion_window_gain_ = high_cwnd_gain_;
}
void BbrSender::EnterProbeBandwidthMode(QuicTime now) {
mode_ = PROBE_BW;
congestion_window_gain_ = congestion_window_gain_constant_;
cycle_current_offset_ = random_->RandUint64() % (kGainCycleLength - 1);
if (cycle_current_offset_ >= 1) {
cycle_current_offset_ += 1;
}
last_cycle_start_ = now;
pacing_gain_ = kPacingGain[cycle_current_offset_];
}
bool BbrSender::UpdateRoundTripCounter(QuicPacketNumber last_acked_packet) {
if (!current_round_trip_end_.IsInitialized() ||
last_acked_packet > current_round_trip_end_) {
round_trip_count_++;
current_round_trip_end_ = last_sent_packet_;
if (stats_ && InSlowStart()) {
++stats_->slowstart_num_rtts;
}
return true;
}
return false;
}
bool BbrSender::MaybeUpdateMinRtt(QuicTime now,
QuicTime::Delta sample_min_rtt) {
bool min_rtt_expired =
!min_rtt_.IsZero() && (now > (min_rtt_timestamp_ + kMinRttExpiry));
if (min_rtt_expired || sample_min_rtt < min_rtt_ || min_rtt_.IsZero()) {
QUIC_DVLOG(2) << "Min RTT updated, old value: " << min_rtt_
<< ", new value: " << sample_min_rtt
<< ", current time: " << now.ToDebuggingValue();
min_rtt_ = sample_min_rtt;
min_rtt_timestamp_ = now;
}
QUICHE_DCHECK(!min_rtt_.IsZero());
return min_rtt_expired;
}
void BbrSender::UpdateGainCyclePhase(QuicTime now,
QuicByteCount prior_in_flight,
bool has_losses) {
const QuicByteCount bytes_in_flight = unacked_packets_->bytes_in_flight();
bool should_advance_gain_cycling = now - last_cycle_start_ > GetMinRtt();
if (pacing_gain_ > 1.0 && !has_losses &&
prior_in_flight < GetTargetCongestionWindow(pacing_gain_)) {
should_advance_gain_cycling = false;
}
if (pacing_gain_ < 1.0 && bytes_in_flight <= GetTargetCongestionWindow(1)) {
should_advance_gain_cycling = true;
}
if (should_advance_gain_cycling) {
cycle_current_offset_ = (cycle_current_offset_ + 1) % kGainCycleLength;
if (cycle_current_offset_ == 0) {
++stats_->bbr_num_cycles;
}
last_cycle_start_ = now;
if (drain_to_target_ && pacing_gain_ < 1 &&
kPacingGain[cycle_current_offset_] == 1 &&
bytes_in_flight > GetTargetCongestionWindow(1)) {
return;
}
pacing_gain_ = kPacingGain[cycle_current_offset_];
}
}
void BbrSender::CheckIfFullBandwidthReached(
const SendTimeState& last_packet_send_state) {
if (last_sample_is_app_limited_) {
return;
}
QuicBandwidth target = bandwidth_at_last_round_ * kStartupGrowthTarget;
if (BandwidthEstimate() >= target) {
bandwidth_at_last_round_ = BandwidthEstimate();
rounds_without_bandwidth_gain_ = 0;
if (expire_ack_aggregation_in_startup_) {
sampler_.ResetMaxAckHeightTracker(0, round_trip_count_);
}
return;
}
rounds_without_bandwidth_gain_++;
if ((rounds_without_bandwidth_gain_ >= num_startup_rtts_) ||
ShouldExitStartupDueToLoss(last_packet_send_state)) {
QUICHE_DCHECK(has_non_app_limited_sample_);
is_at_full_bandwidth_ = true;
}
}
void BbrSender::MaybeExitStartupOrDrain(QuicTime now) {
if (mode_ == STARTUP && is_at_full_bandwidth_) {
OnExitStartup(now);
mode_ = DRAIN;
pacing_gain_ = drain_gain_;
congestion_window_gain_ = high_cwnd_gain_;
}
if (mode_ == DRAIN &&
unacked_packets_->bytes_in_flight() <= GetTargetCongestionWindow(1)) {
EnterProbeBandwidthMode(now);
}
}
void BbrSender::OnExitStartup(QuicTime now) {
QUICHE_DCHECK_EQ(mode_, STARTUP);
if (stats_) {
stats_->slowstart_duration.Stop(now);
}
}
bool BbrSender::ShouldExitStartupDueToLoss(
const SendTimeState& last_packet_send_state) const {
if (num_loss_events_in_round_ <
GetQuicFlag(quic_bbr2_default_startup_full_loss_count) ||
!last_packet_send_state.is_valid) {
return false;
}
const QuicByteCount inflight_at_send = last_packet_send_state.bytes_in_flight;
if (inflight_at_send > 0 && bytes_lost_in_round_ > 0) {
if (bytes_lost_in_round_ >
inflight_at_send * GetQuicFlag(quic_bbr2_default_loss_threshold)) {
stats_->bbr_exit_startup_due_to_loss = true;
return true;
}
return false;
}
return false;
}
void BbrSender::MaybeEnterOrExitProbeRtt(QuicTime now, bool is_round_start,
bool min_rtt_expired) {
if (min_rtt_expired && !exiting_quiescence_ && mode_ != PROBE_RTT) {
if (InSlowStart()) {
OnExitStartup(now);
}
mode_ = PROBE_RTT;
pacing_gain_ = 1;
exit_probe_rtt_at_ = QuicTime::Zero();
}
if (mode_ == PROBE_RTT) {
sampler_.OnAppLimited();
if (exit_probe_rtt_at_ == QuicTime::Zero()) {
if (unacked_packets_->bytes_in_flight() <
ProbeRttCongestionWindow() + kMaxOutgoingPacketSize) {
exit_probe_rtt_at_ = now + kProbeRttTime;
probe_rtt_round_passed_ = false;
}
} else {
if (is_round_start) {
probe_rtt_round_passed_ = true;
}
if (now >= exit_probe_rtt_at_ && probe_rtt_round_passed_) {
min_rtt_timestamp_ = now;
if (!is_at_full_bandwidth_) {
EnterStartupMode(now);
} else {
EnterProbeBandwidthMode(now);
}
}
}
}
exiting_quiescence_ = false;
}
void BbrSender::UpdateRecoveryState(QuicPacketNumber last_acked_packet,
bool has_losses, bool is_round_start) {
if (!is_at_full_bandwidth_) {
return;
}
if (has_losses) {
end_recovery_at_ = last_sent_packet_;
}
switch (recovery_state_) {
case NOT_IN_RECOVERY:
if (has_losses) {
recovery_state_ = CONSERVATION;
recovery_window_ = 0;
current_round_trip_end_ = last_sent_packet_;
}
break;
case CONSERVATION:
if (is_round_start) {
recovery_state_ = GROWTH;
}
ABSL_FALLTHROUGH_INTENDED;
case GROWTH:
if (!has_losses && last_acked_packet > end_recovery_at_) {
recovery_state_ = NOT_IN_RECOVERY;
}
break;
}
}
void BbrSender::CalculatePacingRate(QuicByteCount bytes_lost) {
if (BandwidthEstimate().IsZero()) {
return;
}
QuicBandwidth target_rate = pacing_gain_ * BandwidthEstimate();
if (is_at_full_bandwidth_) {
pacing_rate_ = target_rate;
return;
}
if (pacing_rate_.IsZero() && !rtt_stats_->min_rtt().IsZero()) {
pacing_rate_ = QuicBandwidth::FromBytesAndTimeDelta(
initial_congestion_window_, rtt_stats_->min_rtt());
return;
}
if (detect_overshooting_) {
bytes_lost_while_detecting_overshooting_ += bytes_lost;
if (pacing_rate_ > target_rate &&
bytes_lost_while_detecting_overshooting_ > 0) {
if (has_non_app_limited_sample_ ||
bytes_lost_while_detecting_overshooting_ *
bytes_lost_multiplier_while_detecting_overshooting_ >
initial_congestion_window_) {
pacing_rate_ = std::max(
target_rate, QuicBandwidth::FromBytesAndTimeDelta(
cwnd_to_calculate_min_pacing_rate_, GetMinRtt()));
if (stats_) {
stats_->overshooting_detected_with_network_parameters_adjusted = true;
}
bytes_lost_while_detecting_overshooting_ = 0;
detect_overshooting_ = false;
}
}
}
pacing_rate_ = std::max(pacing_rate_, target_rate);
}
void BbrSender::CalculateCongestionWindow(QuicByteCount bytes_acked,
QuicByteCount excess_acked) {
if (mode_ == PROBE_RTT) {
return;
}
QuicByteCount target_window =
GetTargetCongestionWindow(congestion_window_gain_);
if (is_at_full_bandwidth_) {
target_window += sampler_.max_ack_height();
} else if (enable_ack_aggregation_during_startup_) {
target_window += excess_acked;
}
if (is_at_full_bandwidth_) {
congestion_window_ =
std::min(target_window, congestion_window_ + bytes_acked);
} else if (congestion_window_ < target_window ||
sampler_.total_bytes_acked() < initial_congestion_window_) {
congestion_window_ = congestion_window_ + bytes_acked;
}
congestion_window_ = std::max(congestion_window_, min_congestion_window_);
congestion_window_ = std::min(congestion_window_, max_congestion_window_);
}
void BbrSender::CalculateRecoveryWindow(QuicByteCount bytes_acked,
QuicByteCount bytes_lost) {
if (recovery_state_ == NOT_IN_RECOVERY) {
return;
}
if (recovery_window_ == 0) {
recovery_window_ = unacked_packets_->bytes_in_flight() + bytes_acked;
recovery_window_ = std::max(min_congestion_window_, recovery_window_);
return;
}
recovery_window_ = recovery_window_ >= bytes_lost
? recovery_window_ - bytes_lost
: kMaxSegmentSize;
if (recovery_state_ == GROWTH) {
recovery_window_ += bytes_acked;
}
recovery_window_ = std::max(
recovery_window_, unacked_packets_->bytes_in_flight() + bytes_acked);
recovery_window_ = std::max(min_congestion_window_, recovery_window_);
}
std::string BbrSender::GetDebugState() const {
std::ostringstream stream;
stream << ExportDebugState();
return stream.str();
}
void BbrSender::OnApplicationLimited(QuicByteCount bytes_in_flight) {
if (bytes_in_flight >= GetCongestionWindow()) {
return;
}
sampler_.OnAppLimited();
QUIC_DVLOG(2) << "Becoming application limited. Last sent packet: "
<< last_sent_packet_ << ", CWND: " << GetCongestionWindow();
}
void BbrSender::PopulateConnectionStats(QuicConnectionStats* stats) const {
stats->num_ack_aggregation_epochs = sampler_.num_ack_aggregation_epochs();
}
BbrSender::DebugState BbrSender::ExportDebugState() const {
return DebugState(*this);
}
static std::string ModeToString(BbrSender::Mode mode) {
switch (mode) {
case BbrSender::STARTUP:
return "STARTUP";
case BbrSender::DRAIN:
return "DRAIN";
case BbrSender::PROBE_BW:
return "PROBE_BW";
case BbrSender::PROBE_RTT:
return "PROBE_RTT";
}
return "???";
}
std::ostream& operator<<(std::ostream& os, const BbrSender::Mode& mode) {
os << ModeToString(mode);
return os;
}
std::ostream& operator<<(std::ostream& os, const BbrSender::DebugState& state) {
os << "Mode: " << ModeToString(state.mode) << std::endl;
os << "Maximum bandwidth: " << state.max_bandwidth << std::endl;
os << "Round trip counter: " << state.round_trip_count << std::endl;
os << "Gain cycle index: " << static_cast<int>(state.gain_cycle_index)
<< std::endl;
os << "Congestion window: " << state.congestion_window << " bytes"
<< std::endl;
if (state.mode == BbrSender::STARTUP) {
os << "(startup) Bandwidth at last round: " << state.bandwidth_at_last_round
<< std::endl;
os << "(startup) Rounds without gain: "
<< state.rounds_without_bandwidth_gain << std::endl;
}
os << "Minimum RTT: " << state.min_rtt << std::endl;
os << "Minimum RTT timestamp: " << state.min_rtt_timestamp.ToDebuggingValue()
<< std::endl;
os << "Last sample is app-limited: "
<< (state.last_sample_is_app_limited ? "yes" : "no");
return os;
}
} | #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_interval = QuicTime::Delta::FromMilliseconds(300);
for (int i = 0; i < 2; i++) {
SendBursts(5, target_bandwidth * burst_interval, burst_interval);
EXPECT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode);
EXPECT_EQ(0, sender_->ExportDebugState().gain_cycle_index);
EXPECT_APPROX_EQ(kTestLinkBandwidth,
sender_->ExportDebugState().max_bandwidth, 0.02f);
}
bbr_sender_.AddBytesToTransfer(1.3 * kTestBdp);
ASSERT_TRUE(simulator_.RunUntilOrTimeout(
[this]() { return sender_->ExportDebugState().gain_cycle_index == 1; },
timeout));
simulator_.RunFor(0.75 * sender_->ExportDebugState().min_rtt);
EXPECT_EQ(BbrSender::PROBE_BW, sender_->ExportDebugState().mode);
EXPECT_EQ(2, sender_->ExportDebugState().gain_cycle_index);
}
TEST_F(BbrSenderTest, NoBandwidthDropOnStartup) {
CreateDefaultSetup();
const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
bool simulator_result;
QuicBandwidth initial_rate = QuicBandwidth::FromBytesAndTimeDelta(
kInitialCongestionWindowPackets * kDefaultTCPMSS,
rtt_stats_->initial_rtt());
EXPECT_GE(sender_->PacingRate(0), initial_rate);
bbr_sender_.AddBytesToTransfer(1000);
simulator_result = simulator_.RunUntilOrTimeout(
[this]() { return receiver_.bytes_received() == 1000; }, timeout);
ASSERT_TRUE(simulator_result);
EXPECT_GE(sender_->PacingRate(0), initial_rate);
simulator_.RunFor(QuicTime::Delta::FromSeconds(2));
EXPECT_GE(sender_->PacingRate(0), initial_rate);
bbr_sender_.AddBytesToTransfer(1000);
simulator_result = simulator_.RunUntilOrTimeout(
[this]() { return receiver_.bytes_received() == 2000; }, timeout);
ASSERT_TRUE(simulator_result);
EXPECT_GE(sender_->PacingRate(0), initial_rate);
}
TEST_F(BbrSenderTest, SimpleTransfer1RTTStartup) {
CreateDefaultSetup();
SetConnectionOption(k1RTT);
EXPECT_EQ(1u, sender_->num_startup_rtts());
bbr_sender_.AddBytesToTransfer(12 * 1024 * 1024);
QuicRoundTripCount max_bw_round = 0;
QuicBandwidth max_bw(QuicBandwidth::Zero());
bool simulator_result = simulator_.RunUntilOrTimeout(
[this, &max_bw, &max_bw_round]() {
if (max_bw < sender_->ExportDebugState().max_bandwidth) {
max_bw = sender_->ExportDebugState().max_bandwidth;
max_bw_round = sender_->ExportDebugState().round_trip_count;
}
return sender_->ExportDebugState().is_at_full_bandwidth;
},
QuicTime::Delta::FromSeconds(5));
ASSERT_TRUE(simulator_result);
EXPECT_EQ(BbrSender::DRAIN, sender_->ExportDebugState().mode);
EXPECT_EQ(1u, sender_->ExportDebugState().round_trip_count - max_bw_round);
EXPECT_EQ(1u, sender_->ExportDebugState().rounds_without_bandwidth_gain);
EXPECT_EQ(0u, bbr_sender_.connection()->GetStats().packets_lost);
EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited);
}
TEST_F(BbrSenderTest, SimpleTransfer2RTTStartup) {
CreateDefaultSetup();
SetConnectionOption(k2RTT);
EXPECT_EQ(2u, sender_->num_startup_rtts());
bbr_sender_.AddBytesToTransfer(12 * 1024 * 1024);
QuicRoundTripCount max_bw_round = 0;
QuicBandwidth max_bw(QuicBandwidth::Zero());
bool simulator_result = simulator_.RunUntilOrTimeout(
[this, &max_bw, &max_bw_round]() {
if (max_bw * 1.001 < sender_->ExportDebugState().max_bandwidth) {
max_bw = sender_->ExportDebugState().max_bandwidth;
max_bw_round = sender_->ExportDebugState().round_trip_count;
}
return sender_->ExportDebugState().is_at_full_bandwidth;
},
QuicTime::Delta::FromSeconds(5));
ASSERT_TRUE(simulator_result);
EXPECT_EQ(BbrSender::DRAIN, sender_->ExportDebugState().mode);
EXPECT_EQ(2u, sender_->ExportDebugState().round_trip_count - max_bw_round);
EXPECT_EQ(2u, sender_->ExportDebugState().rounds_without_bandwidth_gain);
EXPECT_EQ(0u, bbr_sender_.connection()->GetStats().packets_lost);
EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited);
}
TEST_F(BbrSenderTest, SimpleTransferExitStartupOnLoss) {
CreateDefaultSetup();
EXPECT_EQ(3u, sender_->num_startup_rtts());
bbr_sender_.AddBytesToTransfer(12 * 1024 * 1024);
QuicRoundTripCount max_bw_round = 0;
QuicBandwidth max_bw(QuicBandwidth::Zero());
bool simulator_result = simulator_.RunUntilOrTimeout(
[this, &max_bw, &max_bw_round]() {
if (max_bw * 1.001 < sender_->ExportDebugState().max_bandwidth) {
max_bw = sender_->ExportDebugState().max_bandwidth;
max_bw_round = sender_->ExportDebugState().round_trip_count;
}
return sender_->ExportDebugState().is_at_full_bandwidth;
},
QuicTime::Delta::FromSeconds(5));
ASSERT_TRUE(simulator_result);
EXPECT_EQ(BbrSender::DRAIN, sender_->ExportDebugState().mode);
EXPECT_EQ(3u, sender_->ExportDebugState().round_trip_count - max_bw_round);
EXPECT_EQ(3u, sender_->ExportDebugState().rounds_without_bandwidth_gain);
EXPECT_EQ(0u, bbr_sender_.connection()->GetStats().packets_lost);
EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited);
}
TEST_F(BbrSenderTest, SimpleTransferExitStartupOnLossSmallBuffer) {
CreateSmallBufferSetup();
EXPECT_EQ(3u, sender_->num_startup_rtts());
bbr_sender_.AddBytesToTransfer(12 * 1024 * 1024);
QuicRoundTripCount max_bw_round = 0;
QuicBandwidth max_bw(QuicBandwidth::Zero());
bool simulator_result = simulator_.RunUntilOrTimeout(
[this, &max_bw, &max_bw_round]() {
if (max_bw < sender_->ExportDebugState().max_bandwidth) {
max_bw = sender_->ExportDebugState().max_bandwidth;
max_bw_round = sender_->ExportDebugState().round_trip_count;
}
return sender_->ExportDebugState().is_at_full_bandwidth;
},
QuicTime::Delta::FromSeconds(5));
ASSERT_TRUE(simulator_result);
EXPECT_EQ(BbrSender::DRAIN, sender_->ExportDebugState().mode);
EXPECT_GE(2u, sender_->ExportDebugState().round_trip_count - max_bw_round);
EXPECT_EQ(1u, sender_->ExportDebugState().rounds_without_bandwidth_gain);
EXPECT_NE(0u, bbr_sender_.connection()->GetStats().packets_lost);
EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited);
}
TEST_F(BbrSenderTest, DerivedPacingGainStartup) {
CreateDefaultSetup();
SetConnectionOption(kBBQ1);
EXPECT_EQ(3u, sender_->num_startup_rtts());
EXPECT_TRUE(sender_->InSlowStart());
QuicBandwidth expected_pacing_rate = QuicBandwidth::FromBytesAndTimeDelta(
2.773 * kDefaultWindowTCP, rtt_stats_->initial_rtt());
EXPECT_APPROX_EQ(expected_pacing_rate.ToBitsPerSecond(),
sender_->PacingRate(0).ToBitsPerSecond(), 0.01f);
bbr_sender_.AddBytesToTransfer(12 * 1024 * 1024);
bool simulator_result = simulator_.RunUntilOrTimeout(
[this]() { return sender_->ExportDebugState().is_at_full_bandwidth; },
QuicTime::Delta::FromSeconds(5));
ASSERT_TRUE(simulator_result);
EXPECT_EQ(BbrSender::DRAIN, sender_->ExportDebugState().mode);
EXPECT_EQ(3u, sender_->ExportDebugState().rounds_without_bandwidth_gain);
EXPECT_APPROX_EQ(kTestLinkBandwidth,
sender_->ExportDebugState().max_bandwidth, 0.01f);
EXPECT_EQ(0u, bbr_sender_.connection()->GetStats().packets_lost);
EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited);
}
TEST_F(BbrSenderTest, DerivedCWNDGainStartup) {
CreateSmallBufferSetup();
EXPECT_EQ(3u, sender_->num_startup_rtts());
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);
bbr_sender_.AddBytesToTransfer(12 * 1024 * 1024);
bool simulator_result = simulator_.RunUntilOrTimeout(
[this]() { return sender_->ExportDebugState().is_at_full_bandwidth; },
QuicTime::Delta::FromSeconds(5));
ASSERT_TRUE(simulator_result);
EXPECT_EQ(BbrSender::DRAIN, sender_->ExportDebugState().mode);
if (!bbr_sender_.connection()->GetStats().bbr_exit_startup_due_to_loss) {
EXPECT_EQ(3u, sender_->ExportDebugState().rounds_without_bandwidth_gain);
}
EXPECT_APPROX_EQ(kTestLinkBandwidth,
sender_->ExportDebugState().max_bandwidth, 0.01f);
float loss_rate =
static_cast<float>(bbr_sender_.connection()->GetStats().packets_lost) /
bbr_sender_.connection()->GetStats().packets_sent;
EXPECT_LT(loss_rate, 0.15f);
EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited);
EXPECT_GT(kTestRtt * 2.7, rtt_stats_->smoothed_rtt());
}
TEST_F(BbrSenderTest, AckAggregationInStartup) {
CreateDefaultSetup();
SetConnectionOption(kBBQ3);
EXPECT_EQ(3u, sender_->num_startup_rtts());
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);
bbr_sender_.AddBytesToTransfer(12 * 1024 * 1024);
bool simulator_result = simulator_.RunUntilOrTimeout(
[this]() { return sender_->ExportDebugState().is_at_full_bandwidth; },
QuicTime::Delta::FromSeconds(5));
ASSERT_TRUE(simulator_result);
EXPECT_EQ(BbrSender::DRAIN, sender_->ExportDebugState().mode);
EXPECT_EQ(3u, sender_->ExportDebugState().rounds_without_bandwidth_gain);
EXPECT_APPROX_EQ(kTestLinkBandwidth,
sender_->ExportDebugState().max_bandwidth, 0.01f);
EXPECT_EQ(0u, bbr_sender_.connection()->GetStats().packets_lost);
EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited);
}
TEST_F(BbrSenderTest, SimpleCompetition) {
const QuicByteCount transfer_size = 10 * 1024 * 1024;
const QuicTime::Delta transfer_time =
kTestLinkBandwidth.TransferTime(transfer_size);
CreateBbrVsBbrSetup();
bbr_sender_.AddBytesToTransfer(transfer_size);
bool simulator_result = simulator_.RunUntilOrTimeout(
[this]() { return receiver_.bytes_received() >= 0.1 * transfer_size; },
transfer_time);
ASSERT_TRUE(simulator_result);
competing_sender_.AddBytesToTransfer(transfer_size);
simulator_result = simulator_.RunUntilOrTimeout(
[this]() {
return receiver_.bytes_received() == transfer_size &&
competing_receiver_.bytes_received() == transfer_size;
},
3 * transfer_time);
ASSERT_TRUE(simulator_result);
}
TEST_F(BbrSenderTest, ResumeConnectionState) {
CreateDefaultSetup();
bbr_sender_.connection()->AdjustNetworkParameters(
SendAlgorithmInterface::NetworkParams(kTestLinkBandwidth, kTestRtt,
false));
EXPECT_EQ(kTestLinkBandwidth * kTestRtt,
sender_->ExportDebugState().congestion_window);
EXPECT_EQ(kTestLinkBandwidth, sender_->PacingRate(0));
EXPECT_APPROX_EQ(kTestRtt, sender_->ExportDebugState().min_rtt, 0.01f);
DriveOutOfStartup();
}
TEST_F(BbrSenderTest, ProbeRTTMinCWND1) {
CreateDefaultSetup();
SetConnectionOption(kMIN1);
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);
EXPECT_EQ(kDefaultTCPMSS, sender_->GetCongestionWindow());
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, StartupStats) {
CreateDefaultSetup();
DriveOutOfStartup();
ASSERT_FALSE(sender_->InSlowStart());
const QuicConnectionStats& stats = bbr_sender_.connection()->GetStats();
EXPECT_EQ(1u, stats.slowstart_count);
EXPECT_THAT(stats.slowstart_num_rtts, AllOf(Ge(5u), Le(15u)));
EXPECT_THAT(stats.slowstart_packets_sent, AllOf(Ge(100u), Le(1000u)));
EXPECT_THAT(stats.slowstart_bytes_sent, AllOf(Ge(100000u), Le(1000000u)));
EXPECT_LE(stats.slowstart_packets_lost, 10u);
EXPECT_LE(stats.slowstart_bytes_lost, 10000u);
EXPECT_FALSE(stats.slowstart_duration.IsRunning());
EXPECT_THAT(stats.slowstart_duration.GetTotalElapsedTime(),
AllOf(Ge(QuicTime::Delta::FromMilliseconds(500)),
Le(QuicTime::Delta::FromMilliseconds(1500))));
EXPECT_EQ(stats.slowstart_duration.GetTotalElapsedTime(),
QuicConnectionPeer::GetSentPacketManager(bbr_sender_.connection())
->GetSlowStartDuration());
}
TEST_F(BbrSenderTest, RecalculatePacingRateOnCwndChange1RTT) {
CreateDefaultSetup();
bbr_sender_.AddBytesToTransfer(1 * 1024 * 1024);
const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
bool simulator_result = simulator_.RunUntilOrTimeout(
[this]() { return !sender_->ExportDebugState().min_rtt.IsZero(); },
timeout);
ASSERT_TRUE(simulator_result);
const QuicByteCount previous_cwnd =
sender_->ExportDebugState().congestion_window;
bbr_sender_.connection()->AdjustNetworkParameters(
SendAlgorithmInterface::NetworkParams(kTestLinkBandwidth,
QuicTime::Delta::Zero(), false));
EXPECT_LT(previous_cwnd, sender_->ExportDebugState().congestion_window);
EXPECT_APPROX_EQ(QuicBandwidth::FromBytesAndTimeDelta(
sender_->ExportDebugState().congestion_window,
sender_->ExportDebugState().min_rtt),
sender_->PacingRate(0), 0.01f);
}
TEST_F(BbrSenderTest, RecalculatePacingRateOnCwndChange0RTT) {
CreateDefaultSetup();
const_cast<RttStats*>(rtt_stats_)->set_initial_rtt(kTestRtt);
bbr_sender_.connection()->AdjustNetworkParameters(
SendAlgorithmInterface::NetworkParams(kTestLinkBandwidth,
QuicTime::Delta::Zero(), false));
EXPECT_LT(kInitialCongestionWindowPackets * kDefaultTCPMSS,
sender_->ExportDebugState().congestion_window);
EXPECT_TRUE(sender_->ExportDebugState().min_rtt.IsZero());
EXPECT_APPROX_EQ(QuicBandwidth::FromBytesAndTimeDelta(
sender_->ExportDebugState().congestion_window,
rtt_stats_->initial_rtt()),
sender_->PacingRate(0), 0.01f);
}
TEST_F(BbrSenderTest, MitigateCwndBootstrappingOvershoot) {
CreateDefaultSetup();
bbr_sender_.AddBytesToTransfer(1 * 1024 * 1024);
const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
bool simulator_result = simulator_.RunUntilOrTimeout(
[this]() { return !sender_->ExportDebugState().min_rtt.IsZero(); },
timeout);
ASSERT_TRUE(simulator_result);
bbr_sender_.connection()->AdjustNetworkParameters(
SendAlgorithmInterface::NetworkParams(8 * kTestLinkBandwidth,
QuicTime::Delta::Zero(), false));
QuicBandwidth pacing_rate = sender_->PacingRate(0);
EXPECT_EQ(8 * kTestLinkBandwidth, pacing_rate);
simulator_result = simulator_.RunUntilOrTimeout(
[this, pacing_rate]() { return sender_->PacingRate(0) < pacing_rate; },
timeout);
ASSERT_TRUE(simulator_result);
EXPECT_EQ(BbrSender::STARTUP, sender_->ExportDebugState().mode);
if (GetQuicReloadableFlag(quic_conservative_cwnd_and_pacing_gains)) {
EXPECT_APPROX_EQ(2.0f * sender_->BandwidthEstimate(),
sender_->PacingRate(0), 0.01f);
} else {
EXPECT_APPROX_EQ(2.885f * sender_->BandwidthEstimate(),
sender_->PacingRate(0), 0.01f);
}
}
TEST_F(BbrSenderTest, 200InitialCongestionWindowWithNetworkParameterAdjusted) {
CreateDefaultSetup();
bbr_sender_.AddBytesToTransfer(1 * 1024 * 1024);
const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
bool simulator_result = simulator_.RunUntilOrTimeout(
[this]() { return !sender_->ExportDebugState().min_rtt.IsZero(); },
timeout);
ASSERT_TRUE(simulator_result);
bbr_sender_.connection()->AdjustNetworkParameters(
SendAlgorithmInterface::NetworkParams(1024 * kTestLinkBandwidth,
QuicTime::Delta::Zero(), false));
EXPECT_EQ(200 * kDefaultTCPMSS,
sender_->ExportDebugState().congestion_window);
EXPECT_GT(1024 * kTestLinkBandwidth, sender_->PacingRate(0));
}
TEST_F(BbrSenderTest, 100InitialCongestionWindowFromNetworkParameter) {
CreateDefaultSetup();
bbr_sender_.AddBytesToTransfer(1 * 1024 * 1024);
const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
bool simulator_result = simulator_.RunUntilOrTimeout(
[this]() { return !sender_->ExportDebugState().min_rtt.IsZero(); },
timeout);
ASSERT_TRUE(simulator_result);
SendAlgorithmInterface::NetworkParams network_params(
1024 * kTestLinkBandwidth, QuicTime::Delta::Zero(), false);
network_params.max_initial_congestion_window = 100;
bbr_sender_.connection()->AdjustNetworkParameters(network_params);
EXPECT_EQ(100 * kDefaultTCPMSS,
sender_->ExportDebugState().congestion_window);
EXPECT_GT(1024 * kTestLinkBandwidth, sender_->PacingRate(0));
}
TEST_F(BbrSenderTest, 100InitialCongestionWindowWithNetworkParameterAdjusted) {
SetConnectionOption(kICW1);
CreateDefaultSetup();
bbr_sender_.AddBytesToTransfer(1 * 1024 * 1024);
const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
bool simulator_result = simulator_.RunUntilOrTimeout(
[this]() { return !sender_->ExportDebugState().min_rtt.IsZero(); },
timeout);
ASSERT_TRUE(simulator_result);
bbr_sender_.connection()->AdjustNetworkParameters(
SendAlgorithmInterface::NetworkParams(1024 * kTestLinkBandwidth,
QuicTime::Delta::Zero(), false));
EXPECT_EQ(100 * kDefaultTCPMSS,
sender_->ExportDebugState().congestion_window);
EXPECT_GT(1024 * kTestLinkBandwidth, sender_->PacingRate(0));
}
TEST_F(BbrSenderTest, LossOnlyCongestionEvent) {
CreateDefaultSetup();
DriveOutOfStartup();
EXPECT_FALSE(sender_->ExportDebugState().last_sample_is_app_limited);
SendBursts(20, 512, QuicTime::Delta::FromSeconds(3));
QuicUnackedPacketMap* unacked_packets =
QuicSentPacketManagerPeer::GetUnackedPacketMap(
QuicConnectionPeer::GetSentPacketManager(bbr_sender_.connection()));
bbr_sender_.AddBytesToTransfer(50 * 1024 * 1024);
bool simulator_result = simulator_.RunUntilOrTimeout(
[&]() { return unacked_packets->bytes_in_flight() > 0; },
QuicTime::Delta::FromSeconds(5));
ASSERT_TRUE(simulator_result);
const QuicBandwidth prior_bandwidth_estimate = sender_->BandwidthEstimate();
EXPECT_APPROX_EQ(kTestLinkBandwidth, prior_bandwidth_estimate, 0.01f);
LostPacketVector lost_packets;
lost_packets.emplace_back(
bbr_sender_.connection()->sent_packet_manager().GetLeastUnacked(),
kDefaultMaxPacketSize);
QuicTime now = simulator_.GetClock()->Now() + kTestRtt * 0.25;
sender_->OnCongestionEvent(false, unacked_packets->bytes_in_flight(), now, {},
lost_packets, 0, 0);
EXPECT_EQ(prior_bandwidth_estimate, sender_->BandwidthEstimate());
}
TEST_F(BbrSenderTest, EnableOvershootingDetection) {
SetConnectionOption(kDTOS);
CreateSmallBufferSetup();
sender_->SetInitialCongestionWindowInPackets(200);
const QuicConnectionStats& stats = bbr_sender_.connection()->GetStats();
EXPECT_FALSE(stats.overshooting_detected_with_network_parameters_adjusted);
DoSimpleTransfer(12 * 1024 * 1024, QuicTime::Delta::FromSeconds(30));
EXPECT_TRUE(stats.overshooting_detected_with_network_parameters_adjusted);
}
}
} | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/bbr_sender.cc | https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/congestion_control/bbr_sender_test.cc | 6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6 |