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
59850b8a-9af1-4d1f-93e0-83f0db49b34b
cpp
google/quiche
priority_payload_decoder
quiche/http2/decoder/payload_decoders/priority_payload_decoder.cc
quiche/http2/decoder/payload_decoders/priority_payload_decoder_test.cc
#include "quiche/http2/decoder/payload_decoders/priority_payload_decoder.h" #include "quiche/http2/decoder/decode_buffer.h" #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/http2_structures.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { DecodeStatus PriorityPayloadDecoder::StartDecodingPayload( FrameDecoderState* state, DecodeBuffer* db) { QUICHE_DVLOG(2) << "PriorityPayloadDecoder::StartDecodingPayload: " << state->frame_header(); QUICHE_DCHECK_EQ(Http2FrameType::PRIORITY, state->frame_header().type); QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length); QUICHE_DCHECK_EQ(0, state->frame_header().flags); state->InitializeRemainders(); return HandleStatus( state, state->StartDecodingStructureInPayload(&priority_fields_, db)); } DecodeStatus PriorityPayloadDecoder::ResumeDecodingPayload( FrameDecoderState* state, DecodeBuffer* db) { QUICHE_DVLOG(2) << "PriorityPayloadDecoder::ResumeDecodingPayload" << " remaining_payload=" << state->remaining_payload() << " db->Remaining=" << db->Remaining(); QUICHE_DCHECK_EQ(Http2FrameType::PRIORITY, state->frame_header().type); QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length); return HandleStatus( state, state->ResumeDecodingStructureInPayload(&priority_fields_, db)); } DecodeStatus PriorityPayloadDecoder::HandleStatus(FrameDecoderState* state, DecodeStatus status) { if (status == DecodeStatus::kDecodeDone) { if (state->remaining_payload() == 0) { state->listener()->OnPriorityFrame(state->frame_header(), priority_fields_); return DecodeStatus::kDecodeDone; } return state->ReportFrameSizeError(); } QUICHE_DCHECK( (status == DecodeStatus::kDecodeInProgress && state->remaining_payload() > 0) || (status == DecodeStatus::kDecodeError && state->remaining_payload() == 0)) << "\n status=" << status << "; remaining_payload=" << state->remaining_payload(); return status; } }
#include "quiche/http2/decoder/payload_decoders/priority_payload_decoder.h" #include <stddef.h> #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/test_tools/frame_parts.h" #include "quiche/http2/test_tools/frame_parts_collector.h" #include "quiche/http2/test_tools/http2_frame_builder.h" #include "quiche/http2/test_tools/http2_random.h" #include "quiche/http2/test_tools/http2_structures_test_util.h" #include "quiche/http2/test_tools/payload_decoder_base_test_util.h" #include "quiche/http2/test_tools/random_decoder_test_base.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { class PriorityPayloadDecoderPeer { public: static constexpr Http2FrameType FrameType() { return Http2FrameType::PRIORITY; } static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; } }; namespace { struct Listener : public FramePartsCollector { void OnPriorityFrame(const Http2FrameHeader& header, const Http2PriorityFields& priority_fields) override { QUICHE_VLOG(1) << "OnPriority: " << header << "; " << priority_fields; StartAndEndFrame(header)->OnPriorityFrame(header, priority_fields); } void OnFrameSizeError(const Http2FrameHeader& header) override { QUICHE_VLOG(1) << "OnFrameSizeError: " << header; FrameError(header)->OnFrameSizeError(header); } }; class PriorityPayloadDecoderTest : public AbstractPayloadDecoderTest<PriorityPayloadDecoder, PriorityPayloadDecoderPeer, Listener> { protected: Http2PriorityFields RandPriorityFields() { Http2PriorityFields fields; test::Randomize(&fields, RandomPtr()); return fields; } }; TEST_F(PriorityPayloadDecoderTest, WrongSize) { auto approve_size = [](size_t size) { return size != Http2PriorityFields::EncodedSize(); }; Http2FrameBuilder fb; fb.Append(RandPriorityFields()); fb.Append(RandPriorityFields()); EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size)); } TEST_F(PriorityPayloadDecoderTest, VariousPayloads) { for (int n = 0; n < 100; ++n) { Http2PriorityFields fields = RandPriorityFields(); Http2FrameBuilder fb; fb.Append(fields); Http2FrameHeader header(fb.size(), Http2FrameType::PRIORITY, RandFlags(), RandStreamId()); set_frame_header(header); FrameParts expected(header); expected.SetOptPriority(fields); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected)); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/payload_decoders/priority_payload_decoder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/payload_decoders/priority_payload_decoder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
f857cb78-1b84-4589-8034-a066e6472e42
cpp
google/quiche
altsvc_payload_decoder
quiche/http2/decoder/payload_decoders/altsvc_payload_decoder.cc
quiche/http2/decoder/payload_decoders/altsvc_payload_decoder_test.cc
#include "quiche/http2/decoder/payload_decoders/altsvc_payload_decoder.h" #include <stddef.h> #include <ostream> #include "absl/base/macros.h" #include "quiche/http2/decoder/decode_buffer.h" #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/http2_structures.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { std::ostream& operator<<(std::ostream& out, AltSvcPayloadDecoder::PayloadState v) { switch (v) { case AltSvcPayloadDecoder::PayloadState::kStartDecodingStruct: return out << "kStartDecodingStruct"; case AltSvcPayloadDecoder::PayloadState::kMaybeDecodedStruct: return out << "kMaybeDecodedStruct"; case AltSvcPayloadDecoder::PayloadState::kDecodingStrings: return out << "kDecodingStrings"; case AltSvcPayloadDecoder::PayloadState::kResumeDecodingStruct: return out << "kResumeDecodingStruct"; } int unknown = static_cast<int>(v); QUICHE_BUG(http2_bug_163_1) << "Invalid AltSvcPayloadDecoder::PayloadState: " << unknown; return out << "AltSvcPayloadDecoder::PayloadState(" << unknown << ")"; } DecodeStatus AltSvcPayloadDecoder::StartDecodingPayload( FrameDecoderState* state, DecodeBuffer* db) { QUICHE_DVLOG(2) << "AltSvcPayloadDecoder::StartDecodingPayload: " << state->frame_header(); QUICHE_DCHECK_EQ(Http2FrameType::ALTSVC, state->frame_header().type); QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length); QUICHE_DCHECK_EQ(0, state->frame_header().flags); state->InitializeRemainders(); payload_state_ = PayloadState::kStartDecodingStruct; return ResumeDecodingPayload(state, db); } DecodeStatus AltSvcPayloadDecoder::ResumeDecodingPayload( FrameDecoderState* state, DecodeBuffer* db) { const Http2FrameHeader& frame_header = state->frame_header(); QUICHE_DVLOG(2) << "AltSvcPayloadDecoder::ResumeDecodingPayload: " << frame_header; QUICHE_DCHECK_EQ(Http2FrameType::ALTSVC, frame_header.type); QUICHE_DCHECK_LE(state->remaining_payload(), frame_header.payload_length); QUICHE_DCHECK_LE(db->Remaining(), state->remaining_payload()); QUICHE_DCHECK_NE(PayloadState::kMaybeDecodedStruct, payload_state_); DecodeStatus status = DecodeStatus::kDecodeError; while (true) { QUICHE_DVLOG(2) << "AltSvcPayloadDecoder::ResumeDecodingPayload payload_state_=" << payload_state_; switch (payload_state_) { case PayloadState::kStartDecodingStruct: status = state->StartDecodingStructureInPayload(&altsvc_fields_, db); ABSL_FALLTHROUGH_INTENDED; case PayloadState::kMaybeDecodedStruct: if (status == DecodeStatus::kDecodeDone && altsvc_fields_.origin_length <= state->remaining_payload()) { size_t origin_length = altsvc_fields_.origin_length; size_t value_length = state->remaining_payload() - origin_length; state->listener()->OnAltSvcStart(frame_header, origin_length, value_length); } else if (status != DecodeStatus::kDecodeDone) { QUICHE_DCHECK(state->remaining_payload() > 0 || status == DecodeStatus::kDecodeError) << "\nremaining_payload: " << state->remaining_payload() << "\nstatus: " << status << "\nheader: " << frame_header; payload_state_ = PayloadState::kResumeDecodingStruct; return status; } else { QUICHE_DCHECK_GT(altsvc_fields_.origin_length, state->remaining_payload()); return state->ReportFrameSizeError(); } ABSL_FALLTHROUGH_INTENDED; case PayloadState::kDecodingStrings: return DecodeStrings(state, db); case PayloadState::kResumeDecodingStruct: status = state->ResumeDecodingStructureInPayload(&altsvc_fields_, db); payload_state_ = PayloadState::kMaybeDecodedStruct; continue; } QUICHE_BUG(http2_bug_163_2) << "PayloadState: " << payload_state_; } } DecodeStatus AltSvcPayloadDecoder::DecodeStrings(FrameDecoderState* state, DecodeBuffer* db) { QUICHE_DVLOG(2) << "AltSvcPayloadDecoder::DecodeStrings remaining_payload=" << state->remaining_payload() << ", db->Remaining=" << db->Remaining(); size_t origin_length = altsvc_fields_.origin_length; size_t value_length = state->frame_header().payload_length - origin_length - Http2AltSvcFields::EncodedSize(); if (state->remaining_payload() > value_length) { size_t remaining_origin_length = state->remaining_payload() - value_length; size_t avail = db->MinLengthRemaining(remaining_origin_length); state->listener()->OnAltSvcOriginData(db->cursor(), avail); db->AdvanceCursor(avail); state->ConsumePayload(avail); if (remaining_origin_length > avail) { payload_state_ = PayloadState::kDecodingStrings; return DecodeStatus::kDecodeInProgress; } } QUICHE_DCHECK_LE(state->remaining_payload(), value_length); QUICHE_DCHECK_LE(db->Remaining(), state->remaining_payload()); if (db->HasData()) { size_t avail = db->Remaining(); state->listener()->OnAltSvcValueData(db->cursor(), avail); db->AdvanceCursor(avail); state->ConsumePayload(avail); } if (state->remaining_payload() == 0) { state->listener()->OnAltSvcEnd(); return DecodeStatus::kDecodeDone; } payload_state_ = PayloadState::kDecodingStrings; return DecodeStatus::kDecodeInProgress; } }
#include "quiche/http2/decoder/payload_decoders/altsvc_payload_decoder.h" #include <stddef.h> #include <string> #include <tuple> #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/test_tools/frame_parts.h" #include "quiche/http2/test_tools/frame_parts_collector.h" #include "quiche/http2/test_tools/http2_frame_builder.h" #include "quiche/http2/test_tools/http2_random.h" #include "quiche/http2/test_tools/http2_structures_test_util.h" #include "quiche/http2/test_tools/payload_decoder_base_test_util.h" #include "quiche/http2/test_tools/random_decoder_test_base.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { class AltSvcPayloadDecoderPeer { public: static constexpr Http2FrameType FrameType() { return Http2FrameType::ALTSVC; } static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; } }; namespace { struct Listener : public FramePartsCollector { void OnAltSvcStart(const Http2FrameHeader& header, size_t origin_length, size_t value_length) override { QUICHE_VLOG(1) << "OnAltSvcStart header: " << header << "; origin_length=" << origin_length << "; value_length=" << value_length; StartFrame(header)->OnAltSvcStart(header, origin_length, value_length); } void OnAltSvcOriginData(const char* data, size_t len) override { QUICHE_VLOG(1) << "OnAltSvcOriginData: len=" << len; CurrentFrame()->OnAltSvcOriginData(data, len); } void OnAltSvcValueData(const char* data, size_t len) override { QUICHE_VLOG(1) << "OnAltSvcValueData: len=" << len; CurrentFrame()->OnAltSvcValueData(data, len); } void OnAltSvcEnd() override { QUICHE_VLOG(1) << "OnAltSvcEnd"; EndFrame()->OnAltSvcEnd(); } void OnFrameSizeError(const Http2FrameHeader& header) override { QUICHE_VLOG(1) << "OnFrameSizeError: " << header; FrameError(header)->OnFrameSizeError(header); } }; class AltSvcPayloadDecoderTest : public AbstractPayloadDecoderTest<AltSvcPayloadDecoder, AltSvcPayloadDecoderPeer, Listener> {}; TEST_F(AltSvcPayloadDecoderTest, Truncated) { Http2FrameBuilder fb; fb.Append(Http2AltSvcFields{0xffff}); fb.Append("Too little origin!"); EXPECT_TRUE( VerifyDetectsFrameSizeError(0, fb.buffer(), nullptr)); } class AltSvcPayloadLengthTests : public AltSvcPayloadDecoderTest, public ::testing::WithParamInterface<std::tuple<uint16_t, uint32_t>> { protected: AltSvcPayloadLengthTests() : origin_length_(std::get<0>(GetParam())), value_length_(std::get<1>(GetParam())) { QUICHE_VLOG(1) << "################ origin_length_=" << origin_length_ << " value_length_=" << value_length_ << " ################"; } const uint16_t origin_length_; const uint32_t value_length_; }; INSTANTIATE_TEST_SUITE_P(VariousOriginAndValueLengths, AltSvcPayloadLengthTests, ::testing::Combine(::testing::Values(0, 1, 3, 65535), ::testing::Values(0, 1, 3, 65537))); TEST_P(AltSvcPayloadLengthTests, ValidOriginAndValueLength) { std::string origin = Random().RandString(origin_length_); std::string value = Random().RandString(value_length_); Http2FrameBuilder fb; fb.Append(Http2AltSvcFields{origin_length_}); fb.Append(origin); fb.Append(value); Http2FrameHeader header(fb.size(), Http2FrameType::ALTSVC, RandFlags(), RandStreamId()); set_frame_header(header); FrameParts expected(header); expected.SetAltSvcExpected(origin, value); ASSERT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected)); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/payload_decoders/altsvc_payload_decoder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/payload_decoders/altsvc_payload_decoder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
4f8d5d5e-32e1-4d9c-88f8-05cfbfcd8c32
cpp
google/quiche
headers_payload_decoder
quiche/http2/decoder/payload_decoders/headers_payload_decoder.cc
quiche/http2/decoder/payload_decoders/headers_payload_decoder_test.cc
#include "quiche/http2/decoder/payload_decoders/headers_payload_decoder.h" #include <stddef.h> #include <ostream> #include "absl/base/macros.h" #include "quiche/http2/decoder/decode_buffer.h" #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/http2_structures.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { std::ostream& operator<<(std::ostream& out, HeadersPayloadDecoder::PayloadState v) { switch (v) { case HeadersPayloadDecoder::PayloadState::kReadPadLength: return out << "kReadPadLength"; case HeadersPayloadDecoder::PayloadState::kStartDecodingPriorityFields: return out << "kStartDecodingPriorityFields"; case HeadersPayloadDecoder::PayloadState::kResumeDecodingPriorityFields: return out << "kResumeDecodingPriorityFields"; case HeadersPayloadDecoder::PayloadState::kReadPayload: return out << "kReadPayload"; case HeadersPayloadDecoder::PayloadState::kSkipPadding: return out << "kSkipPadding"; } int unknown = static_cast<int>(v); QUICHE_BUG(http2_bug_189_1) << "Invalid HeadersPayloadDecoder::PayloadState: " << unknown; return out << "HeadersPayloadDecoder::PayloadState(" << unknown << ")"; } DecodeStatus HeadersPayloadDecoder::StartDecodingPayload( FrameDecoderState* state, DecodeBuffer* db) { const Http2FrameHeader& frame_header = state->frame_header(); const uint32_t total_length = frame_header.payload_length; QUICHE_DVLOG(2) << "HeadersPayloadDecoder::StartDecodingPayload: " << frame_header; QUICHE_DCHECK_EQ(Http2FrameType::HEADERS, frame_header.type); QUICHE_DCHECK_LE(db->Remaining(), total_length); QUICHE_DCHECK_EQ( 0, frame_header.flags & ~(Http2FrameFlag::END_STREAM | Http2FrameFlag::END_HEADERS | Http2FrameFlag::PADDED | Http2FrameFlag::PRIORITY)); const auto payload_flags = Http2FrameFlag::PADDED | Http2FrameFlag::PRIORITY; if (!frame_header.HasAnyFlags(payload_flags)) { QUICHE_DVLOG(2) << "StartDecodingPayload !IsPadded && !HasPriority"; if (db->Remaining() == total_length) { QUICHE_DVLOG(2) << "StartDecodingPayload all present"; state->listener()->OnHeadersStart(frame_header); if (total_length > 0) { state->listener()->OnHpackFragment(db->cursor(), total_length); db->AdvanceCursor(total_length); } state->listener()->OnHeadersEnd(); return DecodeStatus::kDecodeDone; } payload_state_ = PayloadState::kReadPayload; } else if (frame_header.IsPadded()) { payload_state_ = PayloadState::kReadPadLength; } else { QUICHE_DCHECK(frame_header.HasPriority()) << frame_header; payload_state_ = PayloadState::kStartDecodingPriorityFields; } state->InitializeRemainders(); state->listener()->OnHeadersStart(frame_header); return ResumeDecodingPayload(state, db); } DecodeStatus HeadersPayloadDecoder::ResumeDecodingPayload( FrameDecoderState* state, DecodeBuffer* db) { QUICHE_DVLOG(2) << "HeadersPayloadDecoder::ResumeDecodingPayload " << "remaining_payload=" << state->remaining_payload() << "; db->Remaining=" << db->Remaining(); const Http2FrameHeader& frame_header = state->frame_header(); QUICHE_DCHECK_EQ(Http2FrameType::HEADERS, frame_header.type); QUICHE_DCHECK_LE(state->remaining_payload_and_padding(), frame_header.payload_length); QUICHE_DCHECK_LE(db->Remaining(), state->remaining_payload_and_padding()); DecodeStatus status; size_t avail; while (true) { QUICHE_DVLOG(2) << "HeadersPayloadDecoder::ResumeDecodingPayload payload_state_=" << payload_state_; switch (payload_state_) { case PayloadState::kReadPadLength: status = state->ReadPadLength(db, true); if (status != DecodeStatus::kDecodeDone) { return status; } if (!frame_header.HasPriority()) { payload_state_ = PayloadState::kReadPayload; continue; } ABSL_FALLTHROUGH_INTENDED; case PayloadState::kStartDecodingPriorityFields: status = state->StartDecodingStructureInPayload(&priority_fields_, db); if (status != DecodeStatus::kDecodeDone) { payload_state_ = PayloadState::kResumeDecodingPriorityFields; return status; } state->listener()->OnHeadersPriority(priority_fields_); ABSL_FALLTHROUGH_INTENDED; case PayloadState::kReadPayload: avail = state->AvailablePayload(db); if (avail > 0) { state->listener()->OnHpackFragment(db->cursor(), avail); db->AdvanceCursor(avail); state->ConsumePayload(avail); } if (state->remaining_payload() > 0) { payload_state_ = PayloadState::kReadPayload; return DecodeStatus::kDecodeInProgress; } ABSL_FALLTHROUGH_INTENDED; case PayloadState::kSkipPadding: if (state->SkipPadding(db)) { state->listener()->OnHeadersEnd(); return DecodeStatus::kDecodeDone; } payload_state_ = PayloadState::kSkipPadding; return DecodeStatus::kDecodeInProgress; case PayloadState::kResumeDecodingPriorityFields: status = state->ResumeDecodingStructureInPayload(&priority_fields_, db); if (status != DecodeStatus::kDecodeDone) { return status; } state->listener()->OnHeadersPriority(priority_fields_); payload_state_ = PayloadState::kReadPayload; continue; } QUICHE_BUG(http2_bug_189_2) << "PayloadState: " << payload_state_; } } }
#include "quiche/http2/decoder/payload_decoders/headers_payload_decoder.h" #include <stddef.h> #include <string> #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/test_tools/frame_parts.h" #include "quiche/http2/test_tools/frame_parts_collector.h" #include "quiche/http2/test_tools/http2_frame_builder.h" #include "quiche/http2/test_tools/http2_random.h" #include "quiche/http2/test_tools/http2_structures_test_util.h" #include "quiche/http2/test_tools/payload_decoder_base_test_util.h" #include "quiche/http2/test_tools/random_decoder_test_base.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { class HeadersPayloadDecoderPeer { public: static constexpr Http2FrameType FrameType() { return Http2FrameType::HEADERS; } static constexpr uint8_t FlagsAffectingPayloadDecoding() { return Http2FrameFlag::PADDED | Http2FrameFlag::PRIORITY; } }; namespace { struct Listener : public FramePartsCollector { void OnHeadersStart(const Http2FrameHeader& header) override { QUICHE_VLOG(1) << "OnHeadersStart: " << header; StartFrame(header)->OnHeadersStart(header); } void OnHeadersPriority(const Http2PriorityFields& priority) override { QUICHE_VLOG(1) << "OnHeadersPriority: " << priority; CurrentFrame()->OnHeadersPriority(priority); } void OnHpackFragment(const char* data, size_t len) override { QUICHE_VLOG(1) << "OnHpackFragment: len=" << len; CurrentFrame()->OnHpackFragment(data, len); } void OnHeadersEnd() override { QUICHE_VLOG(1) << "OnHeadersEnd"; EndFrame()->OnHeadersEnd(); } void OnPadLength(size_t pad_length) override { QUICHE_VLOG(1) << "OnPadLength: " << pad_length; CurrentFrame()->OnPadLength(pad_length); } void OnPadding(const char* padding, size_t skipped_length) override { QUICHE_VLOG(1) << "OnPadding: " << skipped_length; CurrentFrame()->OnPadding(padding, skipped_length); } void OnPaddingTooLong(const Http2FrameHeader& header, size_t missing_length) override { QUICHE_VLOG(1) << "OnPaddingTooLong: " << header << "; missing_length: " << missing_length; FrameError(header)->OnPaddingTooLong(header, missing_length); } void OnFrameSizeError(const Http2FrameHeader& header) override { QUICHE_VLOG(1) << "OnFrameSizeError: " << header; FrameError(header)->OnFrameSizeError(header); } }; class HeadersPayloadDecoderTest : public AbstractPaddablePayloadDecoderTest< HeadersPayloadDecoder, HeadersPayloadDecoderPeer, Listener> {}; INSTANTIATE_TEST_SUITE_P(VariousPadLengths, HeadersPayloadDecoderTest, ::testing::Values(0, 1, 2, 3, 4, 254, 255, 256)); TEST_P(HeadersPayloadDecoderTest, VariousHpackPayloadSizes) { for (size_t hpack_size : {0, 1, 2, 3, 255, 256, 1024}) { QUICHE_LOG(INFO) << "########### hpack_size = " << hpack_size << " ###########"; Http2PriorityFields priority(RandStreamId(), 1 + Random().Rand8(), Random().OneIn(2)); for (bool has_priority : {false, true}) { Reset(); ASSERT_EQ(IsPadded() ? 1u : 0u, frame_builder_.size()); uint8_t flags = RandFlags(); if (has_priority) { flags |= Http2FrameFlag::PRIORITY; frame_builder_.Append(priority); } std::string hpack_payload = Random().RandString(hpack_size); frame_builder_.Append(hpack_payload); MaybeAppendTrailingPadding(); Http2FrameHeader frame_header(frame_builder_.size(), Http2FrameType::HEADERS, flags, RandStreamId()); set_frame_header(frame_header); ScrubFlagsOfHeader(&frame_header); FrameParts expected(frame_header, hpack_payload, total_pad_length_); if (has_priority) { expected.SetOptPriority(priority); } EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(frame_builder_.buffer(), expected)); } } } TEST_P(HeadersPayloadDecoderTest, Truncated) { auto approve_size = [](size_t size) { return size != Http2PriorityFields::EncodedSize(); }; Http2FrameBuilder fb; fb.Append(Http2PriorityFields(RandStreamId(), 1 + Random().Rand8(), Random().OneIn(2))); EXPECT_TRUE(VerifyDetectsMultipleFrameSizeErrors( Http2FrameFlag::PRIORITY, fb.buffer(), approve_size, total_pad_length_)); } TEST_P(HeadersPayloadDecoderTest, PaddingTooLong) { EXPECT_TRUE(VerifyDetectsPaddingTooLong()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/payload_decoders/headers_payload_decoder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/payload_decoders/headers_payload_decoder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
b6914a15-6630-4a43-882b-2ed081ace8fd
cpp
google/quiche
window_update_payload_decoder
quiche/http2/decoder/payload_decoders/window_update_payload_decoder.cc
quiche/http2/decoder/payload_decoders/window_update_payload_decoder_test.cc
#include "quiche/http2/decoder/payload_decoders/window_update_payload_decoder.h" #include "quiche/http2/decoder/decode_buffer.h" #include "quiche/http2/decoder/decode_http2_structures.h" #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/http2_structures.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { DecodeStatus WindowUpdatePayloadDecoder::StartDecodingPayload( FrameDecoderState* state, DecodeBuffer* db) { const Http2FrameHeader& frame_header = state->frame_header(); const uint32_t total_length = frame_header.payload_length; QUICHE_DVLOG(2) << "WindowUpdatePayloadDecoder::StartDecodingPayload: " << frame_header; QUICHE_DCHECK_EQ(Http2FrameType::WINDOW_UPDATE, frame_header.type); QUICHE_DCHECK_LE(db->Remaining(), total_length); QUICHE_DCHECK_EQ(0, frame_header.flags); if (db->Remaining() == Http2WindowUpdateFields::EncodedSize() && total_length == Http2WindowUpdateFields::EncodedSize()) { DoDecode(&window_update_fields_, db); state->listener()->OnWindowUpdate( frame_header, window_update_fields_.window_size_increment); return DecodeStatus::kDecodeDone; } state->InitializeRemainders(); return HandleStatus(state, state->StartDecodingStructureInPayload( &window_update_fields_, db)); } DecodeStatus WindowUpdatePayloadDecoder::ResumeDecodingPayload( FrameDecoderState* state, DecodeBuffer* db) { QUICHE_DVLOG(2) << "ResumeDecodingPayload: remaining_payload=" << state->remaining_payload() << "; db->Remaining=" << db->Remaining(); QUICHE_DCHECK_EQ(Http2FrameType::WINDOW_UPDATE, state->frame_header().type); QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length); return HandleStatus(state, state->ResumeDecodingStructureInPayload( &window_update_fields_, db)); } DecodeStatus WindowUpdatePayloadDecoder::HandleStatus(FrameDecoderState* state, DecodeStatus status) { QUICHE_DVLOG(2) << "HandleStatus: status=" << status << "; remaining_payload=" << state->remaining_payload(); if (status == DecodeStatus::kDecodeDone) { if (state->remaining_payload() == 0) { state->listener()->OnWindowUpdate( state->frame_header(), window_update_fields_.window_size_increment); return DecodeStatus::kDecodeDone; } return state->ReportFrameSizeError(); } QUICHE_DCHECK( (status == DecodeStatus::kDecodeInProgress && state->remaining_payload() > 0) || (status == DecodeStatus::kDecodeError && state->remaining_payload() == 0)) << "\n status=" << status << "; remaining_payload=" << state->remaining_payload(); return status; } }
#include "quiche/http2/decoder/payload_decoders/window_update_payload_decoder.h" #include <stddef.h> #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/test_tools/frame_parts.h" #include "quiche/http2/test_tools/frame_parts_collector.h" #include "quiche/http2/test_tools/http2_frame_builder.h" #include "quiche/http2/test_tools/http2_random.h" #include "quiche/http2/test_tools/http2_structures_test_util.h" #include "quiche/http2/test_tools/payload_decoder_base_test_util.h" #include "quiche/http2/test_tools/random_decoder_test_base.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { class WindowUpdatePayloadDecoderPeer { public: static constexpr Http2FrameType FrameType() { return Http2FrameType::WINDOW_UPDATE; } static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; } }; namespace { struct Listener : public FramePartsCollector { void OnWindowUpdate(const Http2FrameHeader& header, uint32_t window_size_increment) override { QUICHE_VLOG(1) << "OnWindowUpdate: " << header << "; window_size_increment=" << window_size_increment; EXPECT_EQ(Http2FrameType::WINDOW_UPDATE, header.type); StartAndEndFrame(header)->OnWindowUpdate(header, window_size_increment); } void OnFrameSizeError(const Http2FrameHeader& header) override { QUICHE_VLOG(1) << "OnFrameSizeError: " << header; FrameError(header)->OnFrameSizeError(header); } }; class WindowUpdatePayloadDecoderTest : public AbstractPayloadDecoderTest<WindowUpdatePayloadDecoder, WindowUpdatePayloadDecoderPeer, Listener> { protected: Http2WindowUpdateFields RandWindowUpdateFields() { Http2WindowUpdateFields fields; test::Randomize(&fields, RandomPtr()); QUICHE_VLOG(3) << "RandWindowUpdateFields: " << fields; return fields; } }; TEST_F(WindowUpdatePayloadDecoderTest, WrongSize) { auto approve_size = [](size_t size) { return size != Http2WindowUpdateFields::EncodedSize(); }; Http2FrameBuilder fb; fb.Append(RandWindowUpdateFields()); fb.Append(RandWindowUpdateFields()); fb.Append(RandWindowUpdateFields()); EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size)); } TEST_F(WindowUpdatePayloadDecoderTest, VariousPayloads) { for (int n = 0; n < 100; ++n) { uint32_t stream_id = n == 0 ? 0 : RandStreamId(); Http2WindowUpdateFields fields = RandWindowUpdateFields(); Http2FrameBuilder fb; fb.Append(fields); Http2FrameHeader header(fb.size(), Http2FrameType::WINDOW_UPDATE, RandFlags(), stream_id); set_frame_header(header); FrameParts expected(header); expected.SetOptWindowUpdateIncrement(fields.window_size_increment); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected)); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/payload_decoders/window_update_payload_decoder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/payload_decoders/window_update_payload_decoder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
d2386078-ce90-43a2-9dde-276049b32c97
cpp
google/quiche
push_promise_payload_decoder
quiche/http2/decoder/payload_decoders/push_promise_payload_decoder.cc
quiche/http2/decoder/payload_decoders/push_promise_payload_decoder_test.cc
#include "quiche/http2/decoder/payload_decoders/push_promise_payload_decoder.h" #include <stddef.h> #include <ostream> #include "absl/base/macros.h" #include "quiche/http2/decoder/decode_buffer.h" #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/http2_structures.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { std::ostream& operator<<(std::ostream& out, PushPromisePayloadDecoder::PayloadState v) { switch (v) { case PushPromisePayloadDecoder::PayloadState::kReadPadLength: return out << "kReadPadLength"; case PushPromisePayloadDecoder::PayloadState:: kStartDecodingPushPromiseFields: return out << "kStartDecodingPushPromiseFields"; case PushPromisePayloadDecoder::PayloadState::kReadPayload: return out << "kReadPayload"; case PushPromisePayloadDecoder::PayloadState::kSkipPadding: return out << "kSkipPadding"; case PushPromisePayloadDecoder::PayloadState:: kResumeDecodingPushPromiseFields: return out << "kResumeDecodingPushPromiseFields"; } return out << static_cast<int>(v); } DecodeStatus PushPromisePayloadDecoder::StartDecodingPayload( FrameDecoderState* state, DecodeBuffer* db) { const Http2FrameHeader& frame_header = state->frame_header(); const uint32_t total_length = frame_header.payload_length; QUICHE_DVLOG(2) << "PushPromisePayloadDecoder::StartDecodingPayload: " << frame_header; QUICHE_DCHECK_EQ(Http2FrameType::PUSH_PROMISE, frame_header.type); QUICHE_DCHECK_LE(db->Remaining(), total_length); QUICHE_DCHECK_EQ(0, frame_header.flags & ~(Http2FrameFlag::END_HEADERS | Http2FrameFlag::PADDED)); if (!frame_header.IsPadded()) { payload_state_ = PayloadState::kStartDecodingPushPromiseFields; } else { payload_state_ = PayloadState::kReadPadLength; } state->InitializeRemainders(); return ResumeDecodingPayload(state, db); } DecodeStatus PushPromisePayloadDecoder::ResumeDecodingPayload( FrameDecoderState* state, DecodeBuffer* db) { QUICHE_DVLOG(2) << "UnknownPayloadDecoder::ResumeDecodingPayload" << " remaining_payload=" << state->remaining_payload() << " db->Remaining=" << db->Remaining(); const Http2FrameHeader& frame_header = state->frame_header(); QUICHE_DCHECK_EQ(Http2FrameType::PUSH_PROMISE, frame_header.type); QUICHE_DCHECK_LE(state->remaining_payload(), frame_header.payload_length); QUICHE_DCHECK_LE(db->Remaining(), frame_header.payload_length); DecodeStatus status; while (true) { QUICHE_DVLOG(2) << "PushPromisePayloadDecoder::ResumeDecodingPayload payload_state_=" << payload_state_; switch (payload_state_) { case PayloadState::kReadPadLength: QUICHE_DCHECK_EQ(state->remaining_payload(), frame_header.payload_length); status = state->ReadPadLength(db, false); if (status != DecodeStatus::kDecodeDone) { payload_state_ = PayloadState::kReadPadLength; return status; } ABSL_FALLTHROUGH_INTENDED; case PayloadState::kStartDecodingPushPromiseFields: status = state->StartDecodingStructureInPayload(&push_promise_fields_, db); if (status != DecodeStatus::kDecodeDone) { payload_state_ = PayloadState::kResumeDecodingPushPromiseFields; return status; } ReportPushPromise(state); ABSL_FALLTHROUGH_INTENDED; case PayloadState::kReadPayload: QUICHE_DCHECK_LT(state->remaining_payload(), frame_header.payload_length); QUICHE_DCHECK_LE(state->remaining_payload(), frame_header.payload_length - Http2PushPromiseFields::EncodedSize()); QUICHE_DCHECK_LE( state->remaining_payload(), frame_header.payload_length - Http2PushPromiseFields::EncodedSize() - (frame_header.IsPadded() ? (1 + state->remaining_padding()) : 0)); { size_t avail = state->AvailablePayload(db); state->listener()->OnHpackFragment(db->cursor(), avail); db->AdvanceCursor(avail); state->ConsumePayload(avail); } if (state->remaining_payload() > 0) { payload_state_ = PayloadState::kReadPayload; return DecodeStatus::kDecodeInProgress; } ABSL_FALLTHROUGH_INTENDED; case PayloadState::kSkipPadding: if (state->SkipPadding(db)) { state->listener()->OnPushPromiseEnd(); return DecodeStatus::kDecodeDone; } payload_state_ = PayloadState::kSkipPadding; return DecodeStatus::kDecodeInProgress; case PayloadState::kResumeDecodingPushPromiseFields: status = state->ResumeDecodingStructureInPayload(&push_promise_fields_, db); if (status == DecodeStatus::kDecodeDone) { ReportPushPromise(state); payload_state_ = PayloadState::kReadPayload; continue; } payload_state_ = PayloadState::kResumeDecodingPushPromiseFields; return status; } QUICHE_BUG(http2_bug_183_1) << "PayloadState: " << payload_state_; } } void PushPromisePayloadDecoder::ReportPushPromise(FrameDecoderState* state) { const Http2FrameHeader& frame_header = state->frame_header(); if (frame_header.IsPadded()) { state->listener()->OnPushPromiseStart(frame_header, push_promise_fields_, 1 + state->remaining_padding()); } else { state->listener()->OnPushPromiseStart(frame_header, push_promise_fields_, 0); } } }
#include "quiche/http2/decoder/payload_decoders/push_promise_payload_decoder.h" #include <stddef.h> #include <string> #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/test_tools/frame_parts.h" #include "quiche/http2/test_tools/frame_parts_collector.h" #include "quiche/http2/test_tools/http2_frame_builder.h" #include "quiche/http2/test_tools/http2_random.h" #include "quiche/http2/test_tools/http2_structures_test_util.h" #include "quiche/http2/test_tools/payload_decoder_base_test_util.h" #include "quiche/http2/test_tools/random_decoder_test_base.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { class PushPromisePayloadDecoderPeer { public: static constexpr Http2FrameType FrameType() { return Http2FrameType::PUSH_PROMISE; } static constexpr uint8_t FlagsAffectingPayloadDecoding() { return Http2FrameFlag::PADDED; } }; namespace { struct Listener : public FramePartsCollector { void OnPushPromiseStart(const Http2FrameHeader& header, const Http2PushPromiseFields& promise, size_t total_padding_length) override { QUICHE_VLOG(1) << "OnPushPromiseStart header: " << header << " promise: " << promise << " total_padding_length: " << total_padding_length; EXPECT_EQ(Http2FrameType::PUSH_PROMISE, header.type); StartFrame(header)->OnPushPromiseStart(header, promise, total_padding_length); } void OnHpackFragment(const char* data, size_t len) override { QUICHE_VLOG(1) << "OnHpackFragment: len=" << len; CurrentFrame()->OnHpackFragment(data, len); } void OnPushPromiseEnd() override { QUICHE_VLOG(1) << "OnPushPromiseEnd"; EndFrame()->OnPushPromiseEnd(); } void OnPadding(const char* padding, size_t skipped_length) override { QUICHE_VLOG(1) << "OnPadding: " << skipped_length; CurrentFrame()->OnPadding(padding, skipped_length); } void OnPaddingTooLong(const Http2FrameHeader& header, size_t missing_length) override { QUICHE_VLOG(1) << "OnPaddingTooLong: " << header << "; missing_length: " << missing_length; FrameError(header)->OnPaddingTooLong(header, missing_length); } void OnFrameSizeError(const Http2FrameHeader& header) override { QUICHE_VLOG(1) << "OnFrameSizeError: " << header; FrameError(header)->OnFrameSizeError(header); } }; class PushPromisePayloadDecoderTest : public AbstractPaddablePayloadDecoderTest< PushPromisePayloadDecoder, PushPromisePayloadDecoderPeer, Listener> { }; INSTANTIATE_TEST_SUITE_P(VariousPadLengths, PushPromisePayloadDecoderTest, ::testing::Values(0, 1, 2, 3, 4, 254, 255, 256)); TEST_P(PushPromisePayloadDecoderTest, VariousHpackPayloadSizes) { for (size_t hpack_size : {0, 1, 2, 3, 255, 256, 1024}) { QUICHE_LOG(INFO) << "########### hpack_size = " << hpack_size << " ###########"; Reset(); std::string hpack_payload = Random().RandString(hpack_size); Http2PushPromiseFields push_promise{RandStreamId()}; frame_builder_.Append(push_promise); frame_builder_.Append(hpack_payload); MaybeAppendTrailingPadding(); Http2FrameHeader frame_header(frame_builder_.size(), Http2FrameType::PUSH_PROMISE, RandFlags(), RandStreamId()); set_frame_header(frame_header); FrameParts expected(frame_header, hpack_payload, total_pad_length_); expected.SetOptPushPromise(push_promise); EXPECT_TRUE( DecodePayloadAndValidateSeveralWays(frame_builder_.buffer(), expected)); } } TEST_P(PushPromisePayloadDecoderTest, Truncated) { auto approve_size = [](size_t size) { return size != Http2PushPromiseFields::EncodedSize(); }; Http2PushPromiseFields push_promise{RandStreamId()}; Http2FrameBuilder fb; fb.Append(push_promise); EXPECT_TRUE(VerifyDetectsMultipleFrameSizeErrors(0, fb.buffer(), approve_size, total_pad_length_)); } TEST_P(PushPromisePayloadDecoderTest, PaddingTooLong) { EXPECT_TRUE(VerifyDetectsPaddingTooLong()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/payload_decoders/push_promise_payload_decoder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/payload_decoders/push_promise_payload_decoder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
2a27a67d-619c-4efb-a55a-b7f6ba66a70d
cpp
google/quiche
ping_payload_decoder
quiche/http2/decoder/payload_decoders/ping_payload_decoder.cc
quiche/http2/decoder/payload_decoders/ping_payload_decoder_test.cc
#include "quiche/http2/decoder/payload_decoders/ping_payload_decoder.h" #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { namespace { constexpr auto kOpaqueSize = Http2PingFields::EncodedSize(); } DecodeStatus PingPayloadDecoder::StartDecodingPayload(FrameDecoderState* state, DecodeBuffer* db) { const Http2FrameHeader& frame_header = state->frame_header(); const uint32_t total_length = frame_header.payload_length; QUICHE_DVLOG(2) << "PingPayloadDecoder::StartDecodingPayload: " << frame_header; QUICHE_DCHECK_EQ(Http2FrameType::PING, frame_header.type); QUICHE_DCHECK_LE(db->Remaining(), total_length); QUICHE_DCHECK_EQ(0, frame_header.flags & ~(Http2FrameFlag::ACK)); if (db->Remaining() == kOpaqueSize && total_length == kOpaqueSize) { static_assert(sizeof(Http2PingFields) == kOpaqueSize, "If not, then can't enter this block!"); auto* ping = reinterpret_cast<const Http2PingFields*>(db->cursor()); if (frame_header.IsAck()) { state->listener()->OnPingAck(frame_header, *ping); } else { state->listener()->OnPing(frame_header, *ping); } db->AdvanceCursor(kOpaqueSize); return DecodeStatus::kDecodeDone; } state->InitializeRemainders(); return HandleStatus( state, state->StartDecodingStructureInPayload(&ping_fields_, db)); } DecodeStatus PingPayloadDecoder::ResumeDecodingPayload(FrameDecoderState* state, DecodeBuffer* db) { QUICHE_DVLOG(2) << "ResumeDecodingPayload: remaining_payload=" << state->remaining_payload(); QUICHE_DCHECK_EQ(Http2FrameType::PING, state->frame_header().type); QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length); return HandleStatus( state, state->ResumeDecodingStructureInPayload(&ping_fields_, db)); } DecodeStatus PingPayloadDecoder::HandleStatus(FrameDecoderState* state, DecodeStatus status) { QUICHE_DVLOG(2) << "HandleStatus: status=" << status << "; remaining_payload=" << state->remaining_payload(); if (status == DecodeStatus::kDecodeDone) { if (state->remaining_payload() == 0) { const Http2FrameHeader& frame_header = state->frame_header(); if (frame_header.IsAck()) { state->listener()->OnPingAck(frame_header, ping_fields_); } else { state->listener()->OnPing(frame_header, ping_fields_); } return DecodeStatus::kDecodeDone; } return state->ReportFrameSizeError(); } QUICHE_DCHECK( (status == DecodeStatus::kDecodeInProgress && state->remaining_payload() > 0) || (status == DecodeStatus::kDecodeError && state->remaining_payload() == 0)) << "\n status=" << status << "; remaining_payload=" << state->remaining_payload(); return status; } }
#include "quiche/http2/decoder/payload_decoders/ping_payload_decoder.h" #include <stddef.h> #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/test_tools/frame_parts.h" #include "quiche/http2/test_tools/frame_parts_collector.h" #include "quiche/http2/test_tools/http2_frame_builder.h" #include "quiche/http2/test_tools/http2_random.h" #include "quiche/http2/test_tools/http2_structures_test_util.h" #include "quiche/http2/test_tools/payload_decoder_base_test_util.h" #include "quiche/http2/test_tools/random_decoder_test_base.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { class PingPayloadDecoderPeer { public: static constexpr Http2FrameType FrameType() { return Http2FrameType::PING; } static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; } }; namespace { struct Listener : public FramePartsCollector { void OnPing(const Http2FrameHeader& header, const Http2PingFields& ping) override { QUICHE_VLOG(1) << "OnPing: " << header << "; " << ping; StartAndEndFrame(header)->OnPing(header, ping); } void OnPingAck(const Http2FrameHeader& header, const Http2PingFields& ping) override { QUICHE_VLOG(1) << "OnPingAck: " << header << "; " << ping; StartAndEndFrame(header)->OnPingAck(header, ping); } void OnFrameSizeError(const Http2FrameHeader& header) override { QUICHE_VLOG(1) << "OnFrameSizeError: " << header; FrameError(header)->OnFrameSizeError(header); } }; class PingPayloadDecoderTest : public AbstractPayloadDecoderTest<PingPayloadDecoder, PingPayloadDecoderPeer, Listener> { protected: Http2PingFields RandPingFields() { Http2PingFields fields; test::Randomize(&fields, RandomPtr()); return fields; } }; TEST_F(PingPayloadDecoderTest, WrongSize) { auto approve_size = [](size_t size) { return size != Http2PingFields::EncodedSize(); }; Http2FrameBuilder fb; fb.Append(RandPingFields()); fb.Append(RandPingFields()); fb.Append(RandPingFields()); EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size)); } TEST_F(PingPayloadDecoderTest, Ping) { for (int n = 0; n < 100; ++n) { Http2PingFields fields = RandPingFields(); Http2FrameBuilder fb; fb.Append(fields); Http2FrameHeader header(fb.size(), Http2FrameType::PING, RandFlags() & ~Http2FrameFlag::ACK, RandStreamId()); set_frame_header(header); FrameParts expected(header); expected.SetOptPing(fields); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected)); } } TEST_F(PingPayloadDecoderTest, PingAck) { for (int n = 0; n < 100; ++n) { Http2PingFields fields; Randomize(&fields, RandomPtr()); Http2FrameBuilder fb; fb.Append(fields); Http2FrameHeader header(fb.size(), Http2FrameType::PING, RandFlags() | Http2FrameFlag::ACK, RandStreamId()); set_frame_header(header); FrameParts expected(header); expected.SetOptPing(fields); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected)); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/payload_decoders/ping_payload_decoder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/payload_decoders/ping_payload_decoder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
32ba9709-ceb9-419a-9415-2ed32cd72d6a
cpp
google/quiche
rst_stream_payload_decoder
quiche/http2/decoder/payload_decoders/rst_stream_payload_decoder.cc
quiche/http2/decoder/payload_decoders/rst_stream_payload_decoder_test.cc
#include "quiche/http2/decoder/payload_decoders/rst_stream_payload_decoder.h" #include "quiche/http2/decoder/decode_buffer.h" #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/http2_structures.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { DecodeStatus RstStreamPayloadDecoder::StartDecodingPayload( FrameDecoderState* state, DecodeBuffer* db) { QUICHE_DVLOG(2) << "RstStreamPayloadDecoder::StartDecodingPayload: " << state->frame_header(); QUICHE_DCHECK_EQ(Http2FrameType::RST_STREAM, state->frame_header().type); QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length); QUICHE_DCHECK_EQ(0, state->frame_header().flags); state->InitializeRemainders(); return HandleStatus( state, state->StartDecodingStructureInPayload(&rst_stream_fields_, db)); } DecodeStatus RstStreamPayloadDecoder::ResumeDecodingPayload( FrameDecoderState* state, DecodeBuffer* db) { QUICHE_DVLOG(2) << "RstStreamPayloadDecoder::ResumeDecodingPayload" << " remaining_payload=" << state->remaining_payload() << " db->Remaining=" << db->Remaining(); QUICHE_DCHECK_EQ(Http2FrameType::RST_STREAM, state->frame_header().type); QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length); return HandleStatus( state, state->ResumeDecodingStructureInPayload(&rst_stream_fields_, db)); } DecodeStatus RstStreamPayloadDecoder::HandleStatus(FrameDecoderState* state, DecodeStatus status) { QUICHE_DVLOG(2) << "HandleStatus: status=" << status << "; remaining_payload=" << state->remaining_payload(); if (status == DecodeStatus::kDecodeDone) { if (state->remaining_payload() == 0) { state->listener()->OnRstStream(state->frame_header(), rst_stream_fields_.error_code); return DecodeStatus::kDecodeDone; } return state->ReportFrameSizeError(); } QUICHE_DCHECK( (status == DecodeStatus::kDecodeInProgress && state->remaining_payload() > 0) || (status == DecodeStatus::kDecodeError && state->remaining_payload() == 0)) << "\n status=" << status << "; remaining_payload=" << state->remaining_payload(); return status; } }
#include "quiche/http2/decoder/payload_decoders/rst_stream_payload_decoder.h" #include <stddef.h> #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/test_tools/frame_parts.h" #include "quiche/http2/test_tools/frame_parts_collector.h" #include "quiche/http2/test_tools/http2_constants_test_util.h" #include "quiche/http2/test_tools/http2_frame_builder.h" #include "quiche/http2/test_tools/http2_random.h" #include "quiche/http2/test_tools/http2_structures_test_util.h" #include "quiche/http2/test_tools/payload_decoder_base_test_util.h" #include "quiche/http2/test_tools/random_decoder_test_base.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { class RstStreamPayloadDecoderPeer { public: static constexpr Http2FrameType FrameType() { return Http2FrameType::RST_STREAM; } static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; } }; namespace { struct Listener : public FramePartsCollector { void OnRstStream(const Http2FrameHeader& header, Http2ErrorCode error_code) override { QUICHE_VLOG(1) << "OnRstStream: " << header << "; error_code=" << error_code; StartAndEndFrame(header)->OnRstStream(header, error_code); } void OnFrameSizeError(const Http2FrameHeader& header) override { QUICHE_VLOG(1) << "OnFrameSizeError: " << header; FrameError(header)->OnFrameSizeError(header); } }; class RstStreamPayloadDecoderTest : public AbstractPayloadDecoderTest<RstStreamPayloadDecoder, RstStreamPayloadDecoderPeer, Listener> { protected: Http2RstStreamFields RandRstStreamFields() { Http2RstStreamFields fields; test::Randomize(&fields, RandomPtr()); return fields; } }; TEST_F(RstStreamPayloadDecoderTest, WrongSize) { auto approve_size = [](size_t size) { return size != Http2RstStreamFields::EncodedSize(); }; Http2FrameBuilder fb; fb.Append(RandRstStreamFields()); fb.Append(RandRstStreamFields()); fb.Append(RandRstStreamFields()); EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size)); } TEST_F(RstStreamPayloadDecoderTest, AllErrors) { for (auto error_code : AllHttp2ErrorCodes()) { Http2RstStreamFields fields{error_code}; Http2FrameBuilder fb; fb.Append(fields); Http2FrameHeader header(fb.size(), Http2FrameType::RST_STREAM, RandFlags(), RandStreamId()); set_frame_header(header); FrameParts expected(header); expected.SetOptRstStreamErrorCode(error_code); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected)); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/payload_decoders/rst_stream_payload_decoder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/payload_decoders/rst_stream_payload_decoder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
c7ec514c-d713-4b48-a241-615bd39daf6d
cpp
google/quiche
continuation_payload_decoder
quiche/http2/decoder/payload_decoders/continuation_payload_decoder.cc
quiche/http2/decoder/payload_decoders/continuation_payload_decoder_test.cc
#include "quiche/http2/decoder/payload_decoders/continuation_payload_decoder.h" #include <stddef.h> #include "quiche/http2/decoder/decode_buffer.h" #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/http2_structures.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { DecodeStatus ContinuationPayloadDecoder::StartDecodingPayload( FrameDecoderState* state, DecodeBuffer* db) { const Http2FrameHeader& frame_header = state->frame_header(); const uint32_t total_length = frame_header.payload_length; QUICHE_DVLOG(2) << "ContinuationPayloadDecoder::StartDecodingPayload: " << frame_header; QUICHE_DCHECK_EQ(Http2FrameType::CONTINUATION, frame_header.type); QUICHE_DCHECK_LE(db->Remaining(), total_length); QUICHE_DCHECK_EQ(0, frame_header.flags & ~(Http2FrameFlag::END_HEADERS)); state->InitializeRemainders(); state->listener()->OnContinuationStart(frame_header); return ResumeDecodingPayload(state, db); } DecodeStatus ContinuationPayloadDecoder::ResumeDecodingPayload( FrameDecoderState* state, DecodeBuffer* db) { QUICHE_DVLOG(2) << "ContinuationPayloadDecoder::ResumeDecodingPayload" << " remaining_payload=" << state->remaining_payload() << " db->Remaining=" << db->Remaining(); QUICHE_DCHECK_EQ(Http2FrameType::CONTINUATION, state->frame_header().type); QUICHE_DCHECK_LE(state->remaining_payload(), state->frame_header().payload_length); QUICHE_DCHECK_LE(db->Remaining(), state->remaining_payload()); size_t avail = db->Remaining(); QUICHE_DCHECK_LE(avail, state->remaining_payload()); if (avail > 0) { state->listener()->OnHpackFragment(db->cursor(), avail); db->AdvanceCursor(avail); state->ConsumePayload(avail); } if (state->remaining_payload() == 0) { state->listener()->OnContinuationEnd(); return DecodeStatus::kDecodeDone; } return DecodeStatus::kDecodeInProgress; } }
#include "quiche/http2/decoder/payload_decoders/continuation_payload_decoder.h" #include <stddef.h> #include <string> #include <type_traits> #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/http2_structures.h" #include "quiche/http2/test_tools/frame_parts.h" #include "quiche/http2/test_tools/frame_parts_collector.h" #include "quiche/http2/test_tools/payload_decoder_base_test_util.h" #include "quiche/http2/test_tools/random_decoder_test_base.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { class ContinuationPayloadDecoderPeer { public: static constexpr Http2FrameType FrameType() { return Http2FrameType::CONTINUATION; } static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; } }; namespace { struct Listener : public FramePartsCollector { void OnContinuationStart(const Http2FrameHeader& header) override { QUICHE_VLOG(1) << "OnContinuationStart: " << header; StartFrame(header)->OnContinuationStart(header); } void OnHpackFragment(const char* data, size_t len) override { QUICHE_VLOG(1) << "OnHpackFragment: len=" << len; CurrentFrame()->OnHpackFragment(data, len); } void OnContinuationEnd() override { QUICHE_VLOG(1) << "OnContinuationEnd"; EndFrame()->OnContinuationEnd(); } }; class ContinuationPayloadDecoderTest : public AbstractPayloadDecoderTest< ContinuationPayloadDecoder, ContinuationPayloadDecoderPeer, Listener>, public ::testing::WithParamInterface<uint32_t> { protected: ContinuationPayloadDecoderTest() : length_(GetParam()) { QUICHE_VLOG(1) << "################ length_=" << length_ << " ################"; } const uint32_t length_; }; INSTANTIATE_TEST_SUITE_P(VariousLengths, ContinuationPayloadDecoderTest, ::testing::Values(0, 1, 2, 3, 4, 5, 6)); TEST_P(ContinuationPayloadDecoderTest, ValidLength) { std::string hpack_payload = Random().RandString(length_); Http2FrameHeader frame_header(length_, Http2FrameType::CONTINUATION, RandFlags(), RandStreamId()); set_frame_header(frame_header); FrameParts expected(frame_header, hpack_payload); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(hpack_payload, expected)); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/payload_decoders/continuation_payload_decoder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/payload_decoders/continuation_payload_decoder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
ca03b724-c668-4b97-a31c-86e5d1ef4ee6
cpp
google/quiche
settings_payload_decoder
quiche/http2/decoder/payload_decoders/settings_payload_decoder.cc
quiche/http2/decoder/payload_decoders/settings_payload_decoder_test.cc
#include "quiche/http2/decoder/payload_decoders/settings_payload_decoder.h" #include "quiche/http2/decoder/decode_buffer.h" #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/http2_structures.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { DecodeStatus SettingsPayloadDecoder::StartDecodingPayload( FrameDecoderState* state, DecodeBuffer* db) { const Http2FrameHeader& frame_header = state->frame_header(); const uint32_t total_length = frame_header.payload_length; QUICHE_DVLOG(2) << "SettingsPayloadDecoder::StartDecodingPayload: " << frame_header; QUICHE_DCHECK_EQ(Http2FrameType::SETTINGS, frame_header.type); QUICHE_DCHECK_LE(db->Remaining(), total_length); QUICHE_DCHECK_EQ(0, frame_header.flags & ~(Http2FrameFlag::ACK)); if (frame_header.IsAck()) { if (total_length == 0) { state->listener()->OnSettingsAck(frame_header); return DecodeStatus::kDecodeDone; } else { state->InitializeRemainders(); return state->ReportFrameSizeError(); } } else { state->InitializeRemainders(); state->listener()->OnSettingsStart(frame_header); return StartDecodingSettings(state, db); } } DecodeStatus SettingsPayloadDecoder::ResumeDecodingPayload( FrameDecoderState* state, DecodeBuffer* db) { QUICHE_DVLOG(2) << "SettingsPayloadDecoder::ResumeDecodingPayload" << " remaining_payload=" << state->remaining_payload() << " db->Remaining=" << db->Remaining(); QUICHE_DCHECK_EQ(Http2FrameType::SETTINGS, state->frame_header().type); QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length); DecodeStatus status = state->ResumeDecodingStructureInPayload(&setting_fields_, db); if (status == DecodeStatus::kDecodeDone) { state->listener()->OnSetting(setting_fields_); return StartDecodingSettings(state, db); } return HandleNotDone(state, db, status); } DecodeStatus SettingsPayloadDecoder::StartDecodingSettings( FrameDecoderState* state, DecodeBuffer* db) { QUICHE_DVLOG(2) << "SettingsPayloadDecoder::StartDecodingSettings" << " remaining_payload=" << state->remaining_payload() << " db->Remaining=" << db->Remaining(); while (state->remaining_payload() > 0) { DecodeStatus status = state->StartDecodingStructureInPayload(&setting_fields_, db); if (status == DecodeStatus::kDecodeDone) { state->listener()->OnSetting(setting_fields_); continue; } return HandleNotDone(state, db, status); } QUICHE_DVLOG(2) << "LEAVING SettingsPayloadDecoder::StartDecodingSettings" << "\n\tdb->Remaining=" << db->Remaining() << "\n\t remaining_payload=" << state->remaining_payload(); state->listener()->OnSettingsEnd(); return DecodeStatus::kDecodeDone; } DecodeStatus SettingsPayloadDecoder::HandleNotDone(FrameDecoderState* state, DecodeBuffer* db, DecodeStatus status) { QUICHE_DCHECK( (status == DecodeStatus::kDecodeInProgress && state->remaining_payload() > 0) || (status == DecodeStatus::kDecodeError && state->remaining_payload() == 0)) << "\n status=" << status << "; remaining_payload=" << state->remaining_payload() << "; db->Remaining=" << db->Remaining(); return status; } }
#include "quiche/http2/decoder/payload_decoders/settings_payload_decoder.h" #include <stddef.h> #include <vector> #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/test_tools/frame_parts.h" #include "quiche/http2/test_tools/frame_parts_collector.h" #include "quiche/http2/test_tools/http2_constants_test_util.h" #include "quiche/http2/test_tools/http2_frame_builder.h" #include "quiche/http2/test_tools/http2_random.h" #include "quiche/http2/test_tools/http2_structures_test_util.h" #include "quiche/http2/test_tools/payload_decoder_base_test_util.h" #include "quiche/http2/test_tools/random_decoder_test_base.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { class SettingsPayloadDecoderPeer { public: static constexpr Http2FrameType FrameType() { return Http2FrameType::SETTINGS; } static constexpr uint8_t FlagsAffectingPayloadDecoding() { return Http2FrameFlag::ACK; } }; namespace { struct Listener : public FramePartsCollector { void OnSettingsStart(const Http2FrameHeader& header) override { QUICHE_VLOG(1) << "OnSettingsStart: " << header; EXPECT_EQ(Http2FrameType::SETTINGS, header.type) << header; EXPECT_EQ(Http2FrameFlag(), header.flags) << header; StartFrame(header)->OnSettingsStart(header); } void OnSetting(const Http2SettingFields& setting_fields) override { QUICHE_VLOG(1) << "Http2SettingFields: setting_fields=" << setting_fields; CurrentFrame()->OnSetting(setting_fields); } void OnSettingsEnd() override { QUICHE_VLOG(1) << "OnSettingsEnd"; EndFrame()->OnSettingsEnd(); } void OnSettingsAck(const Http2FrameHeader& header) override { QUICHE_VLOG(1) << "OnSettingsAck: " << header; StartAndEndFrame(header)->OnSettingsAck(header); } void OnFrameSizeError(const Http2FrameHeader& header) override { QUICHE_VLOG(1) << "OnFrameSizeError: " << header; FrameError(header)->OnFrameSizeError(header); } }; class SettingsPayloadDecoderTest : public AbstractPayloadDecoderTest<SettingsPayloadDecoder, SettingsPayloadDecoderPeer, Listener> { protected: Http2SettingFields RandSettingsFields() { Http2SettingFields fields; test::Randomize(&fields, RandomPtr()); return fields; } }; TEST_F(SettingsPayloadDecoderTest, SettingsWrongSize) { auto approve_size = [](size_t size) { return 0 != (size % Http2SettingFields::EncodedSize()); }; Http2FrameBuilder fb; fb.Append(RandSettingsFields()); fb.Append(RandSettingsFields()); fb.Append(RandSettingsFields()); EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size)); } TEST_F(SettingsPayloadDecoderTest, SettingsAkcWrongSize) { auto approve_size = [](size_t size) { return size != 0; }; Http2FrameBuilder fb; fb.Append(RandSettingsFields()); fb.Append(RandSettingsFields()); fb.Append(RandSettingsFields()); EXPECT_TRUE(VerifyDetectsFrameSizeError(Http2FrameFlag::ACK, fb.buffer(), approve_size)); } TEST_F(SettingsPayloadDecoderTest, SettingsAck) { for (int stream_id = 0; stream_id < 3; ++stream_id) { Http2FrameHeader header(0, Http2FrameType::SETTINGS, RandFlags() | Http2FrameFlag::ACK, stream_id); set_frame_header(header); FrameParts expected(header); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays("", expected)); } } TEST_F(SettingsPayloadDecoderTest, OneRealSetting) { std::vector<uint32_t> values = {0, 1, 0xffffffff, Random().Rand32()}; for (auto param : AllHttp2SettingsParameters()) { for (uint32_t value : values) { Http2SettingFields fields(param, value); Http2FrameBuilder fb; fb.Append(fields); Http2FrameHeader header(fb.size(), Http2FrameType::SETTINGS, RandFlags(), RandStreamId()); set_frame_header(header); FrameParts expected(header); expected.AppendSetting(fields); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected)); } } } TEST_F(SettingsPayloadDecoderTest, ManySettings) { const size_t num_settings = 100; const size_t size = Http2SettingFields::EncodedSize() * num_settings; Http2FrameHeader header(size, Http2FrameType::SETTINGS, RandFlags(), RandStreamId()); set_frame_header(header); FrameParts expected(header); Http2FrameBuilder fb; for (size_t n = 0; n < num_settings; ++n) { Http2SettingFields fields(static_cast<Http2SettingsParameter>(n), Random().Rand32()); fb.Append(fields); expected.AppendSetting(fields); } ASSERT_EQ(size, fb.size()); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected)); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/payload_decoders/settings_payload_decoder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/payload_decoders/settings_payload_decoder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
4fffa125-f742-4a2d-bc4b-9936af28e8c4
cpp
google/quiche
unknown_payload_decoder
quiche/http2/decoder/payload_decoders/unknown_payload_decoder.cc
quiche/http2/decoder/payload_decoders/unknown_payload_decoder_test.cc
#include "quiche/http2/decoder/payload_decoders/unknown_payload_decoder.h" #include <stddef.h> #include "quiche/http2/decoder/decode_buffer.h" #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/http2_structures.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { DecodeStatus UnknownPayloadDecoder::StartDecodingPayload( FrameDecoderState* state, DecodeBuffer* db) { const Http2FrameHeader& frame_header = state->frame_header(); QUICHE_DVLOG(2) << "UnknownPayloadDecoder::StartDecodingPayload: " << frame_header; QUICHE_DCHECK(!IsSupportedHttp2FrameType(frame_header.type)) << frame_header; QUICHE_DCHECK_LE(db->Remaining(), frame_header.payload_length); state->InitializeRemainders(); state->listener()->OnUnknownStart(frame_header); return ResumeDecodingPayload(state, db); } DecodeStatus UnknownPayloadDecoder::ResumeDecodingPayload( FrameDecoderState* state, DecodeBuffer* db) { QUICHE_DVLOG(2) << "UnknownPayloadDecoder::ResumeDecodingPayload " << "remaining_payload=" << state->remaining_payload() << "; db->Remaining=" << db->Remaining(); QUICHE_DCHECK(!IsSupportedHttp2FrameType(state->frame_header().type)) << state->frame_header(); QUICHE_DCHECK_LE(state->remaining_payload(), state->frame_header().payload_length); QUICHE_DCHECK_LE(db->Remaining(), state->remaining_payload()); size_t avail = db->Remaining(); if (avail > 0) { state->listener()->OnUnknownPayload(db->cursor(), avail); db->AdvanceCursor(avail); state->ConsumePayload(avail); } if (state->remaining_payload() == 0) { state->listener()->OnUnknownEnd(); return DecodeStatus::kDecodeDone; } return DecodeStatus::kDecodeInProgress; } }
#include "quiche/http2/decoder/payload_decoders/unknown_payload_decoder.h" #include <stddef.h> #include <string> #include <type_traits> #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/http2_structures.h" #include "quiche/http2/test_tools/frame_parts.h" #include "quiche/http2/test_tools/frame_parts_collector.h" #include "quiche/http2/test_tools/http2_random.h" #include "quiche/http2/test_tools/payload_decoder_base_test_util.h" #include "quiche/http2/test_tools/random_decoder_test_base.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { namespace { Http2FrameType g_unknown_frame_type; } class UnknownPayloadDecoderPeer { public: static Http2FrameType FrameType() { return g_unknown_frame_type; } static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; } }; namespace { struct Listener : public FramePartsCollector { void OnUnknownStart(const Http2FrameHeader& header) override { QUICHE_VLOG(1) << "OnUnknownStart: " << header; StartFrame(header)->OnUnknownStart(header); } void OnUnknownPayload(const char* data, size_t len) override { QUICHE_VLOG(1) << "OnUnknownPayload: len=" << len; CurrentFrame()->OnUnknownPayload(data, len); } void OnUnknownEnd() override { QUICHE_VLOG(1) << "OnUnknownEnd"; EndFrame()->OnUnknownEnd(); } }; constexpr bool SupportedFrameType = false; class UnknownPayloadDecoderTest : public AbstractPayloadDecoderTest<UnknownPayloadDecoder, UnknownPayloadDecoderPeer, Listener, SupportedFrameType>, public ::testing::WithParamInterface<uint32_t> { protected: UnknownPayloadDecoderTest() : length_(GetParam()) { QUICHE_VLOG(1) << "################ length_=" << length_ << " ################"; do { g_unknown_frame_type = static_cast<Http2FrameType>(Random().Rand8()); } while (IsSupportedHttp2FrameType(g_unknown_frame_type)); } const uint32_t length_; }; INSTANTIATE_TEST_SUITE_P(VariousLengths, UnknownPayloadDecoderTest, ::testing::Values(0, 1, 2, 3, 255, 256)); TEST_P(UnknownPayloadDecoderTest, ValidLength) { std::string unknown_payload = Random().RandString(length_); Http2FrameHeader frame_header(length_, g_unknown_frame_type, Random().Rand8(), RandStreamId()); set_frame_header(frame_header); FrameParts expected(frame_header, unknown_payload); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(unknown_payload, expected)); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/payload_decoders/unknown_payload_decoder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/payload_decoders/unknown_payload_decoder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
6e6030d9-01ce-44e0-b935-a3ee95e13c9b
cpp
google/quiche
priority_update_payload_decoder
quiche/http2/decoder/payload_decoders/priority_update_payload_decoder.cc
quiche/http2/decoder/payload_decoders/priority_update_payload_decoder_test.cc
#include "quiche/http2/decoder/payload_decoders/priority_update_payload_decoder.h" #include <stddef.h> #include <ostream> #include "absl/base/macros.h" #include "quiche/http2/decoder/decode_buffer.h" #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/http2_structures.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { std::ostream& operator<<(std::ostream& out, PriorityUpdatePayloadDecoder::PayloadState v) { switch (v) { case PriorityUpdatePayloadDecoder::PayloadState::kStartDecodingFixedFields: return out << "kStartDecodingFixedFields"; case PriorityUpdatePayloadDecoder::PayloadState::kResumeDecodingFixedFields: return out << "kResumeDecodingFixedFields"; case PriorityUpdatePayloadDecoder::PayloadState::kHandleFixedFieldsStatus: return out << "kHandleFixedFieldsStatus"; case PriorityUpdatePayloadDecoder::PayloadState::kReadPriorityFieldValue: return out << "kReadPriorityFieldValue"; } int unknown = static_cast<int>(v); QUICHE_BUG(http2_bug_173_1) << "Invalid PriorityUpdatePayloadDecoder::PayloadState: " << unknown; return out << "PriorityUpdatePayloadDecoder::PayloadState(" << unknown << ")"; } DecodeStatus PriorityUpdatePayloadDecoder::StartDecodingPayload( FrameDecoderState* state, DecodeBuffer* db) { QUICHE_DVLOG(2) << "PriorityUpdatePayloadDecoder::StartDecodingPayload: " << state->frame_header(); QUICHE_DCHECK_EQ(Http2FrameType::PRIORITY_UPDATE, state->frame_header().type); QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length); QUICHE_DCHECK_EQ(0, state->frame_header().flags); state->InitializeRemainders(); payload_state_ = PayloadState::kStartDecodingFixedFields; return ResumeDecodingPayload(state, db); } DecodeStatus PriorityUpdatePayloadDecoder::ResumeDecodingPayload( FrameDecoderState* state, DecodeBuffer* db) { QUICHE_DVLOG(2) << "PriorityUpdatePayloadDecoder::ResumeDecodingPayload: " "remaining_payload=" << state->remaining_payload() << ", db->Remaining=" << db->Remaining(); const Http2FrameHeader& frame_header = state->frame_header(); QUICHE_DCHECK_EQ(Http2FrameType::PRIORITY_UPDATE, frame_header.type); QUICHE_DCHECK_LE(db->Remaining(), frame_header.payload_length); QUICHE_DCHECK_NE(PayloadState::kHandleFixedFieldsStatus, payload_state_); DecodeStatus status = DecodeStatus::kDecodeError; size_t avail; while (true) { QUICHE_DVLOG(2) << "PriorityUpdatePayloadDecoder::ResumeDecodingPayload payload_state_=" << payload_state_; switch (payload_state_) { case PayloadState::kStartDecodingFixedFields: status = state->StartDecodingStructureInPayload( &priority_update_fields_, db); ABSL_FALLTHROUGH_INTENDED; case PayloadState::kHandleFixedFieldsStatus: if (status == DecodeStatus::kDecodeDone) { state->listener()->OnPriorityUpdateStart(frame_header, priority_update_fields_); } else { QUICHE_DCHECK((status == DecodeStatus::kDecodeInProgress && state->remaining_payload() > 0) || (status == DecodeStatus::kDecodeError && state->remaining_payload() == 0)) << "\n status=" << status << "; remaining_payload=" << state->remaining_payload(); payload_state_ = PayloadState::kResumeDecodingFixedFields; return status; } ABSL_FALLTHROUGH_INTENDED; case PayloadState::kReadPriorityFieldValue: avail = db->Remaining(); if (avail > 0) { state->listener()->OnPriorityUpdatePayload(db->cursor(), avail); db->AdvanceCursor(avail); state->ConsumePayload(avail); } if (state->remaining_payload() > 0) { payload_state_ = PayloadState::kReadPriorityFieldValue; return DecodeStatus::kDecodeInProgress; } state->listener()->OnPriorityUpdateEnd(); return DecodeStatus::kDecodeDone; case PayloadState::kResumeDecodingFixedFields: status = state->ResumeDecodingStructureInPayload( &priority_update_fields_, db); payload_state_ = PayloadState::kHandleFixedFieldsStatus; continue; } QUICHE_BUG(http2_bug_173_2) << "PayloadState: " << payload_state_; } } }
#include "quiche/http2/decoder/payload_decoders/priority_update_payload_decoder.h" #include <stddef.h> #include <string> #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/test_tools/frame_parts.h" #include "quiche/http2/test_tools/frame_parts_collector.h" #include "quiche/http2/test_tools/http2_frame_builder.h" #include "quiche/http2/test_tools/http2_random.h" #include "quiche/http2/test_tools/http2_structures_test_util.h" #include "quiche/http2/test_tools/payload_decoder_base_test_util.h" #include "quiche/http2/test_tools/random_decoder_test_base.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { class PriorityUpdatePayloadDecoderPeer { public: static constexpr Http2FrameType FrameType() { return Http2FrameType::PRIORITY_UPDATE; } static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; } }; namespace { struct Listener : public FramePartsCollector { void OnPriorityUpdateStart( const Http2FrameHeader& header, const Http2PriorityUpdateFields& priority_update) override { QUICHE_VLOG(1) << "OnPriorityUpdateStart header: " << header << "; priority_update: " << priority_update; StartFrame(header)->OnPriorityUpdateStart(header, priority_update); } void OnPriorityUpdatePayload(const char* data, size_t len) override { QUICHE_VLOG(1) << "OnPriorityUpdatePayload: len=" << len; CurrentFrame()->OnPriorityUpdatePayload(data, len); } void OnPriorityUpdateEnd() override { QUICHE_VLOG(1) << "OnPriorityUpdateEnd"; EndFrame()->OnPriorityUpdateEnd(); } void OnFrameSizeError(const Http2FrameHeader& header) override { QUICHE_VLOG(1) << "OnFrameSizeError: " << header; FrameError(header)->OnFrameSizeError(header); } }; class PriorityUpdatePayloadDecoderTest : public AbstractPayloadDecoderTest<PriorityUpdatePayloadDecoder, PriorityUpdatePayloadDecoderPeer, Listener> {}; TEST_F(PriorityUpdatePayloadDecoderTest, Truncated) { auto approve_size = [](size_t size) { return size != Http2PriorityUpdateFields::EncodedSize(); }; Http2FrameBuilder fb; fb.Append(Http2PriorityUpdateFields(123)); EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size)); } class PriorityUpdatePayloadLengthTests : public AbstractPayloadDecoderTest<PriorityUpdatePayloadDecoder, PriorityUpdatePayloadDecoderPeer, Listener>, public ::testing::WithParamInterface<uint32_t> { protected: PriorityUpdatePayloadLengthTests() : length_(GetParam()) { QUICHE_VLOG(1) << "################ length_=" << length_ << " ################"; } const uint32_t length_; }; INSTANTIATE_TEST_SUITE_P(VariousLengths, PriorityUpdatePayloadLengthTests, ::testing::Values(0, 1, 2, 3, 4, 5, 6)); TEST_P(PriorityUpdatePayloadLengthTests, ValidLength) { Http2PriorityUpdateFields priority_update; Randomize(&priority_update, RandomPtr()); std::string priority_field_value = Random().RandString(length_); Http2FrameBuilder fb; fb.Append(priority_update); fb.Append(priority_field_value); Http2FrameHeader header(fb.size(), Http2FrameType::PRIORITY_UPDATE, RandFlags(), RandStreamId()); set_frame_header(header); FrameParts expected(header, priority_field_value); expected.SetOptPriorityUpdate(Http2PriorityUpdateFields{priority_update}); ASSERT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected)); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/payload_decoders/priority_update_payload_decoder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/payload_decoders/priority_update_payload_decoder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
ab55e1df-78ae-42c3-b2c8-909a704646da
cpp
google/quiche
goaway_payload_decoder
quiche/http2/decoder/payload_decoders/goaway_payload_decoder.cc
quiche/http2/decoder/payload_decoders/goaway_payload_decoder_test.cc
#include "quiche/http2/decoder/payload_decoders/goaway_payload_decoder.h" #include <stddef.h> #include <ostream> #include "absl/base/macros.h" #include "quiche/http2/decoder/decode_buffer.h" #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/http2_structures.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { std::ostream& operator<<(std::ostream& out, GoAwayPayloadDecoder::PayloadState v) { switch (v) { case GoAwayPayloadDecoder::PayloadState::kStartDecodingFixedFields: return out << "kStartDecodingFixedFields"; case GoAwayPayloadDecoder::PayloadState::kHandleFixedFieldsStatus: return out << "kHandleFixedFieldsStatus"; case GoAwayPayloadDecoder::PayloadState::kReadOpaqueData: return out << "kReadOpaqueData"; case GoAwayPayloadDecoder::PayloadState::kResumeDecodingFixedFields: return out << "kResumeDecodingFixedFields"; } int unknown = static_cast<int>(v); QUICHE_BUG(http2_bug_167_1) << "Invalid GoAwayPayloadDecoder::PayloadState: " << unknown; return out << "GoAwayPayloadDecoder::PayloadState(" << unknown << ")"; } DecodeStatus GoAwayPayloadDecoder::StartDecodingPayload( FrameDecoderState* state, DecodeBuffer* db) { QUICHE_DVLOG(2) << "GoAwayPayloadDecoder::StartDecodingPayload: " << state->frame_header(); QUICHE_DCHECK_EQ(Http2FrameType::GOAWAY, state->frame_header().type); QUICHE_DCHECK_LE(db->Remaining(), state->frame_header().payload_length); QUICHE_DCHECK_EQ(0, state->frame_header().flags); state->InitializeRemainders(); payload_state_ = PayloadState::kStartDecodingFixedFields; return ResumeDecodingPayload(state, db); } DecodeStatus GoAwayPayloadDecoder::ResumeDecodingPayload( FrameDecoderState* state, DecodeBuffer* db) { QUICHE_DVLOG(2) << "GoAwayPayloadDecoder::ResumeDecodingPayload: remaining_payload=" << state->remaining_payload() << ", db->Remaining=" << db->Remaining(); const Http2FrameHeader& frame_header = state->frame_header(); QUICHE_DCHECK_EQ(Http2FrameType::GOAWAY, frame_header.type); QUICHE_DCHECK_LE(db->Remaining(), frame_header.payload_length); QUICHE_DCHECK_NE(PayloadState::kHandleFixedFieldsStatus, payload_state_); DecodeStatus status = DecodeStatus::kDecodeError; size_t avail; while (true) { QUICHE_DVLOG(2) << "GoAwayPayloadDecoder::ResumeDecodingPayload payload_state_=" << payload_state_; switch (payload_state_) { case PayloadState::kStartDecodingFixedFields: status = state->StartDecodingStructureInPayload(&goaway_fields_, db); ABSL_FALLTHROUGH_INTENDED; case PayloadState::kHandleFixedFieldsStatus: if (status == DecodeStatus::kDecodeDone) { state->listener()->OnGoAwayStart(frame_header, goaway_fields_); } else { QUICHE_DCHECK((status == DecodeStatus::kDecodeInProgress && state->remaining_payload() > 0) || (status == DecodeStatus::kDecodeError && state->remaining_payload() == 0)) << "\n status=" << status << "; remaining_payload=" << state->remaining_payload(); payload_state_ = PayloadState::kResumeDecodingFixedFields; return status; } ABSL_FALLTHROUGH_INTENDED; case PayloadState::kReadOpaqueData: avail = db->Remaining(); if (avail > 0) { state->listener()->OnGoAwayOpaqueData(db->cursor(), avail); db->AdvanceCursor(avail); state->ConsumePayload(avail); } if (state->remaining_payload() > 0) { payload_state_ = PayloadState::kReadOpaqueData; return DecodeStatus::kDecodeInProgress; } state->listener()->OnGoAwayEnd(); return DecodeStatus::kDecodeDone; case PayloadState::kResumeDecodingFixedFields: status = state->ResumeDecodingStructureInPayload(&goaway_fields_, db); payload_state_ = PayloadState::kHandleFixedFieldsStatus; continue; } QUICHE_BUG(http2_bug_167_2) << "PayloadState: " << payload_state_; } } }
#include "quiche/http2/decoder/payload_decoders/goaway_payload_decoder.h" #include <stddef.h> #include <string> #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/test_tools/frame_parts.h" #include "quiche/http2/test_tools/frame_parts_collector.h" #include "quiche/http2/test_tools/http2_frame_builder.h" #include "quiche/http2/test_tools/http2_random.h" #include "quiche/http2/test_tools/http2_structures_test_util.h" #include "quiche/http2/test_tools/payload_decoder_base_test_util.h" #include "quiche/http2/test_tools/random_decoder_test_base.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { class GoAwayPayloadDecoderPeer { public: static constexpr Http2FrameType FrameType() { return Http2FrameType::GOAWAY; } static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; } }; namespace { struct Listener : public FramePartsCollector { void OnGoAwayStart(const Http2FrameHeader& header, const Http2GoAwayFields& goaway) override { QUICHE_VLOG(1) << "OnGoAwayStart header: " << header << "; goaway: " << goaway; StartFrame(header)->OnGoAwayStart(header, goaway); } void OnGoAwayOpaqueData(const char* data, size_t len) override { QUICHE_VLOG(1) << "OnGoAwayOpaqueData: len=" << len; CurrentFrame()->OnGoAwayOpaqueData(data, len); } void OnGoAwayEnd() override { QUICHE_VLOG(1) << "OnGoAwayEnd"; EndFrame()->OnGoAwayEnd(); } void OnFrameSizeError(const Http2FrameHeader& header) override { QUICHE_VLOG(1) << "OnFrameSizeError: " << header; FrameError(header)->OnFrameSizeError(header); } }; class GoAwayPayloadDecoderTest : public AbstractPayloadDecoderTest<GoAwayPayloadDecoder, GoAwayPayloadDecoderPeer, Listener> {}; TEST_F(GoAwayPayloadDecoderTest, Truncated) { auto approve_size = [](size_t size) { return size != Http2GoAwayFields::EncodedSize(); }; Http2FrameBuilder fb; fb.Append(Http2GoAwayFields(123, Http2ErrorCode::ENHANCE_YOUR_CALM)); EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size)); } class GoAwayOpaqueDataLengthTests : public GoAwayPayloadDecoderTest, public ::testing::WithParamInterface<uint32_t> { protected: GoAwayOpaqueDataLengthTests() : length_(GetParam()) { QUICHE_VLOG(1) << "################ length_=" << length_ << " ################"; } const uint32_t length_; }; INSTANTIATE_TEST_SUITE_P(VariousLengths, GoAwayOpaqueDataLengthTests, ::testing::Values(0, 1, 2, 3, 4, 5, 6)); TEST_P(GoAwayOpaqueDataLengthTests, ValidLength) { Http2GoAwayFields goaway; Randomize(&goaway, RandomPtr()); std::string opaque_data = Random().RandString(length_); Http2FrameBuilder fb; fb.Append(goaway); fb.Append(opaque_data); Http2FrameHeader header(fb.size(), Http2FrameType::GOAWAY, RandFlags(), RandStreamId()); set_frame_header(header); FrameParts expected(header, opaque_data); expected.SetOptGoaway(goaway); ASSERT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected)); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/payload_decoders/goaway_payload_decoder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/decoder/payload_decoders/goaway_payload_decoder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
11fa5562-8f1d-4479-b049-91d37b07b020
cpp
google/quiche
noop_header_validator
quiche/http2/adapter/noop_header_validator.cc
quiche/http2/adapter/noop_header_validator_test.cc
#include "quiche/http2/adapter/noop_header_validator.h" #include <string> #include "absl/strings/escaping.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { namespace adapter { HeaderValidatorBase::HeaderStatus NoopHeaderValidator::ValidateSingleHeader( absl::string_view key, absl::string_view value) { if (key == ":status") { status_ = std::string(value); } return HEADER_OK; } bool NoopHeaderValidator::FinishHeaderBlock(HeaderType ) { return true; } } }
#include "quiche/http2/adapter/noop_header_validator.h" #include <limits> #include <optional> #include <utility> #include <vector> #include "absl/strings/str_cat.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace adapter { namespace test { using ::testing::Optional; using Header = std::pair<absl::string_view, absl::string_view>; constexpr Header kSampleRequestPseudoheaders[] = {{":authority", "www.foo.com"}, {":method", "GET"}, {":path", "/foo"}, {":scheme", "https"}}; TEST(NoopHeaderValidatorTest, HeaderNameEmpty) { NoopHeaderValidator v; NoopHeaderValidator::HeaderStatus status = v.ValidateSingleHeader("", "value"); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, status); } TEST(NoopHeaderValidatorTest, HeaderValueEmpty) { NoopHeaderValidator v; NoopHeaderValidator::HeaderStatus status = v.ValidateSingleHeader("name", ""); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, status); } TEST(NoopHeaderValidatorTest, ExceedsMaxSize) { NoopHeaderValidator v; v.SetMaxFieldSize(64u); NoopHeaderValidator::HeaderStatus status = v.ValidateSingleHeader("name", "value"); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, status); status = v.ValidateSingleHeader( "name2", "Antidisestablishmentariansism is supercalifragilisticexpialodocious."); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, status); } TEST(NoopHeaderValidatorTest, AnyNameCharIsValid) { NoopHeaderValidator v; char pseudo_name[] = ":met hod"; char name[] = "na me"; for (int i = std::numeric_limits<char>::min(); i < std::numeric_limits<char>::max(); ++i) { char c = static_cast<char>(i); pseudo_name[3] = c; auto sv = absl::string_view(pseudo_name, 8); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(sv, "value")); name[2] = c; sv = absl::string_view(name, 5); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(sv, "value")); } } TEST(NoopHeaderValidatorTest, AnyValueCharIsValid) { NoopHeaderValidator v; char value[] = "val ue"; for (int i = std::numeric_limits<char>::min(); i < std::numeric_limits<char>::max(); ++i) { char c = static_cast<char>(i); value[3] = c; auto sv = absl::string_view(value, 6); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("name", sv)); } } TEST(NoopHeaderValidatorTest, AnyStatusIsValid) { NoopHeaderValidator v; for (HeaderType type : {HeaderType::RESPONSE, HeaderType::RESPONSE_100}) { v.StartHeaderBlock(); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "bar")); EXPECT_TRUE(v.FinishHeaderBlock(type)); v.StartHeaderBlock(); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "10")); EXPECT_TRUE(v.FinishHeaderBlock(type)); v.StartHeaderBlock(); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "9000")); EXPECT_TRUE(v.FinishHeaderBlock(type)); v.StartHeaderBlock(); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "400")); EXPECT_TRUE(v.FinishHeaderBlock(type)); } } TEST(NoopHeaderValidatorTest, AnyAuthorityCharIsValid) { char value[] = "ho st.example.com"; for (int i = std::numeric_limits<char>::min(); i < std::numeric_limits<char>::max(); ++i) { char c = static_cast<char>(i); value[2] = c; auto sv = absl::string_view(value, 17); for (absl::string_view key : {":authority", "host"}) { NoopHeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(key, sv)); } } } TEST(NoopHeaderValidatorTest, RequestHostAndAuthority) { NoopHeaderValidator v; v.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("host", "www.foo.com")); EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST)); v.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("host", "www.bar.com")); } TEST(NoopHeaderValidatorTest, RequestPseudoHeaders) { NoopHeaderValidator v; for (Header to_skip : kSampleRequestPseudoheaders) { v.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { if (to_add != to_skip) { EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } } EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST)); } v.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST)); v.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(":extra", "blah")); EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST)); for (Header to_repeat : kSampleRequestPseudoheaders) { v.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); if (to_add == to_repeat) { EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } } EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST)); } } TEST(NoopHeaderValidatorTest, WebsocketPseudoHeaders) { NoopHeaderValidator v; v.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(":protocol", "websocket")); EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST)); v.SetAllowExtendedConnect(); v.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(":protocol", "websocket")); EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST)); v.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { if (to_add.first == ":method") { EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, "CONNECT")); } else { EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } } EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(":protocol", "websocket")); EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST)); } TEST(NoopHeaderValidatorTest, AsteriskPathPseudoHeader) { NoopHeaderValidator v; v.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { if (to_add.first == ":path") { EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, "*")); } else { EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } } EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST)); v.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { if (to_add.first == ":path") { EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, "*")); } else if (to_add.first == ":method") { EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, "OPTIONS")); } else { EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } } EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST)); } TEST(NoopHeaderValidatorTest, InvalidPathPseudoHeader) { NoopHeaderValidator v; v.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { if (to_add.first == ":path") { EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, "")); } else { EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } } EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST)); v.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { if (to_add.first == ":path") { EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, "shawarma")); } else { EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } } EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST)); } TEST(NoopHeaderValidatorTest, ResponsePseudoHeaders) { NoopHeaderValidator v; for (HeaderType type : {HeaderType::RESPONSE, HeaderType::RESPONSE_100}) { v.StartHeaderBlock(); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("foo", "bar")); EXPECT_TRUE(v.FinishHeaderBlock(type)); v.StartHeaderBlock(); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "199")); EXPECT_TRUE(v.FinishHeaderBlock(type)); EXPECT_EQ("199", v.status_header()); v.StartHeaderBlock(); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "199")); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "299")); EXPECT_TRUE(v.FinishHeaderBlock(type)); v.StartHeaderBlock(); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "199")); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(":extra", "blorp")); EXPECT_TRUE(v.FinishHeaderBlock(type)); } } TEST(NoopHeaderValidatorTest, ResponseWithHost) { NoopHeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "200")); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("host", "myserver.com")); EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::RESPONSE)); } TEST(NoopHeaderValidatorTest, Response204) { NoopHeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "204")); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("x-content", "is not present")); EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::RESPONSE)); } TEST(NoopHeaderValidatorTest, ResponseWithMultipleIdenticalContentLength) { NoopHeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "200")); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("content-length", "13")); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("content-length", "13")); } TEST(NoopHeaderValidatorTest, ResponseWithMultipleDifferingContentLength) { NoopHeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "200")); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("content-length", "13")); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("content-length", "17")); } TEST(NoopHeaderValidatorTest, Response204WithContentLengthZero) { NoopHeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "204")); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("x-content", "is not present")); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("content-length", "0")); EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::RESPONSE)); } TEST(NoopHeaderValidatorTest, Response204WithContentLength) { NoopHeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "204")); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("x-content", "is not present")); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("content-length", "1")); } TEST(NoopHeaderValidatorTest, Response100) { NoopHeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "100")); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("x-content", "is not present")); EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::RESPONSE)); } TEST(NoopHeaderValidatorTest, Response100WithContentLengthZero) { NoopHeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "100")); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("x-content", "is not present")); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("content-length", "0")); EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::RESPONSE)); } TEST(NoopHeaderValidatorTest, Response100WithContentLength) { NoopHeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "100")); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("x-content", "is not present")); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("content-length", "1")); } TEST(NoopHeaderValidatorTest, ResponseTrailerPseudoHeaders) { NoopHeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("foo", "bar")); EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::RESPONSE_TRAILER)); v.StartHeaderBlock(); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "200")); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("foo", "bar")); EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::RESPONSE_TRAILER)); } TEST(NoopHeaderValidatorTest, ValidContentLength) { NoopHeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(v.content_length(), std::nullopt); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("content-length", "41")); EXPECT_EQ(v.content_length(), std::nullopt); v.StartHeaderBlock(); EXPECT_EQ(v.content_length(), std::nullopt); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("content-length", "42")); EXPECT_EQ(v.content_length(), std::nullopt); } TEST(NoopHeaderValidatorTest, InvalidContentLength) { NoopHeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(v.content_length(), std::nullopt); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("content-length", "")); EXPECT_EQ(v.content_length(), std::nullopt); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("content-length", "nan")); EXPECT_EQ(v.content_length(), std::nullopt); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("content-length", "-42")); EXPECT_EQ(v.content_length(), std::nullopt); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("content-length", "42")); EXPECT_EQ(v.content_length(), std::nullopt); } TEST(NoopHeaderValidatorTest, TeHeader) { NoopHeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("te", "trailers")); v.StartHeaderBlock(); EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader("te", "trailers, deflate")); } TEST(NoopHeaderValidatorTest, ConnectionSpecificHeaders) { const std::vector<Header> connection_headers = { {"connection", "keep-alive"}, {"proxy-connection", "keep-alive"}, {"keep-alive", "timeout=42"}, {"transfer-encoding", "chunked"}, {"upgrade", "h2c"}, }; for (const auto& [connection_key, connection_value] : connection_headers) { NoopHeaderValidator v; v.StartHeaderBlock(); for (const auto& [sample_key, sample_value] : kSampleRequestPseudoheaders) { EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(sample_key, sample_value)); } EXPECT_EQ(NoopHeaderValidator::HEADER_OK, v.ValidateSingleHeader(connection_key, connection_value)); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/noop_header_validator.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/noop_header_validator_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
b9be3bd0-5a4d-4172-90ed-9de74789151f
cpp
google/quiche
nghttp2_session
quiche/http2/adapter/nghttp2_session.cc
quiche/http2/adapter/nghttp2_session_test.cc
#include "quiche/http2/adapter/nghttp2_session.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { namespace adapter { NgHttp2Session::NgHttp2Session(Perspective perspective, nghttp2_session_callbacks_unique_ptr callbacks, const nghttp2_option* options, void* userdata) : session_(MakeSessionPtr(nullptr)), perspective_(perspective) { nghttp2_session* session; switch (perspective_) { case Perspective::kClient: nghttp2_session_client_new2(&session, callbacks.get(), userdata, options); break; case Perspective::kServer: nghttp2_session_server_new2(&session, callbacks.get(), userdata, options); break; } session_ = MakeSessionPtr(session); } NgHttp2Session::~NgHttp2Session() { const bool pending_reads = nghttp2_session_want_read(session_.get()) != 0; const bool pending_writes = nghttp2_session_want_write(session_.get()) != 0; if (pending_reads || pending_writes) { QUICHE_VLOG(1) << "Shutting down connection with pending reads: " << pending_reads << " or pending writes: " << pending_writes; } } int64_t NgHttp2Session::ProcessBytes(absl::string_view bytes) { return nghttp2_session_mem_recv( session_.get(), reinterpret_cast<const uint8_t*>(bytes.data()), bytes.size()); } int NgHttp2Session::Consume(Http2StreamId stream_id, size_t num_bytes) { return nghttp2_session_consume(session_.get(), stream_id, num_bytes); } bool NgHttp2Session::want_read() const { return nghttp2_session_want_read(session_.get()) != 0; } bool NgHttp2Session::want_write() const { return nghttp2_session_want_write(session_.get()) != 0; } int NgHttp2Session::GetRemoteWindowSize() const { return nghttp2_session_get_remote_window_size(session_.get()); } } }
#include "quiche/http2/adapter/nghttp2_session.h" #include <string> #include <vector> #include "quiche/http2/adapter/mock_http2_visitor.h" #include "quiche/http2/adapter/nghttp2_callbacks.h" #include "quiche/http2/adapter/nghttp2_util.h" #include "quiche/http2/adapter/test_frame_sequence.h" #include "quiche/http2/adapter/test_utils.h" #include "quiche/common/platform/api/quiche_expect_bug.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace adapter { namespace test { namespace { using testing::_; enum FrameType { DATA, HEADERS, PRIORITY, RST_STREAM, SETTINGS, PUSH_PROMISE, PING, GOAWAY, WINDOW_UPDATE, }; class NgHttp2SessionTest : public quiche::test::QuicheTest { public: void SetUp() override { nghttp2_option_new(&options_); nghttp2_option_set_no_auto_window_update(options_, 1); } void TearDown() override { nghttp2_option_del(options_); } nghttp2_session_callbacks_unique_ptr CreateCallbacks() { nghttp2_session_callbacks_unique_ptr callbacks = callbacks::Create(nullptr); return callbacks; } TestVisitor visitor_; nghttp2_option* options_ = nullptr; }; TEST_F(NgHttp2SessionTest, ClientConstruction) { NgHttp2Session session(Perspective::kClient, CreateCallbacks(), options_, &visitor_); EXPECT_TRUE(session.want_read()); EXPECT_FALSE(session.want_write()); EXPECT_EQ(session.GetRemoteWindowSize(), kInitialFlowControlWindowSize); EXPECT_NE(session.raw_ptr(), nullptr); } TEST_F(NgHttp2SessionTest, ClientHandlesFrames) { NgHttp2Session session(Perspective::kClient, CreateCallbacks(), options_, &visitor_); ASSERT_EQ(0, nghttp2_session_send(session.raw_ptr())); ASSERT_GT(visitor_.data().size(), 0); const std::string initial_frames = TestFrameSequence() .ServerPreface() .Ping(42) .WindowUpdate(0, 1000) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor_, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor_, OnSettingsStart()); EXPECT_CALL(visitor_, OnSettingsEnd()); EXPECT_CALL(visitor_, OnFrameHeader(0, 8, PING, 0)); EXPECT_CALL(visitor_, OnPing(42, false)); EXPECT_CALL(visitor_, OnFrameHeader(0, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor_, OnWindowUpdate(0, 1000)); const int64_t initial_result = session.ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), initial_result); EXPECT_EQ(session.GetRemoteWindowSize(), kInitialFlowControlWindowSize + 1000); EXPECT_CALL(visitor_, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor_, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_CALL(visitor_, OnBeforeFrameSent(PING, 0, 8, 0x1)); EXPECT_CALL(visitor_, OnFrameSent(PING, 0, 8, 0x1, 0)); ASSERT_EQ(0, nghttp2_session_send(session.raw_ptr())); absl::string_view serialized = visitor_.data(); ASSERT_THAT(serialized, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(serialized, EqualsFrames({spdy::SpdyFrameType::SETTINGS, spdy::SpdyFrameType::PING})); visitor_.Clear(); const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const auto nvs1 = GetNghttp2Nvs(headers1); const std::vector<Header> headers2 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}); const auto nvs2 = GetNghttp2Nvs(headers2); const std::vector<Header> headers3 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/three"}}); const auto nvs3 = GetNghttp2Nvs(headers3); const int32_t stream_id1 = nghttp2_submit_request( session.raw_ptr(), nullptr, nvs1.data(), nvs1.size(), nullptr, nullptr); ASSERT_GT(stream_id1, 0); QUICHE_LOG(INFO) << "Created stream: " << stream_id1; const int32_t stream_id2 = nghttp2_submit_request( session.raw_ptr(), nullptr, nvs2.data(), nvs2.size(), nullptr, nullptr); ASSERT_GT(stream_id2, 0); QUICHE_LOG(INFO) << "Created stream: " << stream_id2; const int32_t stream_id3 = nghttp2_submit_request( session.raw_ptr(), nullptr, nvs3.data(), nvs3.size(), nullptr, nullptr); ASSERT_GT(stream_id3, 0); QUICHE_LOG(INFO) << "Created stream: " << stream_id3; EXPECT_CALL(visitor_, OnBeforeFrameSent(HEADERS, 1, _, 0x5)); EXPECT_CALL(visitor_, OnFrameSent(HEADERS, 1, _, 0x5, 0)); EXPECT_CALL(visitor_, OnBeforeFrameSent(HEADERS, 3, _, 0x5)); EXPECT_CALL(visitor_, OnFrameSent(HEADERS, 3, _, 0x5, 0)); EXPECT_CALL(visitor_, OnBeforeFrameSent(HEADERS, 5, _, 0x5)); EXPECT_CALL(visitor_, OnFrameSent(HEADERS, 5, _, 0x5, 0)); ASSERT_EQ(0, nghttp2_session_send(session.raw_ptr())); serialized = visitor_.data(); EXPECT_THAT(serialized, EqualsFrames({spdy::SpdyFrameType::HEADERS, spdy::SpdyFrameType::HEADERS, spdy::SpdyFrameType::HEADERS})); visitor_.Clear(); const std::string stream_frames = TestFrameSequence() .Headers(1, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, false) .Data(1, "This is the response body.") .RstStream(3, Http2ErrorCode::INTERNAL_ERROR) .GoAway(5, Http2ErrorCode::ENHANCE_YOUR_CALM, "calm down!!") .Serialize(); EXPECT_CALL(visitor_, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor_, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor_, OnHeaderForStream(1, ":status", "200")); EXPECT_CALL(visitor_, OnHeaderForStream(1, "server", "my-fake-server")); EXPECT_CALL(visitor_, OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT")); EXPECT_CALL(visitor_, OnEndHeadersForStream(1)); EXPECT_CALL(visitor_, OnFrameHeader(1, 26, DATA, 0)); EXPECT_CALL(visitor_, OnBeginDataForStream(1, 26)); EXPECT_CALL(visitor_, OnDataForStream(1, "This is the response body.")); EXPECT_CALL(visitor_, OnFrameHeader(3, 4, RST_STREAM, 0)); EXPECT_CALL(visitor_, OnRstStream(3, Http2ErrorCode::INTERNAL_ERROR)); EXPECT_CALL(visitor_, OnCloseStream(3, Http2ErrorCode::INTERNAL_ERROR)); EXPECT_CALL(visitor_, OnFrameHeader(0, 19, GOAWAY, 0)); EXPECT_CALL(visitor_, OnGoAway(5, Http2ErrorCode::ENHANCE_YOUR_CALM, "calm down!!")); const int64_t stream_result = session.ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), stream_result); EXPECT_TRUE(session.want_read()); EXPECT_CALL(visitor_, OnFrameHeader(1, 0, DATA, 1)); EXPECT_CALL(visitor_, OnBeginDataForStream(1, 0)); EXPECT_CALL(visitor_, OnEndStream(1)); EXPECT_CALL(visitor_, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_CALL(visitor_, OnFrameHeader(5, 4, RST_STREAM, 0)); EXPECT_CALL(visitor_, OnRstStream(5, Http2ErrorCode::REFUSED_STREAM)); EXPECT_CALL(visitor_, OnCloseStream(5, Http2ErrorCode::REFUSED_STREAM)); session.ProcessBytes(TestFrameSequence() .Data(1, "", true) .RstStream(5, Http2ErrorCode::REFUSED_STREAM) .Serialize()); EXPECT_FALSE(session.want_read()); EXPECT_FALSE(session.want_write()); ASSERT_EQ(0, nghttp2_session_send(session.raw_ptr())); serialized = visitor_.data(); EXPECT_EQ(serialized.size(), 0); } TEST_F(NgHttp2SessionTest, ServerConstruction) { NgHttp2Session session(Perspective::kServer, CreateCallbacks(), options_, &visitor_); EXPECT_TRUE(session.want_read()); EXPECT_FALSE(session.want_write()); EXPECT_EQ(session.GetRemoteWindowSize(), kInitialFlowControlWindowSize); EXPECT_NE(session.raw_ptr(), nullptr); } TEST_F(NgHttp2SessionTest, ServerHandlesFrames) { NgHttp2Session session(Perspective::kServer, CreateCallbacks(), options_, &visitor_); const std::string frames = TestFrameSequence() .ClientPreface() .Ping(42) .WindowUpdate(0, 1000) .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .WindowUpdate(1, 2000) .Data(1, "This is the request body.") .Headers(3, {{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}, true) .RstStream(3, Http2ErrorCode::CANCEL) .Ping(47) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor_, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor_, OnSettingsStart()); EXPECT_CALL(visitor_, OnSettingsEnd()); EXPECT_CALL(visitor_, OnFrameHeader(0, 8, PING, 0)); EXPECT_CALL(visitor_, OnPing(42, false)); EXPECT_CALL(visitor_, OnFrameHeader(0, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor_, OnWindowUpdate(0, 1000)); EXPECT_CALL(visitor_, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor_, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor_, OnHeaderForStream(1, ":method", "POST")); EXPECT_CALL(visitor_, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor_, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor_, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor_, OnEndHeadersForStream(1)); EXPECT_CALL(visitor_, OnFrameHeader(1, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor_, OnWindowUpdate(1, 2000)); EXPECT_CALL(visitor_, OnFrameHeader(1, 25, DATA, 0)); EXPECT_CALL(visitor_, OnBeginDataForStream(1, 25)); EXPECT_CALL(visitor_, OnDataForStream(1, "This is the request body.")); EXPECT_CALL(visitor_, OnFrameHeader(3, _, HEADERS, 5)); EXPECT_CALL(visitor_, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor_, OnHeaderForStream(3, ":method", "GET")); EXPECT_CALL(visitor_, OnHeaderForStream(3, ":scheme", "http")); EXPECT_CALL(visitor_, OnHeaderForStream(3, ":authority", "example.com")); EXPECT_CALL(visitor_, OnHeaderForStream(3, ":path", "/this/is/request/two")); EXPECT_CALL(visitor_, OnEndHeadersForStream(3)); EXPECT_CALL(visitor_, OnEndStream(3)); EXPECT_CALL(visitor_, OnFrameHeader(3, 4, RST_STREAM, 0)); EXPECT_CALL(visitor_, OnRstStream(3, Http2ErrorCode::CANCEL)); EXPECT_CALL(visitor_, OnCloseStream(3, Http2ErrorCode::CANCEL)); EXPECT_CALL(visitor_, OnFrameHeader(0, 8, PING, 0)); EXPECT_CALL(visitor_, OnPing(47, false)); const int64_t result = session.ProcessBytes(frames); EXPECT_EQ(frames.size(), result); EXPECT_EQ(session.GetRemoteWindowSize(), kInitialFlowControlWindowSize + 1000); EXPECT_CALL(visitor_, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor_, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_CALL(visitor_, OnBeforeFrameSent(PING, 0, 8, 0x1)); EXPECT_CALL(visitor_, OnFrameSent(PING, 0, 8, 0x1, 0)); EXPECT_CALL(visitor_, OnBeforeFrameSent(PING, 0, 8, 0x1)); EXPECT_CALL(visitor_, OnFrameSent(PING, 0, 8, 0x1, 0)); EXPECT_TRUE(session.want_write()); ASSERT_EQ(0, nghttp2_session_send(session.raw_ptr())); absl::string_view serialized = visitor_.data(); EXPECT_THAT(serialized, EqualsFrames({spdy::SpdyFrameType::SETTINGS, spdy::SpdyFrameType::PING, spdy::SpdyFrameType::PING})); } TEST_F(NgHttp2SessionTest, NullPayload) { NgHttp2Session session(Perspective::kClient, CreateCallbacks(), options_, &visitor_); void* payload = nullptr; const int result = nghttp2_submit_extension( session.raw_ptr(), kMetadataFrameType, 0, 1, payload); ASSERT_EQ(0, result); EXPECT_TRUE(session.want_write()); int send_result = -1; EXPECT_QUICHE_BUG( { send_result = nghttp2_session_send(session.raw_ptr()); EXPECT_EQ(NGHTTP2_ERR_CALLBACK_FAILURE, send_result); }, "Extension frame payload for stream 1 is null!"); } TEST_F(NgHttp2SessionTest, ServerSeesErrorOnEndStream) { NgHttp2Session session(Perspective::kServer, CreateCallbacks(), options_, &visitor_); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/"}}, false) .Data(1, "Request body", true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor_, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor_, OnSettingsStart()); EXPECT_CALL(visitor_, OnSettingsEnd()); EXPECT_CALL(visitor_, OnFrameHeader(1, _, HEADERS, 0x4)); EXPECT_CALL(visitor_, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor_, OnHeaderForStream(1, ":method", "POST")); EXPECT_CALL(visitor_, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor_, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor_, OnHeaderForStream(1, ":path", "/")); EXPECT_CALL(visitor_, OnEndHeadersForStream(1)); EXPECT_CALL(visitor_, OnFrameHeader(1, _, DATA, 0x1)); EXPECT_CALL(visitor_, OnBeginDataForStream(1, _)); EXPECT_CALL(visitor_, OnDataForStream(1, "Request body")); EXPECT_CALL(visitor_, OnEndStream(1)).WillOnce(testing::Return(false)); const int64_t result = session.ProcessBytes(frames); EXPECT_EQ(NGHTTP2_ERR_CALLBACK_FAILURE, result); EXPECT_TRUE(session.want_write()); EXPECT_CALL(visitor_, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor_, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); ASSERT_EQ(0, nghttp2_session_send(session.raw_ptr())); EXPECT_THAT(visitor_.data(), EqualsFrames({spdy::SpdyFrameType::SETTINGS})); visitor_.Clear(); EXPECT_FALSE(session.want_write()); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/nghttp2_session.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/nghttp2_session_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
518097c4-f474-42d5-b007-433b27b9c447
cpp
google/quiche
chunked_buffer
quiche/http2/adapter/chunked_buffer.cc
quiche/http2/adapter/chunked_buffer_test.cc
#include "quiche/http2/adapter/chunked_buffer.h" #include <algorithm> #include <memory> #include <utility> #include <vector> namespace http2 { namespace adapter { namespace { constexpr size_t kKilobyte = 1024; size_t RoundUpToNearestKilobyte(size_t n) { return ((n - 1) | (kKilobyte - 1)) + 1; } } void ChunkedBuffer::Append(absl::string_view data) { const size_t to_copy = std::min(TailBytesFree(), data.size()); if (to_copy > 0) { chunks_.back().AppendSuffix(data.substr(0, to_copy)); data.remove_prefix(to_copy); } EnsureTailBytesFree(data.size()); chunks_.back().AppendSuffix(data); } void ChunkedBuffer::Append(std::unique_ptr<char[]> data, size_t size) { if (TailBytesFree() >= size) { Chunk& c = chunks_.back(); c.AppendSuffix(absl::string_view(data.get(), size)); return; } while (!chunks_.empty() && chunks_.front().Empty()) { chunks_.pop_front(); } absl::string_view v = {data.get(), size}; chunks_.push_back({std::move(data), size, v}); } absl::string_view ChunkedBuffer::GetPrefix() const { if (chunks_.empty()) { return ""; } return chunks_.front().live; } std::vector<absl::string_view> ChunkedBuffer::Read() const { std::vector<absl::string_view> result; result.reserve(chunks_.size()); for (const Chunk& c : chunks_) { result.push_back(c.live); } return result; } void ChunkedBuffer::RemovePrefix(size_t n) { while (!Empty() && n > 0) { Chunk& c = chunks_.front(); const size_t to_remove = std::min(n, c.live.size()); c.RemovePrefix(to_remove); n -= to_remove; if (c.Empty()) { TrimFirstChunk(); } } } bool ChunkedBuffer::Empty() const { return chunks_.empty() || (chunks_.size() == 1 && chunks_.front().live.empty()); } void ChunkedBuffer::Chunk::RemovePrefix(size_t n) { QUICHE_DCHECK_GE(live.size(), n); live.remove_prefix(n); } void ChunkedBuffer::Chunk::AppendSuffix(absl::string_view to_append) { QUICHE_DCHECK_GE(TailBytesFree(), to_append.size()); if (live.empty()) { std::copy(to_append.begin(), to_append.end(), data.get()); live = absl::string_view(data.get(), to_append.size()); } else { std::copy(to_append.begin(), to_append.end(), const_cast<char*>(live.data()) + live.size()); live = absl::string_view(live.data(), live.size() + to_append.size()); } } size_t ChunkedBuffer::TailBytesFree() const { if (chunks_.empty()) { return 0; } return chunks_.back().TailBytesFree(); } void ChunkedBuffer::EnsureTailBytesFree(size_t n) { if (TailBytesFree() >= n) { return; } const size_t to_allocate = RoundUpToNearestKilobyte(n); auto data = std::unique_ptr<char[]>(new char[to_allocate]); chunks_.push_back({std::move(data), to_allocate, ""}); } void ChunkedBuffer::TrimFirstChunk() { if (chunks_.empty() || (chunks_.size() == 1 && chunks_.front().size == kDefaultChunkSize)) { return; } chunks_.pop_front(); } } }
#include "quiche/http2/adapter/chunked_buffer.h" #include <algorithm> #include <initializer_list> #include <memory> #include <utility> #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace adapter { namespace { constexpr absl::string_view kLoremIpsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod " "tempor incididunt ut labore et dolore magna aliqua."; struct DataAndSize { std::unique_ptr<char[]> data; size_t size; }; DataAndSize MakeDataAndSize(absl::string_view source) { auto data = std::unique_ptr<char[]>(new char[source.size()]); std::copy(source.begin(), source.end(), data.get()); return {std::move(data), source.size()}; } TEST(ChunkedBufferTest, Empty) { ChunkedBuffer buffer; EXPECT_TRUE(buffer.Empty()); buffer.Append("some data"); EXPECT_FALSE(buffer.Empty()); buffer.RemovePrefix(9); EXPECT_TRUE(buffer.Empty()); } TEST(ChunkedBufferTest, ReusedAfterEmptied) { ChunkedBuffer buffer; buffer.Append("some data"); buffer.RemovePrefix(9); buffer.Append("different data"); EXPECT_EQ("different data", buffer.GetPrefix()); } TEST(ChunkedBufferTest, LargeAppendAfterEmptied) { ChunkedBuffer buffer; buffer.Append("some data"); EXPECT_THAT(buffer.GetPrefix(), testing::StartsWith("some data")); buffer.RemovePrefix(9); auto more_data = MakeDataAndSize(absl::StrCat("different data", std::string(2048, 'x'))); buffer.Append(std::move(more_data.data), more_data.size); EXPECT_THAT(buffer.GetPrefix(), testing::StartsWith("different data")); } TEST(ChunkedBufferTest, LargeAppends) { ChunkedBuffer buffer; buffer.Append(std::string(500, 'a')); buffer.Append(std::string(2000, 'b')); buffer.Append(std::string(10, 'c')); auto more_data = MakeDataAndSize(std::string(4490, 'd')); buffer.Append(std::move(more_data.data), more_data.size); EXPECT_EQ(500 + 2000 + 10 + 4490, absl::StrJoin(buffer.Read(), "").size()); } TEST(ChunkedBufferTest, RemovePartialPrefix) { ChunkedBuffer buffer; auto data_and_size = MakeDataAndSize(kLoremIpsum); buffer.Append(std::move(data_and_size.data), data_and_size.size); buffer.RemovePrefix(6); EXPECT_THAT(buffer.GetPrefix(), testing::StartsWith("ipsum")); buffer.RemovePrefix(20); EXPECT_THAT(buffer.GetPrefix(), testing::StartsWith(", consectetur")); buffer.Append(" Anday igpay atinlay!"); const std::initializer_list<absl::string_view> parts = { kLoremIpsum.substr(26), " Anday igpay atinlay!"}; EXPECT_EQ(absl::StrJoin(parts, ""), absl::StrJoin(buffer.Read(), "")); } TEST(ChunkedBufferTest, DifferentAppends) { ChunkedBuffer buffer; buffer.Append("Lorem ipsum"); auto more_data = MakeDataAndSize(" dolor sit amet, "); buffer.Append(std::move(more_data.data), more_data.size); buffer.Append("consectetur adipiscing elit, "); more_data = MakeDataAndSize("sed do eiusmod tempor incididunt ut "); buffer.Append(std::move(more_data.data), more_data.size); buffer.Append("labore et dolore magna aliqua."); EXPECT_EQ(kLoremIpsum, absl::StrJoin(buffer.Read(), "")); buffer.RemovePrefix(kLoremIpsum.size()); EXPECT_TRUE(buffer.Empty()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/chunked_buffer.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/chunked_buffer_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
90913fc5-ee46-4fb6-91db-f159b0b8b5f7
cpp
google/quiche
nghttp2_adapter
quiche/http2/adapter/nghttp2_adapter.cc
quiche/http2/adapter/nghttp2_adapter_test.cc
#include "quiche/http2/adapter/nghttp2_adapter.h" #include <cstring> #include <iterator> #include <memory> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/http2/adapter/http2_visitor_interface.h" #include "quiche/http2/adapter/nghttp2.h" #include "quiche/http2/adapter/nghttp2_callbacks.h" #include "quiche/http2/adapter/nghttp2_data_provider.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_endian.h" namespace http2 { namespace adapter { namespace { using ConnectionError = Http2VisitorInterface::ConnectionError; const size_t kFrameHeaderSize = 9; ssize_t DataFrameReadCallback(nghttp2_session* , int32_t stream_id, uint8_t* , size_t length, uint32_t* data_flags, nghttp2_data_source* source, void* ) { NgHttp2Adapter* adapter = reinterpret_cast<NgHttp2Adapter*>(source->ptr); return adapter->DelegateReadCallback(stream_id, length, data_flags); } int DataFrameSendCallback(nghttp2_session* , nghttp2_frame* frame, const uint8_t* framehd, size_t length, nghttp2_data_source* source, void* ) { NgHttp2Adapter* adapter = reinterpret_cast<NgHttp2Adapter*>(source->ptr); return adapter->DelegateSendCallback(frame->hd.stream_id, framehd, length); } } class NgHttp2Adapter::NotifyingMetadataSource : public MetadataSource { public: explicit NotifyingMetadataSource(NgHttp2Adapter* adapter, Http2StreamId stream_id, std::unique_ptr<MetadataSource> source) : adapter_(adapter), stream_id_(stream_id), source_(std::move(source)) {} size_t NumFrames(size_t max_frame_size) const override { return source_->NumFrames(max_frame_size); } std::pair<int64_t, bool> Pack(uint8_t* dest, size_t dest_len) override { const auto result = source_->Pack(dest, dest_len); if (result.first < 0 || result.second) { adapter_->RemovePendingMetadata(stream_id_); } return result; } void OnFailure() override { source_->OnFailure(); adapter_->RemovePendingMetadata(stream_id_); } private: NgHttp2Adapter* const adapter_; const Http2StreamId stream_id_; std::unique_ptr<MetadataSource> source_; }; class NgHttp2Adapter::NotifyingVisitorMetadataSource : public MetadataSource { public: explicit NotifyingVisitorMetadataSource(NgHttp2Adapter* adapter, Http2StreamId stream_id, Http2VisitorInterface& visitor) : adapter_(adapter), stream_id_(stream_id), visitor_(visitor) {} size_t NumFrames(size_t ) const override { QUICHE_LOG(DFATAL) << "Should not be invoked."; return 0; } std::pair<int64_t, bool> Pack(uint8_t* dest, size_t dest_len) override { const auto [packed, end_metadata] = visitor_.PackMetadataForStream(stream_id_, dest, dest_len); if (packed < 0 || end_metadata) { adapter_->RemovePendingMetadata(stream_id_); } return {packed, end_metadata}; } void OnFailure() override { adapter_->RemovePendingMetadata(stream_id_); } private: NgHttp2Adapter* const adapter_; const Http2StreamId stream_id_; Http2VisitorInterface& visitor_; }; std::unique_ptr<NgHttp2Adapter> NgHttp2Adapter::CreateClientAdapter( Http2VisitorInterface& visitor, const nghttp2_option* options) { auto adapter = new NgHttp2Adapter(visitor, Perspective::kClient, options); adapter->Initialize(); return absl::WrapUnique(adapter); } std::unique_ptr<NgHttp2Adapter> NgHttp2Adapter::CreateServerAdapter( Http2VisitorInterface& visitor, const nghttp2_option* options) { auto adapter = new NgHttp2Adapter(visitor, Perspective::kServer, options); adapter->Initialize(); return absl::WrapUnique(adapter); } bool NgHttp2Adapter::IsServerSession() const { int result = nghttp2_session_check_server_session(session_->raw_ptr()); QUICHE_DCHECK_EQ(perspective_ == Perspective::kServer, result > 0); return result > 0; } int64_t NgHttp2Adapter::ProcessBytes(absl::string_view bytes) { const int64_t processed_bytes = session_->ProcessBytes(bytes); if (processed_bytes < 0) { visitor_.OnConnectionError(ConnectionError::kParseError); } return processed_bytes; } void NgHttp2Adapter::SubmitSettings(absl::Span<const Http2Setting> settings) { std::vector<nghttp2_settings_entry> nghttp2_settings; absl::c_transform(settings, std::back_inserter(nghttp2_settings), [](const Http2Setting& setting) { return nghttp2_settings_entry{setting.id, setting.value}; }); nghttp2_submit_settings(session_->raw_ptr(), NGHTTP2_FLAG_NONE, nghttp2_settings.data(), nghttp2_settings.size()); } void NgHttp2Adapter::SubmitPriorityForStream(Http2StreamId stream_id, Http2StreamId parent_stream_id, int weight, bool exclusive) { nghttp2_priority_spec priority_spec; nghttp2_priority_spec_init(&priority_spec, parent_stream_id, weight, static_cast<int>(exclusive)); nghttp2_submit_priority(session_->raw_ptr(), NGHTTP2_FLAG_NONE, stream_id, &priority_spec); } void NgHttp2Adapter::SubmitPing(Http2PingId ping_id) { uint8_t opaque_data[8] = {}; Http2PingId ping_id_to_serialize = quiche::QuicheEndian::HostToNet64(ping_id); std::memcpy(opaque_data, &ping_id_to_serialize, sizeof(Http2PingId)); nghttp2_submit_ping(session_->raw_ptr(), NGHTTP2_FLAG_NONE, opaque_data); } void NgHttp2Adapter::SubmitShutdownNotice() { nghttp2_submit_shutdown_notice(session_->raw_ptr()); } void NgHttp2Adapter::SubmitGoAway(Http2StreamId last_accepted_stream_id, Http2ErrorCode error_code, absl::string_view opaque_data) { nghttp2_submit_goaway(session_->raw_ptr(), NGHTTP2_FLAG_NONE, last_accepted_stream_id, static_cast<uint32_t>(error_code), ToUint8Ptr(opaque_data.data()), opaque_data.size()); } void NgHttp2Adapter::SubmitWindowUpdate(Http2StreamId stream_id, int window_increment) { nghttp2_submit_window_update(session_->raw_ptr(), NGHTTP2_FLAG_NONE, stream_id, window_increment); } void NgHttp2Adapter::SubmitMetadata(Http2StreamId stream_id, size_t max_frame_size, std::unique_ptr<MetadataSource> source) { auto wrapped_source = std::make_unique<NotifyingMetadataSource>( this, stream_id, std::move(source)); const size_t num_frames = wrapped_source->NumFrames(max_frame_size); size_t num_successes = 0; for (size_t i = 1; i <= num_frames; ++i) { const int result = nghttp2_submit_extension(session_->raw_ptr(), kMetadataFrameType, i == num_frames ? kMetadataEndFlag : 0, stream_id, wrapped_source.get()); if (result != 0) { QUICHE_LOG(DFATAL) << "Failed to submit extension frame " << i << " of " << num_frames; break; } ++num_successes; } if (num_successes > 0) { auto [it, _] = stream_metadata_.insert({stream_id, MetadataSourceVec{}}); it->second.push_back(std::move(wrapped_source)); } } void NgHttp2Adapter::SubmitMetadata(Http2StreamId stream_id, size_t num_frames) { auto wrapped_source = std::make_unique<NotifyingVisitorMetadataSource>( this, stream_id, visitor_); size_t num_successes = 0; for (size_t i = 1; i <= num_frames; ++i) { const int result = nghttp2_submit_extension(session_->raw_ptr(), kMetadataFrameType, i == num_frames ? kMetadataEndFlag : 0, stream_id, wrapped_source.get()); if (result != 0) { QUICHE_LOG(DFATAL) << "Failed to submit extension frame " << i << " of " << num_frames; break; } ++num_successes; } if (num_successes > 0) { auto [it, _] = stream_metadata_.insert({stream_id, MetadataSourceVec{}}); it->second.push_back(std::move(wrapped_source)); } } int NgHttp2Adapter::Send() { const int result = nghttp2_session_send(session_->raw_ptr()); if (result != 0) { QUICHE_VLOG(1) << "nghttp2_session_send returned " << result; visitor_.OnConnectionError(ConnectionError::kSendError); } return result; } int NgHttp2Adapter::GetSendWindowSize() const { return session_->GetRemoteWindowSize(); } int NgHttp2Adapter::GetStreamSendWindowSize(Http2StreamId stream_id) const { return nghttp2_session_get_stream_remote_window_size(session_->raw_ptr(), stream_id); } int NgHttp2Adapter::GetStreamReceiveWindowLimit(Http2StreamId stream_id) const { return nghttp2_session_get_stream_effective_local_window_size( session_->raw_ptr(), stream_id); } int NgHttp2Adapter::GetStreamReceiveWindowSize(Http2StreamId stream_id) const { return nghttp2_session_get_stream_local_window_size(session_->raw_ptr(), stream_id); } int NgHttp2Adapter::GetReceiveWindowSize() const { return nghttp2_session_get_local_window_size(session_->raw_ptr()); } int NgHttp2Adapter::GetHpackEncoderDynamicTableSize() const { return nghttp2_session_get_hd_deflate_dynamic_table_size(session_->raw_ptr()); } int NgHttp2Adapter::GetHpackDecoderDynamicTableSize() const { return nghttp2_session_get_hd_inflate_dynamic_table_size(session_->raw_ptr()); } Http2StreamId NgHttp2Adapter::GetHighestReceivedStreamId() const { return nghttp2_session_get_last_proc_stream_id(session_->raw_ptr()); } void NgHttp2Adapter::MarkDataConsumedForStream(Http2StreamId stream_id, size_t num_bytes) { int rc = session_->Consume(stream_id, num_bytes); if (rc != 0) { QUICHE_LOG(ERROR) << "Error " << rc << " marking " << num_bytes << " bytes consumed for stream " << stream_id; } } void NgHttp2Adapter::SubmitRst(Http2StreamId stream_id, Http2ErrorCode error_code) { int status = nghttp2_submit_rst_stream(session_->raw_ptr(), NGHTTP2_FLAG_NONE, stream_id, static_cast<uint32_t>(error_code)); if (status < 0) { QUICHE_LOG(WARNING) << "Reset stream failed: " << stream_id << " with status code " << status; } } int32_t NgHttp2Adapter::SubmitRequest( absl::Span<const Header> headers, std::unique_ptr<DataFrameSource> data_source, bool end_stream, void* stream_user_data) { auto nvs = GetNghttp2Nvs(headers); std::unique_ptr<nghttp2_data_provider> provider; if (data_source != nullptr || !end_stream) { provider = std::make_unique<nghttp2_data_provider>(); provider->source.ptr = this; provider->read_callback = &DataFrameReadCallback; } int32_t stream_id = nghttp2_submit_request(session_->raw_ptr(), nullptr, nvs.data(), nvs.size(), provider.get(), stream_user_data); if (data_source != nullptr) { sources_.emplace(stream_id, std::move(data_source)); } QUICHE_VLOG(1) << "Submitted request with " << nvs.size() << " request headers and user data " << stream_user_data << "; resulted in stream " << stream_id; return stream_id; } int NgHttp2Adapter::SubmitResponse(Http2StreamId stream_id, absl::Span<const Header> headers, std::unique_ptr<DataFrameSource> data_source, bool end_stream) { auto nvs = GetNghttp2Nvs(headers); std::unique_ptr<nghttp2_data_provider> provider; if (data_source != nullptr || !end_stream) { provider = std::make_unique<nghttp2_data_provider>(); provider->source.ptr = this; provider->read_callback = &DataFrameReadCallback; } if (data_source != nullptr) { sources_.emplace(stream_id, std::move(data_source)); } int result = nghttp2_submit_response(session_->raw_ptr(), stream_id, nvs.data(), nvs.size(), provider.get()); QUICHE_VLOG(1) << "Submitted response with " << nvs.size() << " response headers; result = " << result; return result; } int NgHttp2Adapter::SubmitTrailer(Http2StreamId stream_id, absl::Span<const Header> trailers) { auto nvs = GetNghttp2Nvs(trailers); int result = nghttp2_submit_trailer(session_->raw_ptr(), stream_id, nvs.data(), nvs.size()); QUICHE_VLOG(1) << "Submitted trailers with " << nvs.size() << " response trailers; result = " << result; return result; } void NgHttp2Adapter::SetStreamUserData(Http2StreamId stream_id, void* stream_user_data) { nghttp2_session_set_stream_user_data(session_->raw_ptr(), stream_id, stream_user_data); } void* NgHttp2Adapter::GetStreamUserData(Http2StreamId stream_id) { return nghttp2_session_get_stream_user_data(session_->raw_ptr(), stream_id); } bool NgHttp2Adapter::ResumeStream(Http2StreamId stream_id) { return 0 == nghttp2_session_resume_data(session_->raw_ptr(), stream_id); } void NgHttp2Adapter::FrameNotSent(Http2StreamId stream_id, uint8_t frame_type) { if (frame_type == kMetadataFrameType) { RemovePendingMetadata(stream_id); } } void NgHttp2Adapter::RemoveStream(Http2StreamId stream_id) { sources_.erase(stream_id); } ssize_t NgHttp2Adapter::DelegateReadCallback(int32_t stream_id, size_t max_length, uint32_t* data_flags) { auto it = sources_.find(stream_id); if (it == sources_.end()) { return callbacks::VisitorReadCallback(visitor_, stream_id, max_length, data_flags); } else { return callbacks::DataFrameSourceReadCallback(*it->second, max_length, data_flags); } } int NgHttp2Adapter::DelegateSendCallback(int32_t stream_id, const uint8_t* framehd, size_t length) { auto it = sources_.find(stream_id); if (it == sources_.end()) { visitor_.SendDataFrame(stream_id, ToStringView(framehd, kFrameHeaderSize), length); } else { it->second->Send(ToStringView(framehd, kFrameHeaderSize), length); } return 0; } NgHttp2Adapter::NgHttp2Adapter(Http2VisitorInterface& visitor, Perspective perspective, const nghttp2_option* options) : Http2Adapter(visitor), visitor_(visitor), options_(options), perspective_(perspective) {} NgHttp2Adapter::~NgHttp2Adapter() {} void NgHttp2Adapter::Initialize() { nghttp2_option* owned_options = nullptr; if (options_ == nullptr) { nghttp2_option_new(&owned_options); nghttp2_option_set_no_closed_streams(owned_options, 1); nghttp2_option_set_no_auto_window_update(owned_options, 1); nghttp2_option_set_max_send_header_block_length(owned_options, 0x2000000); nghttp2_option_set_max_outbound_ack(owned_options, 10000); nghttp2_option_set_user_recv_extension_type(owned_options, kMetadataFrameType); options_ = owned_options; } session_ = std::make_unique<NgHttp2Session>( perspective_, callbacks::Create(&DataFrameSendCallback), options_, static_cast<void*>(&visitor_)); if (owned_options != nullptr) { nghttp2_option_del(owned_options); } options_ = nullptr; } void NgHttp2Adapter::RemovePendingMetadata(Http2StreamId stream_id) { auto it = stream_metadata_.find(stream_id); if (it != stream_metadata_.end()) { it->second.erase(it->second.begin()); if (it->second.empty()) { stream_metadata_.erase(it); } } } } }
#include "quiche/http2/adapter/nghttp2_adapter.h" #include <memory> #include <string> #include <vector> #include "quiche/http2/adapter/http2_protocol.h" #include "quiche/http2/adapter/http2_visitor_interface.h" #include "quiche/http2/adapter/mock_http2_visitor.h" #include "quiche/http2/adapter/nghttp2.h" #include "quiche/http2/adapter/nghttp2_test_utils.h" #include "quiche/http2/adapter/oghttp2_util.h" #include "quiche/http2/adapter/test_frame_sequence.h" #include "quiche/http2/adapter/test_utils.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace adapter { namespace test { namespace { using ConnectionError = Http2VisitorInterface::ConnectionError; using spdy::SpdyFrameType; using testing::_; enum FrameType { DATA, HEADERS, PRIORITY, RST_STREAM, SETTINGS, PUSH_PROMISE, PING, GOAWAY, WINDOW_UPDATE, CONTINUATION, }; int TestSendCallback(nghttp2_session*, nghttp2_frame* , const uint8_t* framehd, size_t length, nghttp2_data_source* source, void* user_data) { auto* visitor = static_cast<Http2VisitorInterface*>(user_data); ssize_t result = visitor->OnReadyToSend(ToStringView(framehd, 9)); if (result == 0) { return NGHTTP2_ERR_WOULDBLOCK; } auto* test_source = static_cast<TestDataSource*>(source->ptr); absl::string_view payload = test_source->ReadNext(length); visitor->OnReadyToSend(payload); return 0; } TEST(NgHttp2AdapterTest, ClientConstruction) { testing::StrictMock<MockHttp2Visitor> visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); ASSERT_NE(nullptr, adapter); EXPECT_TRUE(adapter->want_read()); EXPECT_FALSE(adapter->want_write()); EXPECT_FALSE(adapter->IsServerSession()); } TEST(NgHttp2AdapterTest, ClientHandlesFrames) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), testing::StrEq(spdy::kHttp2ConnectionHeaderPrefix)); visitor.Clear(); EXPECT_EQ(0, adapter->GetHighestReceivedStreamId()); const std::string initial_frames = TestFrameSequence() .ServerPreface() .Ping(42) .WindowUpdate(0, 1000) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, 8, PING, 0)); EXPECT_CALL(visitor, OnPing(42, false)); EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(0, 1000)); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), initial_result); EXPECT_EQ(adapter->GetSendWindowSize(), kInitialFlowControlWindowSize + 1000); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(PING, 0, 8, 0x1)); EXPECT_CALL(visitor, OnFrameSent(PING, 0, 8, 0x1, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::PING})); visitor.Clear(); const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const std::vector<Header> headers2 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}); const std::vector<Header> headers3 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/three"}}); const char* kSentinel1 = "arbitrary pointer 1"; const char* kSentinel3 = "arbitrary pointer 3"; const int32_t stream_id1 = adapter->SubmitRequest( headers1, nullptr, true, const_cast<char*>(kSentinel1)); ASSERT_GT(stream_id1, 0); QUICHE_LOG(INFO) << "Created stream: " << stream_id1; const int32_t stream_id2 = adapter->SubmitRequest(headers2, nullptr, true, nullptr); ASSERT_GT(stream_id2, 0); QUICHE_LOG(INFO) << "Created stream: " << stream_id2; const int32_t stream_id3 = adapter->SubmitRequest( headers3, nullptr, true, const_cast<char*>(kSentinel3)); ASSERT_GT(stream_id3, 0); QUICHE_LOG(INFO) << "Created stream: " << stream_id3; const char* kSentinel2 = "arbitrary pointer 2"; adapter->SetStreamUserData(stream_id2, const_cast<char*>(kSentinel2)); adapter->SetStreamUserData(stream_id3, nullptr); EXPECT_EQ(adapter->sources_size(), 0); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id2, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id2, _, 0x5, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id3, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id3, _, 0x5, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::HEADERS, SpdyFrameType::HEADERS})); visitor.Clear(); EXPECT_EQ(kInitialFlowControlWindowSize, adapter->GetStreamReceiveWindowSize(stream_id1)); EXPECT_EQ(kInitialFlowControlWindowSize, adapter->GetStreamReceiveWindowSize(stream_id2)); EXPECT_EQ(kInitialFlowControlWindowSize, adapter->GetStreamReceiveWindowSize(stream_id3)); EXPECT_EQ(kInitialFlowControlWindowSize, adapter->GetStreamReceiveWindowLimit(stream_id1)); EXPECT_EQ(kInitialFlowControlWindowSize, adapter->GetReceiveWindowSize()); EXPECT_EQ(0, adapter->GetHighestReceivedStreamId()); EXPECT_EQ(kSentinel1, adapter->GetStreamUserData(stream_id1)); EXPECT_EQ(kSentinel2, adapter->GetStreamUserData(stream_id2)); EXPECT_EQ(nullptr, adapter->GetStreamUserData(stream_id3)); EXPECT_EQ(0, adapter->GetHpackDecoderDynamicTableSize()); const std::string stream_frames = TestFrameSequence() .Headers(1, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, false) .Data(1, "This is the response body.") .RstStream(3, Http2ErrorCode::INTERNAL_ERROR) .GoAway(5, Http2ErrorCode::ENHANCE_YOUR_CALM, "calm down!!") .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200")); EXPECT_CALL(visitor, OnHeaderForStream(1, "server", "my-fake-server")); EXPECT_CALL(visitor, OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, 26, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 26)); EXPECT_CALL(visitor, OnDataForStream(1, "This is the response body.")); EXPECT_CALL(visitor, OnFrameHeader(3, 4, RST_STREAM, 0)); EXPECT_CALL(visitor, OnRstStream(3, Http2ErrorCode::INTERNAL_ERROR)); EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::INTERNAL_ERROR)) .WillOnce( [&adapter](Http2StreamId stream_id, Http2ErrorCode ) { adapter->RemoveStream(stream_id); return true; }); EXPECT_CALL(visitor, OnFrameHeader(0, 19, GOAWAY, 0)); EXPECT_CALL(visitor, OnGoAway(5, Http2ErrorCode::ENHANCE_YOUR_CALM, "calm down!!")); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), stream_result); EXPECT_GT(kInitialFlowControlWindowSize, adapter->GetStreamReceiveWindowSize(stream_id1)); EXPECT_EQ(-1, adapter->GetStreamReceiveWindowSize(stream_id2)); EXPECT_EQ(kInitialFlowControlWindowSize, adapter->GetStreamReceiveWindowSize(stream_id3)); EXPECT_EQ(adapter->GetReceiveWindowSize(), adapter->GetStreamReceiveWindowSize(stream_id1)); EXPECT_EQ(kInitialFlowControlWindowSize, adapter->GetStreamReceiveWindowLimit(stream_id1)); EXPECT_GT(adapter->GetHpackDecoderDynamicTableSize(), 0); EXPECT_EQ(0, adapter->GetHighestReceivedStreamId()); EXPECT_TRUE(adapter->want_read()); EXPECT_CALL(visitor, OnFrameHeader(1, 0, DATA, 1)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 0)); EXPECT_CALL(visitor, OnEndStream(1)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)) .WillOnce( [&adapter](Http2StreamId stream_id, Http2ErrorCode ) { adapter->RemoveStream(stream_id); return true; }); EXPECT_CALL(visitor, OnFrameHeader(5, 4, RST_STREAM, 0)); EXPECT_CALL(visitor, OnRstStream(5, Http2ErrorCode::REFUSED_STREAM)); EXPECT_CALL(visitor, OnCloseStream(5, Http2ErrorCode::REFUSED_STREAM)) .WillOnce( [&adapter](Http2StreamId stream_id, Http2ErrorCode ) { adapter->RemoveStream(stream_id); return true; }); adapter->ProcessBytes(TestFrameSequence() .Data(1, "", true) .RstStream(5, Http2ErrorCode::REFUSED_STREAM) .Serialize()); EXPECT_EQ(0, adapter->GetHighestReceivedStreamId()); EXPECT_FALSE(adapter->want_read()); EXPECT_FALSE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), testing::IsEmpty()); } TEST(NgHttp2AdapterTest, QueuingWindowUpdateAffectsWindow) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); EXPECT_EQ(adapter->GetReceiveWindowSize(), kInitialFlowControlWindowSize); adapter->SubmitWindowUpdate(0, 10000); EXPECT_EQ(adapter->GetReceiveWindowSize(), kInitialFlowControlWindowSize + 10000); const std::vector<Header> headers = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr); EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 0, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 0, 4, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x5, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id), kInitialFlowControlWindowSize); adapter->SubmitWindowUpdate(1, 20000); EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id), kInitialFlowControlWindowSize + 20000); } TEST(NgHttp2AdapterTest, AckOfSettingInitialWindowSizeAffectsWindow) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); testing::InSequence s; const std::vector<Header> headers = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id1 = adapter->SubmitRequest(headers, nullptr, true, nullptr); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); const std::string initial_frames = TestFrameSequence().ServerPreface().Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0x0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); int64_t parse_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), static_cast<size_t>(parse_result)); EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id1), kInitialFlowControlWindowSize); adapter->SubmitSettings({{INITIAL_WINDOW_SIZE, 80000u}}); EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id1), kInitialFlowControlWindowSize); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id1), kInitialFlowControlWindowSize); const std::string settings_ack = TestFrameSequence().SettingsAck().Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0x1)); EXPECT_CALL(visitor, OnSettingsAck); parse_result = adapter->ProcessBytes(settings_ack); EXPECT_EQ(settings_ack.size(), static_cast<size_t>(parse_result)); EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id1), 80000); const std::vector<Header> headers2 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}); const int32_t stream_id2 = adapter->SubmitRequest(headers, nullptr, true, nullptr); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id2, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id2, _, 0x5, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id2), 80000); } TEST(NgHttp2AdapterTest, ClientRejects100HeadersWithFin) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id1 = adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); QUICHE_LOG(INFO) << "Created stream: " << stream_id1; EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "100"}}, false) .Headers(1, {{":status", "100"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "100")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "100")); EXPECT_CALL(visitor, OnInvalidFrame( 1, Http2VisitorInterface::InvalidFrameError::kHttpMessaging)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, 1)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST(NgHttp2AdapterTest, ClientRejects100HeadersWithContent) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id1 = adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "100"}}, false) .Data(1, "We needed the final headers before data, whoops") .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "100")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, _)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST(NgHttp2AdapterTest, ClientRejects100HeadersWithContentLength) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id1 = adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "100"}, {"content-length", "42"}}, false) .Headers(1, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "100")); EXPECT_CALL( visitor, OnErrorDebug("Invalid HTTP header field was received: frame type: 1, " "stream: 1, name: [content-length], value: [42]")); EXPECT_CALL( visitor, OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } class ResponseCompleteBeforeRequestTest : public quiche::test::QuicheTestWithParam<std::tuple<bool, bool>> { public: bool HasTrailers() const { return std::get<0>(GetParam()); } bool HasRstStream() const { return std::get<1>(GetParam()); } }; INSTANTIATE_TEST_SUITE_P(TrailersAndRstStreamAllCombinations, ResponseCompleteBeforeRequestTest, testing::Combine(testing::Bool(), testing::Bool())); TEST_P(ResponseCompleteBeforeRequestTest, ClientHandlesResponseBeforeRequestComplete) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "POST"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); adapter->SubmitSettings({}); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); const int32_t stream_id1 = adapter->SubmitRequest(headers1, std::move(body1), false, nullptr); ASSERT_GT(stream_id1, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, END_HEADERS_FLAG, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); visitor.Clear(); TestFrameSequence response; response.ServerPreface() .Headers(1, {{":status", "200"}, {"content-length", "2"}}, false) .Data(1, "hi", !HasTrailers(), 10); if (HasTrailers()) { response.Headers(1, {{"my-weird-trailer", "has a value"}}, true); } if (HasRstStream()) { response.RstStream(1, Http2ErrorCode::HTTP2_NO_ERROR); } const std::string stream_frames = response.Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200")); EXPECT_CALL(visitor, OnHeaderForStream(1, "content-length", "2")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, 2 + 10, DATA, HasTrailers() ? 0x8 : 0x9)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 2 + 10)); EXPECT_CALL(visitor, OnDataForStream(1, "hi")); EXPECT_CALL(visitor, OnDataPaddingLength(1, 10)); if (HasTrailers()) { EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, "my-weird-trailer", "has a value")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); } EXPECT_CALL(visitor, OnEndStream(1)); if (HasRstStream()) { EXPECT_CALL(visitor, OnFrameHeader(1, _, RST_STREAM, 0)); EXPECT_CALL(visitor, OnRstStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); } const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({ SpdyFrameType::SETTINGS, })); if (!HasRstStream()) { visitor.AppendPayloadForStream(1, "final fragment"); } visitor.SetEndData(1, true); adapter->ResumeStream(1); if (!HasRstStream()) { EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, END_STREAM_FLAG, 0)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); } result = adapter->Send(); EXPECT_EQ(0, result); } TEST(NgHttp2AdapterTest, ClientHandles204WithContent) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id1 = adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); const std::vector<Header> headers2 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}); const int32_t stream_id2 = adapter->SubmitRequest(headers2, nullptr, true, nullptr); ASSERT_GT(stream_id2, stream_id1); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id2, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id2, _, 0x5, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "204"}, {"content-length", "2"}}, false) .Data(1, "hi") .Headers(3, {{":status", "204"}}, false) .Data(3, "hi") .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "204")); EXPECT_CALL( visitor, OnErrorDebug("Invalid HTTP header field was received: frame type: 1, " "stream: 1, name: [content-length], value: [2]")); EXPECT_CALL( visitor, OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, ":status", "204")); EXPECT_CALL(visitor, OnEndHeadersForStream(3)); EXPECT_CALL(visitor, OnFrameHeader(3, _, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(3, 2)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 3, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 3, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::PROTOCOL_ERROR)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM, SpdyFrameType::RST_STREAM})); } TEST(NgHttp2AdapterTest, ClientHandles304WithContent) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id1 = adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "304"}, {"content-length", "2"}}, false) .Data(1, "hi") .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "304")); EXPECT_CALL(visitor, OnHeaderForStream(1, "content-length", "2")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 2)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST(NgHttp2AdapterTest, ClientHandles304WithContentLength) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); testing::InSequence s; const std::vector<Header> headers = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr); ASSERT_GT(stream_id, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x5, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "304"}, {"content-length", "2"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "304")); EXPECT_CALL(visitor, OnHeaderForStream(1, "content-length", "2")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); } TEST(NgHttp2AdapterTest, ClientHandlesTrailers) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const char* kSentinel1 = "arbitrary pointer 1"; const int32_t stream_id1 = adapter->SubmitRequest( headers1, nullptr, true, const_cast<char*>(kSentinel1)); ASSERT_GT(stream_id1, 0); QUICHE_LOG(INFO) << "Created stream: " << stream_id1; EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS})); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, false) .Data(1, "This is the response body.") .Headers(1, {{"final-status", "A-OK"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200")); EXPECT_CALL(visitor, OnHeaderForStream(1, "server", "my-fake-server")); EXPECT_CALL(visitor, OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, 26, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 26)); EXPECT_CALL(visitor, OnDataForStream(1, "This is the response body.")); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, "final-status", "A-OK")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), stream_result); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); } class NgHttp2AdapterDataTest : public quiche::test::QuicheTestWithParam<bool> { }; INSTANTIATE_TEST_SUITE_P(BothValues, NgHttp2AdapterDataTest, testing::Bool()); TEST_P(NgHttp2AdapterDataTest, ClientSendsTrailers) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const Http2StreamId kStreamId = 1; const std::string kBody = "This is an example request body."; visitor.AppendPayloadForStream(kStreamId, kBody); visitor.SetEndData(kStreamId, false); auto body1 = std::make_unique<VisitorDataSource>(visitor, kStreamId); const int32_t stream_id1 = adapter->SubmitRequest( headers1, GetParam() ? nullptr : std::move(body1), false, nullptr); ASSERT_GT(stream_id1, 0); EXPECT_EQ(stream_id1, kStreamId); EXPECT_EQ(adapter->sources_size(), GetParam() ? 0 : 1); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id1, _, 0x0, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::DATA})); visitor.Clear(); const std::vector<Header> trailers1 = ToHeaders({{"extra-info", "Trailers are weird but good?"}}); adapter->SubmitTrailer(stream_id1, trailers1); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0)); result = adapter->Send(); EXPECT_EQ(0, result); data = visitor.data(); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS})); } TEST(NgHttp2AdapterTest, ClientHandlesMetadata) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const char* kSentinel1 = "arbitrary pointer 1"; const int32_t stream_id1 = adapter->SubmitRequest( headers1, nullptr, true, const_cast<char*>(kSentinel1)); ASSERT_GT(stream_id1, 0); QUICHE_LOG(INFO) << "Created stream: " << stream_id1; EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS})); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Metadata(0, "Example connection metadata") .Headers(1, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, false) .Metadata(1, "Example stream metadata") .Data(1, "This is the response body.", true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, _, kMetadataFrameType, 4)); EXPECT_CALL(visitor, OnBeginMetadataForStream(0, _)); EXPECT_CALL(visitor, OnMetadataForStream(0, _)); EXPECT_CALL(visitor, OnMetadataEndForStream(0)); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200")); EXPECT_CALL(visitor, OnHeaderForStream(1, "server", "my-fake-server")); EXPECT_CALL(visitor, OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, kMetadataFrameType, 4)); EXPECT_CALL(visitor, OnBeginMetadataForStream(1, _)); EXPECT_CALL(visitor, OnMetadataForStream(1, _)); EXPECT_CALL(visitor, OnMetadataEndForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, 26, DATA, 1)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 26)); EXPECT_CALL(visitor, OnDataForStream(1, "This is the response body.")); EXPECT_CALL(visitor, OnEndStream(1)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), stream_result); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); } TEST(NgHttp2AdapterTest, ClientHandlesMetadataWithEmptyPayload) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id = adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x5, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS})); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, false) .Metadata(1, "") .Data(1, "This is the response body.", true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(3); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, kMetadataFrameType, 4)); EXPECT_CALL(visitor, OnBeginMetadataForStream(1, _)); EXPECT_CALL(visitor, OnMetadataEndForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 1)); EXPECT_CALL(visitor, OnBeginDataForStream(1, _)); EXPECT_CALL(visitor, OnDataForStream(1, "This is the response body.")); EXPECT_CALL(visitor, OnEndStream(1)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); } TEST(NgHttp2AdapterTest, ClientHandlesMetadataWithError) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const char* kSentinel1 = "arbitrary pointer 1"; const int32_t stream_id1 = adapter->SubmitRequest( headers1, nullptr, true, const_cast<char*>(kSentinel1)); ASSERT_GT(stream_id1, 0); QUICHE_LOG(INFO) << "Created stream: " << stream_id1; EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Metadata(0, "Example connection metadata") .Headers(1, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, false) .Metadata(1, "Example stream metadata") .Data(1, "This is the response body.", true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, _, kMetadataFrameType, 4)); EXPECT_CALL(visitor, OnBeginMetadataForStream(0, _)); EXPECT_CALL(visitor, OnMetadataForStream(0, _)); EXPECT_CALL(visitor, OnMetadataEndForStream(0)); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200")); EXPECT_CALL(visitor, OnHeaderForStream(1, "server", "my-fake-server")); EXPECT_CALL(visitor, OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, kMetadataFrameType, 4)); EXPECT_CALL(visitor, OnBeginMetadataForStream(1, _)); EXPECT_CALL(visitor, OnMetadataForStream(1, _)) .WillOnce(testing::Return(false)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kParseError)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_result, NGHTTP2_ERR_CALLBACK_FAILURE); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_TRUE(adapter->want_write()); EXPECT_TRUE(adapter->want_read()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); } TEST(NgHttp2AdapterTest, ClientHandlesHpackHeaderTableSetting) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({ {":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"x-i-do-not-like", "green eggs and ham"}, {"x-i-will-not-eat-them", "here or there, in a box, with a fox"}, {"x-like-them-in-a-house", "no"}, {"x-like-them-with-a-mouse", "no"}, }); const int32_t stream_id1 = adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); visitor.Clear(); EXPECT_GT(adapter->GetHpackEncoderDynamicTableSize(), 100); const std::string stream_frames = TestFrameSequence().Settings({{HEADER_TABLE_SIZE, 100u}}).Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSetting(Http2Setting{HEADER_TABLE_SIZE, 100u})); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), stream_result); EXPECT_LE(adapter->GetHpackEncoderDynamicTableSize(), 100); } TEST(NgHttp2AdapterTest, ClientHandlesInvalidTrailers) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const char* kSentinel1 = "arbitrary pointer 1"; const int32_t stream_id1 = adapter->SubmitRequest( headers1, nullptr, true, const_cast<char*>(kSentinel1)); ASSERT_GT(stream_id1, 0); QUICHE_LOG(INFO) << "Created stream: " << stream_id1; EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS})); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, false) .Data(1, "This is the response body.") .Headers(1, {{":bad-status", "9000"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200")); EXPECT_CALL(visitor, OnHeaderForStream(1, "server", "my-fake-server")); EXPECT_CALL(visitor, OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, 26, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 26)); EXPECT_CALL(visitor, OnDataForStream(1, "This is the response body.")); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL( visitor, OnErrorDebug("Invalid HTTP header field was received: frame type: 1, " "stream: 1, name: [:bad-status], value: [9000]")); EXPECT_CALL( visitor, OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), stream_result); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, stream_id1, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, stream_id1, 4, 0x0, 1)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST(NgHttp2AdapterTest, ClientRstStreamWhileHandlingHeaders) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const char* kSentinel1 = "arbitrary pointer 1"; const int32_t stream_id1 = adapter->SubmitRequest( headers1, nullptr, true, const_cast<char*>(kSentinel1)); ASSERT_GT(stream_id1, 0); QUICHE_LOG(INFO) << "Created stream: " << stream_id1; EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS})); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, false) .Data(1, "This is the response body.") .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200")); EXPECT_CALL(visitor, OnHeaderForStream(1, "server", "my-fake-server")); EXPECT_CALL(visitor, OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT")) .WillOnce(testing::DoAll( testing::InvokeWithoutArgs([&adapter]() { adapter->SubmitRst(1, Http2ErrorCode::REFUSED_STREAM); }), testing::Return(Http2VisitorInterface::HEADER_RST_STREAM))); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), stream_result); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, stream_id1, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, stream_id1, 4, 0x0, static_cast<int>(Http2ErrorCode::REFUSED_STREAM))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::REFUSED_STREAM)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST(NgHttp2AdapterTest, ClientConnectionErrorWhileHandlingHeaders) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const char* kSentinel1 = "arbitrary pointer 1"; const int32_t stream_id1 = adapter->SubmitRequest( headers1, nullptr, true, const_cast<char*>(kSentinel1)); ASSERT_GT(stream_id1, 0); QUICHE_LOG(INFO) << "Created stream: " << stream_id1; EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS})); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, false) .Data(1, "This is the response body.") .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200")); EXPECT_CALL(visitor, OnHeaderForStream(1, "server", "my-fake-server")); EXPECT_CALL(visitor, OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT")) .WillOnce( testing::Return(Http2VisitorInterface::HEADER_CONNECTION_ERROR)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kParseError)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(-902 , stream_result); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); } TEST(NgHttp2AdapterTest, ClientConnectionErrorWhileHandlingHeadersOnly) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const char* kSentinel1 = "arbitrary pointer 1"; const int32_t stream_id1 = adapter->SubmitRequest( headers1, nullptr, true, const_cast<char*>(kSentinel1)); ASSERT_GT(stream_id1, 0); QUICHE_LOG(INFO) << "Created stream: " << stream_id1; EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS})); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200")); EXPECT_CALL(visitor, OnHeaderForStream(1, "server", "my-fake-server")); EXPECT_CALL(visitor, OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT")) .WillOnce( testing::Return(Http2VisitorInterface::HEADER_CONNECTION_ERROR)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kParseError)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(-902 , stream_result); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); } TEST(NgHttp2AdapterTest, ClientRejectsHeaders) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const char* kSentinel1 = "arbitrary pointer 1"; const int32_t stream_id1 = adapter->SubmitRequest( headers1, nullptr, true, const_cast<char*>(kSentinel1)); ASSERT_GT(stream_id1, 0); QUICHE_LOG(INFO) << "Created stream: " << stream_id1; EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS})); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, false) .Data(1, "This is the response body.") .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)) .WillOnce(testing::Return(false)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kParseError)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(NGHTTP2_ERR_CALLBACK_FAILURE, stream_result); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); } TEST(NgHttp2AdapterTest, ClientStartsShutdown) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); EXPECT_FALSE(adapter->want_write()); adapter->SubmitShutdownNotice(); EXPECT_FALSE(adapter->want_write()); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_EQ(visitor.data(), spdy::kHttp2ConnectionHeaderPrefix); } TEST(NgHttp2AdapterTest, ClientReceivesGoAway) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id1 = adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); const std::vector<Header> headers2 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}); const int32_t stream_id2 = adapter->SubmitRequest(headers2, nullptr, true, nullptr); ASSERT_GT(stream_id2, stream_id1); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id2, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id2, _, 0x5, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::HEADERS})); visitor.Clear(); adapter->SubmitWindowUpdate(3, 42); const std::string stream_frames = TestFrameSequence() .ServerPreface() .RstStream(1, Http2ErrorCode::ENHANCE_YOUR_CALM) .GoAway(1, Http2ErrorCode::INTERNAL_ERROR, "indigestion") .WindowUpdate(0, 42) .WindowUpdate(1, 42) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, 4, RST_STREAM, 0)); EXPECT_CALL(visitor, OnRstStream(1, Http2ErrorCode::ENHANCE_YOUR_CALM)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::ENHANCE_YOUR_CALM)); EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0)); EXPECT_CALL(visitor, OnGoAway(1, Http2ErrorCode::INTERNAL_ERROR, "indigestion")); EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::REFUSED_STREAM)); EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(0, 42)); EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), stream_result); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); } TEST(NgHttp2AdapterTest, ClientReceivesMultipleGoAways) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id1 = adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS})); visitor.Clear(); const std::string initial_frames = TestFrameSequence() .ServerPreface() .GoAway(kMaxStreamId, Http2ErrorCode::INTERNAL_ERROR, "indigestion") .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0)); EXPECT_CALL(visitor, OnGoAway(kMaxStreamId, Http2ErrorCode::INTERNAL_ERROR, "indigestion")); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), static_cast<size_t>(initial_result)); adapter->SubmitWindowUpdate(1, 42); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 1, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 1, 4, 0x0, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::WINDOW_UPDATE})); visitor.Clear(); const std::string final_frames = TestFrameSequence() .GoAway(0, Http2ErrorCode::INTERNAL_ERROR, "indigestion") .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0)); EXPECT_CALL(visitor, OnGoAway(0, Http2ErrorCode::INTERNAL_ERROR, "indigestion")); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::REFUSED_STREAM)); const int64_t final_result = adapter->ProcessBytes(final_frames); EXPECT_EQ(final_frames.size(), static_cast<size_t>(final_result)); EXPECT_FALSE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), testing::IsEmpty()); } TEST(NgHttp2AdapterTest, ClientReceivesMultipleGoAwaysWithIncreasingStreamId) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id1 = adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS})); visitor.Clear(); auto source = std::make_unique<TestMetadataSource>(ToHeaderBlock(ToHeaders( {{"query-cost", "is too darn high"}, {"secret-sauce", "hollandaise"}}))); adapter->SubmitMetadata(stream_id1, 16384u, std::move(source)); const std::string frames = TestFrameSequence() .ServerPreface() .GoAway(0, Http2ErrorCode::HTTP2_NO_ERROR, "") .GoAway(0, Http2ErrorCode::ENHANCE_YOUR_CALM, "") .GoAway(1, Http2ErrorCode::INTERNAL_ERROR, "") .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0)); EXPECT_CALL(visitor, OnGoAway(0, Http2ErrorCode::HTTP2_NO_ERROR, "")); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::REFUSED_STREAM)); EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0)); EXPECT_CALL(visitor, OnGoAway(0, Http2ErrorCode::ENHANCE_YOUR_CALM, "")); EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0)); EXPECT_CALL( visitor, OnInvalidFrame(0, Http2VisitorInterface::InvalidFrameError::kProtocol)); const int64_t frames_result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(frames_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY})); } TEST(NgHttp2AdapterTest, ClientReceivesGoAwayWithPendingStreams) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), testing::StrEq(spdy::kHttp2ConnectionHeaderPrefix)); visitor.Clear(); testing::InSequence s; const std::string initial_frames = TestFrameSequence() .ServerPreface({{MAX_CONCURRENT_STREAMS, 1}}) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSetting); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), initial_result); const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id1 = adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); const std::vector<Header> headers2 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}); const int32_t stream_id2 = adapter->SubmitRequest(headers2, nullptr, true, nullptr); ASSERT_GT(stream_id2, stream_id1); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .GoAway(kMaxStreamId, Http2ErrorCode::INTERNAL_ERROR, "indigestion") .Settings({{MAX_CONCURRENT_STREAMS, 42u}}) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0)); EXPECT_CALL(visitor, OnGoAway(kMaxStreamId, Http2ErrorCode::INTERNAL_ERROR, "indigestion")); EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSetting(Http2Setting{MAX_CONCURRENT_STREAMS, 42u})); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), stream_result); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::REFUSED_STREAM)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); visitor.Clear(); const std::vector<Header> headers3 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/three"}}); const int32_t stream_id3 = adapter->SubmitRequest(headers3, nullptr, true, nullptr); ASSERT_GT(stream_id3, stream_id2); EXPECT_CALL(visitor, OnCloseStream(5, Http2ErrorCode::REFUSED_STREAM)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), testing::IsEmpty()); EXPECT_FALSE(adapter->want_write()); } TEST(NgHttp2AdapterTest, ClientFailsOnGoAway) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const char* kSentinel1 = "arbitrary pointer 1"; const int32_t stream_id1 = adapter->SubmitRequest( headers1, nullptr, true, const_cast<char*>(kSentinel1)); ASSERT_GT(stream_id1, 0); QUICHE_LOG(INFO) << "Created stream: " << stream_id1; EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS})); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, false) .GoAway(1, Http2ErrorCode::INTERNAL_ERROR, "indigestion") .Data(1, "This is the response body.") .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200")); EXPECT_CALL(visitor, OnHeaderForStream(1, "server", "my-fake-server")); EXPECT_CALL(visitor, OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0)); EXPECT_CALL(visitor, OnGoAway(1, Http2ErrorCode::INTERNAL_ERROR, "indigestion")) .WillOnce(testing::Return(false)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kParseError)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(NGHTTP2_ERR_CALLBACK_FAILURE, stream_result); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); } TEST(NgHttp2AdapterTest, ClientRejects101Response) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"upgrade", "new-protocol"}}); const int32_t stream_id1 = adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS})); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "101"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, false) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL( visitor, OnErrorDebug("Invalid HTTP header field was received: frame type: 1, " "stream: 1, name: [:status], value: [101]")); EXPECT_CALL( visitor, OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(static_cast<int64_t>(stream_frames.size()), stream_result); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, 4, 0x0)); EXPECT_CALL( visitor, OnFrameSent(RST_STREAM, 1, 4, 0x0, static_cast<uint32_t>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST_P(NgHttp2AdapterDataTest, ClientSubmitRequest) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), testing::StrEq(spdy::kHttp2ConnectionHeaderPrefix)); visitor.Clear(); const std::string initial_frames = TestFrameSequence().ServerPreface().Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), initial_result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); visitor.Clear(); EXPECT_EQ(0, adapter->GetHpackEncoderDynamicTableSize()); EXPECT_FALSE(adapter->want_write()); const char* kSentinel = ""; const absl::string_view kBody = "This is an example request body."; visitor.AppendPayloadForStream(1, kBody); visitor.SetEndData(1, true); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); int stream_id = adapter->SubmitRequest(ToHeaders({{":method", "POST"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}), GetParam() ? nullptr : std::move(body1), false, const_cast<char*>(kSentinel)); ASSERT_EQ(1, stream_id); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, _, 0x1, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_EQ(kInitialFlowControlWindowSize, adapter->GetStreamReceiveWindowSize(stream_id)); EXPECT_EQ(kInitialFlowControlWindowSize, adapter->GetReceiveWindowSize()); EXPECT_EQ(kInitialFlowControlWindowSize, adapter->GetStreamReceiveWindowLimit(stream_id)); EXPECT_GT(adapter->GetHpackEncoderDynamicTableSize(), 0); EXPECT_LT(adapter->GetStreamSendWindowSize(stream_id), kInitialFlowControlWindowSize); EXPECT_GT(adapter->GetStreamSendWindowSize(stream_id), 0); EXPECT_EQ(-1, adapter->GetStreamSendWindowSize(stream_id + 2)); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::DATA})); EXPECT_THAT(visitor.data(), testing::HasSubstr(kBody)); visitor.Clear(); EXPECT_FALSE(adapter->want_write()); stream_id = adapter->SubmitRequest(ToHeaders({{":method", "POST"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}), nullptr, true, nullptr); EXPECT_GT(stream_id, 0); EXPECT_TRUE(adapter->want_write()); const char* kSentinel2 = "arbitrary pointer 2"; EXPECT_EQ(nullptr, adapter->GetStreamUserData(stream_id)); adapter->SetStreamUserData(stream_id, const_cast<char*>(kSentinel2)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x5, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS})); EXPECT_EQ(kSentinel2, adapter->GetStreamUserData(stream_id)); EXPECT_EQ(adapter->GetStreamSendWindowSize(stream_id), kInitialFlowControlWindowSize); } TEST(NgHttp2AdapterTest, ClientSubmitRequestWithDataProvider) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), testing::StrEq(spdy::kHttp2ConnectionHeaderPrefix)); visitor.Clear(); const std::string initial_frames = TestFrameSequence().ServerPreface().Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), initial_result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); visitor.Clear(); EXPECT_FALSE(adapter->want_write()); const absl::string_view kBody = "This is an example request body."; TestDataSource body1{kBody}; nghttp2_data_provider provider = body1.MakeDataProvider(); nghttp2_send_data_callback send_callback = &TestSendCallback; std::unique_ptr<DataFrameSource> frame_source = MakeZeroCopyDataFrameSource(provider, &visitor, std::move(send_callback)); int stream_id = adapter->SubmitRequest(ToHeaders({{":method", "POST"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}), std::move(frame_source), false, nullptr); EXPECT_GT(stream_id, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, _, 0x1, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::DATA})); EXPECT_THAT(visitor.data(), testing::HasSubstr(kBody)); EXPECT_FALSE(adapter->want_write()); } TEST(NgHttp2AdapterTest, ClientSubmitRequestWithDataProviderAndReadBlock) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); const absl::string_view kBody = "This is an example request body."; TestDataSource body1{kBody}; body1.set_is_data_available(false); nghttp2_data_provider provider = body1.MakeDataProvider(); nghttp2_send_data_callback send_callback = &TestSendCallback; std::unique_ptr<DataFrameSource> frame_source = MakeZeroCopyDataFrameSource(provider, &visitor, std::move(send_callback)); int stream_id = adapter->SubmitRequest(ToHeaders({{":method", "POST"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}), std::move(frame_source), false, nullptr); EXPECT_GT(stream_id, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view serialized = visitor.data(); EXPECT_THAT(serialized, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::HEADERS})); visitor.Clear(); EXPECT_FALSE(adapter->want_write()); body1.set_is_data_available(true); EXPECT_TRUE(adapter->ResumeStream(stream_id)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, _, 0x1, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::DATA})); EXPECT_FALSE(adapter->want_write()); EXPECT_FALSE(adapter->ResumeStream(stream_id)); EXPECT_FALSE(adapter->want_write()); } TEST(NgHttp2AdapterTest, ClientSubmitRequestEmptyDataWithFin) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); const absl::string_view kEmptyBody = ""; TestDataSource body1{kEmptyBody}; body1.set_is_data_available(false); nghttp2_data_provider provider = body1.MakeDataProvider(); nghttp2_send_data_callback send_callback = &TestSendCallback; std::unique_ptr<DataFrameSource> frame_source = MakeZeroCopyDataFrameSource(provider, &visitor, std::move(send_callback)); int stream_id = adapter->SubmitRequest(ToHeaders({{":method", "POST"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}), std::move(frame_source), false, nullptr); EXPECT_GT(stream_id, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view serialized = visitor.data(); EXPECT_THAT(serialized, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::HEADERS})); visitor.Clear(); EXPECT_FALSE(adapter->want_write()); body1.set_is_data_available(true); EXPECT_TRUE(adapter->ResumeStream(stream_id)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, 0, 0x1, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::DATA})); EXPECT_FALSE(adapter->want_write()); EXPECT_FALSE(adapter->ResumeStream(stream_id)); EXPECT_FALSE(adapter->want_write()); } TEST(NgHttp2AdapterTest, ClientSubmitRequestWithDataProviderAndWriteBlock) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); const absl::string_view kBody = "This is an example request body."; TestDataSource body1{kBody}; nghttp2_data_provider provider = body1.MakeDataProvider(); nghttp2_send_data_callback send_callback = &TestSendCallback; std::unique_ptr<DataFrameSource> frame_source = MakeZeroCopyDataFrameSource(provider, &visitor, std::move(send_callback)); int stream_id = adapter->SubmitRequest(ToHeaders({{":method", "POST"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}), std::move(frame_source), false, nullptr); EXPECT_GT(stream_id, 0); EXPECT_TRUE(adapter->want_write()); visitor.set_is_write_blocked(true); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), testing::IsEmpty()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, _, 0x1, 0)); visitor.set_is_write_blocked(false); result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view serialized = visitor.data(); EXPECT_THAT(serialized, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::DATA})); EXPECT_FALSE(adapter->want_write()); } TEST(NgHttp2AdapterTest, ClientReceivesDataOnClosedStream) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), testing::StrEq(spdy::kHttp2ConnectionHeaderPrefix)); visitor.Clear(); const std::string initial_frames = TestFrameSequence().ServerPreface().Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), initial_result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); visitor.Clear(); int stream_id = adapter->SubmitRequest(ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}), nullptr, true, nullptr); EXPECT_GT(stream_id, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x5, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS})); visitor.Clear(); adapter->SubmitRst(stream_id, Http2ErrorCode::CANCEL); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, stream_id, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, stream_id, _, 0x0, static_cast<int>(Http2ErrorCode::CANCEL))); EXPECT_CALL(visitor, OnCloseStream(stream_id, Http2ErrorCode::CANCEL)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::RST_STREAM})); visitor.Clear(); const std::string response_frames = TestFrameSequence() .Headers(stream_id, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, false) .Data(stream_id, "This is the response body.", true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(stream_id, _, HEADERS, 0x4)); EXPECT_CALL(visitor, OnFrameHeader(stream_id, _, DATA, _)).Times(0); const int64_t response_result = adapter->ProcessBytes(response_frames); EXPECT_EQ(response_frames.size(), response_result); EXPECT_FALSE(adapter->want_write()); } TEST(NgHttp2AdapterTest, ClientQueuesRequests) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); testing::InSequence s; adapter->SubmitSettings({}); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); adapter->Send(); const std::string initial_frames = TestFrameSequence() .ServerPreface({{MAX_CONCURRENT_STREAMS, 2}}) .SettingsAck() .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0x0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSetting(Http2Setting{ Http2KnownSettingsId::MAX_CONCURRENT_STREAMS, 2u})); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0x1)); EXPECT_CALL(visitor, OnSettingsAck()); adapter->ProcessBytes(initial_frames); const std::vector<Header> headers = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/example/request"}}); std::vector<int32_t> stream_ids; int32_t stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr); stream_ids.push_back(stream_id); stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr); stream_ids.push_back(stream_id); stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr); stream_ids.push_back(stream_id); stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr); stream_ids.push_back(stream_id); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_ids[0], _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_ids[0], _, 0x5, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_ids[1], _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_ids[1], _, 0x5, 0)); adapter->Send(); const std::string update_streams = TestFrameSequence().Settings({{MAX_CONCURRENT_STREAMS, 5}}).Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0x0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSetting(Http2Setting{ Http2KnownSettingsId::MAX_CONCURRENT_STREAMS, 5u})); EXPECT_CALL(visitor, OnSettingsEnd()); adapter->ProcessBytes(update_streams); stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr); stream_ids.push_back(stream_id); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_ids[2], _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_ids[2], _, 0x5, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_ids[3], _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_ids[3], _, 0x5, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_ids[4], _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_ids[4], _, 0x5, 0)); adapter->Send(); } TEST(NgHttp2AdapterTest, ClientAcceptsHeadResponseWithContentLength) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); const std::vector<Header> headers = ToHeaders({{":method", "HEAD"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/"}}); const int32_t stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr); testing::InSequence s; EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x5, 0)); adapter->Send(); const std::string initial_frames = TestFrameSequence() .ServerPreface() .Headers(stream_id, {{":status", "200"}, {"content-length", "101"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, _, SETTINGS, 0x0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(stream_id, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(stream_id)); EXPECT_CALL(visitor, OnHeaderForStream).Times(2); EXPECT_CALL(visitor, OnEndHeadersForStream(stream_id)); EXPECT_CALL(visitor, OnEndStream(stream_id)); EXPECT_CALL(visitor, OnCloseStream(stream_id, Http2ErrorCode::HTTP2_NO_ERROR)); adapter->ProcessBytes(initial_frames); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); adapter->Send(); } class MetadataApiTest : public quiche::test::QuicheTestWithParam<bool> {}; INSTANTIATE_TEST_SUITE_P(WithAndWithoutNewApi, MetadataApiTest, testing::Bool()); TEST_P(MetadataApiTest, SubmitMetadata) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); const quiche::HttpHeaderBlock block = ToHeaderBlock(ToHeaders( {{"query-cost", "is too darn high"}, {"secret-sauce", "hollandaise"}})); if (GetParam()) { visitor.AppendMetadataForStream(1, block); adapter->SubmitMetadata(1, 1); } else { auto source = std::make_unique<TestMetadataSource>(block); adapter->SubmitMetadata(1, 16384u, std::move(source)); } EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(kMetadataFrameType, 1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(kMetadataFrameType, 1, _, 0x4, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view serialized = visitor.data(); EXPECT_THAT(serialized, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(serialized, EqualsFrames({static_cast<SpdyFrameType>(kMetadataFrameType)})); EXPECT_FALSE(adapter->want_write()); } size_t DivRoundUp(size_t numerator, size_t denominator) { return numerator / denominator + (numerator % denominator == 0 ? 0 : 1); } TEST_P(MetadataApiTest, SubmitMetadataMultipleFrames) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); const auto kLargeValue = std::string(63 * 1024, 'a'); const quiche::HttpHeaderBlock block = ToHeaderBlock(ToHeaders({{"large-value", kLargeValue}})); if (GetParam()) { visitor.AppendMetadataForStream(1, block); adapter->SubmitMetadata(1, DivRoundUp(kLargeValue.size(), 16384u)); } else { auto source = std::make_unique<TestMetadataSource>(block); adapter->SubmitMetadata(1, 16384u, std::move(source)); } EXPECT_TRUE(adapter->want_write()); testing::InSequence seq; EXPECT_CALL(visitor, OnBeforeFrameSent(kMetadataFrameType, 1, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(kMetadataFrameType, 1, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(kMetadataFrameType, 1, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(kMetadataFrameType, 1, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(kMetadataFrameType, 1, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(kMetadataFrameType, 1, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(kMetadataFrameType, 1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(kMetadataFrameType, 1, _, 0x4, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view serialized = visitor.data(); EXPECT_THAT(serialized, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(serialized, EqualsFrames({static_cast<SpdyFrameType>(kMetadataFrameType), static_cast<SpdyFrameType>(kMetadataFrameType), static_cast<SpdyFrameType>(kMetadataFrameType), static_cast<SpdyFrameType>(kMetadataFrameType)})); EXPECT_FALSE(adapter->want_write()); } TEST_P(MetadataApiTest, SubmitConnectionMetadata) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); const quiche::HttpHeaderBlock block = ToHeaderBlock(ToHeaders( {{"query-cost", "is too darn high"}, {"secret-sauce", "hollandaise"}})); if (GetParam()) { visitor.AppendMetadataForStream(0, block); adapter->SubmitMetadata(0, 1); } else { auto source = std::make_unique<TestMetadataSource>(block); adapter->SubmitMetadata(0, 16384u, std::move(source)); } EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(kMetadataFrameType, 0, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(kMetadataFrameType, 0, _, 0x4, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view serialized = visitor.data(); EXPECT_THAT(serialized, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(serialized, EqualsFrames({static_cast<SpdyFrameType>(kMetadataFrameType)})); EXPECT_FALSE(adapter->want_write()); } TEST_P(MetadataApiTest, ClientSubmitMetadataWithGoaway) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); adapter->SubmitSettings({}); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, _, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, _, _, 0x0, 0)); adapter->Send(); const std::vector<Header> headers = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr); const quiche::HttpHeaderBlock block = ToHeaderBlock(ToHeaders( {{"query-cost", "is too darn high"}, {"secret-sauce", "hollandaise"}})); if (GetParam()) { visitor.AppendMetadataForStream(stream_id, block); adapter->SubmitMetadata(stream_id, 1); } else { auto source = std::make_unique<TestMetadataSource>(block); adapter->SubmitMetadata(stream_id, 16384u, std::move(source)); } EXPECT_TRUE(adapter->want_write()); const std::string initial_frames = TestFrameSequence() .ServerPreface() .GoAway(3, Http2ErrorCode::HTTP2_NO_ERROR, "server shutting down") .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0)); EXPECT_CALL(visitor, OnGoAway(3, Http2ErrorCode::HTTP2_NO_ERROR, _)); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), initial_result); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(kMetadataFrameType, stream_id, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(kMetadataFrameType, stream_id, _, 0x4, 0)); EXPECT_CALL(visitor, OnCloseStream(stream_id, Http2ErrorCode::REFUSED_STREAM)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view serialized = visitor.data(); EXPECT_THAT(serialized, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, static_cast<SpdyFrameType>(kMetadataFrameType)})); EXPECT_FALSE(adapter->want_write()); } TEST_P(MetadataApiTest, ClientSubmitMetadataWithFailureBefore) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); adapter->SubmitSettings({}); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, _, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, _, _, 0x0, 0)); adapter->Send(); const std::vector<Header> headers = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr); const quiche::HttpHeaderBlock block = ToHeaderBlock(ToHeaders( {{"query-cost", "is too darn high"}, {"secret-sauce", "hollandaise"}})); if (GetParam()) { visitor.AppendMetadataForStream(stream_id, block); adapter->SubmitMetadata(stream_id, 1); } else { auto source = std::make_unique<TestMetadataSource>(block); adapter->SubmitMetadata(stream_id, 16384u, std::move(source)); } EXPECT_TRUE(adapter->want_write()); const std::string initial_frames = TestFrameSequence().ServerPreface().Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), initial_result); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(kMetadataFrameType, stream_id, _, 0x4)) .WillOnce(testing::Return(NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE)); EXPECT_CALL(visitor, OnConnectionError( Http2VisitorInterface::ConnectionError::kSendError)); int result = adapter->Send(); EXPECT_EQ(NGHTTP2_ERR_CALLBACK_FAILURE, result); absl::string_view serialized = visitor.data(); EXPECT_THAT(serialized, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS})); } TEST_P(MetadataApiTest, ClientSubmitMetadataWithFailureDuring) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); adapter->SubmitSettings({}); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, _, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, _, _, 0x0, 0)); adapter->Send(); const std::vector<Header> headers = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr); const quiche::HttpHeaderBlock block = ToHeaderBlock( ToHeaders({{"more-than-one-frame", std::string(20000, 'a')}})); if (GetParam()) { visitor.AppendMetadataForStream(stream_id, block); adapter->SubmitMetadata(stream_id, 2); } else { auto source = std::make_unique<TestMetadataSource>(block); adapter->SubmitMetadata(stream_id, 16384u, std::move(source)); } EXPECT_TRUE(adapter->want_write()); const std::string initial_frames = TestFrameSequence().ServerPreface().Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), initial_result); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(kMetadataFrameType, stream_id, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(kMetadataFrameType, stream_id, _, 0x0, 0)) .WillOnce(testing::Return(NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE)); EXPECT_CALL(visitor, OnConnectionError( Http2VisitorInterface::ConnectionError::kSendError)); int result = adapter->Send(); EXPECT_EQ(NGHTTP2_ERR_CALLBACK_FAILURE, result); absl::string_view serialized = visitor.data(); EXPECT_THAT(serialized, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, static_cast<SpdyFrameType>(kMetadataFrameType)})); } TEST_P(MetadataApiTest, ClientSubmitMetadataWithFailureSending) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); adapter->SubmitSettings({}); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, _, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, _, _, 0x0, 0)); adapter->Send(); const std::vector<Header> headers = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr); if (GetParam()) { adapter->SubmitMetadata(stream_id, 2); } else { auto source = std::make_unique<TestMetadataSource>(ToHeaderBlock( ToHeaders({{"more-than-one-frame", std::string(20000, 'a')}}))); source->InjectFailure(); adapter->SubmitMetadata(stream_id, 16384u, std::move(source)); } EXPECT_TRUE(adapter->want_write()); const std::string initial_frames = TestFrameSequence().ServerPreface().Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), initial_result); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnConnectionError( Http2VisitorInterface::ConnectionError::kSendError)); int result = adapter->Send(); EXPECT_EQ(NGHTTP2_ERR_CALLBACK_FAILURE, result); absl::string_view serialized = visitor.data(); EXPECT_THAT(serialized, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(serialized, EqualsFrames({ SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, })); } TEST_P(NgHttp2AdapterDataTest, ClientObeysMaxConcurrentStreams) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), testing::StrEq(spdy::kHttp2ConnectionHeaderPrefix)); visitor.Clear(); const std::string initial_frames = TestFrameSequence() .ServerPreface({{MAX_CONCURRENT_STREAMS, 1}}) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSetting); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), initial_result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); visitor.Clear(); EXPECT_FALSE(adapter->want_write()); const absl::string_view kBody = "This is an example request body."; visitor.AppendPayloadForStream(1, kBody); visitor.SetEndData(1, true); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); const int stream_id = adapter->SubmitRequest( ToHeaders({{":method", "POST"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}), GetParam() ? nullptr : std::move(body1), false, nullptr); EXPECT_GT(stream_id, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, _, 0x1, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::DATA})); EXPECT_THAT(visitor.data(), testing::HasSubstr(kBody)); visitor.Clear(); EXPECT_FALSE(adapter->want_write()); const int next_stream_id = adapter->SubmitRequest(ToHeaders({{":method", "POST"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}), nullptr, true, nullptr); EXPECT_GT(next_stream_id, stream_id); EXPECT_FALSE(adapter->want_write()); const std::string stream_frames = TestFrameSequence() .Headers(stream_id, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, false) .Data(stream_id, "This is the response body.", true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(stream_id, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(stream_id)); EXPECT_CALL(visitor, OnHeaderForStream(stream_id, ":status", "200")); EXPECT_CALL(visitor, OnHeaderForStream(stream_id, "server", "my-fake-server")); EXPECT_CALL(visitor, OnHeaderForStream(stream_id, "date", "Tue, 6 Apr 2021 12:54:01 GMT")); EXPECT_CALL(visitor, OnEndHeadersForStream(stream_id)); EXPECT_CALL(visitor, OnFrameHeader(stream_id, 26, DATA, 0x1)); EXPECT_CALL(visitor, OnBeginDataForStream(stream_id, 26)); EXPECT_CALL(visitor, OnDataForStream(stream_id, "This is the response body.")); EXPECT_CALL(visitor, OnEndStream(stream_id)); EXPECT_CALL(visitor, OnCloseStream(stream_id, Http2ErrorCode::HTTP2_NO_ERROR)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), stream_result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, next_stream_id, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, next_stream_id, _, 0x5, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS})); visitor.Clear(); EXPECT_FALSE(adapter->want_write()); } TEST_P(NgHttp2AdapterDataTest, ClientReceivesInitialWindowSetting) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); const std::string initial_frames = TestFrameSequence() .Settings({{INITIAL_WINDOW_SIZE, 80000u}}) .WindowUpdate(0, 65536) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSetting(Http2Setting{INITIAL_WINDOW_SIZE, 80000u})); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(0, 65536)); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), static_cast<size_t>(initial_result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); int64_t result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view serialized = visitor.data(); EXPECT_THAT(serialized, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::SETTINGS})); visitor.Clear(); const std::string kLongBody = std::string(81000, 'c'); visitor.AppendPayloadForStream(1, kLongBody); visitor.SetEndData(1, true); auto body1 = std::make_unique<VisitorDataSource>(visitor, true); const int stream_id = adapter->SubmitRequest( ToHeaders({{":method", "POST"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}), GetParam() ? nullptr : std::move(body1), false, nullptr); EXPECT_GT(stream_id, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, 16384, 0x0, 0)).Times(4); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, 14464, 0x0, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::DATA, SpdyFrameType::DATA, SpdyFrameType::DATA, SpdyFrameType::DATA, SpdyFrameType::DATA})); } TEST_P(NgHttp2AdapterDataTest, ClientReceivesInitialWindowSettingAfterStreamStart) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); const std::string initial_frames = TestFrameSequence().ServerPreface().WindowUpdate(0, 65536).Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(0, 65536)); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), static_cast<size_t>(initial_result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); int64_t result = adapter->Send(); EXPECT_EQ(0, result); visitor.Clear(); const std::string kLongBody = std::string(81000, 'c'); visitor.AppendPayloadForStream(1, kLongBody); visitor.SetEndData(1, true); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); const int stream_id = adapter->SubmitRequest( ToHeaders({{":method", "POST"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}), GetParam() ? nullptr : std::move(body1), false, nullptr); EXPECT_GT(stream_id, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, 16384, 0x0, 0)).Times(3); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, 16383, 0x0, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::DATA, SpdyFrameType::DATA, SpdyFrameType::DATA, SpdyFrameType::DATA})); visitor.Clear(); EXPECT_FALSE(adapter->want_write()); const std::string settings_frame = TestFrameSequence().Settings({{INITIAL_WINDOW_SIZE, 80000u}}).Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSetting(Http2Setting{INITIAL_WINDOW_SIZE, 80000u})); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t settings_result = adapter->ProcessBytes(settings_frame); EXPECT_EQ(settings_frame.size(), static_cast<size_t>(settings_result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, 14465, 0x0, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::DATA})); } TEST(NgHttp2AdapterTest, InvalidInitialWindowSetting) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); const uint32_t kTooLargeInitialWindow = 1u << 31; const std::string initial_frames = TestFrameSequence() .Settings({{INITIAL_WINDOW_SIZE, kTooLargeInitialWindow}}) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnInvalidFrame( 0, Http2VisitorInterface::InvalidFrameError::kFlowControl)); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), static_cast<size_t>(initial_result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL( visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::FLOW_CONTROL_ERROR))); int64_t result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view serialized = visitor.data(); EXPECT_THAT(serialized, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::GOAWAY})); visitor.Clear(); } TEST(NgHttp2AdapterTest, InitialWindowSettingCausesOverflow) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); testing::InSequence s; const std::vector<Header> headers = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr); ASSERT_GT(stream_id, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x5, 0)); int64_t write_result = adapter->Send(); EXPECT_EQ(0, write_result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS})); visitor.Clear(); const uint32_t kLargeInitialWindow = (1u << 31) - 1; const std::string frames = TestFrameSequence() .ServerPreface() .Headers(stream_id, {{":status", "200"}}, false) .WindowUpdate(stream_id, 65536u) .Settings({{INITIAL_WINDOW_SIZE, kLargeInitialWindow}}) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(stream_id, _, HEADERS, 0x4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(stream_id)); EXPECT_CALL(visitor, OnHeaderForStream(stream_id, ":status", "200")); EXPECT_CALL(visitor, OnEndHeadersForStream(stream_id)); EXPECT_CALL(visitor, OnFrameHeader(stream_id, 4, WINDOW_UPDATE, 0x0)); EXPECT_CALL(visitor, OnWindowUpdate(stream_id, 65536)); EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSetting(Http2Setting{INITIAL_WINDOW_SIZE, kLargeInitialWindow})); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t read_result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(read_result), frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, stream_id, 4, 0x0)); EXPECT_CALL( visitor, OnFrameSent(RST_STREAM, stream_id, 4, 0x0, static_cast<int>(Http2ErrorCode::FLOW_CONTROL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(stream_id, Http2ErrorCode::FLOW_CONTROL_ERROR)); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST(NgHttp2AdapterTest, ClientForbidsPushPromise) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); adapter->SubmitSettings({{ENABLE_PUSH, 0}}); testing::InSequence s; EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); int write_result = adapter->Send(); EXPECT_EQ(0, write_result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS})); visitor.Clear(); const std::vector<Header> headers = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr); ASSERT_GT(stream_id, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x5, 0)); write_result = adapter->Send(); EXPECT_EQ(0, write_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS})); visitor.Clear(); const std::vector<Header> push_headers = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/push"}}); const std::string frames = TestFrameSequence() .ServerPreface() .SettingsAck() .PushPromise(stream_id, 2, push_headers) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0x1)); EXPECT_CALL(visitor, OnSettingsAck); EXPECT_CALL(visitor, OnFrameHeader(stream_id, _, PUSH_PROMISE, _)); EXPECT_CALL(visitor, OnInvalidFrame(stream_id, _)); const int64_t read_result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), read_result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL( visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int32_t>(Http2ErrorCode::PROTOCOL_ERROR))); write_result = adapter->Send(); EXPECT_EQ(0, write_result); } TEST(NgHttp2AdapterTest, ClientForbidsPushStream) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); adapter->SubmitSettings({{ENABLE_PUSH, 0}}); testing::InSequence s; EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); int write_result = adapter->Send(); EXPECT_EQ(0, write_result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS})); visitor.Clear(); const std::vector<Header> headers = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr); ASSERT_GT(stream_id, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x5, 0)); write_result = adapter->Send(); EXPECT_EQ(0, write_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS})); visitor.Clear(); const std::string frames = TestFrameSequence() .ServerPreface() .SettingsAck() .Headers(2, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0x1)); EXPECT_CALL(visitor, OnSettingsAck); EXPECT_CALL(visitor, OnFrameHeader(2, _, HEADERS, _)); EXPECT_CALL(visitor, OnInvalidFrame(2, _)); const int64_t read_result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), read_result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL( visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int32_t>(Http2ErrorCode::PROTOCOL_ERROR))); write_result = adapter->Send(); EXPECT_EQ(0, write_result); } TEST(NgHttp2AdapterTest, FailureSendingConnectionPreface) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); visitor.set_has_write_error(); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kSendError)); int result = adapter->Send(); EXPECT_EQ(result, NGHTTP2_ERR_CALLBACK_FAILURE); } TEST(NgHttp2AdapterTest, MaxFrameSizeSettingNotAppliedBeforeAck) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); const uint32_t large_frame_size = kDefaultFramePayloadSizeLimit + 42; adapter->SubmitSettings({{MAX_FRAME_SIZE, large_frame_size}}); const int32_t stream_id = adapter->SubmitRequest( ToHeaders({{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}), nullptr, true, nullptr); EXPECT_GT(stream_id, 0); EXPECT_TRUE(adapter->want_write()); testing::InSequence s; EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x5, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); visitor.Clear(); const std::string server_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "200"}}, false) .Data(1, std::string(large_frame_size, 'a')) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); const int64_t process_result = adapter->ProcessBytes(server_frames); EXPECT_EQ(server_frames.size(), static_cast<size_t>(process_result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::FRAME_SIZE_ERROR))); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY})); } TEST(NgHttp2AdapterTest, MaxFrameSizeSettingAppliedAfterAck) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateClientAdapter(visitor); const uint32_t large_frame_size = kDefaultFramePayloadSizeLimit + 42; adapter->SubmitSettings({{MAX_FRAME_SIZE, large_frame_size}}); const int32_t stream_id = adapter->SubmitRequest( ToHeaders({{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}), nullptr, true, nullptr); EXPECT_GT(stream_id, 0); EXPECT_TRUE(adapter->want_write()); testing::InSequence s; EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x5, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); visitor.Clear(); const std::string server_frames = TestFrameSequence() .ServerPreface() .SettingsAck() .Headers(1, {{":status", "200"}}, false) .Data(1, std::string(large_frame_size, 'a')) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0x1)); EXPECT_CALL(visitor, OnSettingsAck()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, large_frame_size, DATA, 0x0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, large_frame_size)); EXPECT_CALL(visitor, OnDataForStream(1, _)); const int64_t process_result = adapter->ProcessBytes(server_frames); EXPECT_EQ(server_frames.size(), static_cast<size_t>(process_result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); } TEST(NgHttp2AdapterTest, WindowUpdateRaisesFlowControlWindowLimit) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string data_chunk(kDefaultFramePayloadSizeLimit, 'a'); const std::string request = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/"}}, false) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); adapter->ProcessBytes(request); adapter->SubmitWindowUpdate(0, 2 * kDefaultFramePayloadSizeLimit); adapter->SubmitWindowUpdate(1, 2 * kDefaultFramePayloadSizeLimit); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 0, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 0, 4, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 1, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 1, 4, 0x0, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_EQ(kInitialFlowControlWindowSize + 2 * kDefaultFramePayloadSizeLimit, adapter->GetReceiveWindowSize()); EXPECT_EQ(kInitialFlowControlWindowSize + 2 * kDefaultFramePayloadSizeLimit, adapter->GetStreamReceiveWindowSize(1)); const std::string request_body = TestFrameSequence() .Data(1, data_chunk) .Data(1, data_chunk) .Data(1, data_chunk) .Data(1, data_chunk) .Data(1, data_chunk) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0)).Times(5); EXPECT_CALL(visitor, OnBeginDataForStream(1, _)).Times(5); EXPECT_CALL(visitor, OnDataForStream(1, _)).Times(5); adapter->ProcessBytes(request_body); EXPECT_EQ(kInitialFlowControlWindowSize - 3 * kDefaultFramePayloadSizeLimit, adapter->GetReceiveWindowSize()); EXPECT_EQ(kInitialFlowControlWindowSize - 3 * kDefaultFramePayloadSizeLimit, adapter->GetStreamReceiveWindowSize(1)); adapter->MarkDataConsumedForStream(1, 4 * kDefaultFramePayloadSizeLimit); EXPECT_GT(adapter->GetReceiveWindowSize(), kInitialFlowControlWindowSize); EXPECT_GT(adapter->GetStreamReceiveWindowSize(1), kInitialFlowControlWindowSize); } TEST(NgHttp2AdapterTest, ConnectionErrorOnControlFrameSent) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames = TestFrameSequence().ClientPreface().Ping(42).Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, _, PING, 0)); EXPECT_CALL(visitor, OnPing(42, false)); const int64_t read_result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(read_result), frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)) .WillOnce(testing::Return(-902)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kSendError)); int send_result = adapter->Send(); EXPECT_LT(send_result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(PING, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(PING, 0, _, 0x1, 0)); send_result = adapter->Send(); EXPECT_EQ(send_result, 0); EXPECT_FALSE(adapter->want_write()); } TEST_P(NgHttp2AdapterDataTest, ConnectionErrorOnDataFrameSent) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0x5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t read_result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(read_result), frames.size()); auto body = std::make_unique<VisitorDataSource>(visitor, 1); visitor.AppendPayloadForStream( 1, "Here is some data, which will lead to a fatal error"); int submit_result = adapter->SubmitResponse(1, ToHeaders({{":status", "200"}}), GetParam() ? nullptr : std::move(body), false); ASSERT_EQ(0, submit_result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0)) .WillOnce(testing::Return(-902)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kSendError)); int send_result = adapter->Send(); EXPECT_LT(send_result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0)); send_result = adapter->Send(); EXPECT_EQ(send_result, 0); EXPECT_FALSE(adapter->want_write()); } TEST(NgHttp2AdapterTest, ServerConstruction) { testing::StrictMock<MockHttp2Visitor> visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); ASSERT_NE(nullptr, adapter); EXPECT_TRUE(adapter->want_read()); EXPECT_FALSE(adapter->want_write()); EXPECT_TRUE(adapter->IsServerSession()); } TEST(NgHttp2AdapterTest, ServerHandlesFrames) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); EXPECT_EQ(0, adapter->GetHighestReceivedStreamId()); EXPECT_EQ(0, adapter->GetHpackDecoderDynamicTableSize()); const std::string frames = TestFrameSequence() .ClientPreface() .Ping(42) .WindowUpdate(0, 1000) .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .WindowUpdate(1, 2000) .Data(1, "This is the request body.") .Headers(3, {{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}, true) .RstStream(3, Http2ErrorCode::CANCEL) .Ping(47) .Serialize(); testing::InSequence s; const char* kSentinel1 = "arbitrary pointer 1"; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, 8, PING, 0)); EXPECT_CALL(visitor, OnPing(42, false)); EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(0, 1000)); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)) .WillOnce(testing::InvokeWithoutArgs([&adapter, kSentinel1]() { adapter->SetStreamUserData(1, const_cast<char*>(kSentinel1)); return true; })); EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(1, 2000)); EXPECT_CALL(visitor, OnFrameHeader(1, 25, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 25)); EXPECT_CALL(visitor, OnDataForStream(1, "This is the request body.")); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(3, ":scheme", "http")); EXPECT_CALL(visitor, OnHeaderForStream(3, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(3, ":path", "/this/is/request/two")); EXPECT_CALL(visitor, OnEndHeadersForStream(3)); EXPECT_CALL(visitor, OnEndStream(3)); EXPECT_CALL(visitor, OnFrameHeader(3, 4, RST_STREAM, 0)); EXPECT_CALL(visitor, OnRstStream(3, Http2ErrorCode::CANCEL)); EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::CANCEL)); EXPECT_CALL(visitor, OnFrameHeader(0, 8, PING, 0)); EXPECT_CALL(visitor, OnPing(47, false)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), result); EXPECT_EQ(kSentinel1, adapter->GetStreamUserData(1)); EXPECT_GT(kInitialFlowControlWindowSize, adapter->GetStreamReceiveWindowSize(1)); EXPECT_EQ(adapter->GetStreamReceiveWindowSize(1), adapter->GetReceiveWindowSize()); EXPECT_EQ(kInitialFlowControlWindowSize, adapter->GetStreamReceiveWindowLimit(1)); EXPECT_GT(adapter->GetHpackDecoderDynamicTableSize(), 0); const char* kSentinel3 = "another arbitrary pointer"; adapter->SetStreamUserData(3, const_cast<char*>(kSentinel3)); EXPECT_EQ(nullptr, adapter->GetStreamUserData(3)); EXPECT_EQ(3, adapter->GetHighestReceivedStreamId()); EXPECT_EQ(adapter->GetSendWindowSize(), kInitialFlowControlWindowSize + 1000); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(PING, 0, 8, 0x1)); EXPECT_CALL(visitor, OnFrameSent(PING, 0, 8, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(PING, 0, 8, 0x1)); EXPECT_CALL(visitor, OnFrameSent(PING, 0, 8, 0x1, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::PING, SpdyFrameType::PING})); } TEST(NgHttp2AdapterTest, ServerVisitorRejectsHeaders) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); EXPECT_FALSE(adapter->want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"header1", "ok"}, {"header2", "rejected"}, {"header3", "not processed"}, {"header4", "not processed"}, {"header5", "not processed"}, {"header6", "not processed"}, {"header7", "not processed"}, {"header8", "not processed"}}, false, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0x0)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(5); EXPECT_CALL(visitor, OnHeaderForStream(1, "header2", _)) .WillOnce(testing::Return(Http2VisitorInterface::HEADER_RST_STREAM)); int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(result), frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, static_cast<int>(Http2ErrorCode::INTERNAL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::INTERNAL_ERROR)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST(OgHttp2AdapterTest, HeaderValuesWithObsTextAllowed) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/"}, {"name", "val\xa1ue"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/")); EXPECT_CALL(visitor, OnHeaderForStream(1, "name", "val\xa1ue")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); } TEST(NgHttp2AdapterTest, ServerHandlesDataWithPadding) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .Data(1, "This is the request body.", true, 39) .Headers(3, {{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, 25 + 39, DATA, 0x9)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 25 + 39)); EXPECT_CALL(visitor, OnDataForStream(1, "This is the request body.")); EXPECT_CALL(visitor, OnDataPaddingLength(1, 39)); EXPECT_CALL(visitor, OnEndStream(1)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(3)); EXPECT_CALL(visitor, OnEndStream(3)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); } TEST(NgHttp2AdapterTest, ServerHandlesHostHeader) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":path", "/this/is/request/one"}, {"host", "example.com"}}, true) .Headers(3, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"host", "example.com"}}, true) .Headers(5, {{":method", "POST"}, {":scheme", "https"}, {":authority", "foo.com"}, {":path", "/this/is/request/one"}, {"host", "bar.com"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(5); EXPECT_CALL(visitor, OnEndHeadersForStream(3)); EXPECT_CALL(visitor, OnEndStream(3)); EXPECT_CALL(visitor, OnFrameHeader(5, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(5)); EXPECT_CALL(visitor, OnHeaderForStream(5, _, _)).Times(5); EXPECT_CALL(visitor, OnEndHeadersForStream(5)); EXPECT_CALL(visitor, OnEndStream(5)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); visitor.Clear(); } TEST_P(NgHttp2AdapterDataTest, ServerSubmitsTrailersWhileDataDeferred) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .WindowUpdate(1, 2000) .Data(1, "This is the request body.") .WindowUpdate(0, 2000) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(1, 2000)); EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, _)); EXPECT_CALL(visitor, OnDataForStream(1, "This is the request body.")); EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(0, 2000)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); visitor.Clear(); const absl::string_view kBody = "This is an example response body."; visitor.AppendPayloadForStream(1, kBody); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse( 1, ToHeaders({{":status", "200"}, {"x-comment", "Sure, sounds good."}}), GetParam() ? nullptr : std::move(body1), false); EXPECT_EQ(submit_result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0)); send_result = adapter->Send(); EXPECT_EQ(0, send_result); visitor.Clear(); EXPECT_FALSE(adapter->want_write()); int trailer_result = adapter->SubmitTrailer(1, ToHeaders({{"final-status", "a-ok"}})); ASSERT_EQ(trailer_result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x5, 0)); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS})); visitor.Clear(); visitor.AppendPayloadForStream(1, kBody); visitor.SetEndData(1, true); adapter->ResumeStream(1); EXPECT_TRUE(adapter->want_write()); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), testing::IsEmpty()); EXPECT_FALSE(adapter->want_write()); } TEST_P(NgHttp2AdapterDataTest, ServerSubmitsTrailersWithDataEndStream) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}) .Data(1, "Example data, woohoo.") .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, _)); EXPECT_CALL(visitor, OnDataForStream(1, _)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(result), frames.size()); const absl::string_view kBody = "This is an example response body."; visitor.AppendPayloadForStream(1, kBody); visitor.SetEndData(1, true); auto body = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse(1, ToHeaders({{":status", "200"}}), GetParam() ? nullptr : std::move(body), false); ASSERT_EQ(submit_result, 0); const std::vector<Header> trailers = ToHeaders({{"extra-info", "Trailers are weird but good?"}}); submit_result = adapter->SubmitTrailer(1, trailers); ASSERT_EQ(submit_result, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, END_HEADERS_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, END_HEADERS_FLAG | END_STREAM_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, END_HEADERS_FLAG | END_STREAM_FLAG, 0)); const int send_result = adapter->Send(); EXPECT_EQ(send_result, 0); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS, SpdyFrameType::HEADERS})); } TEST_P(NgHttp2AdapterDataTest, ServerSubmitsTrailersWithDataEndStreamAndDeferral) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}) .Data(1, "Example data, woohoo.") .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, _)); EXPECT_CALL(visitor, OnDataForStream(1, _)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(result), frames.size()); const absl::string_view kBody = "This is an example response body."; visitor.AppendPayloadForStream(1, kBody); auto body = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse(1, ToHeaders({{":status", "200"}}), GetParam() ? nullptr : std::move(body), false); ASSERT_EQ(submit_result, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, END_HEADERS_FLAG, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS, SpdyFrameType::DATA})); visitor.Clear(); const std::vector<Header> trailers = ToHeaders({{"extra-info", "Trailers are weird but good?"}}); submit_result = adapter->SubmitTrailer(1, trailers); ASSERT_EQ(submit_result, 0); visitor.AppendPayloadForStream(1, kBody); visitor.SetEndData(1, false); adapter->ResumeStream(1); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, END_HEADERS_FLAG | END_STREAM_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, END_HEADERS_FLAG | END_STREAM_FLAG, 0)); send_result = adapter->Send(); EXPECT_EQ(send_result, 0); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS})); } TEST(NgHttp2AdapterTest, ClientDisobeysConnectionFlowControl) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"accept", "some bogus value!"}}, false) .Data(1, std::string(16384, 'a')) .Data(1, std::string(16384, 'a')) .Data(1, std::string(16384, 'a')) .Data(1, std::string(16384, 'a')) .Data(1, std::string(4464, 'a')) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream).Times(5); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, 16384, DATA, 0x0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 16384)); EXPECT_CALL(visitor, OnDataForStream(1, _)); EXPECT_CALL(visitor, OnFrameHeader(1, 16384, DATA, 0x0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 16384)); EXPECT_CALL(visitor, OnDataForStream(1, _)); EXPECT_CALL(visitor, OnFrameHeader(1, 16384, DATA, 0x0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 16384)); EXPECT_CALL(visitor, OnDataForStream(1, _)); EXPECT_CALL(visitor, OnFrameHeader(1, 16384, DATA, 0x0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 16384)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL( visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::FLOW_CONTROL_ERROR))); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY})); } TEST(NgHttp2AdapterTest, ClientDisobeysConnectionFlowControlWithOneDataFrame) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const uint32_t window_overflow_bytes = kInitialFlowControlWindowSize + 1; adapter->SubmitSettings({{MAX_FRAME_SIZE, window_overflow_bytes}}); const std::string initial_frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); int64_t process_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), static_cast<size_t>(process_result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS})); visitor.Clear(); const std::string overflow_frames = TestFrameSequence() .SettingsAck() .Data(1, std::string(window_overflow_bytes, 'a')) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0x1)); EXPECT_CALL(visitor, OnSettingsAck()); EXPECT_CALL(visitor, OnFrameHeader(1, window_overflow_bytes, DATA, 0x0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, window_overflow_bytes)); process_result = adapter->ProcessBytes(overflow_frames); EXPECT_EQ(overflow_frames.size(), static_cast<size_t>(process_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL( visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::FLOW_CONTROL_ERROR))); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY})); } TEST(NgHttp2AdapterTest, ClientDisobeysConnectionFlowControlAcrossReads) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const uint32_t window_overflow_bytes = kInitialFlowControlWindowSize + 1; adapter->SubmitSettings({{MAX_FRAME_SIZE, window_overflow_bytes}}); const std::string initial_frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); int64_t process_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), static_cast<size_t>(process_result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS})); visitor.Clear(); const std::string overflow_frames = TestFrameSequence() .SettingsAck() .Data(1, std::string(window_overflow_bytes, 'a')) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0x1)); EXPECT_CALL(visitor, OnSettingsAck()); EXPECT_CALL(visitor, OnFrameHeader(1, window_overflow_bytes, DATA, 0x0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, window_overflow_bytes)); EXPECT_CALL(visitor, OnDataForStream(1, _)) .WillRepeatedly( [&adapter](Http2StreamId stream_id, absl::string_view data) { adapter->MarkDataConsumedForStream(stream_id, data.size()); return true; }); const size_t chunk_length = 16384; ASSERT_GE(overflow_frames.size(), chunk_length); absl::string_view remaining = overflow_frames; while (!remaining.empty()) { absl::string_view chunk = remaining.substr(0, chunk_length); process_result = adapter->ProcessBytes(chunk); EXPECT_EQ(chunk.length(), static_cast<size_t>(process_result)); remaining.remove_prefix(chunk.length()); } EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 0, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 0, 4, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 1, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 1, 4, 0x0, 0)); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::WINDOW_UPDATE, SpdyFrameType::WINDOW_UPDATE})); } TEST(NgHttp2AdapterTest, ClientDisobeysStreamFlowControl) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"accept", "some bogus value!"}}, false) .Serialize(); const std::string more_frames = TestFrameSequence() .Data(1, std::string(16384, 'a')) .Data(1, std::string(16384, 'a')) .Data(1, std::string(16384, 'a')) .Data(1, std::string(16384, 'a')) .Data(1, std::string(4464, 'a')) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream).Times(5); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); adapter->SubmitWindowUpdate(0, 20000); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 0, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 0, 4, 0x0, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::WINDOW_UPDATE})); visitor.Clear(); EXPECT_CALL(visitor, OnFrameHeader(1, 16384, DATA, 0x0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 16384)); EXPECT_CALL(visitor, OnDataForStream(1, _)); EXPECT_CALL(visitor, OnFrameHeader(1, 16384, DATA, 0x0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 16384)); EXPECT_CALL(visitor, OnDataForStream(1, _)); EXPECT_CALL(visitor, OnFrameHeader(1, 16384, DATA, 0x0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 16384)); EXPECT_CALL(visitor, OnDataForStream(1, _)); EXPECT_CALL(visitor, OnFrameHeader(1, 16384, DATA, 0x0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 16384)); EXPECT_CALL(visitor, OnDataForStream(1, _)); result = adapter->ProcessBytes(more_frames); EXPECT_EQ(more_frames.size(), static_cast<size_t>(result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, 4, 0x0)); EXPECT_CALL( visitor, OnFrameSent(RST_STREAM, 1, 4, 0x0, static_cast<int>(Http2ErrorCode::FLOW_CONTROL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::FLOW_CONTROL_ERROR)); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::RST_STREAM})); } TEST(NgHttp2AdapterTest, ServerErrorWhileHandlingHeaders) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"accept", "some bogus value!"}}, false) .WindowUpdate(1, 2000) .Data(1, "This is the request body.") .WindowUpdate(0, 2000) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnHeaderForStream(1, "accept", "some bogus value!")) .WillOnce(testing::Return(Http2VisitorInterface::HEADER_RST_STREAM)); EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(1, 2000)); EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(0, 2000)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, 4, 0x0, static_cast<int>(Http2ErrorCode::INTERNAL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::INTERNAL_ERROR)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST(NgHttp2AdapterTest, ServerErrorWhileHandlingHeadersDropsFrames) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"accept", "some bogus value!"}}, false) .WindowUpdate(1, 2000) .Data(1, "This is the request body.") .Metadata(1, "This is the request metadata.") .RstStream(1, Http2ErrorCode::CANCEL) .WindowUpdate(0, 2000) .Headers(3, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}, false) .Metadata(3, "This is the request metadata.", true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnHeaderForStream(1, "accept", "some bogus value!")) .WillOnce(testing::Return(Http2VisitorInterface::HEADER_RST_STREAM)); EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(1, 2000)); EXPECT_CALL(visitor, OnFrameHeader(1, _, kMetadataFrameType, 4)); EXPECT_CALL(visitor, OnBeginMetadataForStream(1, _)); EXPECT_CALL(visitor, OnMetadataForStream(1, _)); EXPECT_CALL(visitor, OnMetadataEndForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, 4, RST_STREAM, 0)); EXPECT_CALL(visitor, OnRstStream(1, Http2ErrorCode::CANCEL)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::CANCEL)); EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(0, 2000)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(3)); EXPECT_CALL(visitor, OnFrameHeader(3, _, kMetadataFrameType, 0)); EXPECT_CALL(visitor, OnBeginMetadataForStream(3, _)); EXPECT_CALL(visitor, OnMetadataForStream(3, "This is the re")) .WillOnce(testing::DoAll(testing::InvokeWithoutArgs([&adapter]() { adapter->SubmitRst( 3, Http2ErrorCode::REFUSED_STREAM); }), testing::Return(true))); EXPECT_CALL(visitor, OnFrameHeader(3, _, kMetadataFrameType, 4)); EXPECT_CALL(visitor, OnBeginMetadataForStream(3, _)); EXPECT_CALL(visitor, OnMetadataForStream(3, "quest metadata.")); EXPECT_CALL(visitor, OnMetadataEndForStream(3)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, 4, 0x0, static_cast<int>(Http2ErrorCode::INTERNAL_ERROR))); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 3, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 3, 4, 0x0, static_cast<int>(Http2ErrorCode::REFUSED_STREAM))); EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::REFUSED_STREAM)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM, SpdyFrameType::RST_STREAM})); } TEST(NgHttp2AdapterTest, ServerConnectionErrorWhileHandlingHeaders) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"Accept", "uppercase, oh boy!"}}, false) .WindowUpdate(1, 2000) .Data(1, "This is the request body.") .WindowUpdate(0, 2000) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnErrorDebug); EXPECT_CALL( visitor, OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader)) .WillOnce(testing::Return(false)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kParseError)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(result, NGHTTP2_ERR_CALLBACK_FAILURE); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, 4, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST(NgHttp2AdapterTest, ServerErrorAfterHandlingHeaders) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .WindowUpdate(1, 2000) .Data(1, "This is the request body.") .WindowUpdate(0, 2000) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)) .WillOnce(testing::Return(false)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kParseError)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(-902, result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); } TEST(NgHttp2AdapterTest, ServerRejectsFrameHeader) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames = TestFrameSequence() .ClientPreface() .Ping(64) .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .WindowUpdate(1, 2000) .Data(1, "This is the request body.") .WindowUpdate(0, 2000) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, 8, PING, 0)) .WillOnce(testing::Return(false)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kParseError)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(-902, result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); } TEST(NgHttp2AdapterTest, ServerRejectsBeginningOfData) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .Data(1, "This is the request body.") .Headers(3, {{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}, true) .RstStream(3, Http2ErrorCode::CANCEL) .Ping(47) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, 25, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 25)) .WillOnce(testing::Return(false)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kParseError)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(NGHTTP2_ERR_CALLBACK_FAILURE, result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); } TEST(NgHttp2AdapterTest, ServerRejectsStreamData) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .Data(1, "This is the request body.") .Headers(3, {{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}, true) .RstStream(3, Http2ErrorCode::CANCEL) .Ping(47) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, 25, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 25)); EXPECT_CALL(visitor, OnDataForStream(1, _)).WillOnce(testing::Return(false)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kParseError)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(NGHTTP2_ERR_CALLBACK_FAILURE, result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); } TEST(NgHttp2AdapterTest, ServerReceivesTooLargeHeader) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string too_large_value = std::string(80 * 1024, 'q'); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"x-toobig", too_large_value}}, false) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, 8, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, 8, 0x0, static_cast<int>(Http2ErrorCode::COMPRESSION_ERROR))); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY})); } TEST(NgHttp2AdapterTest, ServerReceivesInvalidAuthority) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "ex|ample.com"}, {":path", "/this/is/request/one"}}, false) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL( visitor, OnErrorDebug("Invalid HTTP header field was received: frame type: 1, " "stream: 1, name: [:authority], value: [ex|ample.com]")); EXPECT_CALL( visitor, OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0x0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, 4, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST(NgHttpAdapterTest, ServerReceivesGoAway) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true) .GoAway(0, Http2ErrorCode::HTTP2_NO_ERROR, "") .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0x5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0x0)); EXPECT_CALL(visitor, OnGoAway(0, Http2ErrorCode::HTTP2_NO_ERROR, "")); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<int64_t>(frames.size()), result); const int submit_result = adapter->SubmitResponse(1, ToHeaders({{":status", "200"}}), nullptr, true); ASSERT_EQ(0, submit_result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0x0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x5, 0)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); } TEST_P(NgHttp2AdapterDataTest, ServerSubmitResponse) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); EXPECT_FALSE(adapter->want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true) .Serialize(); testing::InSequence s; const char* kSentinel1 = "arbitrary pointer 1"; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)) .WillOnce(testing::InvokeWithoutArgs([&adapter, kSentinel1]() { adapter->SetStreamUserData(1, const_cast<char*>(kSentinel1)); return true; })); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), result); EXPECT_EQ(1, adapter->GetHighestReceivedStreamId()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); visitor.Clear(); EXPECT_EQ(0, adapter->GetHpackEncoderDynamicTableSize()); EXPECT_FALSE(adapter->want_write()); const absl::string_view kBody = "This is an example response body."; visitor.AppendPayloadForStream(1, kBody); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse( 1, ToHeaders({{":status", "404"}, {"x-comment", "I have no idea what you're talking about."}}), GetParam() ? nullptr : std::move(body1), false); EXPECT_EQ(submit_result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_EQ(kSentinel1, adapter->GetStreamUserData(1)); adapter->SetStreamUserData(1, nullptr); EXPECT_EQ(nullptr, adapter->GetStreamUserData(1)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0)); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::DATA})); EXPECT_THAT(visitor.data(), testing::HasSubstr(kBody)); EXPECT_FALSE(adapter->want_write()); EXPECT_LT(adapter->GetStreamSendWindowSize(1), kInitialFlowControlWindowSize); EXPECT_GT(adapter->GetStreamSendWindowSize(1), 0); EXPECT_EQ(adapter->GetStreamSendWindowSize(3), -1); EXPECT_GT(adapter->GetHpackEncoderDynamicTableSize(), 0); } TEST_P(NgHttp2AdapterDataTest, ServerSubmitResponseWithResetFromClient) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); EXPECT_FALSE(adapter->want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), result); EXPECT_EQ(1, adapter->GetHighestReceivedStreamId()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); visitor.Clear(); EXPECT_FALSE(adapter->want_write()); const absl::string_view kBody = "This is an example response body."; visitor.AppendPayloadForStream(1, kBody); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse( 1, ToHeaders({{":status", "404"}, {"x-comment", "I have no idea what you're talking about."}}), GetParam() ? nullptr : std::move(body1), false); EXPECT_EQ(submit_result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_EQ(adapter->sources_size(), GetParam() ? 0 : 1); const std::string reset = TestFrameSequence().RstStream(1, Http2ErrorCode::CANCEL).Serialize(); EXPECT_CALL(visitor, OnFrameHeader(1, 4, RST_STREAM, 0)); EXPECT_CALL(visitor, OnRstStream(1, Http2ErrorCode::CANCEL)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::CANCEL)) .WillOnce( [&adapter](Http2StreamId stream_id, Http2ErrorCode ) { adapter->RemoveStream(stream_id); return true; }); const int64_t reset_result = adapter->ProcessBytes(reset); EXPECT_EQ(reset.size(), static_cast<size_t>(reset_result)); EXPECT_EQ(adapter->sources_size(), 0); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, _)).Times(0); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, _, _)).Times(0); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, _, _)).Times(0); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), testing::IsEmpty()); } TEST(NgHttp2AdapterTest, ServerSendsShutdown) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), result); adapter->SubmitShutdownNotice(); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY})); } TEST_P(NgHttp2AdapterDataTest, ServerSendsTrailers) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); EXPECT_FALSE(adapter->want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); visitor.Clear(); EXPECT_FALSE(adapter->want_write()); const absl::string_view kBody = "This is an example response body."; visitor.AppendPayloadForStream(1, kBody); visitor.SetEndData(1, false); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse( 1, ToHeaders({{":status", "200"}, {"x-comment", "Sure, sounds good."}}), GetParam() ? nullptr : std::move(body1), false); EXPECT_EQ(submit_result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0)); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::DATA})); EXPECT_THAT(visitor.data(), testing::HasSubstr(kBody)); visitor.Clear(); EXPECT_FALSE(adapter->want_write()); int trailer_result = adapter->SubmitTrailer( 1, ToHeaders({{"final-status", "a-ok"}, {"x-comment", "trailers sure are cool"}})); ASSERT_EQ(trailer_result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x5, 0)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS})); } TEST(NgHttp2AdapterTest, ClientSendsContinuation) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); EXPECT_FALSE(adapter->want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 1)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnFrameHeader(1, _, CONTINUATION, 4)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), result); } TEST(NgHttp2AdapterTest, ClientSendsMetadataWithContinuation) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); EXPECT_FALSE(adapter->want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Metadata(0, "Example connection metadata in multiple frames", true) .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false, true) .Metadata(1, "Some stream metadata that's also sent in multiple frames", true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, _, kMetadataFrameType, 0)); EXPECT_CALL(visitor, OnBeginMetadataForStream(0, _)); EXPECT_CALL(visitor, OnMetadataForStream(0, _)); EXPECT_CALL(visitor, OnFrameHeader(0, _, kMetadataFrameType, 4)); EXPECT_CALL(visitor, OnBeginMetadataForStream(0, _)); EXPECT_CALL(visitor, OnMetadataForStream(0, _)); EXPECT_CALL(visitor, OnMetadataEndForStream(0)); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnFrameHeader(1, _, CONTINUATION, 4)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, kMetadataFrameType, 0)); EXPECT_CALL(visitor, OnBeginMetadataForStream(1, _)); EXPECT_CALL(visitor, OnMetadataForStream(1, _)); EXPECT_CALL(visitor, OnFrameHeader(1, _, kMetadataFrameType, 4)); EXPECT_CALL(visitor, OnBeginMetadataForStream(1, _)); EXPECT_CALL(visitor, OnMetadataForStream(1, _)); EXPECT_CALL(visitor, OnMetadataEndForStream(1)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), result); EXPECT_EQ("Example connection metadata in multiple frames", absl::StrJoin(visitor.GetMetadata(0), "")); EXPECT_EQ("Some stream metadata that's also sent in multiple frames", absl::StrJoin(visitor.GetMetadata(1), "")); } TEST_P(NgHttp2AdapterDataTest, RepeatedHeaderNames) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); EXPECT_FALSE(adapter->want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"accept", "text/plain"}, {"accept", "text/html"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnHeaderForStream(1, "accept", "text/plain")); EXPECT_CALL(visitor, OnHeaderForStream(1, "accept", "text/html")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); const std::vector<Header> headers1 = ToHeaders( {{":status", "200"}, {"content-length", "10"}, {"content-length", "10"}}); visitor.AppendPayloadForStream(1, "perfection"); visitor.SetEndData(1, true); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse( 1, headers1, GetParam() ? nullptr : std::move(body1), false); ASSERT_EQ(0, submit_result); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, 10, 0x1, 0)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS, SpdyFrameType::DATA})); } TEST_P(NgHttp2AdapterDataTest, ServerRespondsToRequestWithTrailers) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); EXPECT_FALSE(adapter->want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}) .Data(1, "Example data, woohoo.") .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, _)); EXPECT_CALL(visitor, OnDataForStream(1, _)); int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); const std::vector<Header> headers1 = ToHeaders({{":status", "200"}}); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse( 1, headers1, GetParam() ? nullptr : std::move(body1), false); ASSERT_EQ(0, submit_result); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); visitor.Clear(); const std::string more_frames = TestFrameSequence() .Headers(1, {{"extra-info", "Trailers are weird but good?"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, "extra-info", "Trailers are weird but good?")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); result = adapter->ProcessBytes(more_frames); EXPECT_EQ(more_frames.size(), static_cast<size_t>(result)); visitor.SetEndData(1, true); EXPECT_EQ(true, adapter->ResumeStream(1)); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, 0, 0x1, 0)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::DATA})); } TEST_P(NgHttp2AdapterDataTest, ServerSubmitsResponseWithDataSourceError) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); EXPECT_FALSE(adapter->want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); visitor.SimulateError(1); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse( 1, ToHeaders({{":status", "200"}, {"x-comment", "Sure, sounds good."}}), GetParam() ? nullptr : std::move(body1), false); EXPECT_EQ(submit_result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, 2)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::INTERNAL_ERROR)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS, SpdyFrameType::RST_STREAM})); visitor.Clear(); EXPECT_FALSE(adapter->want_write()); int trailer_result = adapter->SubmitTrailer(1, ToHeaders({{":final-status", "a-ok"}})); EXPECT_EQ(trailer_result, 0); } TEST(NgHttp2AdapterTest, CompleteRequestWithServerResponse) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); EXPECT_FALSE(adapter->want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .Data(1, "This is the response body.", true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 1)); EXPECT_CALL(visitor, OnBeginDataForStream(1, _)); EXPECT_CALL(visitor, OnDataForStream(1, _)); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); int submit_result = adapter->SubmitResponse( 1, ToHeaders({{":status", "200"}}), nullptr, true); EXPECT_EQ(submit_result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x5, 0)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); EXPECT_FALSE(adapter->want_write()); } TEST(NgHttp2AdapterTest, IncompleteRequestWithServerResponse) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); EXPECT_FALSE(adapter->want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); int submit_result = adapter->SubmitResponse( 1, ToHeaders({{":status", "200"}}), nullptr, true); EXPECT_EQ(submit_result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x5, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); EXPECT_FALSE(adapter->want_write()); } TEST(NgHttp2AdapterTest, ServerHandlesMultipleContentLength) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); EXPECT_FALSE(adapter->want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/1"}, {"content-length", "7"}, {"content-length", "7"}}, false) .Headers(3, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/3"}, {"content-length", "11"}, {"content-length", "13"}}, false) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/1")); EXPECT_CALL(visitor, OnHeaderForStream(1, "content-length", "7")); EXPECT_CALL( visitor, OnErrorDebug("Invalid HTTP header field was received: frame type: 1, " "stream: 1, name: [content-length], value: [7]")); EXPECT_CALL( visitor, OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(3, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(3, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(3, ":path", "/3")); EXPECT_CALL(visitor, OnHeaderForStream(3, "content-length", "11")); EXPECT_CALL( visitor, OnErrorDebug("Invalid HTTP header field was received: frame type: 1, " "stream: 3, name: [content-length], value: [13]")); EXPECT_CALL( visitor, OnInvalidFrame(3, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); } TEST_P(NgHttp2AdapterDataTest, ServerSendsInvalidTrailers) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); EXPECT_FALSE(adapter->want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), result); const absl::string_view kBody = "This is an example response body."; visitor.AppendPayloadForStream(1, kBody); visitor.SetEndData(1, false); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse( 1, ToHeaders({{":status", "200"}, {"x-comment", "Sure, sounds good."}}), GetParam() ? nullptr : std::move(body1), false); EXPECT_EQ(submit_result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS, SpdyFrameType::DATA})); EXPECT_THAT(visitor.data(), testing::HasSubstr(kBody)); visitor.Clear(); EXPECT_FALSE(adapter->want_write()); int trailer_result = adapter->SubmitTrailer(1, ToHeaders({{":final-status", "a-ok"}})); ASSERT_EQ(trailer_result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x5, 0)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS})); } TEST(NgHttp2AdapterTest, ServerDropsNewStreamBelowWatermark) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); EXPECT_EQ(0, adapter->GetHighestReceivedStreamId()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(3, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .Data(3, "This is the request body.") .Headers(1, {{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(3, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(3, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(3, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(3)); EXPECT_CALL(visitor, OnFrameHeader(3, 25, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(3, 25)); EXPECT_CALL(visitor, OnDataForStream(3, "This is the request body.")); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnInvalidFrame).Times(0); EXPECT_CALL(visitor, OnConnectionError).Times(0); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), result); EXPECT_EQ(3, adapter->GetHighestReceivedStreamId()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); } TEST(NgHttp2AdapterInteractionTest, ClientServerInteractionRepeatedHeaderNames) { TestVisitor client_visitor; auto client_adapter = NgHttp2Adapter::CreateClientAdapter(client_visitor); client_adapter->SubmitSettings({}); const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"accept", "text/plain"}, {"accept", "text/html"}}); const int32_t stream_id1 = client_adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); EXPECT_CALL(client_visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(client_visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(client_visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x5)); EXPECT_CALL(client_visitor, OnFrameSent(HEADERS, stream_id1, _, 0x5, 0)); int send_result = client_adapter->Send(); EXPECT_EQ(0, send_result); TestVisitor server_visitor; auto server_adapter = NgHttp2Adapter::CreateServerAdapter(server_visitor); testing::InSequence s; EXPECT_CALL(server_visitor, OnFrameHeader(0, _, SETTINGS, 0)); EXPECT_CALL(server_visitor, OnSettingsStart()); EXPECT_CALL(server_visitor, OnSetting(_)).Times(testing::AnyNumber()); EXPECT_CALL(server_visitor, OnSettingsEnd()); EXPECT_CALL(server_visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(server_visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(server_visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(server_visitor, OnHeaderForStream(1, ":scheme", "http")); EXPECT_CALL(server_visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(server_visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(server_visitor, OnHeaderForStream(1, "accept", "text/plain")); EXPECT_CALL(server_visitor, OnHeaderForStream(1, "accept", "text/html")); EXPECT_CALL(server_visitor, OnEndHeadersForStream(1)); EXPECT_CALL(server_visitor, OnEndStream(1)); int64_t result = server_adapter->ProcessBytes(client_visitor.data()); EXPECT_EQ(client_visitor.data().size(), static_cast<size_t>(result)); } TEST(NgHttp2AdapterInteractionTest, ClientServerInteractionWithCookies) { TestVisitor client_visitor; auto client_adapter = NgHttp2Adapter::CreateClientAdapter(client_visitor); client_adapter->SubmitSettings({}); const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"cookie", "a; b=2; c"}, {"cookie", "d=e, f, g; h"}}); const int32_t stream_id1 = client_adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); EXPECT_CALL(client_visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(client_visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(client_visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(client_visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int send_result = client_adapter->Send(); EXPECT_EQ(0, send_result); TestVisitor server_visitor; auto server_adapter = NgHttp2Adapter::CreateServerAdapter(server_visitor); testing::InSequence s; EXPECT_CALL(server_visitor, OnFrameHeader(0, _, SETTINGS, 0)); EXPECT_CALL(server_visitor, OnSettingsStart()); EXPECT_CALL(server_visitor, OnSetting).Times(testing::AnyNumber()); EXPECT_CALL(server_visitor, OnSettingsEnd()); EXPECT_CALL(server_visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(server_visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(server_visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(server_visitor, OnHeaderForStream(1, ":scheme", "http")); EXPECT_CALL(server_visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(server_visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(server_visitor, OnHeaderForStream(1, "cookie", "a; b=2; c")); EXPECT_CALL(server_visitor, OnHeaderForStream(1, "cookie", "d=e, f, g; h")); EXPECT_CALL(server_visitor, OnEndHeadersForStream(1)); EXPECT_CALL(server_visitor, OnEndStream(1)); int64_t result = server_adapter->ProcessBytes(client_visitor.data()); EXPECT_EQ(client_visitor.data().size(), static_cast<size_t>(result)); } TEST(NgHttp2AdapterTest, ServerForbidsWindowUpdateOnIdleStream) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); EXPECT_EQ(0, adapter->GetHighestReceivedStreamId()); const std::string frames = TestFrameSequence().ClientPreface().WindowUpdate(1, 42).Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnInvalidFrame(1, _)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), result); EXPECT_EQ(0, adapter->GetHighestReceivedStreamId()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY})); } TEST(NgHttp2AdapterTest, ServerForbidsDataOnIdleStream) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); EXPECT_EQ(0, adapter->GetHighestReceivedStreamId()); const std::string frames = TestFrameSequence() .ClientPreface() .Data(1, "Sorry, out of order") .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), result); EXPECT_EQ(0, adapter->GetHighestReceivedStreamId()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY})); } TEST(NgHttp2AdapterTest, ServerForbidsRstStreamOnIdleStream) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); EXPECT_EQ(0, adapter->GetHighestReceivedStreamId()); const std::string frames = TestFrameSequence() .ClientPreface() .RstStream(1, Http2ErrorCode::ENHANCE_YOUR_CALM) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, RST_STREAM, 0)); EXPECT_CALL(visitor, OnInvalidFrame(1, _)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), result); EXPECT_EQ(0, adapter->GetHighestReceivedStreamId()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY})); } TEST(NgHttp2AdapterTest, ServerForbidsNewStreamAboveStreamLimit) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); adapter->SubmitSettings({{MAX_CONCURRENT_STREAMS, 1}}); const std::string initial_frames = TestFrameSequence().ClientPreface().Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), initial_result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS})); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .SettingsAck() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true) .Headers(3, {{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0x1)); EXPECT_CALL(visitor, OnSettingsAck()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0x5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 0x5)); EXPECT_CALL( visitor, OnInvalidFrame(3, Http2VisitorInterface::InvalidFrameError::kProtocol)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), stream_result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY})); } TEST(NgHttp2AdapterTest, ServerRstStreamsNewStreamAboveStreamLimitBeforeAck) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); adapter->SubmitSettings({{MAX_CONCURRENT_STREAMS, 1}}); const std::string initial_frames = TestFrameSequence().ClientPreface().Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), initial_result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS})); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true) .Headers(3, {{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0x5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 0x5)); EXPECT_CALL(visitor, OnInvalidFrame( 3, Http2VisitorInterface::InvalidFrameError::kRefusedStream)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_result, stream_frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 3, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 3, _, 0x0, static_cast<int>(Http2ErrorCode::REFUSED_STREAM))); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::RST_STREAM})); } TEST(NgHttp2AdapterTest, AutomaticSettingsAndPingAcks) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames = TestFrameSequence().ClientPreface().Ping(42).Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, _, PING, 0)); EXPECT_CALL(visitor, OnPing(42, false)); const int64_t read_result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(read_result), frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(PING, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(PING, 0, _, 0x1, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::PING})); } TEST(NgHttp2AdapterTest, AutomaticPingAcksDisabled) { TestVisitor visitor; nghttp2_option* options; nghttp2_option_new(&options); nghttp2_option_set_no_auto_ping_ack(options, 1); auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor, options); nghttp2_option_del(options); const std::string frames = TestFrameSequence().ClientPreface().Ping(42).Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, _, PING, 0)); EXPECT_CALL(visitor, OnPing(42, false)); const int64_t read_result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(read_result), frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); } TEST(NgHttp2AdapterTest, InvalidMaxFrameSizeSetting) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames = TestFrameSequence().ClientPreface({{MAX_FRAME_SIZE, 3u}}).Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL( visitor, OnInvalidFrame(0, Http2VisitorInterface::InvalidFrameError::kProtocol)); const int64_t read_result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(read_result), frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY})); } TEST(OgHttp2AdapterTest, InvalidPushSetting) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames = TestFrameSequence().ClientPreface({{ENABLE_PUSH, 3u}}).Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnInvalidFrame(0, _)); const int64_t read_result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(read_result), frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY})); } TEST(NgHttp2AdapterTest, InvalidConnectProtocolSetting) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames = TestFrameSequence() .ClientPreface({{ENABLE_CONNECT_PROTOCOL, 3u}}) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL( visitor, OnInvalidFrame(0, Http2VisitorInterface::InvalidFrameError::kProtocol)); int64_t read_result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(read_result), frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY})); auto adapter2 = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames2 = TestFrameSequence() .ClientPreface({{ENABLE_CONNECT_PROTOCOL, 1}}) .Settings({{ENABLE_CONNECT_PROTOCOL, 0}}) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSetting(Http2Setting{ENABLE_CONNECT_PROTOCOL, 1u})); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSetting(Http2Setting{ENABLE_CONNECT_PROTOCOL, 0u})); EXPECT_CALL(visitor, OnSettingsEnd()); read_result = adapter2->ProcessBytes(frames2); EXPECT_EQ(static_cast<size_t>(read_result), frames2.size()); EXPECT_TRUE(adapter2->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); adapter2->Send(); } TEST(NgHttp2AdapterTest, ServerForbidsProtocolPseudoheaderBeforeAck) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string initial_frames = TestFrameSequence().ClientPreface().Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(static_cast<size_t>(initial_result), initial_frames.size()); const std::string stream1_frames = TestFrameSequence() .Headers(1, {{":method", "CONNECT"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {":protocol", "websocket"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0x5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL( visitor, OnErrorDebug("Invalid HTTP header field was received: frame type: 1, " "stream: 1, name: [:protocol], value: [websocket]")); EXPECT_CALL( visitor, OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); int64_t stream_result = adapter->ProcessBytes(stream1_frames); EXPECT_EQ(static_cast<size_t>(stream_result), stream1_frames.size()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR)); adapter->SubmitSettings({{ENABLE_CONNECT_PROTOCOL, 1}}); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); visitor.Clear(); const std::string stream3_frames = TestFrameSequence() .Headers(3, {{":method", "CONNECT"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}, {":protocol", "websocket"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 0x5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(5); EXPECT_CALL(visitor, OnEndHeadersForStream(3)); EXPECT_CALL(visitor, OnEndStream(3)); stream_result = adapter->ProcessBytes(stream3_frames); EXPECT_EQ(static_cast<size_t>(stream_result), stream3_frames.size()); EXPECT_FALSE(adapter->want_write()); } TEST(NgHttp2AdapterTest, ServerAllowsProtocolPseudoheaderAfterAck) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); adapter->SubmitSettings({{ENABLE_CONNECT_PROTOCOL, 1}}); const std::string initial_frames = TestFrameSequence().ClientPreface().Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(static_cast<size_t>(initial_result), initial_frames.size()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .SettingsAck() .Headers(1, {{":method", "CONNECT"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {":protocol", "websocket"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, _, SETTINGS, 0x1)); EXPECT_CALL(visitor, OnSettingsAck()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0x5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(5); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(static_cast<size_t>(stream_result), stream_frames.size()); EXPECT_FALSE(adapter->want_write()); } TEST_P(NgHttp2AdapterDataTest, SkipsSendingFramesForRejectedStream) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string initial_frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0x5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(static_cast<size_t>(initial_result), initial_frames.size()); visitor.AppendPayloadForStream( 1, "Here is some data, which will be completely ignored!"); auto body = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse(1, ToHeaders({{":status", "200"}}), GetParam() ? nullptr : std::move(body), false); ASSERT_EQ(0, submit_result); auto source = std::make_unique<TestMetadataSource>(ToHeaderBlock(ToHeaders( {{"query-cost", "is too darn high"}, {"secret-sauce", "hollandaise"}}))); adapter->SubmitMetadata(1, 16384u, std::move(source)); adapter->SubmitWindowUpdate(1, 1024); adapter->SubmitRst(1, Http2ErrorCode::INTERNAL_ERROR); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(kMetadataFrameType, 1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(kMetadataFrameType, 1, _, 0x4, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, static_cast<int>(Http2ErrorCode::INTERNAL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::INTERNAL_ERROR)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, static_cast<SpdyFrameType>(kMetadataFrameType), SpdyFrameType::RST_STREAM})); } TEST_P(NgHttp2AdapterDataTest, ServerQueuesMetadataWithStreamReset) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string initial_frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0x4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(static_cast<size_t>(initial_result), initial_frames.size()); visitor.AppendPayloadForStream( 1, "Here is some data, which will be completely ignored!"); auto body = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse(1, ToHeaders({{":status", "200"}}), GetParam() ? nullptr : std::move(body), false); ASSERT_EQ(0, submit_result); auto source = std::make_unique<TestMetadataSource>(ToHeaderBlock(ToHeaders( {{"query-cost", "is too darn high"}, {"secret-sauce", "hollandaise"}}))); adapter->SubmitMetadata(1, 16384u, std::move(source)); adapter->SubmitWindowUpdate(1, 1024); const std::string reset_frame = TestFrameSequence().RstStream(1, Http2ErrorCode::CANCEL).Serialize(); EXPECT_CALL(visitor, OnFrameHeader(1, _, RST_STREAM, 0x0)); EXPECT_CALL(visitor, OnRstStream(1, Http2ErrorCode::CANCEL)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::CANCEL)); adapter->ProcessBytes(reset_frame); source = std::make_unique<TestMetadataSource>( ToHeaderBlock(ToHeaders({{"really-important", "information!"}}))); adapter->SubmitMetadata(1, 16384u, std::move(source)); EXPECT_EQ(1, adapter->stream_metadata_size()); EXPECT_EQ(2, adapter->pending_metadata_count(1)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(kMetadataFrameType, 1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(kMetadataFrameType, 1, _, 0x4, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(kMetadataFrameType, 1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(kMetadataFrameType, 1, _, 0x4, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, static_cast<SpdyFrameType>(kMetadataFrameType), static_cast<SpdyFrameType>(kMetadataFrameType)})); EXPECT_EQ(0, adapter->stream_metadata_size()); EXPECT_EQ(0, adapter->pending_metadata_count(1)); } TEST(NgHttp2AdapterTest, ServerStartsShutdown) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); EXPECT_FALSE(adapter->want_write()); adapter->SubmitShutdownNotice(); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY})); } TEST(NgHttp2AdapterTest, ServerStartsShutdownAfterGoaway) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); EXPECT_FALSE(adapter->want_write()); adapter->SubmitGoAway(1, Http2ErrorCode::HTTP2_NO_ERROR, "and don't come back!"); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY})); adapter->SubmitShutdownNotice(); EXPECT_FALSE(adapter->want_write()); } TEST(NgHttp2AdapterTest, ConnectionErrorWithBlackholeSinkingData) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames = TestFrameSequence().ClientPreface().WindowUpdate(1, 42).Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnInvalidFrame(1, _)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(result), frames.size()); const std::string next_frame = TestFrameSequence().Ping(42).Serialize(); const int64_t next_result = adapter->ProcessBytes(next_frame); EXPECT_EQ(static_cast<size_t>(next_result), next_frame.size()); } TEST_P(NgHttp2AdapterDataTest, ServerDoesNotSendFramesAfterImmediateGoAway) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); adapter->SubmitSettings({{HEADER_TABLE_SIZE, 100u}}); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0x5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t read_result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(read_result), frames.size()); visitor.AppendPayloadForStream(1, "This data is doomed to never be written."); auto body = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse(1, ToHeaders({{":status", "200"}}), GetParam() ? nullptr : std::move(body), false); ASSERT_EQ(0, submit_result); adapter->SubmitWindowUpdate(kConnectionStreamId, 42); adapter->SubmitSettings({}); auto source = std::make_unique<TestMetadataSource>(ToHeaderBlock(ToHeaders( {{"query-cost", "is too darn high"}, {"secret-sauce", "hollandaise"}}))); adapter->SubmitMetadata(1, 16384u, std::move(source)); EXPECT_TRUE(adapter->want_write()); const std::string connection_error_frames = TestFrameSequence().WindowUpdate(3, 42).Serialize(); EXPECT_CALL(visitor, OnFrameHeader(3, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnInvalidFrame(3, _)); const int64_t result = adapter->ProcessBytes(connection_error_frames); EXPECT_EQ(static_cast<size_t>(result), connection_error_frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY})); visitor.Clear(); adapter->SubmitPing(42); EXPECT_FALSE(adapter->want_write()); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), testing::IsEmpty()); } TEST(NgHttp2AdapterTest, ServerHandlesContentLength) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); testing::InSequence s; const std::string stream_frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"content-length", "2"}}) .Data(1, "hi", true) .Headers(3, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}, {"content-length", "nan"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(5); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 1)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 2)); EXPECT_CALL(visitor, OnDataForStream(1, "hi")); EXPECT_CALL(visitor, OnEndStream(1)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(4); EXPECT_CALL( visitor, OnErrorDebug("Invalid HTTP header field was received: frame type: 1, " "stream: 3, name: [content-length], value: [nan]")); EXPECT_CALL( visitor, OnInvalidFrame(3, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 3, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 3, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::PROTOCOL_ERROR)); EXPECT_TRUE(adapter->want_write()); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST(NgHttp2AdapterTest, ServerHandlesContentLengthMismatch) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); testing::InSequence s; const std::string stream_frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}, {"content-length", "2"}}) .Data(1, "h", true) .Headers(3, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/three"}, {"content-length", "2"}}) .Data(3, "howdy", true) .Headers(5, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/four"}, {"content-length", "2"}}, true) .Headers(7, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/four"}, {"content-length", "2"}}, false) .Data(7, "h", false) .Headers(7, {{"extra-info", "Trailers with content-length mismatch"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(5); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 1)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 1)); EXPECT_CALL(visitor, OnDataForStream(1, "h")); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(5); EXPECT_CALL(visitor, OnEndHeadersForStream(3)); EXPECT_CALL(visitor, OnFrameHeader(3, _, DATA, 1)); EXPECT_CALL(visitor, OnBeginDataForStream(3, 5)); EXPECT_CALL(visitor, OnFrameHeader(5, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(5)); EXPECT_CALL(visitor, OnHeaderForStream(5, _, _)).Times(5); EXPECT_CALL(visitor, OnInvalidFrame( 5, Http2VisitorInterface::InvalidFrameError::kHttpMessaging)); EXPECT_CALL(visitor, OnFrameHeader(7, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(7)); EXPECT_CALL(visitor, OnHeaderForStream(7, _, _)).Times(5); EXPECT_CALL(visitor, OnEndHeadersForStream(7)); EXPECT_CALL(visitor, OnFrameHeader(7, _, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(7, 1)); EXPECT_CALL(visitor, OnDataForStream(7, "h")); EXPECT_CALL(visitor, OnFrameHeader(7, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(7)); EXPECT_CALL(visitor, OnHeaderForStream(7, _, _)); EXPECT_CALL(visitor, OnInvalidFrame( 7, Http2VisitorInterface::InvalidFrameError::kHttpMessaging)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 3, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 3, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::PROTOCOL_ERROR)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 5, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 5, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(5, Http2ErrorCode::PROTOCOL_ERROR)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 7, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 7, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(7, Http2ErrorCode::PROTOCOL_ERROR)); EXPECT_TRUE(adapter->want_write()); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT( visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM, SpdyFrameType::RST_STREAM, SpdyFrameType::RST_STREAM, SpdyFrameType::RST_STREAM})); } TEST(NgHttp2AdapterTest, ServerHandlesAsteriskPathForOptions) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); testing::InSequence s; const std::string stream_frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":scheme", "https"}, {":authority", "example.com"}, {":path", "*"}, {":method", "OPTIONS"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_TRUE(adapter->want_write()); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); } TEST(NgHttp2AdapterTest, ServerHandlesInvalidPath) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); testing::InSequence s; const std::string stream_frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":scheme", "https"}, {":authority", "example.com"}, {":path", "*"}, {":method", "GET"}}, true) .Headers(3, {{":scheme", "https"}, {":authority", "example.com"}, {":path", "other/non/slash/starter"}, {":method", "GET"}}, true) .Headers(5, {{":scheme", "https"}, {":authority", "example.com"}, {":path", ""}, {":method", "GET"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnInvalidFrame( 1, Http2VisitorInterface::InvalidFrameError::kHttpMessaging)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(4); EXPECT_CALL(visitor, OnInvalidFrame( 3, Http2VisitorInterface::InvalidFrameError::kHttpMessaging)); EXPECT_CALL(visitor, OnFrameHeader(5, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(5)); EXPECT_CALL(visitor, OnHeaderForStream(5, _, _)).Times(2); EXPECT_CALL( visitor, OnErrorDebug("Invalid HTTP header field was received: frame type: 1, " "stream: 5, name: [:path], value: []")); EXPECT_CALL( visitor, OnInvalidFrame(5, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 3, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 3, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::PROTOCOL_ERROR)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 5, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 5, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(5, Http2ErrorCode::PROTOCOL_ERROR)); EXPECT_TRUE(adapter->want_write()); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT( visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM, SpdyFrameType::RST_STREAM, SpdyFrameType::RST_STREAM})); } TEST(NgHttp2AdapterTest, ServerHandlesTeHeader) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); testing::InSequence s; const std::string stream_frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":scheme", "https"}, {":authority", "example.com"}, {":path", "/"}, {":method", "GET"}, {"te", "trailers"}}, true) .Headers(3, {{":scheme", "https"}, {":authority", "example.com"}, {":path", "/"}, {":method", "GET"}, {"te", "trailers, deflate"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(5); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(4); EXPECT_CALL( visitor, OnErrorDebug("Invalid HTTP header field was received: frame type: 1, " "stream: 3, name: [te], value: [trailers, deflate]")); EXPECT_CALL( visitor, OnInvalidFrame(3, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 3, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 3, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::PROTOCOL_ERROR)); EXPECT_TRUE(adapter->want_write()); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST(NgHttp2AdapterTest, ServerHandlesConnectionSpecificHeaders) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); testing::InSequence s; const std::string stream_frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":scheme", "https"}, {":authority", "example.com"}, {":path", "/"}, {":method", "GET"}, {"connection", "keep-alive"}}, true) .Headers(3, {{":scheme", "https"}, {":authority", "example.com"}, {":path", "/"}, {":method", "GET"}, {"proxy-connection", "keep-alive"}}, true) .Headers(5, {{":scheme", "https"}, {":authority", "example.com"}, {":path", "/"}, {":method", "GET"}, {"keep-alive", "timeout=42"}}, true) .Headers(7, {{":scheme", "https"}, {":authority", "example.com"}, {":path", "/"}, {":method", "GET"}, {"transfer-encoding", "chunked"}}, true) .Headers(9, {{":scheme", "https"}, {":authority", "example.com"}, {":path", "/"}, {":method", "GET"}, {"upgrade", "h2c"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL( visitor, OnErrorDebug("Invalid HTTP header field was received: frame type: 1, " "stream: 1, name: [connection], value: [keep-alive]")); EXPECT_CALL( visitor, OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(4); EXPECT_CALL( visitor, OnErrorDebug("Invalid HTTP header field was received: frame type: 1, " "stream: 3, name: [proxy-connection], value: [keep-alive]")); EXPECT_CALL( visitor, OnInvalidFrame(3, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); EXPECT_CALL(visitor, OnFrameHeader(5, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(5)); EXPECT_CALL(visitor, OnHeaderForStream(5, _, _)).Times(4); EXPECT_CALL( visitor, OnErrorDebug("Invalid HTTP header field was received: frame type: 1, " "stream: 5, name: [keep-alive], value: [timeout=42]")); EXPECT_CALL( visitor, OnInvalidFrame(5, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); EXPECT_CALL(visitor, OnFrameHeader(7, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(7)); EXPECT_CALL(visitor, OnHeaderForStream(7, _, _)).Times(4); EXPECT_CALL( visitor, OnErrorDebug("Invalid HTTP header field was received: frame type: 1, " "stream: 7, name: [transfer-encoding], value: [chunked]")); EXPECT_CALL( visitor, OnInvalidFrame(7, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); EXPECT_CALL(visitor, OnFrameHeader(9, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(9)); EXPECT_CALL(visitor, OnHeaderForStream(9, _, _)).Times(4); EXPECT_CALL( visitor, OnErrorDebug("Invalid HTTP header field was received: frame type: 1, " "stream: 9, name: [upgrade], value: [h2c]")); EXPECT_CALL( visitor, OnInvalidFrame(9, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 3, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 3, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::PROTOCOL_ERROR)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 5, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 5, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(5, Http2ErrorCode::PROTOCOL_ERROR)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 7, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 7, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(7, Http2ErrorCode::PROTOCOL_ERROR)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 9, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 9, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(9, Http2ErrorCode::PROTOCOL_ERROR)); EXPECT_TRUE(adapter->want_write()); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT( visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM, SpdyFrameType::RST_STREAM, SpdyFrameType::RST_STREAM, SpdyFrameType::RST_STREAM, SpdyFrameType::RST_STREAM})); } TEST(OgHttp2AdapterTest, ServerConsumesDataWithPadding) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); TestFrameSequence seq = std::move(TestFrameSequence().ClientPreface().Headers( 1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false)); size_t total_size = 0; while (total_size < 62 * 1024) { seq.Data(1, "a", false, 254); total_size += 255; } const std::string frames = seq.Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0x8)) .Times(testing::AtLeast(1)); EXPECT_CALL(visitor, OnBeginDataForStream(1, _)).Times(testing::AtLeast(1)); EXPECT_CALL(visitor, OnDataForStream(1, "a")).Times(testing::AtLeast(1)); EXPECT_CALL(visitor, OnDataPaddingLength(1, _)).Times(testing::AtLeast(1)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(result, frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 1, _, 0x0)).Times(1); EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 1, _, 0x0, 0)).Times(1); EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 0, _, 0x0)).Times(1); EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 0, _, 0x0, 0)).Times(1); const int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::WINDOW_UPDATE, SpdyFrameType::WINDOW_UPDATE})); } TEST_P(NgHttp2AdapterDataTest, NegativeFlowControlStreamResumption) { TestVisitor visitor; auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames = TestFrameSequence() .ClientPreface({{INITIAL_WINDOW_SIZE, 128u * 1024u}}) .WindowUpdate(0, 1 << 20) .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSetting(Http2Setting{Http2KnownSettingsId::INITIAL_WINDOW_SIZE, 128u * 1024u})); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(0, 1 << 20)); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0x5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t read_result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(read_result), frames.size()); visitor.AppendPayloadForStream(1, std::string(70000, 'a')); auto body = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse(1, ToHeaders({{":status", "200"}}), GetParam() ? nullptr : std::move(body), false); ASSERT_EQ(0, submit_result); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0)).Times(5); adapter->Send(); EXPECT_FALSE(adapter->want_write()); EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSetting(Http2Setting{Http2KnownSettingsId::INITIAL_WINDOW_SIZE, 64u * 1024u})); EXPECT_CALL(visitor, OnSettingsEnd()); adapter->ProcessBytes(TestFrameSequence() .Settings({{INITIAL_WINDOW_SIZE, 64u * 1024u}}) .Serialize()); EXPECT_TRUE(adapter->want_write()); EXPECT_EQ(adapter->GetStreamSendWindowSize(1), 0); visitor.AppendPayloadForStream(1, "Stream should be resumed."); adapter->ResumeStream(1); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); adapter->Send(); EXPECT_FALSE(adapter->want_write()); EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(1, 10000)); adapter->ProcessBytes(TestFrameSequence().WindowUpdate(1, 10000).Serialize()); EXPECT_TRUE(adapter->want_write()); EXPECT_GT(adapter->GetStreamSendWindowSize(1), 0); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0)); adapter->Send(); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/nghttp2_adapter.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/nghttp2_adapter_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
4edb19f6-cee0-47a3-8de4-a5364205c64d
cpp
google/quiche
oghttp2_session
quiche/http2/adapter/oghttp2_session.cc
quiche/http2/adapter/oghttp2_session_test.cc
#include "quiche/http2/adapter/oghttp2_session.h" #include <algorithm> #include <cstdint> #include <limits> #include <memory> #include <optional> #include <string> #include <tuple> #include <utility> #include <vector> #include "absl/cleanup/cleanup.h" #include "absl/memory/memory.h" #include "absl/strings/escaping.h" #include "quiche/http2/adapter/header_validator.h" #include "quiche/http2/adapter/http2_protocol.h" #include "quiche/http2/adapter/http2_util.h" #include "quiche/http2/adapter/http2_visitor_interface.h" #include "quiche/http2/adapter/noop_header_validator.h" #include "quiche/http2/adapter/oghttp2_util.h" #include "quiche/http2/core/spdy_protocol.h" #include "quiche/common/quiche_callbacks.h" namespace http2 { namespace adapter { namespace { using ConnectionError = Http2VisitorInterface::ConnectionError; using DataFrameHeaderInfo = Http2VisitorInterface::DataFrameHeaderInfo; using SpdyFramerError = Http2DecoderAdapter::SpdyFramerError; using ::spdy::SpdySettingsIR; const uint32_t kMaxAllowedMetadataFrameSize = 65536u; const uint32_t kDefaultHpackTableCapacity = 4096u; const uint32_t kMaximumHpackTableCapacity = 65536u; const int kSendError = -902; constexpr absl::string_view kHeadValue = "HEAD"; class FrameAttributeCollector : public spdy::SpdyFrameVisitor { public: FrameAttributeCollector() = default; void VisitData(const spdy::SpdyDataIR& data) override { frame_type_ = static_cast<uint8_t>(data.frame_type()); stream_id_ = data.stream_id(); flags_ = (data.fin() ? END_STREAM_FLAG : 0) | (data.padded() ? PADDED_FLAG : 0); } void VisitHeaders(const spdy::SpdyHeadersIR& headers) override { frame_type_ = static_cast<uint8_t>(headers.frame_type()); stream_id_ = headers.stream_id(); flags_ = END_HEADERS_FLAG | (headers.fin() ? END_STREAM_FLAG : 0) | (headers.padded() ? PADDED_FLAG : 0) | (headers.has_priority() ? PRIORITY_FLAG : 0); } void VisitPriority(const spdy::SpdyPriorityIR& priority) override { frame_type_ = static_cast<uint8_t>(priority.frame_type()); frame_type_ = 2; stream_id_ = priority.stream_id(); } void VisitRstStream(const spdy::SpdyRstStreamIR& rst_stream) override { frame_type_ = static_cast<uint8_t>(rst_stream.frame_type()); frame_type_ = 3; stream_id_ = rst_stream.stream_id(); error_code_ = rst_stream.error_code(); } void VisitSettings(const spdy::SpdySettingsIR& settings) override { frame_type_ = static_cast<uint8_t>(settings.frame_type()); frame_type_ = 4; flags_ = (settings.is_ack() ? ACK_FLAG : 0); } void VisitPushPromise(const spdy::SpdyPushPromiseIR& push_promise) override { frame_type_ = static_cast<uint8_t>(push_promise.frame_type()); frame_type_ = 5; stream_id_ = push_promise.stream_id(); flags_ = (push_promise.padded() ? PADDED_FLAG : 0); } void VisitPing(const spdy::SpdyPingIR& ping) override { frame_type_ = static_cast<uint8_t>(ping.frame_type()); frame_type_ = 6; flags_ = (ping.is_ack() ? ACK_FLAG : 0); } void VisitGoAway(const spdy::SpdyGoAwayIR& goaway) override { frame_type_ = static_cast<uint8_t>(goaway.frame_type()); frame_type_ = 7; error_code_ = goaway.error_code(); } void VisitWindowUpdate( const spdy::SpdyWindowUpdateIR& window_update) override { frame_type_ = static_cast<uint8_t>(window_update.frame_type()); frame_type_ = 8; stream_id_ = window_update.stream_id(); } void VisitContinuation( const spdy::SpdyContinuationIR& continuation) override { frame_type_ = static_cast<uint8_t>(continuation.frame_type()); stream_id_ = continuation.stream_id(); flags_ = continuation.end_headers() ? END_HEADERS_FLAG : 0; } void VisitUnknown(const spdy::SpdyUnknownIR& unknown) override { frame_type_ = static_cast<uint8_t>(unknown.frame_type()); stream_id_ = unknown.stream_id(); flags_ = unknown.flags(); } void VisitAltSvc(const spdy::SpdyAltSvcIR& ) override {} void VisitPriorityUpdate( const spdy::SpdyPriorityUpdateIR& ) override {} void VisitAcceptCh(const spdy::SpdyAcceptChIR& ) override {} uint32_t stream_id() { return stream_id_; } uint32_t error_code() { return error_code_; } uint8_t frame_type() { return frame_type_; } uint8_t flags() { return flags_; } private: uint32_t stream_id_ = 0; uint32_t error_code_ = 0; uint8_t frame_type_ = 0; uint8_t flags_ = 0; }; absl::string_view TracePerspectiveAsString(Perspective p) { switch (p) { case Perspective::kClient: return "OGHTTP2_CLIENT"; case Perspective::kServer: return "OGHTTP2_SERVER"; } return "OGHTTP2_SERVER"; } Http2ErrorCode GetHttp2ErrorCode(SpdyFramerError error) { switch (error) { case SpdyFramerError::SPDY_NO_ERROR: return Http2ErrorCode::HTTP2_NO_ERROR; case SpdyFramerError::SPDY_INVALID_STREAM_ID: case SpdyFramerError::SPDY_INVALID_CONTROL_FRAME: case SpdyFramerError::SPDY_INVALID_PADDING: case SpdyFramerError::SPDY_INVALID_DATA_FRAME_FLAGS: case SpdyFramerError::SPDY_UNEXPECTED_FRAME: return Http2ErrorCode::PROTOCOL_ERROR; case SpdyFramerError::SPDY_CONTROL_PAYLOAD_TOO_LARGE: case SpdyFramerError::SPDY_INVALID_CONTROL_FRAME_SIZE: case SpdyFramerError::SPDY_OVERSIZED_PAYLOAD: return Http2ErrorCode::FRAME_SIZE_ERROR; case SpdyFramerError::SPDY_DECOMPRESS_FAILURE: case SpdyFramerError::SPDY_HPACK_INDEX_VARINT_ERROR: case SpdyFramerError::SPDY_HPACK_NAME_LENGTH_VARINT_ERROR: case SpdyFramerError::SPDY_HPACK_VALUE_LENGTH_VARINT_ERROR: case SpdyFramerError::SPDY_HPACK_NAME_TOO_LONG: case SpdyFramerError::SPDY_HPACK_VALUE_TOO_LONG: case SpdyFramerError::SPDY_HPACK_NAME_HUFFMAN_ERROR: case SpdyFramerError::SPDY_HPACK_VALUE_HUFFMAN_ERROR: case SpdyFramerError::SPDY_HPACK_MISSING_DYNAMIC_TABLE_SIZE_UPDATE: case SpdyFramerError::SPDY_HPACK_INVALID_INDEX: case SpdyFramerError::SPDY_HPACK_INVALID_NAME_INDEX: case SpdyFramerError::SPDY_HPACK_DYNAMIC_TABLE_SIZE_UPDATE_NOT_ALLOWED: case SpdyFramerError:: SPDY_HPACK_INITIAL_DYNAMIC_TABLE_SIZE_UPDATE_IS_ABOVE_LOW_WATER_MARK: case SpdyFramerError:: SPDY_HPACK_DYNAMIC_TABLE_SIZE_UPDATE_IS_ABOVE_ACKNOWLEDGED_SETTING: case SpdyFramerError::SPDY_HPACK_TRUNCATED_BLOCK: case SpdyFramerError::SPDY_HPACK_FRAGMENT_TOO_LONG: case SpdyFramerError::SPDY_HPACK_COMPRESSED_HEADER_SIZE_EXCEEDS_LIMIT: return Http2ErrorCode::COMPRESSION_ERROR; case SpdyFramerError::SPDY_INTERNAL_FRAMER_ERROR: case SpdyFramerError::SPDY_STOP_PROCESSING: case SpdyFramerError::LAST_ERROR: return Http2ErrorCode::INTERNAL_ERROR; } return Http2ErrorCode::INTERNAL_ERROR; } bool IsResponse(HeaderType type) { return type == HeaderType::RESPONSE_100 || type == HeaderType::RESPONSE; } bool StatusIs1xx(absl::string_view status) { return status.size() == 3 && status[0] == '1'; } uint32_t HpackCapacityBound(const OgHttp2Session::Options& o) { return o.max_hpack_encoding_table_capacity.value_or( kMaximumHpackTableCapacity); } bool IsNonAckSettings(const spdy::SpdyFrameIR& frame) { return frame.frame_type() == spdy::SpdyFrameType::SETTINGS && !reinterpret_cast<const SpdySettingsIR&>(frame).is_ack(); } } OgHttp2Session::PassthroughHeadersHandler::PassthroughHeadersHandler( OgHttp2Session& session, Http2VisitorInterface& visitor) : session_(session), visitor_(visitor) { if (session_.options_.validate_http_headers) { QUICHE_VLOG(2) << "instantiating regular header validator"; validator_ = std::make_unique<HeaderValidator>(); if (session_.options_.validate_path) { validator_->SetValidatePath(); } if (session_.options_.allow_fragment_in_path) { validator_->SetAllowFragmentInPath(); } if (session_.options_.allow_different_host_and_authority) { validator_->SetAllowDifferentHostAndAuthority(); } } else { QUICHE_VLOG(2) << "instantiating noop header validator"; validator_ = std::make_unique<NoopHeaderValidator>(); } } void OgHttp2Session::PassthroughHeadersHandler::OnHeaderBlockStart() { Reset(); const bool status = visitor_.OnBeginHeadersForStream(stream_id_); if (!status) { QUICHE_VLOG(1) << "Visitor rejected header block, returning HEADER_CONNECTION_ERROR"; SetResult(Http2VisitorInterface::HEADER_CONNECTION_ERROR); } validator_->StartHeaderBlock(); } Http2VisitorInterface::OnHeaderResult InterpretHeaderStatus( HeaderValidator::HeaderStatus status) { switch (status) { case HeaderValidator::HEADER_OK: case HeaderValidator::HEADER_SKIP: return Http2VisitorInterface::HEADER_OK; case HeaderValidator::HEADER_FIELD_INVALID: return Http2VisitorInterface::HEADER_FIELD_INVALID; case HeaderValidator::HEADER_FIELD_TOO_LONG: return Http2VisitorInterface::HEADER_RST_STREAM; } return Http2VisitorInterface::HEADER_CONNECTION_ERROR; } void OgHttp2Session::PassthroughHeadersHandler::OnHeader( absl::string_view key, absl::string_view value) { if (error_encountered_) { QUICHE_VLOG(2) << "Early return; status not HEADER_OK"; return; } const HeaderValidator::HeaderStatus validation_result = validator_->ValidateSingleHeader(key, value); if (validation_result == HeaderValidator::HEADER_SKIP) { return; } if (validation_result != HeaderValidator::HEADER_OK) { QUICHE_VLOG(2) << "Header validation failed with result " << static_cast<int>(validation_result); SetResult(InterpretHeaderStatus(validation_result)); return; } const Http2VisitorInterface::OnHeaderResult result = visitor_.OnHeaderForStream(stream_id_, key, value); SetResult(result); } void OgHttp2Session::PassthroughHeadersHandler::OnHeaderBlockEnd( size_t , size_t ) { if (error_encountered_) { return; } if (!validator_->FinishHeaderBlock(type_)) { QUICHE_VLOG(1) << "FinishHeaderBlock returned false; returning " << "HEADER_HTTP_MESSAGING"; SetResult(Http2VisitorInterface::HEADER_HTTP_MESSAGING); return; } if (frame_contains_fin_ && IsResponse(type_) && StatusIs1xx(status_header())) { QUICHE_VLOG(1) << "Unexpected end of stream without final headers"; SetResult(Http2VisitorInterface::HEADER_HTTP_MESSAGING); return; } const bool result = visitor_.OnEndHeadersForStream(stream_id_); if (!result) { session_.fatal_visitor_callback_failure_ = true; session_.decoder_.StopProcessing(); } } bool OgHttp2Session::PassthroughHeadersHandler::CanReceiveBody() const { switch (header_type()) { case HeaderType::REQUEST_TRAILER: case HeaderType::RESPONSE_TRAILER: case HeaderType::RESPONSE_100: return false; case HeaderType::RESPONSE: return status_header() != "304" && status_header() != "204"; case HeaderType::REQUEST: return true; } return true; } void OgHttp2Session::PassthroughHeadersHandler::SetResult( Http2VisitorInterface::OnHeaderResult result) { if (result != Http2VisitorInterface::HEADER_OK) { error_encountered_ = true; session_.OnHeaderStatus(stream_id_, result); } } struct OgHttp2Session::ProcessBytesResultVisitor { int64_t operator()(const int64_t bytes) const { return bytes; } int64_t operator()(const ProcessBytesError error) const { switch (error) { case ProcessBytesError::kUnspecified: return -1; case ProcessBytesError::kInvalidConnectionPreface: return -903; case ProcessBytesError::kVisitorCallbackFailed: return -902; } return -1; } }; OgHttp2Session::OgHttp2Session(Http2VisitorInterface& visitor, Options options) : visitor_(visitor), options_(options), event_forwarder_([this]() { return !latched_error_; }, *this), receive_logger_( &event_forwarder_, TracePerspectiveAsString(options.perspective), [logging_enabled = GetQuicheFlag(quiche_oghttp2_debug_trace)]() { return logging_enabled; }, this), send_logger_( TracePerspectiveAsString(options.perspective), [logging_enabled = GetQuicheFlag(quiche_oghttp2_debug_trace)]() { return logging_enabled; }, this), headers_handler_(*this, visitor), noop_headers_handler_(nullptr), connection_window_manager_( kInitialFlowControlWindowSize, [this](size_t window_update_delta) { SendWindowUpdate(kConnectionStreamId, window_update_delta); }, options.should_window_update_fn, false), max_outbound_concurrent_streams_( options.remote_max_concurrent_streams.value_or(100u)) { decoder_.set_visitor(&receive_logger_); if (options_.max_header_list_bytes) { decoder_.GetHpackDecoder().set_max_decode_buffer_size_bytes( 2 * *options_.max_header_list_bytes); decoder_.GetHpackDecoder().set_max_header_block_bytes( 4 * *options_.max_header_list_bytes); } if (IsServerSession()) { remaining_preface_ = {spdy::kHttp2ConnectionHeaderPrefix, spdy::kHttp2ConnectionHeaderPrefixSize}; } if (options_.max_header_field_size.has_value()) { headers_handler_.SetMaxFieldSize(*options_.max_header_field_size); } headers_handler_.SetAllowObsText(options_.allow_obs_text); if (!options_.crumble_cookies) { framer_.GetHpackEncoder()->DisableCookieCrumbling(); } } OgHttp2Session::~OgHttp2Session() {} void OgHttp2Session::SetStreamUserData(Http2StreamId stream_id, void* user_data) { auto it = stream_map_.find(stream_id); if (it != stream_map_.end()) { it->second.user_data = user_data; } } void* OgHttp2Session::GetStreamUserData(Http2StreamId stream_id) { auto it = stream_map_.find(stream_id); if (it != stream_map_.end()) { return it->second.user_data; } auto p = pending_streams_.find(stream_id); if (p != pending_streams_.end()) { return p->second.user_data; } return nullptr; } bool OgHttp2Session::ResumeStream(Http2StreamId stream_id) { auto it = stream_map_.find(stream_id); if (it == stream_map_.end() || !HasMoreData(it->second) || !write_scheduler_.StreamRegistered(stream_id)) { return false; } it->second.data_deferred = false; write_scheduler_.MarkStreamReady(stream_id, false); return true; } int OgHttp2Session::GetStreamSendWindowSize(Http2StreamId stream_id) const { auto it = stream_map_.find(stream_id); if (it != stream_map_.end()) { return it->second.send_window; } return -1; } int OgHttp2Session::GetStreamReceiveWindowLimit(Http2StreamId stream_id) const { auto it = stream_map_.find(stream_id); if (it != stream_map_.end()) { return it->second.window_manager.WindowSizeLimit(); } return -1; } int OgHttp2Session::GetStreamReceiveWindowSize(Http2StreamId stream_id) const { auto it = stream_map_.find(stream_id); if (it != stream_map_.end()) { return it->second.window_manager.CurrentWindowSize(); } return -1; } int OgHttp2Session::GetReceiveWindowSize() const { return connection_window_manager_.CurrentWindowSize(); } int OgHttp2Session::GetHpackEncoderDynamicTableSize() const { const spdy::HpackEncoder* encoder = framer_.GetHpackEncoder(); return encoder == nullptr ? 0 : encoder->GetDynamicTableSize(); } int OgHttp2Session::GetHpackEncoderDynamicTableCapacity() const { const spdy::HpackEncoder* encoder = framer_.GetHpackEncoder(); return encoder == nullptr ? kDefaultHpackTableCapacity : encoder->CurrentHeaderTableSizeSetting(); } int OgHttp2Session::GetHpackDecoderDynamicTableSize() const { return decoder_.GetHpackDecoder().GetDynamicTableSize(); } int OgHttp2Session::GetHpackDecoderSizeLimit() const { return decoder_.GetHpackDecoder().GetCurrentHeaderTableSizeSetting(); } int64_t OgHttp2Session::ProcessBytes(absl::string_view bytes) { QUICHE_VLOG(2) << TracePerspectiveAsString(options_.perspective) << " processing [" << absl::CEscape(bytes) << "]"; return absl::visit(ProcessBytesResultVisitor(), ProcessBytesImpl(bytes)); } absl::variant<int64_t, OgHttp2Session::ProcessBytesError> OgHttp2Session::ProcessBytesImpl(absl::string_view bytes) { if (processing_bytes_) { QUICHE_VLOG(1) << "Returning early; already processing bytes."; return 0; } processing_bytes_ = true; auto cleanup = absl::MakeCleanup([this]() { processing_bytes_ = false; }); if (options_.blackhole_data_on_connection_error && latched_error_) { return static_cast<int64_t>(bytes.size()); } int64_t preface_consumed = 0; if (!remaining_preface_.empty()) { QUICHE_VLOG(2) << "Preface bytes remaining: " << remaining_preface_.size(); size_t min_size = std::min(remaining_preface_.size(), bytes.size()); if (!absl::StartsWith(remaining_preface_, bytes.substr(0, min_size))) { QUICHE_DLOG(INFO) << "Preface doesn't match! Expected: [" << absl::CEscape(remaining_preface_) << "], actual: [" << absl::CEscape(bytes) << "]"; LatchErrorAndNotify(Http2ErrorCode::PROTOCOL_ERROR, ConnectionError::kInvalidConnectionPreface); return ProcessBytesError::kInvalidConnectionPreface; } remaining_preface_.remove_prefix(min_size); bytes.remove_prefix(min_size); if (!remaining_preface_.empty()) { QUICHE_VLOG(2) << "Preface bytes remaining: " << remaining_preface_.size(); return static_cast<int64_t>(min_size); } preface_consumed = min_size; } int64_t result = decoder_.ProcessInput(bytes.data(), bytes.size()); QUICHE_VLOG(2) << "ProcessBytes result: " << result; if (fatal_visitor_callback_failure_) { QUICHE_DCHECK(latched_error_); QUICHE_VLOG(2) << "Visitor callback failed while processing bytes."; return ProcessBytesError::kVisitorCallbackFailed; } if (latched_error_ || result < 0) { QUICHE_VLOG(2) << "ProcessBytes encountered an error."; if (options_.blackhole_data_on_connection_error) { return static_cast<int64_t>(bytes.size() + preface_consumed); } else { return ProcessBytesError::kUnspecified; } } return result + preface_consumed; } int OgHttp2Session::Consume(Http2StreamId stream_id, size_t num_bytes) { auto it = stream_map_.find(stream_id); if (it == stream_map_.end()) { QUICHE_VLOG(1) << "Stream " << stream_id << " not found when consuming " << num_bytes << " bytes"; } else { it->second.window_manager.MarkDataFlushed(num_bytes); } connection_window_manager_.MarkDataFlushed(num_bytes); return 0; } void OgHttp2Session::StartGracefulShutdown() { if (IsServerSession()) { if (!queued_goaway_) { EnqueueFrame(std::make_unique<spdy::SpdyGoAwayIR>( std::numeric_limits<int32_t>::max(), spdy::ERROR_CODE_NO_ERROR, "graceful_shutdown")); } } else { QUICHE_LOG(ERROR) << "Graceful shutdown not needed for clients."; } } void OgHttp2Session::EnqueueFrame(std::unique_ptr<spdy::SpdyFrameIR> frame) { if (queued_immediate_goaway_) { return; } const bool is_non_ack_settings = IsNonAckSettings(*frame); MaybeSetupPreface(is_non_ack_settings); if (frame->frame_type() == spdy::SpdyFrameType::GOAWAY) { queued_goaway_ = true; if (latched_error_) { PrepareForImmediateGoAway(); } } else if (frame->fin() || frame->frame_type() == spdy::SpdyFrameType::RST_STREAM) { auto iter = stream_map_.find(frame->stream_id()); if (iter != stream_map_.end()) { iter->second.half_closed_local = true; } if (frame->frame_type() == spdy::SpdyFrameType::RST_STREAM) { streams_reset_.insert(frame->stream_id()); } } else if (frame->frame_type() == spdy::SpdyFrameType::WINDOW_UPDATE) { UpdateReceiveWindow( frame->stream_id(), reinterpret_cast<spdy::SpdyWindowUpdateIR&>(*frame).delta()); } else if (is_non_ack_settings) { HandleOutboundSettings( *reinterpret_cast<spdy::SpdySettingsIR*>(frame.get())); } if (frame->stream_id() != 0) { auto result = queued_frames_.insert({frame->stream_id(), 1}); if (!result.second) { ++(result.first->second); } } frames_.push_back(std::move(frame)); } int OgHttp2Session::Send() { if (sending_) { QUICHE_VLOG(1) << TracePerspectiveAsString(options_.perspective) << " returning early; already sending."; return 0; } sending_ = true; auto cleanup = absl::MakeCleanup([this]() { sending_ = false; }); if (fatal_send_error_) { return kSendError; } MaybeSetupPreface(false); SendResult continue_writing = SendQueuedFrames(); if (queued_immediate_goaway_) { return InterpretSendResult(continue_writing); } CloseGoAwayRejectedStreams(); while (continue_writing == SendResult::SEND_OK && HasReadyStream()) { const Http2StreamId stream_id = GetNextReadyStream(); QUICHE_VLOG(1) << "Waking stream " << stream_id << " for writes."; continue_writing = WriteForStream(stream_id); } if (continue_writing == SendResult::SEND_OK) { continue_writing = SendQueuedFrames(); } return InterpretSendResult(continue_writing); } int OgHttp2Session::InterpretSendResult(SendResult result) { if (result == SendResult::SEND_ERROR) { fatal_send_error_ = true; return kSendError; } else { return 0; } } bool OgHttp2Session::HasReadyStream() const { return !trailers_ready_.empty() || (write_scheduler_.HasReadyStreams() && connection_send_window_ > 0); } Http2StreamId OgHttp2Session::GetNextReadyStream() { QUICHE_DCHECK(HasReadyStream()); if (!trailers_ready_.empty()) { const Http2StreamId stream_id = *trailers_ready_.begin(); write_scheduler_.MarkStreamNotReady(stream_id); trailers_ready_.erase(trailers_ready_.begin()); return stream_id; } return write_scheduler_.PopNextReadyStream(); } int32_t OgHttp2Session::SubmitRequestInternal( absl::Span<const Header> headers, std::unique_ptr<DataFrameSource> data_source, bool end_stream, void* user_data) { const Http2StreamId stream_id = next_stream_id_; next_stream_id_ += 2; if (!pending_streams_.empty() || !CanCreateStream()) { pending_streams_.insert( {stream_id, PendingStreamState{ToHeaderBlock(headers), std::move(data_source), user_data, end_stream}}); StartPendingStreams(); } else { StartRequest(stream_id, ToHeaderBlock(headers), std::move(data_source), user_data, end_stream); } return stream_id; } int OgHttp2Session::SubmitResponseInternal( Http2StreamId stream_id, absl::Span<const Header> headers, std::unique_ptr<DataFrameSource> data_source, bool end_stream) { auto iter = stream_map_.find(stream_id); if (iter == stream_map_.end()) { QUICHE_LOG(ERROR) << "Unable to find stream " << stream_id; return -501; } if (data_source != nullptr) { iter->second.outbound_body = std::move(data_source); write_scheduler_.MarkStreamReady(stream_id, false); } else if (!end_stream) { iter->second.check_visitor_for_body = true; write_scheduler_.MarkStreamReady(stream_id, false); } SendHeaders(stream_id, ToHeaderBlock(headers), end_stream); return 0; } OgHttp2Session::SendResult OgHttp2Session::MaybeSendBufferedData() { int64_t result = std::numeric_limits<int64_t>::max(); while (result > 0 && !buffered_data_.Empty()) { result = visitor_.OnReadyToSend(buffered_data_.GetPrefix()); if (result > 0) { buffered_data_.RemovePrefix(result); } } if (result < 0) { LatchErrorAndNotify(Http2ErrorCode::INTERNAL_ERROR, ConnectionError::kSendError); return SendResult::SEND_ERROR; } return buffered_data_.Empty() ? SendResult::SEND_OK : SendResult::SEND_BLOCKED; } OgHttp2Session::SendResult OgHttp2Session::SendQueuedFrames() { if (const SendResult result = MaybeSendBufferedData(); result != SendResult::SEND_OK) { return result; } while (!frames_.empty()) { const auto& frame_ptr = frames_.front(); FrameAttributeCollector c; frame_ptr->Visit(&c); QUICHE_DCHECK_NE(c.frame_type(), 0); const bool stream_reset = c.stream_id() != 0 && streams_reset_.count(c.stream_id()) > 0; if (stream_reset && c.frame_type() != static_cast<uint8_t>(FrameType::RST_STREAM)) { DecrementQueuedFrameCount(c.stream_id(), c.frame_type()); frames_.pop_front(); continue; } else if (!IsServerSession() && received_goaway_ && c.stream_id() > static_cast<uint32_t>(received_goaway_stream_id_)) { frames_.pop_front(); continue; } spdy::SpdySerializedFrame frame = framer_.SerializeFrame(*frame_ptr); const size_t frame_payload_length = frame.size() - spdy::kFrameHeaderSize; frame_ptr->Visit(&send_logger_); visitor_.OnBeforeFrameSent(c.frame_type(), c.stream_id(), frame_payload_length, c.flags()); const int64_t result = visitor_.OnReadyToSend(absl::string_view(frame)); if (result < 0) { LatchErrorAndNotify(Http2ErrorCode::INTERNAL_ERROR, ConnectionError::kSendError); return SendResult::SEND_ERROR; } else if (result == 0) { return SendResult::SEND_BLOCKED; } else { frames_.pop_front(); const bool ok = AfterFrameSent(c.frame_type(), c.stream_id(), frame_payload_length, c.flags(), c.error_code()); if (!ok) { LatchErrorAndNotify(Http2ErrorCode::INTERNAL_ERROR, ConnectionError::kSendError); return SendResult::SEND_ERROR; } if (static_cast<size_t>(result) < frame.size()) { buffered_data_.Append( absl::string_view(frame.data() + result, frame.size() - result)); return SendResult::SEND_BLOCKED; } } } return SendResult::SEND_OK; } bool OgHttp2Session::AfterFrameSent(uint8_t frame_type_int, uint32_t stream_id, size_t payload_length, uint8_t flags, uint32_t error_code) { const FrameType frame_type = static_cast<FrameType>(frame_type_int); int result = visitor_.OnFrameSent(frame_type_int, stream_id, payload_length, flags, error_code); if (result < 0) { return false; } if (stream_id == 0) { if (frame_type == FrameType::SETTINGS) { const bool is_settings_ack = (flags & ACK_FLAG); if (is_settings_ack && encoder_header_table_capacity_when_acking_) { framer_.UpdateHeaderEncoderTableSize( *encoder_header_table_capacity_when_acking_); encoder_header_table_capacity_when_acking_ = std::nullopt; } else if (!is_settings_ack) { sent_non_ack_settings_ = true; } } return true; } const bool contains_fin = (frame_type == FrameType::DATA || frame_type == FrameType::HEADERS) && (flags & END_STREAM_FLAG) == END_STREAM_FLAG; auto it = stream_map_.find(stream_id); const bool still_open_remote = it != stream_map_.end() && !it->second.half_closed_remote; if (contains_fin && still_open_remote && options_.rst_stream_no_error_when_incomplete && IsServerSession()) { frames_.push_front(std::make_unique<spdy::SpdyRstStreamIR>( stream_id, spdy::SpdyErrorCode::ERROR_CODE_NO_ERROR)); auto queued_result = queued_frames_.insert({stream_id, 1}); if (!queued_result.second) { ++(queued_result.first->second); } it->second.half_closed_remote = true; } DecrementQueuedFrameCount(stream_id, frame_type_int); return true; } OgHttp2Session::SendResult OgHttp2Session::WriteForStream( Http2StreamId stream_id) { auto it = stream_map_.find(stream_id); if (it == stream_map_.end()) { QUICHE_LOG(ERROR) << "Can't find stream " << stream_id << " which is ready to write!"; return SendResult::SEND_OK; } StreamState& state = it->second; auto reset_it = streams_reset_.find(stream_id); if (reset_it != streams_reset_.end()) { AbandonData(state); state.trailers = nullptr; return SendResult::SEND_OK; } SendResult connection_can_write = SendResult::SEND_OK; if (!IsReadyToWriteData(state)) { if (state.trailers != nullptr) { AbandonData(state); auto block_ptr = std::move(state.trailers); if (state.half_closed_local) { QUICHE_LOG(ERROR) << "Sent fin; can't send trailers."; CloseStream(stream_id, Http2ErrorCode::INTERNAL_ERROR); } else { SendTrailers(stream_id, std::move(*block_ptr)); } } return SendResult::SEND_OK; } int32_t available_window = std::min({connection_send_window_, state.send_window, static_cast<int32_t>(max_frame_payload_)}); while (connection_can_write == SendResult::SEND_OK && available_window > 0 && IsReadyToWriteData(state)) { DataFrameHeaderInfo info = GetDataFrameInfo(stream_id, available_window, state); QUICHE_VLOG(2) << "WriteForStream | length: " << info.payload_length << " end_data: " << info.end_data << " end_stream: " << info.end_stream << " trailers: " << state.trailers.get(); if (info.payload_length == 0 && !info.end_data && state.trailers == nullptr) { state.data_deferred = true; break; } else if (info.payload_length == DataFrameSource::kError) { CloseStream(stream_id, Http2ErrorCode::INTERNAL_ERROR); break; } if (info.payload_length > 0 || info.end_stream) { spdy::SpdyDataIR data(stream_id); data.set_fin(info.end_stream); data.SetDataShallow(info.payload_length); spdy::SpdySerializedFrame header = spdy::SpdyFramer::SerializeDataFrameHeaderWithPaddingLengthField( data); QUICHE_DCHECK(buffered_data_.Empty() && frames_.empty()); data.Visit(&send_logger_); const bool success = SendDataFrame(stream_id, absl::string_view(header), info.payload_length, state); if (!success) { connection_can_write = SendResult::SEND_BLOCKED; break; } connection_send_window_ -= info.payload_length; state.send_window -= info.payload_length; available_window = std::min({connection_send_window_, state.send_window, static_cast<int32_t>(max_frame_payload_)}); if (info.end_stream) { state.half_closed_local = true; MaybeFinWithRstStream(it); } const bool ok = AfterFrameSent( 0, stream_id, info.payload_length, info.end_stream ? END_STREAM_FLAG : 0x0, 0); if (!ok) { LatchErrorAndNotify(Http2ErrorCode::INTERNAL_ERROR, ConnectionError::kSendError); return SendResult::SEND_ERROR; } if (!stream_map_.contains(stream_id)) { break; } } if (info.end_data || (info.payload_length == 0 && state.trailers != nullptr)) { if (state.trailers != nullptr) { auto block_ptr = std::move(state.trailers); if (info.end_stream) { QUICHE_LOG(ERROR) << "Sent fin; can't send trailers."; CloseStream(stream_id, Http2ErrorCode::INTERNAL_ERROR); break; } else { SendTrailers(stream_id, std::move(*block_ptr)); } } AbandonData(state); } } if (stream_map_.contains(stream_id) && !state.data_deferred && state.send_window > 0 && HasMoreData(state)) { write_scheduler_.MarkStreamReady(stream_id, false); } if (connection_can_write != SendResult::SEND_OK) { return connection_can_write; } return connection_send_window_ <= 0 ? SendResult::SEND_BLOCKED : SendResult::SEND_OK; } void OgHttp2Session::SerializeMetadata(Http2StreamId stream_id, std::unique_ptr<MetadataSource> source) { const uint32_t max_payload_size = std::min(kMaxAllowedMetadataFrameSize, max_frame_payload_); auto payload_buffer = std::make_unique<uint8_t[]>(max_payload_size); while (true) { auto [written, end_metadata] = source->Pack(payload_buffer.get(), max_payload_size); if (written < 0) { return; } QUICHE_DCHECK_LE(static_cast<size_t>(written), max_payload_size); auto payload = absl::string_view( reinterpret_cast<const char*>(payload_buffer.get()), written); EnqueueFrame(std::make_unique<spdy::SpdyUnknownIR>( stream_id, kMetadataFrameType, end_metadata ? kMetadataEndFlag : 0u, std::string(payload))); if (end_metadata) { return; } } } void OgHttp2Session::SerializeMetadata(Http2StreamId stream_id) { const uint32_t max_payload_size = std::min(kMaxAllowedMetadataFrameSize, max_frame_payload_); auto payload_buffer = std::make_unique<uint8_t[]>(max_payload_size); while (true) { auto [written, end_metadata] = visitor_.PackMetadataForStream( stream_id, payload_buffer.get(), max_payload_size); if (written < 0) { return; } QUICHE_DCHECK_LE(static_cast<size_t>(written), max_payload_size); auto payload = absl::string_view( reinterpret_cast<const char*>(payload_buffer.get()), written); EnqueueFrame(std::make_unique<spdy::SpdyUnknownIR>( stream_id, kMetadataFrameType, end_metadata ? kMetadataEndFlag : 0u, std::string(payload))); if (end_metadata) { return; } } } int32_t OgHttp2Session::SubmitRequest( absl::Span<const Header> headers, std::unique_ptr<DataFrameSource> data_source, bool end_stream, void* user_data) { return SubmitRequestInternal(headers, std::move(data_source), end_stream, user_data); } int OgHttp2Session::SubmitResponse(Http2StreamId stream_id, absl::Span<const Header> headers, std::unique_ptr<DataFrameSource> data_source, bool end_stream) { return SubmitResponseInternal(stream_id, headers, std::move(data_source), end_stream); } int OgHttp2Session::SubmitTrailer(Http2StreamId stream_id, absl::Span<const Header> trailers) { auto iter = stream_map_.find(stream_id); if (iter == stream_map_.end()) { QUICHE_LOG(ERROR) << "Unable to find stream " << stream_id; return -501; } StreamState& state = iter->second; if (state.half_closed_local) { QUICHE_LOG(ERROR) << "Stream " << stream_id << " is half closed (local)"; return -514; } if (state.trailers != nullptr) { QUICHE_LOG(ERROR) << "Stream " << stream_id << " already has trailers queued"; return -514; } if (!HasMoreData(state)) { SendTrailers(stream_id, ToHeaderBlock(trailers)); } else { state.trailers = std::make_unique<quiche::HttpHeaderBlock>(ToHeaderBlock(trailers)); trailers_ready_.insert(stream_id); } return 0; } void OgHttp2Session::SubmitMetadata(Http2StreamId stream_id, std::unique_ptr<MetadataSource> source) { SerializeMetadata(stream_id, std::move(source)); } void OgHttp2Session::SubmitMetadata(Http2StreamId stream_id) { SerializeMetadata(stream_id); } void OgHttp2Session::SubmitSettings(absl::Span<const Http2Setting> settings) { auto frame = PrepareSettingsFrame(settings); EnqueueFrame(std::move(frame)); } void OgHttp2Session::OnError(SpdyFramerError error, std::string detailed_error) { QUICHE_VLOG(1) << "Error: " << http2::Http2DecoderAdapter::SpdyFramerErrorToString(error) << " details: " << detailed_error; LatchErrorAndNotify(GetHttp2ErrorCode(error), ConnectionError::kParseError); } void OgHttp2Session::OnCommonHeader(spdy::SpdyStreamId stream_id, size_t length, uint8_t type, uint8_t flags) { current_frame_type_ = type; highest_received_stream_id_ = std::max(static_cast<Http2StreamId>(stream_id), highest_received_stream_id_); if (streams_reset_.contains(stream_id)) { return; } const bool result = visitor_.OnFrameHeader(stream_id, length, type, flags); if (!result) { fatal_visitor_callback_failure_ = true; decoder_.StopProcessing(); } } void OgHttp2Session::OnDataFrameHeader(spdy::SpdyStreamId stream_id, size_t length, bool ) { auto iter = stream_map_.find(stream_id); if (iter == stream_map_.end() || streams_reset_.contains(stream_id)) { if (static_cast<Http2StreamId>(stream_id) > highest_processed_stream_id_) { LatchErrorAndNotify(Http2ErrorCode::PROTOCOL_ERROR, ConnectionError::kWrongFrameSequence); } return; } if (static_cast<int64_t>(length) > connection_window_manager_.CurrentWindowSize()) { LatchErrorAndNotify( Http2ErrorCode::FLOW_CONTROL_ERROR, Http2VisitorInterface::ConnectionError::kFlowControlError); return; } if (static_cast<int64_t>(length) > iter->second.window_manager.CurrentWindowSize()) { EnqueueFrame(std::make_unique<spdy::SpdyRstStreamIR>( stream_id, spdy::ERROR_CODE_FLOW_CONTROL_ERROR)); return; } const bool result = visitor_.OnBeginDataForStream(stream_id, length); if (!result) { fatal_visitor_callback_failure_ = true; decoder_.StopProcessing(); } if (!iter->second.can_receive_body && length > 0) { EnqueueFrame(std::make_unique<spdy::SpdyRstStreamIR>( stream_id, spdy::ERROR_CODE_PROTOCOL_ERROR)); return; } } void OgHttp2Session::OnStreamFrameData(spdy::SpdyStreamId stream_id, const char* data, size_t len) { MarkDataBuffered(stream_id, len); auto iter = stream_map_.find(stream_id); if (iter == stream_map_.end()) { return; } if (iter->second.remaining_content_length.has_value()) { if (len > *iter->second.remaining_content_length) { HandleContentLengthError(stream_id); iter->second.remaining_content_length.reset(); } else { *iter->second.remaining_content_length -= len; } } if (streams_reset_.contains(stream_id)) { return; } const bool result = visitor_.OnDataForStream(stream_id, absl::string_view(data, len)); if (!result) { fatal_visitor_callback_failure_ = true; decoder_.StopProcessing(); } } void OgHttp2Session::OnStreamEnd(spdy::SpdyStreamId stream_id) { auto iter = stream_map_.find(stream_id); if (iter != stream_map_.end()) { iter->second.half_closed_remote = true; if (streams_reset_.contains(stream_id)) { return; } if (iter->second.remaining_content_length.has_value() && *iter->second.remaining_content_length != 0) { HandleContentLengthError(stream_id); return; } const bool result = visitor_.OnEndStream(stream_id); if (!result) { fatal_visitor_callback_failure_ = true; decoder_.StopProcessing(); } } auto queued_frames_iter = queued_frames_.find(stream_id); const bool no_queued_frames = queued_frames_iter == queued_frames_.end() || queued_frames_iter->second == 0; if (iter != stream_map_.end() && iter->second.half_closed_local && !IsServerSession() && no_queued_frames) { CloseStream(stream_id, Http2ErrorCode::HTTP2_NO_ERROR); } } void OgHttp2Session::OnStreamPadLength(spdy::SpdyStreamId stream_id, size_t value) { const size_t padding_length = 1 + value; const bool result = visitor_.OnDataPaddingLength(stream_id, padding_length); if (!result) { fatal_visitor_callback_failure_ = true; decoder_.StopProcessing(); } connection_window_manager_.MarkWindowConsumed(padding_length); if (auto it = stream_map_.find(stream_id); it != stream_map_.end()) { it->second.window_manager.MarkWindowConsumed(padding_length); } } void OgHttp2Session::OnStreamPadding(spdy::SpdyStreamId , size_t ) { } spdy::SpdyHeadersHandlerInterface* OgHttp2Session::OnHeaderFrameStart( spdy::SpdyStreamId stream_id) { auto it = stream_map_.find(stream_id); if (it != stream_map_.end() && !streams_reset_.contains(stream_id)) { headers_handler_.set_stream_id(stream_id); headers_handler_.set_header_type( NextHeaderType(it->second.received_header_type)); return &headers_handler_; } else { return &noop_headers_handler_; } } void OgHttp2Session::OnHeaderFrameEnd(spdy::SpdyStreamId stream_id) { auto it = stream_map_.find(stream_id); if (it != stream_map_.end()) { if (headers_handler_.header_type() == HeaderType::RESPONSE && !headers_handler_.status_header().empty() && headers_handler_.status_header()[0] == '1') { headers_handler_.set_header_type(HeaderType::RESPONSE_100); } it->second.received_header_type = headers_handler_.header_type(); it->second.can_receive_body = headers_handler_.CanReceiveBody() && !it->second.sent_head_method; if (it->second.can_receive_body) { it->second.remaining_content_length = headers_handler_.content_length(); } headers_handler_.set_stream_id(0); } } void OgHttp2Session::OnRstStream(spdy::SpdyStreamId stream_id, spdy::SpdyErrorCode error_code) { auto iter = stream_map_.find(stream_id); if (iter != stream_map_.end()) { iter->second.half_closed_remote = true; AbandonData(iter->second); } else if (static_cast<Http2StreamId>(stream_id) > highest_processed_stream_id_) { LatchErrorAndNotify(Http2ErrorCode::PROTOCOL_ERROR, ConnectionError::kWrongFrameSequence); return; } if (streams_reset_.contains(stream_id)) { return; } visitor_.OnRstStream(stream_id, TranslateErrorCode(error_code)); CloseStream(stream_id, TranslateErrorCode(error_code)); } void OgHttp2Session::OnSettings() { visitor_.OnSettingsStart(); auto settings = std::make_unique<SpdySettingsIR>(); settings->set_is_ack(true); EnqueueFrame(std::move(settings)); } void OgHttp2Session::OnSetting(spdy::SpdySettingsId id, uint32_t value) { switch (id) { case HEADER_TABLE_SIZE: value = std::min(value, HpackCapacityBound(options_)); if (value < framer_.GetHpackEncoder()->CurrentHeaderTableSizeSetting()) { QUICHE_VLOG(2) << TracePerspectiveAsString(options_.perspective) << " applying encoder table capacity " << value; framer_.GetHpackEncoder()->ApplyHeaderTableSizeSetting(value); } else { QUICHE_VLOG(2) << TracePerspectiveAsString(options_.perspective) << " NOT applying encoder table capacity until writing ack: " << value; encoder_header_table_capacity_when_acking_ = value; } break; case ENABLE_PUSH: if (value > 1u) { visitor_.OnInvalidFrame( 0, Http2VisitorInterface::InvalidFrameError::kProtocol); LatchErrorAndNotify( Http2ErrorCode::PROTOCOL_ERROR, Http2VisitorInterface::ConnectionError::kInvalidSetting); return; } break; case MAX_CONCURRENT_STREAMS: max_outbound_concurrent_streams_ = value; if (!IsServerSession()) { StartPendingStreams(); } break; case INITIAL_WINDOW_SIZE: if (value > spdy::kSpdyMaximumWindowSize) { visitor_.OnInvalidFrame( 0, Http2VisitorInterface::InvalidFrameError::kFlowControl); LatchErrorAndNotify( Http2ErrorCode::FLOW_CONTROL_ERROR, Http2VisitorInterface::ConnectionError::kFlowControlError); return; } else { UpdateStreamSendWindowSizes(value); } break; case MAX_FRAME_SIZE: if (value < kDefaultFramePayloadSizeLimit || value > kMaximumFramePayloadSizeLimit) { visitor_.OnInvalidFrame( 0, Http2VisitorInterface::InvalidFrameError::kProtocol); LatchErrorAndNotify( Http2ErrorCode::PROTOCOL_ERROR, Http2VisitorInterface::ConnectionError::kInvalidSetting); return; } max_frame_payload_ = value; break; case ENABLE_CONNECT_PROTOCOL: if (value > 1u || (value == 0 && peer_enables_connect_protocol_)) { visitor_.OnInvalidFrame( 0, Http2VisitorInterface::InvalidFrameError::kProtocol); LatchErrorAndNotify( Http2ErrorCode::PROTOCOL_ERROR, Http2VisitorInterface::ConnectionError::kInvalidSetting); return; } peer_enables_connect_protocol_ = (value == 1u); break; case kMetadataExtensionId: peer_supports_metadata_ = (value != 0); break; default: QUICHE_VLOG(1) << "Unimplemented SETTING id: " << id; } visitor_.OnSetting({id, value}); } void OgHttp2Session::OnSettingsEnd() { visitor_.OnSettingsEnd(); } void OgHttp2Session::OnSettingsAck() { if (!settings_ack_callbacks_.empty()) { SettingsAckCallback callback = std::move(settings_ack_callbacks_.front()); settings_ack_callbacks_.pop_front(); std::move(callback)(); } visitor_.OnSettingsAck(); } void OgHttp2Session::OnPing(spdy::SpdyPingId unique_id, bool is_ack) { visitor_.OnPing(unique_id, is_ack); if (options_.auto_ping_ack && !is_ack) { auto ping = std::make_unique<spdy::SpdyPingIR>(unique_id); ping->set_is_ack(true); EnqueueFrame(std::move(ping)); } } void OgHttp2Session::OnGoAway(spdy::SpdyStreamId last_accepted_stream_id, spdy::SpdyErrorCode error_code) { if (received_goaway_ && last_accepted_stream_id > static_cast<spdy::SpdyStreamId>(received_goaway_stream_id_)) { const bool ok = visitor_.OnInvalidFrame( kConnectionStreamId, Http2VisitorInterface::InvalidFrameError::kProtocol); if (!ok) { fatal_visitor_callback_failure_ = true; } LatchErrorAndNotify(Http2ErrorCode::PROTOCOL_ERROR, ConnectionError::kInvalidGoAwayLastStreamId); return; } received_goaway_ = true; received_goaway_stream_id_ = last_accepted_stream_id; const bool result = visitor_.OnGoAway(last_accepted_stream_id, TranslateErrorCode(error_code), ""); if (!result) { fatal_visitor_callback_failure_ = true; decoder_.StopProcessing(); } if (last_accepted_stream_id == spdy::kMaxStreamId || IsServerSession()) { return; } std::vector<Http2StreamId> streams_to_close; for (const auto& [stream_id, stream_state] : stream_map_) { if (static_cast<spdy::SpdyStreamId>(stream_id) > last_accepted_stream_id) { streams_to_close.push_back(stream_id); } } for (Http2StreamId stream_id : streams_to_close) { CloseStream(stream_id, Http2ErrorCode::REFUSED_STREAM); } } bool OgHttp2Session::OnGoAwayFrameData(const char* , size_t ) { return true; } void OgHttp2Session::OnHeaders(spdy::SpdyStreamId stream_id, size_t , bool , int , spdy::SpdyStreamId , bool , bool fin, bool ) { if (stream_id % 2 == 0) { LatchErrorAndNotify(Http2ErrorCode::PROTOCOL_ERROR, ConnectionError::kInvalidNewStreamId); return; } headers_handler_.set_frame_contains_fin(fin); if (IsServerSession()) { const auto new_stream_id = static_cast<Http2StreamId>(stream_id); if (stream_map_.find(new_stream_id) != stream_map_.end() && fin) { return; } if (new_stream_id <= highest_processed_stream_id_) { LatchErrorAndNotify(Http2ErrorCode::PROTOCOL_ERROR, ConnectionError::kInvalidNewStreamId); return; } if (stream_map_.size() >= max_inbound_concurrent_streams_) { bool ok = visitor_.OnInvalidFrame( stream_id, Http2VisitorInterface::InvalidFrameError::kProtocol); if (!ok) { fatal_visitor_callback_failure_ = true; } LatchErrorAndNotify(Http2ErrorCode::PROTOCOL_ERROR, ConnectionError::kExceededMaxConcurrentStreams); return; } if (stream_map_.size() >= pending_max_inbound_concurrent_streams_) { EnqueueFrame(std::make_unique<spdy::SpdyRstStreamIR>( stream_id, spdy::ERROR_CODE_REFUSED_STREAM)); const bool ok = visitor_.OnInvalidFrame( stream_id, Http2VisitorInterface::InvalidFrameError::kRefusedStream); if (!ok) { fatal_visitor_callback_failure_ = true; LatchErrorAndNotify(Http2ErrorCode::REFUSED_STREAM, ConnectionError::kExceededMaxConcurrentStreams); } return; } CreateStream(stream_id); } } void OgHttp2Session::OnWindowUpdate(spdy::SpdyStreamId stream_id, int delta_window_size) { constexpr int kMaxWindowValue = 2147483647; if (stream_id == 0) { if (delta_window_size == 0) { LatchErrorAndNotify(Http2ErrorCode::PROTOCOL_ERROR, ConnectionError::kFlowControlError); return; } if (connection_send_window_ > 0 && delta_window_size > (kMaxWindowValue - connection_send_window_)) { LatchErrorAndNotify(Http2ErrorCode::FLOW_CONTROL_ERROR, ConnectionError::kFlowControlError); return; } connection_send_window_ += delta_window_size; } else { if (delta_window_size == 0) { EnqueueFrame(std::make_unique<spdy::SpdyRstStreamIR>( stream_id, spdy::ERROR_CODE_PROTOCOL_ERROR)); return; } auto it = stream_map_.find(stream_id); if (it == stream_map_.end()) { QUICHE_VLOG(1) << "Stream " << stream_id << " not found!"; if (static_cast<Http2StreamId>(stream_id) > highest_processed_stream_id_) { LatchErrorAndNotify(Http2ErrorCode::PROTOCOL_ERROR, ConnectionError::kWrongFrameSequence); } return; } else { if (streams_reset_.contains(stream_id)) { return; } if (it->second.send_window > 0 && delta_window_size > (kMaxWindowValue - it->second.send_window)) { EnqueueFrame(std::make_unique<spdy::SpdyRstStreamIR>( stream_id, spdy::ERROR_CODE_FLOW_CONTROL_ERROR)); return; } const bool was_blocked = (it->second.send_window <= 0); it->second.send_window += delta_window_size; if (was_blocked && it->second.send_window > 0) { QUICHE_VLOG(1) << "Marking stream " << stream_id << " ready to write."; write_scheduler_.MarkStreamReady(stream_id, false); } } } visitor_.OnWindowUpdate(stream_id, delta_window_size); } void OgHttp2Session::OnPushPromise(spdy::SpdyStreamId , spdy::SpdyStreamId , bool ) { LatchErrorAndNotify(Http2ErrorCode::PROTOCOL_ERROR, ConnectionError::kInvalidPushPromise); } void OgHttp2Session::OnContinuation(spdy::SpdyStreamId , size_t , bool ) {} void OgHttp2Session::OnAltSvc(spdy::SpdyStreamId , absl::string_view , const spdy::SpdyAltSvcWireFormat:: AlternativeServiceVector& ) { } void OgHttp2Session::OnPriority(spdy::SpdyStreamId , spdy::SpdyStreamId , int , bool ) {} void OgHttp2Session::OnPriorityUpdate( spdy::SpdyStreamId , absl::string_view ) {} bool OgHttp2Session::OnUnknownFrame(spdy::SpdyStreamId , uint8_t ) { return true; } void OgHttp2Session::OnUnknownFrameStart(spdy::SpdyStreamId stream_id, size_t length, uint8_t type, uint8_t flags) { process_metadata_ = false; if (streams_reset_.contains(stream_id)) { return; } if (type == kMetadataFrameType) { QUICHE_DCHECK_EQ(metadata_length_, 0u); visitor_.OnBeginMetadataForStream(stream_id, length); metadata_length_ = length; process_metadata_ = true; end_metadata_ = flags & kMetadataEndFlag; MaybeHandleMetadataEndForStream(stream_id); } else { QUICHE_DLOG(INFO) << "Received unexpected frame type " << static_cast<int>(type); } } void OgHttp2Session::OnUnknownFramePayload(spdy::SpdyStreamId stream_id, absl::string_view payload) { if (!process_metadata_) { return; } if (streams_reset_.contains(stream_id)) { return; } if (metadata_length_ > 0) { QUICHE_DCHECK_LE(payload.size(), metadata_length_); const bool payload_success = visitor_.OnMetadataForStream(stream_id, payload); if (payload_success) { metadata_length_ -= payload.size(); MaybeHandleMetadataEndForStream(stream_id); } else { fatal_visitor_callback_failure_ = true; decoder_.StopProcessing(); } } else { QUICHE_DLOG(INFO) << "Unexpected metadata payload for stream " << stream_id; } } void OgHttp2Session::OnHeaderStatus( Http2StreamId stream_id, Http2VisitorInterface::OnHeaderResult result) { QUICHE_DCHECK_NE(result, Http2VisitorInterface::HEADER_OK); QUICHE_VLOG(1) << "OnHeaderStatus(stream_id=" << stream_id << ", result=" << result << ")"; const bool should_reset_stream = result == Http2VisitorInterface::HEADER_RST_STREAM || result == Http2VisitorInterface::HEADER_FIELD_INVALID || result == Http2VisitorInterface::HEADER_HTTP_MESSAGING; if (should_reset_stream) { const Http2ErrorCode error_code = (result == Http2VisitorInterface::HEADER_RST_STREAM) ? Http2ErrorCode::INTERNAL_ERROR : Http2ErrorCode::PROTOCOL_ERROR; const spdy::SpdyErrorCode spdy_error_code = TranslateErrorCode(error_code); const Http2VisitorInterface::InvalidFrameError frame_error = (result == Http2VisitorInterface::HEADER_RST_STREAM || result == Http2VisitorInterface::HEADER_FIELD_INVALID) ? Http2VisitorInterface::InvalidFrameError::kHttpHeader : Http2VisitorInterface::InvalidFrameError::kHttpMessaging; auto it = streams_reset_.find(stream_id); if (it == streams_reset_.end()) { EnqueueFrame( std::make_unique<spdy::SpdyRstStreamIR>(stream_id, spdy_error_code)); if (result == Http2VisitorInterface::HEADER_FIELD_INVALID || result == Http2VisitorInterface::HEADER_HTTP_MESSAGING) { const bool ok = visitor_.OnInvalidFrame(stream_id, frame_error); if (!ok) { fatal_visitor_callback_failure_ = true; LatchErrorAndNotify(error_code, ConnectionError::kHeaderError); } } } } else if (result == Http2VisitorInterface::HEADER_CONNECTION_ERROR) { fatal_visitor_callback_failure_ = true; LatchErrorAndNotify(Http2ErrorCode::INTERNAL_ERROR, ConnectionError::kHeaderError); } else if (result == Http2VisitorInterface::HEADER_COMPRESSION_ERROR) { LatchErrorAndNotify(Http2ErrorCode::COMPRESSION_ERROR, ConnectionError::kHeaderError); } } void OgHttp2Session::MaybeSetupPreface(bool sending_outbound_settings) { if (!queued_preface_) { queued_preface_ = true; if (!IsServerSession()) { buffered_data_.Append( absl::string_view(spdy::kHttp2ConnectionHeaderPrefix, spdy::kHttp2ConnectionHeaderPrefixSize)); } if (!sending_outbound_settings) { QUICHE_DCHECK(frames_.empty()); EnqueueFrame(PrepareSettingsFrame(GetInitialSettings())); } } } std::vector<Http2Setting> OgHttp2Session::GetInitialSettings() const { std::vector<Http2Setting> settings; if (!IsServerSession()) { settings.push_back({Http2KnownSettingsId::ENABLE_PUSH, 0}); } if (options_.max_header_list_bytes) { settings.push_back({Http2KnownSettingsId::MAX_HEADER_LIST_SIZE, *options_.max_header_list_bytes}); } if (options_.allow_extended_connect && IsServerSession()) { settings.push_back({Http2KnownSettingsId::ENABLE_CONNECT_PROTOCOL, 1u}); } return settings; } std::unique_ptr<SpdySettingsIR> OgHttp2Session::PrepareSettingsFrame( absl::Span<const Http2Setting> settings) { auto settings_ir = std::make_unique<SpdySettingsIR>(); for (const Http2Setting& setting : settings) { settings_ir->AddSetting(setting.id, setting.value); } return settings_ir; } void OgHttp2Session::HandleOutboundSettings( const spdy::SpdySettingsIR& settings_frame) { for (const auto& [id, value] : settings_frame.values()) { switch (static_cast<Http2KnownSettingsId>(id)) { case MAX_CONCURRENT_STREAMS: pending_max_inbound_concurrent_streams_ = value; break; case ENABLE_CONNECT_PROTOCOL: if (value == 1u && IsServerSession()) { headers_handler_.SetAllowExtendedConnect(); } break; case HEADER_TABLE_SIZE: case ENABLE_PUSH: case INITIAL_WINDOW_SIZE: case MAX_FRAME_SIZE: case MAX_HEADER_LIST_SIZE: QUICHE_VLOG(2) << "Not adjusting internal state for outbound setting with id " << id; break; } } settings_ack_callbacks_.push_back( [this, settings_map = settings_frame.values()]() { for (const auto& [id, value] : settings_map) { switch (static_cast<Http2KnownSettingsId>(id)) { case MAX_CONCURRENT_STREAMS: max_inbound_concurrent_streams_ = value; break; case HEADER_TABLE_SIZE: decoder_.GetHpackDecoder().ApplyHeaderTableSizeSetting(value); break; case INITIAL_WINDOW_SIZE: UpdateStreamReceiveWindowSizes(value); initial_stream_receive_window_ = value; break; case MAX_FRAME_SIZE: decoder_.SetMaxFrameSize(value); break; case ENABLE_PUSH: case MAX_HEADER_LIST_SIZE: case ENABLE_CONNECT_PROTOCOL: QUICHE_VLOG(2) << "No action required in ack for outbound setting with id " << id; break; } } }); } void OgHttp2Session::SendWindowUpdate(Http2StreamId stream_id, size_t update_delta) { EnqueueFrame( std::make_unique<spdy::SpdyWindowUpdateIR>(stream_id, update_delta)); } void OgHttp2Session::SendHeaders(Http2StreamId stream_id, quiche::HttpHeaderBlock headers, bool end_stream) { auto frame = std::make_unique<spdy::SpdyHeadersIR>(stream_id, std::move(headers)); frame->set_fin(end_stream); EnqueueFrame(std::move(frame)); } void OgHttp2Session::SendTrailers(Http2StreamId stream_id, quiche::HttpHeaderBlock trailers) { auto frame = std::make_unique<spdy::SpdyHeadersIR>(stream_id, std::move(trailers)); frame->set_fin(true); EnqueueFrame(std::move(frame)); trailers_ready_.erase(stream_id); } void OgHttp2Session::MaybeFinWithRstStream(StreamStateMap::iterator iter) { QUICHE_DCHECK(iter != stream_map_.end() && iter->second.half_closed_local); if (options_.rst_stream_no_error_when_incomplete && IsServerSession() && !iter->second.half_closed_remote) { EnqueueFrame(std::make_unique<spdy::SpdyRstStreamIR>( iter->first, spdy::SpdyErrorCode::ERROR_CODE_NO_ERROR)); iter->second.half_closed_remote = true; } } void OgHttp2Session::MarkDataBuffered(Http2StreamId stream_id, size_t bytes) { connection_window_manager_.MarkDataBuffered(bytes); if (auto it = stream_map_.find(stream_id); it != stream_map_.end()) { it->second.window_manager.MarkDataBuffered(bytes); } } OgHttp2Session::StreamStateMap::iterator OgHttp2Session::CreateStream( Http2StreamId stream_id) { WindowManager::WindowUpdateListener listener = [this, stream_id](size_t window_update_delta) { SendWindowUpdate(stream_id, window_update_delta); }; auto [iter, inserted] = stream_map_.try_emplace( stream_id, StreamState(initial_stream_receive_window_, initial_stream_send_window_, std::move(listener), options_.should_window_update_fn)); if (inserted) { const spdy::SpdyPriority priority = 3; write_scheduler_.RegisterStream(stream_id, priority); highest_processed_stream_id_ = std::max(highest_processed_stream_id_, stream_id); } return iter; } void OgHttp2Session::StartRequest(Http2StreamId stream_id, quiche::HttpHeaderBlock headers, std::unique_ptr<DataFrameSource> data_source, void* user_data, bool end_stream) { if (received_goaway_) { goaway_rejected_streams_.insert(stream_id); return; } auto iter = CreateStream(stream_id); if (data_source != nullptr) { iter->second.outbound_body = std::move(data_source); write_scheduler_.MarkStreamReady(stream_id, false); } else if (!end_stream) { iter->second.check_visitor_for_body = true; write_scheduler_.MarkStreamReady(stream_id, false); } iter->second.user_data = user_data; for (const auto& [name, value] : headers) { if (name == kHttp2MethodPseudoHeader && value == kHeadValue) { iter->second.sent_head_method = true; } } SendHeaders(stream_id, std::move(headers), end_stream); } void OgHttp2Session::StartPendingStreams() { while (!pending_streams_.empty() && CanCreateStream()) { auto& [stream_id, pending_stream] = pending_streams_.front(); StartRequest(stream_id, std::move(pending_stream.headers), std::move(pending_stream.data_source), pending_stream.user_data, pending_stream.end_stream); pending_streams_.pop_front(); } } void OgHttp2Session::CloseStream(Http2StreamId stream_id, Http2ErrorCode error_code) { const bool result = visitor_.OnCloseStream(stream_id, error_code); if (!result) { latched_error_ = true; decoder_.StopProcessing(); } stream_map_.erase(stream_id); trailers_ready_.erase(stream_id); streams_reset_.erase(stream_id); auto queued_it = queued_frames_.find(stream_id); if (queued_it != queued_frames_.end()) { int frames_remaining = queued_it->second; queued_frames_.erase(queued_it); for (auto it = frames_.begin(); frames_remaining > 0 && it != frames_.end();) { if (static_cast<Http2StreamId>((*it)->stream_id()) == stream_id) { it = frames_.erase(it); --frames_remaining; } else { ++it; } } } if (write_scheduler_.StreamRegistered(stream_id)) { write_scheduler_.UnregisterStream(stream_id); } StartPendingStreams(); } bool OgHttp2Session::CanCreateStream() const { return stream_map_.size() < max_outbound_concurrent_streams_; } HeaderType OgHttp2Session::NextHeaderType( std::optional<HeaderType> current_type) { if (IsServerSession()) { if (!current_type) { return HeaderType::REQUEST; } else { return HeaderType::REQUEST_TRAILER; } } else if (!current_type || *current_type == HeaderType::RESPONSE_100) { return HeaderType::RESPONSE; } else { return HeaderType::RESPONSE_TRAILER; } } void OgHttp2Session::LatchErrorAndNotify(Http2ErrorCode error_code, ConnectionError error) { if (latched_error_) { return; } latched_error_ = true; visitor_.OnConnectionError(error); decoder_.StopProcessing(); EnqueueFrame(std::make_unique<spdy::SpdyGoAwayIR>( highest_processed_stream_id_, TranslateErrorCode(error_code), ConnectionErrorToString(error))); } void OgHttp2Session::CloseStreamIfReady(uint8_t frame_type, uint32_t stream_id) { auto iter = stream_map_.find(stream_id); if (iter == stream_map_.end()) { return; } const StreamState& state = iter->second; if (static_cast<FrameType>(frame_type) == FrameType::RST_STREAM || (state.half_closed_local && state.half_closed_remote)) { CloseStream(stream_id, Http2ErrorCode::HTTP2_NO_ERROR); } } void OgHttp2Session::CloseGoAwayRejectedStreams() { for (Http2StreamId stream_id : goaway_rejected_streams_) { const bool result = visitor_.OnCloseStream(stream_id, Http2ErrorCode::REFUSED_STREAM); if (!result) { latched_error_ = true; decoder_.StopProcessing(); } } goaway_rejected_streams_.clear(); } void OgHttp2Session::PrepareForImmediateGoAway() { queued_immediate_goaway_ = true; std::unique_ptr<spdy::SpdyFrameIR> initial_settings; if (!sent_non_ack_settings_ && !frames_.empty() && IsNonAckSettings(*frames_.front())) { initial_settings = std::move(frames_.front()); frames_.pop_front(); } frames_.remove_if([](const auto& frame) { return frame->frame_type() != spdy::SpdyFrameType::RST_STREAM; }); if (initial_settings != nullptr) { frames_.push_front(std::move(initial_settings)); } } void OgHttp2Session::MaybeHandleMetadataEndForStream(Http2StreamId stream_id) { if (metadata_length_ == 0 && end_metadata_) { const bool completion_success = visitor_.OnMetadataEndForStream(stream_id); if (!completion_success) { fatal_visitor_callback_failure_ = true; decoder_.StopProcessing(); } process_metadata_ = false; end_metadata_ = false; } } void OgHttp2Session::DecrementQueuedFrameCount(uint32_t stream_id, uint8_t frame_type) { auto iter = queued_frames_.find(stream_id); if (iter == queued_frames_.end()) { QUICHE_LOG(ERROR) << "Unable to find a queued frame count for stream " << stream_id; return; } if (static_cast<FrameType>(frame_type) != FrameType::DATA) { --iter->second; } if (iter->second == 0) { CloseStreamIfReady(frame_type, stream_id); } } void OgHttp2Session::HandleContentLengthError(Http2StreamId stream_id) { if (current_frame_type_ == static_cast<uint8_t>(FrameType::HEADERS)) { visitor_.OnInvalidFrame( stream_id, Http2VisitorInterface::InvalidFrameError::kHttpMessaging); } EnqueueFrame(std::make_unique<spdy::SpdyRstStreamIR>( stream_id, spdy::ERROR_CODE_PROTOCOL_ERROR)); } void OgHttp2Session::UpdateReceiveWindow(Http2StreamId stream_id, int32_t delta) { if (stream_id == 0) { connection_window_manager_.IncreaseWindow(delta); const int64_t current_window = connection_window_manager_.CurrentWindowSize(); if (current_window > connection_window_manager_.WindowSizeLimit()) { connection_window_manager_.SetWindowSizeLimit(current_window); } } else { auto iter = stream_map_.find(stream_id); if (iter != stream_map_.end()) { WindowManager& manager = iter->second.window_manager; manager.IncreaseWindow(delta); const int64_t current_window = manager.CurrentWindowSize(); if (current_window > manager.WindowSizeLimit()) { manager.SetWindowSizeLimit(current_window); } } } } void OgHttp2Session::UpdateStreamSendWindowSizes(uint32_t new_value) { const int32_t delta = static_cast<int32_t>(new_value) - initial_stream_send_window_; initial_stream_send_window_ = new_value; for (auto& [stream_id, stream_state] : stream_map_) { const int64_t current_window_size = stream_state.send_window; const int64_t new_window_size = current_window_size + delta; if (new_window_size > spdy::kSpdyMaximumWindowSize) { EnqueueFrame(std::make_unique<spdy::SpdyRstStreamIR>( stream_id, spdy::ERROR_CODE_FLOW_CONTROL_ERROR)); } else { stream_state.send_window += delta; } if (current_window_size <= 0 && new_window_size > 0) { write_scheduler_.MarkStreamReady(stream_id, false); } } } void OgHttp2Session::UpdateStreamReceiveWindowSizes(uint32_t new_value) { for (auto& [stream_id, stream_state] : stream_map_) { stream_state.window_manager.OnWindowSizeLimitChange(new_value); } } bool OgHttp2Session::HasMoreData(const StreamState& stream_state) const { return stream_state.outbound_body != nullptr || stream_state.check_visitor_for_body; } bool OgHttp2Session::IsReadyToWriteData(const StreamState& stream_state) const { return HasMoreData(stream_state) && !stream_state.data_deferred; } void OgHttp2Session::AbandonData(StreamState& stream_state) { stream_state.outbound_body = nullptr; stream_state.check_visitor_for_body = false; } OgHttp2Session::DataFrameHeaderInfo OgHttp2Session::GetDataFrameInfo( Http2StreamId stream_id, size_t flow_control_available, StreamState& stream_state) { if (stream_state.outbound_body != nullptr) { DataFrameHeaderInfo info; std::tie(info.payload_length, info.end_data) = stream_state.outbound_body->SelectPayloadLength(flow_control_available); info.end_stream = info.end_data ? stream_state.outbound_body->send_fin() : false; return info; } else if (stream_state.check_visitor_for_body) { DataFrameHeaderInfo info = visitor_.OnReadyToSendDataForStream(stream_id, flow_control_available); info.end_data = info.end_data || info.end_stream; return info; } QUICHE_LOG(DFATAL) << "GetDataFrameInfo for stream " << stream_id << " but no body available!"; return {0, true, true}; } bool OgHttp2Session::SendDataFrame(Http2StreamId stream_id, absl::string_view frame_header, size_t payload_length, StreamState& stream_state) { if (stream_state.outbound_body != nullptr) { return stream_state.outbound_body->Send(frame_header, payload_length); } else { QUICHE_DCHECK(stream_state.check_visitor_for_body); return visitor_.SendDataFrame(stream_id, frame_header, payload_length); } } } }
#include "quiche/http2/adapter/oghttp2_session.h" #include <memory> #include <string> #include <utility> #include "quiche/http2/adapter/mock_http2_visitor.h" #include "quiche/http2/adapter/test_frame_sequence.h" #include "quiche/http2/adapter/test_utils.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace adapter { namespace test { namespace { using spdy::SpdyFrameType; using testing::_; enum FrameType { DATA, HEADERS, PRIORITY, RST_STREAM, SETTINGS, PUSH_PROMISE, PING, GOAWAY, WINDOW_UPDATE, }; } TEST(OgHttp2SessionTest, ClientConstruction) { testing::StrictMock<MockHttp2Visitor> visitor; OgHttp2Session::Options options; options.perspective = Perspective::kClient; OgHttp2Session session(visitor, options); EXPECT_TRUE(session.want_read()); EXPECT_FALSE(session.want_write()); EXPECT_EQ(session.GetRemoteWindowSize(), kInitialFlowControlWindowSize); EXPECT_FALSE(session.IsServerSession()); EXPECT_EQ(0, session.GetHighestReceivedStreamId()); EXPECT_EQ(100u, session.GetMaxOutboundConcurrentStreams()); } TEST(OgHttp2SessionTest, ClientConstructionWithMaxStreams) { testing::StrictMock<MockHttp2Visitor> visitor; OgHttp2Session::Options options; options.perspective = Perspective::kClient; options.remote_max_concurrent_streams = 200u; OgHttp2Session session(visitor, options); EXPECT_EQ(200u, session.GetMaxOutboundConcurrentStreams()); } TEST(OgHttp2SessionTest, ClientHandlesFrames) { TestVisitor visitor; OgHttp2Session::Options options; options.perspective = Perspective::kClient; OgHttp2Session session(visitor, options); const std::string initial_frames = TestFrameSequence() .ServerPreface() .Ping(42) .WindowUpdate(0, 1000) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, 8, PING, 0)); EXPECT_CALL(visitor, OnPing(42, false)); EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(0, 1000)); const int64_t initial_result = session.ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), static_cast<size_t>(initial_result)); EXPECT_EQ(session.GetRemoteWindowSize(), kInitialFlowControlWindowSize + 1000); EXPECT_EQ(0, session.GetHighestReceivedStreamId()); EXPECT_EQ(kInitialFlowControlWindowSize, session.GetReceiveWindowSize()); EXPECT_EQ(0, session.GetHpackDecoderDynamicTableSize()); const char* kSentinel1 = "arbitrary pointer 1"; visitor.AppendPayloadForStream(1, "This is an example request body."); visitor.SetEndData(1, true); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); int stream_id = session.SubmitRequest( ToHeaders({{":method", "POST"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}), std::move(body1), false, const_cast<char*>(kSentinel1)); ASSERT_EQ(stream_id, 1); int stream_id2 = session.SubmitRequest(ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}), nullptr, true, nullptr); EXPECT_EQ(stream_id2, 3); const std::string stream_frames = TestFrameSequence() .Headers(stream_id, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, false) .Data(stream_id, "This is the response body.") .RstStream(stream_id2, Http2ErrorCode::INTERNAL_ERROR) .GoAway(5, Http2ErrorCode::ENHANCE_YOUR_CALM, "calm down!!") .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(stream_id, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(stream_id)); EXPECT_CALL(visitor, OnHeaderForStream(stream_id, ":status", "200")); EXPECT_CALL(visitor, OnHeaderForStream(stream_id, "server", "my-fake-server")); EXPECT_CALL(visitor, OnHeaderForStream(stream_id, "date", "Tue, 6 Apr 2021 12:54:01 GMT")); EXPECT_CALL(visitor, OnEndHeadersForStream(stream_id)); EXPECT_CALL(visitor, OnFrameHeader(stream_id, 26, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(stream_id, 26)); EXPECT_CALL(visitor, OnDataForStream(stream_id, "This is the response body.")); EXPECT_CALL(visitor, OnFrameHeader(stream_id2, 4, RST_STREAM, 0)); EXPECT_CALL(visitor, OnRstStream(stream_id2, Http2ErrorCode::INTERNAL_ERROR)); EXPECT_CALL(visitor, OnCloseStream(stream_id2, Http2ErrorCode::INTERNAL_ERROR)); EXPECT_CALL(visitor, OnFrameHeader(0, 19, GOAWAY, 0)); EXPECT_CALL(visitor, OnGoAway(5, Http2ErrorCode::ENHANCE_YOUR_CALM, "")); const int64_t stream_result = session.ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_EQ(stream_id2, session.GetHighestReceivedStreamId()); EXPECT_GT(kInitialFlowControlWindowSize, session.GetStreamReceiveWindowSize(stream_id)); EXPECT_EQ(session.GetReceiveWindowSize(), session.GetStreamReceiveWindowSize(stream_id)); EXPECT_EQ(kInitialFlowControlWindowSize, session.GetStreamReceiveWindowLimit(stream_id)); EXPECT_GT(session.GetHpackDecoderDynamicTableSize(), 0); } TEST(OgHttp2SessionTest, ClientEnqueuesSettingsOnSend) { TestVisitor visitor; OgHttp2Session::Options options; options.perspective = Perspective::kClient; OgHttp2Session session(visitor, options); EXPECT_FALSE(session.want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); int result = session.Send(); EXPECT_EQ(0, result); absl::string_view serialized = visitor.data(); EXPECT_THAT(serialized, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::SETTINGS})); } TEST(OgHttp2SessionTest, ClientEnqueuesSettingsBeforeOtherFrame) { TestVisitor visitor; OgHttp2Session::Options options; options.perspective = Perspective::kClient; OgHttp2Session session(visitor, options); EXPECT_FALSE(session.want_write()); session.EnqueueFrame(std::make_unique<spdy::SpdyPingIR>(42)); EXPECT_TRUE(session.want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(PING, 0, 8, 0x0)); EXPECT_CALL(visitor, OnFrameSent(PING, 0, 8, 0x0, 0)); int result = session.Send(); EXPECT_EQ(0, result); absl::string_view serialized = visitor.data(); EXPECT_THAT(serialized, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::PING})); } TEST(OgHttp2SessionTest, ClientEnqueuesSettingsOnce) { TestVisitor visitor; OgHttp2Session::Options options; options.perspective = Perspective::kClient; OgHttp2Session session(visitor, options); EXPECT_FALSE(session.want_write()); session.EnqueueFrame(std::make_unique<spdy::SpdySettingsIR>()); EXPECT_TRUE(session.want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); int result = session.Send(); EXPECT_EQ(0, result); absl::string_view serialized = visitor.data(); EXPECT_THAT(serialized, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::SETTINGS})); } TEST(OgHttp2SessionTest, ClientSubmitRequest) { TestVisitor visitor; OgHttp2Session::Options options; options.perspective = Perspective::kClient; OgHttp2Session session(visitor, options); EXPECT_FALSE(session.want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); int result = session.Send(); EXPECT_EQ(0, result); absl::string_view serialized = visitor.data(); EXPECT_THAT(serialized, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::SETTINGS})); visitor.Clear(); const std::string initial_frames = TestFrameSequence().ServerPreface().Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t initial_result = session.ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), static_cast<size_t>(initial_result)); EXPECT_TRUE(session.want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); result = session.Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); visitor.Clear(); EXPECT_EQ(0, session.GetHpackEncoderDynamicTableSize()); const char* kSentinel1 = "arbitrary pointer 1"; visitor.AppendPayloadForStream(1, "This is an example request body."); visitor.SetEndData(1, true); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); int stream_id = session.SubmitRequest( ToHeaders({{":method", "POST"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}), std::move(body1), false, const_cast<char*>(kSentinel1)); ASSERT_EQ(stream_id, 1); EXPECT_TRUE(session.want_write()); EXPECT_EQ(kSentinel1, session.GetStreamUserData(stream_id)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, _, 0x1, 0)); result = session.Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({spdy::SpdyFrameType::HEADERS, spdy::SpdyFrameType::DATA})); visitor.Clear(); EXPECT_FALSE(session.want_write()); EXPECT_LT(session.GetStreamSendWindowSize(stream_id), kInitialFlowControlWindowSize); EXPECT_GT(session.GetStreamSendWindowSize(stream_id), 0); EXPECT_EQ(-1, session.GetStreamSendWindowSize(stream_id + 2)); EXPECT_GT(session.GetHpackEncoderDynamicTableSize(), 0); stream_id = session.SubmitRequest(ToHeaders({{":method", "POST"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}), nullptr, true, nullptr); EXPECT_GT(stream_id, 0); EXPECT_TRUE(session.want_write()); const char* kSentinel2 = "arbitrary pointer 2"; EXPECT_EQ(nullptr, session.GetStreamUserData(stream_id)); session.SetStreamUserData(stream_id, const_cast<char*>(kSentinel2)); EXPECT_EQ(kSentinel2, session.GetStreamUserData(stream_id)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x5, 0)); result = session.Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({spdy::SpdyFrameType::HEADERS})); EXPECT_EQ(session.GetStreamSendWindowSize(stream_id), kInitialFlowControlWindowSize); } TEST(OgHttp2SessionTest, ClientSubmitRequestWithLargePayload) { TestVisitor visitor; OgHttp2Session::Options options; options.perspective = Perspective::kClient; OgHttp2Session session(visitor, options); EXPECT_FALSE(session.want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); int result = session.Send(); EXPECT_EQ(0, result); absl::string_view serialized = visitor.data(); EXPECT_THAT(serialized, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::SETTINGS})); visitor.Clear(); const std::string initial_frames = TestFrameSequence() .ServerPreface( {Http2Setting{Http2KnownSettingsId::MAX_FRAME_SIZE, 32768u}}) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSetting(Http2Setting{ Http2KnownSettingsId::MAX_FRAME_SIZE, 32768u})); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t initial_result = session.ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), static_cast<size_t>(initial_result)); EXPECT_TRUE(session.want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); result = session.Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); visitor.Clear(); visitor.AppendPayloadForStream(1, std::string(20000, 'a')); visitor.SetEndData(1, true); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); int stream_id = session.SubmitRequest(ToHeaders({{":method", "POST"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}), std::move(body1), false, nullptr); ASSERT_EQ(stream_id, 1); EXPECT_TRUE(session.want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, _, 0x1, 0)); result = session.Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({spdy::SpdyFrameType::HEADERS, spdy::SpdyFrameType::DATA})); visitor.Clear(); EXPECT_FALSE(session.want_write()); } TEST(OgHttp2SessionTest, ClientSubmitRequestWithReadBlock) { TestVisitor visitor; OgHttp2Session::Options options; options.perspective = Perspective::kClient; OgHttp2Session session(visitor, options); EXPECT_FALSE(session.want_write()); const char* kSentinel1 = "arbitrary pointer 1"; auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); int stream_id = session.SubmitRequest( ToHeaders({{":method", "POST"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}), std::move(body1), false, const_cast<char*>(kSentinel1)); EXPECT_GT(stream_id, 0); EXPECT_TRUE(session.want_write()); EXPECT_EQ(kSentinel1, session.GetStreamUserData(stream_id)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0)); int result = session.Send(); EXPECT_EQ(0, result); absl::string_view serialized = visitor.data(); EXPECT_THAT(serialized, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); visitor.Clear(); EXPECT_FALSE(session.want_write()); visitor.AppendPayloadForStream(1, "This is an example request body."); visitor.SetEndData(1, true); EXPECT_TRUE(session.ResumeStream(stream_id)); EXPECT_TRUE(session.want_write()); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, _, 0x1, 0)); result = session.Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::DATA})); EXPECT_FALSE(session.want_write()); EXPECT_FALSE(session.ResumeStream(stream_id)); EXPECT_FALSE(session.want_write()); } TEST(OgHttp2SessionTest, ClientSubmitRequestEmptyDataWithFin) { TestVisitor visitor; OgHttp2Session::Options options; options.perspective = Perspective::kClient; OgHttp2Session session(visitor, options); EXPECT_FALSE(session.want_write()); const char* kSentinel1 = "arbitrary pointer 1"; auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); int stream_id = session.SubmitRequest( ToHeaders({{":method", "POST"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}), std::move(body1), false, const_cast<char*>(kSentinel1)); EXPECT_GT(stream_id, 0); EXPECT_TRUE(session.want_write()); EXPECT_EQ(kSentinel1, session.GetStreamUserData(stream_id)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0)); int result = session.Send(); EXPECT_EQ(0, result); absl::string_view serialized = visitor.data(); EXPECT_THAT(serialized, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); visitor.Clear(); EXPECT_FALSE(session.want_write()); visitor.SetEndData(1, true); EXPECT_TRUE(session.ResumeStream(stream_id)); EXPECT_TRUE(session.want_write()); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, 0, 0x1, 0)); result = session.Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::DATA})); EXPECT_FALSE(session.want_write()); EXPECT_FALSE(session.ResumeStream(stream_id)); EXPECT_FALSE(session.want_write()); } TEST(OgHttp2SessionTest, ClientSubmitRequestWithWriteBlock) { TestVisitor visitor; OgHttp2Session::Options options; options.perspective = Perspective::kClient; OgHttp2Session session(visitor, options); EXPECT_FALSE(session.want_write()); const char* kSentinel1 = "arbitrary pointer 1"; visitor.AppendPayloadForStream(1, "This is an example request body."); visitor.SetEndData(1, true); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); int stream_id = session.SubmitRequest( ToHeaders({{":method", "POST"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}), std::move(body1), false, const_cast<char*>(kSentinel1)); EXPECT_GT(stream_id, 0); EXPECT_TRUE(session.want_write()); EXPECT_EQ(kSentinel1, session.GetStreamUserData(stream_id)); visitor.set_is_write_blocked(true); int result = session.Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), testing::IsEmpty()); EXPECT_TRUE(session.want_write()); visitor.set_is_write_blocked(false); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, _, 0x1, 0)); result = session.Send(); EXPECT_EQ(0, result); absl::string_view serialized = visitor.data(); EXPECT_THAT(serialized, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS, SpdyFrameType::DATA})); EXPECT_FALSE(session.want_write()); } TEST(OgHttp2SessionTest, ServerConstruction) { testing::StrictMock<MockHttp2Visitor> visitor; OgHttp2Session::Options options; options.perspective = Perspective::kServer; OgHttp2Session session(visitor, options); EXPECT_TRUE(session.want_read()); EXPECT_FALSE(session.want_write()); EXPECT_EQ(session.GetRemoteWindowSize(), kInitialFlowControlWindowSize); EXPECT_TRUE(session.IsServerSession()); EXPECT_EQ(0, session.GetHighestReceivedStreamId()); } TEST(OgHttp2SessionTest, ServerHandlesFrames) { TestVisitor visitor; OgHttp2Session::Options options; options.perspective = Perspective::kServer; OgHttp2Session session(visitor, options); EXPECT_EQ(0, session.GetHpackDecoderDynamicTableSize()); const std::string frames = TestFrameSequence() .ClientPreface() .Ping(42) .WindowUpdate(0, 1000) .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .WindowUpdate(1, 2000) .Data(1, "This is the request body.") .Headers(3, {{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}, true) .RstStream(3, Http2ErrorCode::CANCEL) .Ping(47) .Serialize(); testing::InSequence s; const char* kSentinel1 = "arbitrary pointer 1"; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, 8, PING, 0)); EXPECT_CALL(visitor, OnPing(42, false)); EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(0, 1000)); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)) .WillOnce(testing::InvokeWithoutArgs([&session, kSentinel1]() { session.SetStreamUserData(1, const_cast<char*>(kSentinel1)); return true; })); EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(1, 2000)); EXPECT_CALL(visitor, OnFrameHeader(1, 25, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 25)); EXPECT_CALL(visitor, OnDataForStream(1, "This is the request body.")); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(3, ":scheme", "http")); EXPECT_CALL(visitor, OnHeaderForStream(3, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(3, ":path", "/this/is/request/two")); EXPECT_CALL(visitor, OnEndHeadersForStream(3)); EXPECT_CALL(visitor, OnEndStream(3)); EXPECT_CALL(visitor, OnFrameHeader(3, 4, RST_STREAM, 0)); EXPECT_CALL(visitor, OnRstStream(3, Http2ErrorCode::CANCEL)); EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::CANCEL)); EXPECT_CALL(visitor, OnFrameHeader(0, 8, PING, 0)); EXPECT_CALL(visitor, OnPing(47, false)); const int64_t result = session.ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); EXPECT_EQ(kSentinel1, session.GetStreamUserData(1)); EXPECT_GT(kInitialFlowControlWindowSize, session.GetStreamReceiveWindowSize(1)); EXPECT_EQ(session.GetReceiveWindowSize(), session.GetStreamReceiveWindowSize(1)); EXPECT_EQ(kInitialFlowControlWindowSize, session.GetStreamReceiveWindowLimit(1)); EXPECT_GT(session.GetHpackDecoderDynamicTableSize(), 0); const char* kSentinel3 = "another arbitrary pointer"; session.SetStreamUserData(3, const_cast<char*>(kSentinel3)); EXPECT_EQ(nullptr, session.GetStreamUserData(3)); EXPECT_EQ(session.GetRemoteWindowSize(), kInitialFlowControlWindowSize + 1000); EXPECT_EQ(3, session.GetHighestReceivedStreamId()); EXPECT_TRUE(session.want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(PING, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(PING, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(PING, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(PING, 0, _, 0x1, 0)); int send_result = session.Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames( {spdy::SpdyFrameType::SETTINGS, spdy::SpdyFrameType::SETTINGS, spdy::SpdyFrameType::PING, spdy::SpdyFrameType::PING})); } TEST(OgHttp2SessionTest, ServerEnqueuesSettingsBeforeOtherFrame) { TestVisitor visitor; OgHttp2Session::Options options; options.perspective = Perspective::kServer; OgHttp2Session session(visitor, options); EXPECT_FALSE(session.want_write()); session.EnqueueFrame(std::make_unique<spdy::SpdyPingIR>(42)); EXPECT_TRUE(session.want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(PING, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(PING, 0, _, 0x0, 0)); int result = session.Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::PING})); } TEST(OgHttp2SessionTest, ServerEnqueuesSettingsOnce) { TestVisitor visitor; OgHttp2Session::Options options; options.perspective = Perspective::kServer; OgHttp2Session session(visitor, options); EXPECT_FALSE(session.want_write()); session.EnqueueFrame(std::make_unique<spdy::SpdySettingsIR>()); EXPECT_TRUE(session.want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); int result = session.Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); } TEST(OgHttp2SessionTest, ServerSubmitResponse) { TestVisitor visitor; OgHttp2Session::Options options; options.perspective = Perspective::kServer; OgHttp2Session session(visitor, options); EXPECT_FALSE(session.want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true) .Serialize(); testing::InSequence s; const char* kSentinel1 = "arbitrary pointer 1"; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)) .WillOnce(testing::InvokeWithoutArgs([&session, kSentinel1]() { session.SetStreamUserData(1, const_cast<char*>(kSentinel1)); return true; })); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t result = session.ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); EXPECT_EQ(1, session.GetHighestReceivedStreamId()); EXPECT_EQ(0, session.GetHpackEncoderDynamicTableSize()); EXPECT_TRUE(session.want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); int send_result = session.Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS})); visitor.Clear(); EXPECT_FALSE(session.want_write()); visitor.AppendPayloadForStream(1, "This is an example response body."); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = session.SubmitResponse( 1, ToHeaders({{":status", "404"}, {"x-comment", "I have no idea what you're talking about."}}), std::move(body1), false); EXPECT_EQ(submit_result, 0); EXPECT_TRUE(session.want_write()); EXPECT_EQ(kSentinel1, session.GetStreamUserData(1)); session.SetStreamUserData(1, nullptr); EXPECT_EQ(nullptr, session.GetStreamUserData(1)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0)); send_result = session.Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::DATA})); EXPECT_FALSE(session.want_write()); EXPECT_LT(session.GetStreamSendWindowSize(1), kInitialFlowControlWindowSize); EXPECT_GT(session.GetStreamSendWindowSize(1), 0); EXPECT_EQ(session.GetStreamSendWindowSize(3), -1); EXPECT_GT(session.GetHpackEncoderDynamicTableSize(), 0); } TEST(OgHttp2SessionTest, ServerSendsTrailers) { TestVisitor visitor; OgHttp2Session::Options options; options.perspective = Perspective::kServer; OgHttp2Session session(visitor, options); EXPECT_FALSE(session.want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t result = session.ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); EXPECT_TRUE(session.want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); int send_result = session.Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS})); visitor.Clear(); EXPECT_FALSE(session.want_write()); visitor.AppendPayloadForStream(1, "This is an example response body."); visitor.SetEndData(1, false); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = session.SubmitResponse( 1, ToHeaders({{":status", "200"}, {"x-comment", "Sure, sounds good."}}), std::move(body1), false); EXPECT_EQ(submit_result, 0); EXPECT_TRUE(session.want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0)); send_result = session.Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::DATA})); visitor.Clear(); EXPECT_FALSE(session.want_write()); int trailer_result = session.SubmitTrailer( 1, ToHeaders({{"final-status", "a-ok"}, {"x-comment", "trailers sure are cool"}})); ASSERT_EQ(trailer_result, 0); EXPECT_TRUE(session.want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x5, 0)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); send_result = session.Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS})); } TEST(OgHttp2SessionTest, ServerQueuesTrailersWithResponse) { TestVisitor visitor; OgHttp2Session::Options options; options.perspective = Perspective::kServer; OgHttp2Session session(visitor, options); EXPECT_FALSE(session.want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t result = session.ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); EXPECT_TRUE(session.want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); int send_result = session.Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS})); visitor.Clear(); EXPECT_FALSE(session.want_write()); visitor.AppendPayloadForStream(1, "This is an example response body."); visitor.SetEndData(1, false); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = session.SubmitResponse( 1, ToHeaders({{":status", "200"}, {"x-comment", "Sure, sounds good."}}), std::move(body1), false); EXPECT_EQ(submit_result, 0); EXPECT_TRUE(session.want_write()); int trailer_result = session.SubmitTrailer( 1, ToHeaders({{"final-status", "a-ok"}, {"x-comment", "trailers sure are cool"}})); ASSERT_EQ(trailer_result, 0); EXPECT_TRUE(session.want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x5)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x5, 0)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); send_result = session.Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::DATA, SpdyFrameType::HEADERS})); } TEST(OgHttp2SessionTest, ServerSeesErrorOnEndStream) { TestVisitor visitor; OgHttp2Session::Options options; options.perspective = Perspective::kServer; OgHttp2Session session(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/"}}, false) .Data(1, "Request body", true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0x4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0x1)); EXPECT_CALL(visitor, OnBeginDataForStream(1, _)); EXPECT_CALL(visitor, OnDataForStream(1, "Request body")); EXPECT_CALL(visitor, OnEndStream(1)).WillOnce(testing::Return(false)); EXPECT_CALL( visitor, OnConnectionError(Http2VisitorInterface::ConnectionError::kParseError)); const int64_t result = session.ProcessBytes(frames); EXPECT_EQ(-902, result); EXPECT_TRUE(session.want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL( visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>( Http2VisitorInterface::ConnectionError::kParseError))); int send_result = session.Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY})); visitor.Clear(); EXPECT_FALSE(session.want_write()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/oghttp2_session.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/oghttp2_session_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
d860f9ce-8480-49bb-8ab4-5ebe9fdd68e0
cpp
google/quiche
oghttp2_util
quiche/http2/adapter/oghttp2_util.cc
quiche/http2/adapter/oghttp2_util_test.cc
#include "quiche/http2/adapter/oghttp2_util.h" namespace http2 { namespace adapter { quiche::HttpHeaderBlock ToHeaderBlock(absl::Span<const Header> headers) { quiche::HttpHeaderBlock block; for (const Header& header : headers) { absl::string_view name = GetStringView(header.first).first; absl::string_view value = GetStringView(header.second).first; block.AppendValueOrAddHeader(name, value); } return block; } } }
#include "quiche/http2/adapter/oghttp2_util.h" #include <utility> #include <vector> #include "quiche/http2/adapter/http2_protocol.h" #include "quiche/http2/adapter/test_frame_sequence.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace adapter { namespace test { namespace { using HeaderPair = std::pair<absl::string_view, absl::string_view>; TEST(ToHeaderBlock, EmptySpan) { quiche::HttpHeaderBlock block = ToHeaderBlock({}); EXPECT_TRUE(block.empty()); } TEST(ToHeaderBlock, ExampleRequestHeaders) { const std::vector<HeaderPair> pairs = {{":authority", "example.com"}, {":method", "GET"}, {":path", "/example.html"}, {":scheme", "http"}, {"accept", "text/plain, text/html"}}; const std::vector<Header> headers = ToHeaders(pairs); quiche::HttpHeaderBlock block = ToHeaderBlock(headers); EXPECT_THAT(block, testing::ElementsAreArray(pairs)); } TEST(ToHeaderBlock, ExampleResponseHeaders) { const std::vector<HeaderPair> pairs = { {":status", "403"}, {"content-length", "1023"}, {"x-extra-info", "humblest apologies"}}; const std::vector<Header> headers = ToHeaders(pairs); quiche::HttpHeaderBlock block = ToHeaderBlock(headers); EXPECT_THAT(block, testing::ElementsAreArray(pairs)); } TEST(ToHeaderBlock, RepeatedRequestHeaderNames) { const std::vector<HeaderPair> pairs = { {":authority", "example.com"}, {":method", "GET"}, {":path", "/example.html"}, {":scheme", "http"}, {"cookie", "chocolate_chips=yes"}, {"accept", "text/plain, text/html"}, {"cookie", "raisins=no"}}; const std::vector<HeaderPair> expected = { {":authority", "example.com"}, {":method", "GET"}, {":path", "/example.html"}, {":scheme", "http"}, {"cookie", "chocolate_chips=yes; raisins=no"}, {"accept", "text/plain, text/html"}}; const std::vector<Header> headers = ToHeaders(pairs); quiche::HttpHeaderBlock block = ToHeaderBlock(headers); EXPECT_THAT(block, testing::ElementsAreArray(expected)); } TEST(ToHeaderBlock, RepeatedResponseHeaderNames) { const std::vector<HeaderPair> pairs = { {":status", "403"}, {"x-extra-info", "sorry"}, {"content-length", "1023"}, {"x-extra-info", "humblest apologies"}, {"content-length", "1024"}, {"set-cookie", "chocolate_chips=yes"}, {"set-cookie", "raisins=no"}}; const std::vector<HeaderPair> expected = { {":status", "403"}, {"x-extra-info", absl::string_view("sorry\0humblest apologies", 24)}, {"content-length", absl::string_view("1023" "\0" "1024", 9)}, {"set-cookie", absl::string_view("chocolate_chips=yes\0raisins=no", 30)}}; const std::vector<Header> headers = ToHeaders(pairs); quiche::HttpHeaderBlock block = ToHeaderBlock(headers); EXPECT_THAT(block, testing::ElementsAreArray(expected)); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/oghttp2_util.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/oghttp2_util_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
85616131-3443-4e65-a297-10371fcfbd75
cpp
google/quiche
oghttp2_adapter
quiche/http2/adapter/oghttp2_adapter.cc
quiche/http2/adapter/oghttp2_adapter_test.cc
#include "quiche/http2/adapter/oghttp2_adapter.h" #include <memory> #include <string> #include <utility> #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "quiche/http2/adapter/http2_util.h" #include "quiche/http2/core/spdy_protocol.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" namespace http2 { namespace adapter { namespace { using spdy::SpdyGoAwayIR; using spdy::SpdyPingIR; using spdy::SpdyPriorityIR; using spdy::SpdyWindowUpdateIR; } std::unique_ptr<OgHttp2Adapter> OgHttp2Adapter::Create( Http2VisitorInterface& visitor, Options options) { return absl::WrapUnique(new OgHttp2Adapter(visitor, std::move(options))); } OgHttp2Adapter::~OgHttp2Adapter() {} bool OgHttp2Adapter::IsServerSession() const { return session_->IsServerSession(); } int64_t OgHttp2Adapter::ProcessBytes(absl::string_view bytes) { return session_->ProcessBytes(bytes); } void OgHttp2Adapter::SubmitSettings(absl::Span<const Http2Setting> settings) { session_->SubmitSettings(settings); } void OgHttp2Adapter::SubmitPriorityForStream(Http2StreamId stream_id, Http2StreamId parent_stream_id, int weight, bool exclusive) { session_->EnqueueFrame(std::make_unique<SpdyPriorityIR>( stream_id, parent_stream_id, weight, exclusive)); } void OgHttp2Adapter::SubmitPing(Http2PingId ping_id) { session_->EnqueueFrame(std::make_unique<SpdyPingIR>(ping_id)); } void OgHttp2Adapter::SubmitShutdownNotice() { session_->StartGracefulShutdown(); } void OgHttp2Adapter::SubmitGoAway(Http2StreamId last_accepted_stream_id, Http2ErrorCode error_code, absl::string_view opaque_data) { session_->EnqueueFrame(std::make_unique<SpdyGoAwayIR>( last_accepted_stream_id, TranslateErrorCode(error_code), std::string(opaque_data))); } void OgHttp2Adapter::SubmitWindowUpdate(Http2StreamId stream_id, int window_increment) { session_->EnqueueFrame( std::make_unique<SpdyWindowUpdateIR>(stream_id, window_increment)); } void OgHttp2Adapter::SubmitMetadata(Http2StreamId stream_id, size_t , std::unique_ptr<MetadataSource> source) { session_->SubmitMetadata(stream_id, std::move(source)); } void OgHttp2Adapter::SubmitMetadata(Http2StreamId stream_id, size_t ) { session_->SubmitMetadata(stream_id); } int OgHttp2Adapter::Send() { return session_->Send(); } int OgHttp2Adapter::GetSendWindowSize() const { return session_->GetRemoteWindowSize(); } int OgHttp2Adapter::GetStreamSendWindowSize(Http2StreamId stream_id) const { return session_->GetStreamSendWindowSize(stream_id); } int OgHttp2Adapter::GetStreamReceiveWindowLimit(Http2StreamId stream_id) const { return session_->GetStreamReceiveWindowLimit(stream_id); } int OgHttp2Adapter::GetStreamReceiveWindowSize(Http2StreamId stream_id) const { return session_->GetStreamReceiveWindowSize(stream_id); } int OgHttp2Adapter::GetReceiveWindowSize() const { return session_->GetReceiveWindowSize(); } int OgHttp2Adapter::GetHpackEncoderDynamicTableSize() const { return session_->GetHpackEncoderDynamicTableSize(); } int OgHttp2Adapter::GetHpackEncoderDynamicTableCapacity() const { return session_->GetHpackEncoderDynamicTableCapacity(); } int OgHttp2Adapter::GetHpackDecoderDynamicTableSize() const { return session_->GetHpackDecoderDynamicTableSize(); } int OgHttp2Adapter::GetHpackDecoderSizeLimit() const { return session_->GetHpackDecoderSizeLimit(); } Http2StreamId OgHttp2Adapter::GetHighestReceivedStreamId() const { return session_->GetHighestReceivedStreamId(); } void OgHttp2Adapter::MarkDataConsumedForStream(Http2StreamId stream_id, size_t num_bytes) { session_->Consume(stream_id, num_bytes); } void OgHttp2Adapter::SubmitRst(Http2StreamId stream_id, Http2ErrorCode error_code) { session_->EnqueueFrame(std::make_unique<spdy::SpdyRstStreamIR>( stream_id, TranslateErrorCode(error_code))); } int32_t OgHttp2Adapter::SubmitRequest( absl::Span<const Header> headers, std::unique_ptr<DataFrameSource> data_source, bool end_stream, void* user_data) { return session_->SubmitRequest(headers, std::move(data_source), end_stream, user_data); } int OgHttp2Adapter::SubmitResponse(Http2StreamId stream_id, absl::Span<const Header> headers, std::unique_ptr<DataFrameSource> data_source, bool end_stream) { return session_->SubmitResponse(stream_id, headers, std::move(data_source), end_stream); } int OgHttp2Adapter::SubmitTrailer(Http2StreamId stream_id, absl::Span<const Header> trailers) { return session_->SubmitTrailer(stream_id, trailers); } void OgHttp2Adapter::SetStreamUserData(Http2StreamId stream_id, void* user_data) { session_->SetStreamUserData(stream_id, user_data); } void* OgHttp2Adapter::GetStreamUserData(Http2StreamId stream_id) { return session_->GetStreamUserData(stream_id); } bool OgHttp2Adapter::ResumeStream(Http2StreamId stream_id) { return session_->ResumeStream(stream_id); } OgHttp2Adapter::OgHttp2Adapter(Http2VisitorInterface& visitor, Options options) : Http2Adapter(visitor), session_(std::make_unique<OgHttp2Session>(visitor, std::move(options))) {} } }
#include "quiche/http2/adapter/oghttp2_adapter.h" #include <cstdint> #include <limits> #include <memory> #include <string> #include <vector> #include "absl/strings/str_join.h" #include "quiche/http2/adapter/http2_protocol.h" #include "quiche/http2/adapter/http2_visitor_interface.h" #include "quiche/http2/adapter/mock_http2_visitor.h" #include "quiche/http2/adapter/oghttp2_util.h" #include "quiche/http2/adapter/test_frame_sequence.h" #include "quiche/http2/adapter/test_utils.h" #include "quiche/common/http/http_header_block.h" #include "quiche/common/platform/api/quiche_expect_bug.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace adapter { namespace test { namespace { using ConnectionError = Http2VisitorInterface::ConnectionError; using spdy::SpdyFrameType; using testing::_; enum FrameType { DATA, HEADERS, PRIORITY, RST_STREAM, SETTINGS, PUSH_PROMISE, PING, GOAWAY, WINDOW_UPDATE, CONTINUATION, }; TEST(OgHttp2AdapterTest, IsServerSession) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); EXPECT_TRUE(adapter->IsServerSession()); } TEST(OgHttp2AdapterTest, ProcessBytes) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence seq; EXPECT_CALL(visitor, OnFrameHeader(0, 0, 4, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, 8, 6, 0)); EXPECT_CALL(visitor, OnPing(17, false)); adapter->ProcessBytes( TestFrameSequence().ClientPreface().Ping(17).Serialize()); } TEST(OgHttp2AdapterTest, HeaderValuesWithObsTextAllowedByDefault) { TestVisitor visitor; OgHttp2Session::Options options; options.perspective = Perspective::kServer; ASSERT_TRUE(options.allow_obs_text); auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/"}, {"name", "val\xa1ue"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/")); EXPECT_CALL(visitor, OnHeaderForStream(1, "name", "val\xa1ue")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); } TEST(OgHttp2AdapterTest, HeaderValuesWithObsTextDisallowed) { TestVisitor visitor; OgHttp2Session::Options options; options.allow_obs_text = false; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/"}, {"name", "val\xa1ue"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/")); EXPECT_CALL( visitor, OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); } TEST(OgHttp2AdapterTest, RequestPathWithSpaceOrTab) { TestVisitor visitor; OgHttp2Session::Options options; options.allow_obs_text = false; options.perspective = Perspective::kServer; ASSERT_EQ(false, options.validate_path); options.validate_path = true; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/ fragment"}}, true) .Headers(3, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/\tfragment2"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL( visitor, OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(3, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(3, ":authority", "example.com")); EXPECT_CALL( visitor, OnInvalidFrame(3, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); } TEST(OgHttp2AdapterTest, RequestPathWithSpaceOrTabNoPathValidation) { TestVisitor visitor; OgHttp2Session::Options options; options.allow_obs_text = false; options.perspective = Perspective::kServer; ASSERT_EQ(false, options.validate_path); auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/ fragment"}}, true) .Headers(3, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/\tfragment2"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/ fragment")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(3, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(3, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(3, ":path", "/\tfragment2")); EXPECT_CALL(visitor, OnEndHeadersForStream(3)); EXPECT_CALL(visitor, OnEndStream(3)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); } TEST(OgHttp2AdapterTest, InitialSettingsNoExtendedConnect) { TestVisitor client_visitor; OgHttp2Adapter::Options client_options; client_options.perspective = Perspective::kClient; client_options.max_header_list_bytes = 42; client_options.allow_extended_connect = false; auto client_adapter = OgHttp2Adapter::Create(client_visitor, client_options); TestVisitor server_visitor; OgHttp2Adapter::Options server_options; server_options.perspective = Perspective::kServer; server_options.allow_extended_connect = false; auto server_adapter = OgHttp2Adapter::Create(server_visitor, server_options); testing::InSequence s; EXPECT_CALL(client_visitor, OnBeforeFrameSent(SETTINGS, 0, 12, 0x0)); EXPECT_CALL(client_visitor, OnFrameSent(SETTINGS, 0, 12, 0x0, 0)); { int result = client_adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = client_visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS})); } EXPECT_CALL(server_visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x0)); EXPECT_CALL(server_visitor, OnFrameSent(SETTINGS, 0, 0, 0x0, 0)); { int result = server_adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = server_visitor.data(); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS})); } EXPECT_CALL(client_visitor, OnFrameHeader(0, 0, SETTINGS, 0x0)); EXPECT_CALL(client_visitor, OnSettingsStart()); EXPECT_CALL(client_visitor, OnSettingsEnd()); { const int64_t result = client_adapter->ProcessBytes(server_visitor.data()); EXPECT_EQ(server_visitor.data().size(), static_cast<size_t>(result)); } EXPECT_CALL(server_visitor, OnFrameHeader(0, 12, SETTINGS, 0x0)); EXPECT_CALL(server_visitor, OnSettingsStart()); EXPECT_CALL(server_visitor, OnSetting(Http2Setting{Http2KnownSettingsId::ENABLE_PUSH, 0u})); EXPECT_CALL( server_visitor, OnSetting(Http2Setting{Http2KnownSettingsId::MAX_HEADER_LIST_SIZE, 42u})); EXPECT_CALL(server_visitor, OnSettingsEnd()); { const int64_t result = server_adapter->ProcessBytes(client_visitor.data()); EXPECT_EQ(client_visitor.data().size(), static_cast<size_t>(result)); } } TEST(OgHttp2AdapterTest, InitialSettings) { TestVisitor client_visitor; OgHttp2Adapter::Options client_options; client_options.perspective = Perspective::kClient; client_options.max_header_list_bytes = 42; ASSERT_TRUE(client_options.allow_extended_connect); auto client_adapter = OgHttp2Adapter::Create(client_visitor, client_options); TestVisitor server_visitor; OgHttp2Adapter::Options server_options; server_options.perspective = Perspective::kServer; ASSERT_TRUE(server_options.allow_extended_connect); auto server_adapter = OgHttp2Adapter::Create(server_visitor, server_options); testing::InSequence s; EXPECT_CALL(client_visitor, OnBeforeFrameSent(SETTINGS, 0, 12, 0x0)); EXPECT_CALL(client_visitor, OnFrameSent(SETTINGS, 0, 12, 0x0, 0)); { int result = client_adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = client_visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS})); } EXPECT_CALL(server_visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(server_visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); { int result = server_adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = server_visitor.data(); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS})); } EXPECT_CALL(client_visitor, OnFrameHeader(0, 6, SETTINGS, 0x0)); EXPECT_CALL(client_visitor, OnSettingsStart()); EXPECT_CALL(client_visitor, OnSetting(Http2Setting{ Http2KnownSettingsId::ENABLE_CONNECT_PROTOCOL, 1u})); EXPECT_CALL(client_visitor, OnSettingsEnd()); { const int64_t result = client_adapter->ProcessBytes(server_visitor.data()); EXPECT_EQ(server_visitor.data().size(), static_cast<size_t>(result)); } EXPECT_CALL(server_visitor, OnFrameHeader(0, 12, SETTINGS, 0x0)); EXPECT_CALL(server_visitor, OnSettingsStart()); EXPECT_CALL(server_visitor, OnSetting(Http2Setting{Http2KnownSettingsId::ENABLE_PUSH, 0u})); EXPECT_CALL( server_visitor, OnSetting(Http2Setting{Http2KnownSettingsId::MAX_HEADER_LIST_SIZE, 42u})); EXPECT_CALL(server_visitor, OnSettingsEnd()); { const int64_t result = server_adapter->ProcessBytes(client_visitor.data()); EXPECT_EQ(client_visitor.data().size(), static_cast<size_t>(result)); } } TEST(OgHttp2AdapterTest, AutomaticSettingsAndPingAcks) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence().ClientPreface().Ping(42).Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, _, PING, 0)); EXPECT_CALL(visitor, OnPing(42, false)); const int64_t read_result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(read_result), frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(PING, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(PING, 0, _, ACK_FLAG, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::PING})); } TEST(OgHttp2AdapterTest, AutomaticPingAcksDisabled) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; options.auto_ping_ack = false; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence().ClientPreface().Ping(42).Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, _, PING, 0)); EXPECT_CALL(visitor, OnPing(42, false)); const int64_t read_result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(read_result), frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS})); } TEST(OgHttp2AdapterTest, InvalidMaxFrameSizeSetting) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence().ClientPreface({{MAX_FRAME_SIZE, 3u}}).Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL( visitor, OnInvalidFrame(0, Http2VisitorInterface::InvalidFrameError::kProtocol)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kInvalidSetting)); const int64_t read_result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(read_result), frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY})); } TEST(OgHttp2AdapterTest, InvalidPushSetting) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence().ClientPreface({{ENABLE_PUSH, 3u}}).Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL( visitor, OnInvalidFrame(0, Http2VisitorInterface::InvalidFrameError::kProtocol)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kInvalidSetting)); const int64_t read_result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(read_result), frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY})); } TEST(OgHttp2AdapterTest, InvalidConnectProtocolSetting) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface({{ENABLE_CONNECT_PROTOCOL, 3u}}) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL( visitor, OnInvalidFrame(0, Http2VisitorInterface::InvalidFrameError::kProtocol)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kInvalidSetting)); int64_t read_result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(read_result), frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY})); auto adapter2 = OgHttp2Adapter::Create(visitor, options); const std::string frames2 = TestFrameSequence() .ClientPreface({{ENABLE_CONNECT_PROTOCOL, 1}}) .Settings({{ENABLE_CONNECT_PROTOCOL, 0}}) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSetting(Http2Setting{ENABLE_CONNECT_PROTOCOL, 1u})); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL( visitor, OnInvalidFrame(0, Http2VisitorInterface::InvalidFrameError::kProtocol)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kInvalidSetting)); read_result = adapter2->ProcessBytes(frames2); EXPECT_EQ(static_cast<size_t>(read_result), frames2.size()); EXPECT_TRUE(adapter2->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); adapter2->Send(); } TEST(OgHttp2AdapterTest, ClientSetsRemoteMaxStreamOption) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; options.remote_max_concurrent_streams = 3; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/"}}); const int32_t stream_id1 = adapter->SubmitRequest(headers, nullptr, true, nullptr); const int32_t stream_id2 = adapter->SubmitRequest(headers, nullptr, true, nullptr); const int32_t stream_id3 = adapter->SubmitRequest(headers, nullptr, true, nullptr); const int32_t stream_id4 = adapter->SubmitRequest(headers, nullptr, true, nullptr); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id2, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id2, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id3, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id3, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(stream_id1, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(stream_id1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(stream_id1)); EXPECT_CALL(visitor, OnHeaderForStream(stream_id1, ":status", "200")); EXPECT_CALL(visitor, OnHeaderForStream(stream_id1, "server", "my-fake-server")); EXPECT_CALL(visitor, OnHeaderForStream(stream_id1, "date", "Tue, 6 Apr 2021 12:54:01 GMT")); EXPECT_CALL(visitor, OnEndHeadersForStream(stream_id1)); EXPECT_CALL(visitor, OnEndStream(stream_id1)); EXPECT_CALL(visitor, OnCloseStream(stream_id1, Http2ErrorCode::HTTP2_NO_ERROR)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); ASSERT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id4, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id4, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); result = adapter->Send(); EXPECT_EQ(0, result); } TEST(OgHttp2AdapterTest, ClientHandles100Headers) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id1 = adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); QUICHE_LOG(INFO) << "Created stream: " << stream_id1; EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "100"}}, false) .Ping(101) .Headers(1, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "100")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(0, 8, PING, 0)); EXPECT_CALL(visitor, OnPing(101, false)); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200")); EXPECT_CALL(visitor, OnHeaderForStream(1, "server", "my-fake-server")); EXPECT_CALL(visitor, OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(PING, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(PING, 0, _, ACK_FLAG, 0)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::PING})); } TEST(OgHttp2AdapterTest, QueuingWindowUpdateAffectsWindow) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); EXPECT_EQ(adapter->GetReceiveWindowSize(), kInitialFlowControlWindowSize); adapter->SubmitWindowUpdate(0, 10000); EXPECT_EQ(adapter->GetReceiveWindowSize(), kInitialFlowControlWindowSize + 10000); const std::vector<Header> headers = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 0, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 0, 4, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id), kInitialFlowControlWindowSize); adapter->SubmitWindowUpdate(1, 20000); EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id), kInitialFlowControlWindowSize + 20000); } TEST(OgHttp2AdapterTest, AckOfSettingInitialWindowSizeAffectsWindow) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id1 = adapter->SubmitRequest(headers, nullptr, true, nullptr); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); const std::string initial_frames = TestFrameSequence() .ServerPreface() .SettingsAck() .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0x0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, ACK_FLAG)); EXPECT_CALL(visitor, OnSettingsAck); int64_t parse_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), static_cast<size_t>(parse_result)); EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id1), kInitialFlowControlWindowSize); adapter->SubmitSettings({{INITIAL_WINDOW_SIZE, 80000u}}); EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id1), kInitialFlowControlWindowSize); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id1), kInitialFlowControlWindowSize); const std::string settings_ack = TestFrameSequence().SettingsAck().Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, ACK_FLAG)); EXPECT_CALL(visitor, OnSettingsAck); parse_result = adapter->ProcessBytes(settings_ack); EXPECT_EQ(settings_ack.size(), static_cast<size_t>(parse_result)); EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id1), 80000); const std::vector<Header> headers2 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}); const int32_t stream_id2 = adapter->SubmitRequest(headers, nullptr, true, nullptr); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id2, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id2, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_EQ(adapter->GetStreamReceiveWindowSize(stream_id2), 80000); } TEST(OgHttp2AdapterTest, ClientRejects100HeadersWithFin) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id1 = adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); QUICHE_LOG(INFO) << "Created stream: " << stream_id1; EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "100"}}, false) .Headers(1, {{":status", "100"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "100")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "100")); EXPECT_CALL(visitor, OnInvalidFrame( 1, Http2VisitorInterface::InvalidFrameError::kHttpMessaging)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, 1)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST(OgHttp2AdapterTest, ClientRejects100HeadersWithContent) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id1 = adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "100"}}, false) .Data(1, "We needed the final headers before data, whoops") .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "100")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, _)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST(OgHttp2AdapterTest, ClientRejects100HeadersWithContentLength) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id1 = adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "100"}, {"content-length", "42"}}, false) .Headers(1, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "100")); EXPECT_CALL( visitor, OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST(OgHttp2AdapterTest, ClientHandlesResponseWithContentLengthAndPadding) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id1 = adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); const std::vector<Header> headers2 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}); const int32_t stream_id2 = adapter->SubmitRequest(headers2, nullptr, true, nullptr); ASSERT_GT(stream_id2, stream_id1); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id2, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id2, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "200"}, {"content-length", "2"}}, false) .Data(1, "hi", true, 10) .Headers(3, {{":status", "200"}, {"content-length", "24"}}, false) .Data(3, "hi", false, 11) .Data(3, " it's nice", false, 12) .Data(3, " to meet you", true, 13) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200")); EXPECT_CALL(visitor, OnHeaderForStream(1, "content-length", "2")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, 2 + 10, DATA, 0x9)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 2 + 10)); EXPECT_CALL(visitor, OnDataPaddingLength(1, 10)); EXPECT_CALL(visitor, OnDataForStream(1, "hi")); EXPECT_CALL(visitor, OnEndStream(1)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, ":status", "200")); EXPECT_CALL(visitor, OnHeaderForStream(3, "content-length", "24")); EXPECT_CALL(visitor, OnEndHeadersForStream(3)); EXPECT_CALL(visitor, OnFrameHeader(3, 2 + 11, DATA, 0x8)); EXPECT_CALL(visitor, OnBeginDataForStream(3, 2 + 11)); EXPECT_CALL(visitor, OnDataPaddingLength(3, 11)); EXPECT_CALL(visitor, OnDataForStream(3, "hi")); EXPECT_CALL(visitor, OnFrameHeader(3, 10 + 12, DATA, 0x8)); EXPECT_CALL(visitor, OnBeginDataForStream(3, 10 + 12)); EXPECT_CALL(visitor, OnDataPaddingLength(3, 12)); EXPECT_CALL(visitor, OnDataForStream(3, " it's nice")); EXPECT_CALL(visitor, OnFrameHeader(3, 12 + 13, DATA, 0x9)); EXPECT_CALL(visitor, OnBeginDataForStream(3, 12 + 13)); EXPECT_CALL(visitor, OnDataPaddingLength(3, 13)); EXPECT_CALL(visitor, OnDataForStream(3, " to meet you")); EXPECT_CALL(visitor, OnEndStream(3)); EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::HTTP2_NO_ERROR)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({ SpdyFrameType::SETTINGS, })); } class ResponseCompleteBeforeRequestTest : public quiche::test::QuicheTestWithParam<std::tuple<bool, bool>> { public: bool HasTrailers() const { return std::get<0>(GetParam()); } bool HasRstStream() const { return std::get<1>(GetParam()); } }; INSTANTIATE_TEST_SUITE_P(TrailersAndRstStreamAllCombinations, ResponseCompleteBeforeRequestTest, testing::Combine(testing::Bool(), testing::Bool())); TEST_P(ResponseCompleteBeforeRequestTest, ClientHandlesResponseBeforeRequestComplete) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "POST"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); const int32_t stream_id1 = adapter->SubmitRequest(headers1, std::move(body1), false, nullptr); ASSERT_GT(stream_id1, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, END_HEADERS_FLAG, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); visitor.Clear(); TestFrameSequence response; response.ServerPreface() .Headers(1, {{":status", "200"}, {"content-length", "2"}}, false) .Data(1, "hi", !HasTrailers(), 10); if (HasTrailers()) { response.Headers(1, {{"my-weird-trailer", "has a value"}}, true); } if (HasRstStream()) { response.RstStream(1, Http2ErrorCode::HTTP2_NO_ERROR); } const std::string stream_frames = response.Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200")); EXPECT_CALL(visitor, OnHeaderForStream(1, "content-length", "2")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, 2 + 10, DATA, HasTrailers() ? 0x8 : 0x9)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 2 + 10)); EXPECT_CALL(visitor, OnDataPaddingLength(1, 10)); EXPECT_CALL(visitor, OnDataForStream(1, "hi")); if (HasTrailers()) { EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, "my-weird-trailer", "has a value")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); } EXPECT_CALL(visitor, OnEndStream(1)); if (HasRstStream()) { EXPECT_CALL(visitor, OnFrameHeader(1, _, RST_STREAM, 0)); EXPECT_CALL(visitor, OnRstStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); } const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({ SpdyFrameType::SETTINGS, })); if (!HasRstStream()) { visitor.AppendPayloadForStream(1, "final fragment"); } visitor.SetEndData(1, true); adapter->ResumeStream(1); if (!HasRstStream()) { EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, END_STREAM_FLAG, 0)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); } result = adapter->Send(); EXPECT_EQ(0, result); } TEST(OgHttp2AdapterTest, ClientHandles204WithContent) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id1 = adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); const std::vector<Header> headers2 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}); const int32_t stream_id2 = adapter->SubmitRequest(headers2, nullptr, true, nullptr); ASSERT_GT(stream_id2, stream_id1); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id2, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id2, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "204"}, {"content-length", "2"}}, false) .Data(1, "hi") .Headers(3, {{":status", "204"}}, false) .Data(3, "hi") .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "204")); EXPECT_CALL( visitor, OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, ":status", "204")); EXPECT_CALL(visitor, OnEndHeadersForStream(3)); EXPECT_CALL(visitor, OnFrameHeader(3, _, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(3, 2)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 3, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 3, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM, SpdyFrameType::RST_STREAM})); } TEST(OgHttp2AdapterTest, ClientHandles304WithContent) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id1 = adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "304"}, {"content-length", "2"}}, false) .Data(1, "hi") .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "304")); EXPECT_CALL(visitor, OnHeaderForStream(1, "content-length", "2")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 2)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST(OgHttp2AdapterTest, ClientHandles304WithContentLength) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr); ASSERT_GT(stream_id, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "304"}, {"content-length", "2"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "304")); EXPECT_CALL(visitor, OnHeaderForStream(1, "content-length", "2")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); } TEST(OgHttp2AdapterTest, ClientHandlesTrailers) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const char* kSentinel1 = "arbitrary pointer 1"; const int32_t stream_id1 = adapter->SubmitRequest( headers1, nullptr, true, const_cast<char*>(kSentinel1)); ASSERT_GT(stream_id1, 0); QUICHE_LOG(INFO) << "Created stream: " << stream_id1; EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, false) .Data(1, "This is the response body.") .Headers(1, {{"final-status", "A-OK"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200")); EXPECT_CALL(visitor, OnHeaderForStream(1, "server", "my-fake-server")); EXPECT_CALL(visitor, OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, 26, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 26)); EXPECT_CALL(visitor, OnDataForStream(1, "This is the response body.")); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, "final-status", "A-OK")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); } class OgHttp2AdapterDataTest : public quiche::test::QuicheTestWithParam<bool> { }; INSTANTIATE_TEST_SUITE_P(BothValues, OgHttp2AdapterDataTest, testing::Bool()); TEST_P(OgHttp2AdapterDataTest, ClientSendsTrailers) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const std::string kBody = "This is an example request body."; visitor.AppendPayloadForStream(1, kBody); visitor.SetEndData(1, false); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); const int32_t stream_id1 = adapter->SubmitRequest( headers1, GetParam() ? nullptr : std::move(body1), false, nullptr); ASSERT_EQ(stream_id1, 1); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id1, _, 0x0, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS, SpdyFrameType::DATA})); visitor.Clear(); const std::vector<Header> trailers1 = ToHeaders({{"extra-info", "Trailers are weird but good?"}}); adapter->SubmitTrailer(stream_id1, trailers1); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); result = adapter->Send(); EXPECT_EQ(0, result); data = visitor.data(); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::HEADERS})); } TEST(OgHttp2AdapterTest, ClientRstStreamWhileHandlingHeaders) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const char* kSentinel1 = "arbitrary pointer 1"; const int32_t stream_id1 = adapter->SubmitRequest( headers1, nullptr, true, const_cast<char*>(kSentinel1)); ASSERT_GT(stream_id1, 0); QUICHE_LOG(INFO) << "Created stream: " << stream_id1; EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, false) .Data(1, "This is the response body.") .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200")); EXPECT_CALL(visitor, OnHeaderForStream(1, "server", "my-fake-server")); EXPECT_CALL(visitor, OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT")) .WillOnce(testing::DoAll( testing::InvokeWithoutArgs([&adapter]() { adapter->SubmitRst(1, Http2ErrorCode::REFUSED_STREAM); }), testing::Return(Http2VisitorInterface::HEADER_RST_STREAM))); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, stream_id1, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, stream_id1, 4, 0x0, static_cast<int>(Http2ErrorCode::REFUSED_STREAM))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST(OgHttp2AdapterTest, ClientConnectionErrorWhileHandlingHeaders) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const char* kSentinel1 = "arbitrary pointer 1"; const int32_t stream_id1 = adapter->SubmitRequest( headers1, nullptr, true, const_cast<char*>(kSentinel1)); ASSERT_GT(stream_id1, 0); QUICHE_LOG(INFO) << "Created stream: " << stream_id1; EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, false) .Data(1, "This is the response body.") .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200")); EXPECT_CALL(visitor, OnHeaderForStream(1, "server", "my-fake-server")); EXPECT_CALL(visitor, OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT")) .WillOnce( testing::Return(Http2VisitorInterface::HEADER_CONNECTION_ERROR)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kHeaderError)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_LT(stream_result, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::INTERNAL_ERROR))); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY})); } TEST(OgHttp2AdapterTest, ClientConnectionErrorWhileHandlingHeadersOnly) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const char* kSentinel1 = "arbitrary pointer 1"; const int32_t stream_id1 = adapter->SubmitRequest( headers1, nullptr, true, const_cast<char*>(kSentinel1)); ASSERT_GT(stream_id1, 0); QUICHE_LOG(INFO) << "Created stream: " << stream_id1; EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200")); EXPECT_CALL(visitor, OnHeaderForStream(1, "server", "my-fake-server")); EXPECT_CALL(visitor, OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT")) .WillOnce( testing::Return(Http2VisitorInterface::HEADER_CONNECTION_ERROR)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kHeaderError)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_LT(stream_result, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::INTERNAL_ERROR))); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY})); } TEST(OgHttp2AdapterTest, ClientRejectsHeaders) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const char* kSentinel1 = "arbitrary pointer 1"; const int32_t stream_id1 = adapter->SubmitRequest( headers1, nullptr, true, const_cast<char*>(kSentinel1)); ASSERT_GT(stream_id1, 0); QUICHE_LOG(INFO) << "Created stream: " << stream_id1; EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, false) .Data(1, "This is the response body.") .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)) .WillOnce(testing::Return(false)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kHeaderError)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_LT(stream_result, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::INTERNAL_ERROR))); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY})); } TEST(OgHttp2AdapterTest, ClientHandlesSmallerHpackHeaderTableSetting) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({ {":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"x-i-do-not-like", "green eggs and ham"}, {"x-i-will-not-eat-them", "here or there, in a box, with a fox"}, {"x-like-them-in-a-house", "no"}, {"x-like-them-with-a-mouse", "no"}, }); const int32_t stream_id1 = adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); visitor.Clear(); EXPECT_GT(adapter->GetHpackEncoderDynamicTableSize(), 100); const std::string stream_frames = TestFrameSequence().Settings({{HEADER_TABLE_SIZE, 100u}}).Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSetting(Http2Setting{HEADER_TABLE_SIZE, 100u})); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_EQ(adapter->GetHpackEncoderDynamicTableCapacity(), 100); EXPECT_LE(adapter->GetHpackEncoderDynamicTableSize(), 100); } TEST(OgHttp2AdapterTest, ClientHandlesLargerHpackHeaderTableSetting) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); visitor.Clear(); EXPECT_EQ(adapter->GetHpackEncoderDynamicTableCapacity(), 4096); const std::string stream_frames = TestFrameSequence().Settings({{HEADER_TABLE_SIZE, 40960u}}).Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSetting(Http2Setting{HEADER_TABLE_SIZE, 40960u})); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_EQ(adapter->GetHpackEncoderDynamicTableCapacity(), 4096); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); result = adapter->Send(); EXPECT_EQ(0, result); visitor.Clear(); EXPECT_EQ(adapter->GetHpackEncoderDynamicTableCapacity(), 40960); } TEST(OgHttp2AdapterTest, ClientSendsHpackHeaderTableSetting) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({ {":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, }); const int32_t stream_id1 = adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .SettingsAck() .Headers( 1, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}, {"x-i-do-not-like", "green eggs and ham"}, {"x-i-will-not-eat-them", "here or there, in a box, with a fox"}, {"x-like-them-in-a-house", "no"}, {"x-like-them-with-a-mouse", "no"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 1)); EXPECT_CALL(visitor, OnSettingsAck()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(7); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_GT(adapter->GetHpackDecoderSizeLimit(), 100); adapter->SubmitSettings({{HEADER_TABLE_SIZE, 100u}}); EXPECT_GT(adapter->GetHpackDecoderSizeLimit(), 100); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); EXPECT_GT(adapter->GetHpackDecoderSizeLimit(), 100); result = adapter->Send(); EXPECT_EQ(0, result); visitor.Clear(); const std::vector<Header> headers2 = ToHeaders({ {":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}, }); const int32_t stream_id2 = adapter->SubmitRequest(headers2, nullptr, true, nullptr); ASSERT_GT(stream_id2, stream_id1); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id2, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id2, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); result = adapter->Send(); EXPECT_EQ(0, result); visitor.Clear(); const std::string response_frames = TestFrameSequence() .Headers(stream_id2, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(stream_id2, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(stream_id2)); EXPECT_CALL(visitor, OnHeaderForStream(stream_id2, _, _)).Times(3); EXPECT_CALL(visitor, OnEndHeadersForStream(stream_id2)); EXPECT_CALL(visitor, OnEndStream(stream_id2)); EXPECT_CALL(visitor, OnCloseStream(stream_id2, Http2ErrorCode::HTTP2_NO_ERROR)); const int64_t response_result = adapter->ProcessBytes(response_frames); EXPECT_EQ(response_frames.size(), static_cast<size_t>(response_result)); EXPECT_GT(adapter->GetHpackDecoderSizeLimit(), 100); const std::string settings_ack = TestFrameSequence().SettingsAck().Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 1)); EXPECT_CALL(visitor, OnSettingsAck()); const int64_t ack_result = adapter->ProcessBytes(settings_ack); EXPECT_EQ(settings_ack.size(), static_cast<size_t>(ack_result)); EXPECT_EQ(adapter->GetHpackDecoderSizeLimit(), 100); } TEST(OgHttp2AdapterTest, DISABLED_ClientHandlesInvalidTrailers) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const char* kSentinel1 = "arbitrary pointer 1"; const int32_t stream_id1 = adapter->SubmitRequest( headers1, nullptr, true, const_cast<char*>(kSentinel1)); ASSERT_GT(stream_id1, 0); QUICHE_LOG(INFO) << "Created stream: " << stream_id1; EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, false) .Data(1, "This is the response body.") .Headers(1, {{":bad-status", "9000"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200")); EXPECT_CALL(visitor, OnHeaderForStream(1, "server", "my-fake-server")); EXPECT_CALL(visitor, OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, 26, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 26)); EXPECT_CALL(visitor, OnDataForStream(1, "This is the response body.")); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, stream_id1, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, stream_id1, 4, 0x0, 1)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::PROTOCOL_ERROR)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST(OgHttp2AdapterTest, ClientStartsShutdown) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); EXPECT_FALSE(adapter->want_write()); adapter->SubmitShutdownNotice(); EXPECT_FALSE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view serialized = visitor.data(); EXPECT_THAT(serialized, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::SETTINGS})); } TEST(OgHttp2AdapterTest, ClientReceivesGoAway) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id1 = adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); const std::vector<Header> headers2 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}); const int32_t stream_id2 = adapter->SubmitRequest(headers2, nullptr, true, nullptr); ASSERT_GT(stream_id2, stream_id1); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id2, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id2, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS, SpdyFrameType::HEADERS})); visitor.Clear(); adapter->SubmitWindowUpdate(3, 42); const std::string stream_frames = TestFrameSequence() .ServerPreface() .RstStream(1, Http2ErrorCode::ENHANCE_YOUR_CALM) .GoAway(1, Http2ErrorCode::INTERNAL_ERROR, "indigestion") .WindowUpdate(0, 42) .WindowUpdate(1, 42) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, 4, RST_STREAM, 0)); EXPECT_CALL(visitor, OnRstStream(1, Http2ErrorCode::ENHANCE_YOUR_CALM)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::ENHANCE_YOUR_CALM)); EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0)); EXPECT_CALL(visitor, OnGoAway(1, Http2ErrorCode::INTERNAL_ERROR, "")); EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::REFUSED_STREAM)); EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(0, 42)); EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); } TEST(OgHttp2AdapterTest, ClientReceivesMultipleGoAways) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id1 = adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); visitor.Clear(); const std::string initial_frames = TestFrameSequence() .ServerPreface() .GoAway(kMaxStreamId, Http2ErrorCode::INTERNAL_ERROR, "indigestion") .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0)); EXPECT_CALL(visitor, OnGoAway(kMaxStreamId, Http2ErrorCode::INTERNAL_ERROR, "")); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), static_cast<size_t>(initial_result)); adapter->SubmitWindowUpdate(1, 42); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 1, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 1, 4, 0x0, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::WINDOW_UPDATE})); visitor.Clear(); const std::string final_frames = TestFrameSequence() .GoAway(0, Http2ErrorCode::INTERNAL_ERROR, "indigestion") .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0)); EXPECT_CALL(visitor, OnGoAway(0, Http2ErrorCode::INTERNAL_ERROR, "")); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::REFUSED_STREAM)); const int64_t final_result = adapter->ProcessBytes(final_frames); EXPECT_EQ(final_frames.size(), static_cast<size_t>(final_result)); EXPECT_FALSE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), testing::IsEmpty()); } TEST(OgHttp2AdapterTest, ClientReceivesMultipleGoAwaysWithIncreasingStreamId) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id1 = adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); visitor.Clear(); const std::string frames = TestFrameSequence() .ServerPreface() .GoAway(0, Http2ErrorCode::HTTP2_NO_ERROR, "") .GoAway(0, Http2ErrorCode::ENHANCE_YOUR_CALM, "") .GoAway(1, Http2ErrorCode::INTERNAL_ERROR, "") .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0)); EXPECT_CALL(visitor, OnGoAway(0, Http2ErrorCode::HTTP2_NO_ERROR, "")); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::REFUSED_STREAM)); EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0)); EXPECT_CALL(visitor, OnGoAway(0, Http2ErrorCode::ENHANCE_YOUR_CALM, "")); EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0)); EXPECT_CALL( visitor, OnInvalidFrame(0, Http2VisitorInterface::InvalidFrameError::kProtocol)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kInvalidGoAwayLastStreamId)); const int64_t frames_result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(frames_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY})); } TEST(OgHttp2AdapterTest, ClientReceivesGoAwayWithPendingStreams) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS})); visitor.Clear(); const std::string initial_frames = TestFrameSequence() .ServerPreface({{MAX_CONCURRENT_STREAMS, 1}}) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSetting); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), static_cast<size_t>(initial_result)); const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id1 = adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); const std::vector<Header> headers2 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}); const int32_t stream_id2 = adapter->SubmitRequest(headers2, nullptr, true, nullptr); ASSERT_GT(stream_id2, stream_id1); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .GoAway(kMaxStreamId, Http2ErrorCode::INTERNAL_ERROR, "indigestion") .Settings({{MAX_CONCURRENT_STREAMS, 42u}}) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0)); EXPECT_CALL(visitor, OnGoAway(kMaxStreamId, Http2ErrorCode::INTERNAL_ERROR, "")); EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSetting(Http2Setting{MAX_CONCURRENT_STREAMS, 42u})); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::REFUSED_STREAM)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); visitor.Clear(); const std::vector<Header> headers3 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/three"}}); const int32_t stream_id3 = adapter->SubmitRequest(headers3, nullptr, true, nullptr); ASSERT_GT(stream_id3, stream_id2); EXPECT_CALL(visitor, OnCloseStream(5, Http2ErrorCode::REFUSED_STREAM)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), testing::IsEmpty()); EXPECT_FALSE(adapter->want_write()); } TEST(OgHttp2AdapterTest, ClientFailsOnGoAway) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const char* kSentinel1 = "arbitrary pointer 1"; const int32_t stream_id1 = adapter->SubmitRequest( headers1, nullptr, true, const_cast<char*>(kSentinel1)); ASSERT_GT(stream_id1, 0); QUICHE_LOG(INFO) << "Created stream: " << stream_id1; EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, false) .GoAway(1, Http2ErrorCode::INTERNAL_ERROR, "indigestion") .Data(1, "This is the response body.") .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200")); EXPECT_CALL(visitor, OnHeaderForStream(1, "server", "my-fake-server")); EXPECT_CALL(visitor, OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0)); EXPECT_CALL(visitor, OnGoAway(1, Http2ErrorCode::INTERNAL_ERROR, "")) .WillOnce(testing::Return(false)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kParseError)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_LT(stream_result, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::INTERNAL_ERROR))); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY})); } TEST(OgHttp2AdapterTest, ClientRejects101Response) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"upgrade", "new-protocol"}}); const int32_t stream_id1 = adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "101"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, false) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL( visitor, OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(static_cast<int64_t>(stream_frames.size()), stream_result); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, 4, 0x0)); EXPECT_CALL( visitor, OnFrameSent(RST_STREAM, 1, 4, 0x0, static_cast<uint32_t>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST_P(OgHttp2AdapterDataTest, ClientObeysMaxConcurrentStreams) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); EXPECT_FALSE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view serialized = visitor.data(); EXPECT_THAT(serialized, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::SETTINGS})); visitor.Clear(); const std::string initial_frames = TestFrameSequence() .ServerPreface({{MAX_CONCURRENT_STREAMS, 1}}) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSetting); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), static_cast<size_t>(initial_result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); visitor.Clear(); const std::string kBody = "This is an example request body."; visitor.AppendPayloadForStream(1, kBody); visitor.SetEndData(1, true); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); const int stream_id = adapter->SubmitRequest( ToHeaders({{":method", "POST"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}), GetParam() ? nullptr : std::move(body1), false, nullptr); ASSERT_EQ(stream_id, 1); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, END_HEADERS_FLAG, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, _, END_STREAM_FLAG, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::DATA})); EXPECT_THAT(visitor.data(), testing::HasSubstr(kBody)); visitor.Clear(); EXPECT_FALSE(adapter->want_write()); const int next_stream_id = adapter->SubmitRequest(ToHeaders({{":method", "POST"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}), nullptr, true, nullptr); EXPECT_GT(next_stream_id, stream_id); EXPECT_FALSE(adapter->want_write()); const std::string stream_frames = TestFrameSequence() .Headers(stream_id, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, false) .Data(stream_id, "This is the response body.", true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(stream_id, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(stream_id)); EXPECT_CALL(visitor, OnHeaderForStream(stream_id, ":status", "200")); EXPECT_CALL(visitor, OnHeaderForStream(stream_id, "server", "my-fake-server")); EXPECT_CALL(visitor, OnHeaderForStream(stream_id, "date", "Tue, 6 Apr 2021 12:54:01 GMT")); EXPECT_CALL(visitor, OnEndHeadersForStream(stream_id)); EXPECT_CALL(visitor, OnFrameHeader(stream_id, 26, DATA, END_STREAM_FLAG)); EXPECT_CALL(visitor, OnBeginDataForStream(stream_id, 26)); EXPECT_CALL(visitor, OnDataForStream(stream_id, "This is the response body.")); EXPECT_CALL(visitor, OnEndStream(stream_id)); EXPECT_CALL(visitor, OnCloseStream(stream_id, Http2ErrorCode::HTTP2_NO_ERROR)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, next_stream_id, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, next_stream_id, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS})); visitor.Clear(); EXPECT_FALSE(adapter->want_write()); } TEST_P(OgHttp2AdapterDataTest, ClientReceivesInitialWindowSetting) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string initial_frames = TestFrameSequence() .Settings({{INITIAL_WINDOW_SIZE, 80000u}}) .WindowUpdate(0, 65536) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSetting(Http2Setting{INITIAL_WINDOW_SIZE, 80000u})); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(0, 65536)); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), static_cast<size_t>(initial_result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); int64_t result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view serialized = visitor.data(); EXPECT_THAT(serialized, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS})); visitor.Clear(); const std::string kLongBody = std::string(81000, 'c'); visitor.AppendPayloadForStream(1, kLongBody); visitor.SetEndData(1, true); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); const int stream_id = adapter->SubmitRequest( ToHeaders({{":method", "POST"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}), GetParam() ? nullptr : std::move(body1), false, nullptr); EXPECT_GT(stream_id, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, 16384, 0x0, 0)).Times(4); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, 14464, 0x0, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::DATA, SpdyFrameType::DATA, SpdyFrameType::DATA, SpdyFrameType::DATA, SpdyFrameType::DATA})); } TEST_P(OgHttp2AdapterDataTest, ClientReceivesInitialWindowSettingAfterStreamStart) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string initial_frames = TestFrameSequence().ServerPreface().WindowUpdate(0, 65536).Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(0, 65536)); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), static_cast<size_t>(initial_result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); int64_t result = adapter->Send(); EXPECT_EQ(0, result); visitor.Clear(); const std::string kLongBody = std::string(81000, 'c'); visitor.AppendPayloadForStream(1, kLongBody); visitor.SetEndData(1, true); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); const int stream_id = adapter->SubmitRequest( ToHeaders({{":method", "POST"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}), GetParam() ? nullptr : std::move(body1), false, nullptr); EXPECT_GT(stream_id, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, 16384, 0x0, 0)).Times(3); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, 16383, 0x0, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::DATA, SpdyFrameType::DATA, SpdyFrameType::DATA, SpdyFrameType::DATA})); visitor.Clear(); EXPECT_FALSE(adapter->want_write()); const std::string settings_frame = TestFrameSequence().Settings({{INITIAL_WINDOW_SIZE, 80000u}}).Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSetting(Http2Setting{INITIAL_WINDOW_SIZE, 80000u})); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t settings_result = adapter->ProcessBytes(settings_frame); EXPECT_EQ(settings_frame.size(), static_cast<size_t>(settings_result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id, 14465, 0x0, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::DATA})); } TEST(OgHttp2AdapterTest, InvalidInitialWindowSetting) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); const uint32_t kTooLargeInitialWindow = 1u << 31; const std::string initial_frames = TestFrameSequence() .Settings({{INITIAL_WINDOW_SIZE, kTooLargeInitialWindow}}) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnInvalidFrame( 0, Http2VisitorInterface::InvalidFrameError::kFlowControl)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kFlowControlError)); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), static_cast<size_t>(initial_result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL( visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::FLOW_CONTROL_ERROR))); int64_t result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view serialized = visitor.data(); EXPECT_THAT(serialized, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); serialized.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(serialized, EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY})); visitor.Clear(); } TEST(OggHttp2AdapterClientTest, InitialWindowSettingCausesOverflow) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr); ASSERT_GT(stream_id, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int64_t write_result = adapter->Send(); EXPECT_EQ(0, write_result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); visitor.Clear(); const uint32_t kLargeInitialWindow = (1u << 31) - 1; const std::string frames = TestFrameSequence() .ServerPreface() .Headers(stream_id, {{":status", "200"}}, false) .WindowUpdate(stream_id, 65536u) .Settings({{INITIAL_WINDOW_SIZE, kLargeInitialWindow}}) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(stream_id, _, HEADERS, 0x4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(stream_id)); EXPECT_CALL(visitor, OnHeaderForStream(stream_id, ":status", "200")); EXPECT_CALL(visitor, OnEndHeadersForStream(stream_id)); EXPECT_CALL(visitor, OnFrameHeader(stream_id, 4, WINDOW_UPDATE, 0x0)); EXPECT_CALL(visitor, OnWindowUpdate(stream_id, 65536)); EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSetting(Http2Setting{INITIAL_WINDOW_SIZE, kLargeInitialWindow})); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t read_result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(read_result), frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, stream_id, 4, 0x0)); EXPECT_CALL( visitor, OnFrameSent(RST_STREAM, stream_id, 4, 0x0, static_cast<int>(Http2ErrorCode::FLOW_CONTROL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(stream_id, Http2ErrorCode::HTTP2_NO_ERROR)); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST(OgHttp2AdapterTest, FailureSendingConnectionPreface) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); visitor.set_has_write_error(); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kSendError)); int result = adapter->Send(); EXPECT_LT(result, 0); } TEST(OgHttp2AdapterTest, MaxFrameSizeSettingNotAppliedBeforeAck) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); const uint32_t large_frame_size = kDefaultFramePayloadSizeLimit + 42; adapter->SubmitSettings({{MAX_FRAME_SIZE, large_frame_size}}); const int32_t stream_id = adapter->SubmitRequest( ToHeaders({{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}), nullptr, true, nullptr); EXPECT_GT(stream_id, 0); EXPECT_TRUE(adapter->want_write()); testing::InSequence s; EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); visitor.Clear(); const std::string server_frames = TestFrameSequence() .ServerPreface() .Headers(1, {{":status", "200"}}, false) .Data(1, std::string(large_frame_size, 'a')) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, large_frame_size, DATA, 0x0)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kParseError)); const int64_t process_result = adapter->ProcessBytes(server_frames); EXPECT_EQ(server_frames.size(), static_cast<size_t>(process_result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::FRAME_SIZE_ERROR))); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY})); } TEST(OgHttp2AdapterTest, MaxFrameSizeSettingAppliedAfterAck) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); const uint32_t large_frame_size = kDefaultFramePayloadSizeLimit + 42; adapter->SubmitSettings({{MAX_FRAME_SIZE, large_frame_size}}); const int32_t stream_id = adapter->SubmitRequest( ToHeaders({{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}), nullptr, true, nullptr); EXPECT_GT(stream_id, 0); EXPECT_TRUE(adapter->want_write()); testing::InSequence s; EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); visitor.Clear(); const std::string server_frames = TestFrameSequence() .ServerPreface() .SettingsAck() .Headers(1, {{":status", "200"}}, false) .Data(1, std::string(large_frame_size, 'a')) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, ACK_FLAG)); EXPECT_CALL(visitor, OnSettingsAck()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":status", "200")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, large_frame_size, DATA, 0x0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, large_frame_size)); EXPECT_CALL(visitor, OnDataForStream(1, _)); const int64_t process_result = adapter->ProcessBytes(server_frames); EXPECT_EQ(server_frames.size(), static_cast<size_t>(process_result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); } TEST(OgHttp2AdapterTest, ClientForbidsPushPromise) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); int write_result = adapter->Send(); EXPECT_EQ(0, write_result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS})); visitor.Clear(); const std::vector<Header> headers = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr); ASSERT_GT(stream_id, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); write_result = adapter->Send(); EXPECT_EQ(0, write_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS})); visitor.Clear(); const std::vector<Header> push_headers = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/push"}}); const std::string frames = TestFrameSequence() .ServerPreface() .SettingsAck() .PushPromise(stream_id, 2, push_headers) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, ACK_FLAG)); EXPECT_CALL(visitor, OnSettingsAck); EXPECT_CALL(visitor, OnFrameHeader(stream_id, _, PUSH_PROMISE, _)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kInvalidPushPromise)); const int64_t read_result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(read_result), frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY})); } TEST(OgHttp2AdapterTest, ClientForbidsPushStream) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); int write_result = adapter->Send(); EXPECT_EQ(0, write_result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS})); visitor.Clear(); const std::vector<Header> headers = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr); ASSERT_GT(stream_id, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); write_result = adapter->Send(); EXPECT_EQ(0, write_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS})); visitor.Clear(); const std::string frames = TestFrameSequence() .ServerPreface() .SettingsAck() .Headers(2, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, ACK_FLAG)); EXPECT_CALL(visitor, OnSettingsAck); EXPECT_CALL(visitor, OnFrameHeader(2, _, HEADERS, _)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kInvalidNewStreamId)); const int64_t read_result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(read_result), frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY})); } TEST(OgHttp2AdapterTest, ClientReceivesDataOnClosedStream) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); absl::string_view data = visitor.data(); EXPECT_THAT(data, testing::StartsWith(spdy::kHttp2ConnectionHeaderPrefix)); data.remove_prefix(strlen(spdy::kHttp2ConnectionHeaderPrefix)); EXPECT_THAT(data, EqualsFrames({SpdyFrameType::SETTINGS})); visitor.Clear(); const std::string initial_frames = TestFrameSequence().ServerPreface().Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), static_cast<size_t>(initial_result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS})); visitor.Clear(); int stream_id = adapter->SubmitRequest(ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}), nullptr, true, nullptr); EXPECT_GT(stream_id, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS})); visitor.Clear(); adapter->SubmitRst(stream_id, Http2ErrorCode::CANCEL); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, stream_id, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, stream_id, _, 0x0, static_cast<int>(Http2ErrorCode::CANCEL))); EXPECT_CALL(visitor, OnCloseStream(stream_id, Http2ErrorCode::HTTP2_NO_ERROR)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::RST_STREAM})); visitor.Clear(); const std::string response_frames = TestFrameSequence() .Headers(stream_id, {{":status", "200"}, {"server", "my-fake-server"}, {"date", "Tue, 6 Apr 2021 12:54:01 GMT"}}, false) .Data(stream_id, "This is the response body.", true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(stream_id, _, HEADERS, 0x4)); EXPECT_CALL(visitor, OnFrameHeader(stream_id, _, DATA, END_STREAM_FLAG)); const int64_t response_result = adapter->ProcessBytes(response_frames); EXPECT_EQ(response_frames.size(), static_cast<size_t>(response_result)); EXPECT_FALSE(adapter->want_write()); } TEST_P(OgHttp2AdapterDataTest, ClientEncountersFlowControlBlock) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const std::string kBody = std::string(100 * 1024, 'a'); visitor.AppendPayloadForStream(1, kBody); visitor.SetEndData(1, false); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); const int32_t stream_id1 = adapter->SubmitRequest( headers1, GetParam() ? nullptr : std::move(body1), false, nullptr); ASSERT_GT(stream_id1, 0); const std::vector<Header> headers2 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}); visitor.AppendPayloadForStream(3, kBody); visitor.SetEndData(3, false); auto body2 = std::make_unique<VisitorDataSource>(visitor, 3); const int32_t stream_id2 = adapter->SubmitRequest( headers2, GetParam() ? nullptr : std::move(body2), false, nullptr); ASSERT_EQ(stream_id2, 3); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x4, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id2, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id2, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id1, _, 0x0, 0)).Times(4); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_EQ(0, adapter->GetSendWindowSize()); const std::string stream_frames = TestFrameSequence() .ServerPreface() .WindowUpdate(0, 80000) .WindowUpdate(stream_id1, 20000) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(0, 80000)); EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(1, 20000)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id2, _, 0x0, 0)) .Times(testing::AtLeast(1)); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id1, _, 0x0, 0)) .Times(testing::AtLeast(1)); EXPECT_TRUE(adapter->want_write()); result = adapter->Send(); EXPECT_EQ(0, result); } TEST_P(OgHttp2AdapterDataTest, ClientSendsTrailersAfterFlowControlBlock) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); visitor.AppendPayloadForStream(1, "Really small body."); visitor.SetEndData(1, false); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); const int32_t stream_id1 = adapter->SubmitRequest( headers1, GetParam() ? nullptr : std::move(body1), false, nullptr); ASSERT_GT(stream_id1, 0); const std::vector<Header> headers2 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}); const std::string kBody = std::string(100 * 1024, 'a'); visitor.AppendPayloadForStream(3, kBody); visitor.SetEndData(3, false); auto body2 = std::make_unique<VisitorDataSource>(visitor, 3); const int32_t stream_id2 = adapter->SubmitRequest( headers2, GetParam() ? nullptr : std::move(body2), false, nullptr); ASSERT_GT(stream_id2, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, 0x4, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id2, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id2, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id1, _, 0x0, 0)).Times(1); EXPECT_CALL(visitor, OnFrameSent(DATA, stream_id2, _, 0x0, 0)).Times(4); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_FALSE(adapter->want_write()); EXPECT_EQ(0, adapter->GetSendWindowSize()); const std::vector<Header> trailers1 = ToHeaders({{"extra-info", "Trailers are weird but good?"}}); adapter->SubmitTrailer(stream_id1, trailers1); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); result = adapter->Send(); EXPECT_EQ(0, result); } TEST(OgHttp2AdapterTest, ClientQueuesRequests) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); adapter->Send(); const std::string initial_frames = TestFrameSequence() .ServerPreface({{MAX_CONCURRENT_STREAMS, 2}}) .SettingsAck() .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0x0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSetting(Http2Setting{ Http2KnownSettingsId::MAX_CONCURRENT_STREAMS, 2u})); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, ACK_FLAG)); EXPECT_CALL(visitor, OnSettingsAck()); adapter->ProcessBytes(initial_frames); const std::vector<Header> headers = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/example/request"}}); std::vector<int32_t> stream_ids; int32_t stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr); stream_ids.push_back(stream_id); stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr); stream_ids.push_back(stream_id); stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr); stream_ids.push_back(stream_id); stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr); stream_ids.push_back(stream_id); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_ids[0], _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_ids[0], _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_ids[1], _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_ids[1], _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); adapter->Send(); const std::string update_streams = TestFrameSequence().Settings({{MAX_CONCURRENT_STREAMS, 5}}).Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0x0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSetting(Http2Setting{ Http2KnownSettingsId::MAX_CONCURRENT_STREAMS, 5u})); EXPECT_CALL(visitor, OnSettingsEnd()); adapter->ProcessBytes(update_streams); stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr); stream_ids.push_back(stream_id); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_ids[2], _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_ids[2], _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_ids[3], _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_ids[3], _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_ids[4], _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_ids[4], _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); adapter->Send(); } TEST(OgHttp2AdapterTest, ClientAcceptsHeadResponseWithContentLength) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::vector<Header> headers = ToHeaders({{":method", "HEAD"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/"}}); const int32_t stream_id = adapter->SubmitRequest(headers, nullptr, true, nullptr); testing::InSequence s; EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, stream_id, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, stream_id, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); adapter->Send(); const std::string initial_frames = TestFrameSequence() .ServerPreface() .SettingsAck() .Headers(stream_id, {{":status", "200"}, {"content-length", "101"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, _, SETTINGS, 0x0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, ACK_FLAG)); EXPECT_CALL(visitor, OnSettingsAck()); EXPECT_CALL(visitor, OnFrameHeader(stream_id, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(stream_id)); EXPECT_CALL(visitor, OnHeaderForStream).Times(2); EXPECT_CALL(visitor, OnEndHeadersForStream(stream_id)); EXPECT_CALL(visitor, OnEndStream(stream_id)); EXPECT_CALL(visitor, OnCloseStream(stream_id, Http2ErrorCode::HTTP2_NO_ERROR)); adapter->ProcessBytes(initial_frames); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); adapter->Send(); } TEST(OgHttp2AdapterTest, GetSendWindowSize) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const int peer_window = adapter->GetSendWindowSize(); EXPECT_EQ(peer_window, kInitialFlowControlWindowSize); } TEST(OgHttp2AdapterTest, WindowUpdateZeroDelta) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string data_chunk(kDefaultFramePayloadSizeLimit, 'a'); const std::string request = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/"}}, false) .WindowUpdate(1, 0) .Data(1, "Subsequent frames on stream 1 are not delivered.") .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0)); adapter->ProcessBytes(request); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, _)); adapter->Send(); const std::string window_update = TestFrameSequence().WindowUpdate(0, 0).Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kFlowControlError)); adapter->ProcessBytes(window_update); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); adapter->Send(); } TEST(OgHttp2AdapterTest, WindowUpdateCausesWindowOverflow) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string data_chunk(kDefaultFramePayloadSizeLimit, 'a'); const std::string request = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/"}}, false) .WindowUpdate(1, std::numeric_limits<int>::max()) .Data(1, "Subsequent frames on stream 1 are not delivered.") .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0)); adapter->ProcessBytes(request); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0)); EXPECT_CALL( visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, static_cast<int>(Http2ErrorCode::FLOW_CONTROL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, _)); adapter->Send(); const std::string window_update = TestFrameSequence() .WindowUpdate(0, std::numeric_limits<int>::max()) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kFlowControlError)); adapter->ProcessBytes(window_update); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL( visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::FLOW_CONTROL_ERROR))); adapter->Send(); } TEST(OgHttp2AdapterTest, WindowUpdateRaisesFlowControlWindowLimit) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string data_chunk(kDefaultFramePayloadSizeLimit, 'a'); const std::string request = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/"}}, false) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); adapter->ProcessBytes(request); adapter->SubmitWindowUpdate(0, 2 * kDefaultFramePayloadSizeLimit); adapter->SubmitWindowUpdate(1, 2 * kDefaultFramePayloadSizeLimit); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 0, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 0, 4, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 1, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 1, 4, 0x0, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_EQ(kInitialFlowControlWindowSize + 2 * kDefaultFramePayloadSizeLimit, adapter->GetReceiveWindowSize()); EXPECT_EQ(kInitialFlowControlWindowSize + 2 * kDefaultFramePayloadSizeLimit, adapter->GetStreamReceiveWindowSize(1)); const std::string request_body = TestFrameSequence() .Data(1, data_chunk) .Data(1, data_chunk) .Data(1, data_chunk) .Data(1, data_chunk) .Data(1, data_chunk) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0)).Times(5); EXPECT_CALL(visitor, OnBeginDataForStream(1, _)).Times(5); EXPECT_CALL(visitor, OnDataForStream(1, _)).Times(5); adapter->ProcessBytes(request_body); EXPECT_EQ(kInitialFlowControlWindowSize - 3 * kDefaultFramePayloadSizeLimit, adapter->GetReceiveWindowSize()); EXPECT_EQ(kInitialFlowControlWindowSize - 3 * kDefaultFramePayloadSizeLimit, adapter->GetStreamReceiveWindowSize(1)); adapter->MarkDataConsumedForStream(1, 4 * kDefaultFramePayloadSizeLimit); EXPECT_GT(adapter->GetReceiveWindowSize(), kInitialFlowControlWindowSize); EXPECT_GT(adapter->GetStreamReceiveWindowSize(1), kInitialFlowControlWindowSize); } TEST(OgHttp2AdapterTest, MarkDataConsumedForNonexistentStream) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .Data(1, "Some data on stream 1") .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, _)); EXPECT_CALL(visitor, OnDataForStream(1, _)); adapter->ProcessBytes(frames); adapter->MarkDataConsumedForStream(3, 11); } TEST(OgHttp2AdapterTest, TestSerialize) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); EXPECT_TRUE(adapter->want_read()); EXPECT_FALSE(adapter->want_write()); adapter->SubmitSettings( {{HEADER_TABLE_SIZE, 128}, {MAX_FRAME_SIZE, 128 << 10}}); EXPECT_TRUE(adapter->want_write()); const Http2StreamId accepted_stream = 3; const Http2StreamId rejected_stream = 7; adapter->SubmitPriorityForStream(accepted_stream, 1, 255, true); adapter->SubmitRst(rejected_stream, Http2ErrorCode::CANCEL); adapter->SubmitPing(42); adapter->SubmitGoAway(13, Http2ErrorCode::HTTP2_NO_ERROR, ""); adapter->SubmitWindowUpdate(accepted_stream, 127); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(PRIORITY, accepted_stream, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(PRIORITY, accepted_stream, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, rejected_stream, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, rejected_stream, _, 0x0, 0x8)); EXPECT_CALL(visitor, OnBeforeFrameSent(PING, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(PING, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, accepted_stream, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, accepted_stream, _, 0x0, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT( visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::PRIORITY, SpdyFrameType::RST_STREAM, SpdyFrameType::PING, SpdyFrameType::GOAWAY, SpdyFrameType::WINDOW_UPDATE})); EXPECT_FALSE(adapter->want_write()); } TEST(OgHttp2AdapterTest, TestPartialSerialize) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); EXPECT_FALSE(adapter->want_write()); adapter->SubmitSettings( {{HEADER_TABLE_SIZE, 128}, {MAX_FRAME_SIZE, 128 << 10}}); adapter->SubmitGoAway(13, Http2ErrorCode::HTTP2_NO_ERROR, "And don't come back!"); adapter->SubmitPing(42); EXPECT_TRUE(adapter->want_write()); visitor.set_send_limit(20); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(PING, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(PING, 0, _, 0x0, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_FALSE(adapter->want_write()); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY, SpdyFrameType::PING})); } TEST(OgHttp2AdapterTest, TestStreamInitialWindowSizeUpdates) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); adapter->SubmitSettings({{INITIAL_WINDOW_SIZE, 80000}}); EXPECT_TRUE(adapter->want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0x4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); const int64_t read_result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(read_result), frames.size()); EXPECT_EQ(adapter->GetStreamReceiveWindowSize(1), 65535); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_EQ(adapter->GetStreamReceiveWindowSize(1), 65535); const std::string ack = TestFrameSequence().SettingsAck().Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, ACK_FLAG)); EXPECT_CALL(visitor, OnSettingsAck()); adapter->ProcessBytes(ack); EXPECT_EQ(adapter->GetStreamReceiveWindowSize(1), 80000); adapter->SubmitSettings({{INITIAL_WINDOW_SIZE, 90000}}); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_EQ(adapter->GetStreamReceiveWindowSize(1), 80000); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, ACK_FLAG)); EXPECT_CALL(visitor, OnSettingsAck()); adapter->ProcessBytes(ack); EXPECT_EQ(adapter->GetStreamReceiveWindowSize(1), 90000); } TEST(OgHttp2AdapterTest, ConnectionErrorOnControlFrameSent) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence().ClientPreface().Ping(42).Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, _, PING, 0)); EXPECT_CALL(visitor, OnPing(42, false)); const int64_t read_result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(read_result), frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)) .WillOnce(testing::Return(-902)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kSendError)); int send_result = adapter->Send(); EXPECT_LT(send_result, 0); EXPECT_FALSE(adapter->want_write()); send_result = adapter->Send(); EXPECT_LT(send_result, 0); } TEST_P(OgHttp2AdapterDataTest, ConnectionErrorOnDataFrameSent) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t read_result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(read_result), frames.size()); visitor.AppendPayloadForStream( 1, "Here is some data, which will lead to a fatal error"); auto body = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse(1, ToHeaders({{":status", "200"}}), GetParam() ? nullptr : std::move(body), false); ASSERT_EQ(0, submit_result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0)) .WillOnce(testing::Return(-902)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kSendError)); int send_result = adapter->Send(); EXPECT_LT(send_result, 0); visitor.AppendPayloadForStream( 1, "After the fatal error, data will be sent no more"); EXPECT_FALSE(adapter->want_write()); send_result = adapter->Send(); EXPECT_LT(send_result, 0); } TEST(OgHttp2AdapterTest, ClientSendsContinuation) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); EXPECT_FALSE(adapter->want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 1)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnFrameHeader(1, _, CONTINUATION, 4)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); } TEST_P(OgHttp2AdapterDataTest, RepeatedHeaderNames) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); EXPECT_FALSE(adapter->want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"accept", "text/plain"}, {"accept", "text/html"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnHeaderForStream(1, "accept", "text/plain")); EXPECT_CALL(visitor, OnHeaderForStream(1, "accept", "text/html")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); const std::vector<Header> headers1 = ToHeaders( {{":status", "200"}, {"content-length", "10"}, {"content-length", "10"}}); visitor.AppendPayloadForStream(1, "perfection"); visitor.SetEndData(1, true); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse( 1, headers1, GetParam() ? nullptr : std::move(body1), false); ASSERT_EQ(0, submit_result); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, 10, END_STREAM, 0)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS, SpdyFrameType::DATA})); } TEST_P(OgHttp2AdapterDataTest, ServerRespondsToRequestWithTrailers) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); EXPECT_FALSE(adapter->want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}) .Data(1, "Example data, woohoo.") .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, _)); EXPECT_CALL(visitor, OnDataForStream(1, _)); int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); const std::vector<Header> headers1 = ToHeaders({{":status", "200"}}); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse( 1, headers1, GetParam() ? nullptr : std::move(body1), false); ASSERT_EQ(0, submit_result); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); visitor.Clear(); const std::string more_frames = TestFrameSequence() .Headers(1, {{"extra-info", "Trailers are weird but good?"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, "extra-info", "Trailers are weird but good?")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); result = adapter->ProcessBytes(more_frames); EXPECT_EQ(more_frames.size(), static_cast<size_t>(result)); visitor.SetEndData(1, true); EXPECT_EQ(true, adapter->ResumeStream(1)); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, 0, END_STREAM, 0)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::DATA})); } TEST(OgHttp2AdapterTest, ServerReceivesMoreHeaderBytesThanConfigured) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; options.max_header_list_bytes = 42; auto adapter = OgHttp2Adapter::Create(visitor, options); EXPECT_FALSE(adapter->want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"from-douglas-de-fermat", "I have discovered a truly marvelous answer to the life, " "the universe, and everything that the header setting is " "too narrow to contain."}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kParseError)); int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(result), frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::COMPRESSION_ERROR))); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY})); } TEST(OgHttp2AdapterTest, ServerVisitorRejectsHeaders) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); EXPECT_FALSE(adapter->want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"header1", "ok"}, {"header2", "rejected"}, {"header3", "not processed"}, {"header4", "not processed"}, {"header5", "not processed"}, {"header6", "not processed"}, {"header7", "not processed"}, {"header8", "not processed"}}, false, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 0x0)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(5); EXPECT_CALL(visitor, OnHeaderForStream(1, "header2", _)) .WillOnce(testing::Return(Http2VisitorInterface::HEADER_RST_STREAM)); int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(result), frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x1)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x1, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, static_cast<int>(Http2ErrorCode::INTERNAL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST_P(OgHttp2AdapterDataTest, ServerSubmitsResponseWithDataSourceError) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); EXPECT_FALSE(adapter->want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); visitor.SimulateError(1); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse( 1, ToHeaders({{":status", "200"}, {"x-comment", "Sure, sounds good."}}), GetParam() ? nullptr : std::move(body1), false); EXPECT_EQ(submit_result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::INTERNAL_ERROR)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); visitor.Clear(); EXPECT_FALSE(adapter->want_write()); int trailer_result = adapter->SubmitTrailer(1, ToHeaders({{":final-status", "a-ok"}})); ASSERT_LT(trailer_result, 0); EXPECT_FALSE(adapter->want_write()); } TEST(OgHttp2AdapterTest, CompleteRequestWithServerResponse) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); EXPECT_FALSE(adapter->want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .Data(1, "This is the response body.", true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 1)); EXPECT_CALL(visitor, OnBeginDataForStream(1, _)); EXPECT_CALL(visitor, OnDataForStream(1, _)); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); int submit_result = adapter->SubmitResponse( 1, ToHeaders({{":status", "200"}}), nullptr, true); EXPECT_EQ(submit_result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); EXPECT_FALSE(adapter->want_write()); } TEST(OgHttp2AdapterTest, IncompleteRequestWithServerResponse) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); EXPECT_FALSE(adapter->want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); int submit_result = adapter->SubmitResponse( 1, ToHeaders({{":status", "200"}}), nullptr, true); EXPECT_EQ(submit_result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); EXPECT_FALSE(adapter->want_write()); } TEST(OgHttp2AdapterTest, IncompleteRequestWithServerResponseRstStreamEnabled) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; options.rst_stream_no_error_when_incomplete = true; auto adapter = OgHttp2Adapter::Create(visitor, options); EXPECT_FALSE(adapter->want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); int submit_result = adapter->SubmitResponse( 1, ToHeaders({{":status", "200"}}), nullptr, true); EXPECT_EQ(submit_result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, 4, 0x0, 0)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT( visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS, SpdyFrameType::RST_STREAM})); EXPECT_FALSE(adapter->want_write()); } TEST(OgHttp2AdapterTest, ServerHandlesMultipleContentLength) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); EXPECT_FALSE(adapter->want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/1"}, {"content-length", "7"}, {"content-length", "7"}}, false) .Headers(3, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/3"}, {"content-length", "11"}, {"content-length", "13"}}, false) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/1")); EXPECT_CALL(visitor, OnHeaderForStream(1, "content-length", "7")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(3, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(3, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(3, ":path", "/3")); EXPECT_CALL(visitor, OnHeaderForStream(3, "content-length", "11")); EXPECT_CALL( visitor, OnInvalidFrame(3, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); } TEST_P(OgHttp2AdapterDataTest, ServerSendsInvalidTrailers) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); EXPECT_FALSE(adapter->want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); const absl::string_view kBody = "This is an example response body."; visitor.AppendPayloadForStream(1, kBody); visitor.SetEndData(1, false); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse( 1, ToHeaders({{":status", "200"}, {"x-comment", "Sure, sounds good."}}), GetParam() ? nullptr : std::move(body1), false); EXPECT_EQ(submit_result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS, SpdyFrameType::DATA})); EXPECT_THAT(visitor.data(), testing::HasSubstr(kBody)); visitor.Clear(); EXPECT_FALSE(adapter->want_write()); int trailer_result = adapter->SubmitTrailer(1, ToHeaders({{":final-status", "a-ok"}})); ASSERT_EQ(trailer_result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS})); } TEST(OgHttp2AdapterTest, ServerHandlesDataWithPadding) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .Data(1, "This is the request body.", true, 39) .Headers(3, {{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, 25 + 39, DATA, 0x9)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 25 + 39)); EXPECT_CALL(visitor, OnDataPaddingLength(1, 39)); EXPECT_CALL(visitor, OnDataForStream(1, "This is the request body.")); EXPECT_CALL(visitor, OnEndStream(1)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(3)); EXPECT_CALL(visitor, OnEndStream(3)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<int64_t>(frames.size()), result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS})); } TEST(OgHttp2AdapterTest, ServerHandlesHostHeader) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":path", "/this/is/request/one"}, {"host", "example.com"}}, true) .Headers(3, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"host", "example.com"}}, true) .Headers(5, {{":method", "POST"}, {":scheme", "https"}, {":authority", "foo.com"}, {":path", "/this/is/request/one"}, {"host", "bar.com"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(5); EXPECT_CALL(visitor, OnEndHeadersForStream(3)); EXPECT_CALL(visitor, OnEndStream(3)); EXPECT_CALL(visitor, OnFrameHeader(5, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(5)); EXPECT_CALL(visitor, OnHeaderForStream(5, _, _)).Times(4); EXPECT_CALL( visitor, OnInvalidFrame(5, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 5, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 5, 4, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(5, Http2ErrorCode::HTTP2_NO_ERROR)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); visitor.Clear(); } TEST(OgHttp2AdapterTest, ServerHandlesHostHeaderWithLaxValidation) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; options.allow_different_host_and_authority = true; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":path", "/this/is/request/one"}, {"host", "example.com"}}, true) .Headers(3, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"host", "example.com"}}, true) .Headers(5, {{":method", "POST"}, {":scheme", "https"}, {":authority", "foo.com"}, {":path", "/this/is/request/one"}, {"host", "bar.com"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(5); EXPECT_CALL(visitor, OnEndHeadersForStream(3)); EXPECT_CALL(visitor, OnEndStream(3)); EXPECT_CALL(visitor, OnFrameHeader(5, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(5)); EXPECT_CALL(visitor, OnHeaderForStream(5, _, _)).Times(5); EXPECT_CALL(visitor, OnEndHeadersForStream(5)); EXPECT_CALL(visitor, OnEndStream(5)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); visitor.Clear(); } TEST_P(OgHttp2AdapterDataTest, ServerSubmitsTrailersWhileDataDeferred) { OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; for (const bool add_more_body_data : {true, false}) { TestVisitor visitor; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .WindowUpdate(1, 2000) .Data(1, "This is the request body.") .WindowUpdate(0, 2000) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(1, 2000)); EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, _)); EXPECT_CALL(visitor, OnDataForStream(1, "This is the request body.")); EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(0, 2000)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); visitor.Clear(); const absl::string_view kBody = "This is an example response body."; visitor.AppendPayloadForStream(1, kBody); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse( 1, ToHeaders({{":status", "200"}, {"x-comment", "Sure, sounds good."}}), GetParam() ? nullptr : std::move(body1), false); EXPECT_EQ(submit_result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0)); send_result = adapter->Send(); EXPECT_EQ(0, send_result); visitor.Clear(); EXPECT_FALSE(adapter->want_write()); if (add_more_body_data) { visitor.AppendPayloadForStream(1, " More body! This is ignored."); } int trailer_result = adapter->SubmitTrailer(1, ToHeaders({{"final-status", "a-ok"}})); ASSERT_EQ(trailer_result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS})); EXPECT_FALSE(adapter->want_write()); } } TEST_P(OgHttp2AdapterDataTest, ServerSubmitsTrailersWithFlowControlBlockage) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .WindowUpdate(0, 2000) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(0, 2000)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); visitor.Clear(); EXPECT_EQ(kInitialFlowControlWindowSize, adapter->GetStreamSendWindowSize(1)); const std::string kBody(60000, 'a'); visitor.AppendPayloadForStream(1, kBody); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse( 1, ToHeaders({{":status", "200"}, {"x-comment", "Sure, sounds good."}}), GetParam() ? nullptr : std::move(body1), false); EXPECT_EQ(submit_result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0)).Times(4); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::DATA, SpdyFrameType::DATA, SpdyFrameType::DATA, SpdyFrameType::DATA})); visitor.Clear(); EXPECT_FALSE(adapter->want_write()); visitor.AppendPayloadForStream(1, std::string(6000, 'b')); EXPECT_LT(adapter->GetStreamSendWindowSize(1), 6000); EXPECT_GT(adapter->GetSendWindowSize(), 6000); adapter->ResumeStream(1); int trailer_result = adapter->SubmitTrailer(1, ToHeaders({{"final-status", "a-ok"}})); ASSERT_EQ(trailer_result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0)); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::DATA})); visitor.Clear(); EXPECT_EQ(adapter->GetStreamSendWindowSize(1), 0); EXPECT_GT(adapter->GetSendWindowSize(), 0); EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(1, 2000)); adapter->ProcessBytes(TestFrameSequence().WindowUpdate(1, 2000).Serialize()); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::DATA, SpdyFrameType::HEADERS})); EXPECT_FALSE(adapter->want_write()); } TEST_P(OgHttp2AdapterDataTest, ServerSubmitsTrailersWithDataEndStream) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}) .Data(1, "Example data, woohoo.") .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, _)); EXPECT_CALL(visitor, OnDataForStream(1, _)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(result), frames.size()); const absl::string_view kBody = "This is an example response body."; visitor.AppendPayloadForStream(1, kBody); visitor.SetEndData(1, true); auto body = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse(1, ToHeaders({{":status", "200"}}), GetParam() ? nullptr : std::move(body), false); ASSERT_EQ(submit_result, 0); const std::vector<Header> trailers = ToHeaders({{"extra-info", "Trailers are weird but good?"}}); submit_result = adapter->SubmitTrailer(1, trailers); ASSERT_EQ(submit_result, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, END_HEADERS_FLAG, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, END_STREAM_FLAG, 0)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::INTERNAL_ERROR)); const int send_result = adapter->Send(); EXPECT_EQ(send_result, 0); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS, SpdyFrameType::DATA})); } TEST_P(OgHttp2AdapterDataTest, ServerSubmitsTrailersWithDataEndStreamAndDeferral) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}) .Data(1, "Example data, woohoo.") .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, _)); EXPECT_CALL(visitor, OnDataForStream(1, _)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(result), frames.size()); const absl::string_view kBody = "This is an example response body."; visitor.AppendPayloadForStream(1, kBody); auto body = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse(1, ToHeaders({{":status", "200"}}), GetParam() ? nullptr : std::move(body), false); ASSERT_EQ(submit_result, 0); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, END_HEADERS_FLAG, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0)); int send_result = adapter->Send(); EXPECT_EQ(send_result, 0); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS, SpdyFrameType::DATA})); visitor.Clear(); const std::vector<Header> trailers = ToHeaders({{"extra-info", "Trailers are weird but good?"}}); submit_result = adapter->SubmitTrailer(1, trailers); ASSERT_EQ(submit_result, 0); visitor.AppendPayloadForStream(1, kBody); visitor.SetEndData(1, true); adapter->ResumeStream(1); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, END_STREAM_FLAG, 0)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::INTERNAL_ERROR)); send_result = adapter->Send(); EXPECT_EQ(send_result, 0); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::DATA})); } TEST(OgHttp2AdapterTest, ClientDisobeysConnectionFlowControl) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"accept", "some bogus value!"}}, false) .Data(1, std::string(16384, 'a')) .Data(1, std::string(16384, 'a')) .Data(1, std::string(16384, 'a')) .Data(1, std::string(16384, 'a')) .Data(1, std::string(4464, 'a')) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream).Times(5); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, 16384, DATA, 0x0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 16384)); EXPECT_CALL(visitor, OnDataForStream(1, _)); EXPECT_CALL(visitor, OnFrameHeader(1, 16384, DATA, 0x0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 16384)); EXPECT_CALL(visitor, OnDataForStream(1, _)); EXPECT_CALL(visitor, OnFrameHeader(1, 16384, DATA, 0x0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 16384)); EXPECT_CALL(visitor, OnDataForStream(1, _)); EXPECT_CALL(visitor, OnFrameHeader(1, 16384, DATA, 0x0)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kFlowControlError)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL( visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::FLOW_CONTROL_ERROR))); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY})); } TEST(OgHttp2AdapterTest, ClientDisobeysConnectionFlowControlWithOneDataFrame) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const uint32_t window_overflow_bytes = kInitialFlowControlWindowSize + 1; adapter->SubmitSettings({{MAX_FRAME_SIZE, window_overflow_bytes}}); const std::string initial_frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); int64_t process_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), static_cast<size_t>(process_result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS})); visitor.Clear(); const std::string overflow_frames = TestFrameSequence() .SettingsAck() .Data(1, std::string(window_overflow_bytes, 'a')) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, ACK_FLAG)); EXPECT_CALL(visitor, OnSettingsAck()); EXPECT_CALL(visitor, OnFrameHeader(1, window_overflow_bytes, DATA, 0x0)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kFlowControlError)); process_result = adapter->ProcessBytes(overflow_frames); EXPECT_EQ(overflow_frames.size(), static_cast<size_t>(process_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL( visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::FLOW_CONTROL_ERROR))); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY})); } TEST(OgHttp2AdapterTest, ClientDisobeysConnectionFlowControlAcrossReads) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const uint32_t window_overflow_bytes = kInitialFlowControlWindowSize + 1; adapter->SubmitSettings({{MAX_FRAME_SIZE, window_overflow_bytes}}); const std::string initial_frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); int64_t process_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(initial_frames.size(), static_cast<size_t>(process_result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS})); visitor.Clear(); const std::string overflow_frames = TestFrameSequence() .SettingsAck() .Data(1, std::string(window_overflow_bytes, 'a')) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, ACK_FLAG)); EXPECT_CALL(visitor, OnSettingsAck()); EXPECT_CALL(visitor, OnFrameHeader(1, window_overflow_bytes, DATA, 0x0)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kFlowControlError)); const size_t chunk_length = 16384; ASSERT_GE(overflow_frames.size(), chunk_length); process_result = adapter->ProcessBytes(overflow_frames.substr(0, chunk_length)); EXPECT_EQ(chunk_length, static_cast<size_t>(process_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL( visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::FLOW_CONTROL_ERROR))); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY})); } TEST(OgHttp2AdapterTest, ClientDisobeysStreamFlowControl) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"accept", "some bogus value!"}}, false) .Serialize(); const std::string more_frames = TestFrameSequence() .Data(1, std::string(16384, 'a')) .Data(1, std::string(16384, 'a')) .Data(1, std::string(16384, 'a')) .Data(1, std::string(16384, 'a')) .Data(1, std::string(4464, 'a')) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream).Times(5); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); adapter->SubmitWindowUpdate(0, 20000); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 0, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 0, 4, 0x0, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::WINDOW_UPDATE})); visitor.Clear(); EXPECT_CALL(visitor, OnFrameHeader(1, 16384, DATA, 0x0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 16384)); EXPECT_CALL(visitor, OnDataForStream(1, _)); EXPECT_CALL(visitor, OnFrameHeader(1, 16384, DATA, 0x0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 16384)); EXPECT_CALL(visitor, OnDataForStream(1, _)); EXPECT_CALL(visitor, OnFrameHeader(1, 16384, DATA, 0x0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 16384)); EXPECT_CALL(visitor, OnDataForStream(1, _)); EXPECT_CALL(visitor, OnFrameHeader(1, 16384, DATA, 0x0)); result = adapter->ProcessBytes(more_frames); EXPECT_EQ(more_frames.size(), static_cast<size_t>(result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, 4, 0x0)); EXPECT_CALL( visitor, OnFrameSent(RST_STREAM, 1, 4, 0x0, static_cast<int>(Http2ErrorCode::FLOW_CONTROL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::RST_STREAM})); } TEST(OgHttp2AdapterTest, ServerErrorWhileHandlingHeaders) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"accept", "some bogus value!"}}, false) .WindowUpdate(1, 2000) .Data(1, "This is the request body.") .WindowUpdate(0, 2000) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnHeaderForStream(1, "accept", "some bogus value!")) .WillOnce(testing::Return(Http2VisitorInterface::HEADER_RST_STREAM)); EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(0, 2000)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, 4, 0x0, static_cast<int>(Http2ErrorCode::INTERNAL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST(OgHttp2AdapterTest, ServerErrorWhileHandlingHeadersDropsFrames) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"accept", "some bogus value!"}}, false) .WindowUpdate(1, 2000) .Data(1, "This is the request body.") .Metadata(1, "This is the request metadata.") .RstStream(1, Http2ErrorCode::CANCEL) .WindowUpdate(0, 2000) .Headers(3, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}, false) .Metadata(3, "This is the request metadata.", true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnHeaderForStream(1, "accept", "some bogus value!")) .WillOnce(testing::Return(Http2VisitorInterface::HEADER_RST_STREAM)); EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(0, 2000)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(3)); EXPECT_CALL(visitor, OnFrameHeader(3, _, kMetadataFrameType, 0)); EXPECT_CALL(visitor, OnBeginMetadataForStream(3, _)); EXPECT_CALL(visitor, OnMetadataForStream(3, "This is the re")) .WillOnce(testing::DoAll(testing::InvokeWithoutArgs([&adapter]() { adapter->SubmitRst( 3, Http2ErrorCode::REFUSED_STREAM); }), testing::Return(true))); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, 4, 0x0, static_cast<int>(Http2ErrorCode::INTERNAL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 3, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 3, 4, 0x0, static_cast<int>(Http2ErrorCode::REFUSED_STREAM))); EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::HTTP2_NO_ERROR)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT( visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM, SpdyFrameType::RST_STREAM})); } TEST(OgHttp2AdapterTest, ServerConnectionErrorWhileHandlingHeaders) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"Accept", "uppercase, oh boy!"}}, false) .WindowUpdate(1, 2000) .Data(1, "This is the request body.") .WindowUpdate(0, 2000) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL( visitor, OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader)) .WillOnce(testing::Return(false)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kHeaderError)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_LT(result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, 4, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM, SpdyFrameType::GOAWAY})); } TEST(OgHttp2AdapterTest, ServerErrorAfterHandlingHeaders) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .WindowUpdate(1, 2000) .Data(1, "This is the request body.") .WindowUpdate(0, 2000) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)) .WillOnce(testing::Return(false)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kParseError)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_LT(result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::INTERNAL_ERROR))); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY})); } TEST(OgHttp2AdapterTest, ServerRejectsFrameHeader) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface() .Ping(64) .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .WindowUpdate(1, 2000) .Data(1, "This is the request body.") .WindowUpdate(0, 2000) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, 8, PING, 0)) .WillOnce(testing::Return(false)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kParseError)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_LT(result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::INTERNAL_ERROR))); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY})); } TEST(OgHttp2AdapterTest, ServerRejectsBeginningOfData) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .Data(1, "This is the request body.") .Headers(3, {{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}, true) .RstStream(3, Http2ErrorCode::CANCEL) .Ping(47) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, 25, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 25)) .WillOnce(testing::Return(false)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kParseError)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_LT(result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::INTERNAL_ERROR))); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY})); } TEST(OgHttp2AdapterTest, ServerReceivesTooLargeHeader) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; options.max_header_list_bytes = 64 * 1024; options.max_header_field_size = 64 * 1024; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string too_large_value = std::string(80 * 1024, 'q'); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"x-toobig", too_large_value}}, true) .Headers(3, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, END_STREAM_FLAG)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnFrameHeader(1, _, CONTINUATION, 0)).Times(3); EXPECT_CALL(visitor, OnFrameHeader(1, _, CONTINUATION, END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(3)); EXPECT_CALL(visitor, OnEndStream(3)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<int64_t>(frames.size()), result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, 4, 0x0, static_cast<int>(Http2ErrorCode::INTERNAL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST(OgHttp2AdapterTest, ServerReceivesInvalidAuthority) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "ex|ample.com"}, {":path", "/this/is/request/one"}}, false) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL( visitor, OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<int64_t>(frames.size()), result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0x0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0x0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, 4, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST(OgHttpAdapterTest, ServerReceivesGoAway) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true) .GoAway(0, Http2ErrorCode::HTTP2_NO_ERROR, "") .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); EXPECT_CALL(visitor, OnFrameHeader(0, _, GOAWAY, 0x0)); EXPECT_CALL(visitor, OnGoAway(0, Http2ErrorCode::HTTP2_NO_ERROR, "")); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<int64_t>(frames.size()), result); const int submit_result = adapter->SubmitResponse(1, ToHeaders({{":status", "200"}}), nullptr, true); ASSERT_EQ(0, submit_result); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0x0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0x0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::HEADERS})); } TEST_P(OgHttp2AdapterDataTest, ServerSubmitResponse) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); EXPECT_FALSE(adapter->want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true) .Serialize(); testing::InSequence s; const char* kSentinel1 = "arbitrary pointer 1"; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)) .WillOnce(testing::InvokeWithoutArgs([&adapter, kSentinel1]() { adapter->SetStreamUserData(1, const_cast<char*>(kSentinel1)); return true; })); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), result); EXPECT_EQ(1, adapter->GetHighestReceivedStreamId()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS})); visitor.Clear(); EXPECT_EQ(0, adapter->GetHpackEncoderDynamicTableSize()); EXPECT_FALSE(adapter->want_write()); const absl::string_view kBody = "This is an example response body."; visitor.AppendPayloadForStream(1, kBody); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse( 1, ToHeaders({{":status", "404"}, {"x-comment", "I have no idea what you're talking about."}}), GetParam() ? nullptr : std::move(body1), false); EXPECT_EQ(submit_result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_EQ(kSentinel1, adapter->GetStreamUserData(1)); adapter->SetStreamUserData(1, nullptr); EXPECT_EQ(nullptr, adapter->GetStreamUserData(1)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x4)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, 0x4, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0)); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::HEADERS, SpdyFrameType::DATA})); EXPECT_THAT(visitor.data(), testing::HasSubstr(kBody)); EXPECT_FALSE(adapter->want_write()); EXPECT_LT(adapter->GetStreamSendWindowSize(1), kInitialFlowControlWindowSize); EXPECT_GT(adapter->GetStreamSendWindowSize(1), 0); EXPECT_EQ(adapter->GetStreamSendWindowSize(3), -1); EXPECT_GT(adapter->GetHpackEncoderDynamicTableSize(), 0); } TEST_P(OgHttp2AdapterDataTest, ServerSubmitResponseWithResetFromClient) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); EXPECT_FALSE(adapter->want_write()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), result); EXPECT_EQ(1, adapter->GetHighestReceivedStreamId()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS})); visitor.Clear(); EXPECT_FALSE(adapter->want_write()); const absl::string_view kBody = "This is an example response body."; visitor.AppendPayloadForStream(1, kBody); auto body1 = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse( 1, ToHeaders({{":status", "404"}, {"x-comment", "I have no idea what you're talking about."}}), GetParam() ? nullptr : std::move(body1), false); EXPECT_EQ(submit_result, 0); EXPECT_TRUE(adapter->want_write()); const std::string reset = TestFrameSequence().RstStream(1, Http2ErrorCode::CANCEL).Serialize(); EXPECT_CALL(visitor, OnFrameHeader(1, 4, RST_STREAM, 0)); EXPECT_CALL(visitor, OnRstStream(1, Http2ErrorCode::CANCEL)); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::CANCEL)); const int64_t reset_result = adapter->ProcessBytes(reset); EXPECT_EQ(reset.size(), static_cast<size_t>(reset_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, _)).Times(0); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, _, _)).Times(0); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, _, _)).Times(0); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), testing::IsEmpty()); } TEST(OgHttp2AdapterTest, ServerRejectsStreamData) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .Data(1, "This is the request body.") .Headers(3, {{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}, true) .RstStream(3, Http2ErrorCode::CANCEL) .Ping(47) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, 25, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 25)); EXPECT_CALL(visitor, OnDataForStream(1, _)).WillOnce(testing::Return(false)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kParseError)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_LT(result, 0); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::INTERNAL_ERROR))); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY})); } using OgHttp2AdapterInteractionDataTest = OgHttp2AdapterDataTest; INSTANTIATE_TEST_SUITE_P(BothValues, OgHttp2AdapterInteractionDataTest, testing::Bool()); TEST_P(OgHttp2AdapterInteractionDataTest, ClientServerInteractionTest) { TestVisitor client_visitor; OgHttp2Adapter::Options client_options; client_options.perspective = Perspective::kClient; auto client_adapter = OgHttp2Adapter::Create(client_visitor, client_options); TestVisitor server_visitor; OgHttp2Adapter::Options server_options; server_options.perspective = Perspective::kServer; auto server_adapter = OgHttp2Adapter::Create(server_visitor, server_options); EXPECT_CALL(client_visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(client_visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0x0)); EXPECT_CALL(client_visitor, OnBeforeFrameSent(HEADERS, 1, _, 0x5)); EXPECT_CALL(client_visitor, OnFrameSent(HEADERS, 1, _, 0x5, 0x0)); EXPECT_CALL(client_visitor, OnReadyToSend(_)) .WillRepeatedly( testing::Invoke(server_adapter.get(), &OgHttp2Adapter::ProcessBytes)); EXPECT_CALL(server_visitor, OnReadyToSend(_)) .WillRepeatedly( testing::Invoke(client_adapter.get(), &OgHttp2Adapter::ProcessBytes)); EXPECT_CALL(server_visitor, OnEndHeadersForStream(_)) .WillRepeatedly([&server_adapter](Http2StreamId stream_id) { server_adapter->SubmitResponse( stream_id, ToHeaders({{":status", "200"}}), nullptr, true); server_adapter->Send(); return true; }); EXPECT_CALL(client_visitor, OnEndHeadersForStream(_)) .WillRepeatedly([&client_adapter, &client_visitor](Http2StreamId stream_id) { if (stream_id < 10) { const Http2StreamId new_stream_id = stream_id + 2; client_visitor.AppendPayloadForStream( new_stream_id, "This is an example request body."); client_visitor.SetEndData(new_stream_id, true); auto body = std::make_unique<VisitorDataSource>(client_visitor, new_stream_id); const int created_stream_id = client_adapter->SubmitRequest( ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", absl::StrCat("/this/is/request/", new_stream_id)}}), GetParam() ? nullptr : std::move(body), false, nullptr); EXPECT_EQ(new_stream_id, created_stream_id); client_adapter->Send(); } return true; }); int stream_id = client_adapter->SubmitRequest( ToHeaders({{":method", "POST"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}), nullptr, true, nullptr); EXPECT_EQ(stream_id, 1); client_adapter->Send(); } TEST(OgHttp2AdapterInteractionTest, ClientServerInteractionRepeatedHeaderNames) { TestVisitor client_visitor; OgHttp2Adapter::Options client_options; client_options.perspective = Perspective::kClient; auto client_adapter = OgHttp2Adapter::Create(client_visitor, client_options); const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"accept", "text/plain"}, {"accept", "text/html"}}); const int32_t stream_id1 = client_adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); EXPECT_CALL(client_visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(client_visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(client_visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(client_visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int send_result = client_adapter->Send(); EXPECT_EQ(0, send_result); TestVisitor server_visitor; OgHttp2Adapter::Options server_options; server_options.perspective = Perspective::kServer; auto server_adapter = OgHttp2Adapter::Create(server_visitor, server_options); testing::InSequence s; EXPECT_CALL(server_visitor, OnFrameHeader(0, _, SETTINGS, 0)); EXPECT_CALL(server_visitor, OnSettingsStart()); EXPECT_CALL(server_visitor, OnSetting).Times(testing::AnyNumber()); EXPECT_CALL(server_visitor, OnSettingsEnd()); EXPECT_CALL(server_visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(server_visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(server_visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(server_visitor, OnHeaderForStream(1, ":scheme", "http")); EXPECT_CALL(server_visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(server_visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(server_visitor, OnHeaderForStream(1, "accept", "text/plain")); EXPECT_CALL(server_visitor, OnHeaderForStream(1, "accept", "text/html")); EXPECT_CALL(server_visitor, OnEndHeadersForStream(1)); EXPECT_CALL(server_visitor, OnEndStream(1)); int64_t result = server_adapter->ProcessBytes(client_visitor.data()); EXPECT_EQ(client_visitor.data().size(), static_cast<size_t>(result)); } TEST(OgHttp2AdapterInteractionTest, ClientServerInteractionWithCookies) { TestVisitor client_visitor; OgHttp2Adapter::Options client_options; client_options.perspective = Perspective::kClient; auto client_adapter = OgHttp2Adapter::Create(client_visitor, client_options); const std::vector<Header> headers1 = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"cookie", "a; b=2; c"}, {"cookie", "d=e, f, g; h"}}); const int32_t stream_id1 = client_adapter->SubmitRequest(headers1, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); EXPECT_CALL(client_visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(client_visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(client_visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(client_visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); int send_result = client_adapter->Send(); EXPECT_EQ(0, send_result); TestVisitor server_visitor; OgHttp2Adapter::Options server_options; server_options.perspective = Perspective::kServer; auto server_adapter = OgHttp2Adapter::Create(server_visitor, server_options); testing::InSequence s; EXPECT_CALL(server_visitor, OnFrameHeader(0, _, SETTINGS, 0)); EXPECT_CALL(server_visitor, OnSettingsStart()); EXPECT_CALL(server_visitor, OnSetting).Times(testing::AnyNumber()); EXPECT_CALL(server_visitor, OnSettingsEnd()); EXPECT_CALL(server_visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(server_visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(server_visitor, OnHeaderForStream(1, ":method", "GET")); EXPECT_CALL(server_visitor, OnHeaderForStream(1, ":scheme", "http")); EXPECT_CALL(server_visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(server_visitor, OnHeaderForStream(1, ":path", "/this/is/request/one")); EXPECT_CALL(server_visitor, OnHeaderForStream(1, "cookie", "a; b=2; c; d=e, f, g; h")); EXPECT_CALL(server_visitor, OnEndHeadersForStream(1)); EXPECT_CALL(server_visitor, OnEndStream(1)); int64_t result = server_adapter->ProcessBytes(client_visitor.data()); EXPECT_EQ(client_visitor.data().size(), static_cast<size_t>(result)); } TEST(OgHttp2AdapterTest, ServerForbidsNewStreamBelowWatermark) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); EXPECT_EQ(0, adapter->GetHighestReceivedStreamId()); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(3, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .Data(3, "This is the request body.") .Headers(1, {{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(3, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(3, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(3, ":path", "/this/is/request/one")); EXPECT_CALL(visitor, OnEndHeadersForStream(3)); EXPECT_CALL(visitor, OnFrameHeader(3, 25, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(3, 25)); EXPECT_CALL(visitor, OnDataForStream(3, "This is the request body.")); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kInvalidNewStreamId)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(result), frames.size()); EXPECT_EQ(3, adapter->GetHighestReceivedStreamId()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY})); } TEST(OgHttp2AdapterTest, ServerForbidsWindowUpdateOnIdleStream) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); EXPECT_EQ(0, adapter->GetHighestReceivedStreamId()); const std::string frames = TestFrameSequence().ClientPreface().WindowUpdate(1, 42).Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kWrongFrameSequence)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(result), frames.size()); EXPECT_EQ(1, adapter->GetHighestReceivedStreamId()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY})); } TEST(OgHttp2AdapterTest, ServerForbidsDataOnIdleStream) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); EXPECT_EQ(0, adapter->GetHighestReceivedStreamId()); const std::string frames = TestFrameSequence() .ClientPreface() .Data(1, "Sorry, out of order") .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kWrongFrameSequence)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(result), frames.size()); EXPECT_EQ(1, adapter->GetHighestReceivedStreamId()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY})); } TEST(OgHttp2AdapterTest, ServerForbidsRstStreamOnIdleStream) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); EXPECT_EQ(0, adapter->GetHighestReceivedStreamId()); const std::string frames = TestFrameSequence() .ClientPreface() .RstStream(1, Http2ErrorCode::ENHANCE_YOUR_CALM) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, RST_STREAM, 0)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kWrongFrameSequence)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(result), frames.size()); EXPECT_EQ(1, adapter->GetHighestReceivedStreamId()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY})); } TEST(OgHttp2AdapterTest, ServerForbidsNewStreamAboveStreamLimit) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); adapter->SubmitSettings({{MAX_CONCURRENT_STREAMS, 1}}); const std::string initial_frames = TestFrameSequence().ClientPreface().Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(static_cast<size_t>(initial_result), initial_frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS})); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .SettingsAck() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true) .Headers(3, {{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, ACK_FLAG)); EXPECT_CALL(visitor, OnSettingsAck()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL( visitor, OnInvalidFrame(3, Http2VisitorInterface::InvalidFrameError::kProtocol)); EXPECT_CALL(visitor, OnConnectionError( ConnectionError::kExceededMaxConcurrentStreams)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(static_cast<size_t>(stream_result), stream_frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::GOAWAY})); } TEST(OgHttp2AdapterTest, ServerRstStreamsNewStreamAboveStreamLimitBeforeAck) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); adapter->SubmitSettings({{MAX_CONCURRENT_STREAMS, 1}}); const std::string initial_frames = TestFrameSequence().ClientPreface().Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(static_cast<size_t>(initial_result), initial_frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS})); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true) .Headers(3, {{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnInvalidFrame( 3, Http2VisitorInterface::InvalidFrameError::kRefusedStream)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(static_cast<size_t>(stream_result), stream_frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 3, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 3, _, 0x0, static_cast<int>(Http2ErrorCode::REFUSED_STREAM))); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::RST_STREAM})); } TEST(OgHttp2AdapterTest, ServerForbidsProtocolPseudoheaderBeforeAck) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; options.allow_extended_connect = false; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string initial_frames = TestFrameSequence().ClientPreface().Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(static_cast<size_t>(initial_result), initial_frames.size()); const std::string stream1_frames = TestFrameSequence() .Headers(1, {{":method", "CONNECT"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {":protocol", "websocket"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(5); EXPECT_CALL(visitor, OnInvalidFrame( 1, Http2VisitorInterface::InvalidFrameError::kHttpMessaging)); int64_t stream_result = adapter->ProcessBytes(stream1_frames); EXPECT_EQ(static_cast<size_t>(stream_result), stream1_frames.size()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); adapter->SubmitSettings({{ENABLE_CONNECT_PROTOCOL, 1}}); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT( visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM, SpdyFrameType::SETTINGS})); visitor.Clear(); const std::string stream3_frames = TestFrameSequence() .Headers(3, {{":method", "CONNECT"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}, {":protocol", "websocket"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(5); EXPECT_CALL(visitor, OnEndHeadersForStream(3)); EXPECT_CALL(visitor, OnEndStream(3)); stream_result = adapter->ProcessBytes(stream3_frames); EXPECT_EQ(static_cast<size_t>(stream_result), stream3_frames.size()); EXPECT_FALSE(adapter->want_write()); } TEST(OgHttp2AdapterTest, ServerAllowsProtocolPseudoheaderAfterAck) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); adapter->SubmitSettings({{ENABLE_CONNECT_PROTOCOL, 1}}); const std::string initial_frames = TestFrameSequence().ClientPreface().Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(static_cast<size_t>(initial_result), initial_frames.size()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); visitor.Clear(); const std::string stream_frames = TestFrameSequence() .SettingsAck() .Headers(1, {{":method", "CONNECT"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {":protocol", "websocket"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, _, SETTINGS, ACK_FLAG)); EXPECT_CALL(visitor, OnSettingsAck()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(5); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(static_cast<size_t>(stream_result), stream_frames.size()); EXPECT_FALSE(adapter->want_write()); } TEST_P(OgHttp2AdapterDataTest, SkipsSendingFramesForRejectedStream) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string initial_frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t initial_result = adapter->ProcessBytes(initial_frames); EXPECT_EQ(static_cast<size_t>(initial_result), initial_frames.size()); visitor.AppendPayloadForStream( 1, "Here is some data, which will be completely ignored!"); auto body = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse(1, ToHeaders({{":status", "200"}}), GetParam() ? nullptr : std::move(body), false); ASSERT_EQ(0, submit_result); auto source = std::make_unique<TestMetadataSource>(ToHeaderBlock(ToHeaders( {{"query-cost", "is too darn high"}, {"secret-sauce", "hollandaise"}}))); adapter->SubmitMetadata(1, 16384u, std::move(source)); adapter->SubmitWindowUpdate(1, 1024); adapter->SubmitRst(1, Http2ErrorCode::INTERNAL_ERROR); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, static_cast<int>(Http2ErrorCode::INTERNAL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST(OgHttpAdapterServerTest, ServerStartsShutdown) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); EXPECT_FALSE(adapter->want_write()); adapter->SubmitShutdownNotice(); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY})); } TEST(OgHttp2AdapterTest, ServerStartsShutdownAfterGoaway) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); EXPECT_FALSE(adapter->want_write()); adapter->SubmitGoAway(1, Http2ErrorCode::HTTP2_NO_ERROR, "and don't come back!"); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, 0)); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY})); adapter->SubmitShutdownNotice(); EXPECT_FALSE(adapter->want_write()); } TEST(OgHttp2AdapterTest, ConnectionErrorWithBlackholingData) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; options.blackhole_data_on_connection_error = true; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence().ClientPreface().WindowUpdate(1, 42).Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kWrongFrameSequence)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(result), frames.size()); const std::string next_frame = TestFrameSequence().Ping(42).Serialize(); const int64_t next_result = adapter->ProcessBytes(next_frame); EXPECT_EQ(static_cast<size_t>(next_result), next_frame.size()); } TEST(OgHttp2AdapterTest, ConnectionErrorWithoutBlackholingData) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; options.blackhole_data_on_connection_error = false; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence().ClientPreface().WindowUpdate(1, 42).Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kWrongFrameSequence)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_LT(result, 0); const std::string next_frame = TestFrameSequence().Ping(42).Serialize(); const int64_t next_result = adapter->ProcessBytes(next_frame); EXPECT_LT(next_result, 0); } TEST_P(OgHttp2AdapterDataTest, ServerDoesNotSendFramesAfterImmediateGoAway) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); adapter->SubmitSettings({{HEADER_TABLE_SIZE, 100u}}); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t read_result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(read_result), frames.size()); visitor.AppendPayloadForStream(1, "This data is doomed to never be written."); auto body = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse(1, ToHeaders({{":status", "200"}}), GetParam() ? nullptr : std::move(body), false); ASSERT_EQ(0, submit_result); adapter->SubmitWindowUpdate(kConnectionStreamId, 42); adapter->SubmitSettings({}); auto source = std::make_unique<TestMetadataSource>(ToHeaderBlock(ToHeaders( {{"query-cost", "is too darn high"}, {"secret-sauce", "hollandaise"}}))); adapter->SubmitMetadata(1, 16384u, std::move(source)); EXPECT_TRUE(adapter->want_write()); const std::string connection_error_frames = TestFrameSequence().WindowUpdate(3, 42).Serialize(); EXPECT_CALL(visitor, OnFrameHeader(3, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnConnectionError(ConnectionError::kWrongFrameSequence)); const int64_t result = adapter->ProcessBytes(connection_error_frames); EXPECT_EQ(static_cast<size_t>(result), connection_error_frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 6, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 6, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(GOAWAY, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(GOAWAY, 0, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::GOAWAY})); visitor.Clear(); adapter->SubmitPing(42); send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), testing::IsEmpty()); } TEST(OgHttp2AdapterTest, ServerHandlesContentLength) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::string stream_frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}, {"content-length", "2"}}) .Data(1, "hi", true) .Headers(3, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/three"}, {"content-length", "nan"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(5); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 1)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 2)); EXPECT_CALL(visitor, OnDataForStream(1, "hi")); EXPECT_CALL(visitor, OnEndStream(1)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(4); EXPECT_CALL( visitor, OnInvalidFrame(3, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 3, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 3, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_TRUE(adapter->want_write()); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST(OgHttp2AdapterTest, ServerHandlesContentLengthMismatch) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::string stream_frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/two"}, {"content-length", "2"}}) .Data(1, "h", true) .Headers(3, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/three"}, {"content-length", "2"}}) .Data(3, "howdy", true) .Headers(5, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/four"}, {"content-length", "2"}}, true) .Headers(7, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/four"}, {"content-length", "2"}}, false) .Data(7, "h", false) .Headers(7, {{"extra-info", "Trailers with content-length mismatch"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(5); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 1)); EXPECT_CALL(visitor, OnBeginDataForStream(1, 1)); EXPECT_CALL(visitor, OnDataForStream(1, "h")); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(5); EXPECT_CALL(visitor, OnEndHeadersForStream(3)); EXPECT_CALL(visitor, OnFrameHeader(3, _, DATA, 1)); EXPECT_CALL(visitor, OnBeginDataForStream(3, 5)); EXPECT_CALL(visitor, OnFrameHeader(5, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(5)); EXPECT_CALL(visitor, OnHeaderForStream(5, _, _)).Times(5); EXPECT_CALL(visitor, OnEndHeadersForStream(5)); EXPECT_CALL(visitor, OnInvalidFrame( 5, Http2VisitorInterface::InvalidFrameError::kHttpMessaging)); EXPECT_CALL(visitor, OnFrameHeader(7, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(7)); EXPECT_CALL(visitor, OnHeaderForStream(7, _, _)).Times(5); EXPECT_CALL(visitor, OnEndHeadersForStream(7)); EXPECT_CALL(visitor, OnFrameHeader(7, _, DATA, 0)); EXPECT_CALL(visitor, OnBeginDataForStream(7, 1)); EXPECT_CALL(visitor, OnDataForStream(7, "h")); EXPECT_CALL(visitor, OnFrameHeader(7, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(7)); EXPECT_CALL(visitor, OnHeaderForStream(7, _, _)); EXPECT_CALL(visitor, OnEndHeadersForStream(7)); EXPECT_CALL(visitor, OnInvalidFrame( 7, Http2VisitorInterface::InvalidFrameError::kHttpMessaging)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 3, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 3, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 5, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 5, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(5, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 7, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 7, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(7, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_TRUE(adapter->want_write()); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT( visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM, SpdyFrameType::RST_STREAM, SpdyFrameType::RST_STREAM, SpdyFrameType::RST_STREAM})); } TEST(OgHttp2AdapterTest, ServerHandlesAsteriskPathForOptions) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::string stream_frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":scheme", "https"}, {":authority", "example.com"}, {":path", "*"}, {":method", "OPTIONS"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_TRUE(adapter->want_write()); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS})); } TEST(OgHttp2AdapterTest, ServerHandlesInvalidPath) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::string stream_frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":scheme", "https"}, {":authority", "example.com"}, {":path", "*"}, {":method", "GET"}}, true) .Headers(3, {{":scheme", "https"}, {":authority", "example.com"}, {":path", "other/non/slash/starter"}, {":method", "GET"}}, true) .Headers(5, {{":scheme", "https"}, {":authority", "example.com"}, {":path", ""}, {":method", "GET"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnInvalidFrame( 1, Http2VisitorInterface::InvalidFrameError::kHttpMessaging)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(4); EXPECT_CALL(visitor, OnInvalidFrame( 3, Http2VisitorInterface::InvalidFrameError::kHttpMessaging)); EXPECT_CALL(visitor, OnFrameHeader(5, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(5)); EXPECT_CALL(visitor, OnHeaderForStream(5, _, _)).Times(2); EXPECT_CALL( visitor, OnInvalidFrame(5, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 3, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 3, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 5, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 5, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(5, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_TRUE(adapter->want_write()); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT( visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM, SpdyFrameType::RST_STREAM, SpdyFrameType::RST_STREAM})); } TEST(OgHttp2AdapterTest, ServerHandlesTeHeader) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::string stream_frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":scheme", "https"}, {":authority", "example.com"}, {":path", "/"}, {":method", "GET"}, {"te", "trailers"}}, true) .Headers(3, {{":scheme", "https"}, {":authority", "example.com"}, {":path", "/"}, {":method", "GET"}, {"te", "trailers, deflate"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(5); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(4); EXPECT_CALL( visitor, OnInvalidFrame(3, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 3, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 3, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_TRUE(adapter->want_write()); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM})); } TEST(OgHttp2AdapterTest, ServerHandlesConnectionSpecificHeaders) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); testing::InSequence s; const std::string stream_frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":scheme", "https"}, {":authority", "example.com"}, {":path", "/"}, {":method", "GET"}, {"connection", "keep-alive"}}, true) .Headers(3, {{":scheme", "https"}, {":authority", "example.com"}, {":path", "/"}, {":method", "GET"}, {"proxy-connection", "keep-alive"}}, true) .Headers(5, {{":scheme", "https"}, {":authority", "example.com"}, {":path", "/"}, {":method", "GET"}, {"keep-alive", "timeout=42"}}, true) .Headers(7, {{":scheme", "https"}, {":authority", "example.com"}, {":path", "/"}, {":method", "GET"}, {"transfer-encoding", "chunked"}}, true) .Headers(9, {{":scheme", "https"}, {":authority", "example.com"}, {":path", "/"}, {":method", "GET"}, {"upgrade", "h2c"}}, true) .Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL( visitor, OnInvalidFrame(1, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, _, _)).Times(4); EXPECT_CALL( visitor, OnInvalidFrame(3, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); EXPECT_CALL(visitor, OnFrameHeader(5, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(5)); EXPECT_CALL(visitor, OnHeaderForStream(5, _, _)).Times(4); EXPECT_CALL( visitor, OnInvalidFrame(5, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); EXPECT_CALL(visitor, OnFrameHeader(7, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(7)); EXPECT_CALL(visitor, OnHeaderForStream(7, _, _)).Times(4); EXPECT_CALL( visitor, OnInvalidFrame(7, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); EXPECT_CALL(visitor, OnFrameHeader(9, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(9)); EXPECT_CALL(visitor, OnHeaderForStream(9, _, _)).Times(4); EXPECT_CALL( visitor, OnInvalidFrame(9, Http2VisitorInterface::InvalidFrameError::kHttpHeader)); const int64_t stream_result = adapter->ProcessBytes(stream_frames); EXPECT_EQ(stream_frames.size(), static_cast<size_t>(stream_result)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 1, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 1, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 3, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 3, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(3, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 5, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 5, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(5, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 7, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 7, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(7, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_CALL(visitor, OnBeforeFrameSent(RST_STREAM, 9, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(RST_STREAM, 9, _, 0x0, static_cast<int>(Http2ErrorCode::PROTOCOL_ERROR))); EXPECT_CALL(visitor, OnCloseStream(9, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_TRUE(adapter->want_write()); int result = adapter->Send(); EXPECT_EQ(0, result); EXPECT_THAT( visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::RST_STREAM, SpdyFrameType::RST_STREAM, SpdyFrameType::RST_STREAM, SpdyFrameType::RST_STREAM, SpdyFrameType::RST_STREAM})); } TEST(OgHttp2AdapterTest, ServerUsesCustomWindowUpdateStrategy) { TestVisitor visitor; OgHttp2Adapter::Options options; options.should_window_update_fn = [](int64_t , int64_t , int64_t ) { return true; }; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false) .Data(1, "This is the request body.", true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, END_STREAM_FLAG)); EXPECT_CALL(visitor, OnBeginDataForStream(1, _)); EXPECT_CALL(visitor, OnDataForStream(1, "This is the request body.")); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<int64_t>(frames.size()), result); adapter->MarkDataConsumedForStream(1, 5); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 1, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 1, 4, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 0, 4, 0x0)); EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 0, 4, 0x0, 0)); int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::WINDOW_UPDATE, SpdyFrameType::WINDOW_UPDATE})); } TEST(OgHttp2AdapterTest, ServerConsumesDataWithPadding) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); TestFrameSequence seq = std::move(TestFrameSequence().ClientPreface().Headers( 1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, false)); size_t total_size = 0; while (total_size < 62 * 1024) { seq.Data(1, "a", false, 254); total_size += 255; } const std::string frames = seq.Serialize(); EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(1, _, DATA, 0x8)) .Times(testing::AtLeast(1)); EXPECT_CALL(visitor, OnBeginDataForStream(1, _)).Times(testing::AtLeast(1)); EXPECT_CALL(visitor, OnDataForStream(1, "a")).Times(testing::AtLeast(1)); EXPECT_CALL(visitor, OnDataPaddingLength(1, _)).Times(testing::AtLeast(1)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(result, frames.size()); EXPECT_TRUE(adapter->want_write()); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 1, _, 0x0)).Times(1); EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 1, _, 0x0, 0)).Times(1); EXPECT_CALL(visitor, OnBeforeFrameSent(WINDOW_UPDATE, 0, _, 0x0)).Times(1); EXPECT_CALL(visitor, OnFrameSent(WINDOW_UPDATE, 0, _, 0x0, 0)).Times(1); const int send_result = adapter->Send(); EXPECT_EQ(0, send_result); EXPECT_THAT(visitor.data(), EqualsFrames({SpdyFrameType::SETTINGS, SpdyFrameType::SETTINGS, SpdyFrameType::WINDOW_UPDATE, SpdyFrameType::WINDOW_UPDATE})); } TEST(OgHttp2AdapterTest, NoopHeaderValidatorTest) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; options.validate_http_headers = false; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/1"}, {"content-length", "7"}, {"content-length", "7"}}, false) .Headers(3, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/3"}, {"content-length", "11"}, {"content-length", "13"}}, false) .Headers(5, {{":method", "POST"}, {":scheme", "https"}, {":authority", "foo.com"}, {":path", "/"}, {"host", "bar.com"}}, true) .Headers(7, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/"}, {"Accept", "uppercase, oh boy!"}}, false) .Headers(9, {{":method", "POST"}, {":scheme", "https"}, {":authority", "ex|ample.com"}, {":path", "/"}}, false) .Headers(11, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/"}, {"content-length", "nan"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 0, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(1, ":path", "/1")); EXPECT_CALL(visitor, OnHeaderForStream(1, "content-length", "7")); EXPECT_CALL(visitor, OnHeaderForStream(1, "content-length", "7")); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnFrameHeader(3, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(3)); EXPECT_CALL(visitor, OnHeaderForStream(3, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(3, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(3, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(3, ":path", "/3")); EXPECT_CALL(visitor, OnHeaderForStream(3, "content-length", "11")); EXPECT_CALL(visitor, OnHeaderForStream(3, "content-length", "13")); EXPECT_CALL(visitor, OnEndHeadersForStream(3)); EXPECT_CALL(visitor, OnFrameHeader(5, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(5)); EXPECT_CALL(visitor, OnHeaderForStream(5, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(5, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(5, ":authority", "foo.com")); EXPECT_CALL(visitor, OnHeaderForStream(5, ":path", "/")); EXPECT_CALL(visitor, OnHeaderForStream(5, "host", "bar.com")); EXPECT_CALL(visitor, OnEndHeadersForStream(5)); EXPECT_CALL(visitor, OnEndStream(5)); EXPECT_CALL(visitor, OnFrameHeader(7, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(7)); EXPECT_CALL(visitor, OnHeaderForStream(7, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(7, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(7, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(7, ":path", "/")); EXPECT_CALL(visitor, OnHeaderForStream(7, "Accept", "uppercase, oh boy!")); EXPECT_CALL(visitor, OnEndHeadersForStream(7)); EXPECT_CALL(visitor, OnFrameHeader(9, _, HEADERS, 4)); EXPECT_CALL(visitor, OnBeginHeadersForStream(9)); EXPECT_CALL(visitor, OnHeaderForStream(9, ":method", "POST")); EXPECT_CALL(visitor, OnHeaderForStream(9, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(9, ":authority", "ex|ample.com")); EXPECT_CALL(visitor, OnHeaderForStream(9, ":path", "/")); EXPECT_CALL(visitor, OnEndHeadersForStream(9)); EXPECT_CALL(visitor, OnFrameHeader(11, _, HEADERS, 5)); EXPECT_CALL(visitor, OnBeginHeadersForStream(11)); EXPECT_CALL(visitor, OnHeaderForStream(11, ":method", "GET")); EXPECT_CALL(visitor, OnHeaderForStream(11, ":scheme", "https")); EXPECT_CALL(visitor, OnHeaderForStream(11, ":authority", "example.com")); EXPECT_CALL(visitor, OnHeaderForStream(11, ":path", "/")); EXPECT_CALL(visitor, OnHeaderForStream(11, "content-length", "nan")); EXPECT_CALL(visitor, OnEndHeadersForStream(11)); EXPECT_CALL(visitor, OnEndStream(11)); const int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), static_cast<size_t>(result)); } TEST_P(OgHttp2AdapterDataTest, NegativeFlowControlStreamResumption) { TestVisitor visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kServer; auto adapter = OgHttp2Adapter::Create(visitor, options); const std::string frames = TestFrameSequence() .ClientPreface({{INITIAL_WINDOW_SIZE, 128u * 1024u}}) .WindowUpdate(0, 1 << 20) .Headers(1, {{":method", "GET"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}, true) .Serialize(); testing::InSequence s; EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSetting(Http2Setting{Http2KnownSettingsId::INITIAL_WINDOW_SIZE, 128u * 1024u})); EXPECT_CALL(visitor, OnSettingsEnd()); EXPECT_CALL(visitor, OnFrameHeader(0, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(0, 1 << 20)); EXPECT_CALL(visitor, OnFrameHeader(1, _, HEADERS, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnBeginHeadersForStream(1)); EXPECT_CALL(visitor, OnHeaderForStream(1, _, _)).Times(4); EXPECT_CALL(visitor, OnEndHeadersForStream(1)); EXPECT_CALL(visitor, OnEndStream(1)); const int64_t read_result = adapter->ProcessBytes(frames); EXPECT_EQ(static_cast<size_t>(read_result), frames.size()); visitor.AppendPayloadForStream(1, std::string(70000, 'a')); auto body = std::make_unique<VisitorDataSource>(visitor, 1); int submit_result = adapter->SubmitResponse(1, ToHeaders({{":status", "200"}}), GetParam() ? nullptr : std::move(body), false); ASSERT_EQ(0, submit_result); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); EXPECT_CALL(visitor, OnBeforeFrameSent(HEADERS, 1, _, END_HEADERS_FLAG)); EXPECT_CALL(visitor, OnFrameSent(HEADERS, 1, _, END_HEADERS_FLAG, 0)); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0)).Times(5); adapter->Send(); EXPECT_FALSE(adapter->want_write()); EXPECT_CALL(visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(visitor, OnSettingsStart()); EXPECT_CALL(visitor, OnSetting(Http2Setting{Http2KnownSettingsId::INITIAL_WINDOW_SIZE, 64u * 1024u})); EXPECT_CALL(visitor, OnSettingsEnd()); adapter->ProcessBytes(TestFrameSequence() .Settings({{INITIAL_WINDOW_SIZE, 64u * 1024u}}) .Serialize()); EXPECT_TRUE(adapter->want_write()); EXPECT_LT(adapter->GetStreamSendWindowSize(1), 0); visitor.AppendPayloadForStream(1, "Stream should be resumed."); adapter->ResumeStream(1); EXPECT_CALL(visitor, OnBeforeFrameSent(SETTINGS, 0, _, ACK_FLAG)); EXPECT_CALL(visitor, OnFrameSent(SETTINGS, 0, _, ACK_FLAG, 0)); adapter->Send(); EXPECT_FALSE(adapter->want_write()); EXPECT_CALL(visitor, OnFrameHeader(1, 4, WINDOW_UPDATE, 0)); EXPECT_CALL(visitor, OnWindowUpdate(1, 10000)); adapter->ProcessBytes(TestFrameSequence().WindowUpdate(1, 10000).Serialize()); EXPECT_TRUE(adapter->want_write()); EXPECT_GT(adapter->GetStreamSendWindowSize(1), 0); EXPECT_CALL(visitor, OnFrameSent(DATA, 1, _, 0x0, 0)); adapter->Send(); } TEST(OgHttp2AdapterTest, SetCookieRoundtrip) { TestVisitor client_visitor; OgHttp2Adapter::Options options; options.perspective = Perspective::kClient; auto client_adapter = OgHttp2Adapter::Create(client_visitor, options); TestVisitor server_visitor; options.perspective = Perspective::kServer; auto server_adapter = OgHttp2Adapter::Create(server_visitor, options); const std::vector<Header> request_headers = ToHeaders({{":method", "GET"}, {":scheme", "http"}, {":authority", "example.com"}, {":path", "/this/is/request/one"}}); const int32_t stream_id1 = client_adapter->SubmitRequest(request_headers, nullptr, true, nullptr); ASSERT_GT(stream_id1, 0); EXPECT_CALL(client_visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(client_visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(client_visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(client_visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); EXPECT_EQ(0, client_adapter->Send()); EXPECT_CALL(server_visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(server_visitor, OnSettingsStart()); EXPECT_CALL(server_visitor, OnSetting(Http2Setting{Http2KnownSettingsId::ENABLE_PUSH, 0u})); EXPECT_CALL(server_visitor, OnSettingsEnd()); EXPECT_CALL(server_visitor, OnFrameHeader(stream_id1, _, HEADERS, 5)); EXPECT_CALL(server_visitor, OnBeginHeadersForStream(stream_id1)); EXPECT_CALL(server_visitor, OnHeaderForStream).Times(4); EXPECT_CALL(server_visitor, OnEndHeadersForStream(stream_id1)); EXPECT_CALL(server_visitor, OnEndStream(stream_id1)); ASSERT_EQ(client_visitor.data().size(), server_adapter->ProcessBytes(client_visitor.data())); const std::vector<Header> response_headers = ToHeaders({{":status", "200"}, {"set-cookie", "chocolate_chip=yummy"}, {"set-cookie", "macadamia_nut=okay"}}); EXPECT_EQ(0, server_adapter->SubmitResponse(stream_id1, response_headers, nullptr, true)); EXPECT_CALL(server_visitor, OnBeforeFrameSent(SETTINGS, 0, _, 0x0)); EXPECT_CALL(server_visitor, OnFrameSent(SETTINGS, 0, _, 0x0, 0)); EXPECT_CALL(server_visitor, OnBeforeFrameSent(SETTINGS, 0, 0, ACK_FLAG)); EXPECT_CALL(server_visitor, OnFrameSent(SETTINGS, 0, 0, ACK_FLAG, 0)); EXPECT_CALL(server_visitor, OnBeforeFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG)); EXPECT_CALL(server_visitor, OnFrameSent(HEADERS, stream_id1, _, END_STREAM_FLAG | END_HEADERS_FLAG, 0)); EXPECT_CALL(server_visitor, OnCloseStream(stream_id1, Http2ErrorCode::HTTP2_NO_ERROR)); EXPECT_EQ(0, server_adapter->Send()); EXPECT_CALL(client_visitor, OnFrameHeader(0, 6, SETTINGS, 0)); EXPECT_CALL(client_visitor, OnSettingsStart()); EXPECT_CALL(client_visitor, OnSetting(Http2Setting{ Http2KnownSettingsId::ENABLE_CONNECT_PROTOCOL, 1u})); EXPECT_CALL(client_visitor, OnSettingsEnd()); EXPECT_CALL(client_visitor, OnFrameHeader(0, 0, SETTINGS, ACK_FLAG)); EXPECT_CALL(client_visitor, OnSettingsAck()); EXPECT_CALL(client_visitor, OnFrameHeader(stream_id1, _, HEADERS, 5)); EXPECT_CALL(client_visitor, OnBeginHeadersForStream(stream_id1)); EXPECT_CALL(client_visitor, OnHeaderForStream(stream_id1, ":status", "200")); EXPECT_CALL(client_visitor, OnHeaderForStream(stream_id1, "set-cookie", "chocolate_chip=yummy")); EXPECT_CALL(client_visitor, OnHeaderForStream(stream_id1, "set-cookie", "macadamia_nut=okay")); EXPECT_CALL(client_visitor, OnEndHeadersForStream(stream_id1)); EXPECT_CALL(client_visitor, OnEndStream(stream_id1)); EXPECT_CALL(client_visitor, OnCloseStream(stream_id1, Http2ErrorCode::HTTP2_NO_ERROR)); ASSERT_EQ(server_visitor.data().size(), client_adapter->ProcessBytes(server_visitor.data())); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/oghttp2_adapter.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/oghttp2_adapter_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
1c3ea12b-9590-4f05-917c-0adaca0d8b2d
cpp
google/quiche
recording_http2_visitor
quiche/http2/adapter/recording_http2_visitor.cc
quiche/http2/adapter/recording_http2_visitor_test.cc
#include "quiche/http2/adapter/recording_http2_visitor.h" #include "absl/strings/str_format.h" #include "quiche/http2/adapter/http2_protocol.h" #include "quiche/http2/adapter/http2_util.h" namespace http2 { namespace adapter { namespace test { int64_t RecordingHttp2Visitor::OnReadyToSend(absl::string_view serialized) { events_.push_back(absl::StrFormat("OnReadyToSend %d", serialized.size())); return serialized.size(); } Http2VisitorInterface::DataFrameHeaderInfo RecordingHttp2Visitor::OnReadyToSendDataForStream(Http2StreamId stream_id, size_t max_length) { events_.push_back(absl::StrFormat("OnReadyToSendDataForStream %d %d", stream_id, max_length)); return {70000, true, true}; } bool RecordingHttp2Visitor::SendDataFrame(Http2StreamId stream_id, absl::string_view , size_t payload_bytes) { events_.push_back( absl::StrFormat("SendDataFrame %d %d", stream_id, payload_bytes)); return true; } void RecordingHttp2Visitor::OnConnectionError(ConnectionError error) { events_.push_back( absl::StrFormat("OnConnectionError %s", ConnectionErrorToString(error))); } bool RecordingHttp2Visitor::OnFrameHeader(Http2StreamId stream_id, size_t length, uint8_t type, uint8_t flags) { events_.push_back(absl::StrFormat("OnFrameHeader %d %d %d %d", stream_id, length, type, flags)); return true; } void RecordingHttp2Visitor::OnSettingsStart() { events_.push_back("OnSettingsStart"); } void RecordingHttp2Visitor::OnSetting(Http2Setting setting) { events_.push_back(absl::StrFormat( "OnSetting %s %d", Http2SettingsIdToString(setting.id), setting.value)); } void RecordingHttp2Visitor::OnSettingsEnd() { events_.push_back("OnSettingsEnd"); } void RecordingHttp2Visitor::OnSettingsAck() { events_.push_back("OnSettingsAck"); } bool RecordingHttp2Visitor::OnBeginHeadersForStream(Http2StreamId stream_id) { events_.push_back(absl::StrFormat("OnBeginHeadersForStream %d", stream_id)); return true; } Http2VisitorInterface::OnHeaderResult RecordingHttp2Visitor::OnHeaderForStream( Http2StreamId stream_id, absl::string_view name, absl::string_view value) { events_.push_back( absl::StrFormat("OnHeaderForStream %d %s %s", stream_id, name, value)); return HEADER_OK; } bool RecordingHttp2Visitor::OnEndHeadersForStream(Http2StreamId stream_id) { events_.push_back(absl::StrFormat("OnEndHeadersForStream %d", stream_id)); return true; } bool RecordingHttp2Visitor::OnDataPaddingLength(Http2StreamId stream_id, size_t padding_length) { events_.push_back( absl::StrFormat("OnDataPaddingLength %d %d", stream_id, padding_length)); return true; } bool RecordingHttp2Visitor::OnBeginDataForStream(Http2StreamId stream_id, size_t payload_length) { events_.push_back( absl::StrFormat("OnBeginDataForStream %d %d", stream_id, payload_length)); return true; } bool RecordingHttp2Visitor::OnDataForStream(Http2StreamId stream_id, absl::string_view data) { events_.push_back(absl::StrFormat("OnDataForStream %d %s", stream_id, data)); return true; } bool RecordingHttp2Visitor::OnEndStream(Http2StreamId stream_id) { events_.push_back(absl::StrFormat("OnEndStream %d", stream_id)); return true; } void RecordingHttp2Visitor::OnRstStream(Http2StreamId stream_id, Http2ErrorCode error_code) { events_.push_back(absl::StrFormat("OnRstStream %d %s", stream_id, Http2ErrorCodeToString(error_code))); } bool RecordingHttp2Visitor::OnCloseStream(Http2StreamId stream_id, Http2ErrorCode error_code) { events_.push_back(absl::StrFormat("OnCloseStream %d %s", stream_id, Http2ErrorCodeToString(error_code))); return true; } void RecordingHttp2Visitor::OnPriorityForStream(Http2StreamId stream_id, Http2StreamId parent_stream_id, int weight, bool exclusive) { events_.push_back(absl::StrFormat("OnPriorityForStream %d %d %d %d", stream_id, parent_stream_id, weight, exclusive)); } void RecordingHttp2Visitor::OnPing(Http2PingId ping_id, bool is_ack) { events_.push_back(absl::StrFormat("OnPing %d %d", ping_id, is_ack)); } void RecordingHttp2Visitor::OnPushPromiseForStream( Http2StreamId stream_id, Http2StreamId promised_stream_id) { events_.push_back(absl::StrFormat("OnPushPromiseForStream %d %d", stream_id, promised_stream_id)); } bool RecordingHttp2Visitor::OnGoAway(Http2StreamId last_accepted_stream_id, Http2ErrorCode error_code, absl::string_view opaque_data) { events_.push_back( absl::StrFormat("OnGoAway %d %s %s", last_accepted_stream_id, Http2ErrorCodeToString(error_code), opaque_data)); return true; } void RecordingHttp2Visitor::OnWindowUpdate(Http2StreamId stream_id, int window_increment) { events_.push_back( absl::StrFormat("OnWindowUpdate %d %d", stream_id, window_increment)); } int RecordingHttp2Visitor::OnBeforeFrameSent(uint8_t frame_type, Http2StreamId stream_id, size_t length, uint8_t flags) { events_.push_back(absl::StrFormat("OnBeforeFrameSent %d %d %d %d", frame_type, stream_id, length, flags)); return 0; } int RecordingHttp2Visitor::OnFrameSent(uint8_t frame_type, Http2StreamId stream_id, size_t length, uint8_t flags, uint32_t error_code) { events_.push_back(absl::StrFormat("OnFrameSent %d %d %d %d %d", frame_type, stream_id, length, flags, error_code)); return 0; } bool RecordingHttp2Visitor::OnInvalidFrame(Http2StreamId stream_id, InvalidFrameError error) { events_.push_back(absl::StrFormat("OnInvalidFrame %d %s", stream_id, InvalidFrameErrorToString(error))); return true; } void RecordingHttp2Visitor::OnBeginMetadataForStream(Http2StreamId stream_id, size_t payload_length) { events_.push_back(absl::StrFormat("OnBeginMetadataForStream %d %d", stream_id, payload_length)); } bool RecordingHttp2Visitor::OnMetadataForStream(Http2StreamId stream_id, absl::string_view metadata) { events_.push_back( absl::StrFormat("OnMetadataForStream %d %s", stream_id, metadata)); return true; } bool RecordingHttp2Visitor::OnMetadataEndForStream(Http2StreamId stream_id) { events_.push_back(absl::StrFormat("OnMetadataEndForStream %d", stream_id)); return true; } std::pair<int64_t, bool> RecordingHttp2Visitor::PackMetadataForStream( Http2StreamId stream_id, uint8_t* , size_t ) { events_.push_back(absl::StrFormat("PackMetadataForStream %d", stream_id)); return {1, true}; } void RecordingHttp2Visitor::OnErrorDebug(absl::string_view message) { events_.push_back(absl::StrFormat("OnErrorDebug %s", message)); } } } }
#include "quiche/http2/adapter/recording_http2_visitor.h" #include <list> #include <string> #include "quiche/http2/adapter/http2_protocol.h" #include "quiche/http2/adapter/http2_visitor_interface.h" #include "quiche/http2/test_tools/http2_random.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace adapter { namespace test { namespace { using ::testing::IsEmpty; TEST(RecordingHttp2VisitorTest, EmptySequence) { RecordingHttp2Visitor chocolate_visitor; RecordingHttp2Visitor vanilla_visitor; EXPECT_THAT(chocolate_visitor.GetEventSequence(), IsEmpty()); EXPECT_THAT(vanilla_visitor.GetEventSequence(), IsEmpty()); EXPECT_EQ(chocolate_visitor.GetEventSequence(), vanilla_visitor.GetEventSequence()); chocolate_visitor.OnSettingsStart(); EXPECT_THAT(chocolate_visitor.GetEventSequence(), testing::Not(IsEmpty())); EXPECT_THAT(vanilla_visitor.GetEventSequence(), IsEmpty()); EXPECT_NE(chocolate_visitor.GetEventSequence(), vanilla_visitor.GetEventSequence()); chocolate_visitor.Clear(); EXPECT_THAT(chocolate_visitor.GetEventSequence(), IsEmpty()); EXPECT_THAT(vanilla_visitor.GetEventSequence(), IsEmpty()); EXPECT_EQ(chocolate_visitor.GetEventSequence(), vanilla_visitor.GetEventSequence()); } TEST(RecordingHttp2VisitorTest, SameEventsProduceSameSequence) { RecordingHttp2Visitor chocolate_visitor; RecordingHttp2Visitor vanilla_visitor; http2::test::Http2Random random; const Http2StreamId stream_id = random.Uniform(kMaxStreamId); const Http2StreamId another_stream_id = random.Uniform(kMaxStreamId); const size_t length = random.Rand16(); const uint8_t type = random.Rand8(); const uint8_t flags = random.Rand8(); const Http2ErrorCode error_code = static_cast<Http2ErrorCode>( random.Uniform(static_cast<int>(Http2ErrorCode::MAX_ERROR_CODE))); const Http2Setting setting = {random.Rand16(), random.Rand32()}; const absl::string_view alphabet = "abcdefghijklmnopqrstuvwxyz0123456789-"; const std::string some_string = random.RandStringWithAlphabet(random.Rand8(), alphabet); const std::string another_string = random.RandStringWithAlphabet(random.Rand8(), alphabet); const uint16_t some_int = random.Rand16(); const bool some_bool = random.OneIn(2); std::list<RecordingHttp2Visitor*> visitors = {&chocolate_visitor, &vanilla_visitor}; for (RecordingHttp2Visitor* visitor : visitors) { visitor->OnConnectionError( Http2VisitorInterface::ConnectionError::kSendError); visitor->OnFrameHeader(stream_id, length, type, flags); visitor->OnSettingsStart(); visitor->OnSetting(setting); visitor->OnSettingsEnd(); visitor->OnSettingsAck(); visitor->OnBeginHeadersForStream(stream_id); visitor->OnHeaderForStream(stream_id, some_string, another_string); visitor->OnEndHeadersForStream(stream_id); visitor->OnBeginDataForStream(stream_id, length); visitor->OnDataForStream(stream_id, some_string); visitor->OnDataForStream(stream_id, another_string); visitor->OnEndStream(stream_id); visitor->OnRstStream(stream_id, error_code); visitor->OnCloseStream(stream_id, error_code); visitor->OnPriorityForStream(stream_id, another_stream_id, some_int, some_bool); visitor->OnPing(some_int, some_bool); visitor->OnPushPromiseForStream(stream_id, another_stream_id); visitor->OnGoAway(stream_id, error_code, some_string); visitor->OnWindowUpdate(stream_id, some_int); visitor->OnBeginMetadataForStream(stream_id, length); visitor->OnMetadataForStream(stream_id, some_string); visitor->OnMetadataForStream(stream_id, another_string); visitor->OnMetadataEndForStream(stream_id); } EXPECT_EQ(chocolate_visitor.GetEventSequence(), vanilla_visitor.GetEventSequence()); } TEST(RecordingHttp2VisitorTest, DifferentEventsProduceDifferentSequence) { RecordingHttp2Visitor chocolate_visitor; RecordingHttp2Visitor vanilla_visitor; EXPECT_EQ(chocolate_visitor.GetEventSequence(), vanilla_visitor.GetEventSequence()); const Http2StreamId stream_id = 1; const size_t length = 42; chocolate_visitor.OnBeginDataForStream(stream_id, length); vanilla_visitor.OnBeginMetadataForStream(stream_id, length); EXPECT_NE(chocolate_visitor.GetEventSequence(), vanilla_visitor.GetEventSequence()); chocolate_visitor.Clear(); vanilla_visitor.Clear(); EXPECT_EQ(chocolate_visitor.GetEventSequence(), vanilla_visitor.GetEventSequence()); chocolate_visitor.OnBeginHeadersForStream(stream_id); vanilla_visitor.OnBeginHeadersForStream(stream_id + 2); EXPECT_NE(chocolate_visitor.GetEventSequence(), vanilla_visitor.GetEventSequence()); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/recording_http2_visitor.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/recording_http2_visitor_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
efb8c578-1307-4e81-8fd7-3cc4c3c6661e
cpp
google/quiche
nghttp2_util
quiche/http2/adapter/nghttp2_util.cc
quiche/http2/adapter/nghttp2_util_test.cc
#include "quiche/http2/adapter/nghttp2_util.h" #include <cstdint> #include <cstring> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/http2/adapter/http2_protocol.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_endian.h" namespace http2 { namespace adapter { namespace { using InvalidFrameError = Http2VisitorInterface::InvalidFrameError; void DeleteCallbacks(nghttp2_session_callbacks* callbacks) { if (callbacks) { nghttp2_session_callbacks_del(callbacks); } } void DeleteSession(nghttp2_session* session) { if (session) { nghttp2_session_del(session); } } } nghttp2_session_callbacks_unique_ptr MakeCallbacksPtr( nghttp2_session_callbacks* callbacks) { return nghttp2_session_callbacks_unique_ptr(callbacks, &DeleteCallbacks); } nghttp2_session_unique_ptr MakeSessionPtr(nghttp2_session* session) { return nghttp2_session_unique_ptr(session, &DeleteSession); } uint8_t* ToUint8Ptr(char* str) { return reinterpret_cast<uint8_t*>(str); } uint8_t* ToUint8Ptr(const char* str) { return const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(str)); } absl::string_view ToStringView(nghttp2_rcbuf* rc_buffer) { nghttp2_vec buffer = nghttp2_rcbuf_get_buf(rc_buffer); return absl::string_view(reinterpret_cast<const char*>(buffer.base), buffer.len); } absl::string_view ToStringView(uint8_t* pointer, size_t length) { return absl::string_view(reinterpret_cast<const char*>(pointer), length); } absl::string_view ToStringView(const uint8_t* pointer, size_t length) { return absl::string_view(reinterpret_cast<const char*>(pointer), length); } std::vector<nghttp2_nv> GetNghttp2Nvs(absl::Span<const Header> headers) { const int num_headers = headers.size(); std::vector<nghttp2_nv> nghttp2_nvs; nghttp2_nvs.reserve(num_headers); for (int i = 0; i < num_headers; ++i) { nghttp2_nv header; uint8_t flags = NGHTTP2_NV_FLAG_NONE; const auto [name, no_copy_name] = GetStringView(headers[i].first); header.name = ToUint8Ptr(name.data()); header.namelen = name.size(); if (no_copy_name) { flags |= NGHTTP2_NV_FLAG_NO_COPY_NAME; } const auto [value, no_copy_value] = GetStringView(headers[i].second); header.value = ToUint8Ptr(value.data()); header.valuelen = value.size(); if (no_copy_value) { flags |= NGHTTP2_NV_FLAG_NO_COPY_VALUE; } header.flags = flags; nghttp2_nvs.push_back(std::move(header)); } return nghttp2_nvs; } std::vector<nghttp2_nv> GetResponseNghttp2Nvs( const quiche::HttpHeaderBlock& headers, absl::string_view response_code) { const int num_headers = headers.size(); std::vector<nghttp2_nv> nghttp2_nvs; nghttp2_nvs.reserve(num_headers + 1); nghttp2_nv status; status.name = ToUint8Ptr(kHttp2StatusPseudoHeader.data()); status.namelen = kHttp2StatusPseudoHeader.size(); status.value = ToUint8Ptr(response_code.data()); status.valuelen = response_code.size(); status.flags = NGHTTP2_FLAG_NONE; nghttp2_nvs.push_back(std::move(status)); for (const auto& header_pair : headers) { nghttp2_nv header; header.name = ToUint8Ptr(header_pair.first.data()); header.namelen = header_pair.first.size(); header.value = ToUint8Ptr(header_pair.second.data()); header.valuelen = header_pair.second.size(); header.flags = NGHTTP2_FLAG_NONE; nghttp2_nvs.push_back(std::move(header)); } return nghttp2_nvs; } Http2ErrorCode ToHttp2ErrorCode(uint32_t wire_error_code) { if (wire_error_code > static_cast<int>(Http2ErrorCode::MAX_ERROR_CODE)) { return Http2ErrorCode::INTERNAL_ERROR; } return static_cast<Http2ErrorCode>(wire_error_code); } int ToNgHttp2ErrorCode(InvalidFrameError error) { switch (error) { case InvalidFrameError::kProtocol: return NGHTTP2_ERR_PROTO; case InvalidFrameError::kRefusedStream: return NGHTTP2_ERR_REFUSED_STREAM; case InvalidFrameError::kHttpHeader: return NGHTTP2_ERR_HTTP_HEADER; case InvalidFrameError::kHttpMessaging: return NGHTTP2_ERR_HTTP_MESSAGING; case InvalidFrameError::kFlowControl: return NGHTTP2_ERR_FLOW_CONTROL; case InvalidFrameError::kStreamClosed: return NGHTTP2_ERR_STREAM_CLOSED; } return NGHTTP2_ERR_PROTO; } InvalidFrameError ToInvalidFrameError(int error) { switch (error) { case NGHTTP2_ERR_PROTO: return InvalidFrameError::kProtocol; case NGHTTP2_ERR_REFUSED_STREAM: return InvalidFrameError::kRefusedStream; case NGHTTP2_ERR_HTTP_HEADER: return InvalidFrameError::kHttpHeader; case NGHTTP2_ERR_HTTP_MESSAGING: return InvalidFrameError::kHttpMessaging; case NGHTTP2_ERR_FLOW_CONTROL: return InvalidFrameError::kFlowControl; case NGHTTP2_ERR_STREAM_CLOSED: return InvalidFrameError::kStreamClosed; } return InvalidFrameError::kProtocol; } class Nghttp2DataFrameSource : public DataFrameSource { public: Nghttp2DataFrameSource(nghttp2_data_provider provider, nghttp2_send_data_callback send_data, void* user_data) : provider_(std::move(provider)), send_data_(std::move(send_data)), user_data_(user_data) {} std::pair<int64_t, bool> SelectPayloadLength(size_t max_length) override { const int32_t stream_id = 0; uint32_t data_flags = 0; int64_t result = provider_.read_callback( nullptr , stream_id, nullptr , max_length, &data_flags, &provider_.source, nullptr ); if (result == NGHTTP2_ERR_DEFERRED) { return {kBlocked, false}; } else if (result < 0) { return {kError, false}; } else if ((data_flags & NGHTTP2_DATA_FLAG_NO_COPY) == 0) { QUICHE_LOG(ERROR) << "Source did not use the zero-copy API!"; return {kError, false}; } else { const bool eof = data_flags & NGHTTP2_DATA_FLAG_EOF; if (eof && (data_flags & NGHTTP2_DATA_FLAG_NO_END_STREAM) == 0) { send_fin_ = true; } return {result, eof}; } } bool Send(absl::string_view frame_header, size_t payload_length) override { nghttp2_frame frame; frame.hd.type = 0; frame.hd.length = payload_length; frame.hd.flags = 0; frame.hd.stream_id = 0; frame.data.padlen = 0; const int result = send_data_( nullptr , &frame, ToUint8Ptr(frame_header.data()), payload_length, &provider_.source, user_data_); QUICHE_LOG_IF(ERROR, result < 0 && result != NGHTTP2_ERR_WOULDBLOCK) << "Unexpected error code from send: " << result; return result == 0; } bool send_fin() const override { return send_fin_; } private: nghttp2_data_provider provider_; nghttp2_send_data_callback send_data_; void* user_data_; bool send_fin_ = false; }; std::unique_ptr<DataFrameSource> MakeZeroCopyDataFrameSource( nghttp2_data_provider provider, void* user_data, nghttp2_send_data_callback send_data) { return std::make_unique<Nghttp2DataFrameSource>( std::move(provider), std::move(send_data), user_data); } absl::string_view ErrorString(uint32_t error_code) { return Http2ErrorCodeToString(static_cast<Http2ErrorCode>(error_code)); } size_t PaddingLength(uint8_t flags, size_t padlen) { return (flags & PADDED_FLAG ? 1 : 0) + padlen; } struct NvFormatter { void operator()(std::string* out, const nghttp2_nv& nv) { absl::StrAppend(out, ToStringView(nv.name, nv.namelen), ": ", ToStringView(nv.value, nv.valuelen)); } }; std::string NvsAsString(nghttp2_nv* nva, size_t nvlen) { return absl::StrJoin(absl::MakeConstSpan(nva, nvlen), ", ", NvFormatter()); } #define HTTP2_FRAME_SEND_LOG QUICHE_VLOG(1) void LogBeforeSend(const nghttp2_frame& frame) { switch (static_cast<FrameType>(frame.hd.type)) { case FrameType::DATA: HTTP2_FRAME_SEND_LOG << "Sending DATA on stream " << frame.hd.stream_id << " with length " << frame.hd.length - PaddingLength(frame.hd.flags, frame.data.padlen) << " and padding " << PaddingLength(frame.hd.flags, frame.data.padlen); break; case FrameType::HEADERS: HTTP2_FRAME_SEND_LOG << "Sending HEADERS on stream " << frame.hd.stream_id << " with headers [" << NvsAsString(frame.headers.nva, frame.headers.nvlen) << "]"; break; case FrameType::PRIORITY: HTTP2_FRAME_SEND_LOG << "Sending PRIORITY"; break; case FrameType::RST_STREAM: HTTP2_FRAME_SEND_LOG << "Sending RST_STREAM on stream " << frame.hd.stream_id << " with error code " << ErrorString(frame.rst_stream.error_code); break; case FrameType::SETTINGS: HTTP2_FRAME_SEND_LOG << "Sending SETTINGS with " << frame.settings.niv << " entries, is_ack: " << (frame.hd.flags & ACK_FLAG); break; case FrameType::PUSH_PROMISE: HTTP2_FRAME_SEND_LOG << "Sending PUSH_PROMISE"; break; case FrameType::PING: { Http2PingId ping_id; std::memcpy(&ping_id, frame.ping.opaque_data, sizeof(Http2PingId)); HTTP2_FRAME_SEND_LOG << "Sending PING with unique_id " << quiche::QuicheEndian::NetToHost64(ping_id) << ", is_ack: " << (frame.hd.flags & ACK_FLAG); break; } case FrameType::GOAWAY: HTTP2_FRAME_SEND_LOG << "Sending GOAWAY with last_stream: " << frame.goaway.last_stream_id << " and error " << ErrorString(frame.goaway.error_code); break; case FrameType::WINDOW_UPDATE: HTTP2_FRAME_SEND_LOG << "Sending WINDOW_UPDATE on stream " << frame.hd.stream_id << " with update delta " << frame.window_update.window_size_increment; break; case FrameType::CONTINUATION: HTTP2_FRAME_SEND_LOG << "Sending CONTINUATION, which is unexpected"; break; } } #undef HTTP2_FRAME_SEND_LOG } }
#include "quiche/http2/adapter/nghttp2_util.h" #include <memory> #include <string> #include "quiche/http2/adapter/nghttp2_test_utils.h" #include "quiche/http2/adapter/test_utils.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace adapter { namespace test { namespace { int FakeSendCallback(nghttp2_session*, nghttp2_frame* , const uint8_t* framehd, size_t length, nghttp2_data_source* source, void* user_data) { auto* dest = static_cast<std::string*>(user_data); absl::StrAppend(dest, ToStringView(framehd, 9)); auto* test_source = static_cast<TestDataSource*>(source->ptr); absl::string_view payload = test_source->ReadNext(length); absl::StrAppend(dest, payload); return 0; } TEST(MakeZeroCopyDataFrameSource, EmptyPayload) { std::string result; const absl::string_view kEmptyBody = ""; TestDataSource body1{kEmptyBody}; nghttp2_data_provider provider = body1.MakeDataProvider(); std::unique_ptr<DataFrameSource> frame_source = MakeZeroCopyDataFrameSource(provider, &result, FakeSendCallback); auto [length, eof] = frame_source->SelectPayloadLength(100); EXPECT_EQ(length, 0); EXPECT_TRUE(eof); frame_source->Send("ninebytes", 0); EXPECT_EQ(result, "ninebytes"); } TEST(MakeZeroCopyDataFrameSource, ShortPayload) { std::string result; const absl::string_view kShortBody = "<html><head><title>Example Page!</title></head>" "<body><div><span><table><tr><th><blink>Wow!!" "</blink></th></tr></table></span></div></body>" "</html>"; TestDataSource body1{kShortBody}; nghttp2_data_provider provider = body1.MakeDataProvider(); std::unique_ptr<DataFrameSource> frame_source = MakeZeroCopyDataFrameSource(provider, &result, FakeSendCallback); auto [length, eof] = frame_source->SelectPayloadLength(200); EXPECT_EQ(length, kShortBody.size()); EXPECT_TRUE(eof); frame_source->Send("ninebytes", length); EXPECT_EQ(result, absl::StrCat("ninebytes", kShortBody)); } TEST(MakeZeroCopyDataFrameSource, MultiFramePayload) { std::string result; const absl::string_view kShortBody = "<html><head><title>Example Page!</title></head>" "<body><div><span><table><tr><th><blink>Wow!!" "</blink></th></tr></table></span></div></body>" "</html>"; TestDataSource body1{kShortBody}; nghttp2_data_provider provider = body1.MakeDataProvider(); std::unique_ptr<DataFrameSource> frame_source = MakeZeroCopyDataFrameSource(provider, &result, FakeSendCallback); auto ret = frame_source->SelectPayloadLength(50); EXPECT_EQ(ret.first, 50); EXPECT_FALSE(ret.second); frame_source->Send("ninebyte1", ret.first); ret = frame_source->SelectPayloadLength(50); EXPECT_EQ(ret.first, 50); EXPECT_FALSE(ret.second); frame_source->Send("ninebyte2", ret.first); ret = frame_source->SelectPayloadLength(50); EXPECT_EQ(ret.first, 44); EXPECT_TRUE(ret.second); frame_source->Send("ninebyte3", ret.first); EXPECT_EQ(result, "ninebyte1<html><head><title>Example Page!</title></head><bo" "ninebyte2dy><div><span><table><tr><th><blink>Wow!!</blink><" "ninebyte3/th></tr></table></span></div></body></html>"); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/nghttp2_util.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/nghttp2_util_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
235ebbea-734a-47f7-930c-f3acde9d6ade
cpp
google/quiche
nghttp2_data_provider
quiche/http2/adapter/nghttp2_data_provider.cc
quiche/http2/adapter/nghttp2_data_provider_test.cc
#include "quiche/http2/adapter/nghttp2_data_provider.h" #include <memory> #include "quiche/http2/adapter/http2_visitor_interface.h" #include "quiche/http2/adapter/nghttp2_util.h" namespace http2 { namespace adapter { namespace callbacks { ssize_t VisitorReadCallback(Http2VisitorInterface& visitor, int32_t stream_id, size_t max_length, uint32_t* data_flags) { *data_flags |= NGHTTP2_DATA_FLAG_NO_COPY; auto [payload_length, end_data, end_stream] = visitor.OnReadyToSendDataForStream(stream_id, max_length); if (payload_length == 0 && !end_data) { return NGHTTP2_ERR_DEFERRED; } else if (payload_length == DataFrameSource::kError) { return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE; } if (end_data) { *data_flags |= NGHTTP2_DATA_FLAG_EOF; } if (!end_stream) { *data_flags |= NGHTTP2_DATA_FLAG_NO_END_STREAM; } return payload_length; } ssize_t DataFrameSourceReadCallback(DataFrameSource& source, size_t length, uint32_t* data_flags) { *data_flags |= NGHTTP2_DATA_FLAG_NO_COPY; auto [result_length, done] = source.SelectPayloadLength(length); if (result_length == 0 && !done) { return NGHTTP2_ERR_DEFERRED; } else if (result_length == DataFrameSource::kError) { return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE; } if (done) { *data_flags |= NGHTTP2_DATA_FLAG_EOF; } if (!source.send_fin()) { *data_flags |= NGHTTP2_DATA_FLAG_NO_END_STREAM; } return result_length; } } } }
#include "quiche/http2/adapter/nghttp2_data_provider.h" #include "quiche/http2/adapter/nghttp2_util.h" #include "quiche/http2/adapter/test_utils.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace adapter { namespace test { const size_t kFrameHeaderSize = 9; TEST(DataFrameSourceTest, ReadLessThanSourceProvides) { const int32_t kStreamId = 1; TestVisitor visitor; visitor.AppendPayloadForStream(kStreamId, "Example payload"); visitor.SetEndData(kStreamId, true); VisitorDataSource source(visitor, kStreamId); uint32_t data_flags = 0; const size_t kReadLength = 10; ssize_t result = callbacks::DataFrameSourceReadCallback(source, kReadLength, &data_flags); ASSERT_EQ(kReadLength, result); EXPECT_EQ(NGHTTP2_DATA_FLAG_NO_COPY | NGHTTP2_DATA_FLAG_NO_END_STREAM, data_flags); const uint8_t framehd[kFrameHeaderSize] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; source.Send(ToStringView(framehd, kFrameHeaderSize), result); EXPECT_EQ(visitor.data().size(), kFrameHeaderSize + kReadLength); } TEST(VisitorTest, ReadLessThanSourceProvides) { const int32_t kStreamId = 1; TestVisitor visitor; visitor.AppendPayloadForStream(kStreamId, "Example payload"); visitor.SetEndData(kStreamId, true); uint32_t data_flags = 0; const size_t kReadLength = 10; ssize_t result = callbacks::VisitorReadCallback(visitor, kStreamId, kReadLength, &data_flags); ASSERT_EQ(kReadLength, result); EXPECT_EQ(NGHTTP2_DATA_FLAG_NO_COPY | NGHTTP2_DATA_FLAG_NO_END_STREAM, data_flags); const uint8_t framehd[kFrameHeaderSize] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; visitor.SendDataFrame(kStreamId, ToStringView(framehd, kFrameHeaderSize), result); EXPECT_EQ(visitor.data().size(), kFrameHeaderSize + kReadLength); } TEST(DataFrameSourceTest, ReadMoreThanSourceProvides) { const int32_t kStreamId = 1; const absl::string_view kPayload = "Example payload"; TestVisitor visitor; visitor.AppendPayloadForStream(kStreamId, kPayload); visitor.SetEndData(kStreamId, true); VisitorDataSource source(visitor, kStreamId); uint32_t data_flags = 0; const size_t kReadLength = 30; ssize_t result = callbacks::DataFrameSourceReadCallback(source, kReadLength, &data_flags); ASSERT_EQ(kPayload.size(), result); EXPECT_EQ(NGHTTP2_DATA_FLAG_NO_COPY | NGHTTP2_DATA_FLAG_EOF, data_flags); const uint8_t framehd[kFrameHeaderSize] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; source.Send(ToStringView(framehd, kFrameHeaderSize), result); EXPECT_EQ(visitor.data().size(), kFrameHeaderSize + kPayload.size()); } TEST(VisitorTest, ReadMoreThanSourceProvides) { const int32_t kStreamId = 1; const absl::string_view kPayload = "Example payload"; TestVisitor visitor; visitor.AppendPayloadForStream(kStreamId, kPayload); visitor.SetEndData(kStreamId, true); VisitorDataSource source(visitor, kStreamId); uint32_t data_flags = 0; const size_t kReadLength = 30; ssize_t result = callbacks::VisitorReadCallback(visitor, kStreamId, kReadLength, &data_flags); ASSERT_EQ(kPayload.size(), result); EXPECT_EQ(NGHTTP2_DATA_FLAG_NO_COPY | NGHTTP2_DATA_FLAG_EOF, data_flags); const uint8_t framehd[kFrameHeaderSize] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; visitor.SendDataFrame(kStreamId, ToStringView(framehd, kFrameHeaderSize), result); EXPECT_EQ(visitor.data().size(), kFrameHeaderSize + kPayload.size()); } TEST(DataFrameSourceTest, ReadFromBlockedSource) { const int32_t kStreamId = 1; TestVisitor visitor; VisitorDataSource source(visitor, kStreamId); uint32_t data_flags = 0; const size_t kReadLength = 10; ssize_t result = callbacks::DataFrameSourceReadCallback(source, kReadLength, &data_flags); EXPECT_EQ(NGHTTP2_ERR_DEFERRED, result); } TEST(VisitorTest, ReadFromBlockedSource) { const int32_t kStreamId = 1; TestVisitor visitor; uint32_t data_flags = 0; const size_t kReadLength = 10; ssize_t result = callbacks::VisitorReadCallback(visitor, kStreamId, kReadLength, &data_flags); EXPECT_EQ(NGHTTP2_ERR_DEFERRED, result); } TEST(DataFrameSourceTest, ReadFromZeroLengthSource) { const int32_t kStreamId = 1; TestVisitor visitor; visitor.SetEndData(kStreamId, true); VisitorDataSource source(visitor, kStreamId); uint32_t data_flags = 0; const size_t kReadLength = 10; ssize_t result = callbacks::DataFrameSourceReadCallback(source, kReadLength, &data_flags); ASSERT_EQ(0, result); EXPECT_EQ(NGHTTP2_DATA_FLAG_NO_COPY | NGHTTP2_DATA_FLAG_EOF, data_flags); const uint8_t framehd[kFrameHeaderSize] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; source.Send(ToStringView(framehd, kFrameHeaderSize), result); EXPECT_EQ(visitor.data().size(), kFrameHeaderSize); } TEST(VisitorTest, ReadFromZeroLengthSource) { const int32_t kStreamId = 1; TestVisitor visitor; visitor.SetEndData(kStreamId, true); uint32_t data_flags = 0; const size_t kReadLength = 10; ssize_t result = callbacks::VisitorReadCallback(visitor, kStreamId, kReadLength, &data_flags); ASSERT_EQ(0, result); EXPECT_EQ(NGHTTP2_DATA_FLAG_NO_COPY | NGHTTP2_DATA_FLAG_EOF, data_flags); const uint8_t framehd[kFrameHeaderSize] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; visitor.SendDataFrame(kStreamId, ToStringView(framehd, kFrameHeaderSize), result); EXPECT_EQ(visitor.data().size(), kFrameHeaderSize); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/nghttp2_data_provider.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/nghttp2_data_provider_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
bccc1600-dd25-4f2b-be39-df2417b732ee
cpp
google/quiche
event_forwarder
quiche/http2/adapter/event_forwarder.cc
quiche/http2/adapter/event_forwarder_test.cc
#include "quiche/http2/adapter/event_forwarder.h" #include <string> #include <utility> namespace http2 { namespace adapter { EventForwarder::EventForwarder(ForwardPredicate can_forward, spdy::SpdyFramerVisitorInterface& receiver) : can_forward_(std::move(can_forward)), receiver_(receiver) {} void EventForwarder::OnError(Http2DecoderAdapter::SpdyFramerError error, std::string detailed_error) { if (can_forward_()) { receiver_.OnError(error, std::move(detailed_error)); } } void EventForwarder::OnCommonHeader(spdy::SpdyStreamId stream_id, size_t length, uint8_t type, uint8_t flags) { if (can_forward_()) { receiver_.OnCommonHeader(stream_id, length, type, flags); } } void EventForwarder::OnDataFrameHeader(spdy::SpdyStreamId stream_id, size_t length, bool fin) { if (can_forward_()) { receiver_.OnDataFrameHeader(stream_id, length, fin); } } void EventForwarder::OnStreamFrameData(spdy::SpdyStreamId stream_id, const char* data, size_t len) { if (can_forward_()) { receiver_.OnStreamFrameData(stream_id, data, len); } } void EventForwarder::OnStreamEnd(spdy::SpdyStreamId stream_id) { if (can_forward_()) { receiver_.OnStreamEnd(stream_id); } } void EventForwarder::OnStreamPadLength(spdy::SpdyStreamId stream_id, size_t value) { if (can_forward_()) { receiver_.OnStreamPadLength(stream_id, value); } } void EventForwarder::OnStreamPadding(spdy::SpdyStreamId stream_id, size_t len) { if (can_forward_()) { receiver_.OnStreamPadding(stream_id, len); } } spdy::SpdyHeadersHandlerInterface* EventForwarder::OnHeaderFrameStart( spdy::SpdyStreamId stream_id) { return receiver_.OnHeaderFrameStart(stream_id); } void EventForwarder::OnHeaderFrameEnd(spdy::SpdyStreamId stream_id) { if (can_forward_()) { receiver_.OnHeaderFrameEnd(stream_id); } } void EventForwarder::OnRstStream(spdy::SpdyStreamId stream_id, spdy::SpdyErrorCode error_code) { if (can_forward_()) { receiver_.OnRstStream(stream_id, error_code); } } void EventForwarder::OnSettings() { if (can_forward_()) { receiver_.OnSettings(); } } void EventForwarder::OnSetting(spdy::SpdySettingsId id, uint32_t value) { if (can_forward_()) { receiver_.OnSetting(id, value); } } void EventForwarder::OnSettingsEnd() { if (can_forward_()) { receiver_.OnSettingsEnd(); } } void EventForwarder::OnSettingsAck() { if (can_forward_()) { receiver_.OnSettingsAck(); } } void EventForwarder::OnPing(spdy::SpdyPingId unique_id, bool is_ack) { if (can_forward_()) { receiver_.OnPing(unique_id, is_ack); } } void EventForwarder::OnGoAway(spdy::SpdyStreamId last_accepted_stream_id, spdy::SpdyErrorCode error_code) { if (can_forward_()) { receiver_.OnGoAway(last_accepted_stream_id, error_code); } } bool EventForwarder::OnGoAwayFrameData(const char* goaway_data, size_t len) { if (can_forward_()) { return receiver_.OnGoAwayFrameData(goaway_data, len); } return false; } void EventForwarder::OnHeaders(spdy::SpdyStreamId stream_id, size_t payload_length, bool has_priority, int weight, spdy::SpdyStreamId parent_stream_id, bool exclusive, bool fin, bool end) { if (can_forward_()) { receiver_.OnHeaders(stream_id, payload_length, has_priority, weight, parent_stream_id, exclusive, fin, end); } } void EventForwarder::OnWindowUpdate(spdy::SpdyStreamId stream_id, int delta_window_size) { if (can_forward_()) { receiver_.OnWindowUpdate(stream_id, delta_window_size); } } void EventForwarder::OnPushPromise(spdy::SpdyStreamId stream_id, spdy::SpdyStreamId promised_stream_id, bool end) { if (can_forward_()) { receiver_.OnPushPromise(stream_id, promised_stream_id, end); } } void EventForwarder::OnContinuation(spdy::SpdyStreamId stream_id, size_t payload_length, bool end) { if (can_forward_()) { receiver_.OnContinuation(stream_id, payload_length, end); } } void EventForwarder::OnAltSvc( spdy::SpdyStreamId stream_id, absl::string_view origin, const spdy::SpdyAltSvcWireFormat::AlternativeServiceVector& altsvc_vector) { if (can_forward_()) { receiver_.OnAltSvc(stream_id, origin, altsvc_vector); } } void EventForwarder::OnPriority(spdy::SpdyStreamId stream_id, spdy::SpdyStreamId parent_stream_id, int weight, bool exclusive) { if (can_forward_()) { receiver_.OnPriority(stream_id, parent_stream_id, weight, exclusive); } } void EventForwarder::OnPriorityUpdate(spdy::SpdyStreamId prioritized_stream_id, absl::string_view priority_field_value) { if (can_forward_()) { receiver_.OnPriorityUpdate(prioritized_stream_id, priority_field_value); } } bool EventForwarder::OnUnknownFrame(spdy::SpdyStreamId stream_id, uint8_t frame_type) { if (can_forward_()) { return receiver_.OnUnknownFrame(stream_id, frame_type); } return false; } void EventForwarder::OnUnknownFrameStart(spdy::SpdyStreamId stream_id, size_t length, uint8_t type, uint8_t flags) { if (can_forward_()) { receiver_.OnUnknownFrameStart(stream_id, length, type, flags); } } void EventForwarder::OnUnknownFramePayload(spdy::SpdyStreamId stream_id, absl::string_view payload) { if (can_forward_()) { receiver_.OnUnknownFramePayload(stream_id, payload); } } } }
#include "quiche/http2/adapter/event_forwarder.h" #include <string> #include "absl/strings/string_view.h" #include "quiche/http2/adapter/http2_protocol.h" #include "quiche/http2/core/spdy_protocol.h" #include "quiche/http2/test_tools/mock_spdy_framer_visitor.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace adapter { namespace test { namespace { constexpr absl::string_view some_data = "Here is some data for events"; constexpr spdy::SpdyStreamId stream_id = 1; constexpr spdy::SpdyErrorCode error_code = spdy::SpdyErrorCode::ERROR_CODE_ENHANCE_YOUR_CALM; constexpr size_t length = 42; TEST(EventForwarderTest, ForwardsEventsWithTruePredicate) { spdy::test::MockSpdyFramerVisitor receiver; receiver.DelegateHeaderHandling(); EventForwarder event_forwarder([]() { return true; }, receiver); EXPECT_CALL( receiver, OnError(Http2DecoderAdapter::SpdyFramerError::SPDY_STOP_PROCESSING, std::string(some_data))); event_forwarder.OnError( Http2DecoderAdapter::SpdyFramerError::SPDY_STOP_PROCESSING, std::string(some_data)); EXPECT_CALL(receiver, OnCommonHeader(stream_id, length, 0x0, END_STREAM_FLAG)); event_forwarder.OnCommonHeader(stream_id, length, 0x0, END_STREAM_FLAG); EXPECT_CALL(receiver, OnDataFrameHeader(stream_id, length, true)); event_forwarder.OnDataFrameHeader(stream_id, length, true); EXPECT_CALL(receiver, OnStreamFrameData(stream_id, some_data.data(), some_data.size())); event_forwarder.OnStreamFrameData(stream_id, some_data.data(), some_data.size()); EXPECT_CALL(receiver, OnStreamEnd(stream_id)); event_forwarder.OnStreamEnd(stream_id); EXPECT_CALL(receiver, OnStreamPadLength(stream_id, length)); event_forwarder.OnStreamPadLength(stream_id, length); EXPECT_CALL(receiver, OnStreamPadding(stream_id, length)); event_forwarder.OnStreamPadding(stream_id, length); EXPECT_CALL(receiver, OnHeaderFrameStart(stream_id)); spdy::SpdyHeadersHandlerInterface* handler = event_forwarder.OnHeaderFrameStart(stream_id); EXPECT_EQ(handler, receiver.ReturnTestHeadersHandler(stream_id)); EXPECT_CALL(receiver, OnHeaderFrameEnd(stream_id)); event_forwarder.OnHeaderFrameEnd(stream_id); EXPECT_CALL(receiver, OnRstStream(stream_id, error_code)); event_forwarder.OnRstStream(stream_id, error_code); EXPECT_CALL(receiver, OnSettings()); event_forwarder.OnSettings(); EXPECT_CALL( receiver, OnSetting(spdy::SpdyKnownSettingsId::SETTINGS_MAX_CONCURRENT_STREAMS, 100)); event_forwarder.OnSetting( spdy::SpdyKnownSettingsId::SETTINGS_MAX_CONCURRENT_STREAMS, 100); EXPECT_CALL(receiver, OnSettingsEnd()); event_forwarder.OnSettingsEnd(); EXPECT_CALL(receiver, OnSettingsAck()); event_forwarder.OnSettingsAck(); EXPECT_CALL(receiver, OnPing(42, false)); event_forwarder.OnPing(42, false); EXPECT_CALL(receiver, OnGoAway(stream_id, error_code)); event_forwarder.OnGoAway(stream_id, error_code); EXPECT_CALL(receiver, OnGoAwayFrameData(some_data.data(), some_data.size())); event_forwarder.OnGoAwayFrameData(some_data.data(), some_data.size()); EXPECT_CALL(receiver, OnHeaders(stream_id, 1234, false, 42, stream_id + 2, false, true, true)); event_forwarder.OnHeaders(stream_id, 1234, false, 42, stream_id + 2, false, true, true); EXPECT_CALL(receiver, OnWindowUpdate(stream_id, 42)); event_forwarder.OnWindowUpdate(stream_id, 42); EXPECT_CALL(receiver, OnPushPromise(stream_id, stream_id + 1, true)); event_forwarder.OnPushPromise(stream_id, stream_id + 1, true); EXPECT_CALL(receiver, OnContinuation(stream_id, 42, true)); event_forwarder.OnContinuation(stream_id, 42, true); const spdy::SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; EXPECT_CALL(receiver, OnAltSvc(stream_id, some_data, altsvc_vector)); event_forwarder.OnAltSvc(stream_id, some_data, altsvc_vector); EXPECT_CALL(receiver, OnPriority(stream_id, stream_id + 2, 42, false)); event_forwarder.OnPriority(stream_id, stream_id + 2, 42, false); EXPECT_CALL(receiver, OnPriorityUpdate(stream_id, some_data)); event_forwarder.OnPriorityUpdate(stream_id, some_data); EXPECT_CALL(receiver, OnUnknownFrame(stream_id, 0x4D)); event_forwarder.OnUnknownFrame(stream_id, 0x4D); EXPECT_CALL(receiver, OnUnknownFrameStart(stream_id, 42, 0x4D, 0x0)); event_forwarder.OnUnknownFrameStart(stream_id, 42, 0x4D, 0x0); } TEST(EventForwarderTest, DoesNotForwardEventsWithFalsePredicate) { spdy::test::MockSpdyFramerVisitor receiver; receiver.DelegateHeaderHandling(); EventForwarder event_forwarder([]() { return false; }, receiver); EXPECT_CALL(receiver, OnError).Times(0); event_forwarder.OnError( Http2DecoderAdapter::SpdyFramerError::SPDY_STOP_PROCESSING, std::string(some_data)); EXPECT_CALL(receiver, OnCommonHeader).Times(0); event_forwarder.OnCommonHeader(stream_id, length, 0x0, END_STREAM_FLAG); EXPECT_CALL(receiver, OnDataFrameHeader).Times(0); event_forwarder.OnDataFrameHeader(stream_id, length, true); EXPECT_CALL(receiver, OnStreamFrameData).Times(0); event_forwarder.OnStreamFrameData(stream_id, some_data.data(), some_data.size()); EXPECT_CALL(receiver, OnStreamEnd).Times(0); event_forwarder.OnStreamEnd(stream_id); EXPECT_CALL(receiver, OnStreamPadLength).Times(0); event_forwarder.OnStreamPadLength(stream_id, length); EXPECT_CALL(receiver, OnStreamPadding).Times(0); event_forwarder.OnStreamPadding(stream_id, length); EXPECT_CALL(receiver, OnHeaderFrameStart(stream_id)); spdy::SpdyHeadersHandlerInterface* handler = event_forwarder.OnHeaderFrameStart(stream_id); EXPECT_EQ(handler, receiver.ReturnTestHeadersHandler(stream_id)); EXPECT_CALL(receiver, OnHeaderFrameEnd).Times(0); event_forwarder.OnHeaderFrameEnd(stream_id); EXPECT_CALL(receiver, OnRstStream).Times(0); event_forwarder.OnRstStream(stream_id, error_code); EXPECT_CALL(receiver, OnSettings).Times(0); event_forwarder.OnSettings(); EXPECT_CALL(receiver, OnSetting).Times(0); event_forwarder.OnSetting( spdy::SpdyKnownSettingsId::SETTINGS_MAX_CONCURRENT_STREAMS, 100); EXPECT_CALL(receiver, OnSettingsEnd).Times(0); event_forwarder.OnSettingsEnd(); EXPECT_CALL(receiver, OnSettingsAck).Times(0); event_forwarder.OnSettingsAck(); EXPECT_CALL(receiver, OnPing).Times(0); event_forwarder.OnPing(42, false); EXPECT_CALL(receiver, OnGoAway).Times(0); event_forwarder.OnGoAway(stream_id, error_code); EXPECT_CALL(receiver, OnGoAwayFrameData).Times(0); event_forwarder.OnGoAwayFrameData(some_data.data(), some_data.size()); EXPECT_CALL(receiver, OnHeaders).Times(0); event_forwarder.OnHeaders(stream_id, 1234, false, 42, stream_id + 2, false, true, true); EXPECT_CALL(receiver, OnWindowUpdate).Times(0); event_forwarder.OnWindowUpdate(stream_id, 42); EXPECT_CALL(receiver, OnPushPromise).Times(0); event_forwarder.OnPushPromise(stream_id, stream_id + 1, true); EXPECT_CALL(receiver, OnContinuation).Times(0); event_forwarder.OnContinuation(stream_id, 42, true); EXPECT_CALL(receiver, OnAltSvc).Times(0); const spdy::SpdyAltSvcWireFormat::AlternativeServiceVector altsvc_vector; event_forwarder.OnAltSvc(stream_id, some_data, altsvc_vector); EXPECT_CALL(receiver, OnPriority).Times(0); event_forwarder.OnPriority(stream_id, stream_id + 2, 42, false); EXPECT_CALL(receiver, OnPriorityUpdate).Times(0); event_forwarder.OnPriorityUpdate(stream_id, some_data); EXPECT_CALL(receiver, OnUnknownFrame).Times(0); event_forwarder.OnUnknownFrame(stream_id, 0x4D); EXPECT_CALL(receiver, OnUnknownFrameStart).Times(0); event_forwarder.OnUnknownFrameStart(stream_id, 42, 0x4D, 0x0); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/event_forwarder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/event_forwarder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
e0bef799-486b-47a4-b7eb-edab0c90a13d
cpp
google/quiche
callback_visitor
quiche/http2/adapter/callback_visitor.cc
quiche/http2/adapter/callback_visitor_test.cc
#include "quiche/http2/adapter/callback_visitor.h" #include <cstring> #include "absl/strings/escaping.h" #include "quiche/http2/adapter/http2_util.h" #include "quiche/http2/adapter/nghttp2.h" #include "quiche/http2/adapter/nghttp2_util.h" #include "quiche/common/quiche_endian.h" #ifdef NGHTTP2_16 namespace { using FunctionPtr = void (*)(void); } struct nghttp2_session_callbacks { nghttp2_send_callback send_callback; FunctionPtr send_callback2; nghttp2_recv_callback recv_callback; FunctionPtr recv_callback2; nghttp2_on_frame_recv_callback on_frame_recv_callback; nghttp2_on_invalid_frame_recv_callback on_invalid_frame_recv_callback; nghttp2_on_data_chunk_recv_callback on_data_chunk_recv_callback; nghttp2_before_frame_send_callback before_frame_send_callback; nghttp2_on_frame_send_callback on_frame_send_callback; nghttp2_on_frame_not_send_callback on_frame_not_send_callback; nghttp2_on_stream_close_callback on_stream_close_callback; nghttp2_on_begin_headers_callback on_begin_headers_callback; nghttp2_on_header_callback on_header_callback; nghttp2_on_header_callback2 on_header_callback2; nghttp2_on_invalid_header_callback on_invalid_header_callback; nghttp2_on_invalid_header_callback2 on_invalid_header_callback2; nghttp2_select_padding_callback select_padding_callback; FunctionPtr select_padding_callback2; nghttp2_data_source_read_length_callback read_length_callback; FunctionPtr read_length_callback2; nghttp2_on_begin_frame_callback on_begin_frame_callback; nghttp2_send_data_callback send_data_callback; nghttp2_pack_extension_callback pack_extension_callback; FunctionPtr pack_extension_callback2; nghttp2_unpack_extension_callback unpack_extension_callback; nghttp2_on_extension_chunk_recv_callback on_extension_chunk_recv_callback; nghttp2_error_callback error_callback; nghttp2_error_callback2 error_callback2; }; #else struct nghttp2_session_callbacks { nghttp2_send_callback send_callback; nghttp2_recv_callback recv_callback; nghttp2_on_frame_recv_callback on_frame_recv_callback; nghttp2_on_invalid_frame_recv_callback on_invalid_frame_recv_callback; nghttp2_on_data_chunk_recv_callback on_data_chunk_recv_callback; nghttp2_before_frame_send_callback before_frame_send_callback; nghttp2_on_frame_send_callback on_frame_send_callback; nghttp2_on_frame_not_send_callback on_frame_not_send_callback; nghttp2_on_stream_close_callback on_stream_close_callback; nghttp2_on_begin_headers_callback on_begin_headers_callback; nghttp2_on_header_callback on_header_callback; nghttp2_on_header_callback2 on_header_callback2; nghttp2_on_invalid_header_callback on_invalid_header_callback; nghttp2_on_invalid_header_callback2 on_invalid_header_callback2; nghttp2_select_padding_callback select_padding_callback; nghttp2_data_source_read_length_callback read_length_callback; nghttp2_on_begin_frame_callback on_begin_frame_callback; nghttp2_send_data_callback send_data_callback; nghttp2_pack_extension_callback pack_extension_callback; nghttp2_unpack_extension_callback unpack_extension_callback; nghttp2_on_extension_chunk_recv_callback on_extension_chunk_recv_callback; nghttp2_error_callback error_callback; nghttp2_error_callback2 error_callback2; }; #endif namespace http2 { namespace adapter { CallbackVisitor::CallbackVisitor(Perspective perspective, const nghttp2_session_callbacks& callbacks, void* user_data) : perspective_(perspective), callbacks_(MakeCallbacksPtr(nullptr)), user_data_(user_data) { nghttp2_session_callbacks* c; nghttp2_session_callbacks_new(&c); *c = callbacks; callbacks_ = MakeCallbacksPtr(c); memset(&current_frame_, 0, sizeof(current_frame_)); } int64_t CallbackVisitor::OnReadyToSend(absl::string_view serialized) { if (!callbacks_->send_callback) { return kSendError; } int64_t result = callbacks_->send_callback( nullptr, ToUint8Ptr(serialized.data()), serialized.size(), 0, user_data_); QUICHE_VLOG(1) << "CallbackVisitor::OnReadyToSend called with " << serialized.size() << " bytes, returning " << result; QUICHE_VLOG(2) << (perspective_ == Perspective::kClient ? "Client" : "Server") << " sending: [" << absl::CEscape(serialized) << "]"; if (result > 0) { return result; } else if (result == NGHTTP2_ERR_WOULDBLOCK) { return kSendBlocked; } else { return kSendError; } } Http2VisitorInterface::DataFrameHeaderInfo CallbackVisitor::OnReadyToSendDataForStream(Http2StreamId , size_t ) { QUICHE_LOG(FATAL) << "Not implemented; should not be used with nghttp2 callbacks."; return {}; } bool CallbackVisitor::SendDataFrame(Http2StreamId , absl::string_view , size_t ) { QUICHE_LOG(FATAL) << "Not implemented; should not be used with nghttp2 callbacks."; return false; } void CallbackVisitor::OnConnectionError(ConnectionError ) { QUICHE_VLOG(1) << "OnConnectionError not implemented"; } bool CallbackVisitor::OnFrameHeader(Http2StreamId stream_id, size_t length, uint8_t type, uint8_t flags) { QUICHE_VLOG(1) << "CallbackVisitor::OnFrameHeader(stream_id=" << stream_id << ", type=" << int(type) << ", length=" << length << ", flags=" << int(flags) << ")"; if (static_cast<FrameType>(type) == FrameType::CONTINUATION) { if (static_cast<FrameType>(current_frame_.hd.type) != FrameType::HEADERS || current_frame_.hd.stream_id == 0 || current_frame_.hd.stream_id != stream_id) { return false; } current_frame_.hd.length += length; current_frame_.hd.flags |= flags; QUICHE_DLOG_IF(ERROR, length == 0) << "Empty CONTINUATION!"; nghttp2_frame_hd hd; memset(&hd, 0, sizeof(hd)); hd.stream_id = stream_id; hd.length = length; hd.type = type; hd.flags = flags; if (callbacks_->on_begin_frame_callback) { const int result = callbacks_->on_begin_frame_callback(nullptr, &hd, user_data_); return result == 0; } return true; } memset(&current_frame_, 0, sizeof(current_frame_)); current_frame_.hd.stream_id = stream_id; current_frame_.hd.length = length; current_frame_.hd.type = type; current_frame_.hd.flags = flags; if (callbacks_->on_begin_frame_callback) { const int result = callbacks_->on_begin_frame_callback( nullptr, &current_frame_.hd, user_data_); return result == 0; } return true; } void CallbackVisitor::OnSettingsStart() {} void CallbackVisitor::OnSetting(Http2Setting setting) { settings_.push_back({setting.id, setting.value}); } void CallbackVisitor::OnSettingsEnd() { current_frame_.settings.niv = settings_.size(); current_frame_.settings.iv = settings_.data(); QUICHE_VLOG(1) << "OnSettingsEnd, received settings of size " << current_frame_.settings.niv; if (callbacks_->on_frame_recv_callback) { const int result = callbacks_->on_frame_recv_callback( nullptr, &current_frame_, user_data_); QUICHE_DCHECK_EQ(0, result); } settings_.clear(); } void CallbackVisitor::OnSettingsAck() { QUICHE_VLOG(1) << "OnSettingsAck()"; if (callbacks_->on_frame_recv_callback) { const int result = callbacks_->on_frame_recv_callback( nullptr, &current_frame_, user_data_); QUICHE_DCHECK_EQ(0, result); } } bool CallbackVisitor::OnBeginHeadersForStream(Http2StreamId stream_id) { auto it = GetStreamInfo(stream_id); if (it == stream_map_.end()) { current_frame_.headers.cat = NGHTTP2_HCAT_HEADERS; } else { if (it->second.received_headers) { QUICHE_VLOG(1) << "Headers already received for stream " << stream_id << ", these are trailers or headers following a 100 response"; current_frame_.headers.cat = NGHTTP2_HCAT_HEADERS; } else { switch (perspective_) { case Perspective::kClient: QUICHE_VLOG(1) << "First headers at the client for stream " << stream_id << "; these are response headers"; current_frame_.headers.cat = NGHTTP2_HCAT_RESPONSE; break; case Perspective::kServer: QUICHE_VLOG(1) << "First headers at the server for stream " << stream_id << "; these are request headers"; current_frame_.headers.cat = NGHTTP2_HCAT_REQUEST; break; } } it->second.received_headers = true; } if (callbacks_->on_begin_headers_callback) { const int result = callbacks_->on_begin_headers_callback( nullptr, &current_frame_, user_data_); return result == 0; } return true; } Http2VisitorInterface::OnHeaderResult CallbackVisitor::OnHeaderForStream( Http2StreamId stream_id, absl::string_view name, absl::string_view value) { QUICHE_VLOG(2) << "OnHeaderForStream(stream_id=" << stream_id << ", name=[" << absl::CEscape(name) << "], value=[" << absl::CEscape(value) << "])"; if (callbacks_->on_header_callback) { const int result = callbacks_->on_header_callback( nullptr, &current_frame_, ToUint8Ptr(name.data()), name.size(), ToUint8Ptr(value.data()), value.size(), NGHTTP2_NV_FLAG_NONE, user_data_); if (result == 0) { return HEADER_OK; } else if (result == NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE) { return HEADER_RST_STREAM; } else { return HEADER_CONNECTION_ERROR; } } return HEADER_OK; } bool CallbackVisitor::OnEndHeadersForStream(Http2StreamId stream_id) { QUICHE_VLOG(1) << "OnEndHeadersForStream(stream_id=" << stream_id << ")"; if (callbacks_->on_frame_recv_callback) { const int result = callbacks_->on_frame_recv_callback( nullptr, &current_frame_, user_data_); return result == 0; } return true; } bool CallbackVisitor::OnDataPaddingLength(Http2StreamId , size_t padding_length) { current_frame_.data.padlen = padding_length; remaining_data_ -= padding_length; if (remaining_data_ == 0 && (current_frame_.hd.flags & NGHTTP2_FLAG_END_STREAM) == 0 && callbacks_->on_frame_recv_callback != nullptr) { const int result = callbacks_->on_frame_recv_callback( nullptr, &current_frame_, user_data_); return result == 0; } return true; } bool CallbackVisitor::OnBeginDataForStream(Http2StreamId , size_t payload_length) { remaining_data_ = payload_length; if (remaining_data_ == 0 && (current_frame_.hd.flags & NGHTTP2_FLAG_END_STREAM) == 0 && callbacks_->on_frame_recv_callback != nullptr) { const int result = callbacks_->on_frame_recv_callback( nullptr, &current_frame_, user_data_); return result == 0; } return true; } bool CallbackVisitor::OnDataForStream(Http2StreamId stream_id, absl::string_view data) { QUICHE_VLOG(1) << "OnDataForStream(stream_id=" << stream_id << ", data.size()=" << data.size() << ")"; int result = 0; if (callbacks_->on_data_chunk_recv_callback) { result = callbacks_->on_data_chunk_recv_callback( nullptr, current_frame_.hd.flags, stream_id, ToUint8Ptr(data.data()), data.size(), user_data_); } remaining_data_ -= data.size(); if (result == 0 && remaining_data_ == 0 && (current_frame_.hd.flags & NGHTTP2_FLAG_END_STREAM) == 0 && callbacks_->on_frame_recv_callback) { result = callbacks_->on_frame_recv_callback(nullptr, &current_frame_, user_data_); } return result == 0; } bool CallbackVisitor::OnEndStream(Http2StreamId stream_id) { QUICHE_VLOG(1) << "OnEndStream(stream_id=" << stream_id << ")"; int result = 0; if (static_cast<FrameType>(current_frame_.hd.type) == FrameType::DATA && (current_frame_.hd.flags & NGHTTP2_FLAG_END_STREAM) != 0 && callbacks_->on_frame_recv_callback) { result = callbacks_->on_frame_recv_callback(nullptr, &current_frame_, user_data_); } return result == 0; } void CallbackVisitor::OnRstStream(Http2StreamId stream_id, Http2ErrorCode error_code) { QUICHE_VLOG(1) << "OnRstStream(stream_id=" << stream_id << ", error_code=" << static_cast<int>(error_code) << ")"; current_frame_.rst_stream.error_code = static_cast<uint32_t>(error_code); if (callbacks_->on_frame_recv_callback) { const int result = callbacks_->on_frame_recv_callback( nullptr, &current_frame_, user_data_); QUICHE_DCHECK_EQ(0, result); } } bool CallbackVisitor::OnCloseStream(Http2StreamId stream_id, Http2ErrorCode error_code) { QUICHE_VLOG(1) << "OnCloseStream(stream_id=" << stream_id << ", error_code=" << static_cast<int>(error_code) << ")"; int result = 0; if (callbacks_->on_stream_close_callback) { result = callbacks_->on_stream_close_callback( nullptr, stream_id, static_cast<uint32_t>(error_code), user_data_); } stream_map_.erase(stream_id); if (stream_close_listener_) { stream_close_listener_(stream_id); } return result == 0; } void CallbackVisitor::OnPriorityForStream(Http2StreamId , Http2StreamId parent_stream_id, int weight, bool exclusive) { current_frame_.priority.pri_spec.stream_id = parent_stream_id; current_frame_.priority.pri_spec.weight = weight; current_frame_.priority.pri_spec.exclusive = exclusive; if (callbacks_->on_frame_recv_callback) { const int result = callbacks_->on_frame_recv_callback( nullptr, &current_frame_, user_data_); QUICHE_DCHECK_EQ(0, result); } } void CallbackVisitor::OnPing(Http2PingId ping_id, bool is_ack) { QUICHE_VLOG(1) << "OnPing(ping_id=" << static_cast<int64_t>(ping_id) << ", is_ack=" << is_ack << ")"; uint64_t network_order_opaque_data = quiche::QuicheEndian::HostToNet64(ping_id); std::memcpy(current_frame_.ping.opaque_data, &network_order_opaque_data, sizeof(network_order_opaque_data)); if (callbacks_->on_frame_recv_callback) { const int result = callbacks_->on_frame_recv_callback( nullptr, &current_frame_, user_data_); QUICHE_DCHECK_EQ(0, result); } } void CallbackVisitor::OnPushPromiseForStream( Http2StreamId , Http2StreamId ) { QUICHE_LOG(DFATAL) << "Not implemented"; } bool CallbackVisitor::OnGoAway(Http2StreamId last_accepted_stream_id, Http2ErrorCode error_code, absl::string_view opaque_data) { QUICHE_VLOG(1) << "OnGoAway(last_accepted_stream_id=" << last_accepted_stream_id << ", error_code=" << static_cast<int>(error_code) << ", opaque_data=[" << absl::CEscape(opaque_data) << "])"; current_frame_.goaway.last_stream_id = last_accepted_stream_id; current_frame_.goaway.error_code = static_cast<uint32_t>(error_code); current_frame_.goaway.opaque_data = ToUint8Ptr(opaque_data.data()); current_frame_.goaway.opaque_data_len = opaque_data.size(); if (callbacks_->on_frame_recv_callback) { const int result = callbacks_->on_frame_recv_callback( nullptr, &current_frame_, user_data_); return result == 0; } return true; } void CallbackVisitor::OnWindowUpdate(Http2StreamId stream_id, int window_increment) { QUICHE_VLOG(1) << "OnWindowUpdate(stream_id=" << stream_id << ", delta=" << window_increment << ")"; current_frame_.window_update.window_size_increment = window_increment; if (callbacks_->on_frame_recv_callback) { const int result = callbacks_->on_frame_recv_callback( nullptr, &current_frame_, user_data_); QUICHE_DCHECK_EQ(0, result); } } void CallbackVisitor::PopulateFrame(nghttp2_frame& frame, uint8_t frame_type, Http2StreamId stream_id, size_t length, uint8_t flags, uint32_t error_code, bool sent_headers) { frame.hd.type = frame_type; frame.hd.stream_id = stream_id; frame.hd.length = length; frame.hd.flags = flags; const FrameType frame_type_enum = static_cast<FrameType>(frame_type); if (frame_type_enum == FrameType::HEADERS) { if (sent_headers) { frame.headers.cat = NGHTTP2_HCAT_HEADERS; } else { switch (perspective_) { case Perspective::kClient: QUICHE_VLOG(1) << "First headers sent by the client for stream " << stream_id << "; these are request headers"; frame.headers.cat = NGHTTP2_HCAT_REQUEST; break; case Perspective::kServer: QUICHE_VLOG(1) << "First headers sent by the server for stream " << stream_id << "; these are response headers"; frame.headers.cat = NGHTTP2_HCAT_RESPONSE; break; } } } else if (frame_type_enum == FrameType::RST_STREAM) { frame.rst_stream.error_code = error_code; } else if (frame_type_enum == FrameType::GOAWAY) { frame.goaway.error_code = error_code; } } int CallbackVisitor::OnBeforeFrameSent(uint8_t frame_type, Http2StreamId stream_id, size_t length, uint8_t flags) { QUICHE_VLOG(1) << "OnBeforeFrameSent(stream_id=" << stream_id << ", type=" << int(frame_type) << ", length=" << length << ", flags=" << int(flags) << ")"; if (callbacks_->before_frame_send_callback) { nghttp2_frame frame; bool before_sent_headers = true; auto it = GetStreamInfo(stream_id); if (it != stream_map_.end()) { before_sent_headers = it->second.before_sent_headers; it->second.before_sent_headers = true; } PopulateFrame(frame, frame_type, stream_id, length, flags, 0, before_sent_headers); return callbacks_->before_frame_send_callback(nullptr, &frame, user_data_); } return 0; } int CallbackVisitor::OnFrameSent(uint8_t frame_type, Http2StreamId stream_id, size_t length, uint8_t flags, uint32_t error_code) { QUICHE_VLOG(1) << "OnFrameSent(stream_id=" << stream_id << ", type=" << int(frame_type) << ", length=" << length << ", flags=" << int(flags) << ", error_code=" << error_code << ")"; if (callbacks_->on_frame_send_callback) { nghttp2_frame frame; bool sent_headers = true; auto it = GetStreamInfo(stream_id); if (it != stream_map_.end()) { sent_headers = it->second.sent_headers; it->second.sent_headers = true; } PopulateFrame(frame, frame_type, stream_id, length, flags, error_code, sent_headers); return callbacks_->on_frame_send_callback(nullptr, &frame, user_data_); } return 0; } bool CallbackVisitor::OnInvalidFrame(Http2StreamId stream_id, InvalidFrameError error) { QUICHE_VLOG(1) << "OnInvalidFrame(" << stream_id << ", " << InvalidFrameErrorToString(error) << ")"; QUICHE_DCHECK_EQ(stream_id, current_frame_.hd.stream_id); if (callbacks_->on_invalid_frame_recv_callback) { return 0 == callbacks_->on_invalid_frame_recv_callback( nullptr, &current_frame_, ToNgHttp2ErrorCode(error), user_data_); } return true; } void CallbackVisitor::OnBeginMetadataForStream(Http2StreamId stream_id, size_t payload_length) { QUICHE_VLOG(1) << "OnBeginMetadataForStream(stream_id=" << stream_id << ", payload_length=" << payload_length << ")"; } bool CallbackVisitor::OnMetadataForStream(Http2StreamId stream_id, absl::string_view metadata) { QUICHE_VLOG(1) << "OnMetadataForStream(stream_id=" << stream_id << ", len=" << metadata.size() << ")"; if (callbacks_->on_extension_chunk_recv_callback) { int result = callbacks_->on_extension_chunk_recv_callback( nullptr, &current_frame_.hd, ToUint8Ptr(metadata.data()), metadata.size(), user_data_); return result == 0; } return true; } bool CallbackVisitor::OnMetadataEndForStream(Http2StreamId stream_id) { if ((current_frame_.hd.flags & kMetadataEndFlag) == 0) { QUICHE_VLOG(1) << "Expected kMetadataEndFlag during call to " << "OnMetadataEndForStream!"; return true; } QUICHE_VLOG(1) << "OnMetadataEndForStream(stream_id=" << stream_id << ")"; if (callbacks_->unpack_extension_callback) { void* payload; int result = callbacks_->unpack_extension_callback( nullptr, &payload, &current_frame_.hd, user_data_); if (result == 0 && callbacks_->on_frame_recv_callback) { current_frame_.ext.payload = payload; result = callbacks_->on_frame_recv_callback(nullptr, &current_frame_, user_data_); } return (result == 0); } return true; } std::pair<int64_t, bool> CallbackVisitor::PackMetadataForStream( Http2StreamId , uint8_t* , size_t ) { QUICHE_LOG(DFATAL) << "Unimplemented."; return {-1, false}; } void CallbackVisitor::OnErrorDebug(absl::string_view message) { QUICHE_VLOG(1) << "OnErrorDebug(message=[" << absl::CEscape(message) << "])"; if (callbacks_->error_callback2) { callbacks_->error_callback2(nullptr, -1, message.data(), message.size(), user_data_); } } CallbackVisitor::StreamInfoMap::iterator CallbackVisitor::GetStreamInfo( Http2StreamId stream_id) { auto it = stream_map_.find(stream_id); if (it == stream_map_.end() && stream_id > stream_id_watermark_) { auto p = stream_map_.insert({stream_id, {}}); it = p.first; stream_id_watermark_ = stream_id; } return it; } } }
#include "quiche/http2/adapter/callback_visitor.h" #include <string> #include "absl/container/flat_hash_map.h" #include "quiche/http2/adapter/http2_protocol.h" #include "quiche/http2/adapter/mock_nghttp2_callbacks.h" #include "quiche/http2/adapter/nghttp2_adapter.h" #include "quiche/http2/adapter/nghttp2_test_utils.h" #include "quiche/http2/adapter/test_frame_sequence.h" #include "quiche/http2/adapter/test_utils.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace adapter { namespace test { namespace { using testing::_; using testing::IsEmpty; using testing::Pair; using testing::UnorderedElementsAre; enum FrameType { DATA, HEADERS, PRIORITY, RST_STREAM, SETTINGS, PUSH_PROMISE, PING, GOAWAY, WINDOW_UPDATE, CONTINUATION, }; TEST(ClientCallbackVisitorUnitTest, ConnectionFrames) { testing::StrictMock<MockNghttp2Callbacks> callbacks; CallbackVisitor visitor(Perspective::kClient, *MockNghttp2Callbacks::GetCallbacks(), &callbacks); testing::InSequence seq; EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(0, SETTINGS, _))); visitor.OnFrameHeader(0, 0, SETTINGS, 0); visitor.OnSettingsStart(); EXPECT_CALL(callbacks, OnFrameRecv(IsSettings(testing::IsEmpty()))); visitor.OnSettingsEnd(); EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(0, PING, _))); visitor.OnFrameHeader(0, 8, PING, 0); EXPECT_CALL(callbacks, OnFrameRecv(IsPing(42))); visitor.OnPing(42, false); EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(0, WINDOW_UPDATE, _))); visitor.OnFrameHeader(0, 4, WINDOW_UPDATE, 0); EXPECT_CALL(callbacks, OnFrameRecv(IsWindowUpdate(1000))); visitor.OnWindowUpdate(0, 1000); EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(0, PING, NGHTTP2_FLAG_ACK))); visitor.OnFrameHeader(0, 8, PING, 1); EXPECT_CALL(callbacks, OnFrameRecv(IsPingAck(247))); visitor.OnPing(247, true); EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(0, GOAWAY, 0))); visitor.OnFrameHeader(0, 19, GOAWAY, 0); EXPECT_CALL(callbacks, OnFrameRecv(IsGoAway(5, NGHTTP2_ENHANCE_YOUR_CALM, "calm down!!"))); visitor.OnGoAway(5, Http2ErrorCode::ENHANCE_YOUR_CALM, "calm down!!"); EXPECT_EQ(visitor.stream_map_size(), 0); } TEST(ClientCallbackVisitorUnitTest, StreamFrames) { testing::StrictMock<MockNghttp2Callbacks> callbacks; CallbackVisitor visitor(Perspective::kClient, *MockNghttp2Callbacks::GetCallbacks(), &callbacks); absl::flat_hash_map<Http2StreamId, int> stream_close_counts; visitor.set_stream_close_listener( [&stream_close_counts](Http2StreamId stream_id) { ++stream_close_counts[stream_id]; }); testing::InSequence seq; EXPECT_EQ(visitor.stream_map_size(), 0); EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(1, HEADERS, _))); visitor.OnFrameHeader(1, 23, HEADERS, 4); EXPECT_CALL(callbacks, OnBeginHeaders(IsHeaders(1, _, NGHTTP2_HCAT_RESPONSE))); visitor.OnBeginHeadersForStream(1); EXPECT_EQ(visitor.stream_map_size(), 1); EXPECT_CALL(callbacks, OnHeader(_, ":status", "200", _)); visitor.OnHeaderForStream(1, ":status", "200"); EXPECT_CALL(callbacks, OnHeader(_, "server", "my-fake-server", _)); visitor.OnHeaderForStream(1, "server", "my-fake-server"); EXPECT_CALL(callbacks, OnHeader(_, "date", "Tue, 6 Apr 2021 12:54:01 GMT", _)); visitor.OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT"); EXPECT_CALL(callbacks, OnHeader(_, "trailer", "x-server-status", _)); visitor.OnHeaderForStream(1, "trailer", "x-server-status"); EXPECT_CALL(callbacks, OnFrameRecv(IsHeaders(1, _, NGHTTP2_HCAT_RESPONSE))); visitor.OnEndHeadersForStream(1); EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(1, DATA, 0))); visitor.OnFrameHeader(1, 26, DATA, 0); visitor.OnBeginDataForStream(1, 26); EXPECT_CALL(callbacks, OnDataChunkRecv(0, 1, "This is the response body.")); EXPECT_CALL(callbacks, OnFrameRecv(IsData(1, _, 0))); visitor.OnDataForStream(1, "This is the response body."); EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(1, HEADERS, _))); visitor.OnFrameHeader(1, 23, HEADERS, 4); EXPECT_CALL(callbacks, OnBeginHeaders(IsHeaders(1, _, NGHTTP2_HCAT_HEADERS))); visitor.OnBeginHeadersForStream(1); EXPECT_CALL(callbacks, OnHeader(_, "x-server-status", "OK", _)); visitor.OnHeaderForStream(1, "x-server-status", "OK"); EXPECT_CALL(callbacks, OnFrameRecv(IsHeaders(1, _, NGHTTP2_HCAT_HEADERS))); visitor.OnEndHeadersForStream(1); EXPECT_THAT(stream_close_counts, IsEmpty()); EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(3, RST_STREAM, 0))); visitor.OnFrameHeader(3, 4, RST_STREAM, 0); EXPECT_EQ(visitor.stream_map_size(), 1); EXPECT_THAT(stream_close_counts, IsEmpty()); EXPECT_CALL(callbacks, OnFrameRecv(IsRstStream(3, NGHTTP2_INTERNAL_ERROR))); visitor.OnRstStream(3, Http2ErrorCode::INTERNAL_ERROR); EXPECT_CALL(callbacks, OnStreamClose(3, NGHTTP2_INTERNAL_ERROR)); visitor.OnCloseStream(3, Http2ErrorCode::INTERNAL_ERROR); EXPECT_THAT(stream_close_counts, UnorderedElementsAre(Pair(3, 1))); EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(1, DATA, NGHTTP2_FLAG_END_STREAM))); visitor.OnFrameHeader(1, 0, DATA, 1); EXPECT_CALL(callbacks, OnFrameRecv(IsData(1, _, NGHTTP2_FLAG_END_STREAM))); visitor.OnBeginDataForStream(1, 0); EXPECT_TRUE(visitor.OnEndStream(1)); EXPECT_CALL(callbacks, OnStreamClose(1, NGHTTP2_NO_ERROR)); visitor.OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR); EXPECT_EQ(visitor.stream_map_size(), 0); EXPECT_THAT(stream_close_counts, UnorderedElementsAre(Pair(3, 1), Pair(1, 1))); EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(5, RST_STREAM, _))); visitor.OnFrameHeader(5, 4, RST_STREAM, 0); EXPECT_CALL(callbacks, OnFrameRecv(IsRstStream(5, NGHTTP2_REFUSED_STREAM))); visitor.OnRstStream(5, Http2ErrorCode::REFUSED_STREAM); EXPECT_CALL(callbacks, OnStreamClose(5, NGHTTP2_REFUSED_STREAM)); visitor.OnCloseStream(5, Http2ErrorCode::REFUSED_STREAM); EXPECT_EQ(visitor.stream_map_size(), 0); EXPECT_THAT(stream_close_counts, UnorderedElementsAre(Pair(3, 1), Pair(1, 1), Pair(5, 1))); } TEST(ClientCallbackVisitorUnitTest, HeadersWithContinuation) { testing::StrictMock<MockNghttp2Callbacks> callbacks; CallbackVisitor visitor(Perspective::kClient, *MockNghttp2Callbacks::GetCallbacks(), &callbacks); testing::InSequence seq; EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(1, HEADERS, 0x0))); ASSERT_TRUE(visitor.OnFrameHeader(1, 23, HEADERS, 0x0)); EXPECT_CALL(callbacks, OnBeginHeaders(IsHeaders(1, _, NGHTTP2_HCAT_RESPONSE))); visitor.OnBeginHeadersForStream(1); EXPECT_CALL(callbacks, OnHeader(_, ":status", "200", _)); visitor.OnHeaderForStream(1, ":status", "200"); EXPECT_CALL(callbacks, OnHeader(_, "server", "my-fake-server", _)); visitor.OnHeaderForStream(1, "server", "my-fake-server"); EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(1, CONTINUATION, END_HEADERS_FLAG))); ASSERT_TRUE(visitor.OnFrameHeader(1, 23, CONTINUATION, END_HEADERS_FLAG)); EXPECT_CALL(callbacks, OnHeader(_, "date", "Tue, 6 Apr 2021 12:54:01 GMT", _)); visitor.OnHeaderForStream(1, "date", "Tue, 6 Apr 2021 12:54:01 GMT"); EXPECT_CALL(callbacks, OnHeader(_, "trailer", "x-server-status", _)); visitor.OnHeaderForStream(1, "trailer", "x-server-status"); EXPECT_CALL(callbacks, OnFrameRecv(IsHeaders(1, _, NGHTTP2_HCAT_RESPONSE))); visitor.OnEndHeadersForStream(1); } TEST(ClientCallbackVisitorUnitTest, ContinuationNoHeaders) { testing::StrictMock<MockNghttp2Callbacks> callbacks; CallbackVisitor visitor(Perspective::kClient, *MockNghttp2Callbacks::GetCallbacks(), &callbacks); EXPECT_FALSE(visitor.OnFrameHeader(1, 23, CONTINUATION, END_HEADERS_FLAG)); } TEST(ClientCallbackVisitorUnitTest, ContinuationWrongPrecedingType) { testing::StrictMock<MockNghttp2Callbacks> callbacks; CallbackVisitor visitor(Perspective::kClient, *MockNghttp2Callbacks::GetCallbacks(), &callbacks); EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(1, WINDOW_UPDATE, _))); visitor.OnFrameHeader(1, 4, WINDOW_UPDATE, 0); EXPECT_FALSE(visitor.OnFrameHeader(1, 23, CONTINUATION, END_HEADERS_FLAG)); } TEST(ClientCallbackVisitorUnitTest, ContinuationWrongStream) { testing::StrictMock<MockNghttp2Callbacks> callbacks; CallbackVisitor visitor(Perspective::kClient, *MockNghttp2Callbacks::GetCallbacks(), &callbacks); EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(1, HEADERS, 0x0))); ASSERT_TRUE(visitor.OnFrameHeader(1, 23, HEADERS, 0x0)); EXPECT_CALL(callbacks, OnBeginHeaders(IsHeaders(1, _, NGHTTP2_HCAT_RESPONSE))); visitor.OnBeginHeadersForStream(1); EXPECT_CALL(callbacks, OnHeader(_, ":status", "200", _)); visitor.OnHeaderForStream(1, ":status", "200"); EXPECT_CALL(callbacks, OnHeader(_, "server", "my-fake-server", _)); visitor.OnHeaderForStream(1, "server", "my-fake-server"); EXPECT_FALSE(visitor.OnFrameHeader(3, 23, CONTINUATION, END_HEADERS_FLAG)); } TEST(ClientCallbackVisitorUnitTest, ResetAndGoaway) { testing::StrictMock<MockNghttp2Callbacks> callbacks; CallbackVisitor visitor(Perspective::kClient, *MockNghttp2Callbacks::GetCallbacks(), &callbacks); testing::InSequence seq; EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(1, RST_STREAM, 0x0))); EXPECT_TRUE(visitor.OnFrameHeader(1, 13, RST_STREAM, 0x0)); EXPECT_CALL(callbacks, OnFrameRecv(IsRstStream(1, NGHTTP2_INTERNAL_ERROR))); visitor.OnRstStream(1, Http2ErrorCode::INTERNAL_ERROR); EXPECT_CALL(callbacks, OnStreamClose(1, NGHTTP2_INTERNAL_ERROR)); EXPECT_TRUE(visitor.OnCloseStream(1, Http2ErrorCode::INTERNAL_ERROR)); EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(0, GOAWAY, 0x0))); EXPECT_TRUE(visitor.OnFrameHeader(0, 13, GOAWAY, 0x0)); EXPECT_CALL(callbacks, OnFrameRecv(IsGoAway(3, NGHTTP2_ENHANCE_YOUR_CALM, "calma te"))); EXPECT_TRUE( visitor.OnGoAway(3, Http2ErrorCode::ENHANCE_YOUR_CALM, "calma te")); EXPECT_CALL(callbacks, OnStreamClose(5, NGHTTP2_STREAM_CLOSED)) .WillOnce(testing::Return(NGHTTP2_ERR_CALLBACK_FAILURE)); EXPECT_FALSE(visitor.OnCloseStream(5, Http2ErrorCode::STREAM_CLOSED)); } TEST(ServerCallbackVisitorUnitTest, ConnectionFrames) { testing::StrictMock<MockNghttp2Callbacks> callbacks; CallbackVisitor visitor(Perspective::kServer, *MockNghttp2Callbacks::GetCallbacks(), &callbacks); testing::InSequence seq; EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(0, SETTINGS, _))); visitor.OnFrameHeader(0, 0, SETTINGS, 0); visitor.OnSettingsStart(); EXPECT_CALL(callbacks, OnFrameRecv(IsSettings(testing::IsEmpty()))); visitor.OnSettingsEnd(); EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(0, PING, _))); visitor.OnFrameHeader(0, 8, PING, 0); EXPECT_CALL(callbacks, OnFrameRecv(IsPing(42))); visitor.OnPing(42, false); EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(0, WINDOW_UPDATE, _))); visitor.OnFrameHeader(0, 4, WINDOW_UPDATE, 0); EXPECT_CALL(callbacks, OnFrameRecv(IsWindowUpdate(1000))); visitor.OnWindowUpdate(0, 1000); EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(0, PING, NGHTTP2_FLAG_ACK))); visitor.OnFrameHeader(0, 8, PING, 1); EXPECT_CALL(callbacks, OnFrameRecv(IsPingAck(247))); visitor.OnPing(247, true); EXPECT_EQ(visitor.stream_map_size(), 0); } TEST(ServerCallbackVisitorUnitTest, StreamFrames) { testing::StrictMock<MockNghttp2Callbacks> callbacks; CallbackVisitor visitor(Perspective::kServer, *MockNghttp2Callbacks::GetCallbacks(), &callbacks); testing::InSequence seq; EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader( 1, HEADERS, NGHTTP2_FLAG_END_HEADERS))); visitor.OnFrameHeader(1, 23, HEADERS, 4); EXPECT_CALL(callbacks, OnBeginHeaders(IsHeaders(1, NGHTTP2_FLAG_END_HEADERS, NGHTTP2_HCAT_REQUEST))); visitor.OnBeginHeadersForStream(1); EXPECT_EQ(visitor.stream_map_size(), 1); EXPECT_CALL(callbacks, OnHeader(_, ":method", "POST", _)); visitor.OnHeaderForStream(1, ":method", "POST"); EXPECT_CALL(callbacks, OnHeader(_, ":path", "/example/path", _)); visitor.OnHeaderForStream(1, ":path", "/example/path"); EXPECT_CALL(callbacks, OnHeader(_, ":scheme", "https", _)); visitor.OnHeaderForStream(1, ":scheme", "https"); EXPECT_CALL(callbacks, OnHeader(_, ":authority", "example.com", _)); visitor.OnHeaderForStream(1, ":authority", "example.com"); EXPECT_CALL(callbacks, OnHeader(_, "accept", "text/html", _)); visitor.OnHeaderForStream(1, "accept", "text/html"); EXPECT_CALL(callbacks, OnFrameRecv(IsHeaders(1, NGHTTP2_FLAG_END_HEADERS, NGHTTP2_HCAT_REQUEST))); visitor.OnEndHeadersForStream(1); EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(1, DATA, NGHTTP2_FLAG_END_STREAM))); visitor.OnFrameHeader(1, 25, DATA, NGHTTP2_FLAG_END_STREAM); visitor.OnBeginDataForStream(1, 25); EXPECT_CALL(callbacks, OnDataChunkRecv(NGHTTP2_FLAG_END_STREAM, 1, "This is the request body.")); EXPECT_CALL(callbacks, OnFrameRecv(IsData(1, _, NGHTTP2_FLAG_END_STREAM))); visitor.OnDataForStream(1, "This is the request body."); EXPECT_TRUE(visitor.OnEndStream(1)); EXPECT_CALL(callbacks, OnStreamClose(1, NGHTTP2_NO_ERROR)); visitor.OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR); EXPECT_EQ(visitor.stream_map_size(), 0); EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(3, RST_STREAM, 0))); visitor.OnFrameHeader(3, 4, RST_STREAM, 0); EXPECT_CALL(callbacks, OnFrameRecv(IsRstStream(3, NGHTTP2_INTERNAL_ERROR))); visitor.OnRstStream(3, Http2ErrorCode::INTERNAL_ERROR); EXPECT_CALL(callbacks, OnStreamClose(3, NGHTTP2_INTERNAL_ERROR)); visitor.OnCloseStream(3, Http2ErrorCode::INTERNAL_ERROR); EXPECT_EQ(visitor.stream_map_size(), 0); } TEST(ServerCallbackVisitorUnitTest, DataWithPadding) { testing::StrictMock<MockNghttp2Callbacks> callbacks; CallbackVisitor visitor(Perspective::kServer, *MockNghttp2Callbacks::GetCallbacks(), &callbacks); const size_t kPaddingLength = 39; const uint8_t kFlags = NGHTTP2_FLAG_PADDED | NGHTTP2_FLAG_END_STREAM; testing::InSequence seq; EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(1, DATA, kFlags))); EXPECT_TRUE(visitor.OnFrameHeader(1, 25 + kPaddingLength, DATA, kFlags)); EXPECT_TRUE(visitor.OnBeginDataForStream(1, 25 + kPaddingLength)); EXPECT_TRUE(visitor.OnDataPaddingLength(1, kPaddingLength)); EXPECT_CALL(callbacks, OnDataChunkRecv(kFlags, 1, "This is the request body.")); EXPECT_CALL(callbacks, OnFrameRecv(IsData(1, _, kFlags, kPaddingLength))); EXPECT_TRUE(visitor.OnDataForStream(1, "This is the request body.")); EXPECT_TRUE(visitor.OnEndStream(1)); EXPECT_CALL(callbacks, OnStreamClose(1, NGHTTP2_NO_ERROR)); visitor.OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR); EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(3, DATA, kFlags))); EXPECT_TRUE(visitor.OnFrameHeader(3, 25 + kPaddingLength, DATA, kFlags)); EXPECT_TRUE(visitor.OnBeginDataForStream(3, 25 + kPaddingLength)); EXPECT_CALL(callbacks, OnDataChunkRecv(kFlags, 3, "This is the request body.")); EXPECT_TRUE(visitor.OnDataForStream(3, "This is the request body.")); EXPECT_CALL(callbacks, OnFrameRecv(IsData(3, _, kFlags, kPaddingLength))); EXPECT_TRUE(visitor.OnDataPaddingLength(3, kPaddingLength)); EXPECT_TRUE(visitor.OnEndStream(3)); EXPECT_CALL(callbacks, OnStreamClose(3, NGHTTP2_NO_ERROR)); visitor.OnCloseStream(3, Http2ErrorCode::HTTP2_NO_ERROR); EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(5, DATA, kFlags))); EXPECT_TRUE(visitor.OnFrameHeader(5, 25 + kPaddingLength, DATA, kFlags)); EXPECT_TRUE(visitor.OnBeginDataForStream(5, 25 + kPaddingLength)); EXPECT_CALL(callbacks, OnDataChunkRecv(kFlags, 5, "This is the request body.")); EXPECT_TRUE(visitor.OnDataForStream(5, "This is the request body.")); EXPECT_CALL(callbacks, OnFrameRecv(IsData(5, _, kFlags, kPaddingLength))) .WillOnce(testing::Return(NGHTTP2_ERR_CALLBACK_FAILURE)); EXPECT_TRUE(visitor.OnDataPaddingLength(5, kPaddingLength)); EXPECT_FALSE(visitor.OnEndStream(3)); EXPECT_CALL(callbacks, OnStreamClose(5, NGHTTP2_NO_ERROR)); visitor.OnCloseStream(5, Http2ErrorCode::HTTP2_NO_ERROR); } TEST(ServerCallbackVisitorUnitTest, MismatchedContentLengthCallbacks) { testing::StrictMock<MockNghttp2Callbacks> callbacks; CallbackVisitor visitor(Perspective::kServer, *MockNghttp2Callbacks::GetCallbacks(), &callbacks); auto adapter = NgHttp2Adapter::CreateServerAdapter(visitor); const std::string frames = TestFrameSequence() .ClientPreface() .Headers(1, {{":method", "POST"}, {":scheme", "https"}, {":authority", "example.com"}, {":path", "/"}, {"content-length", "50"}}, false) .Data(1, "Less than 50 bytes.", true) .Serialize(); EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(0, SETTINGS, _))); EXPECT_CALL(callbacks, OnFrameRecv(IsSettings(testing::IsEmpty()))); EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader( 1, HEADERS, NGHTTP2_FLAG_END_HEADERS))); EXPECT_CALL(callbacks, OnBeginHeaders(IsHeaders(1, NGHTTP2_FLAG_END_HEADERS, NGHTTP2_HCAT_REQUEST))); EXPECT_CALL(callbacks, OnHeader(_, ":method", "POST", _)); EXPECT_CALL(callbacks, OnHeader(_, ":path", "/", _)); EXPECT_CALL(callbacks, OnHeader(_, ":scheme", "https", _)); EXPECT_CALL(callbacks, OnHeader(_, ":authority", "example.com", _)); EXPECT_CALL(callbacks, OnHeader(_, "content-length", "50", _)); EXPECT_CALL(callbacks, OnFrameRecv(IsHeaders(1, NGHTTP2_FLAG_END_HEADERS, NGHTTP2_HCAT_REQUEST))); EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader(1, DATA, NGHTTP2_FLAG_END_STREAM))); EXPECT_CALL(callbacks, OnDataChunkRecv(NGHTTP2_FLAG_END_STREAM, 1, "Less than 50 bytes.")); int64_t result = adapter->ProcessBytes(frames); EXPECT_EQ(frames.size(), result); } TEST(ServerCallbackVisitorUnitTest, HeadersAfterFin) { testing::StrictMock<MockNghttp2Callbacks> callbacks; CallbackVisitor visitor(Perspective::kServer, *MockNghttp2Callbacks::GetCallbacks(), &callbacks); testing::InSequence seq; EXPECT_CALL( callbacks, OnBeginFrame(HasFrameHeader( 1, HEADERS, NGHTTP2_FLAG_END_HEADERS | NGHTTP2_FLAG_END_STREAM))); visitor.OnFrameHeader(1, 23, HEADERS, 5); EXPECT_CALL(callbacks, OnBeginHeaders(IsHeaders( 1, NGHTTP2_FLAG_END_HEADERS | NGHTTP2_FLAG_END_STREAM, NGHTTP2_HCAT_REQUEST))); EXPECT_TRUE(visitor.OnBeginHeadersForStream(1)); EXPECT_EQ(visitor.stream_map_size(), 1); EXPECT_CALL(callbacks, OnHeader).Times(5); visitor.OnHeaderForStream(1, ":method", "POST"); visitor.OnHeaderForStream(1, ":path", "/example/path"); visitor.OnHeaderForStream(1, ":scheme", "https"); visitor.OnHeaderForStream(1, ":authority", "example.com"); visitor.OnHeaderForStream(1, "accept", "text/html"); EXPECT_CALL(callbacks, OnFrameRecv(IsHeaders( 1, NGHTTP2_FLAG_END_HEADERS | NGHTTP2_FLAG_END_STREAM, NGHTTP2_HCAT_REQUEST))); visitor.OnEndHeadersForStream(1); EXPECT_TRUE(visitor.OnEndStream(1)); EXPECT_CALL(callbacks, OnStreamClose(1, NGHTTP2_NO_ERROR)); visitor.OnCloseStream(1, Http2ErrorCode::HTTP2_NO_ERROR); EXPECT_EQ(visitor.stream_map_size(), 0); EXPECT_CALL(callbacks, OnBeginFrame(HasFrameHeader( 1, HEADERS, NGHTTP2_FLAG_END_HEADERS))); visitor.OnFrameHeader(1, 23, HEADERS, 4); EXPECT_CALL(callbacks, OnBeginHeaders(IsHeaders(1, NGHTTP2_FLAG_END_HEADERS, NGHTTP2_HCAT_HEADERS))); EXPECT_TRUE(visitor.OnBeginHeadersForStream(1)); EXPECT_EQ(visitor.stream_map_size(), 0); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/callback_visitor.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/callback_visitor_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
7221b1d8-3e12-4d64-a79a-9293f0400d31
cpp
google/quiche
test_utils
quiche/http2/adapter/test_utils.cc
quiche/http2/adapter/test_utils_test.cc
#include "quiche/http2/adapter/test_utils.h" #include <cstring> #include <optional> #include <ostream> #include <vector> #include "absl/strings/str_format.h" #include "quiche/http2/adapter/http2_visitor_interface.h" #include "quiche/http2/core/spdy_protocol.h" #include "quiche/http2/hpack/hpack_encoder.h" #include "quiche/common/quiche_data_reader.h" namespace http2 { namespace adapter { namespace test { namespace { using ConnectionError = Http2VisitorInterface::ConnectionError; std::string EncodeHeaders(const quiche::HttpHeaderBlock& entries) { spdy::HpackEncoder encoder; encoder.DisableCompression(); return encoder.EncodeHeaderBlock(entries); } } TestVisitor::DataFrameHeaderInfo TestVisitor::OnReadyToSendDataForStream( Http2StreamId stream_id, size_t max_length) { auto it = data_map_.find(stream_id); if (it == data_map_.end()) { QUICHE_DVLOG(1) << "Source not in map; returning blocked."; return {0, false, false}; } DataPayload& payload = it->second; if (payload.return_error) { QUICHE_DVLOG(1) << "Simulating error response for stream " << stream_id; return {DataFrameSource::kError, false, false}; } const absl::string_view prefix = payload.data.GetPrefix(); const size_t frame_length = std::min(max_length, prefix.size()); const bool is_final_fragment = payload.data.Read().size() <= 1; const bool end_data = payload.end_data && is_final_fragment && frame_length == prefix.size(); const bool end_stream = payload.end_stream && end_data; return {static_cast<int64_t>(frame_length), end_data, end_stream}; } bool TestVisitor::SendDataFrame(Http2StreamId stream_id, absl::string_view frame_header, size_t payload_bytes) { const int64_t frame_result = OnReadyToSend(frame_header); if (frame_result < 0 || static_cast<size_t>(frame_result) != frame_header.size()) { return false; } auto it = data_map_.find(stream_id); if (it == data_map_.end()) { if (payload_bytes > 0) { return false; } else { return true; } } DataPayload& payload = it->second; absl::string_view frame_payload = payload.data.GetPrefix(); if (frame_payload.size() < payload_bytes) { return false; } frame_payload = frame_payload.substr(0, payload_bytes); const int64_t payload_result = OnReadyToSend(frame_payload); if (payload_result < 0 || static_cast<size_t>(payload_result) != frame_payload.size()) { return false; } payload.data.RemovePrefix(payload_bytes); return true; } void TestVisitor::AppendPayloadForStream(Http2StreamId stream_id, absl::string_view payload) { auto char_data = std::unique_ptr<char[]>(new char[payload.size()]); std::copy(payload.begin(), payload.end(), char_data.get()); data_map_[stream_id].data.Append(std::move(char_data), payload.size()); } void TestVisitor::SetEndData(Http2StreamId stream_id, bool end_stream) { DataPayload& payload = data_map_[stream_id]; payload.end_data = true; payload.end_stream = end_stream; } void TestVisitor::SimulateError(Http2StreamId stream_id) { DataPayload& payload = data_map_[stream_id]; payload.return_error = true; } std::pair<int64_t, bool> TestVisitor::PackMetadataForStream( Http2StreamId stream_id, uint8_t* dest, size_t dest_len) { auto it = outbound_metadata_map_.find(stream_id); if (it == outbound_metadata_map_.end()) { return {-1, false}; } const size_t to_copy = std::min(it->second.size(), dest_len); auto* src = reinterpret_cast<uint8_t*>(it->second.data()); std::copy(src, src + to_copy, dest); it->second = it->second.substr(to_copy); if (it->second.empty()) { outbound_metadata_map_.erase(it); return {to_copy, true}; } return {to_copy, false}; } void TestVisitor::AppendMetadataForStream( Http2StreamId stream_id, const quiche::HttpHeaderBlock& payload) { outbound_metadata_map_.insert({stream_id, EncodeHeaders(payload)}); } VisitorDataSource::VisitorDataSource(Http2VisitorInterface& visitor, Http2StreamId stream_id) : visitor_(visitor), stream_id_(stream_id) {} bool VisitorDataSource::send_fin() const { return has_fin_; } std::pair<int64_t, bool> VisitorDataSource::SelectPayloadLength( size_t max_length) { auto [payload_length, end_data, end_stream] = visitor_.OnReadyToSendDataForStream(stream_id_, max_length); has_fin_ = end_stream; return {payload_length, end_data}; } bool VisitorDataSource::Send(absl::string_view frame_header, size_t payload_length) { return visitor_.SendDataFrame(stream_id_, frame_header, payload_length); } TestMetadataSource::TestMetadataSource(const quiche::HttpHeaderBlock& entries) : encoded_entries_(EncodeHeaders(entries)) { remaining_ = encoded_entries_; } std::pair<int64_t, bool> TestMetadataSource::Pack(uint8_t* dest, size_t dest_len) { if (fail_when_packing_) { return {-1, false}; } const size_t copied = std::min(dest_len, remaining_.size()); std::memcpy(dest, remaining_.data(), copied); remaining_.remove_prefix(copied); return std::make_pair(copied, remaining_.empty()); } namespace { using TypeAndOptionalLength = std::pair<spdy::SpdyFrameType, std::optional<size_t>>; std::ostream& operator<<( std::ostream& os, const std::vector<TypeAndOptionalLength>& types_and_lengths) { for (const auto& type_and_length : types_and_lengths) { os << "(" << spdy::FrameTypeToString(type_and_length.first) << ", " << (type_and_length.second ? absl::StrCat(type_and_length.second.value()) : "<unspecified>") << ") "; } return os; } std::string FrameTypeToString(uint8_t frame_type) { if (spdy::IsDefinedFrameType(frame_type)) { return spdy::FrameTypeToString(spdy::ParseFrameType(frame_type)); } else { return absl::StrFormat("0x%x", static_cast<int>(frame_type)); } } class SpdyControlFrameMatcher : public testing::MatcherInterface<absl::string_view> { public: explicit SpdyControlFrameMatcher( std::vector<TypeAndOptionalLength> types_and_lengths) : expected_types_and_lengths_(std::move(types_and_lengths)) {} bool MatchAndExplain(absl::string_view s, testing::MatchResultListener* listener) const override { quiche::QuicheDataReader reader(s.data(), s.size()); for (TypeAndOptionalLength expected : expected_types_and_lengths_) { if (!MatchAndExplainOneFrame(expected.first, expected.second, &reader, listener)) { return false; } } if (!reader.IsDoneReading()) { *listener << "; " << reader.BytesRemaining() << " bytes left to read!"; return false; } return true; } bool MatchAndExplainOneFrame(spdy::SpdyFrameType expected_type, std::optional<size_t> expected_length, quiche::QuicheDataReader* reader, testing::MatchResultListener* listener) const { uint32_t payload_length; if (!reader->ReadUInt24(&payload_length)) { *listener << "; unable to read length field for expected_type " << FrameTypeToString(expected_type) << ". data too short!"; return false; } if (expected_length && payload_length != expected_length.value()) { *listener << "; actual length: " << payload_length << " but expected length: " << expected_length.value(); return false; } uint8_t raw_type; if (!reader->ReadUInt8(&raw_type)) { *listener << "; unable to read type field for expected_type " << FrameTypeToString(expected_type) << ". data too short!"; return false; } if (raw_type != static_cast<uint8_t>(expected_type)) { *listener << "; actual type: " << FrameTypeToString(raw_type) << " but expected type: " << FrameTypeToString(expected_type); return false; } reader->Seek(5 + payload_length); return true; } void DescribeTo(std::ostream* os) const override { *os << "Data contains frames of types in sequence " << expected_types_and_lengths_; } void DescribeNegationTo(std::ostream* os) const override { *os << "Data does not contain frames of types in sequence " << expected_types_and_lengths_; } private: const std::vector<TypeAndOptionalLength> expected_types_and_lengths_; }; } testing::Matcher<absl::string_view> EqualsFrames( std::vector<std::pair<spdy::SpdyFrameType, std::optional<size_t>>> types_and_lengths) { return MakeMatcher(new SpdyControlFrameMatcher(std::move(types_and_lengths))); } testing::Matcher<absl::string_view> EqualsFrames( std::vector<spdy::SpdyFrameType> types) { std::vector<std::pair<spdy::SpdyFrameType, std::optional<size_t>>> types_and_lengths; types_and_lengths.reserve(types.size()); for (spdy::SpdyFrameType type : types) { types_and_lengths.push_back({type, std::nullopt}); } return MakeMatcher(new SpdyControlFrameMatcher(std::move(types_and_lengths))); } } } }
#include "quiche/http2/adapter/test_utils.h" #include <optional> #include <string> #include <utility> #include "quiche/http2/core/spdy_framer.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace adapter { namespace test { namespace { using spdy::SpdyFramer; TEST(EqualsFrames, Empty) { EXPECT_THAT("", EqualsFrames(std::vector<spdy::SpdyFrameType>{})); } TEST(EqualsFrames, SingleFrameWithLength) { SpdyFramer framer{SpdyFramer::ENABLE_COMPRESSION}; spdy::SpdyPingIR ping{511}; EXPECT_THAT(framer.SerializeFrame(ping), EqualsFrames({{spdy::SpdyFrameType::PING, 8}})); spdy::SpdyWindowUpdateIR window_update{1, 101}; EXPECT_THAT(framer.SerializeFrame(window_update), EqualsFrames({{spdy::SpdyFrameType::WINDOW_UPDATE, 4}})); spdy::SpdyDataIR data{3, "Some example data, ha ha!"}; EXPECT_THAT(framer.SerializeFrame(data), EqualsFrames({{spdy::SpdyFrameType::DATA, 25}})); } TEST(EqualsFrames, SingleFrameWithoutLength) { SpdyFramer framer{SpdyFramer::ENABLE_COMPRESSION}; spdy::SpdyRstStreamIR rst_stream{7, spdy::ERROR_CODE_REFUSED_STREAM}; EXPECT_THAT(framer.SerializeFrame(rst_stream), EqualsFrames({{spdy::SpdyFrameType::RST_STREAM, std::nullopt}})); spdy::SpdyGoAwayIR goaway{13, spdy::ERROR_CODE_ENHANCE_YOUR_CALM, "Consider taking some deep breaths."}; EXPECT_THAT(framer.SerializeFrame(goaway), EqualsFrames({{spdy::SpdyFrameType::GOAWAY, std::nullopt}})); quiche::HttpHeaderBlock block; block[":method"] = "GET"; block[":path"] = "/example"; block[":authority"] = "example.com"; spdy::SpdyHeadersIR headers{17, std::move(block)}; EXPECT_THAT(framer.SerializeFrame(headers), EqualsFrames({{spdy::SpdyFrameType::HEADERS, std::nullopt}})); } TEST(EqualsFrames, MultipleFrames) { SpdyFramer framer{SpdyFramer::ENABLE_COMPRESSION}; spdy::SpdyPingIR ping{511}; spdy::SpdyWindowUpdateIR window_update{1, 101}; spdy::SpdyDataIR data{3, "Some example data, ha ha!"}; spdy::SpdyRstStreamIR rst_stream{7, spdy::ERROR_CODE_REFUSED_STREAM}; spdy::SpdyGoAwayIR goaway{13, spdy::ERROR_CODE_ENHANCE_YOUR_CALM, "Consider taking some deep breaths."}; quiche::HttpHeaderBlock block; block[":method"] = "GET"; block[":path"] = "/example"; block[":authority"] = "example.com"; spdy::SpdyHeadersIR headers{17, std::move(block)}; const std::string frame_sequence = absl::StrCat(absl::string_view(framer.SerializeFrame(ping)), absl::string_view(framer.SerializeFrame(window_update)), absl::string_view(framer.SerializeFrame(data)), absl::string_view(framer.SerializeFrame(rst_stream)), absl::string_view(framer.SerializeFrame(goaway)), absl::string_view(framer.SerializeFrame(headers))); absl::string_view frame_sequence_view = frame_sequence; EXPECT_THAT(frame_sequence, EqualsFrames({{spdy::SpdyFrameType::PING, std::nullopt}, {spdy::SpdyFrameType::WINDOW_UPDATE, std::nullopt}, {spdy::SpdyFrameType::DATA, 25}, {spdy::SpdyFrameType::RST_STREAM, std::nullopt}, {spdy::SpdyFrameType::GOAWAY, 42}, {spdy::SpdyFrameType::HEADERS, 19}})); EXPECT_THAT(frame_sequence_view, EqualsFrames({{spdy::SpdyFrameType::PING, std::nullopt}, {spdy::SpdyFrameType::WINDOW_UPDATE, std::nullopt}, {spdy::SpdyFrameType::DATA, 25}, {spdy::SpdyFrameType::RST_STREAM, std::nullopt}, {spdy::SpdyFrameType::GOAWAY, 42}, {spdy::SpdyFrameType::HEADERS, 19}})); EXPECT_THAT( frame_sequence, EqualsFrames( {spdy::SpdyFrameType::PING, spdy::SpdyFrameType::WINDOW_UPDATE, spdy::SpdyFrameType::DATA, spdy::SpdyFrameType::RST_STREAM, spdy::SpdyFrameType::GOAWAY, spdy::SpdyFrameType::HEADERS})); EXPECT_THAT( frame_sequence_view, EqualsFrames( {spdy::SpdyFrameType::PING, spdy::SpdyFrameType::WINDOW_UPDATE, spdy::SpdyFrameType::DATA, spdy::SpdyFrameType::RST_STREAM, spdy::SpdyFrameType::GOAWAY, spdy::SpdyFrameType::HEADERS})); EXPECT_THAT( frame_sequence, testing::Not(EqualsFrames( {spdy::SpdyFrameType::PING, spdy::SpdyFrameType::WINDOW_UPDATE, spdy::SpdyFrameType::DATA, spdy::SpdyFrameType::RST_STREAM, spdy::SpdyFrameType::GOAWAY}))); EXPECT_THAT( frame_sequence_view, testing::Not(EqualsFrames( {spdy::SpdyFrameType::PING, spdy::SpdyFrameType::WINDOW_UPDATE, spdy::SpdyFrameType::DATA, spdy::SpdyFrameType::RST_STREAM, spdy::SpdyFrameType::GOAWAY}))); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/test_utils.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/test_utils_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
f7a41391-75c0-4b84-9f2d-3a731b52a23c
cpp
google/quiche
header_validator
quiche/http2/adapter/header_validator.cc
quiche/http2/adapter/header_validator_test.cc
#include "quiche/http2/adapter/header_validator.h" #include <array> #include <bitset> #include <string> #include "absl/strings/ascii.h" #include "absl/strings/escaping.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "quiche/http2/adapter/header_validator_base.h" #include "quiche/http2/http2_constants.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { namespace adapter { namespace { constexpr absl::string_view kHttpTokenChars = "!#$%&'*+-.^_`|~0123456789" "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; constexpr absl::string_view kHttp2HeaderNameAllowedChars = "!#$%&'*+-.0123456789" "^_`abcdefghijklmnopqrstuvwxyz|~"; constexpr absl::string_view kHttp2HeaderValueAllowedChars = "\t " "!\"#$%&'()*+,-./" "0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`" "abcdefghijklmnopqrstuvwxyz{|}~"; constexpr absl::string_view kHttp2StatusValueAllowedChars = "0123456789"; constexpr absl::string_view kValidAuthorityChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~%!$&'()[" "]*+,;=:"; constexpr absl::string_view kValidPathChars = "/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~%!$&'()" "*+,;=:@?"; constexpr absl::string_view kValidPathCharsWithFragment = "/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~%!$&'()" "*+,;=:@?#"; using CharMap = std::array<bool, 256>; constexpr CharMap BuildValidCharMap(absl::string_view valid_chars) { CharMap map = {}; for (char c : valid_chars) { map[static_cast<uint8_t>(c)] = true; } return map; } constexpr CharMap AllowObsText(CharMap map) { for (uint8_t c = 0xff; c >= 0x80; --c) { map[c] = true; } return map; } bool AllCharsInMap(absl::string_view str, const CharMap& map) { for (char c : str) { if (!map[static_cast<uint8_t>(c)]) { return false; } } return true; } bool IsValidStatus(absl::string_view status) { static constexpr CharMap valid_chars = BuildValidCharMap(kHttp2StatusValueAllowedChars); return AllCharsInMap(status, valid_chars); } bool IsValidMethod(absl::string_view method) { static constexpr CharMap valid_chars = BuildValidCharMap(kHttpTokenChars); return AllCharsInMap(method, valid_chars); } } void HeaderValidator::StartHeaderBlock() { HeaderValidatorBase::StartHeaderBlock(); pseudo_headers_.reset(); pseudo_header_state_.reset(); authority_.clear(); } void HeaderValidator::RecordPseudoHeader(PseudoHeaderTag tag) { if (pseudo_headers_[tag]) { pseudo_headers_[TAG_UNKNOWN_EXTRA] = true; } else { pseudo_headers_[tag] = true; } } HeaderValidator::HeaderStatus HeaderValidator::ValidateSingleHeader( absl::string_view key, absl::string_view value) { if (key.empty()) { return HEADER_FIELD_INVALID; } if (max_field_size_.has_value() && key.size() + value.size() > *max_field_size_) { QUICHE_VLOG(2) << "Header field size is " << key.size() + value.size() << ", exceeds max size of " << *max_field_size_; return HEADER_FIELD_TOO_LONG; } if (key[0] == ':') { key.remove_prefix(1); if (key == "status") { if (value.size() != 3 || !IsValidStatus(value)) { QUICHE_VLOG(2) << "malformed status value: [" << absl::CEscape(value) << "]"; return HEADER_FIELD_INVALID; } if (value == "101") { return HEADER_FIELD_INVALID; } status_ = std::string(value); RecordPseudoHeader(TAG_STATUS); } else if (key == "method") { if (value == "OPTIONS") { pseudo_header_state_[STATE_METHOD_IS_OPTIONS] = true; } else if (value == "CONNECT") { pseudo_header_state_[STATE_METHOD_IS_CONNECT] = true; } else if (!IsValidMethod(value)) { return HEADER_FIELD_INVALID; } RecordPseudoHeader(TAG_METHOD); } else if (key == "authority") { if (!ValidateAndSetAuthority(value)) { return HEADER_FIELD_INVALID; } RecordPseudoHeader(TAG_AUTHORITY); } else if (key == "path") { if (value == "*") { pseudo_header_state_[STATE_PATH_IS_STAR] = true; } else if (value.empty()) { pseudo_header_state_[STATE_PATH_IS_EMPTY] = true; return HEADER_FIELD_INVALID; } else if (validate_path_ && !IsValidPath(value, allow_fragment_in_path_)) { return HEADER_FIELD_INVALID; } if (value[0] == '/') { pseudo_header_state_[STATE_PATH_INITIAL_SLASH] = true; } RecordPseudoHeader(TAG_PATH); } else if (key == "protocol") { RecordPseudoHeader(TAG_PROTOCOL); } else if (key == "scheme") { RecordPseudoHeader(TAG_SCHEME); } else { pseudo_headers_[TAG_UNKNOWN_EXTRA] = true; if (!IsValidHeaderName(key)) { QUICHE_VLOG(2) << "invalid chars in header name: [" << absl::CEscape(key) << "]"; return HEADER_FIELD_INVALID; } } if (!IsValidHeaderValue(value, obs_text_option_)) { QUICHE_VLOG(2) << "invalid chars in header value: [" << absl::CEscape(value) << "]"; return HEADER_FIELD_INVALID; } } else { std::string lowercase_key; if (allow_uppercase_in_header_names_) { lowercase_key = absl::AsciiStrToLower(key); key = lowercase_key; } if (!IsValidHeaderName(key)) { QUICHE_VLOG(2) << "invalid chars in header name: [" << absl::CEscape(key) << "]"; return HEADER_FIELD_INVALID; } if (!IsValidHeaderValue(value, obs_text_option_)) { QUICHE_VLOG(2) << "invalid chars in header value: [" << absl::CEscape(value) << "]"; return HEADER_FIELD_INVALID; } if (key == "host") { if (pseudo_headers_[TAG_STATUS]) { } else { if (!ValidateAndSetAuthority(value)) { return HEADER_FIELD_INVALID; } pseudo_headers_[TAG_AUTHORITY] = true; } } else if (key == "content-length") { const ContentLengthStatus status = HandleContentLength(value); switch (status) { case CONTENT_LENGTH_ERROR: return HEADER_FIELD_INVALID; case CONTENT_LENGTH_SKIP: return HEADER_SKIP; case CONTENT_LENGTH_OK: return HEADER_OK; default: return HEADER_FIELD_INVALID; } } else if (key == "te" && value != "trailers") { return HEADER_FIELD_INVALID; } else if (key == "upgrade" || GetInvalidHttp2HeaderSet().contains(key)) { return HEADER_FIELD_INVALID; } } return HEADER_OK; } bool HeaderValidator::FinishHeaderBlock(HeaderType type) { switch (type) { case HeaderType::REQUEST: return ValidateRequestHeaders(pseudo_headers_, pseudo_header_state_, allow_extended_connect_); case HeaderType::REQUEST_TRAILER: return ValidateRequestTrailers(pseudo_headers_); case HeaderType::RESPONSE_100: case HeaderType::RESPONSE: return ValidateResponseHeaders(pseudo_headers_); case HeaderType::RESPONSE_TRAILER: return ValidateResponseTrailers(pseudo_headers_); } return false; } bool HeaderValidator::IsValidHeaderName(absl::string_view name) { static constexpr CharMap valid_chars = BuildValidCharMap(kHttp2HeaderNameAllowedChars); return AllCharsInMap(name, valid_chars); } bool HeaderValidator::IsValidHeaderValue(absl::string_view value, ObsTextOption option) { static constexpr CharMap valid_chars = BuildValidCharMap(kHttp2HeaderValueAllowedChars); static constexpr CharMap valid_chars_with_obs_text = AllowObsText(BuildValidCharMap(kHttp2HeaderValueAllowedChars)); return AllCharsInMap(value, option == ObsTextOption::kAllow ? valid_chars_with_obs_text : valid_chars); } bool HeaderValidator::IsValidAuthority(absl::string_view authority) { static constexpr CharMap valid_chars = BuildValidCharMap(kValidAuthorityChars); return AllCharsInMap(authority, valid_chars); } bool HeaderValidator::IsValidPath(absl::string_view path, bool allow_fragment) { static constexpr CharMap valid_chars = BuildValidCharMap(kValidPathChars); static constexpr CharMap valid_chars_with_fragment = BuildValidCharMap(kValidPathCharsWithFragment); if (allow_fragment) { return AllCharsInMap(path, valid_chars_with_fragment); } else { return AllCharsInMap(path, valid_chars); } } HeaderValidator::ContentLengthStatus HeaderValidator::HandleContentLength( absl::string_view value) { if (value.empty()) { return CONTENT_LENGTH_ERROR; } if (status_ == "204" && value != "0") { return CONTENT_LENGTH_ERROR; } if (!status_.empty() && status_[0] == '1' && value != "0") { return CONTENT_LENGTH_ERROR; } size_t content_length = 0; const bool valid = absl::SimpleAtoi(value, &content_length); if (!valid) { return CONTENT_LENGTH_ERROR; } if (content_length_.has_value()) { return content_length == *content_length_ ? CONTENT_LENGTH_SKIP : CONTENT_LENGTH_ERROR; } content_length_ = content_length; return CONTENT_LENGTH_OK; } bool HeaderValidator::ValidateAndSetAuthority(absl::string_view authority) { if (!IsValidAuthority(authority)) { return false; } if (!allow_different_host_and_authority_ && pseudo_headers_[TAG_AUTHORITY] && authority != authority_) { return false; } if (!authority.empty()) { pseudo_header_state_[STATE_AUTHORITY_IS_NONEMPTY] = true; if (authority_.empty()) { authority_ = authority; } else { absl::StrAppend(&authority_, ", ", authority); } } return true; } bool HeaderValidator::ValidateRequestHeaders( const PseudoHeaderTagSet& pseudo_headers, const PseudoHeaderStateSet& pseudo_header_state, bool allow_extended_connect) { QUICHE_VLOG(2) << "Request pseudo-headers: [" << pseudo_headers << "], pseudo_header_state: [" << pseudo_header_state << "], allow_extended_connect: " << allow_extended_connect; if (pseudo_header_state[STATE_METHOD_IS_CONNECT]) { if (allow_extended_connect) { static const auto* kExtendedConnectHeaders = new PseudoHeaderTagSet(0b0011111); if (pseudo_headers == *kExtendedConnectHeaders) { return true; } } static const auto* kConnectHeaders = new PseudoHeaderTagSet(0b0000011); return pseudo_header_state[STATE_AUTHORITY_IS_NONEMPTY] && pseudo_headers == *kConnectHeaders; } if (pseudo_header_state[STATE_PATH_IS_EMPTY]) { return false; } if (pseudo_header_state[STATE_PATH_IS_STAR]) { if (!pseudo_header_state[STATE_METHOD_IS_OPTIONS]) { return false; } } else if (!pseudo_header_state[STATE_PATH_INITIAL_SLASH]) { return false; } static const auto* kRequiredHeaders = new PseudoHeaderTagSet(0b0010111); return pseudo_headers == *kRequiredHeaders; } bool HeaderValidator::ValidateRequestTrailers( const PseudoHeaderTagSet& pseudo_headers) { return pseudo_headers.none(); } bool HeaderValidator::ValidateResponseHeaders( const PseudoHeaderTagSet& pseudo_headers) { static const auto* kRequiredHeaders = new PseudoHeaderTagSet(0b0100000); return pseudo_headers == *kRequiredHeaders; } bool HeaderValidator::ValidateResponseTrailers( const PseudoHeaderTagSet& pseudo_headers) { return pseudo_headers.none(); } } }
#include "quiche/http2/adapter/header_validator.h" #include <optional> #include <string> #include <utility> #include <vector> #include "absl/strings/str_cat.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace adapter { namespace test { using ::testing::Optional; using Header = std::pair<absl::string_view, absl::string_view>; constexpr Header kSampleRequestPseudoheaders[] = {{":authority", "www.foo.com"}, {":method", "GET"}, {":path", "/foo"}, {":scheme", "https"}}; TEST(HeaderValidatorTest, HeaderNameEmpty) { HeaderValidator v; HeaderValidator::HeaderStatus status = v.ValidateSingleHeader("", "value"); EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, status); } TEST(HeaderValidatorTest, HeaderValueEmpty) { HeaderValidator v; HeaderValidator::HeaderStatus status = v.ValidateSingleHeader("name", ""); EXPECT_EQ(HeaderValidator::HEADER_OK, status); } TEST(HeaderValidatorTest, ExceedsMaxSize) { HeaderValidator v; v.SetMaxFieldSize(64u); HeaderValidator::HeaderStatus status = v.ValidateSingleHeader("name", "value"); EXPECT_EQ(HeaderValidator::HEADER_OK, status); status = v.ValidateSingleHeader( "name2", "Antidisestablishmentariansism is supercalifragilisticexpialodocious."); EXPECT_EQ(HeaderValidator::HEADER_FIELD_TOO_LONG, status); } TEST(HeaderValidatorTest, NameHasInvalidChar) { HeaderValidator v; for (const bool is_pseudo_header : {true, false}) { for (const char* c : {"!", "3", "a", "_", "|", "~"}) { const std::string name = is_pseudo_header ? absl::StrCat(":met", c, "hod") : absl::StrCat("na", c, "me"); HeaderValidator::HeaderStatus status = v.ValidateSingleHeader(name, "value"); EXPECT_EQ(HeaderValidator::HEADER_OK, status); } for (const char* c : {"\\", "<", ";", "[", "=", " ", "\r", "\n", ",", "\"", "\x1F", "\x91"}) { const std::string name = is_pseudo_header ? absl::StrCat(":met", c, "hod") : absl::StrCat("na", c, "me"); HeaderValidator::HeaderStatus status = v.ValidateSingleHeader(name, "value"); EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, status) << "with name [" << name << "]"; } { const absl::string_view name = is_pseudo_header ? absl::string_view(":met\0hod", 8) : absl::string_view("na\0me", 5); HeaderValidator::HeaderStatus status = v.ValidateSingleHeader(name, "value"); EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, status); } const std::string uc_name = is_pseudo_header ? ":Method" : "Name"; HeaderValidator::HeaderStatus status = v.ValidateSingleHeader(uc_name, "value"); EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, status); } } TEST(HeaderValidatorTest, ValueHasInvalidChar) { HeaderValidator v; for (const char* c : {"!", "3", "a", "_", "|", "~", "\\", "<", ";", "[", "=", "A", "\t"}) { const std::string value = absl::StrCat("val", c, "ue"); EXPECT_TRUE( HeaderValidator::IsValidHeaderValue(value, ObsTextOption::kDisallow)); HeaderValidator::HeaderStatus status = v.ValidateSingleHeader("name", value); EXPECT_EQ(HeaderValidator::HEADER_OK, status); } for (const char* c : {"\r", "\n"}) { const std::string value = absl::StrCat("val", c, "ue"); EXPECT_FALSE( HeaderValidator::IsValidHeaderValue(value, ObsTextOption::kDisallow)); HeaderValidator::HeaderStatus status = v.ValidateSingleHeader("name", value); EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, status); } { const std::string value("val\0ue", 6); EXPECT_FALSE( HeaderValidator::IsValidHeaderValue(value, ObsTextOption::kDisallow)); HeaderValidator::HeaderStatus status = v.ValidateSingleHeader("name", value); EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, status); } { const std::string obs_text_value = "val\xa9ue"; EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, v.ValidateSingleHeader("name", obs_text_value)); v.SetObsTextOption(ObsTextOption::kDisallow); EXPECT_FALSE(HeaderValidator::IsValidHeaderValue(obs_text_value, ObsTextOption::kDisallow)); EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, v.ValidateSingleHeader("name", obs_text_value)); v.SetObsTextOption(ObsTextOption::kAllow); EXPECT_TRUE(HeaderValidator::IsValidHeaderValue(obs_text_value, ObsTextOption::kAllow)); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader("name", obs_text_value)); } } TEST(HeaderValidatorTest, StatusHasInvalidChar) { HeaderValidator v; for (HeaderType type : {HeaderType::RESPONSE, HeaderType::RESPONSE_100}) { v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, v.ValidateSingleHeader(":status", "bar")); EXPECT_FALSE(v.FinishHeaderBlock(type)); v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, v.ValidateSingleHeader(":status", "10")); EXPECT_FALSE(v.FinishHeaderBlock(type)); v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, v.ValidateSingleHeader(":status", "9000")); EXPECT_FALSE(v.FinishHeaderBlock(type)); v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "400")); EXPECT_TRUE(v.FinishHeaderBlock(type)); } } TEST(HeaderValidatorTest, AuthorityHasInvalidChar) { for (absl::string_view key : {":authority", "host"}) { for (const absl::string_view c : {"1", "-", "!", ":", "+", "=", ","}) { const std::string value = absl::StrCat("ho", c, "st.example.com"); EXPECT_TRUE(HeaderValidator::IsValidAuthority(value)); HeaderValidator v; v.StartHeaderBlock(); HeaderValidator::HeaderStatus status = v.ValidateSingleHeader(key, value); EXPECT_EQ(HeaderValidator::HEADER_OK, status) << " with name [" << key << "] and value [" << value << "]"; } for (const absl::string_view c : {"\r", "\n", "|", "\\", "`"}) { const std::string value = absl::StrCat("ho", c, "st.example.com"); EXPECT_FALSE(HeaderValidator::IsValidAuthority(value)); HeaderValidator v; v.StartHeaderBlock(); HeaderValidator::HeaderStatus status = v.ValidateSingleHeader(key, value); EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, status); } { const std::string value = "123.45.67.89"; EXPECT_TRUE(HeaderValidator::IsValidAuthority(value)); HeaderValidator v; v.StartHeaderBlock(); HeaderValidator::HeaderStatus status = v.ValidateSingleHeader(key, value); EXPECT_EQ(HeaderValidator::HEADER_OK, status); } { const std::string value1 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"; EXPECT_TRUE(HeaderValidator::IsValidAuthority(value1)); HeaderValidator v; v.StartHeaderBlock(); HeaderValidator::HeaderStatus status = v.ValidateSingleHeader(key, value1); EXPECT_EQ(HeaderValidator::HEADER_OK, status); const std::string value2 = "[::1]:80"; EXPECT_TRUE(HeaderValidator::IsValidAuthority(value2)); HeaderValidator v2; v2.StartHeaderBlock(); status = v2.ValidateSingleHeader(key, value2); EXPECT_EQ(HeaderValidator::HEADER_OK, status); } { EXPECT_TRUE(HeaderValidator::IsValidAuthority("")); HeaderValidator v; v.StartHeaderBlock(); HeaderValidator::HeaderStatus status = v.ValidateSingleHeader(key, ""); EXPECT_EQ(HeaderValidator::HEADER_OK, status); } } } TEST(HeaderValidatorTest, RequestHostAndAuthority) { HeaderValidator v; v.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader("host", "www.foo.com")); EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST)); v.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, v.ValidateSingleHeader("host", "www.bar.com")); } TEST(HeaderValidatorTest, RequestHostAndAuthorityLax) { HeaderValidator v; v.SetAllowDifferentHostAndAuthority(); v.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader("host", "www.bar.com")); } TEST(HeaderValidatorTest, MethodHasInvalidChar) { HeaderValidator v; v.StartHeaderBlock(); std::vector<absl::string_view> bad_methods = { "In[]valid{}", "co,mma", "spac e", "a@t", "equals=", "question?mark", "co:lon", "semi;colon", "sla/sh", "back\\slash", }; std::vector<absl::string_view> good_methods = { "lowercase", "MiXeDcAsE", "NONCANONICAL", "HASH#", "under_score", "PI|PE", "Tilde~", "quote'", }; for (absl::string_view value : bad_methods) { v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, v.ValidateSingleHeader(":method", value)); } for (absl::string_view value : good_methods) { v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":method", value)); for (Header to_add : kSampleRequestPseudoheaders) { if (to_add.first == ":method") { continue; } EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST)); } } TEST(HeaderValidatorTest, RequestPseudoHeaders) { HeaderValidator v; for (Header to_skip : kSampleRequestPseudoheaders) { v.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { if (to_add != to_skip) { EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } } EXPECT_FALSE(v.FinishHeaderBlock(HeaderType::REQUEST)); } v.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST)); v.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":extra", "blah")); EXPECT_FALSE(v.FinishHeaderBlock(HeaderType::REQUEST)); for (Header to_repeat : kSampleRequestPseudoheaders) { v.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); if (to_add == to_repeat) { EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } } EXPECT_FALSE(v.FinishHeaderBlock(HeaderType::REQUEST)); } } TEST(HeaderValidatorTest, ConnectHeaders) { HeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":authority", "athena.dialup.mit.edu:23")); EXPECT_FALSE(v.FinishHeaderBlock(HeaderType::REQUEST)); v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":method", "CONNECT")); EXPECT_FALSE(v.FinishHeaderBlock(HeaderType::REQUEST)); v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":authority", "athena.dialup.mit.edu:23")); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":method", "CONNECT")); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":path", "/")); EXPECT_FALSE(v.FinishHeaderBlock(HeaderType::REQUEST)); v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":authority", "")); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":method", "CONNECT")); EXPECT_FALSE(v.FinishHeaderBlock(HeaderType::REQUEST)); v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":authority", "athena.dialup.mit.edu:23")); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":method", "CONNECT")); EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST)); v.SetAllowExtendedConnect(); v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":authority", "athena.dialup.mit.edu:23")); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":method", "CONNECT")); EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST)); } TEST(HeaderValidatorTest, WebsocketPseudoHeaders) { HeaderValidator v; v.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":protocol", "websocket")); EXPECT_FALSE(v.FinishHeaderBlock(HeaderType::REQUEST)); v.SetAllowExtendedConnect(); v.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":protocol", "websocket")); EXPECT_FALSE(v.FinishHeaderBlock(HeaderType::REQUEST)); v.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { if (to_add.first == ":method") { EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, "CONNECT")); } else { EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } } EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":protocol", "websocket")); EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST)); } TEST(HeaderValidatorTest, AsteriskPathPseudoHeader) { HeaderValidator v; v.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { if (to_add.first == ":path") { EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, "*")); } else { EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } } EXPECT_FALSE(v.FinishHeaderBlock(HeaderType::REQUEST)); v.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { if (to_add.first == ":path") { EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, "*")); } else if (to_add.first == ":method") { EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, "OPTIONS")); } else { EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } } EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::REQUEST)); } TEST(HeaderValidatorTest, InvalidPathPseudoHeader) { HeaderValidator v; v.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { if (to_add.first == ":path") { EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, v.ValidateSingleHeader(to_add.first, "")); } else { EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } } EXPECT_FALSE(v.FinishHeaderBlock(HeaderType::REQUEST)); v.SetValidatePath(); v.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { if (to_add.first == ":path") { EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, "shawarma")); } else { EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } } EXPECT_FALSE(v.FinishHeaderBlock(HeaderType::REQUEST)); for (const absl::string_view c : {"/", "?", "_", "'", "9", "&", "(", "@", ":"}) { const std::string value = absl::StrCat("/shawa", c, "rma"); HeaderValidator validator; validator.SetValidatePath(); validator.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { if (to_add.first == ":path") { EXPECT_EQ(HeaderValidator::HEADER_OK, validator.ValidateSingleHeader(to_add.first, value)) << "Problematic char: [" << c << "]"; } else { EXPECT_EQ(HeaderValidator::HEADER_OK, validator.ValidateSingleHeader(to_add.first, to_add.second)); } } EXPECT_TRUE(validator.FinishHeaderBlock(HeaderType::REQUEST)); } for (const absl::string_view c : {"[", "<", "}", "`", "\\", " ", "\t", "#"}) { const std::string value = absl::StrCat("/shawa", c, "rma"); HeaderValidator validator; validator.SetValidatePath(); validator.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { if (to_add.first == ":path") { EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, validator.ValidateSingleHeader(to_add.first, value)); } else { EXPECT_EQ(HeaderValidator::HEADER_OK, validator.ValidateSingleHeader(to_add.first, to_add.second)); } } EXPECT_FALSE(validator.FinishHeaderBlock(HeaderType::REQUEST)); } { HeaderValidator validator; validator.SetValidatePath(); validator.SetAllowFragmentInPath(); validator.StartHeaderBlock(); for (Header to_add : kSampleRequestPseudoheaders) { if (to_add.first == ":path") { EXPECT_EQ(HeaderValidator::HEADER_OK, validator.ValidateSingleHeader(to_add.first, "/shawa#rma")); } else { EXPECT_EQ(HeaderValidator::HEADER_OK, validator.ValidateSingleHeader(to_add.first, to_add.second)); } } EXPECT_TRUE(validator.FinishHeaderBlock(HeaderType::REQUEST)); } } TEST(HeaderValidatorTest, ResponsePseudoHeaders) { HeaderValidator v; for (HeaderType type : {HeaderType::RESPONSE, HeaderType::RESPONSE_100}) { v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader("foo", "bar")); EXPECT_FALSE(v.FinishHeaderBlock(type)); v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "199")); EXPECT_TRUE(v.FinishHeaderBlock(type)); EXPECT_EQ("199", v.status_header()); v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "199")); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "299")); EXPECT_FALSE(v.FinishHeaderBlock(type)); v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "199")); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":extra", "blorp")); EXPECT_FALSE(v.FinishHeaderBlock(type)); } } TEST(HeaderValidatorTest, ResponseWithHost) { HeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "200")); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader("host", "myserver.com")); EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::RESPONSE)); } TEST(HeaderValidatorTest, Response204) { HeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "204")); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader("x-content", "is not present")); EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::RESPONSE)); } TEST(HeaderValidatorTest, ResponseWithMultipleIdenticalContentLength) { HeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "200")); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader("content-length", "13")); EXPECT_EQ(HeaderValidator::HEADER_SKIP, v.ValidateSingleHeader("content-length", "13")); } TEST(HeaderValidatorTest, ResponseWithMultipleDifferingContentLength) { HeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "200")); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader("content-length", "13")); EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, v.ValidateSingleHeader("content-length", "17")); } TEST(HeaderValidatorTest, Response204WithContentLengthZero) { HeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "204")); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader("x-content", "is not present")); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader("content-length", "0")); EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::RESPONSE)); } TEST(HeaderValidatorTest, Response204WithContentLength) { HeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "204")); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader("x-content", "is not present")); EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, v.ValidateSingleHeader("content-length", "1")); } TEST(HeaderValidatorTest, Response100) { HeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "100")); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader("x-content", "is not present")); EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::RESPONSE)); } TEST(HeaderValidatorTest, Response100WithContentLengthZero) { HeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "100")); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader("x-content", "is not present")); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader("content-length", "0")); EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::RESPONSE)); } TEST(HeaderValidatorTest, Response100WithContentLength) { HeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "100")); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader("x-content", "is not present")); EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, v.ValidateSingleHeader("content-length", "1")); } TEST(HeaderValidatorTest, ResponseTrailerPseudoHeaders) { HeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader("foo", "bar")); EXPECT_TRUE(v.FinishHeaderBlock(HeaderType::RESPONSE_TRAILER)); v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(":status", "200")); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader("foo", "bar")); EXPECT_FALSE(v.FinishHeaderBlock(HeaderType::RESPONSE_TRAILER)); } TEST(HeaderValidatorTest, ValidContentLength) { HeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(v.content_length(), std::nullopt); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader("content-length", "41")); EXPECT_THAT(v.content_length(), Optional(41)); v.StartHeaderBlock(); EXPECT_EQ(v.content_length(), std::nullopt); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader("content-length", "42")); EXPECT_THAT(v.content_length(), Optional(42)); } TEST(HeaderValidatorTest, InvalidContentLength) { HeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(v.content_length(), std::nullopt); EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, v.ValidateSingleHeader("content-length", "")); EXPECT_EQ(v.content_length(), std::nullopt); EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, v.ValidateSingleHeader("content-length", "nan")); EXPECT_EQ(v.content_length(), std::nullopt); EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, v.ValidateSingleHeader("content-length", "-42")); EXPECT_EQ(v.content_length(), std::nullopt); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader("content-length", "42")); EXPECT_THAT(v.content_length(), Optional(42)); } TEST(HeaderValidatorTest, TeHeader) { HeaderValidator v; v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader("te", "trailers")); v.StartHeaderBlock(); EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, v.ValidateSingleHeader("te", "trailers, deflate")); } TEST(HeaderValidatorTest, ConnectionSpecificHeaders) { const std::vector<Header> connection_headers = { {"connection", "keep-alive"}, {"proxy-connection", "keep-alive"}, {"keep-alive", "timeout=42"}, {"transfer-encoding", "chunked"}, {"upgrade", "h2c"}, }; for (const auto& [connection_key, connection_value] : connection_headers) { HeaderValidator v; v.StartHeaderBlock(); for (const auto& [sample_key, sample_value] : kSampleRequestPseudoheaders) { EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(sample_key, sample_value)); } EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, v.ValidateSingleHeader(connection_key, connection_value)); } } TEST(HeaderValidatorTest, MixedCaseHeaderName) { HeaderValidator v; v.SetAllowUppercaseInHeaderNames(); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader("MixedCaseName", "value")); } TEST(HeaderValidatorTest, MixedCasePseudoHeader) { HeaderValidator v; v.SetAllowUppercaseInHeaderNames(); EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, v.ValidateSingleHeader(":PATH", "/")); } TEST(HeaderValidatorTest, MixedCaseHost) { HeaderValidator v; v.SetAllowUppercaseInHeaderNames(); for (Header to_add : kSampleRequestPseudoheaders) { EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader(to_add.first, to_add.second)); } EXPECT_EQ(HeaderValidator::HEADER_FIELD_INVALID, v.ValidateSingleHeader("Host", "www.bar.com")); } TEST(HeaderValidatorTest, MixedCaseContentLength) { HeaderValidator v; v.SetAllowUppercaseInHeaderNames(); EXPECT_EQ(v.content_length(), std::nullopt); EXPECT_EQ(HeaderValidator::HEADER_OK, v.ValidateSingleHeader("Content-Length", "42")); EXPECT_THAT(v.content_length(), Optional(42)); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/header_validator.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/header_validator_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
ceea81cc-89f9-4b41-ad70-93eed3f74f6f
cpp
google/quiche
window_manager
quiche/http2/adapter/window_manager.cc
quiche/http2/adapter/window_manager_test.cc
#include "quiche/http2/adapter/window_manager.h" #include <utility> #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" namespace http2 { namespace adapter { bool DefaultShouldWindowUpdateFn(int64_t limit, int64_t window, int64_t delta) { const int64_t kDesiredMinWindow = limit / 2; const int64_t kDesiredMinDelta = limit / 3; if (delta >= kDesiredMinDelta) { return true; } else if (window < kDesiredMinWindow) { return true; } return false; } WindowManager::WindowManager(int64_t window_size_limit, WindowUpdateListener listener, ShouldWindowUpdateFn should_window_update_fn, bool update_window_on_notify) : limit_(window_size_limit), window_(window_size_limit), buffered_(0), listener_(std::move(listener)), should_window_update_fn_(std::move(should_window_update_fn)), update_window_on_notify_(update_window_on_notify) { if (!should_window_update_fn_) { should_window_update_fn_ = DefaultShouldWindowUpdateFn; } } void WindowManager::OnWindowSizeLimitChange(const int64_t new_limit) { QUICHE_VLOG(2) << "WindowManager@" << this << " OnWindowSizeLimitChange from old limit of " << limit_ << " to new limit of " << new_limit; window_ += (new_limit - limit_); limit_ = new_limit; } void WindowManager::SetWindowSizeLimit(int64_t new_limit) { QUICHE_VLOG(2) << "WindowManager@" << this << " SetWindowSizeLimit from old limit of " << limit_ << " to new limit of " << new_limit; limit_ = new_limit; MaybeNotifyListener(); } bool WindowManager::MarkDataBuffered(int64_t bytes) { QUICHE_VLOG(2) << "WindowManager@" << this << " window: " << window_ << " bytes: " << bytes; if (window_ < bytes) { QUICHE_VLOG(2) << "WindowManager@" << this << " window underflow " << "window: " << window_ << " bytes: " << bytes; window_ = 0; } else { window_ -= bytes; } buffered_ += bytes; if (window_ == 0) { MaybeNotifyListener(); } return window_ > 0; } void WindowManager::MarkDataFlushed(int64_t bytes) { QUICHE_VLOG(2) << "WindowManager@" << this << " buffered: " << buffered_ << " bytes: " << bytes; if (buffered_ < bytes) { QUICHE_BUG(bug_2816_1) << "WindowManager@" << this << " buffered underflow " << "buffered_: " << buffered_ << " bytes: " << bytes; buffered_ = 0; } else { buffered_ -= bytes; } MaybeNotifyListener(); } void WindowManager::MaybeNotifyListener() { const int64_t delta = limit_ - (buffered_ + window_); if (should_window_update_fn_(limit_, window_, delta) && delta > 0) { QUICHE_VLOG(2) << "WindowManager@" << this << " Informing listener of delta: " << delta; listener_(delta); if (update_window_on_notify_) { window_ += delta; } } } } }
#include "quiche/http2/adapter/window_manager.h" #include <algorithm> #include <list> #include "absl/functional/bind_front.h" #include "quiche/http2/test_tools/http2_random.h" #include "quiche/common/platform/api/quiche_expect_bug.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace adapter { namespace test { class WindowManagerPeer { public: explicit WindowManagerPeer(const WindowManager& wm) : wm_(wm) {} int64_t buffered() { return wm_.buffered_; } private: const WindowManager& wm_; }; namespace { class WindowManagerTest : public quiche::test::QuicheTest { protected: WindowManagerTest() : wm_(kDefaultLimit, absl::bind_front(&WindowManagerTest::OnCall, this)), peer_(wm_) {} void OnCall(int64_t s) { call_sequence_.push_back(s); } const int64_t kDefaultLimit = 32 * 1024 * 3; std::list<int64_t> call_sequence_; WindowManager wm_; WindowManagerPeer peer_; ::http2::test::Http2Random random_; }; TEST_F(WindowManagerTest, NoOps) { wm_.SetWindowSizeLimit(kDefaultLimit); wm_.SetWindowSizeLimit(0); wm_.SetWindowSizeLimit(kDefaultLimit); wm_.MarkDataBuffered(0); wm_.MarkDataFlushed(0); EXPECT_TRUE(call_sequence_.empty()); } TEST_F(WindowManagerTest, DataOnlyBuffered) { int64_t total = 0; while (total < kDefaultLimit) { int64_t s = std::min<int64_t>(kDefaultLimit - total, random_.Uniform(1024)); total += s; wm_.MarkDataBuffered(s); } EXPECT_THAT(call_sequence_, ::testing::IsEmpty()); } TEST_F(WindowManagerTest, DataBufferedAndFlushed) { int64_t total_buffered = 0; int64_t total_flushed = 0; while (call_sequence_.empty()) { int64_t buffered = std::min<int64_t>(kDefaultLimit - total_buffered, random_.Uniform(1024)); wm_.MarkDataBuffered(buffered); total_buffered += buffered; EXPECT_TRUE(call_sequence_.empty()); int64_t flushed = (total_buffered - total_flushed) > 0 ? random_.Uniform(total_buffered - total_flushed) : 0; wm_.MarkDataFlushed(flushed); total_flushed += flushed; } EXPECT_GE(total_buffered, kDefaultLimit / 3); } TEST_F(WindowManagerTest, AvoidWindowUnderflow) { EXPECT_EQ(wm_.CurrentWindowSize(), wm_.WindowSizeLimit()); wm_.MarkDataBuffered(wm_.WindowSizeLimit() + 1); EXPECT_EQ(wm_.CurrentWindowSize(), 0u); } TEST_F(WindowManagerTest, AvoidBufferedUnderflow) { EXPECT_EQ(peer_.buffered(), 0u); EXPECT_QUICHE_BUG(wm_.MarkDataFlushed(1), "buffered underflow"); EXPECT_EQ(peer_.buffered(), 0u); wm_.MarkDataBuffered(42); EXPECT_EQ(peer_.buffered(), 42u); EXPECT_QUICHE_BUG( { wm_.MarkDataFlushed(43); EXPECT_EQ(peer_.buffered(), 0u); }, "buffered underflow"); } TEST_F(WindowManagerTest, WindowConsumed) { int64_t consumed = kDefaultLimit / 3 - 1; wm_.MarkWindowConsumed(consumed); EXPECT_TRUE(call_sequence_.empty()); const int64_t extra = 1; wm_.MarkWindowConsumed(extra); EXPECT_THAT(call_sequence_, testing::ElementsAre(consumed + extra)); } TEST_F(WindowManagerTest, ListenerCalledOnSizeUpdate) { wm_.SetWindowSizeLimit(kDefaultLimit - 1024); EXPECT_TRUE(call_sequence_.empty()); wm_.SetWindowSizeLimit(kDefaultLimit * 5); EXPECT_THAT(call_sequence_, testing::ElementsAre(kDefaultLimit * 4)); } TEST_F(WindowManagerTest, WindowUpdateAfterLimitDecreased) { wm_.MarkDataBuffered(kDefaultLimit - 1024); wm_.SetWindowSizeLimit(kDefaultLimit - 2048); wm_.MarkDataFlushed(512); EXPECT_TRUE(call_sequence_.empty()); wm_.MarkDataFlushed(512); EXPECT_TRUE(call_sequence_.empty()); wm_.MarkDataFlushed(512); EXPECT_TRUE(call_sequence_.empty()); wm_.MarkDataFlushed(1024); EXPECT_THAT(call_sequence_, testing::ElementsAre(512)); } TEST_F(WindowManagerTest, ZeroWindowNotification) { wm_.MarkWindowConsumed(1); wm_.MarkDataBuffered(kDefaultLimit - 1); EXPECT_THAT(call_sequence_, testing::ElementsAre(1)); } TEST_F(WindowManagerTest, OnWindowSizeLimitChange) { wm_.MarkDataBuffered(10000); EXPECT_EQ(wm_.CurrentWindowSize(), kDefaultLimit - 10000); EXPECT_EQ(wm_.WindowSizeLimit(), kDefaultLimit); wm_.OnWindowSizeLimitChange(kDefaultLimit + 1000); EXPECT_EQ(wm_.CurrentWindowSize(), kDefaultLimit - 9000); EXPECT_EQ(wm_.WindowSizeLimit(), kDefaultLimit + 1000); wm_.OnWindowSizeLimitChange(kDefaultLimit - 1000); EXPECT_EQ(wm_.CurrentWindowSize(), kDefaultLimit - 11000); EXPECT_EQ(wm_.WindowSizeLimit(), kDefaultLimit - 1000); } TEST_F(WindowManagerTest, NegativeWindowSize) { wm_.MarkDataBuffered(80000); EXPECT_EQ(wm_.CurrentWindowSize(), 18304); wm_.OnWindowSizeLimitChange(65535); EXPECT_EQ(wm_.CurrentWindowSize(), -14465); wm_.MarkDataFlushed(70000); EXPECT_EQ(wm_.CurrentWindowSize(), 55535); EXPECT_THAT(call_sequence_, testing::ElementsAre(70000)); } TEST_F(WindowManagerTest, IncreaseWindow) { wm_.MarkDataBuffered(1000); EXPECT_EQ(wm_.CurrentWindowSize(), kDefaultLimit - 1000); EXPECT_EQ(wm_.WindowSizeLimit(), kDefaultLimit); wm_.IncreaseWindow(5000); EXPECT_EQ(wm_.CurrentWindowSize(), kDefaultLimit + 4000); EXPECT_EQ(wm_.WindowSizeLimit(), kDefaultLimit); wm_.MarkWindowConsumed(80000); EXPECT_THAT(call_sequence_, testing::ElementsAre(75000)); EXPECT_EQ(wm_.CurrentWindowSize(), kDefaultLimit - 1000); } TEST(WindowManagerNoUpdateTest, NoWindowUpdateOnListener) { const int64_t kDefaultLimit = 65535; std::list<int64_t> call_sequence1; WindowManager wm1( kDefaultLimit, [&call_sequence1](int64_t delta) { call_sequence1.push_back(delta); }, {}, true); std::list<int64_t> call_sequence2; WindowManager wm2( kDefaultLimit, [&call_sequence2](int64_t delta) { call_sequence2.push_back(delta); }, {}, false); const int64_t consumed = kDefaultLimit / 3 - 1; wm1.MarkWindowConsumed(consumed); EXPECT_TRUE(call_sequence1.empty()); wm2.MarkWindowConsumed(consumed); EXPECT_TRUE(call_sequence2.empty()); EXPECT_EQ(wm1.CurrentWindowSize(), kDefaultLimit - consumed); EXPECT_EQ(wm2.CurrentWindowSize(), kDefaultLimit - consumed); const int64_t extra = 1; wm1.MarkWindowConsumed(extra); EXPECT_THAT(call_sequence1, testing::ElementsAre(consumed + extra)); EXPECT_EQ(wm1.CurrentWindowSize(), kDefaultLimit); call_sequence1.clear(); wm2.MarkWindowConsumed(extra); EXPECT_THAT(call_sequence2, testing::ElementsAre(consumed + extra)); EXPECT_EQ(wm2.CurrentWindowSize(), kDefaultLimit - (consumed + extra)); call_sequence2.clear(); wm2.IncreaseWindow(consumed + extra); EXPECT_EQ(wm2.CurrentWindowSize(), kDefaultLimit); wm1.SetWindowSizeLimit(kDefaultLimit * 5); EXPECT_THAT(call_sequence1, testing::ElementsAre(kDefaultLimit * 4)); EXPECT_EQ(wm1.CurrentWindowSize(), kDefaultLimit * 5); wm2.SetWindowSizeLimit(kDefaultLimit * 5); EXPECT_THAT(call_sequence2, testing::ElementsAre(kDefaultLimit * 4)); EXPECT_EQ(wm2.CurrentWindowSize(), kDefaultLimit); } TEST(WindowManagerShouldUpdateTest, CustomShouldWindowUpdateFn) { const int64_t kDefaultLimit = 65535; std::list<int64_t> call_sequence1; WindowManager wm1( kDefaultLimit, [&call_sequence1](int64_t delta) { call_sequence1.push_back(delta); }, [](int64_t , int64_t , int64_t ) { return true; }); std::list<int64_t> call_sequence2; WindowManager wm2( kDefaultLimit, [&call_sequence2](int64_t delta) { call_sequence2.push_back(delta); }, [](int64_t , int64_t , int64_t ) { return false; }); std::list<int64_t> call_sequence3; WindowManager wm3( kDefaultLimit, [&call_sequence3](int64_t delta) { call_sequence3.push_back(delta); }, [](int64_t limit, int64_t window, int64_t delta) { return delta == limit - window; }); const int64_t consumed = kDefaultLimit / 4; wm1.MarkWindowConsumed(consumed); EXPECT_THAT(call_sequence1, testing::ElementsAre(consumed)); wm2.MarkWindowConsumed(consumed); EXPECT_TRUE(call_sequence2.empty()); wm3.MarkWindowConsumed(consumed); EXPECT_THAT(call_sequence3, testing::ElementsAre(consumed)); const int64_t buffered = 42; wm1.MarkDataBuffered(buffered); EXPECT_THAT(call_sequence1, testing::ElementsAre(consumed)); wm2.MarkDataBuffered(buffered); EXPECT_TRUE(call_sequence2.empty()); wm3.MarkDataBuffered(buffered); EXPECT_THAT(call_sequence3, testing::ElementsAre(consumed)); wm1.MarkDataFlushed(buffered / 3); EXPECT_THAT(call_sequence1, testing::ElementsAre(consumed, buffered / 3)); wm2.MarkDataFlushed(buffered / 3); EXPECT_TRUE(call_sequence2.empty()); wm3.MarkDataFlushed(buffered / 3); EXPECT_THAT(call_sequence3, testing::ElementsAre(consumed)); wm1.MarkDataFlushed(2 * buffered / 3); EXPECT_THAT(call_sequence1, testing::ElementsAre(consumed, buffered / 3, 2 * buffered / 3)); wm2.MarkDataFlushed(2 * buffered / 3); EXPECT_TRUE(call_sequence2.empty()); wm3.MarkDataFlushed(2 * buffered / 3); EXPECT_THAT(call_sequence3, testing::ElementsAre(consumed, buffered)); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/window_manager.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/http2/adapter/window_manager_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
c40de239-0441-4f1d-97f9-7210d0c66dc3
cpp
google/quiche
structured_headers
quiche/common/structured_headers.cc
quiche/common/structured_headers_test.cc
#include "quiche/common/structured_headers.h" #include <cmath> #include <cstddef> #include <cstdint> #include <optional> #include <sstream> #include <string> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/container/flat_hash_set.h" #include "absl/strings/ascii.h" #include "absl/strings/escaping.h" #include "absl/strings/numbers.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quiche { namespace structured_headers { namespace { #define DIGIT "0123456789" #define LCALPHA "abcdefghijklmnopqrstuvwxyz" #define UCALPHA "ABCDEFGHIJKLMNOPQRSTUVWXYZ" #define TCHAR DIGIT LCALPHA UCALPHA "!#$%&'*+-.^_`|~" constexpr char kTokenChars09[] = DIGIT UCALPHA LCALPHA "_-.:%*/"; constexpr char kTokenChars[] = TCHAR ":/"; constexpr char kKeyChars09[] = DIGIT LCALPHA "_-"; constexpr char kKeyChars[] = DIGIT LCALPHA "_-.*"; constexpr char kSP[] = " "; constexpr char kOWS[] = " \t"; #undef DIGIT #undef LCALPHA #undef UCALPHA constexpr int64_t kMaxInteger = 999'999'999'999'999L; constexpr int64_t kMinInteger = -999'999'999'999'999L; constexpr double kTooLargeDecimal = 1e12 - 0.0005; void StripLeft(absl::string_view& s, absl::string_view remove) { size_t i = s.find_first_not_of(remove); if (i == absl::string_view::npos) { i = s.size(); } s.remove_prefix(i); } class StructuredHeaderParser { public: enum DraftVersion { kDraft09, kFinal, }; explicit StructuredHeaderParser(absl::string_view str, DraftVersion version) : input_(str), version_(version) { SkipWhitespaces(); } StructuredHeaderParser(const StructuredHeaderParser&) = delete; StructuredHeaderParser& operator=(const StructuredHeaderParser&) = delete; bool FinishParsing() { SkipWhitespaces(); return input_.empty(); } std::optional<ListOfLists> ReadListOfLists() { QUICHE_CHECK_EQ(version_, kDraft09); ListOfLists result; while (true) { std::vector<Item> inner_list; while (true) { std::optional<Item> item(ReadBareItem()); if (!item) return std::nullopt; inner_list.push_back(std::move(*item)); SkipWhitespaces(); if (!ConsumeChar(';')) break; SkipWhitespaces(); } result.push_back(std::move(inner_list)); SkipWhitespaces(); if (!ConsumeChar(',')) break; SkipWhitespaces(); } return result; } std::optional<List> ReadList() { QUICHE_CHECK_EQ(version_, kFinal); List members; while (!input_.empty()) { std::optional<ParameterizedMember> member(ReadItemOrInnerList()); if (!member) return std::nullopt; members.push_back(std::move(*member)); SkipOWS(); if (input_.empty()) break; if (!ConsumeChar(',')) return std::nullopt; SkipOWS(); if (input_.empty()) return std::nullopt; } return members; } std::optional<ParameterizedItem> ReadItem() { std::optional<Item> item = ReadBareItem(); if (!item) return std::nullopt; std::optional<Parameters> parameters = ReadParameters(); if (!parameters) return std::nullopt; return ParameterizedItem(std::move(*item), std::move(*parameters)); } std::optional<Item> ReadBareItem() { if (input_.empty()) { QUICHE_DVLOG(1) << "ReadBareItem: unexpected EOF"; return std::nullopt; } switch (input_.front()) { case '"': return ReadString(); case '*': if (version_ == kDraft09) return ReadByteSequence(); return ReadToken(); case ':': if (version_ == kFinal) return ReadByteSequence(); return std::nullopt; case '?': return ReadBoolean(); default: if (input_.front() == '-' || absl::ascii_isdigit(input_.front())) return ReadNumber(); if (absl::ascii_isalpha(input_.front())) return ReadToken(); return std::nullopt; } } std::optional<Dictionary> ReadDictionary() { QUICHE_CHECK_EQ(version_, kFinal); Dictionary members; while (!input_.empty()) { std::optional<std::string> key(ReadKey()); if (!key) return std::nullopt; std::optional<ParameterizedMember> member; if (ConsumeChar('=')) { member = ReadItemOrInnerList(); if (!member) return std::nullopt; } else { std::optional<Parameters> parameters = ReadParameters(); if (!parameters) return std::nullopt; member = ParameterizedMember{Item(true), std::move(*parameters)}; } members[*key] = std::move(*member); SkipOWS(); if (input_.empty()) break; if (!ConsumeChar(',')) return std::nullopt; SkipOWS(); if (input_.empty()) return std::nullopt; } return members; } std::optional<ParameterisedList> ReadParameterisedList() { QUICHE_CHECK_EQ(version_, kDraft09); ParameterisedList items; while (true) { std::optional<ParameterisedIdentifier> item = ReadParameterisedIdentifier(); if (!item) return std::nullopt; items.push_back(std::move(*item)); SkipWhitespaces(); if (!ConsumeChar(',')) return items; SkipWhitespaces(); } } private: std::optional<ParameterisedIdentifier> ReadParameterisedIdentifier() { QUICHE_CHECK_EQ(version_, kDraft09); std::optional<Item> primary_identifier = ReadToken(); if (!primary_identifier) return std::nullopt; ParameterisedIdentifier::Parameters parameters; SkipWhitespaces(); while (ConsumeChar(';')) { SkipWhitespaces(); std::optional<std::string> name = ReadKey(); if (!name) return std::nullopt; Item value; if (ConsumeChar('=')) { auto item = ReadBareItem(); if (!item) return std::nullopt; value = std::move(*item); } if (!parameters.emplace(*name, std::move(value)).second) { QUICHE_DVLOG(1) << "ReadParameterisedIdentifier: duplicated parameter: " << *name; return std::nullopt; } SkipWhitespaces(); } return ParameterisedIdentifier(std::move(*primary_identifier), std::move(parameters)); } std::optional<ParameterizedMember> ReadItemOrInnerList() { QUICHE_CHECK_EQ(version_, kFinal); bool member_is_inner_list = (!input_.empty() && input_.front() == '('); if (member_is_inner_list) { return ReadInnerList(); } else { auto item = ReadItem(); if (!item) return std::nullopt; return ParameterizedMember(std::move(item->item), std::move(item->params)); } } std::optional<Parameters> ReadParameters() { Parameters parameters; absl::flat_hash_set<std::string> keys; while (ConsumeChar(';')) { SkipWhitespaces(); std::optional<std::string> name = ReadKey(); if (!name) return std::nullopt; bool is_duplicate_key = !keys.insert(*name).second; Item value{true}; if (ConsumeChar('=')) { auto item = ReadBareItem(); if (!item) return std::nullopt; value = std::move(*item); } if (is_duplicate_key) { for (auto& param : parameters) { if (param.first == name) { param.second = std::move(value); break; } } } else { parameters.emplace_back(std::move(*name), std::move(value)); } } return parameters; } std::optional<ParameterizedMember> ReadInnerList() { QUICHE_CHECK_EQ(version_, kFinal); if (!ConsumeChar('(')) return std::nullopt; std::vector<ParameterizedItem> inner_list; while (true) { SkipWhitespaces(); if (ConsumeChar(')')) { std::optional<Parameters> parameters = ReadParameters(); if (!parameters) return std::nullopt; return ParameterizedMember(std::move(inner_list), true, std::move(*parameters)); } auto item = ReadItem(); if (!item) return std::nullopt; inner_list.push_back(std::move(*item)); if (input_.empty() || (input_.front() != ' ' && input_.front() != ')')) return std::nullopt; } QUICHE_NOTREACHED(); return std::nullopt; } std::optional<std::string> ReadKey() { if (version_ == kDraft09) { if (input_.empty() || !absl::ascii_islower(input_.front())) { LogParseError("ReadKey", "lcalpha"); return std::nullopt; } } else { if (input_.empty() || (!absl::ascii_islower(input_.front()) && input_.front() != '*')) { LogParseError("ReadKey", "lcalpha | *"); return std::nullopt; } } const char* allowed_chars = (version_ == kDraft09 ? kKeyChars09 : kKeyChars); size_t len = input_.find_first_not_of(allowed_chars); if (len == absl::string_view::npos) len = input_.size(); std::string key(input_.substr(0, len)); input_.remove_prefix(len); return key; } std::optional<Item> ReadToken() { if (input_.empty() || !(absl::ascii_isalpha(input_.front()) || input_.front() == '*')) { LogParseError("ReadToken", "ALPHA"); return std::nullopt; } size_t len = input_.find_first_not_of(version_ == kDraft09 ? kTokenChars09 : kTokenChars); if (len == absl::string_view::npos) len = input_.size(); std::string token(input_.substr(0, len)); input_.remove_prefix(len); return Item(std::move(token), Item::kTokenType); } std::optional<Item> ReadNumber() { bool is_negative = ConsumeChar('-'); bool is_decimal = false; size_t decimal_position = 0; size_t i = 0; for (; i < input_.size(); ++i) { if (i > 0 && input_[i] == '.' && !is_decimal) { is_decimal = true; decimal_position = i; continue; } if (!absl::ascii_isdigit(input_[i])) break; } if (i == 0) { LogParseError("ReadNumber", "DIGIT"); return std::nullopt; } if (!is_decimal) { if (version_ == kFinal && i > 15) { LogParseError("ReadNumber", "integer too long"); return std::nullopt; } } else { if (version_ != kFinal && i > 16) { LogParseError("ReadNumber", "float too long"); return std::nullopt; } if (version_ == kFinal && decimal_position > 12) { LogParseError("ReadNumber", "decimal too long"); return std::nullopt; } if (i - decimal_position > (version_ == kFinal ? 4 : 7)) { LogParseError("ReadNumber", "too many digits after decimal"); return std::nullopt; } if (i == decimal_position) { LogParseError("ReadNumber", "no digits after decimal"); return std::nullopt; } } std::string output_number_string(input_.substr(0, i)); input_.remove_prefix(i); if (is_decimal) { double f; if (!absl::SimpleAtod(output_number_string, &f)) return std::nullopt; return Item(is_negative ? -f : f); } else { int64_t n; if (!absl::SimpleAtoi(output_number_string, &n)) return std::nullopt; QUICHE_CHECK(version_ != kFinal || (n <= kMaxInteger && n >= kMinInteger)); return Item(is_negative ? -n : n); } } std::optional<Item> ReadString() { std::string s; if (!ConsumeChar('"')) { LogParseError("ReadString", "'\"'"); return std::nullopt; } while (!ConsumeChar('"')) { size_t i = 0; for (; i < input_.size(); ++i) { if (!absl::ascii_isprint(input_[i])) { QUICHE_DVLOG(1) << "ReadString: non printable-ASCII character"; return std::nullopt; } if (input_[i] == '"' || input_[i] == '\\') break; } if (i == input_.size()) { QUICHE_DVLOG(1) << "ReadString: missing closing '\"'"; return std::nullopt; } s.append(std::string(input_.substr(0, i))); input_.remove_prefix(i); if (ConsumeChar('\\')) { if (input_.empty()) { QUICHE_DVLOG(1) << "ReadString: backslash at string end"; return std::nullopt; } if (input_[0] != '"' && input_[0] != '\\') { QUICHE_DVLOG(1) << "ReadString: invalid escape"; return std::nullopt; } s.push_back(input_.front()); input_.remove_prefix(1); } } return s; } std::optional<Item> ReadByteSequence() { char delimiter = (version_ == kDraft09 ? '*' : ':'); if (!ConsumeChar(delimiter)) { LogParseError("ReadByteSequence", "delimiter"); return std::nullopt; } size_t len = input_.find(delimiter); if (len == absl::string_view::npos) { QUICHE_DVLOG(1) << "ReadByteSequence: missing closing delimiter"; return std::nullopt; } std::string base64(input_.substr(0, len)); base64.resize((base64.size() + 3) / 4 * 4, '='); std::string binary; if (!absl::Base64Unescape(base64, &binary)) { QUICHE_DVLOG(1) << "ReadByteSequence: failed to decode base64: " << base64; return std::nullopt; } input_.remove_prefix(len); ConsumeChar(delimiter); return Item(std::move(binary), Item::kByteSequenceType); } std::optional<Item> ReadBoolean() { if (!ConsumeChar('?')) { LogParseError("ReadBoolean", "'?'"); return std::nullopt; } if (ConsumeChar('1')) { return Item(true); } if (ConsumeChar('0')) { return Item(false); } return std::nullopt; } void SkipWhitespaces() { if (version_ == kDraft09) { StripLeft(input_, kOWS); } else { StripLeft(input_, kSP); } } void SkipOWS() { StripLeft(input_, kOWS); } bool ConsumeChar(char expected) { if (!input_.empty() && input_.front() == expected) { input_.remove_prefix(1); return true; } return false; } void LogParseError(const char* func, const char* expected) { QUICHE_DVLOG(1) << func << ": " << expected << " expected, got " << (input_.empty() ? "EOS" : "'" + std::string(input_.substr(0, 1)) + "'"); } absl::string_view input_; DraftVersion version_; }; class StructuredHeaderSerializer { public: StructuredHeaderSerializer() = default; ~StructuredHeaderSerializer() = default; StructuredHeaderSerializer(const StructuredHeaderSerializer&) = delete; StructuredHeaderSerializer& operator=(const StructuredHeaderSerializer&) = delete; std::string Output() { return output_.str(); } bool WriteList(const List& value) { bool first = true; for (const auto& member : value) { if (!first) output_ << ", "; if (!WriteParameterizedMember(member)) return false; first = false; } return true; } bool WriteItem(const ParameterizedItem& value) { if (!WriteBareItem(value.item)) return false; return WriteParameters(value.params); } bool WriteBareItem(const Item& value) { if (value.is_string()) { output_ << "\""; for (const char& c : value.GetString()) { if (!absl::ascii_isprint(c)) return false; if (c == '\\' || c == '\"') output_ << "\\"; output_ << c; } output_ << "\""; return true; } if (value.is_token()) { if (!IsValidToken(value.GetString())) { return false; } output_ << value.GetString(); return true; } if (value.is_byte_sequence()) { output_ << ":"; output_ << absl::Base64Escape(value.GetString()); output_ << ":"; return true; } if (value.is_integer()) { if (value.GetInteger() > kMaxInteger || value.GetInteger() < kMinInteger) return false; output_ << value.GetInteger(); return true; } if (value.is_decimal()) { double decimal_value = value.GetDecimal(); if (!std::isfinite(decimal_value) || fabs(decimal_value) >= kTooLargeDecimal) return false; if (decimal_value < 0) output_ << "-"; decimal_value = fabs(decimal_value); double remainder = fmod(decimal_value, 0.002); if (remainder == 0.0005) { decimal_value -= 0.0005; } else if (remainder == 0.0015) { decimal_value += 0.0005; } else { decimal_value = round(decimal_value * 1000.0) / 1000.0; } char buffer[17]; absl::SNPrintF(buffer, std::size(buffer), "%#.3f", decimal_value); absl::string_view formatted_number(buffer); auto truncate_index = formatted_number.find_last_not_of('0'); if (formatted_number[truncate_index] == '.') truncate_index++; output_ << formatted_number.substr(0, truncate_index + 1); return true; } if (value.is_boolean()) { output_ << (value.GetBoolean() ? "?1" : "?0"); return true; } return false; } bool WriteDictionary(const Dictionary& value) { bool first = true; for (const auto& [dict_key, dict_value] : value) { if (!first) output_ << ", "; if (!WriteKey(dict_key)) return false; first = false; if (!dict_value.member_is_inner_list && !dict_value.member.empty() && dict_value.member.front().item.is_boolean() && dict_value.member.front().item.GetBoolean()) { if (!WriteParameters(dict_value.params)) return false; } else { output_ << "="; if (!WriteParameterizedMember(dict_value)) return false; } } return true; } private: bool WriteParameterizedMember(const ParameterizedMember& value) { if (value.member_is_inner_list) { if (!WriteInnerList(value.member)) return false; } else { QUICHE_CHECK_EQ(value.member.size(), 1UL); if (!WriteItem(value.member[0])) return false; } return WriteParameters(value.params); } bool WriteInnerList(const std::vector<ParameterizedItem>& value) { output_ << "("; bool first = true; for (const ParameterizedItem& member : value) { if (!first) output_ << " "; if (!WriteItem(member)) return false; first = false; } output_ << ")"; return true; } bool WriteParameters(const Parameters& value) { for (const auto& param_name_and_value : value) { const std::string& param_name = param_name_and_value.first; const Item& param_value = param_name_and_value.second; output_ << ";"; if (!WriteKey(param_name)) return false; if (!param_value.is_null()) { if (param_value.is_boolean() && param_value.GetBoolean()) continue; output_ << "="; if (!WriteBareItem(param_value)) return false; } } return true; } bool WriteKey(const std::string& value) { if (value.empty()) return false; if (value.find_first_not_of(kKeyChars) != std::string::npos) return false; if (!absl::ascii_islower(value[0]) && value[0] != '*') return false; output_ << value; return true; } std::ostringstream output_; }; } absl::string_view ItemTypeToString(Item::ItemType type) { switch (type) { case Item::kNullType: return "null"; case Item::kIntegerType: return "integer"; case Item::kDecimalType: return "decimal"; case Item::kStringType: return "string"; case Item::kTokenType: return "token"; case Item::kByteSequenceType: return "byte sequence"; case Item::kBooleanType: return "boolean"; } return "[invalid type]"; } bool IsValidToken(absl::string_view str) { if (str.empty() || !(absl::ascii_isalpha(str.front()) || str.front() == '*')) { return false; } if (str.find_first_not_of(kTokenChars) != std::string::npos) { return false; } return true; } Item::Item() {} Item::Item(std::string value, Item::ItemType type) { switch (type) { case kStringType: value_.emplace<kStringType>(std::move(value)); break; case kTokenType: value_.emplace<kTokenType>(std::move(value)); break; case kByteSequenceType: value_.emplace<kByteSequenceType>(std::move(value)); break; default: QUICHE_CHECK(false); break; } } Item::Item(const char* value, Item::ItemType type) : Item(std::string(value), type) {} Item::Item(int64_t value) : value_(value) {} Item::Item(double value) : value_(value) {} Item::Item(bool value) : value_(value) {} bool operator==(const Item& lhs, const Item& rhs) { return lhs.value_ == rhs.value_; } ParameterizedItem::ParameterizedItem() = default; ParameterizedItem::ParameterizedItem(const ParameterizedItem&) = default; ParameterizedItem& ParameterizedItem::operator=(const ParameterizedItem&) = default; ParameterizedItem::ParameterizedItem(Item id, Parameters ps) : item(std::move(id)), params(std::move(ps)) {} ParameterizedItem::~ParameterizedItem() = default; ParameterizedMember::ParameterizedMember() = default; ParameterizedMember::ParameterizedMember(const ParameterizedMember&) = default; ParameterizedMember& ParameterizedMember::operator=( const ParameterizedMember&) = default; ParameterizedMember::ParameterizedMember(std::vector<ParameterizedItem> id, bool member_is_inner_list, Parameters ps) : member(std::move(id)), member_is_inner_list(member_is_inner_list), params(std::move(ps)) {} ParameterizedMember::ParameterizedMember(std::vector<ParameterizedItem> id, Parameters ps) : member(std::move(id)), member_is_inner_list(true), params(std::move(ps)) {} ParameterizedMember::ParameterizedMember(Item id, Parameters ps) : member({{std::move(id), {}}}), member_is_inner_list(false), params(std::move(ps)) {} ParameterizedMember::~ParameterizedMember() = default; ParameterisedIdentifier::ParameterisedIdentifier() = default; ParameterisedIdentifier::ParameterisedIdentifier( const ParameterisedIdentifier&) = default; ParameterisedIdentifier& ParameterisedIdentifier::operator=( const ParameterisedIdentifier&) = default; ParameterisedIdentifier::ParameterisedIdentifier(Item id, Parameters ps) : identifier(std::move(id)), params(std::move(ps)) {} ParameterisedIdentifier::~ParameterisedIdentifier() = default; Dictionary::Dictionary() = default; Dictionary::Dictionary(const Dictionary&) = default; Dictionary::Dictionary(Dictionary&&) = default; Dictionary::Dictionary(std::vector<DictionaryMember> members) : members_(std::move(members)) {} Dictionary::~Dictionary() = default; Dictionary::iterator Dictionary::begin() { return members_.begin(); } Dictionary::const_iterator Dictionary::begin() const { return members_.begin(); } Dictionary::iterator Dictionary::end() { return members_.end(); } Dictionary::const_iterator Dictionary::end() const { return members_.end(); } ParameterizedMember& Dictionary::operator[](std::size_t idx) { return members_[idx].second; } const ParameterizedMember& Dictionary::operator[](std::size_t idx) const { return members_[idx].second; } ParameterizedMember& Dictionary::at(std::size_t idx) { return (*this)[idx]; } const ParameterizedMember& Dictionary::at(std::size_t idx) const { return (*this)[idx]; } ParameterizedMember& Dictionary::operator[](absl::string_view key) { auto it = find(key); if (it != end()) return it->second; return members_.emplace_back(key, ParameterizedMember()).second; } ParameterizedMember& Dictionary::at(absl::string_view key) { auto it = find(key); QUICHE_CHECK(it != end()) << "Provided key not found in dictionary"; return it->second; } const ParameterizedMember& Dictionary::at(absl::string_view key) const { auto it = find(key); QUICHE_CHECK(it != end()) << "Provided key not found in dictionary"; return it->second; } Dictionary::const_iterator Dictionary::find(absl::string_view key) const { return absl::c_find_if( members_, [key](const auto& member) { return member.first == key; }); } Dictionary::iterator Dictionary::find(absl::string_view key) { return absl::c_find_if( members_, [key](const auto& member) { return member.first == key; }); } bool Dictionary::empty() const { return members_.empty(); } std::size_t Dictionary::size() const { return members_.size(); } bool Dictionary::contains(absl::string_view key) const { return find(key) != end(); } void Dictionary::clear() { members_.clear(); } std::optional<ParameterizedItem> ParseItem(absl::string_view str) { StructuredHeaderParser parser(str, StructuredHeaderParser::kFinal); std::optional<ParameterizedItem> item = parser.ReadItem(); if (item && parser.FinishParsing()) return item; return std::nullopt; } std::optional<Item> ParseBareItem(absl::string_view str) { StructuredHeaderParser parser(str, StructuredHeaderParser::kFinal); std::optional<Item> item = parser.ReadBareItem(); if (item && parser.FinishParsing()) return item; return std::nullopt; } std::optional<ParameterisedList> ParseParameterisedList(absl::string_view str) { StructuredHeaderParser parser(str, StructuredHeaderParser::kDraft09); std::optional<ParameterisedList> param_list = parser.ReadParameterisedList(); if (param_list && parser.FinishParsing()) return param_list; return std::nullopt; } std::optional<ListOfLists> ParseListOfLists(absl::string_view str) { StructuredHeaderParser parser(str, StructuredHeaderParser::kDraft09); std::optional<ListOfLists> list_of_lists = parser.ReadListOfLists(); if (list_of_lists && parser.FinishParsing()) return list_of_lists; return std::nullopt; } std::optional<List> ParseList(absl::string_view str) { StructuredHeaderParser parser(str, StructuredHeaderParser::kFinal); std::optional<List> list = parser.ReadList(); if (list && parser.FinishParsing()) return list; return std::nullopt; } std::optional<Dictionary> ParseDictionary(absl::string_view str) { StructuredHeaderParser parser(str, StructuredHeaderParser::kFinal); std::optional<Dictionary> dictionary = parser.ReadDictionary(); if (dictionary && parser.FinishParsing()) return dictionary; return std::nullopt; } std::optional<std::string> SerializeItem(const Item& value) { StructuredHeaderSerializer s; if (s.WriteItem(ParameterizedItem(value, {}))) return s.Output(); return std::nullopt; } std::optional<std::string> SerializeItem(const ParameterizedItem& value) { StructuredHeaderSerializer s; if (s.WriteItem(value)) return s.Output(); return std::nullopt; } std::optional<std::string> SerializeList(const List& value) { StructuredHeaderSerializer s; if (s.WriteList(value)) return s.Output(); return std::nullopt; } std::optional<std::string> SerializeDictionary(const Dictionary& value) { StructuredHeaderSerializer s; if (s.WriteDictionary(value)) return s.Output(); return std::nullopt; } } }
#include "quiche/common/structured_headers.h" #include <math.h> #include <limits> #include <optional> #include <string> #include <utility> #include "quiche/common/platform/api/quiche_test.h" namespace quiche { namespace structured_headers { namespace { Item Token(std::string value) { return Item(value, Item::kTokenType); } Item Integer(int64_t value) { return Item(value); } std::pair<std::string, Item> NullParam(std::string key) { return std::make_pair(key, Item()); } std::pair<std::string, Item> BooleanParam(std::string key, bool value) { return std::make_pair(key, Item(value)); } std::pair<std::string, Item> DoubleParam(std::string key, double value) { return std::make_pair(key, Item(value)); } std::pair<std::string, Item> Param(std::string key, int64_t value) { return std::make_pair(key, Item(value)); } std::pair<std::string, Item> Param(std::string key, std::string value) { return std::make_pair(key, Item(value)); } std::pair<std::string, Item> ByteSequenceParam(std::string key, std::string value) { return std::make_pair(key, Item(value, Item::kByteSequenceType)); } std::pair<std::string, Item> TokenParam(std::string key, std::string value) { return std::make_pair(key, Token(value)); } const struct ItemTestCase { const char* name; const char* raw; const std::optional<Item> expected; const char* canonical; } item_test_cases[] = { {"bad token - item", "abc$@%!", std::nullopt, nullptr}, {"leading whitespace", " foo", Token("foo"), "foo"}, {"trailing whitespace", "foo ", Token("foo"), "foo"}, {"leading asterisk", "*foo", Token("*foo"), nullptr}, {"long integer", "999999999999999", Integer(999999999999999L), nullptr}, {"long negative integer", "-999999999999999", Integer(-999999999999999L), nullptr}, {"too long integer", "1000000000000000", std::nullopt, nullptr}, {"negative too long integer", "-1000000000000000", std::nullopt, nullptr}, {"integral decimal", "1.0", Item(1.0), nullptr}, {"basic string", "\"foo\"", Item("foo"), nullptr}, {"non-ascii string", "\"f\xC3\xBC\xC3\xBC\"", std::nullopt, nullptr}, {"valid quoting containing \\n", "\"\\\\n\"", Item("\\n"), nullptr}, {"valid quoting containing \\t", "\"\\\\t\"", Item("\\t"), nullptr}, {"valid quoting containing \\x", "\"\\\\x61\"", Item("\\x61"), nullptr}, {"c-style hex escape in string", "\"\\x61\"", std::nullopt, nullptr}, {"valid quoting containing \\u", "\"\\\\u0061\"", Item("\\u0061"), nullptr}, {"c-style unicode escape in string", "\"\\u0061\"", std::nullopt, nullptr}, }; const ItemTestCase sh09_item_test_cases[] = { {"large integer", "9223372036854775807", Integer(9223372036854775807L), nullptr}, {"large negative integer", "-9223372036854775807", Integer(-9223372036854775807L), nullptr}, {"too large integer", "9223372036854775808", std::nullopt, nullptr}, {"too large negative integer", "-9223372036854775808", std::nullopt, nullptr}, {"basic binary", "*aGVsbG8=*", Item("hello", Item::kByteSequenceType), nullptr}, {"empty binary", "**", Item("", Item::kByteSequenceType), nullptr}, {"bad paddding", "*aGVsbG8*", Item("hello", Item::kByteSequenceType), "*aGVsbG8=*"}, {"bad end delimiter", "*aGVsbG8=", std::nullopt, nullptr}, {"extra whitespace", "*aGVsb G8=*", std::nullopt, nullptr}, {"extra chars", "*aGVsbG!8=*", std::nullopt, nullptr}, {"suffix chars", "*aGVsbG8=!*", std::nullopt, nullptr}, {"non-zero pad bits", "*iZ==*", Item("\x89", Item::kByteSequenceType), "*iQ==*"}, {"non-ASCII binary", "*/+Ah*", Item("\xFF\xE0!", Item::kByteSequenceType), nullptr}, {"base64url binary", "*_-Ah*", std::nullopt, nullptr}, {"token with leading asterisk", "*foo", std::nullopt, nullptr}, }; const struct ParameterizedItemTestCase { const char* name; const char* raw; const std::optional<ParameterizedItem> expected; const char* canonical; } parameterized_item_test_cases[] = { {"single parameter item", "text/html;q=1.0", {{Token("text/html"), {DoubleParam("q", 1)}}}, nullptr}, {"missing parameter value item", "text/html;a;q=1.0", {{Token("text/html"), {BooleanParam("a", true), DoubleParam("q", 1)}}}, nullptr}, {"missing terminal parameter value item", "text/html;q=1.0;a", {{Token("text/html"), {DoubleParam("q", 1), BooleanParam("a", true)}}}, nullptr}, {"duplicate parameter keys with different value", "text/html;a=1;b=2;a=3.0", {{Token("text/html"), {DoubleParam("a", 3), Param("b", 2L)}}}, "text/html;a=3.0;b=2"}, {"multiple duplicate parameter keys at different position", "text/html;c=1;a=2;b;b=3.0;a", {{Token("text/html"), {Param("c", 1L), BooleanParam("a", true), DoubleParam("b", 3)}}}, "text/html;c=1;a;b=3.0"}, {"duplicate parameter keys with missing value", "text/html;a;a=1", {{Token("text/html"), {Param("a", 1L)}}}, "text/html;a=1"}, {"whitespace before = parameterised item", "text/html, text/plain;q =0.5", std::nullopt, nullptr}, {"whitespace after = parameterised item", "text/html, text/plain;q= 0.5", std::nullopt, nullptr}, {"whitespace before ; parameterised item", "text/html, text/plain ;q=0.5", std::nullopt, nullptr}, {"whitespace after ; parameterised item", "text/plain; q=0.5", {{Token("text/plain"), {DoubleParam("q", 0.5)}}}, "text/plain;q=0.5"}, {"extra whitespace parameterised item", "text/plain; q=0.5; charset=utf-8", {{Token("text/plain"), {DoubleParam("q", 0.5), TokenParam("charset", "utf-8")}}}, "text/plain;q=0.5;charset=utf-8"}, }; const struct ListTestCase { const char* name; const char* raw; const std::optional<List> expected; const char* canonical; } list_test_cases[] = { {"extra whitespace list of lists", "(1 42)", {{{{{Integer(1L), {}}, {Integer(42L), {}}}, {}}}}, "(1 42)"}, {"basic parameterised list", "abc_123;a=1;b=2; cdef_456, ghi;q=\"9\";r=\"+w\"", {{{Token("abc_123"), {Param("a", 1), Param("b", 2), BooleanParam("cdef_456", true)}}, {Token("ghi"), {Param("q", "9"), Param("r", "+w")}}}}, "abc_123;a=1;b=2;cdef_456, ghi;q=\"9\";r=\"+w\""}, {"parameterised basic list of lists", "(1;a=1.0 2), (42 43)", {{{{{Integer(1L), {DoubleParam("a", 1.0)}}, {Integer(2L), {}}}, {}}, {{{Integer(42L), {}}, {Integer(43L), {}}}, {}}}}, nullptr}, {"parameters on inner members", "(1;a=1.0 2;b=c), (42;d=?0 43;e=:Zmdo:)", {{{{{Integer(1L), {DoubleParam("a", 1.0)}}, {Integer(2L), {TokenParam("b", "c")}}}, {}}, {{{Integer(42L), {BooleanParam("d", false)}}, {Integer(43L), {ByteSequenceParam("e", "fgh")}}}, {}}}}, nullptr}, {"parameters on inner lists", "(1 2);a=1.0, (42 43);b=?0", {{{{{Integer(1L), {}}, {Integer(2L), {}}}, {DoubleParam("a", 1.0)}}, {{{Integer(42L), {}}, {Integer(43L), {}}}, {BooleanParam("b", false)}}}}, nullptr}, {"default true values for parameters on inner list members", "(1;a 2), (42 43;b)", {{{{{Integer(1L), {BooleanParam("a", true)}}, {Integer(2L), {}}}, {}}, {{{Integer(42L), {}}, {Integer(43L), {BooleanParam("b", true)}}}, {}}}}, nullptr}, {"default true values for parameters on inner lists", "(1 2);a, (42 43);b", {{{{{Integer(1L), {}}, {Integer(2L), {}}}, {BooleanParam("a", true)}}, {{{Integer(42L), {}}, {Integer(43L), {}}}, {BooleanParam("b", true)}}}}, nullptr}, {"extra whitespace before semicolon in parameters on inner list member", "(a;b ;c b)", std::nullopt, nullptr}, {"extra whitespace between parameters on inner list member", "(a;b; c b)", {{{{{Token("a"), {BooleanParam("b", true), BooleanParam("c", true)}}, {Token("b"), {}}}, {}}}}, "(a;b;c b)"}, {"extra whitespace before semicolon in parameters on inner list", "(a b);c ;d, (e)", std::nullopt, nullptr}, {"extra whitespace between parameters on inner list", "(a b);c; d, (e)", {{{{{Token("a"), {}}, {Token("b"), {}}}, {BooleanParam("c", true), BooleanParam("d", true)}}, {{{Token("e"), {}}}, {}}}}, "(a b);c;d, (e)"}, }; const struct DictionaryTestCase { const char* name; const char* raw; const std::optional<Dictionary> expected; const char* canonical; } dictionary_test_cases[] = { {"basic dictionary", "en=\"Applepie\", da=:aGVsbG8=:", {Dictionary{{{"en", {Item("Applepie"), {}}}, {"da", {Item("hello", Item::kByteSequenceType), {}}}}}}, nullptr}, {"tab separated dictionary", "a=1\t,\tb=2", {Dictionary{{{"a", {Integer(1L), {}}}, {"b", {Integer(2L), {}}}}}}, "a=1, b=2"}, {"missing value with params dictionary", "a=1, b;foo=9, c=3", {Dictionary{{{"a", {Integer(1L), {}}}, {"b", {Item(true), {Param("foo", 9)}}}, {"c", {Integer(3L), {}}}}}}, nullptr}, {"parameterised inner list member dict", "a=(\"1\";b=1;c=?0 \"2\");d=\"e\"", {Dictionary{{{"a", {{{Item("1"), {Param("b", 1), BooleanParam("c", false)}}, {Item("2"), {}}}, {Param("d", "e")}}}}}}, nullptr}, {"explicit true value with parameter", "a=?1;b=1", {Dictionary{{{"a", {Item(true), {Param("b", 1)}}}}}}, "a;b=1"}, {"implicit true value with parameter", "a;b=1", {Dictionary{{{"a", {Item(true), {Param("b", 1)}}}}}}, nullptr}, {"implicit true value with implicitly-valued parameter", "a;b", {Dictionary{{{"a", {Item(true), {BooleanParam("b", true)}}}}}}, nullptr}, }; } TEST(StructuredHeaderTest, ParseBareItem) { for (const auto& c : item_test_cases) { SCOPED_TRACE(c.name); std::optional<Item> result = ParseBareItem(c.raw); EXPECT_EQ(result, c.expected); } } TEST(StructuredHeaderTest, ParseItem) { for (const auto& c : parameterized_item_test_cases) { SCOPED_TRACE(c.name); std::optional<ParameterizedItem> result = ParseItem(c.raw); EXPECT_EQ(result, c.expected); } } TEST(StructuredHeaderTest, ParseSH09Item) { for (const auto& c : sh09_item_test_cases) { SCOPED_TRACE(c.name); std::optional<ListOfLists> result = ParseListOfLists(c.raw); if (c.expected.has_value()) { EXPECT_TRUE(result.has_value()); EXPECT_EQ(result->size(), 1UL); EXPECT_EQ((*result)[0].size(), 1UL); EXPECT_EQ((*result)[0][0], c.expected); } else { EXPECT_FALSE(result.has_value()); } } } TEST(StructuredHeaderTest, SH09HighPrecisionFloats) { std::optional<ListOfLists> result = ParseListOfLists("1.03125;-1.03125;12345678901234.5;-12345678901234.5"); ASSERT_TRUE(result.has_value()); EXPECT_EQ(*result, (ListOfLists{{Item(1.03125), Item(-1.03125), Item(12345678901234.5), Item(-12345678901234.5)}})); result = ParseListOfLists("123456789012345.0"); EXPECT_FALSE(result.has_value()); result = ParseListOfLists("-123456789012345.0"); EXPECT_FALSE(result.has_value()); } TEST(StructuredHeaderTest, ParseListOfLists) { static const struct TestCase { const char* name; const char* raw; ListOfLists expected; } cases[] = { {"basic list of lists", "1;2, 42;43", {{Integer(1L), Integer(2L)}, {Integer(42L), Integer(43L)}}}, {"empty list of lists", "", {}}, {"single item list of lists", "42", {{Integer(42L)}}}, {"no whitespace list of lists", "1,42", {{Integer(1L)}, {Integer(42L)}}}, {"no inner whitespace list of lists", "1;2, 42;43", {{Integer(1L), Integer(2L)}, {Integer(42L), Integer(43L)}}}, {"extra whitespace list of lists", "1 , 42", {{Integer(1L)}, {Integer(42L)}}}, {"extra inner whitespace list of lists", "1 ; 2,42 ; 43", {{Integer(1L), Integer(2L)}, {Integer(42L), Integer(43L)}}}, {"trailing comma list of lists", "1;2, 42,", {}}, {"trailing semicolon list of lists", "1;2, 42;43;", {}}, {"leading comma list of lists", ",1;2, 42", {}}, {"leading semicolon list of lists", ";1;2, 42;43", {}}, {"empty item list of lists", "1,,42", {}}, {"empty inner item list of lists", "1;;2,42", {}}, }; for (const auto& c : cases) { SCOPED_TRACE(c.name); std::optional<ListOfLists> result = ParseListOfLists(c.raw); if (!c.expected.empty()) { EXPECT_TRUE(result.has_value()); EXPECT_EQ(*result, c.expected); } else { EXPECT_FALSE(result.has_value()); } } } TEST(StructuredHeaderTest, ParseParameterisedList) { static const struct TestCase { const char* name; const char* raw; ParameterisedList expected; } cases[] = { {"basic param-list", "abc_123;a=1;b=2; cdef_456, ghi;q=\"9\";r=\"w\"", { {Token("abc_123"), {Param("a", 1), Param("b", 2), NullParam("cdef_456")}}, {Token("ghi"), {Param("q", "9"), Param("r", "w")}}, }}, {"empty param-list", "", {}}, {"single item param-list", "text/html;q=1", {{Token("text/html"), {Param("q", 1)}}}}, {"empty param-list", "", {}}, {"no whitespace param-list", "text/html,text/plain;q=1", {{Token("text/html"), {}}, {Token("text/plain"), {Param("q", 1)}}}}, {"whitespace before = param-list", "text/html, text/plain;q =1", {}}, {"whitespace after = param-list", "text/html, text/plain;q= 1", {}}, {"extra whitespace param-list", "text/html , text/plain ; q=1", {{Token("text/html"), {}}, {Token("text/plain"), {Param("q", 1)}}}}, {"duplicate key", "abc;a=1;b=2;a=1", {}}, {"numeric key", "abc;a=1;1b=2;c=1", {}}, {"uppercase key", "abc;a=1;B=2;c=1", {}}, {"bad key", "abc;a=1;b!=2;c=1", {}}, {"another bad key", "abc;a=1;b==2;c=1", {}}, {"empty key name", "abc;a=1;=2;c=1", {}}, {"empty parameter", "abc;a=1;;c=1", {}}, {"empty list item", "abc;a=1,,def;b=1", {}}, {"extra semicolon", "abc;a=1;b=1;", {}}, {"extra comma", "abc;a=1,def;b=1,", {}}, {"leading semicolon", ";abc;a=1", {}}, {"leading comma", ",abc;a=1", {}}, }; for (const auto& c : cases) { SCOPED_TRACE(c.name); std::optional<ParameterisedList> result = ParseParameterisedList(c.raw); if (c.expected.empty()) { EXPECT_FALSE(result.has_value()); continue; } EXPECT_TRUE(result.has_value()); EXPECT_EQ(result->size(), c.expected.size()); if (result->size() == c.expected.size()) { for (size_t i = 0; i < c.expected.size(); ++i) { EXPECT_EQ((*result)[i], c.expected[i]); } } } } TEST(StructuredHeaderTest, ParseList) { for (const auto& c : list_test_cases) { SCOPED_TRACE(c.name); std::optional<List> result = ParseList(c.raw); EXPECT_EQ(result, c.expected); } } TEST(StructuredHeaderTest, ParseDictionary) { for (const auto& c : dictionary_test_cases) { SCOPED_TRACE(c.name); std::optional<Dictionary> result = ParseDictionary(c.raw); EXPECT_EQ(result, c.expected); } } TEST(StructuredHeaderTest, SerializeItem) { for (const auto& c : item_test_cases) { SCOPED_TRACE(c.name); if (c.expected) { std::optional<std::string> result = SerializeItem(*c.expected); EXPECT_TRUE(result.has_value()); EXPECT_EQ(result.value(), std::string(c.canonical ? c.canonical : c.raw)); } } } TEST(StructuredHeaderTest, SerializeParameterizedItem) { for (const auto& c : parameterized_item_test_cases) { SCOPED_TRACE(c.name); if (c.expected) { std::optional<std::string> result = SerializeItem(*c.expected); EXPECT_TRUE(result.has_value()); EXPECT_EQ(result.value(), std::string(c.canonical ? c.canonical : c.raw)); } } } TEST(StructuredHeaderTest, UnserializableItems) { EXPECT_FALSE(SerializeItem(Item()).has_value()); } TEST(StructuredHeaderTest, UnserializableTokens) { static const struct UnserializableString { const char* name; const char* value; } bad_tokens[] = { {"empty token", ""}, {"contains high ascii", "a\xff"}, {"contains nonprintable character", "a\x7f"}, {"contains C0", "a\x01"}, {"UTF-8 encoded", "a\xc3\xa9"}, {"contains TAB", "a\t"}, {"contains LF", "a\n"}, {"contains CR", "a\r"}, {"contains SP", "a "}, {"begins with digit", "9token"}, {"begins with hyphen", "-token"}, {"begins with LF", "\ntoken"}, {"begins with SP", " token"}, {"begins with colon", ":token"}, {"begins with percent", "%token"}, {"begins with period", ".token"}, {"begins with slash", "/token"}, }; for (const auto& bad_token : bad_tokens) { SCOPED_TRACE(bad_token.name); std::optional<std::string> serialization = SerializeItem(Token(bad_token.value)); EXPECT_FALSE(serialization.has_value()) << *serialization; } } TEST(StructuredHeaderTest, UnserializableKeys) { static const struct UnserializableString { const char* name; const char* value; } bad_keys[] = { {"empty key", ""}, {"contains high ascii", "a\xff"}, {"contains nonprintable character", "a\x7f"}, {"contains C0", "a\x01"}, {"UTF-8 encoded", "a\xc3\xa9"}, {"contains TAB", "a\t"}, {"contains LF", "a\n"}, {"contains CR", "a\r"}, {"contains SP", "a "}, {"begins with uppercase", "Atoken"}, {"begins with digit", "9token"}, {"begins with hyphen", "-token"}, {"begins with LF", "\ntoken"}, {"begins with SP", " token"}, {"begins with colon", ":token"}, {"begins with percent", "%token"}, {"begins with period", ".token"}, {"begins with slash", "/token"}, }; for (const auto& bad_key : bad_keys) { SCOPED_TRACE(bad_key.name); std::optional<std::string> serialization = SerializeItem(ParameterizedItem("a", {{bad_key.value, "a"}})); EXPECT_FALSE(serialization.has_value()) << *serialization; } } TEST(StructuredHeaderTest, UnserializableStrings) { static const struct UnserializableString { const char* name; const char* value; } bad_strings[] = { {"contains high ascii", "a\xff"}, {"contains nonprintable character", "a\x7f"}, {"UTF-8 encoded", "a\xc3\xa9"}, {"contains TAB", "a\t"}, {"contains LF", "a\n"}, {"contains CR", "a\r"}, {"contains C0", "a\x01"}, }; for (const auto& bad_string : bad_strings) { SCOPED_TRACE(bad_string.name); std::optional<std::string> serialization = SerializeItem(Item(bad_string.value)); EXPECT_FALSE(serialization.has_value()) << *serialization; } } TEST(StructuredHeaderTest, UnserializableIntegers) { EXPECT_FALSE(SerializeItem(Integer(1e15L)).has_value()); EXPECT_FALSE(SerializeItem(Integer(-1e15L)).has_value()); } TEST(StructuredHeaderTest, UnserializableDecimals) { for (double value : {std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::infinity(), -std::numeric_limits<double>::infinity(), 1e12, 1e12 - 0.0001, 1e12 - 0.0005, -1e12, -1e12 + 0.0001, -1e12 + 0.0005}) { auto x = SerializeItem(Item(value)); EXPECT_FALSE(SerializeItem(Item(value)).has_value()); } } TEST(StructuredHeaderTest, SerializeUnparseableDecimals) { struct UnparseableDecimal { const char* name; double value; const char* canonical; } float_test_cases[] = { {"negative 0", -0.0, "0.0"}, {"0.0001", 0.0001, "0.0"}, {"0.0000001", 0.0000001, "0.0"}, {"1.0001", 1.0001, "1.0"}, {"1.0009", 1.0009, "1.001"}, {"round positive odd decimal", 0.0015, "0.002"}, {"round positive even decimal", 0.0025, "0.002"}, {"round negative odd decimal", -0.0015, "-0.002"}, {"round negative even decimal", -0.0025, "-0.002"}, {"round decimal up to integer part", 9.9995, "10.0"}, {"subnormal numbers", std::numeric_limits<double>::denorm_min(), "0.0"}, {"round up to 10 digits", 1e9 - 0.0000001, "1000000000.0"}, {"round up to 11 digits", 1e10 - 0.000001, "10000000000.0"}, {"round up to 12 digits", 1e11 - 0.00001, "100000000000.0"}, {"largest serializable float", nextafter(1e12 - 0.0005, 0), "999999999999.999"}, {"largest serializable negative float", -nextafter(1e12 - 0.0005, 0), "-999999999999.999"}, {"float rounds up to next int", 3.9999999, "4.0"}, {"don't double round", 3.99949, "3.999"}, {"don't double round", 123456789.99949, "123456789.999"}, }; for (const auto& test_case : float_test_cases) { SCOPED_TRACE(test_case.name); std::optional<std::string> serialization = SerializeItem(Item(test_case.value)); EXPECT_TRUE(serialization.has_value()); EXPECT_EQ(*serialization, test_case.canonical); } } TEST(StructuredHeaderTest, SerializeList) { for (const auto& c : list_test_cases) { SCOPED_TRACE(c.name); if (c.expected) { std::optional<std::string> result = SerializeList(*c.expected); EXPECT_TRUE(result.has_value()); EXPECT_EQ(result.value(), std::string(c.canonical ? c.canonical : c.raw)); } } } TEST(StructuredHeaderTest, UnserializableLists) { static const struct UnserializableList { const char* name; const List value; } bad_lists[] = { {"Null item as member", {{Item(), {}}}}, {"Unserializable item as member", {{Token("\n"), {}}}}, {"Key is empty", {{Token("abc"), {Param("", 1)}}}}, {"Key containswhitespace", {{Token("abc"), {Param("a\n", 1)}}}}, {"Key contains UTF8", {{Token("abc"), {Param("a\xc3\xa9", 1)}}}}, {"Key contains unprintable characters", {{Token("abc"), {Param("a\x7f", 1)}}}}, {"Key contains disallowed characters", {{Token("abc"), {Param("a:", 1)}}}}, {"Param value is unserializable", {{Token("abc"), {{"a", Token("\n")}}}}}, {"Inner list contains unserializable item", {{std::vector<ParameterizedItem>{{Token("\n"), {}}}, {}}}}, }; for (const auto& bad_list : bad_lists) { SCOPED_TRACE(bad_list.name); std::optional<std::string> serialization = SerializeList(bad_list.value); EXPECT_FALSE(serialization.has_value()) << *serialization; } } TEST(StructuredHeaderTest, SerializeDictionary) { for (const auto& c : dictionary_test_cases) { SCOPED_TRACE(c.name); if (c.expected) { std::optional<std::string> result = SerializeDictionary(*c.expected); EXPECT_TRUE(result.has_value()); EXPECT_EQ(result.value(), std::string(c.canonical ? c.canonical : c.raw)); } } } TEST(StructuredHeaderTest, DictionaryConstructors) { const std::string key0 = "key0"; const std::string key1 = "key1"; const ParameterizedMember member0{Item("Applepie"), {}}; const ParameterizedMember member1{Item("hello", Item::kByteSequenceType), {}}; Dictionary dict; EXPECT_TRUE(dict.empty()); EXPECT_EQ(0U, dict.size()); dict[key0] = member0; EXPECT_FALSE(dict.empty()); EXPECT_EQ(1U, dict.size()); const Dictionary dict_copy = dict; EXPECT_FALSE(dict_copy.empty()); EXPECT_EQ(1U, dict_copy.size()); EXPECT_EQ(dict, dict_copy); const Dictionary dict_init{{{key0, member0}, {key1, member1}}}; EXPECT_FALSE(dict_init.empty()); EXPECT_EQ(2U, dict_init.size()); EXPECT_EQ(member0, dict_init.at(key0)); EXPECT_EQ(member1, dict_init.at(key1)); } TEST(StructuredHeaderTest, DictionaryClear) { const std::string key0 = "key0"; const ParameterizedMember member0{Item("Applepie"), {}}; Dictionary dict({{key0, member0}}); EXPECT_EQ(1U, dict.size()); EXPECT_FALSE(dict.empty()); EXPECT_TRUE(dict.contains(key0)); dict.clear(); EXPECT_EQ(0U, dict.size()); EXPECT_TRUE(dict.empty()); EXPECT_FALSE(dict.contains(key0)); } TEST(StructuredHeaderTest, DictionaryAccessors) { const std::string key0 = "key0"; const std::string key1 = "key1"; const ParameterizedMember nonempty_member0{Item("Applepie"), {}}; const ParameterizedMember nonempty_member1{ Item("hello", Item::kByteSequenceType), {}}; const ParameterizedMember empty_member; Dictionary dict{{{key0, nonempty_member0}}}; EXPECT_TRUE(dict.contains(key0)); EXPECT_EQ(nonempty_member0, dict[key0]); EXPECT_EQ(&dict[key0], &dict.at(key0)); EXPECT_EQ(&dict[key0], &dict[0]); EXPECT_EQ(&dict[key0], &dict.at(0)); { auto it = dict.find(key0); ASSERT_TRUE(it != dict.end()); EXPECT_EQ(it->first, key0); EXPECT_EQ(it->second, nonempty_member0); } ASSERT_FALSE(dict.contains(key1)); EXPECT_TRUE(dict.find(key1) == dict.end()); ParameterizedMember& member1 = dict[key1]; EXPECT_TRUE(dict.contains(key1)); EXPECT_EQ(empty_member, member1); EXPECT_EQ(&member1, &dict[key1]); EXPECT_EQ(&member1, &dict.at(key1)); EXPECT_EQ(&member1, &dict[1]); EXPECT_EQ(&member1, &dict.at(1)); member1 = nonempty_member1; EXPECT_EQ(nonempty_member1, dict[key1]); EXPECT_EQ(&dict[key1], &dict.at(key1)); EXPECT_EQ(&dict[key1], &dict[1]); EXPECT_EQ(&dict[key1], &dict.at(1)); const Dictionary& dict_ref = dict; EXPECT_EQ(&member1, &dict_ref.at(key1)); EXPECT_EQ(&member1, &dict_ref[1]); EXPECT_EQ(&member1, &dict_ref.at(1)); } TEST(StructuredHeaderTest, UnserializableDictionary) { static const struct UnserializableDictionary { const char* name; const Dictionary value; } bad_dictionaries[] = { {"Unserializable dict key", Dictionary{{{"ABC", {Token("abc"), {}}}}}}, {"Dictionary item is unserializable", Dictionary{{{"abc", {Token("abc="), {}}}}}}, {"Param value is unserializable", Dictionary{{{"abc", {Token("abc"), {{"a", Token("\n")}}}}}}}, {"Dictionary inner-list contains unserializable item", Dictionary{ {{"abc", {std::vector<ParameterizedItem>{{Token("abc="), {}}}, {}}}}}}, }; for (const auto& bad_dictionary : bad_dictionaries) { SCOPED_TRACE(bad_dictionary.name); std::optional<std::string> serialization = SerializeDictionary(bad_dictionary.value); EXPECT_FALSE(serialization.has_value()) << *serialization; } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/structured_headers.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/structured_headers_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
23f03aa2-bf49-43f8-b085-00c345b87bac
cpp
google/quiche
quiche_data_writer
quiche/common/quiche_data_writer.cc
quiche/common/quiche_data_writer_test.cc
#include "quiche/common/quiche_data_writer.h" #include <algorithm> #include <limits> #include <string> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/quiche_endian.h" namespace quiche { QuicheDataWriter::QuicheDataWriter(size_t size, char* buffer) : QuicheDataWriter(size, buffer, quiche::NETWORK_BYTE_ORDER) {} QuicheDataWriter::QuicheDataWriter(size_t size, char* buffer, quiche::Endianness endianness) : buffer_(buffer), capacity_(size), length_(0), endianness_(endianness) {} QuicheDataWriter::~QuicheDataWriter() {} char* QuicheDataWriter::data() { return buffer_; } bool QuicheDataWriter::WriteUInt8(uint8_t value) { return WriteBytes(&value, sizeof(value)); } bool QuicheDataWriter::WriteUInt16(uint16_t value) { if (endianness_ == quiche::NETWORK_BYTE_ORDER) { value = quiche::QuicheEndian::HostToNet16(value); } return WriteBytes(&value, sizeof(value)); } bool QuicheDataWriter::WriteUInt32(uint32_t value) { if (endianness_ == quiche::NETWORK_BYTE_ORDER) { value = quiche::QuicheEndian::HostToNet32(value); } return WriteBytes(&value, sizeof(value)); } bool QuicheDataWriter::WriteUInt64(uint64_t value) { if (endianness_ == quiche::NETWORK_BYTE_ORDER) { value = quiche::QuicheEndian::HostToNet64(value); } return WriteBytes(&value, sizeof(value)); } bool QuicheDataWriter::WriteBytesToUInt64(size_t num_bytes, uint64_t value) { if (num_bytes > sizeof(value)) { return false; } if (endianness_ == quiche::HOST_BYTE_ORDER) { return WriteBytes(&value, num_bytes); } value = quiche::QuicheEndian::HostToNet64(value); return WriteBytes(reinterpret_cast<char*>(&value) + sizeof(value) - num_bytes, num_bytes); } bool QuicheDataWriter::WriteStringPiece16(absl::string_view val) { if (val.size() > std::numeric_limits<uint16_t>::max()) { return false; } if (!WriteUInt16(static_cast<uint16_t>(val.size()))) { return false; } return WriteBytes(val.data(), val.size()); } bool QuicheDataWriter::WriteStringPiece(absl::string_view val) { return WriteBytes(val.data(), val.size()); } char* QuicheDataWriter::BeginWrite(size_t length) { if (length_ > capacity_) { return nullptr; } if (capacity_ - length_ < length) { return nullptr; } #ifdef ARCH_CPU_64_BITS QUICHE_DCHECK_LE(length, std::numeric_limits<uint32_t>::max()); #endif return buffer_ + length_; } bool QuicheDataWriter::WriteBytes(const void* data, size_t data_len) { char* dest = BeginWrite(data_len); if (!dest) { return false; } std::copy(static_cast<const char*>(data), static_cast<const char*>(data) + data_len, dest); length_ += data_len; return true; } bool QuicheDataWriter::WriteRepeatedByte(uint8_t byte, size_t count) { char* dest = BeginWrite(count); if (!dest) { return false; } std::fill(dest, dest + count, byte); length_ += count; return true; } void QuicheDataWriter::WritePadding() { QUICHE_DCHECK_LE(length_, capacity_); if (length_ > capacity_) { return; } std::fill(buffer_ + length_, buffer_ + capacity_, 0x00); length_ = capacity_; } bool QuicheDataWriter::WritePaddingBytes(size_t count) { return WriteRepeatedByte(0x00, count); } bool QuicheDataWriter::WriteTag(uint32_t tag) { return WriteBytes(&tag, sizeof(tag)); } bool QuicheDataWriter::WriteVarInt62(uint64_t value) { QUICHE_DCHECK_EQ(endianness(), quiche::NETWORK_BYTE_ORDER); size_t remaining_bytes = remaining(); char* next = buffer() + length(); if ((value & kVarInt62ErrorMask) == 0) { if ((value & kVarInt62Mask8Bytes) != 0) { if (remaining_bytes >= 8) { *(next + 0) = ((value >> 56) & 0x3f) + 0xc0; *(next + 1) = (value >> 48) & 0xff; *(next + 2) = (value >> 40) & 0xff; *(next + 3) = (value >> 32) & 0xff; *(next + 4) = (value >> 24) & 0xff; *(next + 5) = (value >> 16) & 0xff; *(next + 6) = (value >> 8) & 0xff; *(next + 7) = value & 0xff; IncreaseLength(8); return true; } return false; } if ((value & kVarInt62Mask4Bytes) != 0) { if (remaining_bytes >= 4) { *(next + 0) = ((value >> 24) & 0x3f) + 0x80; *(next + 1) = (value >> 16) & 0xff; *(next + 2) = (value >> 8) & 0xff; *(next + 3) = value & 0xff; IncreaseLength(4); return true; } return false; } if ((value & kVarInt62Mask2Bytes) != 0) { if (remaining_bytes >= 2) { *(next + 0) = ((value >> 8) & 0x3f) + 0x40; *(next + 1) = (value)&0xff; IncreaseLength(2); return true; } return false; } if (remaining_bytes >= 1) { *next = (value & 0x3f); IncreaseLength(1); return true; } return false; } return false; } bool QuicheDataWriter::WriteStringPieceVarInt62( const absl::string_view& string_piece) { if (!WriteVarInt62(string_piece.size())) { return false; } if (!string_piece.empty()) { if (!WriteBytes(string_piece.data(), string_piece.size())) { return false; } } return true; } QuicheVariableLengthIntegerLength QuicheDataWriter::GetVarInt62Len( uint64_t value) { if ((value & kVarInt62ErrorMask) != 0) { QUICHE_BUG(invalid_varint) << "Attempted to encode a value, " << value << ", that is too big for VarInt62"; return VARIABLE_LENGTH_INTEGER_LENGTH_0; } if ((value & kVarInt62Mask8Bytes) != 0) { return VARIABLE_LENGTH_INTEGER_LENGTH_8; } if ((value & kVarInt62Mask4Bytes) != 0) { return VARIABLE_LENGTH_INTEGER_LENGTH_4; } if ((value & kVarInt62Mask2Bytes) != 0) { return VARIABLE_LENGTH_INTEGER_LENGTH_2; } return VARIABLE_LENGTH_INTEGER_LENGTH_1; } bool QuicheDataWriter::WriteVarInt62WithForcedLength( uint64_t value, QuicheVariableLengthIntegerLength write_length) { QUICHE_DCHECK_EQ(endianness(), NETWORK_BYTE_ORDER); size_t remaining_bytes = remaining(); if (remaining_bytes < write_length) { return false; } const QuicheVariableLengthIntegerLength min_length = GetVarInt62Len(value); if (write_length < min_length) { QUICHE_BUG(invalid_varint_forced) << "Cannot write value " << value << " with write_length " << write_length; return false; } if (write_length == min_length) { return WriteVarInt62(value); } if (write_length == VARIABLE_LENGTH_INTEGER_LENGTH_2) { return WriteUInt8(0b01000000) && WriteUInt8(value); } if (write_length == VARIABLE_LENGTH_INTEGER_LENGTH_4) { return WriteUInt8(0b10000000) && WriteUInt8(0) && WriteUInt16(value); } if (write_length == VARIABLE_LENGTH_INTEGER_LENGTH_8) { return WriteUInt8(0b11000000) && WriteUInt8(0) && WriteUInt16(0) && WriteUInt32(value); } QUICHE_BUG(invalid_write_length) << "Invalid write_length " << static_cast<int>(write_length); return false; } bool QuicheDataWriter::Seek(size_t length) { if (!BeginWrite(length)) { return false; } length_ += length; return true; } std::string QuicheDataWriter::DebugString() const { return absl::StrCat(" { capacity: ", capacity_, ", length: ", length_, " }"); } }
#include "quiche/common/quiche_data_writer.h" #include <cstdint> #include <cstring> #include <string> #include <vector> #include "absl/base/macros.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/quiche_data_reader.h" #include "quiche/common/quiche_endian.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace quiche { namespace test { namespace { char* AsChars(unsigned char* data) { return reinterpret_cast<char*>(data); } struct TestParams { explicit TestParams(quiche::Endianness endianness) : endianness(endianness) {} quiche::Endianness endianness; }; std::string PrintToString(const TestParams& p) { return absl::StrCat( (p.endianness == quiche::NETWORK_BYTE_ORDER ? "Network" : "Host"), "ByteOrder"); } std::vector<TestParams> GetTestParams() { std::vector<TestParams> params; for (quiche::Endianness endianness : {quiche::NETWORK_BYTE_ORDER, quiche::HOST_BYTE_ORDER}) { params.push_back(TestParams(endianness)); } return params; } class QuicheDataWriterTest : public QuicheTestWithParam<TestParams> {}; INSTANTIATE_TEST_SUITE_P(QuicheDataWriterTests, QuicheDataWriterTest, ::testing::ValuesIn(GetTestParams()), ::testing::PrintToStringParamName()); TEST_P(QuicheDataWriterTest, Write16BitUnsignedIntegers) { char little_endian16[] = {0x22, 0x11}; char big_endian16[] = {0x11, 0x22}; char buffer16[2]; { uint16_t in_memory16 = 0x1122; QuicheDataWriter writer(2, buffer16, GetParam().endianness); writer.WriteUInt16(in_memory16); test::CompareCharArraysWithHexError( "uint16_t", buffer16, 2, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian16 : little_endian16, 2); uint16_t read_number16; QuicheDataReader reader(buffer16, 2, GetParam().endianness); reader.ReadUInt16(&read_number16); EXPECT_EQ(in_memory16, read_number16); } { uint64_t in_memory16 = 0x0000000000001122; QuicheDataWriter writer(2, buffer16, GetParam().endianness); writer.WriteBytesToUInt64(2, in_memory16); test::CompareCharArraysWithHexError( "uint16_t", buffer16, 2, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian16 : little_endian16, 2); uint64_t read_number16; QuicheDataReader reader(buffer16, 2, GetParam().endianness); reader.ReadBytesToUInt64(2, &read_number16); EXPECT_EQ(in_memory16, read_number16); } } TEST_P(QuicheDataWriterTest, Write24BitUnsignedIntegers) { char little_endian24[] = {0x33, 0x22, 0x11}; char big_endian24[] = {0x11, 0x22, 0x33}; char buffer24[3]; uint64_t in_memory24 = 0x0000000000112233; QuicheDataWriter writer(3, buffer24, GetParam().endianness); writer.WriteBytesToUInt64(3, in_memory24); test::CompareCharArraysWithHexError( "uint24", buffer24, 3, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian24 : little_endian24, 3); uint64_t read_number24; QuicheDataReader reader(buffer24, 3, GetParam().endianness); reader.ReadBytesToUInt64(3, &read_number24); EXPECT_EQ(in_memory24, read_number24); } TEST_P(QuicheDataWriterTest, Write32BitUnsignedIntegers) { char little_endian32[] = {0x44, 0x33, 0x22, 0x11}; char big_endian32[] = {0x11, 0x22, 0x33, 0x44}; char buffer32[4]; { uint32_t in_memory32 = 0x11223344; QuicheDataWriter writer(4, buffer32, GetParam().endianness); writer.WriteUInt32(in_memory32); test::CompareCharArraysWithHexError( "uint32_t", buffer32, 4, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian32 : little_endian32, 4); uint32_t read_number32; QuicheDataReader reader(buffer32, 4, GetParam().endianness); reader.ReadUInt32(&read_number32); EXPECT_EQ(in_memory32, read_number32); } { uint64_t in_memory32 = 0x11223344; QuicheDataWriter writer(4, buffer32, GetParam().endianness); writer.WriteBytesToUInt64(4, in_memory32); test::CompareCharArraysWithHexError( "uint32_t", buffer32, 4, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian32 : little_endian32, 4); uint64_t read_number32; QuicheDataReader reader(buffer32, 4, GetParam().endianness); reader.ReadBytesToUInt64(4, &read_number32); EXPECT_EQ(in_memory32, read_number32); } } TEST_P(QuicheDataWriterTest, Write40BitUnsignedIntegers) { uint64_t in_memory40 = 0x0000001122334455; char little_endian40[] = {0x55, 0x44, 0x33, 0x22, 0x11}; char big_endian40[] = {0x11, 0x22, 0x33, 0x44, 0x55}; char buffer40[5]; QuicheDataWriter writer(5, buffer40, GetParam().endianness); writer.WriteBytesToUInt64(5, in_memory40); test::CompareCharArraysWithHexError( "uint40", buffer40, 5, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian40 : little_endian40, 5); uint64_t read_number40; QuicheDataReader reader(buffer40, 5, GetParam().endianness); reader.ReadBytesToUInt64(5, &read_number40); EXPECT_EQ(in_memory40, read_number40); } TEST_P(QuicheDataWriterTest, Write48BitUnsignedIntegers) { uint64_t in_memory48 = 0x0000112233445566; char little_endian48[] = {0x66, 0x55, 0x44, 0x33, 0x22, 0x11}; char big_endian48[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66}; char buffer48[6]; QuicheDataWriter writer(6, buffer48, GetParam().endianness); writer.WriteBytesToUInt64(6, in_memory48); test::CompareCharArraysWithHexError( "uint48", buffer48, 6, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian48 : little_endian48, 6); uint64_t read_number48; QuicheDataReader reader(buffer48, 6, GetParam().endianness); reader.ReadBytesToUInt64(6., &read_number48); EXPECT_EQ(in_memory48, read_number48); } TEST_P(QuicheDataWriterTest, Write56BitUnsignedIntegers) { uint64_t in_memory56 = 0x0011223344556677; char little_endian56[] = {0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11}; char big_endian56[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77}; char buffer56[7]; QuicheDataWriter writer(7, buffer56, GetParam().endianness); writer.WriteBytesToUInt64(7, in_memory56); test::CompareCharArraysWithHexError( "uint56", buffer56, 7, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian56 : little_endian56, 7); uint64_t read_number56; QuicheDataReader reader(buffer56, 7, GetParam().endianness); reader.ReadBytesToUInt64(7, &read_number56); EXPECT_EQ(in_memory56, read_number56); } TEST_P(QuicheDataWriterTest, Write64BitUnsignedIntegers) { uint64_t in_memory64 = 0x1122334455667788; unsigned char little_endian64[] = {0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11}; unsigned char big_endian64[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}; char buffer64[8]; QuicheDataWriter writer(8, buffer64, GetParam().endianness); writer.WriteBytesToUInt64(8, in_memory64); test::CompareCharArraysWithHexError( "uint64_t", buffer64, 8, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? AsChars(big_endian64) : AsChars(little_endian64), 8); uint64_t read_number64; QuicheDataReader reader(buffer64, 8, GetParam().endianness); reader.ReadBytesToUInt64(8, &read_number64); EXPECT_EQ(in_memory64, read_number64); QuicheDataWriter writer2(8, buffer64, GetParam().endianness); writer2.WriteUInt64(in_memory64); test::CompareCharArraysWithHexError( "uint64_t", buffer64, 8, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? AsChars(big_endian64) : AsChars(little_endian64), 8); read_number64 = 0u; QuicheDataReader reader2(buffer64, 8, GetParam().endianness); reader2.ReadUInt64(&read_number64); EXPECT_EQ(in_memory64, read_number64); } TEST_P(QuicheDataWriterTest, WriteIntegers) { char buf[43]; uint8_t i8 = 0x01; uint16_t i16 = 0x0123; uint32_t i32 = 0x01234567; uint64_t i64 = 0x0123456789ABCDEF; QuicheDataWriter writer(46, buf, GetParam().endianness); for (size_t i = 0; i < 10; ++i) { switch (i) { case 0u: EXPECT_TRUE(writer.WriteBytesToUInt64(i, i64)); break; case 1u: EXPECT_TRUE(writer.WriteUInt8(i8)); EXPECT_TRUE(writer.WriteBytesToUInt64(i, i64)); break; case 2u: EXPECT_TRUE(writer.WriteUInt16(i16)); EXPECT_TRUE(writer.WriteBytesToUInt64(i, i64)); break; case 3u: EXPECT_TRUE(writer.WriteBytesToUInt64(i, i64)); break; case 4u: EXPECT_TRUE(writer.WriteUInt32(i32)); EXPECT_TRUE(writer.WriteBytesToUInt64(i, i64)); break; case 5u: case 6u: case 7u: case 8u: EXPECT_TRUE(writer.WriteBytesToUInt64(i, i64)); break; default: EXPECT_FALSE(writer.WriteBytesToUInt64(i, i64)); } } QuicheDataReader reader(buf, 46, GetParam().endianness); for (size_t i = 0; i < 10; ++i) { uint8_t read8; uint16_t read16; uint32_t read32; uint64_t read64; switch (i) { case 0u: EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(0u, read64); break; case 1u: EXPECT_TRUE(reader.ReadUInt8(&read8)); EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(i8, read8); EXPECT_EQ(0xEFu, read64); break; case 2u: EXPECT_TRUE(reader.ReadUInt16(&read16)); EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(i16, read16); EXPECT_EQ(0xCDEFu, read64); break; case 3u: EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(0xABCDEFu, read64); break; case 4u: EXPECT_TRUE(reader.ReadUInt32(&read32)); EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(i32, read32); EXPECT_EQ(0x89ABCDEFu, read64); break; case 5u: EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(0x6789ABCDEFu, read64); break; case 6u: EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(0x456789ABCDEFu, read64); break; case 7u: EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(0x23456789ABCDEFu, read64); break; case 8u: EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(0x0123456789ABCDEFu, read64); break; default: EXPECT_FALSE(reader.ReadBytesToUInt64(i, &read64)); } } } TEST_P(QuicheDataWriterTest, WriteBytes) { char bytes[] = {0, 1, 2, 3, 4, 5, 6, 7, 8}; char buf[ABSL_ARRAYSIZE(bytes)]; QuicheDataWriter writer(ABSL_ARRAYSIZE(buf), buf, GetParam().endianness); EXPECT_TRUE(writer.WriteBytes(bytes, ABSL_ARRAYSIZE(bytes))); for (unsigned int i = 0; i < ABSL_ARRAYSIZE(bytes); ++i) { EXPECT_EQ(bytes[i], buf[i]); } } const int kVarIntBufferLength = 1024; bool EncodeDecodeValue(uint64_t value_in, char* buffer, size_t size_of_buffer) { memset(buffer, 0, size_of_buffer); QuicheDataWriter writer(size_of_buffer, buffer, quiche::Endianness::NETWORK_BYTE_ORDER); if (writer.WriteVarInt62(value_in) != true) { return false; } size_t expected_length = 0; if (value_in <= 0x3f) { expected_length = 1; } else if (value_in <= 0x3fff) { expected_length = 2; } else if (value_in <= 0x3fffffff) { expected_length = 4; } else { expected_length = 8; } if (writer.length() != expected_length) { return false; } QuicheDataReader reader(buffer, expected_length, quiche::Endianness::NETWORK_BYTE_ORDER); uint64_t value_out; if (reader.ReadVarInt62(&value_out) == false) { return false; } if (value_in != value_out) { return false; } return reader.IsDoneReading(); } TEST_P(QuicheDataWriterTest, VarInt8Layout) { char buffer[1024]; memset(buffer, 0, sizeof(buffer)); QuicheDataWriter writer(sizeof(buffer), static_cast<char*>(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); EXPECT_TRUE(writer.WriteVarInt62(UINT64_C(0x3142f3e4d5c6b7a8))); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 0)), (0x31 + 0xc0)); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 1)), 0x42); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 2)), 0xf3); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 3)), 0xe4); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 4)), 0xd5); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 5)), 0xc6); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 6)), 0xb7); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 7)), 0xa8); } TEST_P(QuicheDataWriterTest, VarInt4Layout) { char buffer[1024]; memset(buffer, 0, sizeof(buffer)); QuicheDataWriter writer(sizeof(buffer), static_cast<char*>(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); EXPECT_TRUE(writer.WriteVarInt62(0x3243f4e5)); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 0)), (0x32 + 0x80)); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 1)), 0x43); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 2)), 0xf4); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 3)), 0xe5); } TEST_P(QuicheDataWriterTest, VarInt2Layout) { char buffer[1024]; memset(buffer, 0, sizeof(buffer)); QuicheDataWriter writer(sizeof(buffer), static_cast<char*>(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); EXPECT_TRUE(writer.WriteVarInt62(0x3647)); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 0)), (0x36 + 0x40)); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 1)), 0x47); } TEST_P(QuicheDataWriterTest, VarInt1Layout) { char buffer[1024]; memset(buffer, 0, sizeof(buffer)); QuicheDataWriter writer(sizeof(buffer), static_cast<char*>(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); EXPECT_TRUE(writer.WriteVarInt62(0x3f)); EXPECT_EQ(static_cast<unsigned char>(*(writer.data() + 0)), 0x3f); } TEST_P(QuicheDataWriterTest, VarIntGoodTargetedValues) { char buffer[kVarIntBufferLength]; uint64_t passing_values[] = { 0, 1, 0x3e, 0x3f, 0x40, 0x41, 0x3ffe, 0x3fff, 0x4000, 0x4001, 0x3ffffffe, 0x3fffffff, 0x40000000, 0x40000001, 0x3ffffffffffffffe, 0x3fffffffffffffff, 0xfe, 0xff, 0x100, 0x101, 0xfffe, 0xffff, 0x10000, 0x10001, 0xfffffe, 0xffffff, 0x1000000, 0x1000001, 0xfffffffe, 0xffffffff, 0x100000000, 0x100000001, 0xfffffffffe, 0xffffffffff, 0x10000000000, 0x10000000001, 0xfffffffffffe, 0xffffffffffff, 0x1000000000000, 0x1000000000001, 0xfffffffffffffe, 0xffffffffffffff, 0x100000000000000, 0x100000000000001, }; for (uint64_t test_val : passing_values) { EXPECT_TRUE( EncodeDecodeValue(test_val, static_cast<char*>(buffer), sizeof(buffer))) << " encode/decode of " << test_val << " failed"; } } TEST_P(QuicheDataWriterTest, VarIntBadTargetedValues) { char buffer[kVarIntBufferLength]; uint64_t failing_values[] = { 0x4000000000000000, 0x4000000000000001, 0xfffffffffffffffe, 0xffffffffffffffff, }; for (uint64_t test_val : failing_values) { EXPECT_FALSE( EncodeDecodeValue(test_val, static_cast<char*>(buffer), sizeof(buffer))) << " encode/decode of " << test_val << " succeeded, but was an " << "invalid value"; } } TEST_P(QuicheDataWriterTest, WriteVarInt62WithForcedLength) { char buffer[90]; memset(buffer, 0, sizeof(buffer)); QuicheDataWriter writer(sizeof(buffer), static_cast<char*>(buffer)); writer.WriteVarInt62WithForcedLength(1, VARIABLE_LENGTH_INTEGER_LENGTH_1); writer.WriteVarInt62WithForcedLength(1, VARIABLE_LENGTH_INTEGER_LENGTH_2); writer.WriteVarInt62WithForcedLength(1, VARIABLE_LENGTH_INTEGER_LENGTH_4); writer.WriteVarInt62WithForcedLength(1, VARIABLE_LENGTH_INTEGER_LENGTH_8); writer.WriteVarInt62WithForcedLength(63, VARIABLE_LENGTH_INTEGER_LENGTH_1); writer.WriteVarInt62WithForcedLength(63, VARIABLE_LENGTH_INTEGER_LENGTH_2); writer.WriteVarInt62WithForcedLength(63, VARIABLE_LENGTH_INTEGER_LENGTH_4); writer.WriteVarInt62WithForcedLength(63, VARIABLE_LENGTH_INTEGER_LENGTH_8); writer.WriteVarInt62WithForcedLength(64, VARIABLE_LENGTH_INTEGER_LENGTH_2); writer.WriteVarInt62WithForcedLength(64, VARIABLE_LENGTH_INTEGER_LENGTH_4); writer.WriteVarInt62WithForcedLength(64, VARIABLE_LENGTH_INTEGER_LENGTH_8); writer.WriteVarInt62WithForcedLength(16383, VARIABLE_LENGTH_INTEGER_LENGTH_2); writer.WriteVarInt62WithForcedLength(16383, VARIABLE_LENGTH_INTEGER_LENGTH_4); writer.WriteVarInt62WithForcedLength(16383, VARIABLE_LENGTH_INTEGER_LENGTH_8); writer.WriteVarInt62WithForcedLength(16384, VARIABLE_LENGTH_INTEGER_LENGTH_4); writer.WriteVarInt62WithForcedLength(16384, VARIABLE_LENGTH_INTEGER_LENGTH_8); writer.WriteVarInt62WithForcedLength(1073741823, VARIABLE_LENGTH_INTEGER_LENGTH_4); writer.WriteVarInt62WithForcedLength(1073741823, VARIABLE_LENGTH_INTEGER_LENGTH_8); writer.WriteVarInt62WithForcedLength(1073741824, VARIABLE_LENGTH_INTEGER_LENGTH_8); QuicheDataReader reader(buffer, sizeof(buffer)); uint64_t test_val = 0; for (int i = 0; i < 4; ++i) { EXPECT_TRUE(reader.ReadVarInt62(&test_val)); EXPECT_EQ(test_val, 1u); } for (int i = 0; i < 4; ++i) { EXPECT_TRUE(reader.ReadVarInt62(&test_val)); EXPECT_EQ(test_val, 63u); } for (int i = 0; i < 3; ++i) { EXPECT_TRUE(reader.ReadVarInt62(&test_val)); EXPECT_EQ(test_val, 64u); } for (int i = 0; i < 3; ++i) { EXPECT_TRUE(reader.ReadVarInt62(&test_val)); EXPECT_EQ(test_val, 16383u); } for (int i = 0; i < 2; ++i) { EXPECT_TRUE(reader.ReadVarInt62(&test_val)); EXPECT_EQ(test_val, 16384u); } for (int i = 0; i < 2; ++i) { EXPECT_TRUE(reader.ReadVarInt62(&test_val)); EXPECT_EQ(test_val, 1073741823u); } EXPECT_TRUE(reader.ReadVarInt62(&test_val)); EXPECT_EQ(test_val, 1073741824u); EXPECT_FALSE(reader.ReadVarInt62(&test_val)); } const int kMultiVarCount = 1000; TEST_P(QuicheDataWriterTest, MultiVarInt8) { uint64_t test_val; char buffer[8 * kMultiVarCount]; memset(buffer, 0, sizeof(buffer)); QuicheDataWriter writer(sizeof(buffer), static_cast<char*>(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); for (int i = 0; i < kMultiVarCount; i++) { EXPECT_TRUE(writer.WriteVarInt62(UINT64_C(0x3142f3e4d5c6b7a8) + i)); } EXPECT_EQ(writer.length(), 8u * kMultiVarCount); EXPECT_FALSE(writer.WriteVarInt62(UINT64_C(0x3142f3e4d5c6b7a8))); QuicheDataReader reader(buffer, sizeof(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); for (int i = 0; i < kMultiVarCount; i++) { EXPECT_TRUE(reader.ReadVarInt62(&test_val)); EXPECT_EQ(test_val, (UINT64_C(0x3142f3e4d5c6b7a8) + i)); } EXPECT_FALSE(reader.ReadVarInt62(&test_val)); } TEST_P(QuicheDataWriterTest, MultiVarInt4) { uint64_t test_val; char buffer[4 * kMultiVarCount]; memset(buffer, 0, sizeof(buffer)); QuicheDataWriter writer(sizeof(buffer), static_cast<char*>(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); for (int i = 0; i < kMultiVarCount; i++) { EXPECT_TRUE(writer.WriteVarInt62(UINT64_C(0x3142f3e4) + i)); } EXPECT_EQ(writer.length(), 4u * kMultiVarCount); EXPECT_FALSE(writer.WriteVarInt62(UINT64_C(0x3142f3e4))); QuicheDataReader reader(buffer, sizeof(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); for (int i = 0; i < kMultiVarCount; i++) { EXPECT_TRUE(reader.ReadVarInt62(&test_val)); EXPECT_EQ(test_val, (UINT64_C(0x3142f3e4) + i)); } EXPECT_FALSE(reader.ReadVarInt62(&test_val)); } TEST_P(QuicheDataWriterTest, MultiVarInt2) { uint64_t test_val; char buffer[2 * kMultiVarCount]; memset(buffer, 0, sizeof(buffer)); QuicheDataWriter writer(sizeof(buffer), static_cast<char*>(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); for (int i = 0; i < kMultiVarCount; i++) { EXPECT_TRUE(writer.WriteVarInt62(UINT64_C(0x3142) + i)); } EXPECT_EQ(writer.length(), 2u * kMultiVarCount); EXPECT_FALSE(writer.WriteVarInt62(UINT64_C(0x3142))); QuicheDataReader reader(buffer, sizeof(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); for (int i = 0; i < kMultiVarCount; i++) { EXPECT_TRUE(reader.ReadVarInt62(&test_val)); EXPECT_EQ(test_val, (UINT64_C(0x3142) + i)); } EXPECT_FALSE(reader.ReadVarInt62(&test_val)); } TEST_P(QuicheDataWriterTest, MultiVarInt1) { uint64_t test_val; char buffer[1 * kMultiVarCount]; memset(buffer, 0, sizeof(buffer)); QuicheDataWriter writer(sizeof(buffer), static_cast<char*>(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); for (int i = 0; i < kMultiVarCount; i++) { EXPECT_TRUE(writer.WriteVarInt62(UINT64_C(0x30) + (i & 0xf))); } EXPECT_EQ(writer.length(), 1u * kMultiVarCount); EXPECT_FALSE(writer.WriteVarInt62(UINT64_C(0x31))); QuicheDataReader reader(buffer, sizeof(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); for (int i = 0; i < kMultiVarCount; i++) { EXPECT_TRUE(reader.ReadVarInt62(&test_val)); EXPECT_EQ(test_val, (UINT64_C(0x30) + (i & 0xf))); } EXPECT_FALSE(reader.ReadVarInt62(&test_val)); } TEST_P(QuicheDataWriterTest, Seek) { char buffer[3] = {}; QuicheDataWriter writer(ABSL_ARRAYSIZE(buffer), buffer, GetParam().endianness); EXPECT_TRUE(writer.WriteUInt8(42)); EXPECT_TRUE(writer.Seek(1)); EXPECT_TRUE(writer.WriteUInt8(3)); char expected[] = {42, 0, 3}; for (size_t i = 0; i < ABSL_ARRAYSIZE(expected); ++i) { EXPECT_EQ(buffer[i], expected[i]); } } TEST_P(QuicheDataWriterTest, SeekTooFarFails) { char buffer[20]; { QuicheDataWriter writer(ABSL_ARRAYSIZE(buffer), buffer, GetParam().endianness); EXPECT_TRUE(writer.Seek(20)); EXPECT_FALSE(writer.Seek(1)); } { QuicheDataWriter writer(ABSL_ARRAYSIZE(buffer), buffer, GetParam().endianness); EXPECT_FALSE(writer.Seek(100)); } { QuicheDataWriter writer(ABSL_ARRAYSIZE(buffer), buffer, GetParam().endianness); EXPECT_TRUE(writer.Seek(10)); EXPECT_FALSE(writer.Seek(std::numeric_limits<size_t>::max())); } } TEST_P(QuicheDataWriterTest, PayloadReads) { char buffer[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; char expected_first_read[4] = {1, 2, 3, 4}; char expected_remaining[12] = {5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; QuicheDataReader reader(buffer, sizeof(buffer)); absl::string_view previously_read_payload1 = reader.PreviouslyReadPayload(); EXPECT_TRUE(previously_read_payload1.empty()); char first_read_buffer[4] = {}; EXPECT_TRUE(reader.ReadBytes(first_read_buffer, sizeof(first_read_buffer))); test::CompareCharArraysWithHexError( "first read", first_read_buffer, sizeof(first_read_buffer), expected_first_read, sizeof(expected_first_read)); absl::string_view peeked_remaining_payload = reader.PeekRemainingPayload(); test::CompareCharArraysWithHexError( "peeked_remaining_payload", peeked_remaining_payload.data(), peeked_remaining_payload.length(), expected_remaining, sizeof(expected_remaining)); absl::string_view full_payload = reader.FullPayload(); test::CompareCharArraysWithHexError("full_payload", full_payload.data(), full_payload.length(), buffer, sizeof(buffer)); absl::string_view previously_read_payload2 = reader.PreviouslyReadPayload(); test::CompareCharArraysWithHexError( "previously_read_payload2", previously_read_payload2.data(), previously_read_payload2.length(), first_read_buffer, sizeof(first_read_buffer)); absl::string_view read_remaining_payload = reader.ReadRemainingPayload(); test::CompareCharArraysWithHexError( "read_remaining_payload", read_remaining_payload.data(), read_remaining_payload.length(), expected_remaining, sizeof(expected_remaining)); EXPECT_TRUE(reader.IsDoneReading()); absl::string_view full_payload2 = reader.FullPayload(); test::CompareCharArraysWithHexError("full_payload2", full_payload2.data(), full_payload2.length(), buffer, sizeof(buffer)); absl::string_view previously_read_payload3 = reader.PreviouslyReadPayload(); test::CompareCharArraysWithHexError( "previously_read_payload3", previously_read_payload3.data(), previously_read_payload3.length(), buffer, sizeof(buffer)); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_data_writer.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_data_writer_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
4756e541-df87-49ee-8f7e-723acdc0b81c
cpp
google/quiche
quiche_random
quiche/common/quiche_random.cc
quiche/common/quiche_random_test.cc
#include "quiche/common/quiche_random.h" #include <cstdint> #include <cstring> #include "openssl/rand.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quiche { namespace { inline uint64_t Xoshiro256InitializeRngStateMember() { uint64_t result; RAND_bytes(reinterpret_cast<uint8_t*>(&result), sizeof(result)); return result; } inline uint64_t Xoshiro256PlusPlusRotLeft(uint64_t x, int k) { return (x << k) | (x >> (64 - k)); } uint64_t Xoshiro256PlusPlus() { static thread_local uint64_t rng_state[4] = { Xoshiro256InitializeRngStateMember(), Xoshiro256InitializeRngStateMember(), Xoshiro256InitializeRngStateMember(), Xoshiro256InitializeRngStateMember()}; const uint64_t result = Xoshiro256PlusPlusRotLeft(rng_state[0] + rng_state[3], 23) + rng_state[0]; const uint64_t t = rng_state[1] << 17; rng_state[2] ^= rng_state[0]; rng_state[3] ^= rng_state[1]; rng_state[1] ^= rng_state[2]; rng_state[0] ^= rng_state[3]; rng_state[2] ^= t; rng_state[3] = Xoshiro256PlusPlusRotLeft(rng_state[3], 45); return result; } class DefaultQuicheRandom : public QuicheRandom { public: DefaultQuicheRandom() {} DefaultQuicheRandom(const DefaultQuicheRandom&) = delete; DefaultQuicheRandom& operator=(const DefaultQuicheRandom&) = delete; ~DefaultQuicheRandom() override {} void RandBytes(void* data, size_t len) override; uint64_t RandUint64() override; void InsecureRandBytes(void* data, size_t len) override; uint64_t InsecureRandUint64() override; }; void DefaultQuicheRandom::RandBytes(void* data, size_t len) { RAND_bytes(reinterpret_cast<uint8_t*>(data), len); } uint64_t DefaultQuicheRandom::RandUint64() { uint64_t value; RandBytes(&value, sizeof(value)); return value; } void DefaultQuicheRandom::InsecureRandBytes(void* data, size_t len) { while (len >= sizeof(uint64_t)) { uint64_t random_bytes64 = Xoshiro256PlusPlus(); memcpy(data, &random_bytes64, sizeof(uint64_t)); data = reinterpret_cast<char*>(data) + sizeof(uint64_t); len -= sizeof(uint64_t); } if (len > 0) { QUICHE_DCHECK_LT(len, sizeof(uint64_t)); uint64_t random_bytes64 = Xoshiro256PlusPlus(); memcpy(data, &random_bytes64, len); } } uint64_t DefaultQuicheRandom::InsecureRandUint64() { return Xoshiro256PlusPlus(); } } QuicheRandom* QuicheRandom::GetInstance() { static DefaultQuicheRandom* random = new DefaultQuicheRandom(); return random; } }
#include "quiche/common/quiche_random.h" #include "quiche/common/platform/api/quiche_test.h" namespace quiche { namespace { TEST(QuicheRandom, RandBytes) { unsigned char buf1[16]; unsigned char buf2[16]; memset(buf1, 0xaf, sizeof(buf1)); memset(buf2, 0xaf, sizeof(buf2)); ASSERT_EQ(0, memcmp(buf1, buf2, sizeof(buf1))); auto rng = QuicheRandom::GetInstance(); rng->RandBytes(buf1, sizeof(buf1)); EXPECT_NE(0, memcmp(buf1, buf2, sizeof(buf1))); } TEST(QuicheRandom, RandUint64) { auto rng = QuicheRandom::GetInstance(); uint64_t value1 = rng->RandUint64(); uint64_t value2 = rng->RandUint64(); EXPECT_NE(value1, value2); } TEST(QuicheRandom, InsecureRandBytes) { unsigned char buf1[16]; unsigned char buf2[16]; memset(buf1, 0xaf, sizeof(buf1)); memset(buf2, 0xaf, sizeof(buf2)); ASSERT_EQ(0, memcmp(buf1, buf2, sizeof(buf1))); auto rng = QuicheRandom::GetInstance(); rng->InsecureRandBytes(buf1, sizeof(buf1)); EXPECT_NE(0, memcmp(buf1, buf2, sizeof(buf1))); } TEST(QuicheRandom, InsecureRandUint64) { auto rng = QuicheRandom::GetInstance(); uint64_t value1 = rng->InsecureRandUint64(); uint64_t value2 = rng->InsecureRandUint64(); EXPECT_NE(value1, value2); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_random.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_random_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
3358f23b-4b78-4872-945b-0d8d3aa38831
cpp
google/quiche
quiche_data_reader
quiche/common/quiche_data_reader.cc
quiche/common/quiche_data_reader_test.cc
#include "quiche/common/quiche_data_reader.h" #include <algorithm> #include <cstring> #include <string> #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_endian.h" namespace quiche { QuicheDataReader::QuicheDataReader(absl::string_view data) : QuicheDataReader(data.data(), data.length(), quiche::NETWORK_BYTE_ORDER) { } QuicheDataReader::QuicheDataReader(const char* data, const size_t len) : QuicheDataReader(data, len, quiche::NETWORK_BYTE_ORDER) {} QuicheDataReader::QuicheDataReader(const char* data, const size_t len, quiche::Endianness endianness) : data_(data), len_(len), pos_(0), endianness_(endianness) {} bool QuicheDataReader::ReadUInt8(uint8_t* result) { return ReadBytes(result, sizeof(*result)); } bool QuicheDataReader::ReadUInt16(uint16_t* result) { if (!ReadBytes(result, sizeof(*result))) { return false; } if (endianness_ == quiche::NETWORK_BYTE_ORDER) { *result = quiche::QuicheEndian::NetToHost16(*result); } return true; } bool QuicheDataReader::ReadUInt24(uint32_t* result) { if (endianness_ != quiche::NETWORK_BYTE_ORDER) { QUICHE_BUG(QuicheDataReader_ReadUInt24_NotImplemented); return false; } *result = 0; if (!ReadBytes(reinterpret_cast<char*>(result) + 1, 3u)) { return false; } *result = quiche::QuicheEndian::NetToHost32(*result); return true; } bool QuicheDataReader::ReadUInt32(uint32_t* result) { if (!ReadBytes(result, sizeof(*result))) { return false; } if (endianness_ == quiche::NETWORK_BYTE_ORDER) { *result = quiche::QuicheEndian::NetToHost32(*result); } return true; } bool QuicheDataReader::ReadUInt64(uint64_t* result) { if (!ReadBytes(result, sizeof(*result))) { return false; } if (endianness_ == quiche::NETWORK_BYTE_ORDER) { *result = quiche::QuicheEndian::NetToHost64(*result); } return true; } bool QuicheDataReader::ReadBytesToUInt64(size_t num_bytes, uint64_t* result) { *result = 0u; if (num_bytes > sizeof(*result)) { return false; } if (endianness_ == quiche::HOST_BYTE_ORDER) { return ReadBytes(result, num_bytes); } if (!ReadBytes(reinterpret_cast<char*>(result) + sizeof(*result) - num_bytes, num_bytes)) { return false; } *result = quiche::QuicheEndian::NetToHost64(*result); return true; } bool QuicheDataReader::ReadStringPiece16(absl::string_view* result) { uint16_t result_len; if (!ReadUInt16(&result_len)) { return false; } return ReadStringPiece(result, result_len); } bool QuicheDataReader::ReadStringPiece8(absl::string_view* result) { uint8_t result_len; if (!ReadUInt8(&result_len)) { return false; } return ReadStringPiece(result, result_len); } bool QuicheDataReader::ReadStringPiece(absl::string_view* result, size_t size) { if (!CanRead(size)) { OnFailure(); return false; } *result = absl::string_view(data_ + pos_, size); pos_ += size; return true; } absl::string_view QuicheDataReader::ReadAtMost(size_t size) { size_t actual_size = std::min(size, BytesRemaining()); absl::string_view result = absl::string_view(data_ + pos_, actual_size); AdvancePos(actual_size); return result; } bool QuicheDataReader::ReadTag(uint32_t* tag) { return ReadBytes(tag, sizeof(*tag)); } bool QuicheDataReader::ReadDecimal64(size_t num_digits, uint64_t* result) { absl::string_view digits; if (!ReadStringPiece(&digits, num_digits)) { return false; } return absl::SimpleAtoi(digits, result); } QuicheVariableLengthIntegerLength QuicheDataReader::PeekVarInt62Length() { QUICHE_DCHECK_EQ(endianness(), NETWORK_BYTE_ORDER); const unsigned char* next = reinterpret_cast<const unsigned char*>(data() + pos()); if (BytesRemaining() == 0) { return VARIABLE_LENGTH_INTEGER_LENGTH_0; } return static_cast<QuicheVariableLengthIntegerLength>( 1 << ((*next & 0b11000000) >> 6)); } bool QuicheDataReader::ReadVarInt62(uint64_t* result) { QUICHE_DCHECK_EQ(endianness(), quiche::NETWORK_BYTE_ORDER); size_t remaining = BytesRemaining(); const unsigned char* next = reinterpret_cast<const unsigned char*>(data() + pos()); if (remaining != 0) { switch (*next & 0xc0) { case 0xc0: if (remaining >= 8) { *result = (static_cast<uint64_t>((*(next)) & 0x3f) << 56) + (static_cast<uint64_t>(*(next + 1)) << 48) + (static_cast<uint64_t>(*(next + 2)) << 40) + (static_cast<uint64_t>(*(next + 3)) << 32) + (static_cast<uint64_t>(*(next + 4)) << 24) + (static_cast<uint64_t>(*(next + 5)) << 16) + (static_cast<uint64_t>(*(next + 6)) << 8) + (static_cast<uint64_t>(*(next + 7)) << 0); AdvancePos(8); return true; } return false; case 0x80: if (remaining >= 4) { *result = (((*(next)) & 0x3f) << 24) + (((*(next + 1)) << 16)) + (((*(next + 2)) << 8)) + (((*(next + 3)) << 0)); AdvancePos(4); return true; } return false; case 0x40: if (remaining >= 2) { *result = (((*(next)) & 0x3f) << 8) + (*(next + 1)); AdvancePos(2); return true; } return false; case 0x00: *result = (*next) & 0x3f; AdvancePos(1); return true; } } return false; } bool QuicheDataReader::ReadStringPieceVarInt62(absl::string_view* result) { uint64_t result_length; if (!ReadVarInt62(&result_length)) { return false; } return ReadStringPiece(result, result_length); } bool QuicheDataReader::ReadStringVarInt62(std::string& result) { absl::string_view result_view; bool success = ReadStringPieceVarInt62(&result_view); result = std::string(result_view); return success; } absl::string_view QuicheDataReader::ReadRemainingPayload() { absl::string_view payload = PeekRemainingPayload(); pos_ = len_; return payload; } absl::string_view QuicheDataReader::PeekRemainingPayload() const { return absl::string_view(data_ + pos_, len_ - pos_); } absl::string_view QuicheDataReader::FullPayload() const { return absl::string_view(data_, len_); } absl::string_view QuicheDataReader::PreviouslyReadPayload() const { return absl::string_view(data_, pos_); } bool QuicheDataReader::ReadBytes(void* result, size_t size) { if (!CanRead(size)) { OnFailure(); return false; } memcpy(result, data_ + pos_, size); pos_ += size; return true; } bool QuicheDataReader::Seek(size_t size) { if (!CanRead(size)) { OnFailure(); return false; } pos_ += size; return true; } bool QuicheDataReader::IsDoneReading() const { return len_ == pos_; } size_t QuicheDataReader::BytesRemaining() const { if (pos_ > len_) { QUICHE_BUG(quiche_reader_pos_out_of_bound) << "QUIC reader pos out of bound: " << pos_ << ", len: " << len_; return 0; } return len_ - pos_; } bool QuicheDataReader::TruncateRemaining(size_t truncation_length) { if (truncation_length > BytesRemaining()) { return false; } len_ = pos_ + truncation_length; return true; } bool QuicheDataReader::CanRead(size_t bytes) const { return bytes <= (len_ - pos_); } void QuicheDataReader::OnFailure() { pos_ = len_; } uint8_t QuicheDataReader::PeekByte() const { if (pos_ >= len_) { QUICHE_LOG(FATAL) << "Reading is done, cannot peek next byte. Tried to read pos = " << pos_ << " buffer length = " << len_; return 0; } return data_[pos_]; } std::string QuicheDataReader::DebugString() const { return absl::StrCat(" { length: ", len_, ", position: ", pos_, " }"); } #undef ENDPOINT }
#include "quiche/common/quiche_data_reader.h" #include <cstdint> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/quiche_endian.h" namespace quiche { TEST(QuicheDataReaderTest, ReadUInt16) { const uint16_t kData[] = { QuicheEndian::HostToNet16(1), QuicheEndian::HostToNet16(1 << 15), }; QuicheDataReader reader(reinterpret_cast<const char*>(kData), sizeof(kData)); EXPECT_FALSE(reader.IsDoneReading()); uint16_t uint16_val; EXPECT_TRUE(reader.ReadUInt16(&uint16_val)); EXPECT_FALSE(reader.IsDoneReading()); EXPECT_EQ(1, uint16_val); EXPECT_TRUE(reader.ReadUInt16(&uint16_val)); EXPECT_TRUE(reader.IsDoneReading()); EXPECT_EQ(1 << 15, uint16_val); } TEST(QuicheDataReaderTest, ReadUInt32) { const uint32_t kData[] = { QuicheEndian::HostToNet32(1), QuicheEndian::HostToNet32(0x80000000), }; QuicheDataReader reader(reinterpret_cast<const char*>(kData), ABSL_ARRAYSIZE(kData) * sizeof(uint32_t)); EXPECT_FALSE(reader.IsDoneReading()); uint32_t uint32_val; EXPECT_TRUE(reader.ReadUInt32(&uint32_val)); EXPECT_FALSE(reader.IsDoneReading()); EXPECT_EQ(1u, uint32_val); EXPECT_TRUE(reader.ReadUInt32(&uint32_val)); EXPECT_TRUE(reader.IsDoneReading()); EXPECT_EQ(1u << 31, uint32_val); } TEST(QuicheDataReaderTest, ReadStringPiece16) { const char kData[] = { 0x00, 0x02, 0x48, 0x69, 0x00, 0x10, 0x54, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2c, 0x20, 0x31, 0x2c, 0x20, 0x32, 0x2c, 0x20, 0x33, }; QuicheDataReader reader(kData, ABSL_ARRAYSIZE(kData)); EXPECT_FALSE(reader.IsDoneReading()); absl::string_view stringpiece_val; EXPECT_TRUE(reader.ReadStringPiece16(&stringpiece_val)); EXPECT_FALSE(reader.IsDoneReading()); EXPECT_EQ(0, stringpiece_val.compare("Hi")); EXPECT_TRUE(reader.ReadStringPiece16(&stringpiece_val)); EXPECT_TRUE(reader.IsDoneReading()); EXPECT_EQ(0, stringpiece_val.compare("Testing, 1, 2, 3")); } TEST(QuicheDataReaderTest, ReadUInt16WithBufferTooSmall) { const char kData[] = { 0x00, }; QuicheDataReader reader(kData, ABSL_ARRAYSIZE(kData)); EXPECT_FALSE(reader.IsDoneReading()); uint16_t uint16_val; EXPECT_FALSE(reader.ReadUInt16(&uint16_val)); } TEST(QuicheDataReaderTest, ReadUInt32WithBufferTooSmall) { const char kData[] = { 0x00, 0x00, 0x00, }; QuicheDataReader reader(kData, ABSL_ARRAYSIZE(kData)); EXPECT_FALSE(reader.IsDoneReading()); uint32_t uint32_val; EXPECT_FALSE(reader.ReadUInt32(&uint32_val)); uint16_t uint16_val; EXPECT_FALSE(reader.ReadUInt16(&uint16_val)); } TEST(QuicheDataReaderTest, ReadStringPiece16WithBufferTooSmall) { const char kData[] = { 0x00, 0x03, 0x48, 0x69, }; QuicheDataReader reader(kData, ABSL_ARRAYSIZE(kData)); EXPECT_FALSE(reader.IsDoneReading()); absl::string_view stringpiece_val; EXPECT_FALSE(reader.ReadStringPiece16(&stringpiece_val)); uint16_t uint16_val; EXPECT_FALSE(reader.ReadUInt16(&uint16_val)); } TEST(QuicheDataReaderTest, ReadStringPiece16WithBufferWayTooSmall) { const char kData[] = { 0x00, }; QuicheDataReader reader(kData, ABSL_ARRAYSIZE(kData)); EXPECT_FALSE(reader.IsDoneReading()); absl::string_view stringpiece_val; EXPECT_FALSE(reader.ReadStringPiece16(&stringpiece_val)); uint16_t uint16_val; EXPECT_FALSE(reader.ReadUInt16(&uint16_val)); } TEST(QuicheDataReaderTest, ReadBytes) { const char kData[] = { 0x66, 0x6f, 0x6f, 0x48, 0x69, }; QuicheDataReader reader(kData, ABSL_ARRAYSIZE(kData)); EXPECT_FALSE(reader.IsDoneReading()); char dest1[3] = {}; EXPECT_TRUE(reader.ReadBytes(&dest1, ABSL_ARRAYSIZE(dest1))); EXPECT_FALSE(reader.IsDoneReading()); EXPECT_EQ("foo", absl::string_view(dest1, ABSL_ARRAYSIZE(dest1))); char dest2[2] = {}; EXPECT_TRUE(reader.ReadBytes(&dest2, ABSL_ARRAYSIZE(dest2))); EXPECT_TRUE(reader.IsDoneReading()); EXPECT_EQ("Hi", absl::string_view(dest2, ABSL_ARRAYSIZE(dest2))); } TEST(QuicheDataReaderTest, ReadBytesWithBufferTooSmall) { const char kData[] = { 0x01, }; QuicheDataReader reader(kData, ABSL_ARRAYSIZE(kData)); EXPECT_FALSE(reader.IsDoneReading()); char dest[ABSL_ARRAYSIZE(kData) + 2] = {}; EXPECT_FALSE(reader.ReadBytes(&dest, ABSL_ARRAYSIZE(kData) + 1)); EXPECT_STREQ("", dest); } TEST(QuicheDataReaderTest, ReadAtMost) { constexpr absl::string_view kData = "foobar"; QuicheDataReader reader(kData); EXPECT_EQ(reader.ReadAtMost(0), ""); EXPECT_EQ(reader.ReadAtMost(3), "foo"); EXPECT_EQ(reader.ReadAtMost(6), "bar"); EXPECT_EQ(reader.ReadAtMost(1000), ""); } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_data_reader.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_data_reader_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
9cbfb9af-6194-4234-b240-8a2e574acaef
cpp
google/quiche
quiche_ip_address
quiche/common/quiche_ip_address.cc
quiche/common/quiche_ip_address_test.cc
#include "quiche/common/quiche_ip_address.h" #include <algorithm> #include <cstdint> #include <cstring> #include <string> #include "absl/strings/str_cat.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_ip_address_family.h" namespace quiche { QuicheIpAddress QuicheIpAddress::Loopback4() { QuicheIpAddress result; result.family_ = IpAddressFamily::IP_V4; result.address_.bytes[0] = 127; result.address_.bytes[1] = 0; result.address_.bytes[2] = 0; result.address_.bytes[3] = 1; return result; } QuicheIpAddress QuicheIpAddress::Loopback6() { QuicheIpAddress result; result.family_ = IpAddressFamily::IP_V6; uint8_t* bytes = result.address_.bytes; memset(bytes, 0, 15); bytes[15] = 1; return result; } QuicheIpAddress QuicheIpAddress::Any4() { in_addr address; memset(&address, 0, sizeof(address)); return QuicheIpAddress(address); } QuicheIpAddress QuicheIpAddress::Any6() { in6_addr address; memset(&address, 0, sizeof(address)); return QuicheIpAddress(address); } QuicheIpAddress::QuicheIpAddress() : family_(IpAddressFamily::IP_UNSPEC) {} QuicheIpAddress::QuicheIpAddress(const in_addr& ipv4_address) : family_(IpAddressFamily::IP_V4) { address_.v4 = ipv4_address; } QuicheIpAddress::QuicheIpAddress(const in6_addr& ipv6_address) : family_(IpAddressFamily::IP_V6) { address_.v6 = ipv6_address; } bool operator==(QuicheIpAddress lhs, QuicheIpAddress rhs) { if (lhs.family_ != rhs.family_) { return false; } switch (lhs.family_) { case IpAddressFamily::IP_V4: return std::equal(lhs.address_.bytes, lhs.address_.bytes + QuicheIpAddress::kIPv4AddressSize, rhs.address_.bytes); case IpAddressFamily::IP_V6: return std::equal(lhs.address_.bytes, lhs.address_.bytes + QuicheIpAddress::kIPv6AddressSize, rhs.address_.bytes); case IpAddressFamily::IP_UNSPEC: return true; } QUICHE_BUG(quiche_bug_10126_2) << "Invalid IpAddressFamily " << static_cast<int32_t>(lhs.family_); return false; } bool operator!=(QuicheIpAddress lhs, QuicheIpAddress rhs) { return !(lhs == rhs); } bool QuicheIpAddress::IsInitialized() const { return family_ != IpAddressFamily::IP_UNSPEC; } IpAddressFamily QuicheIpAddress::address_family() const { return family_; } int QuicheIpAddress::AddressFamilyToInt() const { return ToPlatformAddressFamily(family_); } std::string QuicheIpAddress::ToPackedString() const { switch (family_) { case IpAddressFamily::IP_V4: return std::string(address_.chars, sizeof(address_.v4)); case IpAddressFamily::IP_V6: return std::string(address_.chars, sizeof(address_.v6)); case IpAddressFamily::IP_UNSPEC: return ""; } QUICHE_BUG(quiche_bug_10126_3) << "Invalid IpAddressFamily " << static_cast<int32_t>(family_); return ""; } std::string QuicheIpAddress::ToString() const { if (!IsInitialized()) { return ""; } char buffer[INET6_ADDRSTRLEN] = {0}; const char* result = inet_ntop(AddressFamilyToInt(), address_.bytes, buffer, sizeof(buffer)); QUICHE_BUG_IF(quiche_bug_10126_4, result == nullptr) << "Failed to convert an IP address to string"; return buffer; } static const uint8_t kMappedAddressPrefix[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, }; QuicheIpAddress QuicheIpAddress::Normalized() const { if (!IsIPv6()) { return *this; } if (!std::equal(std::begin(kMappedAddressPrefix), std::end(kMappedAddressPrefix), address_.bytes)) { return *this; } in_addr result; memcpy(&result, &address_.bytes[12], sizeof(result)); return QuicheIpAddress(result); } QuicheIpAddress QuicheIpAddress::DualStacked() const { if (!IsIPv4()) { return *this; } QuicheIpAddress result; result.family_ = IpAddressFamily::IP_V6; memcpy(result.address_.bytes, kMappedAddressPrefix, sizeof(kMappedAddressPrefix)); memcpy(result.address_.bytes + 12, address_.bytes, kIPv4AddressSize); return result; } bool QuicheIpAddress::FromPackedString(const char* data, size_t length) { switch (length) { case kIPv4AddressSize: family_ = IpAddressFamily::IP_V4; break; case kIPv6AddressSize: family_ = IpAddressFamily::IP_V6; break; default: return false; } memcpy(address_.chars, data, length); return true; } bool QuicheIpAddress::FromString(std::string str) { for (IpAddressFamily family : {IpAddressFamily::IP_V6, IpAddressFamily::IP_V4}) { int result = inet_pton(ToPlatformAddressFamily(family), str.c_str(), address_.bytes); if (result > 0) { family_ = family; return true; } } return false; } bool QuicheIpAddress::IsIPv4() const { return family_ == IpAddressFamily::IP_V4; } bool QuicheIpAddress::IsIPv6() const { return family_ == IpAddressFamily::IP_V6; } bool QuicheIpAddress::InSameSubnet(const QuicheIpAddress& other, int subnet_length) { if (!IsInitialized()) { QUICHE_BUG(quiche_bug_10126_5) << "Attempting to do subnet matching on undefined address"; return false; } if ((IsIPv4() && subnet_length > 32) || (IsIPv6() && subnet_length > 128)) { QUICHE_BUG(quiche_bug_10126_6) << "Subnet mask is out of bounds"; return false; } int bytes_to_check = subnet_length / 8; int bits_to_check = subnet_length % 8; const uint8_t* const lhs = address_.bytes; const uint8_t* const rhs = other.address_.bytes; if (!std::equal(lhs, lhs + bytes_to_check, rhs)) { return false; } if (bits_to_check == 0) { return true; } QUICHE_DCHECK_LT(static_cast<size_t>(bytes_to_check), sizeof(address_.bytes)); int mask = (~0u) << (8u - bits_to_check); return (lhs[bytes_to_check] & mask) == (rhs[bytes_to_check] & mask); } in_addr QuicheIpAddress::GetIPv4() const { QUICHE_DCHECK(IsIPv4()); return address_.v4; } in6_addr QuicheIpAddress::GetIPv6() const { QUICHE_DCHECK(IsIPv6()); return address_.v6; } QuicheIpPrefix::QuicheIpPrefix() : prefix_length_(0) {} QuicheIpPrefix::QuicheIpPrefix(const QuicheIpAddress& address) : address_(address) { if (address_.IsIPv6()) { prefix_length_ = QuicheIpAddress::kIPv6AddressSize * 8; } else if (address_.IsIPv4()) { prefix_length_ = QuicheIpAddress::kIPv4AddressSize * 8; } else { prefix_length_ = 0; } } QuicheIpPrefix::QuicheIpPrefix(const QuicheIpAddress& address, uint8_t prefix_length) : address_(address), prefix_length_(prefix_length) { QUICHE_DCHECK(prefix_length <= QuicheIpPrefix(address).prefix_length()) << "prefix_length cannot be longer than the size of the IP address"; } std::string QuicheIpPrefix::ToString() const { return absl::StrCat(address_.ToString(), "/", prefix_length_); } bool operator==(const QuicheIpPrefix& lhs, const QuicheIpPrefix& rhs) { return lhs.address_ == rhs.address_ && lhs.prefix_length_ == rhs.prefix_length_; } bool operator!=(const QuicheIpPrefix& lhs, const QuicheIpPrefix& rhs) { return !(lhs == rhs); } }
#include "quiche/common/quiche_ip_address.h" #include <cstdint> #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/quiche_ip_address_family.h" namespace quiche { namespace test { namespace { TEST(QuicheIpAddressTest, IPv4) { QuicheIpAddress ip_address; EXPECT_FALSE(ip_address.IsInitialized()); EXPECT_TRUE(ip_address.FromString("127.0.52.223")); EXPECT_TRUE(ip_address.IsInitialized()); EXPECT_EQ(IpAddressFamily::IP_V4, ip_address.address_family()); EXPECT_TRUE(ip_address.IsIPv4()); EXPECT_FALSE(ip_address.IsIPv6()); EXPECT_EQ("127.0.52.223", ip_address.ToString()); const in_addr v4_address = ip_address.GetIPv4(); const uint8_t* const v4_address_ptr = reinterpret_cast<const uint8_t*>(&v4_address); EXPECT_EQ(127u, *(v4_address_ptr + 0)); EXPECT_EQ(0u, *(v4_address_ptr + 1)); EXPECT_EQ(52u, *(v4_address_ptr + 2)); EXPECT_EQ(223u, *(v4_address_ptr + 3)); } TEST(QuicheIpAddressTest, IPv6) { QuicheIpAddress ip_address; EXPECT_FALSE(ip_address.IsInitialized()); EXPECT_TRUE(ip_address.FromString("fe80::1ff:fe23:4567")); EXPECT_TRUE(ip_address.IsInitialized()); EXPECT_EQ(IpAddressFamily::IP_V6, ip_address.address_family()); EXPECT_FALSE(ip_address.IsIPv4()); EXPECT_TRUE(ip_address.IsIPv6()); EXPECT_EQ("fe80::1ff:fe23:4567", ip_address.ToString()); const in6_addr v6_address = ip_address.GetIPv6(); const uint16_t* const v6_address_ptr = reinterpret_cast<const uint16_t*>(&v6_address); EXPECT_EQ(0x80feu, *(v6_address_ptr + 0)); EXPECT_EQ(0x0000u, *(v6_address_ptr + 1)); EXPECT_EQ(0x0000u, *(v6_address_ptr + 2)); EXPECT_EQ(0x0000u, *(v6_address_ptr + 3)); EXPECT_EQ(0x0000u, *(v6_address_ptr + 4)); EXPECT_EQ(0xff01u, *(v6_address_ptr + 5)); EXPECT_EQ(0x23feu, *(v6_address_ptr + 6)); EXPECT_EQ(0x6745u, *(v6_address_ptr + 7)); EXPECT_EQ(ip_address, ip_address.Normalized()); EXPECT_EQ(ip_address, ip_address.DualStacked()); } TEST(QuicheIpAddressTest, FromPackedString) { QuicheIpAddress loopback4, loopback6; const char loopback4_packed[] = "\x7f\0\0\x01"; const char loopback6_packed[] = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x01"; EXPECT_TRUE(loopback4.FromPackedString(loopback4_packed, 4)); EXPECT_TRUE(loopback6.FromPackedString(loopback6_packed, 16)); EXPECT_EQ(loopback4, QuicheIpAddress::Loopback4()); EXPECT_EQ(loopback6, QuicheIpAddress::Loopback6()); } TEST(QuicheIpAddressTest, MappedAddress) { QuicheIpAddress ipv4_address; QuicheIpAddress mapped_address; EXPECT_TRUE(ipv4_address.FromString("127.0.0.1")); EXPECT_TRUE(mapped_address.FromString("::ffff:7f00:1")); EXPECT_EQ(mapped_address, ipv4_address.DualStacked()); EXPECT_EQ(ipv4_address, mapped_address.Normalized()); } TEST(QuicheIpAddressTest, Subnets) { struct { const char* address1; const char* address2; int subnet_size; bool same_subnet; } test_cases[] = { {"127.0.0.1", "127.0.0.2", 24, true}, {"8.8.8.8", "127.0.0.1", 24, false}, {"8.8.8.8", "127.0.0.1", 16, false}, {"8.8.8.8", "127.0.0.1", 8, false}, {"8.8.8.8", "127.0.0.1", 2, false}, {"8.8.8.8", "127.0.0.1", 1, true}, {"127.0.0.1", "127.0.0.128", 24, true}, {"127.0.0.1", "127.0.0.128", 25, false}, {"127.0.0.1", "127.0.0.127", 25, true}, {"127.0.0.1", "127.0.0.0", 30, true}, {"127.0.0.1", "127.0.0.1", 30, true}, {"127.0.0.1", "127.0.0.2", 30, true}, {"127.0.0.1", "127.0.0.3", 30, true}, {"127.0.0.1", "127.0.0.4", 30, false}, {"127.0.0.1", "127.0.0.2", 31, false}, {"127.0.0.1", "127.0.0.0", 31, true}, {"::1", "fe80::1", 8, false}, {"::1", "fe80::1", 1, false}, {"::1", "fe80::1", 0, true}, {"fe80::1", "fe80::2", 126, true}, {"fe80::1", "fe80::2", 127, false}, }; for (const auto& test_case : test_cases) { QuicheIpAddress address1, address2; ASSERT_TRUE(address1.FromString(test_case.address1)); ASSERT_TRUE(address2.FromString(test_case.address2)); EXPECT_EQ(test_case.same_subnet, address1.InSameSubnet(address2, test_case.subnet_size)) << "Addresses: " << test_case.address1 << ", " << test_case.address2 << "; subnet: /" << test_case.subnet_size; } } TEST(QuicheIpAddress, LoopbackAddresses) { QuicheIpAddress loopback4; QuicheIpAddress loopback6; ASSERT_TRUE(loopback4.FromString("127.0.0.1")); ASSERT_TRUE(loopback6.FromString("::1")); EXPECT_EQ(loopback4, QuicheIpAddress::Loopback4()); EXPECT_EQ(loopback6, QuicheIpAddress::Loopback6()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_ip_address.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_ip_address_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
2e519ae5-e075-4766-9cc9-255206de4de0
cpp
google/quiche
quiche_text_utils
quiche/common/quiche_text_utils.cc
quiche/common/quiche_text_utils_test.cc
#include "quiche/common/quiche_text_utils.h" #include <algorithm> #include <optional> #include <string> #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" namespace quiche { void QuicheTextUtils::Base64Encode(const uint8_t* data, size_t data_len, std::string* output) { absl::Base64Escape(std::string(reinterpret_cast<const char*>(data), data_len), output); size_t len = output->size(); if (len >= 2) { if ((*output)[len - 1] == '=') { len--; if ((*output)[len - 1] == '=') { len--; } output->resize(len); } } } std::optional<std::string> QuicheTextUtils::Base64Decode( absl::string_view input) { std::string output; if (!absl::Base64Unescape(input, &output)) { return std::nullopt; } return output; } std::string QuicheTextUtils::HexDump(absl::string_view binary_data) { const int kBytesPerLine = 16; int offset = 0; const char* p = binary_data.data(); int bytes_remaining = binary_data.size(); std::string output; while (bytes_remaining > 0) { const int line_bytes = std::min(bytes_remaining, kBytesPerLine); absl::StrAppendFormat(&output, "0x%04x: ", offset); for (int i = 0; i < kBytesPerLine; ++i) { if (i < line_bytes) { absl::StrAppendFormat(&output, "%02x", static_cast<unsigned char>(p[i])); } else { absl::StrAppend(&output, " "); } if (i % 2) { absl::StrAppend(&output, " "); } } absl::StrAppend(&output, " "); for (int i = 0; i < line_bytes; ++i) { output += absl::ascii_isgraph(p[i]) ? p[i] : '.'; } bytes_remaining -= line_bytes; offset += line_bytes; p += line_bytes; absl::StrAppend(&output, "\n"); } return output; } }
#include "quiche/common/quiche_text_utils.h" #include <string> #include "absl/strings/escaping.h" #include "quiche/common/platform/api/quiche_test.h" namespace quiche { namespace test { TEST(QuicheTestUtilsTest, StringPieceCaseHash) { const auto hasher = StringPieceCaseHash(); EXPECT_EQ(hasher("content-length"), hasher("Content-Length")); EXPECT_EQ(hasher("Content-Length"), hasher("CONTENT-LENGTH")); EXPECT_EQ(hasher("CoNteNT-lEngTH"), hasher("content-length")); EXPECT_NE(hasher("content-length"), hasher("content_length")); EXPECT_NE(hasher("Türkiye"), hasher("TÜRKİYE")); EXPECT_EQ( hasher("This is a string that is too long for inlining and requires a " "heap allocation. Apparently PowerPC has 128 byte cache lines. " "Since our inline array is sized according to a cache line, we " "need this string to be longer than 128 bytes."), hasher("This Is A String That Is Too Long For Inlining And Requires A " "Heap Allocation. Apparently PowerPC Has 128 Byte Cache Lines. " "Since Our Inline Array Is Sized According To A Cache Line, We " "Need This String To Be Longer Than 128 Bytes.")); } TEST(QuicheTextUtilsTest, ToLower) { EXPECT_EQ("lower", quiche::QuicheTextUtils::ToLower("LOWER")); EXPECT_EQ("lower", quiche::QuicheTextUtils::ToLower("lower")); EXPECT_EQ("lower", quiche::QuicheTextUtils::ToLower("lOwEr")); EXPECT_EQ("123", quiche::QuicheTextUtils::ToLower("123")); EXPECT_EQ("", quiche::QuicheTextUtils::ToLower("")); } TEST(QuicheTextUtilsTest, RemoveLeadingAndTrailingWhitespace) { for (auto* const input : {"text", " text", " text", "text ", "text ", " text ", " text ", "\r\n\ttext", "text\n\r\t"}) { absl::string_view piece(input); quiche::QuicheTextUtils::RemoveLeadingAndTrailingWhitespace(&piece); EXPECT_EQ("text", piece); } } TEST(QuicheTextUtilsTest, HexDump) { std::string empty; ASSERT_TRUE(absl::HexStringToBytes("", &empty)); EXPECT_EQ("", quiche::QuicheTextUtils::HexDump(empty)); char packet[] = { 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x51, 0x55, 0x49, 0x43, 0x21, 0x20, 0x54, 0x68, 0x69, 0x73, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x20, 0x73, 0x68, 0x6f, 0x75, 0x6c, 0x64, 0x20, 0x62, 0x65, 0x20, 0x6c, 0x6f, 0x6e, 0x67, 0x20, 0x65, 0x6e, 0x6f, 0x75, 0x67, 0x68, 0x20, 0x74, 0x6f, 0x20, 0x73, 0x70, 0x61, 0x6e, 0x20, 0x6d, 0x75, 0x6c, 0x74, 0x69, 0x70, 0x6c, 0x65, 0x20, 0x6c, 0x69, 0x6e, 0x65, 0x73, 0x20, 0x6f, 0x66, 0x20, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x2e, 0x01, 0x02, 0x03, 0x00, }; EXPECT_EQ( quiche::QuicheTextUtils::HexDump(packet), "0x0000: 4865 6c6c 6f2c 2051 5549 4321 2054 6869 Hello,.QUIC!.Thi\n" "0x0010: 7320 7374 7269 6e67 2073 686f 756c 6420 s.string.should.\n" "0x0020: 6265 206c 6f6e 6720 656e 6f75 6768 2074 be.long.enough.t\n" "0x0030: 6f20 7370 616e 206d 756c 7469 706c 6520 o.span.multiple.\n" "0x0040: 6c69 6e65 7320 6f66 206f 7574 7075 742e lines.of.output.\n" "0x0050: 0102 03 ...\n"); std::string printable_and_unprintable_chars; ASSERT_TRUE( absl::HexStringToBytes("20217e7f", &printable_and_unprintable_chars)); EXPECT_EQ("0x0000: 2021 7e7f .!~.\n", quiche::QuicheTextUtils::HexDump(printable_and_unprintable_chars)); std::string large_chars; ASSERT_TRUE(absl::HexStringToBytes("90aaff", &large_chars)); EXPECT_EQ("0x0000: 90aa ff ...\n", quiche::QuicheTextUtils::HexDump(large_chars)); } TEST(QuicheTextUtilsTest, Base64Encode) { std::string output; std::string input = "Hello"; quiche::QuicheTextUtils::Base64Encode( reinterpret_cast<const uint8_t*>(input.data()), input.length(), &output); EXPECT_EQ("SGVsbG8", output); input = "Hello, QUIC! This string should be long enough to span" "multiple lines of output\n"; quiche::QuicheTextUtils::Base64Encode( reinterpret_cast<const uint8_t*>(input.data()), input.length(), &output); EXPECT_EQ( "SGVsbG8sIFFVSUMhIFRoaXMgc3RyaW5nIHNob3VsZCBiZSBsb25n" "IGVub3VnaCB0byBzcGFubXVsdGlwbGUgbGluZXMgb2Ygb3V0cHV0Cg", output); } TEST(QuicheTextUtilsTest, ContainsUpperCase) { EXPECT_FALSE(quiche::QuicheTextUtils::ContainsUpperCase("abc")); EXPECT_FALSE(quiche::QuicheTextUtils::ContainsUpperCase("")); EXPECT_FALSE(quiche::QuicheTextUtils::ContainsUpperCase("123")); EXPECT_TRUE(quiche::QuicheTextUtils::ContainsUpperCase("ABC")); EXPECT_TRUE(quiche::QuicheTextUtils::ContainsUpperCase("aBc")); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_text_utils.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_text_utils_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
34ca573c-4dda-4c6b-af92-9ccafd413f77
cpp
google/quiche
quiche_simple_arena
quiche/common/quiche_simple_arena.cc
quiche/common/quiche_simple_arena_test.cc
#include "quiche/common/quiche_simple_arena.h" #include <algorithm> #include <cstring> #include <utility> #include "quiche/common/platform/api/quiche_logging.h" namespace quiche { QuicheSimpleArena::QuicheSimpleArena(size_t block_size) : block_size_(block_size) {} QuicheSimpleArena::~QuicheSimpleArena() = default; QuicheSimpleArena::QuicheSimpleArena(QuicheSimpleArena&& other) = default; QuicheSimpleArena& QuicheSimpleArena::operator=(QuicheSimpleArena&& other) = default; char* QuicheSimpleArena::Alloc(size_t size) { Reserve(size); Block& b = blocks_.back(); QUICHE_DCHECK_GE(b.size, b.used + size); char* out = b.data.get() + b.used; b.used += size; return out; } char* QuicheSimpleArena::Realloc(char* original, size_t oldsize, size_t newsize) { QUICHE_DCHECK(!blocks_.empty()); Block& last = blocks_.back(); if (last.data.get() <= original && original < last.data.get() + last.size) { QUICHE_DCHECK_GE(last.data.get() + last.used, original + oldsize); if (original + oldsize == last.data.get() + last.used) { if (original + newsize < last.data.get() + last.size) { last.used += newsize - oldsize; return original; } } } char* out = Alloc(newsize); memcpy(out, original, oldsize); return out; } char* QuicheSimpleArena::Memdup(const char* data, size_t size) { char* out = Alloc(size); memcpy(out, data, size); return out; } void QuicheSimpleArena::Free(char* data, size_t size) { if (blocks_.empty()) { return; } Block& b = blocks_.back(); if (size <= b.used && data + size == b.data.get() + b.used) { b.used -= size; } } void QuicheSimpleArena::Reset() { blocks_.clear(); status_.bytes_allocated_ = 0; } void QuicheSimpleArena::Reserve(size_t additional_space) { if (blocks_.empty()) { AllocBlock(std::max(additional_space, block_size_)); } else { const Block& last = blocks_.back(); if (last.size < last.used + additional_space) { AllocBlock(std::max(additional_space, block_size_)); } } } void QuicheSimpleArena::AllocBlock(size_t size) { blocks_.push_back(Block(size)); status_.bytes_allocated_ += size; } QuicheSimpleArena::Block::Block(size_t s) : data(new char[s]), size(s), used(0) {} QuicheSimpleArena::Block::~Block() = default; QuicheSimpleArena::Block::Block(QuicheSimpleArena::Block&& other) : size(other.size), used(other.used) { data = std::move(other.data); } QuicheSimpleArena::Block& QuicheSimpleArena::Block::operator=( QuicheSimpleArena::Block&& other) { size = other.size; used = other.used; data = std::move(other.data); return *this; } }
#include "quiche/common/quiche_simple_arena.h" #include <string> #include <vector> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_test.h" namespace quiche { namespace { size_t kDefaultBlockSize = 2048; const char kTestString[] = "This is a decently long test string."; TEST(QuicheSimpleArenaTest, NoAllocationOnConstruction) { QuicheSimpleArena arena(kDefaultBlockSize); EXPECT_EQ(0u, arena.status().bytes_allocated()); } TEST(QuicheSimpleArenaTest, Memdup) { QuicheSimpleArena arena(kDefaultBlockSize); const size_t length = strlen(kTestString); char* c = arena.Memdup(kTestString, length); EXPECT_NE(nullptr, c); EXPECT_NE(c, kTestString); EXPECT_EQ(absl::string_view(c, length), kTestString); } TEST(QuicheSimpleArenaTest, MemdupLargeString) { QuicheSimpleArena arena(10 ); const size_t length = strlen(kTestString); char* c = arena.Memdup(kTestString, length); EXPECT_NE(nullptr, c); EXPECT_NE(c, kTestString); EXPECT_EQ(absl::string_view(c, length), kTestString); } TEST(QuicheSimpleArenaTest, MultipleBlocks) { QuicheSimpleArena arena(40 ); std::vector<std::string> strings = { "One decently long string.", "Another string.", "A third string that will surely go in a different block."}; std::vector<absl::string_view> copies; for (const std::string& s : strings) { absl::string_view sp(arena.Memdup(s.data(), s.size()), s.size()); copies.push_back(sp); } EXPECT_EQ(strings.size(), copies.size()); for (size_t i = 0; i < strings.size(); ++i) { EXPECT_EQ(copies[i], strings[i]); } } TEST(QuicheSimpleArenaTest, UseAfterReset) { QuicheSimpleArena arena(kDefaultBlockSize); const size_t length = strlen(kTestString); char* c = arena.Memdup(kTestString, length); arena.Reset(); c = arena.Memdup(kTestString, length); EXPECT_NE(nullptr, c); EXPECT_NE(c, kTestString); EXPECT_EQ(absl::string_view(c, length), kTestString); } TEST(QuicheSimpleArenaTest, Free) { QuicheSimpleArena arena(kDefaultBlockSize); const size_t length = strlen(kTestString); arena.Free(const_cast<char*>(kTestString), length); char* c1 = arena.Memdup("Foo", 3); char* c2 = arena.Memdup(kTestString, length); arena.Free(const_cast<char*>(kTestString), length); char* c3 = arena.Memdup("Bar", 3); char* c4 = arena.Memdup(kTestString, length); EXPECT_NE(c1, c2); EXPECT_NE(c1, c3); EXPECT_NE(c1, c4); EXPECT_NE(c2, c3); EXPECT_NE(c2, c4); EXPECT_NE(c3, c4); arena.Free(c4, length); arena.Free(c2, length); char* c5 = arena.Memdup("Baz", 3); EXPECT_EQ(c4, c5); } TEST(QuicheSimpleArenaTest, Alloc) { QuicheSimpleArena arena(kDefaultBlockSize); const size_t length = strlen(kTestString); char* c1 = arena.Alloc(length); char* c2 = arena.Alloc(2 * length); char* c3 = arena.Alloc(3 * length); char* c4 = arena.Memdup(kTestString, length); EXPECT_EQ(c1 + length, c2); EXPECT_EQ(c2 + 2 * length, c3); EXPECT_EQ(c3 + 3 * length, c4); EXPECT_EQ(absl::string_view(c4, length), kTestString); } TEST(QuicheSimpleArenaTest, Realloc) { QuicheSimpleArena arena(kDefaultBlockSize); const size_t length = strlen(kTestString); char* c1 = arena.Memdup(kTestString, length); char* c2 = arena.Realloc(c1, length, 2 * length); EXPECT_TRUE(c1); EXPECT_EQ(c1, c2); EXPECT_EQ(absl::string_view(c1, length), kTestString); char* c3 = arena.Memdup(kTestString, length); EXPECT_EQ(c2 + 2 * length, c3); EXPECT_EQ(absl::string_view(c3, length), kTestString); char* c4 = arena.Realloc(c3, length, 2 * length); EXPECT_EQ(c3, c4); EXPECT_EQ(absl::string_view(c4, length), kTestString); char* c5 = arena.Realloc(c4, 2 * length, 3 * length); EXPECT_EQ(c4, c5); EXPECT_EQ(absl::string_view(c5, length), kTestString); char* c6 = arena.Memdup(kTestString, length); EXPECT_EQ(c5 + 3 * length, c6); EXPECT_EQ(absl::string_view(c6, length), kTestString); char* c7 = arena.Realloc(c6, length, kDefaultBlockSize); EXPECT_EQ(absl::string_view(c7, length), kTestString); arena.Free(c7, kDefaultBlockSize); char* c8 = arena.Memdup(kTestString, length); EXPECT_NE(c6, c7); EXPECT_EQ(c7, c8); EXPECT_EQ(absl::string_view(c8, length), kTestString); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_simple_arena.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_simple_arena_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
8776898b-4b66-476c-826a-904aac0af537
cpp
google/quiche
quiche_buffer_allocator
quiche/common/quiche_buffer_allocator.cc
quiche/common/quiche_buffer_allocator_test.cc
#include "quiche/common/quiche_buffer_allocator.h" #include <algorithm> #include <cstring> #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_prefetch.h" namespace quiche { QuicheBuffer QuicheBuffer::CopyFromIovec(QuicheBufferAllocator* allocator, const struct iovec* iov, int iov_count, size_t iov_offset, size_t buffer_length) { if (buffer_length == 0) { return {}; } int iovnum = 0; while (iovnum < iov_count && iov_offset >= iov[iovnum].iov_len) { iov_offset -= iov[iovnum].iov_len; ++iovnum; } QUICHE_DCHECK_LE(iovnum, iov_count); if (iovnum >= iov_count) { QUICHE_BUG(quiche_bug_10839_1) << "iov_offset larger than iovec total size."; return {}; } QUICHE_DCHECK_LE(iov_offset, iov[iovnum].iov_len); const size_t iov_available = iov[iovnum].iov_len - iov_offset; size_t copy_len = std::min(buffer_length, iov_available); if (copy_len == iov_available && iovnum + 1 < iov_count) { char* next_base = static_cast<char*>(iov[iovnum + 1].iov_base); quiche::QuichePrefetchT0(next_base); if (iov[iovnum + 1].iov_len >= 64) { quiche::QuichePrefetchT0(next_base + ABSL_CACHELINE_SIZE); } } QuicheBuffer buffer(allocator, buffer_length); const char* src = static_cast<char*>(iov[iovnum].iov_base) + iov_offset; char* dst = buffer.data(); while (true) { memcpy(dst, src, copy_len); buffer_length -= copy_len; dst += copy_len; if (buffer_length == 0 || ++iovnum >= iov_count) { break; } src = static_cast<char*>(iov[iovnum].iov_base); copy_len = std::min(buffer_length, iov[iovnum].iov_len); } QUICHE_BUG_IF(quiche_bug_10839_2, buffer_length > 0) << "iov_offset + buffer_length larger than iovec total size."; return buffer; } }
#include "quiche/common/quiche_buffer_allocator.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_expect_bug.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/simple_buffer_allocator.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace quiche { namespace test { namespace { TEST(QuicheBuffer, CopyFromEmpty) { SimpleBufferAllocator allocator; QuicheBuffer buffer = QuicheBuffer::Copy(&allocator, ""); EXPECT_TRUE(buffer.empty()); } TEST(QuicheBuffer, Copy) { SimpleBufferAllocator allocator; QuicheBuffer buffer = QuicheBuffer::Copy(&allocator, "foobar"); EXPECT_EQ("foobar", buffer.AsStringView()); } TEST(QuicheBuffer, CopyFromIovecZeroBytes) { const int buffer_length = 0; SimpleBufferAllocator allocator; QuicheBuffer buffer = QuicheBuffer::CopyFromIovec( &allocator, nullptr, 0, 0, buffer_length); EXPECT_TRUE(buffer.empty()); constexpr absl::string_view kData("foobar"); iovec iov = MakeIOVector(kData); buffer = QuicheBuffer::CopyFromIovec(&allocator, &iov, 1, 0, buffer_length); EXPECT_TRUE(buffer.empty()); buffer = QuicheBuffer::CopyFromIovec(&allocator, &iov, 1, 3, buffer_length); EXPECT_TRUE(buffer.empty()); } TEST(QuicheBuffer, CopyFromIovecSimple) { constexpr absl::string_view kData("foobar"); iovec iov = MakeIOVector(kData); SimpleBufferAllocator allocator; QuicheBuffer buffer = QuicheBuffer::CopyFromIovec(&allocator, &iov, 1, 0, 6); EXPECT_EQ("foobar", buffer.AsStringView()); buffer = QuicheBuffer::CopyFromIovec(&allocator, &iov, 1, 0, 3); EXPECT_EQ("foo", buffer.AsStringView()); buffer = QuicheBuffer::CopyFromIovec(&allocator, &iov, 1, 3, 3); EXPECT_EQ("bar", buffer.AsStringView()); buffer = QuicheBuffer::CopyFromIovec(&allocator, &iov, 1, 1, 4); EXPECT_EQ("ooba", buffer.AsStringView()); } TEST(QuicheBuffer, CopyFromIovecMultiple) { constexpr absl::string_view kData1("foo"); constexpr absl::string_view kData2("bar"); iovec iov[] = {MakeIOVector(kData1), MakeIOVector(kData2)}; SimpleBufferAllocator allocator; QuicheBuffer buffer = QuicheBuffer::CopyFromIovec(&allocator, &iov[0], 2, 0, 6); EXPECT_EQ("foobar", buffer.AsStringView()); buffer = QuicheBuffer::CopyFromIovec(&allocator, &iov[0], 2, 0, 3); EXPECT_EQ("foo", buffer.AsStringView()); buffer = QuicheBuffer::CopyFromIovec(&allocator, &iov[0], 2, 3, 3); EXPECT_EQ("bar", buffer.AsStringView()); buffer = QuicheBuffer::CopyFromIovec(&allocator, &iov[0], 2, 1, 4); EXPECT_EQ("ooba", buffer.AsStringView()); } TEST(QuicheBuffer, CopyFromIovecOffsetTooLarge) { constexpr absl::string_view kData1("foo"); constexpr absl::string_view kData2("bar"); iovec iov[] = {MakeIOVector(kData1), MakeIOVector(kData2)}; SimpleBufferAllocator allocator; EXPECT_QUICHE_BUG( QuicheBuffer::CopyFromIovec(&allocator, &iov[0], 2, 10, 6), "iov_offset larger than iovec total size"); } TEST(QuicheBuffer, CopyFromIovecTooManyBytesRequested) { constexpr absl::string_view kData1("foo"); constexpr absl::string_view kData2("bar"); iovec iov[] = {MakeIOVector(kData1), MakeIOVector(kData2)}; SimpleBufferAllocator allocator; EXPECT_QUICHE_BUG( QuicheBuffer::CopyFromIovec(&allocator, &iov[0], 2, 2, 10), R"(iov_offset \+ buffer_length larger than iovec total size)"); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_buffer_allocator.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_buffer_allocator_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
a843f051-effe-47f8-874c-478a730b6a98
cpp
google/quiche
quiche_mem_slice_storage
quiche/common/quiche_mem_slice_storage.cc
quiche/common/quiche_mem_slice_storage_test.cc
#include "quiche/common/quiche_mem_slice_storage.h" #include <algorithm> #include <utility> #include "quiche/quic/core/quic_utils.h" namespace quiche { QuicheMemSliceStorage::QuicheMemSliceStorage( const struct iovec* iov, int iov_count, QuicheBufferAllocator* allocator, const quic::QuicByteCount max_slice_len) { if (iov == nullptr) { return; } quic::QuicByteCount write_len = 0; for (int i = 0; i < iov_count; ++i) { write_len += iov[i].iov_len; } QUICHE_DCHECK_LT(0u, write_len); size_t io_offset = 0; while (write_len > 0) { size_t slice_len = std::min(write_len, max_slice_len); QuicheBuffer buffer = QuicheBuffer::CopyFromIovec(allocator, iov, iov_count, io_offset, slice_len); storage_.push_back(QuicheMemSlice(std::move(buffer))); write_len -= slice_len; io_offset += slice_len; } } }
#include "quiche/common/quiche_mem_slice_storage.h" #include <string> #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/simple_buffer_allocator.h" namespace quiche { namespace test { namespace { class QuicheMemSliceStorageImplTest : public QuicheTest { public: QuicheMemSliceStorageImplTest() = default; }; TEST_F(QuicheMemSliceStorageImplTest, EmptyIov) { QuicheMemSliceStorage storage(nullptr, 0, nullptr, 1024); EXPECT_TRUE(storage.ToSpan().empty()); } TEST_F(QuicheMemSliceStorageImplTest, SingleIov) { SimpleBufferAllocator allocator; std::string body(3, 'c'); struct iovec iov = {const_cast<char*>(body.data()), body.length()}; QuicheMemSliceStorage storage(&iov, 1, &allocator, 1024); auto span = storage.ToSpan(); EXPECT_EQ("ccc", span[0].AsStringView()); EXPECT_NE(static_cast<const void*>(span[0].data()), body.data()); } TEST_F(QuicheMemSliceStorageImplTest, MultipleIovInSingleSlice) { SimpleBufferAllocator allocator; std::string body1(3, 'a'); std::string body2(4, 'b'); struct iovec iov[] = {{const_cast<char*>(body1.data()), body1.length()}, {const_cast<char*>(body2.data()), body2.length()}}; QuicheMemSliceStorage storage(iov, 2, &allocator, 1024); auto span = storage.ToSpan(); EXPECT_EQ("aaabbbb", span[0].AsStringView()); } TEST_F(QuicheMemSliceStorageImplTest, MultipleIovInMultipleSlice) { SimpleBufferAllocator allocator; std::string body1(4, 'a'); std::string body2(4, 'b'); struct iovec iov[] = {{const_cast<char*>(body1.data()), body1.length()}, {const_cast<char*>(body2.data()), body2.length()}}; QuicheMemSliceStorage storage(iov, 2, &allocator, 4); auto span = storage.ToSpan(); EXPECT_EQ("aaaa", span[0].AsStringView()); EXPECT_EQ("bbbb", span[1].AsStringView()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_mem_slice_storage.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/quiche_mem_slice_storage_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
7beea957-2f27-4d00-9869-9d10b6996c6c
cpp
google/quiche
simple_buffer_allocator
quiche/common/simple_buffer_allocator.cc
quiche/common/simple_buffer_allocator_test.cc
#include "quiche/common/simple_buffer_allocator.h" namespace quiche { char* SimpleBufferAllocator::New(size_t size) { return new char[size]; } char* SimpleBufferAllocator::New(size_t size, bool ) { return New(size); } void SimpleBufferAllocator::Delete(char* buffer) { delete[] buffer; } }
#include "quiche/common/simple_buffer_allocator.h" #include <utility> #include "quiche/common/platform/api/quiche_test.h" namespace quiche { namespace { TEST(SimpleBufferAllocatorTest, NewDelete) { SimpleBufferAllocator alloc; char* buf = alloc.New(4); EXPECT_NE(nullptr, buf); alloc.Delete(buf); } TEST(SimpleBufferAllocatorTest, DeleteNull) { SimpleBufferAllocator alloc; alloc.Delete(nullptr); } TEST(SimpleBufferAllocatorTest, MoveBuffersConstructor) { SimpleBufferAllocator alloc; QuicheBuffer buffer1(&alloc, 16); EXPECT_NE(buffer1.data(), nullptr); EXPECT_EQ(buffer1.size(), 16u); QuicheBuffer buffer2(std::move(buffer1)); EXPECT_EQ(buffer1.data(), nullptr); EXPECT_EQ(buffer1.size(), 0u); EXPECT_NE(buffer2.data(), nullptr); EXPECT_EQ(buffer2.size(), 16u); } TEST(SimpleBufferAllocatorTest, MoveBuffersAssignment) { SimpleBufferAllocator alloc; QuicheBuffer buffer1(&alloc, 16); QuicheBuffer buffer2; EXPECT_NE(buffer1.data(), nullptr); EXPECT_EQ(buffer1.size(), 16u); EXPECT_EQ(buffer2.data(), nullptr); EXPECT_EQ(buffer2.size(), 0u); buffer2 = std::move(buffer1); EXPECT_EQ(buffer1.data(), nullptr); EXPECT_EQ(buffer1.size(), 0u); EXPECT_NE(buffer2.data(), nullptr); EXPECT_EQ(buffer2.size(), 16u); } TEST(SimpleBufferAllocatorTest, CopyBuffer) { SimpleBufferAllocator alloc; const absl::string_view original = "Test string"; QuicheBuffer copy = QuicheBuffer::Copy(&alloc, original); EXPECT_EQ(copy.AsStringView(), original); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/simple_buffer_allocator.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/simple_buffer_allocator_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
772ecdae-719a-4552-84ed-7c36b3f447ac
cpp
google/quiche
capsule
quiche/common/capsule.cc
quiche/common/capsule_test.cc
#include "quiche/common/capsule.h" #include <cstddef> #include <cstdint> #include <limits> #include <ostream> #include <string> #include <type_traits> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "absl/types/variant.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_export.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_buffer_allocator.h" #include "quiche/common/quiche_data_reader.h" #include "quiche/common/quiche_data_writer.h" #include "quiche/common/quiche_ip_address.h" #include "quiche/common/quiche_status_utils.h" #include "quiche/common/wire_serialization.h" #include "quiche/web_transport/web_transport.h" namespace quiche { std::string CapsuleTypeToString(CapsuleType capsule_type) { switch (capsule_type) { case CapsuleType::DATAGRAM: return "DATAGRAM"; case CapsuleType::LEGACY_DATAGRAM: return "LEGACY_DATAGRAM"; case CapsuleType::LEGACY_DATAGRAM_WITHOUT_CONTEXT: return "LEGACY_DATAGRAM_WITHOUT_CONTEXT"; case CapsuleType::CLOSE_WEBTRANSPORT_SESSION: return "CLOSE_WEBTRANSPORT_SESSION"; case CapsuleType::DRAIN_WEBTRANSPORT_SESSION: return "DRAIN_WEBTRANSPORT_SESSION"; case CapsuleType::ADDRESS_REQUEST: return "ADDRESS_REQUEST"; case CapsuleType::ADDRESS_ASSIGN: return "ADDRESS_ASSIGN"; case CapsuleType::ROUTE_ADVERTISEMENT: return "ROUTE_ADVERTISEMENT"; case CapsuleType::WT_STREAM: return "WT_STREAM"; case CapsuleType::WT_STREAM_WITH_FIN: return "WT_STREAM_WITH_FIN"; case CapsuleType::WT_RESET_STREAM: return "WT_RESET_STREAM"; case CapsuleType::WT_STOP_SENDING: return "WT_STOP_SENDING"; case CapsuleType::WT_MAX_STREAM_DATA: return "WT_MAX_STREAM_DATA"; case CapsuleType::WT_MAX_STREAMS_BIDI: return "WT_MAX_STREAMS_BIDI"; case CapsuleType::WT_MAX_STREAMS_UNIDI: return "WT_MAX_STREAMS_UNIDI"; } return absl::StrCat("Unknown(", static_cast<uint64_t>(capsule_type), ")"); } std::ostream& operator<<(std::ostream& os, const CapsuleType& capsule_type) { os << CapsuleTypeToString(capsule_type); return os; } Capsule Capsule::Datagram(absl::string_view http_datagram_payload) { return Capsule(DatagramCapsule{http_datagram_payload}); } Capsule Capsule::LegacyDatagram(absl::string_view http_datagram_payload) { return Capsule(LegacyDatagramCapsule{http_datagram_payload}); } Capsule Capsule::LegacyDatagramWithoutContext( absl::string_view http_datagram_payload) { return Capsule(LegacyDatagramWithoutContextCapsule{http_datagram_payload}); } Capsule Capsule::CloseWebTransportSession( webtransport::SessionErrorCode error_code, absl::string_view error_message) { return Capsule(CloseWebTransportSessionCapsule({error_code, error_message})); } Capsule Capsule::AddressRequest() { return Capsule(AddressRequestCapsule()); } Capsule Capsule::AddressAssign() { return Capsule(AddressAssignCapsule()); } Capsule Capsule::RouteAdvertisement() { return Capsule(RouteAdvertisementCapsule()); } Capsule Capsule::Unknown(uint64_t capsule_type, absl::string_view unknown_capsule_data) { return Capsule(UnknownCapsule{capsule_type, unknown_capsule_data}); } bool Capsule::operator==(const Capsule& other) const { return capsule_ == other.capsule_; } std::string DatagramCapsule::ToString() const { return absl::StrCat("DATAGRAM[", absl::BytesToHexString(http_datagram_payload), "]"); } std::string LegacyDatagramCapsule::ToString() const { return absl::StrCat("LEGACY_DATAGRAM[", absl::BytesToHexString(http_datagram_payload), "]"); } std::string LegacyDatagramWithoutContextCapsule::ToString() const { return absl::StrCat("LEGACY_DATAGRAM_WITHOUT_CONTEXT[", absl::BytesToHexString(http_datagram_payload), "]"); } std::string CloseWebTransportSessionCapsule::ToString() const { return absl::StrCat("CLOSE_WEBTRANSPORT_SESSION(error_code=", error_code, ",error_message=\"", error_message, "\")"); } std::string DrainWebTransportSessionCapsule::ToString() const { return "DRAIN_WEBTRANSPORT_SESSION()"; } std::string AddressRequestCapsule::ToString() const { std::string rv = "ADDRESS_REQUEST["; for (auto requested_address : requested_addresses) { absl::StrAppend(&rv, "(", requested_address.request_id, "-", requested_address.ip_prefix.ToString(), ")"); } absl::StrAppend(&rv, "]"); return rv; } std::string AddressAssignCapsule::ToString() const { std::string rv = "ADDRESS_ASSIGN["; for (auto assigned_address : assigned_addresses) { absl::StrAppend(&rv, "(", assigned_address.request_id, "-", assigned_address.ip_prefix.ToString(), ")"); } absl::StrAppend(&rv, "]"); return rv; } std::string RouteAdvertisementCapsule::ToString() const { std::string rv = "ROUTE_ADVERTISEMENT["; for (auto ip_address_range : ip_address_ranges) { absl::StrAppend(&rv, "(", ip_address_range.start_ip_address.ToString(), "-", ip_address_range.end_ip_address.ToString(), "-", static_cast<int>(ip_address_range.ip_protocol), ")"); } absl::StrAppend(&rv, "]"); return rv; } std::string UnknownCapsule::ToString() const { return absl::StrCat("Unknown(", type, ") [", absl::BytesToHexString(payload), "]"); } std::string WebTransportStreamDataCapsule::ToString() const { return absl::StrCat(CapsuleTypeToString(capsule_type()), " [stream_id=", stream_id, ", data=", absl::BytesToHexString(data), "]"); } std::string WebTransportResetStreamCapsule::ToString() const { return absl::StrCat("WT_RESET_STREAM(stream_id=", stream_id, ", error_code=", error_code, ")"); } std::string WebTransportStopSendingCapsule::ToString() const { return absl::StrCat("WT_STOP_SENDING(stream_id=", stream_id, ", error_code=", error_code, ")"); } std::string WebTransportMaxStreamDataCapsule::ToString() const { return absl::StrCat("WT_MAX_STREAM_DATA (stream_id=", stream_id, ", max_stream_data=", max_stream_data, ")"); } std::string WebTransportMaxStreamsCapsule::ToString() const { return absl::StrCat(CapsuleTypeToString(capsule_type()), " (max_streams=", max_stream_count, ")"); } std::string Capsule::ToString() const { return absl::visit([](const auto& capsule) { return capsule.ToString(); }, capsule_); } std::ostream& operator<<(std::ostream& os, const Capsule& capsule) { os << capsule.ToString(); return os; } CapsuleParser::CapsuleParser(Visitor* visitor) : visitor_(visitor) { QUICHE_DCHECK_NE(visitor_, nullptr); } class WirePrefixWithId { public: using DataType = PrefixWithId; WirePrefixWithId(const PrefixWithId& prefix) : prefix_(prefix) {} size_t GetLengthOnWire() { return ComputeLengthOnWire( WireVarInt62(prefix_.request_id), WireUint8(prefix_.ip_prefix.address().IsIPv4() ? 4 : 6), WireBytes(prefix_.ip_prefix.address().ToPackedString()), WireUint8(prefix_.ip_prefix.prefix_length())); } absl::Status SerializeIntoWriter(QuicheDataWriter& writer) { return AppendToStatus( quiche::SerializeIntoWriter( writer, WireVarInt62(prefix_.request_id), WireUint8(prefix_.ip_prefix.address().IsIPv4() ? 4 : 6), WireBytes(prefix_.ip_prefix.address().ToPackedString()), WireUint8(prefix_.ip_prefix.prefix_length())), " while serializing a PrefixWithId"); } private: const PrefixWithId& prefix_; }; class WireIpAddressRange { public: using DataType = IpAddressRange; explicit WireIpAddressRange(const IpAddressRange& range) : range_(range) {} size_t GetLengthOnWire() { return ComputeLengthOnWire( WireUint8(range_.start_ip_address.IsIPv4() ? 4 : 6), WireBytes(range_.start_ip_address.ToPackedString()), WireBytes(range_.end_ip_address.ToPackedString()), WireUint8(range_.ip_protocol)); } absl::Status SerializeIntoWriter(QuicheDataWriter& writer) { return AppendToStatus( ::quiche::SerializeIntoWriter( writer, WireUint8(range_.start_ip_address.IsIPv4() ? 4 : 6), WireBytes(range_.start_ip_address.ToPackedString()), WireBytes(range_.end_ip_address.ToPackedString()), WireUint8(range_.ip_protocol)), " while serializing an IpAddressRange"); } private: const IpAddressRange& range_; }; template <typename... T> absl::StatusOr<quiche::QuicheBuffer> SerializeCapsuleFields( CapsuleType type, QuicheBufferAllocator* allocator, T... fields) { size_t capsule_payload_size = ComputeLengthOnWire(fields...); return SerializeIntoBuffer(allocator, WireVarInt62(type), WireVarInt62(capsule_payload_size), fields...); } absl::StatusOr<quiche::QuicheBuffer> SerializeCapsuleWithStatus( const Capsule& capsule, quiche::QuicheBufferAllocator* allocator) { switch (capsule.capsule_type()) { case CapsuleType::DATAGRAM: return SerializeCapsuleFields( capsule.capsule_type(), allocator, WireBytes(capsule.datagram_capsule().http_datagram_payload)); case CapsuleType::LEGACY_DATAGRAM: return SerializeCapsuleFields( capsule.capsule_type(), allocator, WireBytes(capsule.legacy_datagram_capsule().http_datagram_payload)); case CapsuleType::LEGACY_DATAGRAM_WITHOUT_CONTEXT: return SerializeCapsuleFields( capsule.capsule_type(), allocator, WireBytes(capsule.legacy_datagram_without_context_capsule() .http_datagram_payload)); case CapsuleType::CLOSE_WEBTRANSPORT_SESSION: return SerializeCapsuleFields( capsule.capsule_type(), allocator, WireUint32(capsule.close_web_transport_session_capsule().error_code), WireBytes( capsule.close_web_transport_session_capsule().error_message)); case CapsuleType::DRAIN_WEBTRANSPORT_SESSION: return SerializeCapsuleFields(capsule.capsule_type(), allocator); case CapsuleType::ADDRESS_REQUEST: return SerializeCapsuleFields( capsule.capsule_type(), allocator, WireSpan<WirePrefixWithId>(absl::MakeConstSpan( capsule.address_request_capsule().requested_addresses))); case CapsuleType::ADDRESS_ASSIGN: return SerializeCapsuleFields( capsule.capsule_type(), allocator, WireSpan<WirePrefixWithId>(absl::MakeConstSpan( capsule.address_assign_capsule().assigned_addresses))); case CapsuleType::ROUTE_ADVERTISEMENT: return SerializeCapsuleFields( capsule.capsule_type(), allocator, WireSpan<WireIpAddressRange>(absl::MakeConstSpan( capsule.route_advertisement_capsule().ip_address_ranges))); case CapsuleType::WT_STREAM: case CapsuleType::WT_STREAM_WITH_FIN: return SerializeCapsuleFields( capsule.capsule_type(), allocator, WireVarInt62(capsule.web_transport_stream_data().stream_id), WireBytes(capsule.web_transport_stream_data().data)); case CapsuleType::WT_RESET_STREAM: return SerializeCapsuleFields( capsule.capsule_type(), allocator, WireVarInt62(capsule.web_transport_reset_stream().stream_id), WireVarInt62(capsule.web_transport_reset_stream().error_code)); case CapsuleType::WT_STOP_SENDING: return SerializeCapsuleFields( capsule.capsule_type(), allocator, WireVarInt62(capsule.web_transport_stop_sending().stream_id), WireVarInt62(capsule.web_transport_stop_sending().error_code)); case CapsuleType::WT_MAX_STREAM_DATA: return SerializeCapsuleFields( capsule.capsule_type(), allocator, WireVarInt62(capsule.web_transport_max_stream_data().stream_id), WireVarInt62( capsule.web_transport_max_stream_data().max_stream_data)); case CapsuleType::WT_MAX_STREAMS_BIDI: case CapsuleType::WT_MAX_STREAMS_UNIDI: return SerializeCapsuleFields( capsule.capsule_type(), allocator, WireVarInt62(capsule.web_transport_max_streams().max_stream_count)); default: return SerializeCapsuleFields( capsule.capsule_type(), allocator, WireBytes(capsule.unknown_capsule().payload)); } } QuicheBuffer SerializeDatagramCapsuleHeader(uint64_t datagram_size, QuicheBufferAllocator* allocator) { absl::StatusOr<QuicheBuffer> buffer = SerializeIntoBuffer(allocator, WireVarInt62(CapsuleType::DATAGRAM), WireVarInt62(datagram_size)); if (!buffer.ok()) { return QuicheBuffer(); } return *std::move(buffer); } QUICHE_EXPORT QuicheBuffer SerializeWebTransportStreamCapsuleHeader( webtransport::StreamId stream_id, bool fin, uint64_t write_size, QuicheBufferAllocator* allocator) { absl::StatusOr<QuicheBuffer> buffer = SerializeIntoBuffer( allocator, WireVarInt62(fin ? CapsuleType::WT_STREAM_WITH_FIN : CapsuleType::WT_STREAM), WireVarInt62(write_size + QuicheDataWriter::GetVarInt62Len(stream_id)), WireVarInt62(stream_id)); if (!buffer.ok()) { return QuicheBuffer(); } return *std::move(buffer); } QuicheBuffer SerializeCapsule(const Capsule& capsule, quiche::QuicheBufferAllocator* allocator) { absl::StatusOr<QuicheBuffer> serialized = SerializeCapsuleWithStatus(capsule, allocator); if (!serialized.ok()) { QUICHE_BUG(capsule_serialization_failed) << "Failed to serialize the following capsule:\n" << capsule << "Serialization error: " << serialized.status(); return QuicheBuffer(); } return *std::move(serialized); } bool CapsuleParser::IngestCapsuleFragment(absl::string_view capsule_fragment) { if (parsing_error_occurred_) { return false; } absl::StrAppend(&buffered_data_, capsule_fragment); while (true) { const absl::StatusOr<size_t> buffered_data_read = AttemptParseCapsule(); if (!buffered_data_read.ok()) { ReportParseFailure(buffered_data_read.status().message()); buffered_data_.clear(); return false; } if (*buffered_data_read == 0) { break; } buffered_data_.erase(0, *buffered_data_read); } static constexpr size_t kMaxCapsuleBufferSize = 1024 * 1024; if (buffered_data_.size() > kMaxCapsuleBufferSize) { buffered_data_.clear(); ReportParseFailure("Refusing to buffer too much capsule data"); return false; } return true; } namespace { absl::Status ReadWebTransportStreamId(QuicheDataReader& reader, webtransport::StreamId& id) { uint64_t raw_id; if (!reader.ReadVarInt62(&raw_id)) { return absl::InvalidArgumentError("Failed to read WebTransport Stream ID"); } if (raw_id > std::numeric_limits<uint32_t>::max()) { return absl::InvalidArgumentError("Stream ID does not fit into a uint32_t"); } id = static_cast<webtransport::StreamId>(raw_id); return absl::OkStatus(); } absl::StatusOr<Capsule> ParseCapsulePayload(QuicheDataReader& reader, CapsuleType type) { switch (type) { case CapsuleType::DATAGRAM: return Capsule::Datagram(reader.ReadRemainingPayload()); case CapsuleType::LEGACY_DATAGRAM: return Capsule::LegacyDatagram(reader.ReadRemainingPayload()); case CapsuleType::LEGACY_DATAGRAM_WITHOUT_CONTEXT: return Capsule::LegacyDatagramWithoutContext( reader.ReadRemainingPayload()); case CapsuleType::CLOSE_WEBTRANSPORT_SESSION: { CloseWebTransportSessionCapsule capsule; if (!reader.ReadUInt32(&capsule.error_code)) { return absl::InvalidArgumentError( "Unable to parse capsule CLOSE_WEBTRANSPORT_SESSION error code"); } capsule.error_message = reader.ReadRemainingPayload(); return Capsule(std::move(capsule)); } case CapsuleType::DRAIN_WEBTRANSPORT_SESSION: return Capsule(DrainWebTransportSessionCapsule()); case CapsuleType::ADDRESS_REQUEST: { AddressRequestCapsule capsule; while (!reader.IsDoneReading()) { PrefixWithId requested_address; if (!reader.ReadVarInt62(&requested_address.request_id)) { return absl::InvalidArgumentError( "Unable to parse capsule ADDRESS_REQUEST request ID"); } uint8_t address_family; if (!reader.ReadUInt8(&address_family)) { return absl::InvalidArgumentError( "Unable to parse capsule ADDRESS_REQUEST family"); } if (address_family != 4 && address_family != 6) { return absl::InvalidArgumentError("Bad ADDRESS_REQUEST family"); } absl::string_view ip_address_bytes; if (!reader.ReadStringPiece(&ip_address_bytes, address_family == 4 ? QuicheIpAddress::kIPv4AddressSize : QuicheIpAddress::kIPv6AddressSize)) { return absl::InvalidArgumentError( "Unable to read capsule ADDRESS_REQUEST address"); } quiche::QuicheIpAddress ip_address; if (!ip_address.FromPackedString(ip_address_bytes.data(), ip_address_bytes.size())) { return absl::InvalidArgumentError( "Unable to parse capsule ADDRESS_REQUEST address"); } uint8_t ip_prefix_length; if (!reader.ReadUInt8(&ip_prefix_length)) { return absl::InvalidArgumentError( "Unable to parse capsule ADDRESS_REQUEST IP prefix length"); } if (ip_prefix_length > QuicheIpPrefix(ip_address).prefix_length()) { return absl::InvalidArgumentError("Invalid IP prefix length"); } requested_address.ip_prefix = QuicheIpPrefix(ip_address, ip_prefix_length); capsule.requested_addresses.push_back(requested_address); } return Capsule(std::move(capsule)); } case CapsuleType::ADDRESS_ASSIGN: { AddressAssignCapsule capsule; while (!reader.IsDoneReading()) { PrefixWithId assigned_address; if (!reader.ReadVarInt62(&assigned_address.request_id)) { return absl::InvalidArgumentError( "Unable to parse capsule ADDRESS_ASSIGN request ID"); } uint8_t address_family; if (!reader.ReadUInt8(&address_family)) { return absl::InvalidArgumentError( "Unable to parse capsule ADDRESS_ASSIGN family"); } if (address_family != 4 && address_family != 6) { return absl::InvalidArgumentError("Bad ADDRESS_ASSIGN family"); } absl::string_view ip_address_bytes; if (!reader.ReadStringPiece(&ip_address_bytes, address_family == 4 ? QuicheIpAddress::kIPv4AddressSize : QuicheIpAddress::kIPv6AddressSize)) { return absl::InvalidArgumentError( "Unable to read capsule ADDRESS_ASSIGN address"); } quiche::QuicheIpAddress ip_address; if (!ip_address.FromPackedString(ip_address_bytes.data(), ip_address_bytes.size())) { return absl::InvalidArgumentError( "Unable to parse capsule ADDRESS_ASSIGN address"); } uint8_t ip_prefix_length; if (!reader.ReadUInt8(&ip_prefix_length)) { return absl::InvalidArgumentError( "Unable to parse capsule ADDRESS_ASSIGN IP prefix length"); } if (ip_prefix_length > QuicheIpPrefix(ip_address).prefix_length()) { return absl::InvalidArgumentError("Invalid IP prefix length"); } assigned_address.ip_prefix = QuicheIpPrefix(ip_address, ip_prefix_length); capsule.assigned_addresses.push_back(assigned_address); } return Capsule(std::move(capsule)); } case CapsuleType::ROUTE_ADVERTISEMENT: { RouteAdvertisementCapsule capsule; while (!reader.IsDoneReading()) { uint8_t address_family; if (!reader.ReadUInt8(&address_family)) { return absl::InvalidArgumentError( "Unable to parse capsule ROUTE_ADVERTISEMENT family"); } if (address_family != 4 && address_family != 6) { return absl::InvalidArgumentError("Bad ROUTE_ADVERTISEMENT family"); } IpAddressRange ip_address_range; absl::string_view start_ip_address_bytes; if (!reader.ReadStringPiece(&start_ip_address_bytes, address_family == 4 ? QuicheIpAddress::kIPv4AddressSize : QuicheIpAddress::kIPv6AddressSize)) { return absl::InvalidArgumentError( "Unable to read capsule ROUTE_ADVERTISEMENT start address"); } if (!ip_address_range.start_ip_address.FromPackedString( start_ip_address_bytes.data(), start_ip_address_bytes.size())) { return absl::InvalidArgumentError( "Unable to parse capsule ROUTE_ADVERTISEMENT start address"); } absl::string_view end_ip_address_bytes; if (!reader.ReadStringPiece(&end_ip_address_bytes, address_family == 4 ? QuicheIpAddress::kIPv4AddressSize : QuicheIpAddress::kIPv6AddressSize)) { return absl::InvalidArgumentError( "Unable to read capsule ROUTE_ADVERTISEMENT end address"); } if (!ip_address_range.end_ip_address.FromPackedString( end_ip_address_bytes.data(), end_ip_address_bytes.size())) { return absl::InvalidArgumentError( "Unable to parse capsule ROUTE_ADVERTISEMENT end address"); } if (!reader.ReadUInt8(&ip_address_range.ip_protocol)) { return absl::InvalidArgumentError( "Unable to parse capsule ROUTE_ADVERTISEMENT IP protocol"); } capsule.ip_address_ranges.push_back(ip_address_range); } return Capsule(std::move(capsule)); } case CapsuleType::WT_STREAM: case CapsuleType::WT_STREAM_WITH_FIN: { WebTransportStreamDataCapsule capsule; capsule.fin = (type == CapsuleType::WT_STREAM_WITH_FIN); QUICHE_RETURN_IF_ERROR( ReadWebTransportStreamId(reader, capsule.stream_id)); capsule.data = reader.ReadRemainingPayload(); return Capsule(std::move(capsule)); } case CapsuleType::WT_RESET_STREAM: { WebTransportResetStreamCapsule capsule; QUICHE_RETURN_IF_ERROR( ReadWebTransportStreamId(reader, capsule.stream_id)); if (!reader.ReadVarInt62(&capsule.error_code)) { return absl::InvalidArgumentError( "Failed to parse the RESET_STREAM error code"); } return Capsule(std::move(capsule)); } case CapsuleType::WT_STOP_SENDING: { WebTransportStopSendingCapsule capsule; QUICHE_RETURN_IF_ERROR( ReadWebTransportStreamId(reader, capsule.stream_id)); if (!reader.ReadVarInt62(&capsule.error_code)) { return absl::InvalidArgumentError( "Failed to parse the STOP_SENDING error code"); } return Capsule(std::move(capsule)); } case CapsuleType::WT_MAX_STREAM_DATA: { WebTransportMaxStreamDataCapsule capsule; QUICHE_RETURN_IF_ERROR( ReadWebTransportStreamId(reader, capsule.stream_id)); if (!reader.ReadVarInt62(&capsule.max_stream_data)) { return absl::InvalidArgumentError( "Failed to parse the max stream data field"); } return Capsule(std::move(capsule)); } case CapsuleType::WT_MAX_STREAMS_UNIDI: case CapsuleType::WT_MAX_STREAMS_BIDI: { WebTransportMaxStreamsCapsule capsule; capsule.stream_type = type == CapsuleType::WT_MAX_STREAMS_UNIDI ? webtransport::StreamType::kUnidirectional : webtransport::StreamType::kBidirectional; if (!reader.ReadVarInt62(&capsule.max_stream_count)) { return absl::InvalidArgumentError( "Failed to parse the max streams field"); } return Capsule(std::move(capsule)); } default: return Capsule(UnknownCapsule{static_cast<uint64_t>(type), reader.ReadRemainingPayload()}); } } } absl::StatusOr<size_t> CapsuleParser::AttemptParseCapsule() { QUICHE_DCHECK(!parsing_error_occurred_); if (buffered_data_.empty()) { return 0; } QuicheDataReader capsule_fragment_reader(buffered_data_); uint64_t capsule_type64; if (!capsule_fragment_reader.ReadVarInt62(&capsule_type64)) { QUICHE_DVLOG(2) << "Partial read: not enough data to read capsule type"; return 0; } absl::string_view capsule_data; if (!capsule_fragment_reader.ReadStringPieceVarInt62(&capsule_data)) { QUICHE_DVLOG(2) << "Partial read: not enough data to read capsule length or " "full capsule data"; return 0; } QuicheDataReader capsule_data_reader(capsule_data); absl::StatusOr<Capsule> capsule = ParseCapsulePayload( capsule_data_reader, static_cast<CapsuleType>(capsule_type64)); QUICHE_RETURN_IF_ERROR(capsule.status()); if (!visitor_->OnCapsule(*capsule)) { return absl::AbortedError("Visitor failed to process capsule"); } return capsule_fragment_reader.PreviouslyReadPayload().length(); } void CapsuleParser::ReportParseFailure(absl::string_view error_message) { if (parsing_error_occurred_) { QUICHE_BUG(multiple parse errors) << "Experienced multiple parse failures"; return; } parsing_error_occurred_ = true; visitor_->OnCapsuleParseFailure(error_message); } void CapsuleParser::ErrorIfThereIsRemainingBufferedData() { if (parsing_error_occurred_) { return; } if (!buffered_data_.empty()) { ReportParseFailure("Incomplete capsule left at the end of the stream"); } } bool PrefixWithId::operator==(const PrefixWithId& other) const { return request_id == other.request_id && ip_prefix == other.ip_prefix; } bool IpAddressRange::operator==(const IpAddressRange& other) const { return start_ip_address == other.start_ip_address && end_ip_address == other.end_ip_address && ip_protocol == other.ip_protocol; } bool AddressAssignCapsule::operator==(const AddressAssignCapsule& other) const { return assigned_addresses == other.assigned_addresses; } bool AddressRequestCapsule::operator==( const AddressRequestCapsule& other) const { return requested_addresses == other.requested_addresses; } bool RouteAdvertisementCapsule::operator==( const RouteAdvertisementCapsule& other) const { return ip_address_ranges == other.ip_address_ranges; } bool WebTransportStreamDataCapsule::operator==( const WebTransportStreamDataCapsule& other) const { return stream_id == other.stream_id && data == other.data && fin == other.fin; } bool WebTransportResetStreamCapsule::operator==( const WebTransportResetStreamCapsule& other) const { return stream_id == other.stream_id && error_code == other.error_code; } bool WebTransportStopSendingCapsule::operator==( const WebTransportStopSendingCapsule& other) const { return stream_id == other.stream_id && error_code == other.error_code; } bool WebTransportMaxStreamDataCapsule::operator==( const WebTransportMaxStreamDataCapsule& other) const { return stream_id == other.stream_id && max_stream_data == other.max_stream_data; } bool WebTransportMaxStreamsCapsule::operator==( const WebTransportMaxStreamsCapsule& other) const { return stream_type == other.stream_type && max_stream_count == other.max_stream_count; } }
#include "quiche/common/capsule.h" #include <cstddef> #include <deque> #include <string> #include <vector> #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/quiche_buffer_allocator.h" #include "quiche/common/quiche_ip_address.h" #include "quiche/common/simple_buffer_allocator.h" #include "quiche/common/test_tools/quiche_test_utils.h" #include "quiche/web_transport/web_transport.h" using ::testing::_; using ::testing::InSequence; using ::testing::Return; using ::webtransport::StreamType; namespace quiche { namespace test { class CapsuleParserPeer { public: static std::string* buffered_data(CapsuleParser* capsule_parser) { return &capsule_parser->buffered_data_; } }; namespace { class MockCapsuleParserVisitor : public CapsuleParser::Visitor { public: MockCapsuleParserVisitor() { ON_CALL(*this, OnCapsule(_)).WillByDefault(Return(true)); } ~MockCapsuleParserVisitor() override = default; MOCK_METHOD(bool, OnCapsule, (const Capsule& capsule), (override)); MOCK_METHOD(void, OnCapsuleParseFailure, (absl::string_view error_message), (override)); }; class CapsuleTest : public QuicheTest { public: CapsuleTest() : capsule_parser_(&visitor_) {} void ValidateParserIsEmpty() { EXPECT_CALL(visitor_, OnCapsule(_)).Times(0); EXPECT_CALL(visitor_, OnCapsuleParseFailure(_)).Times(0); capsule_parser_.ErrorIfThereIsRemainingBufferedData(); EXPECT_TRUE(CapsuleParserPeer::buffered_data(&capsule_parser_)->empty()); } void TestSerialization(const Capsule& capsule, const std::string& expected_bytes) { quiche::QuicheBuffer serialized_capsule = SerializeCapsule(capsule, SimpleBufferAllocator::Get()); quiche::test::CompareCharArraysWithHexError( "Serialized capsule", serialized_capsule.data(), serialized_capsule.size(), expected_bytes.data(), expected_bytes.size()); } ::testing::StrictMock<MockCapsuleParserVisitor> visitor_; CapsuleParser capsule_parser_; }; TEST_F(CapsuleTest, DatagramCapsule) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("00" "08" "a1a2a3a4a5a6a7a8", &capsule_fragment)); std::string datagram_payload; ASSERT_TRUE(absl::HexStringToBytes("a1a2a3a4a5a6a7a8", &datagram_payload)); Capsule expected_capsule = Capsule::Datagram(datagram_payload); { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, DatagramCapsuleViaHeader) { std::string datagram_payload; ASSERT_TRUE(absl::HexStringToBytes("a1a2a3a4a5a6a7a8", &datagram_payload)); quiche::QuicheBuffer expected_capsule = SerializeCapsule( Capsule::Datagram(datagram_payload), SimpleBufferAllocator::Get()); quiche::QuicheBuffer actual_header = SerializeDatagramCapsuleHeader( datagram_payload.size(), SimpleBufferAllocator::Get()); EXPECT_EQ(expected_capsule.AsStringView(), absl::StrCat(actual_header.AsStringView(), datagram_payload)); } TEST_F(CapsuleTest, LegacyDatagramCapsule) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("80ff37a0" "08" "a1a2a3a4a5a6a7a8", &capsule_fragment)); std::string datagram_payload; ASSERT_TRUE(absl::HexStringToBytes("a1a2a3a4a5a6a7a8", &datagram_payload)); Capsule expected_capsule = Capsule::LegacyDatagram(datagram_payload); { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, LegacyDatagramWithoutContextCapsule) { std::string capsule_fragment; ASSERT_TRUE(absl::HexStringToBytes( "80ff37a5" "08" "a1a2a3a4a5a6a7a8", &capsule_fragment)); std::string datagram_payload; ASSERT_TRUE(absl::HexStringToBytes("a1a2a3a4a5a6a7a8", &datagram_payload)); Capsule expected_capsule = Capsule::LegacyDatagramWithoutContext(datagram_payload); { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, CloseWebTransportStreamCapsule) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("6843" "09" "00001234" "68656c6c6f", &capsule_fragment)); Capsule expected_capsule = Capsule::CloseWebTransportSession( 0x1234, "hello"); { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, DrainWebTransportStreamCapsule) { std::string capsule_fragment; ASSERT_TRUE(absl::HexStringToBytes( "800078ae" "00", &capsule_fragment)); Capsule expected_capsule = Capsule(DrainWebTransportSessionCapsule()); { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, AddressAssignCapsule) { std::string capsule_fragment; ASSERT_TRUE(absl::HexStringToBytes( "9ECA6A00" "1A" "00" "04" "C000022A" "1F" "01" "06" "20010db8123456780000000000000000" "40", &capsule_fragment)); Capsule expected_capsule = Capsule::AddressAssign(); quiche::QuicheIpAddress ip_address1; ip_address1.FromString("192.0.2.42"); PrefixWithId assigned_address1; assigned_address1.request_id = 0; assigned_address1.ip_prefix = quiche::QuicheIpPrefix(ip_address1, 31); expected_capsule.address_assign_capsule().assigned_addresses.push_back( assigned_address1); quiche::QuicheIpAddress ip_address2; ip_address2.FromString("2001:db8:1234:5678::"); PrefixWithId assigned_address2; assigned_address2.request_id = 1; assigned_address2.ip_prefix = quiche::QuicheIpPrefix(ip_address2, 64); expected_capsule.address_assign_capsule().assigned_addresses.push_back( assigned_address2); { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, AddressRequestCapsule) { std::string capsule_fragment; ASSERT_TRUE(absl::HexStringToBytes( "9ECA6A01" "1A" "00" "04" "C000022A" "1F" "01" "06" "20010db8123456780000000000000000" "40", &capsule_fragment)); Capsule expected_capsule = Capsule::AddressRequest(); quiche::QuicheIpAddress ip_address1; ip_address1.FromString("192.0.2.42"); PrefixWithId requested_address1; requested_address1.request_id = 0; requested_address1.ip_prefix = quiche::QuicheIpPrefix(ip_address1, 31); expected_capsule.address_request_capsule().requested_addresses.push_back( requested_address1); quiche::QuicheIpAddress ip_address2; ip_address2.FromString("2001:db8:1234:5678::"); PrefixWithId requested_address2; requested_address2.request_id = 1; requested_address2.ip_prefix = quiche::QuicheIpPrefix(ip_address2, 64); expected_capsule.address_request_capsule().requested_addresses.push_back( requested_address2); { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, RouteAdvertisementCapsule) { std::string capsule_fragment; ASSERT_TRUE(absl::HexStringToBytes( "9ECA6A02" "2C" "04" "C0000218" "C000022A" "00" "06" "00000000000000000000000000000000" "ffffffffffffffffffffffffffffffff" "01", &capsule_fragment)); Capsule expected_capsule = Capsule::RouteAdvertisement(); IpAddressRange ip_address_range1; ip_address_range1.start_ip_address.FromString("192.0.2.24"); ip_address_range1.end_ip_address.FromString("192.0.2.42"); ip_address_range1.ip_protocol = 0; expected_capsule.route_advertisement_capsule().ip_address_ranges.push_back( ip_address_range1); IpAddressRange ip_address_range2; ip_address_range2.start_ip_address.FromString("::"); ip_address_range2.end_ip_address.FromString( "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); ip_address_range2.ip_protocol = 1; expected_capsule.route_advertisement_capsule().ip_address_ranges.push_back( ip_address_range2); { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, WebTransportStreamData) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("990b4d3b" "04" "17" "abcdef", &capsule_fragment)); Capsule expected_capsule = Capsule(WebTransportStreamDataCapsule()); expected_capsule.web_transport_stream_data().stream_id = 0x17; expected_capsule.web_transport_stream_data().data = "\xab\xcd\xef"; expected_capsule.web_transport_stream_data().fin = false; { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, WebTransportStreamDataHeader) { std::string capsule_fragment; ASSERT_TRUE(absl::HexStringToBytes( "990b4d3b" "04" "17", &capsule_fragment)); QuicheBufferAllocator* allocator = SimpleBufferAllocator::Get(); QuicheBuffer capsule_header = quiche::SerializeWebTransportStreamCapsuleHeader(0x17, false, 3, allocator); EXPECT_EQ(capsule_header.AsStringView(), capsule_fragment); } TEST_F(CapsuleTest, WebTransportStreamDataWithFin) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("990b4d3c" "04" "17" "abcdef", &capsule_fragment)); Capsule expected_capsule = Capsule(WebTransportStreamDataCapsule()); expected_capsule.web_transport_stream_data().stream_id = 0x17; expected_capsule.web_transport_stream_data().data = "\xab\xcd\xef"; expected_capsule.web_transport_stream_data().fin = true; { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, WebTransportResetStream) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("990b4d39" "02" "17" "07", &capsule_fragment)); Capsule expected_capsule = Capsule(WebTransportResetStreamCapsule()); expected_capsule.web_transport_reset_stream().stream_id = 0x17; expected_capsule.web_transport_reset_stream().error_code = 0x07; { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, WebTransportStopSending) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("990b4d3a" "02" "17" "07", &capsule_fragment)); Capsule expected_capsule = Capsule(WebTransportStopSendingCapsule()); expected_capsule.web_transport_stop_sending().stream_id = 0x17; expected_capsule.web_transport_stop_sending().error_code = 0x07; { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, WebTransportMaxStreamData) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("990b4d3e" "02" "17" "10", &capsule_fragment)); Capsule expected_capsule = Capsule(WebTransportMaxStreamDataCapsule()); expected_capsule.web_transport_max_stream_data().stream_id = 0x17; expected_capsule.web_transport_max_stream_data().max_stream_data = 0x10; { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, WebTransportMaxStreamsBi) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("990b4d3f" "01" "17", &capsule_fragment)); Capsule expected_capsule = Capsule(WebTransportMaxStreamsCapsule()); expected_capsule.web_transport_max_streams().stream_type = StreamType::kBidirectional; expected_capsule.web_transport_max_streams().max_stream_count = 0x17; { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, WebTransportMaxStreamsUni) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("990b4d40" "01" "17", &capsule_fragment)); Capsule expected_capsule = Capsule(WebTransportMaxStreamsCapsule()); expected_capsule.web_transport_max_streams().stream_type = StreamType::kUnidirectional; expected_capsule.web_transport_max_streams().max_stream_count = 0x17; { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, UnknownCapsule) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("17" "08" "a1a2a3a4a5a6a7a8", &capsule_fragment)); std::string unknown_capsule_data; ASSERT_TRUE( absl::HexStringToBytes("a1a2a3a4a5a6a7a8", &unknown_capsule_data)); Capsule expected_capsule = Capsule::Unknown(0x17, unknown_capsule_data); { EXPECT_CALL(visitor_, OnCapsule(expected_capsule)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); TestSerialization(expected_capsule, capsule_fragment); } TEST_F(CapsuleTest, TwoCapsules) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("00" "08" "a1a2a3a4a5a6a7a8" "00" "08" "b1b2b3b4b5b6b7b8", &capsule_fragment)); std::string datagram_payload1; ASSERT_TRUE(absl::HexStringToBytes("a1a2a3a4a5a6a7a8", &datagram_payload1)); std::string datagram_payload2; ASSERT_TRUE(absl::HexStringToBytes("b1b2b3b4b5b6b7b8", &datagram_payload2)); Capsule expected_capsule1 = Capsule::Datagram(datagram_payload1); Capsule expected_capsule2 = Capsule::Datagram(datagram_payload2); { InSequence s; EXPECT_CALL(visitor_, OnCapsule(expected_capsule1)); EXPECT_CALL(visitor_, OnCapsule(expected_capsule2)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } ValidateParserIsEmpty(); } TEST_F(CapsuleTest, TwoCapsulesPartialReads) { std::string capsule_fragment1; ASSERT_TRUE(absl::HexStringToBytes( "00" "08" "a1a2a3a4", &capsule_fragment1)); std::string capsule_fragment2; ASSERT_TRUE(absl::HexStringToBytes( "a5a6a7a8" "00", &capsule_fragment2)); std::string capsule_fragment3; ASSERT_TRUE(absl::HexStringToBytes( "08" "b1b2b3b4b5b6b7b8", &capsule_fragment3)); capsule_parser_.ErrorIfThereIsRemainingBufferedData(); std::string datagram_payload1; ASSERT_TRUE(absl::HexStringToBytes("a1a2a3a4a5a6a7a8", &datagram_payload1)); std::string datagram_payload2; ASSERT_TRUE(absl::HexStringToBytes("b1b2b3b4b5b6b7b8", &datagram_payload2)); Capsule expected_capsule1 = Capsule::Datagram(datagram_payload1); Capsule expected_capsule2 = Capsule::Datagram(datagram_payload2); { InSequence s; EXPECT_CALL(visitor_, OnCapsule(expected_capsule1)); EXPECT_CALL(visitor_, OnCapsule(expected_capsule2)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment1)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment2)); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment3)); } ValidateParserIsEmpty(); } TEST_F(CapsuleTest, TwoCapsulesOneByteAtATime) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("00" "08" "a1a2a3a4a5a6a7a8" "00" "08" "b1b2b3b4b5b6b7b8", &capsule_fragment)); std::string datagram_payload1; ASSERT_TRUE(absl::HexStringToBytes("a1a2a3a4a5a6a7a8", &datagram_payload1)); std::string datagram_payload2; ASSERT_TRUE(absl::HexStringToBytes("b1b2b3b4b5b6b7b8", &datagram_payload2)); Capsule expected_capsule1 = Capsule::Datagram(datagram_payload1); Capsule expected_capsule2 = Capsule::Datagram(datagram_payload2); for (size_t i = 0; i < capsule_fragment.size(); i++) { if (i < capsule_fragment.size() / 2 - 1) { EXPECT_CALL(visitor_, OnCapsule(_)).Times(0); ASSERT_TRUE( capsule_parser_.IngestCapsuleFragment(capsule_fragment.substr(i, 1))); } else if (i == capsule_fragment.size() / 2 - 1) { EXPECT_CALL(visitor_, OnCapsule(expected_capsule1)); ASSERT_TRUE( capsule_parser_.IngestCapsuleFragment(capsule_fragment.substr(i, 1))); EXPECT_TRUE(CapsuleParserPeer::buffered_data(&capsule_parser_)->empty()); } else if (i < capsule_fragment.size() - 1) { EXPECT_CALL(visitor_, OnCapsule(_)).Times(0); ASSERT_TRUE( capsule_parser_.IngestCapsuleFragment(capsule_fragment.substr(i, 1))); } else { EXPECT_CALL(visitor_, OnCapsule(expected_capsule2)); ASSERT_TRUE( capsule_parser_.IngestCapsuleFragment(capsule_fragment.substr(i, 1))); EXPECT_TRUE(CapsuleParserPeer::buffered_data(&capsule_parser_)->empty()); } } capsule_parser_.ErrorIfThereIsRemainingBufferedData(); EXPECT_TRUE(CapsuleParserPeer::buffered_data(&capsule_parser_)->empty()); } TEST_F(CapsuleTest, PartialCapsuleThenError) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("00" "08" "a1a2a3a4", &capsule_fragment)); EXPECT_CALL(visitor_, OnCapsule(_)).Times(0); { EXPECT_CALL(visitor_, OnCapsuleParseFailure(_)).Times(0); ASSERT_TRUE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } { EXPECT_CALL(visitor_, OnCapsuleParseFailure( "Incomplete capsule left at the end of the stream")); capsule_parser_.ErrorIfThereIsRemainingBufferedData(); } } TEST_F(CapsuleTest, RejectOverlyLongCapsule) { std::string capsule_fragment; ASSERT_TRUE( absl::HexStringToBytes("17" "80123456", &capsule_fragment)); absl::StrAppend(&capsule_fragment, std::string(1111111, '?')); EXPECT_CALL(visitor_, OnCapsuleParseFailure( "Refusing to buffer too much capsule data")); EXPECT_FALSE(capsule_parser_.IngestCapsuleFragment(capsule_fragment)); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/capsule.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/capsule_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
8ad50b9e-3347-4ebf-a039-ec6826ed5c98
cpp
google/quiche
connect_ip_datagram_payload
quiche/common/masque/connect_ip_datagram_payload.cc
quiche/common/masque/connect_ip_datagram_payload_test.cc
#include "quiche/common/masque/connect_ip_datagram_payload.h" #include <cstddef> #include <cstdint> #include <memory> #include <string> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_data_reader.h" #include "quiche/common/quiche_data_writer.h" namespace quiche { std::unique_ptr<ConnectIpDatagramPayload> ConnectIpDatagramPayload::Parse( absl::string_view datagram_payload) { QuicheDataReader data_reader(datagram_payload); uint64_t context_id; if (!data_reader.ReadVarInt62(&context_id)) { QUICHE_DVLOG(1) << "Could not parse malformed IP proxy payload"; return nullptr; } if (ContextId{context_id} == ConnectIpDatagramIpPacketPayload::kContextId) { return std::make_unique<ConnectIpDatagramIpPacketPayload>( data_reader.ReadRemainingPayload()); } else { return std::make_unique<ConnectIpDatagramUnknownPayload>( ContextId{context_id}, data_reader.ReadRemainingPayload()); } } std::string ConnectIpDatagramPayload::Serialize() const { std::string buffer(SerializedLength(), '\0'); QuicheDataWriter writer(buffer.size(), buffer.data()); bool result = SerializeTo(writer); QUICHE_DCHECK(result); QUICHE_DCHECK_EQ(writer.remaining(), 0u); return buffer; } ConnectIpDatagramIpPacketPayload::ConnectIpDatagramIpPacketPayload( absl::string_view ip_packet) : ip_packet_(ip_packet) {} ConnectIpDatagramPayload::ContextId ConnectIpDatagramIpPacketPayload::GetContextId() const { return kContextId; } ConnectIpDatagramPayload::Type ConnectIpDatagramIpPacketPayload::GetType() const { return Type::kIpPacket; } absl::string_view ConnectIpDatagramIpPacketPayload::GetIpProxyingPayload() const { return ip_packet_; } size_t ConnectIpDatagramIpPacketPayload::SerializedLength() const { return ip_packet_.size() + QuicheDataWriter::GetVarInt62Len(uint64_t{kContextId}); } bool ConnectIpDatagramIpPacketPayload::SerializeTo( QuicheDataWriter& writer) const { if (!writer.WriteVarInt62(uint64_t{kContextId})) { return false; } if (!writer.WriteStringPiece(ip_packet_)) { return false; } return true; } ConnectIpDatagramUnknownPayload::ConnectIpDatagramUnknownPayload( ContextId context_id, absl::string_view ip_proxying_payload) : context_id_(context_id), ip_proxying_payload_(ip_proxying_payload) { if (context_id == ConnectIpDatagramIpPacketPayload::kContextId) { QUICHE_BUG(ip_proxy_unknown_payload_ip_context) << "ConnectIpDatagramUnknownPayload created with IP packet context " "ID (0). Should instead create a " "ConnectIpDatagramIpPacketPayload."; } } ConnectIpDatagramPayload::ContextId ConnectIpDatagramUnknownPayload::GetContextId() const { return context_id_; } ConnectIpDatagramPayload::Type ConnectIpDatagramUnknownPayload::GetType() const { return Type::kUnknown; } absl::string_view ConnectIpDatagramUnknownPayload::GetIpProxyingPayload() const { return ip_proxying_payload_; } size_t ConnectIpDatagramUnknownPayload::SerializedLength() const { return ip_proxying_payload_.size() + QuicheDataWriter::GetVarInt62Len(uint64_t{context_id_}); } bool ConnectIpDatagramUnknownPayload::SerializeTo( QuicheDataWriter& writer) const { if (!writer.WriteVarInt62(uint64_t{context_id_})) { return false; } if (!writer.WriteStringPiece(ip_proxying_payload_)) { return false; } return true; } }
#include "quiche/common/masque/connect_ip_datagram_payload.h" #include <memory> #include <string> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_test.h" namespace quiche::test { namespace { TEST(ConnectIpDatagramPayloadTest, ParseIpPacket) { static constexpr char kDatagramPayload[] = "\x00packet"; std::unique_ptr<ConnectIpDatagramPayload> parsed = ConnectIpDatagramPayload::Parse( absl::string_view(kDatagramPayload, sizeof(kDatagramPayload) - 1)); ASSERT_TRUE(parsed); EXPECT_EQ(parsed->GetContextId(), ConnectIpDatagramIpPacketPayload::kContextId); EXPECT_EQ(parsed->GetType(), ConnectIpDatagramPayload::Type::kIpPacket); EXPECT_EQ(parsed->GetIpProxyingPayload(), "packet"); } TEST(ConnectIpDatagramPayloadTest, SerializeIpPacket) { static constexpr absl::string_view kIpPacket = "packet"; ConnectIpDatagramIpPacketPayload payload(kIpPacket); EXPECT_EQ(payload.GetIpProxyingPayload(), kIpPacket); EXPECT_EQ(payload.Serialize(), std::string("\x00packet", 7)); } TEST(ConnectIpDatagramPayloadTest, ParseUnknownPacket) { static constexpr char kDatagramPayload[] = "\x05packet"; std::unique_ptr<ConnectIpDatagramPayload> parsed = ConnectIpDatagramPayload::Parse( absl::string_view(kDatagramPayload, sizeof(kDatagramPayload) - 1)); ASSERT_TRUE(parsed); EXPECT_EQ(parsed->GetContextId(), 5); EXPECT_EQ(parsed->GetType(), ConnectIpDatagramPayload::Type::kUnknown); EXPECT_EQ(parsed->GetIpProxyingPayload(), "packet"); } TEST(ConnectIpDatagramPayloadTest, SerializeUnknownPacket) { static constexpr absl::string_view kInnerIpProxyingPayload = "packet"; ConnectIpDatagramUnknownPayload payload(4u, kInnerIpProxyingPayload); EXPECT_EQ(payload.GetIpProxyingPayload(), kInnerIpProxyingPayload); EXPECT_EQ(payload.Serialize(), std::string("\x04packet", 7)); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/masque/connect_ip_datagram_payload.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/masque/connect_ip_datagram_payload_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
d8467ab7-3264-4340-a4dd-5ef9bc2415d2
cpp
google/quiche
connect_udp_datagram_payload
quiche/common/masque/connect_udp_datagram_payload.cc
quiche/common/masque/connect_udp_datagram_payload_test.cc
#include "quiche/common/masque/connect_udp_datagram_payload.h" #include <cstdint> #include <memory> #include <string> #include <utility> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_data_reader.h" #include "quiche/common/quiche_data_writer.h" namespace quiche { std::unique_ptr<ConnectUdpDatagramPayload> ConnectUdpDatagramPayload::Parse( absl::string_view datagram_payload) { QuicheDataReader data_reader(datagram_payload); uint64_t context_id; if (!data_reader.ReadVarInt62(&context_id)) { QUICHE_DVLOG(1) << "Could not parse malformed UDP proxy payload"; return nullptr; } if (ContextId{context_id} == ConnectUdpDatagramUdpPacketPayload::kContextId) { return std::make_unique<ConnectUdpDatagramUdpPacketPayload>( data_reader.ReadRemainingPayload()); } else { return std::make_unique<ConnectUdpDatagramUnknownPayload>( ContextId{context_id}, data_reader.ReadRemainingPayload()); } } std::string ConnectUdpDatagramPayload::Serialize() const { std::string buffer(SerializedLength(), '\0'); QuicheDataWriter writer(buffer.size(), buffer.data()); bool result = SerializeTo(writer); QUICHE_DCHECK(result); QUICHE_DCHECK_EQ(writer.remaining(), 0u); return buffer; } ConnectUdpDatagramUdpPacketPayload::ConnectUdpDatagramUdpPacketPayload( absl::string_view udp_packet) : udp_packet_(udp_packet) {} ConnectUdpDatagramPayload::ContextId ConnectUdpDatagramUdpPacketPayload::GetContextId() const { return kContextId; } ConnectUdpDatagramPayload::Type ConnectUdpDatagramUdpPacketPayload::GetType() const { return Type::kUdpPacket; } absl::string_view ConnectUdpDatagramUdpPacketPayload::GetUdpProxyingPayload() const { return udp_packet_; } size_t ConnectUdpDatagramUdpPacketPayload::SerializedLength() const { return udp_packet_.size() + QuicheDataWriter::GetVarInt62Len(uint64_t{kContextId}); } bool ConnectUdpDatagramUdpPacketPayload::SerializeTo( QuicheDataWriter& writer) const { if (!writer.WriteVarInt62(uint64_t{kContextId})) { return false; } if (!writer.WriteStringPiece(udp_packet_)) { return false; } return true; } ConnectUdpDatagramUnknownPayload::ConnectUdpDatagramUnknownPayload( ContextId context_id, absl::string_view udp_proxying_payload) : context_id_(context_id), udp_proxying_payload_(udp_proxying_payload) { if (context_id == ConnectUdpDatagramUdpPacketPayload::kContextId) { QUICHE_BUG(udp_proxy_unknown_payload_udp_context) << "ConnectUdpDatagramUnknownPayload created with UDP packet context " "type (0). Should instead create a " "ConnectUdpDatagramUdpPacketPayload."; } } ConnectUdpDatagramPayload::ContextId ConnectUdpDatagramUnknownPayload::GetContextId() const { return context_id_; } ConnectUdpDatagramPayload::Type ConnectUdpDatagramUnknownPayload::GetType() const { return Type::kUnknown; } absl::string_view ConnectUdpDatagramUnknownPayload::GetUdpProxyingPayload() const { return udp_proxying_payload_; } size_t ConnectUdpDatagramUnknownPayload::SerializedLength() const { return udp_proxying_payload_.size() + QuicheDataWriter::GetVarInt62Len(uint64_t{context_id_}); } bool ConnectUdpDatagramUnknownPayload::SerializeTo( QuicheDataWriter& writer) const { if (!writer.WriteVarInt62(uint64_t{context_id_})) { return false; } if (!writer.WriteStringPiece(udp_proxying_payload_)) { return false; } return true; } }
#include "quiche/common/masque/connect_udp_datagram_payload.h" #include <memory> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_test.h" namespace quiche::test { namespace { TEST(ConnectUdpDatagramPayloadTest, ParseUdpPacket) { static constexpr char kDatagramPayload[] = "\x00packet"; std::unique_ptr<ConnectUdpDatagramPayload> parsed = ConnectUdpDatagramPayload::Parse( absl::string_view(kDatagramPayload, sizeof(kDatagramPayload) - 1)); ASSERT_TRUE(parsed); EXPECT_EQ(parsed->GetContextId(), ConnectUdpDatagramUdpPacketPayload::kContextId); EXPECT_EQ(parsed->GetType(), ConnectUdpDatagramPayload::Type::kUdpPacket); EXPECT_EQ(parsed->GetUdpProxyingPayload(), "packet"); } TEST(ConnectUdpDatagramPayloadTest, SerializeUdpPacket) { static constexpr absl::string_view kUdpPacket = "packet"; ConnectUdpDatagramUdpPacketPayload payload(kUdpPacket); EXPECT_EQ(payload.GetUdpProxyingPayload(), kUdpPacket); EXPECT_EQ(payload.Serialize(), std::string("\x00packet", 7)); } TEST(ConnectUdpDatagramPayloadTest, ParseUnknownPacket) { static constexpr char kDatagramPayload[] = "\x05packet"; std::unique_ptr<ConnectUdpDatagramPayload> parsed = ConnectUdpDatagramPayload::Parse( absl::string_view(kDatagramPayload, sizeof(kDatagramPayload) - 1)); ASSERT_TRUE(parsed); EXPECT_EQ(parsed->GetContextId(), 5); EXPECT_EQ(parsed->GetType(), ConnectUdpDatagramPayload::Type::kUnknown); EXPECT_EQ(parsed->GetUdpProxyingPayload(), "packet"); } TEST(ConnectUdpDatagramPayloadTest, SerializeUnknownPacket) { static constexpr absl::string_view kInnerUdpProxyingPayload = "packet"; ConnectUdpDatagramUnknownPayload payload(4u, kInnerUdpProxyingPayload); EXPECT_EQ(payload.GetUdpProxyingPayload(), kInnerUdpProxyingPayload); EXPECT_EQ(payload.Serialize(), std::string("\x04packet", 7)); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/masque/connect_udp_datagram_payload.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/masque/connect_udp_datagram_payload_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
1426a3dd-c421-4482-8c1c-1fc35b1628e4
cpp
google/quiche
quiche_test_utils
quiche/common/test_tools/quiche_test_utils.cc
quiche/common/test_tools/quiche_test_utils_test.cc
#include "quiche/common/test_tools/quiche_test_utils.h" #include <algorithm> #include <memory> #include <string> #include "quiche/common/platform/api/quiche_googleurl.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" namespace { std::string HexDumpWithMarks(const char* data, int length, const bool* marks, int mark_length) { static const char kHexChars[] = "0123456789abcdef"; static const int kColumns = 4; const int kSizeLimit = 1024; if (length > kSizeLimit || mark_length > kSizeLimit) { QUICHE_LOG(ERROR) << "Only dumping first " << kSizeLimit << " bytes."; length = std::min(length, kSizeLimit); mark_length = std::min(mark_length, kSizeLimit); } std::string hex; for (const char* row = data; length > 0; row += kColumns, length -= kColumns) { for (const char* p = row; p < row + 4; ++p) { if (p < row + length) { const bool mark = (marks && (p - data) < mark_length && marks[p - data]); hex += mark ? '*' : ' '; hex += kHexChars[(*p & 0xf0) >> 4]; hex += kHexChars[*p & 0x0f]; hex += mark ? '*' : ' '; } else { hex += " "; } } hex = hex + " "; for (const char* p = row; p < row + 4 && p < row + length; ++p) { hex += (*p >= 0x20 && *p < 0x7f) ? (*p) : '.'; } hex = hex + '\n'; } return hex; } } namespace quiche { namespace test { void CompareCharArraysWithHexError(const std::string& description, const char* actual, const int actual_len, const char* expected, const int expected_len) { EXPECT_EQ(actual_len, expected_len); const int min_len = std::min(actual_len, expected_len); const int max_len = std::max(actual_len, expected_len); std::unique_ptr<bool[]> marks(new bool[max_len]); bool identical = (actual_len == expected_len); for (int i = 0; i < min_len; ++i) { if (actual[i] != expected[i]) { marks[i] = true; identical = false; } else { marks[i] = false; } } for (int i = min_len; i < max_len; ++i) { marks[i] = true; } if (identical) return; ADD_FAILURE() << "Description:\n" << description << "\n\nExpected:\n" << HexDumpWithMarks(expected, expected_len, marks.get(), max_len) << "\nActual:\n" << HexDumpWithMarks(actual, actual_len, marks.get(), max_len); } iovec MakeIOVector(absl::string_view str) { return iovec{const_cast<char*>(str.data()), static_cast<size_t>(str.size())}; } bool GoogleUrlSupportsIdnaForTest() { const std::string kTestInput = "https: const std::string kExpectedOutput = "https: GURL url(kTestInput); bool valid = url.is_valid() && url.spec() == kExpectedOutput; QUICHE_CHECK(valid || !url.is_valid()) << url.spec(); return valid; } } }
#include "quiche/common/test_tools/quiche_test_utils.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "quiche/common/platform/api/quiche_test.h" namespace quiche::test { namespace { using ::testing::HasSubstr; using ::testing::Not; TEST(QuicheTestUtilsTest, StatusMatchers) { const absl::Status ok = absl::OkStatus(); QUICHE_EXPECT_OK(ok); QUICHE_ASSERT_OK(ok); EXPECT_THAT(ok, IsOk()); const absl::StatusOr<int> ok_with_value = 2023; QUICHE_EXPECT_OK(ok_with_value); QUICHE_ASSERT_OK(ok_with_value); EXPECT_THAT(ok_with_value, IsOk()); EXPECT_THAT(ok_with_value, IsOkAndHolds(2023)); const absl::Status err = absl::InternalError("test error"); EXPECT_THAT(err, Not(IsOk())); EXPECT_THAT(err, StatusIs(absl::StatusCode::kInternal, HasSubstr("test"))); const absl::StatusOr<int> err_with_value = absl::InternalError("test error"); EXPECT_THAT(err_with_value, Not(IsOk())); EXPECT_THAT(err_with_value, Not(IsOkAndHolds(2023))); EXPECT_THAT(err_with_value, StatusIs(absl::StatusCode::kInternal, HasSubstr("test"))); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/test_tools/quiche_test_utils.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/test_tools/quiche_test_utils_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
3797474d-2ba5-43bc-bc6a-07e9099bc36a
cpp
google/quiche
quiche_file_utils
quiche/common/platform/api/quiche_file_utils.cc
quiche/common/platform/api/quiche_file_utils_test.cc
#include "quiche/common/platform/api/quiche_file_utils.h" #include <optional> #include <string> #include <vector> #include "quiche_platform_impl/quiche_file_utils_impl.h" namespace quiche { std::string JoinPath(absl::string_view a, absl::string_view b) { return JoinPathImpl(a, b); } std::optional<std::string> ReadFileContents(absl::string_view file) { return ReadFileContentsImpl(file); } bool EnumerateDirectory(absl::string_view path, std::vector<std::string>& directories, std::vector<std::string>& files) { return EnumerateDirectoryImpl(path, directories, files); } bool EnumerateDirectoryRecursivelyInner(absl::string_view path, int recursion_limit, std::vector<std::string>& files) { if (recursion_limit < 0) { return false; } std::vector<std::string> local_files; std::vector<std::string> directories; if (!EnumerateDirectory(path, directories, local_files)) { return false; } for (const std::string& directory : directories) { if (!EnumerateDirectoryRecursivelyInner(JoinPath(path, directory), recursion_limit - 1, files)) { return false; } } for (const std::string& file : local_files) { files.push_back(JoinPath(path, file)); } return true; } bool EnumerateDirectoryRecursively(absl::string_view path, std::vector<std::string>& files) { constexpr int kRecursionLimit = 20; return EnumerateDirectoryRecursivelyInner(path, kRecursionLimit, files); } }
#include "quiche/common/platform/api/quiche_file_utils.h" #include <optional> #include <string> #include <vector> #include "absl/algorithm/container.h" #include "absl/strings/str_cat.h" #include "absl/strings/strip.h" #include "quiche/common/platform/api/quiche_test.h" namespace quiche { namespace test { namespace { using testing::UnorderedElementsAre; using testing::UnorderedElementsAreArray; TEST(QuicheFileUtilsTest, ReadFileContents) { std::string path = absl::StrCat(QuicheGetCommonSourcePath(), "/platform/api/testdir/testfile"); std::optional<std::string> contents = ReadFileContents(path); ASSERT_TRUE(contents.has_value()); EXPECT_EQ(*contents, "This is a test file."); } TEST(QuicheFileUtilsTest, ReadFileContentsFileNotFound) { std::string path = absl::StrCat(QuicheGetCommonSourcePath(), "/platform/api/testdir/file-that-does-not-exist"); std::optional<std::string> contents = ReadFileContents(path); EXPECT_FALSE(contents.has_value()); } TEST(QuicheFileUtilsTest, EnumerateDirectory) { std::string path = absl::StrCat(QuicheGetCommonSourcePath(), "/platform/api/testdir"); std::vector<std::string> dirs; std::vector<std::string> files; bool success = EnumerateDirectory(path, dirs, files); EXPECT_TRUE(success); EXPECT_THAT(files, UnorderedElementsAre("testfile", "README.md")); EXPECT_THAT(dirs, UnorderedElementsAre("a")); } TEST(QuicheFileUtilsTest, EnumerateDirectoryNoSuchDirectory) { std::string path = absl::StrCat(QuicheGetCommonSourcePath(), "/platform/api/testdir/no-such-directory"); std::vector<std::string> dirs; std::vector<std::string> files; bool success = EnumerateDirectory(path, dirs, files); EXPECT_FALSE(success); } TEST(QuicheFileUtilsTest, EnumerateDirectoryNotADirectory) { std::string path = absl::StrCat(QuicheGetCommonSourcePath(), "/platform/api/testdir/testfile"); std::vector<std::string> dirs; std::vector<std::string> files; bool success = EnumerateDirectory(path, dirs, files); EXPECT_FALSE(success); } TEST(QuicheFileUtilsTest, EnumerateDirectoryRecursively) { std::vector<std::string> expected_paths = {"a/b/c/d/e", "a/subdir/testfile", "a/z", "testfile", "README.md"}; std::string root_path = absl::StrCat(QuicheGetCommonSourcePath(), "/platform/api/testdir"); for (std::string& path : expected_paths) { if (JoinPath("a", "b") == "a\\b") { absl::c_replace(path, '/', '\\'); } path = JoinPath(root_path, path); } std::vector<std::string> files; bool success = EnumerateDirectoryRecursively(root_path, files); EXPECT_TRUE(success); EXPECT_THAT(files, UnorderedElementsAreArray(expected_paths)); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/platform/api/quiche_file_utils.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/platform/api/quiche_file_utils_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
8b4e682b-c33b-48fd-a609-fd3a0ddd81d2
cpp
google/quiche
quiche_hostname_utils
quiche/common/platform/api/quiche_hostname_utils.cc
quiche/common/platform/api/quiche_hostname_utils_test.cc
#include "quiche/common/platform/api/quiche_hostname_utils.h" #include <string> #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_googleurl.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quiche { namespace { std::string CanonicalizeHost(absl::string_view host, url::CanonHostInfo* host_info) { const url::Component raw_host_component(0, static_cast<int>(host.length())); std::string canon_host; url::StdStringCanonOutput canon_host_output(&canon_host); url::CanonicalizeHostVerbose(host.data(), raw_host_component, &canon_host_output, host_info); if (host_info->out_host.is_nonempty() && host_info->family != url::CanonHostInfo::BROKEN) { canon_host_output.Complete(); QUICHE_DCHECK_EQ(host_info->out_host.len, static_cast<int>(canon_host.length())); } else { canon_host.clear(); } return canon_host; } bool IsHostCharAlphanumeric(char c) { return ((c >= 'a') && (c <= 'z')) || ((c >= '0') && (c <= '9')); } bool IsCanonicalizedHostCompliant(const std::string& host) { if (host.empty()) { return false; } bool in_component = false; bool most_recent_component_started_alphanumeric = false; for (char c : host) { if (!in_component) { most_recent_component_started_alphanumeric = IsHostCharAlphanumeric(c); if (!most_recent_component_started_alphanumeric && (c != '-') && (c != '_')) { return false; } in_component = true; } else if (c == '.') { in_component = false; } else if (!IsHostCharAlphanumeric(c) && (c != '-') && (c != '_')) { return false; } } return most_recent_component_started_alphanumeric; } } bool QuicheHostnameUtils::IsValidSNI(absl::string_view sni) { url::CanonHostInfo host_info; std::string canonicalized_host = CanonicalizeHost(sni, &host_info); return !host_info.IsIPAddress() && IsCanonicalizedHostCompliant(canonicalized_host); } std::string QuicheHostnameUtils::NormalizeHostname(absl::string_view hostname) { url::CanonHostInfo host_info; std::string host = CanonicalizeHost(hostname, &host_info); size_t host_end = host.length(); while (host_end != 0 && host[host_end - 1] == '.') { host_end--; } if (host_end != host.length()) { host.erase(host_end, host.length() - host_end); } return host; } }
#include "quiche/common/platform/api/quiche_hostname_utils.h" #include <string> #include "absl/base/macros.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace quiche { namespace test { namespace { class QuicheHostnameUtilsTest : public QuicheTest {}; TEST_F(QuicheHostnameUtilsTest, IsValidSNI) { EXPECT_FALSE(QuicheHostnameUtils::IsValidSNI("192.168.0.1")); EXPECT_TRUE(QuicheHostnameUtils::IsValidSNI("somedomain")); EXPECT_TRUE(QuicheHostnameUtils::IsValidSNI("some_domain.com")); EXPECT_FALSE(QuicheHostnameUtils::IsValidSNI("")); EXPECT_TRUE(QuicheHostnameUtils::IsValidSNI("test.google.com")); } TEST_F(QuicheHostnameUtilsTest, NormalizeHostname) { struct { const char *input, *expected; } tests[] = { { "www.google.com", "www.google.com", }, { "WWW.GOOGLE.COM", "www.google.com", }, { "www.google.com.", "www.google.com", }, { "www.google.COM.", "www.google.com", }, { "www.google.com..", "www.google.com", }, { "www.google.com........", "www.google.com", }, { "", "", }, { ".", "", }, { "........", "", }, }; for (size_t i = 0; i < ABSL_ARRAYSIZE(tests); ++i) { EXPECT_EQ(std::string(tests[i].expected), QuicheHostnameUtils::NormalizeHostname(tests[i].input)); } if (GoogleUrlSupportsIdnaForTest()) { EXPECT_EQ("xn--54q.google.com", QuicheHostnameUtils::NormalizeHostname( "\xe5\x85\x89.google.com")); } else { EXPECT_EQ( "", QuicheHostnameUtils::NormalizeHostname("\xe5\x85\x89.google.com")); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/platform/api/quiche_hostname_utils.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/platform/api/quiche_hostname_utils_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
c3cd288c-cd28-4217-a6cd-3e198a8c404d
cpp
google/quiche
http_header_storage
quiche/common/http/http_header_storage.cc
quiche/common/http/http_header_storage_test.cc
#include "quiche/common/http/http_header_storage.h" #include <cstring> #include "quiche/common/platform/api/quiche_logging.h" namespace quiche { namespace { const size_t kDefaultStorageBlockSize = 2048; } HttpHeaderStorage::HttpHeaderStorage() : arena_(kDefaultStorageBlockSize) {} absl::string_view HttpHeaderStorage::Write(const absl::string_view s) { return absl::string_view(arena_.Memdup(s.data(), s.size()), s.size()); } void HttpHeaderStorage::Rewind(const absl::string_view s) { arena_.Free(const_cast<char*>(s.data()), s.size()); } absl::string_view HttpHeaderStorage::WriteFragments( const Fragments& fragments, absl::string_view separator) { if (fragments.empty()) { return absl::string_view(); } size_t total_size = separator.size() * (fragments.size() - 1); for (const absl::string_view& fragment : fragments) { total_size += fragment.size(); } char* dst = arena_.Alloc(total_size); size_t written = Join(dst, fragments, separator); QUICHE_DCHECK_EQ(written, total_size); return absl::string_view(dst, total_size); } size_t Join(char* dst, const Fragments& fragments, absl::string_view separator) { if (fragments.empty()) { return 0; } auto* original_dst = dst; auto it = fragments.begin(); memcpy(dst, it->data(), it->size()); dst += it->size(); for (++it; it != fragments.end(); ++it) { memcpy(dst, separator.data(), separator.size()); dst += separator.size(); memcpy(dst, it->data(), it->size()); dst += it->size(); } return dst - original_dst; } }
#include "quiche/common/http/http_header_storage.h" #include "quiche/common/platform/api/quiche_test.h" namespace quiche { namespace test { TEST(JoinTest, JoinEmpty) { Fragments empty; absl::string_view separator = ", "; char buf[10] = ""; size_t written = Join(buf, empty, separator); EXPECT_EQ(0u, written); } TEST(JoinTest, JoinOne) { Fragments v = {"one"}; absl::string_view separator = ", "; char buf[15]; size_t written = Join(buf, v, separator); EXPECT_EQ(3u, written); EXPECT_EQ("one", absl::string_view(buf, written)); } TEST(JoinTest, JoinMultiple) { Fragments v = {"one", "two", "three"}; absl::string_view separator = ", "; char buf[15]; size_t written = Join(buf, v, separator); EXPECT_EQ(15u, written); EXPECT_EQ("one, two, three", absl::string_view(buf, written)); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/http/http_header_storage.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/http/http_header_storage_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
ab8e77a8-8e05-43ff-bb57-1109a479b6e3
cpp
google/quiche
http_header_block
quiche/common/http/http_header_block.cc
quiche/common/http/http_header_block_test.cc
#include "quiche/common/http/http_header_block.h" #include <string.h> #include <algorithm> #include <ios> #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quiche { namespace { const size_t kInitialMapBuckets = 11; const char kCookieKey[] = "cookie"; const char kNullSeparator = 0; absl::string_view SeparatorForKey(absl::string_view key) { if (key == kCookieKey) { static absl::string_view cookie_separator = "; "; return cookie_separator; } else { return absl::string_view(&kNullSeparator, 1); } } } HttpHeaderBlock::HeaderValue::HeaderValue(HttpHeaderStorage* storage, absl::string_view key, absl::string_view initial_value) : storage_(storage), fragments_({initial_value}), pair_({key, {}}), size_(initial_value.size()), separator_size_(SeparatorForKey(key).size()) {} HttpHeaderBlock::HeaderValue::HeaderValue(HeaderValue&& other) : storage_(other.storage_), fragments_(std::move(other.fragments_)), pair_(std::move(other.pair_)), size_(other.size_), separator_size_(other.separator_size_) {} HttpHeaderBlock::HeaderValue& HttpHeaderBlock::HeaderValue::operator=( HeaderValue&& other) { storage_ = other.storage_; fragments_ = std::move(other.fragments_); pair_ = std::move(other.pair_); size_ = other.size_; separator_size_ = other.separator_size_; return *this; } void HttpHeaderBlock::HeaderValue::set_storage(HttpHeaderStorage* storage) { storage_ = storage; } HttpHeaderBlock::HeaderValue::~HeaderValue() = default; absl::string_view HttpHeaderBlock::HeaderValue::ConsolidatedValue() const { if (fragments_.empty()) { return absl::string_view(); } if (fragments_.size() > 1) { fragments_ = { storage_->WriteFragments(fragments_, SeparatorForKey(pair_.first))}; } return fragments_[0]; } void HttpHeaderBlock::HeaderValue::Append(absl::string_view fragment) { size_ += (fragment.size() + separator_size_); fragments_.push_back(fragment); } const std::pair<absl::string_view, absl::string_view>& HttpHeaderBlock::HeaderValue::as_pair() const { pair_.second = ConsolidatedValue(); return pair_; } HttpHeaderBlock::iterator::iterator(MapType::const_iterator it) : it_(it) {} HttpHeaderBlock::iterator::iterator(const iterator& other) = default; HttpHeaderBlock::iterator::~iterator() = default; HttpHeaderBlock::ValueProxy::ValueProxy( HttpHeaderBlock* block, HttpHeaderBlock::MapType::iterator lookup_result, const absl::string_view key, size_t* spdy_header_block_value_size) : block_(block), lookup_result_(lookup_result), key_(key), spdy_header_block_value_size_(spdy_header_block_value_size), valid_(true) {} HttpHeaderBlock::ValueProxy::ValueProxy(ValueProxy&& other) : block_(other.block_), lookup_result_(other.lookup_result_), key_(other.key_), spdy_header_block_value_size_(other.spdy_header_block_value_size_), valid_(true) { other.valid_ = false; } HttpHeaderBlock::ValueProxy& HttpHeaderBlock::ValueProxy::operator=( HttpHeaderBlock::ValueProxy&& other) { block_ = other.block_; lookup_result_ = other.lookup_result_; key_ = other.key_; valid_ = true; other.valid_ = false; spdy_header_block_value_size_ = other.spdy_header_block_value_size_; return *this; } HttpHeaderBlock::ValueProxy::~ValueProxy() { if (valid_ && lookup_result_ == block_->map_.end()) { block_->storage_.Rewind(key_); } } HttpHeaderBlock::ValueProxy& HttpHeaderBlock::ValueProxy::operator=( absl::string_view value) { *spdy_header_block_value_size_ += value.size(); HttpHeaderStorage* storage = &block_->storage_; if (lookup_result_ == block_->map_.end()) { QUICHE_DVLOG(1) << "Inserting: (" << key_ << ", " << value << ")"; lookup_result_ = block_->map_ .emplace(std::make_pair( key_, HeaderValue(storage, key_, storage->Write(value)))) .first; } else { QUICHE_DVLOG(1) << "Updating key: " << key_ << " with value: " << value; *spdy_header_block_value_size_ -= lookup_result_->second.SizeEstimate(); lookup_result_->second = HeaderValue(storage, key_, storage->Write(value)); } return *this; } bool HttpHeaderBlock::ValueProxy::operator==(absl::string_view value) const { if (lookup_result_ == block_->map_.end()) { return false; } else { return value == lookup_result_->second.value(); } } std::string HttpHeaderBlock::ValueProxy::as_string() const { if (lookup_result_ == block_->map_.end()) { return ""; } else { return std::string(lookup_result_->second.value()); } } HttpHeaderBlock::HttpHeaderBlock() : map_(kInitialMapBuckets) {} HttpHeaderBlock::HttpHeaderBlock(HttpHeaderBlock&& other) : map_(kInitialMapBuckets) { map_.swap(other.map_); storage_ = std::move(other.storage_); for (auto& p : map_) { p.second.set_storage(&storage_); } key_size_ = other.key_size_; value_size_ = other.value_size_; } HttpHeaderBlock::~HttpHeaderBlock() = default; HttpHeaderBlock& HttpHeaderBlock::operator=(HttpHeaderBlock&& other) { map_.swap(other.map_); storage_ = std::move(other.storage_); for (auto& p : map_) { p.second.set_storage(&storage_); } key_size_ = other.key_size_; value_size_ = other.value_size_; return *this; } HttpHeaderBlock HttpHeaderBlock::Clone() const { HttpHeaderBlock copy; for (const auto& p : *this) { copy.AppendHeader(p.first, p.second); } return copy; } bool HttpHeaderBlock::operator==(const HttpHeaderBlock& other) const { return size() == other.size() && std::equal(begin(), end(), other.begin()); } bool HttpHeaderBlock::operator!=(const HttpHeaderBlock& other) const { return !(operator==(other)); } std::string HttpHeaderBlock::DebugString() const { if (empty()) { return "{}"; } std::string output = "\n{\n"; for (auto it = begin(); it != end(); ++it) { absl::StrAppend(&output, " ", it->first, " ", it->second, "\n"); } absl::StrAppend(&output, "}\n"); return output; } void HttpHeaderBlock::erase(absl::string_view key) { auto iter = map_.find(key); if (iter != map_.end()) { QUICHE_DVLOG(1) << "Erasing header with name: " << key; key_size_ -= key.size(); value_size_ -= iter->second.SizeEstimate(); map_.erase(iter); } } void HttpHeaderBlock::clear() { key_size_ = 0; value_size_ = 0; map_.clear(); storage_.Clear(); } HttpHeaderBlock::InsertResult HttpHeaderBlock::insert( const HttpHeaderBlock::value_type& value) { value_size_ += value.second.size(); auto iter = map_.find(value.first); if (iter == map_.end()) { QUICHE_DVLOG(1) << "Inserting: (" << value.first << ", " << value.second << ")"; AppendHeader(value.first, value.second); return InsertResult::kInserted; } else { QUICHE_DVLOG(1) << "Updating key: " << iter->first << " with value: " << value.second; value_size_ -= iter->second.SizeEstimate(); iter->second = HeaderValue(&storage_, iter->first, storage_.Write(value.second)); return InsertResult::kReplaced; } } HttpHeaderBlock::ValueProxy HttpHeaderBlock::operator[]( const absl::string_view key) { QUICHE_DVLOG(2) << "Operator[] saw key: " << key; absl::string_view out_key; auto iter = map_.find(key); if (iter == map_.end()) { out_key = WriteKey(key); QUICHE_DVLOG(2) << "Key written as: " << std::hex << static_cast<const void*>(key.data()) << ", " << std::dec << key.size(); } else { out_key = iter->first; } return ValueProxy(this, iter, out_key, &value_size_); } void HttpHeaderBlock::AppendValueOrAddHeader(const absl::string_view key, const absl::string_view value) { value_size_ += value.size(); auto iter = map_.find(key); if (iter == map_.end()) { QUICHE_DVLOG(1) << "Inserting: (" << key << ", " << value << ")"; AppendHeader(key, value); return; } QUICHE_DVLOG(1) << "Updating key: " << iter->first << "; appending value: " << value; value_size_ += SeparatorForKey(key).size(); iter->second.Append(storage_.Write(value)); } void HttpHeaderBlock::AppendHeader(const absl::string_view key, const absl::string_view value) { auto backed_key = WriteKey(key); map_.emplace(std::make_pair( backed_key, HeaderValue(&storage_, backed_key, storage_.Write(value)))); } absl::string_view HttpHeaderBlock::WriteKey(const absl::string_view key) { key_size_ += key.size(); return storage_.Write(key); } size_t HttpHeaderBlock::bytes_allocated() const { return storage_.bytes_allocated(); } }
#include "quiche/common/http/http_header_block.h" #include <memory> #include <string> #include <utility> #include "quiche/http2/test_tools/spdy_test_utils.h" #include "quiche/common/platform/api/quiche_test.h" using ::testing::ElementsAre; namespace quiche { namespace test { class ValueProxyPeer { public: static absl::string_view key(HttpHeaderBlock::ValueProxy* p) { return p->key_; } }; std::pair<absl::string_view, absl::string_view> Pair(absl::string_view k, absl::string_view v) { return std::make_pair(k, v); } TEST(HttpHeaderBlockTest, EmptyBlock) { HttpHeaderBlock block; EXPECT_TRUE(block.empty()); EXPECT_EQ(0u, block.size()); EXPECT_EQ(block.end(), block.find("foo")); EXPECT_FALSE(block.contains("foo")); EXPECT_TRUE(block.end() == block.begin()); block.erase("bar"); } TEST(HttpHeaderBlockTest, KeyMemoryReclaimedOnLookup) { HttpHeaderBlock block; absl::string_view copied_key1; { auto proxy1 = block["some key name"]; copied_key1 = ValueProxyPeer::key(&proxy1); } absl::string_view copied_key2; { auto proxy2 = block["some other key name"]; copied_key2 = ValueProxyPeer::key(&proxy2); } EXPECT_EQ(copied_key1.data(), copied_key2.data()); { auto proxy1 = block["some key name"]; block["some other key name"] = "some value"; } block["key"] = "value"; EXPECT_EQ("value", block["key"]); EXPECT_EQ("some value", block["some other key name"]); EXPECT_TRUE(block.find("some key name") == block.end()); } TEST(HttpHeaderBlockTest, AddHeaders) { HttpHeaderBlock block; block["foo"] = std::string(300, 'x'); block["bar"] = "baz"; block["qux"] = "qux1"; block["qux"] = "qux2"; block.insert(std::make_pair("key", "value")); EXPECT_EQ(Pair("foo", std::string(300, 'x')), *block.find("foo")); EXPECT_EQ("baz", block["bar"]); std::string qux("qux"); EXPECT_EQ("qux2", block[qux]); ASSERT_NE(block.end(), block.find("key")); ASSERT_TRUE(block.contains("key")); EXPECT_EQ(Pair("key", "value"), *block.find("key")); block.erase("key"); EXPECT_EQ(block.end(), block.find("key")); } TEST(HttpHeaderBlockTest, CopyBlocks) { HttpHeaderBlock block1; block1["foo"] = std::string(300, 'x'); block1["bar"] = "baz"; block1.insert(std::make_pair("qux", "qux1")); HttpHeaderBlock block2 = block1.Clone(); HttpHeaderBlock block3(block1.Clone()); EXPECT_EQ(block1, block2); EXPECT_EQ(block1, block3); } TEST(HttpHeaderBlockTest, Equality) { HttpHeaderBlock block1; block1["foo"] = "bar"; HttpHeaderBlock block2; block2["foo"] = "bar"; HttpHeaderBlock block3; block3["baz"] = "qux"; EXPECT_EQ(block1, block2); EXPECT_NE(block1, block3); block2["baz"] = "qux"; EXPECT_NE(block1, block2); } HttpHeaderBlock ReturnTestHeaderBlock() { HttpHeaderBlock block; block["foo"] = "bar"; block.insert(std::make_pair("foo2", "baz")); return block; } TEST(HttpHeaderBlockTest, MovedFromIsValid) { HttpHeaderBlock block1; block1["foo"] = "bar"; HttpHeaderBlock block2(std::move(block1)); EXPECT_THAT(block2, ElementsAre(Pair("foo", "bar"))); block1["baz"] = "qux"; HttpHeaderBlock block3(std::move(block1)); block1["foo"] = "bar"; HttpHeaderBlock block4(std::move(block1)); block1.clear(); EXPECT_TRUE(block1.empty()); block1["foo"] = "bar"; EXPECT_THAT(block1, ElementsAre(Pair("foo", "bar"))); HttpHeaderBlock block5 = ReturnTestHeaderBlock(); block5.AppendValueOrAddHeader("foo", "bar2"); EXPECT_THAT(block5, ElementsAre(Pair("foo", std::string("bar\0bar2", 8)), Pair("foo2", "baz"))); } TEST(HttpHeaderBlockTest, AppendHeaders) { HttpHeaderBlock block; block["foo"] = "foo"; block.AppendValueOrAddHeader("foo", "bar"); EXPECT_EQ(Pair("foo", std::string("foo\0bar", 7)), *block.find("foo")); block.insert(std::make_pair("foo", "baz")); EXPECT_EQ("baz", block["foo"]); EXPECT_EQ(Pair("foo", "baz"), *block.find("foo")); block["cookie"] = "key1=value1"; block.AppendValueOrAddHeader("h1", "h1v1"); block.insert(std::make_pair("h2", "h2v1")); block.AppendValueOrAddHeader("h3", "h3v2"); block.AppendValueOrAddHeader("h2", "h2v2"); block.AppendValueOrAddHeader("h1", "h1v2"); block.AppendValueOrAddHeader("cookie", "key2=value2"); block.AppendValueOrAddHeader("cookie", "key3=value3"); block.AppendValueOrAddHeader("h1", "h1v3"); block.AppendValueOrAddHeader("h2", "h2v3"); block.AppendValueOrAddHeader("h3", "h3v3"); block.AppendValueOrAddHeader("h4", "singleton"); block.AppendValueOrAddHeader("set-cookie", "yummy"); block.AppendValueOrAddHeader("set-cookie", "scrumptious"); EXPECT_EQ("key1=value1; key2=value2; key3=value3", block["cookie"]); EXPECT_EQ("baz", block["foo"]); EXPECT_EQ(std::string("h1v1\0h1v2\0h1v3", 14), block["h1"]); EXPECT_EQ(std::string("h2v1\0h2v2\0h2v3", 14), block["h2"]); EXPECT_EQ(std::string("h3v2\0h3v3", 9), block["h3"]); EXPECT_EQ("singleton", block["h4"]); EXPECT_EQ(std::string("yummy\0scrumptious", 17), block["set-cookie"]); } TEST(HttpHeaderBlockTest, CompareValueToStringPiece) { HttpHeaderBlock block; block["foo"] = "foo"; block.AppendValueOrAddHeader("foo", "bar"); const auto& val = block["foo"]; const char expected[] = "foo\0bar"; EXPECT_TRUE(absl::string_view(expected, 7) == val); EXPECT_TRUE(val == absl::string_view(expected, 7)); EXPECT_FALSE(absl::string_view(expected, 3) == val); EXPECT_FALSE(val == absl::string_view(expected, 3)); const char not_expected[] = "foo\0barextra"; EXPECT_FALSE(absl::string_view(not_expected, 12) == val); EXPECT_FALSE(val == absl::string_view(not_expected, 12)); const auto& val2 = block["foo2"]; EXPECT_FALSE(absl::string_view(expected, 7) == val2); EXPECT_FALSE(val2 == absl::string_view(expected, 7)); EXPECT_FALSE(absl::string_view("") == val2); EXPECT_FALSE(val2 == absl::string_view("")); } TEST(HttpHeaderBlockTest, UpperCaseNames) { HttpHeaderBlock block; block["Foo"] = "foo"; block.AppendValueOrAddHeader("Foo", "bar"); EXPECT_NE(block.end(), block.find("foo")); EXPECT_EQ(Pair("Foo", std::string("foo\0bar", 7)), *block.find("Foo")); block.AppendValueOrAddHeader("foo", "baz"); EXPECT_THAT(block, ElementsAre(Pair("Foo", std::string("foo\0bar\0baz", 11)))); } namespace { size_t HttpHeaderBlockSize(const HttpHeaderBlock& block) { size_t size = 0; for (const auto& pair : block) { size += pair.first.size() + pair.second.size(); } return size; } } TEST(HttpHeaderBlockTest, TotalBytesUsed) { HttpHeaderBlock block; const size_t value_size = 300; block["foo"] = std::string(value_size, 'x'); EXPECT_EQ(block.TotalBytesUsed(), HttpHeaderBlockSize(block)); block.insert(std::make_pair("key", std::string(value_size, 'x'))); EXPECT_EQ(block.TotalBytesUsed(), HttpHeaderBlockSize(block)); block.AppendValueOrAddHeader("abc", std::string(value_size, 'x')); EXPECT_EQ(block.TotalBytesUsed(), HttpHeaderBlockSize(block)); block["foo"] = std::string(value_size, 'x'); EXPECT_EQ(block.TotalBytesUsed(), HttpHeaderBlockSize(block)); block.insert(std::make_pair("key", std::string(value_size, 'x'))); EXPECT_EQ(block.TotalBytesUsed(), HttpHeaderBlockSize(block)); block.AppendValueOrAddHeader("abc", std::string(value_size, 'x')); EXPECT_EQ(block.TotalBytesUsed(), HttpHeaderBlockSize(block)); size_t block_size = block.TotalBytesUsed(); HttpHeaderBlock block_copy = std::move(block); EXPECT_EQ(block_size, block_copy.TotalBytesUsed()); block_copy.erase("foo"); EXPECT_EQ(block_copy.TotalBytesUsed(), HttpHeaderBlockSize(block_copy)); block_copy.erase("key"); EXPECT_EQ(block_copy.TotalBytesUsed(), HttpHeaderBlockSize(block_copy)); block_copy.erase("abc"); EXPECT_EQ(block_copy.TotalBytesUsed(), HttpHeaderBlockSize(block_copy)); } TEST(HttpHeaderBlockTest, OrderPreserved) { HttpHeaderBlock block; block[":method"] = "GET"; block["foo"] = "bar"; block[":path"] = "/"; EXPECT_THAT(block, ElementsAre(Pair(":method", "GET"), Pair("foo", "bar"), Pair(":path", "/"))); } TEST(HttpHeaderBlockTest, InsertReturnValue) { HttpHeaderBlock block; EXPECT_EQ(HttpHeaderBlock::InsertResult::kInserted, block.insert({"foo", "bar"})); EXPECT_EQ(HttpHeaderBlock::InsertResult::kReplaced, block.insert({"foo", "baz"})); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/http/http_header_block.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/common/http/http_header_block_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
88e33272-0175-44d5-8bd6-5c049c7994d0
cpp
google/quiche
binary_http_message
quiche/binary_http/binary_http_message.cc
quiche/binary_http/binary_http_message_test.cc
#include "quiche/binary_http/binary_http_message.h" #include <algorithm> #include <cstdint> #include <functional> #include <iterator> #include <memory> #include <ostream> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/ascii.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "quiche/common/quiche_callbacks.h" #include "quiche/common/quiche_data_reader.h" #include "quiche/common/quiche_data_writer.h" namespace quiche { namespace { constexpr uint8_t kKnownLengthRequestFraming = 0; constexpr uint8_t kKnownLengthResponseFraming = 1; bool ReadStringValue(quiche::QuicheDataReader& reader, std::string& data) { absl::string_view data_view; if (!reader.ReadStringPieceVarInt62(&data_view)) { return false; } data = std::string(data_view); return true; } bool IsValidPadding(absl::string_view data) { return std::all_of(data.begin(), data.end(), [](char c) { return c == '\0'; }); } absl::StatusOr<BinaryHttpRequest::ControlData> DecodeControlData( quiche::QuicheDataReader& reader) { BinaryHttpRequest::ControlData control_data; if (!ReadStringValue(reader, control_data.method)) { return absl::InvalidArgumentError("Failed to read method."); } if (!ReadStringValue(reader, control_data.scheme)) { return absl::InvalidArgumentError("Failed to read scheme."); } if (!ReadStringValue(reader, control_data.authority)) { return absl::InvalidArgumentError("Failed to read authority."); } if (!ReadStringValue(reader, control_data.path)) { return absl::InvalidArgumentError("Failed to read path."); } return control_data; } absl::Status DecodeFields(quiche::QuicheDataReader& reader, quiche::UnretainedCallback<void( absl::string_view name, absl::string_view value)> callback) { absl::string_view fields; if (!reader.ReadStringPieceVarInt62(&fields)) { return absl::InvalidArgumentError("Failed to read fields."); } quiche::QuicheDataReader fields_reader(fields); while (!fields_reader.IsDoneReading()) { absl::string_view name; if (!fields_reader.ReadStringPieceVarInt62(&name)) { return absl::InvalidArgumentError("Failed to read field name."); } absl::string_view value; if (!fields_reader.ReadStringPieceVarInt62(&value)) { return absl::InvalidArgumentError("Failed to read field value."); } callback(name, value); } return absl::OkStatus(); } absl::Status DecodeFieldsAndBody(quiche::QuicheDataReader& reader, BinaryHttpMessage& message) { if (const absl::Status status = DecodeFields( reader, [&message](absl::string_view name, absl::string_view value) { message.AddHeaderField({std::string(name), std::string(value)}); }); !status.ok()) { return status; } if (reader.IsDoneReading()) { return absl::OkStatus(); } absl::string_view body; if (!reader.ReadStringPieceVarInt62(&body)) { return absl::InvalidArgumentError("Failed to read body."); } message.set_body(std::string(body)); return absl::OkStatus(); } absl::StatusOr<BinaryHttpRequest> DecodeKnownLengthRequest( quiche::QuicheDataReader& reader) { const auto control_data = DecodeControlData(reader); if (!control_data.ok()) { return control_data.status(); } BinaryHttpRequest request(std::move(*control_data)); if (const absl::Status status = DecodeFieldsAndBody(reader, request); !status.ok()) { return status; } if (!IsValidPadding(reader.PeekRemainingPayload())) { return absl::InvalidArgumentError("Non-zero padding."); } request.set_num_padding_bytes(reader.BytesRemaining()); return request; } absl::StatusOr<BinaryHttpResponse> DecodeKnownLengthResponse( quiche::QuicheDataReader& reader) { std::vector<std::pair<uint16_t, std::vector<BinaryHttpMessage::Field>>> informational_responses; uint64_t status_code; bool reading_response_control_data = true; while (reading_response_control_data) { if (!reader.ReadVarInt62(&status_code)) { return absl::InvalidArgumentError("Failed to read status code."); } if (status_code >= 100 && status_code <= 199) { std::vector<BinaryHttpMessage::Field> fields; if (const absl::Status status = DecodeFields( reader, [&fields](absl::string_view name, absl::string_view value) { fields.push_back({std::string(name), std::string(value)}); }); !status.ok()) { return status; } informational_responses.emplace_back(status_code, std::move(fields)); } else { reading_response_control_data = false; } } BinaryHttpResponse response(status_code); for (const auto& informational_response : informational_responses) { if (const absl::Status status = response.AddInformationalResponse( informational_response.first, std::move(informational_response.second)); !status.ok()) { return status; } } if (const absl::Status status = DecodeFieldsAndBody(reader, response); !status.ok()) { return status; } if (!IsValidPadding(reader.PeekRemainingPayload())) { return absl::InvalidArgumentError("Non-zero padding."); } response.set_num_padding_bytes(reader.BytesRemaining()); return response; } uint64_t StringPieceVarInt62Len(absl::string_view s) { return quiche::QuicheDataWriter::GetVarInt62Len(s.length()) + s.length(); } } void BinaryHttpMessage::Fields::AddField(BinaryHttpMessage::Field field) { fields_.push_back(std::move(field)); } absl::Status BinaryHttpMessage::Fields::Encode( quiche::QuicheDataWriter& writer) const { if (!writer.WriteVarInt62(EncodedFieldsSize())) { return absl::InvalidArgumentError("Failed to write encoded field size."); } for (const BinaryHttpMessage::Field& field : fields_) { if (!writer.WriteStringPieceVarInt62(field.name)) { return absl::InvalidArgumentError("Failed to write field name."); } if (!writer.WriteStringPieceVarInt62(field.value)) { return absl::InvalidArgumentError("Failed to write field value."); } } return absl::OkStatus(); } size_t BinaryHttpMessage::Fields::EncodedSize() const { const size_t size = EncodedFieldsSize(); return size + quiche::QuicheDataWriter::GetVarInt62Len(size); } size_t BinaryHttpMessage::Fields::EncodedFieldsSize() const { size_t size = 0; for (const BinaryHttpMessage::Field& field : fields_) { size += StringPieceVarInt62Len(field.name) + StringPieceVarInt62Len(field.value); } return size; } BinaryHttpMessage* BinaryHttpMessage::AddHeaderField( BinaryHttpMessage::Field field) { const std::string lower_name = absl::AsciiStrToLower(field.name); if (lower_name == "host") { has_host_ = true; } header_fields_.AddField({std::move(lower_name), std::move(field.value)}); return this; } absl::Status BinaryHttpMessage::EncodeKnownLengthFieldsAndBody( quiche::QuicheDataWriter& writer) const { if (const absl::Status status = header_fields_.Encode(writer); !status.ok()) { return status; } if (!writer.WriteStringPieceVarInt62(body_)) { return absl::InvalidArgumentError("Failed to encode body."); } return absl::OkStatus(); } size_t BinaryHttpMessage::EncodedKnownLengthFieldsAndBodySize() const { return header_fields_.EncodedSize() + StringPieceVarInt62Len(body_); } absl::Status BinaryHttpResponse::AddInformationalResponse( uint16_t status_code, std::vector<Field> header_fields) { if (status_code < 100) { return absl::InvalidArgumentError("status code < 100"); } if (status_code > 199) { return absl::InvalidArgumentError("status code > 199"); } InformationalResponse data(status_code); for (Field& header : header_fields) { data.AddField(header.name, std::move(header.value)); } informational_response_control_data_.push_back(std::move(data)); return absl::OkStatus(); } absl::StatusOr<std::string> BinaryHttpResponse::Serialize() const { return EncodeAsKnownLength(); } absl::StatusOr<std::string> BinaryHttpResponse::EncodeAsKnownLength() const { std::string data; data.resize(EncodedSize()); quiche::QuicheDataWriter writer(data.size(), data.data()); if (!writer.WriteUInt8(kKnownLengthResponseFraming)) { return absl::InvalidArgumentError("Failed to write framing indicator"); } for (const auto& informational : informational_response_control_data_) { if (const absl::Status status = informational.Encode(writer); !status.ok()) { return status; } } if (!writer.WriteVarInt62(status_code_)) { return absl::InvalidArgumentError("Failed to write status code"); } if (const absl::Status status = EncodeKnownLengthFieldsAndBody(writer); !status.ok()) { return status; } QUICHE_DCHECK_EQ(writer.remaining(), num_padding_bytes()); writer.WritePadding(); return data; } size_t BinaryHttpResponse::EncodedSize() const { size_t size = sizeof(kKnownLengthResponseFraming); for (const auto& informational : informational_response_control_data_) { size += informational.EncodedSize(); } return size + quiche::QuicheDataWriter::GetVarInt62Len(status_code_) + EncodedKnownLengthFieldsAndBodySize() + num_padding_bytes(); } void BinaryHttpResponse::InformationalResponse::AddField(absl::string_view name, std::string value) { fields_.AddField({absl::AsciiStrToLower(name), std::move(value)}); } absl::Status BinaryHttpResponse::InformationalResponse::Encode( quiche::QuicheDataWriter& writer) const { writer.WriteVarInt62(status_code_); return fields_.Encode(writer); } size_t BinaryHttpResponse::InformationalResponse::EncodedSize() const { return quiche::QuicheDataWriter::GetVarInt62Len(status_code_) + fields_.EncodedSize(); } absl::StatusOr<std::string> BinaryHttpRequest::Serialize() const { return EncodeAsKnownLength(); } absl::Status BinaryHttpRequest::EncodeControlData( quiche::QuicheDataWriter& writer) const { if (!writer.WriteStringPieceVarInt62(control_data_.method)) { return absl::InvalidArgumentError("Failed to encode method."); } if (!writer.WriteStringPieceVarInt62(control_data_.scheme)) { return absl::InvalidArgumentError("Failed to encode scheme."); } if (!has_host()) { if (!writer.WriteStringPieceVarInt62(control_data_.authority)) { return absl::InvalidArgumentError("Failed to encode authority."); } } else { if (!writer.WriteStringPieceVarInt62("")) { return absl::InvalidArgumentError("Failed to encode authority."); } } if (!writer.WriteStringPieceVarInt62(control_data_.path)) { return absl::InvalidArgumentError("Failed to encode path."); } return absl::OkStatus(); } size_t BinaryHttpRequest::EncodedControlDataSize() const { size_t size = StringPieceVarInt62Len(control_data_.method) + StringPieceVarInt62Len(control_data_.scheme) + StringPieceVarInt62Len(control_data_.path); if (!has_host()) { size += StringPieceVarInt62Len(control_data_.authority); } else { size += StringPieceVarInt62Len(""); } return size; } size_t BinaryHttpRequest::EncodedSize() const { return sizeof(kKnownLengthRequestFraming) + EncodedControlDataSize() + EncodedKnownLengthFieldsAndBodySize() + num_padding_bytes(); } absl::StatusOr<std::string> BinaryHttpRequest::EncodeAsKnownLength() const { std::string data; data.resize(EncodedSize()); quiche::QuicheDataWriter writer(data.size(), data.data()); if (!writer.WriteUInt8(kKnownLengthRequestFraming)) { return absl::InvalidArgumentError("Failed to encode framing indicator."); } if (const absl::Status status = EncodeControlData(writer); !status.ok()) { return status; } if (const absl::Status status = EncodeKnownLengthFieldsAndBody(writer); !status.ok()) { return status; } QUICHE_DCHECK_EQ(writer.remaining(), num_padding_bytes()); writer.WritePadding(); return data; } absl::StatusOr<BinaryHttpRequest> BinaryHttpRequest::Create( absl::string_view data) { quiche::QuicheDataReader reader(data); uint8_t framing; if (!reader.ReadUInt8(&framing)) { return absl::InvalidArgumentError("Missing framing indicator."); } if (framing == kKnownLengthRequestFraming) { return DecodeKnownLengthRequest(reader); } return absl::UnimplementedError( absl::StrCat("Unsupported framing type ", framing)); } absl::StatusOr<BinaryHttpResponse> BinaryHttpResponse::Create( absl::string_view data) { quiche::QuicheDataReader reader(data); uint8_t framing; if (!reader.ReadUInt8(&framing)) { return absl::InvalidArgumentError("Missing framing indicator."); } if (framing == kKnownLengthResponseFraming) { return DecodeKnownLengthResponse(reader); } return absl::UnimplementedError( absl::StrCat("Unsupported framing type ", framing)); } std::string BinaryHttpMessage::DebugString() const { std::vector<std::string> headers; for (const auto& field : GetHeaderFields()) { headers.emplace_back(field.DebugString()); } return absl::StrCat("BinaryHttpMessage{Headers{", absl::StrJoin(headers, ";"), "}Body{", body(), "}}"); } std::string BinaryHttpMessage::Field::DebugString() const { return absl::StrCat("Field{", name, "=", value, "}"); } std::string BinaryHttpResponse::InformationalResponse::DebugString() const { std::vector<std::string> fs; for (const auto& field : fields()) { fs.emplace_back(field.DebugString()); } return absl::StrCat("InformationalResponse{", absl::StrJoin(fs, ";"), "}"); } std::string BinaryHttpResponse::DebugString() const { std::vector<std::string> irs; for (const auto& ir : informational_responses()) { irs.emplace_back(ir.DebugString()); } return absl::StrCat("BinaryHttpResponse(", status_code_, "){", BinaryHttpMessage::DebugString(), absl::StrJoin(irs, ";"), "}"); } std::string BinaryHttpRequest::DebugString() const { return absl::StrCat("BinaryHttpRequest{", BinaryHttpMessage::DebugString(), "}"); } void PrintTo(const BinaryHttpRequest& msg, std::ostream* os) { *os << msg.DebugString(); } void PrintTo(const BinaryHttpResponse& msg, std::ostream* os) { *os << msg.DebugString(); } void PrintTo(const BinaryHttpMessage::Field& msg, std::ostream* os) { *os << msg.DebugString(); } }
#include "quiche/binary_http/binary_http_message.h" #include <cstdint> #include <memory> #include <sstream> #include <string> #include <vector> #include "absl/container/flat_hash_map.h" #include "quiche/common/platform/api/quiche_test.h" using ::testing::ContainerEq; using ::testing::FieldsAre; using ::testing::StrEq; namespace quiche { namespace { std::string WordToBytes(uint32_t word) { return std::string({static_cast<char>(word >> 24), static_cast<char>(word >> 16), static_cast<char>(word >> 8), static_cast<char>(word)}); } template <class T> void TestPrintTo(const T& resp) { std::ostringstream os; PrintTo(resp, &os); EXPECT_EQ(os.str(), resp.DebugString()); } } TEST(BinaryHttpRequest, EncodeGetNoBody) { BinaryHttpRequest request({"GET", "https", "www.example.com", "/hello.txt"}); request .AddHeaderField({"User-Agent", "curl/7.16.3 libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3"}) ->AddHeaderField({"Host", "www.example.com"}) ->AddHeaderField({"Accept-Language", "en, mi"}); const uint32_t expected_words[] = { 0x00034745, 0x54056874, 0x74707300, 0x0a2f6865, 0x6c6c6f2e, 0x74787440, 0x6c0a7573, 0x65722d61, 0x67656e74, 0x34637572, 0x6c2f372e, 0x31362e33, 0x206c6962, 0x6375726c, 0x2f372e31, 0x362e3320, 0x4f70656e, 0x53534c2f, 0x302e392e, 0x376c207a, 0x6c69622f, 0x312e322e, 0x3304686f, 0x73740f77, 0x77772e65, 0x78616d70, 0x6c652e63, 0x6f6d0f61, 0x63636570, 0x742d6c61, 0x6e677561, 0x67650665, 0x6e2c206d, 0x69000000}; std::string expected; for (const auto& word : expected_words) { expected += WordToBytes(word); } expected.resize(expected.size() - 2); const auto result = request.Serialize(); ASSERT_TRUE(result.ok()); ASSERT_EQ(*result, expected); EXPECT_THAT( request.DebugString(), StrEq("BinaryHttpRequest{BinaryHttpMessage{Headers{Field{user-agent=curl/" "7.16.3 " "libcurl/7.16.3 OpenSSL/0.9.7l " "zlib/1.2.3};Field{host=www.example.com};Field{accept-language=en, " "mi}}Body{}}}")); TestPrintTo(request); } TEST(BinaryHttpRequest, DecodeGetNoBody) { const uint32_t words[] = { 0x00034745, 0x54056874, 0x74707300, 0x0a2f6865, 0x6c6c6f2e, 0x74787440, 0x6c0a7573, 0x65722d61, 0x67656e74, 0x34637572, 0x6c2f372e, 0x31362e33, 0x206c6962, 0x6375726c, 0x2f372e31, 0x362e3320, 0x4f70656e, 0x53534c2f, 0x302e392e, 0x376c207a, 0x6c69622f, 0x312e322e, 0x3304686f, 0x73740f77, 0x77772e65, 0x78616d70, 0x6c652e63, 0x6f6d0f61, 0x63636570, 0x742d6c61, 0x6e677561, 0x67650665, 0x6e2c206d, 0x69000000}; std::string data; for (const auto& word : words) { data += WordToBytes(word); } data.resize(data.size() - 3); const auto request_so = BinaryHttpRequest::Create(data); ASSERT_TRUE(request_so.ok()); const BinaryHttpRequest request = *request_so; ASSERT_THAT(request.control_data(), FieldsAre("GET", "https", "", "/hello.txt")); std::vector<BinaryHttpMessage::Field> expected_fields = { {"user-agent", "curl/7.16.3 libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3"}, {"host", "www.example.com"}, {"accept-language", "en, mi"}}; for (const auto& field : expected_fields) { TestPrintTo(field); } ASSERT_THAT(request.GetHeaderFields(), ContainerEq(expected_fields)); ASSERT_EQ(request.body(), ""); EXPECT_THAT( request.DebugString(), StrEq("BinaryHttpRequest{BinaryHttpMessage{Headers{Field{user-agent=curl/" "7.16.3 " "libcurl/7.16.3 OpenSSL/0.9.7l " "zlib/1.2.3};Field{host=www.example.com};Field{accept-language=en, " "mi}}Body{}}}")); TestPrintTo(request); } TEST(BinaryHttpRequest, EncodeGetWithAuthority) { BinaryHttpRequest request({"GET", "https", "www.example.com", "/hello.txt"}); request .AddHeaderField({"User-Agent", "curl/7.16.3 libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3"}) ->AddHeaderField({"Accept-Language", "en, mi"}); const uint32_t expected_words[] = { 0x00034745, 0x54056874, 0x7470730f, 0x7777772e, 0x6578616d, 0x706c652e, 0x636f6d0a, 0x2f68656c, 0x6c6f2e74, 0x78744057, 0x0a757365, 0x722d6167, 0x656e7434, 0x6375726c, 0x2f372e31, 0x362e3320, 0x6c696263, 0x75726c2f, 0x372e3136, 0x2e33204f, 0x70656e53, 0x534c2f30, 0x2e392e37, 0x6c207a6c, 0x69622f31, 0x2e322e33, 0x0f616363, 0x6570742d, 0x6c616e67, 0x75616765, 0x06656e2c, 0x206d6900}; std::string expected; for (const auto& word : expected_words) { expected += WordToBytes(word); } const auto result = request.Serialize(); ASSERT_TRUE(result.ok()); ASSERT_EQ(*result, expected); EXPECT_THAT( request.DebugString(), StrEq("BinaryHttpRequest{BinaryHttpMessage{Headers{Field{user-agent=curl/" "7.16.3 libcurl/7.16.3 OpenSSL/0.9.7l " "zlib/1.2.3};Field{accept-language=en, mi}}Body{}}}")); } TEST(BinaryHttpRequest, DecodeGetWithAuthority) { const uint32_t words[] = { 0x00034745, 0x54056874, 0x7470730f, 0x7777772e, 0x6578616d, 0x706c652e, 0x636f6d0a, 0x2f68656c, 0x6c6f2e74, 0x78744057, 0x0a757365, 0x722d6167, 0x656e7434, 0x6375726c, 0x2f372e31, 0x362e3320, 0x6c696263, 0x75726c2f, 0x372e3136, 0x2e33204f, 0x70656e53, 0x534c2f30, 0x2e392e37, 0x6c207a6c, 0x69622f31, 0x2e322e33, 0x0f616363, 0x6570742d, 0x6c616e67, 0x75616765, 0x06656e2c, 0x206d6900, 0x00}; std::string data; for (const auto& word : words) { data += WordToBytes(word); } const auto request_so = BinaryHttpRequest::Create(data); ASSERT_TRUE(request_so.ok()); const BinaryHttpRequest request = *request_so; ASSERT_THAT(request.control_data(), FieldsAre("GET", "https", "www.example.com", "/hello.txt")); std::vector<BinaryHttpMessage::Field> expected_fields = { {"user-agent", "curl/7.16.3 libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3"}, {"accept-language", "en, mi"}}; ASSERT_THAT(request.GetHeaderFields(), ContainerEq(expected_fields)); ASSERT_EQ(request.body(), ""); EXPECT_THAT( request.DebugString(), StrEq("BinaryHttpRequest{BinaryHttpMessage{Headers{Field{user-agent=curl/" "7.16.3 libcurl/7.16.3 OpenSSL/0.9.7l " "zlib/1.2.3};Field{accept-language=en, mi}}Body{}}}")); } TEST(BinaryHttpRequest, EncodePostBody) { BinaryHttpRequest request({"POST", "https", "www.example.com", "/hello.txt"}); request.AddHeaderField({"User-Agent", "not/telling"}) ->AddHeaderField({"Host", "www.example.com"}) ->AddHeaderField({"Accept-Language", "en"}) ->set_body({"Some body that I used to post.\r\n"}); const uint32_t expected_words[] = { 0x0004504f, 0x53540568, 0x74747073, 0x000a2f68, 0x656c6c6f, 0x2e747874, 0x3f0a7573, 0x65722d61, 0x67656e74, 0x0b6e6f74, 0x2f74656c, 0x6c696e67, 0x04686f73, 0x740f7777, 0x772e6578, 0x616d706c, 0x652e636f, 0x6d0f6163, 0x63657074, 0x2d6c616e, 0x67756167, 0x6502656e, 0x20536f6d, 0x6520626f, 0x64792074, 0x68617420, 0x49207573, 0x65642074, 0x6f20706f, 0x73742e0d, 0x0a000000}; std::string expected; for (const auto& word : expected_words) { expected += WordToBytes(word); } expected.resize(expected.size() - 3); const auto result = request.Serialize(); ASSERT_TRUE(result.ok()); ASSERT_EQ(*result, expected); EXPECT_THAT( request.DebugString(), StrEq("BinaryHttpRequest{BinaryHttpMessage{Headers{Field{user-agent=not/" "telling};Field{host=www.example.com};Field{accept-language=en}}" "Body{Some " "body that I used to post.\r\n}}}")); } TEST(BinaryHttpRequest, DecodePostBody) { const uint32_t words[] = { 0x0004504f, 0x53540568, 0x74747073, 0x000a2f68, 0x656c6c6f, 0x2e747874, 0x3f0a7573, 0x65722d61, 0x67656e74, 0x0b6e6f74, 0x2f74656c, 0x6c696e67, 0x04686f73, 0x740f7777, 0x772e6578, 0x616d706c, 0x652e636f, 0x6d0f6163, 0x63657074, 0x2d6c616e, 0x67756167, 0x6502656e, 0x20536f6d, 0x6520626f, 0x64792074, 0x68617420, 0x49207573, 0x65642074, 0x6f20706f, 0x73742e0d, 0x0a000000}; std::string data; for (const auto& word : words) { data += WordToBytes(word); } const auto request_so = BinaryHttpRequest::Create(data); ASSERT_TRUE(request_so.ok()); BinaryHttpRequest request = *request_so; ASSERT_THAT(request.control_data(), FieldsAre("POST", "https", "", "/hello.txt")); std::vector<BinaryHttpMessage::Field> expected_fields = { {"user-agent", "not/telling"}, {"host", "www.example.com"}, {"accept-language", "en"}}; ASSERT_THAT(request.GetHeaderFields(), ContainerEq(expected_fields)); ASSERT_EQ(request.body(), "Some body that I used to post.\r\n"); EXPECT_THAT( request.DebugString(), StrEq("BinaryHttpRequest{BinaryHttpMessage{Headers{Field{user-agent=not/" "telling};Field{host=www.example.com};Field{accept-language=en}}" "Body{Some " "body that I used to post.\r\n}}}")); } TEST(BinaryHttpRequest, Equality) { BinaryHttpRequest request({"POST", "https", "www.example.com", "/hello.txt"}); request.AddHeaderField({"User-Agent", "not/telling"}) ->set_body({"hello, world!\r\n"}); BinaryHttpRequest same({"POST", "https", "www.example.com", "/hello.txt"}); same.AddHeaderField({"User-Agent", "not/telling"}) ->set_body({"hello, world!\r\n"}); EXPECT_EQ(request, same); } TEST(BinaryHttpRequest, Inequality) { BinaryHttpRequest request({"POST", "https", "www.example.com", "/hello.txt"}); request.AddHeaderField({"User-Agent", "not/telling"}) ->set_body({"hello, world!\r\n"}); BinaryHttpRequest different_control( {"PUT", "https", "www.example.com", "/hello.txt"}); different_control.AddHeaderField({"User-Agent", "not/telling"}) ->set_body({"hello, world!\r\n"}); EXPECT_NE(request, different_control); BinaryHttpRequest different_header( {"PUT", "https", "www.example.com", "/hello.txt"}); different_header.AddHeaderField({"User-Agent", "told/you"}) ->set_body({"hello, world!\r\n"}); EXPECT_NE(request, different_header); BinaryHttpRequest no_header( {"PUT", "https", "www.example.com", "/hello.txt"}); no_header.set_body({"hello, world!\r\n"}); EXPECT_NE(request, no_header); BinaryHttpRequest different_body( {"POST", "https", "www.example.com", "/hello.txt"}); different_body.AddHeaderField({"User-Agent", "not/telling"}) ->set_body({"goodbye, world!\r\n"}); EXPECT_NE(request, different_body); BinaryHttpRequest no_body({"POST", "https", "www.example.com", "/hello.txt"}); no_body.AddHeaderField({"User-Agent", "not/telling"}); EXPECT_NE(request, no_body); } TEST(BinaryHttpResponse, EncodeNoBody) { BinaryHttpResponse response(404); response.AddHeaderField({"Server", "Apache"}); const uint32_t expected_words[] = {0x0141940e, 0x06736572, 0x76657206, 0x41706163, 0x68650000}; std::string expected; for (const auto& word : expected_words) { expected += WordToBytes(word); } expected.resize(expected.size() - 1); const auto result = response.Serialize(); ASSERT_TRUE(result.ok()); ASSERT_EQ(*result, expected); EXPECT_THAT( response.DebugString(), StrEq("BinaryHttpResponse(404){BinaryHttpMessage{Headers{Field{server=" "Apache}}Body{}}}")); } TEST(BinaryHttpResponse, DecodeNoBody) { const uint32_t words[] = {0x0141940e, 0x06736572, 0x76657206, 0x41706163, 0x68650000}; std::string data; for (const auto& word : words) { data += WordToBytes(word); } const auto response_so = BinaryHttpResponse::Create(data); ASSERT_TRUE(response_so.ok()); const BinaryHttpResponse response = *response_so; ASSERT_EQ(response.status_code(), 404); std::vector<BinaryHttpMessage::Field> expected_fields = { {"server", "Apache"}}; ASSERT_THAT(response.GetHeaderFields(), ContainerEq(expected_fields)); ASSERT_EQ(response.body(), ""); ASSERT_TRUE(response.informational_responses().empty()); EXPECT_THAT( response.DebugString(), StrEq("BinaryHttpResponse(404){BinaryHttpMessage{Headers{Field{server=" "Apache}}Body{}}}")); } TEST(BinaryHttpResponse, EncodeBody) { BinaryHttpResponse response(200); response.AddHeaderField({"Server", "Apache"}); response.set_body("Hello, world!\r\n"); const uint32_t expected_words[] = {0x0140c80e, 0x06736572, 0x76657206, 0x41706163, 0x68650f48, 0x656c6c6f, 0x2c20776f, 0x726c6421, 0x0d0a0000}; std::string expected; for (const auto& word : expected_words) { expected += WordToBytes(word); } expected.resize(expected.size() - 2); const auto result = response.Serialize(); ASSERT_TRUE(result.ok()); ASSERT_EQ(*result, expected); EXPECT_THAT( response.DebugString(), StrEq("BinaryHttpResponse(200){BinaryHttpMessage{Headers{Field{server=" "Apache}}Body{Hello, world!\r\n}}}")); } TEST(BinaryHttpResponse, DecodeBody) { const uint32_t words[] = {0x0140c80e, 0x06736572, 0x76657206, 0x41706163, 0x68650f48, 0x656c6c6f, 0x2c20776f, 0x726c6421, 0x0d0a0000}; std::string data; for (const auto& word : words) { data += WordToBytes(word); } const auto response_so = BinaryHttpResponse::Create(data); ASSERT_TRUE(response_so.ok()); const BinaryHttpResponse response = *response_so; ASSERT_EQ(response.status_code(), 200); std::vector<BinaryHttpMessage::Field> expected_fields = { {"server", "Apache"}}; ASSERT_THAT(response.GetHeaderFields(), ContainerEq(expected_fields)); ASSERT_EQ(response.body(), "Hello, world!\r\n"); ASSERT_TRUE(response.informational_responses().empty()); EXPECT_THAT( response.DebugString(), StrEq("BinaryHttpResponse(200){BinaryHttpMessage{Headers{Field{server=" "Apache}}Body{Hello, world!\r\n}}}")); } TEST(BHttpResponse, AddBadInformationalResponseCode) { BinaryHttpResponse response(200); ASSERT_FALSE(response.AddInformationalResponse(50, {}).ok()); ASSERT_FALSE(response.AddInformationalResponse(300, {}).ok()); } TEST(BinaryHttpResponse, EncodeMultiInformationalWithBody) { BinaryHttpResponse response(200); response.AddHeaderField({"Date", "Mon, 27 Jul 2009 12:28:53 GMT"}) ->AddHeaderField({"Server", "Apache"}) ->AddHeaderField({"Last-Modified", "Wed, 22 Jul 2009 19:15:56 GMT"}) ->AddHeaderField({"ETag", "\"34aa387-d-1568eb00\""}) ->AddHeaderField({"Accept-Ranges", "bytes"}) ->AddHeaderField({"Content-Length", "51"}) ->AddHeaderField({"Vary", "Accept-Encoding"}) ->AddHeaderField({"Content-Type", "text/plain"}); response.set_body("Hello World! My content includes a trailing CRLF.\r\n"); ASSERT_TRUE( response.AddInformationalResponse(102, {{"Running", "\"sleep 15\""}}) .ok()); ASSERT_TRUE(response .AddInformationalResponse( 103, {{"Link", "</style.css>; rel=preload; as=style"}, {"Link", "</script.js>; rel=preload; as=script"}}) .ok()); const uint32_t expected_words[] = { 0x01406613, 0x0772756e, 0x6e696e67, 0x0a22736c, 0x65657020, 0x31352240, 0x67405304, 0x6c696e6b, 0x233c2f73, 0x74796c65, 0x2e637373, 0x3e3b2072, 0x656c3d70, 0x72656c6f, 0x61643b20, 0x61733d73, 0x74796c65, 0x046c696e, 0x6b243c2f, 0x73637269, 0x70742e6a, 0x733e3b20, 0x72656c3d, 0x7072656c, 0x6f61643b, 0x2061733d, 0x73637269, 0x707440c8, 0x40ca0464, 0x6174651d, 0x4d6f6e2c, 0x20323720, 0x4a756c20, 0x32303039, 0x2031323a, 0x32383a35, 0x3320474d, 0x54067365, 0x72766572, 0x06417061, 0x6368650d, 0x6c617374, 0x2d6d6f64, 0x69666965, 0x641d5765, 0x642c2032, 0x32204a75, 0x6c203230, 0x30392031, 0x393a3135, 0x3a353620, 0x474d5404, 0x65746167, 0x14223334, 0x61613338, 0x372d642d, 0x31353638, 0x65623030, 0x220d6163, 0x63657074, 0x2d72616e, 0x67657305, 0x62797465, 0x730e636f, 0x6e74656e, 0x742d6c65, 0x6e677468, 0x02353104, 0x76617279, 0x0f416363, 0x6570742d, 0x456e636f, 0x64696e67, 0x0c636f6e, 0x74656e74, 0x2d747970, 0x650a7465, 0x78742f70, 0x6c61696e, 0x3348656c, 0x6c6f2057, 0x6f726c64, 0x21204d79, 0x20636f6e, 0x74656e74, 0x20696e63, 0x6c756465, 0x73206120, 0x74726169, 0x6c696e67, 0x2043524c, 0x462e0d0a}; std::string expected; for (const auto& word : expected_words) { expected += WordToBytes(word); } const auto result = response.Serialize(); ASSERT_TRUE(result.ok()); ASSERT_EQ(*result, expected); EXPECT_THAT( response.DebugString(), StrEq( "BinaryHttpResponse(200){BinaryHttpMessage{Headers{Field{date=Mon, " "27 Jul 2009 12:28:53 " "GMT};Field{server=Apache};Field{last-modified=Wed, 22 Jul 2009 " "19:15:56 " "GMT};Field{etag=\"34aa387-d-1568eb00\"};Field{accept-ranges=bytes};" "Field{" "content-length=51};Field{vary=Accept-Encoding};Field{content-type=" "text/plain}}Body{Hello World! My content includes a trailing " "CRLF.\r\n}}InformationalResponse{Field{running=\"sleep " "15\"}};InformationalResponse{Field{link=</style.css>; rel=preload; " "as=style};Field{link=</script.js>; rel=preload; as=script}}}")); TestPrintTo(response); } TEST(BinaryHttpResponse, DecodeMultiInformationalWithBody) { const uint32_t words[] = { 0x01406613, 0x0772756e, 0x6e696e67, 0x0a22736c, 0x65657020, 0x31352240, 0x67405304, 0x6c696e6b, 0x233c2f73, 0x74796c65, 0x2e637373, 0x3e3b2072, 0x656c3d70, 0x72656c6f, 0x61643b20, 0x61733d73, 0x74796c65, 0x046c696e, 0x6b243c2f, 0x73637269, 0x70742e6a, 0x733e3b20, 0x72656c3d, 0x7072656c, 0x6f61643b, 0x2061733d, 0x73637269, 0x707440c8, 0x40ca0464, 0x6174651d, 0x4d6f6e2c, 0x20323720, 0x4a756c20, 0x32303039, 0x2031323a, 0x32383a35, 0x3320474d, 0x54067365, 0x72766572, 0x06417061, 0x6368650d, 0x6c617374, 0x2d6d6f64, 0x69666965, 0x641d5765, 0x642c2032, 0x32204a75, 0x6c203230, 0x30392031, 0x393a3135, 0x3a353620, 0x474d5404, 0x65746167, 0x14223334, 0x61613338, 0x372d642d, 0x31353638, 0x65623030, 0x220d6163, 0x63657074, 0x2d72616e, 0x67657305, 0x62797465, 0x730e636f, 0x6e74656e, 0x742d6c65, 0x6e677468, 0x02353104, 0x76617279, 0x0f416363, 0x6570742d, 0x456e636f, 0x64696e67, 0x0c636f6e, 0x74656e74, 0x2d747970, 0x650a7465, 0x78742f70, 0x6c61696e, 0x3348656c, 0x6c6f2057, 0x6f726c64, 0x21204d79, 0x20636f6e, 0x74656e74, 0x20696e63, 0x6c756465, 0x73206120, 0x74726169, 0x6c696e67, 0x2043524c, 0x462e0d0a, 0x00000000}; std::string data; for (const auto& word : words) { data += WordToBytes(word); } const auto response_so = BinaryHttpResponse::Create(data); ASSERT_TRUE(response_so.ok()); const BinaryHttpResponse response = *response_so; std::vector<BinaryHttpMessage::Field> expected_fields = { {"date", "Mon, 27 Jul 2009 12:28:53 GMT"}, {"server", "Apache"}, {"last-modified", "Wed, 22 Jul 2009 19:15:56 GMT"}, {"etag", "\"34aa387-d-1568eb00\""}, {"accept-ranges", "bytes"}, {"content-length", "51"}, {"vary", "Accept-Encoding"}, {"content-type", "text/plain"}}; ASSERT_THAT(response.GetHeaderFields(), ContainerEq(expected_fields)); ASSERT_EQ(response.body(), "Hello World! My content includes a trailing CRLF.\r\n"); std::vector<BinaryHttpMessage::Field> header102 = { {"running", "\"sleep 15\""}}; std::vector<BinaryHttpMessage::Field> header103 = { {"link", "</style.css>; rel=preload; as=style"}, {"link", "</script.js>; rel=preload; as=script"}}; std::vector<BinaryHttpResponse::InformationalResponse> expected_control = { {102, header102}, {103, header103}}; ASSERT_THAT(response.informational_responses(), ContainerEq(expected_control)); EXPECT_THAT( response.DebugString(), StrEq( "BinaryHttpResponse(200){BinaryHttpMessage{Headers{Field{date=Mon, " "27 Jul 2009 12:28:53 " "GMT};Field{server=Apache};Field{last-modified=Wed, 22 Jul 2009 " "19:15:56 " "GMT};Field{etag=\"34aa387-d-1568eb00\"};Field{accept-ranges=bytes};" "Field{" "content-length=51};Field{vary=Accept-Encoding};Field{content-type=" "text/plain}}Body{Hello World! My content includes a trailing " "CRLF.\r\n}}InformationalResponse{Field{running=\"sleep " "15\"}};InformationalResponse{Field{link=</style.css>; rel=preload; " "as=style};Field{link=</script.js>; rel=preload; as=script}}}")); TestPrintTo(response); } TEST(BinaryHttpMessage, SwapBody) { BinaryHttpRequest request({}); request.set_body("hello, world!"); std::string other = "goodbye, world!"; request.swap_body(other); EXPECT_EQ(request.body(), "goodbye, world!"); EXPECT_EQ(other, "hello, world!"); } TEST(BinaryHttpResponse, Equality) { BinaryHttpResponse response(200); response.AddHeaderField({"Server", "Apache"})->set_body("Hello, world!\r\n"); ASSERT_TRUE( response.AddInformationalResponse(102, {{"Running", "\"sleep 15\""}}) .ok()); BinaryHttpResponse same(200); same.AddHeaderField({"Server", "Apache"})->set_body("Hello, world!\r\n"); ASSERT_TRUE( same.AddInformationalResponse(102, {{"Running", "\"sleep 15\""}}).ok()); ASSERT_EQ(response, same); } TEST(BinaryHttpResponse, Inequality) { BinaryHttpResponse response(200); response.AddHeaderField({"Server", "Apache"})->set_body("Hello, world!\r\n"); ASSERT_TRUE( response.AddInformationalResponse(102, {{"Running", "\"sleep 15\""}}) .ok()); BinaryHttpResponse different_status(201); different_status.AddHeaderField({"Server", "Apache"}) ->set_body("Hello, world!\r\n"); EXPECT_TRUE(different_status .AddInformationalResponse(102, {{"Running", "\"sleep 15\""}}) .ok()); EXPECT_NE(response, different_status); BinaryHttpResponse different_header(200); different_header.AddHeaderField({"Server", "python3"}) ->set_body("Hello, world!\r\n"); EXPECT_TRUE(different_header .AddInformationalResponse(102, {{"Running", "\"sleep 15\""}}) .ok()); EXPECT_NE(response, different_header); BinaryHttpResponse no_header(200); no_header.set_body("Hello, world!\r\n"); EXPECT_TRUE( no_header.AddInformationalResponse(102, {{"Running", "\"sleep 15\""}}) .ok()); EXPECT_NE(response, no_header); BinaryHttpResponse different_body(200); different_body.AddHeaderField({"Server", "Apache"}) ->set_body("Goodbye, world!\r\n"); EXPECT_TRUE(different_body .AddInformationalResponse(102, {{"Running", "\"sleep 15\""}}) .ok()); EXPECT_NE(response, different_body); BinaryHttpResponse no_body(200); no_body.AddHeaderField({"Server", "Apache"}); EXPECT_TRUE( no_body.AddInformationalResponse(102, {{"Running", "\"sleep 15\""}}) .ok()); EXPECT_NE(response, no_body); BinaryHttpResponse different_informational(200); different_informational.AddHeaderField({"Server", "Apache"}) ->set_body("Hello, world!\r\n"); EXPECT_TRUE(different_informational .AddInformationalResponse(198, {{"Running", "\"sleep 15\""}}) .ok()); EXPECT_NE(response, different_informational); BinaryHttpResponse no_informational(200); no_informational.AddHeaderField({"Server", "Apache"}) ->set_body("Hello, world!\r\n"); EXPECT_NE(response, no_informational); } MATCHER_P(HasEqPayload, value, "Payloads of messages are equivalent.") { return arg.IsPayloadEqual(value); } template <typename T> void TestPadding(T& message) { const auto data_so = message.Serialize(); ASSERT_TRUE(data_so.ok()); auto data = *data_so; ASSERT_EQ(data.size(), message.EncodedSize()); message.set_num_padding_bytes(10); const auto padded_data_so = message.Serialize(); ASSERT_TRUE(padded_data_so.ok()); const auto padded_data = *padded_data_so; ASSERT_EQ(padded_data.size(), message.EncodedSize()); ASSERT_EQ(data.size() + 10, padded_data.size()); data.resize(data.size() + 10); ASSERT_EQ(data, padded_data); const auto deserialized_padded_message_so = T::Create(data); ASSERT_TRUE(deserialized_padded_message_so.ok()); const auto deserialized_padded_message = *deserialized_padded_message_so; ASSERT_EQ(deserialized_padded_message, message); ASSERT_EQ(deserialized_padded_message.num_padding_bytes(), size_t(10)); data[data.size() - 1] = 'a'; const auto bad_so = T::Create(data); ASSERT_FALSE(bad_so.ok()); data.resize(data.size() - 10); const auto deserialized_message_so = T::Create(data); ASSERT_TRUE(deserialized_message_so.ok()); const auto deserialized_message = *deserialized_message_so; ASSERT_EQ(deserialized_message.num_padding_bytes(), size_t(0)); ASSERT_THAT(deserialized_message, HasEqPayload(deserialized_padded_message)); ASSERT_NE(deserialized_message, deserialized_padded_message); } TEST(BinaryHttpRequest, Padding) { BinaryHttpRequest request({"GET", "https", "", "/hello.txt"}); request .AddHeaderField({"User-Agent", "curl/7.16.3 libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3"}) ->AddHeaderField({"Host", "www.example.com"}) ->AddHeaderField({"Accept-Language", "en, mi"}); TestPadding(request); } TEST(BinaryHttpResponse, Padding) { BinaryHttpResponse response(200); response.AddHeaderField({"Server", "Apache"}); response.set_body("Hello, world!\r\n"); TestPadding(response); } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/binary_http/binary_http_message.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/binary_http/binary_http_message_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
70211bbd-e67e-484e-a711-d1383b5f6173
cpp
google/quiche
blind_sign_auth
quiche/blind_sign_auth/blind_sign_auth.cc
quiche/blind_sign_auth/blind_sign_auth_test.cc
#include "quiche/blind_sign_auth/blind_sign_auth.h" #include <cstddef> #include <cstdint> #include <cstring> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/functional/bind_front.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "absl/types/span.h" #include "anonymous_tokens/cpp/crypto/crypto_utils.h" #include "anonymous_tokens/cpp/privacy_pass/rsa_bssa_public_metadata_client.h" #include "anonymous_tokens/cpp/privacy_pass/token_encodings.h" #include "anonymous_tokens/cpp/shared/proto_utils.h" #include "quiche/blind_sign_auth/blind_sign_auth_interface.h" #include "quiche/blind_sign_auth/blind_sign_auth_protos.h" #include "quiche/blind_sign_auth/blind_sign_message_interface.h" #include "quiche/blind_sign_auth/blind_sign_message_response.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_random.h" namespace quiche { namespace { template <typename T> std::string OmitDefault(T value) { return value == 0 ? "" : absl::StrCat(value); } constexpr absl::string_view kIssuerHostname = "https: } void BlindSignAuth::GetTokens(std::optional<std::string> oauth_token, int num_tokens, ProxyLayer proxy_layer, BlindSignAuthServiceType service_type, SignedTokenCallback callback) { privacy::ppn::GetInitialDataRequest request; request.set_use_attestation(false); request.set_service_type(BlindSignAuthServiceTypeToString(service_type)); request.set_location_granularity( privacy::ppn::GetInitialDataRequest_LocationGranularity_CITY_GEOS); request.set_validation_version(2); request.set_proxy_layer(QuicheProxyLayerToPpnProxyLayer(proxy_layer)); std::string body = request.SerializeAsString(); BlindSignMessageCallback initial_data_callback = absl::bind_front( &BlindSignAuth::GetInitialDataCallback, this, oauth_token, num_tokens, proxy_layer, service_type, std::move(callback)); fetcher_->DoRequest(BlindSignMessageRequestType::kGetInitialData, oauth_token, body, std::move(initial_data_callback)); } void BlindSignAuth::GetInitialDataCallback( std::optional<std::string> oauth_token, int num_tokens, ProxyLayer proxy_layer, BlindSignAuthServiceType service_type, SignedTokenCallback callback, absl::StatusOr<BlindSignMessageResponse> response) { if (!response.ok()) { QUICHE_LOG(WARNING) << "GetInitialDataRequest failed: " << response.status(); std::move(callback)(absl::InvalidArgumentError( "GetInitialDataRequest failed: invalid response")); return; } absl::StatusCode code = response->status_code(); if (code != absl::StatusCode::kOk) { std::string message = absl::StrCat("GetInitialDataRequest failed with code: ", code); QUICHE_LOG(WARNING) << message; std::move(callback)( absl::InvalidArgumentError("GetInitialDataRequest failed")); return; } privacy::ppn::GetInitialDataResponse initial_data_response; if (!initial_data_response.ParseFromString(response->body())) { QUICHE_LOG(WARNING) << "Failed to parse GetInitialDataResponse"; std::move(callback)( absl::InternalError("Failed to parse GetInitialDataResponse")); return; } bool use_privacy_pass_client = initial_data_response.has_privacy_pass_data() && auth_options_.enable_privacy_pass(); if (use_privacy_pass_client) { QUICHE_DVLOG(1) << "Using Privacy Pass client"; GeneratePrivacyPassTokens(initial_data_response, std::move(oauth_token), num_tokens, proxy_layer, service_type, std::move(callback)); } else { QUICHE_LOG(ERROR) << "Non-Privacy Pass tokens are no longer supported"; std::move(callback)(absl::UnimplementedError( "Non-Privacy Pass tokens are no longer supported")); } } void BlindSignAuth::GeneratePrivacyPassTokens( privacy::ppn::GetInitialDataResponse initial_data_response, std::optional<std::string> oauth_token, int num_tokens, ProxyLayer proxy_layer, BlindSignAuthServiceType service_type, SignedTokenCallback callback) { anonymous_tokens::RSAPublicKey public_key_proto; if (!public_key_proto.ParseFromString( initial_data_response.at_public_metadata_public_key() .serialized_public_key())) { std::move(callback)( absl::InvalidArgumentError("Failed to parse Privacy Pass public key")); return; } absl::StatusOr<bssl::UniquePtr<RSA>> bssl_rsa_key = anonymous_tokens::CreatePublicKeyRSA( public_key_proto.n(), public_key_proto.e()); if (!bssl_rsa_key.ok()) { QUICHE_LOG(ERROR) << "Failed to create RSA public key: " << bssl_rsa_key.status(); std::move(callback)(absl::InternalError("Failed to create RSA public key")); return; } absl::StatusOr<anonymous_tokens::Extensions> extensions = anonymous_tokens::DecodeExtensions( initial_data_response.privacy_pass_data() .public_metadata_extensions()); if (!extensions.ok()) { QUICHE_LOG(WARNING) << "Failed to decode extensions: " << extensions.status(); std::move(callback)( absl::InvalidArgumentError("Failed to decode extensions")); return; } std::vector<uint16_t> kExpectedExtensionTypes = { 0x0001, 0x0002, 0xF001, 0xF002, 0xF003}; absl::Status result = anonymous_tokens::ValidateExtensionsOrderAndValues( *extensions, absl::MakeSpan(kExpectedExtensionTypes), absl::Now()); if (!result.ok()) { QUICHE_LOG(WARNING) << "Failed to validate extensions: " << result; std::move(callback)( absl::InvalidArgumentError("Failed to validate extensions")); return; } absl::StatusOr<anonymous_tokens::ExpirationTimestamp> expiration_timestamp = anonymous_tokens:: ExpirationTimestamp::FromExtension(extensions->extensions.at(0)); if (!expiration_timestamp.ok()) { QUICHE_LOG(WARNING) << "Failed to parse expiration timestamp: " << expiration_timestamp.status(); std::move(callback)( absl::InvalidArgumentError("Failed to parse expiration timestamp")); return; } absl::Time public_metadata_expiry_time = absl::FromUnixSeconds(expiration_timestamp->timestamp); absl::StatusOr<anonymous_tokens::GeoHint> geo_hint = anonymous_tokens::GeoHint::FromExtension( extensions->extensions.at(1)); QUICHE_CHECK(geo_hint.ok()); anonymous_tokens::TokenChallenge challenge; challenge.issuer_name = kIssuerHostname; absl::StatusOr<std::string> token_challenge = anonymous_tokens::MarshalTokenChallenge(challenge); if (!token_challenge.ok()) { QUICHE_LOG(WARNING) << "Failed to marshal token challenge: " << token_challenge.status(); std::move(callback)( absl::InvalidArgumentError("Failed to marshal token challenge")); return; } QuicheRandom* random = QuicheRandom::GetInstance(); std::vector<anonymous_tokens::ExtendedTokenRequest> extended_token_requests; std::vector<std::unique_ptr<anonymous_tokens:: PrivacyPassRsaBssaPublicMetadataClient>> privacy_pass_clients; std::vector<std::string> privacy_pass_blinded_tokens; for (int i = 0; i < num_tokens; i++) { auto client = anonymous_tokens:: PrivacyPassRsaBssaPublicMetadataClient::Create(*bssl_rsa_key.value()); if (!client.ok()) { QUICHE_LOG(WARNING) << "Failed to create Privacy Pass client: " << client.status(); std::move(callback)( absl::InternalError("Failed to create Privacy Pass client")); return; } std::string nonce_rand(32, '\0'); random->RandBytes(nonce_rand.data(), nonce_rand.size()); absl::StatusOr<anonymous_tokens::ExtendedTokenRequest> extended_token_request = client.value()->CreateTokenRequest( *token_challenge, nonce_rand, initial_data_response.privacy_pass_data().token_key_id(), *extensions); if (!extended_token_request.ok()) { QUICHE_LOG(WARNING) << "Failed to create ExtendedTokenRequest: " << extended_token_request.status(); std::move(callback)( absl::InternalError("Failed to create ExtendedTokenRequest")); return; } privacy_pass_clients.push_back(*std::move(client)); extended_token_requests.push_back(*extended_token_request); privacy_pass_blinded_tokens.push_back(absl::Base64Escape( extended_token_request->request.blinded_token_request)); } privacy::ppn::AuthAndSignRequest sign_request; sign_request.set_service_type(BlindSignAuthServiceTypeToString(service_type)); sign_request.set_key_type(privacy::ppn::AT_PUBLIC_METADATA_KEY_TYPE); sign_request.set_key_version( initial_data_response.at_public_metadata_public_key().key_version()); sign_request.mutable_blinded_token()->Assign( privacy_pass_blinded_tokens.begin(), privacy_pass_blinded_tokens.end()); sign_request.mutable_public_metadata_extensions()->assign( initial_data_response.privacy_pass_data().public_metadata_extensions()); sign_request.set_do_not_use_rsa_public_exponent(true); sign_request.set_proxy_layer(QuicheProxyLayerToPpnProxyLayer(proxy_layer)); absl::StatusOr<anonymous_tokens::AnonymousTokensUseCase> use_case = anonymous_tokens::ParseUseCase( initial_data_response.at_public_metadata_public_key().use_case()); if (!use_case.ok()) { QUICHE_LOG(WARNING) << "Failed to parse use case: " << use_case.status(); std::move(callback)(absl::InvalidArgumentError("Failed to parse use case")); return; } BlindSignMessageCallback auth_and_sign_callback = absl::bind_front(&BlindSignAuth::PrivacyPassAuthAndSignCallback, this, std::move(initial_data_response.privacy_pass_data() .public_metadata_extensions()), public_metadata_expiry_time, *geo_hint, *use_case, std::move(privacy_pass_clients), std::move(callback)); fetcher_->DoRequest(BlindSignMessageRequestType::kAuthAndSign, oauth_token, sign_request.SerializeAsString(), std::move(auth_and_sign_callback)); } void BlindSignAuth::PrivacyPassAuthAndSignCallback( std::string encoded_extensions, absl::Time public_key_expiry_time, anonymous_tokens::GeoHint geo_hint, anonymous_tokens::AnonymousTokensUseCase use_case, std::vector<std::unique_ptr<anonymous_tokens:: PrivacyPassRsaBssaPublicMetadataClient>> privacy_pass_clients, SignedTokenCallback callback, absl::StatusOr<BlindSignMessageResponse> response) { if (!response.ok()) { QUICHE_LOG(WARNING) << "AuthAndSign failed: " << response.status(); std::move(callback)( absl::InvalidArgumentError("AuthAndSign failed: invalid response")); return; } absl::StatusCode code = response->status_code(); if (code != absl::StatusCode::kOk) { std::string message = absl::StrCat("AuthAndSign failed with code: ", code); QUICHE_LOG(WARNING) << message; std::move(callback)(absl::InvalidArgumentError("AuthAndSign failed")); return; } privacy::ppn::AuthAndSignResponse sign_response; if (!sign_response.ParseFromString(response->body())) { QUICHE_LOG(WARNING) << "Failed to parse AuthAndSignResponse"; std::move(callback)( absl::InternalError("Failed to parse AuthAndSignResponse")); return; } if (static_cast<size_t>(sign_response.blinded_token_signature_size()) != privacy_pass_clients.size()) { QUICHE_LOG(WARNING) << "Number of signatures does not equal number of " "Privacy Pass tokens sent"; std::move(callback)( absl::InternalError("Number of signatures does not equal number of " "Privacy Pass tokens sent")); return; } std::vector<BlindSignToken> tokens_vec; for (int i = 0; i < sign_response.blinded_token_signature_size(); i++) { std::string unescaped_blinded_sig; if (!absl::Base64Unescape(sign_response.blinded_token_signature()[i], &unescaped_blinded_sig)) { QUICHE_LOG(WARNING) << "Failed to unescape blinded signature"; std::move(callback)( absl::InternalError("Failed to unescape blinded signature")); return; } absl::StatusOr<anonymous_tokens::Token> token = privacy_pass_clients[i]->FinalizeToken(unescaped_blinded_sig); if (!token.ok()) { QUICHE_LOG(WARNING) << "Failed to finalize token: " << token.status(); std::move(callback)(absl::InternalError("Failed to finalize token")); return; } absl::StatusOr<std::string> marshaled_token = anonymous_tokens::MarshalToken(*token); if (!marshaled_token.ok()) { QUICHE_LOG(WARNING) << "Failed to marshal token: " << marshaled_token.status(); std::move(callback)(absl::InternalError("Failed to marshal token")); return; } privacy::ppn::PrivacyPassTokenData privacy_pass_token_data; privacy_pass_token_data.mutable_token()->assign( ConvertBase64ToWebSafeBase64(absl::Base64Escape(*marshaled_token))); privacy_pass_token_data.mutable_encoded_extensions()->assign( ConvertBase64ToWebSafeBase64(absl::Base64Escape(encoded_extensions))); privacy_pass_token_data.set_use_case_override(use_case); tokens_vec.push_back( BlindSignToken{privacy_pass_token_data.SerializeAsString(), public_key_expiry_time, geo_hint}); } std::move(callback)(absl::Span<BlindSignToken>(tokens_vec)); } privacy::ppn::ProxyLayer BlindSignAuth::QuicheProxyLayerToPpnProxyLayer( quiche::ProxyLayer proxy_layer) { switch (proxy_layer) { case ProxyLayer::kProxyA: { return privacy::ppn::ProxyLayer::PROXY_A; } case ProxyLayer::kProxyB: { return privacy::ppn::ProxyLayer::PROXY_B; } } } std::string BlindSignAuth::ConvertBase64ToWebSafeBase64( std::string base64_string) { absl::c_replace(base64_string, '+', '-'); absl::c_replace(base64_string, '/', '_'); return base64_string; } std::string BlindSignAuthServiceTypeToString( quiche::BlindSignAuthServiceType service_type) { switch (service_type) { case BlindSignAuthServiceType::kChromeIpBlinding: { return "chromeipblinding"; } case BlindSignAuthServiceType::kCronetIpBlinding: { return "cronetipblinding"; } case BlindSignAuthServiceType::kWebviewIpBlinding: { return "chromeipblinding"; } } } }
#include "quiche/blind_sign_auth/blind_sign_auth.h" #include <cstdint> #include <memory> #include <string> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "absl/types/span.h" #include "anonymous_tokens/cpp/crypto/crypto_utils.h" #include "anonymous_tokens/cpp/privacy_pass/token_encodings.h" #include "anonymous_tokens/cpp/testing/utils.h" #include "openssl/base.h" #include "openssl/digest.h" #include "quiche/blind_sign_auth/blind_sign_auth_interface.h" #include "quiche/blind_sign_auth/blind_sign_auth_protos.h" #include "quiche/blind_sign_auth/blind_sign_message_interface.h" #include "quiche/blind_sign_auth/blind_sign_message_response.h" #include "quiche/blind_sign_auth/test_tools/mock_blind_sign_message_interface.h" #include "quiche/common/platform/api/quiche_mutex.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace quiche { namespace test { namespace { using ::testing::_; using ::testing::Eq; using ::testing::InSequence; using ::testing::Invoke; using ::testing::StartsWith; using ::testing::Unused; class BlindSignAuthTest : public QuicheTest { protected: void SetUp() override { auto [test_rsa_public_key, test_rsa_private_key] = anonymous_tokens::GetStrongTestRsaKeyPair2048(); ANON_TOKENS_ASSERT_OK_AND_ASSIGN( rsa_public_key_, anonymous_tokens::CreatePublicKeyRSA( test_rsa_public_key.n, test_rsa_public_key.e)); ANON_TOKENS_ASSERT_OK_AND_ASSIGN( rsa_private_key_, anonymous_tokens::CreatePrivateKeyRSA( test_rsa_private_key.n, test_rsa_private_key.e, test_rsa_private_key.d, test_rsa_private_key.p, test_rsa_private_key.q, test_rsa_private_key.dp, test_rsa_private_key.dq, test_rsa_private_key.crt)); anonymous_tokens::RSAPublicKey public_key; public_key.set_n(test_rsa_public_key.n); public_key.set_e(test_rsa_public_key.e); public_key_proto_.set_key_version(1); public_key_proto_.set_use_case("TEST_USE_CASE"); public_key_proto_.set_serialized_public_key(public_key.SerializeAsString()); public_key_proto_.set_sig_hash_type( anonymous_tokens::AT_HASH_TYPE_SHA384); public_key_proto_.set_mask_gen_function( anonymous_tokens::AT_MGF_SHA384); public_key_proto_.set_salt_length(48); public_key_proto_.set_key_size(256); public_key_proto_.set_message_mask_type( anonymous_tokens::AT_MESSAGE_MASK_NO_MASK); public_key_proto_.set_message_mask_size(0); expected_get_initial_data_request_.set_use_attestation(false); expected_get_initial_data_request_.set_service_type("chromeipblinding"); expected_get_initial_data_request_.set_location_granularity( privacy::ppn::GetInitialDataRequest_LocationGranularity_CITY_GEOS); expected_get_initial_data_request_.set_validation_version(2); expected_get_initial_data_request_.set_proxy_layer(privacy::ppn::PROXY_A); privacy::ppn::GetInitialDataResponse fake_get_initial_data_response; *fake_get_initial_data_response.mutable_at_public_metadata_public_key() = public_key_proto_; fake_get_initial_data_response_ = fake_get_initial_data_response; privacy::ppn::GetInitialDataResponse::PrivacyPassData privacy_pass_data; ANON_TOKENS_ASSERT_OK_AND_ASSIGN( std::string public_key_der, anonymous_tokens::RsaSsaPssPublicKeyToDerEncoding( rsa_public_key_.get())); const EVP_MD* sha256 = EVP_sha256(); ANON_TOKENS_ASSERT_OK_AND_ASSIGN( token_key_id_, anonymous_tokens::ComputeHash( public_key_der, *sha256)); anonymous_tokens::ExpirationTimestamp expiration_timestamp; int64_t one_hour_away = absl::ToUnixSeconds(absl::Now() + absl::Hours(1)); expiration_timestamp.timestamp = one_hour_away - (one_hour_away % 900); expiration_timestamp.timestamp_precision = 900; absl::StatusOr<anonymous_tokens::Extension> expiration_extension = expiration_timestamp.AsExtension(); QUICHE_EXPECT_OK(expiration_extension); extensions_.extensions.push_back(*expiration_extension); anonymous_tokens::GeoHint geo_hint; geo_hint.geo_hint = "US,US-AL,ALABASTER"; absl::StatusOr<anonymous_tokens::Extension> geo_hint_extension = geo_hint.AsExtension(); QUICHE_EXPECT_OK(geo_hint_extension); extensions_.extensions.push_back(*geo_hint_extension); anonymous_tokens::ServiceType service_type; service_type.service_type_id = anonymous_tokens::ServiceType::kChromeIpBlinding; absl::StatusOr<anonymous_tokens::Extension> service_type_extension = service_type.AsExtension(); QUICHE_EXPECT_OK(service_type_extension); extensions_.extensions.push_back(*service_type_extension); anonymous_tokens::DebugMode debug_mode; debug_mode.mode = anonymous_tokens::DebugMode::kDebug; absl::StatusOr<anonymous_tokens::Extension> debug_mode_extension = debug_mode.AsExtension(); QUICHE_EXPECT_OK(debug_mode_extension); extensions_.extensions.push_back(*debug_mode_extension); anonymous_tokens::ProxyLayer proxy_layer; proxy_layer.layer = anonymous_tokens::ProxyLayer::kProxyA; absl::StatusOr<anonymous_tokens::Extension> proxy_layer_extension = proxy_layer.AsExtension(); QUICHE_EXPECT_OK(proxy_layer_extension); extensions_.extensions.push_back(*proxy_layer_extension); absl::StatusOr<std::string> serialized_extensions = anonymous_tokens::EncodeExtensions(extensions_); QUICHE_EXPECT_OK(serialized_extensions); privacy_pass_data.set_token_key_id(token_key_id_); privacy_pass_data.set_public_metadata_extensions(*serialized_extensions); *fake_get_initial_data_response.mutable_public_metadata_info() = public_metadata_info_; *fake_get_initial_data_response.mutable_privacy_pass_data() = privacy_pass_data; fake_get_initial_data_response_ = fake_get_initial_data_response; privacy::ppn::BlindSignAuthOptions options; options.set_enable_privacy_pass(true); blind_sign_auth_ = std::make_unique<BlindSignAuth>(&mock_message_interface_, options); } void TearDown() override { blind_sign_auth_.reset(nullptr); } public: void CreateSignResponse(const std::string& body, bool use_privacy_pass) { privacy::ppn::AuthAndSignRequest request; ASSERT_TRUE(request.ParseFromString(body)); EXPECT_EQ(request.service_type(), "chromeipblinding"); EXPECT_EQ(request.key_type(), privacy::ppn::AT_PUBLIC_METADATA_KEY_TYPE); EXPECT_EQ(request.public_key_hash(), ""); EXPECT_EQ(request.key_version(), public_key_proto_.key_version()); EXPECT_EQ(request.do_not_use_rsa_public_exponent(), true); EXPECT_NE(request.blinded_token().size(), 0); if (use_privacy_pass) { EXPECT_EQ(request.public_metadata_extensions(), fake_get_initial_data_response_.privacy_pass_data() .public_metadata_extensions()); } else { EXPECT_EQ(request.public_metadata_info().SerializeAsString(), public_metadata_info_.SerializeAsString()); } privacy::ppn::AuthAndSignResponse response; for (const auto& request_token : request.blinded_token()) { std::string decoded_blinded_token; ASSERT_TRUE(absl::Base64Unescape(request_token, &decoded_blinded_token)); if (use_privacy_pass) { absl::StatusOr<std::string> signature = anonymous_tokens::TestSignWithPublicMetadata( decoded_blinded_token, request.public_metadata_extensions(), *rsa_private_key_, false); QUICHE_EXPECT_OK(signature); response.add_blinded_token_signature(absl::Base64Escape(*signature)); } else { absl::StatusOr<std::string> serialized_token = anonymous_tokens::TestSign( decoded_blinded_token, rsa_private_key_.get()); QUICHE_EXPECT_OK(serialized_token); response.add_blinded_token_signature( absl::Base64Escape(*serialized_token)); } } sign_response_ = response; } void ValidatePrivacyPassTokensOutput(absl::Span<BlindSignToken> tokens) { for (const auto& token : tokens) { privacy::ppn::PrivacyPassTokenData privacy_pass_token_data; ASSERT_TRUE(privacy_pass_token_data.ParseFromString(token.token)); std::string decoded_token; ASSERT_TRUE(absl::WebSafeBase64Unescape(privacy_pass_token_data.token(), &decoded_token)); EXPECT_EQ(privacy_pass_token_data.encoded_extensions().back(), '='); std::string decoded_extensions; ASSERT_TRUE(absl::WebSafeBase64Unescape( privacy_pass_token_data.encoded_extensions(), &decoded_extensions)); EXPECT_EQ(token.geo_hint.geo_hint, "US,US-AL,ALABASTER"); EXPECT_EQ(token.geo_hint.country_code, "US"); EXPECT_EQ(token.geo_hint.region, "US-AL"); EXPECT_EQ(token.geo_hint.city, "ALABASTER"); } } MockBlindSignMessageInterface mock_message_interface_; std::unique_ptr<BlindSignAuth> blind_sign_auth_; anonymous_tokens::RSABlindSignaturePublicKey public_key_proto_; bssl::UniquePtr<RSA> rsa_public_key_; bssl::UniquePtr<RSA> rsa_private_key_; std::string token_key_id_; anonymous_tokens::Extensions extensions_; privacy::ppn::PublicMetadataInfo public_metadata_info_; privacy::ppn::AuthAndSignResponse sign_response_; privacy::ppn::GetInitialDataResponse fake_get_initial_data_response_; std::string oauth_token_ = "oauth_token"; privacy::ppn::GetInitialDataRequest expected_get_initial_data_request_; }; TEST_F(BlindSignAuthTest, TestGetTokensFailedNetworkError) { EXPECT_CALL(mock_message_interface_, DoRequest(Eq(BlindSignMessageRequestType::kGetInitialData), Eq(oauth_token_), _, _)) .Times(1) .WillOnce([=](auto&&, auto&&, auto&&, auto get_initial_data_cb) { std::move(get_initial_data_cb)( absl::InternalError("Failed to create socket")); }); EXPECT_CALL(mock_message_interface_, DoRequest(Eq(BlindSignMessageRequestType::kAuthAndSign), _, _, _)) .Times(0); int num_tokens = 1; QuicheNotification done; SignedTokenCallback callback = [&done](absl::StatusOr<absl::Span<BlindSignToken>> tokens) { EXPECT_THAT(tokens.status().code(), absl::StatusCode::kInvalidArgument); done.Notify(); }; blind_sign_auth_->GetTokens(oauth_token_, num_tokens, ProxyLayer::kProxyA, BlindSignAuthServiceType::kChromeIpBlinding, std::move(callback)); done.WaitForNotification(); } TEST_F(BlindSignAuthTest, TestGetTokensFailedBadGetInitialDataResponse) { *fake_get_initial_data_response_.mutable_at_public_metadata_public_key() ->mutable_use_case() = "SPAM"; BlindSignMessageResponse fake_public_key_response( absl::StatusCode::kOk, fake_get_initial_data_response_.SerializeAsString()); EXPECT_CALL( mock_message_interface_, DoRequest(Eq(BlindSignMessageRequestType::kGetInitialData), Eq(oauth_token_), Eq(expected_get_initial_data_request_.SerializeAsString()), _)) .Times(1) .WillOnce([=](auto&&, auto&&, auto&&, auto get_initial_data_cb) { std::move(get_initial_data_cb)(fake_public_key_response); }); EXPECT_CALL(mock_message_interface_, DoRequest(Eq(BlindSignMessageRequestType::kAuthAndSign), _, _, _)) .Times(0); int num_tokens = 1; QuicheNotification done; SignedTokenCallback callback = [&done](absl::StatusOr<absl::Span<BlindSignToken>> tokens) { EXPECT_THAT(tokens.status().code(), absl::StatusCode::kInvalidArgument); done.Notify(); }; blind_sign_auth_->GetTokens(oauth_token_, num_tokens, ProxyLayer::kProxyA, BlindSignAuthServiceType::kChromeIpBlinding, std::move(callback)); done.WaitForNotification(); } TEST_F(BlindSignAuthTest, TestGetTokensFailedBadAuthAndSignResponse) { BlindSignMessageResponse fake_public_key_response( absl::StatusCode::kOk, fake_get_initial_data_response_.SerializeAsString()); { InSequence seq; EXPECT_CALL( mock_message_interface_, DoRequest( Eq(BlindSignMessageRequestType::kGetInitialData), Eq(oauth_token_), Eq(expected_get_initial_data_request_.SerializeAsString()), _)) .Times(1) .WillOnce([=](auto&&, auto&&, auto&&, auto get_initial_data_cb) { std::move(get_initial_data_cb)(fake_public_key_response); }); EXPECT_CALL(mock_message_interface_, DoRequest(Eq(BlindSignMessageRequestType::kAuthAndSign), Eq(oauth_token_), _, _)) .Times(1) .WillOnce(Invoke([this](Unused, Unused, const std::string& body, BlindSignMessageCallback callback) { CreateSignResponse(body, false); sign_response_.add_blinded_token_signature("invalid_signature%"); BlindSignMessageResponse response(absl::StatusCode::kOk, sign_response_.SerializeAsString()); std::move(callback)(response); })); } int num_tokens = 1; QuicheNotification done; SignedTokenCallback callback = [&done](absl::StatusOr<absl::Span<BlindSignToken>> tokens) { EXPECT_THAT(tokens.status().code(), absl::StatusCode::kInternal); done.Notify(); }; blind_sign_auth_->GetTokens(oauth_token_, num_tokens, ProxyLayer::kProxyA, BlindSignAuthServiceType::kChromeIpBlinding, std::move(callback)); done.WaitForNotification(); } TEST_F(BlindSignAuthTest, TestPrivacyPassGetTokensSucceeds) { BlindSignMessageResponse fake_public_key_response( absl::StatusCode::kOk, fake_get_initial_data_response_.SerializeAsString()); { InSequence seq; EXPECT_CALL( mock_message_interface_, DoRequest( Eq(BlindSignMessageRequestType::kGetInitialData), Eq(oauth_token_), Eq(expected_get_initial_data_request_.SerializeAsString()), _)) .Times(1) .WillOnce([=](auto&&, auto&&, auto&&, auto get_initial_data_cb) { std::move(get_initial_data_cb)(fake_public_key_response); }); EXPECT_CALL(mock_message_interface_, DoRequest(Eq(BlindSignMessageRequestType::kAuthAndSign), Eq(oauth_token_), _, _)) .Times(1) .WillOnce(Invoke([this](Unused, Unused, const std::string& body, BlindSignMessageCallback callback) { CreateSignResponse(body, true); BlindSignMessageResponse response(absl::StatusCode::kOk, sign_response_.SerializeAsString()); std::move(callback)(response); })); } int num_tokens = 1; QuicheNotification done; SignedTokenCallback callback = [this, &done](absl::StatusOr<absl::Span<BlindSignToken>> tokens) { QUICHE_EXPECT_OK(tokens); ValidatePrivacyPassTokensOutput(*tokens); done.Notify(); }; blind_sign_auth_->GetTokens(oauth_token_, num_tokens, ProxyLayer::kProxyA, BlindSignAuthServiceType::kChromeIpBlinding, std::move(callback)); done.WaitForNotification(); } TEST_F(BlindSignAuthTest, TestPrivacyPassGetTokensFailsWithBadExtensions) { privacy::ppn::BlindSignAuthOptions options; options.set_enable_privacy_pass(true); blind_sign_auth_ = std::make_unique<BlindSignAuth>(&mock_message_interface_, options); public_key_proto_.set_message_mask_type( anonymous_tokens::AT_MESSAGE_MASK_NO_MASK); public_key_proto_.set_message_mask_size(0); *fake_get_initial_data_response_.mutable_at_public_metadata_public_key() = public_key_proto_; fake_get_initial_data_response_.mutable_privacy_pass_data() ->set_public_metadata_extensions("spam"); BlindSignMessageResponse fake_public_key_response( absl::StatusCode::kOk, fake_get_initial_data_response_.SerializeAsString()); EXPECT_CALL( mock_message_interface_, DoRequest(Eq(BlindSignMessageRequestType::kGetInitialData), Eq(oauth_token_), Eq(expected_get_initial_data_request_.SerializeAsString()), _)) .Times(1) .WillOnce([=](auto&&, auto&&, auto&&, auto get_initial_data_cb) { std::move(get_initial_data_cb)(fake_public_key_response); }); int num_tokens = 1; QuicheNotification done; SignedTokenCallback callback = [&done](absl::StatusOr<absl::Span<BlindSignToken>> tokens) { EXPECT_THAT(tokens.status().code(), absl::StatusCode::kInvalidArgument); done.Notify(); }; blind_sign_auth_->GetTokens(oauth_token_, num_tokens, ProxyLayer::kProxyA, BlindSignAuthServiceType::kChromeIpBlinding, std::move(callback)); done.WaitForNotification(); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/blind_sign_auth/blind_sign_auth.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/blind_sign_auth/blind_sign_auth_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
4249b828-0428-4326-a480-4dd2c2864c5d
cpp
google/quiche
cached_blind_sign_auth
quiche/blind_sign_auth/cached_blind_sign_auth.cc
quiche/blind_sign_auth/cached_blind_sign_auth_test.cc
#include "quiche/blind_sign_auth/cached_blind_sign_auth.h" #include <optional> #include <string> #include <utility> #include <vector> #include "absl/functional/bind_front.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "absl/types/span.h" #include "quiche/blind_sign_auth/blind_sign_auth_interface.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_mutex.h" namespace quiche { constexpr absl::Duration kFreshnessConstant = absl::Minutes(5); void CachedBlindSignAuth::GetTokens(std::optional<std::string> oauth_token, int num_tokens, ProxyLayer proxy_layer, BlindSignAuthServiceType service_type, SignedTokenCallback callback) { if (num_tokens > max_tokens_per_request_) { std::move(callback)(absl::InvalidArgumentError( absl::StrFormat("Number of tokens requested exceeds maximum: %d", kBlindSignAuthRequestMaxTokens))); return; } if (num_tokens < 0) { std::move(callback)(absl::InvalidArgumentError(absl::StrFormat( "Negative number of tokens requested: %d", num_tokens))); return; } std::vector<BlindSignToken> output_tokens; { QuicheWriterMutexLock lock(&mutex_); RemoveExpiredTokens(); if (static_cast<size_t>(num_tokens) <= cached_tokens_.size()) { output_tokens = CreateOutputTokens(num_tokens); } } if (!output_tokens.empty() || num_tokens == 0) { std::move(callback)(absl::MakeSpan(output_tokens)); return; } SignedTokenCallback caching_callback = absl::bind_front(&CachedBlindSignAuth::HandleGetTokensResponse, this, std::move(callback), num_tokens); blind_sign_auth_->GetTokens(oauth_token, kBlindSignAuthRequestMaxTokens, proxy_layer, service_type, std::move(caching_callback)); } void CachedBlindSignAuth::HandleGetTokensResponse( SignedTokenCallback callback, int num_tokens, absl::StatusOr<absl::Span<BlindSignToken>> tokens) { if (!tokens.ok()) { QUICHE_LOG(WARNING) << "BlindSignAuth::GetTokens failed: " << tokens.status(); std::move(callback)(tokens); return; } if (tokens->size() < static_cast<size_t>(num_tokens) || tokens->size() > kBlindSignAuthRequestMaxTokens) { QUICHE_LOG(WARNING) << "Expected " << num_tokens << " tokens, got " << tokens->size(); } std::vector<BlindSignToken> output_tokens; size_t cache_size; { QuicheWriterMutexLock lock(&mutex_); for (const BlindSignToken& token : *tokens) { cached_tokens_.push_back(token); } RemoveExpiredTokens(); cache_size = cached_tokens_.size(); if (cache_size >= static_cast<size_t>(num_tokens)) { output_tokens = CreateOutputTokens(num_tokens); } } if (!output_tokens.empty()) { std::move(callback)(absl::MakeSpan(output_tokens)); return; } std::move(callback)(absl::ResourceExhaustedError(absl::StrFormat( "Requested %d tokens, cache only has %d after GetTokensRequest", num_tokens, cache_size))); } std::vector<BlindSignToken> CachedBlindSignAuth::CreateOutputTokens( int num_tokens) { std::vector<BlindSignToken> output_tokens; if (cached_tokens_.size() < static_cast<size_t>(num_tokens)) { QUICHE_LOG(FATAL) << "Check failed, not enough tokens in cache: " << cached_tokens_.size() << " < " << num_tokens; } for (int i = 0; i < num_tokens; i++) { output_tokens.push_back(std::move(cached_tokens_.front())); cached_tokens_.pop_front(); } return output_tokens; } void CachedBlindSignAuth::RemoveExpiredTokens() { size_t original_size = cached_tokens_.size(); absl::Time now_plus_five_mins = absl::Now() + kFreshnessConstant; for (size_t i = 0; i < original_size; i++) { BlindSignToken token = std::move(cached_tokens_.front()); cached_tokens_.pop_front(); if (token.expiration > now_plus_five_mins) { cached_tokens_.push_back(std::move(token)); } } } }
#include "quiche/blind_sign_auth/cached_blind_sign_auth.h" #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "absl/types/span.h" #include "quiche/blind_sign_auth/blind_sign_auth_interface.h" #include "quiche/blind_sign_auth/test_tools/mock_blind_sign_auth_interface.h" #include "quiche/common/platform/api/quiche_mutex.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace quiche { namespace test { namespace { using ::testing::_; using ::testing::InvokeArgument; using ::testing::Unused; class CachedBlindSignAuthTest : public QuicheTest { protected: void SetUp() override { cached_blind_sign_auth_ = std::make_unique<CachedBlindSignAuth>(&mock_blind_sign_auth_interface_); } void TearDown() override { fake_tokens_.clear(); cached_blind_sign_auth_.reset(); } public: std::vector<BlindSignToken> MakeFakeTokens(int num_tokens) { std::vector<BlindSignToken> fake_tokens; for (int i = 0; i < kBlindSignAuthRequestMaxTokens; i++) { fake_tokens.push_back(BlindSignToken{absl::StrCat("token:", i), absl::Now() + absl::Hours(1)}); } return fake_tokens; } std::vector<BlindSignToken> MakeExpiredTokens(int num_tokens) { std::vector<BlindSignToken> fake_tokens; for (int i = 0; i < kBlindSignAuthRequestMaxTokens; i++) { fake_tokens.push_back(BlindSignToken{absl::StrCat("token:", i), absl::Now() - absl::Hours(1)}); } return fake_tokens; } MockBlindSignAuthInterface mock_blind_sign_auth_interface_; std::unique_ptr<CachedBlindSignAuth> cached_blind_sign_auth_; std::optional<std::string> oauth_token_ = "oauth_token"; std::vector<BlindSignToken> fake_tokens_; }; TEST_F(CachedBlindSignAuthTest, TestGetTokensOneCallSuccessful) { EXPECT_CALL(mock_blind_sign_auth_interface_, GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _)) .Times(1) .WillOnce([this](Unused, int num_tokens, Unused, Unused, SignedTokenCallback callback) { fake_tokens_ = MakeFakeTokens(num_tokens); std::move(callback)(absl::MakeSpan(fake_tokens_)); }); int num_tokens = 5; QuicheNotification done; SignedTokenCallback callback = [num_tokens, &done](absl::StatusOr<absl::Span<BlindSignToken>> tokens) { QUICHE_EXPECT_OK(tokens); EXPECT_EQ(num_tokens, tokens->size()); for (int i = 0; i < num_tokens; i++) { EXPECT_EQ(tokens->at(i).token, absl::StrCat("token:", i)); } done.Notify(); }; cached_blind_sign_auth_->GetTokens( oauth_token_, num_tokens, ProxyLayer::kProxyA, BlindSignAuthServiceType::kChromeIpBlinding, std::move(callback)); done.WaitForNotification(); } TEST_F(CachedBlindSignAuthTest, TestGetTokensMultipleRemoteCallsSuccessful) { EXPECT_CALL(mock_blind_sign_auth_interface_, GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _)) .Times(2) .WillRepeatedly([this](Unused, int num_tokens, Unused, Unused, SignedTokenCallback callback) { fake_tokens_ = MakeFakeTokens(num_tokens); std::move(callback)(absl::MakeSpan(fake_tokens_)); }); int num_tokens = kBlindSignAuthRequestMaxTokens - 1; QuicheNotification first; SignedTokenCallback first_callback = [num_tokens, &first](absl::StatusOr<absl::Span<BlindSignToken>> tokens) { QUICHE_EXPECT_OK(tokens); EXPECT_EQ(num_tokens, tokens->size()); for (int i = 0; i < num_tokens; i++) { EXPECT_EQ(tokens->at(i).token, absl::StrCat("token:", i)); } first.Notify(); }; cached_blind_sign_auth_->GetTokens( oauth_token_, num_tokens, ProxyLayer::kProxyA, BlindSignAuthServiceType::kChromeIpBlinding, std::move(first_callback)); first.WaitForNotification(); QuicheNotification second; SignedTokenCallback second_callback = [num_tokens, &second](absl::StatusOr<absl::Span<BlindSignToken>> tokens) { QUICHE_EXPECT_OK(tokens); EXPECT_EQ(num_tokens, tokens->size()); EXPECT_EQ(tokens->at(0).token, absl::StrCat("token:", kBlindSignAuthRequestMaxTokens - 1)); for (int i = 1; i < num_tokens; i++) { EXPECT_EQ(tokens->at(i).token, absl::StrCat("token:", i - 1)); } second.Notify(); }; cached_blind_sign_auth_->GetTokens( oauth_token_, num_tokens, ProxyLayer::kProxyA, BlindSignAuthServiceType::kChromeIpBlinding, std::move(second_callback)); second.WaitForNotification(); } TEST_F(CachedBlindSignAuthTest, TestGetTokensSecondRequestFilledFromCache) { EXPECT_CALL(mock_blind_sign_auth_interface_, GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _)) .Times(1) .WillOnce([this](Unused, int num_tokens, Unused, Unused, SignedTokenCallback callback) { fake_tokens_ = MakeFakeTokens(num_tokens); std::move(callback)(absl::MakeSpan(fake_tokens_)); }); int num_tokens = kBlindSignAuthRequestMaxTokens / 2; QuicheNotification first; SignedTokenCallback first_callback = [num_tokens, &first](absl::StatusOr<absl::Span<BlindSignToken>> tokens) { QUICHE_EXPECT_OK(tokens); EXPECT_EQ(num_tokens, tokens->size()); for (int i = 0; i < num_tokens; i++) { EXPECT_EQ(tokens->at(i).token, absl::StrCat("token:", i)); } first.Notify(); }; cached_blind_sign_auth_->GetTokens( oauth_token_, num_tokens, ProxyLayer::kProxyA, BlindSignAuthServiceType::kChromeIpBlinding, std::move(first_callback)); first.WaitForNotification(); QuicheNotification second; SignedTokenCallback second_callback = [num_tokens, &second](absl::StatusOr<absl::Span<BlindSignToken>> tokens) { QUICHE_EXPECT_OK(tokens); EXPECT_EQ(num_tokens, tokens->size()); for (int i = 0; i < num_tokens; i++) { EXPECT_EQ(tokens->at(i).token, absl::StrCat("token:", i + num_tokens)); } second.Notify(); }; cached_blind_sign_auth_->GetTokens( oauth_token_, num_tokens, ProxyLayer::kProxyA, BlindSignAuthServiceType::kChromeIpBlinding, std::move(second_callback)); second.WaitForNotification(); } TEST_F(CachedBlindSignAuthTest, TestGetTokensThirdRequestRefillsCache) { EXPECT_CALL(mock_blind_sign_auth_interface_, GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _)) .Times(2) .WillRepeatedly([this](Unused, int num_tokens, Unused, Unused, SignedTokenCallback callback) { fake_tokens_ = MakeFakeTokens(num_tokens); std::move(callback)(absl::MakeSpan(fake_tokens_)); }); int num_tokens = kBlindSignAuthRequestMaxTokens / 2; QuicheNotification first; SignedTokenCallback first_callback = [num_tokens, &first](absl::StatusOr<absl::Span<BlindSignToken>> tokens) { QUICHE_EXPECT_OK(tokens); EXPECT_EQ(num_tokens, tokens->size()); for (int i = 0; i < num_tokens; i++) { EXPECT_EQ(tokens->at(i).token, absl::StrCat("token:", i)); } first.Notify(); }; cached_blind_sign_auth_->GetTokens( oauth_token_, num_tokens, ProxyLayer::kProxyA, BlindSignAuthServiceType::kChromeIpBlinding, std::move(first_callback)); first.WaitForNotification(); QuicheNotification second; SignedTokenCallback second_callback = [num_tokens, &second](absl::StatusOr<absl::Span<BlindSignToken>> tokens) { QUICHE_EXPECT_OK(tokens); EXPECT_EQ(num_tokens, tokens->size()); for (int i = 0; i < num_tokens; i++) { EXPECT_EQ(tokens->at(i).token, absl::StrCat("token:", i + num_tokens)); } second.Notify(); }; cached_blind_sign_auth_->GetTokens( oauth_token_, num_tokens, ProxyLayer::kProxyA, BlindSignAuthServiceType::kChromeIpBlinding, std::move(second_callback)); second.WaitForNotification(); QuicheNotification third; int third_request_tokens = 10; SignedTokenCallback third_callback = [third_request_tokens, &third](absl::StatusOr<absl::Span<BlindSignToken>> tokens) { QUICHE_EXPECT_OK(tokens); EXPECT_EQ(third_request_tokens, tokens->size()); for (int i = 0; i < third_request_tokens; i++) { EXPECT_EQ(tokens->at(i).token, absl::StrCat("token:", i)); } third.Notify(); }; cached_blind_sign_auth_->GetTokens( oauth_token_, third_request_tokens, ProxyLayer::kProxyA, BlindSignAuthServiceType::kChromeIpBlinding, std::move(third_callback)); third.WaitForNotification(); } TEST_F(CachedBlindSignAuthTest, TestGetTokensRequestTooLarge) { EXPECT_CALL(mock_blind_sign_auth_interface_, GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _)) .Times(0); int num_tokens = kBlindSignAuthRequestMaxTokens + 1; SignedTokenCallback callback = [](absl::StatusOr<absl::Span<BlindSignToken>> tokens) { EXPECT_THAT(tokens.status().code(), absl::StatusCode::kInvalidArgument); EXPECT_THAT( tokens.status().message(), absl::StrFormat("Number of tokens requested exceeds maximum: %d", kBlindSignAuthRequestMaxTokens)); }; cached_blind_sign_auth_->GetTokens( oauth_token_, num_tokens, ProxyLayer::kProxyA, BlindSignAuthServiceType::kChromeIpBlinding, std::move(callback)); } TEST_F(CachedBlindSignAuthTest, TestGetTokensRequestNegative) { EXPECT_CALL(mock_blind_sign_auth_interface_, GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _)) .Times(0); int num_tokens = -1; SignedTokenCallback callback = [num_tokens](absl::StatusOr<absl::Span<BlindSignToken>> tokens) { EXPECT_THAT(tokens.status().code(), absl::StatusCode::kInvalidArgument); EXPECT_THAT(tokens.status().message(), absl::StrFormat("Negative number of tokens requested: %d", num_tokens)); }; cached_blind_sign_auth_->GetTokens( oauth_token_, num_tokens, ProxyLayer::kProxyA, BlindSignAuthServiceType::kChromeIpBlinding, std::move(callback)); } TEST_F(CachedBlindSignAuthTest, TestHandleGetTokensResponseErrorHandling) { EXPECT_CALL(mock_blind_sign_auth_interface_, GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _)) .Times(2) .WillOnce([](Unused, int num_tokens, Unused, Unused, SignedTokenCallback callback) { std::move(callback)(absl::InternalError("AuthAndSign failed")); }) .WillOnce([this](Unused, int num_tokens, Unused, Unused, SignedTokenCallback callback) { fake_tokens_ = MakeFakeTokens(num_tokens); fake_tokens_.pop_back(); std::move(callback)(absl::MakeSpan(fake_tokens_)); }); int num_tokens = kBlindSignAuthRequestMaxTokens; QuicheNotification first; SignedTokenCallback first_callback = [&first](absl::StatusOr<absl::Span<BlindSignToken>> tokens) { EXPECT_THAT(tokens.status().code(), absl::StatusCode::kInternal); EXPECT_THAT(tokens.status().message(), "AuthAndSign failed"); first.Notify(); }; cached_blind_sign_auth_->GetTokens( oauth_token_, num_tokens, ProxyLayer::kProxyA, BlindSignAuthServiceType::kChromeIpBlinding, std::move(first_callback)); first.WaitForNotification(); QuicheNotification second; SignedTokenCallback second_callback = [&second](absl::StatusOr<absl::Span<BlindSignToken>> tokens) { EXPECT_THAT(tokens.status().code(), absl::StatusCode::kResourceExhausted); second.Notify(); }; cached_blind_sign_auth_->GetTokens( oauth_token_, num_tokens, ProxyLayer::kProxyA, BlindSignAuthServiceType::kChromeIpBlinding, std::move(second_callback)); second.WaitForNotification(); } TEST_F(CachedBlindSignAuthTest, TestGetTokensZeroTokensRequested) { EXPECT_CALL(mock_blind_sign_auth_interface_, GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _)) .Times(0); int num_tokens = 0; SignedTokenCallback callback = [](absl::StatusOr<absl::Span<BlindSignToken>> tokens) { QUICHE_EXPECT_OK(tokens); EXPECT_EQ(tokens->size(), 0); }; cached_blind_sign_auth_->GetTokens( oauth_token_, num_tokens, ProxyLayer::kProxyA, BlindSignAuthServiceType::kChromeIpBlinding, std::move(callback)); } TEST_F(CachedBlindSignAuthTest, TestExpiredTokensArePruned) { EXPECT_CALL(mock_blind_sign_auth_interface_, GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _)) .Times(1) .WillOnce([this](Unused, int num_tokens, Unused, Unused, SignedTokenCallback callback) { fake_tokens_ = MakeExpiredTokens(num_tokens); std::move(callback)(absl::MakeSpan(fake_tokens_)); }); int num_tokens = kBlindSignAuthRequestMaxTokens; QuicheNotification first; SignedTokenCallback first_callback = [&first](absl::StatusOr<absl::Span<BlindSignToken>> tokens) { EXPECT_THAT(tokens.status().code(), absl::StatusCode::kResourceExhausted); first.Notify(); }; cached_blind_sign_auth_->GetTokens( oauth_token_, num_tokens, ProxyLayer::kProxyA, BlindSignAuthServiceType::kChromeIpBlinding, std::move(first_callback)); first.WaitForNotification(); } TEST_F(CachedBlindSignAuthTest, TestClearCacheRemovesTokens) { EXPECT_CALL(mock_blind_sign_auth_interface_, GetTokens(oauth_token_, kBlindSignAuthRequestMaxTokens, _, _, _)) .Times(2) .WillRepeatedly([this](Unused, int num_tokens, Unused, Unused, SignedTokenCallback callback) { fake_tokens_ = MakeExpiredTokens(num_tokens); std::move(callback)(absl::MakeSpan(fake_tokens_)); }); int num_tokens = kBlindSignAuthRequestMaxTokens / 2; QuicheNotification first; SignedTokenCallback first_callback = [&first](absl::StatusOr<absl::Span<BlindSignToken>> tokens) { EXPECT_THAT(tokens.status().code(), absl::StatusCode::kResourceExhausted); first.Notify(); }; cached_blind_sign_auth_->GetTokens( oauth_token_, num_tokens, ProxyLayer::kProxyA, BlindSignAuthServiceType::kChromeIpBlinding, std::move(first_callback)); first.WaitForNotification(); cached_blind_sign_auth_->ClearCache(); QuicheNotification second; SignedTokenCallback second_callback = [&second](absl::StatusOr<absl::Span<BlindSignToken>> tokens) { EXPECT_THAT(tokens.status().code(), absl::StatusCode::kResourceExhausted); second.Notify(); }; cached_blind_sign_auth_->GetTokens( oauth_token_, num_tokens, ProxyLayer::kProxyA, BlindSignAuthServiceType::kChromeIpBlinding, std::move(second_callback)); second.WaitForNotification(); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/blind_sign_auth/cached_blind_sign_auth.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/blind_sign_auth/cached_blind_sign_auth_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
5b2ce1fc-0d45-460e-9387-c716d81999e0
cpp
google/quiche
quic_simple_server_stream
quiche/quic/tools/quic_simple_server_stream.cc
quiche/quic/tools/quic_simple_server_stream_test.cc
#include "quiche/quic/tools/quic_simple_server_stream.h" #include <algorithm> #include <cstdint> #include <list> #include <optional> #include <string> #include <utility> #include "absl/strings/numbers.h" #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_stream.h" #include "quiche/quic/core/http/spdy_utils.h" #include "quiche/quic/core/http/web_transport_http3.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_utils.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" #include "quiche/quic/tools/quic_simple_server_session.h" using quiche::HttpHeaderBlock; namespace quic { QuicSimpleServerStream::QuicSimpleServerStream( QuicStreamId id, QuicSpdySession* session, StreamType type, QuicSimpleServerBackend* quic_simple_server_backend) : QuicSpdyServerStreamBase(id, session, type), content_length_(-1), generate_bytes_length_(0), quic_simple_server_backend_(quic_simple_server_backend) { QUICHE_DCHECK(quic_simple_server_backend_); } QuicSimpleServerStream::QuicSimpleServerStream( PendingStream* pending, QuicSpdySession* session, QuicSimpleServerBackend* quic_simple_server_backend) : QuicSpdyServerStreamBase(pending, session), content_length_(-1), generate_bytes_length_(0), quic_simple_server_backend_(quic_simple_server_backend) { QUICHE_DCHECK(quic_simple_server_backend_); } QuicSimpleServerStream::~QuicSimpleServerStream() { quic_simple_server_backend_->CloseBackendResponseStream(this); } void QuicSimpleServerStream::OnInitialHeadersComplete( bool fin, size_t frame_len, const QuicHeaderList& header_list) { QuicSpdyStream::OnInitialHeadersComplete(fin, frame_len, header_list); if (!response_sent_ && !SpdyUtils::CopyAndValidateHeaders(header_list, &content_length_, &request_headers_)) { QUIC_DVLOG(1) << "Invalid headers"; SendErrorResponse(); } ConsumeHeaderList(); if (!fin && !response_sent_ && IsConnectRequest()) { if (quic_simple_server_backend_ == nullptr) { QUIC_DVLOG(1) << "Backend is missing on CONNECT headers."; SendErrorResponse(); return; } if (web_transport() != nullptr) { QuicSimpleServerBackend::WebTransportResponse response = quic_simple_server_backend_->ProcessWebTransportRequest( request_headers_, web_transport()); if (response.response_headers[":status"] == "200") { WriteHeaders(std::move(response.response_headers), false, nullptr); if (response.visitor != nullptr) { web_transport()->SetVisitor(std::move(response.visitor)); } web_transport()->HeadersReceived(request_headers_); } else { WriteHeaders(std::move(response.response_headers), true, nullptr); } return; } quic_simple_server_backend_->HandleConnectHeaders(request_headers_, this); } } void QuicSimpleServerStream::OnBodyAvailable() { while (HasBytesToRead()) { struct iovec iov; if (GetReadableRegions(&iov, 1) == 0) { break; } QUIC_DVLOG(1) << "Stream " << id() << " processed " << iov.iov_len << " bytes."; body_.append(static_cast<char*>(iov.iov_base), iov.iov_len); if (content_length_ >= 0 && body_.size() > static_cast<uint64_t>(content_length_)) { QUIC_DVLOG(1) << "Body size (" << body_.size() << ") > content length (" << content_length_ << ")."; SendErrorResponse(); return; } MarkConsumed(iov.iov_len); } if (!sequencer()->IsClosed()) { if (IsConnectRequest()) { HandleRequestConnectData(false); } sequencer()->SetUnblocked(); return; } OnFinRead(); if (write_side_closed() || fin_buffered()) { return; } if (IsConnectRequest()) { HandleRequestConnectData(true); } else { SendResponse(); } } void QuicSimpleServerStream::HandleRequestConnectData(bool fin_received) { QUICHE_DCHECK(IsConnectRequest()); if (quic_simple_server_backend_ == nullptr) { QUIC_DVLOG(1) << "Backend is missing on CONNECT data."; ResetWriteSide( QuicResetStreamError::FromInternal(QUIC_STREAM_CONNECT_ERROR)); return; } std::string data = std::move(body_); body_.clear(); quic_simple_server_backend_->HandleConnectData(data, fin_received, this); } void QuicSimpleServerStream::SendResponse() { QUICHE_DCHECK(!IsConnectRequest()); if (request_headers_.empty()) { QUIC_DVLOG(1) << "Request headers empty."; SendErrorResponse(); return; } if (content_length_ > 0 && static_cast<uint64_t>(content_length_) != body_.size()) { QUIC_DVLOG(1) << "Content length (" << content_length_ << ") != body size (" << body_.size() << ")."; SendErrorResponse(); return; } if (!request_headers_.contains(":authority")) { QUIC_DVLOG(1) << "Request headers do not contain :authority."; SendErrorResponse(); return; } if (!request_headers_.contains(":path")) { QUIC_DVLOG(1) << "Request headers do not contain :path."; SendErrorResponse(); return; } if (quic_simple_server_backend_ == nullptr) { QUIC_DVLOG(1) << "Backend is missing in SendResponse()."; SendErrorResponse(); return; } if (web_transport() != nullptr) { QuicSimpleServerBackend::WebTransportResponse response = quic_simple_server_backend_->ProcessWebTransportRequest( request_headers_, web_transport()); if (response.response_headers[":status"] == "200") { WriteHeaders(std::move(response.response_headers), false, nullptr); if (response.visitor != nullptr) { web_transport()->SetVisitor(std::move(response.visitor)); } web_transport()->HeadersReceived(request_headers_); } else { WriteHeaders(std::move(response.response_headers), true, nullptr); } return; } quic_simple_server_backend_->FetchResponseFromBackend(request_headers_, body_, this); } QuicConnectionId QuicSimpleServerStream::connection_id() const { return spdy_session()->connection_id(); } QuicStreamId QuicSimpleServerStream::stream_id() const { return id(); } std::string QuicSimpleServerStream::peer_host() const { return spdy_session()->peer_address().host().ToString(); } QuicSpdyStream* QuicSimpleServerStream::GetStream() { return this; } namespace { class DelayedResponseAlarm : public QuicAlarm::DelegateWithContext { public: DelayedResponseAlarm(QuicSimpleServerStream* stream, const QuicBackendResponse* response) : QuicAlarm::DelegateWithContext( stream->spdy_session()->connection()->context()), stream_(stream), response_(response) { stream_ = stream; response_ = response; } ~DelayedResponseAlarm() override = default; void OnAlarm() override { stream_->Respond(response_); } private: QuicSimpleServerStream* stream_; const QuicBackendResponse* response_; }; } void QuicSimpleServerStream::OnResponseBackendComplete( const QuicBackendResponse* response) { if (response == nullptr) { QUIC_DVLOG(1) << "Response not found in cache."; SendNotFoundResponse(); return; } auto delay = response->delay(); if (delay.IsZero()) { Respond(response); return; } auto* connection = session()->connection(); delayed_response_alarm_.reset(connection->alarm_factory()->CreateAlarm( new DelayedResponseAlarm(this, response))); delayed_response_alarm_->Set(connection->clock()->Now() + delay); } void QuicSimpleServerStream::Respond(const QuicBackendResponse* response) { for (const auto& headers : response->early_hints()) { QUIC_DVLOG(1) << "Stream " << id() << " sending an Early Hints response: " << headers.DebugString(); WriteHeaders(headers.Clone(), false, nullptr); } if (response->response_type() == QuicBackendResponse::CLOSE_CONNECTION) { QUIC_DVLOG(1) << "Special response: closing connection."; OnUnrecoverableError(QUIC_NO_ERROR, "Toy server forcing close"); return; } if (response->response_type() == QuicBackendResponse::IGNORE_REQUEST) { QUIC_DVLOG(1) << "Special response: ignoring request."; return; } if (response->response_type() == QuicBackendResponse::BACKEND_ERR_RESPONSE) { QUIC_DVLOG(1) << "Quic Proxy: Backend connection error."; SendErrorResponse(502); return; } std::string request_url = request_headers_[":authority"].as_string() + request_headers_[":path"].as_string(); int response_code; const HttpHeaderBlock& response_headers = response->headers(); if (!ParseHeaderStatusCode(response_headers, &response_code)) { auto status = response_headers.find(":status"); if (status == response_headers.end()) { QUIC_LOG(WARNING) << ":status not present in response from cache for request " << request_url; } else { QUIC_LOG(WARNING) << "Illegal (non-integer) response :status from cache: " << status->second << " for request " << request_url; } SendErrorResponse(); return; } if (response->response_type() == QuicBackendResponse::INCOMPLETE_RESPONSE) { QUIC_DVLOG(1) << "Stream " << id() << " sending an incomplete response, i.e. no trailer, no fin."; SendIncompleteResponse(response->headers().Clone(), response->body()); return; } if (response->response_type() == QuicBackendResponse::GENERATE_BYTES) { QUIC_DVLOG(1) << "Stream " << id() << " sending a generate bytes response."; std::string path = request_headers_[":path"].as_string().substr(1); if (!absl::SimpleAtoi(path, &generate_bytes_length_)) { QUIC_LOG(ERROR) << "Path is not a number."; SendNotFoundResponse(); return; } HttpHeaderBlock headers = response->headers().Clone(); headers["content-length"] = absl::StrCat(generate_bytes_length_); WriteHeaders(std::move(headers), false, nullptr); QUICHE_DCHECK(!response_sent_); response_sent_ = true; WriteGeneratedBytes(); return; } QUIC_DVLOG(1) << "Stream " << id() << " sending response."; SendHeadersAndBodyAndTrailers(response->headers().Clone(), response->body(), response->trailers().Clone()); } void QuicSimpleServerStream::SendStreamData(absl::string_view data, bool close_stream) { QUICHE_DCHECK(!data.empty() || close_stream); if (close_stream) { SendHeadersAndBodyAndTrailers( std::nullopt, data, quiche::HttpHeaderBlock()); } else { SendIncompleteResponse(std::nullopt, data); } } void QuicSimpleServerStream::TerminateStreamWithError( QuicResetStreamError error) { QUIC_DVLOG(1) << "Stream " << id() << " abruptly terminating with error " << error.internal_code(); ResetWriteSide(error); } void QuicSimpleServerStream::OnCanWrite() { QuicSpdyStream::OnCanWrite(); WriteGeneratedBytes(); } void QuicSimpleServerStream::WriteGeneratedBytes() { static size_t kChunkSize = 1024; while (!HasBufferedData() && generate_bytes_length_ > 0) { size_t len = std::min<size_t>(kChunkSize, generate_bytes_length_); std::string data(len, 'a'); generate_bytes_length_ -= len; bool fin = generate_bytes_length_ == 0; WriteOrBufferBody(data, fin); } } void QuicSimpleServerStream::SendNotFoundResponse() { QUIC_DVLOG(1) << "Stream " << id() << " sending not found response."; HttpHeaderBlock headers; headers[":status"] = "404"; headers["content-length"] = absl::StrCat(strlen(kNotFoundResponseBody)); SendHeadersAndBody(std::move(headers), kNotFoundResponseBody); } void QuicSimpleServerStream::SendErrorResponse() { SendErrorResponse(0); } void QuicSimpleServerStream::SendErrorResponse(int resp_code) { QUIC_DVLOG(1) << "Stream " << id() << " sending error response."; if (!reading_stopped()) { StopReading(); } HttpHeaderBlock headers; if (resp_code <= 0) { headers[":status"] = "500"; } else { headers[":status"] = absl::StrCat(resp_code); } headers["content-length"] = absl::StrCat(strlen(kErrorResponseBody)); SendHeadersAndBody(std::move(headers), kErrorResponseBody); } void QuicSimpleServerStream::SendIncompleteResponse( std::optional<HttpHeaderBlock> response_headers, absl::string_view body) { QUICHE_DCHECK_NE(response_headers.has_value(), response_sent_); if (response_headers.has_value()) { QUIC_DLOG(INFO) << "Stream " << id() << " writing headers (fin = false) : " << response_headers.value().DebugString(); int response_code; if (!ParseHeaderStatusCode(*response_headers, &response_code) || response_code != 100) { response_sent_ = true; } WriteHeaders(std::move(response_headers).value(), false, nullptr); } QUIC_DLOG(INFO) << "Stream " << id() << " writing body (fin = false) with size: " << body.size(); if (!body.empty()) { WriteOrBufferBody(body, false); } } void QuicSimpleServerStream::SendHeadersAndBody( HttpHeaderBlock response_headers, absl::string_view body) { SendHeadersAndBodyAndTrailers(std::move(response_headers), body, HttpHeaderBlock()); } void QuicSimpleServerStream::SendHeadersAndBodyAndTrailers( std::optional<HttpHeaderBlock> response_headers, absl::string_view body, HttpHeaderBlock response_trailers) { QUICHE_DCHECK_NE(response_headers.has_value(), response_sent_); if (response_headers.has_value()) { bool send_fin = (body.empty() && response_trailers.empty()); QUIC_DLOG(INFO) << "Stream " << id() << " writing headers (fin = " << send_fin << ") : " << response_headers.value().DebugString(); WriteHeaders(std::move(response_headers).value(), send_fin, nullptr); response_sent_ = true; if (send_fin) { return; } } bool send_fin = response_trailers.empty(); QUIC_DLOG(INFO) << "Stream " << id() << " writing body (fin = " << send_fin << ") with size: " << body.size(); if (!body.empty() || send_fin) { WriteOrBufferBody(body, send_fin); } if (send_fin) { return; } QUIC_DLOG(INFO) << "Stream " << id() << " writing trailers (fin = true): " << response_trailers.DebugString(); WriteTrailers(std::move(response_trailers), nullptr); } bool QuicSimpleServerStream::IsConnectRequest() const { auto method_it = request_headers_.find(":method"); return method_it != request_headers_.end() && method_it->second == "CONNECT"; } void QuicSimpleServerStream::OnInvalidHeaders() { QUIC_DVLOG(1) << "Invalid headers"; SendErrorResponse(400); } const char* const QuicSimpleServerStream::kErrorResponseBody = "bad"; const char* const QuicSimpleServerStream::kNotFoundResponseBody = "file not found"; }
#include "quiche/quic/tools/quic_simple_server_stream.h" #include <list> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/memory/memory.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/http/http_encoder.h" #include "quiche/quic/core/http/spdy_utils.h" #include "quiche/quic/core/quic_alarm_factory.h" #include "quiche/quic/core/quic_default_clock.h" #include "quiche/quic/core/quic_error_codes.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_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/quic_config_peer.h" #include "quiche/quic/test_tools/quic_connection_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/simulator/simulator.h" #include "quiche/quic/tools/quic_backend_response.h" #include "quiche/quic/tools/quic_memory_cache_backend.h" #include "quiche/quic/tools/quic_simple_server_backend.h" #include "quiche/quic/tools/quic_simple_server_session.h" #include "quiche/common/simple_buffer_allocator.h" using testing::_; using testing::AnyNumber; using testing::InSequence; using testing::Invoke; using testing::StrictMock; namespace quic { namespace test { const size_t kFakeFrameLen = 60; const size_t kErrorLength = strlen(QuicSimpleServerStream::kErrorResponseBody); const size_t kDataFrameHeaderLength = 2; class TestStream : public QuicSimpleServerStream { public: TestStream(QuicStreamId stream_id, QuicSpdySession* session, StreamType type, QuicSimpleServerBackend* quic_simple_server_backend) : QuicSimpleServerStream(stream_id, session, type, quic_simple_server_backend) { EXPECT_CALL(*this, WriteOrBufferBody(_, _)) .Times(AnyNumber()) .WillRepeatedly([this](absl::string_view data, bool fin) { this->QuicSimpleServerStream::WriteOrBufferBody(data, fin); }); } ~TestStream() override = default; MOCK_METHOD(void, FireAlarmMock, (), ()); MOCK_METHOD(void, WriteHeadersMock, (bool fin), ()); MOCK_METHOD(void, WriteEarlyHintsHeadersMock, (bool fin), ()); MOCK_METHOD(void, WriteOrBufferBody, (absl::string_view data, bool fin), (override)); size_t WriteHeaders( quiche::HttpHeaderBlock header_block, bool fin, quiche::QuicheReferenceCountedPointer<QuicAckListenerInterface> ) override { if (header_block[":status"] == "103") { WriteEarlyHintsHeadersMock(fin); } else { WriteHeadersMock(fin); } return 0; } void DoSendResponse() { SendResponse(); } void DoSendErrorResponse() { QuicSimpleServerStream::SendErrorResponse(); } quiche::HttpHeaderBlock* mutable_headers() { return &request_headers_; } void set_body(std::string body) { body_ = std::move(body); } const std::string& body() const { return body_; } int content_length() const { return content_length_; } bool send_response_was_called() const { return send_response_was_called_; } bool send_error_response_was_called() const { return send_error_response_was_called_; } absl::string_view GetHeader(absl::string_view key) const { auto it = request_headers_.find(key); QUICHE_DCHECK(it != request_headers_.end()); return it->second; } void ReplaceBackend(QuicSimpleServerBackend* backend) { set_quic_simple_server_backend_for_test(backend); } protected: void SendResponse() override { send_response_was_called_ = true; QuicSimpleServerStream::SendResponse(); } void SendErrorResponse(int resp_code) override { send_error_response_was_called_ = true; QuicSimpleServerStream::SendErrorResponse(resp_code); } private: bool send_response_was_called_ = false; bool send_error_response_was_called_ = false; }; namespace { class MockQuicSimpleServerSession : public QuicSimpleServerSession { public: const size_t kMaxStreamsForTest = 100; MockQuicSimpleServerSession( QuicConnection* connection, MockQuicSessionVisitor* owner, MockQuicCryptoServerStreamHelper* helper, QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache, QuicSimpleServerBackend* quic_simple_server_backend) : QuicSimpleServerSession(DefaultQuicConfig(), CurrentSupportedVersions(), connection, owner, helper, crypto_config, compressed_certs_cache, quic_simple_server_backend) { if (VersionHasIetfQuicFrames(connection->transport_version())) { QuicSessionPeer::SetMaxOpenIncomingUnidirectionalStreams( this, kMaxStreamsForTest); QuicSessionPeer::SetMaxOpenIncomingBidirectionalStreams( this, kMaxStreamsForTest); } else { QuicSessionPeer::SetMaxOpenIncomingStreams(this, kMaxStreamsForTest); QuicSessionPeer::SetMaxOpenOutgoingStreams(this, kMaxStreamsForTest); } ON_CALL(*this, WritevData(_, _, _, _, _, _)) .WillByDefault(Invoke(this, &MockQuicSimpleServerSession::ConsumeData)); } MockQuicSimpleServerSession(const MockQuicSimpleServerSession&) = delete; MockQuicSimpleServerSession& operator=(const MockQuicSimpleServerSession&) = delete; ~MockQuicSimpleServerSession() override = default; MOCK_METHOD(void, OnConnectionClosed, (const QuicConnectionCloseFrame& frame, ConnectionCloseSource source), (override)); MOCK_METHOD(QuicSpdyStream*, CreateIncomingStream, (QuicStreamId id), (override)); MOCK_METHOD(QuicConsumedData, WritevData, (QuicStreamId id, size_t write_length, QuicStreamOffset offset, StreamSendingState state, TransmissionType type, EncryptionLevel level), (override)); MOCK_METHOD(void, OnStreamHeaderList, (QuicStreamId stream_id, bool fin, size_t frame_len, const QuicHeaderList& header_list), (override)); MOCK_METHOD(void, OnStreamHeadersPriority, (QuicStreamId stream_id, const spdy::SpdyStreamPrecedence& precedence), (override)); MOCK_METHOD(void, MaybeSendRstStreamFrame, (QuicStreamId stream_id, QuicResetStreamError error, QuicStreamOffset bytes_written), (override)); MOCK_METHOD(void, MaybeSendStopSendingFrame, (QuicStreamId stream_id, QuicResetStreamError error), (override)); using QuicSession::ActivateStream; QuicConsumedData ConsumeData(QuicStreamId id, size_t write_length, QuicStreamOffset offset, StreamSendingState state, TransmissionType , std::optional<EncryptionLevel> ) { if (write_length > 0) { auto buf = std::make_unique<char[]>(write_length); QuicStream* stream = GetOrCreateStream(id); QUICHE_DCHECK(stream); QuicDataWriter writer(write_length, buf.get(), quiche::HOST_BYTE_ORDER); stream->WriteStreamData(offset, write_length, &writer); } else { QUICHE_DCHECK(state != NO_FIN); } return QuicConsumedData(write_length, state != NO_FIN); } quiche::HttpHeaderBlock original_request_headers_; }; class QuicSimpleServerStreamTest : public QuicTestWithParam<ParsedQuicVersion> { public: QuicSimpleServerStreamTest() : connection_(new StrictMock<MockQuicConnection>( &simulator_, simulator_.GetAlarmFactory(), Perspective::IS_SERVER, SupportedVersions(GetParam()))), crypto_config_(new QuicCryptoServerConfig( QuicCryptoServerConfig::TESTING, QuicRandom::GetInstance(), crypto_test_utils::ProofSourceForTesting(), KeyExchangeSource::Default())), compressed_certs_cache_( QuicCompressedCertsCache::kQuicCompressedCertsCacheSize), session_(connection_, &session_owner_, &session_helper_, crypto_config_.get(), &compressed_certs_cache_, &memory_cache_backend_), quic_response_(new QuicBackendResponse), body_("hello world") { connection_->set_visitor(&session_); header_list_.OnHeader(":authority", "www.google.com"); header_list_.OnHeader(":path", "/"); header_list_.OnHeader(":method", "POST"); header_list_.OnHeader(":scheme", "https"); header_list_.OnHeader("content-length", "11"); header_list_.OnHeaderBlockEnd(128, 128); session_.config()->SetInitialStreamFlowControlWindowToSend( kInitialStreamFlowControlWindowForTest); session_.config()->SetInitialSessionFlowControlWindowToSend( kInitialSessionFlowControlWindowForTest); session_.Initialize(); connection_->SetEncrypter( quic::ENCRYPTION_FORWARD_SECURE, std::make_unique<quic::NullEncrypter>(connection_->perspective())); if (connection_->version().SupportsAntiAmplificationLimit()) { QuicConnectionPeer::SetAddressValidated(connection_); } stream_ = new StrictMock<TestStream>( GetNthClientInitiatedBidirectionalStreamId( connection_->transport_version(), 0), &session_, BIDIRECTIONAL, &memory_cache_backend_); session_.ActivateStream(absl::WrapUnique(stream_)); 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(); simulator_.RunFor(QuicTime::Delta::FromSeconds(1)); } const std::string& StreamBody() { return stream_->body(); } std::string StreamHeadersValue(const std::string& key) { return (*stream_->mutable_headers())[key].as_string(); } bool UsesHttp3() const { return VersionUsesHttp3(connection_->transport_version()); } void ReplaceBackend(std::unique_ptr<QuicSimpleServerBackend> backend) { replacement_backend_ = std::move(backend); stream_->ReplaceBackend(replacement_backend_.get()); } quic::simulator::Simulator simulator_; quiche::HttpHeaderBlock response_headers_; MockQuicConnectionHelper helper_; StrictMock<MockQuicConnection>* connection_; StrictMock<MockQuicSessionVisitor> session_owner_; StrictMock<MockQuicCryptoServerStreamHelper> session_helper_; std::unique_ptr<QuicCryptoServerConfig> crypto_config_; QuicCompressedCertsCache compressed_certs_cache_; QuicMemoryCacheBackend memory_cache_backend_; std::unique_ptr<QuicSimpleServerBackend> replacement_backend_; StrictMock<MockQuicSimpleServerSession> session_; StrictMock<TestStream>* stream_; std::unique_ptr<QuicBackendResponse> quic_response_; std::string body_; QuicHeaderList header_list_; }; INSTANTIATE_TEST_SUITE_P(Tests, QuicSimpleServerStreamTest, ::testing::ValuesIn(AllSupportedVersions()), ::testing::PrintToStringParamName()); TEST_P(QuicSimpleServerStreamTest, TestFraming) { EXPECT_CALL(session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly( Invoke(&session_, &MockQuicSimpleServerSession::ConsumeData)); stream_->OnStreamHeaderList(false, kFakeFrameLen, header_list_); quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader( body_.length(), quiche::SimpleBufferAllocator::Get()); std::string data = UsesHttp3() ? absl::StrCat(header.AsStringView(), body_) : body_; stream_->OnStreamFrame( QuicStreamFrame(stream_->id(), false, 0, data)); EXPECT_EQ("11", StreamHeadersValue("content-length")); EXPECT_EQ("/", StreamHeadersValue(":path")); EXPECT_EQ("POST", StreamHeadersValue(":method")); EXPECT_EQ(body_, StreamBody()); } TEST_P(QuicSimpleServerStreamTest, TestFramingOnePacket) { EXPECT_CALL(session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly( Invoke(&session_, &MockQuicSimpleServerSession::ConsumeData)); stream_->OnStreamHeaderList(false, kFakeFrameLen, header_list_); quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader( body_.length(), quiche::SimpleBufferAllocator::Get()); std::string data = UsesHttp3() ? absl::StrCat(header.AsStringView(), body_) : body_; stream_->OnStreamFrame( QuicStreamFrame(stream_->id(), false, 0, data)); EXPECT_EQ("11", StreamHeadersValue("content-length")); EXPECT_EQ("/", StreamHeadersValue(":path")); EXPECT_EQ("POST", StreamHeadersValue(":method")); EXPECT_EQ(body_, StreamBody()); } TEST_P(QuicSimpleServerStreamTest, SendQuicRstStreamNoErrorInStopReading) { EXPECT_CALL(session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly( Invoke(&session_, &MockQuicSimpleServerSession::ConsumeData)); EXPECT_FALSE(stream_->fin_received()); EXPECT_FALSE(stream_->rst_received()); QuicStreamPeer::SetFinSent(stream_); stream_->CloseWriteSide(); 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); } stream_->StopReading(); } TEST_P(QuicSimpleServerStreamTest, TestFramingExtraData) { InSequence seq; std::string large_body = "hello world!!!!!!"; EXPECT_CALL(*stream_, WriteHeadersMock(false)); if (UsesHttp3()) { EXPECT_CALL(session_, WritevData(_, kDataFrameHeaderLength, _, NO_FIN, _, _)); } EXPECT_CALL(session_, WritevData(_, kErrorLength, _, FIN, _, _)); stream_->OnStreamHeaderList(false, kFakeFrameLen, header_list_); quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader( body_.length(), quiche::SimpleBufferAllocator::Get()); std::string data = UsesHttp3() ? absl::StrCat(header.AsStringView(), body_) : body_; stream_->OnStreamFrame( QuicStreamFrame(stream_->id(), false, 0, data)); header = HttpEncoder::SerializeDataFrameHeader( large_body.length(), quiche::SimpleBufferAllocator::Get()); std::string data2 = UsesHttp3() ? absl::StrCat(header.AsStringView(), large_body) : large_body; stream_->OnStreamFrame( QuicStreamFrame(stream_->id(), true, data.size(), data2)); EXPECT_EQ("11", StreamHeadersValue("content-length")); EXPECT_EQ("/", StreamHeadersValue(":path")); EXPECT_EQ("POST", StreamHeadersValue(":method")); } TEST_P(QuicSimpleServerStreamTest, SendResponseWithIllegalResponseStatus) { quiche::HttpHeaderBlock* request_headers = stream_->mutable_headers(); (*request_headers)[":path"] = "/bar"; (*request_headers)[":authority"] = "www.google.com"; (*request_headers)[":method"] = "GET"; response_headers_[":status"] = "200 OK"; response_headers_["content-length"] = "5"; std::string body = "Yummm"; quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader( body.length(), quiche::SimpleBufferAllocator::Get()); memory_cache_backend_.AddResponse("www.google.com", "/bar", std::move(response_headers_), body); QuicStreamPeer::SetFinReceived(stream_); InSequence s; EXPECT_CALL(*stream_, WriteHeadersMock(false)); if (UsesHttp3()) { EXPECT_CALL(session_, WritevData(_, header.size(), _, NO_FIN, _, _)); } EXPECT_CALL(session_, WritevData(_, kErrorLength, _, FIN, _, _)); stream_->DoSendResponse(); EXPECT_FALSE(QuicStreamPeer::read_side_closed(stream_)); EXPECT_TRUE(stream_->write_side_closed()); } TEST_P(QuicSimpleServerStreamTest, SendResponseWithIllegalResponseStatus2) { quiche::HttpHeaderBlock* request_headers = stream_->mutable_headers(); (*request_headers)[":path"] = "/bar"; (*request_headers)[":authority"] = "www.google.com"; (*request_headers)[":method"] = "GET"; response_headers_[":status"] = "+200"; response_headers_["content-length"] = "5"; std::string body = "Yummm"; quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader( body.length(), quiche::SimpleBufferAllocator::Get()); memory_cache_backend_.AddResponse("www.google.com", "/bar", std::move(response_headers_), body); QuicStreamPeer::SetFinReceived(stream_); InSequence s; EXPECT_CALL(*stream_, WriteHeadersMock(false)); if (UsesHttp3()) { EXPECT_CALL(session_, WritevData(_, header.size(), _, NO_FIN, _, _)); } EXPECT_CALL(session_, WritevData(_, kErrorLength, _, FIN, _, _)); stream_->DoSendResponse(); EXPECT_FALSE(QuicStreamPeer::read_side_closed(stream_)); EXPECT_TRUE(stream_->write_side_closed()); } TEST_P(QuicSimpleServerStreamTest, SendResponseWithValidHeaders) { quiche::HttpHeaderBlock* request_headers = stream_->mutable_headers(); (*request_headers)[":path"] = "/bar"; (*request_headers)[":authority"] = "www.google.com"; (*request_headers)[":method"] = "GET"; response_headers_[":status"] = "200"; response_headers_["content-length"] = "5"; std::string body = "Yummm"; quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader( body.length(), quiche::SimpleBufferAllocator::Get()); memory_cache_backend_.AddResponse("www.google.com", "/bar", std::move(response_headers_), body); QuicStreamPeer::SetFinReceived(stream_); InSequence s; EXPECT_CALL(*stream_, WriteHeadersMock(false)); if (UsesHttp3()) { EXPECT_CALL(session_, WritevData(_, header.size(), _, NO_FIN, _, _)); } EXPECT_CALL(session_, WritevData(_, body.length(), _, FIN, _, _)); stream_->DoSendResponse(); EXPECT_FALSE(QuicStreamPeer::read_side_closed(stream_)); EXPECT_TRUE(stream_->write_side_closed()); } TEST_P(QuicSimpleServerStreamTest, SendResponseWithEarlyHints) { std::string host = "www.google.com"; std::string request_path = "/foo"; std::string body = "Yummm"; quiche::HttpHeaderBlock* request_headers = stream_->mutable_headers(); (*request_headers)[":path"] = request_path; (*request_headers)[":authority"] = host; (*request_headers)[":method"] = "GET"; quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader( body.length(), quiche::SimpleBufferAllocator::Get()); std::vector<quiche::HttpHeaderBlock> early_hints; const size_t kNumEarlyHintsResponses = 2; for (size_t i = 0; i < kNumEarlyHintsResponses; ++i) { quiche::HttpHeaderBlock hints; hints["link"] = "</image.png>; rel=preload; as=image"; early_hints.push_back(std::move(hints)); } response_headers_[":status"] = "200"; response_headers_["content-length"] = "5"; memory_cache_backend_.AddResponseWithEarlyHints( host, request_path, std::move(response_headers_), body, early_hints); QuicStreamPeer::SetFinReceived(stream_); InSequence s; for (size_t i = 0; i < kNumEarlyHintsResponses; ++i) { EXPECT_CALL(*stream_, WriteEarlyHintsHeadersMock(false)); } EXPECT_CALL(*stream_, WriteHeadersMock(false)); if (UsesHttp3()) { EXPECT_CALL(session_, WritevData(_, header.size(), _, NO_FIN, _, _)); } EXPECT_CALL(session_, WritevData(_, body.length(), _, FIN, _, _)); stream_->DoSendResponse(); EXPECT_FALSE(QuicStreamPeer::read_side_closed(stream_)); EXPECT_TRUE(stream_->write_side_closed()); } class AlarmTestDelegate : public QuicAlarm::DelegateWithoutContext { public: AlarmTestDelegate(TestStream* stream) : stream_(stream) {} void OnAlarm() override { stream_->FireAlarmMock(); } private: TestStream* stream_; }; TEST_P(QuicSimpleServerStreamTest, SendResponseWithDelay) { quiche::HttpHeaderBlock* request_headers = stream_->mutable_headers(); std::string host = "www.google.com"; std::string path = "/bar"; (*request_headers)[":path"] = path; (*request_headers)[":authority"] = host; (*request_headers)[":method"] = "GET"; response_headers_[":status"] = "200"; response_headers_["content-length"] = "5"; std::string body = "Yummm"; QuicTime::Delta delay = QuicTime::Delta::FromMilliseconds(3000); quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader( body.length(), quiche::SimpleBufferAllocator::Get()); memory_cache_backend_.AddResponse(host, path, std::move(response_headers_), body); auto did_delay_succeed = memory_cache_backend_.SetResponseDelay(host, path, delay); EXPECT_TRUE(did_delay_succeed); auto did_invalid_delay_succeed = memory_cache_backend_.SetResponseDelay(host, "nonsense", delay); EXPECT_FALSE(did_invalid_delay_succeed); std::unique_ptr<QuicAlarm> alarm(connection_->alarm_factory()->CreateAlarm( new AlarmTestDelegate(stream_))); alarm->Set(connection_->clock()->Now() + delay); QuicStreamPeer::SetFinReceived(stream_); InSequence s; EXPECT_CALL(*stream_, FireAlarmMock()); EXPECT_CALL(*stream_, WriteHeadersMock(false)); if (UsesHttp3()) { EXPECT_CALL(session_, WritevData(_, header.size(), _, NO_FIN, _, _)); } EXPECT_CALL(session_, WritevData(_, body.length(), _, FIN, _, _)); stream_->DoSendResponse(); simulator_.RunFor(delay); EXPECT_FALSE(QuicStreamPeer::read_side_closed(stream_)); EXPECT_TRUE(stream_->write_side_closed()); } TEST_P(QuicSimpleServerStreamTest, TestSendErrorResponse) { QuicStreamPeer::SetFinReceived(stream_); InSequence s; EXPECT_CALL(*stream_, WriteHeadersMock(false)); if (UsesHttp3()) { EXPECT_CALL(session_, WritevData(_, kDataFrameHeaderLength, _, NO_FIN, _, _)); } EXPECT_CALL(session_, WritevData(_, kErrorLength, _, FIN, _, _)); stream_->DoSendErrorResponse(); EXPECT_FALSE(QuicStreamPeer::read_side_closed(stream_)); EXPECT_TRUE(stream_->write_side_closed()); } TEST_P(QuicSimpleServerStreamTest, InvalidMultipleContentLength) { quiche::HttpHeaderBlock request_headers; header_list_.OnHeader("content-length", absl::string_view("11\00012", 5)); if (session_.version().UsesHttp3()) { EXPECT_CALL(session_, MaybeSendStopSendingFrame(_, QuicResetStreamError::FromInternal( QUIC_STREAM_NO_ERROR))); } EXPECT_CALL(*stream_, WriteHeadersMock(false)); EXPECT_CALL(session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly( Invoke(&session_, &MockQuicSimpleServerSession::ConsumeData)); stream_->OnStreamHeaderList(true, kFakeFrameLen, header_list_); EXPECT_TRUE(QuicStreamPeer::read_side_closed(stream_)); EXPECT_TRUE(stream_->reading_stopped()); EXPECT_TRUE(stream_->write_side_closed()); } TEST_P(QuicSimpleServerStreamTest, InvalidLeadingNullContentLength) { quiche::HttpHeaderBlock request_headers; header_list_.OnHeader("content-length", absl::string_view("\00012", 3)); if (session_.version().UsesHttp3()) { EXPECT_CALL(session_, MaybeSendStopSendingFrame(_, QuicResetStreamError::FromInternal( QUIC_STREAM_NO_ERROR))); } EXPECT_CALL(*stream_, WriteHeadersMock(false)); EXPECT_CALL(session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly( Invoke(&session_, &MockQuicSimpleServerSession::ConsumeData)); stream_->OnStreamHeaderList(true, kFakeFrameLen, header_list_); EXPECT_TRUE(QuicStreamPeer::read_side_closed(stream_)); EXPECT_TRUE(stream_->reading_stopped()); EXPECT_TRUE(stream_->write_side_closed()); } TEST_P(QuicSimpleServerStreamTest, InvalidMultipleContentLengthII) { quiche::HttpHeaderBlock request_headers; header_list_.OnHeader("content-length", absl::string_view("11\00011", 5)); if (session_.version().UsesHttp3()) { EXPECT_CALL(session_, MaybeSendStopSendingFrame(_, QuicResetStreamError::FromInternal( QUIC_STREAM_NO_ERROR))); EXPECT_CALL(*stream_, WriteHeadersMock(false)); EXPECT_CALL(session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly( Invoke(&session_, &MockQuicSimpleServerSession::ConsumeData)); } stream_->OnStreamHeaderList(false, kFakeFrameLen, header_list_); if (session_.version().UsesHttp3()) { EXPECT_TRUE(QuicStreamPeer::read_side_closed(stream_)); EXPECT_TRUE(stream_->reading_stopped()); EXPECT_TRUE(stream_->write_side_closed()); } else { EXPECT_EQ(11, stream_->content_length()); EXPECT_FALSE(QuicStreamPeer::read_side_closed(stream_)); EXPECT_FALSE(stream_->reading_stopped()); EXPECT_FALSE(stream_->write_side_closed()); } } TEST_P(QuicSimpleServerStreamTest, DoNotSendQuicRstStreamNoErrorWithRstReceived) { EXPECT_FALSE(stream_->reading_stopped()); if (VersionUsesHttp3(connection_->transport_version())) { auto* qpack_decoder_stream = QuicSpdySessionPeer::GetQpackDecoderSendStream(&session_); EXPECT_CALL(session_, WritevData(qpack_decoder_stream->id(), _, _, _, _, _)) .Times(AnyNumber()); } EXPECT_CALL( session_, MaybeSendRstStreamFrame( _, session_.version().UsesHttp3() ? QuicResetStreamError::FromInternal(QUIC_STREAM_CANCELLED) : QuicResetStreamError::FromInternal(QUIC_RST_ACKNOWLEDGEMENT), _)) .Times(1); QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream_->id(), QUIC_STREAM_CANCELLED, 1234); stream_->OnStreamReset(rst_frame); if (VersionHasIetfQuicFrames(connection_->transport_version())) { EXPECT_CALL(session_owner_, OnStopSendingReceived(_)); 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_P(QuicSimpleServerStreamTest, InvalidHeadersWithFin) { char arr[] = { 0x3a, 0x68, 0x6f, 0x73, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x3a, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x00, 0x00, 0x00, 0x03, 0x47, 0x45, 0x54, 0x00, 0x00, 0x00, 0x05, 0x3a, 0x70, 0x61, 0x74, 0x68, 0x00, 0x00, 0x00, 0x04, 0x2f, 0x66, 0x6f, 0x6f, 0x00, 0x00, 0x00, 0x07, 0x3a, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x3a, 0x76, 0x65, 0x72, 0x73, '\x96', 0x6f, 0x6e, 0x00, 0x00, 0x00, 0x08, 0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x31, }; absl::string_view data(arr, ABSL_ARRAYSIZE(arr)); QuicStreamFrame frame(stream_->id(), true, 0, data); stream_->OnStreamFrame(frame); } class TestQuicSimpleServerBackend : public QuicSimpleServerBackend { public: TestQuicSimpleServerBackend() = default; ~TestQuicSimpleServerBackend() override = default; bool InitializeBackend(const std::string& ) override { return true; } bool IsBackendInitialized() const override { return true; } MOCK_METHOD(void, FetchResponseFromBackend, (const quiche::HttpHeaderBlock&, const std::string&, RequestHandler*), (override)); MOCK_METHOD(void, HandleConnectHeaders, (const quiche::HttpHeaderBlock&, RequestHandler*), (override)); MOCK_METHOD(void, HandleConnectData, (absl::string_view, bool, RequestHandler*), (override)); void CloseBackendResponseStream( RequestHandler* ) override {} }; ACTION_P(SendHeadersResponse, response_ptr) { arg1->OnResponseBackendComplete(response_ptr); } ACTION_P(SendStreamData, data, close_stream) { arg2->SendStreamData(data, close_stream); } ACTION_P(TerminateStream, error) { arg1->TerminateStreamWithError(error); } TEST_P(QuicSimpleServerStreamTest, ConnectSendsIntermediateResponses) { auto test_backend = std::make_unique<TestQuicSimpleServerBackend>(); TestQuicSimpleServerBackend* test_backend_ptr = test_backend.get(); ReplaceBackend(std::move(test_backend)); constexpr absl::string_view kRequestBody = "\x11\x11"; quiche::HttpHeaderBlock response_headers; response_headers[":status"] = "200"; QuicBackendResponse headers_response; headers_response.set_headers(response_headers.Clone()); headers_response.set_response_type(QuicBackendResponse::INCOMPLETE_RESPONSE); constexpr absl::string_view kBody1 = "\x22\x22"; constexpr absl::string_view kBody2 = "\x33\x33"; InSequence s; EXPECT_CALL(*test_backend_ptr, HandleConnectHeaders(_, _)) .WillOnce(SendHeadersResponse(&headers_response)); EXPECT_CALL(*stream_, WriteHeadersMock(false)); EXPECT_CALL(*test_backend_ptr, HandleConnectData(kRequestBody, false, _)) .WillOnce(SendStreamData(kBody1, false)); EXPECT_CALL(*stream_, WriteOrBufferBody(kBody1, false)); EXPECT_CALL(*test_backend_ptr, HandleConnectData(kRequestBody, true, _)) .WillOnce(SendStreamData(kBody2, true)); EXPECT_CALL(*stream_, WriteOrBufferBody(kBody2, true)); QuicHeaderList header_list; header_list.OnHeader(":authority", "www.google.com:4433"); header_list.OnHeader(":method", "CONNECT"); header_list.OnHeaderBlockEnd(128, 128); stream_->OnStreamHeaderList(false, kFakeFrameLen, header_list); quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader( kRequestBody.length(), quiche::SimpleBufferAllocator::Get()); std::string data = UsesHttp3() ? absl::StrCat(header.AsStringView(), kRequestBody) : std::string(kRequestBody); stream_->OnStreamFrame( QuicStreamFrame(stream_->id(), false, 0, data)); stream_->OnStreamFrame( QuicStreamFrame(stream_->id(), true, data.length(), data)); EXPECT_FALSE(stream_->send_response_was_called()); EXPECT_FALSE(stream_->send_error_response_was_called()); } TEST_P(QuicSimpleServerStreamTest, ErrorOnUnhandledConnect) { EXPECT_CALL(*stream_, WriteHeadersMock(true)); EXPECT_CALL(session_, MaybeSendRstStreamFrame(stream_->id(), _, _)); QuicHeaderList header_list; header_list.OnHeader(":authority", "www.google.com:4433"); header_list.OnHeader(":method", "CONNECT"); header_list.OnHeaderBlockEnd(128, 128); constexpr absl::string_view kRequestBody = "\x11\x11"; stream_->OnStreamHeaderList(false, kFakeFrameLen, header_list); quiche::QuicheBuffer header = HttpEncoder::SerializeDataFrameHeader( kRequestBody.length(), quiche::SimpleBufferAllocator::Get()); std::string data = UsesHttp3() ? absl::StrCat(header.AsStringView(), kRequestBody) : std::string(kRequestBody); stream_->OnStreamFrame( QuicStreamFrame(stream_->id(), true, 0, data)); EXPECT_FALSE(stream_->send_response_was_called()); EXPECT_FALSE(stream_->send_error_response_was_called()); } TEST_P(QuicSimpleServerStreamTest, ConnectWithInvalidHeader) { EXPECT_CALL(session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly( Invoke(&session_, &MockQuicSimpleServerSession::ConsumeData)); QuicHeaderList header_list; header_list.OnHeader(":authority", "www.google.com:4433"); header_list.OnHeader(":method", "CONNECT"); header_list.OnHeader("InVaLiD-HeAdEr", "Well that's just wrong!"); header_list.OnHeaderBlockEnd(128, 128); if (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); } EXPECT_CALL(*stream_, WriteHeadersMock(false)); stream_->OnStreamHeaderList(false, kFakeFrameLen, header_list); EXPECT_FALSE(stream_->send_response_was_called()); EXPECT_TRUE(stream_->send_error_response_was_called()); } TEST_P(QuicSimpleServerStreamTest, BackendCanTerminateStream) { auto test_backend = std::make_unique<TestQuicSimpleServerBackend>(); TestQuicSimpleServerBackend* test_backend_ptr = test_backend.get(); ReplaceBackend(std::move(test_backend)); EXPECT_CALL(session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly( Invoke(&session_, &MockQuicSimpleServerSession::ConsumeData)); QuicResetStreamError expected_error = QuicResetStreamError::FromInternal(QUIC_STREAM_CONNECT_ERROR); EXPECT_CALL(*test_backend_ptr, HandleConnectHeaders(_, _)) .WillOnce(TerminateStream(expected_error)); EXPECT_CALL(session_, MaybeSendRstStreamFrame(stream_->id(), expected_error, _)); QuicHeaderList header_list; header_list.OnHeader(":authority", "www.google.com:4433"); header_list.OnHeader(":method", "CONNECT"); header_list.OnHeaderBlockEnd(128, 128); stream_->OnStreamHeaderList(false, kFakeFrameLen, header_list); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/tools/quic_simple_server_stream.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/tools/quic_simple_server_stream_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
23e3a29e-ec56-4902-a008-341d667cbec3
cpp
google/quiche
connect_udp_tunnel
quiche/quic/tools/connect_udp_tunnel.cc
quiche/quic/tools/connect_udp_tunnel_test.cc
#include "quiche/quic/tools/connect_udp_tunnel.h" #include <cstdint> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_server_id.h" #include "quiche/quic/core/socket_factory.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/tools/quic_backend_response.h" #include "quiche/quic/tools/quic_name_lookup.h" #include "quiche/quic/tools/quic_simple_server_backend.h" #include "quiche/common/http/http_header_block.h" #include "quiche/common/masque/connect_udp_datagram_payload.h" #include "quiche/common/platform/api/quiche_googleurl.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_mem_slice.h" #include "quiche/common/platform/api/quiche_url_utils.h" #include "quiche/common/structured_headers.h" namespace quic { namespace structured_headers = quiche::structured_headers; namespace { constexpr size_t kReadSize = 4 * 1024; std::optional<QuicServerId> ValidateAndParseTargetFromPath( absl::string_view path) { std::string canonicalized_path_str; url::StdStringCanonOutput canon_output(&canonicalized_path_str); url::Component path_component; url::CanonicalizePath(path.data(), url::Component(0, path.size()), &canon_output, &path_component); if (!path_component.is_nonempty()) { QUICHE_DVLOG(1) << "CONNECT-UDP request with non-canonicalizable path: " << path; return std::nullopt; } canon_output.Complete(); absl::string_view canonicalized_path = absl::string_view(canonicalized_path_str) .substr(path_component.begin, path_component.len); std::vector<absl::string_view> path_split = absl::StrSplit(canonicalized_path, '/'); if (path_split.size() != 7 || !path_split[0].empty() || path_split[1] != ".well-known" || path_split[2] != "masque" || path_split[3] != "udp" || path_split[4].empty() || path_split[5].empty() || !path_split[6].empty()) { QUICHE_DVLOG(1) << "CONNECT-UDP request with bad path: " << canonicalized_path; return std::nullopt; } std::optional<std::string> decoded_host = quiche::AsciiUrlDecode(path_split[4]); if (!decoded_host.has_value()) { QUICHE_DVLOG(1) << "CONNECT-UDP request with undecodable host: " << path_split[4]; return std::nullopt; } QUICHE_DCHECK(!decoded_host->empty()); std::optional<std::string> decoded_port = quiche::AsciiUrlDecode(path_split[5]); if (!decoded_port.has_value()) { QUICHE_DVLOG(1) << "CONNECT-UDP request with undecodable port: " << path_split[5]; return std::nullopt; } QUICHE_DCHECK(!decoded_port->empty()); int parsed_port_number = url::ParsePort( decoded_port->data(), url::Component(0, decoded_port->size())); if (parsed_port_number <= 0) { QUICHE_DVLOG(1) << "CONNECT-UDP request with bad port: " << *decoded_port; return std::nullopt; } QUICHE_DCHECK_LE(parsed_port_number, std::numeric_limits<uint16_t>::max()); return QuicServerId(*decoded_host, static_cast<uint16_t>(parsed_port_number)); } std::optional<QuicServerId> ValidateHeadersAndGetTarget( const quiche::HttpHeaderBlock& request_headers) { QUICHE_DCHECK(request_headers.contains(":method")); QUICHE_DCHECK(request_headers.find(":method")->second == "CONNECT"); QUICHE_DCHECK(request_headers.contains(":protocol")); QUICHE_DCHECK(request_headers.find(":protocol")->second == "connect-udp"); auto authority_it = request_headers.find(":authority"); if (authority_it == request_headers.end() || authority_it->second.empty()) { QUICHE_DVLOG(1) << "CONNECT-UDP request missing authority"; return std::nullopt; } auto scheme_it = request_headers.find(":scheme"); if (scheme_it == request_headers.end() || scheme_it->second.empty()) { QUICHE_DVLOG(1) << "CONNECT-UDP request missing scheme"; return std::nullopt; } else if (scheme_it->second != "https") { QUICHE_DVLOG(1) << "CONNECT-UDP request contains unexpected scheme: " << scheme_it->second; return std::nullopt; } auto path_it = request_headers.find(":path"); if (path_it == request_headers.end() || path_it->second.empty()) { QUICHE_DVLOG(1) << "CONNECT-UDP request missing path"; return std::nullopt; } std::optional<QuicServerId> target_server_id = ValidateAndParseTargetFromPath(path_it->second); return target_server_id; } bool ValidateTarget( const QuicServerId& target, const absl::flat_hash_set<QuicServerId>& acceptable_targets) { if (acceptable_targets.contains(target)) { return true; } QUICHE_DVLOG(1) << "CONNECT-UDP request target is not an acceptable allow-listed target: " << target.ToHostPortString(); return false; } } ConnectUdpTunnel::ConnectUdpTunnel( QuicSimpleServerBackend::RequestHandler* client_stream_request_handler, SocketFactory* socket_factory, std::string server_label, absl::flat_hash_set<QuicServerId> acceptable_targets) : acceptable_targets_(std::move(acceptable_targets)), socket_factory_(socket_factory), server_label_(std::move(server_label)), client_stream_request_handler_(client_stream_request_handler) { QUICHE_DCHECK(client_stream_request_handler_); QUICHE_DCHECK(socket_factory_); QUICHE_DCHECK(!server_label_.empty()); } ConnectUdpTunnel::~ConnectUdpTunnel() { QUICHE_DCHECK(!IsTunnelOpenToTarget()); QUICHE_DCHECK(!receive_started_); QUICHE_DCHECK(!datagram_visitor_registered_); } void ConnectUdpTunnel::OpenTunnel( const quiche::HttpHeaderBlock& request_headers) { QUICHE_DCHECK(!IsTunnelOpenToTarget()); std::optional<QuicServerId> target = ValidateHeadersAndGetTarget(request_headers); if (!target.has_value()) { TerminateClientStream( "invalid request headers", QuicResetStreamError::FromIetf(QuicHttp3ErrorCode::MESSAGE_ERROR)); return; } if (!ValidateTarget(*target, acceptable_targets_)) { SendErrorResponse("403", "destination_ip_prohibited", "disallowed proxy target"); return; } QuicSocketAddress address = tools::LookupAddress(AF_UNSPEC, *target); if (!address.IsInitialized()) { SendErrorResponse("500", "dns_error", "host resolution error"); return; } target_socket_ = socket_factory_->CreateConnectingUdpClientSocket( address, 0, 0, this); QUICHE_DCHECK(target_socket_); absl::Status connect_result = target_socket_->ConnectBlocking(); if (!connect_result.ok()) { SendErrorResponse( "502", "destination_ip_unroutable", absl::StrCat("UDP socket error: ", connect_result.ToString())); return; } QUICHE_DVLOG(1) << "CONNECT-UDP tunnel opened from stream " << client_stream_request_handler_->stream_id() << " to " << target->ToHostPortString(); client_stream_request_handler_->GetStream()->RegisterHttp3DatagramVisitor( this); datagram_visitor_registered_ = true; SendConnectResponse(); BeginAsyncReadFromTarget(); } bool ConnectUdpTunnel::IsTunnelOpenToTarget() const { return !!target_socket_; } void ConnectUdpTunnel::OnClientStreamClose() { QUICHE_CHECK(client_stream_request_handler_); QUICHE_DVLOG(1) << "CONNECT-UDP stream " << client_stream_request_handler_->stream_id() << " closed"; if (datagram_visitor_registered_) { client_stream_request_handler_->GetStream() ->UnregisterHttp3DatagramVisitor(); datagram_visitor_registered_ = false; } client_stream_request_handler_ = nullptr; if (IsTunnelOpenToTarget()) { target_socket_->Disconnect(); } target_socket_.reset(); } void ConnectUdpTunnel::ConnectComplete(absl::Status ) { QUICHE_NOTREACHED(); } void ConnectUdpTunnel::ReceiveComplete( absl::StatusOr<quiche::QuicheMemSlice> data) { QUICHE_DCHECK(IsTunnelOpenToTarget()); QUICHE_DCHECK(receive_started_); receive_started_ = false; if (!data.ok()) { if (client_stream_request_handler_) { QUICHE_LOG(WARNING) << "Error receiving CONNECT-UDP data from target: " << data.status(); } else { QUICHE_DVLOG(1) << "Error receiving CONNECT-UDP data from target after " "stream already closed."; } return; } QUICHE_DCHECK(client_stream_request_handler_); quiche::ConnectUdpDatagramUdpPacketPayload payload(data->AsStringView()); client_stream_request_handler_->GetStream()->SendHttp3Datagram( payload.Serialize()); BeginAsyncReadFromTarget(); } void ConnectUdpTunnel::SendComplete(absl::Status ) { QUICHE_NOTREACHED(); } void ConnectUdpTunnel::OnHttp3Datagram(QuicStreamId stream_id, absl::string_view payload) { QUICHE_DCHECK(IsTunnelOpenToTarget()); QUICHE_DCHECK_EQ(stream_id, client_stream_request_handler_->stream_id()); QUICHE_DCHECK(!payload.empty()); std::unique_ptr<quiche::ConnectUdpDatagramPayload> parsed_payload = quiche::ConnectUdpDatagramPayload::Parse(payload); if (!parsed_payload) { QUICHE_DVLOG(1) << "Ignoring HTTP Datagram payload, due to inability to " "parse as CONNECT-UDP payload."; return; } switch (parsed_payload->GetType()) { case quiche::ConnectUdpDatagramPayload::Type::kUdpPacket: SendUdpPacketToTarget(parsed_payload->GetUdpProxyingPayload()); break; case quiche::ConnectUdpDatagramPayload::Type::kUnknown: QUICHE_DVLOG(1) << "Ignoring HTTP Datagram payload with unrecognized context ID."; } } void ConnectUdpTunnel::BeginAsyncReadFromTarget() { QUICHE_DCHECK(IsTunnelOpenToTarget()); QUICHE_DCHECK(client_stream_request_handler_); QUICHE_DCHECK(!receive_started_); receive_started_ = true; target_socket_->ReceiveAsync(kReadSize); } void ConnectUdpTunnel::SendUdpPacketToTarget(absl::string_view packet) { absl::Status send_result = target_socket_->SendBlocking(std::string(packet)); if (!send_result.ok()) { QUICHE_LOG(WARNING) << "Error sending CONNECT-UDP datagram to target: " << send_result; } } void ConnectUdpTunnel::SendConnectResponse() { QUICHE_DCHECK(IsTunnelOpenToTarget()); QUICHE_DCHECK(client_stream_request_handler_); quiche::HttpHeaderBlock response_headers; response_headers[":status"] = "200"; std::optional<std::string> capsule_protocol_value = structured_headers::SerializeItem(structured_headers::Item(true)); QUICHE_CHECK(capsule_protocol_value.has_value()); response_headers["Capsule-Protocol"] = *capsule_protocol_value; QuicBackendResponse response; response.set_headers(std::move(response_headers)); response.set_response_type(QuicBackendResponse::INCOMPLETE_RESPONSE); client_stream_request_handler_->OnResponseBackendComplete(&response); } void ConnectUdpTunnel::SendErrorResponse(absl::string_view status, absl::string_view proxy_status_error, absl::string_view error_details) { QUICHE_DCHECK(!status.empty()); QUICHE_DCHECK(!proxy_status_error.empty()); QUICHE_DCHECK(!error_details.empty()); QUICHE_DCHECK(client_stream_request_handler_); #ifndef NDEBUG int status_num = 0; bool is_num = absl::SimpleAtoi(status, &status_num); QUICHE_DCHECK(is_num); QUICHE_DCHECK_GE(status_num, 100); QUICHE_DCHECK_LT(status_num, 600); QUICHE_DCHECK(status_num < 200 || status_num >= 300); #endif quiche::HttpHeaderBlock headers; headers[":status"] = status; structured_headers::Item proxy_status_item(server_label_); structured_headers::Item proxy_status_error_item( std::string{proxy_status_error}); structured_headers::Item proxy_status_details_item( std::string{error_details}); structured_headers::ParameterizedMember proxy_status_member( std::move(proxy_status_item), {{"error", std::move(proxy_status_error_item)}, {"details", std::move(proxy_status_details_item)}}); std::optional<std::string> proxy_status_value = structured_headers::SerializeList({proxy_status_member}); QUICHE_CHECK(proxy_status_value.has_value()); headers["Proxy-Status"] = *proxy_status_value; QuicBackendResponse response; response.set_headers(std::move(headers)); client_stream_request_handler_->OnResponseBackendComplete(&response); } void ConnectUdpTunnel::TerminateClientStream( absl::string_view error_description, QuicResetStreamError error_code) { QUICHE_DCHECK(client_stream_request_handler_); std::string error_description_str = error_description.empty() ? "" : absl::StrCat(" due to ", error_description); QUICHE_DVLOG(1) << "Terminating CONNECT stream " << client_stream_request_handler_->stream_id() << " with error code " << error_code.ietf_application_code() << error_description_str; client_stream_request_handler_->TerminateStreamWithError(error_code); } }
#include "quiche/quic/tools/connect_udp_tunnel.h" #include <memory> #include <string> #include <utility> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/connecting_client_socket.h" #include "quiche/quic/core/http/quic_spdy_stream.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/socket_factory.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/platform/api/quic_test_loopback.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/tools/quic_simple_server_backend.h" #include "quiche/common/masque/connect_udp_datagram_payload.h" #include "quiche/common/platform/api/quiche_googleurl.h" #include "quiche/common/platform/api/quiche_mem_slice.h" #include "quiche/common/platform/api/quiche_test.h" #include "quiche/common/platform/api/quiche_url_utils.h" namespace quic::test { namespace { using ::testing::_; using ::testing::AnyOf; using ::testing::Eq; using ::testing::Ge; using ::testing::Gt; using ::testing::HasSubstr; using ::testing::InvokeWithoutArgs; using ::testing::IsEmpty; using ::testing::Matcher; using ::testing::NiceMock; using ::testing::Pair; using ::testing::Property; using ::testing::Return; using ::testing::StrictMock; using ::testing::UnorderedElementsAre; constexpr QuicStreamId kStreamId = 100; class MockStream : public QuicSpdyStream { public: explicit MockStream(QuicSpdySession* spdy_session) : QuicSpdyStream(kStreamId, spdy_session, BIDIRECTIONAL) {} void OnBodyAvailable() override {} MOCK_METHOD(MessageStatus, SendHttp3Datagram, (absl::string_view data), (override)); }; class MockRequestHandler : public QuicSimpleServerBackend::RequestHandler { public: QuicConnectionId connection_id() const override { return TestConnectionId(41212); } QuicStreamId stream_id() const override { return kStreamId; } std::string peer_host() const override { return "127.0.0.1"; } MOCK_METHOD(QuicSpdyStream*, GetStream, (), (override)); MOCK_METHOD(void, OnResponseBackendComplete, (const QuicBackendResponse* response), (override)); MOCK_METHOD(void, SendStreamData, (absl::string_view data, bool close_stream), (override)); MOCK_METHOD(void, TerminateStreamWithError, (QuicResetStreamError error), (override)); }; class MockSocketFactory : public SocketFactory { public: MOCK_METHOD(std::unique_ptr<ConnectingClientSocket>, CreateTcpClientSocket, (const QuicSocketAddress& peer_address, QuicByteCount receive_buffer_size, QuicByteCount send_buffer_size, ConnectingClientSocket::AsyncVisitor* async_visitor), (override)); MOCK_METHOD(std::unique_ptr<ConnectingClientSocket>, CreateConnectingUdpClientSocket, (const QuicSocketAddress& peer_address, QuicByteCount receive_buffer_size, QuicByteCount send_buffer_size, ConnectingClientSocket::AsyncVisitor* async_visitor), (override)); }; class MockSocket : public ConnectingClientSocket { public: MOCK_METHOD(absl::Status, ConnectBlocking, (), (override)); MOCK_METHOD(void, ConnectAsync, (), (override)); MOCK_METHOD(void, Disconnect, (), (override)); MOCK_METHOD(absl::StatusOr<QuicSocketAddress>, GetLocalAddress, (), (override)); MOCK_METHOD(absl::StatusOr<quiche::QuicheMemSlice>, ReceiveBlocking, (QuicByteCount max_size), (override)); MOCK_METHOD(void, ReceiveAsync, (QuicByteCount max_size), (override)); MOCK_METHOD(absl::Status, SendBlocking, (std::string data), (override)); MOCK_METHOD(absl::Status, SendBlocking, (quiche::QuicheMemSlice data), (override)); MOCK_METHOD(void, SendAsync, (std::string data), (override)); MOCK_METHOD(void, SendAsync, (quiche::QuicheMemSlice data), (override)); }; class ConnectUdpTunnelTest : public quiche::test::QuicheTest { public: void SetUp() override { #if defined(_WIN32) WSADATA wsa_data; const WORD version_required = MAKEWORD(2, 2); ASSERT_EQ(WSAStartup(version_required, &wsa_data), 0); #endif auto socket = std::make_unique<StrictMock<MockSocket>>(); socket_ = socket.get(); ON_CALL(socket_factory_, CreateConnectingUdpClientSocket( AnyOf(QuicSocketAddress(TestLoopback4(), kAcceptablePort), QuicSocketAddress(TestLoopback6(), kAcceptablePort)), _, _, &tunnel_)) .WillByDefault(Return(ByMove(std::move(socket)))); EXPECT_CALL(request_handler_, GetStream()).WillRepeatedly(Return(&stream_)); } protected: static constexpr absl::string_view kAcceptableTarget = "localhost"; static constexpr uint16_t kAcceptablePort = 977; NiceMock<MockQuicConnectionHelper> connection_helper_; NiceMock<MockAlarmFactory> alarm_factory_; NiceMock<MockQuicSpdySession> session_{new NiceMock<MockQuicConnection>( &connection_helper_, &alarm_factory_, Perspective::IS_SERVER)}; StrictMock<MockStream> stream_{&session_}; StrictMock<MockRequestHandler> request_handler_; NiceMock<MockSocketFactory> socket_factory_; StrictMock<MockSocket>* socket_; ConnectUdpTunnel tunnel_{ &request_handler_, &socket_factory_, "server_label", {{std::string(kAcceptableTarget), kAcceptablePort}, {TestLoopback4().ToString(), kAcceptablePort}, {absl::StrCat("[", TestLoopback6().ToString(), "]"), kAcceptablePort}}}; }; TEST_F(ConnectUdpTunnelTest, OpenTunnel) { EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, ReceiveAsync(Gt(0))); EXPECT_CALL(*socket_, Disconnect()).WillOnce(InvokeWithoutArgs([this]() { tunnel_.ReceiveComplete(absl::CancelledError()); })); EXPECT_CALL( request_handler_, OnResponseBackendComplete( AllOf(Property(&QuicBackendResponse::response_type, QuicBackendResponse::INCOMPLETE_RESPONSE), Property(&QuicBackendResponse::headers, UnorderedElementsAre(Pair(":status", "200"), Pair("Capsule-Protocol", "?1"))), Property(&QuicBackendResponse::trailers, IsEmpty()), Property(&QuicBackendResponse::body, IsEmpty())))); quiche::HttpHeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":protocol"] = "connect-udp"; request_headers[":authority"] = "proxy.test"; request_headers[":scheme"] = "https"; request_headers[":path"] = absl::StrCat( "/.well-known/masque/udp/", kAcceptableTarget, "/", kAcceptablePort, "/"); tunnel_.OpenTunnel(request_headers); EXPECT_TRUE(tunnel_.IsTunnelOpenToTarget()); tunnel_.OnClientStreamClose(); EXPECT_FALSE(tunnel_.IsTunnelOpenToTarget()); } TEST_F(ConnectUdpTunnelTest, OpenTunnelToIpv4LiteralTarget) { EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, ReceiveAsync(Gt(0))); EXPECT_CALL(*socket_, Disconnect()).WillOnce(InvokeWithoutArgs([this]() { tunnel_.ReceiveComplete(absl::CancelledError()); })); EXPECT_CALL( request_handler_, OnResponseBackendComplete( AllOf(Property(&QuicBackendResponse::response_type, QuicBackendResponse::INCOMPLETE_RESPONSE), Property(&QuicBackendResponse::headers, UnorderedElementsAre(Pair(":status", "200"), Pair("Capsule-Protocol", "?1"))), Property(&QuicBackendResponse::trailers, IsEmpty()), Property(&QuicBackendResponse::body, IsEmpty())))); quiche::HttpHeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":protocol"] = "connect-udp"; request_headers[":authority"] = "proxy.test"; request_headers[":scheme"] = "https"; request_headers[":path"] = absl::StrCat("/.well-known/masque/udp/", TestLoopback4().ToString(), "/", kAcceptablePort, "/"); tunnel_.OpenTunnel(request_headers); EXPECT_TRUE(tunnel_.IsTunnelOpenToTarget()); tunnel_.OnClientStreamClose(); EXPECT_FALSE(tunnel_.IsTunnelOpenToTarget()); } TEST_F(ConnectUdpTunnelTest, OpenTunnelToIpv6LiteralTarget) { EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, ReceiveAsync(Gt(0))); EXPECT_CALL(*socket_, Disconnect()).WillOnce(InvokeWithoutArgs([this]() { tunnel_.ReceiveComplete(absl::CancelledError()); })); EXPECT_CALL( request_handler_, OnResponseBackendComplete( AllOf(Property(&QuicBackendResponse::response_type, QuicBackendResponse::INCOMPLETE_RESPONSE), Property(&QuicBackendResponse::headers, UnorderedElementsAre(Pair(":status", "200"), Pair("Capsule-Protocol", "?1"))), Property(&QuicBackendResponse::trailers, IsEmpty()), Property(&QuicBackendResponse::body, IsEmpty())))); std::string path; ASSERT_TRUE(quiche::ExpandURITemplate( "/.well-known/masque/udp/{target_host}/{target_port}/", {{"target_host", absl::StrCat("[", TestLoopback6().ToString(), "]")}, {"target_port", absl::StrCat(kAcceptablePort)}}, &path)); quiche::HttpHeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":protocol"] = "connect-udp"; request_headers[":authority"] = "proxy.test"; request_headers[":scheme"] = "https"; request_headers[":path"] = path; tunnel_.OpenTunnel(request_headers); EXPECT_TRUE(tunnel_.IsTunnelOpenToTarget()); tunnel_.OnClientStreamClose(); EXPECT_FALSE(tunnel_.IsTunnelOpenToTarget()); } TEST_F(ConnectUdpTunnelTest, OpenTunnelWithMalformedRequest) { EXPECT_CALL(request_handler_, TerminateStreamWithError(Property( &QuicResetStreamError::ietf_application_code, static_cast<uint64_t>(QuicHttp3ErrorCode::MESSAGE_ERROR)))); quiche::HttpHeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":protocol"] = "connect-udp"; request_headers[":authority"] = "proxy.test"; request_headers[":scheme"] = "https"; tunnel_.OpenTunnel(request_headers); EXPECT_FALSE(tunnel_.IsTunnelOpenToTarget()); tunnel_.OnClientStreamClose(); } TEST_F(ConnectUdpTunnelTest, OpenTunnelWithUnacceptableTarget) { EXPECT_CALL(request_handler_, OnResponseBackendComplete(AllOf( Property(&QuicBackendResponse::response_type, QuicBackendResponse::REGULAR_RESPONSE), Property(&QuicBackendResponse::headers, UnorderedElementsAre( Pair(":status", "403"), Pair("Proxy-Status", HasSubstr("destination_ip_prohibited")))), Property(&QuicBackendResponse::trailers, IsEmpty())))); quiche::HttpHeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":protocol"] = "connect-udp"; request_headers[":authority"] = "proxy.test"; request_headers[":scheme"] = "https"; request_headers[":path"] = "/.well-known/masque/udp/unacceptable.test/100/"; tunnel_.OpenTunnel(request_headers); EXPECT_FALSE(tunnel_.IsTunnelOpenToTarget()); tunnel_.OnClientStreamClose(); } TEST_F(ConnectUdpTunnelTest, ReceiveFromTarget) { static constexpr absl::string_view kData = "\x11\x22\x33\x44\x55"; EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, ReceiveAsync(Ge(kData.size()))).Times(2); EXPECT_CALL(*socket_, Disconnect()).WillOnce(InvokeWithoutArgs([this]() { tunnel_.ReceiveComplete(absl::CancelledError()); })); EXPECT_CALL(request_handler_, OnResponseBackendComplete(_)); EXPECT_CALL( stream_, SendHttp3Datagram( quiche::ConnectUdpDatagramUdpPacketPayload(kData).Serialize())) .WillOnce(Return(MESSAGE_STATUS_SUCCESS)); quiche::HttpHeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":protocol"] = "connect-udp"; request_headers[":authority"] = "proxy.test"; request_headers[":scheme"] = "https"; request_headers[":path"] = absl::StrCat( "/.well-known/masque/udp/", kAcceptableTarget, "/", kAcceptablePort, "/"); tunnel_.OpenTunnel(request_headers); tunnel_.ReceiveComplete(MemSliceFromString(kData)); tunnel_.OnClientStreamClose(); } TEST_F(ConnectUdpTunnelTest, SendToTarget) { static constexpr absl::string_view kData = "\x11\x22\x33\x44\x55"; EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, ReceiveAsync(Gt(0))); EXPECT_CALL(*socket_, SendBlocking(Matcher<std::string>(Eq(kData)))) .WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, Disconnect()).WillOnce(InvokeWithoutArgs([this]() { tunnel_.ReceiveComplete(absl::CancelledError()); })); EXPECT_CALL(request_handler_, OnResponseBackendComplete(_)); quiche::HttpHeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":protocol"] = "connect-udp"; request_headers[":authority"] = "proxy.test"; request_headers[":scheme"] = "https"; request_headers[":path"] = absl::StrCat( "/.well-known/masque/udp/", kAcceptableTarget, "/", kAcceptablePort, "/"); tunnel_.OpenTunnel(request_headers); tunnel_.OnHttp3Datagram( kStreamId, quiche::ConnectUdpDatagramUdpPacketPayload(kData).Serialize()); tunnel_.OnClientStreamClose(); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/tools/connect_udp_tunnel.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/tools/connect_udp_tunnel_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
9696c01c-ac60-49df-98b7-8c5747ddbfef
cpp
google/quiche
quic_simple_server_session
quiche/quic/tools/quic_simple_server_session.cc
quiche/quic/tools/quic_simple_server_session_test.cc
#include "quiche/quic/tools/quic_simple_server_session.h" #include <memory> #include <utility> #include "absl/memory/memory.h" #include "quiche/quic/core/http/quic_server_initiated_spdy_stream.h" #include "quiche/quic/core/http/quic_spdy_session.h" #include "quiche/quic/core/quic_connection.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/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/tools/quic_simple_server_stream.h" namespace quic { QuicSimpleServerSession::QuicSimpleServerSession( const QuicConfig& config, const ParsedQuicVersionVector& supported_versions, QuicConnection* connection, QuicSession::Visitor* visitor, QuicCryptoServerStreamBase::Helper* helper, const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache, QuicSimpleServerBackend* quic_simple_server_backend) : QuicServerSessionBase(config, supported_versions, connection, visitor, helper, crypto_config, compressed_certs_cache), quic_simple_server_backend_(quic_simple_server_backend) { QUICHE_DCHECK(quic_simple_server_backend_); set_max_streams_accepted_per_loop(5u); } QuicSimpleServerSession::~QuicSimpleServerSession() { DeleteConnection(); } std::unique_ptr<QuicCryptoServerStreamBase> QuicSimpleServerSession::CreateQuicCryptoServerStream( const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache) { return CreateCryptoServerStream(crypto_config, compressed_certs_cache, this, stream_helper()); } void QuicSimpleServerSession::OnStreamFrame(const QuicStreamFrame& frame) { if (!IsIncomingStream(frame.stream_id) && !WillNegotiateWebTransport()) { QUIC_LOG(WARNING) << "Client shouldn't send data on server push stream"; connection()->CloseConnection( QUIC_INVALID_STREAM_ID, "Client sent data on server push stream", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } QuicSpdySession::OnStreamFrame(frame); } QuicSpdyStream* QuicSimpleServerSession::CreateIncomingStream(QuicStreamId id) { if (!ShouldCreateIncomingStream(id)) { return nullptr; } QuicSpdyStream* stream = new QuicSimpleServerStream( id, this, BIDIRECTIONAL, quic_simple_server_backend_); ActivateStream(absl::WrapUnique(stream)); return stream; } QuicSpdyStream* QuicSimpleServerSession::CreateIncomingStream( PendingStream* pending) { QuicSpdyStream* stream = new QuicSimpleServerStream(pending, this, quic_simple_server_backend_); ActivateStream(absl::WrapUnique(stream)); return stream; } QuicSpdyStream* QuicSimpleServerSession::CreateOutgoingBidirectionalStream() { if (!WillNegotiateWebTransport()) { QUIC_BUG(QuicSimpleServerSession CreateOutgoingBidirectionalStream without WebTransport support) << "QuicSimpleServerSession::CreateOutgoingBidirectionalStream called " "in a session without WebTransport support."; return nullptr; } if (!ShouldCreateOutgoingBidirectionalStream()) { return nullptr; } QuicServerInitiatedSpdyStream* stream = new QuicServerInitiatedSpdyStream( GetNextOutgoingBidirectionalStreamId(), this, BIDIRECTIONAL); ActivateStream(absl::WrapUnique(stream)); return stream; } QuicSimpleServerStream* QuicSimpleServerSession::CreateOutgoingUnidirectionalStream() { if (!ShouldCreateOutgoingUnidirectionalStream()) { return nullptr; } QuicSimpleServerStream* stream = new QuicSimpleServerStream( GetNextOutgoingUnidirectionalStreamId(), this, WRITE_UNIDIRECTIONAL, quic_simple_server_backend_); ActivateStream(absl::WrapUnique(stream)); return stream; } QuicStream* QuicSimpleServerSession::ProcessBidirectionalPendingStream( PendingStream* pending) { QUICHE_DCHECK(IsEncryptionEstablished()); return CreateIncomingStream(pending); } }
#include "quiche/quic/tools/quic_simple_server_session.h" #include <algorithm> #include <memory> #include <utility> #include "absl/strings/str_cat.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/http/http_encoder.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_utils.h" #include "quiche/quic/core/quic_versions.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/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_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_sustained_bandwidth_recorder_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/tools/quic_backend_response.h" #include "quiche/quic/tools/quic_memory_cache_backend.h" #include "quiche/quic/tools/quic_simple_server_stream.h" using testing::_; using testing::AtLeast; using testing::InSequence; using testing::Invoke; using testing::Return; using testing::StrictMock; namespace quic { namespace test { namespace { const char* const kStreamData = "\1z"; } class QuicSimpleServerSessionPeer { public: static void SetCryptoStream(QuicSimpleServerSession* s, QuicCryptoServerStreamBase* crypto_stream) { s->crypto_stream_.reset(crypto_stream); } static QuicSpdyStream* CreateIncomingStream(QuicSimpleServerSession* s, QuicStreamId id) { return s->CreateIncomingStream(id); } static QuicSimpleServerStream* CreateOutgoingUnidirectionalStream( QuicSimpleServerSession* s) { return s->CreateOutgoingUnidirectionalStream(); } }; namespace { const size_t kMaxStreamsForTest = 10; class MockQuicCryptoServerStream : public QuicCryptoServerStream { public: explicit MockQuicCryptoServerStream( const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache, QuicSession* 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)); bool encryption_established() const override { return true; } }; class MockTlsServerHandshaker : public TlsServerHandshaker { public: explicit MockTlsServerHandshaker(QuicSession* 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)); bool encryption_established() const override { return true; } }; class MockQuicConnectionWithSendStreamData : public MockQuicConnection { public: MockQuicConnectionWithSendStreamData( MockQuicConnectionHelper* helper, MockAlarmFactory* alarm_factory, Perspective perspective, const ParsedQuicVersionVector& supported_versions) : MockQuicConnection(helper, alarm_factory, perspective, supported_versions) { auto consume_all_data = [](QuicStreamId , size_t write_length, QuicStreamOffset , StreamSendingState state) { return QuicConsumedData(write_length, state != NO_FIN); }; ON_CALL(*this, SendStreamData(_, _, _, _)) .WillByDefault(Invoke(consume_all_data)); } MOCK_METHOD(QuicConsumedData, SendStreamData, (QuicStreamId id, size_t write_length, QuicStreamOffset offset, StreamSendingState state), (override)); }; class MockQuicSimpleServerSession : public QuicSimpleServerSession { public: MockQuicSimpleServerSession( const QuicConfig& config, QuicConnection* connection, QuicSession::Visitor* visitor, QuicCryptoServerStreamBase::Helper* helper, const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache, QuicSimpleServerBackend* quic_simple_server_backend) : QuicSimpleServerSession( config, CurrentSupportedVersions(), connection, visitor, helper, crypto_config, compressed_certs_cache, quic_simple_server_backend) { } MOCK_METHOD(void, SendBlocked, (QuicStreamId, QuicStreamOffset), (override)); MOCK_METHOD(bool, WriteControlFrame, (const QuicFrame& frame, TransmissionType type), (override)); }; class QuicSimpleServerSessionTest : 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: QuicSimpleServerSessionTest() : crypto_config_(QuicCryptoServerConfig::TESTING, QuicRandom::GetInstance(), crypto_test_utils::ProofSourceForTesting(), KeyExchangeSource::Default()), compressed_certs_cache_( QuicCompressedCertsCache::kQuicCompressedCertsCacheSize) { config_.SetMaxBidirectionalStreamsToSend(kMaxStreamsForTest); QuicConfigPeer::SetReceivedMaxBidirectionalStreams(&config_, kMaxStreamsForTest); config_.SetMaxUnidirectionalStreamsToSend(kMaxStreamsForTest); config_.SetInitialStreamFlowControlWindowToSend( kInitialStreamFlowControlWindowForTest); config_.SetInitialMaxStreamDataBytesIncomingBidirectionalToSend( kInitialStreamFlowControlWindowForTest); config_.SetInitialMaxStreamDataBytesOutgoingBidirectionalToSend( kInitialStreamFlowControlWindowForTest); config_.SetInitialMaxStreamDataBytesUnidirectionalToSend( kInitialStreamFlowControlWindowForTest); config_.SetInitialSessionFlowControlWindowToSend( kInitialSessionFlowControlWindowForTest); if (VersionUsesHttp3(transport_version())) { QuicConfigPeer::SetReceivedMaxUnidirectionalStreams( &config_, kMaxStreamsForTest + 3); } else { QuicConfigPeer::SetReceivedMaxUnidirectionalStreams(&config_, kMaxStreamsForTest); } ParsedQuicVersionVector supported_versions = SupportedVersions(version()); connection_ = new StrictMock<MockQuicConnectionWithSendStreamData>( &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<MockQuicSimpleServerSession>( 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(); if (VersionHasIetfQuicFrames(transport_version())) { EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillRepeatedly(Invoke(&ClearControlFrameWithTransmissionType)); } session_->OnConfigNegotiated(); } 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 InjectStopSending(QuicStreamId stream_id, QuicRstStreamErrorCode rst_stream_code) { if (!VersionHasIetfQuicFrames(transport_version())) { return; } EXPECT_CALL(owner_, OnStopSendingReceived(_)).Times(1); QuicStopSendingFrame stop_sending(kInvalidControlFrameId, stream_id, rst_stream_code); EXPECT_CALL(*connection_, OnStreamReset(stream_id, rst_stream_code)); session_->OnStopSendingFrame(stop_sending); } StrictMock<MockQuicSessionVisitor> owner_; StrictMock<MockQuicCryptoServerStreamHelper> stream_helper_; MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; StrictMock<MockQuicConnectionWithSendStreamData>* connection_; QuicConfig config_; QuicCryptoServerConfig crypto_config_; QuicCompressedCertsCache compressed_certs_cache_; QuicMemoryCacheBackend memory_cache_backend_; std::unique_ptr<MockQuicSimpleServerSession> session_; std::unique_ptr<CryptoHandshakeMessage> handshake_message_; }; INSTANTIATE_TEST_SUITE_P(Tests, QuicSimpleServerSessionTest, ::testing::ValuesIn(AllSupportedVersions()), ::testing::PrintToStringParamName()); TEST_P(QuicSimpleServerSessionTest, 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); EXPECT_CALL(*session_, WriteControlFrame(_, _)); if (!VersionHasIetfQuicFrames(transport_version())) { EXPECT_CALL(*connection_, OnStreamReset(GetNthClientInitiatedBidirectionalId(0), QUIC_RST_ACKNOWLEDGEMENT)); } session_->OnRstStream(rst1); InjectStopSending(GetNthClientInitiatedBidirectionalId(0), QUIC_ERROR_PROCESSING_STREAM); EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); session_->OnStreamFrame(data1); EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); EXPECT_TRUE(connection_->connected()); } TEST_P(QuicSimpleServerSessionTest, 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); InjectStopSending(GetNthClientInitiatedBidirectionalId(0), QUIC_ERROR_PROCESSING_STREAM); 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(QuicSimpleServerSessionTest, 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); InjectStopSending(GetNthClientInitiatedBidirectionalId(0), QUIC_ERROR_PROCESSING_STREAM); 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(QuicSimpleServerSessionTest, CreateIncomingStreamDisconnected) { if (version() != AllSupportedVersions()[0]) { return; } size_t initial_num_open_stream = QuicSessionPeer::GetNumOpenDynamicStreams(session_.get()); QuicConnectionPeer::TearDownLocalConnectionState(connection_); EXPECT_QUIC_BUG(QuicSimpleServerSessionPeer::CreateIncomingStream( session_.get(), GetNthClientInitiatedBidirectionalId(0)), "ShouldCreateIncomingStream called when disconnected"); EXPECT_EQ(initial_num_open_stream, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); } TEST_P(QuicSimpleServerSessionTest, CreateIncomingStream) { QuicSpdyStream* stream = QuicSimpleServerSessionPeer::CreateIncomingStream( session_.get(), GetNthClientInitiatedBidirectionalId(0)); EXPECT_NE(nullptr, stream); EXPECT_EQ(GetNthClientInitiatedBidirectionalId(0), stream->id()); } TEST_P(QuicSimpleServerSessionTest, CreateOutgoingDynamicStreamDisconnected) { if (version() != AllSupportedVersions()[0]) { return; } size_t initial_num_open_stream = QuicSessionPeer::GetNumOpenDynamicStreams(session_.get()); QuicConnectionPeer::TearDownLocalConnectionState(connection_); EXPECT_QUIC_BUG( QuicSimpleServerSessionPeer::CreateOutgoingUnidirectionalStream( session_.get()), "ShouldCreateOutgoingUnidirectionalStream called when disconnected"); EXPECT_EQ(initial_num_open_stream, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); } TEST_P(QuicSimpleServerSessionTest, CreateOutgoingDynamicStreamUnencrypted) { if (version() != AllSupportedVersions()[0]) { return; } size_t initial_num_open_stream = QuicSessionPeer::GetNumOpenDynamicStreams(session_.get()); EXPECT_QUIC_BUG( QuicSimpleServerSessionPeer::CreateOutgoingUnidirectionalStream( session_.get()), "Encryption not established so no outgoing stream created."); EXPECT_EQ(initial_num_open_stream, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); } TEST_P(QuicSimpleServerSessionTest, GetEvenIncomingError) { const size_t initial_num_open_stream = QuicSessionPeer::GetNumOpenDynamicStreams(session_.get()); const QuicErrorCode expected_error = VersionUsesHttp3(transport_version()) ? QUIC_HTTP_STREAM_WRONG_DIRECTION : QUIC_INVALID_STREAM_ID; EXPECT_CALL(*connection_, CloseConnection(expected_error, "Data for nonexistent stream", _)); EXPECT_EQ(nullptr, QuicSessionPeer::GetOrCreateStream( session_.get(), GetNthServerInitiatedUnidirectionalId(3))); EXPECT_EQ(initial_num_open_stream, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/tools/quic_simple_server_session.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/tools/quic_simple_server_session_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
a08e9eff-c4d9-4548-8237-e935523bf760
cpp
google/quiche
quic_url
quiche/quic/tools/quic_url.cc
quiche/quic/tools/quic_url_test.cc
#include "quiche/quic/tools/quic_url.h" #include <string> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" namespace quic { static constexpr size_t kMaxHostNameLength = 256; QuicUrl::QuicUrl(absl::string_view url) : url_(static_cast<std::string>(url)) {} QuicUrl::QuicUrl(absl::string_view url, absl::string_view default_scheme) : QuicUrl(url) { if (url_.has_scheme()) { return; } url_ = GURL(absl::StrCat(default_scheme, ": } std::string QuicUrl::ToString() const { if (IsValid()) { return url_.spec(); } return ""; } bool QuicUrl::IsValid() const { if (!url_.is_valid() || !url_.has_scheme()) { return false; } if (url_.has_host() && url_.host().length() > kMaxHostNameLength) { return false; } return true; } std::string QuicUrl::HostPort() const { if (!IsValid() || !url_.has_host()) { return ""; } std::string host = url_.host(); int port = url_.IntPort(); if (port == url::PORT_UNSPECIFIED) { return host; } return absl::StrCat(host, ":", port); } std::string QuicUrl::PathParamsQuery() const { if (!IsValid() || !url_.has_path()) { return "/"; } return url_.PathForRequest(); } std::string QuicUrl::scheme() const { if (!IsValid()) { return ""; } return url_.scheme(); } std::string QuicUrl::host() const { if (!IsValid()) { return ""; } return url_.HostNoBrackets(); } std::string QuicUrl::path() const { if (!IsValid()) { return ""; } return url_.path(); } uint16_t QuicUrl::port() const { if (!IsValid()) { return 0; } int port = url_.EffectiveIntPort(); if (port == url::PORT_UNSPECIFIED) { return 0; } return port; } }
#include "quiche/quic/tools/quic_url.h" #include <string> #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { namespace { class QuicUrlTest : public QuicTest {}; TEST_F(QuicUrlTest, Basic) { std::string url_str = "www.example.com"; QuicUrl url(url_str); EXPECT_FALSE(url.IsValid()); url_str = "http: url = QuicUrl(url_str); EXPECT_TRUE(url.IsValid()); EXPECT_EQ("http: EXPECT_EQ("http", url.scheme()); EXPECT_EQ("www.example.com", url.HostPort()); EXPECT_EQ("/", url.PathParamsQuery()); EXPECT_EQ(80u, url.port()); url_str = "https: url = QuicUrl(url_str); EXPECT_TRUE(url.IsValid()); EXPECT_EQ("https: url.ToString()); EXPECT_EQ("https", url.scheme()); EXPECT_EQ("www.example.com:12345", url.HostPort()); EXPECT_EQ("/path/to/resource?a=1&campaign=2", url.PathParamsQuery()); EXPECT_EQ(12345u, url.port()); url_str = "ftp: url = QuicUrl(url_str); EXPECT_TRUE(url.IsValid()); EXPECT_EQ("ftp: EXPECT_EQ("ftp", url.scheme()); EXPECT_EQ("www.example.com", url.HostPort()); EXPECT_EQ("/", url.PathParamsQuery()); EXPECT_EQ(21u, url.port()); } TEST_F(QuicUrlTest, DefaultScheme) { std::string url_str = "www.example.com"; QuicUrl url(url_str, "http"); EXPECT_EQ("http: EXPECT_EQ("http", url.scheme()); url_str = "http: url = QuicUrl(url_str, "https"); EXPECT_EQ("http: EXPECT_EQ("http", url.scheme()); url_str = "www.example.com"; url = QuicUrl(url_str, "ftp"); EXPECT_EQ("ftp: EXPECT_EQ("ftp", url.scheme()); } TEST_F(QuicUrlTest, IsValid) { std::string url_str = "ftp: EXPECT_TRUE(QuicUrl(url_str).IsValid()); url_str = "https: EXPECT_FALSE(QuicUrl(url_str).IsValid()); url_str = "%http: EXPECT_FALSE(QuicUrl(url_str).IsValid()); std::string host(1024, 'a'); url_str = "https: EXPECT_FALSE(QuicUrl(url_str).IsValid()); url_str = "https: EXPECT_FALSE(QuicUrl(url_str).IsValid()); } TEST_F(QuicUrlTest, HostPort) { std::string url_str = "http: QuicUrl url(url_str); EXPECT_EQ("www.example.com", url.HostPort()); EXPECT_EQ("www.example.com", url.host()); EXPECT_EQ(80u, url.port()); url_str = "http: url = QuicUrl(url_str); EXPECT_EQ("www.example.com", url.HostPort()); EXPECT_EQ("www.example.com", url.host()); EXPECT_EQ(80u, url.port()); url_str = "http: url = QuicUrl(url_str); EXPECT_EQ("www.example.com:81", url.HostPort()); EXPECT_EQ("www.example.com", url.host()); EXPECT_EQ(81u, url.port()); url_str = "https: url = QuicUrl(url_str); EXPECT_EQ("192.168.1.1", url.HostPort()); EXPECT_EQ("192.168.1.1", url.host()); EXPECT_EQ(443u, url.port()); url_str = "http: url = QuicUrl(url_str); EXPECT_EQ("[2001::1]", url.HostPort()); EXPECT_EQ("2001::1", url.host()); EXPECT_EQ(80u, url.port()); url_str = "http: url = QuicUrl(url_str); EXPECT_EQ("[2001::1]:81", url.HostPort()); EXPECT_EQ("2001::1", url.host()); EXPECT_EQ(81u, url.port()); } TEST_F(QuicUrlTest, PathParamsQuery) { std::string url_str = "https: QuicUrl url(url_str); EXPECT_EQ("/path/to/resource?a=1&campaign=2", url.PathParamsQuery()); EXPECT_EQ("/path/to/resource", url.path()); url_str = "https: url = QuicUrl(url_str); EXPECT_EQ("/?", url.PathParamsQuery()); EXPECT_EQ("/", url.path()); url_str = "https: url = QuicUrl(url_str); EXPECT_EQ("/", url.PathParamsQuery()); EXPECT_EQ("/", url.path()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/tools/quic_url.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/tools/quic_url_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
02873ad8-4e28-4ca9-854c-96b36f1384eb
cpp
google/quiche
simple_ticket_crypter
quiche/quic/tools/simple_ticket_crypter.cc
quiche/quic/tools/simple_ticket_crypter_test.cc
#include "quiche/quic/tools/simple_ticket_crypter.h" #include <memory> #include <utility> #include <vector> #include "openssl/aead.h" #include "openssl/rand.h" namespace quic { namespace { constexpr QuicTime::Delta kTicketKeyLifetime = QuicTime::Delta::FromSeconds(60 * 60 * 24 * 7); constexpr size_t kEpochSize = 1; constexpr size_t kIVSize = 16; constexpr size_t kAuthTagSize = 16; constexpr size_t kIVOffset = kEpochSize; constexpr size_t kMessageOffset = kIVOffset + kIVSize; } SimpleTicketCrypter::SimpleTicketCrypter(QuicClock* clock) : clock_(clock) { RAND_bytes(&key_epoch_, 1); current_key_ = NewKey(); } SimpleTicketCrypter::~SimpleTicketCrypter() = default; size_t SimpleTicketCrypter::MaxOverhead() { return kEpochSize + kIVSize + kAuthTagSize; } std::vector<uint8_t> SimpleTicketCrypter::Encrypt( absl::string_view in, absl::string_view encryption_key) { QUICHE_DCHECK(encryption_key.empty()); MaybeRotateKeys(); std::vector<uint8_t> out(in.size() + MaxOverhead()); out[0] = key_epoch_; RAND_bytes(out.data() + kIVOffset, kIVSize); size_t out_len; const EVP_AEAD_CTX* ctx = current_key_->aead_ctx.get(); if (!EVP_AEAD_CTX_seal(ctx, out.data() + kMessageOffset, &out_len, out.size() - kMessageOffset, out.data() + kIVOffset, kIVSize, reinterpret_cast<const uint8_t*>(in.data()), in.size(), nullptr, 0)) { return std::vector<uint8_t>(); } out.resize(out_len + kMessageOffset); return out; } std::vector<uint8_t> SimpleTicketCrypter::Decrypt(absl::string_view in) { MaybeRotateKeys(); if (in.size() < kMessageOffset) { return std::vector<uint8_t>(); } const uint8_t* input = reinterpret_cast<const uint8_t*>(in.data()); std::vector<uint8_t> out(in.size() - kMessageOffset); size_t out_len; const EVP_AEAD_CTX* ctx = current_key_->aead_ctx.get(); if (input[0] != key_epoch_) { if (input[0] == static_cast<uint8_t>(key_epoch_ - 1) && previous_key_) { ctx = previous_key_->aead_ctx.get(); } else { return std::vector<uint8_t>(); } } if (!EVP_AEAD_CTX_open(ctx, out.data(), &out_len, out.size(), input + kIVOffset, kIVSize, input + kMessageOffset, in.size() - kMessageOffset, nullptr, 0)) { return std::vector<uint8_t>(); } out.resize(out_len); return out; } void SimpleTicketCrypter::Decrypt( absl::string_view in, std::shared_ptr<quic::ProofSource::DecryptCallback> callback) { callback->Run(Decrypt(in)); } void SimpleTicketCrypter::MaybeRotateKeys() { QuicTime now = clock_->ApproximateNow(); if (current_key_->expiration < now) { previous_key_ = std::move(current_key_); current_key_ = NewKey(); key_epoch_++; } } std::unique_ptr<SimpleTicketCrypter::Key> SimpleTicketCrypter::NewKey() { auto key = std::make_unique<SimpleTicketCrypter::Key>(); RAND_bytes(key->key, kKeySize); EVP_AEAD_CTX_init(key->aead_ctx.get(), EVP_aead_aes_128_gcm(), key->key, kKeySize, EVP_AEAD_DEFAULT_TAG_LENGTH, nullptr); key->expiration = clock_->ApproximateNow() + kTicketKeyLifetime; return key; } }
#include "quiche/quic/tools/simple_ticket_crypter.h" #include <memory> #include <vector> #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_clock.h" namespace quic { namespace test { namespace { constexpr QuicTime::Delta kOneDay = QuicTime::Delta::FromSeconds(60 * 60 * 24); } class DecryptCallback : public quic::ProofSource::DecryptCallback { public: explicit DecryptCallback(std::vector<uint8_t>* out) : out_(out) {} void Run(std::vector<uint8_t> plaintext) override { *out_ = plaintext; } private: std::vector<uint8_t>* out_; }; absl::string_view StringPiece(const std::vector<uint8_t>& in) { return absl::string_view(reinterpret_cast<const char*>(in.data()), in.size()); } class SimpleTicketCrypterTest : public QuicTest { public: SimpleTicketCrypterTest() : ticket_crypter_(&mock_clock_) {} protected: MockClock mock_clock_; SimpleTicketCrypter ticket_crypter_; }; TEST_F(SimpleTicketCrypterTest, EncryptDecrypt) { std::vector<uint8_t> plaintext = {1, 2, 3, 4, 5}; std::vector<uint8_t> ciphertext = ticket_crypter_.Encrypt(StringPiece(plaintext), {}); EXPECT_NE(plaintext, ciphertext); std::vector<uint8_t> out_plaintext; ticket_crypter_.Decrypt(StringPiece(ciphertext), std::make_unique<DecryptCallback>(&out_plaintext)); EXPECT_EQ(out_plaintext, plaintext); } TEST_F(SimpleTicketCrypterTest, CiphertextsDiffer) { std::vector<uint8_t> plaintext = {1, 2, 3, 4, 5}; std::vector<uint8_t> ciphertext1 = ticket_crypter_.Encrypt(StringPiece(plaintext), {}); std::vector<uint8_t> ciphertext2 = ticket_crypter_.Encrypt(StringPiece(plaintext), {}); EXPECT_NE(ciphertext1, ciphertext2); } TEST_F(SimpleTicketCrypterTest, DecryptionFailureWithModifiedCiphertext) { std::vector<uint8_t> plaintext = {1, 2, 3, 4, 5}; std::vector<uint8_t> ciphertext = ticket_crypter_.Encrypt(StringPiece(plaintext), {}); EXPECT_NE(plaintext, ciphertext); for (size_t i = 0; i < ciphertext.size(); i++) { SCOPED_TRACE(i); std::vector<uint8_t> munged_ciphertext = ciphertext; munged_ciphertext[i] ^= 1; std::vector<uint8_t> out_plaintext; ticket_crypter_.Decrypt(StringPiece(munged_ciphertext), std::make_unique<DecryptCallback>(&out_plaintext)); EXPECT_TRUE(out_plaintext.empty()); } } TEST_F(SimpleTicketCrypterTest, DecryptionFailureWithEmptyCiphertext) { std::vector<uint8_t> out_plaintext; ticket_crypter_.Decrypt(absl::string_view(), std::make_unique<DecryptCallback>(&out_plaintext)); EXPECT_TRUE(out_plaintext.empty()); } TEST_F(SimpleTicketCrypterTest, KeyRotation) { std::vector<uint8_t> plaintext = {1, 2, 3}; std::vector<uint8_t> ciphertext = ticket_crypter_.Encrypt(StringPiece(plaintext), {}); EXPECT_FALSE(ciphertext.empty()); mock_clock_.AdvanceTime(kOneDay * 8); std::vector<uint8_t> out_plaintext; ticket_crypter_.Decrypt(StringPiece(ciphertext), std::make_unique<DecryptCallback>(&out_plaintext)); EXPECT_EQ(out_plaintext, plaintext); mock_clock_.AdvanceTime(kOneDay * 8); ticket_crypter_.Decrypt(StringPiece(ciphertext), std::make_unique<DecryptCallback>(&out_plaintext)); EXPECT_TRUE(out_plaintext.empty()); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/tools/simple_ticket_crypter.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/tools/simple_ticket_crypter_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
013cd694-7b33-4684-9141-6b52f144111a
cpp
google/quiche
quic_default_client
quiche/quic/tools/quic_default_client.cc
quiche/quic/tools/quic_default_client_test.cc
#include "quiche/quic/tools/quic_default_client.h" #include <memory> #include <utility> #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_default_connection_helper.h" #include "quiche/quic/core/quic_server_id.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/tools/quic_simple_client_session.h" namespace quic { QuicDefaultClient::QuicDefaultClient( QuicSocketAddress server_address, const QuicServerId& server_id, const ParsedQuicVersionVector& supported_versions, QuicEventLoop* event_loop, std::unique_ptr<ProofVerifier> proof_verifier) : QuicDefaultClient( server_address, server_id, supported_versions, QuicConfig(), event_loop, std::make_unique<QuicClientDefaultNetworkHelper>(event_loop, this), std::move(proof_verifier), nullptr) {} QuicDefaultClient::QuicDefaultClient( QuicSocketAddress server_address, const QuicServerId& server_id, const ParsedQuicVersionVector& supported_versions, QuicEventLoop* event_loop, std::unique_ptr<ProofVerifier> proof_verifier, std::unique_ptr<SessionCache> session_cache) : QuicDefaultClient( server_address, server_id, supported_versions, QuicConfig(), event_loop, std::make_unique<QuicClientDefaultNetworkHelper>(event_loop, this), std::move(proof_verifier), std::move(session_cache)) {} QuicDefaultClient::QuicDefaultClient( QuicSocketAddress server_address, const QuicServerId& server_id, const ParsedQuicVersionVector& supported_versions, const QuicConfig& config, QuicEventLoop* event_loop, std::unique_ptr<ProofVerifier> proof_verifier, std::unique_ptr<SessionCache> session_cache) : QuicDefaultClient( server_address, server_id, supported_versions, config, event_loop, std::make_unique<QuicClientDefaultNetworkHelper>(event_loop, this), std::move(proof_verifier), std::move(session_cache)) {} QuicDefaultClient::QuicDefaultClient( QuicSocketAddress server_address, const QuicServerId& server_id, const ParsedQuicVersionVector& supported_versions, QuicEventLoop* event_loop, std::unique_ptr<QuicClientDefaultNetworkHelper> network_helper, std::unique_ptr<ProofVerifier> proof_verifier) : QuicDefaultClient(server_address, server_id, supported_versions, QuicConfig(), event_loop, std::move(network_helper), std::move(proof_verifier), nullptr) {} QuicDefaultClient::QuicDefaultClient( QuicSocketAddress server_address, const QuicServerId& server_id, const ParsedQuicVersionVector& supported_versions, const QuicConfig& config, QuicEventLoop* event_loop, std::unique_ptr<QuicClientDefaultNetworkHelper> network_helper, std::unique_ptr<ProofVerifier> proof_verifier) : QuicDefaultClient(server_address, server_id, supported_versions, config, event_loop, std::move(network_helper), std::move(proof_verifier), nullptr) {} QuicDefaultClient::QuicDefaultClient( QuicSocketAddress server_address, const QuicServerId& server_id, const ParsedQuicVersionVector& supported_versions, const QuicConfig& config, QuicEventLoop* event_loop, std::unique_ptr<QuicClientDefaultNetworkHelper> network_helper, std::unique_ptr<ProofVerifier> proof_verifier, std::unique_ptr<SessionCache> session_cache) : QuicSpdyClientBase(server_id, supported_versions, config, new QuicDefaultConnectionHelper(), event_loop->CreateAlarmFactory().release(), std::move(network_helper), std::move(proof_verifier), std::move(session_cache)) { set_server_address(server_address); } QuicDefaultClient::~QuicDefaultClient() = default; std::unique_ptr<QuicSession> QuicDefaultClient::CreateQuicClientSession( const ParsedQuicVersionVector& supported_versions, QuicConnection* connection) { return std::make_unique<QuicSimpleClientSession>( *config(), supported_versions, connection, this, network_helper(), server_id(), crypto_config(), drop_response_body(), enable_web_transport()); } QuicClientDefaultNetworkHelper* QuicDefaultClient::default_network_helper() { return static_cast<QuicClientDefaultNetworkHelper*>(network_helper()); } const QuicClientDefaultNetworkHelper* QuicDefaultClient::default_network_helper() const { return static_cast<const QuicClientDefaultNetworkHelper*>(network_helper()); } }
#if defined(__linux__) #include "quiche/quic/tools/quic_default_client.h" #include <dirent.h> #include <sys/types.h> #include <memory> #include <string> #include <utility> #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/io/quic_default_event_loop.h" #include "quiche/quic/core/io/quic_event_loop.h" #include "quiche/quic/core/quic_default_clock.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/platform/api/quic_test_loopback.h" #include "quiche/quic/test_tools/crypto_test_utils.h" #include "quiche/common/quiche_text_utils.h" namespace quic { namespace test { namespace { const char* kPathToFds = "/proc/self/fd"; std::string ReadLink(const std::string& path) { std::string result(PATH_MAX, '\0'); ssize_t result_size = readlink(path.c_str(), &result[0], result.size()); if (result_size < 0 && errno == ENOENT) { return ""; } QUICHE_CHECK(result_size > 0 && static_cast<size_t>(result_size) < result.size()) << "result_size:" << result_size << ", errno:" << errno << ", path:" << path; result.resize(result_size); return result; } size_t NumOpenSocketFDs() { size_t socket_count = 0; dirent* file; std::unique_ptr<DIR, int (*)(DIR*)> fd_directory(opendir(kPathToFds), closedir); while ((file = readdir(fd_directory.get())) != nullptr) { absl::string_view name(file->d_name); if (name == "." || name == "..") { continue; } std::string fd_path = ReadLink(absl::StrCat(kPathToFds, "/", name)); if (absl::StartsWith(fd_path, "socket:")) { socket_count++; } } return socket_count; } class QuicDefaultClientTest : public QuicTest { public: QuicDefaultClientTest() : event_loop_(GetDefaultEventLoop()->Create(QuicDefaultClock::Get())) { CreateAndInitializeQuicClient(); } std::unique_ptr<QuicDefaultClient> CreateAndInitializeQuicClient() { QuicSocketAddress server_address(QuicSocketAddress(TestLoopback(), 0)); QuicServerId server_id("hostname", server_address.port()); ParsedQuicVersionVector versions = AllSupportedVersions(); auto client = std::make_unique<QuicDefaultClient>( server_address, server_id, versions, event_loop_.get(), crypto_test_utils::ProofVerifierForTesting()); EXPECT_TRUE(client->Initialize()); return client; } private: std::unique_ptr<QuicEventLoop> event_loop_; }; TEST_F(QuicDefaultClientTest, DoNotLeakSocketFDs) { size_t number_of_open_fds = NumOpenSocketFDs(); const int kNumClients = 50; for (int i = 0; i < kNumClients; ++i) { EXPECT_EQ(number_of_open_fds, NumOpenSocketFDs()); std::unique_ptr<QuicDefaultClient> client(CreateAndInitializeQuicClient()); EXPECT_EQ(number_of_open_fds + 1, NumOpenSocketFDs()); } EXPECT_EQ(number_of_open_fds, NumOpenSocketFDs()); } TEST_F(QuicDefaultClientTest, CreateAndCleanUpUDPSockets) { size_t number_of_open_fds = NumOpenSocketFDs(); std::unique_ptr<QuicDefaultClient> client(CreateAndInitializeQuicClient()); EXPECT_EQ(number_of_open_fds + 1, NumOpenSocketFDs()); EXPECT_TRUE(client->default_network_helper()->CreateUDPSocketAndBind( client->server_address(), client->bind_to_address(), client->local_port())); EXPECT_EQ(number_of_open_fds + 2, NumOpenSocketFDs()); EXPECT_TRUE(client->default_network_helper()->CreateUDPSocketAndBind( client->server_address(), client->bind_to_address(), client->local_port())); EXPECT_EQ(number_of_open_fds + 3, NumOpenSocketFDs()); client->default_network_helper()->CleanUpUDPSocket(client->GetLatestFD()); EXPECT_EQ(number_of_open_fds + 2, NumOpenSocketFDs()); client->default_network_helper()->CleanUpUDPSocket(client->GetLatestFD()); EXPECT_EQ(number_of_open_fds + 1, NumOpenSocketFDs()); } } } } #endif
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/tools/quic_default_client.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/tools/quic_default_client_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
b2f35519-c36e-48ea-8367-1dee6f4fabac
cpp
google/quiche
quic_memory_cache_backend
quiche/quic/tools/quic_memory_cache_backend.cc
quiche/quic/tools/quic_memory_cache_backend_test.cc
#include "quiche/quic/tools/quic_memory_cache_backend.h" #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/strings/match.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/http/spdy_utils.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/tools/web_transport_test_visitors.h" #include "quiche/common/platform/api/quiche_file_utils.h" #include "quiche/common/quiche_text_utils.h" using quiche::HttpHeaderBlock; using spdy::kV3LowestPriority; namespace quic { QuicMemoryCacheBackend::ResourceFile::ResourceFile(const std::string& file_name) : file_name_(file_name) {} QuicMemoryCacheBackend::ResourceFile::~ResourceFile() = default; void QuicMemoryCacheBackend::ResourceFile::Read() { std::optional<std::string> maybe_file_contents = quiche::ReadFileContents(file_name_); if (!maybe_file_contents) { QUIC_LOG(DFATAL) << "Failed to read file for the memory cache backend: " << file_name_; return; } file_contents_ = *maybe_file_contents; for (size_t start = 0; start < file_contents_.length();) { size_t pos = file_contents_.find('\n', start); if (pos == std::string::npos) { QUIC_LOG(DFATAL) << "Headers invalid or empty, ignoring: " << file_name_; return; } size_t len = pos - start; if (file_contents_[pos - 1] == '\r') { len -= 1; } absl::string_view line(file_contents_.data() + start, len); start = pos + 1; if (line.empty()) { body_ = absl::string_view(file_contents_.data() + start, file_contents_.size() - start); break; } if (line.substr(0, 4) == "HTTP") { pos = line.find(' '); if (pos == std::string::npos) { QUIC_LOG(DFATAL) << "Headers invalid or empty, ignoring: " << file_name_; return; } spdy_headers_[":status"] = line.substr(pos + 1, 3); continue; } pos = line.find(": "); if (pos == std::string::npos) { QUIC_LOG(DFATAL) << "Headers invalid or empty, ignoring: " << file_name_; return; } spdy_headers_.AppendValueOrAddHeader( quiche::QuicheTextUtils::ToLower(line.substr(0, pos)), line.substr(pos + 2)); } spdy_headers_.erase("connection"); if (auto it = spdy_headers_.find("x-original-url"); it != spdy_headers_.end()) { x_original_url_ = it->second; HandleXOriginalUrl(); } } void QuicMemoryCacheBackend::ResourceFile::SetHostPathFromBase( absl::string_view base) { QUICHE_DCHECK(base[0] != '/') << base; size_t path_start = base.find_first_of('/'); if (path_start == absl::string_view::npos) { host_ = std::string(base); path_ = ""; return; } host_ = std::string(base.substr(0, path_start)); size_t query_start = base.find_first_of(','); if (query_start > 0) { path_ = std::string(base.substr(path_start, query_start - 1)); } else { path_ = std::string(base.substr(path_start)); } } absl::string_view QuicMemoryCacheBackend::ResourceFile::RemoveScheme( absl::string_view url) { if (absl::StartsWith(url, "https: url.remove_prefix(8); } else if (absl::StartsWith(url, "http: url.remove_prefix(7); } return url; } void QuicMemoryCacheBackend::ResourceFile::HandleXOriginalUrl() { absl::string_view url(x_original_url_); SetHostPathFromBase(RemoveScheme(url)); } const QuicBackendResponse* QuicMemoryCacheBackend::GetResponse( absl::string_view host, absl::string_view path) const { quiche::QuicheWriterMutexLock lock(&response_mutex_); auto it = responses_.find(GetKey(host, path)); if (it == responses_.end()) { uint64_t ignored = 0; if (generate_bytes_response_) { if (absl::SimpleAtoi(absl::string_view(path.data() + 1, path.size() - 1), &ignored)) { return generate_bytes_response_.get(); } } QUIC_DVLOG(1) << "Get response for resource failed: host " << host << " path " << path; if (default_response_) { return default_response_.get(); } return nullptr; } return it->second.get(); } using SpecialResponseType = QuicBackendResponse::SpecialResponseType; void QuicMemoryCacheBackend::AddSimpleResponse(absl::string_view host, absl::string_view path, int response_code, absl::string_view body) { HttpHeaderBlock response_headers; response_headers[":status"] = absl::StrCat(response_code); response_headers["content-length"] = absl::StrCat(body.length()); AddResponse(host, path, std::move(response_headers), body); } void QuicMemoryCacheBackend::AddDefaultResponse(QuicBackendResponse* response) { quiche::QuicheWriterMutexLock lock(&response_mutex_); default_response_.reset(response); } void QuicMemoryCacheBackend::AddResponse(absl::string_view host, absl::string_view path, HttpHeaderBlock response_headers, absl::string_view response_body) { AddResponseImpl(host, path, QuicBackendResponse::REGULAR_RESPONSE, std::move(response_headers), response_body, HttpHeaderBlock(), std::vector<quiche::HttpHeaderBlock>()); } void QuicMemoryCacheBackend::AddResponse(absl::string_view host, absl::string_view path, HttpHeaderBlock response_headers, absl::string_view response_body, HttpHeaderBlock response_trailers) { AddResponseImpl(host, path, QuicBackendResponse::REGULAR_RESPONSE, std::move(response_headers), response_body, std::move(response_trailers), std::vector<quiche::HttpHeaderBlock>()); } bool QuicMemoryCacheBackend::SetResponseDelay(absl::string_view host, absl::string_view path, QuicTime::Delta delay) { quiche::QuicheWriterMutexLock lock(&response_mutex_); auto it = responses_.find(GetKey(host, path)); if (it == responses_.end()) return false; it->second->set_delay(delay); return true; } void QuicMemoryCacheBackend::AddResponseWithEarlyHints( absl::string_view host, absl::string_view path, quiche::HttpHeaderBlock response_headers, absl::string_view response_body, const std::vector<quiche::HttpHeaderBlock>& early_hints) { AddResponseImpl(host, path, QuicBackendResponse::REGULAR_RESPONSE, std::move(response_headers), response_body, HttpHeaderBlock(), early_hints); } void QuicMemoryCacheBackend::AddSpecialResponse( absl::string_view host, absl::string_view path, SpecialResponseType response_type) { AddResponseImpl(host, path, response_type, HttpHeaderBlock(), "", HttpHeaderBlock(), std::vector<quiche::HttpHeaderBlock>()); } void QuicMemoryCacheBackend::AddSpecialResponse( absl::string_view host, absl::string_view path, quiche::HttpHeaderBlock response_headers, absl::string_view response_body, SpecialResponseType response_type) { AddResponseImpl(host, path, response_type, std::move(response_headers), response_body, HttpHeaderBlock(), std::vector<quiche::HttpHeaderBlock>()); } QuicMemoryCacheBackend::QuicMemoryCacheBackend() : cache_initialized_(false) {} bool QuicMemoryCacheBackend::InitializeBackend( const std::string& cache_directory) { if (cache_directory.empty()) { QUIC_BUG(quic_bug_10932_1) << "cache_directory must not be empty."; return false; } QUIC_LOG(INFO) << "Attempting to initialize QuicMemoryCacheBackend from directory: " << cache_directory; std::vector<std::string> files; if (!quiche::EnumerateDirectoryRecursively(cache_directory, files)) { QUIC_BUG(QuicMemoryCacheBackend unreadable directory) << "Can't read QuicMemoryCacheBackend directory: " << cache_directory; return false; } for (const auto& filename : files) { std::unique_ptr<ResourceFile> resource_file(new ResourceFile(filename)); std::string base(resource_file->file_name()); for (size_t i = 0; i < base.length(); ++i) { if (base[i] == '\\') { base[i] = '/'; } } base.erase(0, cache_directory.length()); if (base[0] == '/') { base.erase(0, 1); } resource_file->SetHostPathFromBase(base); resource_file->Read(); AddResponse(resource_file->host(), resource_file->path(), resource_file->spdy_headers().Clone(), resource_file->body()); } cache_initialized_ = true; return true; } void QuicMemoryCacheBackend::GenerateDynamicResponses() { quiche::QuicheWriterMutexLock lock(&response_mutex_); quiche::HttpHeaderBlock response_headers; response_headers[":status"] = "200"; generate_bytes_response_ = std::make_unique<QuicBackendResponse>(); generate_bytes_response_->set_headers(std::move(response_headers)); generate_bytes_response_->set_response_type( QuicBackendResponse::GENERATE_BYTES); } void QuicMemoryCacheBackend::EnableWebTransport() { enable_webtransport_ = true; } bool QuicMemoryCacheBackend::IsBackendInitialized() const { return cache_initialized_; } void QuicMemoryCacheBackend::FetchResponseFromBackend( const HttpHeaderBlock& request_headers, const std::string& request_body, QuicSimpleServerBackend::RequestHandler* quic_stream) { const QuicBackendResponse* quic_response = nullptr; auto authority = request_headers.find(":authority"); auto path_it = request_headers.find(":path"); const absl::string_view* path = nullptr; if (path_it != request_headers.end()) { path = &path_it->second; } auto method = request_headers.find(":method"); std::unique_ptr<QuicBackendResponse> echo_response; if (path && *path == "/echo" && method != request_headers.end() && method->second == "POST") { echo_response = std::make_unique<QuicBackendResponse>(); quiche::HttpHeaderBlock response_headers; response_headers[":status"] = "200"; echo_response->set_headers(std::move(response_headers)); echo_response->set_body(request_body); quic_response = echo_response.get(); } else if (authority != request_headers.end() && path) { quic_response = GetResponse(authority->second, *path); } std::string request_url; if (authority != request_headers.end()) { request_url = std::string(authority->second); } if (path) { request_url += std::string(*path); } QUIC_DVLOG(1) << "Fetching QUIC response from backend in-memory cache for url " << request_url; quic_stream->OnResponseBackendComplete(quic_response); } void QuicMemoryCacheBackend::CloseBackendResponseStream( QuicSimpleServerBackend::RequestHandler* ) {} QuicMemoryCacheBackend::WebTransportResponse QuicMemoryCacheBackend::ProcessWebTransportRequest( const quiche::HttpHeaderBlock& request_headers, WebTransportSession* session) { if (!SupportsWebTransport()) { return QuicSimpleServerBackend::ProcessWebTransportRequest(request_headers, session); } auto path_it = request_headers.find(":path"); if (path_it == request_headers.end()) { WebTransportResponse response; response.response_headers[":status"] = "400"; return response; } absl::string_view path = path_it->second; if (path == "/echo") { WebTransportResponse response; response.response_headers[":status"] = "200"; response.visitor = std::make_unique<EchoWebTransportSessionVisitor>(session); return response; } WebTransportResponse response; response.response_headers[":status"] = "404"; return response; } QuicMemoryCacheBackend::~QuicMemoryCacheBackend() { { quiche::QuicheWriterMutexLock lock(&response_mutex_); responses_.clear(); } } void QuicMemoryCacheBackend::AddResponseImpl( absl::string_view host, absl::string_view path, SpecialResponseType response_type, HttpHeaderBlock response_headers, absl::string_view response_body, HttpHeaderBlock response_trailers, const std::vector<quiche::HttpHeaderBlock>& early_hints) { quiche::QuicheWriterMutexLock lock(&response_mutex_); QUICHE_DCHECK(!host.empty()) << "Host must be populated, e.g. \"www.google.com\""; std::string key = GetKey(host, path); if (responses_.contains(key)) { QUIC_BUG(quic_bug_10932_3) << "Response for '" << key << "' already exists!"; return; } auto new_response = std::make_unique<QuicBackendResponse>(); new_response->set_response_type(response_type); new_response->set_headers(std::move(response_headers)); new_response->set_body(response_body); new_response->set_trailers(std::move(response_trailers)); for (auto& headers : early_hints) { new_response->AddEarlyHints(headers); } QUIC_DVLOG(1) << "Add response with key " << key; responses_[key] = std::move(new_response); } std::string QuicMemoryCacheBackend::GetKey(absl::string_view host, absl::string_view path) const { std::string host_string = std::string(host); size_t port = host_string.find(':'); if (port != std::string::npos) host_string = std::string(host_string.c_str(), port); return host_string + std::string(path); } }
#include "quiche/quic/tools/quic_memory_cache_backend.h" #include <string> #include <utility> #include <vector> #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/tools/quic_backend_response.h" #include "quiche/common/platform/api/quiche_file_utils.h" #include "quiche/common/platform/api/quiche_test.h" namespace quic { namespace test { namespace { using Response = QuicBackendResponse; class TestRequestHandler : public QuicSimpleServerBackend::RequestHandler { public: ~TestRequestHandler() override = default; QuicConnectionId connection_id() const override { return QuicConnectionId(); } QuicStreamId stream_id() const override { return QuicStreamId(0); } std::string peer_host() const override { return "test.example.com"; } QuicSpdyStream* GetStream() override { return nullptr; } virtual void OnResponseBackendComplete( const QuicBackendResponse* response) override { response_headers_ = response->headers().Clone(); response_body_ = response->body(); } void SendStreamData(absl::string_view, bool) override {} void TerminateStreamWithError(QuicResetStreamError) override {} const quiche::HttpHeaderBlock& ResponseHeaders() const { return response_headers_; } const std::string& ResponseBody() const { return response_body_; } private: quiche::HttpHeaderBlock response_headers_; std::string response_body_; }; } class QuicMemoryCacheBackendTest : public QuicTest { protected: void CreateRequest(std::string host, std::string path, quiche::HttpHeaderBlock* headers) { (*headers)[":method"] = "GET"; (*headers)[":path"] = path; (*headers)[":authority"] = host; (*headers)[":scheme"] = "https"; } std::string CacheDirectory() { return quiche::test::QuicheGetTestMemoryCachePath(); } QuicMemoryCacheBackend cache_; }; TEST_F(QuicMemoryCacheBackendTest, GetResponseNoMatch) { const Response* response = cache_.GetResponse("mail.google.com", "/index.html"); ASSERT_FALSE(response); } TEST_F(QuicMemoryCacheBackendTest, AddSimpleResponseGetResponse) { std::string response_body("hello response"); cache_.AddSimpleResponse("www.google.com", "/", 200, response_body); quiche::HttpHeaderBlock request_headers; CreateRequest("www.google.com", "/", &request_headers); const Response* response = cache_.GetResponse("www.google.com", "/"); ASSERT_TRUE(response); ASSERT_TRUE(response->headers().contains(":status")); EXPECT_EQ("200", response->headers().find(":status")->second); EXPECT_EQ(response_body.size(), response->body().length()); } TEST_F(QuicMemoryCacheBackendTest, AddResponse) { const std::string kRequestHost = "www.foo.com"; const std::string kRequestPath = "/"; const std::string kResponseBody("hello response"); quiche::HttpHeaderBlock response_headers; response_headers[":status"] = "200"; response_headers["content-length"] = absl::StrCat(kResponseBody.size()); quiche::HttpHeaderBlock response_trailers; response_trailers["key-1"] = "value-1"; response_trailers["key-2"] = "value-2"; response_trailers["key-3"] = "value-3"; cache_.AddResponse(kRequestHost, "/", response_headers.Clone(), kResponseBody, response_trailers.Clone()); const Response* response = cache_.GetResponse(kRequestHost, kRequestPath); EXPECT_EQ(response->headers(), response_headers); EXPECT_EQ(response->body(), kResponseBody); EXPECT_EQ(response->trailers(), response_trailers); } #if defined(OS_IOS) #define MAYBE_ReadsCacheDir DISABLED_ReadsCacheDir #else #define MAYBE_ReadsCacheDir ReadsCacheDir #endif TEST_F(QuicMemoryCacheBackendTest, MAYBE_ReadsCacheDir) { cache_.InitializeBackend(CacheDirectory()); const Response* response = cache_.GetResponse("test.example.com", "/index.html"); ASSERT_TRUE(response); ASSERT_TRUE(response->headers().contains(":status")); EXPECT_EQ("200", response->headers().find(":status")->second); EXPECT_FALSE(response->headers().contains("connection")); EXPECT_LT(0U, response->body().length()); } #if defined(OS_IOS) #define MAYBE_UsesOriginalUrl DISABLED_UsesOriginalUrl #else #define MAYBE_UsesOriginalUrl UsesOriginalUrl #endif TEST_F(QuicMemoryCacheBackendTest, MAYBE_UsesOriginalUrl) { cache_.InitializeBackend(CacheDirectory()); const Response* response = cache_.GetResponse("test.example.com", "/site_map.html"); ASSERT_TRUE(response); ASSERT_TRUE(response->headers().contains(":status")); EXPECT_EQ("200", response->headers().find(":status")->second); EXPECT_FALSE(response->headers().contains("connection")); EXPECT_LT(0U, response->body().length()); } #if defined(OS_IOS) #define MAYBE_UsesOriginalUrlOnly DISABLED_UsesOriginalUrlOnly #else #define MAYBE_UsesOriginalUrlOnly UsesOriginalUrlOnly #endif TEST_F(QuicMemoryCacheBackendTest, MAYBE_UsesOriginalUrlOnly) { std::string dir; std::string path = "map.html"; std::vector<std::string> files; ASSERT_TRUE(quiche::EnumerateDirectoryRecursively(CacheDirectory(), files)); for (const std::string& file : files) { if (absl::EndsWithIgnoreCase(file, "map.html")) { dir = file; dir.erase(dir.length() - path.length() - 1); break; } } ASSERT_NE("", dir); cache_.InitializeBackend(dir); const Response* response = cache_.GetResponse("test.example.com", "/site_map.html"); ASSERT_TRUE(response); ASSERT_TRUE(response->headers().contains(":status")); EXPECT_EQ("200", response->headers().find(":status")->second); EXPECT_FALSE(response->headers().contains("connection")); EXPECT_LT(0U, response->body().length()); } TEST_F(QuicMemoryCacheBackendTest, DefaultResponse) { const Response* response = cache_.GetResponse("www.google.com", "/"); ASSERT_FALSE(response); quiche::HttpHeaderBlock response_headers; response_headers[":status"] = "200"; response_headers["content-length"] = "0"; Response* default_response = new Response; default_response->set_headers(std::move(response_headers)); cache_.AddDefaultResponse(default_response); response = cache_.GetResponse("www.google.com", "/"); ASSERT_TRUE(response); ASSERT_TRUE(response->headers().contains(":status")); EXPECT_EQ("200", response->headers().find(":status")->second); cache_.AddSimpleResponse("www.google.com", "/", 302, ""); response = cache_.GetResponse("www.google.com", "/"); ASSERT_TRUE(response); ASSERT_TRUE(response->headers().contains(":status")); EXPECT_EQ("302", response->headers().find(":status")->second); response = cache_.GetResponse("www.google.com", "/asd"); ASSERT_TRUE(response); ASSERT_TRUE(response->headers().contains(":status")); EXPECT_EQ("200", response->headers().find(":status")->second); } TEST_F(QuicMemoryCacheBackendTest, Echo) { quiche::HttpHeaderBlock request_headers; request_headers[":method"] = "POST"; request_headers[":path"] = "/echo"; const std::string request_body("hello request"); TestRequestHandler handler; cache_.FetchResponseFromBackend(request_headers, request_body, &handler); EXPECT_EQ("200", handler.ResponseHeaders().find(":status")->second); EXPECT_EQ(request_body, handler.ResponseBody()); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/tools/quic_memory_cache_backend.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/tools/quic_memory_cache_backend_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
bb987976-7a50-4c17-970f-4192c7c8ad98
cpp
google/quiche
connect_tunnel
quiche/quic/tools/connect_tunnel.cc
quiche/quic/tools/connect_tunnel_test.cc
#include "quiche/quic/tools/connect_tunnel.h" #include <cstdint> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_server_id.h" #include "quiche/quic/core/socket_factory.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/tools/quic_backend_response.h" #include "quiche/quic/tools/quic_name_lookup.h" #include "quiche/quic/tools/quic_simple_server_backend.h" #include "quiche/common/http/http_header_block.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_mem_slice.h" namespace quic { namespace { constexpr size_t kReadSize = 4 * 1024; std::optional<QuicServerId> ValidateHeadersAndGetAuthority( const quiche::HttpHeaderBlock& request_headers) { QUICHE_DCHECK(request_headers.contains(":method")); QUICHE_DCHECK(request_headers.find(":method")->second == "CONNECT"); QUICHE_DCHECK(!request_headers.contains(":protocol")); auto scheme_it = request_headers.find(":scheme"); if (scheme_it != request_headers.end()) { QUICHE_DVLOG(1) << "CONNECT request contains unexpected scheme: " << scheme_it->second; return std::nullopt; } auto path_it = request_headers.find(":path"); if (path_it != request_headers.end()) { QUICHE_DVLOG(1) << "CONNECT request contains unexpected path: " << path_it->second; return std::nullopt; } auto authority_it = request_headers.find(":authority"); if (authority_it == request_headers.end() || authority_it->second.empty()) { QUICHE_DVLOG(1) << "CONNECT request missing authority"; return std::nullopt; } std::optional<QuicServerId> server_id = QuicServerId::ParseFromHostPortString(authority_it->second); if (!server_id.has_value()) { QUICHE_DVLOG(1) << "CONNECT request authority is malformed: " << authority_it->second; return std::nullopt; } return server_id; } bool ValidateAuthority( const QuicServerId& authority, const absl::flat_hash_set<QuicServerId>& acceptable_destinations) { if (acceptable_destinations.contains(authority)) { return true; } QUICHE_DVLOG(1) << "CONNECT request authority: " << authority.ToHostPortString() << " is not an acceptable allow-listed destiation "; return false; } } ConnectTunnel::ConnectTunnel( QuicSimpleServerBackend::RequestHandler* client_stream_request_handler, SocketFactory* socket_factory, absl::flat_hash_set<QuicServerId> acceptable_destinations) : acceptable_destinations_(std::move(acceptable_destinations)), socket_factory_(socket_factory), client_stream_request_handler_(client_stream_request_handler) { QUICHE_DCHECK(client_stream_request_handler_); QUICHE_DCHECK(socket_factory_); } ConnectTunnel::~ConnectTunnel() { QUICHE_DCHECK_EQ(client_stream_request_handler_, nullptr); QUICHE_DCHECK(!IsConnectedToDestination()); QUICHE_DCHECK(!receive_started_); } void ConnectTunnel::OpenTunnel(const quiche::HttpHeaderBlock& request_headers) { QUICHE_DCHECK(!IsConnectedToDestination()); std::optional<QuicServerId> authority = ValidateHeadersAndGetAuthority(request_headers); if (!authority.has_value()) { TerminateClientStream( "invalid request headers", QuicResetStreamError::FromIetf(QuicHttp3ErrorCode::MESSAGE_ERROR)); return; } if (!ValidateAuthority(authority.value(), acceptable_destinations_)) { TerminateClientStream( "disallowed request authority", QuicResetStreamError::FromIetf(QuicHttp3ErrorCode::REQUEST_REJECTED)); return; } QuicSocketAddress address = tools::LookupAddress(AF_UNSPEC, authority.value()); if (!address.IsInitialized()) { TerminateClientStream("host resolution error"); return; } destination_socket_ = socket_factory_->CreateTcpClientSocket(address, 0, 0, this); QUICHE_DCHECK(destination_socket_); absl::Status connect_result = destination_socket_->ConnectBlocking(); if (!connect_result.ok()) { TerminateClientStream( "error connecting TCP socket to destination server: " + connect_result.ToString()); return; } QUICHE_DVLOG(1) << "CONNECT tunnel opened from stream " << client_stream_request_handler_->stream_id() << " to " << authority.value().ToHostPortString(); SendConnectResponse(); BeginAsyncReadFromDestination(); } bool ConnectTunnel::IsConnectedToDestination() const { return !!destination_socket_; } void ConnectTunnel::SendDataToDestination(absl::string_view data) { QUICHE_DCHECK(IsConnectedToDestination()); QUICHE_DCHECK(!data.empty()); absl::Status send_result = destination_socket_->SendBlocking(std::string(data)); if (!send_result.ok()) { TerminateClientStream("TCP error sending data to destination server: " + send_result.ToString()); } } void ConnectTunnel::OnClientStreamClose() { QUICHE_DCHECK(client_stream_request_handler_); QUICHE_DVLOG(1) << "CONNECT stream " << client_stream_request_handler_->stream_id() << " closed"; client_stream_request_handler_ = nullptr; if (IsConnectedToDestination()) { destination_socket_->Disconnect(); } destination_socket_.reset(); } void ConnectTunnel::ConnectComplete(absl::Status ) { QUICHE_NOTREACHED(); } void ConnectTunnel::ReceiveComplete( absl::StatusOr<quiche::QuicheMemSlice> data) { QUICHE_DCHECK(IsConnectedToDestination()); QUICHE_DCHECK(receive_started_); receive_started_ = false; if (!data.ok()) { if (client_stream_request_handler_) { TerminateClientStream("TCP error receiving data from destination server"); } else { QUICHE_DVLOG(1) << "TCP error receiving data from destination server " "after stream already closed."; } return; } else if (data.value().empty()) { OnDestinationConnectionClosed(); return; } QUICHE_DCHECK(client_stream_request_handler_); client_stream_request_handler_->SendStreamData(data.value().AsStringView(), false); BeginAsyncReadFromDestination(); } void ConnectTunnel::SendComplete(absl::Status ) { QUICHE_NOTREACHED(); } void ConnectTunnel::BeginAsyncReadFromDestination() { QUICHE_DCHECK(IsConnectedToDestination()); QUICHE_DCHECK(client_stream_request_handler_); QUICHE_DCHECK(!receive_started_); receive_started_ = true; destination_socket_->ReceiveAsync(kReadSize); } void ConnectTunnel::OnDestinationConnectionClosed() { QUICHE_DCHECK(IsConnectedToDestination()); QUICHE_DCHECK(client_stream_request_handler_); QUICHE_DVLOG(1) << "CONNECT stream " << client_stream_request_handler_->stream_id() << " destination connection closed"; destination_socket_->Disconnect(); destination_socket_.reset(); QUICHE_DCHECK(client_stream_request_handler_); client_stream_request_handler_->SendStreamData("", true); } void ConnectTunnel::SendConnectResponse() { QUICHE_DCHECK(IsConnectedToDestination()); QUICHE_DCHECK(client_stream_request_handler_); quiche::HttpHeaderBlock response_headers; response_headers[":status"] = "200"; QuicBackendResponse response; response.set_headers(std::move(response_headers)); response.set_response_type(QuicBackendResponse::INCOMPLETE_RESPONSE); client_stream_request_handler_->OnResponseBackendComplete(&response); } void ConnectTunnel::TerminateClientStream(absl::string_view error_description, QuicResetStreamError error_code) { QUICHE_DCHECK(client_stream_request_handler_); std::string error_description_str = error_description.empty() ? "" : absl::StrCat(" due to ", error_description); QUICHE_DVLOG(1) << "Terminating CONNECT stream " << client_stream_request_handler_->stream_id() << " with error code " << error_code.ietf_application_code() << error_description_str; client_stream_request_handler_->TerminateStreamWithError(error_code); } }
#include "quiche/quic/tools/connect_tunnel.h" #include <cstdint> #include <memory> #include <string> #include <utility> #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/connecting_client_socket.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/socket_factory.h" #include "quiche/quic/platform/api/quic_socket_address.h" #include "quiche/quic/platform/api/quic_test_loopback.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/tools/quic_backend_response.h" #include "quiche/quic/tools/quic_simple_server_backend.h" #include "quiche/common/http/http_header_block.h" #include "quiche/common/platform/api/quiche_mem_slice.h" #include "quiche/common/platform/api/quiche_test.h" namespace quic::test { namespace { using ::testing::_; using ::testing::AllOf; using ::testing::AnyOf; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::Ge; using ::testing::Gt; using ::testing::InvokeWithoutArgs; using ::testing::IsEmpty; using ::testing::Matcher; using ::testing::NiceMock; using ::testing::Pair; using ::testing::Property; using ::testing::Return; using ::testing::StrictMock; class MockRequestHandler : public QuicSimpleServerBackend::RequestHandler { public: QuicConnectionId connection_id() const override { return TestConnectionId(41212); } QuicStreamId stream_id() const override { return 100; } std::string peer_host() const override { return "127.0.0.1"; } MOCK_METHOD(QuicSpdyStream*, GetStream, (), (override)); MOCK_METHOD(void, OnResponseBackendComplete, (const QuicBackendResponse* response), (override)); MOCK_METHOD(void, SendStreamData, (absl::string_view data, bool close_stream), (override)); MOCK_METHOD(void, TerminateStreamWithError, (QuicResetStreamError error), (override)); }; class MockSocketFactory : public SocketFactory { public: MOCK_METHOD(std::unique_ptr<ConnectingClientSocket>, CreateTcpClientSocket, (const quic::QuicSocketAddress& peer_address, QuicByteCount receive_buffer_size, QuicByteCount send_buffer_size, ConnectingClientSocket::AsyncVisitor* async_visitor), (override)); MOCK_METHOD(std::unique_ptr<ConnectingClientSocket>, CreateConnectingUdpClientSocket, (const quic::QuicSocketAddress& peer_address, QuicByteCount receive_buffer_size, QuicByteCount send_buffer_size, ConnectingClientSocket::AsyncVisitor* async_visitor), (override)); }; class MockSocket : public ConnectingClientSocket { public: MOCK_METHOD(absl::Status, ConnectBlocking, (), (override)); MOCK_METHOD(void, ConnectAsync, (), (override)); MOCK_METHOD(void, Disconnect, (), (override)); MOCK_METHOD(absl::StatusOr<QuicSocketAddress>, GetLocalAddress, (), (override)); MOCK_METHOD(absl::StatusOr<quiche::QuicheMemSlice>, ReceiveBlocking, (QuicByteCount max_size), (override)); MOCK_METHOD(void, ReceiveAsync, (QuicByteCount max_size), (override)); MOCK_METHOD(absl::Status, SendBlocking, (std::string data), (override)); MOCK_METHOD(absl::Status, SendBlocking, (quiche::QuicheMemSlice data), (override)); MOCK_METHOD(void, SendAsync, (std::string data), (override)); MOCK_METHOD(void, SendAsync, (quiche::QuicheMemSlice data), (override)); }; class ConnectTunnelTest : public quiche::test::QuicheTest { public: void SetUp() override { #if defined(_WIN32) WSADATA wsa_data; const WORD version_required = MAKEWORD(2, 2); ASSERT_EQ(WSAStartup(version_required, &wsa_data), 0); #endif auto socket = std::make_unique<StrictMock<MockSocket>>(); socket_ = socket.get(); ON_CALL(socket_factory_, CreateTcpClientSocket( AnyOf(QuicSocketAddress(TestLoopback4(), kAcceptablePort), QuicSocketAddress(TestLoopback6(), kAcceptablePort)), _, _, &tunnel_)) .WillByDefault(Return(ByMove(std::move(socket)))); } protected: static constexpr absl::string_view kAcceptableDestination = "localhost"; static constexpr uint16_t kAcceptablePort = 977; StrictMock<MockRequestHandler> request_handler_; NiceMock<MockSocketFactory> socket_factory_; StrictMock<MockSocket>* socket_; ConnectTunnel tunnel_{ &request_handler_, &socket_factory_, {{std::string(kAcceptableDestination), kAcceptablePort}, {TestLoopback4().ToString(), kAcceptablePort}, {absl::StrCat("[", TestLoopback6().ToString(), "]"), kAcceptablePort}}}; }; TEST_F(ConnectTunnelTest, OpenTunnel) { EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, ReceiveAsync(Gt(0))); EXPECT_CALL(*socket_, Disconnect()).WillOnce(InvokeWithoutArgs([this]() { tunnel_.ReceiveComplete(absl::CancelledError()); })); quiche::HttpHeaderBlock expected_response_headers; expected_response_headers[":status"] = "200"; QuicBackendResponse expected_response; expected_response.set_headers(std::move(expected_response_headers)); expected_response.set_response_type(QuicBackendResponse::INCOMPLETE_RESPONSE); EXPECT_CALL(request_handler_, OnResponseBackendComplete( AllOf(Property(&QuicBackendResponse::response_type, QuicBackendResponse::INCOMPLETE_RESPONSE), Property(&QuicBackendResponse::headers, ElementsAre(Pair(":status", "200"))), Property(&QuicBackendResponse::trailers, IsEmpty()), Property(&QuicBackendResponse::body, IsEmpty())))); quiche::HttpHeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":authority"] = absl::StrCat(kAcceptableDestination, ":", kAcceptablePort); tunnel_.OpenTunnel(request_headers); EXPECT_TRUE(tunnel_.IsConnectedToDestination()); tunnel_.OnClientStreamClose(); EXPECT_FALSE(tunnel_.IsConnectedToDestination()); } TEST_F(ConnectTunnelTest, OpenTunnelToIpv4LiteralDestination) { EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, ReceiveAsync(Gt(0))); EXPECT_CALL(*socket_, Disconnect()).WillOnce(InvokeWithoutArgs([this]() { tunnel_.ReceiveComplete(absl::CancelledError()); })); quiche::HttpHeaderBlock expected_response_headers; expected_response_headers[":status"] = "200"; QuicBackendResponse expected_response; expected_response.set_headers(std::move(expected_response_headers)); expected_response.set_response_type(QuicBackendResponse::INCOMPLETE_RESPONSE); EXPECT_CALL(request_handler_, OnResponseBackendComplete( AllOf(Property(&QuicBackendResponse::response_type, QuicBackendResponse::INCOMPLETE_RESPONSE), Property(&QuicBackendResponse::headers, ElementsAre(Pair(":status", "200"))), Property(&QuicBackendResponse::trailers, IsEmpty()), Property(&QuicBackendResponse::body, IsEmpty())))); quiche::HttpHeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":authority"] = absl::StrCat(TestLoopback4().ToString(), ":", kAcceptablePort); tunnel_.OpenTunnel(request_headers); EXPECT_TRUE(tunnel_.IsConnectedToDestination()); tunnel_.OnClientStreamClose(); EXPECT_FALSE(tunnel_.IsConnectedToDestination()); } TEST_F(ConnectTunnelTest, OpenTunnelToIpv6LiteralDestination) { EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, ReceiveAsync(Gt(0))); EXPECT_CALL(*socket_, Disconnect()).WillOnce(InvokeWithoutArgs([this]() { tunnel_.ReceiveComplete(absl::CancelledError()); })); quiche::HttpHeaderBlock expected_response_headers; expected_response_headers[":status"] = "200"; QuicBackendResponse expected_response; expected_response.set_headers(std::move(expected_response_headers)); expected_response.set_response_type(QuicBackendResponse::INCOMPLETE_RESPONSE); EXPECT_CALL(request_handler_, OnResponseBackendComplete( AllOf(Property(&QuicBackendResponse::response_type, QuicBackendResponse::INCOMPLETE_RESPONSE), Property(&QuicBackendResponse::headers, ElementsAre(Pair(":status", "200"))), Property(&QuicBackendResponse::trailers, IsEmpty()), Property(&QuicBackendResponse::body, IsEmpty())))); quiche::HttpHeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":authority"] = absl::StrCat("[", TestLoopback6().ToString(), "]:", kAcceptablePort); tunnel_.OpenTunnel(request_headers); EXPECT_TRUE(tunnel_.IsConnectedToDestination()); tunnel_.OnClientStreamClose(); EXPECT_FALSE(tunnel_.IsConnectedToDestination()); } TEST_F(ConnectTunnelTest, OpenTunnelWithMalformedRequest) { EXPECT_CALL(request_handler_, TerminateStreamWithError(Property( &QuicResetStreamError::ietf_application_code, static_cast<uint64_t>(QuicHttp3ErrorCode::MESSAGE_ERROR)))); quiche::HttpHeaderBlock request_headers; request_headers[":method"] = "CONNECT"; tunnel_.OpenTunnel(request_headers); EXPECT_FALSE(tunnel_.IsConnectedToDestination()); tunnel_.OnClientStreamClose(); } TEST_F(ConnectTunnelTest, OpenTunnelWithUnacceptableDestination) { EXPECT_CALL( request_handler_, TerminateStreamWithError(Property( &QuicResetStreamError::ietf_application_code, static_cast<uint64_t>(QuicHttp3ErrorCode::REQUEST_REJECTED)))); quiche::HttpHeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":authority"] = "unacceptable.test:100"; tunnel_.OpenTunnel(request_headers); EXPECT_FALSE(tunnel_.IsConnectedToDestination()); tunnel_.OnClientStreamClose(); } TEST_F(ConnectTunnelTest, ReceiveFromDestination) { static constexpr absl::string_view kData = "\x11\x22\x33\x44\x55"; EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, ReceiveAsync(Ge(kData.size()))).Times(2); EXPECT_CALL(*socket_, Disconnect()).WillOnce(InvokeWithoutArgs([this]() { tunnel_.ReceiveComplete(absl::CancelledError()); })); EXPECT_CALL(request_handler_, OnResponseBackendComplete(_)); EXPECT_CALL(request_handler_, SendStreamData(kData, false)); quiche::HttpHeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":authority"] = absl::StrCat(kAcceptableDestination, ":", kAcceptablePort); tunnel_.OpenTunnel(request_headers); tunnel_.ReceiveComplete(MemSliceFromString(kData)); tunnel_.OnClientStreamClose(); } TEST_F(ConnectTunnelTest, SendToDestination) { static constexpr absl::string_view kData = "\x11\x22\x33\x44\x55"; EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, ReceiveAsync(Gt(0))); EXPECT_CALL(*socket_, SendBlocking(Matcher<std::string>(Eq(kData)))) .WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, Disconnect()).WillOnce(InvokeWithoutArgs([this]() { tunnel_.ReceiveComplete(absl::CancelledError()); })); EXPECT_CALL(request_handler_, OnResponseBackendComplete(_)); quiche::HttpHeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":authority"] = absl::StrCat(kAcceptableDestination, ":", kAcceptablePort); tunnel_.OpenTunnel(request_headers); tunnel_.SendDataToDestination(kData); tunnel_.OnClientStreamClose(); } TEST_F(ConnectTunnelTest, DestinationDisconnect) { EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, ReceiveAsync(Gt(0))); EXPECT_CALL(*socket_, Disconnect()); EXPECT_CALL(request_handler_, OnResponseBackendComplete(_)); EXPECT_CALL(request_handler_, SendStreamData("", true)); quiche::HttpHeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":authority"] = absl::StrCat(kAcceptableDestination, ":", kAcceptablePort); tunnel_.OpenTunnel(request_headers); tunnel_.ReceiveComplete(quiche::QuicheMemSlice()); EXPECT_FALSE(tunnel_.IsConnectedToDestination()); tunnel_.OnClientStreamClose(); } TEST_F(ConnectTunnelTest, DestinationTcpConnectionError) { EXPECT_CALL(*socket_, ConnectBlocking()).WillOnce(Return(absl::OkStatus())); EXPECT_CALL(*socket_, ReceiveAsync(Gt(0))); EXPECT_CALL(*socket_, Disconnect()); EXPECT_CALL(request_handler_, OnResponseBackendComplete(_)); EXPECT_CALL(request_handler_, TerminateStreamWithError(Property( &QuicResetStreamError::ietf_application_code, static_cast<uint64_t>(QuicHttp3ErrorCode::CONNECT_ERROR)))); quiche::HttpHeaderBlock request_headers; request_headers[":method"] = "CONNECT"; request_headers[":authority"] = absl::StrCat(kAcceptableDestination, ":", kAcceptablePort); tunnel_.OpenTunnel(request_headers); tunnel_.ReceiveComplete(absl::UnknownError("error")); tunnel_.OnClientStreamClose(); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/tools/connect_tunnel.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/tools/connect_tunnel_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
775abaa1-3f56-4e07-923e-e42057cba524
cpp
google/quiche
quic_tcp_like_trace_converter
quiche/quic/tools/quic_tcp_like_trace_converter.cc
quiche/quic/tools/quic_tcp_like_trace_converter_test.cc
#include "quiche/quic/tools/quic_tcp_like_trace_converter.h" #include <algorithm> #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" namespace quic { QuicTcpLikeTraceConverter::QuicTcpLikeTraceConverter() : largest_observed_control_frame_id_(kInvalidControlFrameId), connection_offset_(0) {} QuicTcpLikeTraceConverter::StreamOffsetSegment::StreamOffsetSegment() : connection_offset(0) {} QuicTcpLikeTraceConverter::StreamOffsetSegment::StreamOffsetSegment( QuicStreamOffset stream_offset, uint64_t connection_offset, QuicByteCount data_length) : stream_data(stream_offset, stream_offset + data_length), connection_offset(connection_offset) {} QuicTcpLikeTraceConverter::StreamInfo::StreamInfo() : fin(false) {} QuicIntervalSet<uint64_t> QuicTcpLikeTraceConverter::OnCryptoFrameSent( EncryptionLevel level, QuicStreamOffset offset, QuicByteCount data_length) { if (level >= NUM_ENCRYPTION_LEVELS) { QUIC_BUG(quic_bug_10907_1) << "Invalid encryption level"; return {}; } return OnFrameSent(offset, data_length, false, &crypto_frames_info_[level]); } QuicIntervalSet<uint64_t> QuicTcpLikeTraceConverter::OnStreamFrameSent( QuicStreamId stream_id, QuicStreamOffset offset, QuicByteCount data_length, bool fin) { return OnFrameSent( offset, data_length, fin, &streams_info_.emplace(stream_id, StreamInfo()).first->second); } QuicIntervalSet<uint64_t> QuicTcpLikeTraceConverter::OnFrameSent( QuicStreamOffset offset, QuicByteCount data_length, bool fin, StreamInfo* info) { QuicIntervalSet<uint64_t> connection_offsets; if (fin) { ++data_length; } for (const auto& segment : info->segments) { QuicInterval<QuicStreamOffset> retransmission(offset, offset + data_length); retransmission.IntersectWith(segment.stream_data); if (retransmission.Empty()) { continue; } const uint64_t connection_offset = segment.connection_offset + retransmission.min() - segment.stream_data.min(); connection_offsets.Add(connection_offset, connection_offset + retransmission.Length()); } if (info->fin) { return connection_offsets; } QuicStreamOffset least_unsent_offset = info->segments.empty() ? 0 : info->segments.back().stream_data.max(); if (least_unsent_offset >= offset + data_length) { return connection_offsets; } QuicStreamOffset new_data_offset = std::max(least_unsent_offset, offset); QuicByteCount new_data_length = offset + data_length - new_data_offset; connection_offsets.Add(connection_offset_, connection_offset_ + new_data_length); if (!info->segments.empty() && new_data_offset == least_unsent_offset && connection_offset_ == info->segments.back().connection_offset + info->segments.back().stream_data.Length()) { info->segments.back().stream_data.SetMax(new_data_offset + new_data_length); } else { info->segments.emplace_back(new_data_offset, connection_offset_, new_data_length); } info->fin = fin; connection_offset_ += new_data_length; return connection_offsets; } QuicInterval<uint64_t> QuicTcpLikeTraceConverter::OnControlFrameSent( QuicControlFrameId control_frame_id, QuicByteCount control_frame_length) { if (control_frame_id > largest_observed_control_frame_id_) { QuicInterval<uint64_t> connection_offset = QuicInterval<uint64_t>( connection_offset_, connection_offset_ + control_frame_length); connection_offset_ += control_frame_length; control_frames_info_[control_frame_id] = connection_offset; largest_observed_control_frame_id_ = control_frame_id; return connection_offset; } const auto iter = control_frames_info_.find(control_frame_id); if (iter == control_frames_info_.end()) { return {}; } return iter->second; } }
#include "quiche/quic/tools/quic_tcp_like_trace_converter.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { namespace { TEST(QuicTcpLikeTraceConverterTest, BasicTest) { QuicTcpLikeTraceConverter converter; EXPECT_EQ(QuicIntervalSet<uint64_t>(0, 100), converter.OnStreamFrameSent(1, 0, 100, false)); EXPECT_EQ(QuicIntervalSet<uint64_t>(100, 200), converter.OnStreamFrameSent(3, 0, 100, false)); EXPECT_EQ(QuicIntervalSet<uint64_t>(200, 300), converter.OnStreamFrameSent(3, 100, 100, false)); EXPECT_EQ(QuicInterval<uint64_t>(300, 450), converter.OnControlFrameSent(2, 150)); EXPECT_EQ(QuicIntervalSet<uint64_t>(450, 550), converter.OnStreamFrameSent(1, 100, 100, false)); EXPECT_EQ(QuicInterval<uint64_t>(550, 650), converter.OnControlFrameSent(3, 100)); EXPECT_EQ(QuicIntervalSet<uint64_t>(650, 850), converter.OnStreamFrameSent(3, 200, 200, false)); EXPECT_EQ(QuicInterval<uint64_t>(850, 1050), converter.OnControlFrameSent(4, 200)); EXPECT_EQ(QuicIntervalSet<uint64_t>(1050, 1100), converter.OnStreamFrameSent(1, 200, 50, false)); EXPECT_EQ(QuicIntervalSet<uint64_t>(1100, 1150), converter.OnStreamFrameSent(1, 250, 50, false)); EXPECT_EQ(QuicIntervalSet<uint64_t>(1150, 1350), converter.OnStreamFrameSent(3, 400, 200, false)); QuicIntervalSet<uint64_t> expected; expected.Add(50, 100); expected.Add(450, 550); expected.Add(1050, 1150); expected.Add(1350, 1401); EXPECT_EQ(expected, converter.OnStreamFrameSent(1, 50, 300, true)); expected.Clear(); expected.Add(250, 300); expected.Add(650, 850); expected.Add(1150, 1250); EXPECT_EQ(expected, converter.OnStreamFrameSent(3, 150, 350, false)); expected.Clear(); expected.Add(750, 850); expected.Add(1150, 1350); expected.Add(1401, 1602); EXPECT_EQ(expected, converter.OnStreamFrameSent(3, 300, 500, true)); expected.Clear(); expected.Add(1601, 1602); EXPECT_EQ(expected, converter.OnStreamFrameSent(3, 800, 0, true)); QuicInterval<uint64_t> expected2; EXPECT_EQ(expected2, converter.OnControlFrameSent(1, 100)); expected2 = {300, 450}; EXPECT_EQ(expected2, converter.OnControlFrameSent(2, 200)); expected2 = {1602, 1702}; EXPECT_EQ(expected2, converter.OnControlFrameSent(10, 100)); } TEST(QuicTcpLikeTraceConverterTest, FuzzerTest) { QuicTcpLikeTraceConverter converter; EXPECT_EQ(QuicIntervalSet<uint64_t>(0, 100), converter.OnStreamFrameSent(1, 100, 100, false)); EXPECT_EQ(QuicIntervalSet<uint64_t>(100, 300), converter.OnStreamFrameSent(3, 200, 200, false)); EXPECT_EQ(QuicIntervalSet<uint64_t>(300, 400), converter.OnStreamFrameSent(1, 300, 100, false)); QuicIntervalSet<uint64_t> expected; expected.Add(0, 100); expected.Add(300, 501); EXPECT_EQ(expected, converter.OnStreamFrameSent(1, 0, 500, true)); EXPECT_EQ(expected, converter.OnStreamFrameSent(1, 50, 600, false)); } TEST(QuicTcpLikeTraceConverterTest, OnCryptoFrameSent) { QuicTcpLikeTraceConverter converter; EXPECT_EQ(QuicIntervalSet<uint64_t>(0, 100), converter.OnCryptoFrameSent(ENCRYPTION_INITIAL, 0, 100)); EXPECT_EQ(QuicIntervalSet<uint64_t>(100, 200), converter.OnStreamFrameSent(1, 0, 100, false)); EXPECT_EQ(QuicIntervalSet<uint64_t>(200, 300), converter.OnStreamFrameSent(1, 100, 100, false)); EXPECT_EQ(QuicIntervalSet<uint64_t>(300, 400), converter.OnCryptoFrameSent(ENCRYPTION_HANDSHAKE, 0, 100)); EXPECT_EQ(QuicIntervalSet<uint64_t>(400, 500), converter.OnCryptoFrameSent(ENCRYPTION_HANDSHAKE, 100, 100)); EXPECT_EQ(QuicIntervalSet<uint64_t>(0, 100), converter.OnCryptoFrameSent(ENCRYPTION_INITIAL, 0, 100)); EXPECT_EQ(QuicIntervalSet<uint64_t>(400, 500), converter.OnCryptoFrameSent(ENCRYPTION_HANDSHAKE, 100, 100)); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/tools/quic_tcp_like_trace_converter.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/tools/quic_tcp_like_trace_converter_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
1e4605fa-a258-4035-815f-4aaa4e0190de
cpp
google/quiche
quic_server
quiche/quic/tools/quic_server.cc
quiche/quic/tools/quic_server_test.cc
#include "quiche/quic/tools/quic_server.h" #include <cstdint> #include <memory> #include <utility> #include "quiche/quic/core/crypto/crypto_handshake.h" #include "quiche/quic/core/crypto/quic_random.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/quic_clock.h" #include "quiche/quic/core/quic_crypto_stream.h" #include "quiche/quic/core/quic_data_reader.h" #include "quiche/quic/core/quic_default_clock.h" #include "quiche/quic/core/quic_default_connection_helper.h" #include "quiche/quic/core/quic_default_packet_writer.h" #include "quiche/quic/core/quic_dispatcher.h" #include "quiche/quic/core/quic_packet_reader.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/tools/quic_simple_crypto_server_stream_helper.h" #include "quiche/quic/tools/quic_simple_dispatcher.h" #include "quiche/quic/tools/quic_simple_server_backend.h" #include "quiche/common/simple_buffer_allocator.h" namespace quic { namespace { const char kSourceAddressTokenSecret[] = "secret"; } const size_t kNumSessionsToCreatePerSocketEvent = 16; QuicServer::QuicServer(std::unique_ptr<ProofSource> proof_source, QuicSimpleServerBackend* quic_simple_server_backend) : QuicServer(std::move(proof_source), quic_simple_server_backend, AllSupportedVersions()) {} QuicServer::QuicServer(std::unique_ptr<ProofSource> proof_source, QuicSimpleServerBackend* quic_simple_server_backend, const ParsedQuicVersionVector& supported_versions) : QuicServer(std::move(proof_source), QuicConfig(), QuicCryptoServerConfig::ConfigOptions(), supported_versions, quic_simple_server_backend, kQuicDefaultConnectionIdLength) {} QuicServer::QuicServer( std::unique_ptr<ProofSource> proof_source, const QuicConfig& config, const QuicCryptoServerConfig::ConfigOptions& crypto_config_options, const ParsedQuicVersionVector& supported_versions, QuicSimpleServerBackend* quic_simple_server_backend, uint8_t expected_server_connection_id_length) : port_(0), fd_(-1), packets_dropped_(0), overflow_supported_(false), silent_close_(false), config_(config), crypto_config_(kSourceAddressTokenSecret, QuicRandom::GetInstance(), std::move(proof_source), KeyExchangeSource::Default()), crypto_config_options_(crypto_config_options), version_manager_(supported_versions), max_sessions_to_create_per_socket_event_( kNumSessionsToCreatePerSocketEvent), packet_reader_(new QuicPacketReader()), quic_simple_server_backend_(quic_simple_server_backend), expected_server_connection_id_length_( expected_server_connection_id_length), connection_id_generator_(expected_server_connection_id_length) { QUICHE_DCHECK(quic_simple_server_backend_); Initialize(); } void QuicServer::Initialize() { const uint32_t kInitialSessionFlowControlWindow = 1 * 1024 * 1024; const uint32_t kInitialStreamFlowControlWindow = 64 * 1024; if (config_.GetInitialStreamFlowControlWindowToSend() == kDefaultFlowControlSendWindow) { config_.SetInitialStreamFlowControlWindowToSend( kInitialStreamFlowControlWindow); } if (config_.GetInitialSessionFlowControlWindowToSend() == kDefaultFlowControlSendWindow) { config_.SetInitialSessionFlowControlWindowToSend( kInitialSessionFlowControlWindow); } std::unique_ptr<CryptoHandshakeMessage> scfg(crypto_config_.AddDefaultConfig( QuicRandom::GetInstance(), QuicDefaultClock::Get(), crypto_config_options_)); } QuicServer::~QuicServer() { if (event_loop_ != nullptr) { if (!event_loop_->UnregisterSocket(fd_)) { QUIC_LOG(ERROR) << "Failed to unregister socket: " << fd_; } } (void)socket_api::Close(fd_); fd_ = kInvalidSocketFd; quic_simple_server_backend_->SetSocketFactory(nullptr); } bool QuicServer::CreateUDPSocketAndListen(const QuicSocketAddress& address) { event_loop_ = CreateEventLoop(); socket_factory_ = std::make_unique<EventLoopSocketFactory>( event_loop_.get(), quiche::SimpleBufferAllocator::Get()); quic_simple_server_backend_->SetSocketFactory(socket_factory_.get()); QuicUdpSocketApi socket_api; fd_ = socket_api.Create(address.host().AddressFamilyToInt(), kDefaultSocketReceiveBuffer, kDefaultSocketReceiveBuffer); if (fd_ == kQuicInvalidSocketFd) { QUIC_LOG(ERROR) << "CreateSocket() failed: " << strerror(errno); return false; } overflow_supported_ = socket_api.EnableDroppedPacketCount(fd_); socket_api.EnableReceiveTimestamp(fd_); bool success = socket_api.Bind(fd_, address); if (!success) { QUIC_LOG(ERROR) << "Bind failed: " << strerror(errno); return false; } QUIC_LOG(INFO) << "Listening on " << address.ToString(); port_ = address.port(); if (port_ == 0) { QuicSocketAddress self_address; if (self_address.FromSocket(fd_) != 0) { QUIC_LOG(ERROR) << "Unable to get self address. Error: " << strerror(errno); } port_ = self_address.port(); } bool register_result = event_loop_->RegisterSocket( fd_, kSocketEventReadable | kSocketEventWritable, this); if (!register_result) { return false; } dispatcher_.reset(CreateQuicDispatcher()); dispatcher_->InitializeWithWriter(CreateWriter(fd_)); return true; } QuicPacketWriter* QuicServer::CreateWriter(int fd) { return new QuicDefaultPacketWriter(fd); } QuicDispatcher* QuicServer::CreateQuicDispatcher() { return new QuicSimpleDispatcher( &config_, &crypto_config_, &version_manager_, std::make_unique<QuicDefaultConnectionHelper>(), std::unique_ptr<QuicCryptoServerStreamBase::Helper>( new QuicSimpleCryptoServerStreamHelper()), event_loop_->CreateAlarmFactory(), quic_simple_server_backend_, expected_server_connection_id_length_, connection_id_generator_); } std::unique_ptr<QuicEventLoop> QuicServer::CreateEventLoop() { return GetDefaultEventLoop()->Create(QuicDefaultClock::Get()); } void QuicServer::HandleEventsForever() { while (true) { WaitForEvents(); } } void QuicServer::WaitForEvents() { event_loop_->RunEventLoopOnce(QuicTime::Delta::FromMilliseconds(50)); } void QuicServer::Shutdown() { if (!silent_close_) { dispatcher_->Shutdown(); } dispatcher_.reset(); event_loop_.reset(); } void QuicServer::OnSocketEvent(QuicEventLoop* , QuicUdpSocketFd fd, QuicSocketEventMask events) { QUICHE_DCHECK_EQ(fd, fd_); if (events & kSocketEventReadable) { QUIC_DVLOG(1) << "EPOLLIN"; dispatcher_->ProcessBufferedChlos(max_sessions_to_create_per_socket_event_); bool more_to_read = true; while (more_to_read) { more_to_read = packet_reader_->ReadAndDispatchPackets( fd_, port_, *QuicDefaultClock::Get(), dispatcher_.get(), overflow_supported_ ? &packets_dropped_ : nullptr); } if (dispatcher_->HasChlosBuffered()) { bool success = event_loop_->ArtificiallyNotifyEvent(fd_, kSocketEventReadable); QUICHE_DCHECK(success); } if (!event_loop_->SupportsEdgeTriggered()) { bool success = event_loop_->RearmSocket(fd_, kSocketEventReadable); QUICHE_DCHECK(success); } } if (events & kSocketEventWritable) { dispatcher_->OnCanWrite(); if (!event_loop_->SupportsEdgeTriggered() && dispatcher_->HasPendingWrites()) { bool success = event_loop_->RearmSocket(fd_, kSocketEventWritable); QUICHE_DCHECK(success); } } } }
#include "quiche/quic/tools/quic_server.h" #include <memory> #include <string> #include <utility> #include "absl/base/macros.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/deterministic_connection_id_generator.h" #include "quiche/quic/core/io/quic_default_event_loop.h" #include "quiche/quic/core/io/quic_event_loop.h" #include "quiche/quic/core/quic_default_clock.h" #include "quiche/quic/core/quic_default_connection_helper.h" #include "quiche/quic/core/quic_default_packet_writer.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_socket_address.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/platform/api/quic_test_loopback.h" #include "quiche/quic/test_tools/crypto_test_utils.h" #include "quiche/quic/test_tools/mock_quic_dispatcher.h" #include "quiche/quic/test_tools/quic_server_peer.h" #include "quiche/quic/tools/quic_memory_cache_backend.h" #include "quiche/quic/tools/quic_simple_crypto_server_stream_helper.h" namespace quic { namespace test { using ::testing::_; namespace { class MockQuicSimpleDispatcher : public QuicSimpleDispatcher { public: MockQuicSimpleDispatcher( const QuicConfig* config, const QuicCryptoServerConfig* crypto_config, QuicVersionManager* version_manager, std::unique_ptr<QuicConnectionHelperInterface> helper, std::unique_ptr<QuicCryptoServerStreamBase::Helper> session_helper, std::unique_ptr<QuicAlarmFactory> alarm_factory, QuicSimpleServerBackend* quic_simple_server_backend, ConnectionIdGeneratorInterface& generator) : QuicSimpleDispatcher(config, crypto_config, version_manager, std::move(helper), std::move(session_helper), std::move(alarm_factory), quic_simple_server_backend, kQuicDefaultConnectionIdLength, generator) {} ~MockQuicSimpleDispatcher() override = default; MOCK_METHOD(void, OnCanWrite, (), (override)); MOCK_METHOD(bool, HasPendingWrites, (), (const, override)); MOCK_METHOD(bool, HasChlosBuffered, (), (const, override)); MOCK_METHOD(void, ProcessBufferedChlos, (size_t), (override)); }; class TestQuicServer : public QuicServer { public: explicit TestQuicServer(QuicEventLoopFactory* event_loop_factory, QuicMemoryCacheBackend* quic_simple_server_backend) : QuicServer(crypto_test_utils::ProofSourceForTesting(), quic_simple_server_backend), quic_simple_server_backend_(quic_simple_server_backend), event_loop_factory_(event_loop_factory) {} ~TestQuicServer() override = default; MockQuicSimpleDispatcher* mock_dispatcher() { return mock_dispatcher_; } protected: QuicDispatcher* CreateQuicDispatcher() override { mock_dispatcher_ = new MockQuicSimpleDispatcher( &config(), &crypto_config(), version_manager(), std::make_unique<QuicDefaultConnectionHelper>(), std::unique_ptr<QuicCryptoServerStreamBase::Helper>( new QuicSimpleCryptoServerStreamHelper()), event_loop()->CreateAlarmFactory(), quic_simple_server_backend_, connection_id_generator()); return mock_dispatcher_; } std::unique_ptr<QuicEventLoop> CreateEventLoop() override { return event_loop_factory_->Create(QuicDefaultClock::Get()); } MockQuicSimpleDispatcher* mock_dispatcher_ = nullptr; QuicMemoryCacheBackend* quic_simple_server_backend_; QuicEventLoopFactory* event_loop_factory_; }; class QuicServerEpollInTest : public QuicTestWithParam<QuicEventLoopFactory*> { public: QuicServerEpollInTest() : server_address_(TestLoopback(), 0), server_(GetParam(), &quic_simple_server_backend_) {} void StartListening() { server_.CreateUDPSocketAndListen(server_address_); server_address_ = QuicSocketAddress(server_address_.host(), server_.port()); ASSERT_TRUE(QuicServerPeer::SetSmallSocket(&server_)); if (!server_.overflow_supported()) { QUIC_LOG(WARNING) << "Overflow not supported. Not testing."; return; } } protected: QuicSocketAddress server_address_; QuicMemoryCacheBackend quic_simple_server_backend_; TestQuicServer server_; }; std::string GetTestParamName( ::testing::TestParamInfo<QuicEventLoopFactory*> info) { return EscapeTestParamName(info.param->GetName()); } INSTANTIATE_TEST_SUITE_P(QuicServerEpollInTests, QuicServerEpollInTest, ::testing::ValuesIn(GetAllSupportedEventLoops()), GetTestParamName); TEST_P(QuicServerEpollInTest, ProcessBufferedCHLOsOnEpollin) { StartListening(); bool more_chlos = true; MockQuicSimpleDispatcher* dispatcher_ = server_.mock_dispatcher(); QUICHE_DCHECK(dispatcher_ != nullptr); EXPECT_CALL(*dispatcher_, OnCanWrite()).Times(testing::AnyNumber()); EXPECT_CALL(*dispatcher_, ProcessBufferedChlos(_)).Times(2); EXPECT_CALL(*dispatcher_, HasPendingWrites()).Times(testing::AnyNumber()); EXPECT_CALL(*dispatcher_, HasChlosBuffered()) .WillOnce(testing::Return(true)) .WillOnce( DoAll(testing::Assign(&more_chlos, false), testing::Return(false))); QuicUdpSocketApi socket_api; SocketFd fd = socket_api.Create(server_address_.host().AddressFamilyToInt(), kDefaultSocketReceiveBuffer, kDefaultSocketReceiveBuffer); ASSERT_NE(fd, kQuicInvalidSocketFd); char buf[1024]; memset(buf, 0, ABSL_ARRAYSIZE(buf)); QuicUdpPacketInfo packet_info; packet_info.SetPeerAddress(server_address_); WriteResult result = socket_api.WritePacket(fd, buf, sizeof(buf), packet_info); if (result.status != WRITE_STATUS_OK) { QUIC_LOG(ERROR) << "Write error for UDP packet: " << result.error_code; } while (more_chlos) { server_.WaitForEvents(); } } class QuicServerDispatchPacketTest : public QuicTest { public: QuicServerDispatchPacketTest() : crypto_config_("blah", QuicRandom::GetInstance(), crypto_test_utils::ProofSourceForTesting(), KeyExchangeSource::Default()), version_manager_(AllSupportedVersions()), event_loop_(GetDefaultEventLoop()->Create(QuicDefaultClock::Get())), connection_id_generator_(kQuicDefaultConnectionIdLength), dispatcher_(&config_, &crypto_config_, &version_manager_, std::make_unique<QuicDefaultConnectionHelper>(), std::make_unique<QuicSimpleCryptoServerStreamHelper>(), event_loop_->CreateAlarmFactory(), &quic_simple_server_backend_, connection_id_generator_) { dispatcher_.InitializeWithWriter(new QuicDefaultPacketWriter(1234)); } void DispatchPacket(const QuicReceivedPacket& packet) { QuicSocketAddress client_addr, server_addr; dispatcher_.ProcessPacket(server_addr, client_addr, packet); } protected: QuicConfig config_; QuicCryptoServerConfig crypto_config_; QuicVersionManager version_manager_; std::unique_ptr<QuicEventLoop> event_loop_; QuicMemoryCacheBackend quic_simple_server_backend_; DeterministicConnectionIdGenerator connection_id_generator_; MockQuicDispatcher dispatcher_; }; TEST_F(QuicServerDispatchPacketTest, DispatchPacket) { unsigned char valid_packet[] = { 0x3C, 0x10, 0x32, 0x54, 0x76, 0x98, 0xBA, 0xDC, 0xFE, 0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12, 0x00 }; QuicReceivedPacket encrypted_valid_packet( reinterpret_cast<char*>(valid_packet), ABSL_ARRAYSIZE(valid_packet), QuicTime::Zero(), false); EXPECT_CALL(dispatcher_, ProcessPacket(_, _, _)).Times(1); DispatchPacket(encrypted_valid_packet); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/tools/quic_server.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/tools/quic_server_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
f03a3830-3544-489a-837c-11b8e6cc9e8f
cpp
google/quiche
load_balancer_server_id
quiche/quic/load_balancer/load_balancer_server_id.cc
quiche/quic/load_balancer/load_balancer_server_id_test.cc
#include "quiche/quic/load_balancer/load_balancer_server_id.h" #include <array> #include <cstdint> #include <cstring> #include <string> #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" namespace quic { LoadBalancerServerId::LoadBalancerServerId(absl::string_view data) : LoadBalancerServerId(absl::MakeSpan( reinterpret_cast<const uint8_t*>(data.data()), data.length())) {} LoadBalancerServerId::LoadBalancerServerId(absl::Span<const uint8_t> data) : length_(data.length()) { if (length_ == 0 || length_ > kLoadBalancerMaxServerIdLen) { QUIC_BUG(quic_bug_433312504_02) << "Attempted to create LoadBalancerServerId with length " << static_cast<int>(length_); length_ = 0; return; } memcpy(data_.data(), data.data(), data.length()); } void LoadBalancerServerId::set_length(uint8_t length) { QUIC_BUG_IF(quic_bug_599862571_01, length == 0 || length > kLoadBalancerMaxServerIdLen) << "Attempted to set LoadBalancerServerId length to " << static_cast<int>(length); length_ = length; } std::string LoadBalancerServerId::ToString() const { return absl::BytesToHexString( absl::string_view(reinterpret_cast<const char*>(data_.data()), length_)); } }
#include "quiche/quic/load_balancer/load_balancer_server_id.h" #include <cstdint> #include <cstring> #include "absl/hash/hash_testing.h" #include "absl/types/span.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { namespace { class LoadBalancerServerIdTest : public QuicTest {}; constexpr uint8_t kRawServerId[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}; TEST_F(LoadBalancerServerIdTest, CreateReturnsNullIfTooLong) { EXPECT_QUIC_BUG(EXPECT_FALSE(LoadBalancerServerId( absl::Span<const uint8_t>(kRawServerId, 16)) .IsValid()), "Attempted to create LoadBalancerServerId with length 16"); EXPECT_QUIC_BUG( EXPECT_FALSE(LoadBalancerServerId(absl::Span<const uint8_t>()).IsValid()), "Attempted to create LoadBalancerServerId with length 0"); } TEST_F(LoadBalancerServerIdTest, CompareIdenticalExceptLength) { LoadBalancerServerId server_id(absl::Span<const uint8_t>(kRawServerId, 15)); ASSERT_TRUE(server_id.IsValid()); EXPECT_EQ(server_id.length(), 15); LoadBalancerServerId shorter_server_id( absl::Span<const uint8_t>(kRawServerId, 5)); ASSERT_TRUE(shorter_server_id.IsValid()); EXPECT_EQ(shorter_server_id.length(), 5); EXPECT_TRUE(shorter_server_id < server_id); EXPECT_FALSE(server_id < shorter_server_id); EXPECT_FALSE(shorter_server_id == server_id); } TEST_F(LoadBalancerServerIdTest, AccessorFunctions) { LoadBalancerServerId server_id(absl::Span<const uint8_t>(kRawServerId, 5)); EXPECT_TRUE(server_id.IsValid()); EXPECT_EQ(server_id.length(), 5); EXPECT_EQ(memcmp(server_id.data().data(), kRawServerId, 5), 0); EXPECT_EQ(server_id.ToString(), "0001020304"); } TEST_F(LoadBalancerServerIdTest, CompareDifferentServerIds) { LoadBalancerServerId server_id(absl::Span<const uint8_t>(kRawServerId, 5)); ASSERT_TRUE(server_id.IsValid()); LoadBalancerServerId reverse({0x0f, 0x0e, 0x0d, 0x0c, 0x0b}); ASSERT_TRUE(reverse.IsValid()); EXPECT_TRUE(server_id < reverse); LoadBalancerServerId long_server_id( absl::Span<const uint8_t>(kRawServerId, 15)); EXPECT_TRUE(long_server_id < reverse); } TEST_F(LoadBalancerServerIdTest, EqualityOperators) { LoadBalancerServerId server_id(absl::Span<const uint8_t>(kRawServerId, 15)); ASSERT_TRUE(server_id.IsValid()); LoadBalancerServerId shorter_server_id( absl::Span<const uint8_t>(kRawServerId, 5)); ASSERT_TRUE(shorter_server_id.IsValid()); EXPECT_FALSE(server_id == shorter_server_id); LoadBalancerServerId server_id2 = server_id; EXPECT_TRUE(server_id == server_id2); } TEST_F(LoadBalancerServerIdTest, SupportsHash) { LoadBalancerServerId server_id(absl::Span<const uint8_t>(kRawServerId, 15)); ASSERT_TRUE(server_id.IsValid()); LoadBalancerServerId shorter_server_id( absl::Span<const uint8_t>(kRawServerId, 5)); ASSERT_TRUE(shorter_server_id.IsValid()); LoadBalancerServerId different_server_id({0x0f, 0x0e, 0x0d, 0x0c, 0x0b}); ASSERT_TRUE(different_server_id.IsValid()); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly({ server_id, shorter_server_id, different_server_id, })); } TEST_F(LoadBalancerServerIdTest, SetLengthInvalid) { LoadBalancerServerId server_id; EXPECT_QUIC_BUG(server_id.set_length(16), "Attempted to set LoadBalancerServerId length to 16"); EXPECT_QUIC_BUG(server_id.set_length(0), "Attempted to set LoadBalancerServerId length to 0"); server_id.set_length(1); EXPECT_EQ(server_id.length(), 1); server_id.set_length(15); EXPECT_EQ(server_id.length(), 15); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/load_balancer/load_balancer_server_id.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/load_balancer/load_balancer_server_id_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
cb2f98ee-8a1a-4cd8-a8f6-ce452937a3e9
cpp
google/quiche
load_balancer_config
quiche/quic/load_balancer/load_balancer_config.cc
quiche/quic/load_balancer/load_balancer_config_test.cc
#include "quiche/quic/load_balancer/load_balancer_config.h" #include <cstdint> #include <cstring> #include <optional> #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "openssl/aes.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/load_balancer/load_balancer_server_id.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" namespace quic { namespace { bool CommonValidation(const uint8_t config_id, const uint8_t server_id_len, const uint8_t nonce_len) { if (config_id >= kNumLoadBalancerConfigs || server_id_len == 0 || nonce_len < kLoadBalancerMinNonceLen || nonce_len > kLoadBalancerMaxNonceLen || server_id_len > (kQuicMaxConnectionIdWithLengthPrefixLength - nonce_len - 1)) { QUIC_BUG(quic_bug_433862549_01) << "Invalid LoadBalancerConfig " << "Config ID " << static_cast<int>(config_id) << " Server ID Length " << static_cast<int>(server_id_len) << " Nonce Length " << static_cast<int>(nonce_len); return false; } return true; } std::optional<AES_KEY> BuildKey(absl::string_view key, bool encrypt) { if (key.empty()) { return std::optional<AES_KEY>(); } AES_KEY raw_key; if (encrypt) { if (AES_set_encrypt_key(reinterpret_cast<const uint8_t *>(key.data()), key.size() * 8, &raw_key) < 0) { return std::optional<AES_KEY>(); } } else if (AES_set_decrypt_key(reinterpret_cast<const uint8_t *>(key.data()), key.size() * 8, &raw_key) < 0) { return std::optional<AES_KEY>(); } return raw_key; } } std::optional<LoadBalancerConfig> LoadBalancerConfig::Create( const uint8_t config_id, const uint8_t server_id_len, const uint8_t nonce_len, const absl::string_view key) { if (key.size() != kLoadBalancerKeyLen) { QUIC_BUG(quic_bug_433862549_02) << "Invalid LoadBalancerConfig Key Length: " << key.size(); return std::optional<LoadBalancerConfig>(); } if (!CommonValidation(config_id, server_id_len, nonce_len)) { return std::optional<LoadBalancerConfig>(); } auto new_config = LoadBalancerConfig(config_id, server_id_len, nonce_len, key); if (!new_config.IsEncrypted()) { QUIC_BUG(quic_bug_433862549_03) << "Something went wrong in initializing " "the load balancing key."; return std::optional<LoadBalancerConfig>(); } return new_config; } std::optional<LoadBalancerConfig> LoadBalancerConfig::CreateUnencrypted( const uint8_t config_id, const uint8_t server_id_len, const uint8_t nonce_len) { return CommonValidation(config_id, server_id_len, nonce_len) ? LoadBalancerConfig(config_id, server_id_len, nonce_len, "") : std::optional<LoadBalancerConfig>(); } bool LoadBalancerConfig::FourPassDecrypt( absl::Span<const uint8_t> ciphertext, LoadBalancerServerId& server_id) const { if (ciphertext.size() < plaintext_len()) { QUIC_BUG(quic_bug_599862571_02) << "Called FourPassDecrypt with a short Connection ID"; return false; } if (!key_.has_value()) { return false; } uint8_t* left = server_id.mutable_data(); uint8_t right[kLoadBalancerBlockSize]; uint8_t half_len; bool is_length_odd = InitializeFourPass(ciphertext.data(), left, right, &half_len); uint8_t end_index = (server_id_len_ > nonce_len_) ? 1 : 2; for (uint8_t index = kNumLoadBalancerCryptoPasses; index >= end_index; --index) { EncryptionPass(index, half_len, is_length_odd, left, right); } if (server_id_len_ < half_len || (server_id_len_ == half_len && !is_length_odd)) { return true; } if (is_length_odd) { right[0] |= *(left + --half_len); } memcpy(server_id.mutable_data() + half_len, right, server_id_len_ - half_len); return true; } QuicConnectionId LoadBalancerConfig::FourPassEncrypt( absl::Span<uint8_t> plaintext) const { if (plaintext.size() < total_len()) { QUIC_BUG(quic_bug_599862571_03) << "Called FourPassEncrypt with a short Connection ID"; return QuicConnectionId(); } if (!key_.has_value()) { return QuicConnectionId(); } uint8_t left[kLoadBalancerBlockSize]; uint8_t right[kLoadBalancerBlockSize]; uint8_t half_len; bool is_length_odd = InitializeFourPass(plaintext.data() + 1, left, right, &half_len); for (uint8_t index = 1; index <= kNumLoadBalancerCryptoPasses; ++index) { EncryptionPass(index, half_len, is_length_odd, left, right); } if (is_length_odd) { right[0] |= left[--half_len]; } memcpy(plaintext.data() + 1, left, half_len); memcpy(plaintext.data() + half_len + 1, right, plaintext_len() - half_len); return QuicConnectionId(reinterpret_cast<char*>(plaintext.data()), total_len()); } bool LoadBalancerConfig::BlockEncrypt( const uint8_t plaintext[kLoadBalancerBlockSize], uint8_t ciphertext[kLoadBalancerBlockSize]) const { if (!key_.has_value()) { return false; } AES_encrypt(plaintext, ciphertext, &*key_); return true; } bool LoadBalancerConfig::BlockDecrypt( const uint8_t ciphertext[kLoadBalancerBlockSize], uint8_t plaintext[kLoadBalancerBlockSize]) const { if (!block_decrypt_key_.has_value()) { return false; } AES_decrypt(ciphertext, plaintext, &*block_decrypt_key_); return true; } LoadBalancerConfig::LoadBalancerConfig(const uint8_t config_id, const uint8_t server_id_len, const uint8_t nonce_len, const absl::string_view key) : config_id_(config_id), server_id_len_(server_id_len), nonce_len_(nonce_len), key_(BuildKey(key, true)), block_decrypt_key_((server_id_len + nonce_len == kLoadBalancerBlockSize) ? BuildKey(key, false) : std::optional<AES_KEY>()) {} bool LoadBalancerConfig::InitializeFourPass(const uint8_t* input, uint8_t* left, uint8_t* right, uint8_t* half_len) const { *half_len = plaintext_len() / 2; bool is_length_odd; if (plaintext_len() % 2 == 1) { ++(*half_len); is_length_odd = true; } else { is_length_odd = false; } memset(left, 0, kLoadBalancerBlockSize); memset(right, 0, kLoadBalancerBlockSize); left[kLoadBalancerBlockSize - 2] = plaintext_len(); right[kLoadBalancerBlockSize - 2] = plaintext_len(); memcpy(left, input, *half_len); memcpy(right, input + (plaintext_len() / 2), *half_len); if (is_length_odd) { left[*half_len - 1] &= 0xf0; right[0] &= 0x0f; } return is_length_odd; } void LoadBalancerConfig::EncryptionPass(uint8_t index, uint8_t half_len, bool is_length_odd, uint8_t* left, uint8_t* right) const { uint8_t ciphertext[kLoadBalancerBlockSize]; if (index % 2 == 0) { right[kLoadBalancerBlockSize - 1] = index; AES_encrypt(right, ciphertext, &*key_); for (int i = 0; i < half_len; ++i) { left[i] ^= ciphertext[i]; } if (is_length_odd) { left[half_len - 1] &= 0xf0; } return; } left[kLoadBalancerBlockSize - 1] = index; AES_encrypt(left, ciphertext, &*key_); for (int i = 0; i < half_len; ++i) { right[i] ^= ciphertext[i]; } if (is_length_odd) { right[0] &= 0x0f; } } }
#include "quiche/quic/load_balancer/load_balancer_config.h" #include <array> #include <cstdint> #include <cstring> #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/load_balancer/load_balancer_server_id.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { class LoadBalancerConfigPeer { public: static bool InitializeFourPass(LoadBalancerConfig& config, const uint8_t* input, uint8_t* left, uint8_t* right, uint8_t* half_len) { return config.InitializeFourPass(input, left, right, half_len); } static void EncryptionPass(LoadBalancerConfig& config, uint8_t index, uint8_t half_len, bool is_length_odd, uint8_t* left, uint8_t* right) { config.EncryptionPass(index, half_len, is_length_odd, left, right); } }; namespace { constexpr char raw_key[] = { 0xfd, 0xf7, 0x26, 0xa9, 0x89, 0x3e, 0xc0, 0x5c, 0x06, 0x32, 0xd3, 0x95, 0x66, 0x80, 0xba, 0xf0, }; class LoadBalancerConfigTest : public QuicTest {}; TEST_F(LoadBalancerConfigTest, InvalidParams) { EXPECT_QUIC_BUG( EXPECT_FALSE(LoadBalancerConfig::CreateUnencrypted(7, 4, 10).has_value()), "Invalid LoadBalancerConfig Config ID 7 Server ID Length 4 " "Nonce Length 10"); EXPECT_QUIC_BUG(EXPECT_FALSE(LoadBalancerConfig::Create( 2, 0, 10, absl::string_view(raw_key, 16)) .has_value()), "Invalid LoadBalancerConfig Config ID 2 Server ID Length 0 " "Nonce Length 10"); EXPECT_QUIC_BUG( EXPECT_FALSE(LoadBalancerConfig::CreateUnencrypted(6, 16, 4).has_value()), "Invalid LoadBalancerConfig Config ID 6 Server ID Length 16 " "Nonce Length 4"); EXPECT_QUIC_BUG( EXPECT_FALSE(LoadBalancerConfig::CreateUnencrypted(6, 4, 2).has_value()), "Invalid LoadBalancerConfig Config ID 6 Server ID Length 4 " "Nonce Length 2"); EXPECT_QUIC_BUG( EXPECT_FALSE(LoadBalancerConfig::CreateUnencrypted(6, 1, 17).has_value()), "Invalid LoadBalancerConfig Config ID 6 Server ID Length 1 " "Nonce Length 17"); EXPECT_QUIC_BUG( EXPECT_FALSE(LoadBalancerConfig::Create(2, 3, 4, "").has_value()), "Invalid LoadBalancerConfig Key Length: 0"); EXPECT_QUIC_BUG(EXPECT_FALSE(LoadBalancerConfig::Create( 2, 3, 4, absl::string_view(raw_key, 10)) .has_value()), "Invalid LoadBalancerConfig Key Length: 10"); EXPECT_QUIC_BUG(EXPECT_FALSE(LoadBalancerConfig::Create( 0, 3, 4, absl::string_view(raw_key, 17)) .has_value()), "Invalid LoadBalancerConfig Key Length: 17"); } TEST_F(LoadBalancerConfigTest, ValidParams) { auto config = LoadBalancerConfig::CreateUnencrypted(0, 3, 4); EXPECT_TRUE(config.has_value()); EXPECT_EQ(config->config_id(), 0); EXPECT_EQ(config->server_id_len(), 3); EXPECT_EQ(config->nonce_len(), 4); EXPECT_EQ(config->plaintext_len(), 7); EXPECT_EQ(config->total_len(), 8); EXPECT_FALSE(config->IsEncrypted()); auto config2 = LoadBalancerConfig::Create(2, 6, 7, absl::string_view(raw_key, 16)); EXPECT_TRUE(config.has_value()); EXPECT_EQ(config2->config_id(), 2); EXPECT_EQ(config2->server_id_len(), 6); EXPECT_EQ(config2->nonce_len(), 7); EXPECT_EQ(config2->plaintext_len(), 13); EXPECT_EQ(config2->total_len(), 14); EXPECT_TRUE(config2->IsEncrypted()); } TEST_F(LoadBalancerConfigTest, TestEncryptionPassExample) { auto config = LoadBalancerConfig::Create(0, 3, 4, absl::string_view(raw_key, 16)); EXPECT_TRUE(config.has_value()); EXPECT_TRUE(config->IsEncrypted()); uint8_t input[] = {0x07, 0x31, 0x44, 0x1a, 0x9c, 0x69, 0xc2, 0x75}; std::array<uint8_t, kLoadBalancerBlockSize> left, right; uint8_t half_len; bool is_length_odd = LoadBalancerConfigPeer::InitializeFourPass( *config, input + 1, left.data(), right.data(), &half_len); EXPECT_TRUE(is_length_odd); std::array<std::array<uint8_t, kLoadBalancerBlockSize>, kNumLoadBalancerCryptoPasses + 1> expected_left = {{ {0x31, 0x44, 0x1a, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00}, {0x31, 0x44, 0x1a, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x01}, {0xd4, 0xa0, 0x48, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x01}, {0xd4, 0xa0, 0x48, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x03}, {0x67, 0x94, 0x7d, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x03}, }}; std::array<std::array<uint8_t, kLoadBalancerBlockSize>, kNumLoadBalancerCryptoPasses + 1> expected_right = {{ {0x0c, 0x69, 0xc2, 0x75, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00}, {0x0e, 0x3c, 0x1f, 0xf9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00}, {0x0e, 0x3c, 0x1f, 0xf9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x02}, {0x09, 0xbe, 0x05, 0x4a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x02}, {0x09, 0xbe, 0x05, 0x4a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x04}, }}; EXPECT_EQ(left, expected_left[0]); EXPECT_EQ(right, expected_right[0]); for (int i = 1; i <= kNumLoadBalancerCryptoPasses; ++i) { LoadBalancerConfigPeer::EncryptionPass(*config, i, half_len, is_length_odd, left.data(), right.data()); EXPECT_EQ(left, expected_left[i]); EXPECT_EQ(right, expected_right[i]); } } TEST_F(LoadBalancerConfigTest, EncryptionPassesAreReversible) { auto config = LoadBalancerConfig::Create(0, 3, 4, absl::string_view(raw_key, 16)); std::array<uint8_t, kLoadBalancerBlockSize> start_left = { 0x31, 0x44, 0x1a, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, }; std::array<uint8_t, kLoadBalancerBlockSize> start_right = { 0x0c, 0x69, 0xc2, 0x75, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, }; std::array<uint8_t, kLoadBalancerBlockSize> left = start_left, right = start_right; LoadBalancerConfigPeer::EncryptionPass(*config, 1, 4, true, left.data(), right.data()); LoadBalancerConfigPeer::EncryptionPass(*config, 2, 4, true, left.data(), right.data()); LoadBalancerConfigPeer::EncryptionPass(*config, 2, 4, true, left.data(), right.data()); LoadBalancerConfigPeer::EncryptionPass(*config, 1, 4, true, left.data(), right.data()); left[15] = 0; right[15] = 0; EXPECT_EQ(left, start_left); EXPECT_EQ(right, start_right); } TEST_F(LoadBalancerConfigTest, InvalidBlockEncryption) { uint8_t pt[kLoadBalancerBlockSize + 1], ct[kLoadBalancerBlockSize]; auto pt_config = LoadBalancerConfig::CreateUnencrypted(0, 8, 8); ASSERT_TRUE(pt_config.has_value()); EXPECT_FALSE(pt_config->BlockEncrypt(pt, ct)); EXPECT_FALSE(pt_config->BlockDecrypt(ct, pt)); EXPECT_TRUE(pt_config->FourPassEncrypt(absl::Span<uint8_t>(pt, sizeof(pt))) .IsEmpty()); LoadBalancerServerId answer; EXPECT_FALSE(pt_config->FourPassDecrypt( absl::Span<uint8_t>(pt, sizeof(pt) - 1), answer)); auto small_cid_config = LoadBalancerConfig::Create(0, 3, 4, absl::string_view(raw_key, 16)); ASSERT_TRUE(small_cid_config.has_value()); EXPECT_TRUE(small_cid_config->BlockEncrypt(pt, ct)); EXPECT_FALSE(small_cid_config->BlockDecrypt(ct, pt)); auto block_config = LoadBalancerConfig::Create(0, 8, 8, absl::string_view(raw_key, 16)); ASSERT_TRUE(block_config.has_value()); EXPECT_TRUE(block_config->BlockEncrypt(pt, ct)); EXPECT_TRUE(block_config->BlockDecrypt(ct, pt)); } TEST_F(LoadBalancerConfigTest, BlockEncryptionExample) { const uint8_t ptext[] = {0xed, 0x79, 0x3a, 0x51, 0xd4, 0x9b, 0x8f, 0x5f, 0xee, 0x08, 0x0d, 0xbf, 0x48, 0xc0, 0xd1, 0xe5}; const uint8_t ctext[] = {0x4d, 0xd2, 0xd0, 0x5a, 0x7b, 0x0d, 0xe9, 0xb2, 0xb9, 0x90, 0x7a, 0xfb, 0x5e, 0xcf, 0x8c, 0xc3}; const char key[] = {0x8f, 0x95, 0xf0, 0x92, 0x45, 0x76, 0x5f, 0x80, 0x25, 0x69, 0x34, 0xe5, 0x0c, 0x66, 0x20, 0x7f}; uint8_t result[sizeof(ptext)]; auto config = LoadBalancerConfig::Create(0, 8, 8, absl::string_view(key, 16)); EXPECT_TRUE(config->BlockEncrypt(ptext, result)); EXPECT_EQ(memcmp(result, ctext, sizeof(ctext)), 0); EXPECT_TRUE(config->BlockDecrypt(ctext, result)); EXPECT_EQ(memcmp(result, ptext, sizeof(ptext)), 0); } TEST_F(LoadBalancerConfigTest, ConfigIsCopyable) { const uint8_t ptext[] = {0xed, 0x79, 0x3a, 0x51, 0xd4, 0x9b, 0x8f, 0x5f, 0xee, 0x08, 0x0d, 0xbf, 0x48, 0xc0, 0xd1, 0xe5}; const uint8_t ctext[] = {0x4d, 0xd2, 0xd0, 0x5a, 0x7b, 0x0d, 0xe9, 0xb2, 0xb9, 0x90, 0x7a, 0xfb, 0x5e, 0xcf, 0x8c, 0xc3}; const char key[] = {0x8f, 0x95, 0xf0, 0x92, 0x45, 0x76, 0x5f, 0x80, 0x25, 0x69, 0x34, 0xe5, 0x0c, 0x66, 0x20, 0x7f}; uint8_t result[sizeof(ptext)]; auto config = LoadBalancerConfig::Create(0, 8, 8, absl::string_view(key, 16)); auto config2 = config; EXPECT_TRUE(config->BlockEncrypt(ptext, result)); EXPECT_EQ(memcmp(result, ctext, sizeof(ctext)), 0); EXPECT_TRUE(config2->BlockEncrypt(ptext, result)); EXPECT_EQ(memcmp(result, ctext, sizeof(ctext)), 0); } TEST_F(LoadBalancerConfigTest, FourPassInputTooShort) { auto config = LoadBalancerConfig::Create(0, 3, 4, absl::string_view(raw_key, 16)); uint8_t input[] = {0x0d, 0xd2, 0xd0, 0x5a, 0x7b, 0x0d, 0xe9}; LoadBalancerServerId answer; bool decrypt_result; EXPECT_QUIC_BUG( decrypt_result = config->FourPassDecrypt( absl::Span<const uint8_t>(input, sizeof(input) - 1), answer), "Called FourPassDecrypt with a short Connection ID"); EXPECT_FALSE(decrypt_result); QuicConnectionId encrypt_result; EXPECT_QUIC_BUG(encrypt_result = config->FourPassEncrypt( absl::Span<uint8_t>(input, sizeof(input))), "Called FourPassEncrypt with a short Connection ID"); EXPECT_TRUE(encrypt_result.IsEmpty()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/load_balancer/load_balancer_config.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/load_balancer/load_balancer_config_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
54496171-6eaf-43ae-b655-2e5df4e67bdd
cpp
google/quiche
load_balancer_encoder
quiche/quic/load_balancer/load_balancer_encoder.cc
quiche/quic/load_balancer/load_balancer_encoder_test.cc
#include "quiche/quic/load_balancer/load_balancer_encoder.h" #include <cstdint> #include <cstring> #include <optional> #include "absl/cleanup/cleanup.h" #include "absl/numeric/int128.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/load_balancer/load_balancer_config.h" #include "quiche/quic/load_balancer/load_balancer_server_id.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" #include "quiche/common/quiche_endian.h" namespace quic { namespace { absl::uint128 NumberOfNonces(uint8_t nonce_len) { return (static_cast<absl::uint128>(1) << (nonce_len * 8)); } bool WriteUint128(const absl::uint128 in, uint8_t size, QuicDataWriter &out) { if (out.remaining() < size) { QUIC_BUG(quic_bug_435375038_05) << "Call to WriteUint128() does not have enough space in |out|"; return false; } uint64_t num64 = absl::Uint128Low64(in); if (size <= sizeof(num64)) { out.WriteBytes(&num64, size); } else { out.WriteBytes(&num64, sizeof(num64)); num64 = absl::Uint128High64(in); out.WriteBytes(&num64, size - sizeof(num64)); } return true; } } std::optional<LoadBalancerEncoder> LoadBalancerEncoder::Create( QuicRandom &random, LoadBalancerEncoderVisitorInterface *const visitor, const bool len_self_encoded, const uint8_t unroutable_connection_id_len) { if (unroutable_connection_id_len == 0 || unroutable_connection_id_len > kQuicMaxConnectionIdWithLengthPrefixLength) { QUIC_BUG(quic_bug_435375038_01) << "Invalid unroutable_connection_id_len = " << static_cast<int>(unroutable_connection_id_len); return std::optional<LoadBalancerEncoder>(); } return LoadBalancerEncoder(random, visitor, len_self_encoded, unroutable_connection_id_len); } bool LoadBalancerEncoder::UpdateConfig(const LoadBalancerConfig &config, const LoadBalancerServerId server_id) { if (config_.has_value() && config_->config_id() == config.config_id()) { QUIC_BUG(quic_bug_435375038_02) << "Attempting to change config with same ID"; return false; } if (server_id.length() != config.server_id_len()) { QUIC_BUG(quic_bug_435375038_03) << "Server ID length " << static_cast<int>(server_id.length()) << " does not match configured value of " << static_cast<int>(config.server_id_len()); return false; } if (visitor_ != nullptr) { if (config_.has_value()) { visitor_->OnConfigChanged(config_->config_id(), config.config_id()); } else { visitor_->OnConfigAdded(config.config_id()); } } config_ = config; server_id_ = server_id; seed_ = absl::MakeUint128(random_.RandUint64(), random_.RandUint64()) % NumberOfNonces(config.nonce_len()); num_nonces_left_ = NumberOfNonces(config.nonce_len()); connection_id_lengths_[config.config_id()] = config.total_len(); return true; } void LoadBalancerEncoder::DeleteConfig() { if (visitor_ != nullptr && config_.has_value()) { visitor_->OnConfigDeleted(config_->config_id()); } config_.reset(); server_id_.reset(); num_nonces_left_ = 0; } QuicConnectionId LoadBalancerEncoder::GenerateConnectionId() { absl::Cleanup cleanup = [&] { if (num_nonces_left_ == 0) { DeleteConfig(); } }; uint8_t config_id = config_.has_value() ? config_->config_id() : kLoadBalancerUnroutableConfigId; uint8_t shifted_config_id = config_id << kConnectionIdLengthBits; uint8_t length = connection_id_lengths_[config_id]; if (config_.has_value() != server_id_.has_value()) { QUIC_BUG(quic_bug_435375038_04) << "Existence of config and server_id are out of sync"; return QuicConnectionId(); } uint8_t first_byte; if (len_self_encoded_) { first_byte = shifted_config_id | (length - 1); } else { random_.RandBytes(static_cast<void *>(&first_byte), 1); first_byte = shifted_config_id | (first_byte & kLoadBalancerLengthMask); } if (!config_.has_value()) { return MakeUnroutableConnectionId(first_byte); } uint8_t result[kQuicMaxConnectionIdWithLengthPrefixLength]; QuicDataWriter writer(length, reinterpret_cast<char *>(result), quiche::HOST_BYTE_ORDER); writer.WriteUInt8(first_byte); absl::uint128 next_nonce = (seed_ + num_nonces_left_--) % NumberOfNonces(config_->nonce_len()); writer.WriteBytes(server_id_->data().data(), server_id_->length()); if (!WriteUint128(next_nonce, config_->nonce_len(), writer)) { return QuicConnectionId(); } if (!config_->IsEncrypted()) { absl::uint128 nonce_hash = QuicUtils::FNV1a_128_Hash(absl::string_view( reinterpret_cast<char *>(result), config_->total_len())); const uint64_t lo = absl::Uint128Low64(nonce_hash); if (config_->nonce_len() <= sizeof(uint64_t)) { memcpy(&result[1 + config_->server_id_len()], &lo, config_->nonce_len()); return QuicConnectionId(reinterpret_cast<char *>(result), config_->total_len()); } memcpy(&result[1 + config_->server_id_len()], &lo, sizeof(uint64_t)); const uint64_t hi = absl::Uint128High64(nonce_hash); memcpy(&result[1 + config_->server_id_len() + sizeof(uint64_t)], &hi, config_->nonce_len() - sizeof(uint64_t)); return QuicConnectionId(reinterpret_cast<char *>(result), config_->total_len()); } if (config_->plaintext_len() == kLoadBalancerBlockSize) { if (!config_->BlockEncrypt(&result[1], &result[1])) { return QuicConnectionId(); } return (QuicConnectionId(reinterpret_cast<char *>(result), config_->total_len())); } return config_->FourPassEncrypt( absl::Span<uint8_t>(result, config_->total_len())); } std::optional<QuicConnectionId> LoadBalancerEncoder::GenerateNextConnectionId( [[maybe_unused]] const QuicConnectionId &original) { return (IsEncoding() && !IsEncrypted()) ? std::optional<QuicConnectionId>() : GenerateConnectionId(); } std::optional<QuicConnectionId> LoadBalancerEncoder::MaybeReplaceConnectionId( const QuicConnectionId &original, const ParsedQuicVersion &version) { uint8_t needed_length = config_.has_value() ? config_->total_len() : connection_id_lengths_[kNumLoadBalancerConfigs]; return (!version.HasIetfQuicFrames() && original.length() == needed_length) ? std::optional<QuicConnectionId>() : GenerateConnectionId(); } uint8_t LoadBalancerEncoder::ConnectionIdLength(uint8_t first_byte) const { if (len_self_encoded()) { return (first_byte &= kLoadBalancerLengthMask) + 1; } return connection_id_lengths_[first_byte >> kConnectionIdLengthBits]; } QuicConnectionId LoadBalancerEncoder::MakeUnroutableConnectionId( uint8_t first_byte) { QuicConnectionId id; uint8_t target_length = connection_id_lengths_[kLoadBalancerUnroutableConfigId]; id.set_length(target_length); id.mutable_data()[0] = first_byte; random_.RandBytes(&id.mutable_data()[1], target_length - 1); return id; } }
#include "quiche/quic/load_balancer/load_balancer_encoder.h" #include <cstddef> #include <cstdint> #include <cstring> #include <optional> #include <queue> #include "absl/numeric/int128.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/load_balancer/load_balancer_config.h" #include "quiche/quic/load_balancer/load_balancer_server_id.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { namespace test { class LoadBalancerEncoderPeer { public: static void SetNumNoncesLeft(LoadBalancerEncoder &encoder, uint64_t nonces_remaining) { encoder.num_nonces_left_ = absl::uint128(nonces_remaining); } }; namespace { class TestLoadBalancerEncoderVisitor : public LoadBalancerEncoderVisitorInterface { public: ~TestLoadBalancerEncoderVisitor() override {} void OnConfigAdded(const uint8_t config_id) override { num_adds_++; current_config_id_ = config_id; } void OnConfigChanged(const uint8_t old_config_id, const uint8_t new_config_id) override { num_adds_++; num_deletes_++; EXPECT_EQ(old_config_id, current_config_id_); current_config_id_ = new_config_id; } void OnConfigDeleted(const uint8_t config_id) override { EXPECT_EQ(config_id, current_config_id_); current_config_id_.reset(); num_deletes_++; } uint32_t num_adds() const { return num_adds_; } uint32_t num_deletes() const { return num_deletes_; } private: uint32_t num_adds_ = 0, num_deletes_ = 0; std::optional<uint8_t> current_config_id_ = std::optional<uint8_t>(); }; class TestRandom : public QuicRandom { public: uint64_t RandUint64() override { if (next_values_.empty()) { return base_; } uint64_t value = next_values_.front(); next_values_.pop(); return value; } void RandBytes(void *data, size_t len) override { size_t written = 0; uint8_t *ptr = static_cast<uint8_t *>(data); while (written < len) { uint64_t result = RandUint64(); size_t to_write = (len - written > sizeof(uint64_t)) ? sizeof(uint64_t) : (len - written); memcpy(ptr + written, &result, to_write); written += to_write; } } void InsecureRandBytes(void *data, size_t len) override { RandBytes(data, len); } uint64_t InsecureRandUint64() override { return RandUint64(); } void AddNextValues(uint64_t hi, uint64_t lo) { next_values_.push(hi); next_values_.push(lo); } private: std::queue<uint64_t> next_values_; uint64_t base_ = 0xDEADBEEFDEADBEEF; }; class LoadBalancerEncoderTest : public QuicTest { public: TestRandom random_; }; LoadBalancerServerId MakeServerId(const uint8_t array[], const uint8_t length) { return LoadBalancerServerId(absl::Span<const uint8_t>(array, length)); } constexpr char kRawKey[] = {0x8f, 0x95, 0xf0, 0x92, 0x45, 0x76, 0x5f, 0x80, 0x25, 0x69, 0x34, 0xe5, 0x0c, 0x66, 0x20, 0x7f}; constexpr absl::string_view kKey(kRawKey, kLoadBalancerKeyLen); constexpr uint64_t kNonceLow = 0xe5d1c048bf0d08ee; constexpr uint64_t kNonceHigh = 0x9321e7e34dde525d; constexpr uint8_t kServerId[] = {0xed, 0x79, 0x3a, 0x51, 0xd4, 0x9b, 0x8f, 0x5f, 0xab, 0x65, 0xba, 0x04, 0xc3, 0x33, 0x0a}; TEST_F(LoadBalancerEncoderTest, BadUnroutableLength) { EXPECT_QUIC_BUG( EXPECT_FALSE( LoadBalancerEncoder::Create(random_, nullptr, false, 0).has_value()), "Invalid unroutable_connection_id_len = 0"); EXPECT_QUIC_BUG( EXPECT_FALSE( LoadBalancerEncoder::Create(random_, nullptr, false, 21).has_value()), "Invalid unroutable_connection_id_len = 21"); } TEST_F(LoadBalancerEncoderTest, BadServerIdLength) { auto encoder = LoadBalancerEncoder::Create(random_, nullptr, true); ASSERT_TRUE(encoder.has_value()); auto config = LoadBalancerConfig::CreateUnencrypted(1, 3, 4); ASSERT_TRUE(config.has_value()); EXPECT_QUIC_BUG( EXPECT_FALSE(encoder->UpdateConfig(*config, MakeServerId(kServerId, 4))), "Server ID length 4 does not match configured value of 3"); EXPECT_FALSE(encoder->IsEncoding()); } TEST_F(LoadBalancerEncoderTest, FailToUpdateConfigWithSameId) { TestLoadBalancerEncoderVisitor visitor; auto encoder = LoadBalancerEncoder::Create(random_, &visitor, true); ASSERT_TRUE(encoder.has_value()); auto config = LoadBalancerConfig::CreateUnencrypted(1, 3, 4); ASSERT_TRUE(config.has_value()); EXPECT_TRUE(encoder->UpdateConfig(*config, MakeServerId(kServerId, 3))); EXPECT_EQ(visitor.num_adds(), 1u); EXPECT_QUIC_BUG( EXPECT_FALSE(encoder->UpdateConfig(*config, MakeServerId(kServerId, 3))), "Attempting to change config with same ID"); EXPECT_EQ(visitor.num_adds(), 1u); } struct LoadBalancerEncoderTestCase { LoadBalancerConfig config; QuicConnectionId connection_id; LoadBalancerServerId server_id; }; TEST_F(LoadBalancerEncoderTest, UnencryptedConnectionIdTestVectors) { const struct LoadBalancerEncoderTestCase test_vectors[2] = { { *LoadBalancerConfig::CreateUnencrypted(0, 3, 4), QuicConnectionId({0x07, 0xed, 0x79, 0x3a, 0x80, 0x49, 0x71, 0x8a}), MakeServerId(kServerId, 3), }, { *LoadBalancerConfig::CreateUnencrypted(1, 8, 5), QuicConnectionId({0x2d, 0xed, 0x79, 0x3a, 0x51, 0xd4, 0x9b, 0x8f, 0x5f, 0x8e, 0x98, 0x53, 0xfe, 0x93}), MakeServerId(kServerId, 8), }, }; for (const auto &test : test_vectors) { random_.AddNextValues(kNonceHigh, kNonceLow); auto encoder = LoadBalancerEncoder::Create(random_, nullptr, true, 8); EXPECT_TRUE(encoder->UpdateConfig(test.config, test.server_id)); absl::uint128 nonces_left = encoder->num_nonces_left(); EXPECT_EQ(encoder->GenerateConnectionId(), test.connection_id); EXPECT_EQ(encoder->num_nonces_left(), nonces_left - 1); } } TEST_F(LoadBalancerEncoderTest, FollowSpecExample) { const uint8_t config_id = 0, server_id_len = 3, nonce_len = 4; const uint8_t raw_server_id[] = { 0x31, 0x44, 0x1a, }; const char raw_key[] = { 0xfd, 0xf7, 0x26, 0xa9, 0x89, 0x3e, 0xc0, 0x5c, 0x06, 0x32, 0xd3, 0x95, 0x66, 0x80, 0xba, 0xf0, }; random_.AddNextValues(0, 0x75c2699c); auto encoder = LoadBalancerEncoder::Create(random_, nullptr, true, 8); ASSERT_TRUE(encoder.has_value()); auto config = LoadBalancerConfig::Create(config_id, server_id_len, nonce_len, absl::string_view(raw_key)); ASSERT_TRUE(config.has_value()); EXPECT_TRUE( encoder->UpdateConfig(*config, LoadBalancerServerId(raw_server_id))); EXPECT_TRUE(encoder->IsEncoding()); const char raw_connection_id[] = {0x07, 0x67, 0x94, 0x7d, 0x29, 0xbe, 0x05, 0x4a}; auto expected = QuicConnectionId(raw_connection_id, 1 + server_id_len + nonce_len); EXPECT_EQ(encoder->GenerateConnectionId(), expected); } TEST_F(LoadBalancerEncoderTest, EncoderTestVectors) { const LoadBalancerEncoderTestCase test_vectors[4] = { { *LoadBalancerConfig::Create(0, 3, 4, kKey), QuicConnectionId({0x07, 0x20, 0xb1, 0xd0, 0x7b, 0x35, 0x9d, 0x3c}), MakeServerId(kServerId, 3), }, { *LoadBalancerConfig::Create(1, 10, 5, kKey), QuicConnectionId({0x2f, 0xcc, 0x38, 0x1b, 0xc7, 0x4c, 0xb4, 0xfb, 0xad, 0x28, 0x23, 0xa3, 0xd1, 0xf8, 0xfe, 0xd2}), MakeServerId(kServerId, 10), }, { *LoadBalancerConfig::Create(2, 8, 8, kKey), QuicConnectionId({0x50, 0x4d, 0xd2, 0xd0, 0x5a, 0x7b, 0x0d, 0xe9, 0xb2, 0xb9, 0x90, 0x7a, 0xfb, 0x5e, 0xcf, 0x8c, 0xc3}), MakeServerId(kServerId, 8), }, { *LoadBalancerConfig::Create(0, 9, 9, kKey), QuicConnectionId({0x12, 0x57, 0x79, 0xc9, 0xcc, 0x86, 0xbe, 0xb3, 0xa3, 0xa4, 0xa3, 0xca, 0x96, 0xfc, 0xe4, 0xbf, 0xe0, 0xcd, 0xbc}), MakeServerId(kServerId, 9), }, }; for (const auto &test : test_vectors) { auto encoder = LoadBalancerEncoder::Create(random_, nullptr, true, 8); ASSERT_TRUE(encoder.has_value()); random_.AddNextValues(kNonceHigh, kNonceLow); EXPECT_TRUE(encoder->UpdateConfig(test.config, test.server_id)); EXPECT_EQ(encoder->GenerateConnectionId(), test.connection_id); } } TEST_F(LoadBalancerEncoderTest, RunOutOfNonces) { const uint8_t server_id_len = 3; TestLoadBalancerEncoderVisitor visitor; auto encoder = LoadBalancerEncoder::Create(random_, &visitor, true, 8); ASSERT_TRUE(encoder.has_value()); auto config = LoadBalancerConfig::Create(0, server_id_len, 4, kKey); ASSERT_TRUE(config.has_value()); EXPECT_TRUE( encoder->UpdateConfig(*config, MakeServerId(kServerId, server_id_len))); EXPECT_EQ(visitor.num_adds(), 1u); LoadBalancerEncoderPeer::SetNumNoncesLeft(*encoder, 2); EXPECT_EQ(encoder->num_nonces_left(), 2); EXPECT_EQ(encoder->GenerateConnectionId(), QuicConnectionId({0x07, 0x29, 0xd8, 0xc2, 0x17, 0xce, 0x2d, 0x92})); EXPECT_EQ(encoder->num_nonces_left(), 1); encoder->GenerateConnectionId(); EXPECT_EQ(encoder->IsEncoding(), false); EXPECT_EQ(visitor.num_deletes(), 1u); } TEST_F(LoadBalancerEncoderTest, UnroutableConnectionId) { random_.AddNextValues(0x83, kNonceHigh); auto encoder = LoadBalancerEncoder::Create(random_, nullptr, false); ASSERT_TRUE(encoder.has_value()); EXPECT_EQ(encoder->num_nonces_left(), 0); auto connection_id = encoder->GenerateConnectionId(); QuicConnectionId expected({0xe3, 0x5d, 0x52, 0xde, 0x4d, 0xe3, 0xe7, 0x21}); EXPECT_EQ(expected, connection_id); } TEST_F(LoadBalancerEncoderTest, NonDefaultUnroutableConnectionIdLength) { auto encoder = LoadBalancerEncoder::Create(random_, nullptr, true, 9); ASSERT_TRUE(encoder.has_value()); QuicConnectionId connection_id = encoder->GenerateConnectionId(); EXPECT_EQ(connection_id.length(), 9); } TEST_F(LoadBalancerEncoderTest, DeleteConfigWhenNoConfigExists) { TestLoadBalancerEncoderVisitor visitor; auto encoder = LoadBalancerEncoder::Create(random_, &visitor, true); ASSERT_TRUE(encoder.has_value()); encoder->DeleteConfig(); EXPECT_EQ(visitor.num_deletes(), 0u); } TEST_F(LoadBalancerEncoderTest, AddConfig) { auto config = LoadBalancerConfig::CreateUnencrypted(0, 3, 4); ASSERT_TRUE(config.has_value()); TestLoadBalancerEncoderVisitor visitor; auto encoder = LoadBalancerEncoder::Create(random_, &visitor, true); EXPECT_TRUE(encoder->UpdateConfig(*config, MakeServerId(kServerId, 3))); EXPECT_EQ(visitor.num_adds(), 1u); absl::uint128 left = encoder->num_nonces_left(); EXPECT_EQ(left, (0x1ull << 32)); EXPECT_TRUE(encoder->IsEncoding()); EXPECT_FALSE(encoder->IsEncrypted()); encoder->GenerateConnectionId(); EXPECT_EQ(encoder->num_nonces_left(), left - 1); EXPECT_EQ(visitor.num_deletes(), 0u); } TEST_F(LoadBalancerEncoderTest, UpdateConfig) { auto config = LoadBalancerConfig::CreateUnencrypted(0, 3, 4); ASSERT_TRUE(config.has_value()); TestLoadBalancerEncoderVisitor visitor; auto encoder = LoadBalancerEncoder::Create(random_, &visitor, true); EXPECT_TRUE(encoder->UpdateConfig(*config, MakeServerId(kServerId, 3))); config = LoadBalancerConfig::Create(1, 4, 4, kKey); ASSERT_TRUE(config.has_value()); EXPECT_TRUE(encoder->UpdateConfig(*config, MakeServerId(kServerId, 4))); EXPECT_EQ(visitor.num_adds(), 2u); EXPECT_EQ(visitor.num_deletes(), 1u); EXPECT_TRUE(encoder->IsEncoding()); EXPECT_TRUE(encoder->IsEncrypted()); } TEST_F(LoadBalancerEncoderTest, DeleteConfig) { auto config = LoadBalancerConfig::CreateUnencrypted(0, 3, 4); ASSERT_TRUE(config.has_value()); TestLoadBalancerEncoderVisitor visitor; auto encoder = LoadBalancerEncoder::Create(random_, &visitor, true); EXPECT_TRUE(encoder->UpdateConfig(*config, MakeServerId(kServerId, 3))); encoder->DeleteConfig(); EXPECT_EQ(visitor.num_adds(), 1u); EXPECT_EQ(visitor.num_deletes(), 1u); EXPECT_FALSE(encoder->IsEncoding()); EXPECT_FALSE(encoder->IsEncrypted()); EXPECT_EQ(encoder->num_nonces_left(), 0); } TEST_F(LoadBalancerEncoderTest, DeleteConfigNoVisitor) { auto config = LoadBalancerConfig::CreateUnencrypted(0, 3, 4); ASSERT_TRUE(config.has_value()); auto encoder = LoadBalancerEncoder::Create(random_, nullptr, true); EXPECT_TRUE(encoder->UpdateConfig(*config, MakeServerId(kServerId, 3))); encoder->DeleteConfig(); EXPECT_FALSE(encoder->IsEncoding()); EXPECT_FALSE(encoder->IsEncrypted()); EXPECT_EQ(encoder->num_nonces_left(), 0); } TEST_F(LoadBalancerEncoderTest, MaybeReplaceConnectionIdReturnsNoChange) { auto encoder = LoadBalancerEncoder::Create(random_, nullptr, false); ASSERT_TRUE(encoder.has_value()); EXPECT_EQ(encoder->MaybeReplaceConnectionId(TestConnectionId(1), ParsedQuicVersion::Q046()), std::nullopt); } TEST_F(LoadBalancerEncoderTest, MaybeReplaceConnectionIdReturnsChange) { random_.AddNextValues(0x83, kNonceHigh); auto encoder = LoadBalancerEncoder::Create(random_, nullptr, false); ASSERT_TRUE(encoder.has_value()); QuicConnectionId expected({0xe3, 0x5d, 0x52, 0xde, 0x4d, 0xe3, 0xe7, 0x21}); EXPECT_EQ(*encoder->MaybeReplaceConnectionId(TestConnectionId(1), ParsedQuicVersion::RFCv1()), expected); } TEST_F(LoadBalancerEncoderTest, GenerateNextConnectionIdReturnsNoChange) { auto config = LoadBalancerConfig::CreateUnencrypted(0, 3, 4); ASSERT_TRUE(config.has_value()); auto encoder = LoadBalancerEncoder::Create(random_, nullptr, true); EXPECT_TRUE(encoder->UpdateConfig(*config, MakeServerId(kServerId, 3))); EXPECT_EQ(encoder->GenerateNextConnectionId(TestConnectionId(1)), std::nullopt); } TEST_F(LoadBalancerEncoderTest, GenerateNextConnectionIdReturnsChange) { random_.AddNextValues(0x83, kNonceHigh); auto encoder = LoadBalancerEncoder::Create(random_, nullptr, false); ASSERT_TRUE(encoder.has_value()); QuicConnectionId expected({0xe3, 0x5d, 0x52, 0xde, 0x4d, 0xe3, 0xe7, 0x21}); EXPECT_EQ(*encoder->GenerateNextConnectionId(TestConnectionId(1)), expected); } TEST_F(LoadBalancerEncoderTest, ConnectionIdLengthsEncoded) { auto len_encoder = LoadBalancerEncoder::Create(random_, nullptr, true); ASSERT_TRUE(len_encoder.has_value()); EXPECT_EQ(len_encoder->ConnectionIdLength(0xe8), 9); EXPECT_EQ(len_encoder->ConnectionIdLength(0x4a), 11); EXPECT_EQ(len_encoder->ConnectionIdLength(0x09), 10); auto encoder = LoadBalancerEncoder::Create(random_, nullptr, false); ASSERT_TRUE(encoder.has_value()); EXPECT_EQ(encoder->ConnectionIdLength(0xe8), kQuicDefaultConnectionIdLength); EXPECT_EQ(encoder->ConnectionIdLength(0x4a), kQuicDefaultConnectionIdLength); EXPECT_EQ(encoder->ConnectionIdLength(0x09), kQuicDefaultConnectionIdLength); uint8_t config_id = 0; uint8_t server_id_len = 3; uint8_t nonce_len = 6; uint8_t config_0_len = server_id_len + nonce_len + 1; auto config0 = LoadBalancerConfig::CreateUnencrypted(config_id, server_id_len, nonce_len); ASSERT_TRUE(config0.has_value()); EXPECT_TRUE( encoder->UpdateConfig(*config0, MakeServerId(kServerId, server_id_len))); EXPECT_EQ(encoder->ConnectionIdLength(0xe8), kQuicDefaultConnectionIdLength); EXPECT_EQ(encoder->ConnectionIdLength(0x4a), kQuicDefaultConnectionIdLength); EXPECT_EQ(encoder->ConnectionIdLength(0x09), config_0_len); config_id = 1; nonce_len++; uint8_t config_1_len = server_id_len + nonce_len + 1; auto config1 = LoadBalancerConfig::CreateUnencrypted(config_id, server_id_len, nonce_len); ASSERT_TRUE(config1.has_value()); EXPECT_TRUE( encoder->UpdateConfig(*config1, MakeServerId(kServerId, server_id_len))); EXPECT_EQ(encoder->ConnectionIdLength(0xe8), kQuicDefaultConnectionIdLength); EXPECT_EQ(encoder->ConnectionIdLength(0x2a), config_1_len); EXPECT_EQ(encoder->ConnectionIdLength(0x09), config_0_len); encoder->DeleteConfig(); EXPECT_EQ(encoder->ConnectionIdLength(0xe8), kQuicDefaultConnectionIdLength); EXPECT_EQ(encoder->ConnectionIdLength(0x2a), config_1_len); EXPECT_EQ(encoder->ConnectionIdLength(0x09), config_0_len); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/load_balancer/load_balancer_encoder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/load_balancer/load_balancer_encoder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
aed1bfa8-3197-4ba7-a461-0988923182a5
cpp
google/quiche
load_balancer_decoder
quiche/quic/load_balancer/load_balancer_decoder.cc
quiche/quic/load_balancer/load_balancer_decoder_test.cc
#include "quiche/quic/load_balancer/load_balancer_decoder.h" #include <cstdint> #include <cstring> #include <optional> #include "absl/types/span.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/load_balancer/load_balancer_config.h" #include "quiche/quic/load_balancer/load_balancer_server_id.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" namespace quic { bool LoadBalancerDecoder::AddConfig(const LoadBalancerConfig& config) { if (config_[config.config_id()].has_value()) { return false; } config_[config.config_id()] = config; return true; } void LoadBalancerDecoder::DeleteConfig(uint8_t config_id) { if (config_id >= kNumLoadBalancerConfigs) { QUIC_BUG(quic_bug_438896865_01) << "Decoder deleting config with invalid config_id " << static_cast<int>(config_id); return; } config_[config_id].reset(); } bool LoadBalancerDecoder::GetServerId(const QuicConnectionId& connection_id, LoadBalancerServerId& server_id) const { std::optional<uint8_t> config_id = GetConfigId(connection_id); if (!config_id.has_value()) { return false; } std::optional<LoadBalancerConfig> config = config_[*config_id]; if (!config.has_value()) { return false; } if (connection_id.length() < config->total_len()) { return false; } const uint8_t* data = reinterpret_cast<const uint8_t*>(connection_id.data()) + 1; uint8_t server_id_len = config->server_id_len(); server_id.set_length(server_id_len); if (!config->IsEncrypted()) { memcpy(server_id.mutable_data(), connection_id.data() + 1, server_id_len); return true; } if (config->plaintext_len() == kLoadBalancerBlockSize) { return config->BlockDecrypt(data, server_id.mutable_data()); } return config->FourPassDecrypt( absl::MakeConstSpan(data, connection_id.length() - 1), server_id); } std::optional<uint8_t> LoadBalancerDecoder::GetConfigId( const QuicConnectionId& connection_id) { if (connection_id.IsEmpty()) { return std::optional<uint8_t>(); } return GetConfigId(*reinterpret_cast<const uint8_t*>(connection_id.data())); } std::optional<uint8_t> LoadBalancerDecoder::GetConfigId( const uint8_t connection_id_first_byte) { uint8_t codepoint = (connection_id_first_byte >> kConnectionIdLengthBits); if (codepoint < kNumLoadBalancerConfigs) { return codepoint; } return std::optional<uint8_t>(); } }
#include "quiche/quic/load_balancer/load_balancer_decoder.h" #include <cstdint> #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/load_balancer/load_balancer_config.h" #include "quiche/quic/load_balancer/load_balancer_server_id.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { namespace { class LoadBalancerDecoderTest : public QuicTest {}; inline LoadBalancerServerId MakeServerId(const uint8_t array[], const uint8_t length) { return LoadBalancerServerId(absl::Span<const uint8_t>(array, length)); } constexpr char kRawKey[] = {0x8f, 0x95, 0xf0, 0x92, 0x45, 0x76, 0x5f, 0x80, 0x25, 0x69, 0x34, 0xe5, 0x0c, 0x66, 0x20, 0x7f}; constexpr absl::string_view kKey(kRawKey, kLoadBalancerKeyLen); constexpr uint8_t kServerId[] = {0xed, 0x79, 0x3a, 0x51, 0xd4, 0x9b, 0x8f, 0x5f, 0xab, 0x65, 0xba, 0x04, 0xc3, 0x33, 0x0a}; struct LoadBalancerDecoderTestCase { LoadBalancerConfig config; QuicConnectionId connection_id; LoadBalancerServerId server_id; }; TEST_F(LoadBalancerDecoderTest, UnencryptedConnectionIdTestVectors) { const struct LoadBalancerDecoderTestCase test_vectors[2] = { { *LoadBalancerConfig::CreateUnencrypted(0, 3, 4), QuicConnectionId({0x07, 0xed, 0x79, 0x3a, 0x80, 0x49, 0x71, 0x8a}), MakeServerId(kServerId, 3), }, { *LoadBalancerConfig::CreateUnencrypted(1, 8, 5), QuicConnectionId({0x2d, 0xed, 0x79, 0x3a, 0x51, 0xd4, 0x9b, 0x8f, 0x5f, 0xee, 0x15, 0xda, 0x27, 0xc4}), MakeServerId(kServerId, 8), }}; for (const auto& test : test_vectors) { LoadBalancerDecoder decoder; LoadBalancerServerId answer; EXPECT_TRUE(decoder.AddConfig(test.config)); EXPECT_TRUE(decoder.GetServerId(test.connection_id, answer)); EXPECT_EQ(answer, test.server_id); } } TEST_F(LoadBalancerDecoderTest, DecoderTestVectors) { const struct LoadBalancerDecoderTestCase test_vectors[4] = { { *LoadBalancerConfig::Create(0, 3, 4, kKey), QuicConnectionId({0x07, 0x20, 0xb1, 0xd0, 0x7b, 0x35, 0x9d, 0x3c}), MakeServerId(kServerId, 3), }, { *LoadBalancerConfig::Create(1, 10, 5, kKey), QuicConnectionId({0x2f, 0xcc, 0x38, 0x1b, 0xc7, 0x4c, 0xb4, 0xfb, 0xad, 0x28, 0x23, 0xa3, 0xd1, 0xf8, 0xfe, 0xd2}), MakeServerId(kServerId, 10), }, { *LoadBalancerConfig::Create(2, 8, 8, kKey), QuicConnectionId({0x50, 0x4d, 0xd2, 0xd0, 0x5a, 0x7b, 0x0d, 0xe9, 0xb2, 0xb9, 0x90, 0x7a, 0xfb, 0x5e, 0xcf, 0x8c, 0xc3}), MakeServerId(kServerId, 8), }, { *LoadBalancerConfig::Create(0, 9, 9, kKey), QuicConnectionId({0x12, 0x57, 0x79, 0xc9, 0xcc, 0x86, 0xbe, 0xb3, 0xa3, 0xa4, 0xa3, 0xca, 0x96, 0xfc, 0xe4, 0xbf, 0xe0, 0xcd, 0xbc}), MakeServerId(kServerId, 9), }, }; for (const auto& test : test_vectors) { LoadBalancerDecoder decoder; EXPECT_TRUE(decoder.AddConfig(test.config)); LoadBalancerServerId answer; EXPECT_TRUE(decoder.GetServerId(test.connection_id, answer)); EXPECT_EQ(answer, test.server_id); } } TEST_F(LoadBalancerDecoderTest, InvalidConfigId) { LoadBalancerServerId server_id({0x01, 0x02, 0x03}); EXPECT_TRUE(server_id.IsValid()); LoadBalancerDecoder decoder; EXPECT_TRUE( decoder.AddConfig(*LoadBalancerConfig::CreateUnencrypted(1, 3, 4))); QuicConnectionId wrong_config_id( {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}); LoadBalancerServerId answer; EXPECT_FALSE(decoder.GetServerId( QuicConnectionId({0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}), answer)); } TEST_F(LoadBalancerDecoderTest, UnroutableCodepoint) { LoadBalancerServerId server_id({0x01, 0x02, 0x03}); EXPECT_TRUE(server_id.IsValid()); LoadBalancerDecoder decoder; EXPECT_TRUE( decoder.AddConfig(*LoadBalancerConfig::CreateUnencrypted(1, 3, 4))); LoadBalancerServerId answer; EXPECT_FALSE(decoder.GetServerId( QuicConnectionId({0xe0, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}), answer)); } TEST_F(LoadBalancerDecoderTest, UnroutableCodepointAnyLength) { LoadBalancerServerId server_id({0x01, 0x02, 0x03}); EXPECT_TRUE(server_id.IsValid()); LoadBalancerDecoder decoder; EXPECT_TRUE( decoder.AddConfig(*LoadBalancerConfig::CreateUnencrypted(1, 3, 4))); LoadBalancerServerId answer; EXPECT_FALSE(decoder.GetServerId(QuicConnectionId({0xff}), answer)); } TEST_F(LoadBalancerDecoderTest, ConnectionIdTooShort) { LoadBalancerServerId server_id({0x01, 0x02, 0x03}); EXPECT_TRUE(server_id.IsValid()); LoadBalancerDecoder decoder; EXPECT_TRUE( decoder.AddConfig(*LoadBalancerConfig::CreateUnencrypted(0, 3, 4))); LoadBalancerServerId answer; EXPECT_FALSE(decoder.GetServerId( QuicConnectionId({0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06}), answer)); } TEST_F(LoadBalancerDecoderTest, ConnectionIdTooLongIsOK) { LoadBalancerServerId server_id({0x01, 0x02, 0x03}); LoadBalancerDecoder decoder; EXPECT_TRUE( decoder.AddConfig(*LoadBalancerConfig::CreateUnencrypted(0, 3, 4))); LoadBalancerServerId answer; EXPECT_TRUE(decoder.GetServerId( QuicConnectionId({0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}), answer)); EXPECT_EQ(answer, server_id); } TEST_F(LoadBalancerDecoderTest, DeleteConfigBadId) { LoadBalancerDecoder decoder; decoder.AddConfig(*LoadBalancerConfig::CreateUnencrypted(2, 3, 4)); decoder.DeleteConfig(0); EXPECT_QUIC_BUG(decoder.DeleteConfig(7), "Decoder deleting config with invalid config_id 7"); LoadBalancerServerId answer; EXPECT_TRUE(decoder.GetServerId( QuicConnectionId({0x40, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}), answer)); } TEST_F(LoadBalancerDecoderTest, DeleteConfigGoodId) { LoadBalancerDecoder decoder; decoder.AddConfig(*LoadBalancerConfig::CreateUnencrypted(2, 3, 4)); decoder.DeleteConfig(2); LoadBalancerServerId answer; EXPECT_FALSE(decoder.GetServerId( QuicConnectionId({0x40, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}), answer)); } TEST_F(LoadBalancerDecoderTest, TwoServerIds) { LoadBalancerServerId server_id1({0x01, 0x02, 0x03}); EXPECT_TRUE(server_id1.IsValid()); LoadBalancerServerId server_id2({0x04, 0x05, 0x06}); LoadBalancerDecoder decoder; EXPECT_TRUE( decoder.AddConfig(*LoadBalancerConfig::CreateUnencrypted(0, 3, 4))); LoadBalancerServerId answer; EXPECT_TRUE(decoder.GetServerId( QuicConnectionId({0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}), answer)); EXPECT_EQ(answer, server_id1); EXPECT_TRUE(decoder.GetServerId( QuicConnectionId({0x00, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a}), answer)); EXPECT_EQ(answer, server_id2); } TEST_F(LoadBalancerDecoderTest, GetConfigId) { EXPECT_FALSE( LoadBalancerDecoder::GetConfigId(QuicConnectionId()).has_value()); for (uint8_t i = 0; i < kNumLoadBalancerConfigs; i++) { const QuicConnectionId connection_id( {static_cast<unsigned char>(i << kConnectionIdLengthBits)}); auto config_id = LoadBalancerDecoder::GetConfigId(connection_id); EXPECT_EQ(config_id, LoadBalancerDecoder::GetConfigId(connection_id.data()[0])); EXPECT_TRUE(config_id.has_value()); EXPECT_EQ(*config_id, i); } EXPECT_FALSE( LoadBalancerDecoder::GetConfigId(QuicConnectionId({0xe0})).has_value()); } TEST_F(LoadBalancerDecoderTest, GetConfig) { LoadBalancerDecoder decoder; decoder.AddConfig(*LoadBalancerConfig::CreateUnencrypted(2, 3, 4)); EXPECT_EQ(decoder.GetConfig(0), nullptr); EXPECT_EQ(decoder.GetConfig(1), nullptr); EXPECT_EQ(decoder.GetConfig(3), nullptr); EXPECT_EQ(decoder.GetConfig(4), nullptr); const LoadBalancerConfig* config = decoder.GetConfig(2); ASSERT_NE(config, nullptr); EXPECT_EQ(config->server_id_len(), 3); EXPECT_EQ(config->nonce_len(), 4); EXPECT_FALSE(config->IsEncrypted()); } TEST_F(LoadBalancerDecoderTest, OnePassIgnoreAdditionalBytes) { uint8_t ptext[] = {0x00, 0xed, 0x79, 0x3a, 0x51, 0xd4, 0x9b, 0x8f, 0x5f, 0xee, 0x08, 0x0d, 0xbf, 0x48, 0xc0, 0xd1, 0xe5, 0xda, 0x41}; uint8_t ctext[] = {0x00, 0x4d, 0xd2, 0xd0, 0x5a, 0x7b, 0x0d, 0xe9, 0xb2, 0xb9, 0x90, 0x7a, 0xfb, 0x5e, 0xcf, 0x8c, 0xc3, 0xda, 0x41}; LoadBalancerDecoder decoder; decoder.AddConfig( *LoadBalancerConfig::Create(0, 8, 8, absl::string_view(kRawKey, 16))); LoadBalancerServerId original_server_id(absl::Span<uint8_t>(&ptext[1], 8)); QuicConnectionId cid(absl::Span<uint8_t>(ctext, sizeof(ctext))); LoadBalancerServerId answer; EXPECT_TRUE(decoder.GetServerId(cid, answer)); EXPECT_EQ(answer, original_server_id); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/load_balancer/load_balancer_decoder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/load_balancer/load_balancer_decoder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
372d4460-9985-4cc1-aa7e-8af1791b749f
cpp
google/quiche
quic_sustained_bandwidth_recorder
quiche/quic/core/quic_sustained_bandwidth_recorder.cc
quiche/quic/core/quic_sustained_bandwidth_recorder_test.cc
#include "quiche/quic/core/quic_sustained_bandwidth_recorder.h" #include "quiche/quic/core/quic_bandwidth.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { QuicSustainedBandwidthRecorder::QuicSustainedBandwidthRecorder() : has_estimate_(false), is_recording_(false), bandwidth_estimate_recorded_during_slow_start_(false), bandwidth_estimate_(QuicBandwidth::Zero()), max_bandwidth_estimate_(QuicBandwidth::Zero()), max_bandwidth_timestamp_(0), start_time_(QuicTime::Zero()) {} void QuicSustainedBandwidthRecorder::RecordEstimate( bool in_recovery, bool in_slow_start, QuicBandwidth bandwidth, QuicTime estimate_time, QuicWallTime wall_time, QuicTime::Delta srtt) { if (in_recovery) { is_recording_ = false; QUIC_DVLOG(1) << "Stopped recording at: " << estimate_time.ToDebuggingValue(); return; } if (!is_recording_) { start_time_ = estimate_time; is_recording_ = true; QUIC_DVLOG(1) << "Started recording at: " << start_time_.ToDebuggingValue(); return; } if (estimate_time - start_time_ >= 3 * srtt) { has_estimate_ = true; bandwidth_estimate_recorded_during_slow_start_ = in_slow_start; bandwidth_estimate_ = bandwidth; QUIC_DVLOG(1) << "New sustained bandwidth estimate (KBytes/s): " << bandwidth_estimate_.ToKBytesPerSecond(); } if (bandwidth > max_bandwidth_estimate_) { max_bandwidth_estimate_ = bandwidth; max_bandwidth_timestamp_ = wall_time.ToUNIXSeconds(); QUIC_DVLOG(1) << "New max bandwidth estimate (KBytes/s): " << max_bandwidth_estimate_.ToKBytesPerSecond(); } } }
#include "quiche/quic/core/quic_sustained_bandwidth_recorder.h" #include "quiche/quic/core/quic_bandwidth.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { namespace { class QuicSustainedBandwidthRecorderTest : public QuicTest {}; TEST_F(QuicSustainedBandwidthRecorderTest, BandwidthEstimates) { QuicSustainedBandwidthRecorder recorder; EXPECT_FALSE(recorder.HasEstimate()); QuicTime estimate_time = QuicTime::Zero(); QuicWallTime wall_time = QuicWallTime::Zero(); QuicTime::Delta srtt = QuicTime::Delta::FromMilliseconds(150); const int kBandwidthBitsPerSecond = 12345678; QuicBandwidth bandwidth = QuicBandwidth::FromBitsPerSecond(kBandwidthBitsPerSecond); bool in_recovery = false; bool in_slow_start = false; recorder.RecordEstimate(in_recovery, in_slow_start, bandwidth, estimate_time, wall_time, srtt); EXPECT_FALSE(recorder.HasEstimate()); estimate_time = estimate_time + srtt; recorder.RecordEstimate(in_recovery, in_slow_start, bandwidth, estimate_time, wall_time, srtt); EXPECT_FALSE(recorder.HasEstimate()); estimate_time = estimate_time + srtt; estimate_time = estimate_time + srtt; recorder.RecordEstimate(in_recovery, in_slow_start, bandwidth, estimate_time, wall_time, srtt); EXPECT_TRUE(recorder.HasEstimate()); EXPECT_EQ(recorder.BandwidthEstimate(), bandwidth); EXPECT_EQ(recorder.BandwidthEstimate(), recorder.MaxBandwidthEstimate()); QuicBandwidth second_bandwidth = QuicBandwidth::FromBitsPerSecond(2 * kBandwidthBitsPerSecond); in_recovery = true; recorder.RecordEstimate(in_recovery, in_slow_start, bandwidth, estimate_time, wall_time, srtt); in_recovery = false; recorder.RecordEstimate(in_recovery, in_slow_start, bandwidth, estimate_time, wall_time, srtt); EXPECT_EQ(recorder.BandwidthEstimate(), bandwidth); estimate_time = estimate_time + 3 * srtt; const int64_t kSeconds = 556677; QuicWallTime second_bandwidth_wall_time = QuicWallTime::FromUNIXSeconds(kSeconds); recorder.RecordEstimate(in_recovery, in_slow_start, second_bandwidth, estimate_time, second_bandwidth_wall_time, srtt); EXPECT_EQ(recorder.BandwidthEstimate(), second_bandwidth); EXPECT_EQ(recorder.BandwidthEstimate(), recorder.MaxBandwidthEstimate()); EXPECT_EQ(recorder.MaxBandwidthTimestamp(), kSeconds); QuicBandwidth third_bandwidth = QuicBandwidth::FromBitsPerSecond(0.5 * kBandwidthBitsPerSecond); recorder.RecordEstimate(in_recovery, in_slow_start, third_bandwidth, estimate_time, wall_time, srtt); recorder.RecordEstimate(in_recovery, in_slow_start, third_bandwidth, estimate_time, wall_time, srtt); EXPECT_EQ(recorder.BandwidthEstimate(), third_bandwidth); estimate_time = estimate_time + 3 * srtt; recorder.RecordEstimate(in_recovery, in_slow_start, third_bandwidth, estimate_time, wall_time, srtt); EXPECT_EQ(recorder.BandwidthEstimate(), third_bandwidth); EXPECT_LT(third_bandwidth, second_bandwidth); EXPECT_EQ(recorder.MaxBandwidthEstimate(), second_bandwidth); EXPECT_EQ(recorder.MaxBandwidthTimestamp(), kSeconds); } TEST_F(QuicSustainedBandwidthRecorderTest, SlowStart) { QuicSustainedBandwidthRecorder recorder; EXPECT_FALSE(recorder.HasEstimate()); QuicTime estimate_time = QuicTime::Zero(); QuicWallTime wall_time = QuicWallTime::Zero(); QuicTime::Delta srtt = QuicTime::Delta::FromMilliseconds(150); const int kBandwidthBitsPerSecond = 12345678; QuicBandwidth bandwidth = QuicBandwidth::FromBitsPerSecond(kBandwidthBitsPerSecond); bool in_recovery = false; bool in_slow_start = true; recorder.RecordEstimate(in_recovery, in_slow_start, bandwidth, estimate_time, wall_time, srtt); estimate_time = estimate_time + 3 * srtt; recorder.RecordEstimate(in_recovery, in_slow_start, bandwidth, estimate_time, wall_time, srtt); EXPECT_TRUE(recorder.HasEstimate()); EXPECT_TRUE(recorder.EstimateRecordedDuringSlowStart()); estimate_time = estimate_time + 3 * srtt; in_slow_start = false; recorder.RecordEstimate(in_recovery, in_slow_start, bandwidth, estimate_time, wall_time, srtt); EXPECT_TRUE(recorder.HasEstimate()); EXPECT_FALSE(recorder.EstimateRecordedDuringSlowStart()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_sustained_bandwidth_recorder.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_sustained_bandwidth_recorder_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
e8e2de40-a21c-4b51-aef3-3f6259a0dd1a
cpp
google/quiche
quic_generic_session
quiche/quic/core/quic_generic_session.cc
quiche/quic/core/quic_generic_session_test.cc
#include "quiche/quic/core/quic_generic_session.h" #include <cstdint> #include <memory> #include <optional> #include <string> #include <utility> #include "absl/strings/string_view.h" #include "quiche/quic/core/http/web_transport_stream_adapter.h" #include "quiche/quic/core/quic_crypto_client_stream.h" #include "quiche/quic/core/quic_session.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_bug_tracker.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/common/simple_buffer_allocator.h" #include "quiche/web_transport/web_transport.h" namespace quic { namespace { class NoOpProofHandler : public QuicCryptoClientStream::ProofHandler { public: void OnProofValid(const QuicCryptoClientConfig::CachedState&) override {} void OnProofVerifyDetailsAvailable(const ProofVerifyDetails&) override {} }; class NoOpServerCryptoHelper : public QuicCryptoServerStreamBase::Helper { public: bool CanAcceptClientHello(const CryptoHandshakeMessage& , const QuicSocketAddress& , const QuicSocketAddress& , const QuicSocketAddress& , std::string* ) const override { return true; } }; } ParsedQuicVersionVector GetQuicVersionsForGenericSession() { return {ParsedQuicVersion::RFCv1()}; } class QUICHE_EXPORT QuicGenericStream : public QuicStream { public: QuicGenericStream(QuicStreamId id, QuicSession* session) : QuicStream(id, session, false, QuicUtils::GetStreamType( id, session->connection()->perspective(), session->IsIncomingStream(id), session->version())), adapter_(session, this, sequencer(), std::nullopt) { adapter_.SetPriority(webtransport::StreamPriority{0, 0}); } WebTransportStreamAdapter* adapter() { return &adapter_; } void OnDataAvailable() override { adapter_.OnDataAvailable(); } void OnCanWriteNewData() override { adapter_.OnCanWriteNewData(); } private: WebTransportStreamAdapter adapter_; }; QuicGenericSessionBase::QuicGenericSessionBase( QuicConnection* connection, bool owns_connection, Visitor* owner, const QuicConfig& config, std::string alpn, WebTransportVisitor* visitor, bool owns_visitor, std::unique_ptr<QuicDatagramQueue::Observer> datagram_observer) : QuicSession(connection, owner, config, GetQuicVersionsForGenericSession(), 0, std::move(datagram_observer), QuicPriorityType::kWebTransport), alpn_(std::move(alpn)), visitor_(visitor), owns_connection_(owns_connection), owns_visitor_(owns_visitor) {} QuicGenericSessionBase::~QuicGenericSessionBase() { if (owns_connection_) { DeleteConnection(); } if (owns_visitor_) { delete visitor_; visitor_ = nullptr; } } QuicStream* QuicGenericSessionBase::CreateIncomingStream(QuicStreamId id) { QUIC_DVLOG(1) << "Creating incoming QuicGenricStream " << id; QuicGenericStream* stream = CreateStream(id); if (stream->type() == BIDIRECTIONAL) { incoming_bidirectional_streams_.push_back(id); visitor_->OnIncomingBidirectionalStreamAvailable(); } else { incoming_unidirectional_streams_.push_back(id); visitor_->OnIncomingUnidirectionalStreamAvailable(); } return stream; } void QuicGenericSessionBase::OnTlsHandshakeComplete() { QuicSession::OnTlsHandshakeComplete(); visitor_->OnSessionReady(); } webtransport::Stream* QuicGenericSessionBase::AcceptIncomingBidirectionalStream() { while (!incoming_bidirectional_streams_.empty()) { webtransport::Stream* stream = GetStreamById(incoming_bidirectional_streams_.front()); incoming_bidirectional_streams_.pop_front(); if (stream != nullptr) { return stream; } } return nullptr; } webtransport::Stream* QuicGenericSessionBase::AcceptIncomingUnidirectionalStream() { while (!incoming_unidirectional_streams_.empty()) { webtransport::Stream* stream = GetStreamById(incoming_unidirectional_streams_.front()); incoming_unidirectional_streams_.pop_front(); if (stream != nullptr) { return stream; } } return nullptr; } webtransport::Stream* QuicGenericSessionBase::OpenOutgoingBidirectionalStream() { if (!CanOpenNextOutgoingBidirectionalStream()) { QUIC_BUG(QuicGenericSessionBase_flow_control_violation_bidi) << "Attempted to open a stream in violation of flow control"; return nullptr; } return CreateStream(GetNextOutgoingBidirectionalStreamId())->adapter(); } webtransport::Stream* QuicGenericSessionBase::OpenOutgoingUnidirectionalStream() { if (!CanOpenNextOutgoingUnidirectionalStream()) { QUIC_BUG(QuicGenericSessionBase_flow_control_violation_unidi) << "Attempted to open a stream in violation of flow control"; return nullptr; } return CreateStream(GetNextOutgoingUnidirectionalStreamId())->adapter(); } QuicGenericStream* QuicGenericSessionBase::CreateStream(QuicStreamId id) { auto stream = std::make_unique<QuicGenericStream>(id, this); QuicGenericStream* stream_ptr = stream.get(); ActivateStream(std::move(stream)); return stream_ptr; } void QuicGenericSessionBase::OnMessageReceived(absl::string_view message) { visitor_->OnDatagramReceived(message); } void QuicGenericSessionBase::OnCanCreateNewOutgoingStream(bool unidirectional) { if (unidirectional) { visitor_->OnCanCreateNewOutgoingUnidirectionalStream(); } else { visitor_->OnCanCreateNewOutgoingBidirectionalStream(); } } webtransport::Stream* QuicGenericSessionBase::GetStreamById( webtransport::StreamId id) { QuicStream* stream = GetActiveStream(id); if (stream == nullptr) { return nullptr; } return static_cast<QuicGenericStream*>(stream)->adapter(); } webtransport::DatagramStatus QuicGenericSessionBase::SendOrQueueDatagram( absl::string_view datagram) { quiche::QuicheBuffer buffer = quiche::QuicheBuffer::Copy( quiche::SimpleBufferAllocator::Get(), datagram); return MessageStatusToWebTransportStatus( datagram_queue()->SendOrQueueDatagram( quiche::QuicheMemSlice(std::move(buffer)))); } void QuicGenericSessionBase::OnConnectionClosed( const QuicConnectionCloseFrame& frame, ConnectionCloseSource source) { QuicSession::OnConnectionClosed(frame, source); visitor_->OnSessionClosed(static_cast<webtransport::SessionErrorCode>( frame.transport_close_frame_type), frame.error_details); } QuicGenericClientSession::QuicGenericClientSession( QuicConnection* connection, bool owns_connection, Visitor* owner, const QuicConfig& config, std::string host, uint16_t port, std::string alpn, webtransport::SessionVisitor* visitor, bool owns_visitor, std::unique_ptr<QuicDatagramQueue::Observer> datagram_observer, QuicCryptoClientConfig* crypto_config) : QuicGenericSessionBase(connection, owns_connection, owner, config, std::move(alpn), visitor, owns_visitor, std::move(datagram_observer)) { static NoOpProofHandler* handler = new NoOpProofHandler(); crypto_stream_ = std::make_unique<QuicCryptoClientStream>( QuicServerId(std::move(host), port), this, crypto_config->proof_verifier()->CreateDefaultContext(), crypto_config, handler, false); } QuicGenericClientSession::QuicGenericClientSession( QuicConnection* connection, bool owns_connection, Visitor* owner, const QuicConfig& config, std::string host, uint16_t port, std::string alpn, CreateWebTransportSessionVisitorCallback create_visitor_callback, std::unique_ptr<QuicDatagramQueue::Observer> datagram_observer, QuicCryptoClientConfig* crypto_config) : QuicGenericClientSession( connection, owns_connection, owner, config, std::move(host), port, std::move(alpn), std::move(create_visitor_callback)(*this).release(), true, std::move(datagram_observer), crypto_config) {} QuicGenericServerSession::QuicGenericServerSession( QuicConnection* connection, bool owns_connection, Visitor* owner, const QuicConfig& config, std::string alpn, webtransport::SessionVisitor* visitor, bool owns_visitor, std::unique_ptr<QuicDatagramQueue::Observer> datagram_observer, const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache) : QuicGenericSessionBase(connection, owns_connection, owner, config, std::move(alpn), visitor, owns_visitor, std::move(datagram_observer)) { static NoOpServerCryptoHelper* helper = new NoOpServerCryptoHelper(); crypto_stream_ = CreateCryptoServerStream( crypto_config, compressed_certs_cache, this, helper); } QuicGenericServerSession::QuicGenericServerSession( QuicConnection* connection, bool owns_connection, Visitor* owner, const QuicConfig& config, std::string alpn, CreateWebTransportSessionVisitorCallback create_visitor_callback, std::unique_ptr<QuicDatagramQueue::Observer> datagram_observer, const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache) : QuicGenericServerSession( connection, owns_connection, owner, config, std::move(alpn), std::move(create_visitor_callback)(*this).release(), true, std::move(datagram_observer), crypto_config, compressed_certs_cache) {} }
#include "quiche/quic/core/quic_generic_session.h" #include <cstddef> #include <cstring> #include <memory> #include <optional> #include <string> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/quic_compressed_certs_cache.h" #include "quiche/quic/core/crypto/quic_crypto_client_config.h" #include "quiche/quic/core/crypto/quic_crypto_server_config.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_datagram_queue.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_stream.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/web_transport_interface.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/crypto_test_utils.h" #include "quiche/quic/test_tools/quic_session_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simulator/simulator.h" #include "quiche/quic/test_tools/simulator/test_harness.h" #include "quiche/quic/test_tools/web_transport_test_tools.h" #include "quiche/quic/tools/web_transport_test_visitors.h" #include "quiche/common/quiche_stream.h" #include "quiche/common/test_tools/quiche_test_utils.h" #include "quiche/web_transport/web_transport.h" namespace quic::test { namespace { enum ServerType { kDiscardServer, kEchoServer }; using quiche::test::StatusIs; using simulator::Simulator; using testing::_; using testing::Assign; using testing::AtMost; using testing::Eq; class CountingDatagramObserver : public QuicDatagramQueue::Observer { public: CountingDatagramObserver(int& total) : total_(total) {} void OnDatagramProcessed(std::optional<MessageStatus>) { ++total_; } private: int& total_; }; class ClientEndpoint : public simulator::QuicEndpointWithConnection { public: ClientEndpoint(Simulator* simulator, const std::string& name, const std::string& peer_name, const QuicConfig& config) : QuicEndpointWithConnection(simulator, name, peer_name, Perspective::IS_CLIENT, GetQuicVersionsForGenericSession()), crypto_config_(crypto_test_utils::ProofVerifierForTesting()), session_(connection_.get(), false, nullptr, config, "test.example.com", 443, "example_alpn", &visitor_, false, std::make_unique<CountingDatagramObserver>( total_datagrams_processed_), &crypto_config_) { session_.Initialize(); session_.connection()->sent_packet_manager().SetSendAlgorithm( CongestionControlType::kBBRv2); EXPECT_CALL(visitor_, OnSessionReady()) .Times(AtMost(1)) .WillOnce(Assign(&session_ready_, true)); } QuicGenericClientSession* session() { return &session_; } MockWebTransportSessionVisitor* visitor() { return &visitor_; } bool session_ready() const { return session_ready_; } int total_datagrams_processed() const { return total_datagrams_processed_; } private: QuicCryptoClientConfig crypto_config_; MockWebTransportSessionVisitor visitor_; QuicGenericClientSession session_; bool session_ready_ = false; int total_datagrams_processed_ = 0; }; class ServerEndpoint : public simulator::QuicEndpointWithConnection { public: ServerEndpoint(Simulator* simulator, const std::string& name, const std::string& peer_name, const QuicConfig& config, ServerType type) : QuicEndpointWithConnection(simulator, name, peer_name, Perspective::IS_SERVER, GetQuicVersionsForGenericSession()), crypto_config_(QuicCryptoServerConfig::TESTING, QuicRandom::GetInstance(), crypto_test_utils::ProofSourceForTesting(), KeyExchangeSource::Default()), compressed_certs_cache_( QuicCompressedCertsCache::kQuicCompressedCertsCacheSize), session_(connection_.get(), false, nullptr, config, "example_alpn", type == kEchoServer ? static_cast<webtransport::SessionVisitor*>( new EchoWebTransportSessionVisitor( &session_, false)) : static_cast<webtransport::SessionVisitor*>( new DiscardWebTransportSessionVisitor(&session_)), true, nullptr, &crypto_config_, &compressed_certs_cache_) { session_.Initialize(); session_.connection()->sent_packet_manager().SetSendAlgorithm( CongestionControlType::kBBRv2); } QuicGenericServerSession* session() { return &session_; } private: QuicCryptoServerConfig crypto_config_; QuicCompressedCertsCache compressed_certs_cache_; QuicGenericServerSession session_; }; class QuicGenericSessionTest : public QuicTest { public: void CreateDefaultEndpoints(ServerType server_type) { client_ = std::make_unique<ClientEndpoint>( &test_harness_.simulator(), "Client", "Server", client_config_); server_ = std::make_unique<ServerEndpoint>(&test_harness_.simulator(), "Server", "Client", server_config_, server_type); test_harness_.set_client(client_.get()); test_harness_.set_server(server_.get()); } void WireUpEndpoints() { test_harness_.WireUpEndpoints(); } void RunHandshake() { client_->session()->CryptoConnect(); bool result = test_harness_.RunUntilWithDefaultTimeout([this]() { return client_->session_ready() || client_->session()->error() != QUIC_NO_ERROR; }); EXPECT_TRUE(result); } protected: QuicConfig client_config_ = DefaultQuicConfig(); QuicConfig server_config_ = DefaultQuicConfig(); simulator::TestHarness test_harness_; std::unique_ptr<ClientEndpoint> client_; std::unique_ptr<ServerEndpoint> server_; }; TEST_F(QuicGenericSessionTest, SuccessfulHandshake) { CreateDefaultEndpoints(kDiscardServer); WireUpEndpoints(); RunHandshake(); EXPECT_TRUE(client_->session_ready()); } TEST_F(QuicGenericSessionTest, SendOutgoingStreams) { CreateDefaultEndpoints(kDiscardServer); WireUpEndpoints(); RunHandshake(); std::vector<webtransport::Stream*> streams; for (int i = 0; i < 10; i++) { webtransport::Stream* stream = client_->session()->OpenOutgoingUnidirectionalStream(); ASSERT_TRUE(stream->Write("test")); streams.push_back(stream); } ASSERT_TRUE(test_harness_.RunUntilWithDefaultTimeout([this]() { return QuicSessionPeer::GetNumOpenDynamicStreams(server_->session()) == 10; })); for (webtransport::Stream* stream : streams) { ASSERT_TRUE(stream->SendFin()); } ASSERT_TRUE(test_harness_.RunUntilWithDefaultTimeout([this]() { return QuicSessionPeer::GetNumOpenDynamicStreams(server_->session()) == 0; })); } TEST_F(QuicGenericSessionTest, EchoBidirectionalStreams) { CreateDefaultEndpoints(kEchoServer); WireUpEndpoints(); RunHandshake(); webtransport::Stream* stream = client_->session()->OpenOutgoingBidirectionalStream(); EXPECT_TRUE(stream->Write("Hello!")); ASSERT_TRUE(test_harness_.RunUntilWithDefaultTimeout( [stream]() { return stream->ReadableBytes() == strlen("Hello!"); })); std::string received; WebTransportStream::ReadResult result = stream->Read(&received); EXPECT_EQ(result.bytes_read, strlen("Hello!")); EXPECT_FALSE(result.fin); EXPECT_EQ(received, "Hello!"); EXPECT_TRUE(stream->SendFin()); ASSERT_TRUE(test_harness_.RunUntilWithDefaultTimeout([this]() { return QuicSessionPeer::GetNumOpenDynamicStreams(server_->session()) == 0; })); } TEST_F(QuicGenericSessionTest, EchoUnidirectionalStreams) { CreateDefaultEndpoints(kEchoServer); WireUpEndpoints(); RunHandshake(); webtransport::Stream* stream1 = client_->session()->OpenOutgoingUnidirectionalStream(); EXPECT_TRUE(stream1->Write("Stream One")); webtransport::Stream* stream2 = client_->session()->OpenOutgoingUnidirectionalStream(); EXPECT_TRUE(stream2->Write("Stream Two")); EXPECT_TRUE(stream2->SendFin()); bool stream_received = false; EXPECT_CALL(*client_->visitor(), OnIncomingUnidirectionalStreamAvailable()) .Times(2) .WillRepeatedly(Assign(&stream_received, true)); ASSERT_TRUE(test_harness_.RunUntilWithDefaultTimeout( [&stream_received]() { return stream_received; })); webtransport::Stream* reply = client_->session()->AcceptIncomingUnidirectionalStream(); ASSERT_TRUE(reply != nullptr); std::string buffer; WebTransportStream::ReadResult result = reply->Read(&buffer); EXPECT_GT(result.bytes_read, 0u); EXPECT_TRUE(result.fin); EXPECT_EQ(buffer, "Stream Two"); stream_received = false; buffer = ""; EXPECT_TRUE(stream1->SendFin()); ASSERT_TRUE(test_harness_.RunUntilWithDefaultTimeout( [&stream_received]() { return stream_received; })); reply = client_->session()->AcceptIncomingUnidirectionalStream(); ASSERT_TRUE(reply != nullptr); result = reply->Read(&buffer); EXPECT_GT(result.bytes_read, 0u); EXPECT_TRUE(result.fin); EXPECT_EQ(buffer, "Stream One"); } TEST_F(QuicGenericSessionTest, EchoStreamsUsingPeekApi) { CreateDefaultEndpoints(kEchoServer); WireUpEndpoints(); RunHandshake(); webtransport::Stream* stream1 = client_->session()->OpenOutgoingBidirectionalStream(); EXPECT_TRUE(stream1->Write("Stream One")); webtransport::Stream* stream2 = client_->session()->OpenOutgoingUnidirectionalStream(); EXPECT_TRUE(stream2->Write("Stream Two")); EXPECT_TRUE(stream2->SendFin()); bool stream_received_unidi = false; EXPECT_CALL(*client_->visitor(), OnIncomingUnidirectionalStreamAvailable()) .WillOnce(Assign(&stream_received_unidi, true)); ASSERT_TRUE(test_harness_.RunUntilWithDefaultTimeout( [&]() { return stream_received_unidi; })); webtransport::Stream* reply = client_->session()->AcceptIncomingUnidirectionalStream(); ASSERT_TRUE(reply != nullptr); std::string buffer; quiche::ReadStream::PeekResult peek_result = reply->PeekNextReadableRegion(); EXPECT_EQ(peek_result.peeked_data, "Stream Two"); EXPECT_EQ(peek_result.fin_next, false); EXPECT_EQ(peek_result.all_data_received, true); bool fin_received = quiche::ProcessAllReadableRegions(*reply, [&](absl::string_view chunk) { buffer.append(chunk.data(), chunk.size()); return true; }); EXPECT_TRUE(fin_received); EXPECT_EQ(buffer, "Stream Two"); ASSERT_TRUE(test_harness_.RunUntilWithDefaultTimeout( [&]() { return stream1->PeekNextReadableRegion().has_data(); })); peek_result = stream1->PeekNextReadableRegion(); EXPECT_EQ(peek_result.peeked_data, "Stream One"); EXPECT_EQ(peek_result.fin_next, false); EXPECT_EQ(peek_result.all_data_received, false); fin_received = stream1->SkipBytes(strlen("Stream One")); EXPECT_FALSE(fin_received); peek_result = stream1->PeekNextReadableRegion(); EXPECT_EQ(peek_result.peeked_data, ""); EXPECT_EQ(peek_result.fin_next, false); EXPECT_EQ(peek_result.all_data_received, false); EXPECT_TRUE(stream1->SendFin()); ASSERT_TRUE(test_harness_.RunUntilWithDefaultTimeout( [&]() { return stream1->PeekNextReadableRegion().all_data_received; })); peek_result = stream1->PeekNextReadableRegion(); EXPECT_EQ(peek_result.peeked_data, ""); EXPECT_EQ(peek_result.fin_next, true); EXPECT_EQ(peek_result.all_data_received, true); webtransport::StreamId id = stream1->GetStreamId(); EXPECT_TRUE(client_->session()->GetStreamById(id) != nullptr); fin_received = stream1->SkipBytes(0); EXPECT_TRUE(fin_received); EXPECT_TRUE(client_->session()->GetStreamById(id) == nullptr); } TEST_F(QuicGenericSessionTest, EchoDatagram) { CreateDefaultEndpoints(kEchoServer); WireUpEndpoints(); RunHandshake(); client_->session()->SendOrQueueDatagram("test"); bool datagram_received = false; EXPECT_CALL(*client_->visitor(), OnDatagramReceived(Eq("test"))) .WillOnce(Assign(&datagram_received, true)); ASSERT_TRUE(test_harness_.RunUntilWithDefaultTimeout( [&datagram_received]() { return datagram_received; })); } TEST_F(QuicGenericSessionTest, EchoALotOfDatagrams) { CreateDefaultEndpoints(kEchoServer); WireUpEndpoints(); RunHandshake(); client_->session()->SetDatagramMaxTimeInQueue( (10000 * simulator::TestHarness::kRtt).ToAbsl()); for (int i = 0; i < 1000; i++) { client_->session()->SendOrQueueDatagram(std::string( client_->session()->GetGuaranteedLargestMessagePayload(), 'a')); } size_t received = 0; EXPECT_CALL(*client_->visitor(), OnDatagramReceived(_)) .WillRepeatedly( [&received](absl::string_view ) { received++; }); ASSERT_TRUE(test_harness_.simulator().RunUntilOrTimeout( [this]() { return client_->total_datagrams_processed() >= 1000; }, 3 * simulator::TestHarness::kServerBandwidth.TransferTime( 1000 * kMaxOutgoingPacketSize))); test_harness_.simulator().RunFor(2 * simulator::TestHarness::kRtt); EXPECT_GT(received, 500u); EXPECT_LT(received, 1000u); } TEST_F(QuicGenericSessionTest, OutgoingStreamFlowControlBlocked) { server_config_.SetMaxUnidirectionalStreamsToSend(4); CreateDefaultEndpoints(kDiscardServer); WireUpEndpoints(); RunHandshake(); webtransport::Stream* stream; for (int i = 0; i <= 3; i++) { ASSERT_TRUE(client_->session()->CanOpenNextOutgoingUnidirectionalStream()); stream = client_->session()->OpenOutgoingUnidirectionalStream(); ASSERT_TRUE(stream != nullptr); ASSERT_TRUE(stream->SendFin()); } EXPECT_FALSE(client_->session()->CanOpenNextOutgoingUnidirectionalStream()); bool can_create_new_stream = false; EXPECT_CALL(*client_->visitor(), OnCanCreateNewOutgoingUnidirectionalStream()) .WillOnce(Assign(&can_create_new_stream, true)); ASSERT_TRUE(test_harness_.RunUntilWithDefaultTimeout( [&can_create_new_stream]() { return can_create_new_stream; })); EXPECT_TRUE(client_->session()->CanOpenNextOutgoingUnidirectionalStream()); } TEST_F(QuicGenericSessionTest, ExpireDatagrams) { CreateDefaultEndpoints(kEchoServer); WireUpEndpoints(); RunHandshake(); client_->session()->SetDatagramMaxTimeInQueue( (0.2 * simulator::TestHarness::kRtt).ToAbsl()); for (int i = 0; i < 1000; i++) { client_->session()->SendOrQueueDatagram(std::string( client_->session()->GetGuaranteedLargestMessagePayload(), 'a')); } size_t received = 0; EXPECT_CALL(*client_->visitor(), OnDatagramReceived(_)) .WillRepeatedly( [&received](absl::string_view ) { received++; }); ASSERT_TRUE(test_harness_.simulator().RunUntilOrTimeout( [this]() { return client_->total_datagrams_processed() >= 1000; }, 3 * simulator::TestHarness::kServerBandwidth.TransferTime( 1000 * kMaxOutgoingPacketSize))); test_harness_.simulator().RunFor(2 * simulator::TestHarness::kRtt); EXPECT_LT(received, 500); EXPECT_EQ(received + client_->session()->GetDatagramStats().expired_outgoing, 1000); } TEST_F(QuicGenericSessionTest, LoseDatagrams) { CreateDefaultEndpoints(kEchoServer); test_harness_.WireUpEndpointsWithLoss(4); RunHandshake(); client_->session()->SetDatagramMaxTimeInQueue( (10000 * simulator::TestHarness::kRtt).ToAbsl()); for (int i = 0; i < 1000; i++) { client_->session()->SendOrQueueDatagram(std::string( client_->session()->GetGuaranteedLargestMessagePayload(), 'a')); } size_t received = 0; EXPECT_CALL(*client_->visitor(), OnDatagramReceived(_)) .WillRepeatedly( [&received](absl::string_view ) { received++; }); ASSERT_TRUE(test_harness_.simulator().RunUntilOrTimeout( [this]() { return client_->total_datagrams_processed() >= 1000; }, 4 * simulator::TestHarness::kServerBandwidth.TransferTime( 1000 * kMaxOutgoingPacketSize))); test_harness_.simulator().RunFor(16 * simulator::TestHarness::kRtt); QuicPacketCount client_lost = client_->session()->GetDatagramStats().lost_outgoing; QuicPacketCount server_lost = server_->session()->GetDatagramStats().lost_outgoing; EXPECT_LT(received, 800u); EXPECT_GT(client_lost, 100u); EXPECT_GT(server_lost, 100u); EXPECT_EQ(received + client_lost + server_lost, 1000u); } TEST_F(QuicGenericSessionTest, WriteWhenBufferFull) { CreateDefaultEndpoints(kEchoServer); WireUpEndpoints(); RunHandshake(); const std::string buffer(64 * 1024 + 1, 'q'); webtransport::Stream* stream = client_->session()->OpenOutgoingBidirectionalStream(); ASSERT_TRUE(stream != nullptr); ASSERT_TRUE(stream->CanWrite()); absl::Status status = quiche::WriteIntoStream(*stream, buffer); QUICHE_EXPECT_OK(status); EXPECT_FALSE(stream->CanWrite()); status = quiche::WriteIntoStream(*stream, buffer); EXPECT_THAT(status, StatusIs(absl::StatusCode::kUnavailable)); quiche::StreamWriteOptions options; options.set_buffer_unconditionally(true); options.set_send_fin(true); status = quiche::WriteIntoStream(*stream, buffer, options); QUICHE_EXPECT_OK(status); EXPECT_FALSE(stream->CanWrite()); QuicByteCount total_received = 0; for (;;) { test_harness_.RunUntilWithDefaultTimeout( [&] { return stream->PeekNextReadableRegion().has_data(); }); quiche::ReadStream::PeekResult result = stream->PeekNextReadableRegion(); total_received += result.peeked_data.size(); bool fin_consumed = stream->SkipBytes(result.peeked_data.size()); if (fin_consumed) { break; } } EXPECT_EQ(total_received, 128u * 1024u + 2); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_generic_session.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_generic_session_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
2635ad77-cef5-4bfd-a7c1-071b30efa586
cpp
google/quiche
quic_utils
quiche/quic/core/quic_utils.cc
quiche/quic/core/quic_utils_test.cc
#include "quiche/quic/core/quic_utils.h" #include <algorithm> #include <cstdint> #include <cstring> #include <limits> #include <string> #include "absl/base/macros.h" #include "absl/base/optimization.h" #include "absl/numeric/int128.h" #include "absl/strings/string_view.h" #include "openssl/sha.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_types.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_flags.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_mem_slice.h" #include "quiche/common/quiche_endian.h" namespace quic { namespace { #if defined(__x86_64__) && \ ((defined(__GNUC__) && \ (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))) || \ defined(__clang__)) #define QUIC_UTIL_HAS_UINT128 1 #endif #ifdef QUIC_UTIL_HAS_UINT128 absl::uint128 IncrementalHashFast(absl::uint128 uhash, absl::string_view data) { static const absl::uint128 kPrime = (static_cast<absl::uint128>(16777216) << 64) + 315; auto hi = absl::Uint128High64(uhash); auto lo = absl::Uint128Low64(uhash); absl::uint128 xhash = (static_cast<absl::uint128>(hi) << 64) + lo; const uint8_t* octets = reinterpret_cast<const uint8_t*>(data.data()); for (size_t i = 0; i < data.length(); ++i) { xhash = (xhash ^ static_cast<uint32_t>(octets[i])) * kPrime; } return absl::MakeUint128(absl::Uint128High64(xhash), absl::Uint128Low64(xhash)); } #endif #ifndef QUIC_UTIL_HAS_UINT128 absl::uint128 IncrementalHashSlow(absl::uint128 hash, absl::string_view data) { static const absl::uint128 kPrime = absl::MakeUint128(16777216, 315); const uint8_t* octets = reinterpret_cast<const uint8_t*>(data.data()); for (size_t i = 0; i < data.length(); ++i) { hash = hash ^ absl::MakeUint128(0, octets[i]); hash = hash * kPrime; } return hash; } #endif absl::uint128 IncrementalHash(absl::uint128 hash, absl::string_view data) { #ifdef QUIC_UTIL_HAS_UINT128 return IncrementalHashFast(hash, data); #else return IncrementalHashSlow(hash, data); #endif } } uint64_t QuicUtils::FNV1a_64_Hash(absl::string_view data) { static const uint64_t kOffset = UINT64_C(14695981039346656037); static const uint64_t kPrime = UINT64_C(1099511628211); const uint8_t* octets = reinterpret_cast<const uint8_t*>(data.data()); uint64_t hash = kOffset; for (size_t i = 0; i < data.length(); ++i) { hash = hash ^ octets[i]; hash = hash * kPrime; } return hash; } absl::uint128 QuicUtils::FNV1a_128_Hash(absl::string_view data) { return FNV1a_128_Hash_Three(data, absl::string_view(), absl::string_view()); } absl::uint128 QuicUtils::FNV1a_128_Hash_Two(absl::string_view data1, absl::string_view data2) { return FNV1a_128_Hash_Three(data1, data2, absl::string_view()); } absl::uint128 QuicUtils::FNV1a_128_Hash_Three(absl::string_view data1, absl::string_view data2, absl::string_view data3) { const absl::uint128 kOffset = absl::MakeUint128( UINT64_C(7809847782465536322), UINT64_C(7113472399480571277)); absl::uint128 hash = IncrementalHash(kOffset, data1); if (data2.empty()) { return hash; } hash = IncrementalHash(hash, data2); if (data3.empty()) { return hash; } return IncrementalHash(hash, data3); } void QuicUtils::SerializeUint128Short(absl::uint128 v, uint8_t* out) { const uint64_t lo = absl::Uint128Low64(v); const uint64_t hi = absl::Uint128High64(v); memcpy(out, &lo, sizeof(lo)); memcpy(out + sizeof(lo), &hi, sizeof(hi) / 2); } #define RETURN_STRING_LITERAL(x) \ case x: \ return #x; std::string QuicUtils::AddressChangeTypeToString(AddressChangeType type) { switch (type) { RETURN_STRING_LITERAL(NO_CHANGE); RETURN_STRING_LITERAL(PORT_CHANGE); RETURN_STRING_LITERAL(IPV4_SUBNET_CHANGE); RETURN_STRING_LITERAL(IPV4_TO_IPV6_CHANGE); RETURN_STRING_LITERAL(IPV6_TO_IPV4_CHANGE); RETURN_STRING_LITERAL(IPV6_TO_IPV6_CHANGE); RETURN_STRING_LITERAL(IPV4_TO_IPV4_CHANGE); } return "INVALID_ADDRESS_CHANGE_TYPE"; } const char* QuicUtils::SentPacketStateToString(SentPacketState state) { switch (state) { RETURN_STRING_LITERAL(OUTSTANDING); RETURN_STRING_LITERAL(NEVER_SENT); RETURN_STRING_LITERAL(ACKED); RETURN_STRING_LITERAL(UNACKABLE); RETURN_STRING_LITERAL(NEUTERED); RETURN_STRING_LITERAL(HANDSHAKE_RETRANSMITTED); RETURN_STRING_LITERAL(LOST); RETURN_STRING_LITERAL(PTO_RETRANSMITTED); RETURN_STRING_LITERAL(NOT_CONTRIBUTING_RTT); } return "INVALID_SENT_PACKET_STATE"; } const char* QuicUtils::QuicLongHeaderTypetoString(QuicLongHeaderType type) { switch (type) { RETURN_STRING_LITERAL(VERSION_NEGOTIATION); RETURN_STRING_LITERAL(INITIAL); RETURN_STRING_LITERAL(RETRY); RETURN_STRING_LITERAL(HANDSHAKE); RETURN_STRING_LITERAL(ZERO_RTT_PROTECTED); default: return "INVALID_PACKET_TYPE"; } } const char* QuicUtils::AckResultToString(AckResult result) { switch (result) { RETURN_STRING_LITERAL(PACKETS_NEWLY_ACKED); RETURN_STRING_LITERAL(NO_PACKETS_NEWLY_ACKED); RETURN_STRING_LITERAL(UNSENT_PACKETS_ACKED); RETURN_STRING_LITERAL(UNACKABLE_PACKETS_ACKED); RETURN_STRING_LITERAL(PACKETS_ACKED_IN_WRONG_PACKET_NUMBER_SPACE); } return "INVALID_ACK_RESULT"; } AddressChangeType QuicUtils::DetermineAddressChangeType( const QuicSocketAddress& old_address, const QuicSocketAddress& new_address) { if (!old_address.IsInitialized() || !new_address.IsInitialized() || old_address == new_address) { return NO_CHANGE; } if (old_address.host() == new_address.host()) { return PORT_CHANGE; } bool old_ip_is_ipv4 = old_address.host().IsIPv4() ? true : false; bool migrating_ip_is_ipv4 = new_address.host().IsIPv4() ? true : false; if (old_ip_is_ipv4 && !migrating_ip_is_ipv4) { return IPV4_TO_IPV6_CHANGE; } if (!old_ip_is_ipv4) { return migrating_ip_is_ipv4 ? IPV6_TO_IPV4_CHANGE : IPV6_TO_IPV6_CHANGE; } const int kSubnetMaskLength = 24; if (old_address.host().InSameSubnet(new_address.host(), kSubnetMaskLength)) { return IPV4_SUBNET_CHANGE; } return IPV4_TO_IPV4_CHANGE; } bool QuicUtils::IsAckable(SentPacketState state) { return state != NEVER_SENT && state != ACKED && state != UNACKABLE; } bool QuicUtils::IsRetransmittableFrame(QuicFrameType type) { switch (type) { case ACK_FRAME: case PADDING_FRAME: case STOP_WAITING_FRAME: case MTU_DISCOVERY_FRAME: case PATH_CHALLENGE_FRAME: case PATH_RESPONSE_FRAME: return false; default: return true; } } bool QuicUtils::IsHandshakeFrame(const QuicFrame& frame, QuicTransportVersion transport_version) { if (!QuicVersionUsesCryptoFrames(transport_version)) { return frame.type == STREAM_FRAME && frame.stream_frame.stream_id == GetCryptoStreamId(transport_version); } else { return frame.type == CRYPTO_FRAME; } } bool QuicUtils::ContainsFrameType(const QuicFrames& frames, QuicFrameType type) { for (const QuicFrame& frame : frames) { if (frame.type == type) { return true; } } return false; } SentPacketState QuicUtils::RetransmissionTypeToPacketState( TransmissionType retransmission_type) { switch (retransmission_type) { case ALL_ZERO_RTT_RETRANSMISSION: return UNACKABLE; case HANDSHAKE_RETRANSMISSION: return HANDSHAKE_RETRANSMITTED; case LOSS_RETRANSMISSION: return LOST; case PTO_RETRANSMISSION: return PTO_RETRANSMITTED; case PATH_RETRANSMISSION: return NOT_CONTRIBUTING_RTT; case ALL_INITIAL_RETRANSMISSION: return UNACKABLE; default: QUIC_BUG(quic_bug_10839_2) << retransmission_type << " is not a retransmission_type"; return UNACKABLE; } } bool QuicUtils::IsIetfPacketHeader(uint8_t first_byte) { return (first_byte & FLAGS_LONG_HEADER) || (first_byte & FLAGS_FIXED_BIT) || !(first_byte & FLAGS_DEMULTIPLEXING_BIT); } bool QuicUtils::IsIetfPacketShortHeader(uint8_t first_byte) { return IsIetfPacketHeader(first_byte) && !(first_byte & FLAGS_LONG_HEADER); } QuicStreamId QuicUtils::GetInvalidStreamId(QuicTransportVersion version) { return VersionHasIetfQuicFrames(version) ? std::numeric_limits<QuicStreamId>::max() : 0; } QuicStreamId QuicUtils::GetCryptoStreamId(QuicTransportVersion version) { QUIC_BUG_IF(quic_bug_12982_1, QuicVersionUsesCryptoFrames(version)) << "CRYPTO data aren't in stream frames; they have no stream ID."; return QuicVersionUsesCryptoFrames(version) ? GetInvalidStreamId(version) : 1; } bool QuicUtils::IsCryptoStreamId(QuicTransportVersion version, QuicStreamId stream_id) { if (QuicVersionUsesCryptoFrames(version)) { return false; } return stream_id == GetCryptoStreamId(version); } QuicStreamId QuicUtils::GetHeadersStreamId(QuicTransportVersion version) { QUICHE_DCHECK(!VersionUsesHttp3(version)); return GetFirstBidirectionalStreamId(version, Perspective::IS_CLIENT); } bool QuicUtils::IsClientInitiatedStreamId(QuicTransportVersion version, QuicStreamId id) { if (id == GetInvalidStreamId(version)) { return false; } return VersionHasIetfQuicFrames(version) ? id % 2 == 0 : id % 2 != 0; } bool QuicUtils::IsServerInitiatedStreamId(QuicTransportVersion version, QuicStreamId id) { if (id == GetInvalidStreamId(version)) { return false; } return VersionHasIetfQuicFrames(version) ? id % 2 != 0 : id % 2 == 0; } bool QuicUtils::IsOutgoingStreamId(ParsedQuicVersion version, QuicStreamId id, Perspective perspective) { const bool perspective_is_server = perspective == Perspective::IS_SERVER; const bool stream_is_server = QuicUtils::IsServerInitiatedStreamId(version.transport_version, id); return perspective_is_server == stream_is_server; } bool QuicUtils::IsBidirectionalStreamId(QuicStreamId id, ParsedQuicVersion version) { QUICHE_DCHECK(version.HasIetfQuicFrames()); return id % 4 < 2; } StreamType QuicUtils::GetStreamType(QuicStreamId id, Perspective perspective, bool peer_initiated, ParsedQuicVersion version) { QUICHE_DCHECK(version.HasIetfQuicFrames()); if (IsBidirectionalStreamId(id, version)) { return BIDIRECTIONAL; } if (peer_initiated) { if (perspective == Perspective::IS_SERVER) { QUICHE_DCHECK_EQ(2u, id % 4); } else { QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, perspective); QUICHE_DCHECK_EQ(3u, id % 4); } return READ_UNIDIRECTIONAL; } if (perspective == Perspective::IS_SERVER) { QUICHE_DCHECK_EQ(3u, id % 4); } else { QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, perspective); QUICHE_DCHECK_EQ(2u, id % 4); } return WRITE_UNIDIRECTIONAL; } QuicStreamId QuicUtils::StreamIdDelta(QuicTransportVersion version) { return VersionHasIetfQuicFrames(version) ? 4 : 2; } QuicStreamId QuicUtils::GetFirstBidirectionalStreamId( QuicTransportVersion version, Perspective perspective) { if (VersionHasIetfQuicFrames(version)) { return perspective == Perspective::IS_CLIENT ? 0 : 1; } else if (QuicVersionUsesCryptoFrames(version)) { return perspective == Perspective::IS_CLIENT ? 1 : 2; } return perspective == Perspective::IS_CLIENT ? 3 : 2; } QuicStreamId QuicUtils::GetFirstUnidirectionalStreamId( QuicTransportVersion version, Perspective perspective) { if (VersionHasIetfQuicFrames(version)) { return perspective == Perspective::IS_CLIENT ? 2 : 3; } else if (QuicVersionUsesCryptoFrames(version)) { return perspective == Perspective::IS_CLIENT ? 1 : 2; } return perspective == Perspective::IS_CLIENT ? 3 : 2; } QuicStreamId QuicUtils::GetMaxClientInitiatedBidirectionalStreamId( QuicTransportVersion version) { if (VersionHasIetfQuicFrames(version)) { return std::numeric_limits<QuicStreamId>::max() - 3; } return std::numeric_limits<QuicStreamId>::max(); } QuicConnectionId QuicUtils::CreateRandomConnectionId() { return CreateRandomConnectionId(kQuicDefaultConnectionIdLength, QuicRandom::GetInstance()); } QuicConnectionId QuicUtils::CreateRandomConnectionId(QuicRandom* random) { return CreateRandomConnectionId(kQuicDefaultConnectionIdLength, random); } QuicConnectionId QuicUtils::CreateRandomConnectionId( uint8_t connection_id_length) { return CreateRandomConnectionId(connection_id_length, QuicRandom::GetInstance()); } QuicConnectionId QuicUtils::CreateRandomConnectionId( uint8_t connection_id_length, QuicRandom* random) { QuicConnectionId connection_id; connection_id.set_length(connection_id_length); if (connection_id.length() > 0) { random->RandBytes(connection_id.mutable_data(), connection_id.length()); } return connection_id; } QuicConnectionId QuicUtils::CreateZeroConnectionId( QuicTransportVersion version) { if (!VersionAllowsVariableLengthConnectionIds(version)) { char connection_id_bytes[8] = {0, 0, 0, 0, 0, 0, 0, 0}; return QuicConnectionId(static_cast<char*>(connection_id_bytes), ABSL_ARRAYSIZE(connection_id_bytes)); } return EmptyQuicConnectionId(); } bool QuicUtils::IsConnectionIdLengthValidForVersion( size_t connection_id_length, QuicTransportVersion transport_version) { if (connection_id_length > static_cast<size_t>(std::numeric_limits<uint8_t>::max())) { return false; } if (transport_version == QUIC_VERSION_UNSUPPORTED || transport_version == QUIC_VERSION_RESERVED_FOR_NEGOTIATION) { return true; } const uint8_t connection_id_length8 = static_cast<uint8_t>(connection_id_length); if (!VersionAllowsVariableLengthConnectionIds(transport_version)) { return connection_id_length8 == kQuicDefaultConnectionIdLength; } return connection_id_length8 <= kQuicMaxConnectionIdWithLengthPrefixLength; } bool QuicUtils::IsConnectionIdValidForVersion( QuicConnectionId connection_id, QuicTransportVersion transport_version) { return IsConnectionIdLengthValidForVersion(connection_id.length(), transport_version); } StatelessResetToken QuicUtils::GenerateStatelessResetToken( QuicConnectionId connection_id) { static_assert(sizeof(absl::uint128) == sizeof(StatelessResetToken), "bad size"); static_assert(alignof(absl::uint128) >= alignof(StatelessResetToken), "bad alignment"); absl::uint128 hash = FNV1a_128_Hash( absl::string_view(connection_id.data(), connection_id.length())); return *reinterpret_cast<StatelessResetToken*>(&hash); } QuicStreamCount QuicUtils::GetMaxStreamCount() { return (kMaxQuicStreamCount >> 2) + 1; } PacketNumberSpace QuicUtils::GetPacketNumberSpace( EncryptionLevel encryption_level) { switch (encryption_level) { case ENCRYPTION_INITIAL: return INITIAL_DATA; case ENCRYPTION_HANDSHAKE: return HANDSHAKE_DATA; case ENCRYPTION_ZERO_RTT: case ENCRYPTION_FORWARD_SECURE: return APPLICATION_DATA; default: QUIC_BUG(quic_bug_10839_3) << "Try to get packet number space of encryption level: " << encryption_level; return NUM_PACKET_NUMBER_SPACES; } } EncryptionLevel QuicUtils::GetEncryptionLevelToSendAckofSpace( PacketNumberSpace packet_number_space) { switch (packet_number_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 QuicUtils::IsProbingFrame(QuicFrameType type) { switch (type) { case PATH_CHALLENGE_FRAME: case PATH_RESPONSE_FRAME: case NEW_CONNECTION_ID_FRAME: case PADDING_FRAME: return true; default: return false; } } bool QuicUtils::IsAckElicitingFrame(QuicFrameType type) { switch (type) { case PADDING_FRAME: case STOP_WAITING_FRAME: case ACK_FRAME: case CONNECTION_CLOSE_FRAME: return false; default: return true; } } bool QuicUtils::AreStatelessResetTokensEqual( const StatelessResetToken& token1, const StatelessResetToken& token2) { char byte = 0; for (size_t i = 0; i < kStatelessResetTokenLength; i++) { byte |= (token1[i] ^ token2[i]); } return byte == 0; } bool IsValidWebTransportSessionId(WebTransportSessionId id, ParsedQuicVersion version) { QUICHE_DCHECK(version.UsesHttp3()); return (id <= std::numeric_limits<QuicStreamId>::max()) && QuicUtils::IsBidirectionalStreamId(id, version) && QuicUtils::IsClientInitiatedStreamId(version.transport_version, id); } QuicByteCount MemSliceSpanTotalSize(absl::Span<quiche::QuicheMemSlice> span) { QuicByteCount total = 0; for (const quiche::QuicheMemSlice& slice : span) { total += slice.length(); } return total; } absl::string_view PosixBasename(absl::string_view path) { constexpr char kPathSeparator = '/'; size_t pos = path.find_last_of(kPathSeparator); if (pos == absl::string_view::npos) { return path; } if (pos == 0) { return absl::ClippedSubstr(path, 1); } return absl::ClippedSubstr(path, pos + 1); } std::string RawSha256(absl::string_view input) { std::string raw_hash; raw_hash.resize(SHA256_DIGEST_LENGTH); SHA256(reinterpret_cast<const uint8_t*>(input.data()), input.size(), reinterpret_cast<uint8_t*>(&raw_hash[0])); return raw_hash; } #undef RETURN_STRING_LITERAL }
#include "quiche/quic/core/quic_utils.h" #include <string> #include <vector> #include "absl/base/macros.h" #include "absl/numeric/int128.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/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { namespace test { namespace { class QuicUtilsTest : public QuicTest {}; TEST_F(QuicUtilsTest, DetermineAddressChangeType) { const std::string kIPv4String1 = "1.2.3.4"; const std::string kIPv4String2 = "1.2.3.5"; const std::string kIPv4String3 = "1.1.3.5"; const std::string kIPv6String1 = "2001:700:300:1800::f"; const std::string kIPv6String2 = "2001:700:300:1800:1:1:1:f"; QuicSocketAddress old_address; QuicSocketAddress new_address; QuicIpAddress address; EXPECT_EQ(NO_CHANGE, QuicUtils::DetermineAddressChangeType(old_address, new_address)); ASSERT_TRUE(address.FromString(kIPv4String1)); old_address = QuicSocketAddress(address, 1234); EXPECT_EQ(NO_CHANGE, QuicUtils::DetermineAddressChangeType(old_address, new_address)); new_address = QuicSocketAddress(address, 1234); EXPECT_EQ(NO_CHANGE, QuicUtils::DetermineAddressChangeType(old_address, new_address)); new_address = QuicSocketAddress(address, 5678); EXPECT_EQ(PORT_CHANGE, QuicUtils::DetermineAddressChangeType(old_address, new_address)); ASSERT_TRUE(address.FromString(kIPv6String1)); old_address = QuicSocketAddress(address, 1234); new_address = QuicSocketAddress(address, 5678); EXPECT_EQ(PORT_CHANGE, QuicUtils::DetermineAddressChangeType(old_address, new_address)); ASSERT_TRUE(address.FromString(kIPv4String1)); old_address = QuicSocketAddress(address, 1234); ASSERT_TRUE(address.FromString(kIPv6String1)); new_address = QuicSocketAddress(address, 1234); EXPECT_EQ(IPV4_TO_IPV6_CHANGE, QuicUtils::DetermineAddressChangeType(old_address, new_address)); old_address = QuicSocketAddress(address, 1234); ASSERT_TRUE(address.FromString(kIPv4String1)); new_address = QuicSocketAddress(address, 1234); EXPECT_EQ(IPV6_TO_IPV4_CHANGE, QuicUtils::DetermineAddressChangeType(old_address, new_address)); ASSERT_TRUE(address.FromString(kIPv6String2)); new_address = QuicSocketAddress(address, 1234); EXPECT_EQ(IPV6_TO_IPV6_CHANGE, QuicUtils::DetermineAddressChangeType(old_address, new_address)); ASSERT_TRUE(address.FromString(kIPv4String1)); old_address = QuicSocketAddress(address, 1234); ASSERT_TRUE(address.FromString(kIPv4String2)); new_address = QuicSocketAddress(address, 1234); EXPECT_EQ(IPV4_SUBNET_CHANGE, QuicUtils::DetermineAddressChangeType(old_address, new_address)); ASSERT_TRUE(address.FromString(kIPv4String3)); new_address = QuicSocketAddress(address, 1234); EXPECT_EQ(IPV4_TO_IPV4_CHANGE, QuicUtils::DetermineAddressChangeType(old_address, new_address)); } absl::uint128 IncrementalHashReference(const void* data, size_t len) { absl::uint128 hash = absl::MakeUint128(UINT64_C(7809847782465536322), UINT64_C(7113472399480571277)); const absl::uint128 kPrime = absl::MakeUint128(16777216, 315); const uint8_t* octets = reinterpret_cast<const uint8_t*>(data); for (size_t i = 0; i < len; ++i) { hash = hash ^ absl::MakeUint128(0, octets[i]); hash = hash * kPrime; } return hash; } TEST_F(QuicUtilsTest, ReferenceTest) { std::vector<uint8_t> data(32); for (size_t i = 0; i < data.size(); ++i) { data[i] = i % 255; } EXPECT_EQ(IncrementalHashReference(data.data(), data.size()), QuicUtils::FNV1a_128_Hash(absl::string_view( reinterpret_cast<const char*>(data.data()), data.size()))); } TEST_F(QuicUtilsTest, IsUnackable) { for (size_t i = FIRST_PACKET_STATE; i <= LAST_PACKET_STATE; ++i) { if (i == NEVER_SENT || i == ACKED || i == UNACKABLE) { EXPECT_FALSE(QuicUtils::IsAckable(static_cast<SentPacketState>(i))); } else { EXPECT_TRUE(QuicUtils::IsAckable(static_cast<SentPacketState>(i))); } } } TEST_F(QuicUtilsTest, RetransmissionTypeToPacketState) { for (size_t i = FIRST_TRANSMISSION_TYPE; i <= LAST_TRANSMISSION_TYPE; ++i) { if (i == NOT_RETRANSMISSION) { continue; } SentPacketState state = QuicUtils::RetransmissionTypeToPacketState( static_cast<TransmissionType>(i)); if (i == HANDSHAKE_RETRANSMISSION) { EXPECT_EQ(HANDSHAKE_RETRANSMITTED, state); } else if (i == LOSS_RETRANSMISSION) { EXPECT_EQ(LOST, state); } else if (i == ALL_ZERO_RTT_RETRANSMISSION) { EXPECT_EQ(UNACKABLE, state); } else if (i == PTO_RETRANSMISSION) { EXPECT_EQ(PTO_RETRANSMITTED, state); } else if (i == PATH_RETRANSMISSION) { EXPECT_EQ(NOT_CONTRIBUTING_RTT, state); } else if (i == ALL_INITIAL_RETRANSMISSION) { EXPECT_EQ(UNACKABLE, state); } else { QUICHE_DCHECK(false) << "No corresponding packet state according to transmission type: " << i; } } } TEST_F(QuicUtilsTest, IsIetfPacketHeader) { uint8_t first_byte = 0; EXPECT_TRUE(QuicUtils::IsIetfPacketHeader(first_byte)); EXPECT_TRUE(QuicUtils::IsIetfPacketShortHeader(first_byte)); first_byte |= (FLAGS_LONG_HEADER | FLAGS_DEMULTIPLEXING_BIT); EXPECT_TRUE(QuicUtils::IsIetfPacketHeader(first_byte)); EXPECT_FALSE(QuicUtils::IsIetfPacketShortHeader(first_byte)); first_byte = 0; first_byte |= FLAGS_LONG_HEADER; EXPECT_TRUE(QuicUtils::IsIetfPacketHeader(first_byte)); EXPECT_FALSE(QuicUtils::IsIetfPacketShortHeader(first_byte)); first_byte = 0; first_byte |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID; EXPECT_FALSE(QuicUtils::IsIetfPacketHeader(first_byte)); EXPECT_FALSE(QuicUtils::IsIetfPacketShortHeader(first_byte)); } TEST_F(QuicUtilsTest, RandomConnectionId) { MockRandom random(33); QuicConnectionId connection_id = QuicUtils::CreateRandomConnectionId(&random); EXPECT_EQ(connection_id.length(), sizeof(uint64_t)); char connection_id_bytes[sizeof(uint64_t)]; random.RandBytes(connection_id_bytes, ABSL_ARRAYSIZE(connection_id_bytes)); EXPECT_EQ(connection_id, QuicConnectionId(static_cast<char*>(connection_id_bytes), ABSL_ARRAYSIZE(connection_id_bytes))); EXPECT_NE(connection_id, EmptyQuicConnectionId()); EXPECT_NE(connection_id, TestConnectionId()); EXPECT_NE(connection_id, TestConnectionId(1)); EXPECT_NE(connection_id, TestConnectionIdNineBytesLong(1)); EXPECT_EQ(QuicUtils::CreateRandomConnectionId().length(), kQuicDefaultConnectionIdLength); } TEST_F(QuicUtilsTest, RandomConnectionIdVariableLength) { MockRandom random(1337); const uint8_t connection_id_length = 9; QuicConnectionId connection_id = QuicUtils::CreateRandomConnectionId(connection_id_length, &random); EXPECT_EQ(connection_id.length(), connection_id_length); char connection_id_bytes[connection_id_length]; random.RandBytes(connection_id_bytes, ABSL_ARRAYSIZE(connection_id_bytes)); EXPECT_EQ(connection_id, QuicConnectionId(static_cast<char*>(connection_id_bytes), ABSL_ARRAYSIZE(connection_id_bytes))); EXPECT_NE(connection_id, EmptyQuicConnectionId()); EXPECT_NE(connection_id, TestConnectionId()); EXPECT_NE(connection_id, TestConnectionId(1)); EXPECT_NE(connection_id, TestConnectionIdNineBytesLong(1)); EXPECT_EQ(QuicUtils::CreateRandomConnectionId(connection_id_length).length(), connection_id_length); } TEST_F(QuicUtilsTest, VariableLengthConnectionId) { EXPECT_FALSE(VersionAllowsVariableLengthConnectionIds(QUIC_VERSION_46)); EXPECT_TRUE(QuicUtils::IsConnectionIdValidForVersion( QuicUtils::CreateZeroConnectionId(QUIC_VERSION_46), QUIC_VERSION_46)); EXPECT_NE(QuicUtils::CreateZeroConnectionId(QUIC_VERSION_46), EmptyQuicConnectionId()); EXPECT_FALSE(QuicUtils::IsConnectionIdValidForVersion(EmptyQuicConnectionId(), QUIC_VERSION_46)); } TEST_F(QuicUtilsTest, StatelessResetToken) { QuicConnectionId connection_id1a = test::TestConnectionId(1); QuicConnectionId connection_id1b = test::TestConnectionId(1); QuicConnectionId connection_id2 = test::TestConnectionId(2); StatelessResetToken token1a = QuicUtils::GenerateStatelessResetToken(connection_id1a); StatelessResetToken token1b = QuicUtils::GenerateStatelessResetToken(connection_id1b); StatelessResetToken token2 = QuicUtils::GenerateStatelessResetToken(connection_id2); EXPECT_EQ(token1a, token1b); EXPECT_NE(token1a, token2); EXPECT_TRUE(QuicUtils::AreStatelessResetTokensEqual(token1a, token1b)); EXPECT_FALSE(QuicUtils::AreStatelessResetTokensEqual(token1a, token2)); } TEST_F(QuicUtilsTest, EcnCodepointToString) { EXPECT_EQ(EcnCodepointToString(ECN_NOT_ECT), "Not-ECT"); EXPECT_EQ(EcnCodepointToString(ECN_ECT0), "ECT(0)"); EXPECT_EQ(EcnCodepointToString(ECN_ECT1), "ECT(1)"); EXPECT_EQ(EcnCodepointToString(ECN_CE), "CE"); } TEST_F(QuicUtilsTest, PosixBasename) { EXPECT_EQ("", PosixBasename("/hello/")); EXPECT_EQ("hello", PosixBasename("/hello")); EXPECT_EQ("world", PosixBasename("hello/world")); EXPECT_EQ("", PosixBasename("hello/")); EXPECT_EQ("world", PosixBasename("world")); EXPECT_EQ("", PosixBasename("/")); EXPECT_EQ("", PosixBasename("")); EXPECT_EQ("C:\\hello", PosixBasename("C:\\hello")); EXPECT_EQ("world", PosixBasename("C:\\hello/world")); } enum class TestEnumClassBit : uint8_t { BIT_ZERO = 0, BIT_ONE, BIT_TWO, }; enum TestEnumBit { TEST_BIT_0 = 0, TEST_BIT_1, TEST_BIT_2, }; TEST(QuicBitMaskTest, EnumClass) { BitMask<TestEnumClassBit> mask( {TestEnumClassBit::BIT_ZERO, TestEnumClassBit::BIT_TWO}); EXPECT_TRUE(mask.IsSet(TestEnumClassBit::BIT_ZERO)); EXPECT_FALSE(mask.IsSet(TestEnumClassBit::BIT_ONE)); EXPECT_TRUE(mask.IsSet(TestEnumClassBit::BIT_TWO)); mask.ClearAll(); EXPECT_FALSE(mask.IsSet(TestEnumClassBit::BIT_ZERO)); EXPECT_FALSE(mask.IsSet(TestEnumClassBit::BIT_ONE)); EXPECT_FALSE(mask.IsSet(TestEnumClassBit::BIT_TWO)); } TEST(QuicBitMaskTest, Enum) { BitMask<TestEnumBit> mask({TEST_BIT_1, TEST_BIT_2}); EXPECT_FALSE(mask.IsSet(TEST_BIT_0)); EXPECT_TRUE(mask.IsSet(TEST_BIT_1)); EXPECT_TRUE(mask.IsSet(TEST_BIT_2)); mask.ClearAll(); EXPECT_FALSE(mask.IsSet(TEST_BIT_0)); EXPECT_FALSE(mask.IsSet(TEST_BIT_1)); EXPECT_FALSE(mask.IsSet(TEST_BIT_2)); } TEST(QuicBitMaskTest, Integer) { BitMask<int> mask({1, 3}); EXPECT_EQ(mask.Max(), 3); mask.Set(3); mask.Set({5, 7, 9}); EXPECT_EQ(mask.Max(), 9); EXPECT_FALSE(mask.IsSet(0)); EXPECT_TRUE(mask.IsSet(1)); EXPECT_FALSE(mask.IsSet(2)); EXPECT_TRUE(mask.IsSet(3)); EXPECT_FALSE(mask.IsSet(4)); EXPECT_TRUE(mask.IsSet(5)); EXPECT_FALSE(mask.IsSet(6)); EXPECT_TRUE(mask.IsSet(7)); EXPECT_FALSE(mask.IsSet(8)); EXPECT_TRUE(mask.IsSet(9)); } TEST(QuicBitMaskTest, NumBits) { EXPECT_EQ(64u, BitMask<int>::NumBits()); EXPECT_EQ(32u, (BitMask<int, uint32_t>::NumBits())); } TEST(QuicBitMaskTest, Constructor) { BitMask<int> empty_mask; for (size_t bit = 0; bit < empty_mask.NumBits(); ++bit) { EXPECT_FALSE(empty_mask.IsSet(bit)); } BitMask<int> mask({1, 3}); BitMask<int> mask2 = mask; BitMask<int> mask3(mask2); for (size_t bit = 0; bit < mask.NumBits(); ++bit) { EXPECT_EQ(mask.IsSet(bit), mask2.IsSet(bit)); EXPECT_EQ(mask.IsSet(bit), mask3.IsSet(bit)); } EXPECT_TRUE(std::is_trivially_copyable<BitMask<int>>::value); } TEST(QuicBitMaskTest, Any) { BitMask<int> mask; EXPECT_FALSE(mask.Any()); mask.Set(3); EXPECT_TRUE(mask.Any()); mask.Set(2); EXPECT_TRUE(mask.Any()); mask.ClearAll(); EXPECT_FALSE(mask.Any()); } TEST(QuicBitMaskTest, And) { using Mask = BitMask<int>; EXPECT_EQ(Mask({1, 3, 6}) & Mask({3, 5, 6}), Mask({3, 6})); EXPECT_EQ(Mask({1, 2, 4}) & Mask({3, 5}), Mask({})); EXPECT_EQ(Mask({1, 2, 3, 4, 5}) & Mask({}), Mask({})); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_utils.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_utils_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
f99744f1-007e-423e-8328-acb078b852c0
cpp
google/quiche
chlo_extractor
quiche/quic/core/chlo_extractor.cc
quiche/quic/core/chlo_extractor_test.cc
#include "quiche/quic/core/chlo_extractor.h" #include <memory> #include <optional> #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/crypto_framer.h" #include "quiche/quic/core/crypto/crypto_handshake.h" #include "quiche/quic/core/crypto/crypto_handshake_message.h" #include "quiche/quic/core/crypto/quic_decrypter.h" #include "quiche/quic/core/crypto/quic_encrypter.h" #include "quiche/quic/core/frames/quic_ack_frequency_frame.h" #include "quiche/quic/core/frames/quic_reset_stream_at_frame.h" #include "quiche/quic/core/quic_framer.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" namespace quic { namespace { class ChloFramerVisitor : public QuicFramerVisitorInterface, public CryptoFramerVisitorInterface { public: ChloFramerVisitor(QuicFramer* framer, const QuicTagVector& create_session_tag_indicators, ChloExtractor::Delegate* delegate); ~ChloFramerVisitor() override = default; void OnError(QuicFramer* ) override {} bool OnProtocolVersionMismatch(ParsedQuicVersion version) override; void OnPacket() override {} void OnVersionNegotiationPacket( const QuicVersionNegotiationPacket& ) override {} void OnRetryPacket(QuicConnectionId , QuicConnectionId , absl::string_view , absl::string_view , absl::string_view ) override {} bool OnUnauthenticatedPublicHeader(const QuicPacketHeader& header) override; bool OnUnauthenticatedHeader(const QuicPacketHeader& header) override; void OnDecryptedPacket(size_t , EncryptionLevel ) override {} bool OnPacketHeader(const QuicPacketHeader& header) override; void OnCoalescedPacket(const QuicEncryptedPacket& packet) override; void OnUndecryptablePacket(const QuicEncryptedPacket& packet, EncryptionLevel decryption_level, bool has_decryption_key) override; bool OnStreamFrame(const QuicStreamFrame& frame) override; bool OnCryptoFrame(const QuicCryptoFrame& frame) override; bool OnAckFrameStart(QuicPacketNumber largest_acked, QuicTime::Delta ack_delay_time) override; bool OnAckRange(QuicPacketNumber start, QuicPacketNumber end) override; bool OnAckTimestamp(QuicPacketNumber packet_number, QuicTime timestamp) override; bool OnAckFrameEnd(QuicPacketNumber start, const std::optional<QuicEcnCounts>& ecn_counts) override; bool OnStopWaitingFrame(const QuicStopWaitingFrame& frame) override; bool OnPingFrame(const QuicPingFrame& frame) override; bool OnRstStreamFrame(const QuicRstStreamFrame& frame) override; bool OnConnectionCloseFrame(const QuicConnectionCloseFrame& frame) override; bool OnNewConnectionIdFrame(const QuicNewConnectionIdFrame& frame) override; bool OnRetireConnectionIdFrame( const QuicRetireConnectionIdFrame& frame) override; bool OnNewTokenFrame(const QuicNewTokenFrame& frame) override; bool OnStopSendingFrame(const QuicStopSendingFrame& frame) override; bool OnPathChallengeFrame(const QuicPathChallengeFrame& frame) override; bool OnPathResponseFrame(const QuicPathResponseFrame& frame) override; bool OnGoAwayFrame(const QuicGoAwayFrame& frame) override; bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) override; bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) override; bool OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) override; bool OnBlockedFrame(const QuicBlockedFrame& frame) override; bool OnPaddingFrame(const QuicPaddingFrame& frame) override; bool OnMessageFrame(const QuicMessageFrame& frame) override; bool OnHandshakeDoneFrame(const QuicHandshakeDoneFrame& frame) override; bool OnAckFrequencyFrame(const QuicAckFrequencyFrame& farme) override; bool OnResetStreamAtFrame(const QuicResetStreamAtFrame& frame) override; void OnPacketComplete() override {} bool IsValidStatelessResetToken( const StatelessResetToken& token) const override; void OnAuthenticatedIetfStatelessResetPacket( const QuicIetfStatelessResetPacket& ) override {} void OnKeyUpdate(KeyUpdateReason ) override; void OnDecryptedFirstPacketInKeyPhase() override; std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter() override; std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override; void OnError(CryptoFramer* framer) override; void OnHandshakeMessage(const CryptoHandshakeMessage& message) override; bool OnHandshakeData(absl::string_view data); bool found_chlo() { return found_chlo_; } bool chlo_contains_tags() { return chlo_contains_tags_; } private: QuicFramer* framer_; const QuicTagVector& create_session_tag_indicators_; ChloExtractor::Delegate* delegate_; bool found_chlo_; bool chlo_contains_tags_; QuicConnectionId connection_id_; }; ChloFramerVisitor::ChloFramerVisitor( QuicFramer* framer, const QuicTagVector& create_session_tag_indicators, ChloExtractor::Delegate* delegate) : framer_(framer), create_session_tag_indicators_(create_session_tag_indicators), delegate_(delegate), found_chlo_(false), chlo_contains_tags_(false), connection_id_(EmptyQuicConnectionId()) {} bool ChloFramerVisitor::OnProtocolVersionMismatch(ParsedQuicVersion version) { if (!framer_->IsSupportedVersion(version)) { return false; } framer_->set_version(version); return true; } bool ChloFramerVisitor::OnUnauthenticatedPublicHeader( const QuicPacketHeader& header) { connection_id_ = header.destination_connection_id; framer_->SetInitialObfuscators(header.destination_connection_id); return true; } bool ChloFramerVisitor::OnUnauthenticatedHeader( const QuicPacketHeader& ) { return true; } bool ChloFramerVisitor::OnPacketHeader(const QuicPacketHeader& ) { return true; } void ChloFramerVisitor::OnCoalescedPacket( const QuicEncryptedPacket& ) {} void ChloFramerVisitor::OnUndecryptablePacket( const QuicEncryptedPacket& , EncryptionLevel , bool ) {} bool ChloFramerVisitor::OnStreamFrame(const QuicStreamFrame& frame) { if (QuicVersionUsesCryptoFrames(framer_->transport_version())) { return false; } absl::string_view data(frame.data_buffer, frame.data_length); if (QuicUtils::IsCryptoStreamId(framer_->transport_version(), frame.stream_id) && frame.offset == 0 && absl::StartsWith(data, "CHLO")) { return OnHandshakeData(data); } return true; } bool ChloFramerVisitor::OnCryptoFrame(const QuicCryptoFrame& frame) { if (!QuicVersionUsesCryptoFrames(framer_->transport_version())) { return false; } absl::string_view data(frame.data_buffer, frame.data_length); if (frame.offset == 0 && absl::StartsWith(data, "CHLO")) { return OnHandshakeData(data); } return true; } bool ChloFramerVisitor::OnHandshakeData(absl::string_view data) { CryptoFramer crypto_framer; crypto_framer.set_visitor(this); if (!crypto_framer.ProcessInput(data)) { return false; } for (const QuicTag tag : create_session_tag_indicators_) { if (crypto_framer.HasTag(tag)) { chlo_contains_tags_ = true; } } if (chlo_contains_tags_ && delegate_) { crypto_framer.ForceHandshake(); } return true; } bool ChloFramerVisitor::OnAckFrameStart(QuicPacketNumber , QuicTime::Delta ) { return true; } bool ChloFramerVisitor::OnResetStreamAtFrame( const QuicResetStreamAtFrame& ) { return true; } bool ChloFramerVisitor::OnAckRange(QuicPacketNumber , QuicPacketNumber ) { return true; } bool ChloFramerVisitor::OnAckTimestamp(QuicPacketNumber , QuicTime ) { return true; } bool ChloFramerVisitor::OnAckFrameEnd( QuicPacketNumber , const std::optional<QuicEcnCounts>& ) { return true; } bool ChloFramerVisitor::OnStopWaitingFrame( const QuicStopWaitingFrame& ) { return true; } bool ChloFramerVisitor::OnPingFrame(const QuicPingFrame& ) { return true; } bool ChloFramerVisitor::OnRstStreamFrame(const QuicRstStreamFrame& ) { return true; } bool ChloFramerVisitor::OnConnectionCloseFrame( const QuicConnectionCloseFrame& ) { return true; } bool ChloFramerVisitor::OnStopSendingFrame( const QuicStopSendingFrame& ) { return true; } bool ChloFramerVisitor::OnPathChallengeFrame( const QuicPathChallengeFrame& ) { return true; } bool ChloFramerVisitor::OnPathResponseFrame( const QuicPathResponseFrame& ) { return true; } bool ChloFramerVisitor::OnGoAwayFrame(const QuicGoAwayFrame& ) { return true; } bool ChloFramerVisitor::OnWindowUpdateFrame( const QuicWindowUpdateFrame& ) { return true; } bool ChloFramerVisitor::OnBlockedFrame(const QuicBlockedFrame& ) { return true; } bool ChloFramerVisitor::OnNewConnectionIdFrame( const QuicNewConnectionIdFrame& ) { return true; } bool ChloFramerVisitor::OnRetireConnectionIdFrame( const QuicRetireConnectionIdFrame& ) { return true; } bool ChloFramerVisitor::OnNewTokenFrame(const QuicNewTokenFrame& ) { return true; } bool ChloFramerVisitor::OnPaddingFrame(const QuicPaddingFrame& ) { return true; } bool ChloFramerVisitor::OnMessageFrame(const QuicMessageFrame& ) { return true; } bool ChloFramerVisitor::OnHandshakeDoneFrame( const QuicHandshakeDoneFrame& ) { return true; } bool ChloFramerVisitor::OnAckFrequencyFrame( const QuicAckFrequencyFrame& ) { return true; } bool ChloFramerVisitor::IsValidStatelessResetToken( const StatelessResetToken& ) const { return false; } bool ChloFramerVisitor::OnMaxStreamsFrame( const QuicMaxStreamsFrame& ) { return true; } bool ChloFramerVisitor::OnStreamsBlockedFrame( const QuicStreamsBlockedFrame& ) { return true; } void ChloFramerVisitor::OnKeyUpdate(KeyUpdateReason ) {} void ChloFramerVisitor::OnDecryptedFirstPacketInKeyPhase() {} std::unique_ptr<QuicDecrypter> ChloFramerVisitor::AdvanceKeysAndCreateCurrentOneRttDecrypter() { return nullptr; } std::unique_ptr<QuicEncrypter> ChloFramerVisitor::CreateCurrentOneRttEncrypter() { return nullptr; } void ChloFramerVisitor::OnError(CryptoFramer* ) {} void ChloFramerVisitor::OnHandshakeMessage( const CryptoHandshakeMessage& message) { if (delegate_ != nullptr) { delegate_->OnChlo(framer_->transport_version(), connection_id_, message); } found_chlo_ = true; } } bool ChloExtractor::Extract(const QuicEncryptedPacket& packet, ParsedQuicVersion version, const QuicTagVector& create_session_tag_indicators, Delegate* delegate, uint8_t connection_id_length) { QUIC_DVLOG(1) << "Extracting CHLO using version " << version; QuicFramer framer({version}, QuicTime::Zero(), Perspective::IS_SERVER, connection_id_length); ChloFramerVisitor visitor(&framer, create_session_tag_indicators, delegate); framer.set_visitor(&visitor); if (!framer.ProcessPacket(packet)) { return false; } return visitor.found_chlo() || visitor.chlo_contains_tags(); } }
#include "quiche/quic/core/chlo_extractor.h" #include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_framer.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" #include "quiche/quic/test_tools/first_flight.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { namespace test { namespace { class TestDelegate : public ChloExtractor::Delegate { public: TestDelegate() = default; ~TestDelegate() override = default; void OnChlo(QuicTransportVersion version, QuicConnectionId connection_id, const CryptoHandshakeMessage& chlo) override { version_ = version; connection_id_ = connection_id; chlo_ = chlo.DebugString(); absl::string_view alpn_value; if (chlo.GetStringPiece(kALPN, &alpn_value)) { alpn_ = std::string(alpn_value); } } QuicConnectionId connection_id() const { return connection_id_; } QuicTransportVersion transport_version() const { return version_; } const std::string& chlo() const { return chlo_; } const std::string& alpn() const { return alpn_; } private: QuicConnectionId connection_id_; QuicTransportVersion version_; std::string chlo_; std::string alpn_; }; class ChloExtractorTest : public QuicTestWithParam<ParsedQuicVersion> { public: ChloExtractorTest() : version_(GetParam()) {} void MakePacket(absl::string_view data, bool munge_offset, bool munge_stream_id) { QuicPacketHeader header; header.destination_connection_id = TestConnectionId(); header.destination_connection_id_included = CONNECTION_ID_PRESENT; header.version_flag = true; header.version = version_; header.reset_flag = false; header.packet_number_length = PACKET_4BYTE_PACKET_NUMBER; header.packet_number = QuicPacketNumber(1); if (version_.HasLongHeaderLengths()) { header.retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1; header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2; } QuicFrames frames; size_t offset = 0; if (munge_offset) { offset++; } QuicFramer framer(SupportedVersions(version_), QuicTime::Zero(), Perspective::IS_CLIENT, kQuicDefaultConnectionIdLength); framer.SetInitialObfuscators(TestConnectionId()); if (!version_.UsesCryptoFrames() || munge_stream_id) { QuicStreamId stream_id = QuicUtils::GetCryptoStreamId(version_.transport_version); if (munge_stream_id) { stream_id++; } frames.push_back( QuicFrame(QuicStreamFrame(stream_id, false, offset, data))); } else { frames.push_back( QuicFrame(new QuicCryptoFrame(ENCRYPTION_INITIAL, offset, data))); } std::unique_ptr<QuicPacket> packet( BuildUnsizedDataPacket(&framer, header, frames)); EXPECT_TRUE(packet != nullptr); size_t encrypted_length = framer.EncryptPayload(ENCRYPTION_INITIAL, header.packet_number, *packet, buffer_, ABSL_ARRAYSIZE(buffer_)); ASSERT_NE(0u, encrypted_length); packet_ = std::make_unique<QuicEncryptedPacket>(buffer_, encrypted_length); EXPECT_TRUE(packet_ != nullptr); DeleteFrames(&frames); } protected: ParsedQuicVersion version_; TestDelegate delegate_; std::unique_ptr<QuicEncryptedPacket> packet_; char buffer_[kMaxOutgoingPacketSize]; }; INSTANTIATE_TEST_SUITE_P( ChloExtractorTests, ChloExtractorTest, ::testing::ValuesIn(AllSupportedVersionsWithQuicCrypto()), ::testing::PrintToStringParamName()); TEST_P(ChloExtractorTest, FindsValidChlo) { CryptoHandshakeMessage client_hello; client_hello.set_tag(kCHLO); std::string client_hello_str(client_hello.GetSerialized().AsStringPiece()); MakePacket(client_hello_str, false, false); EXPECT_TRUE(ChloExtractor::Extract(*packet_, version_, {}, &delegate_, kQuicDefaultConnectionIdLength)); EXPECT_EQ(version_.transport_version, delegate_.transport_version()); EXPECT_EQ(TestConnectionId(), delegate_.connection_id()); EXPECT_EQ(client_hello.DebugString(), delegate_.chlo()); } TEST_P(ChloExtractorTest, DoesNotFindValidChloOnWrongStream) { if (version_.UsesCryptoFrames()) { return; } CryptoHandshakeMessage client_hello; client_hello.set_tag(kCHLO); std::string client_hello_str(client_hello.GetSerialized().AsStringPiece()); MakePacket(client_hello_str, false, true); EXPECT_FALSE(ChloExtractor::Extract(*packet_, version_, {}, &delegate_, kQuicDefaultConnectionIdLength)); } TEST_P(ChloExtractorTest, DoesNotFindValidChloOnWrongOffset) { CryptoHandshakeMessage client_hello; client_hello.set_tag(kCHLO); std::string client_hello_str(client_hello.GetSerialized().AsStringPiece()); MakePacket(client_hello_str, true, false); EXPECT_FALSE(ChloExtractor::Extract(*packet_, version_, {}, &delegate_, kQuicDefaultConnectionIdLength)); } TEST_P(ChloExtractorTest, DoesNotFindInvalidChlo) { MakePacket("foo", false, false); EXPECT_FALSE(ChloExtractor::Extract(*packet_, version_, {}, &delegate_, kQuicDefaultConnectionIdLength)); } TEST_P(ChloExtractorTest, FirstFlight) { std::vector<std::unique_ptr<QuicReceivedPacket>> packets = GetFirstFlightOfPackets(version_); ASSERT_EQ(packets.size(), 1u); EXPECT_TRUE(ChloExtractor::Extract(*packets[0], version_, {}, &delegate_, kQuicDefaultConnectionIdLength)); EXPECT_EQ(version_.transport_version, delegate_.transport_version()); EXPECT_EQ(TestConnectionId(), delegate_.connection_id()); EXPECT_EQ(AlpnForVersion(version_), delegate_.alpn()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/chlo_extractor.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/chlo_extractor_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
01075303-4b1d-4a66-bafd-a961fb92cec6
cpp
google/quiche
uber_received_packet_manager
quiche/quic/core/uber_received_packet_manager.cc
quiche/quic/core/uber_received_packet_manager_test.cc
#include "quiche/quic/core/uber_received_packet_manager.h" #include <algorithm> #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" namespace quic { UberReceivedPacketManager::UberReceivedPacketManager(QuicConnectionStats* stats) : supports_multiple_packet_number_spaces_(false) { for (auto& received_packet_manager : received_packet_managers_) { received_packet_manager.set_connection_stats(stats); } } UberReceivedPacketManager::~UberReceivedPacketManager() {} void UberReceivedPacketManager::SetFromConfig(const QuicConfig& config, Perspective perspective) { for (auto& received_packet_manager : received_packet_managers_) { received_packet_manager.SetFromConfig(config, perspective); } } bool UberReceivedPacketManager::IsAwaitingPacket( EncryptionLevel decrypted_packet_level, QuicPacketNumber packet_number) const { if (!supports_multiple_packet_number_spaces_) { return received_packet_managers_[0].IsAwaitingPacket(packet_number); } return received_packet_managers_[QuicUtils::GetPacketNumberSpace( decrypted_packet_level)] .IsAwaitingPacket(packet_number); } const QuicFrame UberReceivedPacketManager::GetUpdatedAckFrame( PacketNumberSpace packet_number_space, QuicTime approximate_now) { if (!supports_multiple_packet_number_spaces_) { return received_packet_managers_[0].GetUpdatedAckFrame(approximate_now); } return received_packet_managers_[packet_number_space].GetUpdatedAckFrame( approximate_now); } void UberReceivedPacketManager::RecordPacketReceived( EncryptionLevel decrypted_packet_level, const QuicPacketHeader& header, QuicTime receipt_time, QuicEcnCodepoint ecn_codepoint) { if (!supports_multiple_packet_number_spaces_) { received_packet_managers_[0].RecordPacketReceived(header, receipt_time, ecn_codepoint); return; } received_packet_managers_[QuicUtils::GetPacketNumberSpace( decrypted_packet_level)] .RecordPacketReceived(header, receipt_time, ecn_codepoint); } void UberReceivedPacketManager::DontWaitForPacketsBefore( EncryptionLevel decrypted_packet_level, QuicPacketNumber least_unacked) { if (!supports_multiple_packet_number_spaces_) { received_packet_managers_[0].DontWaitForPacketsBefore(least_unacked); return; } received_packet_managers_[QuicUtils::GetPacketNumberSpace( decrypted_packet_level)] .DontWaitForPacketsBefore(least_unacked); } void UberReceivedPacketManager::MaybeUpdateAckTimeout( bool should_last_packet_instigate_acks, EncryptionLevel decrypted_packet_level, QuicPacketNumber last_received_packet_number, QuicTime last_packet_receipt_time, QuicTime now, const RttStats* rtt_stats) { if (!supports_multiple_packet_number_spaces_) { received_packet_managers_[0].MaybeUpdateAckTimeout( should_last_packet_instigate_acks, last_received_packet_number, last_packet_receipt_time, now, rtt_stats); return; } received_packet_managers_[QuicUtils::GetPacketNumberSpace( decrypted_packet_level)] .MaybeUpdateAckTimeout(should_last_packet_instigate_acks, last_received_packet_number, last_packet_receipt_time, now, rtt_stats); } void UberReceivedPacketManager::ResetAckStates( EncryptionLevel encryption_level) { if (!supports_multiple_packet_number_spaces_) { received_packet_managers_[0].ResetAckStates(); return; } received_packet_managers_[QuicUtils::GetPacketNumberSpace(encryption_level)] .ResetAckStates(); if (encryption_level == ENCRYPTION_INITIAL) { received_packet_managers_[INITIAL_DATA].set_local_max_ack_delay( kAlarmGranularity); } } void UberReceivedPacketManager::EnableMultiplePacketNumberSpacesSupport( Perspective perspective) { if (supports_multiple_packet_number_spaces_) { QUIC_BUG(quic_bug_10495_1) << "Multiple packet number spaces has already been enabled"; return; } if (received_packet_managers_[0].GetLargestObserved().IsInitialized()) { QUIC_BUG(quic_bug_10495_2) << "Try to enable multiple packet number spaces support after any " "packet has been received."; return; } if (perspective == Perspective::IS_CLIENT) { received_packet_managers_[INITIAL_DATA].set_local_max_ack_delay( kAlarmGranularity); } received_packet_managers_[HANDSHAKE_DATA].set_local_max_ack_delay( kAlarmGranularity); supports_multiple_packet_number_spaces_ = true; } bool UberReceivedPacketManager::IsAckFrameUpdated() const { if (!supports_multiple_packet_number_spaces_) { return received_packet_managers_[0].ack_frame_updated(); } for (const auto& received_packet_manager : received_packet_managers_) { if (received_packet_manager.ack_frame_updated()) { return true; } } return false; } QuicPacketNumber UberReceivedPacketManager::GetLargestObserved( EncryptionLevel decrypted_packet_level) const { if (!supports_multiple_packet_number_spaces_) { return received_packet_managers_[0].GetLargestObserved(); } return received_packet_managers_[QuicUtils::GetPacketNumberSpace( decrypted_packet_level)] .GetLargestObserved(); } QuicTime UberReceivedPacketManager::GetAckTimeout( PacketNumberSpace packet_number_space) const { if (!supports_multiple_packet_number_spaces_) { return received_packet_managers_[0].ack_timeout(); } return received_packet_managers_[packet_number_space].ack_timeout(); } QuicTime UberReceivedPacketManager::GetEarliestAckTimeout() const { QuicTime ack_timeout = QuicTime::Zero(); for (const auto& received_packet_manager : received_packet_managers_) { const QuicTime timeout = received_packet_manager.ack_timeout(); if (!ack_timeout.IsInitialized()) { ack_timeout = timeout; continue; } if (timeout.IsInitialized()) { ack_timeout = std::min(ack_timeout, timeout); } } return ack_timeout; } bool UberReceivedPacketManager::IsAckFrameEmpty( PacketNumberSpace packet_number_space) const { if (!supports_multiple_packet_number_spaces_) { return received_packet_managers_[0].IsAckFrameEmpty(); } return received_packet_managers_[packet_number_space].IsAckFrameEmpty(); } size_t UberReceivedPacketManager::min_received_before_ack_decimation() const { return received_packet_managers_[0].min_received_before_ack_decimation(); } void UberReceivedPacketManager::set_min_received_before_ack_decimation( size_t new_value) { for (auto& received_packet_manager : received_packet_managers_) { received_packet_manager.set_min_received_before_ack_decimation(new_value); } } void UberReceivedPacketManager::set_ack_frequency(size_t new_value) { for (auto& received_packet_manager : received_packet_managers_) { received_packet_manager.set_ack_frequency(new_value); } } const QuicAckFrame& UberReceivedPacketManager::ack_frame() const { QUICHE_DCHECK(!supports_multiple_packet_number_spaces_); return received_packet_managers_[0].ack_frame(); } const QuicAckFrame& UberReceivedPacketManager::GetAckFrame( PacketNumberSpace packet_number_space) const { QUICHE_DCHECK(supports_multiple_packet_number_spaces_); return received_packet_managers_[packet_number_space].ack_frame(); } void UberReceivedPacketManager::set_max_ack_ranges(size_t max_ack_ranges) { for (auto& received_packet_manager : received_packet_managers_) { received_packet_manager.set_max_ack_ranges(max_ack_ranges); } } void UberReceivedPacketManager::set_save_timestamps(bool save_timestamps) { for (auto& received_packet_manager : received_packet_managers_) { received_packet_manager.set_save_timestamps( save_timestamps, supports_multiple_packet_number_spaces_); } } void UberReceivedPacketManager::OnAckFrequencyFrame( const QuicAckFrequencyFrame& frame) { if (!supports_multiple_packet_number_spaces_) { QUIC_BUG(quic_bug_10495_3) << "Received AckFrequencyFrame when multiple packet number spaces " "is not supported"; return; } received_packet_managers_[APPLICATION_DATA].OnAckFrequencyFrame(frame); } }
#include "quiche/quic/core/uber_received_packet_manager.h" #include <algorithm> #include <memory> #include <utility> #include "quiche/quic/core/congestion_control/rtt_stats.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/quic_connection_stats.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_clock.h" namespace quic { namespace test { class UberReceivedPacketManagerPeer { public: static void SetAckDecimationDelay(UberReceivedPacketManager* manager, float ack_decimation_delay) { for (auto& received_packet_manager : manager->received_packet_managers_) { received_packet_manager.ack_decimation_delay_ = ack_decimation_delay; } } }; namespace { const bool kInstigateAck = true; const QuicTime::Delta kMinRttMs = QuicTime::Delta::FromMilliseconds(40); const QuicTime::Delta kDelayedAckTime = QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs()); EncryptionLevel GetEncryptionLevel(PacketNumberSpace packet_number_space) { switch (packet_number_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; } } class UberReceivedPacketManagerTest : public QuicTest { protected: UberReceivedPacketManagerTest() { manager_ = std::make_unique<UberReceivedPacketManager>(&stats_); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1)); rtt_stats_.UpdateRtt(kMinRttMs, QuicTime::Delta::Zero(), QuicTime::Zero()); manager_->set_save_timestamps(true); } void RecordPacketReceipt(uint64_t packet_number) { RecordPacketReceipt(ENCRYPTION_FORWARD_SECURE, packet_number); } void RecordPacketReceipt(uint64_t packet_number, QuicTime receipt_time) { RecordPacketReceipt(ENCRYPTION_FORWARD_SECURE, packet_number, receipt_time); } void RecordPacketReceipt(EncryptionLevel decrypted_packet_level, uint64_t packet_number) { RecordPacketReceipt(decrypted_packet_level, packet_number, QuicTime::Zero()); } void RecordPacketReceipt(EncryptionLevel decrypted_packet_level, uint64_t packet_number, QuicTime receipt_time) { QuicPacketHeader header; header.packet_number = QuicPacketNumber(packet_number); manager_->RecordPacketReceived(decrypted_packet_level, header, receipt_time, ECN_NOT_ECT); } bool HasPendingAck() { if (!manager_->supports_multiple_packet_number_spaces()) { return manager_->GetAckTimeout(APPLICATION_DATA).IsInitialized(); } return manager_->GetEarliestAckTimeout().IsInitialized(); } void MaybeUpdateAckTimeout(bool should_last_packet_instigate_acks, uint64_t last_received_packet_number) { MaybeUpdateAckTimeout(should_last_packet_instigate_acks, ENCRYPTION_FORWARD_SECURE, last_received_packet_number); } void MaybeUpdateAckTimeout(bool should_last_packet_instigate_acks, EncryptionLevel decrypted_packet_level, uint64_t last_received_packet_number) { manager_->MaybeUpdateAckTimeout( should_last_packet_instigate_acks, decrypted_packet_level, QuicPacketNumber(last_received_packet_number), clock_.ApproximateNow(), clock_.ApproximateNow(), &rtt_stats_); } void CheckAckTimeout(QuicTime time) { QUICHE_DCHECK(HasPendingAck()); if (!manager_->supports_multiple_packet_number_spaces()) { QUICHE_DCHECK(manager_->GetAckTimeout(APPLICATION_DATA) == time); if (time <= clock_.ApproximateNow()) { manager_->ResetAckStates(ENCRYPTION_FORWARD_SECURE); QUICHE_DCHECK(!HasPendingAck()); } return; } QUICHE_DCHECK(manager_->GetEarliestAckTimeout() == time); for (int8_t i = INITIAL_DATA; i < NUM_PACKET_NUMBER_SPACES; ++i) { const QuicTime ack_timeout = manager_->GetAckTimeout(static_cast<PacketNumberSpace>(i)); if (!ack_timeout.IsInitialized() || ack_timeout > clock_.ApproximateNow()) { continue; } manager_->ResetAckStates( GetEncryptionLevel(static_cast<PacketNumberSpace>(i))); } } MockClock clock_; RttStats rtt_stats_; QuicConnectionStats stats_; std::unique_ptr<UberReceivedPacketManager> manager_; }; TEST_F(UberReceivedPacketManagerTest, DontWaitForPacketsBefore) { EXPECT_TRUE(manager_->IsAckFrameEmpty(APPLICATION_DATA)); RecordPacketReceipt(2); EXPECT_FALSE(manager_->IsAckFrameEmpty(APPLICATION_DATA)); RecordPacketReceipt(7); EXPECT_TRUE(manager_->IsAwaitingPacket(ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(3u))); EXPECT_TRUE(manager_->IsAwaitingPacket(ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(6u))); manager_->DontWaitForPacketsBefore(ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(4)); EXPECT_FALSE(manager_->IsAwaitingPacket(ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(3u))); EXPECT_TRUE(manager_->IsAwaitingPacket(ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(6u))); } TEST_F(UberReceivedPacketManagerTest, GetUpdatedAckFrame) { QuicTime two_ms = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(2); EXPECT_FALSE(manager_->IsAckFrameUpdated()); RecordPacketReceipt(2, two_ms); EXPECT_TRUE(manager_->IsAckFrameUpdated()); QuicFrame ack = manager_->GetUpdatedAckFrame(APPLICATION_DATA, QuicTime::Zero()); manager_->ResetAckStates(ENCRYPTION_FORWARD_SECURE); EXPECT_FALSE(manager_->IsAckFrameUpdated()); EXPECT_EQ(QuicTime::Delta::Zero(), ack.ack_frame->ack_delay_time); EXPECT_EQ(1u, ack.ack_frame->received_packet_times.size()); QuicTime four_ms = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(4); ack = manager_->GetUpdatedAckFrame(APPLICATION_DATA, four_ms); manager_->ResetAckStates(ENCRYPTION_FORWARD_SECURE); EXPECT_FALSE(manager_->IsAckFrameUpdated()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(2), ack.ack_frame->ack_delay_time); EXPECT_EQ(1u, ack.ack_frame->received_packet_times.size()); RecordPacketReceipt(999, two_ms); RecordPacketReceipt(4, two_ms); RecordPacketReceipt(1000, two_ms); EXPECT_TRUE(manager_->IsAckFrameUpdated()); ack = manager_->GetUpdatedAckFrame(APPLICATION_DATA, two_ms); manager_->ResetAckStates(ENCRYPTION_FORWARD_SECURE); EXPECT_FALSE(manager_->IsAckFrameUpdated()); EXPECT_EQ(2u, ack.ack_frame->received_packet_times.size()); } TEST_F(UberReceivedPacketManagerTest, UpdateReceivedConnectionStats) { EXPECT_FALSE(manager_->IsAckFrameUpdated()); RecordPacketReceipt(1); EXPECT_TRUE(manager_->IsAckFrameUpdated()); RecordPacketReceipt(6); RecordPacketReceipt(2, QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1)); EXPECT_EQ(4u, stats_.max_sequence_reordering); EXPECT_EQ(1000, stats_.max_time_reordering_us); EXPECT_EQ(1u, stats_.packets_reordered); } TEST_F(UberReceivedPacketManagerTest, LimitAckRanges) { manager_->set_max_ack_ranges(10); EXPECT_FALSE(manager_->IsAckFrameUpdated()); for (int i = 0; i < 100; ++i) { RecordPacketReceipt(1 + 2 * i); EXPECT_TRUE(manager_->IsAckFrameUpdated()); manager_->GetUpdatedAckFrame(APPLICATION_DATA, QuicTime::Zero()); EXPECT_GE(10u, manager_->ack_frame().packets.NumIntervals()); EXPECT_EQ(QuicPacketNumber(1u + 2 * i), manager_->ack_frame().packets.Max()); for (int j = 0; j < std::min(10, i + 1); ++j) { ASSERT_GE(i, j); EXPECT_TRUE(manager_->ack_frame().packets.Contains( QuicPacketNumber(1 + (i - j) * 2))); if (i > j) { EXPECT_FALSE(manager_->ack_frame().packets.Contains( QuicPacketNumber((i - j) * 2))); } } } } TEST_F(UberReceivedPacketManagerTest, IgnoreOutOfOrderTimestamps) { EXPECT_FALSE(manager_->IsAckFrameUpdated()); RecordPacketReceipt(1, QuicTime::Zero()); EXPECT_TRUE(manager_->IsAckFrameUpdated()); EXPECT_EQ(1u, manager_->ack_frame().received_packet_times.size()); RecordPacketReceipt(2, QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1)); EXPECT_EQ(2u, manager_->ack_frame().received_packet_times.size()); RecordPacketReceipt(3, QuicTime::Zero()); EXPECT_EQ(2u, manager_->ack_frame().received_packet_times.size()); } TEST_F(UberReceivedPacketManagerTest, OutOfOrderReceiptCausesAckSent) { EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(3, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 3); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); RecordPacketReceipt(2, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 2); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(1, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 1); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(4, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 4); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } TEST_F(UberReceivedPacketManagerTest, OutOfOrderAckReceiptCausesNoAck) { EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(2, clock_.ApproximateNow()); MaybeUpdateAckTimeout(!kInstigateAck, 2); EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(1, clock_.ApproximateNow()); MaybeUpdateAckTimeout(!kInstigateAck, 1); EXPECT_FALSE(HasPendingAck()); } TEST_F(UberReceivedPacketManagerTest, AckReceiptCausesAckSend) { EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(1, clock_.ApproximateNow()); MaybeUpdateAckTimeout(!kInstigateAck, 1); EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(2, clock_.ApproximateNow()); MaybeUpdateAckTimeout(!kInstigateAck, 2); EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(3, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 3); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); clock_.AdvanceTime(kDelayedAckTime); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(4, clock_.ApproximateNow()); MaybeUpdateAckTimeout(!kInstigateAck, 4); EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(5, clock_.ApproximateNow()); MaybeUpdateAckTimeout(!kInstigateAck, 5); EXPECT_FALSE(HasPendingAck()); } TEST_F(UberReceivedPacketManagerTest, AckSentEveryNthPacket) { EXPECT_FALSE(HasPendingAck()); manager_->set_ack_frequency(3); for (size_t i = 1; i <= 39; ++i) { RecordPacketReceipt(i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, i); if (i % 3 == 0) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } } } TEST_F(UberReceivedPacketManagerTest, AckDecimationReducesAcks) { EXPECT_FALSE(HasPendingAck()); manager_->set_min_received_before_ack_decimation(10); for (size_t i = 1; i <= 29; ++i) { RecordPacketReceipt(i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, i); if (i <= 10) { if (i % 2 == 0) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } continue; } if (i == 20) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kMinRttMs * 0.25); } } RecordPacketReceipt(30, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 30); CheckAckTimeout(clock_.ApproximateNow()); } TEST_F(UberReceivedPacketManagerTest, SendDelayedAckDecimation) { EXPECT_FALSE(HasPendingAck()); QuicTime ack_time = clock_.ApproximateNow() + kMinRttMs * 0.25; uint64_t kFirstDecimatedPacket = 101; for (uint64_t i = 1; i < kFirstDecimatedPacket; ++i) { RecordPacketReceipt(i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, i); if (i % 2 == 0) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } } RecordPacketReceipt(kFirstDecimatedPacket, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket); CheckAckTimeout(ack_time); for (uint64_t i = 1; i < 10; ++i) { RecordPacketReceipt(kFirstDecimatedPacket + i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket + i); } CheckAckTimeout(clock_.ApproximateNow()); } TEST_F(UberReceivedPacketManagerTest, SendDelayedAckDecimationUnlimitedAggregation) { EXPECT_FALSE(HasPendingAck()); QuicConfig config; QuicTagVector connection_options; connection_options.push_back(kAKDU); config.SetConnectionOptionsToSend(connection_options); manager_->SetFromConfig(config, Perspective::IS_CLIENT); QuicTime ack_time = clock_.ApproximateNow() + kMinRttMs * 0.25; uint64_t kFirstDecimatedPacket = 101; for (uint64_t i = 1; i < kFirstDecimatedPacket; ++i) { RecordPacketReceipt(i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, i); if (i % 2 == 0) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } } RecordPacketReceipt(kFirstDecimatedPacket, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket); CheckAckTimeout(ack_time); for (int i = 1; i <= 18; ++i) { RecordPacketReceipt(kFirstDecimatedPacket + i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket + i); } CheckAckTimeout(ack_time); } TEST_F(UberReceivedPacketManagerTest, SendDelayedAckDecimationEighthRtt) { EXPECT_FALSE(HasPendingAck()); UberReceivedPacketManagerPeer::SetAckDecimationDelay(manager_.get(), 0.125); QuicTime ack_time = clock_.ApproximateNow() + kMinRttMs * 0.125; uint64_t kFirstDecimatedPacket = 101; for (uint64_t i = 1; i < kFirstDecimatedPacket; ++i) { RecordPacketReceipt(i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, i); if (i % 2 == 0) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } } RecordPacketReceipt(kFirstDecimatedPacket, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket); CheckAckTimeout(ack_time); for (uint64_t i = 1; i < 10; ++i) { RecordPacketReceipt(kFirstDecimatedPacket + i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket + i); } CheckAckTimeout(clock_.ApproximateNow()); } TEST_F(UberReceivedPacketManagerTest, DontWaitForPacketsBeforeMultiplePacketNumberSpaces) { manager_->EnableMultiplePacketNumberSpacesSupport(Perspective::IS_CLIENT); EXPECT_FALSE( manager_->GetLargestObserved(ENCRYPTION_HANDSHAKE).IsInitialized()); EXPECT_FALSE( manager_->GetLargestObserved(ENCRYPTION_FORWARD_SECURE).IsInitialized()); RecordPacketReceipt(ENCRYPTION_HANDSHAKE, 2); RecordPacketReceipt(ENCRYPTION_HANDSHAKE, 4); RecordPacketReceipt(ENCRYPTION_FORWARD_SECURE, 3); RecordPacketReceipt(ENCRYPTION_FORWARD_SECURE, 7); EXPECT_EQ(QuicPacketNumber(4), manager_->GetLargestObserved(ENCRYPTION_HANDSHAKE)); EXPECT_EQ(QuicPacketNumber(7), manager_->GetLargestObserved(ENCRYPTION_FORWARD_SECURE)); EXPECT_TRUE( manager_->IsAwaitingPacket(ENCRYPTION_HANDSHAKE, QuicPacketNumber(3))); EXPECT_FALSE(manager_->IsAwaitingPacket(ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(3))); EXPECT_TRUE(manager_->IsAwaitingPacket(ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(4))); manager_->DontWaitForPacketsBefore(ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(5)); EXPECT_TRUE( manager_->IsAwaitingPacket(ENCRYPTION_HANDSHAKE, QuicPacketNumber(3))); EXPECT_FALSE(manager_->IsAwaitingPacket(ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(4))); } TEST_F(UberReceivedPacketManagerTest, AckSendingDifferentPacketNumberSpaces) { manager_->EnableMultiplePacketNumberSpacesSupport(Perspective::IS_SERVER); EXPECT_FALSE(HasPendingAck()); EXPECT_FALSE(manager_->IsAckFrameUpdated()); RecordPacketReceipt(ENCRYPTION_INITIAL, 3); EXPECT_TRUE(manager_->IsAckFrameUpdated()); MaybeUpdateAckTimeout(kInstigateAck, ENCRYPTION_INITIAL, 3); EXPECT_TRUE(HasPendingAck()); CheckAckTimeout(clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(25)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(25)); CheckAckTimeout(clock_.ApproximateNow()); EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(ENCRYPTION_INITIAL, 4); EXPECT_TRUE(manager_->IsAckFrameUpdated()); MaybeUpdateAckTimeout(kInstigateAck, ENCRYPTION_INITIAL, 4); EXPECT_TRUE(HasPendingAck()); CheckAckTimeout(clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); CheckAckTimeout(clock_.ApproximateNow()); EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(ENCRYPTION_HANDSHAKE, 3); EXPECT_TRUE(manager_->IsAckFrameUpdated()); MaybeUpdateAckTimeout(kInstigateAck, ENCRYPTION_HANDSHAKE, 3); EXPECT_TRUE(HasPendingAck()); CheckAckTimeout(clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); CheckAckTimeout(clock_.ApproximateNow()); EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(ENCRYPTION_FORWARD_SECURE, 3); MaybeUpdateAckTimeout(kInstigateAck, ENCRYPTION_FORWARD_SECURE, 3); EXPECT_TRUE(HasPendingAck()); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); RecordPacketReceipt(ENCRYPTION_FORWARD_SECURE, 2); MaybeUpdateAckTimeout(kInstigateAck, ENCRYPTION_FORWARD_SECURE, 2); CheckAckTimeout(clock_.ApproximateNow()); EXPECT_FALSE(HasPendingAck()); } TEST_F(UberReceivedPacketManagerTest, AckTimeoutForPreviouslyUndecryptablePackets) { manager_->EnableMultiplePacketNumberSpacesSupport(Perspective::IS_SERVER); EXPECT_FALSE(HasPendingAck()); EXPECT_FALSE(manager_->IsAckFrameUpdated()); const QuicTime packet_receipt_time4 = clock_.ApproximateNow(); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10)); RecordPacketReceipt(ENCRYPTION_HANDSHAKE, 5); MaybeUpdateAckTimeout(kInstigateAck, ENCRYPTION_HANDSHAKE, 5); EXPECT_TRUE(HasPendingAck()); RecordPacketReceipt(ENCRYPTION_FORWARD_SECURE, 4); manager_->MaybeUpdateAckTimeout(kInstigateAck, ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(4), packet_receipt_time4, clock_.ApproximateNow(), &rtt_stats_); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); CheckAckTimeout(clock_.ApproximateNow()); EXPECT_TRUE(HasPendingAck()); CheckAckTimeout(clock_.ApproximateNow() - QuicTime::Delta::FromMilliseconds(11) + kDelayedAckTime); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/uber_received_packet_manager.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/uber_received_packet_manager_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
4645f1f3-7545-471e-aacc-a06c1b1d4adb
cpp
google/quiche
quic_ping_manager
quiche/quic/core/quic_ping_manager.cc
quiche/quic/core/quic_ping_manager_test.cc
#include "quiche/quic/core/quic_ping_manager.h" #include <algorithm> #include "quiche/quic/platform/api/quic_flags.h" namespace quic { namespace { const int kMaxRetransmittableOnWireDelayShift = 10; } QuicPingManager::QuicPingManager(Perspective perspective, Delegate* delegate, QuicAlarm* alarm) : perspective_(perspective), delegate_(delegate), alarm_(*alarm) {} void QuicPingManager::SetAlarm(QuicTime now, bool should_keep_alive, bool has_in_flight_packets) { UpdateDeadlines(now, should_keep_alive, has_in_flight_packets); const QuicTime earliest_deadline = GetEarliestDeadline(); if (!earliest_deadline.IsInitialized()) { alarm_.Cancel(); return; } if (earliest_deadline == keep_alive_deadline_) { alarm_.Update(earliest_deadline, QuicTime::Delta::FromSeconds(1)); return; } alarm_.Update(earliest_deadline, kAlarmGranularity); } void QuicPingManager::OnAlarm() { const QuicTime earliest_deadline = GetEarliestDeadline(); if (!earliest_deadline.IsInitialized()) { QUIC_BUG(quic_ping_manager_alarm_fires_unexpectedly) << "QuicPingManager alarm fires unexpectedly."; return; } if (earliest_deadline == retransmittable_on_wire_deadline_) { retransmittable_on_wire_deadline_ = QuicTime::Zero(); if (GetQuicFlag(quic_max_aggressive_retransmittable_on_wire_ping_count) != 0) { ++consecutive_retransmittable_on_wire_count_; } ++retransmittable_on_wire_count_; delegate_->OnRetransmittableOnWireTimeout(); return; } if (earliest_deadline == keep_alive_deadline_) { keep_alive_deadline_ = QuicTime::Zero(); delegate_->OnKeepAliveTimeout(); } } void QuicPingManager::Stop() { alarm_.PermanentCancel(); retransmittable_on_wire_deadline_ = QuicTime::Zero(); keep_alive_deadline_ = QuicTime::Zero(); } void QuicPingManager::UpdateDeadlines(QuicTime now, bool should_keep_alive, bool has_in_flight_packets) { keep_alive_deadline_ = QuicTime::Zero(); if (perspective_ == Perspective::IS_SERVER && initial_retransmittable_on_wire_timeout_.IsInfinite()) { QUICHE_DCHECK(!retransmittable_on_wire_deadline_.IsInitialized()); return; } if (!should_keep_alive) { retransmittable_on_wire_deadline_ = QuicTime::Zero(); return; } if (perspective_ == Perspective::IS_CLIENT) { keep_alive_deadline_ = now + keep_alive_timeout_; } if (initial_retransmittable_on_wire_timeout_.IsInfinite() || has_in_flight_packets || retransmittable_on_wire_count_ > GetQuicFlag(quic_max_retransmittable_on_wire_ping_count)) { retransmittable_on_wire_deadline_ = QuicTime::Zero(); return; } QUICHE_DCHECK_LT(initial_retransmittable_on_wire_timeout_, keep_alive_timeout_); QuicTime::Delta retransmittable_on_wire_timeout = initial_retransmittable_on_wire_timeout_; const int max_aggressive_retransmittable_on_wire_count = GetQuicFlag(quic_max_aggressive_retransmittable_on_wire_ping_count); QUICHE_DCHECK_LE(0, max_aggressive_retransmittable_on_wire_count); if (consecutive_retransmittable_on_wire_count_ > max_aggressive_retransmittable_on_wire_count) { int shift = std::min(consecutive_retransmittable_on_wire_count_ - max_aggressive_retransmittable_on_wire_count, kMaxRetransmittableOnWireDelayShift); retransmittable_on_wire_timeout = initial_retransmittable_on_wire_timeout_ * (1 << shift); } if (retransmittable_on_wire_deadline_.IsInitialized() && retransmittable_on_wire_deadline_ < now + retransmittable_on_wire_timeout) { return; } retransmittable_on_wire_deadline_ = now + retransmittable_on_wire_timeout; } QuicTime QuicPingManager::GetEarliestDeadline() const { QuicTime earliest_deadline = QuicTime::Zero(); for (QuicTime t : {retransmittable_on_wire_deadline_, keep_alive_deadline_}) { if (!t.IsInitialized()) { continue; } if (!earliest_deadline.IsInitialized() || t < earliest_deadline) { earliest_deadline = t; } } return earliest_deadline; } }
#include "quiche/quic/core/quic_ping_manager.h" #include "quiche/quic/core/quic_connection_alarms.h" #include "quiche/quic/core/quic_one_block_arena.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_quic_connection_alarms.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { namespace test { class QuicPingManagerPeer { public: static QuicAlarm* GetAlarm(QuicPingManager* manager) { return &manager->alarm_; } static void SetPerspective(QuicPingManager* manager, Perspective perspective) { manager->perspective_ = perspective; } }; namespace { const bool kShouldKeepAlive = true; const bool kHasInflightPackets = true; class MockDelegate : public QuicPingManager::Delegate { public: MOCK_METHOD(void, OnKeepAliveTimeout, (), (override)); MOCK_METHOD(void, OnRetransmittableOnWireTimeout, (), (override)); }; class QuicPingManagerTest : public QuicTest { public: QuicPingManagerTest() : alarms_(&connection_alarms_delegate_, alarm_factory_, arena_), manager_(Perspective::IS_CLIENT, &delegate_, &alarms_.ping_alarm()), alarm_(static_cast<MockAlarmFactory::TestAlarm*>( QuicPingManagerPeer::GetAlarm(&manager_))) { clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1)); ON_CALL(connection_alarms_delegate_, OnPingAlarm()).WillByDefault([&] { manager_.OnAlarm(); }); } protected: testing::StrictMock<MockDelegate> delegate_; MockConnectionAlarmsDelegate connection_alarms_delegate_; MockClock clock_; QuicConnectionArena arena_; MockAlarmFactory alarm_factory_; QuicConnectionAlarms alarms_; QuicPingManager manager_; MockAlarmFactory::TestAlarm* alarm_; }; TEST_F(QuicPingManagerTest, KeepAliveTimeout) { EXPECT_FALSE(alarm_->IsSet()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs), alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs) - QuicTime::Delta::FromMilliseconds(5), alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kPingTimeoutSecs)); EXPECT_CALL(delegate_, OnKeepAliveTimeout()); alarm_->Fire(); EXPECT_FALSE(alarm_->IsSet()); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); manager_.SetAlarm(clock_.ApproximateNow(), !kShouldKeepAlive, kHasInflightPackets); EXPECT_FALSE(alarm_->IsSet()); } TEST_F(QuicPingManagerTest, CustomizedKeepAliveTimeout) { EXPECT_FALSE(alarm_->IsSet()); manager_.set_keep_alive_timeout(QuicTime::Delta::FromSeconds(10)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(10), alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ( QuicTime::Delta::FromSeconds(10) - QuicTime::Delta::FromMilliseconds(5), alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10)); EXPECT_CALL(delegate_, OnKeepAliveTimeout()); alarm_->Fire(); EXPECT_FALSE(alarm_->IsSet()); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); manager_.SetAlarm(clock_.ApproximateNow(), !kShouldKeepAlive, kHasInflightPackets); EXPECT_FALSE(alarm_->IsSet()); } TEST_F(QuicPingManagerTest, RetransmittableOnWireTimeout) { const QuicTime::Delta kRtransmittableOnWireTimeout = QuicTime::Delta::FromMilliseconds(50); manager_.set_initial_retransmittable_on_wire_timeout( kRtransmittableOnWireTimeout); EXPECT_FALSE(alarm_->IsSet()); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs), alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(kRtransmittableOnWireTimeout, alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(kRtransmittableOnWireTimeout); EXPECT_CALL(delegate_, OnRetransmittableOnWireTimeout()); alarm_->Fire(); EXPECT_FALSE(alarm_->IsSet()); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); ASSERT_TRUE(alarm_->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs), alarm_->deadline() - clock_.ApproximateNow()); } TEST_F(QuicPingManagerTest, RetransmittableOnWireTimeoutExponentiallyBackOff) { const int kMaxAggressiveRetransmittableOnWireCount = 5; SetQuicFlag(quic_max_aggressive_retransmittable_on_wire_ping_count, kMaxAggressiveRetransmittableOnWireCount); const QuicTime::Delta initial_retransmittable_on_wire_timeout = QuicTime::Delta::FromMilliseconds(200); manager_.set_initial_retransmittable_on_wire_timeout( initial_retransmittable_on_wire_timeout); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); EXPECT_FALSE(alarm_->IsSet()); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs), alarm_->deadline() - clock_.ApproximateNow()); for (int i = 0; i <= kMaxAggressiveRetransmittableOnWireCount; ++i) { clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(initial_retransmittable_on_wire_timeout, alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(initial_retransmittable_on_wire_timeout); EXPECT_CALL(delegate_, OnRetransmittableOnWireTimeout()); alarm_->Fire(); EXPECT_FALSE(alarm_->IsSet()); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); } QuicTime::Delta retransmittable_on_wire_timeout = initial_retransmittable_on_wire_timeout; while (retransmittable_on_wire_timeout * 2 < QuicTime::Delta::FromSeconds(kPingTimeoutSecs)) { retransmittable_on_wire_timeout = retransmittable_on_wire_timeout * 2; clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(retransmittable_on_wire_timeout, alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(retransmittable_on_wire_timeout); EXPECT_CALL(delegate_, OnRetransmittableOnWireTimeout()); alarm_->Fire(); EXPECT_FALSE(alarm_->IsSet()); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); } EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs), alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs) - QuicTime::Delta::FromMilliseconds(5), alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kPingTimeoutSecs) - QuicTime::Delta::FromMilliseconds(5)); EXPECT_CALL(delegate_, OnKeepAliveTimeout()); alarm_->Fire(); EXPECT_FALSE(alarm_->IsSet()); } TEST_F(QuicPingManagerTest, ResetRetransmitableOnWireTimeoutExponentiallyBackOff) { const int kMaxAggressiveRetransmittableOnWireCount = 3; SetQuicFlag(quic_max_aggressive_retransmittable_on_wire_ping_count, kMaxAggressiveRetransmittableOnWireCount); const QuicTime::Delta initial_retransmittable_on_wire_timeout = QuicTime::Delta::FromMilliseconds(200); manager_.set_initial_retransmittable_on_wire_timeout( initial_retransmittable_on_wire_timeout); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); EXPECT_FALSE(alarm_->IsSet()); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs), alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(initial_retransmittable_on_wire_timeout, alarm_->deadline() - clock_.ApproximateNow()); EXPECT_CALL(delegate_, OnRetransmittableOnWireTimeout()); clock_.AdvanceTime(initial_retransmittable_on_wire_timeout); alarm_->Fire(); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(initial_retransmittable_on_wire_timeout, alarm_->deadline() - clock_.ApproximateNow()); manager_.reset_consecutive_retransmittable_on_wire_count(); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_EQ(initial_retransmittable_on_wire_timeout, alarm_->deadline() - clock_.ApproximateNow()); EXPECT_CALL(delegate_, OnRetransmittableOnWireTimeout()); clock_.AdvanceTime(initial_retransmittable_on_wire_timeout); alarm_->Fire(); for (int i = 0; i < kMaxAggressiveRetransmittableOnWireCount; i++) { manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(initial_retransmittable_on_wire_timeout, alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(initial_retransmittable_on_wire_timeout); EXPECT_CALL(delegate_, OnRetransmittableOnWireTimeout()); alarm_->Fire(); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); } manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(initial_retransmittable_on_wire_timeout * 2, alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(2 * initial_retransmittable_on_wire_timeout); EXPECT_CALL(delegate_, OnRetransmittableOnWireTimeout()); alarm_->Fire(); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); manager_.reset_consecutive_retransmittable_on_wire_count(); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(initial_retransmittable_on_wire_timeout, alarm_->deadline() - clock_.ApproximateNow()); } TEST_F(QuicPingManagerTest, RetransmittableOnWireLimit) { static constexpr int kMaxRetransmittableOnWirePingCount = 3; SetQuicFlag(quic_max_retransmittable_on_wire_ping_count, kMaxRetransmittableOnWirePingCount); static constexpr QuicTime::Delta initial_retransmittable_on_wire_timeout = QuicTime::Delta::FromMilliseconds(200); static constexpr QuicTime::Delta kShortDelay = QuicTime::Delta::FromMilliseconds(5); ASSERT_LT(kShortDelay * 10, initial_retransmittable_on_wire_timeout); manager_.set_initial_retransmittable_on_wire_timeout( initial_retransmittable_on_wire_timeout); clock_.AdvanceTime(kShortDelay); EXPECT_FALSE(alarm_->IsSet()); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs), alarm_->deadline() - clock_.ApproximateNow()); for (int i = 0; i <= kMaxRetransmittableOnWirePingCount; i++) { clock_.AdvanceTime(kShortDelay); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(initial_retransmittable_on_wire_timeout, alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(initial_retransmittable_on_wire_timeout); EXPECT_CALL(delegate_, OnRetransmittableOnWireTimeout()); alarm_->Fire(); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); } manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs), alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kPingTimeoutSecs)); EXPECT_CALL(delegate_, OnKeepAliveTimeout()); alarm_->Fire(); EXPECT_FALSE(alarm_->IsSet()); } TEST_F(QuicPingManagerTest, MaxRetransmittableOnWireDelayShift) { QuicPingManagerPeer::SetPerspective(&manager_, Perspective::IS_SERVER); const int kMaxAggressiveRetransmittableOnWireCount = 3; SetQuicFlag(quic_max_aggressive_retransmittable_on_wire_ping_count, kMaxAggressiveRetransmittableOnWireCount); const QuicTime::Delta initial_retransmittable_on_wire_timeout = QuicTime::Delta::FromMilliseconds(200); manager_.set_initial_retransmittable_on_wire_timeout( initial_retransmittable_on_wire_timeout); for (int i = 0; i <= kMaxAggressiveRetransmittableOnWireCount; i++) { manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(initial_retransmittable_on_wire_timeout, alarm_->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(initial_retransmittable_on_wire_timeout); EXPECT_CALL(delegate_, OnRetransmittableOnWireTimeout()); alarm_->Fire(); manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, kHasInflightPackets); } for (int i = 1; i <= 20; ++i) { manager_.SetAlarm(clock_.ApproximateNow(), kShouldKeepAlive, !kHasInflightPackets); EXPECT_TRUE(alarm_->IsSet()); if (i <= 10) { EXPECT_EQ(initial_retransmittable_on_wire_timeout * (1 << i), alarm_->deadline() - clock_.ApproximateNow()); } else { EXPECT_EQ(initial_retransmittable_on_wire_timeout * (1 << 10), alarm_->deadline() - clock_.ApproximateNow()); } clock_.AdvanceTime(alarm_->deadline() - clock_.ApproximateNow()); EXPECT_CALL(delegate_, OnRetransmittableOnWireTimeout()); alarm_->Fire(); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_ping_manager.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_ping_manager_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
61d551f4-8228-487d-8b81-1ef3db72f442
cpp
google/quiche
quic_stream_id_manager
quiche/quic/core/quic_stream_id_manager.cc
quiche/quic/core/quic_stream_id_manager_test.cc
#include "quiche/quic/core/quic_stream_id_manager.h" #include <algorithm> #include <cstdint> #include <string> #include "absl/strings/str_cat.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_constants.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_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { #define ENDPOINT \ (perspective_ == Perspective::IS_SERVER ? " Server: " : " Client: ") QuicStreamIdManager::QuicStreamIdManager( DelegateInterface* delegate, bool unidirectional, Perspective perspective, ParsedQuicVersion version, QuicStreamCount max_allowed_outgoing_streams, QuicStreamCount max_allowed_incoming_streams) : delegate_(delegate), unidirectional_(unidirectional), perspective_(perspective), version_(version), outgoing_max_streams_(max_allowed_outgoing_streams), next_outgoing_stream_id_(GetFirstOutgoingStreamId()), outgoing_stream_count_(0), incoming_actual_max_streams_(max_allowed_incoming_streams), incoming_advertised_max_streams_(max_allowed_incoming_streams), incoming_initial_max_open_streams_(max_allowed_incoming_streams), incoming_stream_count_(0), largest_peer_created_stream_id_( QuicUtils::GetInvalidStreamId(version.transport_version)), stop_increasing_incoming_max_streams_(false) {} QuicStreamIdManager::~QuicStreamIdManager() {} bool QuicStreamIdManager::OnStreamsBlockedFrame( const QuicStreamsBlockedFrame& frame, std::string* error_details) { QUICHE_DCHECK_EQ(frame.unidirectional, unidirectional_); if (frame.stream_count > incoming_advertised_max_streams_) { *error_details = absl::StrCat( "StreamsBlockedFrame's stream count ", frame.stream_count, " exceeds incoming max stream ", incoming_advertised_max_streams_); return false; } QUICHE_DCHECK_LE(incoming_advertised_max_streams_, incoming_actual_max_streams_); if (incoming_advertised_max_streams_ == incoming_actual_max_streams_) { return true; } if (frame.stream_count < incoming_actual_max_streams_ && delegate_->CanSendMaxStreams()) { SendMaxStreamsFrame(); } return true; } bool QuicStreamIdManager::MaybeAllowNewOutgoingStreams( QuicStreamCount max_open_streams) { if (max_open_streams <= outgoing_max_streams_) { return false; } outgoing_max_streams_ = std::min(max_open_streams, QuicUtils::GetMaxStreamCount()); return true; } void QuicStreamIdManager::SetMaxOpenIncomingStreams( QuicStreamCount max_open_streams) { QUIC_BUG_IF(quic_bug_12413_1, incoming_stream_count_ > 0) << "non-zero incoming stream count " << incoming_stream_count_ << " when setting max incoming stream to " << max_open_streams; QUIC_DLOG_IF(WARNING, incoming_initial_max_open_streams_ != max_open_streams) << absl::StrCat(unidirectional_ ? "unidirectional " : "bidirectional: ", "incoming stream limit changed from ", incoming_initial_max_open_streams_, " to ", max_open_streams); incoming_actual_max_streams_ = max_open_streams; incoming_advertised_max_streams_ = max_open_streams; incoming_initial_max_open_streams_ = max_open_streams; } void QuicStreamIdManager::MaybeSendMaxStreamsFrame() { int divisor = GetQuicFlag(quic_max_streams_window_divisor); if (divisor > 0) { if ((incoming_advertised_max_streams_ - incoming_stream_count_) > (incoming_initial_max_open_streams_ / divisor)) { return; } } if (delegate_->CanSendMaxStreams() && incoming_advertised_max_streams_ < incoming_actual_max_streams_) { SendMaxStreamsFrame(); } } void QuicStreamIdManager::SendMaxStreamsFrame() { QUIC_BUG_IF(quic_bug_12413_2, incoming_advertised_max_streams_ >= incoming_actual_max_streams_); incoming_advertised_max_streams_ = incoming_actual_max_streams_; delegate_->SendMaxStreams(incoming_advertised_max_streams_, unidirectional_); } void QuicStreamIdManager::OnStreamClosed(QuicStreamId stream_id) { QUICHE_DCHECK_NE(QuicUtils::IsBidirectionalStreamId(stream_id, version_), unidirectional_); if (QuicUtils::IsOutgoingStreamId(version_, stream_id, perspective_)) { return; } if (incoming_actual_max_streams_ == QuicUtils::GetMaxStreamCount()) { return; } if (!stop_increasing_incoming_max_streams_) { incoming_actual_max_streams_++; MaybeSendMaxStreamsFrame(); } } QuicStreamId QuicStreamIdManager::GetNextOutgoingStreamId() { QUIC_BUG_IF(quic_bug_12413_3, outgoing_stream_count_ >= outgoing_max_streams_) << "Attempt to allocate a new outgoing stream that would exceed the " "limit (" << outgoing_max_streams_ << ")"; QuicStreamId id = next_outgoing_stream_id_; next_outgoing_stream_id_ += QuicUtils::StreamIdDelta(version_.transport_version); outgoing_stream_count_++; return id; } bool QuicStreamIdManager::CanOpenNextOutgoingStream() const { QUICHE_DCHECK(VersionHasIetfQuicFrames(version_.transport_version)); return outgoing_stream_count_ < outgoing_max_streams_; } bool QuicStreamIdManager::MaybeIncreaseLargestPeerStreamId( const QuicStreamId stream_id, std::string* error_details) { QUICHE_DCHECK_NE(QuicUtils::IsBidirectionalStreamId(stream_id, version_), unidirectional_); QUICHE_DCHECK_NE(QuicUtils::IsServerInitiatedStreamId( version_.transport_version, stream_id), perspective_ == Perspective::IS_SERVER); if (available_streams_.erase(stream_id) == 1) { return true; } if (largest_peer_created_stream_id_ != QuicUtils::GetInvalidStreamId(version_.transport_version)) { QUICHE_DCHECK_GT(stream_id, largest_peer_created_stream_id_); } const QuicStreamCount delta = QuicUtils::StreamIdDelta(version_.transport_version); const QuicStreamId least_new_stream_id = largest_peer_created_stream_id_ == QuicUtils::GetInvalidStreamId(version_.transport_version) ? GetFirstIncomingStreamId() : largest_peer_created_stream_id_ + delta; const QuicStreamCount stream_count_increment = (stream_id - least_new_stream_id) / delta + 1; if (incoming_stream_count_ + stream_count_increment > incoming_advertised_max_streams_) { QUIC_DLOG(INFO) << ENDPOINT << "Failed to create a new incoming stream with id:" << stream_id << ", reaching MAX_STREAMS limit: " << incoming_advertised_max_streams_ << "."; *error_details = absl::StrCat("Stream id ", stream_id, " would exceed stream count limit ", incoming_advertised_max_streams_); return false; } for (QuicStreamId id = least_new_stream_id; id < stream_id; id += delta) { available_streams_.insert(id); } incoming_stream_count_ += stream_count_increment; largest_peer_created_stream_id_ = stream_id; return true; } bool QuicStreamIdManager::IsAvailableStream(QuicStreamId id) const { QUICHE_DCHECK_NE(QuicUtils::IsBidirectionalStreamId(id, version_), unidirectional_); if (QuicUtils::IsOutgoingStreamId(version_, id, perspective_)) { return id >= next_outgoing_stream_id_; } return largest_peer_created_stream_id_ == QuicUtils::GetInvalidStreamId(version_.transport_version) || id > largest_peer_created_stream_id_ || available_streams_.contains(id); } QuicStreamId QuicStreamIdManager::GetFirstOutgoingStreamId() const { return (unidirectional_) ? QuicUtils::GetFirstUnidirectionalStreamId( version_.transport_version, perspective_) : QuicUtils::GetFirstBidirectionalStreamId( version_.transport_version, perspective_); } QuicStreamId QuicStreamIdManager::GetFirstIncomingStreamId() const { return (unidirectional_) ? QuicUtils::GetFirstUnidirectionalStreamId( version_.transport_version, QuicUtils::InvertPerspective(perspective_)) : QuicUtils::GetFirstBidirectionalStreamId( version_.transport_version, QuicUtils::InvertPerspective(perspective_)); } QuicStreamCount QuicStreamIdManager::available_incoming_streams() const { return incoming_advertised_max_streams_ - incoming_stream_count_; } }
#include "quiche/quic/core/quic_stream_id_manager.h" #include <cstdint> #include <string> #include <utility> #include <vector> #include "absl/strings/str_cat.h" #include "quiche/quic/core/quic_constants.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_test.h" #include "quiche/quic/test_tools/quic_stream_id_manager_peer.h" using testing::_; using testing::StrictMock; namespace quic { namespace test { namespace { class MockDelegate : public QuicStreamIdManager::DelegateInterface { public: MOCK_METHOD(void, SendMaxStreams, (QuicStreamCount stream_count, bool unidirectional), (override)); MOCK_METHOD(bool, CanSendMaxStreams, (), (override)); }; struct TestParams { TestParams(ParsedQuicVersion version, Perspective perspective, bool is_unidirectional) : version(version), perspective(perspective), is_unidirectional(is_unidirectional) {} ParsedQuicVersion version; Perspective perspective; bool is_unidirectional; }; std::string PrintToString(const TestParams& p) { return absl::StrCat( ParsedQuicVersionToString(p.version), "_", (p.perspective == Perspective::IS_CLIENT ? "Client" : "Server"), (p.is_unidirectional ? "Unidirectional" : "Bidirectional")); } std::vector<TestParams> GetTestParams() { std::vector<TestParams> params; for (const ParsedQuicVersion& version : AllSupportedVersions()) { if (!version.HasIetfQuicFrames()) { continue; } for (Perspective perspective : {Perspective::IS_CLIENT, Perspective::IS_SERVER}) { for (bool is_unidirectional : {true, false}) { params.push_back(TestParams(version, perspective, is_unidirectional)); } } } return params; } class QuicStreamIdManagerTest : public QuicTestWithParam<TestParams> { protected: QuicStreamIdManagerTest() : stream_id_manager_(&delegate_, IsUnidirectional(), perspective(), GetParam().version, 0, kDefaultMaxStreamsPerConnection) { QUICHE_DCHECK(VersionHasIetfQuicFrames(transport_version())); } QuicTransportVersion transport_version() const { return GetParam().version.transport_version; } QuicStreamId GetNthIncomingStreamId(int n) { return QuicUtils::StreamIdDelta(transport_version()) * n + (IsUnidirectional() ? QuicUtils::GetFirstUnidirectionalStreamId( transport_version(), QuicUtils::InvertPerspective(perspective())) : QuicUtils::GetFirstBidirectionalStreamId( transport_version(), QuicUtils::InvertPerspective(perspective()))); } bool IsUnidirectional() { return GetParam().is_unidirectional; } Perspective perspective() { return GetParam().perspective; } StrictMock<MockDelegate> delegate_; QuicStreamIdManager stream_id_manager_; }; INSTANTIATE_TEST_SUITE_P(Tests, QuicStreamIdManagerTest, ::testing::ValuesIn(GetTestParams()), ::testing::PrintToStringParamName()); TEST_P(QuicStreamIdManagerTest, Initialization) { EXPECT_EQ(0u, stream_id_manager_.outgoing_max_streams()); EXPECT_EQ(kDefaultMaxStreamsPerConnection, stream_id_manager_.incoming_actual_max_streams()); EXPECT_EQ(kDefaultMaxStreamsPerConnection, stream_id_manager_.incoming_advertised_max_streams()); EXPECT_EQ(kDefaultMaxStreamsPerConnection, stream_id_manager_.incoming_initial_max_open_streams()); } TEST_P(QuicStreamIdManagerTest, CheckMaxStreamsWindowForSingleStream) { stream_id_manager_.SetMaxOpenIncomingStreams(1); EXPECT_EQ(1u, stream_id_manager_.incoming_initial_max_open_streams()); EXPECT_EQ(1u, stream_id_manager_.incoming_actual_max_streams()); } TEST_P(QuicStreamIdManagerTest, CheckMaxStreamsBadValuesOverMaxFailsOutgoing) { QuicStreamCount implementation_max = QuicUtils::GetMaxStreamCount(); EXPECT_LT(stream_id_manager_.outgoing_max_streams(), implementation_max); EXPECT_TRUE( stream_id_manager_.MaybeAllowNewOutgoingStreams(implementation_max + 1)); EXPECT_EQ(implementation_max, stream_id_manager_.outgoing_max_streams()); } TEST_P(QuicStreamIdManagerTest, ProcessStreamsBlockedOk) { QuicStreamCount stream_count = stream_id_manager_.incoming_initial_max_open_streams(); QuicStreamsBlockedFrame frame(0, stream_count - 1, IsUnidirectional()); EXPECT_CALL(delegate_, SendMaxStreams(stream_count, IsUnidirectional())) .Times(0); std::string error_details; EXPECT_TRUE(stream_id_manager_.OnStreamsBlockedFrame(frame, &error_details)); } TEST_P(QuicStreamIdManagerTest, ProcessStreamsBlockedNoOp) { QuicStreamCount stream_count = stream_id_manager_.incoming_initial_max_open_streams(); QuicStreamsBlockedFrame frame(0, stream_count, IsUnidirectional()); EXPECT_CALL(delegate_, SendMaxStreams(_, _)).Times(0); } TEST_P(QuicStreamIdManagerTest, ProcessStreamsBlockedTooBig) { EXPECT_CALL(delegate_, SendMaxStreams(_, _)).Times(0); QuicStreamCount stream_count = stream_id_manager_.incoming_initial_max_open_streams() + 1; QuicStreamsBlockedFrame frame(0, stream_count, IsUnidirectional()); std::string error_details; EXPECT_FALSE(stream_id_manager_.OnStreamsBlockedFrame(frame, &error_details)); EXPECT_EQ( error_details, "StreamsBlockedFrame's stream count 101 exceeds incoming max stream 100"); } TEST_P(QuicStreamIdManagerTest, IsIncomingStreamIdValidBelowLimit) { QuicStreamId stream_id = GetNthIncomingStreamId( stream_id_manager_.incoming_actual_max_streams() - 2); EXPECT_TRUE( stream_id_manager_.MaybeIncreaseLargestPeerStreamId(stream_id, nullptr)); } TEST_P(QuicStreamIdManagerTest, IsIncomingStreamIdValidAtLimit) { QuicStreamId stream_id = GetNthIncomingStreamId( stream_id_manager_.incoming_actual_max_streams() - 1); EXPECT_TRUE( stream_id_manager_.MaybeIncreaseLargestPeerStreamId(stream_id, nullptr)); } TEST_P(QuicStreamIdManagerTest, IsIncomingStreamIdInValidAboveLimit) { QuicStreamId stream_id = GetNthIncomingStreamId(stream_id_manager_.incoming_actual_max_streams()); std::string error_details; EXPECT_FALSE(stream_id_manager_.MaybeIncreaseLargestPeerStreamId( stream_id, &error_details)); EXPECT_EQ(error_details, absl::StrCat("Stream id ", stream_id, " would exceed stream count limit 100")); } TEST_P(QuicStreamIdManagerTest, OnStreamsBlockedFrame) { QuicStreamCount advertised_stream_count = stream_id_manager_.incoming_advertised_max_streams(); QuicStreamsBlockedFrame frame; frame.unidirectional = IsUnidirectional(); frame.stream_count = advertised_stream_count; std::string error_details; EXPECT_TRUE(stream_id_manager_.OnStreamsBlockedFrame(frame, &error_details)); frame.stream_count = advertised_stream_count + 1; EXPECT_FALSE(stream_id_manager_.OnStreamsBlockedFrame(frame, &error_details)); EXPECT_EQ( error_details, "StreamsBlockedFrame's stream count 101 exceeds incoming max stream 100"); QuicStreamCount actual_stream_count = stream_id_manager_.incoming_actual_max_streams(); stream_id_manager_.OnStreamClosed( QuicStreamIdManagerPeer::GetFirstIncomingStreamId(&stream_id_manager_)); EXPECT_EQ(actual_stream_count + 1u, stream_id_manager_.incoming_actual_max_streams()); EXPECT_EQ(stream_id_manager_.incoming_actual_max_streams(), stream_id_manager_.incoming_advertised_max_streams() + 1u); frame.stream_count = advertised_stream_count; EXPECT_CALL(delegate_, CanSendMaxStreams()).WillOnce(testing::Return(true)); EXPECT_CALL(delegate_, SendMaxStreams(stream_id_manager_.incoming_actual_max_streams(), IsUnidirectional())); EXPECT_TRUE(stream_id_manager_.OnStreamsBlockedFrame(frame, &error_details)); EXPECT_EQ(stream_id_manager_.incoming_actual_max_streams(), stream_id_manager_.incoming_advertised_max_streams()); } TEST_P(QuicStreamIdManagerTest, OnStreamsBlockedFrameCantSend) { QuicStreamCount advertised_stream_count = stream_id_manager_.incoming_advertised_max_streams(); QuicStreamsBlockedFrame frame; frame.unidirectional = IsUnidirectional(); QuicStreamCount actual_stream_count = stream_id_manager_.incoming_actual_max_streams(); stream_id_manager_.OnStreamClosed( QuicStreamIdManagerPeer::GetFirstIncomingStreamId(&stream_id_manager_)); EXPECT_EQ(actual_stream_count + 1u, stream_id_manager_.incoming_actual_max_streams()); EXPECT_EQ(stream_id_manager_.incoming_actual_max_streams(), stream_id_manager_.incoming_advertised_max_streams() + 1u); frame.stream_count = advertised_stream_count; EXPECT_CALL(delegate_, CanSendMaxStreams()).WillOnce(testing::Return(false)); EXPECT_CALL(delegate_, SendMaxStreams(_, _)).Times(0); const QuicStreamCount advertised_max_streams = stream_id_manager_.incoming_advertised_max_streams(); std::string error_details; EXPECT_TRUE(stream_id_manager_.OnStreamsBlockedFrame(frame, &error_details)); EXPECT_EQ(advertised_max_streams, stream_id_manager_.incoming_advertised_max_streams()); } TEST_P(QuicStreamIdManagerTest, GetNextOutgoingStream) { size_t number_of_streams = kDefaultMaxStreamsPerConnection; EXPECT_TRUE( stream_id_manager_.MaybeAllowNewOutgoingStreams(number_of_streams)); QuicStreamId stream_id = IsUnidirectional() ? QuicUtils::GetFirstUnidirectionalStreamId( transport_version(), perspective()) : QuicUtils::GetFirstBidirectionalStreamId( transport_version(), perspective()); EXPECT_EQ(number_of_streams, stream_id_manager_.outgoing_max_streams()); while (number_of_streams) { EXPECT_TRUE(stream_id_manager_.CanOpenNextOutgoingStream()); EXPECT_EQ(stream_id, stream_id_manager_.GetNextOutgoingStreamId()); stream_id += QuicUtils::StreamIdDelta(transport_version()); number_of_streams--; } EXPECT_FALSE(stream_id_manager_.CanOpenNextOutgoingStream()); EXPECT_QUIC_BUG( stream_id_manager_.GetNextOutgoingStreamId(), "Attempt to allocate a new outgoing stream that would exceed the limit"); } TEST_P(QuicStreamIdManagerTest, MaybeIncreaseLargestPeerStreamId) { QuicStreamId max_stream_id = GetNthIncomingStreamId( stream_id_manager_.incoming_actual_max_streams() - 1); EXPECT_TRUE(stream_id_manager_.MaybeIncreaseLargestPeerStreamId(max_stream_id, nullptr)); QuicStreamId first_stream_id = GetNthIncomingStreamId(0); EXPECT_TRUE(stream_id_manager_.MaybeIncreaseLargestPeerStreamId( first_stream_id, nullptr)); std::string error_details; EXPECT_FALSE(stream_id_manager_.MaybeIncreaseLargestPeerStreamId( max_stream_id + QuicUtils::StreamIdDelta(transport_version()), &error_details)); EXPECT_EQ(error_details, absl::StrCat( "Stream id ", max_stream_id + QuicUtils::StreamIdDelta(transport_version()), " would exceed stream count limit 100")); } TEST_P(QuicStreamIdManagerTest, MaxStreamsWindow) { int stream_count = stream_id_manager_.incoming_initial_max_open_streams() / GetQuicFlag(quic_max_streams_window_divisor) - 1; EXPECT_CALL(delegate_, CanSendMaxStreams()).Times(0); EXPECT_CALL(delegate_, SendMaxStreams(_, _)).Times(0); QuicStreamId stream_id = GetNthIncomingStreamId(0); size_t old_available_incoming_streams = stream_id_manager_.available_incoming_streams(); auto i = stream_count; while (i) { EXPECT_TRUE(stream_id_manager_.MaybeIncreaseLargestPeerStreamId(stream_id, nullptr)); old_available_incoming_streams--; EXPECT_EQ(old_available_incoming_streams, stream_id_manager_.available_incoming_streams()); i--; stream_id += QuicUtils::StreamIdDelta(transport_version()); } stream_id = GetNthIncomingStreamId(0); QuicStreamCount expected_actual_max = stream_id_manager_.incoming_actual_max_streams(); QuicStreamCount expected_advertised_max_streams = stream_id_manager_.incoming_advertised_max_streams(); while (stream_count) { stream_id_manager_.OnStreamClosed(stream_id); stream_count--; stream_id += QuicUtils::StreamIdDelta(transport_version()); expected_actual_max++; EXPECT_EQ(expected_actual_max, stream_id_manager_.incoming_actual_max_streams()); EXPECT_EQ(expected_advertised_max_streams, stream_id_manager_.incoming_advertised_max_streams()); } EXPECT_EQ(old_available_incoming_streams, stream_id_manager_.available_incoming_streams()); EXPECT_CALL(delegate_, CanSendMaxStreams()).WillOnce(testing::Return(true)); EXPECT_CALL(delegate_, SendMaxStreams(_, IsUnidirectional())); EXPECT_TRUE( stream_id_manager_.MaybeIncreaseLargestPeerStreamId(stream_id, nullptr)); stream_id_manager_.OnStreamClosed(stream_id); } TEST_P(QuicStreamIdManagerTest, MaxStreamsWindowCantSend) { int stream_count = stream_id_manager_.incoming_initial_max_open_streams() / GetQuicFlag(quic_max_streams_window_divisor) - 1; EXPECT_CALL(delegate_, CanSendMaxStreams()).Times(0); EXPECT_CALL(delegate_, SendMaxStreams(_, _)).Times(0); QuicStreamId stream_id = GetNthIncomingStreamId(0); size_t old_available_incoming_streams = stream_id_manager_.available_incoming_streams(); auto i = stream_count; while (i) { EXPECT_TRUE(stream_id_manager_.MaybeIncreaseLargestPeerStreamId(stream_id, nullptr)); old_available_incoming_streams--; EXPECT_EQ(old_available_incoming_streams, stream_id_manager_.available_incoming_streams()); i--; stream_id += QuicUtils::StreamIdDelta(transport_version()); } stream_id = GetNthIncomingStreamId(0); QuicStreamCount expected_actual_max = stream_id_manager_.incoming_actual_max_streams(); QuicStreamCount expected_advertised_max_streams = stream_id_manager_.incoming_advertised_max_streams(); while (stream_count) { stream_id_manager_.OnStreamClosed(stream_id); stream_count--; stream_id += QuicUtils::StreamIdDelta(transport_version()); expected_actual_max++; EXPECT_EQ(expected_actual_max, stream_id_manager_.incoming_actual_max_streams()); EXPECT_EQ(expected_advertised_max_streams, stream_id_manager_.incoming_advertised_max_streams()); } EXPECT_EQ(old_available_incoming_streams, stream_id_manager_.available_incoming_streams()); EXPECT_CALL(delegate_, CanSendMaxStreams()).WillOnce(testing::Return(false)); EXPECT_CALL(delegate_, SendMaxStreams(_, IsUnidirectional())).Times(0); EXPECT_TRUE( stream_id_manager_.MaybeIncreaseLargestPeerStreamId(stream_id, nullptr)); stream_id_manager_.OnStreamClosed(stream_id); EXPECT_EQ(expected_advertised_max_streams, stream_id_manager_.incoming_advertised_max_streams()); } TEST_P(QuicStreamIdManagerTest, MaxStreamsWindowStopsIncreasing) { QuicStreamId stream_count = stream_id_manager_.incoming_initial_max_open_streams(); QuicStreamId stream_id = GetNthIncomingStreamId(0); for (QuicStreamCount i = 0; i < stream_count; ++i) { EXPECT_TRUE(stream_id_manager_.MaybeIncreaseLargestPeerStreamId(stream_id, nullptr)); stream_id += QuicUtils::StreamIdDelta(transport_version()); } stream_id_manager_.StopIncreasingIncomingMaxStreams(); EXPECT_CALL(delegate_, CanSendMaxStreams()).Times(0); EXPECT_CALL(delegate_, SendMaxStreams(_, _)).Times(0); stream_id = GetNthIncomingStreamId(0); QuicStreamCount expected_actual_max = stream_id_manager_.incoming_actual_max_streams(); QuicStreamCount expected_advertised_max_streams = stream_id_manager_.incoming_advertised_max_streams(); for (QuicStreamCount i = 0; i < stream_count; ++i) { stream_id_manager_.OnStreamClosed(stream_id); stream_id += QuicUtils::StreamIdDelta(transport_version()); EXPECT_EQ(expected_actual_max, stream_id_manager_.incoming_actual_max_streams()); EXPECT_EQ(expected_advertised_max_streams, stream_id_manager_.incoming_advertised_max_streams()); } } TEST_P(QuicStreamIdManagerTest, StreamsBlockedEdgeConditions) { QuicStreamsBlockedFrame frame; frame.unidirectional = IsUnidirectional(); EXPECT_CALL(delegate_, CanSendMaxStreams()).Times(0); EXPECT_CALL(delegate_, SendMaxStreams(_, _)).Times(0); stream_id_manager_.SetMaxOpenIncomingStreams(0); frame.stream_count = 0; std::string error_details; EXPECT_TRUE(stream_id_manager_.OnStreamsBlockedFrame(frame, &error_details)); EXPECT_CALL(delegate_, CanSendMaxStreams()).WillOnce(testing::Return(true)); EXPECT_CALL(delegate_, SendMaxStreams(123u, IsUnidirectional())); QuicStreamIdManagerPeer::set_incoming_actual_max_streams(&stream_id_manager_, 123); frame.stream_count = 0; EXPECT_TRUE(stream_id_manager_.OnStreamsBlockedFrame(frame, &error_details)); } TEST_P(QuicStreamIdManagerTest, MaxStreamsSlidingWindow) { QuicStreamCount first_advert = stream_id_manager_.incoming_advertised_max_streams(); int i = static_cast<int>(stream_id_manager_.incoming_initial_max_open_streams() / GetQuicFlag(quic_max_streams_window_divisor)); QuicStreamId id = QuicStreamIdManagerPeer::GetFirstIncomingStreamId(&stream_id_manager_); EXPECT_CALL(delegate_, CanSendMaxStreams()).WillOnce(testing::Return(true)); EXPECT_CALL(delegate_, SendMaxStreams(first_advert + i, IsUnidirectional())); while (i) { EXPECT_TRUE( stream_id_manager_.MaybeIncreaseLargestPeerStreamId(id, nullptr)); stream_id_manager_.OnStreamClosed(id); i--; id += QuicUtils::StreamIdDelta(transport_version()); } } TEST_P(QuicStreamIdManagerTest, NewStreamDoesNotExceedLimit) { EXPECT_TRUE(stream_id_manager_.MaybeAllowNewOutgoingStreams(100)); size_t stream_count = stream_id_manager_.outgoing_max_streams(); EXPECT_NE(0u, stream_count); while (stream_count) { EXPECT_TRUE(stream_id_manager_.CanOpenNextOutgoingStream()); stream_id_manager_.GetNextOutgoingStreamId(); stream_count--; } EXPECT_EQ(stream_id_manager_.outgoing_stream_count(), stream_id_manager_.outgoing_max_streams()); EXPECT_FALSE(stream_id_manager_.CanOpenNextOutgoingStream()); } TEST_P(QuicStreamIdManagerTest, AvailableStreams) { stream_id_manager_.MaybeIncreaseLargestPeerStreamId(GetNthIncomingStreamId(3), nullptr); EXPECT_TRUE(stream_id_manager_.IsAvailableStream(GetNthIncomingStreamId(1))); EXPECT_TRUE(stream_id_manager_.IsAvailableStream(GetNthIncomingStreamId(2))); EXPECT_FALSE(stream_id_manager_.IsAvailableStream(GetNthIncomingStreamId(3))); EXPECT_TRUE(stream_id_manager_.IsAvailableStream(GetNthIncomingStreamId(4))); } TEST_P(QuicStreamIdManagerTest, ExtremeMaybeIncreaseLargestPeerStreamId) { QuicStreamId too_big_stream_id = GetNthIncomingStreamId( stream_id_manager_.incoming_actual_max_streams() + 20); std::string error_details; EXPECT_FALSE(stream_id_manager_.MaybeIncreaseLargestPeerStreamId( too_big_stream_id, &error_details)); EXPECT_EQ(error_details, absl::StrCat("Stream id ", too_big_stream_id, " would exceed stream count limit 100")); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_stream_id_manager.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_stream_id_manager_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
0f8193a5-8939-4a01-a117-059df31d3aab
cpp
google/quiche
quic_received_packet_manager
quiche/quic/core/quic_received_packet_manager.cc
quiche/quic/core/quic_received_packet_manager_test.cc
#include "quiche/quic/core/quic_received_packet_manager.h" #include <algorithm> #include <limits> #include <utility> #include "quiche/quic/core/congestion_control/rtt_stats.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/quic_config.h" #include "quiche/quic/core/quic_connection_stats.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 { const size_t kMaxPacketsAfterNewMissing = 4; const float kShortAckDecimationDelay = 0.125; } QuicReceivedPacketManager::QuicReceivedPacketManager() : QuicReceivedPacketManager(nullptr) {} QuicReceivedPacketManager::QuicReceivedPacketManager(QuicConnectionStats* stats) : ack_frame_updated_(false), max_ack_ranges_(0), time_largest_observed_(QuicTime::Zero()), save_timestamps_(false), save_timestamps_for_in_order_packets_(false), stats_(stats), num_retransmittable_packets_received_since_last_ack_sent_(0), min_received_before_ack_decimation_(kMinReceivedBeforeAckDecimation), ack_frequency_(kDefaultRetransmittablePacketsBeforeAck), ack_decimation_delay_(GetQuicFlag(quic_ack_decimation_delay)), unlimited_ack_decimation_(false), one_immediate_ack_(false), ignore_order_(false), local_max_ack_delay_( QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs())), ack_timeout_(QuicTime::Zero()), time_of_previous_received_packet_(QuicTime::Zero()), was_last_packet_missing_(false), last_ack_frequency_frame_sequence_number_(-1) {} QuicReceivedPacketManager::~QuicReceivedPacketManager() {} void QuicReceivedPacketManager::SetFromConfig(const QuicConfig& config, Perspective perspective) { if (config.HasClientSentConnectionOption(kAKD3, perspective)) { ack_decimation_delay_ = kShortAckDecimationDelay; } if (config.HasClientSentConnectionOption(kAKDU, perspective)) { unlimited_ack_decimation_ = true; } if (config.HasClientSentConnectionOption(k1ACK, perspective)) { one_immediate_ack_ = true; } } void QuicReceivedPacketManager::RecordPacketReceived( const QuicPacketHeader& header, QuicTime receipt_time, const QuicEcnCodepoint ecn) { const QuicPacketNumber packet_number = header.packet_number; QUICHE_DCHECK(IsAwaitingPacket(packet_number)) << " packet_number:" << packet_number; was_last_packet_missing_ = IsMissing(packet_number); if (!ack_frame_updated_) { ack_frame_.received_packet_times.clear(); } ack_frame_updated_ = true; bool packet_reordered = false; if (LargestAcked(ack_frame_).IsInitialized() && LargestAcked(ack_frame_) > packet_number) { packet_reordered = true; ++stats_->packets_reordered; stats_->max_sequence_reordering = std::max(stats_->max_sequence_reordering, LargestAcked(ack_frame_) - packet_number); int64_t reordering_time_us = (receipt_time - time_largest_observed_).ToMicroseconds(); stats_->max_time_reordering_us = std::max(stats_->max_time_reordering_us, reordering_time_us); } if (!LargestAcked(ack_frame_).IsInitialized() || packet_number > LargestAcked(ack_frame_)) { ack_frame_.largest_acked = packet_number; time_largest_observed_ = receipt_time; } ack_frame_.packets.Add(packet_number); MaybeTrimAckRanges(); if (save_timestamps_) { if (save_timestamps_for_in_order_packets_ && packet_reordered) { QUIC_DLOG(WARNING) << "Not saving receive timestamp for packet " << packet_number; } else if (!ack_frame_.received_packet_times.empty() && ack_frame_.received_packet_times.back().second > receipt_time) { QUIC_LOG(WARNING) << "Receive time went backwards from: " << ack_frame_.received_packet_times.back().second.ToDebuggingValue() << " to " << receipt_time.ToDebuggingValue(); } else { ack_frame_.received_packet_times.push_back( std::make_pair(packet_number, receipt_time)); } } if (ecn != ECN_NOT_ECT) { if (!ack_frame_.ecn_counters.has_value()) { ack_frame_.ecn_counters = QuicEcnCounts(); } switch (ecn) { case ECN_NOT_ECT: QUICHE_NOTREACHED(); break; case ECN_ECT0: ack_frame_.ecn_counters->ect0++; break; case ECN_ECT1: ack_frame_.ecn_counters->ect1++; break; case ECN_CE: ack_frame_.ecn_counters->ce++; break; } } if (least_received_packet_number_.IsInitialized()) { least_received_packet_number_ = std::min(least_received_packet_number_, packet_number); } else { least_received_packet_number_ = packet_number; } } void QuicReceivedPacketManager::MaybeTrimAckRanges() { while (max_ack_ranges_ > 0 && ack_frame_.packets.NumIntervals() > max_ack_ranges_) { ack_frame_.packets.RemoveSmallestInterval(); } } bool QuicReceivedPacketManager::IsMissing(QuicPacketNumber packet_number) { return LargestAcked(ack_frame_).IsInitialized() && packet_number < LargestAcked(ack_frame_) && !ack_frame_.packets.Contains(packet_number); } bool QuicReceivedPacketManager::IsAwaitingPacket( QuicPacketNumber packet_number) const { return quic::IsAwaitingPacket(ack_frame_, packet_number, peer_least_packet_awaiting_ack_); } const QuicFrame QuicReceivedPacketManager::GetUpdatedAckFrame( QuicTime approximate_now) { if (time_largest_observed_ == QuicTime::Zero()) { ack_frame_.ack_delay_time = QuicTime::Delta::Infinite(); } else { ack_frame_.ack_delay_time = approximate_now < time_largest_observed_ ? QuicTime::Delta::Zero() : approximate_now - time_largest_observed_; } const size_t initial_ack_ranges = ack_frame_.packets.NumIntervals(); uint64_t num_iterations = 0; while (max_ack_ranges_ > 0 && ack_frame_.packets.NumIntervals() > max_ack_ranges_) { num_iterations++; QUIC_BUG_IF(quic_rpm_too_many_ack_ranges, (num_iterations % 100000) == 0) << "Too many ack ranges to remove, possibly a dead loop. " "initial_ack_ranges:" << initial_ack_ranges << " max_ack_ranges:" << max_ack_ranges_ << ", current_ack_ranges:" << ack_frame_.packets.NumIntervals() << " num_iterations:" << num_iterations; ack_frame_.packets.RemoveSmallestInterval(); } for (auto it = ack_frame_.received_packet_times.begin(); it != ack_frame_.received_packet_times.end();) { if (LargestAcked(ack_frame_) - it->first >= std::numeric_limits<uint8_t>::max()) { it = ack_frame_.received_packet_times.erase(it); } else { ++it; } } #if QUIC_FRAME_DEBUG QuicFrame frame = QuicFrame(&ack_frame_); frame.delete_forbidden = true; return frame; #else return QuicFrame(&ack_frame_); #endif } void QuicReceivedPacketManager::DontWaitForPacketsBefore( QuicPacketNumber least_unacked) { if (!least_unacked.IsInitialized()) { return; } QUICHE_DCHECK(!peer_least_packet_awaiting_ack_.IsInitialized() || peer_least_packet_awaiting_ack_ <= least_unacked); if (!peer_least_packet_awaiting_ack_.IsInitialized() || least_unacked > peer_least_packet_awaiting_ack_) { peer_least_packet_awaiting_ack_ = least_unacked; bool packets_updated = ack_frame_.packets.RemoveUpTo(least_unacked); if (packets_updated) { ack_frame_updated_ = true; } } QUICHE_DCHECK(ack_frame_.packets.Empty() || !peer_least_packet_awaiting_ack_.IsInitialized() || ack_frame_.packets.Min() >= peer_least_packet_awaiting_ack_); } QuicTime::Delta QuicReceivedPacketManager::GetMaxAckDelay( QuicPacketNumber last_received_packet_number, const RttStats& rtt_stats) const { if (AckFrequencyFrameReceived() || last_received_packet_number < PeerFirstSendingPacketNumber() + min_received_before_ack_decimation_) { return local_max_ack_delay_; } QuicTime::Delta ack_delay = std::min( local_max_ack_delay_, rtt_stats.min_rtt() * ack_decimation_delay_); return std::max(ack_delay, kAlarmGranularity); } void QuicReceivedPacketManager::MaybeUpdateAckFrequency( QuicPacketNumber last_received_packet_number) { if (AckFrequencyFrameReceived()) { return; } if (last_received_packet_number < PeerFirstSendingPacketNumber() + min_received_before_ack_decimation_) { return; } ack_frequency_ = unlimited_ack_decimation_ ? std::numeric_limits<size_t>::max() : kMaxRetransmittablePacketsBeforeAck; } void QuicReceivedPacketManager::MaybeUpdateAckTimeout( bool should_last_packet_instigate_acks, QuicPacketNumber last_received_packet_number, QuicTime last_packet_receipt_time, QuicTime now, const RttStats* rtt_stats) { if (!ack_frame_updated_) { return; } if (!ignore_order_ && was_last_packet_missing_ && last_sent_largest_acked_.IsInitialized() && last_received_packet_number < last_sent_largest_acked_) { ack_timeout_ = now; return; } if (!should_last_packet_instigate_acks) { return; } ++num_retransmittable_packets_received_since_last_ack_sent_; MaybeUpdateAckFrequency(last_received_packet_number); if (num_retransmittable_packets_received_since_last_ack_sent_ >= ack_frequency_) { ack_timeout_ = now; return; } if (!ignore_order_ && HasNewMissingPackets()) { ack_timeout_ = now; return; } const QuicTime updated_ack_time = std::max( now, std::min(last_packet_receipt_time, now) + GetMaxAckDelay(last_received_packet_number, *rtt_stats)); if (!ack_timeout_.IsInitialized() || ack_timeout_ > updated_ack_time) { ack_timeout_ = updated_ack_time; } } void QuicReceivedPacketManager::ResetAckStates() { ack_frame_updated_ = false; ack_timeout_ = QuicTime::Zero(); num_retransmittable_packets_received_since_last_ack_sent_ = 0; last_sent_largest_acked_ = LargestAcked(ack_frame_); } bool QuicReceivedPacketManager::HasMissingPackets() const { if (ack_frame_.packets.Empty()) { return false; } if (ack_frame_.packets.NumIntervals() > 1) { return true; } return peer_least_packet_awaiting_ack_.IsInitialized() && ack_frame_.packets.Min() > peer_least_packet_awaiting_ack_; } bool QuicReceivedPacketManager::HasNewMissingPackets() const { if (one_immediate_ack_) { return HasMissingPackets() && ack_frame_.packets.LastIntervalLength() == 1; } return HasMissingPackets() && ack_frame_.packets.LastIntervalLength() <= kMaxPacketsAfterNewMissing; } bool QuicReceivedPacketManager::ack_frame_updated() const { return ack_frame_updated_; } QuicPacketNumber QuicReceivedPacketManager::GetLargestObserved() const { return LargestAcked(ack_frame_); } QuicPacketNumber QuicReceivedPacketManager::PeerFirstSendingPacketNumber() const { if (!least_received_packet_number_.IsInitialized()) { QUIC_BUG(quic_bug_10849_1) << "No packets have been received yet"; return QuicPacketNumber(1); } return least_received_packet_number_; } bool QuicReceivedPacketManager::IsAckFrameEmpty() const { return ack_frame_.packets.Empty(); } void QuicReceivedPacketManager::OnAckFrequencyFrame( const QuicAckFrequencyFrame& frame) { int64_t new_sequence_number = frame.sequence_number; if (new_sequence_number <= last_ack_frequency_frame_sequence_number_) { return; } last_ack_frequency_frame_sequence_number_ = new_sequence_number; ack_frequency_ = frame.packet_tolerance; local_max_ack_delay_ = frame.max_ack_delay; ignore_order_ = frame.ignore_order; } }
#include "quiche/quic/core/quic_received_packet_manager.h" #include <algorithm> #include <cstddef> #include <ostream> #include <vector> #include "quiche/quic/core/congestion_control/rtt_stats.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/quic_connection_stats.h" #include "quiche/quic/core/quic_constants.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/mock_clock.h" namespace quic { namespace test { class QuicReceivedPacketManagerPeer { public: static void SetOneImmediateAck(QuicReceivedPacketManager* manager, bool one_immediate_ack) { manager->one_immediate_ack_ = one_immediate_ack; } static void SetAckDecimationDelay(QuicReceivedPacketManager* manager, float ack_decimation_delay) { manager->ack_decimation_delay_ = ack_decimation_delay; } }; namespace { const bool kInstigateAck = true; const QuicTime::Delta kMinRttMs = QuicTime::Delta::FromMilliseconds(40); const QuicTime::Delta kDelayedAckTime = QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs()); class QuicReceivedPacketManagerTest : public QuicTest { protected: QuicReceivedPacketManagerTest() : received_manager_(&stats_) { clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1)); rtt_stats_.UpdateRtt(kMinRttMs, QuicTime::Delta::Zero(), QuicTime::Zero()); received_manager_.set_save_timestamps(true, false); } void RecordPacketReceipt(uint64_t packet_number) { RecordPacketReceipt(packet_number, QuicTime::Zero()); } void RecordPacketReceipt(uint64_t packet_number, QuicTime receipt_time) { RecordPacketReceipt(packet_number, receipt_time, ECN_NOT_ECT); } void RecordPacketReceipt(uint64_t packet_number, QuicTime receipt_time, QuicEcnCodepoint ecn_codepoint) { QuicPacketHeader header; header.packet_number = QuicPacketNumber(packet_number); received_manager_.RecordPacketReceived(header, receipt_time, ecn_codepoint); } bool HasPendingAck() { return received_manager_.ack_timeout().IsInitialized(); } void MaybeUpdateAckTimeout(bool should_last_packet_instigate_acks, uint64_t last_received_packet_number) { received_manager_.MaybeUpdateAckTimeout( should_last_packet_instigate_acks, QuicPacketNumber(last_received_packet_number), clock_.ApproximateNow(), clock_.ApproximateNow(), &rtt_stats_); } void CheckAckTimeout(QuicTime time) { QUICHE_DCHECK(HasPendingAck()); QUICHE_DCHECK_EQ(received_manager_.ack_timeout(), time); if (time <= clock_.ApproximateNow()) { received_manager_.ResetAckStates(); QUICHE_DCHECK(!HasPendingAck()); } } MockClock clock_; RttStats rtt_stats_; QuicConnectionStats stats_; QuicReceivedPacketManager received_manager_; }; TEST_F(QuicReceivedPacketManagerTest, DontWaitForPacketsBefore) { QuicPacketHeader header; header.packet_number = QuicPacketNumber(2u); received_manager_.RecordPacketReceived(header, QuicTime::Zero(), ECN_NOT_ECT); header.packet_number = QuicPacketNumber(7u); received_manager_.RecordPacketReceived(header, QuicTime::Zero(), ECN_NOT_ECT); EXPECT_TRUE(received_manager_.IsAwaitingPacket(QuicPacketNumber(3u))); EXPECT_TRUE(received_manager_.IsAwaitingPacket(QuicPacketNumber(6u))); received_manager_.DontWaitForPacketsBefore(QuicPacketNumber(4)); EXPECT_FALSE(received_manager_.IsAwaitingPacket(QuicPacketNumber(3u))); EXPECT_TRUE(received_manager_.IsAwaitingPacket(QuicPacketNumber(6u))); } TEST_F(QuicReceivedPacketManagerTest, GetUpdatedAckFrame) { QuicPacketHeader header; header.packet_number = QuicPacketNumber(2u); QuicTime two_ms = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(2); EXPECT_FALSE(received_manager_.ack_frame_updated()); received_manager_.RecordPacketReceived(header, two_ms, ECN_NOT_ECT); EXPECT_TRUE(received_manager_.ack_frame_updated()); QuicFrame ack = received_manager_.GetUpdatedAckFrame(QuicTime::Zero()); received_manager_.ResetAckStates(); EXPECT_FALSE(received_manager_.ack_frame_updated()); EXPECT_EQ(QuicTime::Delta::Zero(), ack.ack_frame->ack_delay_time); EXPECT_EQ(1u, ack.ack_frame->received_packet_times.size()); QuicTime four_ms = QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(4); ack = received_manager_.GetUpdatedAckFrame(four_ms); received_manager_.ResetAckStates(); EXPECT_FALSE(received_manager_.ack_frame_updated()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(2), ack.ack_frame->ack_delay_time); EXPECT_EQ(1u, ack.ack_frame->received_packet_times.size()); header.packet_number = QuicPacketNumber(999u); received_manager_.RecordPacketReceived(header, two_ms, ECN_NOT_ECT); header.packet_number = QuicPacketNumber(4u); received_manager_.RecordPacketReceived(header, two_ms, ECN_NOT_ECT); header.packet_number = QuicPacketNumber(1000u); received_manager_.RecordPacketReceived(header, two_ms, ECN_NOT_ECT); EXPECT_TRUE(received_manager_.ack_frame_updated()); ack = received_manager_.GetUpdatedAckFrame(two_ms); received_manager_.ResetAckStates(); EXPECT_FALSE(received_manager_.ack_frame_updated()); EXPECT_EQ(2u, ack.ack_frame->received_packet_times.size()); } TEST_F(QuicReceivedPacketManagerTest, UpdateReceivedConnectionStats) { EXPECT_FALSE(received_manager_.ack_frame_updated()); RecordPacketReceipt(1); EXPECT_TRUE(received_manager_.ack_frame_updated()); RecordPacketReceipt(6); RecordPacketReceipt(2, QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1)); EXPECT_EQ(4u, stats_.max_sequence_reordering); EXPECT_EQ(1000, stats_.max_time_reordering_us); EXPECT_EQ(1u, stats_.packets_reordered); } TEST_F(QuicReceivedPacketManagerTest, LimitAckRanges) { received_manager_.set_max_ack_ranges(10); EXPECT_FALSE(received_manager_.ack_frame_updated()); for (int i = 0; i < 100; ++i) { RecordPacketReceipt(1 + 2 * i); EXPECT_TRUE(received_manager_.ack_frame_updated()); received_manager_.GetUpdatedAckFrame(QuicTime::Zero()); EXPECT_GE(10u, received_manager_.ack_frame().packets.NumIntervals()); EXPECT_EQ(QuicPacketNumber(1u + 2 * i), received_manager_.ack_frame().packets.Max()); for (int j = 0; j < std::min(10, i + 1); ++j) { ASSERT_GE(i, j); EXPECT_TRUE(received_manager_.ack_frame().packets.Contains( QuicPacketNumber(1 + (i - j) * 2))); if (i > j) { EXPECT_FALSE(received_manager_.ack_frame().packets.Contains( QuicPacketNumber((i - j) * 2))); } } } } TEST_F(QuicReceivedPacketManagerTest, TrimAckRangesEarly) { const size_t kMaxAckRanges = 10; received_manager_.set_max_ack_ranges(kMaxAckRanges); for (size_t i = 0; i < kMaxAckRanges + 10; ++i) { RecordPacketReceipt(1 + 2 * i); if (i < kMaxAckRanges) { EXPECT_EQ(i + 1, received_manager_.ack_frame().packets.NumIntervals()); } else { EXPECT_EQ(kMaxAckRanges, received_manager_.ack_frame().packets.NumIntervals()); } } } TEST_F(QuicReceivedPacketManagerTest, IgnoreOutOfOrderTimestamps) { EXPECT_FALSE(received_manager_.ack_frame_updated()); RecordPacketReceipt(1, QuicTime::Zero()); EXPECT_TRUE(received_manager_.ack_frame_updated()); EXPECT_EQ(1u, received_manager_.ack_frame().received_packet_times.size()); RecordPacketReceipt(2, QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1)); EXPECT_EQ(2u, received_manager_.ack_frame().received_packet_times.size()); RecordPacketReceipt(3, QuicTime::Zero()); EXPECT_EQ(2u, received_manager_.ack_frame().received_packet_times.size()); } TEST_F(QuicReceivedPacketManagerTest, IgnoreOutOfOrderPackets) { received_manager_.set_save_timestamps(true, true); EXPECT_FALSE(received_manager_.ack_frame_updated()); RecordPacketReceipt(1, QuicTime::Zero()); EXPECT_TRUE(received_manager_.ack_frame_updated()); EXPECT_EQ(1u, received_manager_.ack_frame().received_packet_times.size()); RecordPacketReceipt(4, QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(1)); EXPECT_EQ(2u, received_manager_.ack_frame().received_packet_times.size()); RecordPacketReceipt(3, QuicTime::Zero() + QuicTime::Delta::FromMilliseconds(3)); EXPECT_EQ(2u, received_manager_.ack_frame().received_packet_times.size()); } TEST_F(QuicReceivedPacketManagerTest, HasMissingPackets) { EXPECT_QUIC_BUG(received_manager_.PeerFirstSendingPacketNumber(), "No packets have been received yet"); RecordPacketReceipt(4, QuicTime::Zero()); EXPECT_EQ(QuicPacketNumber(4), received_manager_.PeerFirstSendingPacketNumber()); EXPECT_FALSE(received_manager_.HasMissingPackets()); RecordPacketReceipt(3, QuicTime::Zero()); EXPECT_FALSE(received_manager_.HasMissingPackets()); EXPECT_EQ(QuicPacketNumber(3), received_manager_.PeerFirstSendingPacketNumber()); RecordPacketReceipt(1, QuicTime::Zero()); EXPECT_EQ(QuicPacketNumber(1), received_manager_.PeerFirstSendingPacketNumber()); EXPECT_TRUE(received_manager_.HasMissingPackets()); RecordPacketReceipt(2, QuicTime::Zero()); EXPECT_EQ(QuicPacketNumber(1), received_manager_.PeerFirstSendingPacketNumber()); EXPECT_FALSE(received_manager_.HasMissingPackets()); } TEST_F(QuicReceivedPacketManagerTest, OutOfOrderReceiptCausesAckSent) { EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(3, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 3); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); RecordPacketReceipt(5, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 5); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(6, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 6); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(2, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 2); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(1, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 1); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(7, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 7); CheckAckTimeout(clock_.ApproximateNow()); } TEST_F(QuicReceivedPacketManagerTest, OutOfOrderReceiptCausesAckSent1Ack) { QuicReceivedPacketManagerPeer::SetOneImmediateAck(&received_manager_, true); EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(3, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 3); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); RecordPacketReceipt(5, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 5); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(6, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 6); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); RecordPacketReceipt(2, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 2); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(1, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 1); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(7, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 7); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } TEST_F(QuicReceivedPacketManagerTest, OutOfOrderAckReceiptCausesNoAck) { EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(2, clock_.ApproximateNow()); MaybeUpdateAckTimeout(!kInstigateAck, 2); EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(1, clock_.ApproximateNow()); MaybeUpdateAckTimeout(!kInstigateAck, 1); EXPECT_FALSE(HasPendingAck()); } TEST_F(QuicReceivedPacketManagerTest, AckReceiptCausesAckSend) { EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(1, clock_.ApproximateNow()); MaybeUpdateAckTimeout(!kInstigateAck, 1); EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(2, clock_.ApproximateNow()); MaybeUpdateAckTimeout(!kInstigateAck, 2); EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(3, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 3); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); clock_.AdvanceTime(kDelayedAckTime); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(4, clock_.ApproximateNow()); MaybeUpdateAckTimeout(!kInstigateAck, 4); EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(5, clock_.ApproximateNow()); MaybeUpdateAckTimeout(!kInstigateAck, 5); EXPECT_FALSE(HasPendingAck()); } TEST_F(QuicReceivedPacketManagerTest, AckSentEveryNthPacket) { EXPECT_FALSE(HasPendingAck()); received_manager_.set_ack_frequency(3); for (size_t i = 1; i <= 39; ++i) { RecordPacketReceipt(i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, i); if (i % 3 == 0) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } } } TEST_F(QuicReceivedPacketManagerTest, AckDecimationReducesAcks) { EXPECT_FALSE(HasPendingAck()); received_manager_.set_min_received_before_ack_decimation(10); for (size_t i = 1; i <= 29; ++i) { RecordPacketReceipt(i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, i); if (i <= 10) { if (i % 2 == 0) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } continue; } if (i == 20) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kMinRttMs * 0.25); } } RecordPacketReceipt(30, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 30); CheckAckTimeout(clock_.ApproximateNow()); } TEST_F(QuicReceivedPacketManagerTest, SendDelayedAckDecimation) { EXPECT_FALSE(HasPendingAck()); QuicTime ack_time = clock_.ApproximateNow() + kMinRttMs * 0.25; uint64_t kFirstDecimatedPacket = 101; for (uint64_t i = 1; i < kFirstDecimatedPacket; ++i) { RecordPacketReceipt(i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, i); if (i % 2 == 0) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } } RecordPacketReceipt(kFirstDecimatedPacket, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket); CheckAckTimeout(ack_time); for (uint64_t i = 1; i < 10; ++i) { RecordPacketReceipt(kFirstDecimatedPacket + i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket + i); } CheckAckTimeout(clock_.ApproximateNow()); } TEST_F(QuicReceivedPacketManagerTest, SendDelayedAckDecimationMin1ms) { EXPECT_FALSE(HasPendingAck()); rtt_stats_.UpdateRtt(kAlarmGranularity, QuicTime::Delta::Zero(), clock_.ApproximateNow()); QuicTime ack_time = clock_.ApproximateNow() + kAlarmGranularity; uint64_t kFirstDecimatedPacket = 101; for (uint64_t i = 1; i < kFirstDecimatedPacket; ++i) { RecordPacketReceipt(i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, i); if (i % 2 == 0) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } } RecordPacketReceipt(kFirstDecimatedPacket, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket); CheckAckTimeout(ack_time); for (uint64_t i = 1; i < 10; ++i) { RecordPacketReceipt(kFirstDecimatedPacket + i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket + i); } CheckAckTimeout(clock_.ApproximateNow()); } TEST_F(QuicReceivedPacketManagerTest, SendDelayedAckDecimationUnlimitedAggregation) { EXPECT_FALSE(HasPendingAck()); QuicConfig config; QuicTagVector connection_options; connection_options.push_back(kAKDU); config.SetConnectionOptionsToSend(connection_options); received_manager_.SetFromConfig(config, Perspective::IS_CLIENT); QuicTime ack_time = clock_.ApproximateNow() + kMinRttMs * 0.25; uint64_t kFirstDecimatedPacket = 101; for (uint64_t i = 1; i < kFirstDecimatedPacket; ++i) { RecordPacketReceipt(i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, i); if (i % 2 == 0) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } } RecordPacketReceipt(kFirstDecimatedPacket, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket); CheckAckTimeout(ack_time); for (int i = 1; i <= 18; ++i) { RecordPacketReceipt(kFirstDecimatedPacket + i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket + i); } CheckAckTimeout(ack_time); } TEST_F(QuicReceivedPacketManagerTest, SendDelayedAckDecimationEighthRtt) { EXPECT_FALSE(HasPendingAck()); QuicReceivedPacketManagerPeer::SetAckDecimationDelay(&received_manager_, 0.125); QuicTime ack_time = clock_.ApproximateNow() + kMinRttMs * 0.125; uint64_t kFirstDecimatedPacket = 101; for (uint64_t i = 1; i < kFirstDecimatedPacket; ++i) { RecordPacketReceipt(i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, i); if (i % 2 == 0) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } } RecordPacketReceipt(kFirstDecimatedPacket, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket); CheckAckTimeout(ack_time); for (uint64_t i = 1; i < 10; ++i) { RecordPacketReceipt(kFirstDecimatedPacket + i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, kFirstDecimatedPacket + i); } CheckAckTimeout(clock_.ApproximateNow()); } TEST_F(QuicReceivedPacketManagerTest, UpdateMaxAckDelayAndAckFrequencyFromAckFrequencyFrame) { EXPECT_FALSE(HasPendingAck()); QuicAckFrequencyFrame frame; frame.max_ack_delay = QuicTime::Delta::FromMilliseconds(10); frame.packet_tolerance = 5; received_manager_.OnAckFrequencyFrame(frame); for (int i = 1; i <= 50; ++i) { RecordPacketReceipt(i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, i); if (i % frame.packet_tolerance == 0) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + frame.max_ack_delay); } } } TEST_F(QuicReceivedPacketManagerTest, DisableOutOfOrderAckByIgnoreOrderFromAckFrequencyFrame) { EXPECT_FALSE(HasPendingAck()); QuicAckFrequencyFrame frame; frame.max_ack_delay = kDelayedAckTime; frame.packet_tolerance = 2; frame.ignore_order = true; received_manager_.OnAckFrequencyFrame(frame); RecordPacketReceipt(4, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 4); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); RecordPacketReceipt(5, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 5); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(3, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 3); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); RecordPacketReceipt(2, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 2); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(1, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 1); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } TEST_F(QuicReceivedPacketManagerTest, DisableMissingPaketsAckByIgnoreOrderFromAckFrequencyFrame) { EXPECT_FALSE(HasPendingAck()); QuicConfig config; config.SetConnectionOptionsToSend({kAFFE}); received_manager_.SetFromConfig(config, Perspective::IS_CLIENT); QuicAckFrequencyFrame frame; frame.max_ack_delay = kDelayedAckTime; frame.packet_tolerance = 2; frame.ignore_order = true; received_manager_.OnAckFrequencyFrame(frame); RecordPacketReceipt(1, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 1); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); RecordPacketReceipt(2, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 2); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(4, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 4); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); RecordPacketReceipt(5, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 5); CheckAckTimeout(clock_.ApproximateNow()); RecordPacketReceipt(7, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 7); CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } TEST_F(QuicReceivedPacketManagerTest, AckDecimationDisabledWhenAckFrequencyFrameIsReceived) { EXPECT_FALSE(HasPendingAck()); QuicAckFrequencyFrame frame; frame.max_ack_delay = kDelayedAckTime; frame.packet_tolerance = 3; frame.ignore_order = true; received_manager_.OnAckFrequencyFrame(frame); uint64_t kFirstDecimatedPacket = 101; uint64_t FiftyPacketsAfterAckDecimation = kFirstDecimatedPacket + 50; for (uint64_t i = 1; i < FiftyPacketsAfterAckDecimation; ++i) { RecordPacketReceipt(i, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, i); if (i % 3 == 0) { CheckAckTimeout(clock_.ApproximateNow()); } else { CheckAckTimeout(clock_.ApproximateNow() + kDelayedAckTime); } } } TEST_F(QuicReceivedPacketManagerTest, UpdateAckTimeoutOnPacketReceiptTime) { EXPECT_FALSE(HasPendingAck()); QuicTime packet_receipt_time3 = clock_.ApproximateNow(); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10)); RecordPacketReceipt(3, packet_receipt_time3); received_manager_.MaybeUpdateAckTimeout( kInstigateAck, QuicPacketNumber(3), packet_receipt_time3, clock_.ApproximateNow(), &rtt_stats_); CheckAckTimeout(packet_receipt_time3 + kDelayedAckTime); RecordPacketReceipt(4, clock_.ApproximateNow()); MaybeUpdateAckTimeout(kInstigateAck, 4); CheckAckTimeout(clock_.ApproximateNow()); } TEST_F(QuicReceivedPacketManagerTest, UpdateAckTimeoutOnPacketReceiptTimeLongerQueuingTime) { EXPECT_FALSE(HasPendingAck()); QuicTime packet_receipt_time3 = clock_.ApproximateNow(); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100)); RecordPacketReceipt(3, packet_receipt_time3); received_manager_.MaybeUpdateAckTimeout( kInstigateAck, QuicPacketNumber(3), packet_receipt_time3, clock_.ApproximateNow(), &rtt_stats_); CheckAckTimeout(clock_.ApproximateNow()); } TEST_F(QuicReceivedPacketManagerTest, CountEcnPackets) { EXPECT_FALSE(HasPendingAck()); RecordPacketReceipt(3, QuicTime::Zero(), ECN_NOT_ECT); RecordPacketReceipt(4, QuicTime::Zero(), ECN_ECT0); RecordPacketReceipt(5, QuicTime::Zero(), ECN_ECT1); RecordPacketReceipt(6, QuicTime::Zero(), ECN_CE); QuicFrame ack = received_manager_.GetUpdatedAckFrame(QuicTime::Zero()); EXPECT_TRUE(ack.ack_frame->ecn_counters.has_value()); EXPECT_EQ(ack.ack_frame->ecn_counters->ect0, 1); EXPECT_EQ(ack.ack_frame->ecn_counters->ect1, 1); EXPECT_EQ(ack.ack_frame->ecn_counters->ce, 1); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_received_packet_manager.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_received_packet_manager_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
d1892025-52a7-41d5-b579-88f73051835a
cpp
google/quiche
quic_connection
quiche/quic/core/quic_connection.cc
quiche/quic/core/quic_connection_test.cc
#include "quiche/quic/core/quic_connection.h" #include <string.h> #include <sys/types.h> #include <algorithm> #include <cstddef> #include <cstdint> #include <cstdlib> #include <iterator> #include <limits> #include <memory> #include <optional> #include <ostream> #include <set> #include <string> #include <tuple> #include <utility> #include <vector> #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/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/crypto/crypto_utils.h" #include "quiche/quic/core/crypto/quic_decrypter.h" #include "quiche/quic/core/crypto/quic_encrypter.h" #include "quiche/quic/core/frames/quic_reset_stream_at_frame.h" #include "quiche/quic/core/quic_bandwidth.h" #include "quiche/quic/core/quic_config.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_packet_creator.h" #include "quiche/quic/core/quic_packet_writer.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_path_validator.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_client_stats.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_socket_address.h" #include "quiche/common/platform/api/quiche_flag_utils.h" #include "quiche/common/platform/api/quiche_testvalue.h" #include "quiche/common/quiche_text_utils.h" namespace quic { class QuicDecrypter; class QuicEncrypter; namespace { const QuicPacketCount kMaxConsecutiveNonRetransmittablePackets = 19; const int kMinReleaseTimeIntoFutureMs = 1; const size_t kMaxReceivedClientAddressSize = 20; const uint8_t kEcnPtoLimit = 2; class ScopedCoalescedPacketClearer { public: explicit ScopedCoalescedPacketClearer(QuicCoalescedPacket* coalesced) : coalesced_(coalesced) {} ~ScopedCoalescedPacketClearer() { coalesced_->Clear(); } private: QuicCoalescedPacket* coalesced_; }; bool PacketCanReplaceServerConnectionId(const QuicPacketHeader& header, Perspective perspective) { return perspective == Perspective::IS_CLIENT && header.form == IETF_QUIC_LONG_HEADER_PACKET && header.version.IsKnown() && header.version.AllowsVariableLengthConnectionIds() && (header.long_packet_type == INITIAL || header.long_packet_type == RETRY); } bool NewServerConnectionIdMightBeValid(const QuicPacketHeader& header, Perspective perspective, bool connection_id_already_replaced) { return perspective == Perspective::IS_CLIENT && header.form == IETF_QUIC_LONG_HEADER_PACKET && header.version.IsKnown() && header.version.AllowsVariableLengthConnectionIds() && header.long_packet_type == HANDSHAKE && !connection_id_already_replaced; } CongestionControlType GetDefaultCongestionControlType() { if (GetQuicReloadableFlag(quic_default_to_bbr_v2)) { return kBBRv2; } if (GetQuicReloadableFlag(quic_default_to_bbr)) { return kBBR; } return kCubicBytes; } bool ContainsNonProbingFrame(const SerializedPacket& packet) { for (const QuicFrame& frame : packet.nonretransmittable_frames) { if (!QuicUtils::IsProbingFrame(frame.type)) { return true; } } for (const QuicFrame& frame : packet.retransmittable_frames) { if (!QuicUtils::IsProbingFrame(frame.type)) { return true; } } return false; } } #define ENDPOINT \ (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ") QuicConnection::QuicConnection( QuicConnectionId server_connection_id, QuicSocketAddress initial_self_address, QuicSocketAddress initial_peer_address, QuicConnectionHelperInterface* helper, QuicAlarmFactory* alarm_factory, QuicPacketWriter* writer, bool owns_writer, Perspective perspective, const ParsedQuicVersionVector& supported_versions, ConnectionIdGeneratorInterface& generator) : framer_(supported_versions, helper->GetClock()->ApproximateNow(), perspective, server_connection_id.length()), current_packet_content_(NO_FRAMES_RECEIVED), is_current_packet_connectivity_probing_(false), has_path_challenge_in_current_packet_(false), current_effective_peer_migration_type_(NO_CHANGE), helper_(helper), alarm_factory_(alarm_factory), per_packet_options_(nullptr), writer_(writer), owns_writer_(owns_writer), encryption_level_(ENCRYPTION_INITIAL), clock_(helper->GetClock()), random_generator_(helper->GetRandomGenerator()), client_connection_id_is_set_(false), direct_peer_address_(initial_peer_address), default_path_(initial_self_address, QuicSocketAddress(), EmptyQuicConnectionId(), server_connection_id, std::nullopt), active_effective_peer_migration_type_(NO_CHANGE), support_key_update_for_connection_(false), current_packet_data_(nullptr), should_last_packet_instigate_acks_(false), max_undecryptable_packets_(0), max_tracked_packets_(GetQuicFlag(quic_max_tracked_packet_count)), idle_timeout_connection_close_behavior_( ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET), num_rtos_for_blackhole_detection_(0), uber_received_packet_manager_(&stats_), pending_retransmission_alarm_(false), defer_send_in_response_to_packets_(false), arena_(), alarms_(this, *alarm_factory_, arena_), visitor_(nullptr), debug_visitor_(nullptr), packet_creator_(server_connection_id, &framer_, random_generator_, this), last_received_packet_info_(clock_->ApproximateNow()), sent_packet_manager_(perspective, clock_, random_generator_, &stats_, GetDefaultCongestionControlType()), version_negotiated_(false), perspective_(perspective), connected_(true), can_truncate_connection_ids_(perspective == Perspective::IS_SERVER), mtu_probe_count_(0), previous_validated_mtu_(0), peer_max_packet_size_(kDefaultMaxPacketSizeTransportParam), largest_received_packet_size_(0), write_error_occurred_(false), consecutive_num_packets_with_no_retransmittable_frames_(0), max_consecutive_num_packets_with_no_retransmittable_frames_( kMaxConsecutiveNonRetransmittablePackets), bundle_retransmittable_with_pto_ack_(false), last_control_frame_id_(kInvalidControlFrameId), is_path_degrading_(false), processing_ack_frame_(false), supports_release_time_(false), release_time_into_future_(QuicTime::Delta::Zero()), blackhole_detector_(this, &alarms_.network_blackhole_detector_alarm()), idle_network_detector_(this, clock_->ApproximateNow(), &alarms_.idle_network_detector_alarm()), path_validator_(alarm_factory_, &arena_, this, random_generator_, clock_, &context_), ping_manager_(perspective, this, &alarms_.ping_alarm()), multi_port_probing_interval_(kDefaultMultiPortProbingInterval), connection_id_generator_(generator), received_client_addresses_cache_(kMaxReceivedClientAddressSize) { QUICHE_DCHECK(perspective_ == Perspective::IS_CLIENT || default_path_.self_address.IsInitialized()); QUIC_DLOG(INFO) << ENDPOINT << "Created connection with server connection ID " << server_connection_id << " and version: " << ParsedQuicVersionToString(version()); QUIC_BUG_IF(quic_bug_12714_2, !QuicUtils::IsConnectionIdValidForVersion( server_connection_id, transport_version())) << "QuicConnection: attempted to use server connection ID " << server_connection_id << " which is invalid with version " << version(); framer_.set_visitor(this); stats_.connection_creation_time = clock_->ApproximateNow(); sent_packet_manager_.SetNetworkChangeVisitor(this); SetMaxPacketLength(perspective_ == Perspective::IS_SERVER ? kDefaultServerMaxPacketSize : kDefaultMaxPacketSize); uber_received_packet_manager_.set_max_ack_ranges(255); MaybeEnableMultiplePacketNumberSpacesSupport(); QUICHE_DCHECK(perspective_ == Perspective::IS_CLIENT || supported_versions.size() == 1); InstallInitialCrypters(default_path_.server_connection_id); if (perspective_ == Perspective::IS_SERVER) { version_negotiated_ = true; } if (default_enable_5rto_blackhole_detection_) { num_rtos_for_blackhole_detection_ = 5; if (GetQuicReloadableFlag(quic_disable_server_blackhole_detection) && perspective_ == Perspective::IS_SERVER) { QUIC_RELOADABLE_FLAG_COUNT(quic_disable_server_blackhole_detection); blackhole_detection_disabled_ = true; } } if (perspective_ == Perspective::IS_CLIENT) { AddKnownServerAddress(initial_peer_address); } packet_creator_.SetDefaultPeerAddress(initial_peer_address); } void QuicConnection::InstallInitialCrypters(QuicConnectionId connection_id) { CrypterPair crypters; CryptoUtils::CreateInitialObfuscators(perspective_, version(), connection_id, &crypters); SetEncrypter(ENCRYPTION_INITIAL, std::move(crypters.encrypter)); if (version().KnowsWhichDecrypterToUse()) { InstallDecrypter(ENCRYPTION_INITIAL, std::move(crypters.decrypter)); } else { SetDecrypter(ENCRYPTION_INITIAL, std::move(crypters.decrypter)); } } QuicConnection::~QuicConnection() { QUICHE_DCHECK_GE(stats_.max_egress_mtu, long_term_mtu_); if (owns_writer_) { delete writer_; } ClearQueuedPackets(); if (stats_ .num_tls_server_zero_rtt_packets_received_after_discarding_decrypter > 0) { QUIC_CODE_COUNT_N( quic_server_received_tls_zero_rtt_packet_after_discarding_decrypter, 2, 3); } else { QUIC_CODE_COUNT_N( quic_server_received_tls_zero_rtt_packet_after_discarding_decrypter, 3, 3); } } void QuicConnection::ClearQueuedPackets() { buffered_packets_.clear(); } bool QuicConnection::ValidateConfigConnectionIds(const QuicConfig& config) { QUICHE_DCHECK(config.negotiated()); if (!version().UsesTls()) { return true; } QuicConnectionId expected_initial_source_connection_id; if (perspective_ == Perspective::IS_CLIENT) { expected_initial_source_connection_id = default_path_.server_connection_id; } else { expected_initial_source_connection_id = default_path_.client_connection_id; } if (!config.HasReceivedInitialSourceConnectionId() || config.ReceivedInitialSourceConnectionId() != expected_initial_source_connection_id) { std::string received_value; if (config.HasReceivedInitialSourceConnectionId()) { received_value = config.ReceivedInitialSourceConnectionId().ToString(); } else { received_value = "none"; } std::string error_details = absl::StrCat("Bad initial_source_connection_id: expected ", expected_initial_source_connection_id.ToString(), ", received ", received_value); CloseConnection(IETF_QUIC_PROTOCOL_VIOLATION, error_details, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return false; } if (perspective_ == Perspective::IS_CLIENT) { if (!config.HasReceivedOriginalConnectionId() || config.ReceivedOriginalConnectionId() != GetOriginalDestinationConnectionId()) { std::string received_value; if (config.HasReceivedOriginalConnectionId()) { received_value = config.ReceivedOriginalConnectionId().ToString(); } else { received_value = "none"; } std::string error_details = absl::StrCat("Bad original_destination_connection_id: expected ", GetOriginalDestinationConnectionId().ToString(), ", received ", received_value); CloseConnection(IETF_QUIC_PROTOCOL_VIOLATION, error_details, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return false; } if (retry_source_connection_id_.has_value()) { if (!config.HasReceivedRetrySourceConnectionId() || config.ReceivedRetrySourceConnectionId() != *retry_source_connection_id_) { std::string received_value; if (config.HasReceivedRetrySourceConnectionId()) { received_value = config.ReceivedRetrySourceConnectionId().ToString(); } else { received_value = "none"; } std::string error_details = absl::StrCat("Bad retry_source_connection_id: expected ", retry_source_connection_id_->ToString(), ", received ", received_value); CloseConnection(IETF_QUIC_PROTOCOL_VIOLATION, error_details, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return false; } } else { if (config.HasReceivedRetrySourceConnectionId()) { std::string error_details = absl::StrCat( "Bad retry_source_connection_id: did not receive RETRY but " "received ", config.ReceivedRetrySourceConnectionId().ToString()); CloseConnection(IETF_QUIC_PROTOCOL_VIOLATION, error_details, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return false; } } } return true; } void QuicConnection::SetFromConfig(const QuicConfig& config) { if (config.negotiated()) { if (ShouldFixTimeouts(config)) { if (!IsHandshakeComplete()) { QUIC_RELOADABLE_FLAG_COUNT_N(quic_fix_timeouts, 1, 2); SetNetworkTimeouts(config.max_time_before_crypto_handshake(), config.max_idle_time_before_crypto_handshake()); } else { QUIC_BUG(set_from_config_after_handshake_complete) << "SetFromConfig is called after Handshake complete"; } } else { SetNetworkTimeouts(QuicTime::Delta::Infinite(), config.IdleNetworkTimeout()); } idle_timeout_connection_close_behavior_ = ConnectionCloseBehavior::SILENT_CLOSE; if (perspective_ == Perspective::IS_SERVER) { idle_timeout_connection_close_behavior_ = ConnectionCloseBehavior:: SILENT_CLOSE_WITH_CONNECTION_CLOSE_PACKET_SERIALIZED; } if (config.HasClientRequestedIndependentOption(kNSLC, perspective_)) { idle_timeout_connection_close_behavior_ = ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET; } if (!ValidateConfigConnectionIds(config)) { return; } support_key_update_for_connection_ = version().UsesTls(); framer_.SetKeyUpdateSupportForConnection( support_key_update_for_connection_); } else { SetNetworkTimeouts(config.max_time_before_crypto_handshake(), config.max_idle_time_before_crypto_handshake()); } if (version().HasIetfQuicFrames() && config.HasReceivedPreferredAddressConnectionIdAndToken()) { QuicNewConnectionIdFrame frame; std::tie(frame.connection_id, frame.stateless_reset_token) = config.ReceivedPreferredAddressConnectionIdAndToken(); frame.sequence_number = 1u; frame.retire_prior_to = 0u; OnNewConnectionIdFrameInner(frame); } if (config.DisableConnectionMigration()) { active_migration_disabled_ = true; } sent_packet_manager_.SetFromConfig(config); if (perspective_ == Perspective::IS_SERVER && config.HasClientSentConnectionOption(kAFF2, perspective_)) { send_ack_frequency_on_handshake_completion_ = true; } if (config.HasReceivedBytesForConnectionId() && can_truncate_connection_ids_) { packet_creator_.SetServerConnectionIdLength( config.ReceivedBytesForConnectionId()); } max_undecryptable_packets_ = config.max_undecryptable_packets(); if (!GetQuicReloadableFlag(quic_enable_mtu_discovery_at_server)) { if (config.HasClientRequestedIndependentOption(kMTUH, perspective_)) { SetMtuDiscoveryTarget(kMtuDiscoveryTargetPacketSizeHigh); } } if (config.HasClientRequestedIndependentOption(kMTUL, perspective_)) { SetMtuDiscoveryTarget(kMtuDiscoveryTargetPacketSizeLow); } if (default_enable_5rto_blackhole_detection_) { if (config.HasClientRequestedIndependentOption(kCBHD, perspective_)) { QUIC_CODE_COUNT(quic_client_only_blackhole_detection); blackhole_detection_disabled_ = true; } if (config.HasClientSentConnectionOption(kNBHD, perspective_)) { blackhole_detection_disabled_ = true; } } if (config.HasClientRequestedIndependentOption(kFIDT, perspective_)) { idle_network_detector_.enable_shorter_idle_timeout_on_sent_packet(); } if (perspective_ == Perspective::IS_CLIENT && version().HasIetfQuicFrames()) { if (config.HasClientRequestedIndependentOption(kROWF, perspective_)) { retransmittable_on_wire_behavior_ = SEND_FIRST_FORWARD_SECURE_PACKET; } if (config.HasClientRequestedIndependentOption(kROWR, perspective_)) { retransmittable_on_wire_behavior_ = SEND_RANDOM_BYTES; } } if (config.HasClientRequestedIndependentOption(k3AFF, perspective_)) { anti_amplification_factor_ = 3; } if (config.HasClientRequestedIndependentOption(k10AF, perspective_)) { anti_amplification_factor_ = 10; } if (GetQuicReloadableFlag(quic_enable_server_on_wire_ping) && perspective_ == Perspective::IS_SERVER && config.HasClientSentConnectionOption(kSRWP, perspective_)) { QUIC_RELOADABLE_FLAG_COUNT(quic_enable_server_on_wire_ping); set_initial_retransmittable_on_wire_timeout( QuicTime::Delta::FromMilliseconds(200)); } if (debug_visitor_ != nullptr) { debug_visitor_->OnSetFromConfig(config); } uber_received_packet_manager_.SetFromConfig(config, perspective_); if (config.HasClientSentConnectionOption(k5RTO, perspective_)) { num_rtos_for_blackhole_detection_ = 5; } if (config.HasClientSentConnectionOption(k6PTO, perspective_) || config.HasClientSentConnectionOption(k7PTO, perspective_) || config.HasClientSentConnectionOption(k8PTO, perspective_)) { num_rtos_for_blackhole_detection_ = 5; } if (config.HasReceivedStatelessResetToken()) { default_path_.stateless_reset_token = config.ReceivedStatelessResetToken(); } if (config.HasReceivedAckDelayExponent()) { framer_.set_peer_ack_delay_exponent(config.ReceivedAckDelayExponent()); } if (config.HasClientSentConnectionOption(kEACK, perspective_)) { bundle_retransmittable_with_pto_ack_ = true; } if (config.HasClientSentConnectionOption(kDFER, perspective_)) { defer_send_in_response_to_packets_ = false; } if (perspective_ == Perspective::IS_CLIENT && config.HasClientSentConnectionOption(kCDFR, perspective_)) { defer_send_in_response_to_packets_ = true; } if (config.HasClientRequestedIndependentOption(kINVC, perspective_)) { send_connection_close_for_invalid_version_ = true; } if (version().HasIetfQuicFrames() && config.HasReceivedPreferredAddressConnectionIdAndToken() && config.SupportsServerPreferredAddress(perspective_)) { if (self_address().host().IsIPv4() && config.HasReceivedIPv4AlternateServerAddress()) { received_server_preferred_address_ = config.ReceivedIPv4AlternateServerAddress(); } else if (self_address().host().IsIPv6() && config.HasReceivedIPv6AlternateServerAddress()) { received_server_preferred_address_ = config.ReceivedIPv6AlternateServerAddress(); } if (received_server_preferred_address_.IsInitialized()) { QUICHE_DLOG(INFO) << ENDPOINT << "Received server preferred address: " << received_server_preferred_address_; if (config.HasClientRequestedIndependentOption(kSPA2, perspective_)) { accelerated_server_preferred_address_ = true; visitor_->OnServerPreferredAddressAvailable( received_server_preferred_address_); } } } if (config.HasReceivedMaxPacketSize()) { peer_max_packet_size_ = config.ReceivedMaxPacketSize(); packet_creator_.SetMaxPacketLength( GetLimitedMaxPacketSize(packet_creator_.max_packet_length())); } if (config.HasReceivedMaxDatagramFrameSize()) { packet_creator_.SetMaxDatagramFrameSize( config.ReceivedMaxDatagramFrameSize()); } supports_release_time_ = writer_ != nullptr && writer_->SupportsReleaseTime() && !config.HasClientSentConnectionOption(kNPCO, perspective_); if (supports_release_time_) { UpdateReleaseTimeIntoFuture(); } if (perspective_ == Perspective::IS_CLIENT && version().HasIetfQuicFrames() && config.HasClientRequestedIndependentOption(kMPQC, perspective_)) { multi_port_stats_ = std::make_unique<MultiPortStats>(); if (config.HasClientRequestedIndependentOption(kMPQM, perspective_)) { multi_port_migration_enabled_ = true; } } reliable_stream_reset_ = config.SupportsReliableStreamReset(); framer_.set_process_reset_stream_at(reliable_stream_reset_); } void QuicConnection::AddDispatcherSentPackets( absl::Span<const DispatcherSentPacket> dispatcher_sent_packets) { QUICHE_DCHECK_EQ(stats_.packets_sent, 0u); QUICHE_DCHECK_EQ(stats_.packets_sent_by_dispatcher, 0u); QUICHE_DCHECK(!sent_packet_manager_.GetLargestSentPacket().IsInitialized()); if (dispatcher_sent_packets.empty()) { return; } stats_.packets_sent_by_dispatcher = dispatcher_sent_packets.size(); for (const DispatcherSentPacket& packet : dispatcher_sent_packets) { const QuicTransmissionInfo& info = sent_packet_manager_.AddDispatcherSentPacket(packet); if (debug_visitor_ != nullptr) { debug_visitor_->OnPacketSent( packet.packet_number, info.bytes_sent, info.has_crypto_handshake, info.transmission_type, info.encryption_level, info.retransmittable_frames, {}, info.sent_time, 0); } } packet_creator_.set_packet_number( dispatcher_sent_packets.back().packet_number); } bool QuicConnection::MaybeTestLiveness() { QUICHE_DCHECK_EQ(perspective_, Perspective::IS_CLIENT); if (liveness_testing_disabled_ || encryption_level_ != ENCRYPTION_FORWARD_SECURE) { return false; } const QuicTime idle_network_deadline = idle_network_detector_.GetIdleNetworkDeadline(); if (!idle_network_deadline.IsInitialized()) { return false; } const QuicTime now = clock_->ApproximateNow(); if (now > idle_network_deadline) { QUIC_DLOG(WARNING) << "Idle network deadline has passed"; return false; } const QuicTime::Delta timeout = idle_network_deadline - now; if (2 * timeout > idle_network_detector_.idle_network_timeout()) { return false; } if (!sent_packet_manager_.IsLessThanThreePTOs(timeout)) { return false; } QUIC_LOG_EVERY_N_SEC(INFO, 60) << "Testing liveness, idle_network_timeout: " << idle_network_detector_.idle_network_timeout() << ", timeout: " << timeout << ", Pto delay: " << sent_packet_manager_.GetPtoDelay() << ", smoothed_rtt: " << sent_packet_manager_.GetRttStats()->smoothed_rtt() << ", mean deviation: " << sent_packet_manager_.GetRttStats()->mean_deviation(); SendConnectivityProbingPacket(writer_, peer_address()); return true; } void QuicConnection::ApplyConnectionOptions( const QuicTagVector& connection_options) { sent_packet_manager_.ApplyConnectionOptions(connection_options); } void QuicConnection::OnSendConnectionState( const CachedNetworkParameters& cached_network_params) { if (debug_visitor_ != nullptr) { debug_visitor_->OnSendConnectionState(cached_network_params); } } void QuicConnection::OnReceiveConnectionState( const CachedNetworkParameters& cached_network_params) { if (debug_visitor_ != nullptr) { debug_visitor_->OnReceiveConnectionState(cached_network_params); } } void QuicConnection::ResumeConnectionState( const CachedNetworkParameters& cached_network_params, bool max_bandwidth_resumption) { sent_packet_manager_.ResumeConnectionState(cached_network_params, max_bandwidth_resumption); } void QuicConnection::SetMaxPacingRate(QuicBandwidth max_pacing_rate) { sent_packet_manager_.SetMaxPacingRate(max_pacing_rate); } void QuicConnection::SetApplicationDrivenPacingRate( QuicBandwidth application_driven_pacing_rate) { sent_packet_manager_.SetApplicationDrivenPacingRate( application_driven_pacing_rate); } void QuicConnection::AdjustNetworkParameters( const SendAlgorithmInterface::NetworkParams& params) { sent_packet_manager_.AdjustNetworkParameters(params); } void QuicConnection::SetLossDetectionTuner( std::unique_ptr<LossDetectionTunerInterface> tuner) { sent_packet_manager_.SetLossDetectionTuner(std::move(tuner)); } void QuicConnection::OnConfigNegotiated() { sent_packet_manager_.OnConfigNegotiated(); if (GetQuicReloadableFlag(quic_enable_mtu_discovery_at_server) && perspective_ == Perspective::IS_SERVER) { QUIC_RELOADABLE_FLAG_COUNT(quic_enable_mtu_discovery_at_server); SetMtuDiscoveryTarget(kMtuDiscoveryTargetPacketSizeHigh); } } QuicBandwidth QuicConnection::MaxPacingRate() const { return sent_packet_manager_.MaxPacingRate(); } QuicBandwidth QuicConnection::ApplicationDrivenPacingRate() const { return sent_packet_manager_.ApplicationDrivenPacingRate(); } bool QuicConnection::SelectMutualVersion( const ParsedQuicVersionVector& available_versions) { const ParsedQuicVersionVector& supported_versions = framer_.supported_versions(); for (size_t i = 0; i < supported_versions.size(); ++i) { const ParsedQuicVersion& version = supported_versions[i]; if (std::find(available_versions.begin(), available_versions.end(), version) != available_versions.end()) { framer_.set_version(version); return true; } } return false; } void QuicConnection::OnError(QuicFramer* framer) { if (!connected_ || !last_received_packet_info_.decrypted) { return; } CloseConnection(framer->error(), framer->detailed_error(), ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); } void QuicConnection::OnPacket() { last_received_packet_info_.decrypted = false; } bool QuicConnection::OnProtocolVersionMismatch( ParsedQuicVersion received_version) { QUIC_DLOG(INFO) << ENDPOINT << "Received packet with mismatched version " << ParsedQuicVersionToString(received_version); if (perspective_ == Perspective::IS_CLIENT) { const std::string error_details = "Protocol version mismatch."; QUIC_BUG(quic_bug_10511_3) << ENDPOINT << error_details; CloseConnection(QUIC_INTERNAL_ERROR, error_details, ConnectionCloseBehavior::SILENT_CLOSE); } return false; } void QuicConnection::OnVersionNegotiationPacket( const QuicVersionNegotiationPacket& packet) { QUICHE_DCHECK_EQ(default_path_.server_connection_id, packet.connection_id); if (perspective_ == Perspective::IS_SERVER) { const std::string error_details = "Server received version negotiation packet."; QUIC_BUG(quic_bug_10511_4) << error_details; QUIC_CODE_COUNT(quic_tear_down_local_connection_on_version_negotiation); CloseConnection(QUIC_INTERNAL_ERROR, error_details, ConnectionCloseBehavior::SILENT_CLOSE); return; } if (debug_visitor_ != nullptr) { debug_visitor_->OnVersionNegotiationPacket(packet); } if (version_negotiated_) { return; } if (std::find(packet.versions.begin(), packet.versions.end(), version()) != packet.versions.end()) { const std::string error_details = absl::StrCat( "Server already supports client's version ", ParsedQuicVersionToString(version()), " and should have accepted the connection instead of sending {", ParsedQuicVersionVectorToString(packet.versions), "}."); QUIC_DLOG(WARNING) << error_details; CloseConnection(QUIC_INVALID_VERSION_NEGOTIATION_PACKET, error_details, ConnectionCloseBehavior::SILENT_CLOSE); return; } server_supported_versions_ = packet.versions; CloseConnection( QUIC_INVALID_VERSION, absl::StrCat( "Client may support one of the versions in the server's list, but " "it's going to close the connection anyway. Supported versions: {", ParsedQuicVersionVectorToString(framer_.supported_versions()), "}, peer supported versions: {", ParsedQuicVersionVectorToString(packet.versions), "}"), send_connection_close_for_invalid_version_ ? ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET : ConnectionCloseBehavior::SILENT_CLOSE); } void QuicConnection::OnRetryPacket(QuicConnectionId original_connection_id, QuicConnectionId new_connection_id, absl::string_view retry_token, absl::string_view retry_integrity_tag, absl::string_view retry_without_tag) { QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, perspective_); if (version().UsesTls()) { if (!CryptoUtils::ValidateRetryIntegrityTag( version(), default_path_.server_connection_id, retry_without_tag, retry_integrity_tag)) { QUIC_DLOG(ERROR) << "Ignoring RETRY with invalid integrity tag"; return; } } else { if (original_connection_id != default_path_.server_connection_id) { QUIC_DLOG(ERROR) << "Ignoring RETRY with original connection ID " << original_connection_id << " not matching expected " << default_path_.server_connection_id << " token " << absl::BytesToHexString(retry_token); return; } } framer_.set_drop_incoming_retry_packets(true); stats_.retry_packet_processed = true; QUIC_DLOG(INFO) << "Received RETRY, replacing connection ID " << default_path_.server_connection_id << " with " << new_connection_id << ", received token " << absl::BytesToHexString(retry_token); if (!original_destination_connection_id_.has_value()) { original_destination_connection_id_ = default_path_.server_connection_id; } QUICHE_DCHECK(!retry_source_connection_id_.has_value()) << *retry_source_connection_id_; retry_source_connection_id_ = new_connection_id; ReplaceInitialServerConnectionId(new_connection_id); packet_creator_.SetRetryToken(retry_token); InstallInitialCrypters(default_path_.server_connection_id); sent_packet_manager_.MarkInitialPacketsForRetransmission(); } void QuicConnection::SetMultiPacketClientHello() { if (debug_visitor_ != nullptr) { debug_visitor_->SetMultiPacketClientHello(); } } void QuicConnection::SetOriginalDestinationConnectionId( const QuicConnectionId& original_destination_connection_id) { QUIC_DLOG(INFO) << "Setting original_destination_connection_id to " << original_destination_connection_id << " on connection with server_connection_id " << default_path_.server_connection_id; QUICHE_DCHECK_NE(original_destination_connection_id, default_path_.server_connection_id); InstallInitialCrypters(original_destination_connection_id); QUICHE_DCHECK(!original_destination_connection_id_.has_value()) << *original_destination_connection_id_; original_destination_connection_id_ = original_destination_connection_id; original_destination_connection_id_replacement_ = default_path_.server_connection_id; } QuicConnectionId QuicConnection::GetOriginalDestinationConnectionId() const { if (original_destination_connection_id_.has_value()) { return *original_destination_connection_id_; } return default_path_.server_connection_id; } void QuicConnection::RetireOriginalDestinationConnectionId() { if (original_destination_connection_id_.has_value()) { visitor_->OnServerConnectionIdRetired(*original_destination_connection_id_); original_destination_connection_id_.reset(); } } void QuicConnection::OnDiscardZeroRttDecryptionKeysAlarm() { QUICHE_DCHECK(connected()); QUIC_DLOG(INFO) << "0-RTT discard alarm fired"; RemoveDecrypter(ENCRYPTION_ZERO_RTT); RetireOriginalDestinationConnectionId(); } bool QuicConnection::ValidateServerConnectionId( const QuicPacketHeader& header) const { if (perspective_ == Perspective::IS_CLIENT && header.form == IETF_QUIC_SHORT_HEADER_PACKET) { return true; } QuicConnectionId server_connection_id = GetServerConnectionIdAsRecipient(header, perspective_); if (server_connection_id == default_path_.server_connection_id || server_connection_id == original_destination_connection_id_) { return true; } if (PacketCanReplaceServerConnectionId(header, perspective_)) { QUIC_DLOG(INFO) << ENDPOINT << "Accepting packet with new connection ID " << server_connection_id << " instead of " << default_path_.server_connection_id; return true; } if (version().HasIetfQuicFrames() && perspective_ == Perspective::IS_SERVER && self_issued_cid_manager_ != nullptr && self_issued_cid_manager_->IsConnectionIdInUse(server_connection_id)) { return true; } if (NewServerConnectionIdMightBeValid( header, perspective_, server_connection_id_replaced_by_initial_)) { return true; } return false; } bool QuicConnection::OnUnauthenticatedPublicHeader( const QuicPacketHeader& header) { last_received_packet_info_.destination_connection_id = header.destination_connection_id; if (perspective_ == Perspective::IS_SERVER && original_destination_connection_id_.has_value() && last_received_packet_info_.destination_connection_id == *original_destination_connection_id_) { last_received_packet_info_.destination_connection_id = original_destination_connection_id_replacement_; } if (header.version_flag && header.long_packet_type == INITIAL) { framer_.set_drop_incoming_retry_packets(true); } if (!ValidateServerConnectionId(header)) { ++stats_.packets_dropped; QuicConnectionId server_connection_id = GetServerConnectionIdAsRecipient(header, perspective_); QUIC_DLOG(INFO) << ENDPOINT << "Ignoring packet from unexpected server connection ID " << server_connection_id << " instead of " << default_path_.server_connection_id; if (debug_visitor_ != nullptr) { debug_visitor_->OnIncorrectConnectionId(server_connection_id); } QUICHE_DCHECK_NE(Perspective::IS_SERVER, perspective_); return false; } if (!version().SupportsClientConnectionIds()) { return true; } if (perspective_ == Perspective::IS_SERVER && header.form == IETF_QUIC_SHORT_HEADER_PACKET) { return true; } QuicConnectionId client_connection_id = GetClientConnectionIdAsRecipient(header, perspective_); if (client_connection_id == default_path_.client_connection_id) { return true; } if (!client_connection_id_is_set_ && perspective_ == Perspective::IS_SERVER) { QUIC_DLOG(INFO) << ENDPOINT << "Setting client connection ID from first packet to " << client_connection_id; set_client_connection_id(client_connection_id); return true; } if (version().HasIetfQuicFrames() && perspective_ == Perspective::IS_CLIENT && self_issued_cid_manager_ != nullptr && self_issued_cid_manager_->IsConnectionIdInUse(client_connection_id)) { return true; } ++stats_.packets_dropped; QUIC_DLOG(INFO) << ENDPOINT << "Ignoring packet from unexpected client connection ID " << client_connection_id << " instead of " << default_path_.client_connection_id; return false; } bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader& header) { if (debug_visitor_ != nullptr) { debug_visitor_->OnUnauthenticatedHeader(header); } QUICHE_DCHECK(ValidateServerConnectionId(header)); if (packet_creator_.HasPendingFrames()) { const std::string error_details = "Pending frames must be serialized before incoming packets are " "processed."; QUIC_BUG(quic_pending_frames_not_serialized) << error_details << ", received header: " << header; CloseConnection(QUIC_INTERNAL_ERROR, error_details, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return false; } return true; } void QuicConnection::OnSuccessfulVersionNegotiation() { visitor_->OnSuccessfulVersionNegotiation(version()); if (debug_visitor_ != nullptr) { debug_visitor_->OnSuccessfulVersionNegotiation(version()); } } void QuicConnection::OnSuccessfulMigration(bool is_port_change) { QUICHE_DCHECK_EQ(perspective_, Perspective::IS_CLIENT); if (IsPathDegrading() && !multi_port_stats_) { OnForwardProgressMade(); } if (IsAlternativePath(default_path_.self_address, default_path_.peer_address)) { alternative_path_.Clear(); } if (version().HasIetfQuicFrames() && !is_port_change) { sent_packet_manager_.OnConnectionMigration(true); } } void QuicConnection::OnTransportParametersSent( const TransportParameters& transport_parameters) const { if (debug_visitor_ != nullptr) { debug_visitor_->OnTransportParametersSent(transport_parameters); } } void QuicConnection::OnTransportParametersReceived( const TransportParameters& transport_parameters) const { if (debug_visitor_ != nullptr) { debug_visitor_->OnTransportParametersReceived(transport_parameters); } } void QuicConnection::OnTransportParametersResumed( const TransportParameters& transport_parameters) const { if (debug_visitor_ != nullptr) { debug_visitor_->OnTransportParametersResumed(transport_parameters); } } void QuicConnection::OnEncryptedClientHelloSent( absl::string_view client_hello) const { if (debug_visitor_ != nullptr) { debug_visitor_->OnEncryptedClientHelloSent(client_hello); } } void QuicConnection::OnEncryptedClientHelloReceived( absl::string_view client_hello) const { if (debug_visitor_ != nullptr) { debug_visitor_->OnEncryptedClientHelloReceived(client_hello); } } void QuicConnection::OnParsedClientHelloInfo( const ParsedClientHello& client_hello) { if (debug_visitor_ != nullptr) { debug_visitor_->OnParsedClientHelloInfo(client_hello); } } bool QuicConnection::HasPendingAcks() const { return ack_alarm().IsSet(); } void QuicConnection::OnUserAgentIdKnown(const std::string& ) { sent_packet_manager_.OnUserAgentIdKnown(); } void QuicConnection::OnDecryptedPacket(size_t , EncryptionLevel level) { last_received_packet_info_.decrypted_level = level; last_received_packet_info_.decrypted = true; if (level == ENCRYPTION_FORWARD_SECURE && !have_decrypted_first_one_rtt_packet_) { have_decrypted_first_one_rtt_packet_ = true; if (version().UsesTls() && perspective_ == Perspective::IS_SERVER) { discard_zero_rtt_decryption_keys_alarm().Set( clock_->ApproximateNow() + sent_packet_manager_.GetPtoDelay() * 3); } } if (EnforceAntiAmplificationLimit() && !IsHandshakeConfirmed() && (level == ENCRYPTION_HANDSHAKE || level == ENCRYPTION_FORWARD_SECURE)) { default_path_.validated = true; stats_.address_validated_via_decrypting_packet = true; } idle_network_detector_.OnPacketReceived( last_received_packet_info_.receipt_time); visitor_->OnPacketDecrypted(level); } QuicSocketAddress QuicConnection::GetEffectivePeerAddressFromCurrentPacket() const { return last_received_packet_info_.source_address; } bool QuicConnection::OnPacketHeader(const QuicPacketHeader& header) { if (debug_visitor_ != nullptr) { debug_visitor_->OnPacketHeader(header, clock_->ApproximateNow(), last_received_packet_info_.decrypted_level); } ++stats_.packets_dropped; if (!ProcessValidatedPacket(header)) { return false; } current_packet_content_ = NO_FRAMES_RECEIVED; is_current_packet_connectivity_probing_ = false; has_path_challenge_in_current_packet_ = false; current_effective_peer_migration_type_ = NO_CHANGE; if (perspective_ == Perspective::IS_CLIENT) { if (!GetLargestReceivedPacket().IsInitialized() || header.packet_number > GetLargestReceivedPacket()) { if (version().HasIetfQuicFrames()) { } else { UpdatePeerAddress(last_received_packet_info_.source_address); default_path_.peer_address = GetEffectivePeerAddressFromCurrentPacket(); } } } else { current_effective_peer_migration_type_ = QuicUtils::DetermineAddressChangeType( default_path_.peer_address, GetEffectivePeerAddressFromCurrentPacket()); if (version().HasIetfQuicFrames()) { auto effective_peer_address = GetEffectivePeerAddressFromCurrentPacket(); if (IsDefaultPath(last_received_packet_info_.destination_address, effective_peer_address)) { default_path_.server_connection_id = last_received_packet_info_.destination_connection_id; } else if (IsAlternativePath( last_received_packet_info_.destination_address, effective_peer_address)) { alternative_path_.server_connection_id = last_received_packet_info_.destination_connection_id; } } if (last_received_packet_info_.destination_connection_id != default_path_.server_connection_id && (!original_destination_connection_id_.has_value() || last_received_packet_info_.destination_connection_id != *original_destination_connection_id_)) { QUIC_CODE_COUNT(quic_connection_id_change); } QUIC_DLOG_IF(INFO, current_effective_peer_migration_type_ != NO_CHANGE) << ENDPOINT << "Effective peer's ip:port changed from " << default_path_.peer_address.ToString() << " to " << GetEffectivePeerAddressFromCurrentPacket().ToString() << ", active_effective_peer_migration_type is " << active_effective_peer_migration_type_; } --stats_.packets_dropped; QUIC_DVLOG(1) << ENDPOINT << "Received packet header: " << header; last_received_packet_info_.header = header; if (!stats_.first_decrypted_packet.IsInitialized()) { stats_.first_decrypted_packet = last_received_packet_info_.header.packet_number; } switch (last_received_packet_info_.ecn_codepoint) { case ECN_NOT_ECT: break; case ECN_ECT0: stats_.num_ecn_marks_received.ect0++; break; case ECN_ECT1: stats_.num_ecn_marks_received.ect1++; break; case ECN_CE: stats_.num_ecn_marks_received.ce++; break; } QuicTime receipt_time = idle_network_detector_.time_of_last_received_packet(); if (SupportsMultiplePacketNumberSpaces()) { receipt_time = last_received_packet_info_.receipt_time; } uber_received_packet_manager_.RecordPacketReceived( last_received_packet_info_.decrypted_level, last_received_packet_info_.header, receipt_time, last_received_packet_info_.ecn_codepoint); if (EnforceAntiAmplificationLimit() && !IsHandshakeConfirmed() && !header.retry_token.empty() && visitor_->ValidateToken(header.retry_token)) { QUIC_DLOG(INFO) << ENDPOINT << "Address validated via token."; QUIC_CODE_COUNT(quic_address_validated_via_token); default_path_.validated = true; stats_.address_validated_via_token = true; } QUICHE_DCHECK(connected_); return true; } bool QuicConnection::OnStreamFrame(const QuicStreamFrame& frame) { QUIC_BUG_IF(quic_bug_12714_3, !connected_) << "Processing STREAM frame when connection is closed. Received packet " "info: " << last_received_packet_info_; if (!UpdatePacketContent(STREAM_FRAME)) { return false; } if (debug_visitor_ != nullptr) { debug_visitor_->OnStreamFrame(frame); } if (!QuicUtils::IsCryptoStreamId(transport_version(), frame.stream_id) && last_received_packet_info_.decrypted_level == ENCRYPTION_INITIAL) { if (MaybeConsiderAsMemoryCorruption(frame)) { CloseConnection(QUIC_MAYBE_CORRUPTED_MEMORY, "Received crypto frame on non crypto stream.", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return false; } QUIC_PEER_BUG(quic_peer_bug_10511_6) << ENDPOINT << "Received an unencrypted data frame: closing connection" << " packet_number:" << last_received_packet_info_.header.packet_number << " stream_id:" << frame.stream_id << " received_packets:" << ack_frame(); CloseConnection(QUIC_UNENCRYPTED_STREAM_DATA, "Unencrypted stream data seen.", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return false; } MaybeUpdateAckTimeout(); visitor_->OnStreamFrame(frame); stats_.stream_bytes_received += frame.data_length; ping_manager_.reset_consecutive_retransmittable_on_wire_count(); return connected_; } bool QuicConnection::OnCryptoFrame(const QuicCryptoFrame& frame) { QUIC_BUG_IF(quic_bug_12714_4, !connected_) << "Processing CRYPTO frame when connection is closed. Received packet " "info: " << last_received_packet_info_; if (!UpdatePacketContent(CRYPTO_FRAME)) { return false; } if (debug_visitor_ != nullptr) { debug_visitor_->OnCryptoFrame(frame); } MaybeUpdateAckTimeout(); visitor_->OnCryptoFrame(frame); return connected_; } bool QuicConnection::OnAckFrameStart(QuicPacketNumber largest_acked, QuicTime::Delta ack_delay_time) { QUIC_BUG_IF(quic_bug_12714_5, !connected_) << "Processing ACK frame start when connection is closed. Received " "packet info: " << last_received_packet_info_; if (processing_ack_frame_) { CloseConnection(QUIC_INVALID_ACK_DATA, "Received a new ack while processing an ack frame.", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return false; } if (!UpdatePacketContent(ACK_FRAME)) { return false; } QUIC_DVLOG(1) << ENDPOINT << "OnAckFrameStart, largest_acked: " << largest_acked; if (GetLargestReceivedPacketWithAck().IsInitialized() && last_received_packet_info_.header.packet_number <= GetLargestReceivedPacketWithAck()) { QUIC_DLOG(INFO) << ENDPOINT << "Received an old ack frame: ignoring"; return true; } if (!sent_packet_manager_.GetLargestSentPacket().IsInitialized() || largest_acked > sent_packet_manager_.GetLargestSentPacket()) { QUIC_DLOG(WARNING) << ENDPOINT << "Peer's observed unsent packet:" << largest_acked << " vs " << sent_packet_manager_.GetLargestSentPacket() << ". SupportsMultiplePacketNumberSpaces():" << SupportsMultiplePacketNumberSpaces() << ", last_received_packet_info_.decrypted_level:" << last_received_packet_info_.decrypted_level; CloseConnection(QUIC_INVALID_ACK_DATA, "Largest observed too high.", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return false; } processing_ack_frame_ = true; sent_packet_manager_.OnAckFrameStart( largest_acked, ack_delay_time, idle_network_detector_.time_of_last_received_packet()); return true; } bool QuicConnection::OnAckRange(QuicPacketNumber start, QuicPacketNumber end) { QUIC_BUG_IF(quic_bug_12714_6, !connected_) << "Processing ACK frame range when connection is closed. Received " "packet info: " << last_received_packet_info_; QUIC_DVLOG(1) << ENDPOINT << "OnAckRange: [" << start << ", " << end << ")"; if (GetLargestReceivedPacketWithAck().IsInitialized() && last_received_packet_info_.header.packet_number <= GetLargestReceivedPacketWithAck()) { QUIC_DLOG(INFO) << ENDPOINT << "Received an old ack frame: ignoring"; return true; } sent_packet_manager_.OnAckRange(start, end); return true; } bool QuicConnection::OnAckTimestamp(QuicPacketNumber packet_number, QuicTime timestamp) { QUIC_BUG_IF(quic_bug_10511_7, !connected_) << "Processing ACK frame time stamp when connection is closed. Received " "packet info: " << last_received_packet_info_; QUIC_DVLOG(1) << ENDPOINT << "OnAckTimestamp: [" << packet_number << ", " << timestamp.ToDebuggingValue() << ")"; if (GetLargestReceivedPacketWithAck().IsInitialized() && last_received_packet_info_.header.packet_number <= GetLargestReceivedPacketWithAck()) { QUIC_DLOG(INFO) << ENDPOINT << "Received an old ack frame: ignoring"; return true; } sent_packet_manager_.OnAckTimestamp(packet_number, timestamp); return true; } bool QuicConnection::OnAckFrameEnd( QuicPacketNumber start, const std::optional<QuicEcnCounts>& ecn_counts) { QUIC_BUG_IF(quic_bug_12714_7, !connected_) << "Processing ACK frame end when connection is closed. Received packet " "info: " << last_received_packet_info_; QUIC_DVLOG(1) << ENDPOINT << "OnAckFrameEnd, start: " << start; if (GetLargestReceivedPacketWithAck().IsInitialized() && last_received_packet_info_.header.packet_number <= GetLargestReceivedPacketWithAck()) { QUIC_DLOG(INFO) << ENDPOINT << "Received an old ack frame: ignoring"; return true; } const bool one_rtt_packet_was_acked = sent_packet_manager_.one_rtt_packet_acked(); const bool zero_rtt_packet_was_acked = sent_packet_manager_.zero_rtt_packet_acked(); const AckResult ack_result = sent_packet_manager_.OnAckFrameEnd( idle_network_detector_.time_of_last_received_packet(), last_received_packet_info_.header.packet_number, last_received_packet_info_.decrypted_level, ecn_counts); if (ack_result != PACKETS_NEWLY_ACKED && ack_result != NO_PACKETS_NEWLY_ACKED) { QUIC_DLOG(ERROR) << ENDPOINT << "Error occurred when processing an ACK frame: " << QuicUtils::AckResultToString(ack_result); return false; } if (SupportsMultiplePacketNumberSpaces() && !one_rtt_packet_was_acked && sent_packet_manager_.one_rtt_packet_acked()) { visitor_->OnOneRttPacketAcknowledged(); } if (debug_visitor_ != nullptr && version().UsesTls() && !zero_rtt_packet_was_acked && sent_packet_manager_.zero_rtt_packet_acked()) { debug_visitor_->OnZeroRttPacketAcked(); } if (send_alarm().IsSet()) { send_alarm().Cancel(); } if (supports_release_time_) { UpdateReleaseTimeIntoFuture(); } SetLargestReceivedPacketWithAck( last_received_packet_info_.header.packet_number); PostProcessAfterAckFrame(ack_result == PACKETS_NEWLY_ACKED); processing_ack_frame_ = false; return connected_; } bool QuicConnection::OnStopWaitingFrame(const QuicStopWaitingFrame& ) { QUIC_BUG_IF(quic_bug_12714_8, !connected_) << "Processing STOP_WAITING frame when connection is closed. Received " "packet info: " << last_received_packet_info_; if (!UpdatePacketContent(STOP_WAITING_FRAME)) { return false; } return connected_; } bool QuicConnection::OnPaddingFrame(const QuicPaddingFrame& frame) { QUIC_BUG_IF(quic_bug_12714_9, !connected_) << "Processing PADDING frame when connection is closed. Received packet " "info: " << last_received_packet_info_; if (!UpdatePacketContent(PADDING_FRAME)) { return false; } if (debug_visitor_ != nullptr) { debug_visitor_->OnPaddingFrame(frame); } return true; } bool QuicConnection::OnPingFrame(const QuicPingFrame& frame) { QUIC_BUG_IF(quic_bug_12714_10, !connected_) << "Processing PING frame when connection is closed. Received packet " "info: " << last_received_packet_info_; if (!UpdatePacketContent(PING_FRAME)) { return false; } if (debug_visitor_ != nullptr) { QuicTime::Delta ping_received_delay = QuicTime::Delta::Zero(); const QuicTime now = clock_->ApproximateNow(); if (now > stats_.connection_creation_time) { ping_received_delay = now - stats_.connection_creation_time; } debug_visitor_->OnPingFrame(frame, ping_received_delay); } MaybeUpdateAckTimeout(); return true; } bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame& frame) { QUIC_BUG_IF(quic_bug_12714_11, !connected_) << "Processing RST_STREAM frame when connection is closed. Received " "packet info: " << last_received_packet_info_; if (!UpdatePacketContent(RST_STREAM_FRAME)) { return false; } if (debug_visitor_ != nullptr) { debug_visitor_->OnRstStreamFrame(frame); } QUIC_DLOG(INFO) << ENDPOINT << "RST_STREAM_FRAME received for stream: " << frame.stream_id << " with error: " << QuicRstStreamErrorCodeToString(frame.error_code); MaybeUpdateAckTimeout(); visitor_->OnRstStream(frame); return connected_; } bool QuicConnection::OnStopSendingFrame(const QuicStopSendingFrame& frame) { QUIC_BUG_IF(quic_bug_12714_12, !connected_) << "Processing STOP_SENDING frame when connection is closed. Received " "packet info: " << last_received_packet_info_; if (!UpdatePacketContent(STOP_SENDING_FRAME)) { return false; } if (debug_visitor_ != nullptr) { debug_visitor_->OnStopSendingFrame(frame); } QUIC_DLOG(INFO) << ENDPOINT << "STOP_SENDING frame received for stream: " << frame.stream_id << " with error: " << frame.ietf_error_code; MaybeUpdateAckTimeout(); visitor_->OnStopSendingFrame(frame); return connected_; } class ReversePathValidationContext : public QuicPathValidationContext { public: ReversePathValidationContext(const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, const QuicSocketAddress& effective_peer_address, QuicConnection* connection) : QuicPathValidationContext(self_address, peer_address, effective_peer_address), connection_(connection) {} QuicPacketWriter* WriterToUse() override { return connection_->writer(); } private: QuicConnection* connection_; }; bool QuicConnection::OnPathChallengeFrame(const QuicPathChallengeFrame& frame) { QUIC_BUG_IF(quic_bug_10511_8, !connected_) << "Processing PATH_CHALLENGE frame when connection is closed. Received " "packet info: " << last_received_packet_info_; if (has_path_challenge_in_current_packet_) { return true; } should_proactively_validate_peer_address_on_path_challenge_ = false; if (!UpdatePacketContent(PATH_CHALLENGE_FRAME)) { return false; } if (debug_visitor_ != nullptr) { debug_visitor_->OnPathChallengeFrame(frame); } const QuicSocketAddress effective_peer_address_to_respond = perspective_ == Perspective::IS_CLIENT ? effective_peer_address() : GetEffectivePeerAddressFromCurrentPacket(); const QuicSocketAddress direct_peer_address_to_respond = perspective_ == Perspective::IS_CLIENT ? direct_peer_address_ : last_received_packet_info_.source_address; QuicConnectionId client_cid, server_cid; FindOnPathConnectionIds(last_received_packet_info_.destination_address, effective_peer_address_to_respond, &client_cid, &server_cid); { QuicPacketCreator::ScopedPeerAddressContext context( &packet_creator_, direct_peer_address_to_respond, client_cid, server_cid); if (should_proactively_validate_peer_address_on_path_challenge_) { QUIC_DVLOG(1) << "Proactively validate the effective peer address " << effective_peer_address_to_respond; QUIC_CODE_COUNT_N(quic_kick_off_client_address_validation, 2, 6); ValidatePath( std::make_unique<ReversePathValidationContext>( default_path_.self_address, direct_peer_address_to_respond, effective_peer_address_to_respond, this), std::make_unique<ReversePathValidationResultDelegate>(this, peer_address()), PathValidationReason::kReversePathValidation); } has_path_challenge_in_current_packet_ = true; MaybeUpdateAckTimeout(); if (!SendPathResponse(frame.data_buffer, direct_peer_address_to_respond, effective_peer_address_to_respond)) { QUIC_CODE_COUNT(quic_failed_to_send_path_response); } ++stats_.num_connectivity_probing_received; } return connected_; } bool QuicConnection::OnPathResponseFrame(const QuicPathResponseFrame& frame) { QUIC_BUG_IF(quic_bug_10511_9, !connected_) << "Processing PATH_RESPONSE frame when connection is closed. Received " "packet info: " << last_received_packet_info_; ++stats_.num_path_response_received; if (!UpdatePacketContent(PATH_RESPONSE_FRAME)) { return false; } if (debug_visitor_ != nullptr) { debug_visitor_->OnPathResponseFrame(frame); } MaybeUpdateAckTimeout(); path_validator_.OnPathResponse( frame.data_buffer, last_received_packet_info_.destination_address); return connected_; } bool QuicConnection::OnConnectionCloseFrame( const QuicConnectionCloseFrame& frame) { QUIC_BUG_IF(quic_bug_10511_10, !connected_) << "Processing CONNECTION_CLOSE frame when connection is closed. " "Received packet info: " << last_received_packet_info_; if (!UpdatePacketContent(CONNECTION_CLOSE_FRAME)) { return false; } if (debug_visitor_ != nullptr) { debug_visitor_->OnConnectionCloseFrame(frame); } switch (frame.close_type) { case GOOGLE_QUIC_CONNECTION_CLOSE: QUIC_DLOG(INFO) << ENDPOINT << "Received ConnectionClose for connection: " << connection_id() << ", with error: " << QuicErrorCodeToString(frame.quic_error_code) << " (" << frame.error_details << ")"; break; case IETF_QUIC_TRANSPORT_CONNECTION_CLOSE: QUIC_DLOG(INFO) << ENDPOINT << "Received Transport ConnectionClose for connection: " << connection_id() << ", with error: " << QuicErrorCodeToString(frame.quic_error_code) << " (" << frame.error_details << ")" << ", transport error code: " << QuicIetfTransportErrorCodeString( static_cast<QuicIetfTransportErrorCodes>( frame.wire_error_code)) << ", error frame type: " << frame.transport_close_frame_type; break; case IETF_QUIC_APPLICATION_CONNECTION_CLOSE: QUIC_DLOG(INFO) << ENDPOINT << "Received Application ConnectionClose for connection: " << connection_id() << ", with error: " << QuicErrorCodeToString(frame.quic_error_code) << " (" << frame.error_details << ")" << ", application error code: " << frame.wire_error_code; break; } if (frame.quic_error_code == QUIC_BAD_MULTIPATH_FLAG) { QUIC_LOG_FIRST_N(ERROR, 10) << "Unexpected QUIC_BAD_MULTIPATH_FLAG error." << " last_received_header: " << last_received_packet_info_.header << " encryption_level: " << encryption_level_; } TearDownLocalConnectionState(frame, ConnectionCloseSource::FROM_PEER); return connected_; } bool QuicConnection::OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) { QUIC_BUG_IF(quic_bug_12714_13, !connected_) << "Processing MAX_STREAMS frame when connection is closed. Received " "packet info: " << last_received_packet_info_; if (!UpdatePacketContent(MAX_STREAMS_FRAME)) { return false; } if (debug_visitor_ != nullptr) { debug_visitor_->OnMaxStreamsFrame(frame); } MaybeUpdateAckTimeout(); return visitor_->OnMaxStreamsFrame(frame) && connected_; } bool QuicConnection::OnStreamsBlockedFrame( const QuicStreamsBlockedFrame& frame) { QUIC_BUG_IF(quic_bug_10511_11, !connected_) << "Processing STREAMS_BLOCKED frame when connection is closed. Received " "packet info: " << last_received_packet_info_; if (!UpdatePacketContent(STREAMS_BLOCKED_FRAME)) { return false; } if (debug_visitor_ != nullptr) { debug_visitor_->OnStreamsBlockedFrame(frame); } MaybeUpdateAckTimeout(); return visitor_->OnStreamsBlockedFrame(frame) && connected_; } bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame& frame) { QUIC_BUG_IF(quic_bug_12714_14, !connected_) << "Processing GOAWAY frame when connection is closed. Received packet " "info: " << last_received_packet_info_; if (!UpdatePacketContent(GOAWAY_FRAME)) { return false; } if (debug_visitor_ != nullptr) { debug_visitor_->OnGoAwayFrame(frame); } QUIC_DLOG(INFO) << ENDPOINT << "GOAWAY_FRAME received with last good stream: " << frame.last_good_stream_id << " and error: " << QuicErrorCodeToString(frame.error_code) << " and reason: " << frame.reason_phrase; MaybeUpdateAckTimeout(); visitor_->OnGoAway(frame); return connected_; } bool QuicConnection::OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) { QUIC_BUG_IF(quic_bug_10511_12, !connected_) << "Processing WINDOW_UPDATE frame when connection is closed. Received " "packet info: " << last_received_packet_info_; if (!UpdatePacketContent(WINDOW_UPDATE_FRAME)) { return false; } if (debug_visitor_ != nullptr) { debug_visitor_->OnWindowUpdateFrame( frame, idle_network_detector_.time_of_last_received_packet()); } QUIC_DVLOG(1) << ENDPOINT << "WINDOW_UPDATE_FRAME received " << frame; MaybeUpdateAckTimeout(); visitor_->OnWindowUpdateFrame(frame); return connected_; } void QuicConnection::OnClientConnectionIdAvailable() { QUICHE_DCHECK(perspective_ == Perspective::IS_SERVER); if (!peer_issued_cid_manager_->HasUnusedConnectionId()) { return; } if (default_path_.client_connection_id.IsEmpty()) { const QuicConnectionIdData* unused_cid_data = peer_issued_cid_manager_->ConsumeOneUnusedConnectionId(); QUIC_DVLOG(1) << ENDPOINT << "Patch connection ID " << unused_cid_data->connection_id << " to default path"; default_path_.client_connection_id = unused_cid_data->connection_id; default_path_.stateless_reset_token = unused_cid_data->stateless_reset_token; QUICHE_DCHECK(!packet_creator_.HasPendingFrames()); QUICHE_DCHECK(packet_creator_.GetDestinationConnectionId().IsEmpty()); packet_creator_.SetClientConnectionId(default_path_.client_connection_id); return; } if (alternative_path_.peer_address.IsInitialized() && alternative_path_.client_connection_id.IsEmpty()) { const QuicConnectionIdData* unused_cid_data = peer_issued_cid_manager_->ConsumeOneUnusedConnectionId(); QUIC_DVLOG(1) << ENDPOINT << "Patch connection ID " << unused_cid_data->connection_id << " to alternative path"; alternative_path_.client_connection_id = unused_cid_data->connection_id; alternative_path_.stateless_reset_token = unused_cid_data->stateless_reset_token; } } NewConnectionIdResult QuicConnection::OnNewConnectionIdFrameInner( const QuicNewConnectionIdFrame& frame) { if (peer_issued_cid_manager_ == nullptr) { CloseConnection( IETF_QUIC_PROTOCOL_VIOLATION, "Receives NEW_CONNECTION_ID while peer uses zero length connection ID", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return NewConnectionIdResult::kProtocolViolation; } std::string error_detail; bool duplicate_new_connection_id = false; QuicErrorCode error = peer_issued_cid_manager_->OnNewConnectionIdFrame( frame, &error_detail, &duplicate_new_connection_id); if (error != QUIC_NO_ERROR) { CloseConnection(error, error_detail, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return NewConnectionIdResult::kProtocolViolation; } if (duplicate_new_connection_id) { return NewConnectionIdResult::kDuplicateFrame; } if (perspective_ == Perspective::IS_SERVER) { OnClientConnectionIdAvailable(); } MaybeUpdateAckTimeout(); return NewConnectionIdResult::kOk; } bool QuicConnection::OnNewConnectionIdFrame( const QuicNewConnectionIdFrame& frame) { QUICHE_DCHECK(version().HasIetfQuicFrames()); QUIC_BUG_IF(quic_bug_10511_13, !connected_) << "Processing NEW_CONNECTION_ID frame when connection is closed. " "Received packet info: " << last_received_packet_info_; if (!UpdatePacketContent(NEW_CONNECTION_ID_FRAME)) { return false; } if (debug_visitor_ != nullptr) { debug_visitor_->OnNewConnectionIdFrame(frame); } NewConnectionIdResult result = OnNewConnectionIdFrameInner(frame); switch (result) { case NewConnectionIdResult::kOk: if (multi_port_stats_ != nullptr) { MaybeCreateMultiPortPath(); } break; case NewConnectionIdResult::kProtocolViolation: return false; case NewConnectionIdResult::kDuplicateFrame: break; } return true; } bool QuicConnection::OnRetireConnectionIdFrame( const QuicRetireConnectionIdFrame& frame) { QUICHE_DCHECK(version().HasIetfQuicFrames()); QUIC_BUG_IF(quic_bug_10511_14, !connected_) << "Processing RETIRE_CONNECTION_ID frame when connection is closed. " "Received packet info: " << last_received_packet_info_; if (!UpdatePacketContent(RETIRE_CONNECTION_ID_FRAME)) { return false; } if (debug_visitor_ != nullptr) { debug_visitor_->OnRetireConnectionIdFrame(frame); } if (self_issued_cid_manager_ == nullptr) { CloseConnection( IETF_QUIC_PROTOCOL_VIOLATION, "Receives RETIRE_CONNECTION_ID while new connection ID is never issued", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return false; } std::string error_detail; QuicErrorCode error = self_issued_cid_manager_->OnRetireConnectionIdFrame( frame, sent_packet_manager_.GetPtoDelay(), &error_detail); if (error != QUIC_NO_ERROR) { CloseConnection(error, error_detail, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return false; } MaybeUpdateAckTimeout(); return true; } bool QuicConnection::OnNewTokenFrame(const QuicNewTokenFrame& frame) { QUIC_BUG_IF(quic_bug_12714_15, !connected_) << "Processing NEW_TOKEN frame when connection is closed. Received " "packet info: " << last_received_packet_info_; if (!UpdatePacketContent(NEW_TOKEN_FRAME)) { return false; } if (debug_visitor_ != nullptr) { debug_visitor_->OnNewTokenFrame(frame); } if (perspective_ == Perspective::IS_SERVER) { CloseConnection(QUIC_INVALID_NEW_TOKEN, "Server received new token frame.", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return false; } MaybeUpdateAckTimeout(); visitor_->OnNewTokenReceived(frame.token); return true; } bool QuicConnection::OnMessageFrame(const QuicMessageFrame& frame) { QUIC_BUG_IF(quic_bug_12714_16, !connected_) << "Processing MESSAGE frame when connection is closed. Received packet " "info: " << last_received_packet_info_; if (!UpdatePacketContent(MESSAGE_FRAME)) { return false; } if (debug_visitor_ != nullptr) { debug_visitor_->OnMessageFrame(frame); } MaybeUpdateAckTimeout(); visitor_->OnMessageReceived( absl::string_view(frame.data, frame.message_length)); return connected_; } bool QuicConnection::OnHandshakeDoneFrame(const QuicHandshakeDoneFrame& frame) { QUIC_BUG_IF(quic_bug_10511_15, !connected_) << "Processing HANDSHAKE_DONE frame when connection " "is closed. Received packet " "info: " << last_received_packet_info_; if (!version().UsesTls()) { CloseConnection(IETF_QUIC_PROTOCOL_VIOLATION, "Handshake done frame is unsupported", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return false; } if (perspective_ == Perspective::IS_SERVER) { CloseConnection(IETF_QUIC_PROTOCOL_VIOLATION, "Server received handshake done frame.", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return false; } if (!UpdatePacketContent(HANDSHAKE_DONE_FRAME)) { return false; } if (debug_visitor_ != nullptr) { debug_visitor_->OnHandshakeDoneFrame(frame); } MaybeUpdateAckTimeout(); visitor_->OnHandshakeDoneReceived(); return connected_; } bool QuicConnection::OnAckFrequencyFrame(const QuicAckFrequencyFrame& frame) { QUIC_BUG_IF(quic_bug_10511_16, !connected_) << "Processing ACK_FREQUENCY frame when connection " "is closed. Received packet " "info: " << last_received_packet_info_; if (debug_visitor_ != nullptr) { debug_visitor_->OnAckFrequencyFrame(frame); } if (!UpdatePacketContent(ACK_FREQUENCY_FRAME)) { return false; } if (!can_receive_ack_frequency_frame_) { QUIC_LOG_EVERY_N_SEC(ERROR, 120) << "Get unexpected AckFrequencyFrame."; return false; } if (auto packet_number_space = QuicUtils::GetPacketNumberSpace( last_received_packet_info_.decrypted_level) == APPLICATION_DATA) { uber_received_packet_manager_.OnAckFrequencyFrame(frame); } else { QUIC_LOG_EVERY_N_SEC(ERROR, 120) << "Get AckFrequencyFrame in packet number space " << packet_number_space; } MaybeUpdateAckTimeout(); return true; } bool QuicConnection::OnResetStreamAtFrame(const QuicResetStreamAtFrame& frame) { QUIC_BUG_IF(OnResetStreamAtFrame_connection_closed, !connected_) << "Processing RESET_STREAM_AT frame while the connection is closed. " "Received packet info: " << last_received_packet_info_; if (debug_visitor_ != nullptr) { debug_visitor_->OnResetStreamAtFrame(frame); } if (!UpdatePacketContent(RESET_STREAM_AT_FRAME)) { return false; } if (!reliable_stream_reset_) { CloseConnection(IETF_QUIC_PROTOCOL_VIOLATION, "Received RESET_STREAM_AT while not negotiated.", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return false; } MaybeUpdateAckTimeout(); visitor_->OnResetStreamAt(frame); return true; } bool QuicConnection::OnBlockedFrame(const QuicBlockedFrame& frame) { QUIC_BUG_IF(quic_bug_12714_17, !connected_) << "Processing BLOCKED frame when connection is closed. Received packet " "info: " << last_received_packet_info_; if (!UpdatePacketContent(BLOCKED_FRAME)) { return false; } if (debug_visitor_ != nullptr) { debug_visitor_->OnBlockedFrame(frame); } QUIC_DLOG(INFO) << ENDPOINT << "BLOCKED_FRAME received for stream: " << frame.stream_id; MaybeUpdateAckTimeout(); visitor_->OnBlockedFrame(frame); stats_.blocked_frames_received++; return connected_; } void QuicConnection::OnPacketComplete() { if (!connected_) { ClearLastFrames(); return; } if (IsCurrentPacketConnectivityProbing()) { QUICHE_DCHECK(!version().HasIetfQuicFrames() && !ignore_gquic_probing_); ++stats_.num_connectivity_probing_received; } QUIC_DVLOG(1) << ENDPOINT << "Got" << (SupportsMultiplePacketNumberSpaces() ? (" " + EncryptionLevelToString( last_received_packet_info_.decrypted_level)) : "") << " packet " << last_received_packet_info_.header.packet_number << " for " << GetServerConnectionIdAsRecipient( last_received_packet_info_.header, perspective_); QUIC_DLOG_IF(INFO, current_packet_content_ == SECOND_FRAME_IS_PADDING) << ENDPOINT << "Received a padded PING packet. is_probing: " << IsCurrentPacketConnectivityProbing(); if (!version().HasIetfQuicFrames() && !ignore_gquic_probing_) { MaybeRespondToConnectivityProbingOrMigration(); } current_effective_peer_migration_type_ = NO_CHANGE; if (!should_last_packet_instigate_acks_) { uber_received_packet_manager_.MaybeUpdateAckTimeout( should_last_packet_instigate_acks_, last_received_packet_info_.decrypted_level, last_received_packet_info_.header.packet_number, last_received_packet_info_.receipt_time, clock_->ApproximateNow(), sent_packet_manager_.GetRttStats()); } ClearLastFrames(); CloseIfTooManyOutstandingSentPackets(); } void QuicConnection::MaybeRespondToConnectivityProbingOrMigration() { QUICHE_DCHECK(!version().HasIetfQuicFrames()); if (IsCurrentPacketConnectivityProbing()) { visitor_->OnPacketReceived(last_received_packet_info_.destination_address, last_received_packet_info_.source_address, true); return; } if (perspective_ == Perspective::IS_CLIENT) { QUIC_DVLOG(1) << ENDPOINT << "Received a speculative connectivity probing packet for " << GetServerConnectionIdAsRecipient( last_received_packet_info_.header, perspective_) << " from ip:port: " << last_received_packet_info_.source_address.ToString() << " to ip:port: " << last_received_packet_info_.destination_address.ToString(); visitor_->OnPacketReceived(last_received_packet_info_.destination_address, last_received_packet_info_.source_address, false); return; } } bool QuicConnection::IsValidStatelessResetToken( const StatelessResetToken& token) const { QUICHE_DCHECK_EQ(perspective_, Perspective::IS_CLIENT); return default_path_.stateless_reset_token.has_value() && QuicUtils::AreStatelessResetTokensEqual( token, *default_path_.stateless_reset_token); } void QuicConnection::OnAuthenticatedIetfStatelessResetPacket( const QuicIetfStatelessResetPacket& ) { QUICHE_DCHECK_EQ(perspective_, Perspective::IS_CLIENT); if (!IsDefaultPath(last_received_packet_info_.destination_address, last_received_packet_info_.source_address)) { if (IsAlternativePath(last_received_packet_info_.destination_address, GetEffectivePeerAddressFromCurrentPacket())) { QUIC_BUG_IF(quic_bug_12714_18, alternative_path_.validated) << "STATELESS_RESET received on alternate path after it's " "validated."; path_validator_.CancelPathValidation(); ++stats_.num_stateless_resets_on_alternate_path; } else { QUIC_BUG(quic_bug_10511_17) << "Received Stateless Reset on unknown socket."; } return; } const std::string error_details = "Received stateless reset."; QUIC_CODE_COUNT(quic_tear_down_local_connection_on_stateless_reset); TearDownLocalConnectionState(QUIC_PUBLIC_RESET, NO_IETF_QUIC_ERROR, error_details, ConnectionCloseSource::FROM_PEER); } void QuicConnection::OnKeyUpdate(KeyUpdateReason reason) { QUICHE_DCHECK(support_key_update_for_connection_); QUIC_DLOG(INFO) << ENDPOINT << "Key phase updated for " << reason; lowest_packet_sent_in_current_key_phase_.Clear(); stats_.key_update_count++; discard_previous_one_rtt_keys_alarm().Cancel(); visitor_->OnKeyUpdate(reason); } void QuicConnection::OnDecryptedFirstPacketInKeyPhase() { QUIC_DLOG(INFO) << ENDPOINT << "OnDecryptedFirstPacketInKeyPhase"; discard_previous_one_rtt_keys_alarm().Set( clock_->ApproximateNow() + sent_packet_manager_.GetPtoDelay() * 3); } std::unique_ptr<QuicDecrypter> QuicConnection::AdvanceKeysAndCreateCurrentOneRttDecrypter() { QUIC_DLOG(INFO) << ENDPOINT << "AdvanceKeysAndCreateCurrentOneRttDecrypter"; return visitor_->AdvanceKeysAndCreateCurrentOneRttDecrypter(); } std::unique_ptr<QuicEncrypter> QuicConnection::CreateCurrentOneRttEncrypter() { QUIC_DLOG(INFO) << ENDPOINT << "CreateCurrentOneRttEncrypter"; return visitor_->CreateCurrentOneRttEncrypter(); } void QuicConnection::ClearLastFrames() { should_last_packet_instigate_acks_ = false; } void QuicConnection::CloseIfTooManyOutstandingSentPackets() { const bool should_close = sent_packet_manager_.GetLargestSentPacket().IsInitialized() && sent_packet_manager_.GetLargestSentPacket() > sent_packet_manager_.GetLeastUnacked() + max_tracked_packets_; if (should_close) { CloseConnection( QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS, absl::StrCat("More than ", max_tracked_packets_, " outstanding, least_unacked: ", sent_packet_manager_.GetLeastUnacked().ToUint64(), ", packets_processed: ", stats_.packets_processed, ", last_decrypted_packet_level: ", EncryptionLevelToString( last_received_packet_info_.decrypted_level)), ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); } } const QuicFrame QuicConnection::GetUpdatedAckFrame() { QUICHE_DCHECK(!uber_received_packet_manager_.IsAckFrameEmpty( QuicUtils::GetPacketNumberSpace(encryption_level_))) << "Try to retrieve an empty ACK frame"; return uber_received_packet_manager_.GetUpdatedAckFrame( QuicUtils::GetPacketNumberSpace(encryption_level_), clock_->ApproximateNow()); } QuicPacketNumber QuicConnection::GetLeastUnacked() const { return sent_packet_manager_.GetLeastUnacked(); } bool QuicConnection::HandleWriteBlocked() { if (!writer_->IsWriteBlocked()) { return false; } visitor_->OnWriteBlocked(); return true; } void QuicConnection::MaybeSendInResponseToPacket() { if (!connected_) { return; } if (IsMissingDestinationConnectionID()) { return; } if (HandleWriteBlocked()) { return; } if (!defer_send_in_response_to_packets_) { WriteIfNotBlocked(); return; } if (!visitor_->WillingAndAbleToWrite()) { QUIC_DVLOG(1) << "No send alarm after processing packet. !WillingAndAbleToWrite."; return; } QuicTime max_deadline = QuicTime::Infinite(); if (send_alarm().IsSet()) { QUIC_DVLOG(1) << "Send alarm already set to " << send_alarm().deadline(); max_deadline = send_alarm().deadline(); send_alarm().Cancel(); } if (CanWrite(HAS_RETRANSMITTABLE_DATA)) { QUIC_BUG_IF(quic_send_alarm_set_with_data_to_send, send_alarm().IsSet()); QUIC_DVLOG(1) << "Immediate send alarm scheduled after processing packet."; send_alarm().Set(clock_->ApproximateNow() + sent_packet_manager_.GetDeferredSendAlarmDelay()); return; } if (send_alarm().IsSet()) { if (send_alarm().deadline() > max_deadline) { QUIC_DVLOG(1) << "Send alarm restored after processing packet. previous deadline:" << max_deadline << ", deadline from CanWrite:" << send_alarm().deadline(); send_alarm().Update(max_deadline, QuicTime::Delta::Zero()); } else { QUIC_DVLOG(1) << "Future send alarm scheduled after processing packet."; } return; } if (max_deadline != QuicTime::Infinite()) { QUIC_DVLOG(1) << "Send alarm restored after processing packet."; send_alarm().Set(max_deadline); return; } QUIC_DVLOG(1) << "No send alarm after processing packet. Other reasons."; } size_t QuicConnection::SendCryptoData(EncryptionLevel level, size_t write_length, QuicStreamOffset offset) { if (write_length == 0) { QUIC_BUG(quic_bug_10511_18) << "Attempt to send empty crypto frame"; return 0; } ScopedPacketFlusher flusher(this); return packet_creator_.ConsumeCryptoData(level, write_length, offset); } QuicConsumedData QuicConnection::SendStreamData(QuicStreamId id, size_t write_length, QuicStreamOffset offset, StreamSendingState state) { if (state == NO_FIN && write_length == 0) { QUIC_BUG(quic_bug_10511_19) << "Attempt to send empty stream frame"; return QuicConsumedData(0, false); } if (perspective_ == Perspective::IS_SERVER && version().CanSendCoalescedPackets() && !IsHandshakeConfirmed()) { if (in_probe_time_out_ && coalesced_packet_.NumberOfPackets() == 0u) { QUIC_CODE_COUNT(quic_try_to_send_half_rtt_data_when_pto_fires); return QuicConsumedData(0, false); } if (coalesced_packet_.ContainsPacketOfEncryptionLevel(ENCRYPTION_INITIAL) && coalesced_packet_.NumberOfPackets() == 1u) { sent_packet_manager_.RetransmitDataOfSpaceIfAny(HANDSHAKE_DATA); } } ScopedPacketFlusher flusher(this); return packet_creator_.ConsumeData(id, write_length, offset, state); } bool QuicConnection::SendControlFrame(const QuicFrame& frame) { if (SupportsMultiplePacketNumberSpaces() && (encryption_level_ == ENCRYPTION_INITIAL || encryption_level_ == ENCRYPTION_HANDSHAKE) && frame.type != PING_FRAME) { QUIC_DVLOG(1) << ENDPOINT << "Failed to send control frame: " << frame << " at encryption level: " << encryption_level_; return false; } ScopedPacketFlusher flusher(this); const bool consumed = packet_creator_.ConsumeRetransmittableControlFrame(frame); if (!consumed) { QUIC_DVLOG(1) << ENDPOINT << "Failed to send control frame: " << frame; return false; } if (frame.type == PING_FRAME) { packet_creator_.FlushCurrentPacket(); stats_.ping_frames_sent++; if (debug_visitor_ != nullptr) { debug_visitor_->OnPingSent(); } } if (frame.type == BLOCKED_FRAME) { stats_.blocked_frames_sent++; } return true; } void QuicConnection::OnStreamReset(QuicStreamId id, QuicRstStreamErrorCode error) { if (error == QUIC_STREAM_NO_ERROR) { return; } if (packet_creator_.HasPendingStreamFramesOfStream(id)) { ScopedPacketFlusher flusher(this); packet_creator_.FlushCurrentPacket(); } } const QuicConnectionStats& QuicConnection::GetStats() { const RttStats* rtt_stats = sent_packet_manager_.GetRttStats(); QuicTime::Delta min_rtt = rtt_stats->min_rtt(); if (min_rtt.IsZero()) { min_rtt = rtt_stats->initial_rtt(); } stats_.min_rtt_us = min_rtt.ToMicroseconds(); QuicTime::Delta srtt = rtt_stats->SmoothedOrInitialRtt(); stats_.srtt_us = srtt.ToMicroseconds(); stats_.estimated_bandwidth = sent_packet_manager_.BandwidthEstimate(); sent_packet_manager_.GetSendAlgorithm()->PopulateConnectionStats(&stats_); stats_.egress_mtu = long_term_mtu_; stats_.ingress_mtu = largest_received_packet_size_; return stats_; } void QuicConnection::OnCoalescedPacket(const QuicEncryptedPacket& packet) { QueueCoalescedPacket(packet); } void QuicConnection::OnUndecryptablePacket(const QuicEncryptedPacket& packet, EncryptionLevel decryption_level, bool has_decryption_key) { QUIC_DVLOG(1) << ENDPOINT << "Received undecryptable packet of length " << packet.length() << " with" << (has_decryption_key ? "" : "out") << " key at level " << decryption_level << " while connection is at encryption level " << encryption_level_; QUICHE_DCHECK(EncryptionLevelIsValid(decryption_level)); if (encryption_level_ != ENCRYPTION_FORWARD_SECURE) { ++stats_.undecryptable_packets_received_before_handshake_complete; } const bool should_enqueue = ShouldEnqueueUnDecryptablePacket(decryption_level, has_decryption_key); if (should_enqueue) { QueueUndecryptablePacket(packet, decryption_level); } if (debug_visitor_ != nullptr) { debug_visitor_->OnUndecryptablePacket(decryption_level, !should_enqueue); } if (has_decryption_key) { stats_.num_failed_authentication_packets_received++; if (version().UsesTls()) { QUICHE_DCHECK(framer_.GetDecrypter(decryption_level)); const QuicPacketCount integrity_limit = framer_.GetDecrypter(decryption_level)->GetIntegrityLimit(); QUIC_DVLOG(2) << ENDPOINT << "Checking AEAD integrity limits:" << " num_failed_authentication_packets_received=" << stats_.num_failed_authentication_packets_received << " integrity_limit=" << integrity_limit; if (stats_.num_failed_authentication_packets_received >= integrity_limit) { const std::string error_details = absl::StrCat( "decrypter integrity limit reached:" " num_failed_authentication_packets_received=", stats_.num_failed_authentication_packets_received, " integrity_limit=", integrity_limit); CloseConnection(QUIC_AEAD_LIMIT_REACHED, error_details, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); } } } if (version().UsesTls() && perspective_ == Perspective::IS_SERVER && decryption_level == ENCRYPTION_ZERO_RTT && !has_decryption_key && had_zero_rtt_decrypter_) { QUIC_CODE_COUNT_N( quic_server_received_tls_zero_rtt_packet_after_discarding_decrypter, 1, 3); stats_ .num_tls_server_zero_rtt_packets_received_after_discarding_decrypter++; } } bool QuicConnection::ShouldEnqueueUnDecryptablePacket( EncryptionLevel decryption_level, bool has_decryption_key) const { if (has_decryption_key) { return false; } if (IsHandshakeComplete()) { return false; } if (undecryptable_packets_.size() >= max_undecryptable_packets_) { return false; } if (version().KnowsWhichDecrypterToUse() && decryption_level == ENCRYPTION_INITIAL) { return false; } if (perspective_ == Perspective::IS_CLIENT && version().UsesTls() && decryption_level == ENCRYPTION_ZERO_RTT) { QUIC_PEER_BUG(quic_peer_bug_client_received_zero_rtt) << "Client received a Zero RTT packet, not buffering."; return false; } return true; } std::string QuicConnection::UndecryptablePacketsInfo() const { std::string info = absl::StrCat( "num_undecryptable_packets: ", undecryptable_packets_.size(), " {"); for (const auto& packet : undecryptable_packets_) { absl::StrAppend(&info, "[", EncryptionLevelToString(packet.encryption_level), ", ", packet.packet->length(), "]"); } absl::StrAppend(&info, "}"); return info; } void QuicConnection::ProcessUdpPacket(const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, const QuicReceivedPacket& packet) { if (!connected_) { return; } QUIC_DVLOG(2) << ENDPOINT << "Received encrypted " << packet.length() << " bytes:" << std::endl << quiche::QuicheTextUtils::HexDump( absl::string_view(packet.data(), packet.length())); QUIC_BUG_IF(quic_bug_12714_21, current_packet_data_ != nullptr) << "ProcessUdpPacket must not be called while processing a packet."; if (debug_visitor_ != nullptr) { debug_visitor_->OnPacketReceived(self_address, peer_address, packet); } last_received_packet_info_ = ReceivedPacketInfo(self_address, peer_address, packet.receipt_time(), packet.length(), packet.ecn_codepoint()); current_packet_data_ = packet.data(); if (!default_path_.self_address.IsInitialized()) { default_path_.self_address = last_received_packet_info_.destination_address; } else if (default_path_.self_address != self_address && expected_server_preferred_address_.IsInitialized() && self_address.Normalized() == expected_server_preferred_address_.Normalized()) { last_received_packet_info_.destination_address = default_path_.self_address; last_received_packet_info_.actual_destination_address = self_address; } if (!direct_peer_address_.IsInitialized()) { if (perspective_ == Perspective::IS_CLIENT) { AddKnownServerAddress(last_received_packet_info_.source_address); } UpdatePeerAddress(last_received_packet_info_.source_address); } if (!default_path_.peer_address.IsInitialized()) { const QuicSocketAddress effective_peer_addr = GetEffectivePeerAddressFromCurrentPacket(); default_path_.peer_address = effective_peer_addr.IsInitialized() ? effective_peer_addr : direct_peer_address_; } stats_.bytes_received += packet.length(); ++stats_.packets_received; if (IsDefaultPath(last_received_packet_info_.destination_address, last_received_packet_info_.source_address) && EnforceAntiAmplificationLimit()) { last_received_packet_info_.received_bytes_counted = true; default_path_.bytes_received_before_address_validation += last_received_packet_info_.length; } if (std::abs((packet.receipt_time() - clock_->ApproximateNow()).ToSeconds()) > 2 * 60) { QUIC_LOG(WARNING) << "(Formerly quic_bug_10511_21): Packet receipt time: " << packet.receipt_time().ToDebuggingValue() << " too far from current time: " << clock_->ApproximateNow().ToDebuggingValue(); } QUIC_DVLOG(1) << ENDPOINT << "time of last received packet: " << packet.receipt_time().ToDebuggingValue() << " from peer " << last_received_packet_info_.source_address << ", to " << last_received_packet_info_.destination_address; ScopedPacketFlusher flusher(this); if (!framer_.ProcessPacket(packet)) { QUIC_DVLOG(1) << ENDPOINT << "Unable to process packet. Last packet processed: " << last_received_packet_info_.header.packet_number; current_packet_data_ = nullptr; is_current_packet_connectivity_probing_ = false; MaybeProcessCoalescedPackets(); return; } ++stats_.packets_processed; QUIC_DLOG_IF(INFO, active_effective_peer_migration_type_ != NO_CHANGE) << "sent_packet_manager_.GetLargestObserved() = " << sent_packet_manager_.GetLargestObserved() << ", highest_packet_sent_before_effective_peer_migration_ = " << highest_packet_sent_before_effective_peer_migration_; if (!framer_.version().HasIetfQuicFrames() && active_effective_peer_migration_type_ != NO_CHANGE && sent_packet_manager_.GetLargestObserved().IsInitialized() && (!highest_packet_sent_before_effective_peer_migration_.IsInitialized() || sent_packet_manager_.GetLargestObserved() > highest_packet_sent_before_effective_peer_migration_)) { if (perspective_ == Perspective::IS_SERVER) { OnEffectivePeerMigrationValidated(true); } } if (!MaybeProcessCoalescedPackets()) { MaybeProcessUndecryptablePackets(); MaybeSendInResponseToPacket(); } SetPingAlarm(); RetirePeerIssuedConnectionIdsNoLongerOnPath(); current_packet_data_ = nullptr; is_current_packet_connectivity_probing_ = false; } void QuicConnection::OnBlockedWriterCanWrite() { writer_->SetWritable(); OnCanWrite(); } void QuicConnection::OnCanWrite() { if (!connected_) { return; } if (writer_->IsWriteBlocked()) { const std::string error_details = "Writer is blocked while calling OnCanWrite."; QUIC_BUG(quic_bug_10511_22) << ENDPOINT << error_details; CloseConnection(QUIC_INTERNAL_ERROR, error_details, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } ScopedPacketFlusher flusher(this); WriteQueuedPackets(); const QuicTime ack_timeout = uber_received_packet_manager_.GetEarliestAckTimeout(); if (ack_timeout.IsInitialized() && ack_timeout <= clock_->ApproximateNow()) { if (SupportsMultiplePacketNumberSpaces()) { SendAllPendingAcks(); } else { SendAck(); } } if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) { return; } visitor_->OnCanWrite(); if (visitor_->WillingAndAbleToWrite() && !send_alarm().IsSet() && CanWrite(HAS_RETRANSMITTABLE_DATA)) { send_alarm().Set(clock_->ApproximateNow()); } } void QuicConnection::OnSendAlarm() { QUICHE_DCHECK(connected()); WriteIfNotBlocked(); } void QuicConnection::WriteIfNotBlocked() { if (framer().is_processing_packet()) { QUIC_BUG(connection_write_mid_packet_processing) << ENDPOINT << "Tried to write in mid of packet processing"; return; } if (IsMissingDestinationConnectionID()) { return; } if (!HandleWriteBlocked()) { OnCanWrite(); } } void QuicConnection::MaybeClearQueuedPacketsOnPathChange() { if (version().HasIetfQuicFrames() && peer_issued_cid_manager_ != nullptr && HasQueuedPackets()) { ClearQueuedPackets(); } } void QuicConnection::ReplaceInitialServerConnectionId( const QuicConnectionId& new_server_connection_id) { QUICHE_DCHECK(perspective_ == Perspective::IS_CLIENT); if (version().HasIetfQuicFrames()) { if (new_server_connection_id.IsEmpty()) { peer_issued_cid_manager_ = nullptr; } else { if (peer_issued_cid_manager_ != nullptr) { QUIC_BUG_IF(quic_bug_12714_22, !peer_issued_cid_manager_->IsConnectionIdActive( default_path_.server_connection_id)) << "Connection ID replaced header is no longer active. old id: " << default_path_.server_connection_id << " new_id: " << new_server_connection_id; peer_issued_cid_manager_->ReplaceConnectionId( default_path_.server_connection_id, new_server_connection_id); } else { peer_issued_cid_manager_ = std::make_unique<QuicPeerIssuedConnectionIdManager>( kMinNumOfActiveConnectionIds, new_server_connection_id, clock_, alarm_factory_, this, context()); } } } default_path_.server_connection_id = new_server_connection_id; packet_creator_.SetServerConnectionId(default_path_.server_connection_id); } void QuicConnection::FindMatchingOrNewClientConnectionIdOrToken( const PathState& default_path, const PathState& alternative_path, const QuicConnectionId& server_connection_id, QuicConnectionId* client_connection_id, std::optional<StatelessResetToken>* stateless_reset_token) { QUICHE_DCHECK(perspective_ == Perspective::IS_SERVER && version().HasIetfQuicFrames()); if (peer_issued_cid_manager_ == nullptr || server_connection_id == default_path.server_connection_id) { *client_connection_id = default_path.client_connection_id; *stateless_reset_token = default_path.stateless_reset_token; return; } if (server_connection_id == alternative_path_.server_connection_id) { *client_connection_id = alternative_path.client_connection_id; *stateless_reset_token = alternative_path.stateless_reset_token; return; } auto* connection_id_data = peer_issued_cid_manager_->ConsumeOneUnusedConnectionId(); if (connection_id_data == nullptr) { return; } *client_connection_id = connection_id_data->connection_id; *stateless_reset_token = connection_id_data->stateless_reset_token; } bool QuicConnection::FindOnPathConnectionIds( const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, QuicConnectionId* client_connection_id, QuicConnectionId* server_connection_id) const { if (IsDefaultPath(self_address, peer_address)) { *client_connection_id = default_path_.client_connection_id, *server_connection_id = default_path_.server_connection_id; return true; } if (IsAlternativePath(self_address, peer_address)) { *client_connection_id = alternative_path_.client_connection_id, *server_connection_id = alternative_path_.server_connection_id; return true; } QUIC_BUG_IF(failed to find on path connection ids, perspective_ == Perspective::IS_CLIENT) << "Fails to find on path connection IDs"; return false; } void QuicConnection::SetDefaultPathState(PathState new_path_state) { QUICHE_DCHECK(version().HasIetfQuicFrames()); default_path_ = std::move(new_path_state); packet_creator_.SetClientConnectionId(default_path_.client_connection_id); packet_creator_.SetServerConnectionId(default_path_.server_connection_id); } bool QuicConnection::PeerAddressChanged() const { if (quic_test_peer_addr_change_after_normalize_) { return direct_peer_address_.Normalized() != last_received_packet_info_.source_address.Normalized(); } return direct_peer_address_ != last_received_packet_info_.source_address; } bool QuicConnection::ProcessValidatedPacket(const QuicPacketHeader& header) { if (perspective_ == Perspective::IS_CLIENT && version().HasIetfQuicFrames() && direct_peer_address_.IsInitialized() && last_received_packet_info_.source_address.IsInitialized() && PeerAddressChanged() && !IsKnownServerAddress(last_received_packet_info_.source_address)) { return false; } if (perspective_ == Perspective::IS_SERVER && default_path_.self_address.IsInitialized() && last_received_packet_info_.destination_address.IsInitialized() && default_path_.self_address != last_received_packet_info_.destination_address) { if (default_path_.self_address.port() != last_received_packet_info_.destination_address.port() || default_path_.self_address.host().Normalized() != last_received_packet_info_.destination_address.host() .Normalized()) { if (!visitor_->AllowSelfAddressChange()) { const std::string error_details = absl::StrCat( "Self address migration is not supported at the server, current " "address: ", default_path_.self_address.ToString(), ", expected server preferred address: ", expected_server_preferred_address_.ToString(), ", received packet address: ", last_received_packet_info_.destination_address.ToString(), ", size: ", last_received_packet_info_.length, ", packet number: ", header.packet_number.ToString(), ", encryption level: ", EncryptionLevelToString( last_received_packet_info_.decrypted_level)); QUIC_LOG_EVERY_N_SEC(INFO, 100) << error_details; QUIC_CODE_COUNT(quic_dropped_packets_with_changed_server_address); return false; } } default_path_.self_address = last_received_packet_info_.destination_address; } if (GetQuicReloadableFlag(quic_use_received_client_addresses_cache) && perspective_ == Perspective::IS_SERVER && !last_received_packet_info_.actual_destination_address.IsInitialized() && last_received_packet_info_.source_address.IsInitialized()) { QUIC_RELOADABLE_FLAG_COUNT(quic_use_received_client_addresses_cache); received_client_addresses_cache_.Insert( last_received_packet_info_.source_address, std::make_unique<bool>(true)); } if (perspective_ == Perspective::IS_SERVER && last_received_packet_info_.actual_destination_address.IsInitialized() && !IsHandshakeConfirmed() && GetEffectivePeerAddressFromCurrentPacket() != default_path_.peer_address) { QUICHE_DCHECK(expected_server_preferred_address_.IsInitialized()); last_received_packet_info_.source_address = direct_peer_address_; } if (PacketCanReplaceServerConnectionId(header, perspective_) && default_path_.server_connection_id != header.source_connection_id) { QUICHE_DCHECK_EQ(header.long_packet_type, INITIAL); if (server_connection_id_replaced_by_initial_) { QUIC_DLOG(ERROR) << ENDPOINT << "Refusing to replace connection ID " << default_path_.server_connection_id << " with " << header.source_connection_id; return false; } server_connection_id_replaced_by_initial_ = true; QUIC_DLOG(INFO) << ENDPOINT << "Replacing connection ID " << default_path_.server_connection_id << " with " << header.source_connection_id; if (!original_destination_connection_id_.has_value()) { original_destination_connection_id_ = default_path_.server_connection_id; } ReplaceInitialServerConnectionId(header.source_connection_id); } if (!ValidateReceivedPacketNumber(header.packet_number)) { return false; } if (!version_negotiated_) { if (perspective_ == Perspective::IS_CLIENT) { QUICHE_DCHECK(!header.version_flag || header.form != GOOGLE_QUIC_PACKET); version_negotiated_ = true; OnSuccessfulVersionNegotiation(); } } if (last_received_packet_info_.length > largest_received_packet_size_) { largest_received_packet_size_ = last_received_packet_info_.length; } if (perspective_ == Perspective::IS_SERVER && encryption_level_ == ENCRYPTION_INITIAL && last_received_packet_info_.length > packet_creator_.max_packet_length()) { if (GetQuicFlag(quic_use_lower_server_response_mtu_for_test)) { SetMaxPacketLength( std::min(last_received_packet_info_.length, QuicByteCount(1250))); } else { SetMaxPacketLength(last_received_packet_info_.length); } } return true; } bool QuicConnection::ValidateReceivedPacketNumber( QuicPacketNumber packet_number) { if (!uber_received_packet_manager_.IsAwaitingPacket( last_received_packet_info_.decrypted_level, packet_number)) { QUIC_DLOG(INFO) << ENDPOINT << "Packet " << packet_number << " no longer being waited for at level " << static_cast<int>( last_received_packet_info_.decrypted_level) << ". Discarding."; if (debug_visitor_ != nullptr) { debug_visitor_->OnDuplicatePacket(packet_number); } return false; } return true; } void QuicConnection::WriteQueuedPackets() { QUICHE_DCHECK(!writer_->IsWriteBlocked()); QUIC_CLIENT_HISTOGRAM_COUNTS("QuicSession.NumQueuedPacketsBeforeWrite", buffered_packets_.size(), 1, 1000, 50, ""); while (!buffered_packets_.empty()) { if (HandleWriteBlocked()) { break; } const BufferedPacket& packet = buffered_packets_.front(); WriteResult result = SendPacketToWriter( packet.data.get(), packet.length, packet.self_address.host(), packet.peer_address, writer_, packet.ecn_codepoint); QUIC_DVLOG(1) << ENDPOINT << "Sending buffered packet, result: " << result; if (IsMsgTooBig(writer_, result) && packet.length > long_term_mtu_) { mtu_discoverer_.Disable(); mtu_discovery_alarm().Cancel(); buffered_packets_.pop_front(); continue; } if (IsWriteError(result.status)) { OnWriteError(result.error_code); break; } if (result.status == WRITE_STATUS_OK || result.status == WRITE_STATUS_BLOCKED_DATA_BUFFERED) { buffered_packets_.pop_front(); } if (IsWriteBlockedStatus(result.status)) { visitor_->OnWriteBlocked(); break; } } } void QuicConnection::MarkZeroRttPacketsForRetransmission(int reject_reason) { sent_packet_manager_.MarkZeroRttPacketsForRetransmission(); if (debug_visitor_ != nullptr && version().UsesTls()) { debug_visitor_->OnZeroRttRejected(reject_reason); } } void QuicConnection::NeuterUnencryptedPackets() { sent_packet_manager_.NeuterUnencryptedPackets(); SetRetransmissionAlarm(); if (default_enable_5rto_blackhole_detection_) { QUIC_RELOADABLE_FLAG_COUNT_N(quic_default_enable_5rto_blackhole_detection2, 1, 3); OnForwardProgressMade(); } if (SupportsMultiplePacketNumberSpaces()) { uber_received_packet_manager_.ResetAckStates(ENCRYPTION_INITIAL); ack_alarm().Update(uber_received_packet_manager_.GetEarliestAckTimeout(), kAlarmGranularity); } } bool QuicConnection::IsMissingDestinationConnectionID() const { return peer_issued_cid_manager_ != nullptr && packet_creator_.GetDestinationConnectionId().IsEmpty(); } bool QuicConnection::ShouldGeneratePacket( HasRetransmittableData retransmittable, IsHandshake handshake) { QUICHE_DCHECK(handshake != IS_HANDSHAKE || QuicVersionUsesCryptoFrames(transport_version())) << ENDPOINT << "Handshake in STREAM frames should not check ShouldGeneratePacket"; if (IsMissingDestinationConnectionID()) { QUICHE_DCHECK(version().HasIetfQuicFrames()); QUIC_CODE_COUNT(quic_generate_packet_blocked_by_no_connection_id); QUIC_BUG_IF(quic_bug_90265_1, perspective_ == Perspective::IS_CLIENT); QUIC_DLOG(INFO) << ENDPOINT << "There is no destination connection ID available to " "generate packet."; return false; } if (IsDefaultPath(default_path_.self_address, packet_creator_.peer_address())) { return CanWrite(retransmittable); } return connected_ && !HandleWriteBlocked(); } void QuicConnection::MaybeBundleOpportunistically( TransmissionType transmission_type) { const bool should_bundle_ack_frequency = !ack_frequency_sent_ && sent_packet_manager_.CanSendAckFrequency() && transmission_type == NOT_RETRANSMISSION && packet_creator_.NextSendingPacketNumber() >= FirstSendingPacketNumber() + kMinReceivedBeforeAckDecimation; if (should_bundle_ack_frequency) { QUIC_RELOADABLE_FLAG_COUNT_N(quic_can_send_ack_frequency, 3, 3); ack_frequency_sent_ = true; auto frame = sent_packet_manager_.GetUpdatedAckFrequencyFrame(); visitor_->SendAckFrequency(frame); } if (transmission_type == NOT_RETRANSMISSION) { visitor_->MaybeBundleOpportunistically(); } if (packet_creator_.has_ack() || !CanWrite(NO_RETRANSMITTABLE_DATA)) { return; } QuicFrames frames; const bool has_pending_ack = uber_received_packet_manager_ .GetAckTimeout(QuicUtils::GetPacketNumberSpace(encryption_level_)) .IsInitialized(); if (!has_pending_ack) { return; } ResetAckStates(); QUIC_DVLOG(1) << ENDPOINT << "Bundle an ACK opportunistically"; QuicFrame updated_ack_frame = GetUpdatedAckFrame(); QUIC_BUG_IF(quic_bug_12714_23, updated_ack_frame.ack_frame->packets.Empty()) << ENDPOINT << "Attempted to opportunistically bundle an empty " << encryption_level_ << " ACK, " << (has_pending_ack ? "" : "!") << "has_pending_ack"; frames.push_back(updated_ack_frame); const bool flushed = packet_creator_.FlushAckFrame(frames); QUIC_BUG_IF(failed_to_flush_ack, !flushed) << ENDPOINT << "Failed to flush ACK frame"; } bool QuicConnection::CanWrite(HasRetransmittableData retransmittable) { if (!connected_) { return false; } if (IsMissingDestinationConnectionID()) { return false; } if (version().CanSendCoalescedPackets() && framer_.HasEncrypterOfEncryptionLevel(ENCRYPTION_INITIAL) && framer_.is_processing_packet()) { QUIC_DVLOG(1) << ENDPOINT << "Suppress sending in the mid of packet processing"; return false; } if (fill_coalesced_packet_) { return packet_creator_.HasSoftMaxPacketLength(); } if (sent_packet_manager_.pending_timer_transmission_count() > 0) { return true; } if (LimitedByAmplificationFactor(packet_creator_.max_packet_length())) { QUIC_CODE_COUNT(quic_throttled_by_amplification_limit); QUIC_DVLOG(1) << ENDPOINT << "Constrained by amplification restriction to peer address " << default_path_.peer_address << " bytes received " << default_path_.bytes_received_before_address_validation << ", bytes sent" << default_path_.bytes_sent_before_address_validation; ++stats_.num_amplification_throttling; return false; } if (HandleWriteBlocked()) { return false; } if (retransmittable == NO_RETRANSMITTABLE_DATA) { return true; } if (send_alarm().IsSet()) { return false; } QuicTime now = clock_->Now(); QuicTime::Delta delay = sent_packet_manager_.TimeUntilSend(now); if (delay.IsInfinite()) { send_alarm().Cancel(); return false; } if (!delay.IsZero()) { if (delay <= release_time_into_future_) { return true; } send_alarm().Update(now + delay, kAlarmGranularity); QUIC_DVLOG(1) << ENDPOINT << "Delaying sending " << delay.ToMilliseconds() << "ms"; return false; } return true; } QuicTime QuicConnection::CalculatePacketSentTime() { const QuicTime now = clock_->Now(); if (!supports_release_time_) { return now; } auto next_release_time_result = sent_packet_manager_.GetNextReleaseTime(); QuicTime next_release_time = std::max(now, next_release_time_result.release_time); packet_writer_params_.release_time_delay = next_release_time - now; packet_writer_params_.allow_burst = next_release_time_result.allow_burst; return next_release_time; } bool QuicConnection::WritePacket(SerializedPacket* packet) { if (sent_packet_manager_.GetLargestSentPacket().IsInitialized() && packet->packet_number < sent_packet_manager_.GetLargestSentPacket()) { QUIC_BUG(quic_bug_10511_23) << "Attempt to write packet:" << packet->packet_number << " after:" << sent_packet_manager_.GetLargestSentPacket(); CloseConnection(QUIC_INTERNAL_ERROR, "Packet written out of order.", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return true; } const bool is_mtu_discovery = QuicUtils::ContainsFrameType( packet->nonretransmittable_frames, MTU_DISCOVERY_FRAME); const SerializedPacketFate fate = packet->fate; QuicErrorCode error_code = QUIC_NO_ERROR; const bool is_termination_packet = IsTerminationPacket(*packet, &error_code); QuicPacketNumber packet_number = packet->packet_number; QuicPacketLength encrypted_length = packet->encrypted_length; if (is_termination_packet) { if (termination_packets_ == nullptr) { termination_packets_.reset( new std::vector<std::unique_ptr<QuicEncryptedPacket>>); } char* buffer_copy = CopyBuffer(*packet); termination_packets_->emplace_back( new QuicEncryptedPacket(buffer_copy, encrypted_length, true)); if (error_code == QUIC_SILENT_IDLE_TIMEOUT) { QUICHE_DCHECK_EQ(Perspective::IS_SERVER, perspective_); QUIC_DVLOG(1) << ENDPOINT << "Added silent connection close to termination packets, " "num of termination packets: " << termination_packets_->size(); return true; } } QUICHE_DCHECK_LE(encrypted_length, kMaxOutgoingPacketSize); QUICHE_DCHECK(is_mtu_discovery || encrypted_length <= packet_creator_.max_packet_length()) << " encrypted_length=" << encrypted_length << " > packet_creator max_packet_length=" << packet_creator_.max_packet_length(); QUIC_DVLOG(1) << ENDPOINT << "Sending packet " << packet_number << " : " << (IsRetransmittable(*packet) == HAS_RETRANSMITTABLE_DATA ? "data bearing " : " ack or probing only ") << ", encryption level: " << packet->encryption_level << ", encrypted length:" << encrypted_length << ", fate: " << fate << " to peer " << packet->peer_address; QUIC_DVLOG(2) << ENDPOINT << packet->encryption_level << " packet number " << packet_number << " of length " << encrypted_length << ": " << std::endl << quiche::QuicheTextUtils::HexDump(absl::string_view( packet->encrypted_buffer, encrypted_length)); QuicTime packet_send_time = CalculatePacketSentTime(); WriteResult result(WRITE_STATUS_OK, encrypted_length); QuicSocketAddress send_to_address = packet->peer_address; QuicSocketAddress send_from_address = self_address(); if (perspective_ == Perspective::IS_SERVER && expected_server_preferred_address_.IsInitialized() && received_client_addresses_cache_.Lookup(send_to_address) == received_client_addresses_cache_.end()) { send_from_address = expected_server_preferred_address_; } const bool send_on_current_path = send_to_address == peer_address(); if (!send_on_current_path) { QUIC_BUG_IF(quic_send_non_probing_frames_on_alternative_path, ContainsNonProbingFrame(*packet)) << "Packet " << packet->packet_number << " with non-probing frames was sent on alternative path: " "nonretransmittable_frames: " << QuicFramesToString(packet->nonretransmittable_frames) << " retransmittable_frames: " << QuicFramesToString(packet->retransmittable_frames); } switch (fate) { case DISCARD: ++stats_.packets_discarded; if (debug_visitor_ != nullptr) { debug_visitor_->OnPacketDiscarded(*packet); } return true; case COALESCE: QUIC_BUG_IF(quic_bug_12714_24, !version().CanSendCoalescedPackets() || coalescing_done_); if (!coalesced_packet_.MaybeCoalescePacket( *packet, send_from_address, send_to_address, helper_->GetStreamSendBufferAllocator(), packet_creator_.max_packet_length(), GetEcnCodepointToSend(send_to_address))) { if (!FlushCoalescedPacket()) { QUIC_BUG_IF(quic_connection_connected_after_flush_coalesced_failure, connected_) << "QUIC connection is still connected after failing to flush " "coalesced packet."; return false; } if (!coalesced_packet_.MaybeCoalescePacket( *packet, send_from_address, send_to_address, helper_->GetStreamSendBufferAllocator(), packet_creator_.max_packet_length(), GetEcnCodepointToSend(send_to_address))) { QUIC_DLOG(ERROR) << ENDPOINT << "Failed to coalesce packet"; result.error_code = WRITE_STATUS_FAILED_TO_COALESCE_PACKET; break; } } if (coalesced_packet_.length() < coalesced_packet_.max_packet_length()) { QUIC_DVLOG(1) << ENDPOINT << "Trying to set soft max packet length to " << coalesced_packet_.max_packet_length() - coalesced_packet_.length(); packet_creator_.SetSoftMaxPacketLength( coalesced_packet_.max_packet_length() - coalesced_packet_.length()); } last_ecn_codepoint_sent_ = coalesced_packet_.ecn_codepoint(); break; case BUFFER: QUIC_DVLOG(1) << ENDPOINT << "Adding packet: " << packet->packet_number << " to buffered packets"; last_ecn_codepoint_sent_ = GetEcnCodepointToSend(send_to_address); buffered_packets_.emplace_back(*packet, send_from_address, send_to_address, last_ecn_codepoint_sent_); break; case SEND_TO_WRITER: coalescing_done_ = true; packet->release_encrypted_buffer = nullptr; result = SendPacketToWriter( packet->encrypted_buffer, encrypted_length, send_from_address.host(), send_to_address, writer_, GetEcnCodepointToSend(send_to_address)); if (is_mtu_discovery && writer_->IsBatchMode()) { result = writer_->Flush(); } break; default: QUICHE_DCHECK(false); break; } QUIC_HISTOGRAM_ENUM( "QuicConnection.WritePacketStatus", result.status, WRITE_STATUS_NUM_VALUES, "Status code returned by writer_->WritePacket() in QuicConnection."); if (IsWriteBlockedStatus(result.status)) { QUICHE_DCHECK(writer_->IsWriteBlocked()); visitor_->OnWriteBlocked(); if (result.status != WRITE_STATUS_BLOCKED_DATA_BUFFERED) { QUIC_DVLOG(1) << ENDPOINT << "Adding packet: " << packet->packet_number << " to buffered packets"; buffered_packets_.emplace_back(*packet, send_from_address, send_to_address, last_ecn_codepoint_sent_); } } if (IsMsgTooBig(writer_, result)) { if (is_mtu_discovery) { QUIC_DVLOG(1) << ENDPOINT << " MTU probe packet too big, size:" << encrypted_length << ", long_term_mtu_:" << long_term_mtu_; mtu_discoverer_.Disable(); mtu_discovery_alarm().Cancel(); return true; } if (!send_on_current_path) { return true; } } if (IsWriteError(result.status)) { QUIC_LOG_FIRST_N(ERROR, 10) << ENDPOINT << "Failed writing packet " << packet_number << " of " << encrypted_length << " bytes from " << send_from_address.host() << " to " << send_to_address << ", with error code " << result.error_code << ". long_term_mtu_:" << long_term_mtu_ << ", previous_validated_mtu_:" << previous_validated_mtu_ << ", max_packet_length():" << max_packet_length() << ", is_mtu_discovery:" << is_mtu_discovery; if (MaybeRevertToPreviousMtu()) { return true; } OnWriteError(result.error_code); return false; } if (result.status == WRITE_STATUS_OK) { packet_send_time = packet_send_time + result.send_time_offset; } if (IsRetransmittable(*packet) == HAS_RETRANSMITTABLE_DATA && !is_termination_packet) { if (!blackhole_detector_.IsDetectionInProgress()) { blackhole_detector_.RestartDetection(GetPathDegradingDeadline(), GetNetworkBlackholeDeadline(), GetPathMtuReductionDeadline()); } idle_network_detector_.OnPacketSent(packet_send_time, sent_packet_manager_.GetPtoDelay()); } MaybeSetMtuAlarm(packet_number); QUIC_DVLOG(1) << ENDPOINT << "time we began writing last sent packet: " << packet_send_time.ToDebuggingValue(); if (IsDefaultPath(default_path_.self_address, send_to_address)) { if (EnforceAntiAmplificationLimit()) { default_path_.bytes_sent_before_address_validation += encrypted_length; } } else { MaybeUpdateBytesSentToAlternativeAddress(send_to_address, encrypted_length); } QUIC_DLOG_IF(INFO, !send_on_current_path) << ENDPOINT << " Sent packet " << packet->packet_number << " on a different path with remote address " << send_to_address << " while current path has peer address " << peer_address(); const bool in_flight = sent_packet_manager_.OnPacketSent( packet, packet_send_time, packet->transmission_type, IsRetransmittable(*packet), send_on_current_path, last_ecn_codepoint_sent_); QUIC_BUG_IF(quic_bug_12714_25, perspective_ == Perspective::IS_SERVER && default_enable_5rto_blackhole_detection_ && blackhole_detector_.IsDetectionInProgress() && !sent_packet_manager_.HasInFlightPackets()) << ENDPOINT << "Trying to start blackhole detection without no bytes in flight"; if (debug_visitor_ != nullptr) { if (sent_packet_manager_.unacked_packets().empty()) { QUIC_BUG(quic_bug_10511_25) << "Unacked map is empty right after packet is sent"; } else { debug_visitor_->OnPacketSent( packet->packet_number, packet->encrypted_length, packet->has_crypto_handshake, packet->transmission_type, packet->encryption_level, sent_packet_manager_.unacked_packets() .rbegin() ->retransmittable_frames, packet->nonretransmittable_frames, packet_send_time, result.batch_id); } } if (packet->encryption_level == ENCRYPTION_HANDSHAKE) { handshake_packet_sent_ = true; } if (packet->encryption_level == ENCRYPTION_FORWARD_SECURE) { if (!lowest_packet_sent_in_current_key_phase_.IsInitialized()) { QUIC_DLOG(INFO) << ENDPOINT << "lowest_packet_sent_in_current_key_phase_ = " << packet_number; lowest_packet_sent_in_current_key_phase_ = packet_number; } if (!is_termination_packet && MaybeHandleAeadConfidentialityLimits(*packet)) { return true; } } if (in_flight || !retransmission_alarm().IsSet()) { SetRetransmissionAlarm(); } SetPingAlarm(); RetirePeerIssuedConnectionIdsNoLongerOnPath(); packet_creator_.UpdatePacketNumberLength( sent_packet_manager_.GetLeastPacketAwaitedByPeer(encryption_level_), sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length())); stats_.bytes_sent += encrypted_length; ++stats_.packets_sent; if (packet->has_ack_ecn) { stats_.num_ack_frames_sent_with_ecn++; } QuicByteCount bytes_not_retransmitted = packet->bytes_not_retransmitted.value_or(0); if (packet->transmission_type != NOT_RETRANSMISSION) { if (static_cast<uint64_t>(encrypted_length) < bytes_not_retransmitted) { QUIC_BUG(quic_packet_bytes_written_lt_bytes_not_retransmitted) << "Total bytes written to the packet should be larger than the " "bytes in not-retransmitted frames. Bytes written: " << encrypted_length << ", bytes not retransmitted: " << bytes_not_retransmitted; } else { stats_.bytes_retransmitted += (encrypted_length - bytes_not_retransmitted); } ++stats_.packets_retransmitted; } return true; } bool QuicConnection::MaybeHandleAeadConfidentialityLimits( const SerializedPacket& packet) { if (!version().UsesTls()) { return false; } if (packet.encryption_level != ENCRYPTION_FORWARD_SECURE) { QUIC_BUG(quic_bug_12714_26) << "MaybeHandleAeadConfidentialityLimits called on non 1-RTT packet"; return false; } if (!lowest_packet_sent_in_current_key_phase_.IsInitialized()) { QUIC_BUG(quic_bug_10511_26) << "lowest_packet_sent_in_current_key_phase_ must be initialized " "before calling MaybeHandleAeadConfidentialityLimits"; return false; } if (packet.packet_number < lowest_packet_sent_in_current_key_phase_) { const std::string error_details = absl::StrCat("packet_number(", packet.packet_number.ToString(), ") < lowest_packet_sent_in_current_key_phase_ (", lowest_packet_sent_in_current_key_phase_.ToString(), ")"); QUIC_BUG(quic_bug_10511_27) << error_details; CloseConnection(QUIC_INTERNAL_ERROR, error_details, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return true; } const QuicPacketCount num_packets_encrypted_in_current_key_phase = packet.packet_number - lowest_packet_sent_in_current_key_phase_ + 1; const QuicPacketCount confidentiality_limit = framer_.GetOneRttEncrypterConfidentialityLimit(); constexpr QuicPacketCount kKeyUpdateConfidentialityLimitOffset = 1000; QuicPacketCount key_update_limit = 0; if (confidentiality_limit > kKeyUpdateConfidentialityLimitOffset) { key_update_limit = confidentiality_limit - kKeyUpdateConfidentialityLimitOffset; } const QuicPacketCount key_update_limit_override = GetQuicFlag(quic_key_update_confidentiality_limit); if (key_update_limit_override) { key_update_limit = key_update_limit_override; } QUIC_DVLOG(2) << ENDPOINT << "Checking AEAD confidentiality limits: " << "num_packets_encrypted_in_current_key_phase=" << num_packets_encrypted_in_current_key_phase << " key_update_limit=" << key_update_limit << " confidentiality_limit=" << confidentiality_limit << " IsKeyUpdateAllowed()=" << IsKeyUpdateAllowed(); if (num_packets_encrypted_in_current_key_phase >= confidentiality_limit) { const std::string error_details = absl::StrCat( "encrypter confidentiality limit reached: " "num_packets_encrypted_in_current_key_phase=", num_packets_encrypted_in_current_key_phase, " key_update_limit=", key_update_limit, " confidentiality_limit=", confidentiality_limit, " IsKeyUpdateAllowed()=", IsKeyUpdateAllowed()); CloseConnection(QUIC_AEAD_LIMIT_REACHED, error_details, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return true; } if (IsKeyUpdateAllowed() && num_packets_encrypted_in_current_key_phase >= key_update_limit) { KeyUpdateReason reason = KeyUpdateReason::kLocalAeadConfidentialityLimit; if (key_update_limit_override) { QUIC_DLOG(INFO) << ENDPOINT << "reached FLAGS_quic_key_update_confidentiality_limit, " "initiating key update: " << "num_packets_encrypted_in_current_key_phase=" << num_packets_encrypted_in_current_key_phase << " key_update_limit=" << key_update_limit << " confidentiality_limit=" << confidentiality_limit; reason = KeyUpdateReason::kLocalKeyUpdateLimitOverride; } else { QUIC_DLOG(INFO) << ENDPOINT << "approaching AEAD confidentiality limit, " "initiating key update: " << "num_packets_encrypted_in_current_key_phase=" << num_packets_encrypted_in_current_key_phase << " key_update_limit=" << key_update_limit << " confidentiality_limit=" << confidentiality_limit; } InitiateKeyUpdate(reason); } return false; } void QuicConnection::FlushPackets() { if (!connected_) { return; } if (!writer_->IsBatchMode()) { return; } if (HandleWriteBlocked()) { QUIC_DLOG(INFO) << ENDPOINT << "FlushPackets called while blocked."; return; } WriteResult result = writer_->Flush(); QUIC_HISTOGRAM_ENUM("QuicConnection.FlushPacketStatus", result.status, WRITE_STATUS_NUM_VALUES, "Status code returned by writer_->Flush() in " "QuicConnection::FlushPackets."); if (HandleWriteBlocked()) { QUICHE_DCHECK_EQ(WRITE_STATUS_BLOCKED, result.status) << "Unexpected flush result:" << result; QUIC_DLOG(INFO) << ENDPOINT << "Write blocked in FlushPackets."; return; } if (IsWriteError(result.status) && !MaybeRevertToPreviousMtu()) { OnWriteError(result.error_code); } } bool QuicConnection::IsMsgTooBig(const QuicPacketWriter* writer, const WriteResult& result) { std::optional<int> writer_error_code = writer->MessageTooBigErrorCode(); return (result.status == WRITE_STATUS_MSG_TOO_BIG) || (writer_error_code.has_value() && IsWriteError(result.status) && result.error_code == *writer_error_code); } bool QuicConnection::ShouldDiscardPacket(EncryptionLevel encryption_level) { if (!connected_) { QUIC_DLOG(INFO) << ENDPOINT << "Not sending packet as connection is disconnected."; return true; } if (encryption_level_ == ENCRYPTION_FORWARD_SECURE && encryption_level == ENCRYPTION_INITIAL) { QUIC_DLOG(INFO) << ENDPOINT << "Dropping NULL encrypted packet since the connection is " "forward secure."; return true; } return false; } QuicTime QuicConnection::GetPathMtuReductionDeadline() const { if (previous_validated_mtu_ == 0) { return QuicTime::Zero(); } QuicTime::Delta delay = sent_packet_manager_.GetMtuReductionDelay( num_rtos_for_blackhole_detection_); if (delay.IsZero()) { return QuicTime::Zero(); } return clock_->ApproximateNow() + delay; } bool QuicConnection::MaybeRevertToPreviousMtu() { if (previous_validated_mtu_ == 0) { return false; } SetMaxPacketLength(previous_validated_mtu_); mtu_discoverer_.Disable(); mtu_discovery_alarm().Cancel(); previous_validated_mtu_ = 0; return true; } void QuicConnection::OnWriteError(int error_code) { if (write_error_occurred_) { return; } write_error_occurred_ = true; const std::string error_details = absl::StrCat( "Write failed with error: ", error_code, " (", strerror(error_code), ")"); QUIC_LOG_FIRST_N(ERROR, 2) << ENDPOINT << error_details; std::optional<int> writer_error_code = writer_->MessageTooBigErrorCode(); if (writer_error_code.has_value() && error_code == *writer_error_code) { CloseConnection(QUIC_PACKET_WRITE_ERROR, error_details, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } QUIC_CODE_COUNT(quic_tear_down_local_connection_on_write_error_ietf); CloseConnection(QUIC_PACKET_WRITE_ERROR, error_details, ConnectionCloseBehavior::SILENT_CLOSE); } QuicPacketBuffer QuicConnection::GetPacketBuffer() { if (version().CanSendCoalescedPackets() && !coalescing_done_) { return {nullptr, nullptr}; } return writer_->GetNextWriteLocation(self_address().host(), peer_address()); } void QuicConnection::OnSerializedPacket(SerializedPacket serialized_packet) { if (serialized_packet.encrypted_buffer == nullptr) { QUIC_CODE_COUNT(quic_tear_down_local_connection_on_serialized_packet_ietf); CloseConnection(QUIC_ENCRYPTION_FAILURE, "Serialized packet does not have an encrypted buffer.", ConnectionCloseBehavior::SILENT_CLOSE); return; } if (serialized_packet.retransmittable_frames.empty()) { ++consecutive_num_packets_with_no_retransmittable_frames_; } else { consecutive_num_packets_with_no_retransmittable_frames_ = 0; } if (retransmittable_on_wire_behavior_ == SEND_FIRST_FORWARD_SECURE_PACKET && first_serialized_one_rtt_packet_ == nullptr && serialized_packet.encryption_level == ENCRYPTION_FORWARD_SECURE) { first_serialized_one_rtt_packet_ = std::make_unique<BufferedPacket>( serialized_packet, self_address(), peer_address(), GetEcnCodepointToSend(peer_address())); } SendOrQueuePacket(std::move(serialized_packet)); } void QuicConnection::OnUnrecoverableError(QuicErrorCode error, const std::string& error_details) { QUIC_CODE_COUNT(quic_tear_down_local_connection_on_unrecoverable_error_ietf); CloseConnection(error, error_details, ConnectionCloseBehavior::SILENT_CLOSE); } void QuicConnection::OnCongestionChange() { visitor_->OnCongestionWindowChange(clock_->ApproximateNow()); QuicTime::Delta rtt = sent_packet_manager_.GetRttStats()->smoothed_rtt(); if (rtt.IsZero()) { rtt = sent_packet_manager_.GetRttStats()->initial_rtt(); } if (debug_visitor_ != nullptr) { debug_visitor_->OnRttChanged(rtt); } } void QuicConnection::OnPathMtuIncreased(QuicPacketLength packet_size) { if (packet_size > max_packet_length()) { previous_validated_mtu_ = max_packet_length(); SetMaxPacketLength(packet_size); mtu_discoverer_.OnMaxPacketLengthUpdated(previous_validated_mtu_, max_packet_length()); } } void QuicConnection::OnInFlightEcnPacketAcked() { QUIC_BUG_IF(quic_bug_518619343_01, !GetQuicRestartFlag(quic_support_ect1)) << "Unexpected call to OnInFlightEcnPacketAcked()"; if (!default_path_.ecn_marked_packet_acked) { QUIC_DVLOG(1) << ENDPOINT << "First ECT packet acked on active path."; QUIC_RESTART_FLAG_COUNT_N(quic_support_ect1, 2, 9); default_path_.ecn_marked_packet_acked = true; } } void QuicConnection::OnInvalidEcnFeedback() { QUIC_BUG_IF(quic_bug_518619343_02, !GetQuicRestartFlag(quic_support_ect1)) << "Unexpected call to OnInvalidEcnFeedback()."; if (disable_ecn_codepoint_validation_) { return; } QUIC_DVLOG(1) << ENDPOINT << "ECN feedback is invalid, stop marking."; packet_writer_params_.ecn_codepoint = ECN_NOT_ECT; } std::unique_ptr<QuicSelfIssuedConnectionIdManager> QuicConnection::MakeSelfIssuedConnectionIdManager() { QUICHE_DCHECK((perspective_ == Perspective::IS_CLIENT && !default_path_.client_connection_id.IsEmpty()) || (perspective_ == Perspective::IS_SERVER && !default_path_.server_connection_id.IsEmpty())); return std::make_unique<QuicSelfIssuedConnectionIdManager>( kMinNumOfActiveConnectionIds, perspective_ == Perspective::IS_CLIENT ? default_path_.client_connection_id : default_path_.server_connection_id, clock_, alarm_factory_, this, context(), connection_id_generator_); } void QuicConnection::MaybeSendConnectionIdToClient() { if (perspective_ == Perspective::IS_CLIENT) { return; } QUICHE_DCHECK(self_issued_cid_manager_ != nullptr); self_issued_cid_manager_->MaybeSendNewConnectionIds(); } void QuicConnection::OnHandshakeComplete() { sent_packet_manager_.SetHandshakeConfirmed(); if (version().HasIetfQuicFrames() && perspective_ == Perspective::IS_SERVER && self_issued_cid_manager_ != nullptr) { self_issued_cid_manager_->MaybeSendNewConnectionIds(); } if (send_ack_frequency_on_handshake_completion_ && sent_packet_manager_.CanSendAckFrequency()) { QUIC_RELOADABLE_FLAG_COUNT_N(quic_can_send_ack_frequency, 2, 3); auto ack_frequency_frame = sent_packet_manager_.GetUpdatedAckFrequencyFrame(); ack_frequency_frame.packet_tolerance = kDefaultRetransmittablePacketsBeforeAck; visitor_->SendAckFrequency(ack_frequency_frame); if (!connected_) { return; } } SetRetransmissionAlarm(); if (default_enable_5rto_blackhole_detection_) { QUIC_RELOADABLE_FLAG_COUNT_N(quic_default_enable_5rto_blackhole_detection2, 2, 3); OnForwardProgressMade(); } if (!SupportsMultiplePacketNumberSpaces()) { if (perspective_ == Perspective::IS_CLIENT && ack_frame_updated()) { ack_alarm().Update(clock_->ApproximateNow(), QuicTime::Delta::Zero()); } return; } uber_received_packet_manager_.ResetAckStates(ENCRYPTION_HANDSHAKE); ack_alarm().Update(uber_received_packet_manager_.GetEarliestAckTimeout(), kAlarmGranularity); if (!accelerated_server_preferred_address_ && received_server_preferred_address_.IsInitialized()) { QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, perspective_); visitor_->OnServerPreferredAddressAvailable( received_server_preferred_address_); } } void QuicConnection::MaybeCreateMultiPortPath() { QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, perspective_); QUIC_CLIENT_HISTOGRAM_BOOL( "QuicConnection.ServerAllowsActiveMigrationForMultiPort", !active_migration_disabled_, "Whether the server allows active migration that's required for " "multi-port"); if (active_migration_disabled_) { return; } if (path_validator_.HasPendingPathValidation()) { QUIC_CLIENT_HISTOGRAM_ENUM("QuicConnection.MultiPortPathCreationCancelled", path_validator_.GetPathValidationReason(), PathValidationReason::kMaxValue, "Reason for cancelled multi port path creation"); return; } if (multi_port_stats_->num_multi_port_paths_created >= kMaxNumMultiPortPaths) { return; } auto context_observer = std::make_unique<ContextObserver>(this); visitor_->CreateContextForMultiPortPath(std::move(context_observer)); } void QuicConnection::SendOrQueuePacket(SerializedPacket packet) { WritePacket(&packet); } void QuicConnection::OnAckAlarm() { QUICHE_DCHECK(ack_frame_updated()); QUICHE_DCHECK(connected()); QuicConnection::ScopedPacketFlusher flusher(this); if (SupportsMultiplePacketNumberSpaces()) { SendAllPendingAcks(); } else { SendAck(); } } void QuicConnection::SendAck() { QUICHE_DCHECK(!SupportsMultiplePacketNumberSpaces()); QUIC_DVLOG(1) << ENDPOINT << "Sending an ACK proactively"; QuicFrames frames; frames.push_back(GetUpdatedAckFrame()); if (!packet_creator_.FlushAckFrame(frames)) { return; } ResetAckStates(); if (!ShouldBundleRetransmittableFrameWithAck()) { return; } consecutive_num_packets_with_no_retransmittable_frames_ = 0; if (packet_creator_.HasPendingRetransmittableFrames() || visitor_->WillingAndAbleToWrite()) { return; } visitor_->OnAckNeedsRetransmittableFrame(); } EncryptionLevel QuicConnection::GetEncryptionLevelToSendPingForSpace( PacketNumberSpace space) const { switch (space) { case INITIAL_DATA: return ENCRYPTION_INITIAL; case HANDSHAKE_DATA: return ENCRYPTION_HANDSHAKE; case APPLICATION_DATA: return framer_.GetEncryptionLevelToSendApplicationData(); default: QUICHE_DCHECK(false); return NUM_ENCRYPTION_LEVELS; } } bool QuicConnection::IsKnownServerAddress( const QuicSocketAddress& address) const { QUICHE_DCHECK(address.IsInitialized()); return std::find(known_server_addresses_.cbegin(), known_server_addresses_.cend(), address) != known_server_addresses_.cend(); } QuicEcnCodepoint QuicConnection::GetEcnCodepointToSend( const QuicSocketAddress& destination_address) const { if (destination_address != peer_address()) { return ECN_NOT_ECT; } if (in_probe_time_out_ && !default_path_.ecn_marked_packet_acked) { return ECN_NOT_ECT; } return packet_writer_params_.ecn_codepoint; } WriteResult QuicConnection::SendPacketToWriter( const char* buffer, size_t buf_len, const QuicIpAddress& self_address, const QuicSocketAddress& destination_address, QuicPacketWriter* writer, const QuicEcnCodepoint ecn_codepoint) { QuicPacketWriterParams params = packet_writer_params_; params.ecn_codepoint = ecn_codepoint; last_ecn_codepoint_sent_ = ecn_codepoint; WriteResult result = writer->WritePacket(buffer, buf_len, self_address, destination_address, per_packet_options_, params); return result; } void QuicConnection::OnRetransmissionAlarm() { QUICHE_DCHECK(connected()); ScopedRetransmissionTimeoutIndicator indicator(this); #ifndef NDEBUG if (sent_packet_manager_.unacked_packets().empty()) { QUICHE_DCHECK(sent_packet_manager_.handshake_mode_disabled()); QUICHE_DCHECK(!IsHandshakeConfirmed()); } #endif if (!connected_) { return; } QuicPacketNumber previous_created_packet_number = packet_creator_.packet_number(); const auto retransmission_mode = sent_packet_manager_.OnRetransmissionTimeout(); if (retransmission_mode == QuicSentPacketManager::PTO_MODE) { const QuicPacketCount num_packet_numbers_to_skip = 1; packet_creator_.SkipNPacketNumbers( num_packet_numbers_to_skip, sent_packet_manager_.GetLeastPacketAwaitedByPeer(encryption_level_), sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length())); previous_created_packet_number += num_packet_numbers_to_skip; if (debug_visitor_ != nullptr) { debug_visitor_->OnNPacketNumbersSkipped(num_packet_numbers_to_skip, clock_->Now()); } } if (default_enable_5rto_blackhole_detection_ && !sent_packet_manager_.HasInFlightPackets() && blackhole_detector_.IsDetectionInProgress()) { QUICHE_DCHECK_EQ(QuicSentPacketManager::LOSS_MODE, retransmission_mode); blackhole_detector_.StopDetection(false); } WriteIfNotBlocked(); if (!connected_) { return; } sent_packet_manager_.MaybeSendProbePacket(); if (packet_creator_.packet_number() == previous_created_packet_number && retransmission_mode == QuicSentPacketManager::PTO_MODE && !visitor_->WillingAndAbleToWrite()) { QUIC_DLOG(INFO) << ENDPOINT << "No packet gets sent when timer fires in mode " << retransmission_mode << ", send PING"; QUICHE_DCHECK_LT(0u, sent_packet_manager_.pending_timer_transmission_count()); if (SupportsMultiplePacketNumberSpaces()) { PacketNumberSpace packet_number_space; if (sent_packet_manager_ .GetEarliestPacketSentTimeForPto(&packet_number_space) .IsInitialized()) { SendPingAtLevel( GetEncryptionLevelToSendPingForSpace(packet_number_space)); } else { QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, perspective_); if (framer_.HasEncrypterOfEncryptionLevel(ENCRYPTION_HANDSHAKE)) { SendPingAtLevel(ENCRYPTION_HANDSHAKE); } else if (framer_.HasEncrypterOfEncryptionLevel(ENCRYPTION_INITIAL)) { SendPingAtLevel(ENCRYPTION_INITIAL); } else { QUIC_BUG(quic_bug_no_pto) << "PTO fired but nothing was sent."; } } } else { SendPingAtLevel(encryption_level_); } } if (retransmission_mode == QuicSentPacketManager::PTO_MODE) { QUIC_BUG_IF( quic_bug_12714_27, packet_creator_.packet_number() == previous_created_packet_number && (!visitor_->WillingAndAbleToWrite() || sent_packet_manager_.pending_timer_transmission_count() == 0u)) << "retransmission_mode: " << retransmission_mode << ", packet_number: " << packet_creator_.packet_number() << ", session has data to write: " << visitor_->WillingAndAbleToWrite() << ", writer is blocked: " << writer_->IsWriteBlocked() << ", pending_timer_transmission_count: " << sent_packet_manager_.pending_timer_transmission_count(); } if (!HasQueuedData() && !retransmission_alarm().IsSet()) { SetRetransmissionAlarm(); } if (packet_writer_params_.ecn_codepoint == ECN_NOT_ECT || default_path_.ecn_marked_packet_acked) { return; } ++default_path_.ecn_pto_count; if (default_path_.ecn_pto_count == kEcnPtoLimit) { QUIC_DVLOG(1) << ENDPOINT << "ECN packets PTO 3 times."; OnInvalidEcnFeedback(); } } void QuicConnection::SetEncrypter(EncryptionLevel level, std::unique_ptr<QuicEncrypter> encrypter) { packet_creator_.SetEncrypter(level, std::move(encrypter)); } void QuicConnection::RemoveEncrypter(EncryptionLevel level) { framer_.RemoveEncrypter(level); } void QuicConnection::SetDiversificationNonce( const DiversificationNonce& nonce) { QUICHE_DCHECK_EQ(Perspective::IS_SERVER, perspective_); packet_creator_.SetDiversificationNonce(nonce); } void QuicConnection::SetDefaultEncryptionLevel(EncryptionLevel level) { QUIC_DVLOG(1) << ENDPOINT << "Setting default encryption level from " << encryption_level_ << " to " << level; const bool changing_level = level != encryption_level_; if (changing_level && packet_creator_.HasPendingFrames()) { ScopedPacketFlusher flusher(this); packet_creator_.FlushCurrentPacket(); } encryption_level_ = level; packet_creator_.set_encryption_level(level); QUIC_BUG_IF(quic_bug_12714_28, !framer_.HasEncrypterOfEncryptionLevel(level)) << ENDPOINT << "Trying to set encryption level to " << EncryptionLevelToString(level) << " while the key is missing"; if (!changing_level) { return; } packet_creator_.UpdatePacketNumberLength( sent_packet_manager_.GetLeastPacketAwaitedByPeer(encryption_level_), sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length())); } void QuicConnection::SetDecrypter(EncryptionLevel level, std::unique_ptr<QuicDecrypter> decrypter) { framer_.SetDecrypter(level, std::move(decrypter)); if (!undecryptable_packets_.empty() && !process_undecryptable_packets_alarm().IsSet()) { process_undecryptable_packets_alarm().Set(clock_->ApproximateNow()); } } void QuicConnection::SetAlternativeDecrypter( EncryptionLevel level, std::unique_ptr<QuicDecrypter> decrypter, bool latch_once_used) { framer_.SetAlternativeDecrypter(level, std::move(decrypter), latch_once_used); if (!undecryptable_packets_.empty() && !process_undecryptable_packets_alarm().IsSet()) { process_undecryptable_packets_alarm().Set(clock_->ApproximateNow()); } } void QuicConnection::InstallDecrypter( EncryptionLevel level, std::unique_ptr<QuicDecrypter> decrypter) { if (level == ENCRYPTION_ZERO_RTT) { had_zero_rtt_decrypter_ = true; } framer_.InstallDecrypter(level, std::move(decrypter)); if (!undecryptable_packets_.empty() && !process_undecryptable_packets_alarm().IsSet()) { process_undecryptable_packets_alarm().Set(clock_->ApproximateNow()); } } void QuicConnection::RemoveDecrypter(EncryptionLevel level) { framer_.RemoveDecrypter(level); } void QuicConnection::OnDiscardPreviousOneRttKeysAlarm() { QUICHE_DCHECK(connected()); framer_.DiscardPreviousOneRttKeys(); } bool QuicConnection::IsKeyUpdateAllowed() const { return support_key_update_for_connection_ && GetLargestAckedPacket().IsInitialized() && lowest_packet_sent_in_current_key_phase_.IsInitialized() && GetLargestAckedPacket() >= lowest_packet_sent_in_current_key_phase_; } bool QuicConnection::HaveSentPacketsInCurrentKeyPhaseButNoneAcked() const { return lowest_packet_sent_in_current_key_phase_.IsInitialized() && (!GetLargestAckedPacket().IsInitialized() || GetLargestAckedPacket() < lowest_packet_sent_in_current_key_phase_); } QuicPacketCount QuicConnection::PotentialPeerKeyUpdateAttemptCount() const { return framer_.PotentialPeerKeyUpdateAttemptCount(); } bool QuicConnection::InitiateKeyUpdate(KeyUpdateReason reason) { QUIC_DLOG(INFO) << ENDPOINT << "InitiateKeyUpdate"; if (!IsKeyUpdateAllowed()) { QUIC_BUG(quic_bug_10511_28) << "key update not allowed"; return false; } return framer_.DoKeyUpdate(reason); } const QuicDecrypter* QuicConnection::decrypter() const { return framer_.decrypter(); } const QuicDecrypter* QuicConnection::alternative_decrypter() const { return framer_.alternative_decrypter(); } void QuicConnection::QueueUndecryptablePacket( const QuicEncryptedPacket& packet, EncryptionLevel decryption_level) { for (const auto& saved_packet : undecryptable_packets_) { if (packet.data() == saved_packet.packet->data() && packet.length() == saved_packet.packet->length()) { QUIC_DVLOG(1) << ENDPOINT << "Not queueing known undecryptable packet"; return; } } QUIC_DVLOG(1) << ENDPOINT << "Queueing undecryptable packet."; undecryptable_packets_.emplace_back(packet, decryption_level, last_received_packet_info_); if (perspective_ == Perspective::IS_CLIENT) { SetRetransmissionAlarm(); } } void QuicConnection::OnProcessUndecryptablePacketsAlarm() { QUICHE_DCHECK(connected()); ScopedPacketFlusher flusher(this); MaybeProcessUndecryptablePackets(); } void QuicConnection::MaybeProcessUndecryptablePackets() { process_undecryptable_packets_alarm().Cancel(); if (undecryptable_packets_.empty() || encryption_level_ == ENCRYPTION_INITIAL) { return; } auto iter = undecryptable_packets_.begin(); while (connected_ && iter != undecryptable_packets_.end()) { packet_creator_.FlushCurrentPacket(); if (!connected_) { return; } UndecryptablePacket* undecryptable_packet = &*iter; QUIC_DVLOG(1) << ENDPOINT << "Attempting to process undecryptable packet"; if (debug_visitor_ != nullptr) { debug_visitor_->OnAttemptingToProcessUndecryptablePacket( undecryptable_packet->encryption_level); } last_received_packet_info_ = undecryptable_packet->packet_info; current_packet_data_ = undecryptable_packet->packet->data(); const bool processed = framer_.ProcessPacket(*undecryptable_packet->packet); current_packet_data_ = nullptr; if (processed) { QUIC_DVLOG(1) << ENDPOINT << "Processed undecryptable packet!"; iter = undecryptable_packets_.erase(iter); ++stats_.packets_processed; continue; } const bool has_decryption_key = version().KnowsWhichDecrypterToUse() && framer_.HasDecrypterOfEncryptionLevel( undecryptable_packet->encryption_level); if (framer_.error() == QUIC_DECRYPTION_FAILURE && ShouldEnqueueUnDecryptablePacket(undecryptable_packet->encryption_level, has_decryption_key)) { QUIC_DVLOG(1) << ENDPOINT << "Need to attempt to process this undecryptable packet later"; ++iter; continue; } iter = undecryptable_packets_.erase(iter); } if (IsHandshakeComplete()) { if (debug_visitor_ != nullptr) { for (const auto& undecryptable_packet : undecryptable_packets_) { debug_visitor_->OnUndecryptablePacket( undecryptable_packet.encryption_level, true); } } undecryptable_packets_.clear(); } if (perspective_ == Perspective::IS_CLIENT) { SetRetransmissionAlarm(); } } void QuicConnection::QueueCoalescedPacket(const QuicEncryptedPacket& packet) { QUIC_DVLOG(1) << ENDPOINT << "Queueing coalesced packet."; received_coalesced_packets_.push_back(packet.Clone()); ++stats_.num_coalesced_packets_received; } bool QuicConnection::MaybeProcessCoalescedPackets() { bool processed = false; while (connected_ && !received_coalesced_packets_.empty()) { packet_creator_.FlushCurrentPacket(); if (!connected_) { return processed; } std::unique_ptr<QuicEncryptedPacket> packet = std::move(received_coalesced_packets_.front()); received_coalesced_packets_.pop_front(); QUIC_DVLOG(1) << ENDPOINT << "Processing coalesced packet"; if (framer_.ProcessPacket(*packet)) { processed = true; ++stats_.num_coalesced_packets_processed; } else { } } if (processed) { MaybeProcessUndecryptablePackets(); MaybeSendInResponseToPacket(); } return processed; } void QuicConnection::CloseConnection( QuicErrorCode error, const std::string& details, ConnectionCloseBehavior connection_close_behavior) { CloseConnection(error, NO_IETF_QUIC_ERROR, details, connection_close_behavior); } void QuicConnection::CloseConnection( QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error, const std::string& error_details, ConnectionCloseBehavior connection_close_behavior) { QUICHE_DCHECK(!error_details.empty()); if (!connected_) { QUIC_DLOG(INFO) << "Connection is already closed."; return; } if (ietf_error != NO_IETF_QUIC_ERROR) { QUIC_DLOG(INFO) << ENDPOINT << "Closing connection: " << connection_id() << ", with wire error: " << ietf_error << ", error: " << QuicErrorCodeToString(error) << ", and details: " << error_details; } else { QUIC_DLOG(INFO) << ENDPOINT << "Closing connection: " << connection_id() << ", with error: " << QuicErrorCodeToString(error) << " (" << error << "), and details: " << error_details; } if (connection_close_behavior != ConnectionCloseBehavior::SILENT_CLOSE) { SendConnectionClosePacket(error, ietf_error, error_details); } TearDownLocalConnectionState(error, ietf_error, error_details, ConnectionCloseSource::FROM_SELF); } void QuicConnection::SendConnectionClosePacket( QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error, const std::string& details) { QuicPacketCreator::ScopedPeerAddressContext peer_address_context( &packet_creator_, peer_address(), default_path_.client_connection_id, default_path_.server_connection_id); if (!SupportsMultiplePacketNumberSpaces()) { QUIC_DLOG(INFO) << ENDPOINT << "Sending connection close packet."; ScopedEncryptionLevelContext encryption_level_context( this, GetConnectionCloseEncryptionLevel()); if (version().CanSendCoalescedPackets()) { coalesced_packet_.Clear(); } ClearQueuedPackets(); ScopedPacketFlusher flusher(this); if (error != QUIC_PACKET_WRITE_ERROR && !uber_received_packet_manager_.IsAckFrameEmpty( QuicUtils::GetPacketNumberSpace(encryption_level_)) && !packet_creator_.has_ack()) { SendAck(); } QuicConnectionCloseFrame* const frame = new QuicConnectionCloseFrame( transport_version(), error, ietf_error, details, framer_.current_received_frame_type()); packet_creator_.ConsumeRetransmittableControlFrame(QuicFrame(frame)); packet_creator_.FlushCurrentPacket(); if (version().CanSendCoalescedPackets()) { FlushCoalescedPacket(); } ClearQueuedPackets(); return; } ScopedPacketFlusher flusher(this); if (version().CanSendCoalescedPackets()) { coalesced_packet_.Clear(); } ClearQueuedPackets(); for (EncryptionLevel level : {ENCRYPTION_INITIAL, ENCRYPTION_HANDSHAKE, ENCRYPTION_ZERO_RTT, ENCRYPTION_FORWARD_SECURE}) { if (!framer_.HasEncrypterOfEncryptionLevel(level)) { continue; } QUIC_DLOG(INFO) << ENDPOINT << "Sending connection close packet at level: " << level; ScopedEncryptionLevelContext context(this, level); if (error != QUIC_PACKET_WRITE_ERROR && !uber_received_packet_manager_.IsAckFrameEmpty( QuicUtils::GetPacketNumberSpace(encryption_level_)) && !packet_creator_.has_ack()) { QuicFrames frames; frames.push_back(GetUpdatedAckFrame()); packet_creator_.FlushAckFrame(frames); } if (level == ENCRYPTION_FORWARD_SECURE && perspective_ == Perspective::IS_SERVER) { visitor_->BeforeConnectionCloseSent(); } auto* frame = new QuicConnectionCloseFrame( transport_version(), error, ietf_error, details, framer_.current_received_frame_type()); packet_creator_.ConsumeRetransmittableControlFrame(QuicFrame(frame)); packet_creator_.FlushCurrentPacket(); } if (version().CanSendCoalescedPackets()) { FlushCoalescedPacket(); } ClearQueuedPackets(); } void QuicConnection::TearDownLocalConnectionState( QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error, const std::string& error_details, ConnectionCloseSource source) { QuicConnectionCloseFrame frame(transport_version(), error, ietf_error, error_details, framer_.current_received_frame_type()); return TearDownLocalConnectionState(frame, source); } void QuicConnection::TearDownLocalConnectionState( const QuicConnectionCloseFrame& frame, ConnectionCloseSource source) { if (!connected_) { QUIC_DLOG(INFO) << "Connection is already closed."; return; } FlushPackets(); connected_ = false; QUICHE_DCHECK(visitor_ != nullptr); visitor_->OnConnectionClosed(frame, source); sent_packet_manager_.OnConnectionClosed(); if (debug_visitor_ != nullptr) { debug_visitor_->OnConnectionClosed(frame, source); } CancelAllAlarms(); CancelPathValidation(); peer_issued_cid_manager_.reset(); self_issued_cid_manager_.reset(); } void QuicConnection::CancelAllAlarms() { QUIC_DVLOG(1) << "Cancelling all QuicConnection alarms."; ack_alarm().PermanentCancel(); ping_manager_.Stop(); retransmission_alarm().PermanentCancel(); send_alarm().PermanentCancel(); mtu_discovery_alarm().PermanentCancel(); process_undecryptable_packets_alarm().PermanentCancel(); discard_previous_one_rtt_keys_alarm().PermanentCancel(); discard_zero_rtt_decryption_keys_alarm().PermanentCancel(); multi_port_probing_alarm().PermanentCancel(); blackhole_detector_.StopDetection(true); idle_network_detector_.StopDetection(); } QuicByteCount QuicConnection::max_packet_length() const { return packet_creator_.max_packet_length(); } void QuicConnection::SetMaxPacketLength(QuicByteCount length) { long_term_mtu_ = length; stats_.max_egress_mtu = std::max(stats_.max_egress_mtu, long_term_mtu_); packet_creator_.SetMaxPacketLength(GetLimitedMaxPacketSize(length)); } bool QuicConnection::HasQueuedData() const { return packet_creator_.HasPendingFrames() || !buffered_packets_.empty(); } void QuicConnection::SetNetworkTimeouts(QuicTime::Delta handshake_timeout, QuicTime::Delta idle_timeout) { QUIC_BUG_IF(quic_bug_12714_29, idle_timeout > handshake_timeout) << "idle_timeout:" << idle_timeout.ToMilliseconds() << " handshake_timeout:" << handshake_timeout.ToMilliseconds(); QUIC_DVLOG(1) << ENDPOINT << "Setting network timeouts: " << "handshake_timeout:" << handshake_timeout.ToMilliseconds() << " idle_timeout:" << idle_timeout.ToMilliseconds(); if (perspective_ == Perspective::IS_SERVER) { idle_timeout = idle_timeout + QuicTime::Delta::FromSeconds(3); } else if (idle_timeout > QuicTime::Delta::FromSeconds(1)) { idle_timeout = idle_timeout - QuicTime::Delta::FromSeconds(1); } idle_network_detector_.SetTimeouts(handshake_timeout, idle_timeout); } void QuicConnection::SetPingAlarm() { if (!connected_) { return; } ping_manager_.SetAlarm(clock_->ApproximateNow(), visitor_->ShouldKeepConnectionAlive(), sent_packet_manager_.HasInFlightPackets()); } void QuicConnection::SetRetransmissionAlarm() { if (!connected_) { if (retransmission_alarm().IsSet()) { QUIC_BUG(quic_bug_10511_29) << ENDPOINT << "Retransmission alarm is set while disconnected"; retransmission_alarm().Cancel(); } return; } if (packet_creator_.PacketFlusherAttached()) { pending_retransmission_alarm_ = true; return; } if (LimitedByAmplificationFactor(packet_creator_.max_packet_length())) { retransmission_alarm().Cancel(); return; } PacketNumberSpace packet_number_space; if (SupportsMultiplePacketNumberSpaces() && !IsHandshakeConfirmed() && !sent_packet_manager_ .GetEarliestPacketSentTimeForPto(&packet_number_space) .IsInitialized()) { if (perspective_ == Perspective::IS_SERVER) { retransmission_alarm().Cancel(); return; } if (retransmission_alarm().IsSet() && GetRetransmissionDeadline() > retransmission_alarm().deadline()) { return; } } retransmission_alarm().Update(GetRetransmissionDeadline(), kAlarmGranularity); } void QuicConnection::MaybeSetMtuAlarm(QuicPacketNumber sent_packet_number) { if (mtu_discovery_alarm().IsSet() || !mtu_discoverer_.ShouldProbeMtu(sent_packet_number)) { return; } mtu_discovery_alarm().Set(clock_->ApproximateNow()); } QuicConnection::ScopedPacketFlusher::ScopedPacketFlusher( QuicConnection* connection) : connection_(connection), flush_and_set_pending_retransmission_alarm_on_delete_(false), handshake_packet_sent_(connection != nullptr && connection->handshake_packet_sent_) { if (connection_ == nullptr) { return; } if (!connection_->packet_creator_.PacketFlusherAttached()) { flush_and_set_pending_retransmission_alarm_on_delete_ = true; connection->packet_creator_.AttachPacketFlusher(); } } QuicConnection::ScopedPacketFlusher::~ScopedPacketFlusher() { if (connection_ == nullptr || !connection_->connected()) { return; } if (flush_and_set_pending_retransmission_alarm_on_delete_) { const QuicTime ack_timeout = connection_->uber_received_packet_manager_.GetEarliestAckTimeout(); if (ack_timeout.IsInitialized()) { if (ack_timeout <= connection_->clock_->ApproximateNow() && !connection_->CanWrite(NO_RETRANSMITTABLE_DATA)) { connection_->ack_alarm().Cancel(); } else if (!connection_->ack_alarm().IsSet() || connection_->ack_alarm().deadline() > ack_timeout) { connection_->ack_alarm().Update(ack_timeout, QuicTime::Delta::Zero()); } } if (connection_->ack_alarm().IsSet() && connection_->ack_alarm().deadline() <= connection_->clock_->ApproximateNow()) { if (connection_->send_alarm().IsSet() && connection_->send_alarm().deadline() <= connection_->clock_->ApproximateNow()) { connection_->ack_alarm().Cancel(); } else if (connection_->SupportsMultiplePacketNumberSpaces()) { connection_->SendAllPendingAcks(); } else { connection_->SendAck(); } } if (connection_->version().CanSendCoalescedPackets()) { connection_->MaybeCoalescePacketOfHigherSpace(); } connection_->packet_creator_.Flush(); if (connection_->version().CanSendCoalescedPackets()) { connection_->FlushCoalescedPacket(); } connection_->FlushPackets(); if (!connection_->connected()) { return; } if (!handshake_packet_sent_ && connection_->handshake_packet_sent_) { connection_->visitor_->OnHandshakePacketSent(); } connection_->SetTransmissionType(NOT_RETRANSMISSION); connection_->CheckIfApplicationLimited(); if (connection_->pending_retransmission_alarm_) { connection_->SetRetransmissionAlarm(); connection_->pending_retransmission_alarm_ = false; } } QUICHE_DCHECK_EQ(flush_and_set_pending_retransmission_alarm_on_delete_, !connection_->packet_creator_.PacketFlusherAttached()); } QuicConnection::ScopedEncryptionLevelContext::ScopedEncryptionLevelContext( QuicConnection* connection, EncryptionLevel encryption_level) : connection_(connection), latched_encryption_level_(ENCRYPTION_INITIAL) { if (connection_ == nullptr) { return; } latched_encryption_level_ = connection_->encryption_level_; connection_->SetDefaultEncryptionLevel(encryption_level); } QuicConnection::ScopedEncryptionLevelContext::~ScopedEncryptionLevelContext() { if (connection_ == nullptr || !connection_->connected_) { return; } connection_->SetDefaultEncryptionLevel(latched_encryption_level_); } QuicConnection::BufferedPacket::BufferedPacket( const SerializedPacket& packet, const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, const QuicEcnCodepoint ecn_codepoint) : BufferedPacket(packet.encrypted_buffer, packet.encrypted_length, self_address, peer_address, ecn_codepoint) {} QuicConnection::BufferedPacket::BufferedPacket( const char* encrypted_buffer, QuicPacketLength encrypted_length, const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, const QuicEcnCodepoint ecn_codepoint) : length(encrypted_length), self_address(self_address), peer_address(peer_address), ecn_codepoint(ecn_codepoint) { data = std::make_unique<char[]>(encrypted_length); memcpy(data.get(), encrypted_buffer, encrypted_length); } QuicConnection::BufferedPacket::BufferedPacket( QuicRandom& random, QuicPacketLength encrypted_length, const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address) : length(encrypted_length), self_address(self_address), peer_address(peer_address) { data = std::make_unique<char[]>(encrypted_length); random.RandBytes(data.get(), encrypted_length); } QuicConnection::ReceivedPacketInfo::ReceivedPacketInfo(QuicTime receipt_time) : receipt_time(receipt_time) {} QuicConnection::ReceivedPacketInfo::ReceivedPacketInfo( const QuicSocketAddress& destination_address, const QuicSocketAddress& source_address, QuicTime receipt_time, QuicByteCount length, QuicEcnCodepoint ecn_codepoint) : destination_address(destination_address), source_address(source_address), receipt_time(receipt_time), length(length), ecn_codepoint(ecn_codepoint) {} std::ostream& operator<<(std::ostream& os, const QuicConnection::ReceivedPacketInfo& info) { os << " { destination_address: " << info.destination_address.ToString() << ", source_address: " << info.source_address.ToString() << ", received_bytes_counted: " << info.received_bytes_counted << ", length: " << info.length << ", destination_connection_id: " << info.destination_connection_id; if (!info.decrypted) { os << " }\n"; return os; } os << ", decrypted: " << info.decrypted << ", decrypted_level: " << EncryptionLevelToString(info.decrypted_level) << ", header: " << info.header << ", frames: "; for (const auto frame : info.frames) { os << frame; } os << " }\n"; return os; } HasRetransmittableData QuicConnection::IsRetransmittable( const SerializedPacket& packet) { if (packet.transmission_type != NOT_RETRANSMISSION || !packet.retransmittable_frames.empty()) { return HAS_RETRANSMITTABLE_DATA; } else { return NO_RETRANSMITTABLE_DATA; } } bool QuicConnection::IsTerminationPacket(const SerializedPacket& packet, QuicErrorCode* error_code) { if (packet.retransmittable_frames.empty()) { return false; } for (const QuicFrame& frame : packet.retransmittable_frames) { if (frame.type == CONNECTION_CLOSE_FRAME) { *error_code = frame.connection_close_frame->quic_error_code; return true; } } return false; } void QuicConnection::SetMtuDiscoveryTarget(QuicByteCount target) { QUIC_DVLOG(2) << ENDPOINT << "SetMtuDiscoveryTarget: " << target; mtu_discoverer_.Disable(); mtu_discoverer_.Enable(max_packet_length(), GetLimitedMaxPacketSize(target)); } QuicByteCount QuicConnection::GetLimitedMaxPacketSize( QuicByteCount suggested_max_packet_size) { if (!peer_address().IsInitialized()) { QUIC_BUG(quic_bug_10511_30) << "Attempted to use a connection without a valid peer address"; return suggested_max_packet_size; } const QuicByteCount writer_limit = writer_->GetMaxPacketSize(peer_address()); QuicByteCount max_packet_size = suggested_max_packet_size; if (max_packet_size > writer_limit) { max_packet_size = writer_limit; } if (max_packet_size > peer_max_packet_size_) { max_packet_size = peer_max_packet_size_; } if (max_packet_size > kMaxOutgoingPacketSize) { max_packet_size = kMaxOutgoingPacketSize; } return max_packet_size; } void QuicConnection::SendMtuDiscoveryPacket(QuicByteCount target_mtu) { QUICHE_DCHECK_EQ(target_mtu, GetLimitedMaxPacketSize(target_mtu)); packet_creator_.GenerateMtuDiscoveryPacket(target_mtu); } bool QuicConnection::SendConnectivityProbingPacket( QuicPacketWriter* probing_writer, const QuicSocketAddress& peer_address) { QUICHE_DCHECK(peer_address.IsInitialized()); if (!connected_) { QUIC_BUG(quic_bug_10511_31) << "Not sending connectivity probing packet as connection is " << "disconnected."; return false; } if (perspective_ == Perspective::IS_SERVER && probing_writer == nullptr) { probing_writer = writer_; } QUICHE_DCHECK(probing_writer); if (probing_writer->IsWriteBlocked()) { QUIC_DLOG(INFO) << ENDPOINT << "Writer blocked when sending connectivity probing packet."; if (probing_writer == writer_) { visitor_->OnWriteBlocked(); } return true; } QUIC_DLOG(INFO) << ENDPOINT << "Sending path probe packet for connection_id = " << default_path_.server_connection_id; std::unique_ptr<SerializedPacket> probing_packet; if (!version().HasIetfQuicFrames()) { probing_packet = packet_creator_.SerializeConnectivityProbingPacket(); } else { QuicPathFrameBuffer transmitted_connectivity_probe_payload; random_generator_->RandBytes(&transmitted_connectivity_probe_payload, sizeof(QuicPathFrameBuffer)); probing_packet = packet_creator_.SerializePathChallengeConnectivityProbingPacket( transmitted_connectivity_probe_payload); } QUICHE_DCHECK_EQ(IsRetransmittable(*probing_packet), NO_RETRANSMITTABLE_DATA); return WritePacketUsingWriter(std::move(probing_packet), probing_writer, self_address(), peer_address, true); } bool QuicConnection::WritePacketUsingWriter( std::unique_ptr<SerializedPacket> packet, QuicPacketWriter* writer, const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, bool measure_rtt) { const QuicTime packet_send_time = clock_->Now(); QUIC_BUG_IF(write using blocked writer, writer->IsWriteBlocked()); QUIC_DVLOG(2) << ENDPOINT << "Sending path probe packet for server connection ID " << default_path_.server_connection_id << std::endl << quiche::QuicheTextUtils::HexDump(absl::string_view( packet->encrypted_buffer, packet->encrypted_length)); WriteResult result = SendPacketToWriter( packet->encrypted_buffer, packet->encrypted_length, self_address.host(), peer_address, writer, GetEcnCodepointToSend(peer_address)); const uint32_t writer_batch_id = result.batch_id; if (writer->IsBatchMode() && result.status == WRITE_STATUS_OK && result.bytes_written == 0) { result = writer->Flush(); } if (IsWriteError(result.status)) { QUIC_DLOG(INFO) << ENDPOINT << "Write probing packet failed with error = " << result.error_code; return false; } sent_packet_manager_.OnPacketSent( packet.get(), packet_send_time, packet->transmission_type, NO_RETRANSMITTABLE_DATA, measure_rtt, last_ecn_codepoint_sent_); if (debug_visitor_ != nullptr) { if (sent_packet_manager_.unacked_packets().empty()) { QUIC_BUG(quic_bug_10511_32) << "Unacked map is empty right after packet is sent"; } else { debug_visitor_->OnPacketSent( packet->packet_number, packet->encrypted_length, packet->has_crypto_handshake, packet->transmission_type, packet->encryption_level, sent_packet_manager_.unacked_packets() .rbegin() ->retransmittable_frames, packet->nonretransmittable_frames, packet_send_time, writer_batch_id); } } if (IsWriteBlockedStatus(result.status)) { if (writer == writer_) { visitor_->OnWriteBlocked(); } if (result.status == WRITE_STATUS_BLOCKED_DATA_BUFFERED) { QUIC_DLOG(INFO) << ENDPOINT << "Write probing packet blocked"; } } return true; } void QuicConnection::DisableMtuDiscovery() { mtu_discoverer_.Disable(); mtu_discovery_alarm().Cancel(); } void QuicConnection::OnMtuDiscoveryAlarm() { QUICHE_DCHECK(connected()); QUICHE_DCHECK(!mtu_discovery_alarm().IsSet()); const QuicPacketNumber largest_sent_packet = sent_packet_manager_.GetLargestSentPacket(); if (mtu_discoverer_.ShouldProbeMtu(largest_sent_packet)) { ++mtu_probe_count_; SendMtuDiscoveryPacket( mtu_discoverer_.GetUpdatedMtuProbeSize(largest_sent_packet)); } QUICHE_DCHECK(!mtu_discovery_alarm().IsSet()); } void QuicConnection::OnEffectivePeerMigrationValidated( bool ) { if (active_effective_peer_migration_type_ == NO_CHANGE) { QUIC_BUG(quic_bug_10511_33) << "No migration underway."; return; } highest_packet_sent_before_effective_peer_migration_.Clear(); const bool send_address_token = active_effective_peer_migration_type_ != PORT_CHANGE; active_effective_peer_migration_type_ = NO_CHANGE; ++stats_.num_validated_peer_migration; if (!framer_.version().HasIetfQuicFrames()) { return; } if (debug_visitor_ != nullptr) { const QuicTime now = clock_->ApproximateNow(); if (now >= stats_.handshake_completion_time) { debug_visitor_->OnPeerMigrationValidated( now - stats_.handshake_completion_time); } else { QUIC_BUG(quic_bug_10511_34) << "Handshake completion time is larger than current time."; } } default_path_.validated = true; alternative_path_.Clear(); if (send_address_token) { visitor_->MaybeSendAddressToken(); } } void QuicConnection::StartEffectivePeerMigration(AddressChangeType type) { if (!framer_.version().HasIetfQuicFrames()) { if (type == NO_CHANGE) { QUIC_BUG(quic_bug_10511_35) << "EffectivePeerMigration started without address change."; return; } QUIC_DLOG(INFO) << ENDPOINT << "Effective peer's ip:port changed from " << default_path_.peer_address.ToString() << " to " << GetEffectivePeerAddressFromCurrentPacket().ToString() << ", address change type is " << type << ", migrating connection without validating new client address."; highest_packet_sent_before_effective_peer_migration_ = sent_packet_manager_.GetLargestSentPacket(); default_path_.peer_address = GetEffectivePeerAddressFromCurrentPacket(); active_effective_peer_migration_type_ = type; OnConnectionMigration(); return; } if (type == NO_CHANGE) { UpdatePeerAddress(last_received_packet_info_.source_address); QUIC_BUG(quic_bug_10511_36) << "EffectivePeerMigration started without address change."; return; } packet_creator_.FlushCurrentPacket(); packet_creator_.SendRemainingPendingPadding(); if (!connected_) { return; } const QuicSocketAddress current_effective_peer_address = GetEffectivePeerAddressFromCurrentPacket(); QUIC_DLOG(INFO) << ENDPOINT << "Effective peer's ip:port changed from " << default_path_.peer_address.ToString() << " to " << current_effective_peer_address.ToString() << ", address change type is " << type << ", migrating connection."; const QuicSocketAddress previous_direct_peer_address = direct_peer_address_; PathState previous_default_path = std::move(default_path_); active_effective_peer_migration_type_ = type; MaybeClearQueuedPacketsOnPathChange(); OnConnectionMigration(); if (type == PORT_CHANGE) { QUICHE_DCHECK(previous_default_path.validated || (alternative_path_.validated && alternative_path_.send_algorithm != nullptr)); } else { previous_default_path.rtt_stats.emplace(); previous_default_path.rtt_stats->CloneFrom( *sent_packet_manager_.GetRttStats()); previous_default_path.send_algorithm = OnPeerIpAddressChanged(); if (alternative_path_.peer_address.host() == current_effective_peer_address.host() && alternative_path_.send_algorithm != nullptr && alternative_path_.rtt_stats.has_value()) { sent_packet_manager_.SetSendAlgorithm( alternative_path_.send_algorithm.release()); sent_packet_manager_.SetRttStats(*alternative_path_.rtt_stats); alternative_path_.rtt_stats = std::nullopt; } } UpdatePeerAddress(last_received_packet_info_.source_address); if (IsAlternativePath(last_received_packet_info_.destination_address, current_effective_peer_address)) { SetDefaultPathState(std::move(alternative_path_)); } else { QuicConnectionId client_connection_id; std::optional<StatelessResetToken> stateless_reset_token; FindMatchingOrNewClientConnectionIdOrToken( previous_default_path, alternative_path_, last_received_packet_info_.destination_connection_id, &client_connection_id, &stateless_reset_token); SetDefaultPathState( PathState(last_received_packet_info_.destination_address, current_effective_peer_address, client_connection_id, last_received_packet_info_.destination_connection_id, stateless_reset_token)); default_path_.validated = (alternative_path_.peer_address.host() == current_effective_peer_address.host() && alternative_path_.validated) || (previous_default_path.validated && type == PORT_CHANGE); } if (!last_received_packet_info_.received_bytes_counted) { default_path_.bytes_received_before_address_validation += last_received_packet_info_.length; last_received_packet_info_.received_bytes_counted = true; } if (!previous_default_path.validated) { QUIC_DVLOG(1) << "Cancel validation of previous peer address change to " << previous_default_path.peer_address << " upon peer migration to " << default_path_.peer_address; path_validator_.CancelPathValidation(); ++stats_.num_peer_migration_while_validating_default_path; } if (alternative_path_.peer_address.host() == default_path_.peer_address.host()) { alternative_path_.Clear(); } if (default_path_.validated) { QUIC_DVLOG(1) << "Peer migrated to a validated address."; if (!(previous_default_path.validated && type == PORT_CHANGE)) { ++stats_.num_peer_migration_to_proactively_validated_address; } OnEffectivePeerMigrationValidated( default_path_.server_connection_id == previous_default_path.server_connection_id); return; } QUICHE_DCHECK(EnforceAntiAmplificationLimit()); QUIC_DVLOG(1) << "Apply anti-amplification limit to effective peer address " << default_path_.peer_address << " with " << default_path_.bytes_sent_before_address_validation << " bytes sent and " << default_path_.bytes_received_before_address_validation << " bytes received."; QUICHE_DCHECK(!alternative_path_.peer_address.IsInitialized() || alternative_path_.peer_address.host() != default_path_.peer_address.host()); if (previous_default_path.validated) { alternative_path_ = std::move(previous_default_path); QUICHE_DCHECK(alternative_path_.send_algorithm != nullptr); } if (!path_validator_.IsValidatingPeerAddress( current_effective_peer_address)) { ++stats_.num_reverse_path_validtion_upon_migration; ValidatePath(std::make_unique<ReversePathValidationContext>( default_path_.self_address, peer_address(), default_path_.peer_address, this), std::make_unique<ReversePathValidationResultDelegate>( this, previous_direct_peer_address), PathValidationReason::kReversePathValidation); } else { QUIC_DVLOG(1) << "Peer address " << default_path_.peer_address << " is already under validation, wait for result."; ++stats_.num_peer_migration_to_proactively_validated_address; } } void QuicConnection::OnConnectionMigration() { if (debug_visitor_ != nullptr) { const QuicTime now = clock_->ApproximateNow(); if (now >= stats_.handshake_completion_time) { debug_visitor_->OnPeerAddressChange( active_effective_peer_migration_type_, now - stats_.handshake_completion_time); } } visitor_->OnConnectionMigration(active_effective_peer_migration_type_); if (active_effective_peer_migration_type_ != PORT_CHANGE && active_effective_peer_migration_type_ != IPV4_SUBNET_CHANGE && !framer_.version().HasIetfQuicFrames()) { sent_packet_manager_.OnConnectionMigration(false); } } bool QuicConnection::IsCurrentPacketConnectivityProbing() const { return is_current_packet_connectivity_probing_; } bool QuicConnection::ack_frame_updated() const { return uber_received_packet_manager_.IsAckFrameUpdated(); } absl::string_view QuicConnection::GetCurrentPacket() { if (current_packet_data_ == nullptr) { return absl::string_view(); } return absl::string_view(current_packet_data_, last_received_packet_info_.length); } bool QuicConnection::MaybeConsiderAsMemoryCorruption( const QuicStreamFrame& frame) { if (QuicUtils::IsCryptoStreamId(transport_version(), frame.stream_id) || last_received_packet_info_.decrypted_level != ENCRYPTION_INITIAL) { return false; } if (perspective_ == Perspective::IS_SERVER && frame.data_length >= sizeof(kCHLO) && strncmp(frame.data_buffer, reinterpret_cast<const char*>(&kCHLO), sizeof(kCHLO)) == 0) { return true; } if (perspective_ == Perspective::IS_CLIENT && frame.data_length >= sizeof(kREJ) && strncmp(frame.data_buffer, reinterpret_cast<const char*>(&kREJ), sizeof(kREJ)) == 0) { return true; } return false; } void QuicConnection::CheckIfApplicationLimited() { if (!connected_) { return; } bool application_limited = buffered_packets_.empty() && !visitor_->WillingAndAbleToWrite(); if (!application_limited) { return; } sent_packet_manager_.OnApplicationLimited(); } bool QuicConnection::UpdatePacketContent(QuicFrameType type) { last_received_packet_info_.frames.push_back(type); if (version().HasIetfQuicFrames()) { if (perspective_ == Perspective::IS_CLIENT) { return connected_; } if (!QuicUtils::IsProbingFrame(type)) { MaybeStartIetfPeerMigration(); return connected_; } QuicSocketAddress current_effective_peer_address = GetEffectivePeerAddressFromCurrentPacket(); if (IsDefaultPath(last_received_packet_info_.destination_address, last_received_packet_info_.source_address)) { return connected_; } if (type == PATH_CHALLENGE_FRAME && !IsAlternativePath(last_received_packet_info_.destination_address, current_effective_peer_address)) { QUIC_DVLOG(1) << "The peer is probing a new path with effective peer address " << current_effective_peer_address << ", self address " << last_received_packet_info_.destination_address; if (!default_path_.validated) { QUIC_DVLOG(1) << "The connection hasn't finished handshake or is " "validating a recent peer address change."; QUIC_BUG_IF(quic_bug_12714_30, IsHandshakeConfirmed() && !alternative_path_.validated) << "No validated peer address to send after handshake comfirmed."; } else if (!IsReceivedPeerAddressValidated()) { QuicConnectionId client_connection_id; std::optional<StatelessResetToken> stateless_reset_token; FindMatchingOrNewClientConnectionIdOrToken( default_path_, alternative_path_, last_received_packet_info_.destination_connection_id, &client_connection_id, &stateless_reset_token); alternative_path_ = PathState(last_received_packet_info_.destination_address, current_effective_peer_address, client_connection_id, last_received_packet_info_.destination_connection_id, stateless_reset_token); should_proactively_validate_peer_address_on_path_challenge_ = true; } } MaybeUpdateBytesReceivedFromAlternativeAddress( last_received_packet_info_.length); return connected_; } if (!ignore_gquic_probing_) { if (current_packet_content_ == NOT_PADDED_PING) { return connected_; } if (type == PING_FRAME) { if (current_packet_content_ == NO_FRAMES_RECEIVED) { current_packet_content_ = FIRST_FRAME_IS_PING; return connected_; } } if (type == PADDING_FRAME && current_packet_content_ == FIRST_FRAME_IS_PING) { current_packet_content_ = SECOND_FRAME_IS_PADDING; QUIC_CODE_COUNT_N(gquic_padded_ping_received, 1, 2); if (perspective_ == Perspective::IS_SERVER) { is_current_packet_connectivity_probing_ = current_effective_peer_migration_type_ != NO_CHANGE; if (is_current_packet_connectivity_probing_) { QUIC_CODE_COUNT_N(gquic_padded_ping_received, 2, 2); } QUIC_DLOG_IF(INFO, is_current_packet_connectivity_probing_) << ENDPOINT << "Detected connectivity probing packet. " "current_effective_peer_migration_type_:" << current_effective_peer_migration_type_; } else { is_current_packet_connectivity_probing_ = (last_received_packet_info_.source_address != peer_address()) || (last_received_packet_info_.destination_address != default_path_.self_address); QUIC_DLOG_IF(INFO, is_current_packet_connectivity_probing_) << ENDPOINT << "Detected connectivity probing packet. " "last_packet_source_address:" << last_received_packet_info_.source_address << ", peer_address_:" << peer_address() << ", last_packet_destination_address:" << last_received_packet_info_.destination_address << ", default path self_address :" << default_path_.self_address; } return connected_; } current_packet_content_ = NOT_PADDED_PING; } else { QUIC_RELOADABLE_FLAG_COUNT(quic_ignore_gquic_probing); QUICHE_DCHECK_EQ(current_packet_content_, NO_FRAMES_RECEIVED); } if (GetLargestReceivedPacket().IsInitialized() && last_received_packet_info_.header.packet_number == GetLargestReceivedPacket()) { UpdatePeerAddress(last_received_packet_info_.source_address); if (current_effective_peer_migration_type_ != NO_CHANGE) { StartEffectivePeerMigration(current_effective_peer_migration_type_); } } current_effective_peer_migration_type_ = NO_CHANGE; return connected_; } void QuicConnection::MaybeStartIetfPeerMigration() { QUICHE_DCHECK(version().HasIetfQuicFrames()); if (current_effective_peer_migration_type_ != NO_CHANGE && !IsHandshakeConfirmed()) { QUIC_LOG_EVERY_N_SEC(INFO, 60) << ENDPOINT << "Effective peer's ip:port changed from " << default_path_.peer_address.ToString() << " to " << GetEffectivePeerAddressFromCurrentPacket().ToString() << " before handshake confirmed, " "current_effective_peer_migration_type_: " << current_effective_peer_migration_type_; CloseConnection( (current_effective_peer_migration_type_ == PORT_CHANGE ? QUIC_PEER_PORT_CHANGE_HANDSHAKE_UNCONFIRMED : QUIC_CONNECTION_MIGRATION_HANDSHAKE_UNCONFIRMED), absl::StrFormat( "Peer address changed from %s to %s before handshake is confirmed.", default_path_.peer_address.ToString(), GetEffectivePeerAddressFromCurrentPacket().ToString()), ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } if (GetLargestReceivedPacket().IsInitialized() && last_received_packet_info_.header.packet_number == GetLargestReceivedPacket()) { if (current_effective_peer_migration_type_ != NO_CHANGE) { StartEffectivePeerMigration(current_effective_peer_migration_type_); } else { UpdatePeerAddress(last_received_packet_info_.source_address); } } current_effective_peer_migration_type_ = NO_CHANGE; } void QuicConnection::PostProcessAfterAckFrame(bool acked_new_packet) { if (!packet_creator_.has_ack()) { uber_received_packet_manager_.DontWaitForPacketsBefore( last_received_packet_info_.decrypted_level, SupportsMultiplePacketNumberSpaces() ? sent_packet_manager_.GetLargestPacketPeerKnowsIsAcked( last_received_packet_info_.decrypted_level) : sent_packet_manager_.largest_packet_peer_knows_is_acked()); } SetRetransmissionAlarm(); if (acked_new_packet) { OnForwardProgressMade(); } else if (default_enable_5rto_blackhole_detection_ && !sent_packet_manager_.HasInFlightPackets() && blackhole_detector_.IsDetectionInProgress()) { blackhole_detector_.StopDetection(false); } } void QuicConnection::SetSessionNotifier( SessionNotifierInterface* session_notifier) { sent_packet_manager_.SetSessionNotifier(session_notifier); } void QuicConnection::SetDataProducer( QuicStreamFrameDataProducer* data_producer) { framer_.set_data_producer(data_producer); } void QuicConnection::SetTransmissionType(TransmissionType type) { packet_creator_.SetTransmissionType(type); } void QuicConnection::UpdateReleaseTimeIntoFuture() { QUICHE_DCHECK(supports_release_time_); const QuicTime::Delta prior_max_release_time = release_time_into_future_; release_time_into_future_ = std::max( QuicTime::Delta::FromMilliseconds(kMinReleaseTimeIntoFutureMs), std::min(QuicTime::Delta::FromMilliseconds( GetQuicFlag(quic_max_pace_time_into_future_ms)), sent_packet_manager_.GetRttStats()->SmoothedOrInitialRtt() * GetQuicFlag(quic_pace_time_into_future_srtt_fraction))); QUIC_DVLOG(3) << "Updated max release time delay from " << prior_max_release_time << " to " << release_time_into_future_; } void QuicConnection::ResetAckStates() { ack_alarm().Cancel(); uber_received_packet_manager_.ResetAckStates(encryption_level_); } MessageStatus QuicConnection::SendMessage( QuicMessageId message_id, absl::Span<quiche::QuicheMemSlice> message, bool flush) { if (MemSliceSpanTotalSize(message) > GetCurrentLargestMessagePayload()) { return MESSAGE_STATUS_TOO_LARGE; } if (!connected_ || (!flush && !CanWrite(HAS_RETRANSMITTABLE_DATA))) { return MESSAGE_STATUS_BLOCKED; } ScopedPacketFlusher flusher(this); return packet_creator_.AddMessageFrame(message_id, message); } QuicPacketLength QuicConnection::GetCurrentLargestMessagePayload() const { return packet_creator_.GetCurrentLargestMessagePayload(); } QuicPacketLength QuicConnection::GetGuaranteedLargestMessagePayload() const { return packet_creator_.GetGuaranteedLargestMessagePayload(); } uint32_t QuicConnection::cipher_id() const { if (version().KnowsWhichDecrypterToUse()) { if (quic_limit_new_streams_per_loop_2_) { QUIC_RELOADABLE_FLAG_COUNT_N(quic_limit_new_streams_per_loop_2, 4, 4); for (auto decryption_level : {ENCRYPTION_FORWARD_SECURE, ENCRYPTION_HANDSHAKE, ENCRYPTION_ZERO_RTT, ENCRYPTION_INITIAL}) { const QuicDecrypter* decrypter = framer_.GetDecrypter(decryption_level); if (decrypter != nullptr) { return decrypter->cipher_id(); } } QUICHE_BUG(no_decrypter_found) << ENDPOINT << "No decrypter found at all encryption levels"; return 0; } else { return framer_.GetDecrypter(last_received_packet_info_.decrypted_level) ->cipher_id(); } } return framer_.decrypter()->cipher_id(); } EncryptionLevel QuicConnection::GetConnectionCloseEncryptionLevel() const { if (perspective_ == Perspective::IS_CLIENT) { return encryption_level_; } if (IsHandshakeComplete()) { QUIC_BUG_IF(quic_bug_12714_31, encryption_level_ != ENCRYPTION_FORWARD_SECURE) << ENDPOINT << "Unexpected connection close encryption level " << encryption_level_; return ENCRYPTION_FORWARD_SECURE; } if (framer_.HasEncrypterOfEncryptionLevel(ENCRYPTION_ZERO_RTT)) { if (encryption_level_ != ENCRYPTION_ZERO_RTT) { QUIC_CODE_COUNT(quic_wrong_encryption_level_connection_close_ietf); } return ENCRYPTION_ZERO_RTT; } return ENCRYPTION_INITIAL; } void QuicConnection::MaybeBundleCryptoDataWithAcks() { QUICHE_DCHECK(SupportsMultiplePacketNumberSpaces()); if (IsHandshakeConfirmed()) { return; } PacketNumberSpace space = HANDSHAKE_DATA; if (perspective() == Perspective::IS_SERVER && framer_.HasEncrypterOfEncryptionLevel(ENCRYPTION_INITIAL)) { space = INITIAL_DATA; } const QuicTime ack_timeout = uber_received_packet_manager_.GetAckTimeout(space); if (!ack_timeout.IsInitialized() || (ack_timeout > clock_->ApproximateNow() && ack_timeout > uber_received_packet_manager_.GetEarliestAckTimeout())) { return; } if (coalesced_packet_.length() > 0) { return; } if (!framer_.HasAnEncrypterForSpace(space)) { QUIC_BUG(quic_bug_10511_39) << ENDPOINT << "Try to bundle crypto with ACK with missing key of space " << PacketNumberSpaceToString(space); return; } sent_packet_manager_.RetransmitDataOfSpaceIfAny(space); } void QuicConnection::SendAllPendingAcks() { QUICHE_DCHECK(SupportsMultiplePacketNumberSpaces()); QUIC_DVLOG(1) << ENDPOINT << "Trying to send all pending ACKs"; ack_alarm().Cancel(); QuicTime earliest_ack_timeout = uber_received_packet_manager_.GetEarliestAckTimeout(); QUIC_BUG_IF(quic_bug_12714_32, !earliest_ack_timeout.IsInitialized()); MaybeBundleCryptoDataWithAcks(); visitor_->MaybeBundleOpportunistically(); earliest_ack_timeout = uber_received_packet_manager_.GetEarliestAckTimeout(); if (!earliest_ack_timeout.IsInitialized()) { return; } for (int8_t i = INITIAL_DATA; i <= APPLICATION_DATA; ++i) { const QuicTime ack_timeout = uber_received_packet_manager_.GetAckTimeout( static_cast<PacketNumberSpace>(i)); if (!ack_timeout.IsInitialized()) { continue; } if (!framer_.HasAnEncrypterForSpace(static_cast<PacketNumberSpace>(i))) { continue; } if (ack_timeout > clock_->ApproximateNow() && ack_timeout > earliest_ack_timeout) { continue; } QUIC_DVLOG(1) << ENDPOINT << "Sending ACK of packet number space " << PacketNumberSpaceToString( static_cast<PacketNumberSpace>(i)); ScopedEncryptionLevelContext context( this, QuicUtils::GetEncryptionLevelToSendAckofSpace( static_cast<PacketNumberSpace>(i))); QuicFrames frames; frames.push_back(uber_received_packet_manager_.GetUpdatedAckFrame( static_cast<PacketNumberSpace>(i), clock_->ApproximateNow())); const bool flushed = packet_creator_.FlushAckFrame(frames); if (!flushed) { QUIC_BUG_IF(quic_bug_12714_33, connected_ && !writer_->IsWriteBlocked() && !LimitedByAmplificationFactor( packet_creator_.max_packet_length()) && !IsMissingDestinationConnectionID()) << "Writer not blocked and not throttled by amplification factor, " "but ACK not flushed for packet space:" << PacketNumberSpaceToString(static_cast<PacketNumberSpace>(i)) << ", fill_coalesced_packet: " << fill_coalesced_packet_ << ", blocked_by_no_connection_id: " << (peer_issued_cid_manager_ != nullptr && packet_creator_.GetDestinationConnectionId().IsEmpty()) << ", has_soft_max_packet_length: " << packet_creator_.HasSoftMaxPacketLength() << ", max_packet_length: " << packet_creator_.max_packet_length() << ", pending frames: " << packet_creator_.GetPendingFramesInfo(); break; } ResetAckStates(); } const QuicTime timeout = uber_received_packet_manager_.GetEarliestAckTimeout(); if (timeout.IsInitialized()) { ack_alarm().Update(timeout, kAlarmGranularity); } if (encryption_level_ != ENCRYPTION_FORWARD_SECURE || !ShouldBundleRetransmittableFrameWithAck()) { return; } consecutive_num_packets_with_no_retransmittable_frames_ = 0; if (packet_creator_.HasPendingRetransmittableFrames() || visitor_->WillingAndAbleToWrite()) { return; } visitor_->OnAckNeedsRetransmittableFrame(); } bool QuicConnection::ShouldBundleRetransmittableFrameWithAck() const { if (consecutive_num_packets_with_no_retransmittable_frames_ >= max_consecutive_num_packets_with_no_retransmittable_frames_) { return true; } if (bundle_retransmittable_with_pto_ack_ && sent_packet_manager_.GetConsecutivePtoCount() > 0) { return true; } return false; } void QuicConnection::MaybeCoalescePacketOfHigherSpace() { if (!connected() || !packet_creator_.HasSoftMaxPacketLength()) { return; } if (fill_coalesced_packet_) { QUIC_BUG(quic_coalesce_packet_reentrant); return; } for (EncryptionLevel retransmission_level : {ENCRYPTION_INITIAL, ENCRYPTION_HANDSHAKE}) { const EncryptionLevel coalesced_level = retransmission_level == ENCRYPTION_INITIAL ? ENCRYPTION_HANDSHAKE : ENCRYPTION_FORWARD_SECURE; if (coalesced_packet_.ContainsPacketOfEncryptionLevel( retransmission_level) && coalesced_packet_.TransmissionTypeOfPacket(retransmission_level) != NOT_RETRANSMISSION && framer_.HasEncrypterOfEncryptionLevel(coalesced_level) && !coalesced_packet_.ContainsPacketOfEncryptionLevel(coalesced_level)) { QUIC_DVLOG(1) << ENDPOINT << "Trying to coalesce packet of encryption level: " << EncryptionLevelToString(coalesced_level); fill_coalesced_packet_ = true; sent_packet_manager_.RetransmitDataOfSpaceIfAny( QuicUtils::GetPacketNumberSpace(coalesced_level)); fill_coalesced_packet_ = false; } } } bool QuicConnection::FlushCoalescedPacket() { ScopedCoalescedPacketClearer clearer(&coalesced_packet_); if (!connected_) { return false; } if (!version().CanSendCoalescedPackets()) { QUIC_BUG_IF(quic_bug_12714_34, coalesced_packet_.length() > 0); return true; } if (coalesced_packet_.ContainsPacketOfEncryptionLevel(ENCRYPTION_INITIAL) && !framer_.HasEncrypterOfEncryptionLevel(ENCRYPTION_INITIAL)) { QUIC_BUG(quic_bug_10511_40) << ENDPOINT << "Coalescer contains initial packet while initial key has " "been dropped."; coalesced_packet_.NeuterInitialPacket(); } if (coalesced_packet_.length() == 0) { return true; } char buffer[kMaxOutgoingPacketSize]; const size_t length = packet_creator_.SerializeCoalescedPacket( coalesced_packet_, buffer, coalesced_packet_.max_packet_length()); if (length == 0) { if (connected_) { CloseConnection(QUIC_FAILED_TO_SERIALIZE_PACKET, "Failed to serialize coalesced packet.", ConnectionCloseBehavior::SILENT_CLOSE); } return false; } if (debug_visitor_ != nullptr) { debug_visitor_->OnCoalescedPacketSent(coalesced_packet_, length); } QUIC_DVLOG(1) << ENDPOINT << "Sending coalesced packet " << coalesced_packet_.ToString(length); const size_t padding_size = length - std::min<size_t>(length, coalesced_packet_.length()); if (!buffered_packets_.empty() || HandleWriteBlocked() || (enforce_strict_amplification_factor_ && LimitedByAmplificationFactor(padding_size))) { QUIC_DVLOG(1) << ENDPOINT << "Buffering coalesced packet of len: " << length; buffered_packets_.emplace_back( buffer, static_cast<QuicPacketLength>(length), coalesced_packet_.self_address(), coalesced_packet_.peer_address(), coalesced_packet_.ecn_codepoint()); } else { WriteResult result = SendPacketToWriter( buffer, length, coalesced_packet_.self_address().host(), coalesced_packet_.peer_address(), writer_, coalesced_packet_.ecn_codepoint()); if (IsWriteError(result.status)) { OnWriteError(result.error_code); return false; } if (IsWriteBlockedStatus(result.status)) { visitor_->OnWriteBlocked(); if (result.status != WRITE_STATUS_BLOCKED_DATA_BUFFERED) { QUIC_DVLOG(1) << ENDPOINT << "Buffering coalesced packet of len: " << length; buffered_packets_.emplace_back( buffer, static_cast<QuicPacketLength>(length), coalesced_packet_.self_address(), coalesced_packet_.peer_address(), coalesced_packet_.ecn_codepoint()); } } } if (accelerated_server_preferred_address_ && stats_.num_duplicated_packets_sent_to_server_preferred_address < kMaxDuplicatedPacketsSentToServerPreferredAddress) { QUICHE_DCHECK(received_server_preferred_address_.IsInitialized()); path_validator_.MaybeWritePacketToAddress( buffer, length, received_server_preferred_address_); ++stats_.num_duplicated_packets_sent_to_server_preferred_address; } if (length > coalesced_packet_.length()) { if (IsDefaultPath(coalesced_packet_.self_address(), coalesced_packet_.peer_address())) { if (EnforceAntiAmplificationLimit()) { default_path_.bytes_sent_before_address_validation += padding_size; } } else { MaybeUpdateBytesSentToAlternativeAddress(coalesced_packet_.peer_address(), padding_size); } stats_.bytes_sent += padding_size; if (coalesced_packet_.initial_packet() != nullptr && coalesced_packet_.initial_packet()->transmission_type != NOT_RETRANSMISSION) { stats_.bytes_retransmitted += padding_size; } } return true; } void QuicConnection::MaybeEnableMultiplePacketNumberSpacesSupport() { if (version().handshake_protocol != PROTOCOL_TLS1_3) { return; } QUIC_DVLOG(1) << ENDPOINT << "connection " << connection_id() << " supports multiple packet number spaces"; framer_.EnableMultiplePacketNumberSpacesSupport(); sent_packet_manager_.EnableMultiplePacketNumberSpacesSupport(); uber_received_packet_manager_.EnableMultiplePacketNumberSpacesSupport( perspective_); } bool QuicConnection::SupportsMultiplePacketNumberSpaces() const { return sent_packet_manager_.supports_multiple_packet_number_spaces(); } void QuicConnection::SetLargestReceivedPacketWithAck( QuicPacketNumber new_value) { if (SupportsMultiplePacketNumberSpaces()) { largest_seen_packets_with_ack_[QuicUtils::GetPacketNumberSpace( last_received_packet_info_.decrypted_level)] = new_value; } else { largest_seen_packet_with_ack_ = new_value; } } void QuicConnection::OnForwardProgressMade() { if (!connected_) { return; } if (is_path_degrading_) { visitor_->OnForwardProgressMadeAfterPathDegrading(); stats_.num_forward_progress_after_path_degrading++; is_path_degrading_ = false; } if (sent_packet_manager_.HasInFlightPackets()) { blackhole_detector_.RestartDetection(GetPathDegradingDeadline(), GetNetworkBlackholeDeadline(), GetPathMtuReductionDeadline()); } else { blackhole_detector_.StopDetection(false); } QUIC_BUG_IF(quic_bug_12714_35, perspective_ == Perspective::IS_SERVER && default_enable_5rto_blackhole_detection_ && blackhole_detector_.IsDetectionInProgress() && !sent_packet_manager_.HasInFlightPackets()) << ENDPOINT << "Trying to start blackhole detection without no bytes in flight"; } QuicPacketNumber QuicConnection::GetLargestReceivedPacketWithAck() const { if (SupportsMultiplePacketNumberSpaces()) { return largest_seen_packets_with_ack_[QuicUtils::GetPacketNumberSpace( last_received_packet_info_.decrypted_level)]; } return largest_seen_packet_with_ack_; } QuicPacketNumber QuicConnection::GetLargestAckedPacket() const { if (SupportsMultiplePacketNumberSpaces()) { return sent_packet_manager_.GetLargestAckedPacket( last_received_packet_info_.decrypted_level); } return sent_packet_manager_.GetLargestObserved(); } QuicPacketNumber QuicConnection::GetLargestReceivedPacket() const { return uber_received_packet_manager_.GetLargestObserved( last_received_packet_info_.decrypted_level); } bool QuicConnection::EnforceAntiAmplificationLimit() const { return version().SupportsAntiAmplificationLimit() && perspective_ == Perspective::IS_SERVER && !default_path_.validated; } bool QuicConnection::ShouldFixTimeouts(const QuicConfig& config) const { return quic_fix_timeouts_ && version().UsesTls() && config.HasClientSentConnectionOption(kFTOE, perspective_); } bool QuicConnection::LimitedByAmplificationFactor(QuicByteCount bytes) const { return EnforceAntiAmplificationLimit() && (default_path_.bytes_sent_before_address_validation + (enforce_strict_amplification_factor_ ? bytes : 0)) >= anti_amplification_factor_ * default_path_.bytes_received_before_address_validation; } SerializedPacketFate QuicConnection::GetSerializedPacketFate( bool is_mtu_discovery, EncryptionLevel encryption_level) { if (ShouldDiscardPacket(encryption_level)) { return DISCARD; } if (version().CanSendCoalescedPackets() && !coalescing_done_ && !is_mtu_discovery) { if (!IsHandshakeConfirmed()) { return COALESCE; } if (coalesced_packet_.length() > 0) { return COALESCE; } } if (!buffered_packets_.empty() || HandleWriteBlocked()) { return BUFFER; } return SEND_TO_WRITER; } bool QuicConnection::IsHandshakeComplete() const { return visitor_->GetHandshakeState() >= HANDSHAKE_COMPLETE; } bool QuicConnection::IsHandshakeConfirmed() const { QUICHE_DCHECK_EQ(PROTOCOL_TLS1_3, version().handshake_protocol); return visitor_->GetHandshakeState() == HANDSHAKE_CONFIRMED; } size_t QuicConnection::min_received_before_ack_decimation() const { return uber_received_packet_manager_.min_received_before_ack_decimation(); } void QuicConnection::set_min_received_before_ack_decimation(size_t new_value) { uber_received_packet_manager_.set_min_received_before_ack_decimation( new_value); } const QuicAckFrame& QuicConnection::ack_frame() const { if (SupportsMultiplePacketNumberSpaces()) { return uber_received_packet_manager_.GetAckFrame( QuicUtils::GetPacketNumberSpace( last_received_packet_info_.decrypted_level)); } return uber_received_packet_manager_.ack_frame(); } void QuicConnection::set_client_connection_id( QuicConnectionId client_connection_id) { if (!version().SupportsClientConnectionIds()) { QUIC_BUG_IF(quic_bug_12714_36, !client_connection_id.IsEmpty()) << ENDPOINT << "Attempted to use client connection ID " << client_connection_id << " with unsupported version " << version(); return; } default_path_.client_connection_id = client_connection_id; client_connection_id_is_set_ = true; if (version().HasIetfQuicFrames() && !client_connection_id.IsEmpty()) { if (perspective_ == Perspective::IS_SERVER) { QUICHE_DCHECK(peer_issued_cid_manager_ == nullptr); peer_issued_cid_manager_ = std::make_unique<QuicPeerIssuedConnectionIdManager>( kMinNumOfActiveConnectionIds, client_connection_id, clock_, alarm_factory_, this, context()); } else { bool create_client_self_issued_cid_manager = true; quiche::AdjustTestValue( "quic::QuicConnection::create_cid_manager_when_set_client_cid", &create_client_self_issued_cid_manager); if (create_client_self_issued_cid_manager) { self_issued_cid_manager_ = MakeSelfIssuedConnectionIdManager(); } } } QUIC_DLOG(INFO) << ENDPOINT << "setting client connection ID to " << default_path_.client_connection_id << " for connection with server connection ID " << default_path_.server_connection_id; packet_creator_.SetClientConnectionId(default_path_.client_connection_id); framer_.SetExpectedClientConnectionIdLength( default_path_.client_connection_id.length()); } void QuicConnection::OnPathDegradingDetected() { is_path_degrading_ = true; visitor_->OnPathDegrading(); stats_.num_path_degrading++; if (multi_port_stats_ && multi_port_migration_enabled_) { MaybeMigrateToMultiPortPath(); } } void QuicConnection::MaybeMigrateToMultiPortPath() { if (!alternative_path_.validated) { QUIC_CLIENT_HISTOGRAM_ENUM( "QuicConnection.MultiPortPathStatusWhenMigrating", MultiPortStatusOnMigration::kNotValidated, MultiPortStatusOnMigration::kMaxValue, "Status of the multi port path upon migration"); return; } std::unique_ptr<QuicPathValidationContext> context; const bool has_pending_validation = path_validator_.HasPendingPathValidation(); if (!has_pending_validation) { context = std::move(multi_port_path_context_); multi_port_probing_alarm().Cancel(); QUIC_CLIENT_HISTOGRAM_ENUM( "QuicConnection.MultiPortPathStatusWhenMigrating", MultiPortStatusOnMigration::kWaitingForRefreshValidation, MultiPortStatusOnMigration::kMaxValue, "Status of the multi port path upon migration"); } else { context = path_validator_.ReleaseContext(); QUIC_CLIENT_HISTOGRAM_ENUM( "QuicConnection.MultiPortPathStatusWhenMigrating", MultiPortStatusOnMigration::kPendingRefreshValidation, MultiPortStatusOnMigration::kMaxValue, "Status of the multi port path upon migration"); } if (context == nullptr) { QUICHE_BUG(quic_bug_12714_90) << "No multi-port context to migrate to"; return; } visitor_->MigrateToMultiPortPath(std::move(context)); } void QuicConnection::OnBlackholeDetected() { if (default_enable_5rto_blackhole_detection_ && !sent_packet_manager_.HasInFlightPackets()) { QUIC_BUG(quic_bug_10511_41) << ENDPOINT << "Blackhole detected, but there is no bytes in flight, version: " << version(); return; } CloseConnection(QUIC_TOO_MANY_RTOS, "Network blackhole detected", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); } void QuicConnection::OnPathMtuReductionDetected() { MaybeRevertToPreviousMtu(); } void QuicConnection::OnHandshakeTimeout() { const QuicTime::Delta duration = clock_->ApproximateNow() - stats_.connection_creation_time; std::string error_details = absl::StrCat( "Handshake timeout expired after ", duration.ToDebuggingValue(), ". Timeout:", idle_network_detector_.handshake_timeout().ToDebuggingValue()); if (perspective() == Perspective::IS_CLIENT && version().UsesTls()) { absl::StrAppend(&error_details, " ", UndecryptablePacketsInfo()); } QUIC_DVLOG(1) << ENDPOINT << error_details; CloseConnection(QUIC_HANDSHAKE_TIMEOUT, error_details, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); } void QuicConnection::OnIdleNetworkDetected() { const QuicTime::Delta duration = clock_->ApproximateNow() - idle_network_detector_.last_network_activity_time(); std::string error_details = absl::StrCat( "No recent network activity after ", duration.ToDebuggingValue(), ". Timeout:", idle_network_detector_.idle_network_timeout().ToDebuggingValue()); if (perspective() == Perspective::IS_CLIENT && version().UsesTls() && !IsHandshakeComplete()) { absl::StrAppend(&error_details, " ", UndecryptablePacketsInfo()); } QUIC_DVLOG(1) << ENDPOINT << error_details; const bool has_consecutive_pto = sent_packet_manager_.GetConsecutivePtoCount() > 0; if (has_consecutive_pto || visitor_->ShouldKeepConnectionAlive()) { if (GetQuicReloadableFlag(quic_add_stream_info_to_idle_close_detail) && !has_consecutive_pto) { QUIC_RELOADABLE_FLAG_COUNT(quic_add_stream_info_to_idle_close_detail); absl::StrAppend(&error_details, ", ", visitor_->GetStreamsInfoForLogging()); } CloseConnection(QUIC_NETWORK_IDLE_TIMEOUT, error_details, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } QuicErrorCode error_code = QUIC_NETWORK_IDLE_TIMEOUT; if (idle_timeout_connection_close_behavior_ == ConnectionCloseBehavior:: SILENT_CLOSE_WITH_CONNECTION_CLOSE_PACKET_SERIALIZED) { error_code = QUIC_SILENT_IDLE_TIMEOUT; } CloseConnection(error_code, error_details, idle_timeout_connection_close_behavior_); } void QuicConnection::OnKeepAliveTimeout() { if (retransmission_alarm().IsSet() || !visitor_->ShouldKeepConnectionAlive()) { return; } SendPingAtLevel(framer().GetEncryptionLevelToSendApplicationData()); } void QuicConnection::OnRetransmittableOnWireTimeout() { if (retransmission_alarm().IsSet() || !visitor_->ShouldKeepConnectionAlive()) { return; } bool packet_buffered = false; switch (retransmittable_on_wire_behavior_) { case DEFAULT: break; case SEND_FIRST_FORWARD_SECURE_PACKET: if (first_serialized_one_rtt_packet_ != nullptr) { buffered_packets_.emplace_back( first_serialized_one_rtt_packet_->data.get(), first_serialized_one_rtt_packet_->length, self_address(), peer_address(), first_serialized_one_rtt_packet_->ecn_codepoint); packet_buffered = true; } break; case SEND_RANDOM_BYTES: const QuicPacketLength random_bytes_length = std::max<QuicPacketLength>( QuicFramer::GetMinStatelessResetPacketLength() + 1, random_generator_->RandUint64() % packet_creator_.max_packet_length()); buffered_packets_.emplace_back(*random_generator_, random_bytes_length, self_address(), peer_address()); packet_buffered = true; break; } if (packet_buffered) { if (!writer_->IsWriteBlocked()) { WriteQueuedPackets(); } if (connected_) { ping_manager_.SetAlarm(clock_->ApproximateNow(), visitor_->ShouldKeepConnectionAlive(), true); } return; } SendPingAtLevel(framer().GetEncryptionLevelToSendApplicationData()); } void QuicConnection::OnPeerIssuedConnectionIdRetired() { QUICHE_DCHECK(peer_issued_cid_manager_ != nullptr); QuicConnectionId* default_path_cid = perspective_ == Perspective::IS_CLIENT ? &default_path_.server_connection_id : &default_path_.client_connection_id; QuicConnectionId* alternative_path_cid = perspective_ == Perspective::IS_CLIENT ? &alternative_path_.server_connection_id : &alternative_path_.client_connection_id; bool default_path_and_alternative_path_use_the_same_peer_connection_id = *default_path_cid == *alternative_path_cid; if (!default_path_cid->IsEmpty() && !peer_issued_cid_manager_->IsConnectionIdActive(*default_path_cid)) { *default_path_cid = QuicConnectionId(); } if (default_path_cid->IsEmpty()) { const QuicConnectionIdData* unused_connection_id_data = peer_issued_cid_manager_->ConsumeOneUnusedConnectionId(); if (unused_connection_id_data != nullptr) { *default_path_cid = unused_connection_id_data->connection_id; default_path_.stateless_reset_token = unused_connection_id_data->stateless_reset_token; if (perspective_ == Perspective::IS_CLIENT) { packet_creator_.SetServerConnectionId( unused_connection_id_data->connection_id); } else { packet_creator_.SetClientConnectionId( unused_connection_id_data->connection_id); } } } if (default_path_and_alternative_path_use_the_same_peer_connection_id) { *alternative_path_cid = *default_path_cid; alternative_path_.stateless_reset_token = default_path_.stateless_reset_token; } else if (!alternative_path_cid->IsEmpty() && !peer_issued_cid_manager_->IsConnectionIdActive( *alternative_path_cid)) { *alternative_path_cid = EmptyQuicConnectionId(); const QuicConnectionIdData* unused_connection_id_data = peer_issued_cid_manager_->ConsumeOneUnusedConnectionId(); if (unused_connection_id_data != nullptr) { *alternative_path_cid = unused_connection_id_data->connection_id; alternative_path_.stateless_reset_token = unused_connection_id_data->stateless_reset_token; } } std::vector<uint64_t> retired_cid_sequence_numbers = peer_issued_cid_manager_->ConsumeToBeRetiredConnectionIdSequenceNumbers(); QUICHE_DCHECK(!retired_cid_sequence_numbers.empty()); for (const auto& sequence_number : retired_cid_sequence_numbers) { ++stats_.num_retire_connection_id_sent; visitor_->SendRetireConnectionId(sequence_number); } } bool QuicConnection::SendNewConnectionId( const QuicNewConnectionIdFrame& frame) { visitor_->SendNewConnectionId(frame); ++stats_.num_new_connection_id_sent; return connected_; } bool QuicConnection::MaybeReserveConnectionId( const QuicConnectionId& connection_id) { if (perspective_ == Perspective::IS_SERVER) { return visitor_->MaybeReserveConnectionId(connection_id); } return true; } void QuicConnection::OnSelfIssuedConnectionIdRetired( const QuicConnectionId& connection_id) { if (perspective_ == Perspective::IS_SERVER) { visitor_->OnServerConnectionIdRetired(connection_id); } } void QuicConnection::MaybeUpdateAckTimeout() { if (should_last_packet_instigate_acks_) { return; } should_last_packet_instigate_acks_ = true; uber_received_packet_manager_.MaybeUpdateAckTimeout( true, last_received_packet_info_.decrypted_level, last_received_packet_info_.header.packet_number, last_received_packet_info_.receipt_time, clock_->ApproximateNow(), sent_packet_manager_.GetRttStats()); } QuicTime QuicConnection::GetPathDegradingDeadline() const { if (!ShouldDetectPathDegrading()) { return QuicTime::Zero(); } return clock_->ApproximateNow() + sent_packet_manager_.GetPathDegradingDelay(); } bool QuicConnection::ShouldDetectPathDegrading() const { if (!connected_) { return false; } if (GetQuicReloadableFlag( quic_no_path_degrading_before_handshake_confirmed) && SupportsMultiplePacketNumberSpaces()) { QUIC_RELOADABLE_FLAG_COUNT_N( quic_no_path_degrading_before_handshake_confirmed, 1, 2); return perspective_ == Perspective::IS_CLIENT && IsHandshakeConfirmed() && !is_path_degrading_; } if (!idle_network_detector_.handshake_timeout().IsInfinite()) { return false; } return perspective_ == Perspective::IS_CLIENT && !is_path_degrading_; } QuicTime QuicConnection::GetNetworkBlackholeDeadline() const { if (!ShouldDetectBlackhole()) { return QuicTime::Zero(); } QUICHE_DCHECK_LT(0u, num_rtos_for_blackhole_detection_); const QuicTime::Delta blackhole_delay = sent_packet_manager_.GetNetworkBlackholeDelay( num_rtos_for_blackhole_detection_); if (!ShouldDetectPathDegrading()) { return clock_->ApproximateNow() + blackhole_delay; } return clock_->ApproximateNow() + CalculateNetworkBlackholeDelay( blackhole_delay, sent_packet_manager_.GetPathDegradingDelay(), sent_packet_manager_.GetPtoDelay()); } QuicTime::Delta QuicConnection::CalculateNetworkBlackholeDelay( QuicTime::Delta blackhole_delay, QuicTime::Delta path_degrading_delay, QuicTime::Delta pto_delay) { const QuicTime::Delta min_delay = path_degrading_delay + pto_delay * 2; if (blackhole_delay < min_delay) { QUIC_CODE_COUNT(quic_extending_short_blackhole_delay); } return std::max(min_delay, blackhole_delay); } void QuicConnection::AddKnownServerAddress(const QuicSocketAddress& address) { QUICHE_DCHECK(perspective_ == Perspective::IS_CLIENT); if (!address.IsInitialized() || IsKnownServerAddress(address)) { return; } known_server_addresses_.push_back(address); } std::optional<QuicNewConnectionIdFrame> QuicConnection::MaybeIssueNewConnectionIdForPreferredAddress() { if (self_issued_cid_manager_ == nullptr) { return std::nullopt; } return self_issued_cid_manager_ ->MaybeIssueNewConnectionIdForPreferredAddress(); } bool QuicConnection::ShouldDetectBlackhole() const { if (!connected_ || blackhole_detection_disabled_) { return false; } if (GetQuicReloadableFlag( quic_no_path_degrading_before_handshake_confirmed) && SupportsMultiplePacketNumberSpaces() && !IsHandshakeConfirmed()) { QUIC_RELOADABLE_FLAG_COUNT_N( quic_no_path_degrading_before_handshake_confirmed, 2, 2); return false; } if (default_enable_5rto_blackhole_detection_) { QUIC_RELOADABLE_FLAG_COUNT_N(quic_default_enable_5rto_blackhole_detection2, 3, 3); return IsHandshakeComplete(); } if (!idle_network_detector_.handshake_timeout().IsInfinite()) { return false; } return num_rtos_for_blackhole_detection_ > 0; } QuicTime QuicConnection::GetRetransmissionDeadline() const { if (perspective_ == Perspective::IS_CLIENT && SupportsMultiplePacketNumberSpaces() && !IsHandshakeConfirmed() && stats_.pto_count == 0 && !framer_.HasDecrypterOfEncryptionLevel(ENCRYPTION_HANDSHAKE) && !undecryptable_packets_.empty()) { return clock_->ApproximateNow() + kAlarmGranularity; } return sent_packet_manager_.GetRetransmissionTime(); } bool QuicConnection::SendPathChallenge( const QuicPathFrameBuffer& data_buffer, const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, const QuicSocketAddress& effective_peer_address, QuicPacketWriter* writer) { if (!framer_.HasEncrypterOfEncryptionLevel(ENCRYPTION_FORWARD_SECURE)) { return connected_; } QuicConnectionId client_cid, server_cid; FindOnPathConnectionIds(self_address, effective_peer_address, &client_cid, &server_cid); if (writer == writer_) { ScopedPacketFlusher flusher(this); { QuicPacketCreator::ScopedPeerAddressContext context( &packet_creator_, peer_address, client_cid, server_cid); packet_creator_.AddPathChallengeFrame(data_buffer); } } else if (!writer->IsWriteBlocked()) { QuicPacketCreator::ScopedPeerAddressContext context( &packet_creator_, peer_address, client_cid, server_cid); std::unique_ptr<SerializedPacket> probing_packet = packet_creator_.SerializePathChallengeConnectivityProbingPacket( data_buffer); QUICHE_DCHECK_EQ(IsRetransmittable(*probing_packet), NO_RETRANSMITTABLE_DATA) << ENDPOINT << "Probing Packet contains retransmittable frames"; QUICHE_DCHECK_EQ(self_address, alternative_path_.self_address) << ENDPOINT << "Send PATH_CHALLENGE from self_address: " << self_address.ToString() << " which is different from alt_path self address: " << alternative_path_.self_address.ToString(); WritePacketUsingWriter(std::move(probing_packet), writer, self_address, peer_address, false); } else { QUIC_DLOG(INFO) << ENDPOINT << "Writer blocked when sending PATH_CHALLENGE."; } return connected_; } QuicTime QuicConnection::GetRetryTimeout( const QuicSocketAddress& peer_address_to_use, QuicPacketWriter* writer_to_use) const { if (writer_to_use == writer_ && peer_address_to_use == peer_address()) { return clock_->ApproximateNow() + sent_packet_manager_.GetPtoDelay(); } return clock_->ApproximateNow() + QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs); } void QuicConnection::ValidatePath( std::unique_ptr<QuicPathValidationContext> context, std::unique_ptr<QuicPathValidator::ResultDelegate> result_delegate, PathValidationReason reason) { QUICHE_DCHECK(version().HasIetfQuicFrames()); if (path_validator_.HasPendingPathValidation()) { if (perspective_ == Perspective::IS_CLIENT && IsValidatingServerPreferredAddress()) { QUIC_CLIENT_HISTOGRAM_BOOL( "QuicSession.ServerPreferredAddressValidationCancelled", true, "How often the caller kicked off another validation while there is " "an on-going server preferred address validation."); } path_validator_.CancelPathValidation(); } if (perspective_ == Perspective::IS_CLIENT && !IsDefaultPath(context->self_address(), context->peer_address())) { if (self_issued_cid_manager_ != nullptr) { self_issued_cid_manager_->MaybeSendNewConnectionIds(); if (!connected_) { return; } } if ((self_issued_cid_manager_ != nullptr && !self_issued_cid_manager_->HasConnectionIdToConsume()) || (peer_issued_cid_manager_ != nullptr && !peer_issued_cid_manager_->HasUnusedConnectionId())) { QUIC_DVLOG(1) << "Client cannot start new path validation as there is no " "requried connection ID is available."; result_delegate->OnPathValidationFailure(std::move(context)); return; } QuicConnectionId client_connection_id, server_connection_id; std::optional<StatelessResetToken> stateless_reset_token; if (self_issued_cid_manager_ != nullptr) { client_connection_id = *self_issued_cid_manager_->ConsumeOneConnectionId(); } if (peer_issued_cid_manager_ != nullptr) { const auto* connection_id_data = peer_issued_cid_manager_->ConsumeOneUnusedConnectionId(); server_connection_id = connection_id_data->connection_id; stateless_reset_token = connection_id_data->stateless_reset_token; } alternative_path_ = PathState(context->self_address(), context->peer_address(), client_connection_id, server_connection_id, stateless_reset_token); } if (multi_port_stats_ != nullptr && reason == PathValidationReason::kMultiPort) { multi_port_stats_->num_client_probing_attempts++; } if (perspective_ == Perspective::IS_CLIENT) { stats_.num_client_probing_attempts++; } path_validator_.StartPathValidation(std::move(context), std::move(result_delegate), reason); if (perspective_ == Perspective::IS_CLIENT && IsValidatingServerPreferredAddress()) { AddKnownServerAddress(received_server_preferred_address_); } } bool QuicConnection::SendPathResponse( const QuicPathFrameBuffer& data_buffer, const QuicSocketAddress& peer_address_to_send, const QuicSocketAddress& effective_peer_address) { if (!framer_.HasEncrypterOfEncryptionLevel(ENCRYPTION_FORWARD_SECURE)) { return false; } QuicConnectionId client_cid, server_cid; FindOnPathConnectionIds(last_received_packet_info_.destination_address, effective_peer_address, &client_cid, &server_cid); QuicPacketCreator::ScopedPeerAddressContext context( &packet_creator_, peer_address_to_send, client_cid, server_cid); QUIC_DVLOG(1) << ENDPOINT << "Send PATH_RESPONSE to " << peer_address_to_send; if (default_path_.self_address == last_received_packet_info_.destination_address) { return packet_creator_.AddPathResponseFrame(data_buffer); } QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, perspective_); if (!path_validator_.HasPendingPathValidation() || path_validator_.GetContext()->self_address() != last_received_packet_info_.destination_address) { return true; } QuicPacketWriter* writer = path_validator_.GetContext()->WriterToUse(); if (writer->IsWriteBlocked()) { QUIC_DLOG(INFO) << ENDPOINT << "Writer blocked when sending PATH_RESPONSE."; return true; } std::unique_ptr<SerializedPacket> probing_packet = packet_creator_.SerializePathResponseConnectivityProbingPacket( {data_buffer}, true); QUICHE_DCHECK_EQ(IsRetransmittable(*probing_packet), NO_RETRANSMITTABLE_DATA); QUIC_DVLOG(1) << ENDPOINT << "Send PATH_RESPONSE from alternative socket with address " << last_received_packet_info_.destination_address; WritePacketUsingWriter(std::move(probing_packet), writer, last_received_packet_info_.destination_address, peer_address_to_send, false); return true; } void QuicConnection::UpdatePeerAddress(QuicSocketAddress peer_address) { direct_peer_address_ = peer_address; packet_creator_.SetDefaultPeerAddress(peer_address); } void QuicConnection::SendPingAtLevel(EncryptionLevel level) { ScopedEncryptionLevelContext context(this, level); SendControlFrame(QuicFrame(QuicPingFrame())); } bool QuicConnection::HasPendingPathValidation() const { return path_validator_.HasPendingPathValidation(); } QuicPathValidationContext* QuicConnection::GetPathValidationContext() const { return path_validator_.GetContext(); } void QuicConnection::CancelPathValidation() { path_validator_.CancelPathValidation(); } bool QuicConnection::UpdateConnectionIdsOnMigration( const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address) { QUICHE_DCHECK(perspective_ == Perspective::IS_CLIENT); if (IsAlternativePath(self_address, peer_address)) { default_path_.client_connection_id = alternative_path_.client_connection_id; default_path_.server_connection_id = alternative_path_.server_connection_id; default_path_.stateless_reset_token = alternative_path_.stateless_reset_token; return true; } if (self_issued_cid_manager_ != nullptr) { self_issued_cid_manager_->MaybeSendNewConnectionIds(); if (!connected_) { return false; } } if ((self_issued_cid_manager_ != nullptr && !self_issued_cid_manager_->HasConnectionIdToConsume()) || (peer_issued_cid_manager_ != nullptr && !peer_issued_cid_manager_->HasUnusedConnectionId())) { return false; } if (self_issued_cid_manager_ != nullptr) { default_path_.client_connection_id = *self_issued_cid_manager_->ConsumeOneConnectionId(); } if (peer_issued_cid_manager_ != nullptr) { const auto* connection_id_data = peer_issued_cid_manager_->ConsumeOneUnusedConnectionId(); default_path_.server_connection_id = connection_id_data->connection_id; default_path_.stateless_reset_token = connection_id_data->stateless_reset_token; } return true; } void QuicConnection::RetirePeerIssuedConnectionIdsNoLongerOnPath() { if (!version().HasIetfQuicFrames() || peer_issued_cid_manager_ == nullptr) { return; } if (perspective_ == Perspective::IS_CLIENT) { peer_issued_cid_manager_->MaybeRetireUnusedConnectionIds( {default_path_.server_connection_id, alternative_path_.server_connection_id}); } else { peer_issued_cid_manager_->MaybeRetireUnusedConnectionIds( {default_path_.client_connection_id, alternative_path_.client_connection_id}); } } bool QuicConnection::MigratePath(const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, QuicPacketWriter* writer, bool owns_writer) { QUICHE_DCHECK(perspective_ == Perspective::IS_CLIENT); if (!connected_) { if (owns_writer) { delete writer; } return false; } QUICHE_DCHECK(!version().UsesHttp3() || IsHandshakeConfirmed() || accelerated_server_preferred_address_); if (version().UsesHttp3()) { if (!UpdateConnectionIdsOnMigration(self_address, peer_address)) { if (owns_writer) { delete writer; } return false; } if (packet_creator_.GetServerConnectionId().length() != default_path_.server_connection_id.length()) { packet_creator_.FlushCurrentPacket(); } packet_creator_.SetClientConnectionId(default_path_.client_connection_id); packet_creator_.SetServerConnectionId(default_path_.server_connection_id); } const auto self_address_change_type = QuicUtils::DetermineAddressChangeType( default_path_.self_address, self_address); const auto peer_address_change_type = QuicUtils::DetermineAddressChangeType( default_path_.peer_address, peer_address); QUICHE_DCHECK(self_address_change_type != NO_CHANGE || peer_address_change_type != NO_CHANGE); const bool is_port_change = (self_address_change_type == PORT_CHANGE || self_address_change_type == NO_CHANGE) && (peer_address_change_type == PORT_CHANGE || peer_address_change_type == NO_CHANGE); SetSelfAddress(self_address); UpdatePeerAddress(peer_address); default_path_.peer_address = peer_address; if (writer_ != writer) { SetQuicPacketWriter(writer, owns_writer); } MaybeClearQueuedPacketsOnPathChange(); OnSuccessfulMigration(is_port_change); return true; } void QuicConnection::OnPathValidationFailureAtClient( bool is_multi_port, const QuicPathValidationContext& context) { QUICHE_DCHECK(perspective_ == Perspective::IS_CLIENT && version().HasIetfQuicFrames()); alternative_path_.Clear(); if (is_multi_port && multi_port_stats_ != nullptr) { if (is_path_degrading_) { multi_port_stats_->num_multi_port_probe_failures_when_path_degrading++; } else { multi_port_stats_ ->num_multi_port_probe_failures_when_path_not_degrading++; } } if (context.peer_address() == received_server_preferred_address_ && received_server_preferred_address_ != default_path_.peer_address) { QUIC_DLOG(INFO) << "Failed to validate server preferred address : " << received_server_preferred_address_; mutable_stats().failed_to_validate_server_preferred_address = true; } RetirePeerIssuedConnectionIdsNoLongerOnPath(); } QuicConnectionId QuicConnection::GetOneActiveServerConnectionId() const { if (perspective_ == Perspective::IS_CLIENT || self_issued_cid_manager_ == nullptr) { return connection_id(); } auto active_connection_ids = GetActiveServerConnectionIds(); QUIC_BUG_IF(quic_bug_6944, active_connection_ids.empty()); if (active_connection_ids.empty() || std::find(active_connection_ids.begin(), active_connection_ids.end(), connection_id()) != active_connection_ids.end()) { return connection_id(); } QUICHE_CODE_COUNT(connection_id_on_default_path_has_been_retired); auto active_connection_id = self_issued_cid_manager_->GetOneActiveConnectionId(); return active_connection_id; } std::vector<QuicConnectionId> QuicConnection::GetActiveServerConnectionIds() const { QUICHE_DCHECK_EQ(Perspective::IS_SERVER, perspective_); std::vector<QuicConnectionId> result; if (self_issued_cid_manager_ == nullptr) { result.push_back(default_path_.server_connection_id); } else { QUICHE_DCHECK(version().HasIetfQuicFrames()); result = self_issued_cid_manager_->GetUnretiredConnectionIds(); } if (!original_destination_connection_id_.has_value()) { return result; } if (std::find(result.begin(), result.end(), *original_destination_connection_id_) != result.end()) { QUIC_BUG(quic_unexpected_original_destination_connection_id) << "original_destination_connection_id: " << *original_destination_connection_id_ << " is unexpectedly in active list"; } else { result.insert(result.end(), *original_destination_connection_id_); } return result; } void QuicConnection::CreateConnectionIdManager() { if (!version().HasIetfQuicFrames()) { return; } if (perspective_ == Perspective::IS_CLIENT) { if (!default_path_.server_connection_id.IsEmpty()) { peer_issued_cid_manager_ = std::make_unique<QuicPeerIssuedConnectionIdManager>( kMinNumOfActiveConnectionIds, default_path_.server_connection_id, clock_, alarm_factory_, this, context()); } } else { if (!default_path_.server_connection_id.IsEmpty()) { self_issued_cid_manager_ = MakeSelfIssuedConnectionIdManager(); } } } void QuicConnection::QuicBugIfHasPendingFrames(QuicStreamId id) const { QUIC_BUG_IF(quic_has_pending_frames_unexpectedly, connected_ && packet_creator_.HasPendingStreamFramesOfStream(id)) << "Stream " << id << " has pending frames unexpectedly. Received packet info: " << last_received_packet_info_; } void QuicConnection::SetUnackedMapInitialCapacity() { sent_packet_manager_.ReserveUnackedPacketsInitialCapacity( GetUnackedMapInitialCapacity()); } void QuicConnection::SetSourceAddressTokenToSend(absl::string_view token) { QUICHE_DCHECK_EQ(perspective_, Perspective::IS_CLIENT); if (!packet_creator_.HasRetryToken()) { packet_creator_.SetRetryToken(std::string(token.data(), token.length())); } } void QuicConnection::MaybeUpdateBytesSentToAlternativeAddress( const QuicSocketAddress& peer_address, QuicByteCount sent_packet_size) { if (!version().SupportsAntiAmplificationLimit() || perspective_ != Perspective::IS_SERVER) { return; } QUICHE_DCHECK(!IsDefaultPath(default_path_.self_address, peer_address)); if (!IsAlternativePath(default_path_.self_address, peer_address)) { QUIC_DLOG(INFO) << "Wrote to uninteresting peer address: " << peer_address << " default direct_peer_address_ " << direct_peer_address_ << " alternative path peer address " << alternative_path_.peer_address; return; } if (alternative_path_.validated) { return; } if (alternative_path_.bytes_sent_before_address_validation >= anti_amplification_factor_ * alternative_path_.bytes_received_before_address_validation) { QUIC_LOG_FIRST_N(WARNING, 100) << "Server sent more data than allowed to unverified alternative " "peer address " << peer_address << " bytes sent " << alternative_path_.bytes_sent_before_address_validation << ", bytes received " << alternative_path_.bytes_received_before_address_validation; } alternative_path_.bytes_sent_before_address_validation += sent_packet_size; } void QuicConnection::MaybeUpdateBytesReceivedFromAlternativeAddress( QuicByteCount received_packet_size) { if (!version().SupportsAntiAmplificationLimit() || perspective_ != Perspective::IS_SERVER || !IsAlternativePath(last_received_packet_info_.destination_address, GetEffectivePeerAddressFromCurrentPacket()) || last_received_packet_info_.received_bytes_counted) { return; } QUICHE_DCHECK(!IsDefaultPath(last_received_packet_info_.destination_address, GetEffectivePeerAddressFromCurrentPacket())); if (!alternative_path_.validated) { alternative_path_.bytes_received_before_address_validation += received_packet_size; } last_received_packet_info_.received_bytes_counted = true; } bool QuicConnection::IsDefaultPath( const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address) const { return direct_peer_address_ == peer_address && default_path_.self_address == self_address; } bool QuicConnection::IsAlternativePath( const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address) const { return alternative_path_.peer_address == peer_address && alternative_path_.self_address == self_address; } void QuicConnection::PathState::Clear() { self_address = QuicSocketAddress(); peer_address = QuicSocketAddress(); client_connection_id = {}; server_connection_id = {}; validated = false; bytes_received_before_address_validation = 0; bytes_sent_before_address_validation = 0; send_algorithm = nullptr; rtt_stats = std::nullopt; stateless_reset_token.reset(); ecn_marked_packet_acked = false; ecn_pto_count = 0; } QuicConnection::PathState::PathState(PathState&& other) { *this = std::move(other); } QuicConnection::PathState& QuicConnection::PathState::operator=( QuicConnection::PathState&& other) { if (this != &other) { self_address = other.self_address; peer_address = other.peer_address; client_connection_id = other.client_connection_id; server_connection_id = other.server_connection_id; stateless_reset_token = other.stateless_reset_token; validated = other.validated; bytes_received_before_address_validation = other.bytes_received_before_address_validation; bytes_sent_before_address_validation = other.bytes_sent_before_address_validation; send_algorithm = std::move(other.send_algorithm); if (other.rtt_stats.has_value()) { rtt_stats.emplace(); rtt_stats->CloneFrom(*other.rtt_stats); } else { rtt_stats.reset(); } other.Clear(); } return *this; } bool QuicConnection::IsReceivedPeerAddressValidated() const { QuicSocketAddress current_effective_peer_address = GetEffectivePeerAddressFromCurrentPacket(); QUICHE_DCHECK(current_effective_peer_address.IsInitialized()); return (alternative_path_.peer_address.host() == current_effective_peer_address.host() && alternative_path_.validated) || (default_path_.validated && default_path_.peer_address.host() == current_effective_peer_address.host()); } void QuicConnection::OnMultiPortPathProbingSuccess( std::unique_ptr<QuicPathValidationContext> context, QuicTime start_time) { QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, perspective()); alternative_path_.validated = true; multi_port_path_context_ = std::move(context); multi_port_probing_alarm().Set(clock_->ApproximateNow() + multi_port_probing_interval_); if (multi_port_stats_ != nullptr) { multi_port_stats_->num_successful_probes++; auto now = clock_->Now(); auto time_delta = now - start_time; multi_port_stats_->rtt_stats.UpdateRtt(time_delta, QuicTime::Delta::Zero(), now); if (is_path_degrading_) { multi_port_stats_->rtt_stats_when_default_path_degrading.UpdateRtt( time_delta, QuicTime::Delta::Zero(), now); } } } void QuicConnection::MaybeProbeMultiPortPath() { if (!connected_ || path_validator_.HasPendingPathValidation() || !multi_port_path_context_ || alternative_path_.self_address != multi_port_path_context_->self_address() || alternative_path_.peer_address != multi_port_path_context_->peer_address() || !visitor_->ShouldKeepConnectionAlive() || multi_port_probing_alarm().IsSet()) { return; } if (multi_port_stats_ != nullptr) { multi_port_stats_->num_client_probing_attempts++; } auto multi_port_validation_result_delegate = std::make_unique<MultiPortPathValidationResultDelegate>(this); path_validator_.StartPathValidation( std::move(multi_port_path_context_), std::move(multi_port_validation_result_delegate), PathValidationReason::kMultiPort); } void QuicConnection::ContextObserver::OnMultiPortPathContextAvailable( std::unique_ptr<QuicPathValidationContext> path_context) { if (!path_context) { return; } auto multi_port_validation_result_delegate = std::make_unique<MultiPortPathValidationResultDelegate>(connection_); connection_->multi_port_probing_alarm().Cancel(); connection_->multi_port_path_context_ = nullptr; connection_->multi_port_stats_->num_multi_port_paths_created++; connection_->ValidatePath(std::move(path_context), std::move(multi_port_validation_result_delegate), PathValidationReason::kMultiPort); } QuicConnection::MultiPortPathValidationResultDelegate:: MultiPortPathValidationResultDelegate(QuicConnection* connection) : connection_(connection) { QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, connection->perspective()); } void QuicConnection::MultiPortPathValidationResultDelegate:: OnPathValidationSuccess(std::unique_ptr<QuicPathValidationContext> context, QuicTime start_time) { connection_->OnMultiPortPathProbingSuccess(std::move(context), start_time); } void QuicConnection::MultiPortPathValidationResultDelegate:: OnPathValidationFailure( std::unique_ptr<QuicPathValidationContext> context) { connection_->OnPathValidationFailureAtClient(true, *context); } QuicConnection::ReversePathValidationResultDelegate:: ReversePathValidationResultDelegate( QuicConnection* connection, const QuicSocketAddress& direct_peer_address) : QuicPathValidator::ResultDelegate(), connection_(connection), original_direct_peer_address_(direct_peer_address), peer_address_default_path_(connection->direct_peer_address_), peer_address_alternative_path_( connection_->alternative_path_.peer_address), active_effective_peer_migration_type_( connection_->active_effective_peer_migration_type_) {} void QuicConnection::ReversePathValidationResultDelegate:: OnPathValidationSuccess(std::unique_ptr<QuicPathValidationContext> context, QuicTime start_time) { QUIC_DLOG(INFO) << "Successfully validated new path " << *context << ", validation started at " << start_time; if (connection_->IsDefaultPath(context->self_address(), context->peer_address())) { QUIC_CODE_COUNT_N(quic_kick_off_client_address_validation, 3, 6); if (connection_->active_effective_peer_migration_type_ == NO_CHANGE) { std::string error_detail = absl::StrCat( "Reverse path validation on default path from ", context->self_address().ToString(), " to ", context->peer_address().ToString(), " completed without active peer address change: current " "peer address on default path ", connection_->direct_peer_address_.ToString(), ", peer address on default path when the reverse path " "validation was kicked off ", peer_address_default_path_.ToString(), ", peer address on alternative path when the reverse " "path validation was kicked off ", peer_address_alternative_path_.ToString(), ", with active_effective_peer_migration_type_ = ", AddressChangeTypeToString(active_effective_peer_migration_type_), ". The last received packet number ", connection_->last_received_packet_info_.header.packet_number .ToString(), " Connection is connected: ", connection_->connected_); QUIC_BUG(quic_bug_10511_43) << error_detail; } connection_->OnEffectivePeerMigrationValidated( connection_->alternative_path_.server_connection_id == connection_->default_path_.server_connection_id); } else { QUICHE_DCHECK(connection_->IsAlternativePath( context->self_address(), context->effective_peer_address())); QUIC_CODE_COUNT_N(quic_kick_off_client_address_validation, 4, 6); QUIC_DVLOG(1) << "Mark alternative peer address " << context->effective_peer_address() << " validated."; connection_->alternative_path_.validated = true; } } void QuicConnection::ReversePathValidationResultDelegate:: OnPathValidationFailure( std::unique_ptr<QuicPathValidationContext> context) { if (!connection_->connected()) { return; } QUIC_DLOG(INFO) << "Fail to validate new path " << *context; if (connection_->IsDefaultPath(context->self_address(), context->peer_address())) { QUIC_CODE_COUNT_N(quic_kick_off_client_address_validation, 5, 6); connection_->RestoreToLastValidatedPath(original_direct_peer_address_); } else if (connection_->IsAlternativePath( context->self_address(), context->effective_peer_address())) { QUIC_CODE_COUNT_N(quic_kick_off_client_address_validation, 6, 6); connection_->alternative_path_.Clear(); } connection_->RetirePeerIssuedConnectionIdsNoLongerOnPath(); } QuicConnection::ScopedRetransmissionTimeoutIndicator:: ScopedRetransmissionTimeoutIndicator(QuicConnection* connection) : connection_(connection) { QUICHE_DCHECK(!connection_->in_probe_time_out_) << "ScopedRetransmissionTimeoutIndicator is not supposed to be nested"; connection_->in_probe_time_out_ = true; } QuicConnection::ScopedRetransmissionTimeoutIndicator:: ~ScopedRetransmissionTimeoutIndicator() { QUICHE_DCHECK(connection_->in_probe_time_out_); connection_->in_probe_time_out_ = false; } void QuicConnection::RestoreToLastValidatedPath( QuicSocketAddress original_direct_peer_address) { QUIC_DLOG(INFO) << "Switch back to use the old peer address " << alternative_path_.peer_address; if (!alternative_path_.validated) { CloseConnection(QUIC_INTERNAL_ERROR, "No validated peer address to use after reverse path " "validation failure.", ConnectionCloseBehavior::SILENT_CLOSE); return; } MaybeClearQueuedPacketsOnPathChange(); OnPeerIpAddressChanged(); if (alternative_path_.send_algorithm != nullptr) { sent_packet_manager_.SetSendAlgorithm( alternative_path_.send_algorithm.release()); } else { QUIC_BUG(quic_bug_10511_42) << "Fail to store congestion controller before migration."; } if (alternative_path_.rtt_stats.has_value()) { sent_packet_manager_.SetRttStats(*alternative_path_.rtt_stats); } UpdatePeerAddress(original_direct_peer_address); SetDefaultPathState(std::move(alternative_path_)); active_effective_peer_migration_type_ = NO_CHANGE; ++stats_.num_invalid_peer_migration; WriteIfNotBlocked(); } std::unique_ptr<SendAlgorithmInterface> QuicConnection::OnPeerIpAddressChanged() { QUICHE_DCHECK(framer_.version().HasIetfQuicFrames()); std::unique_ptr<SendAlgorithmInterface> old_send_algorithm = sent_packet_manager_.OnConnectionMigration( true); QUICHE_DCHECK(!sent_packet_manager_.HasInFlightPackets()); SetRetransmissionAlarm(); blackhole_detector_.StopDetection(false); return old_send_algorithm; } void QuicConnection::set_keep_alive_ping_timeout( QuicTime::Delta keep_alive_ping_timeout) { ping_manager_.set_keep_alive_timeout(keep_alive_ping_timeout); } void QuicConnection::set_initial_retransmittable_on_wire_timeout( QuicTime::Delta retransmittable_on_wire_timeout) { ping_manager_.set_initial_retransmittable_on_wire_timeout( retransmittable_on_wire_timeout); } bool QuicConnection::IsValidatingServerPreferredAddress() const { QUICHE_DCHECK_EQ(perspective_, Perspective::IS_CLIENT); return received_server_preferred_address_.IsInitialized() && received_server_preferred_address_ != default_path_.peer_address && path_validator_.HasPendingPathValidation() && path_validator_.GetContext()->peer_address() == received_server_preferred_address_; } void QuicConnection::OnServerPreferredAddressValidated( QuicPathValidationContext& context, bool owns_writer) { QUIC_DLOG(INFO) << "Server preferred address: " << context.peer_address() << " validated. Migrating path, self_address: " << context.self_address() << ", peer_address: " << context.peer_address(); mutable_stats().server_preferred_address_validated = true; const bool success = MigratePath(context.self_address(), context.peer_address(), context.WriterToUse(), owns_writer); QUIC_BUG_IF(failed to migrate to server preferred address, !success) << "Failed to migrate to server preferred address: " << context.peer_address() << " after successful validation"; } bool QuicConnection::set_ecn_codepoint(QuicEcnCodepoint ecn_codepoint) { if (!GetQuicRestartFlag(quic_support_ect1)) { return false; } QUIC_RESTART_FLAG_COUNT_N(quic_support_ect1, 3, 9); if (disable_ecn_codepoint_validation_ || ecn_codepoint == ECN_NOT_ECT) { packet_writer_params_.ecn_codepoint = ecn_codepoint; return true; } if (!writer_->SupportsEcn()) { return false; } switch (ecn_codepoint) { case ECN_NOT_ECT: QUICHE_DCHECK(false); break; case ECN_ECT0: if (!sent_packet_manager_.EnableECT0()) { return false; } break; case ECN_ECT1: if (!sent_packet_manager_.EnableECT1()) { return false; } break; case ECN_CE: return false; } packet_writer_params_.ecn_codepoint = ecn_codepoint; return true; } void QuicConnection::OnIdleDetectorAlarm() { idle_network_detector_.OnAlarm(); } void QuicConnection::OnPingAlarm() { ping_manager_.OnAlarm(); } void QuicConnection::OnNetworkBlackholeDetectorAlarm() { blackhole_detector_.OnAlarm(); } std::unique_ptr<SerializedPacket> QuicConnection::SerializeLargePacketNumberConnectionClosePacket( QuicErrorCode error, const std::string& error_details) { QUICHE_DCHECK(IsHandshakeConfirmed()); QUICHE_DCHECK(!error_details.empty()); if (!IsHandshakeConfirmed()) { return nullptr; } return packet_creator_.SerializeLargePacketNumberConnectionClosePacket( GetLargestAckedPacket(), error, error_details); } #undef ENDPOINT }
#include "quiche/quic/core/quic_connection.h" #include <errno.h> #include <algorithm> #include <cstdint> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/congestion_control/loss_detection_interface.h" #include "quiche/quic/core/congestion_control/send_algorithm_interface.h" #include "quiche/quic/core/crypto/null_decrypter.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/crypto/quic_decrypter.h" #include "quiche/quic/core/frames/quic_connection_close_frame.h" #include "quiche/quic/core/frames/quic_new_connection_id_frame.h" #include "quiche/quic/core/frames/quic_path_response_frame.h" #include "quiche/quic/core/frames/quic_reset_stream_at_frame.h" #include "quiche/quic/core/frames/quic_rst_stream_frame.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_packet_creator.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_path_validator.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_ip_address.h" #include "quiche/quic/platform/api/quic_ip_address_family.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/mock_clock.h" #include "quiche/quic/test_tools/mock_connection_id_generator.h" #include "quiche/quic/test_tools/mock_random.h" #include "quiche/quic/test_tools/quic_coalesced_packet_peer.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_path_validator_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/simple_data_producer.h" #include "quiche/quic/test_tools/simple_session_notifier.h" #include "quiche/common/simple_buffer_allocator.h" using testing::_; using testing::AnyNumber; using testing::AtLeast; using testing::DoAll; using testing::DoDefault; using testing::ElementsAre; using testing::Ge; using testing::IgnoreResult; using testing::InSequence; using testing::Invoke; using testing::InvokeWithoutArgs; using testing::Lt; using testing::Ref; using testing::Return; using testing::SaveArg; using testing::SetArgPointee; using testing::StrictMock; namespace quic { namespace test { namespace { const char data1[] = "foo data"; const char data2[] = "bar data"; const bool kHasStopWaiting = true; const int kDefaultRetransmissionTimeMs = 500; DiversificationNonce kTestDiversificationNonce = { 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', }; const StatelessResetToken kTestStatelessResetToken{ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f}; const QuicSocketAddress kPeerAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), 12345); const QuicSocketAddress kSelfAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), 443); const QuicSocketAddress kServerPreferredAddress = QuicSocketAddress( []() { QuicIpAddress address; address.FromString("2604:31c0::"); return address; }(), 443); QuicStreamId GetNthClientInitiatedStreamId(int n, QuicTransportVersion version) { return QuicUtils::GetFirstBidirectionalStreamId(version, Perspective::IS_CLIENT) + n * 2; } QuicLongHeaderType EncryptionlevelToLongHeaderType(EncryptionLevel level) { switch (level) { case ENCRYPTION_INITIAL: return INITIAL; case ENCRYPTION_HANDSHAKE: return HANDSHAKE; case ENCRYPTION_ZERO_RTT: return ZERO_RTT_PROTECTED; case ENCRYPTION_FORWARD_SECURE: QUICHE_DCHECK(false); return INVALID_PACKET_TYPE; default: QUICHE_DCHECK(false); return INVALID_PACKET_TYPE; } } class TaggingEncrypterWithConfidentialityLimit : public TaggingEncrypter { public: TaggingEncrypterWithConfidentialityLimit( uint8_t tag, QuicPacketCount confidentiality_limit) : TaggingEncrypter(tag), confidentiality_limit_(confidentiality_limit) {} QuicPacketCount GetConfidentialityLimit() const override { return confidentiality_limit_; } private: QuicPacketCount confidentiality_limit_; }; class StrictTaggingDecrypterWithIntegrityLimit : public StrictTaggingDecrypter { public: StrictTaggingDecrypterWithIntegrityLimit(uint8_t tag, QuicPacketCount integrity_limit) : StrictTaggingDecrypter(tag), integrity_limit_(integrity_limit) {} QuicPacketCount GetIntegrityLimit() const override { return integrity_limit_; } private: QuicPacketCount integrity_limit_; }; class TestConnectionHelper : public QuicConnectionHelperInterface { public: TestConnectionHelper(MockClock* clock, MockRandom* random_generator) : clock_(clock), random_generator_(random_generator) { clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1)); } TestConnectionHelper(const TestConnectionHelper&) = delete; TestConnectionHelper& operator=(const TestConnectionHelper&) = delete; const QuicClock* GetClock() const override { return clock_; } QuicRandom* GetRandomGenerator() override { return random_generator_; } quiche::QuicheBufferAllocator* GetStreamSendBufferAllocator() override { return &buffer_allocator_; } private: MockClock* clock_; MockRandom* random_generator_; quiche::SimpleBufferAllocator buffer_allocator_; }; class TestConnection : public QuicConnection { public: TestConnection(QuicConnectionId connection_id, QuicSocketAddress initial_self_address, QuicSocketAddress initial_peer_address, TestConnectionHelper* helper, TestAlarmFactory* alarm_factory, TestPacketWriter* writer, Perspective perspective, ParsedQuicVersion version, ConnectionIdGeneratorInterface& generator) : QuicConnection(connection_id, initial_self_address, initial_peer_address, helper, alarm_factory, writer, false, perspective, SupportedVersions(version), generator), notifier_(nullptr) { writer->set_perspective(perspective); SetEncrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE)); SetDataProducer(&producer_); ON_CALL(*this, OnSerializedPacket(_)) .WillByDefault([this](SerializedPacket packet) { QuicConnection::OnSerializedPacket(std::move(packet)); }); } TestConnection(const TestConnection&) = delete; TestConnection& operator=(const TestConnection&) = delete; MOCK_METHOD(void, OnSerializedPacket, (SerializedPacket packet), (override)); void OnEffectivePeerMigrationValidated(bool is_migration_linkable) override { QuicConnection::OnEffectivePeerMigrationValidated(is_migration_linkable); if (is_migration_linkable) { num_linkable_client_migration_++; } else { num_unlinkable_client_migration_++; } } uint32_t num_unlinkable_client_migration() const { return num_unlinkable_client_migration_; } uint32_t num_linkable_client_migration() const { return num_linkable_client_migration_; } void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) { QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm); } void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) { QuicConnectionPeer::SetLossAlgorithm(this, loss_algorithm); } void SendPacket(EncryptionLevel , uint64_t packet_number, std::unique_ptr<QuicPacket> packet, HasRetransmittableData retransmittable, bool has_ack, bool has_pending_frames) { ScopedPacketFlusher flusher(this); char buffer[kMaxOutgoingPacketSize]; size_t encrypted_length = QuicConnectionPeer::GetFramer(this)->EncryptPayload( ENCRYPTION_INITIAL, QuicPacketNumber(packet_number), *packet, buffer, kMaxOutgoingPacketSize); SerializedPacket serialized_packet( QuicPacketNumber(packet_number), PACKET_4BYTE_PACKET_NUMBER, buffer, encrypted_length, has_ack, has_pending_frames); serialized_packet.peer_address = kPeerAddress; if (retransmittable == HAS_RETRANSMITTABLE_DATA) { serialized_packet.retransmittable_frames.push_back( QuicFrame(QuicPingFrame())); } OnSerializedPacket(std::move(serialized_packet)); } QuicConsumedData SaveAndSendStreamData(QuicStreamId id, absl::string_view data, QuicStreamOffset offset, StreamSendingState state) { return SaveAndSendStreamData(id, data, offset, state, NOT_RETRANSMISSION); } QuicConsumedData SaveAndSendStreamData(QuicStreamId id, absl::string_view data, QuicStreamOffset offset, StreamSendingState state, TransmissionType transmission_type) { ScopedPacketFlusher flusher(this); producer_.SaveStreamData(id, data); if (notifier_ != nullptr) { return notifier_->WriteOrBufferData(id, data.length(), state, transmission_type); } return QuicConnection::SendStreamData(id, data.length(), offset, state); } QuicConsumedData SendStreamDataWithString(QuicStreamId id, absl::string_view data, QuicStreamOffset offset, StreamSendingState state) { ScopedPacketFlusher flusher(this); if (!QuicUtils::IsCryptoStreamId(transport_version(), id) && this->encryption_level() == ENCRYPTION_INITIAL) { this->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); if (perspective() == Perspective::IS_CLIENT && !IsHandshakeComplete()) { OnHandshakeComplete(); } if (version().SupportsAntiAmplificationLimit()) { QuicConnectionPeer::SetAddressValidated(this); } } return SaveAndSendStreamData(id, data, offset, state); } QuicConsumedData SendApplicationDataAtLevel(EncryptionLevel encryption_level, QuicStreamId id, absl::string_view data, QuicStreamOffset offset, StreamSendingState state) { ScopedPacketFlusher flusher(this); QUICHE_DCHECK(encryption_level >= ENCRYPTION_ZERO_RTT); SetEncrypter(encryption_level, std::make_unique<TaggingEncrypter>(encryption_level)); SetDefaultEncryptionLevel(encryption_level); return SaveAndSendStreamData(id, data, offset, state); } QuicConsumedData SendStreamData3() { return SendStreamDataWithString( GetNthClientInitiatedStreamId(1, transport_version()), "food", 0, NO_FIN); } QuicConsumedData SendStreamData5() { return SendStreamDataWithString( GetNthClientInitiatedStreamId(2, transport_version()), "food2", 0, NO_FIN); } QuicConsumedData EnsureWritableAndSendStreamData5() { EXPECT_TRUE(CanWrite(HAS_RETRANSMITTABLE_DATA)); return SendStreamData5(); } QuicConsumedData SendCryptoStreamData() { QuicStreamOffset offset = 0; absl::string_view data("chlo"); if (!QuicVersionUsesCryptoFrames(transport_version())) { return SendCryptoDataWithString(data, offset); } producer_.SaveCryptoData(ENCRYPTION_INITIAL, offset, data); size_t bytes_written; if (notifier_) { bytes_written = notifier_->WriteCryptoData(ENCRYPTION_INITIAL, data.length(), offset); } else { bytes_written = QuicConnection::SendCryptoData(ENCRYPTION_INITIAL, data.length(), offset); } return QuicConsumedData(bytes_written, false); } QuicConsumedData SendCryptoDataWithString(absl::string_view data, QuicStreamOffset offset) { return SendCryptoDataWithString(data, offset, ENCRYPTION_INITIAL); } QuicConsumedData SendCryptoDataWithString(absl::string_view data, QuicStreamOffset offset, EncryptionLevel encryption_level) { if (!QuicVersionUsesCryptoFrames(transport_version())) { return SendStreamDataWithString( QuicUtils::GetCryptoStreamId(transport_version()), data, offset, NO_FIN); } producer_.SaveCryptoData(encryption_level, offset, data); size_t bytes_written; if (notifier_) { bytes_written = notifier_->WriteCryptoData(encryption_level, data.length(), offset); } else { bytes_written = QuicConnection::SendCryptoData(encryption_level, data.length(), offset); } return QuicConsumedData(bytes_written, false); } void set_version(ParsedQuicVersion version) { QuicConnectionPeer::GetFramer(this)->set_version(version); } void SetSupportedVersions(const ParsedQuicVersionVector& versions) { QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions); writer()->SetSupportedVersions(versions); } void set_perspective(Perspective perspective) { writer()->set_perspective(perspective); QuicConnectionPeer::ResetPeerIssuedConnectionIdManager(this); QuicConnectionPeer::SetPerspective(this, perspective); QuicSentPacketManagerPeer::SetPerspective( QuicConnectionPeer::GetSentPacketManager(this), perspective); QuicConnectionPeer::GetFramer(this)->SetInitialObfuscators( TestConnectionId()); } void EnablePathMtuDiscovery(MockSendAlgorithm* send_algorithm) { ASSERT_EQ(Perspective::IS_SERVER, perspective()); if (GetQuicReloadableFlag(quic_enable_mtu_discovery_at_server)) { OnConfigNegotiated(); } else { QuicConfig config; QuicTagVector connection_options; connection_options.push_back(kMTUH); config.SetInitialReceivedConnectionOptions(connection_options); EXPECT_CALL(*send_algorithm, SetFromConfig(_, _)); SetFromConfig(config); } EXPECT_CALL(*send_algorithm, PacingRate(_)) .WillRepeatedly(Return(QuicBandwidth::Infinite())); } TestAlarmFactory::TestAlarm* GetAckAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( &QuicConnectionPeer::GetAckAlarm(this)); } TestAlarmFactory::TestAlarm* GetPingAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( &QuicConnectionPeer::GetPingAlarm(this)); } TestAlarmFactory::TestAlarm* GetRetransmissionAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( &QuicConnectionPeer::GetRetransmissionAlarm(this)); } TestAlarmFactory::TestAlarm* GetSendAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( &QuicConnectionPeer::GetSendAlarm(this)); } TestAlarmFactory::TestAlarm* GetTimeoutAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( &QuicConnectionPeer::GetIdleNetworkDetectorAlarm(this)); } TestAlarmFactory::TestAlarm* GetMtuDiscoveryAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( &QuicConnectionPeer::GetMtuDiscoveryAlarm(this)); } TestAlarmFactory::TestAlarm* GetProcessUndecryptablePacketsAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( &QuicConnectionPeer::GetProcessUndecryptablePacketsAlarm(this)); } TestAlarmFactory::TestAlarm* GetDiscardPreviousOneRttKeysAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( &QuicConnectionPeer::GetDiscardPreviousOneRttKeysAlarm(this)); } TestAlarmFactory::TestAlarm* GetDiscardZeroRttDecryptionKeysAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( &QuicConnectionPeer::GetDiscardZeroRttDecryptionKeysAlarm(this)); } TestAlarmFactory::TestAlarm* GetBlackholeDetectorAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( &QuicConnectionPeer::GetBlackholeDetectorAlarm(this)); } TestAlarmFactory::TestAlarm* GetRetirePeerIssuedConnectionIdAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( QuicConnectionPeer::GetRetirePeerIssuedConnectionIdAlarm(this)); } TestAlarmFactory::TestAlarm* GetRetireSelfIssuedConnectionIdAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( QuicConnectionPeer::GetRetireSelfIssuedConnectionIdAlarm(this)); } TestAlarmFactory::TestAlarm* GetMultiPortProbingAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( &QuicConnectionPeer::GetMultiPortProbingAlarm(this)); } void PathDegradingTimeout() { QUICHE_DCHECK(PathDegradingDetectionInProgress()); GetBlackholeDetectorAlarm()->Fire(); } bool PathDegradingDetectionInProgress() { return QuicConnectionPeer::GetPathDegradingDeadline(this).IsInitialized(); } bool BlackholeDetectionInProgress() { return QuicConnectionPeer::GetBlackholeDetectionDeadline(this) .IsInitialized(); } bool PathMtuReductionDetectionInProgress() { return QuicConnectionPeer::GetPathMtuReductionDetectionDeadline(this) .IsInitialized(); } QuicByteCount GetBytesInFlight() { return QuicConnectionPeer::GetSentPacketManager(this)->GetBytesInFlight(); } void set_notifier(SimpleSessionNotifier* notifier) { notifier_ = notifier; } void ReturnEffectivePeerAddressForNextPacket(const QuicSocketAddress& addr) { next_effective_peer_addr_ = std::make_unique<QuicSocketAddress>(addr); } void SendOrQueuePacket(SerializedPacket packet) override { QuicConnection::SendOrQueuePacket(std::move(packet)); self_address_on_default_path_while_sending_packet_ = self_address(); } QuicSocketAddress self_address_on_default_path_while_sending_packet() { return self_address_on_default_path_while_sending_packet_; } SimpleDataProducer* producer() { return &producer_; } using QuicConnection::active_effective_peer_migration_type; using QuicConnection::IsCurrentPacketConnectivityProbing; using QuicConnection::SelectMutualVersion; using QuicConnection::set_defer_send_in_response_to_packets; protected: QuicSocketAddress GetEffectivePeerAddressFromCurrentPacket() const override { if (next_effective_peer_addr_) { return *std::move(next_effective_peer_addr_); } return QuicConnection::GetEffectivePeerAddressFromCurrentPacket(); } private: TestPacketWriter* writer() { return static_cast<TestPacketWriter*>(QuicConnection::writer()); } SimpleDataProducer producer_; SimpleSessionNotifier* notifier_; std::unique_ptr<QuicSocketAddress> next_effective_peer_addr_; QuicSocketAddress self_address_on_default_path_while_sending_packet_; uint32_t num_unlinkable_client_migration_ = 0; uint32_t num_linkable_client_migration_ = 0; }; enum class AckResponse { kDefer, kImmediate }; struct TestParams { TestParams(ParsedQuicVersion version, AckResponse ack_response) : version(version), ack_response(ack_response) {} ParsedQuicVersion version; AckResponse ack_response; }; std::string PrintToString(const TestParams& p) { return absl::StrCat( ParsedQuicVersionToString(p.version), "_", (p.ack_response == AckResponse::kDefer ? "defer" : "immediate")); } std::vector<TestParams> GetTestParams() { QuicFlagSaver flags; std::vector<TestParams> params; ParsedQuicVersionVector all_supported_versions = AllSupportedVersions(); for (size_t i = 0; i < all_supported_versions.size(); ++i) { for (AckResponse ack_response : {AckResponse::kDefer, AckResponse::kImmediate}) { params.push_back(TestParams(all_supported_versions[i], ack_response)); } } return params; } class QuicConnectionTest : public QuicTestWithParam<TestParams> { public: void SaveConnectionCloseFrame(const QuicConnectionCloseFrame& frame, ConnectionCloseSource ) { saved_connection_close_frame_ = frame; connection_close_frame_count_++; } protected: QuicConnectionTest() : connection_id_(TestConnectionId()), framer_(SupportedVersions(version()), QuicTime::Zero(), Perspective::IS_CLIENT, connection_id_.length()), send_algorithm_(new StrictMock<MockSendAlgorithm>), loss_algorithm_(new MockLossAlgorithm()), helper_(new TestConnectionHelper(&clock_, &random_generator_)), alarm_factory_(new TestAlarmFactory()), peer_framer_(SupportedVersions(version()), QuicTime::Zero(), Perspective::IS_SERVER, connection_id_.length()), peer_creator_(connection_id_, &peer_framer_, nullptr), writer_( new TestPacketWriter(version(), &clock_, Perspective::IS_CLIENT)), connection_(connection_id_, kSelfAddress, kPeerAddress, helper_.get(), alarm_factory_.get(), writer_.get(), Perspective::IS_CLIENT, version(), connection_id_generator_), creator_(QuicConnectionPeer::GetPacketCreator(&connection_)), manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)), frame1_(0, false, 0, absl::string_view(data1)), frame2_(0, false, 3, absl::string_view(data2)), crypto_frame_(ENCRYPTION_INITIAL, 0, absl::string_view(data1)), packet_number_length_(PACKET_4BYTE_PACKET_NUMBER), connection_id_included_(CONNECTION_ID_PRESENT), notifier_(&connection_), connection_close_frame_count_(0) { QUIC_DVLOG(2) << "QuicConnectionTest(" << PrintToString(GetParam()) << ")"; connection_.set_defer_send_in_response_to_packets(GetParam().ack_response == AckResponse::kDefer); framer_.SetInitialObfuscators(TestConnectionId()); connection_.InstallInitialCrypters(TestConnectionId()); CrypterPair crypters; CryptoUtils::CreateInitialObfuscators(Perspective::IS_SERVER, version(), TestConnectionId(), &crypters); peer_creator_.SetEncrypter(ENCRYPTION_INITIAL, std::move(crypters.encrypter)); if (version().KnowsWhichDecrypterToUse()) { peer_framer_.InstallDecrypter(ENCRYPTION_INITIAL, std::move(crypters.decrypter)); } else { peer_framer_.SetDecrypter(ENCRYPTION_INITIAL, std::move(crypters.decrypter)); } for (EncryptionLevel level : {ENCRYPTION_ZERO_RTT, ENCRYPTION_FORWARD_SECURE}) { peer_creator_.SetEncrypter(level, std::make_unique<TaggingEncrypter>(level)); } QuicFramerPeer::SetLastSerializedServerConnectionId( QuicConnectionPeer::GetFramer(&connection_), connection_id_); QuicFramerPeer::SetLastWrittenPacketNumberLength( QuicConnectionPeer::GetFramer(&connection_), packet_number_length_); QuicStreamId stream_id; if (QuicVersionUsesCryptoFrames(version().transport_version)) { stream_id = QuicUtils::GetFirstBidirectionalStreamId( version().transport_version, Perspective::IS_CLIENT); } else { stream_id = QuicUtils::GetCryptoStreamId(version().transport_version); } frame1_.stream_id = stream_id; frame2_.stream_id = stream_id; connection_.set_visitor(&visitor_); connection_.SetSessionNotifier(&notifier_); connection_.set_notifier(&notifier_); connection_.SetSendAlgorithm(send_algorithm_); connection_.SetLossAlgorithm(loss_algorithm_.get()); EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(AnyNumber()); EXPECT_CALL(*send_algorithm_, OnPacketNeutered(_)).Times(AnyNumber()); EXPECT_CALL(*send_algorithm_, GetCongestionWindow()) .WillRepeatedly(Return(kDefaultTCPMSS)); EXPECT_CALL(*send_algorithm_, PacingRate(_)) .WillRepeatedly(Return(QuicBandwidth::Zero())); EXPECT_CALL(*send_algorithm_, BandwidthEstimate()) .Times(AnyNumber()) .WillRepeatedly(Return(QuicBandwidth::Zero())); EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)) .Times(AnyNumber()); EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber()); EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber()); EXPECT_CALL(*send_algorithm_, GetCongestionControlType()) .Times(AnyNumber()); EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber()); EXPECT_CALL(*send_algorithm_, GetCongestionControlType()) .Times(AnyNumber()); EXPECT_CALL(visitor_, WillingAndAbleToWrite()) .WillRepeatedly( Invoke(&notifier_, &SimpleSessionNotifier::WillingToWrite)); EXPECT_CALL(visitor_, OnPacketDecrypted(_)).Times(AnyNumber()); EXPECT_CALL(visitor_, OnCanWrite()) .WillRepeatedly(Invoke(&notifier_, &SimpleSessionNotifier::OnCanWrite)); EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()) .WillRepeatedly(Return(false)); EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber()); EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(AnyNumber()); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber()); EXPECT_CALL(visitor_, MaybeBundleOpportunistically()).Times(AnyNumber()); EXPECT_CALL(visitor_, GetFlowControlSendWindowSize(_)).Times(AnyNumber()); EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()) .Times(testing::AtMost(1)); EXPECT_CALL(*loss_algorithm_, GetLossTimeout()) .WillRepeatedly(Return(QuicTime::Zero())); EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _)) .Times(AnyNumber()); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_START)); if (connection_.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); } peer_creator_.SetDefaultPeerAddress(kSelfAddress); } QuicConnectionTest(const QuicConnectionTest&) = delete; QuicConnectionTest& operator=(const QuicConnectionTest&) = delete; ParsedQuicVersion version() { return GetParam().version; } void SetClientConnectionId(const QuicConnectionId& client_connection_id) { connection_.set_client_connection_id(client_connection_id); writer_->framer()->framer()->SetExpectedClientConnectionIdLength( client_connection_id.length()); } void SetDecrypter(EncryptionLevel level, std::unique_ptr<QuicDecrypter> decrypter) { if (connection_.version().KnowsWhichDecrypterToUse()) { connection_.InstallDecrypter(level, std::move(decrypter)); } else { connection_.SetAlternativeDecrypter(level, std::move(decrypter), false); } } void ProcessPacket(uint64_t number) { EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacket(number); if (connection_.GetSendAlarm()->IsSet()) { connection_.GetSendAlarm()->Fire(); } } void ProcessReceivedPacket(const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, const QuicReceivedPacket& packet) { connection_.ProcessUdpPacket(self_address, peer_address, packet); if (connection_.GetSendAlarm()->IsSet()) { connection_.GetSendAlarm()->Fire(); } } QuicFrame MakeCryptoFrame() const { if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { return QuicFrame(new QuicCryptoFrame(crypto_frame_)); } return QuicFrame(QuicStreamFrame( QuicUtils::GetCryptoStreamId(connection_.transport_version()), false, 0u, absl::string_view())); } void ProcessFramePacket(QuicFrame frame) { ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress, ENCRYPTION_FORWARD_SECURE); } void ProcessFramePacketWithAddresses(QuicFrame frame, QuicSocketAddress self_address, QuicSocketAddress peer_address, EncryptionLevel level) { QuicFrames frames; frames.push_back(QuicFrame(frame)); return ProcessFramesPacketWithAddresses(frames, self_address, peer_address, level); } std::unique_ptr<QuicReceivedPacket> ConstructPacket(QuicFrames frames, EncryptionLevel level, char* buffer, size_t buffer_len) { QUICHE_DCHECK(peer_framer_.HasEncrypterOfEncryptionLevel(level)); peer_creator_.set_encryption_level(level); QuicPacketCreatorPeer::SetSendVersionInPacket( &peer_creator_, level < ENCRYPTION_FORWARD_SECURE && connection_.perspective() == Perspective::IS_SERVER); SerializedPacket serialized_packet = QuicPacketCreatorPeer::SerializeAllFrames(&peer_creator_, frames, buffer, buffer_len); return std::make_unique<QuicReceivedPacket>( serialized_packet.encrypted_buffer, serialized_packet.encrypted_length, clock_.Now()); } void ProcessFramesPacketWithAddresses(QuicFrames frames, QuicSocketAddress self_address, QuicSocketAddress peer_address, EncryptionLevel level) { char buffer[kMaxOutgoingPacketSize]; connection_.ProcessUdpPacket( self_address, peer_address, *ConstructPacket(std::move(frames), level, buffer, kMaxOutgoingPacketSize)); if (connection_.GetSendAlarm()->IsSet()) { connection_.GetSendAlarm()->Fire(); } } void ForceProcessFramePacket(QuicFrame frame) { QuicFrames frames; frames.push_back(QuicFrame(frame)); bool send_version = connection_.perspective() == Perspective::IS_SERVER; if (connection_.version().KnowsWhichDecrypterToUse()) { send_version = true; } QuicPacketCreatorPeer::SetSendVersionInPacket(&peer_creator_, send_version); QuicPacketHeader header; QuicPacketCreatorPeer::FillPacketHeader(&peer_creator_, &header); char encrypted_buffer[kMaxOutgoingPacketSize]; size_t length = peer_framer_.BuildDataPacket( header, frames, encrypted_buffer, kMaxOutgoingPacketSize, ENCRYPTION_INITIAL); QUICHE_DCHECK_GT(length, 0u); const size_t encrypted_length = peer_framer_.EncryptInPlace( ENCRYPTION_INITIAL, header.packet_number, GetStartOfEncryptedData(peer_framer_.version().transport_version, header), length, kMaxOutgoingPacketSize, encrypted_buffer); QUICHE_DCHECK_GT(encrypted_length, 0u); connection_.ProcessUdpPacket( kSelfAddress, kPeerAddress, QuicReceivedPacket(encrypted_buffer, encrypted_length, clock_.Now())); } size_t ProcessFramePacketAtLevel(uint64_t number, QuicFrame frame, EncryptionLevel level) { return ProcessFramePacketAtLevelWithEcn(number, frame, level, ECN_NOT_ECT); } size_t ProcessFramePacketAtLevelWithEcn(uint64_t number, QuicFrame frame, EncryptionLevel level, QuicEcnCodepoint ecn_codepoint) { QuicFrames frames; frames.push_back(frame); return ProcessFramesPacketAtLevelWithEcn(number, frames, level, ecn_codepoint); } size_t ProcessFramesPacketAtLevel(uint64_t number, QuicFrames frames, EncryptionLevel level) { return ProcessFramesPacketAtLevelWithEcn(number, frames, level, ECN_NOT_ECT); } size_t ProcessFramesPacketAtLevelWithEcn(uint64_t number, const QuicFrames& frames, EncryptionLevel level, QuicEcnCodepoint ecn_codepoint) { QuicPacketHeader header = ConstructPacketHeader(number, level); peer_creator_.set_encryption_level(level); if (level > ENCRYPTION_INITIAL) { peer_framer_.SetEncrypter(level, std::make_unique<TaggingEncrypter>(level)); if (connection_.version().KnowsWhichDecrypterToUse()) { connection_.InstallDecrypter( level, std::make_unique<StrictTaggingDecrypter>(level)); } else { connection_.SetAlternativeDecrypter( level, std::make_unique<StrictTaggingDecrypter>(level), false); } } std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames)); char buffer[kMaxOutgoingPacketSize]; size_t encrypted_length = peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet, buffer, kMaxOutgoingPacketSize); connection_.ProcessUdpPacket( kSelfAddress, kPeerAddress, QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false, 0, true, nullptr, 0, false, ecn_codepoint)); if (connection_.GetSendAlarm()->IsSet()) { connection_.GetSendAlarm()->Fire(); } return encrypted_length; } struct PacketInfo { PacketInfo(uint64_t packet_number, QuicFrames frames, EncryptionLevel level) : packet_number(packet_number), frames(frames), level(level) {} uint64_t packet_number; QuicFrames frames; EncryptionLevel level; }; size_t ProcessCoalescedPacket(std::vector<PacketInfo> packets) { return ProcessCoalescedPacket(packets, ECN_NOT_ECT); } size_t ProcessCoalescedPacket(std::vector<PacketInfo> packets, QuicEcnCodepoint ecn_codepoint) { char coalesced_buffer[kMaxOutgoingPacketSize]; size_t coalesced_size = 0; bool contains_initial = false; for (const auto& packet : packets) { QuicPacketHeader header = ConstructPacketHeader(packet.packet_number, packet.level); peer_creator_.set_encryption_level(packet.level); if (packet.level == ENCRYPTION_INITIAL) { contains_initial = true; } EncryptionLevel level = QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_); if (level > ENCRYPTION_INITIAL) { peer_framer_.SetEncrypter(level, std::make_unique<TaggingEncrypter>(level)); if (connection_.version().KnowsWhichDecrypterToUse()) { connection_.InstallDecrypter( level, std::make_unique<StrictTaggingDecrypter>(level)); } else { connection_.SetDecrypter( level, std::make_unique<StrictTaggingDecrypter>(level)); } } std::unique_ptr<QuicPacket> constructed_packet( ConstructPacket(header, packet.frames)); char buffer[kMaxOutgoingPacketSize]; size_t encrypted_length = peer_framer_.EncryptPayload( packet.level, QuicPacketNumber(packet.packet_number), *constructed_packet, buffer, kMaxOutgoingPacketSize); QUICHE_DCHECK_LE(coalesced_size + encrypted_length, kMaxOutgoingPacketSize); memcpy(coalesced_buffer + coalesced_size, buffer, encrypted_length); coalesced_size += encrypted_length; } if (contains_initial) { memset(coalesced_buffer + coalesced_size, '0', kMaxOutgoingPacketSize - coalesced_size); } connection_.ProcessUdpPacket( kSelfAddress, kPeerAddress, QuicReceivedPacket(coalesced_buffer, coalesced_size, clock_.Now(), false, 0, true, nullptr, 0, false, ecn_codepoint)); if (connection_.GetSendAlarm()->IsSet()) { connection_.GetSendAlarm()->Fire(); } return coalesced_size; } size_t ProcessDataPacket(uint64_t number) { return ProcessDataPacketAtLevel(number, false, ENCRYPTION_FORWARD_SECURE); } size_t ProcessDataPacket(QuicPacketNumber packet_number) { return ProcessDataPacketAtLevel(packet_number, false, ENCRYPTION_FORWARD_SECURE); } size_t ProcessDataPacketAtLevel(QuicPacketNumber packet_number, bool has_stop_waiting, EncryptionLevel level) { return ProcessDataPacketAtLevel(packet_number.ToUint64(), has_stop_waiting, level); } size_t ProcessCryptoPacketAtLevel(uint64_t number, EncryptionLevel level) { QuicPacketHeader header = ConstructPacketHeader(number, level); QuicFrames frames; if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { frames.push_back(QuicFrame(&crypto_frame_)); } else { frames.push_back(QuicFrame(frame1_)); } if (level == ENCRYPTION_INITIAL) { frames.push_back(QuicFrame(QuicPaddingFrame(-1))); } std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames); char buffer[kMaxOutgoingPacketSize]; peer_creator_.set_encryption_level(level); size_t encrypted_length = peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet, buffer, kMaxOutgoingPacketSize); connection_.ProcessUdpPacket( kSelfAddress, kPeerAddress, QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false)); if (connection_.GetSendAlarm()->IsSet()) { connection_.GetSendAlarm()->Fire(); } return encrypted_length; } size_t ProcessDataPacketAtLevel(uint64_t number, bool has_stop_waiting, EncryptionLevel level) { std::unique_ptr<QuicPacket> packet( ConstructDataPacket(number, has_stop_waiting, level)); char buffer[kMaxOutgoingPacketSize]; peer_creator_.set_encryption_level(level); size_t encrypted_length = peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet, buffer, kMaxOutgoingPacketSize); connection_.ProcessUdpPacket( kSelfAddress, kPeerAddress, QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false)); if (connection_.GetSendAlarm()->IsSet()) { connection_.GetSendAlarm()->Fire(); } return encrypted_length; } void ProcessClosePacket(uint64_t number) { std::unique_ptr<QuicPacket> packet(ConstructClosePacket(number)); char buffer[kMaxOutgoingPacketSize]; size_t encrypted_length = peer_framer_.EncryptPayload( ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(number), *packet, buffer, kMaxOutgoingPacketSize); connection_.ProcessUdpPacket( kSelfAddress, kPeerAddress, QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false)); } QuicByteCount SendStreamDataToPeer(QuicStreamId id, absl::string_view data, QuicStreamOffset offset, StreamSendingState state, QuicPacketNumber* last_packet) { QuicByteCount packet_size = 0; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(AnyNumber()) .WillRepeatedly(SaveArg<3>(&packet_size)); connection_.SendStreamDataWithString(id, data, offset, state); if (last_packet != nullptr) { *last_packet = creator_->packet_number(); } EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(AnyNumber()); return packet_size; } void SendAckPacketToPeer() { EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); { QuicConnection::ScopedPacketFlusher flusher(&connection_); connection_.SendAck(); } EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(AnyNumber()); } void SendRstStream(QuicStreamId id, QuicRstStreamErrorCode error, QuicStreamOffset bytes_written) { notifier_.WriteOrBufferRstStream(id, error, bytes_written); connection_.OnStreamReset(id, error); } void SendPing() { notifier_.WriteOrBufferPing(); } MessageStatus SendMessage(absl::string_view message) { connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); quiche::QuicheMemSlice slice(quiche::QuicheBuffer::Copy( connection_.helper()->GetStreamSendBufferAllocator(), message)); return connection_.SendMessage(1, absl::MakeSpan(&slice, 1), false); } void ProcessAckPacket(uint64_t packet_number, QuicAckFrame* frame) { if (packet_number > 1) { QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, packet_number - 1); } else { QuicPacketCreatorPeer::ClearPacketNumber(&peer_creator_); } ProcessFramePacket(QuicFrame(frame)); } void ProcessAckPacket(QuicAckFrame* frame) { ProcessFramePacket(QuicFrame(frame)); } void ProcessStopWaitingPacket(QuicStopWaitingFrame frame) { ProcessFramePacket(QuicFrame(frame)); } size_t ProcessStopWaitingPacketAtLevel(uint64_t number, QuicStopWaitingFrame frame, EncryptionLevel ) { return ProcessFramePacketAtLevel(number, QuicFrame(frame), ENCRYPTION_ZERO_RTT); } void ProcessGoAwayPacket(QuicGoAwayFrame* frame) { ProcessFramePacket(QuicFrame(frame)); } bool IsMissing(uint64_t number) { return IsAwaitingPacket(connection_.ack_frame(), QuicPacketNumber(number), QuicPacketNumber()); } std::unique_ptr<QuicPacket> ConstructPacket(const QuicPacketHeader& header, const QuicFrames& frames) { auto packet = BuildUnsizedDataPacket(&peer_framer_, header, frames); EXPECT_NE(nullptr, packet.get()); return packet; } QuicPacketHeader ConstructPacketHeader(uint64_t number, EncryptionLevel level) { QuicPacketHeader header; if (level < ENCRYPTION_FORWARD_SECURE) { header.version_flag = true; header.form = IETF_QUIC_LONG_HEADER_PACKET; header.long_packet_type = EncryptionlevelToLongHeaderType(level); if (QuicVersionHasLongHeaderLengths( peer_framer_.version().transport_version)) { header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2; if (header.long_packet_type == INITIAL) { header.retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1; } } } if (peer_framer_.perspective() == Perspective::IS_SERVER) { header.source_connection_id = connection_id_; header.source_connection_id_included = connection_id_included_; header.destination_connection_id_included = CONNECTION_ID_ABSENT; } else { header.destination_connection_id = connection_id_; header.destination_connection_id_included = connection_id_included_; } if (peer_framer_.perspective() == Perspective::IS_SERVER) { if (!connection_.client_connection_id().IsEmpty()) { header.destination_connection_id = connection_.client_connection_id(); header.destination_connection_id_included = CONNECTION_ID_PRESENT; } else { header.destination_connection_id_included = CONNECTION_ID_ABSENT; } if (header.version_flag) { header.source_connection_id = connection_id_; header.source_connection_id_included = CONNECTION_ID_PRESENT; if (GetParam().version.handshake_protocol == PROTOCOL_QUIC_CRYPTO && header.long_packet_type == ZERO_RTT_PROTECTED) { header.nonce = &kTestDiversificationNonce; } } } header.packet_number_length = packet_number_length_; header.packet_number = QuicPacketNumber(number); return header; } std::unique_ptr<QuicPacket> ConstructDataPacket(uint64_t number, bool has_stop_waiting, EncryptionLevel level) { QuicPacketHeader header = ConstructPacketHeader(number, level); QuicFrames frames; if (VersionHasIetfQuicFrames(version().transport_version) && (level == ENCRYPTION_INITIAL || level == ENCRYPTION_HANDSHAKE)) { frames.push_back(QuicFrame(QuicPingFrame())); frames.push_back(QuicFrame(QuicPaddingFrame(100))); } else { frames.push_back(QuicFrame(frame1_)); if (has_stop_waiting) { frames.push_back(QuicFrame(stop_waiting_)); } } return ConstructPacket(header, frames); } std::unique_ptr<SerializedPacket> ConstructProbingPacket() { peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); if (VersionHasIetfQuicFrames(version().transport_version)) { QuicPathFrameBuffer payload = { {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}}; return QuicPacketCreatorPeer:: SerializePathChallengeConnectivityProbingPacket(&peer_creator_, payload); } QUICHE_DCHECK(!GetQuicReloadableFlag(quic_ignore_gquic_probing)); return QuicPacketCreatorPeer::SerializeConnectivityProbingPacket( &peer_creator_); } std::unique_ptr<QuicPacket> ConstructClosePacket(uint64_t number) { peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); QuicPacketHeader header; if (peer_framer_.perspective() == Perspective::IS_SERVER) { header.source_connection_id = connection_id_; header.destination_connection_id_included = CONNECTION_ID_ABSENT; } else { header.destination_connection_id = connection_id_; header.destination_connection_id_included = CONNECTION_ID_ABSENT; } header.packet_number = QuicPacketNumber(number); QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY; QuicConnectionCloseFrame qccf(peer_framer_.transport_version(), kQuicErrorCode, NO_IETF_QUIC_ERROR, "", 0); QuicFrames frames; frames.push_back(QuicFrame(&qccf)); return ConstructPacket(header, frames); } QuicTime::Delta DefaultRetransmissionTime() { return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs); } QuicTime::Delta DefaultDelayedAckTime() { return QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs()); } const QuicStopWaitingFrame InitStopWaitingFrame(uint64_t least_unacked) { QuicStopWaitingFrame frame; frame.least_unacked = QuicPacketNumber(least_unacked); return frame; } QuicAckFrame ConstructAckFrame(uint64_t largest_acked, uint64_t missing) { return ConstructAckFrame(QuicPacketNumber(largest_acked), QuicPacketNumber(missing)); } QuicAckFrame ConstructAckFrame(QuicPacketNumber largest_acked, QuicPacketNumber missing) { if (missing == QuicPacketNumber(1)) { return InitAckFrame({{missing + 1, largest_acked + 1}}); } return InitAckFrame( {{QuicPacketNumber(1), missing}, {missing + 1, largest_acked + 1}}); } void AckPacket(QuicPacketNumber arrived, QuicAckFrame* frame) { EXPECT_FALSE(frame->packets.Contains(arrived)); frame->packets.Add(arrived); } void TriggerConnectionClose() { EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)) .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame)); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); QuicAckFrame frame = InitAckFrame(10000); ProcessAckPacket(1, &frame); EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) == nullptr); EXPECT_EQ(1, connection_close_frame_count_); EXPECT_THAT(saved_connection_close_frame_.quic_error_code, IsError(QUIC_INVALID_ACK_DATA)); } void BlockOnNextWrite() { writer_->BlockOnNextWrite(); EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1)); } void SimulateNextPacketTooLarge() { writer_->SimulateNextPacketTooLarge(); } void ExpectNextPacketUnprocessable() { writer_->ExpectNextPacketUnprocessable(); } void AlwaysGetPacketTooLarge() { writer_->AlwaysGetPacketTooLarge(); } void SetWritePauseTimeDelta(QuicTime::Delta delta) { writer_->SetWritePauseTimeDelta(delta); } void CongestionBlockWrites() { EXPECT_CALL(*send_algorithm_, CanSend(_)) .WillRepeatedly(testing::Return(false)); } void CongestionUnblockWrites() { EXPECT_CALL(*send_algorithm_, CanSend(_)) .WillRepeatedly(testing::Return(true)); } void set_perspective(Perspective perspective) { connection_.set_perspective(perspective); if (perspective == Perspective::IS_SERVER) { connection_.set_can_truncate_connection_ids(true); QuicConnectionPeer::SetNegotiatedVersion(&connection_); connection_.OnSuccessfulVersionNegotiation(); } QuicFramerPeer::SetPerspective(&peer_framer_, QuicUtils::InvertPerspective(perspective)); peer_framer_.SetInitialObfuscators(TestConnectionId()); for (EncryptionLevel level : {ENCRYPTION_ZERO_RTT, ENCRYPTION_HANDSHAKE, ENCRYPTION_FORWARD_SECURE}) { if (peer_framer_.HasEncrypterOfEncryptionLevel(level)) { peer_creator_.SetEncrypter(level, std::make_unique<TaggingEncrypter>(level)); } } } void set_packets_between_probes_base( const QuicPacketCount packets_between_probes_base) { QuicConnectionPeer::ReInitializeMtuDiscoverer( &connection_, packets_between_probes_base, QuicPacketNumber(packets_between_probes_base)); } bool IsDefaultTestConfiguration() { TestParams p = GetParam(); return p.ack_response == AckResponse::kImmediate && p.version == AllSupportedVersions()[0]; } void TestConnectionCloseQuicErrorCode(QuicErrorCode expected_code) { EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) == nullptr); const std::vector<QuicConnectionCloseFrame>& connection_close_frames = writer_->connection_close_frames(); ASSERT_EQ(1u, connection_close_frames.size()); EXPECT_THAT(connection_close_frames[0].quic_error_code, IsError(expected_code)); if (!VersionHasIetfQuicFrames(version().transport_version)) { EXPECT_THAT(connection_close_frames[0].wire_error_code, IsError(expected_code)); EXPECT_EQ(GOOGLE_QUIC_CONNECTION_CLOSE, connection_close_frames[0].close_type); return; } QuicErrorCodeToIetfMapping mapping = QuicErrorCodeToTransportErrorCode(expected_code); if (mapping.is_transport_close) { EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE, connection_close_frames[0].close_type); } else { EXPECT_EQ(IETF_QUIC_APPLICATION_CONNECTION_CLOSE, connection_close_frames[0].close_type); } EXPECT_EQ(mapping.error_code, connection_close_frames[0].wire_error_code); } void MtuDiscoveryTestInit() { set_perspective(Perspective::IS_SERVER); QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false); if (version().SupportsAntiAmplificationLimit()) { QuicConnectionPeer::SetAddressValidated(&connection_); } connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); EXPECT_TRUE(connection_.connected()); } void PathProbeTestInit(Perspective perspective, bool receive_new_server_connection_id = true) { set_perspective(perspective); connection_.CreateConnectionIdManager(); EXPECT_EQ(connection_.perspective(), perspective); if (perspective == Perspective::IS_SERVER) { QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false); } connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); connection_.RemoveEncrypter(ENCRYPTION_INITIAL); connection_.NeuterUnencryptedPackets(); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); if (version().SupportsAntiAmplificationLimit() && perspective == Perspective::IS_SERVER) { QuicConnectionPeer::SetAddressValidated(&connection_); } QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress()); QuicConnectionPeer::SetEffectivePeerAddress(&connection_, QuicSocketAddress()); EXPECT_FALSE(connection_.effective_peer_address().IsInitialized()); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); } else { EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber()); } QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2); ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); if (perspective == Perspective::IS_CLIENT && receive_new_server_connection_id && version().HasIetfQuicFrames()) { QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(1234); ASSERT_NE(frame.connection_id, connection_.connection_id()); frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); frame.retire_prior_to = 0u; frame.sequence_number = 1u; connection_.OnNewConnectionIdFrame(frame); } } void ServerHandlePreferredAddressInit() { ASSERT_TRUE(GetParam().version.HasIetfQuicFrames()); set_perspective(Perspective::IS_SERVER); connection_.CreateConnectionIdManager(); QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false); SetQuicReloadableFlag(quic_use_received_client_addresses_cache, true); EXPECT_CALL(visitor_, AllowSelfAddressChange()) .WillRepeatedly(Return(true)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); connection_.RemoveEncrypter(ENCRYPTION_INITIAL); connection_.NeuterUnencryptedPackets(); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); if (version().SupportsAntiAmplificationLimit()) { QuicConnectionPeer::SetAddressValidated(&connection_); } QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress()); QuicConnectionPeer::SetEffectivePeerAddress(&connection_, QuicSocketAddress()); EXPECT_FALSE(connection_.effective_peer_address().IsInitialized()); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); } else { EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber()); } QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2); ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); QuicConfig config; EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); connection_.set_expected_server_preferred_address(kServerPreferredAddress); } void ServerPreferredAddressInit(QuicConfig& config) { ASSERT_EQ(Perspective::IS_CLIENT, connection_.perspective()); ASSERT_TRUE(version().HasIetfQuicFrames()); ASSERT_TRUE(connection_.self_address().host().IsIPv6()); const QuicConnectionId connection_id = TestConnectionId(17); const StatelessResetToken reset_token = QuicUtils::GenerateStatelessResetToken(connection_id); connection_.CreateConnectionIdManager(); connection_.SendCryptoStreamData(); EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); QuicAckFrame frame = InitAckFrame(1); ProcessFramePacketAtLevel(1, QuicFrame(&frame), ENCRYPTION_INITIAL); connection_.RemoveEncrypter(ENCRYPTION_INITIAL); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); config.SetConnectionOptionsToSend(QuicTagVector{kSPAD}); QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestStatelessResetToken); QuicConfigPeer::SetReceivedAlternateServerAddress(&config, kServerPreferredAddress); QuicConfigPeer::SetPreferredAddressConnectionIdAndToken( &config, connection_id, reset_token); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); ASSERT_TRUE( QuicConnectionPeer::GetReceivedServerPreferredAddress(&connection_) .IsInitialized()); EXPECT_EQ( kServerPreferredAddress, QuicConnectionPeer::GetReceivedServerPreferredAddress(&connection_)); } void ForceWillingAndAbleToWriteOnceForDeferSending() { if (GetParam().ack_response == AckResponse::kDefer) { EXPECT_CALL(visitor_, WillingAndAbleToWrite()) .WillOnce(Return(true)) .RetiresOnSaturation(); } } void TestClientRetryHandling(bool invalid_retry_tag, bool missing_original_id_in_config, bool wrong_original_id_in_config, bool missing_retry_id_in_config, bool wrong_retry_id_in_config); void TestReplaceConnectionIdFromInitial(); QuicConnectionId connection_id_; QuicFramer framer_; MockSendAlgorithm* send_algorithm_; std::unique_ptr<MockLossAlgorithm> loss_algorithm_; MockClock clock_; MockRandom random_generator_; quiche::SimpleBufferAllocator buffer_allocator_; std::unique_ptr<TestConnectionHelper> helper_; std::unique_ptr<TestAlarmFactory> alarm_factory_; QuicFramer peer_framer_; QuicPacketCreator peer_creator_; std::unique_ptr<TestPacketWriter> writer_; TestConnection connection_; QuicPacketCreator* creator_; QuicSentPacketManager* manager_; StrictMock<MockQuicConnectionVisitor> visitor_; QuicStreamFrame frame1_; QuicStreamFrame frame2_; QuicCryptoFrame crypto_frame_; QuicAckFrame ack_; QuicStopWaitingFrame stop_waiting_; QuicPacketNumberLength packet_number_length_; QuicConnectionIdIncluded connection_id_included_; SimpleSessionNotifier notifier_; QuicConnectionCloseFrame saved_connection_close_frame_; int connection_close_frame_count_; MockConnectionIdGenerator connection_id_generator_; }; INSTANTIATE_TEST_SUITE_P(QuicConnectionTests, QuicConnectionTest, ::testing::ValuesIn(GetTestParams()), ::testing::PrintToStringParamName()); TEST_P(QuicConnectionTest, CloseErrorCodeTestTransport) { EXPECT_TRUE(connection_.connected()); EXPECT_CALL(visitor_, OnConnectionClosed(_, _)); connection_.CloseConnection( IETF_QUIC_PROTOCOL_VIOLATION, "Should be transport close", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); EXPECT_FALSE(connection_.connected()); TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION); } TEST_P(QuicConnectionTest, CloseErrorCodeTestApplication) { EXPECT_TRUE(connection_.connected()); EXPECT_CALL(visitor_, OnConnectionClosed(_, _)); connection_.CloseConnection( QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE, "Should be application close", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); EXPECT_FALSE(connection_.connected()); TestConnectionCloseQuicErrorCode(QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE); } TEST_P(QuicConnectionTest, SelfAddressChangeAtClient) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective()); EXPECT_TRUE(connection_.connected()); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)); } else { EXPECT_CALL(visitor_, OnStreamFrame(_)); } ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress, ENCRYPTION_INITIAL); QuicIpAddress host; host.FromString("1.1.1.1"); QuicSocketAddress self_address(host, 123); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)); } else { EXPECT_CALL(visitor_, OnStreamFrame(_)); } ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address, kPeerAddress, ENCRYPTION_INITIAL); EXPECT_TRUE(connection_.connected()); EXPECT_NE(connection_.self_address(), self_address); } TEST_P(QuicConnectionTest, SelfAddressChangeAtServer) { set_perspective(Perspective::IS_SERVER); QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false); EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective()); EXPECT_TRUE(connection_.connected()); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)); } else { EXPECT_CALL(visitor_, OnStreamFrame(_)); } ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress, ENCRYPTION_INITIAL); QuicIpAddress host; host.FromString("1.1.1.1"); QuicSocketAddress self_address(host, 123); EXPECT_EQ(0u, connection_.GetStats().packets_dropped); EXPECT_CALL(visitor_, AllowSelfAddressChange()).WillOnce(Return(false)); ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address, kPeerAddress, ENCRYPTION_INITIAL); EXPECT_TRUE(connection_.connected()); EXPECT_EQ(1u, connection_.GetStats().packets_dropped); } TEST_P(QuicConnectionTest, AllowSelfAddressChangeToMappedIpv4AddressAtServer) { set_perspective(Perspective::IS_SERVER); QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false); EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective()); EXPECT_TRUE(connection_.connected()); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3); } else { EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3); } QuicIpAddress host; host.FromString("1.1.1.1"); QuicSocketAddress self_address1(host, 443); connection_.SetSelfAddress(self_address1); ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1, kPeerAddress, ENCRYPTION_INITIAL); QuicIpAddress host2; host2.FromString( absl::StrCat("::ffff:", connection_.self_address().host().ToString())); QuicSocketAddress self_address2(host2, connection_.self_address().port()); ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address2, kPeerAddress, ENCRYPTION_INITIAL); EXPECT_TRUE(connection_.connected()); ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1, kPeerAddress, ENCRYPTION_INITIAL); EXPECT_TRUE(connection_.connected()); } TEST_P(QuicConnectionTest, ClientAddressChangeAndPacketReordered) { set_perspective(Perspective::IS_SERVER); QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress()); QuicConnectionPeer::SetEffectivePeerAddress(&connection_, QuicSocketAddress()); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); } else { EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber()); } QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5); const QuicSocketAddress kNewPeerAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), 23456); ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kNewPeerAddress, ENCRYPTION_INITIAL); EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address()); QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4); EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0); ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress, ENCRYPTION_INITIAL); EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address()); } TEST_P(QuicConnectionTest, PeerPortChangeAtServer) { set_perspective(Perspective::IS_SERVER); QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false); EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective()); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); if (version().SupportsAntiAmplificationLimit()) { QuicConnectionPeer::SetAddressValidated(&connection_); } QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress()); QuicConnectionPeer::SetEffectivePeerAddress(&connection_, QuicSocketAddress()); EXPECT_FALSE(connection_.effective_peer_address().IsInitialized()); 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()); const QuicSocketAddress kNewPeerAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), 23456); EXPECT_CALL(visitor_, OnStreamFrame(_)) .WillOnce(Invoke( [=, this]() { EXPECT_EQ(kPeerAddress, connection_.peer_address()); })) .WillOnce(Invoke([=, this]() { EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); })); QuicFrames frames; frames.push_back(QuicFrame(frame1_)); ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1); QuicFrames frames2; frames2.push_back(QuicFrame(frame2_)); ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address()); EXPECT_EQ(2 * default_init_rtt, rtt_stats->initial_rtt()); EXPECT_EQ(1u, manager_->GetConsecutivePtoCount()); EXPECT_EQ(manager_->GetSendAlgorithm(), send_algorithm_); if (version().HasIetfQuicFrames()) { EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type()); EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration); EXPECT_EQ(1u, connection_.num_linkable_client_migration()); } } TEST_P(QuicConnectionTest, PeerIpAddressChangeAtServer) { set_perspective(Perspective::IS_SERVER); if (!version().SupportsAntiAmplificationLimit() || GetQuicFlag(quic_enforce_strict_amplification_factor)) { return; } QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false); EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective()); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.RemoveEncrypter(ENCRYPTION_INITIAL); connection_.NeuterUnencryptedPackets(); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); QuicConnectionPeer::SetAddressValidated(&connection_); connection_.OnHandshakeComplete(); QuicConfig config; QuicTagVector connection_options; connection_options.push_back(k5RTO); config.SetInitialReceivedConnectionOptions(connection_options); QuicConfigPeer::SetNegotiated(&config, true); QuicConfigPeer::SetReceivedOriginalConnectionId(&config, connection_.connection_id()); QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config, QuicConnectionId()); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress()); QuicConnectionPeer::SetEffectivePeerAddress(&connection_, QuicSocketAddress()); EXPECT_FALSE(connection_.effective_peer_address().IsInitialized()); const QuicSocketAddress kNewPeerAddress = QuicSocketAddress(QuicIpAddress::Loopback4(), 23456); EXPECT_CALL(visitor_, OnStreamFrame(_)) .WillOnce(Invoke( [=, this]() { EXPECT_EQ(kPeerAddress, connection_.peer_address()); })) .WillOnce(Invoke([=, this]() { EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); })); QuicFrames frames; frames.push_back(QuicFrame(frame1_)); ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); connection_.SendStreamData3(); EXPECT_EQ(1u, writer_->packets_write_attempts()); EXPECT_TRUE(connection_.BlackholeDetectionInProgress()); EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA)) .Times(0); EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber()); QuicFrames frames2; frames2.push_back(QuicFrame(frame2_)); ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address()); EXPECT_EQ(IPV6_TO_IPV4_CHANGE, connection_.active_effective_peer_migration_type()); EXPECT_FALSE(connection_.BlackholeDetectionInProgress()); EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); EXPECT_EQ(2u, writer_->packets_write_attempts()); EXPECT_FALSE(writer_->path_challenge_frames().empty()); QuicPathFrameBuffer payload = writer_->path_challenge_frames().front().data_buffer; EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(), send_algorithm_); send_algorithm_ = new StrictMock<MockSendAlgorithm>(); EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true)); EXPECT_CALL(*send_algorithm_, GetCongestionWindow()) .WillRepeatedly(Return(kDefaultTCPMSS)); EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber()); 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_, PopulateConnectionStats(_)).Times(AnyNumber()); connection_.SetSendAlgorithm(send_algorithm_); EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address()); EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address()); EXPECT_EQ(1u, connection_.GetStats().num_reverse_path_validtion_upon_migration); connection_.SendCryptoDataWithString("foo", 0); EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); QuicAckFrame ack_frame = InitAckFrame(2); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _)); ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress, kNewPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address()); EXPECT_EQ(IPV6_TO_IPV4_CHANGE, connection_.active_effective_peer_migration_type()); QuicFrames frames3; frames3.push_back(QuicFrame(QuicPathResponseFrame(99, payload))); EXPECT_CALL(visitor_, MaybeSendAddressToken()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(testing::AtLeast(1u)); ProcessFramesPacketWithAddresses(frames3, kSelfAddress, kNewPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type()); connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0); EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration); EXPECT_EQ(1u, connection_.num_linkable_client_migration()); } TEST_P(QuicConnectionTest, PeerIpAddressChangeAtServerWithMissingConnectionId) { set_perspective(Perspective::IS_SERVER); if (!version().HasIetfQuicFrames()) { return; } QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false); EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective()); QuicConnectionId client_cid0 = TestConnectionId(1); QuicConnectionId client_cid1 = TestConnectionId(3); QuicConnectionId server_cid1; SetClientConnectionId(client_cid0); connection_.CreateConnectionIdManager(); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); QuicConnectionPeer::SetAddressValidated(&connection_); if (!connection_.connection_id().IsEmpty()) { EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_)) .WillOnce(Return(TestConnectionId(456))); } EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)) .WillOnce(Invoke([&](const QuicConnectionId& cid) { server_cid1 = cid; return true; })); EXPECT_CALL(visitor_, SendNewConnectionId(_)); connection_.OnHandshakeComplete(); QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress()); QuicConnectionPeer::SetEffectivePeerAddress(&connection_, QuicSocketAddress()); EXPECT_FALSE(connection_.effective_peer_address().IsInitialized()); const QuicSocketAddress kNewPeerAddress = QuicSocketAddress(QuicIpAddress::Loopback4(), 23456); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2); QuicFrames frames; frames.push_back(QuicFrame(frame1_)); ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); connection_.SendStreamData3(); EXPECT_EQ(1u, writer_->packets_write_attempts()); peer_creator_.SetServerConnectionId(server_cid1); EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1); EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber()); QuicFrames frames2; frames2.push_back(QuicFrame(frame2_)); if (GetQuicFlag(quic_enforce_strict_amplification_factor)) { frames2.push_back(QuicFrame(QuicPaddingFrame(-1))); } ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address()); EXPECT_EQ(1u, writer_->packets_write_attempts()); QuicNewConnectionIdFrame new_cid_frame; new_cid_frame.connection_id = client_cid1; new_cid_frame.sequence_number = 1u; new_cid_frame.retire_prior_to = 0u; connection_.OnNewConnectionIdFrame(new_cid_frame); connection_.SendStreamData3(); EXPECT_EQ(2u, writer_->packets_write_attempts()); } TEST_P(QuicConnectionTest, EffectivePeerAddressChangeAtServer) { if (GetQuicFlag(quic_enforce_strict_amplification_factor)) { return; } set_perspective(Perspective::IS_SERVER); QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false); EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective()); if (version().SupportsAntiAmplificationLimit()) { QuicConnectionPeer::SetAddressValidated(&connection_); } connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.RemoveEncrypter(ENCRYPTION_INITIAL); connection_.NeuterUnencryptedPackets(); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress()); QuicConnectionPeer::SetEffectivePeerAddress(&connection_, QuicSocketAddress()); const QuicSocketAddress kEffectivePeerAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), 43210); connection_.ReturnEffectivePeerAddressForNextPacket(kEffectivePeerAddress); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); } else { EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber()); } ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kEffectivePeerAddress, connection_.effective_peer_address()); const QuicSocketAddress kNewEffectivePeerAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), 54321); connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress); EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1); ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address()); EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address()); if (GetParam().version.HasIetfQuicFrames()) { EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type()); EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration); EXPECT_EQ(1u, connection_.num_linkable_client_migration()); } const QuicSocketAddress kNewPeerAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), 23456); connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress); EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0); if (!GetParam().version.HasIetfQuicFrames()) { QuicAckFrame ack_frame = InitAckFrame(1); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _)); ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress, kNewPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address()); EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type()); } const QuicSocketAddress kNewerEffectivePeerAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), 65432); const QuicSocketAddress kFinalPeerAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), 34567); connection_.ReturnEffectivePeerAddressForNextPacket( kNewerEffectivePeerAddress); EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1); ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kFinalPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(kFinalPeerAddress, connection_.peer_address()); EXPECT_EQ(kNewerEffectivePeerAddress, connection_.effective_peer_address()); if (GetParam().version.HasIetfQuicFrames()) { EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type()); EXPECT_EQ(send_algorithm_, connection_.sent_packet_manager().GetSendAlgorithm()); EXPECT_EQ(2u, connection_.GetStats().num_validated_peer_migration); } const QuicSocketAddress kNewestEffectivePeerAddress = QuicSocketAddress(QuicIpAddress::Loopback4(), 65430); connection_.ReturnEffectivePeerAddressForNextPacket( kNewestEffectivePeerAddress); EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1); if (!GetParam().version.HasIetfQuicFrames()) { EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(1); } ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kFinalPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(kFinalPeerAddress, connection_.peer_address()); EXPECT_EQ(kNewestEffectivePeerAddress, connection_.effective_peer_address()); EXPECT_EQ(IPV6_TO_IPV4_CHANGE, connection_.active_effective_peer_migration_type()); if (GetParam().version.HasIetfQuicFrames()) { EXPECT_NE(send_algorithm_, connection_.sent_packet_manager().GetSendAlgorithm()); EXPECT_EQ(kFinalPeerAddress, writer_->last_write_peer_address()); EXPECT_FALSE(writer_->path_challenge_frames().empty()); EXPECT_EQ(0u, connection_.GetStats() .num_peer_migration_while_validating_default_path); EXPECT_TRUE(connection_.HasPendingPathValidation()); } } TEST_P(QuicConnectionTest, ConnectionMigrationWithPendingPaddingBytes) { set_perspective(Perspective::IS_SERVER); if (!version().HasIetfQuicFrames()) { return; } QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false); connection_.CreateConnectionIdManager(); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); QuicConnectionPeer::SetPeerAddress(&connection_, kPeerAddress); QuicConnectionPeer::SetEffectivePeerAddress(&connection_, kPeerAddress); QuicConnectionPeer::SetAddressValidated(&connection_); QuicConnectionId new_cid; if (!connection_.connection_id().IsEmpty()) { EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_)) .WillOnce(Return(TestConnectionId(456))); } EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)) .WillOnce(Invoke([&](const QuicConnectionId& cid) { new_cid = cid; return true; })); EXPECT_CALL(visitor_, SendNewConnectionId(_)); connection_.RemoveEncrypter(ENCRYPTION_INITIAL); connection_.NeuterUnencryptedPackets(); connection_.OnHandshakeComplete(); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_); packet_creator->FlushCurrentPacket(); packet_creator->AddPendingPadding(50u); const QuicSocketAddress kPeerAddress3 = QuicSocketAddress(QuicIpAddress::Loopback6(), 56789); auto ack_frame = InitAckFrame(1); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _)); EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1); ProcessFramesPacketWithAddresses({QuicFrame(&ack_frame)}, kSelfAddress, kPeerAddress3, ENCRYPTION_FORWARD_SECURE); ASSERT_EQ(connection_.self_address_on_default_path_while_sending_packet() .host() .address_family(), IpAddressFamily::IP_V6); } TEST_P(QuicConnectionTest, ReversePathValidationResponseReceivedFromUnexpectedPeerAddress) { set_perspective(Perspective::IS_SERVER); if (!version().HasIetfQuicFrames() || GetQuicFlag(quic_enforce_strict_amplification_factor)) { return; } QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false); connection_.CreateConnectionIdManager(); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); QuicConnectionPeer::SetPeerAddress(&connection_, kPeerAddress); QuicConnectionPeer::SetEffectivePeerAddress(&connection_, kPeerAddress); QuicConnectionPeer::SetAddressValidated(&connection_); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); QuicConnectionId new_cid; if (!connection_.connection_id().IsEmpty()) { EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_)) .WillOnce(Return(TestConnectionId(456))); } EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)) .WillOnce(Invoke([&](const QuicConnectionId& cid) { new_cid = cid; return true; })); EXPECT_CALL(visitor_, SendNewConnectionId(_)); connection_.RemoveEncrypter(ENCRYPTION_INITIAL); connection_.NeuterUnencryptedPackets(); connection_.OnHandshakeComplete(); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1); const QuicSocketAddress kPeerAddress2 = QuicSocketAddress(QuicIpAddress::Loopback4(), 23456); peer_creator_.SetServerConnectionId(new_cid); ProcessFramesPacketWithAddresses({QuicFrame(QuicPingFrame())}, kSelfAddress, kPeerAddress2, ENCRYPTION_FORWARD_SECURE); EXPECT_FALSE(writer_->path_challenge_frames().empty()); QuicPathFrameBuffer reverse_path_challenge_payload = writer_->path_challenge_frames().front().data_buffer; { QuicConnection::ScopedPacketFlusher flusher(&connection_); const QuicSocketAddress kPeerAddress3 = QuicSocketAddress(QuicIpAddress::Loopback6(), 56789); auto ack_frame = InitAckFrame(1); EXPECT_CALL(visitor_, OnConnectionMigration(IPV4_TO_IPV6_CHANGE)).Times(1); EXPECT_CALL(visitor_, MaybeSendAddressToken()).WillOnce(Invoke([this]() { connection_.SendControlFrame( QuicFrame(new QuicNewTokenFrame(1, "new_token"))); return true; })); ProcessFramesPacketWithAddresses( {QuicFrame(QuicPathResponseFrame(0, reverse_path_challenge_payload)), QuicFrame(&ack_frame)}, kSelfAddress, kPeerAddress3, ENCRYPTION_FORWARD_SECURE); } } TEST_P(QuicConnectionTest, ReversePathValidationFailureAtServer) { set_perspective(Perspective::IS_SERVER); if (!version().HasIetfQuicFrames()) { return; } QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false); EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective()); SetClientConnectionId(TestConnectionId(1)); connection_.CreateConnectionIdManager(); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.RemoveEncrypter(ENCRYPTION_INITIAL); connection_.NeuterUnencryptedPackets(); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); QuicConnectionPeer::SetAddressValidated(&connection_); QuicConnectionId client_cid0 = connection_.client_connection_id(); QuicConnectionId client_cid1 = TestConnectionId(2); QuicConnectionId server_cid0 = connection_.connection_id(); QuicConnectionId server_cid1; if (!connection_.connection_id().IsEmpty()) { EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_)) .WillOnce(Return(TestConnectionId(456))); } EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)) .WillOnce(Invoke([&](const QuicConnectionId& cid) { server_cid1 = cid; return true; })); EXPECT_CALL(visitor_, SendNewConnectionId(_)); connection_.OnHandshakeComplete(); QuicNewConnectionIdFrame new_cid_frame; new_cid_frame.connection_id = client_cid1; new_cid_frame.sequence_number = 1u; new_cid_frame.retire_prior_to = 0u; connection_.OnNewConnectionIdFrame(new_cid_frame); auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_); ASSERT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0); ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0); QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress()); QuicConnectionPeer::SetEffectivePeerAddress(&connection_, QuicSocketAddress()); EXPECT_FALSE(connection_.effective_peer_address().IsInitialized()); const QuicSocketAddress kNewPeerAddress = QuicSocketAddress(QuicIpAddress::Loopback4(), 23456); EXPECT_CALL(visitor_, OnStreamFrame(_)) .WillOnce(Invoke( [=, this]() { EXPECT_EQ(kPeerAddress, connection_.peer_address()); })) .WillOnce(Invoke([=, this]() { EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); })); QuicFrames frames; frames.push_back(QuicFrame(frame1_)); ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1); EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(0); QuicFrames frames2; frames2.push_back(QuicFrame(frame2_)); QuicPaddingFrame padding; frames2.push_back(QuicFrame(padding)); peer_creator_.SetServerConnectionId(server_cid1); ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address()); EXPECT_EQ(IPV6_TO_IPV4_CHANGE, connection_.active_effective_peer_migration_type()); EXPECT_LT(0u, writer_->packets_write_attempts()); EXPECT_TRUE(connection_.HasPendingPathValidation()); EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(), send_algorithm_); EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address()); EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address()); const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_); const auto* alternative_path = QuicConnectionPeer::GetAlternativePath(&connection_); EXPECT_EQ(default_path->client_connection_id, client_cid1); EXPECT_EQ(default_path->server_connection_id, server_cid1); EXPECT_EQ(alternative_path->client_connection_id, client_cid0); EXPECT_EQ(alternative_path->server_connection_id, server_cid0); EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid1); EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid1); for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes; ++i) { clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs)); static_cast<TestAlarmFactory::TestAlarm*>( QuicPathValidatorPeer::retry_timer( QuicConnectionPeer::path_validator(&connection_))) ->Fire(); } EXPECT_EQ(IPV6_TO_IPV4_CHANGE, connection_.active_effective_peer_migration_type()); ProcessFramesPacketWithAddresses( {QuicFrame(QuicPingFrame()), QuicFrame(QuicPaddingFrame())}, kSelfAddress, kNewPeerAddress, ENCRYPTION_FORWARD_SECURE); SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr); EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs)); static_cast<TestAlarmFactory::TestAlarm*>( QuicPathValidatorPeer::retry_timer( QuicConnectionPeer::path_validator(&connection_))) ->Fire(); EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type()); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); EXPECT_EQ(connection_.sent_packet_manager().GetSendAlgorithm(), send_algorithm_); EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); EXPECT_EQ(default_path->client_connection_id, client_cid0); EXPECT_EQ(default_path->server_connection_id, server_cid0); EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty()); EXPECT_FALSE(alternative_path->stateless_reset_token.has_value()); auto* retire_peer_issued_cid_alarm = connection_.GetRetirePeerIssuedConnectionIdAlarm(); ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet()); EXPECT_CALL(visitor_, SendRetireConnectionId(1u)); retire_peer_issued_cid_alarm->Fire(); EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0); EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0); } TEST_P(QuicConnectionTest, ReceivePathProbeWithNoAddressChangeAtServer) { if (!version().HasIetfQuicFrames() && GetQuicReloadableFlag(quic_ignore_gquic_probing)) { return; } PathProbeTestInit(Perspective::IS_SERVER); EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0); EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(0); std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket(); std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket( QuicEncryptedPacket(probing_packet->encrypted_buffer, probing_packet->encrypted_length), clock_.Now())); uint64_t num_probing_received = connection_.GetStats().num_connectivity_probing_received; ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received); EXPECT_EQ( num_probing_received + (GetParam().version.HasIetfQuicFrames() ? 1u : 0u), connection_.GetStats().num_connectivity_probing_received); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); } TEST_P(QuicConnectionTest, BufferedMtuPacketTooBig) { EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1); writer_->SetWriteBlocked(); connection_.SendMtuDiscoveryPacket(kMaxOutgoingPacketSize); EXPECT_EQ(1u, connection_.NumQueuedPackets()); EXPECT_TRUE(writer_->IsWriteBlocked()); writer_->AlwaysGetPacketTooLarge(); writer_->SetWritable(); connection_.OnCanWrite(); } TEST_P(QuicConnectionTest, WriteOutOfOrderQueuedPackets) { if (!IsDefaultTestConfiguration()) { return; } set_perspective(Perspective::IS_CLIENT); BlockOnNextWrite(); QuicStreamId stream_id = 2; connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN); EXPECT_EQ(1u, connection_.NumQueuedPackets()); writer_->SetWritable(); connection_.SendConnectivityProbingPacket(writer_.get(), connection_.peer_address()); EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0); connection_.OnCanWrite(); } TEST_P(QuicConnectionTest, DiscardQueuedPacketsAfterConnectionClose) { { InSequence seq; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(AtLeast(1)); EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(AtLeast(1)); } set_perspective(Perspective::IS_CLIENT); writer_->SimulateNextPacketTooLarge(); connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN); EXPECT_FALSE(connection_.connected()); EXPECT_EQ(0u, connection_.NumQueuedPackets()); EXPECT_EQ(0u, connection_.GetStats().packets_discarded); connection_.OnCanWrite(); EXPECT_EQ(0u, connection_.GetStats().packets_discarded); } class TestQuicPathValidationContext : public QuicPathValidationContext { public: TestQuicPathValidationContext(const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, QuicPacketWriter* writer) : QuicPathValidationContext(self_address, peer_address), writer_(writer) {} QuicPacketWriter* WriterToUse() override { return writer_; } private: QuicPacketWriter* writer_; }; class TestValidationResultDelegate : public QuicPathValidator::ResultDelegate { public: TestValidationResultDelegate(QuicConnection* connection, const QuicSocketAddress& expected_self_address, const QuicSocketAddress& expected_peer_address, bool* success) : QuicPathValidator::ResultDelegate(), connection_(connection), expected_self_address_(expected_self_address), expected_peer_address_(expected_peer_address), success_(success) {} void OnPathValidationSuccess( std::unique_ptr<QuicPathValidationContext> context, QuicTime ) override { EXPECT_EQ(expected_self_address_, context->self_address()); EXPECT_EQ(expected_peer_address_, context->peer_address()); *success_ = true; } void OnPathValidationFailure( std::unique_ptr<QuicPathValidationContext> context) override { EXPECT_EQ(expected_self_address_, context->self_address()); EXPECT_EQ(expected_peer_address_, context->peer_address()); if (connection_->perspective() == Perspective::IS_CLIENT) { connection_->OnPathValidationFailureAtClient(false, *context); } *success_ = false; } private: QuicConnection* connection_; QuicSocketAddress expected_self_address_; QuicSocketAddress expected_peer_address_; bool* success_; }; class ServerPreferredAddressTestResultDelegate : public QuicPathValidator::ResultDelegate { public: explicit ServerPreferredAddressTestResultDelegate(QuicConnection* connection) : connection_(connection) {} void OnPathValidationSuccess( std::unique_ptr<QuicPathValidationContext> context, QuicTime ) override { connection_->OnServerPreferredAddressValidated(*context, false); } void OnPathValidationFailure( std::unique_ptr<QuicPathValidationContext> context) override { connection_->OnPathValidationFailureAtClient(false, *context); } protected: QuicConnection* connection() { return connection_; } private: QuicConnection* connection_; }; TEST_P(QuicConnectionTest, ReceivePathProbingFromNewPeerAddressAtServer) { if (!version().HasIetfQuicFrames() && GetQuicReloadableFlag(quic_ignore_gquic_probing)) { return; } PathProbeTestInit(Perspective::IS_SERVER); EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0); QuicPathFrameBuffer payload; if (!GetParam().version.HasIetfQuicFrames()) { EXPECT_CALL(visitor_, OnPacketReceived(_, _, true)) .Times(1); } else { EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(AtLeast(1u)) .WillOnce(Invoke([&]() { EXPECT_EQ(1u, writer_->path_challenge_frames().size()); EXPECT_EQ(1u, writer_->path_response_frames().size()); payload = writer_->path_challenge_frames().front().data_buffer; })) .WillRepeatedly(DoDefault()); } const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(), 23456); std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket(); std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket( QuicEncryptedPacket(probing_packet->encrypted_buffer, probing_packet->encrypted_length), clock_.Now())); uint64_t num_probing_received = connection_.GetStats().num_connectivity_probing_received; ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received); EXPECT_EQ(num_probing_received + 1, connection_.GetStats().num_connectivity_probing_received); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); if (GetParam().version.HasIetfQuicFrames()) { QuicByteCount bytes_sent = QuicConnectionPeer::BytesSentOnAlternativePath(&connection_); EXPECT_LT(0u, bytes_sent); EXPECT_EQ(received->length(), QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_)); probing_packet = ConstructProbingPacket(); received.reset(ConstructReceivedPacket( QuicEncryptedPacket(probing_packet->encrypted_buffer, probing_packet->encrypted_length), clock_.Now())); ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received); EXPECT_EQ(num_probing_received + 2, connection_.GetStats().num_connectivity_probing_received); EXPECT_EQ(2 * bytes_sent, QuicConnectionPeer::BytesSentOnAlternativePath(&connection_)); EXPECT_EQ(2 * received->length(), QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_)); EXPECT_EQ(2 * bytes_sent, QuicConnectionPeer::BytesSentOnAlternativePath(&connection_)); QuicFrames frames; frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload))); ProcessFramesPacketWithAddresses(frames, connection_.self_address(), kNewPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_LT(2 * received->length(), QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_)); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_)); QuicSocketAddress kNewerPeerAddress(QuicIpAddress::Loopback4(), 34567); probing_packet = ConstructProbingPacket(); received.reset(ConstructReceivedPacket( QuicEncryptedPacket(probing_packet->encrypted_buffer, probing_packet->encrypted_length), clock_.Now())); ProcessReceivedPacket(kSelfAddress, kNewerPeerAddress, *received); EXPECT_FALSE(connection_.HasPendingPathValidation()); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_)); } EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0); ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress, ENCRYPTION_INITIAL); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); } TEST_P(QuicConnectionTest, ReceivePathProbingToPreferredAddressAtServer) { if (!GetParam().version.HasIetfQuicFrames()) { return; } ServerHandlePreferredAddressInit(); EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0); EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0); std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket(); std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket( QuicEncryptedPacket(probing_packet->encrypted_buffer, probing_packet->encrypted_length), clock_.Now())); uint64_t num_probing_received = connection_.GetStats().num_connectivity_probing_received; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(AtLeast(1u)) .WillOnce(Invoke([&]() { EXPECT_EQ(1u, writer_->path_response_frames().size()); EXPECT_EQ(kSelfAddress.host(), writer_->last_write_source_address()); EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address()); })); ProcessReceivedPacket(kServerPreferredAddress, kPeerAddress, *received); EXPECT_EQ(num_probing_received + 1, connection_.GetStats().num_connectivity_probing_received); EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath( &connection_, kServerPreferredAddress, kPeerAddress)); EXPECT_NE(kServerPreferredAddress, connection_.self_address()); const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(), 34567); probing_packet = ConstructProbingPacket(); received.reset(ConstructReceivedPacket( QuicEncryptedPacket(probing_packet->encrypted_buffer, probing_packet->encrypted_length), clock_.Now())); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(AtLeast(1u)) .WillOnce(Invoke([&]() { EXPECT_EQ(1u, writer_->path_response_frames().size()); EXPECT_EQ(1u, writer_->path_challenge_frames().size()); EXPECT_EQ(kServerPreferredAddress.host(), writer_->last_write_source_address()); EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address()); })); ProcessReceivedPacket(kServerPreferredAddress, kNewPeerAddress, *received); EXPECT_EQ(num_probing_received + 2, connection_.GetStats().num_connectivity_probing_received); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(&connection_, kSelfAddress, kNewPeerAddress)); EXPECT_LT(0u, QuicConnectionPeer::BytesSentOnAlternativePath(&connection_)); EXPECT_EQ(received->length(), QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_)); } TEST_P(QuicConnectionTest, ReceivePaddedPingWithPortChangeAtServer) { set_perspective(Perspective::IS_SERVER); QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false); EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective()); if (version().SupportsAntiAmplificationLimit()) { QuicConnectionPeer::SetAddressValidated(&connection_); } QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress()); QuicConnectionPeer::SetEffectivePeerAddress(&connection_, QuicSocketAddress()); EXPECT_FALSE(connection_.effective_peer_address().IsInitialized()); if (GetParam().version.UsesCryptoFrames()) { EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); } else { EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber()); } ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress, ENCRYPTION_INITIAL); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); if (GetParam().version.HasIetfQuicFrames() || GetQuicReloadableFlag(quic_ignore_gquic_probing)) { EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1); EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0); } else { EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0); EXPECT_CALL(visitor_, OnPacketReceived(_, _, true)) .Times(1); } const QuicSocketAddress kNewPeerAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), 23456); QuicFrames frames; QuicPingFrame ping_frame; frames.push_back(QuicFrame(ping_frame)); QuicPaddingFrame padding_frame; frames.push_back(QuicFrame(padding_frame)); uint64_t num_probing_received = connection_.GetStats().num_connectivity_probing_received; ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress, ENCRYPTION_INITIAL); if (GetParam().version.HasIetfQuicFrames() || GetQuicReloadableFlag(quic_ignore_gquic_probing)) { EXPECT_EQ(num_probing_received, connection_.GetStats().num_connectivity_probing_received); EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address()); } else { EXPECT_EQ(num_probing_received + 1, connection_.GetStats().num_connectivity_probing_received); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); } if (GetParam().version.HasIetfQuicFrames() || GetQuicReloadableFlag(quic_ignore_gquic_probing)) { EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1); } ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress, ENCRYPTION_INITIAL); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); } TEST_P(QuicConnectionTest, ReceiveReorderedPathProbingAtServer) { if (!GetParam().version.HasIetfQuicFrames() && GetQuicReloadableFlag(quic_ignore_gquic_probing)) { return; } PathProbeTestInit(Perspective::IS_SERVER); QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4); EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0); if (!GetParam().version.HasIetfQuicFrames()) { EXPECT_CALL(visitor_, OnPacketReceived(_, _, true)) .Times(1); } else { EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0); } const QuicSocketAddress kNewPeerAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), 23456); std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket(); std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket( QuicEncryptedPacket(probing_packet->encrypted_buffer, probing_packet->encrypted_length), clock_.Now())); uint64_t num_probing_received = connection_.GetStats().num_connectivity_probing_received; ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received); EXPECT_EQ(num_probing_received + (!version().HasIetfQuicFrames() && GetQuicReloadableFlag(quic_ignore_gquic_probing) ? 0u : 1u), connection_.GetStats().num_connectivity_probing_received); EXPECT_EQ((!version().HasIetfQuicFrames() && GetQuicReloadableFlag(quic_ignore_gquic_probing) ? kNewPeerAddress : kPeerAddress), connection_.peer_address()); EXPECT_EQ((!version().HasIetfQuicFrames() && GetQuicReloadableFlag(quic_ignore_gquic_probing) ? kNewPeerAddress : kPeerAddress), connection_.effective_peer_address()); } TEST_P(QuicConnectionTest, MigrateAfterProbingAtServer) { if (!GetParam().version.HasIetfQuicFrames() && GetQuicReloadableFlag(quic_ignore_gquic_probing)) { return; } PathProbeTestInit(Perspective::IS_SERVER); EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0); if (!GetParam().version.HasIetfQuicFrames()) { EXPECT_CALL(visitor_, OnPacketReceived(_, _, true)) .Times(1); } else { EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0); } const QuicSocketAddress kNewPeerAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), 23456); std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket(); std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket( QuicEncryptedPacket(probing_packet->encrypted_buffer, probing_packet->encrypted_length), clock_.Now())); ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1); ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kNewPeerAddress, ENCRYPTION_INITIAL); EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address()); } TEST_P(QuicConnectionTest, ReceiveConnectivityProbingPacketAtClient) { if (!version().HasIetfQuicFrames() && GetQuicReloadableFlag(quic_ignore_gquic_probing)) { return; } EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); PathProbeTestInit(Perspective::IS_CLIENT); EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0); std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket(); std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket( QuicEncryptedPacket(probing_packet->encrypted_buffer, probing_packet->encrypted_length), clock_.Now())); uint64_t num_probing_received = connection_.GetStats().num_connectivity_probing_received; ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received); EXPECT_EQ( num_probing_received + (GetParam().version.HasIetfQuicFrames() ? 1u : 0u), connection_.GetStats().num_connectivity_probing_received); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); } TEST_P(QuicConnectionTest, ReceiveConnectivityProbingResponseAtClient) { if (GetParam().version.HasIetfQuicFrames() || GetQuicReloadableFlag(quic_ignore_gquic_probing)) { return; } EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); PathProbeTestInit(Perspective::IS_CLIENT); EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0); if (!GetParam().version.HasIetfQuicFrames()) { EXPECT_CALL(visitor_, OnPacketReceived(_, _, true)) .Times(1); } else { EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0); } const QuicSocketAddress kNewSelfAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), 23456); std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket(); std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket( QuicEncryptedPacket(probing_packet->encrypted_buffer, probing_packet->encrypted_length), clock_.Now())); uint64_t num_probing_received = connection_.GetStats().num_connectivity_probing_received; ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received); EXPECT_EQ(num_probing_received + 1, connection_.GetStats().num_connectivity_probing_received); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); } TEST_P(QuicConnectionTest, PeerAddressChangeAtClient) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); set_perspective(Perspective::IS_CLIENT); EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective()); QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress()); QuicConnectionPeer::SetEffectivePeerAddress(&connection_, QuicSocketAddress()); EXPECT_FALSE(connection_.effective_peer_address().IsInitialized()); if (connection_.version().HasIetfQuicFrames()) { EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1); } else if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(2); } else { EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2); } ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress, ENCRYPTION_INITIAL); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); const QuicSocketAddress kNewPeerAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), 23456); EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0); ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kNewPeerAddress, ENCRYPTION_INITIAL); if (connection_.version().HasIetfQuicFrames()) { EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); } else { EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address()); } } TEST_P(QuicConnectionTest, NoNormalizedPeerAddressChangeAtClient) { if (!version().HasIetfQuicFrames()) { return; } QuicIpAddress peer_ip; peer_ip.FromString("1.1.1.1"); QuicSocketAddress peer_addr = QuicSocketAddress(peer_ip, 443); QuicSocketAddress dualstack_peer_addr = QuicSocketAddress(peer_addr.host().DualStacked(), peer_addr.port()); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber()); set_perspective(Perspective::IS_CLIENT); EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective()); QuicConnectionPeer::SetDirectPeerAddress(&connection_, dualstack_peer_addr); EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber()); ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, peer_addr, ENCRYPTION_INITIAL); EXPECT_TRUE(connection_.connected()); if (GetQuicReloadableFlag(quic_test_peer_addr_change_after_normalize)) { EXPECT_EQ(0u, connection_.GetStats().packets_dropped); } else { EXPECT_EQ(1u, connection_.GetStats().packets_dropped); } } TEST_P(QuicConnectionTest, ServerAddressChangesToKnownAddress) { if (!connection_.version().HasIetfQuicFrames()) { return; } EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); set_perspective(Perspective::IS_CLIENT); EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective()); QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress()); QuicConnectionPeer::SetEffectivePeerAddress(&connection_, QuicSocketAddress()); EXPECT_FALSE(connection_.effective_peer_address().IsInitialized()); EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3); ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress, ENCRYPTION_INITIAL); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); const QuicSocketAddress kNewPeerAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), 23456); connection_.AddKnownServerAddress(kNewPeerAddress); EXPECT_CALL(visitor_, OnConnectionMigration(_)).Times(0); ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kNewPeerAddress, ENCRYPTION_INITIAL); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress, ENCRYPTION_INITIAL); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); } TEST_P(QuicConnectionTest, PeerAddressChangesToPreferredAddressBeforeClientInitiates) { if (!version().HasIetfQuicFrames()) { return; } ASSERT_EQ(Perspective::IS_CLIENT, connection_.perspective()); ASSERT_TRUE(connection_.self_address().host().IsIPv6()); const QuicConnectionId connection_id = TestConnectionId(17); const StatelessResetToken reset_token = QuicUtils::GenerateStatelessResetToken(connection_id); connection_.CreateConnectionIdManager(); connection_.SendCryptoStreamData(); EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); QuicAckFrame frame = InitAckFrame(1); ProcessFramePacketAtLevel(1, QuicFrame(&frame), ENCRYPTION_INITIAL); connection_.RemoveEncrypter(ENCRYPTION_INITIAL); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); QuicConfig config; config.SetConnectionOptionsToSend(QuicTagVector{kSPAD}); QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestStatelessResetToken); QuicConfigPeer::SetReceivedAlternateServerAddress(&config, kServerPreferredAddress); QuicConfigPeer::SetPreferredAddressConnectionIdAndToken( &config, connection_id, reset_token); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); ASSERT_TRUE( QuicConnectionPeer::GetReceivedServerPreferredAddress(&connection_) .IsInitialized()); EXPECT_EQ( kServerPreferredAddress, QuicConnectionPeer::GetReceivedServerPreferredAddress(&connection_)); EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(0); ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kServerPreferredAddress, ENCRYPTION_INITIAL); } TEST_P(QuicConnectionTest, MaxPacketSize) { EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective()); EXPECT_EQ(1250u, connection_.max_packet_length()); } TEST_P(QuicConnectionTest, PeerLowersMaxPacketSize) { EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective()); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); constexpr uint32_t kTestMaxPacketSize = 1233u; QuicConfig config; QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize); connection_.SetFromConfig(config); EXPECT_EQ(kTestMaxPacketSize, connection_.max_packet_length()); } TEST_P(QuicConnectionTest, PeerCannotRaiseMaxPacketSize) { EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective()); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); constexpr uint32_t kTestMaxPacketSize = 1450u; QuicConfig config; QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize); connection_.SetFromConfig(config); EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length()); } TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) { TestConnection connection(TestConnectionId(), kSelfAddress, kPeerAddress, helper_.get(), alarm_factory_.get(), writer_.get(), Perspective::IS_SERVER, version(), connection_id_generator_); EXPECT_EQ(Perspective::IS_SERVER, connection.perspective()); EXPECT_EQ(1000u, connection.max_packet_length()); } TEST_P(QuicConnectionTest, LowerServerResponseMtuTest) { set_perspective(Perspective::IS_SERVER); connection_.SetMaxPacketLength(1000); EXPECT_EQ(1000u, connection_.max_packet_length()); SetQuicFlag(quic_use_lower_server_response_mtu_for_test, true); EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(::testing::AtMost(1)); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(::testing::AtMost(1)); ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL); EXPECT_EQ(1250u, connection_.max_packet_length()); } TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) { set_perspective(Perspective::IS_SERVER); connection_.SetMaxPacketLength(1000); QuicPacketHeader header; header.destination_connection_id = connection_id_; header.version_flag = true; header.packet_number = QuicPacketNumber(12); if (QuicVersionHasLongHeaderLengths( peer_framer_.version().transport_version)) { header.long_packet_type = INITIAL; header.retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1; header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2; } QuicFrames frames; QuicPaddingFrame padding; if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { frames.push_back(QuicFrame(&crypto_frame_)); } else { frames.push_back(QuicFrame(frame1_)); } frames.push_back(QuicFrame(padding)); std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames)); char buffer[kMaxOutgoingPacketSize]; size_t encrypted_length = peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12), *packet, buffer, kMaxOutgoingPacketSize); EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length + (connection_.version().KnowsWhichDecrypterToUse() ? 0 : 4)); framer_.set_version(version()); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1); } else { EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); } connection_.ProcessUdpPacket( kSelfAddress, kPeerAddress, QuicReceivedPacket(buffer, encrypted_length, clock_.ApproximateNow(), false)); EXPECT_EQ(kMaxOutgoingPacketSize, connection_.max_packet_length() + (connection_.version().KnowsWhichDecrypterToUse() ? 0 : 4)); } TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSizeWhileWriterLimited) { const QuicByteCount lower_max_packet_size = 1240; writer_->set_max_packet_size(lower_max_packet_size); set_perspective(Perspective::IS_SERVER); connection_.SetMaxPacketLength(1000); EXPECT_EQ(1000u, connection_.max_packet_length()); QuicPacketHeader header; header.destination_connection_id = connection_id_; header.version_flag = true; header.packet_number = QuicPacketNumber(12); if (QuicVersionHasLongHeaderLengths( peer_framer_.version().transport_version)) { header.long_packet_type = INITIAL; header.retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1; header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2; } QuicFrames frames; QuicPaddingFrame padding; if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { frames.push_back(QuicFrame(&crypto_frame_)); } else { frames.push_back(QuicFrame(frame1_)); } frames.push_back(QuicFrame(padding)); std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames)); char buffer[kMaxOutgoingPacketSize]; size_t encrypted_length = peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12), *packet, buffer, kMaxOutgoingPacketSize); EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length + (connection_.version().KnowsWhichDecrypterToUse() ? 0 : 4)); framer_.set_version(version()); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1); } else { EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); } connection_.ProcessUdpPacket( kSelfAddress, kPeerAddress, QuicReceivedPacket(buffer, encrypted_length, clock_.ApproximateNow(), false)); EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length()); } TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriter) { const QuicByteCount lower_max_packet_size = 1240; writer_->set_max_packet_size(lower_max_packet_size); static_assert(lower_max_packet_size < kDefaultMaxPacketSize, "Default maximum packet size is too low"); connection_.SetMaxPacketLength(kDefaultMaxPacketSize); EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length()); } TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriterForNewConnection) { const QuicConnectionId connection_id = TestConnectionId(17); const QuicByteCount lower_max_packet_size = 1240; writer_->set_max_packet_size(lower_max_packet_size); TestConnection connection(connection_id, kSelfAddress, kPeerAddress, helper_.get(), alarm_factory_.get(), writer_.get(), Perspective::IS_CLIENT, version(), connection_id_generator_); EXPECT_EQ(Perspective::IS_CLIENT, connection.perspective()); EXPECT_EQ(lower_max_packet_size, connection.max_packet_length()); } TEST_P(QuicConnectionTest, PacketsInOrder) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); ProcessPacket(1); EXPECT_EQ(QuicPacketNumber(1u), LargestAcked(connection_.ack_frame())); EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals()); ProcessPacket(2); EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(connection_.ack_frame())); EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals()); ProcessPacket(3); EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame())); EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals()); } TEST_P(QuicConnectionTest, PacketsOutOfOrder) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); ProcessPacket(3); EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame())); EXPECT_TRUE(IsMissing(2)); EXPECT_TRUE(IsMissing(1)); ProcessPacket(2); EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame())); EXPECT_FALSE(IsMissing(2)); EXPECT_TRUE(IsMissing(1)); ProcessPacket(1); EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame())); EXPECT_FALSE(IsMissing(2)); EXPECT_FALSE(IsMissing(1)); } TEST_P(QuicConnectionTest, DuplicatePacket) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); ProcessPacket(3); EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame())); EXPECT_TRUE(IsMissing(2)); EXPECT_TRUE(IsMissing(1)); ProcessDataPacket(3); EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame())); EXPECT_TRUE(IsMissing(2)); EXPECT_TRUE(IsMissing(1)); } TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) { if (connection_.SupportsMultiplePacketNumberSpaces()) { return; } EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); ProcessPacket(3); EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame())); EXPECT_TRUE(IsMissing(2)); EXPECT_TRUE(IsMissing(1)); ProcessPacket(2); EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame())); EXPECT_TRUE(IsMissing(1)); ProcessPacket(5); EXPECT_EQ(QuicPacketNumber(5u), LargestAcked(connection_.ack_frame())); EXPECT_TRUE(IsMissing(1)); EXPECT_TRUE(IsMissing(4)); QuicAckFrame frame = InitAckFrame(1); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _)); ProcessAckPacket(6, &frame); SendAckPacketToPeer(); EXPECT_TRUE(IsMissing(4)); } TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) { if (!IsDefaultTestConfiguration() || VersionHasIetfQuicFrames(version().transport_version)) { return; } frame1_.stream_id = 3; EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)); EXPECT_QUIC_PEER_BUG(ProcessDataPacketAtLevel(1, false, ENCRYPTION_INITIAL), ""); TestConnectionCloseQuicErrorCode(QUIC_UNENCRYPTED_STREAM_DATA); } TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); ProcessPacket(3); EXPECT_EQ(0u, writer_->packets_write_attempts()); ProcessPacket(2); EXPECT_EQ(1u, writer_->packets_write_attempts()); ProcessPacket(1); EXPECT_EQ(2u, writer_->packets_write_attempts()); ProcessPacket(4); EXPECT_EQ(2u, writer_->packets_write_attempts()); } TEST_P(QuicConnectionTest, OutOfOrderAckReceiptCausesNoAck) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr); SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr); EXPECT_EQ(2u, writer_->packets_write_attempts()); QuicAckFrame ack1 = InitAckFrame(1); QuicAckFrame ack2 = InitAckFrame(2); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); if (connection_.SupportsMultiplePacketNumberSpaces()) { EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(1); } ProcessAckPacket(2, &ack2); EXPECT_EQ(2u, writer_->packets_write_attempts()); if (connection_.SupportsMultiplePacketNumberSpaces()) { EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(0); } ProcessAckPacket(1, &ack1); EXPECT_EQ(2u, writer_->packets_write_attempts()); } TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); QuicPacketNumber original, second; QuicByteCount packet_size = SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); QuicAckFrame frame = InitAckFrame({{second, second + 1}}); LostPacketVector lost_packets; lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize)); EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _)) .WillOnce(DoAll(SetArgPointee<5>(lost_packets), Return(LossDetectionInterface::DetectionStats()))); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); QuicPacketNumber retransmission; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, packet_size, _)) .WillOnce(SaveArg<2>(&retransmission)); ProcessAckPacket(&frame); QuicAckFrame frame2 = ConstructAckFrame(retransmission, original); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _)); ProcessAckPacket(&frame2); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)); connection_.SendStreamDataWithString(3, "foo", 6, NO_FIN); size_t padding_frame_count = writer_->padding_frames().size(); EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count()); EXPECT_EQ(1u, writer_->stream_frames().size()); EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _)) .Times(AnyNumber()); ProcessAckPacket(&frame2); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA)); connection_.SendStreamDataWithString(3, "foofoofoo", 9, NO_FIN); EXPECT_EQ(1u, writer_->frame_count()); EXPECT_EQ(1u, writer_->stream_frames().size()); EXPECT_TRUE(writer_->ack_frames().empty()); AckPacket(original, &frame2); ProcessAckPacket(&frame2); ProcessAckPacket(&frame2); } TEST_P(QuicConnectionTest, AckFrequencyUpdatedFromAckFrequencyFrame) { if (!GetParam().version.HasIetfQuicFrames()) { return; } connection_.set_can_receive_ack_frequency_frame(); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(13); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); QuicAckFrequencyFrame ack_frequency_frame; ack_frequency_frame.packet_tolerance = 3; ProcessFramePacketAtLevel(1, QuicFrame(&ack_frequency_frame), ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(38); for (size_t i = 2; i <= 39; ++i) { ProcessDataPacket(i); } } TEST_P(QuicConnectionTest, AckDecimationReducesAcks) { const size_t kMinRttMs = 40; RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats()); rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber()); connection_.set_min_received_before_ack_decimation(10); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(30); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6); for (size_t i = 1; i <= 29; ++i) { ProcessDataPacket(i); } EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); ProcessDataPacket(30); } TEST_P(QuicConnectionTest, AckNeedsRetransmittableFrames) { connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(99); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19); for (size_t i = 1; i <= 39; ++i) { ProcessDataPacket(i); } EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()) .WillOnce(Invoke([this]() { connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0))); })); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); EXPECT_EQ(0u, writer_->window_update_frames().size()); ProcessDataPacket(40); EXPECT_EQ(1u, writer_->window_update_frames().size()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9); for (size_t i = 41; i <= 59; ++i) { ProcessDataPacket(i); } SendStreamDataToPeer( QuicUtils::GetFirstBidirectionalStreamId( connection_.version().transport_version, Perspective::IS_CLIENT), "bar", 0, NO_FIN, nullptr); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19); for (size_t i = 60; i <= 98; ++i) { ProcessDataPacket(i); EXPECT_EQ(0u, writer_->window_update_frames().size()); } EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()) .WillOnce(Invoke([this]() { connection_.SendControlFrame(QuicFrame(QuicPingFrame(1))); })); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); EXPECT_EQ(0u, writer_->ping_frames().size()); ProcessDataPacket(99); EXPECT_EQ(0u, writer_->window_update_frames().size()); EXPECT_EQ(1u, writer_->ping_frames().size()); } TEST_P(QuicConnectionTest, AckNeedsRetransmittableFramesAfterPto) { EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; QuicTagVector connection_options; connection_options.push_back(kEACK); config.SetConnectionOptionsToSend(connection_options); connection_.SetFromConfig(config); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.OnHandshakeComplete(); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(10); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4); for (size_t i = 1; i <= 9; ++i) { ProcessDataPacket(i); } EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2); SendPing(); QuicTime retransmission_time = connection_.GetRetransmissionAlarm()->deadline(); clock_.AdvanceTime(retransmission_time - clock_.Now()); connection_.GetRetransmissionAlarm()->Fire(); ASSERT_LT(0u, manager_->GetConsecutivePtoCount()); EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()) .WillOnce(Invoke([this]() { connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0))); })); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); ProcessDataPacket(11); EXPECT_EQ(1u, writer_->window_update_frames().size()); } TEST_P(QuicConnectionTest, TooManySentPackets) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); QuicPacketCount max_tracked_packets = 50; QuicConnectionPeer::SetMaxTrackedPackets(&connection_, max_tracked_packets); const int num_packets = max_tracked_packets + 5; for (int i = 0; i < num_packets; ++i) { SendStreamDataToPeer(1, "foo", 3 * i, NO_FIN, nullptr); } EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)); ProcessFramePacket(QuicFrame(QuicPingFrame())); TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS); } TEST_P(QuicConnectionTest, LargestObservedLower) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr); SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr); SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); QuicAckFrame frame1 = InitAckFrame(1); QuicAckFrame frame2 = InitAckFrame(2); ProcessAckPacket(&frame2); EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber()); ProcessAckPacket(&frame1); } TEST_P(QuicConnectionTest, AckUnsentData) { EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1)); QuicAckFrame frame = InitAckFrame(1); EXPECT_CALL(visitor_, OnCanWrite()).Times(0); ProcessAckPacket(&frame); TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA); } TEST_P(QuicConnectionTest, BasicSending) { if (connection_.SupportsMultiplePacketNumberSpaces()) { return; } const QuicConnectionStats& stats = connection_.GetStats(); EXPECT_FALSE(stats.first_decrypted_packet.IsInitialized()); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacket(1); EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet); QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2); QuicPacketNumber last_packet; SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); EXPECT_EQ(QuicPacketNumber(1u), last_packet); SendAckPacketToPeer(); SendAckPacketToPeer(); SendStreamDataToPeer(1, "bar", 3, NO_FIN, &last_packet); EXPECT_EQ(QuicPacketNumber(4u), last_packet); SendAckPacketToPeer(); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); QuicAckFrame frame = InitAckFrame(3); ProcessAckPacket(&frame); SendAckPacketToPeer(); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); QuicAckFrame frame2 = InitAckFrame(6); ProcessAckPacket(&frame2); EXPECT_EQ(QuicPacketNumber(6u), writer_->header().packet_number); SendAckPacketToPeer(); SendStreamDataToPeer(1, "eep", 6, NO_FIN, &last_packet); EXPECT_EQ(QuicPacketNumber(8u), last_packet); SendAckPacketToPeer(); EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet); } TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) { QuicTime actual_recorded_send_time = QuicTime::Zero(); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .WillOnce(SaveArg<0>(&actual_recorded_send_time)); QuicTime expected_recorded_send_time = clock_.Now(); connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN); EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time) << "Expected time = " << expected_recorded_send_time.ToDebuggingValue() << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue(); actual_recorded_send_time = QuicTime::Zero(); const QuicTime::Delta write_pause_time_delta = QuicTime::Delta::FromMilliseconds(5000); SetWritePauseTimeDelta(write_pause_time_delta); expected_recorded_send_time = clock_.Now(); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .WillOnce(SaveArg<0>(&actual_recorded_send_time)); connection_.SendStreamDataWithString(2, "baz", 0, NO_FIN); EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time) << "Expected time = " << expected_recorded_send_time.ToDebuggingValue() << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue(); } TEST_P(QuicConnectionTest, ConnectionStatsRetransmission_WithRetransmissions) { connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); { QuicConnection::ScopedPacketFlusher flusher(&connection_); connection_.SaveAndSendStreamData( GetNthClientInitiatedStreamId(1, connection_.transport_version()), "helloworld", 0, NO_FIN, PTO_RETRANSMISSION); connection_.SaveAndSendStreamData( GetNthClientInitiatedStreamId(2, connection_.transport_version()), "helloworld", 0, NO_FIN, LOSS_RETRANSMISSION); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); } EXPECT_EQ(0u, connection_.NumQueuedPackets()); EXPECT_FALSE(connection_.HasQueuedData()); EXPECT_EQ(2u, writer_->frame_count()); for (auto& frame : writer_->stream_frames()) { EXPECT_EQ(frame->data_length, 10u); } ASSERT_EQ(connection_.GetStats().packets_retransmitted, 1u); ASSERT_GE(connection_.GetStats().bytes_retransmitted, 20u); } TEST_P(QuicConnectionTest, ConnectionStatsRetransmission_WithMixedFrames) { connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); { QuicConnection::ScopedPacketFlusher flusher(&connection_); connection_.SaveAndSendStreamData( GetNthClientInitiatedStreamId(1, connection_.transport_version()), "helloworld", 0, NO_FIN, PTO_RETRANSMISSION); connection_.SaveAndSendStreamData( GetNthClientInitiatedStreamId(2, connection_.transport_version()), "helloworld", 0, NO_FIN, NOT_RETRANSMISSION); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); } EXPECT_EQ(0u, connection_.NumQueuedPackets()); EXPECT_FALSE(connection_.HasQueuedData()); EXPECT_EQ(2u, writer_->frame_count()); for (auto& frame : writer_->stream_frames()) { EXPECT_EQ(frame->data_length, 10u); } ASSERT_EQ(connection_.GetStats().packets_retransmitted, 1u); ASSERT_GE(connection_.GetStats().bytes_retransmitted, 10u); } TEST_P(QuicConnectionTest, ConnectionStatsRetransmission_NoRetransmission) { connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); { QuicConnection::ScopedPacketFlusher flusher(&connection_); connection_.SaveAndSendStreamData( GetNthClientInitiatedStreamId(1, connection_.transport_version()), "helloworld", 0, NO_FIN, NOT_RETRANSMISSION); connection_.SaveAndSendStreamData( GetNthClientInitiatedStreamId(2, connection_.transport_version()), "helloworld", 0, NO_FIN, NOT_RETRANSMISSION); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); } EXPECT_EQ(0u, connection_.NumQueuedPackets()); EXPECT_FALSE(connection_.HasQueuedData()); EXPECT_EQ(2u, writer_->frame_count()); ASSERT_EQ(connection_.GetStats().packets_retransmitted, 0u); ASSERT_EQ(connection_.GetStats().bytes_retransmitted, 0u); } TEST_P(QuicConnectionTest, FramePacking) { connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); { QuicConnection::ScopedPacketFlusher flusher(&connection_); connection_.SendStreamData3(); connection_.SendStreamData5(); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); } EXPECT_EQ(0u, connection_.NumQueuedPackets()); EXPECT_FALSE(connection_.HasQueuedData()); EXPECT_EQ(2u, writer_->frame_count()); EXPECT_TRUE(writer_->stop_waiting_frames().empty()); EXPECT_TRUE(writer_->ack_frames().empty()); ASSERT_EQ(2u, writer_->stream_frames().size()); EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()), writer_->stream_frames()[0]->stream_id); EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()), writer_->stream_frames()[1]->stream_id); } TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) { connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); { EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2); QuicConnection::ScopedPacketFlusher flusher(&connection_); connection_.SendStreamData3(); connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); if (!connection_.version().KnowsWhichDecrypterToUse()) { writer_->framer()->framer()->SetAlternativeDecrypter( ENCRYPTION_INITIAL, std::make_unique<NullDecrypter>(Perspective::IS_SERVER), false); } connection_.SendCryptoStreamData(); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); } EXPECT_EQ(0u, connection_.NumQueuedPackets()); EXPECT_FALSE(connection_.HasQueuedData()); EXPECT_LE(2u, writer_->frame_count()); ASSERT_LE(1u, writer_->padding_frames().size()); if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) { ASSERT_EQ(1u, writer_->stream_frames().size()); EXPECT_EQ(QuicUtils::GetCryptoStreamId(connection_.transport_version()), writer_->stream_frames()[0]->stream_id); } else { EXPECT_LE(1u, writer_->crypto_frames().size()); } } TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) { { connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2); QuicConnection::ScopedPacketFlusher flusher(&connection_); connection_.SendCryptoStreamData(); connection_.SendStreamData3(); } EXPECT_EQ(0u, connection_.NumQueuedPackets()); EXPECT_FALSE(connection_.HasQueuedData()); size_t padding_frame_count = writer_->padding_frames().size(); EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count()); ASSERT_EQ(1u, writer_->stream_frames().size()); EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()), writer_->stream_frames()[0]->stream_id); } TEST_P(QuicConnectionTest, FramePackingAckResponse) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1); } else { EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); } ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL); QuicPacketNumber last_packet; if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { connection_.SendCryptoDataWithString("foo", 0); } else { SendStreamDataToPeer( QuicUtils::GetCryptoStreamId(connection_.transport_version()), "foo", 0, NO_FIN, &last_packet); } EXPECT_FALSE(writer_->ack_frames().empty()); EXPECT_CALL(visitor_, OnCanWrite()) .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs( &connection_, &TestConnection::SendStreamData3)), IgnoreResult(InvokeWithoutArgs( &connection_, &TestConnection::SendStreamData5)))); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); peer_framer_.SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE)); SetDecrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE)); ForceWillingAndAbleToWriteOnceForDeferSending(); ProcessDataPacket(2); EXPECT_EQ(0u, connection_.NumQueuedPackets()); EXPECT_FALSE(connection_.HasQueuedData()); EXPECT_EQ(3u, writer_->frame_count()); EXPECT_TRUE(writer_->stop_waiting_frames().empty()); EXPECT_FALSE(writer_->ack_frames().empty()); ASSERT_EQ(2u, writer_->stream_frames().size()); EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()), writer_->stream_frames()[0]->stream_id); EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()), writer_->stream_frames()[1]->stream_id); } TEST_P(QuicConnectionTest, FramePackingSendv) { connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)); QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId( connection_.transport_version(), Perspective::IS_CLIENT); connection_.SaveAndSendStreamData(stream_id, "ABCDEF", 0, NO_FIN); EXPECT_EQ(0u, connection_.NumQueuedPackets()); EXPECT_FALSE(connection_.HasQueuedData()); EXPECT_EQ(1u, writer_->frame_count()); EXPECT_EQ(1u, writer_->stream_frames().size()); EXPECT_EQ(0u, writer_->padding_frames().size()); QuicStreamFrame* frame = writer_->stream_frames()[0].get(); EXPECT_EQ(stream_id, frame->stream_id); EXPECT_EQ("ABCDEF", absl::string_view(frame->data_buffer, frame->data_length)); } TEST_P(QuicConnectionTest, FramePackingSendvQueued) { connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)); BlockOnNextWrite(); QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId( connection_.transport_version(), Perspective::IS_CLIENT); connection_.SaveAndSendStreamData(stream_id, "ABCDEF", 0, NO_FIN); EXPECT_EQ(1u, connection_.NumQueuedPackets()); EXPECT_TRUE(connection_.HasQueuedData()); writer_->SetWritable(); connection_.OnCanWrite(); EXPECT_EQ(0u, connection_.NumQueuedPackets()); EXPECT_EQ(1u, writer_->frame_count()); EXPECT_EQ(1u, writer_->stream_frames().size()); EXPECT_EQ(0u, writer_->padding_frames().size()); QuicStreamFrame* frame = writer_->stream_frames()[0].get(); EXPECT_EQ(stream_id, frame->stream_id); EXPECT_EQ("ABCDEF", absl::string_view(frame->data_buffer, frame->data_length)); } TEST_P(QuicConnectionTest, SendingZeroBytes) { connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)); QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId( connection_.transport_version(), Perspective::IS_CLIENT); connection_.SaveAndSendStreamData(stream_id, {}, 0, FIN); EXPECT_EQ(0u, connection_.NumQueuedPackets()); EXPECT_FALSE(connection_.HasQueuedData()); size_t extra_padding_frames = 0; if (GetParam().version.HasHeaderProtection()) { extra_padding_frames = 1; } EXPECT_EQ(1u + extra_padding_frames, writer_->frame_count()); EXPECT_EQ(extra_padding_frames, writer_->padding_frames().size()); ASSERT_EQ(1u, writer_->stream_frames().size()); EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id); EXPECT_TRUE(writer_->stream_frames()[0]->fin); } TEST_P(QuicConnectionTest, LargeSendWithPendingAck) { connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); ProcessFramePacket(QuicFrame(QuicPingFrame())); EXPECT_TRUE(connection_.HasPendingAcks()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9); const std::string data(10000, '?'); QuicConsumedData consumed = connection_.SaveAndSendStreamData( GetNthClientInitiatedStreamId(0, connection_.transport_version()), data, 0, FIN); EXPECT_EQ(data.length(), consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_EQ(0u, connection_.NumQueuedPackets()); EXPECT_FALSE(connection_.HasQueuedData()); EXPECT_EQ(1u, writer_->frame_count()); ASSERT_EQ(1u, writer_->stream_frames().size()); EXPECT_EQ(GetNthClientInitiatedStreamId(0, connection_.transport_version()), writer_->stream_frames()[0]->stream_id); EXPECT_TRUE(writer_->stream_frames()[0]->fin); EXPECT_FALSE(connection_.HasPendingAcks()); } TEST_P(QuicConnectionTest, OnCanWrite) { EXPECT_CALL(visitor_, OnCanWrite()) .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs( &connection_, &TestConnection::SendStreamData3)), IgnoreResult(InvokeWithoutArgs( &connection_, &TestConnection::SendStreamData5)))); { InSequence seq; EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true)); EXPECT_CALL(visitor_, WillingAndAbleToWrite()) .WillRepeatedly(Return(false)); } EXPECT_CALL(*send_algorithm_, CanSend(_)) .WillRepeatedly(testing::Return(true)); connection_.OnCanWrite(); EXPECT_EQ(2u, writer_->frame_count()); EXPECT_EQ(2u, writer_->stream_frames().size()); EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()), writer_->stream_frames()[0]->stream_id); EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()), writer_->stream_frames()[1]->stream_id); } TEST_P(QuicConnectionTest, RetransmitOnNack) { QuicPacketNumber last_packet; SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); SendStreamDataToPeer(3, "foos", 3, NO_FIN, &last_packet); SendStreamDataToPeer(3, "fooos", 7, NO_FIN, &last_packet); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); QuicAckFrame ack_one = InitAckFrame(1); ProcessAckPacket(&ack_one); QuicAckFrame nack_two = ConstructAckFrame(3, 2); LostPacketVector lost_packets; lost_packets.push_back( LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize)); EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _)) .WillOnce(DoAll(SetArgPointee<5>(lost_packets), Return(LossDetectionInterface::DetectionStats()))); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); EXPECT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_)); ProcessAckPacket(&nack_two); } TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) { BlockOnNextWrite(); QuicStreamId stream_id = 2; connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN); SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); writer_->SetWritable(); connection_.OnCanWrite(); size_t padding_frame_count = writer_->padding_frames().size(); EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count()); EXPECT_EQ(1u, writer_->rst_stream_frames().size()); } TEST_P(QuicConnectionTest, SendQueuedPacketForQuicRstStreamNoError) { BlockOnNextWrite(); QuicStreamId stream_id = 2; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN); SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1)); writer_->SetWritable(); connection_.OnCanWrite(); size_t padding_frame_count = writer_->padding_frames().size(); EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count()); EXPECT_EQ(1u, writer_->rst_stream_frames().size()); } TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) { QuicStreamId stream_id = 2; QuicPacketNumber last_packet; SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet); SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet); SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12); QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); ProcessAckPacket(&nack_two); } TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnNack) { QuicStreamId stream_id = 2; QuicPacketNumber last_packet; SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet); SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet); SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12); QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); LostPacketVector lost_packets; lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize)); EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _)) .WillOnce(DoAll(SetArgPointee<5>(lost_packets), Return(LossDetectionInterface::DetectionStats()))); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1)); ProcessAckPacket(&nack_two); } TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) { QuicStreamId stream_id = 2; QuicPacketNumber last_packet; SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); clock_.AdvanceTime(DefaultRetransmissionTime()); connection_.GetRetransmissionAlarm()->Fire(); size_t padding_frame_count = writer_->padding_frames().size(); EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count()); EXPECT_EQ(1u, writer_->rst_stream_frames().size()); EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id); } TEST_P(QuicConnectionTest, CancelRetransmissionAlarmAfterResetStream) { QuicStreamId stream_id = 2; QuicPacketNumber last_data_packet; SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet); const QuicPacketNumber rst_packet = last_data_packet + 1; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, rst_packet, _, _)).Times(1); SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3); QuicAckFrame nack_stream_data = ConstructAckFrame(rst_packet, last_data_packet); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); ProcessAckPacket(&nack_stream_data); EXPECT_GT(manager_->GetBytesInFlight(), 0u); EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); } TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnPTO) { QuicStreamId stream_id = 2; QuicPacketNumber last_packet; SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1)); clock_.AdvanceTime(DefaultRetransmissionTime()); connection_.GetRetransmissionAlarm()->Fire(); size_t padding_frame_count = writer_->padding_frames().size(); EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count()); } TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) { QuicStreamId stream_id = 2; QuicPacketNumber last_packet; SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet); SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet); BlockOnNextWrite(); connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN); QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); ProcessAckPacket(&ack); SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); writer_->SetWritable(); connection_.OnCanWrite(); size_t padding_frame_count = writer_->padding_frames().size(); EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count()); ASSERT_EQ(1u, writer_->rst_stream_frames().size()); EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id); } TEST_P(QuicConnectionTest, SendPendingRetransmissionForQuicRstStreamNoError) { QuicStreamId stream_id = 2; QuicPacketNumber last_packet; SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet); SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet); BlockOnNextWrite(); connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN); QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); LostPacketVector lost_packets; lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize)); EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _)) .WillOnce(DoAll(SetArgPointee<5>(lost_packets), Return(LossDetectionInterface::DetectionStats()))); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); ProcessAckPacket(&ack); SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2)); writer_->SetWritable(); connection_.OnCanWrite(); connection_.SendControlFrame(QuicFrame( new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14))); size_t padding_frame_count = writer_->padding_frames().size(); EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count()); EXPECT_EQ(1u, writer_->rst_stream_frames().size()); } TEST_P(QuicConnectionTest, RetransmitAckedPacket) { QuicPacketNumber last_packet; SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); SendStreamDataToPeer(1, "foos", 3, NO_FIN, &last_packet); SendStreamDataToPeer(1, "fooos", 7, NO_FIN, &last_packet); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); QuicAckFrame nack_two = ConstructAckFrame(3, 2); BlockOnNextWrite(); LostPacketVector lost_packets; lost_packets.push_back( LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize)); EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _)) .WillOnce(DoAll(SetArgPointee<5>(lost_packets), Return(LossDetectionInterface::DetectionStats()))); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _)) .Times(1); ProcessAckPacket(&nack_two); EXPECT_EQ(1u, connection_.NumQueuedPackets()); EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(false, _, _, _, _, _, _)); QuicAckFrame ack_all = InitAckFrame(3); ProcessAckPacket(&ack_all); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _)) .Times(0); writer_->SetWritable(); connection_.OnCanWrite(); EXPECT_EQ(0u, connection_.NumQueuedPackets()); EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 4)); } TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); QuicPacketNumber original, second; QuicByteCount packet_size = SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); QuicAckFrame frame = InitAckFrame({{second, second + 1}}); LostPacketVector lost_packets; lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize)); EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _)) .WillOnce(DoAll(SetArgPointee<5>(lost_packets), Return(LossDetectionInterface::DetectionStats()))); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, packet_size, _)); ProcessAckPacket(&frame); } TEST_P(QuicConnectionTest, WriteBlockedBufferedThenSent) { BlockOnNextWrite(); writer_->set_is_write_blocked_data_buffered(true); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN); EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); writer_->SetWritable(); connection_.OnCanWrite(); EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); } TEST_P(QuicConnectionTest, WriteBlockedThenSent) { EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); BlockOnNextWrite(); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN); EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); EXPECT_EQ(1u, connection_.NumQueuedPackets()); writer_->SetWritable(); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN); EXPECT_EQ(2u, connection_.NumQueuedPackets()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); connection_.OnCanWrite(); EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); EXPECT_EQ(0u, connection_.NumQueuedPackets()); } TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN); EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); BlockOnNextWrite(); writer_->set_is_write_blocked_data_buffered(true); clock_.AdvanceTime(DefaultRetransmissionTime()); connection_.GetRetransmissionAlarm()->Fire(); QuicAckFrame ack = InitAckFrame(1); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); ProcessAckPacket(&ack); writer_->SetWritable(); connection_.OnCanWrite(); EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 3)); } TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) { BlockOnNextWrite(); connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN); EXPECT_EQ(1u, writer_->packets_write_attempts()); EXPECT_TRUE(writer_->IsWriteBlocked()); connection_.GetSendAlarm()->Set(clock_.ApproximateNow()); connection_.GetSendAlarm()->Fire(); EXPECT_TRUE(writer_->IsWriteBlocked()); EXPECT_EQ(1u, writer_->packets_write_attempts()); } TEST_P(QuicConnectionTest, NoSendAlarmAfterProcessPacketWhenWriteBlocked) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); BlockOnNextWrite(); connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN); EXPECT_TRUE(writer_->IsWriteBlocked()); EXPECT_EQ(1u, connection_.NumQueuedPackets()); EXPECT_FALSE(connection_.GetSendAlarm()->IsSet()); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); const uint64_t received_packet_num = 1; const bool has_stop_waiting = false; const EncryptionLevel level = ENCRYPTION_FORWARD_SECURE; std::unique_ptr<QuicPacket> packet( ConstructDataPacket(received_packet_num, has_stop_waiting, level)); char buffer[kMaxOutgoingPacketSize]; size_t encrypted_length = peer_framer_.EncryptPayload(level, QuicPacketNumber(received_packet_num), *packet, buffer, kMaxOutgoingPacketSize); connection_.ProcessUdpPacket( kSelfAddress, kPeerAddress, QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false)); EXPECT_TRUE(writer_->IsWriteBlocked()); EXPECT_FALSE(connection_.GetSendAlarm()->IsSet()); } TEST_P(QuicConnectionTest, SendAlarmNonZeroDelay) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); connection_.set_defer_send_in_response_to_packets(true); connection_.sent_packet_manager().SetDeferredSendAlarmDelay( QuicTime::Delta::FromMilliseconds(10)); EXPECT_FALSE(connection_.GetSendAlarm()->IsSet()); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); const uint64_t received_packet_num = 1; const bool has_stop_waiting = false; const EncryptionLevel level = ENCRYPTION_FORWARD_SECURE; std::unique_ptr<QuicPacket> packet( ConstructDataPacket(received_packet_num, has_stop_waiting, level)); char buffer[kMaxOutgoingPacketSize]; size_t encrypted_length = peer_framer_.EncryptPayload(level, QuicPacketNumber(received_packet_num), *packet, buffer, kMaxOutgoingPacketSize); EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true)); connection_.ProcessUdpPacket( kSelfAddress, kPeerAddress, QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false)); EXPECT_TRUE(connection_.GetSendAlarm()->IsSet()); EXPECT_TRUE(connection_.GetSendAlarm()->deadline() > clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5)); } TEST_P(QuicConnectionTest, AddToWriteBlockedListIfWriterBlockedWhenProcessing) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr); writer_->SetWriteBlocked(); QuicAckFrame ack1 = InitAckFrame(1); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _)); EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1); ProcessAckPacket(1, &ack1); } TEST_P(QuicConnectionTest, DoNotAddToWriteBlockedListAfterDisconnect) { writer_->SetBatchMode(true); EXPECT_TRUE(connection_.connected()); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)) .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame)); EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0); { QuicConnection::ScopedPacketFlusher flusher(&connection_); connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason", ConnectionCloseBehavior::SILENT_CLOSE); EXPECT_FALSE(connection_.connected()); writer_->SetWriteBlocked(); } EXPECT_EQ(1, connection_close_frame_count_); EXPECT_THAT(saved_connection_close_frame_.quic_error_code, IsError(QUIC_PEER_GOING_AWAY)); } TEST_P(QuicConnectionTest, AddToWriteBlockedListIfBlockedOnFlushPackets) { writer_->SetBatchMode(true); writer_->BlockOnNextFlush(); EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1); { QuicConnection::ScopedPacketFlusher flusher(&connection_); } } TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); int offset = 0; for (int i = 0; i < 15; ++i) { SendStreamDataToPeer(1, "foo", offset, NO_FIN, nullptr); offset += 3; } QuicAckFrame nack = InitAckFrame({{QuicPacketNumber(15), QuicPacketNumber(16)}}); LostPacketVector lost_packets; for (int i = 1; i < 15; ++i) { lost_packets.push_back( LostPacket(QuicPacketNumber(i), kMaxOutgoingPacketSize)); } EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _)) .WillOnce(DoAll(SetArgPointee<5>(lost_packets), Return(LossDetectionInterface::DetectionStats()))); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); ProcessAckPacket(&nack); } TEST_P(QuicConnectionTest, MultipleAcks) { if (connection_.SupportsMultiplePacketNumberSpaces()) { return; } EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacket(1); QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2); QuicPacketNumber last_packet; SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); EXPECT_EQ(QuicPacketNumber(1u), last_packet); SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); EXPECT_EQ(QuicPacketNumber(2u), last_packet); SendAckPacketToPeer(); SendStreamDataToPeer(5, "foo", 0, NO_FIN, &last_packet); EXPECT_EQ(QuicPacketNumber(4u), last_packet); SendStreamDataToPeer(1, "foo", 3, NO_FIN, &last_packet); EXPECT_EQ(QuicPacketNumber(5u), last_packet); SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); EXPECT_EQ(QuicPacketNumber(6u), last_packet); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); QuicAckFrame frame1 = ConstructAckFrame(5, 3); ProcessAckPacket(&frame1); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); QuicAckFrame frame2 = InitAckFrame(6); ProcessAckPacket(&frame2); } TEST_P(QuicConnectionTest, DontLatchUnackedPacket) { if (connection_.SupportsMultiplePacketNumberSpaces()) { return; } EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacket(1); QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2); SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr); SendAckPacketToPeer(); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); QuicAckFrame frame = InitAckFrame(1); ProcessAckPacket(&frame); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); frame = InitAckFrame(2); ProcessAckPacket(&frame); SendAckPacketToPeer(); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); frame = InitAckFrame(3); ProcessAckPacket(&frame); SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr); SendAckPacketToPeer(); SendStreamDataToPeer(1, "bar", 6, NO_FIN, nullptr); SendStreamDataToPeer(1, "bar", 9, NO_FIN, nullptr); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)}, {QuicPacketNumber(7), QuicPacketNumber(8)}}); ProcessAckPacket(&frame); } TEST_P(QuicConnectionTest, SendHandshakeMessages) { EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true)); BlockOnNextWrite(); connection_.SendCryptoDataWithString("foo", 0); EXPECT_EQ(1u, connection_.NumQueuedPackets()); connection_.SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); writer_->SetWritable(); EXPECT_CALL(visitor_, OnCanWrite()); connection_.OnCanWrite(); EXPECT_EQ(0u, connection_.NumQueuedPackets()); EXPECT_NE(0x02020202u, writer_->final_bytes_of_last_packet()); } TEST_P(QuicConnectionTest, DropRetransmitsForInitialPacketAfterForwardSecure) { connection_.SendCryptoStreamData(); BlockOnNextWrite(); clock_.AdvanceTime(DefaultRetransmissionTime()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.GetRetransmissionAlarm()->Fire(); EXPECT_EQ(1u, connection_.NumQueuedPackets()); connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(0x02)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); notifier_.NeuterUnencryptedData(); connection_.NeuterUnencryptedPackets(); connection_.OnHandshakeComplete(); EXPECT_EQ(QuicTime::Zero(), connection_.GetRetransmissionAlarm()->deadline()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); writer_->SetWritable(); connection_.OnCanWrite(); } TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) { connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); connection_.SendCryptoDataWithString("foo", 0); connection_.SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); if (!connection_.version().KnowsWhichDecrypterToUse()) { writer_->framer()->framer()->SetAlternativeDecrypter( ENCRYPTION_ZERO_RTT, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT), false); } SendStreamDataToPeer(2, "bar", 0, NO_FIN, nullptr); EXPECT_FALSE(notifier_.HasLostStreamData()); connection_.MarkZeroRttPacketsForRetransmission(0); EXPECT_TRUE(notifier_.HasLostStreamData()); } TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) { if (connection_.SupportsMultiplePacketNumberSpaces()) { return; } EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; connection_.SetFromConfig(config); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); peer_framer_.SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT)); if (!connection_.version().KnowsWhichDecrypterToUse()) { writer_->framer()->framer()->SetDecrypter( ENCRYPTION_ZERO_RTT, std::make_unique<TaggingDecrypter>()); } ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT); SetDecrypter(ENCRYPTION_ZERO_RTT, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT)); connection_.SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2); ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT); } TEST_P(QuicConnectionTest, Buffer100NonDecryptablePacketsThenKeyChange) { if (connection_.SupportsMultiplePacketNumberSpaces()) { return; } EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; config.set_max_undecryptable_packets(100); connection_.SetFromConfig(config); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); peer_framer_.SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT)); for (uint64_t i = 1; i <= 100; ++i) { ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT); } EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet()); SetDecrypter(ENCRYPTION_ZERO_RTT, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT)); EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet()); connection_.SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(100); if (!connection_.version().KnowsWhichDecrypterToUse()) { writer_->framer()->framer()->SetDecrypter( ENCRYPTION_ZERO_RTT, std::make_unique<TaggingDecrypter>()); } connection_.GetProcessUndecryptablePacketsAlarm()->Fire(); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacketAtLevel(102, !kHasStopWaiting, ENCRYPTION_ZERO_RTT); } TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) { BlockOnNextWrite(); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN); EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); writer_->SetWritable(); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); connection_.OnCanWrite(); EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); } TEST_P(QuicConnectionTest, TestQueued) { EXPECT_EQ(0u, connection_.NumQueuedPackets()); BlockOnNextWrite(); connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN); EXPECT_EQ(1u, connection_.NumQueuedPackets()); writer_->SetWritable(); connection_.OnCanWrite(); EXPECT_EQ(0u, connection_.NumQueuedPackets()); } TEST_P(QuicConnectionTest, InitialTimeout) { EXPECT_TRUE(connection_.connected()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber()); EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet()); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; connection_.SetFromConfig(config); QuicTime default_timeout = clock_.ApproximateNow() + QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1); EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline()); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1)); connection_.GetTimeoutAlarm()->Fire(); EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet()); EXPECT_FALSE(connection_.connected()); EXPECT_FALSE(connection_.HasPendingAcks()); EXPECT_FALSE(connection_.GetPingAlarm()->IsSet()); EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); EXPECT_FALSE(connection_.GetSendAlarm()->IsSet()); EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet()); EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet()); TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT); } TEST_P(QuicConnectionTest, IdleTimeoutAfterFirstSentPacket) { EXPECT_TRUE(connection_.connected()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber()); EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet()); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; connection_.SetFromConfig(config); EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet()); QuicTime initial_ddl = clock_.ApproximateNow() + QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1); EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline()); EXPECT_TRUE(connection_.connected()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20)); QuicPacketNumber last_packet; SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); EXPECT_EQ(QuicPacketNumber(1u), last_packet); QuicTime new_ddl = clock_.ApproximateNow() + QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1); EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0); QuicTime::Delta delay = initial_ddl - clock_.ApproximateNow(); clock_.AdvanceTime(delay); EXPECT_TRUE(connection_.connected()); EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet()); EXPECT_EQ(new_ddl, connection_.GetTimeoutAlarm()->deadline()); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)); clock_.AdvanceTime(new_ddl - clock_.ApproximateNow()); connection_.GetTimeoutAlarm()->Fire(); EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet()); EXPECT_FALSE(connection_.connected()); EXPECT_FALSE(connection_.HasPendingAcks()); EXPECT_FALSE(connection_.GetPingAlarm()->IsSet()); EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); EXPECT_FALSE(connection_.GetSendAlarm()->IsSet()); EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet()); TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT); } TEST_P(QuicConnectionTest, IdleTimeoutAfterSendTwoPackets) { EXPECT_TRUE(connection_.connected()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber()); EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet()); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; connection_.SetFromConfig(config); EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet()); QuicTime initial_ddl = clock_.ApproximateNow() + QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1); EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline()); EXPECT_TRUE(connection_.connected()); QuicPacketNumber last_packet; SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); EXPECT_EQ(QuicPacketNumber(1u), last_packet); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20)); SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); EXPECT_EQ(QuicPacketNumber(2u), last_packet); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)); clock_.AdvanceTime(initial_ddl - clock_.ApproximateNow()); connection_.GetTimeoutAlarm()->Fire(); EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet()); EXPECT_FALSE(connection_.connected()); EXPECT_FALSE(connection_.HasPendingAcks()); EXPECT_FALSE(connection_.GetPingAlarm()->IsSet()); EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); EXPECT_FALSE(connection_.GetSendAlarm()->IsSet()); EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet()); TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT); } TEST_P(QuicConnectionTest, HandshakeTimeout) { const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5); connection_.SetNetworkTimeouts(timeout, timeout); EXPECT_TRUE(connection_.connected()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber()); QuicTime handshake_timeout = clock_.ApproximateNow() + timeout - QuicTime::Delta::FromSeconds(1); EXPECT_EQ(handshake_timeout, connection_.GetTimeoutAlarm()->deadline()); EXPECT_TRUE(connection_.connected()); SendStreamDataToPeer( GetNthClientInitiatedStreamId(0, connection_.transport_version()), "GET /", 0, FIN, nullptr); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3)); QuicAckFrame frame = InitAckFrame(1); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); ProcessAckPacket(&frame); EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet()); EXPECT_TRUE(connection_.connected()); clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(2)); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)); connection_.GetTimeoutAlarm()->Fire(); EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet()); EXPECT_FALSE(connection_.connected()); EXPECT_FALSE(connection_.HasPendingAcks()); EXPECT_FALSE(connection_.GetPingAlarm()->IsSet()); EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); EXPECT_FALSE(connection_.GetSendAlarm()->IsSet()); TestConnectionCloseQuicErrorCode(QUIC_HANDSHAKE_TIMEOUT); } TEST_P(QuicConnectionTest, PingAfterSend) { if (connection_.SupportsMultiplePacketNumberSpaces()) { return; } EXPECT_TRUE(connection_.connected()); EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()) .WillRepeatedly(Return(true)); EXPECT_FALSE(connection_.GetPingAlarm()->IsSet()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); SendStreamDataToPeer( GetNthClientInitiatedStreamId(0, connection_.transport_version()), "GET /", 0, FIN, nullptr); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(15), connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); QuicAckFrame frame = InitAckFrame(1); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); ProcessAckPacket(&frame); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ( QuicTime::Delta::FromSeconds(15) - QuicTime::Delta::FromMilliseconds(5), connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); writer_->Reset(); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15)); connection_.GetPingAlarm()->Fire(); size_t padding_frame_count = writer_->padding_frames().size(); EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count()); ASSERT_EQ(1u, writer_->ping_frames().size()); writer_->Reset(); EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()) .WillRepeatedly(Return(false)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); SendAckPacketToPeer(); EXPECT_FALSE(connection_.GetPingAlarm()->IsSet()); } TEST_P(QuicConnectionTest, ReducedPingTimeout) { if (connection_.SupportsMultiplePacketNumberSpaces()) { return; } EXPECT_TRUE(connection_.connected()); EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()) .WillRepeatedly(Return(true)); EXPECT_FALSE(connection_.GetPingAlarm()->IsSet()); connection_.set_keep_alive_ping_timeout(QuicTime::Delta::FromSeconds(10)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); SendStreamDataToPeer( GetNthClientInitiatedStreamId(0, connection_.transport_version()), "GET /", 0, FIN, nullptr); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(10), connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); QuicAckFrame frame = InitAckFrame(1); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); ProcessAckPacket(&frame); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ( QuicTime::Delta::FromSeconds(10) - QuicTime::Delta::FromMilliseconds(5), connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); writer_->Reset(); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10)); connection_.GetPingAlarm()->Fire(); size_t padding_frame_count = writer_->padding_frames().size(); EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count()); ASSERT_EQ(1u, writer_->ping_frames().size()); writer_->Reset(); EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()) .WillRepeatedly(Return(false)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); SendAckPacketToPeer(); EXPECT_FALSE(connection_.GetPingAlarm()->IsSet()); } TEST_P(QuicConnectionTest, SendMtuDiscoveryPacket) { MtuDiscoveryTestInit(); const size_t new_mtu = kDefaultMaxPacketSize + 100; QuicByteCount mtu_probe_size; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .WillOnce(SaveArg<3>(&mtu_probe_size)); connection_.SendMtuDiscoveryPacket(new_mtu); EXPECT_EQ(new_mtu, mtu_probe_size); EXPECT_EQ(QuicPacketNumber(1u), creator_->packet_number()); const std::string data(kDefaultMaxPacketSize + 1, '.'); QuicByteCount size_before_mtu_change; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(2) .WillOnce(SaveArg<3>(&size_before_mtu_change)) .WillOnce(Return()); connection_.SendStreamDataWithString(3, data, 0, FIN); EXPECT_EQ(QuicPacketNumber(3u), creator_->packet_number()); EXPECT_EQ(kDefaultMaxPacketSize, size_before_mtu_change); QuicAckFrame probe_ack = InitAckFrame(3); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); ProcessAckPacket(&probe_ack); EXPECT_EQ(new_mtu, connection_.max_packet_length()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.SendStreamDataWithString(3, data, 0, FIN); EXPECT_EQ(QuicPacketNumber(4u), creator_->packet_number()); } TEST_P(QuicConnectionTest, BatchWriterFlushedAfterMtuDiscoveryPacket) { writer_->SetBatchMode(true); MtuDiscoveryTestInit(); const size_t target_mtu = kDefaultMaxPacketSize + 100; QuicByteCount mtu_probe_size; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .WillOnce(SaveArg<3>(&mtu_probe_size)); const uint32_t prior_flush_attempts = writer_->flush_attempts(); connection_.SendMtuDiscoveryPacket(target_mtu); EXPECT_EQ(target_mtu, mtu_probe_size); EXPECT_EQ(writer_->flush_attempts(), prior_flush_attempts + 1); } TEST_P(QuicConnectionTest, MtuDiscoveryDisabled) { MtuDiscoveryTestInit(); const QuicPacketCount packets_between_probes_base = 10; set_packets_between_probes_base(packets_between_probes_base); const QuicPacketCount number_of_packets = packets_between_probes_base * 2; for (QuicPacketCount i = 0; i < number_of_packets; i++) { SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr); EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet()); EXPECT_EQ(0u, connection_.mtu_probe_count()); } } TEST_P(QuicConnectionTest, MtuDiscoveryEnabled) { MtuDiscoveryTestInit(); const QuicPacketCount packets_between_probes_base = 5; set_packets_between_probes_base(packets_between_probes_base); connection_.EnablePathMtuDiscovery(send_algorithm_); for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) { SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr); ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet()); } SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN, nullptr); ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet()); QuicByteCount probe_size; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .WillOnce(SaveArg<3>(&probe_size)); connection_.GetMtuDiscoveryAlarm()->Fire(); EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(), kMtuDiscoveryTargetPacketSizeHigh)); const QuicPacketNumber probe_packet_number = FirstSendingPacketNumber() + packets_between_probes_base; ASSERT_EQ(probe_packet_number, creator_->packet_number()); { QuicAckFrame probe_ack = InitAckFrame(probe_packet_number); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)) .Times(AnyNumber()); ProcessAckPacket(&probe_ack); EXPECT_EQ(probe_size, connection_.max_packet_length()); EXPECT_EQ(0u, connection_.GetBytesInFlight()); EXPECT_EQ(1u, connection_.mtu_probe_count()); } QuicStreamOffset stream_offset = packets_between_probes_base; QuicByteCount last_probe_size = 0; for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts; ++num_probes) { for (QuicPacketCount i = 0; i < (packets_between_probes_base << num_probes) - 1; ++i) { SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr); ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet()); } SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr); ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet()); QuicByteCount new_probe_size; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .WillOnce(SaveArg<3>(&new_probe_size)); connection_.GetMtuDiscoveryAlarm()->Fire(); EXPECT_THAT(new_probe_size, InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh)); EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count()); QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number()); ProcessAckPacket(&probe_ack); EXPECT_EQ(new_probe_size, connection_.max_packet_length()); EXPECT_EQ(0u, connection_.GetBytesInFlight()); last_probe_size = probe_size; probe_size = new_probe_size; } EXPECT_EQ(probe_size, kMtuDiscoveryTargetPacketSizeHigh); writer_->SetShouldWriteFail(); SendStreamDataToPeer(3, "(", stream_offset++, NO_FIN, nullptr); EXPECT_EQ(last_probe_size, connection_.max_packet_length()); EXPECT_TRUE(connection_.connected()); EXPECT_CALL(visitor_, OnConnectionClosed(_, _)) .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame)); SendStreamDataToPeer(3, ")", stream_offset++, NO_FIN, nullptr); EXPECT_EQ(last_probe_size, connection_.max_packet_length()); EXPECT_FALSE(connection_.connected()); EXPECT_THAT(saved_connection_close_frame_.quic_error_code, IsError(QUIC_PACKET_WRITE_ERROR)); } TEST_P(QuicConnectionTest, MtuDiscoveryIgnoreOneWriteErrorInFlushAfterSuccessfulProbes) { MtuDiscoveryTestInit(); writer_->SetBatchMode(true); const QuicPacketCount packets_between_probes_base = 5; set_packets_between_probes_base(packets_between_probes_base); connection_.EnablePathMtuDiscovery(send_algorithm_); const QuicByteCount original_max_packet_length = connection_.max_packet_length(); for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) { SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr); ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet()); } SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN, nullptr); ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet()); QuicByteCount probe_size; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .WillOnce(SaveArg<3>(&probe_size)); connection_.GetMtuDiscoveryAlarm()->Fire(); EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(), kMtuDiscoveryTargetPacketSizeHigh)); const QuicPacketNumber probe_packet_number = FirstSendingPacketNumber() + packets_between_probes_base; ASSERT_EQ(probe_packet_number, creator_->packet_number()); { QuicAckFrame probe_ack = InitAckFrame(probe_packet_number); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)) .Times(AnyNumber()); ProcessAckPacket(&probe_ack); EXPECT_EQ(probe_size, connection_.max_packet_length()); EXPECT_EQ(0u, connection_.GetBytesInFlight()); } EXPECT_EQ(1u, connection_.mtu_probe_count()); writer_->SetShouldWriteFail(); { QuicConnection::ScopedPacketFlusher flusher(&connection_); } EXPECT_EQ(original_max_packet_length, connection_.max_packet_length()); EXPECT_TRUE(connection_.connected()); EXPECT_CALL(visitor_, OnConnectionClosed(_, _)) .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame)); { QuicConnection::ScopedPacketFlusher flusher(&connection_); } EXPECT_EQ(original_max_packet_length, connection_.max_packet_length()); EXPECT_FALSE(connection_.connected()); EXPECT_THAT(saved_connection_close_frame_.quic_error_code, IsError(QUIC_PACKET_WRITE_ERROR)); } TEST_P(QuicConnectionTest, MtuDiscoveryWriteBlocked) { MtuDiscoveryTestInit(); const QuicPacketCount packets_between_probes_base = 5; set_packets_between_probes_base(packets_between_probes_base); connection_.EnablePathMtuDiscovery(send_algorithm_); for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) { SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr); ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet()); } QuicByteCount original_max_packet_length = connection_.max_packet_length(); SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN, nullptr); ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)); BlockOnNextWrite(); EXPECT_EQ(0u, connection_.NumQueuedPackets()); connection_.GetMtuDiscoveryAlarm()->Fire(); EXPECT_EQ(1u, connection_.mtu_probe_count()); EXPECT_EQ(1u, connection_.NumQueuedPackets()); ASSERT_TRUE(connection_.connected()); writer_->SetWritable(); SimulateNextPacketTooLarge(); connection_.OnCanWrite(); EXPECT_EQ(0u, connection_.NumQueuedPackets()); EXPECT_EQ(original_max_packet_length, connection_.max_packet_length()); EXPECT_TRUE(connection_.connected()); } TEST_P(QuicConnectionTest, MtuDiscoveryFailed) { MtuDiscoveryTestInit(); const QuicPacketCount packets_between_probes_base = 5; set_packets_between_probes_base(packets_between_probes_base); connection_.EnablePathMtuDiscovery(send_algorithm_); const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(100); EXPECT_EQ(packets_between_probes_base, QuicConnectionPeer::GetPacketsBetweenMtuProbes(&connection_)); const QuicPacketCount number_of_packets = packets_between_probes_base * (1 << (kMtuDiscoveryAttempts + 1)); std::vector<QuicPacketNumber> mtu_discovery_packets; EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)) .Times(AnyNumber()); for (QuicPacketCount i = 0; i < number_of_packets; i++) { SendStreamDataToPeer(3, "!", i, NO_FIN, nullptr); clock_.AdvanceTime(rtt); QuicAckFrame ack; if (!mtu_discovery_packets.empty()) { QuicPacketNumber min_packet = *min_element(mtu_discovery_packets.begin(), mtu_discovery_packets.end()); QuicPacketNumber max_packet = *max_element(mtu_discovery_packets.begin(), mtu_discovery_packets.end()); ack.packets.AddRange(QuicPacketNumber(1), min_packet); ack.packets.AddRange(QuicPacketNumber(max_packet + 1), creator_->packet_number() + 1); ack.largest_acked = creator_->packet_number(); } else { ack.packets.AddRange(QuicPacketNumber(1), creator_->packet_number() + 1); ack.largest_acked = creator_->packet_number(); } ProcessAckPacket(&ack); if (!connection_.GetMtuDiscoveryAlarm()->IsSet()) { continue; } EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)); connection_.GetMtuDiscoveryAlarm()->Fire(); mtu_discovery_packets.push_back(creator_->packet_number()); } ASSERT_EQ(kMtuDiscoveryAttempts, mtu_discovery_packets.size()); for (uint64_t i = 0; i < kMtuDiscoveryAttempts; i++) { const QuicPacketCount packets_between_probes = packets_between_probes_base * ((1 << (i + 1)) - 1); EXPECT_EQ(QuicPacketNumber(packets_between_probes + (i + 1)), mtu_discovery_packets[i]); } EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet()); EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length()); EXPECT_EQ(kMtuDiscoveryAttempts, connection_.mtu_probe_count()); } TEST_P(QuicConnectionTest, MtuDiscoverySecondProbeFailed) { MtuDiscoveryTestInit(); const QuicPacketCount packets_between_probes_base = 5; set_packets_between_probes_base(packets_between_probes_base); connection_.EnablePathMtuDiscovery(send_algorithm_); QuicStreamOffset stream_offset = 0; for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) { SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr); ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet()); } SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN, nullptr); ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet()); QuicByteCount probe_size; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .WillOnce(SaveArg<3>(&probe_size)); connection_.GetMtuDiscoveryAlarm()->Fire(); EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(), kMtuDiscoveryTargetPacketSizeHigh)); const QuicPacketNumber probe_packet_number = FirstSendingPacketNumber() + packets_between_probes_base; ASSERT_EQ(probe_packet_number, creator_->packet_number()); QuicAckFrame first_ack = InitAckFrame(probe_packet_number); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)) .Times(AnyNumber()); ProcessAckPacket(&first_ack); EXPECT_EQ(probe_size, connection_.max_packet_length()); EXPECT_EQ(0u, connection_.GetBytesInFlight()); EXPECT_EQ(1u, connection_.mtu_probe_count()); for (QuicPacketCount i = 0; i < (packets_between_probes_base << 1) - 1; ++i) { SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr); ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet()); } SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr); ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet()); QuicByteCount second_probe_size; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .WillOnce(SaveArg<3>(&second_probe_size)); connection_.GetMtuDiscoveryAlarm()->Fire(); EXPECT_THAT(second_probe_size, InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh)); EXPECT_EQ(2u, connection_.mtu_probe_count()); QuicPacketNumber second_probe_packet_number = creator_->packet_number(); QuicAckFrame second_ack = InitAckFrame(second_probe_packet_number - 1); ProcessAckPacket(&first_ack); EXPECT_EQ(probe_size, connection_.max_packet_length()); for (QuicPacketCount i = 0; i < (packets_between_probes_base << 2) - 1; ++i) { SendStreamDataToPeer(3, "@", stream_offset++, NO_FIN, nullptr); ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet()); } SendStreamDataToPeer(3, "#", stream_offset++, NO_FIN, nullptr); ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet()); QuicByteCount third_probe_size; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .WillOnce(SaveArg<3>(&third_probe_size)); connection_.GetMtuDiscoveryAlarm()->Fire(); EXPECT_THAT(third_probe_size, InRange(probe_size, second_probe_size)); EXPECT_EQ(3u, connection_.mtu_probe_count()); QuicAckFrame third_ack = ConstructAckFrame(creator_->packet_number(), second_probe_packet_number); ProcessAckPacket(&third_ack); EXPECT_EQ(third_probe_size, connection_.max_packet_length()); SendStreamDataToPeer(3, "$", stream_offset++, NO_FIN, nullptr); EXPECT_TRUE(connection_.PathMtuReductionDetectionInProgress()); if (connection_.PathDegradingDetectionInProgress() && QuicConnectionPeer::GetPathDegradingDeadline(&connection_) < QuicConnectionPeer::GetPathMtuReductionDetectionDeadline( &connection_)) { connection_.PathDegradingTimeout(); } EXPECT_EQ(third_probe_size, connection_.max_packet_length()); EXPECT_TRUE(connection_.PathMtuReductionDetectionInProgress()); connection_.GetBlackholeDetectorAlarm()->Fire(); EXPECT_EQ(probe_size, connection_.max_packet_length()); } TEST_P(QuicConnectionTest, MtuDiscoveryWriterLimited) { MtuDiscoveryTestInit(); const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1; writer_->set_max_packet_size(mtu_limit); const QuicPacketCount packets_between_probes_base = 5; set_packets_between_probes_base(packets_between_probes_base); connection_.EnablePathMtuDiscovery(send_algorithm_); for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) { SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr); ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet()); } SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN, nullptr); ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet()); QuicByteCount probe_size; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .WillOnce(SaveArg<3>(&probe_size)); connection_.GetMtuDiscoveryAlarm()->Fire(); EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(), mtu_limit)); const QuicPacketNumber probe_sequence_number = FirstSendingPacketNumber() + packets_between_probes_base; ASSERT_EQ(probe_sequence_number, creator_->packet_number()); { QuicAckFrame probe_ack = InitAckFrame(probe_sequence_number); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)) .Times(AnyNumber()); ProcessAckPacket(&probe_ack); EXPECT_EQ(probe_size, connection_.max_packet_length()); EXPECT_EQ(0u, connection_.GetBytesInFlight()); } EXPECT_EQ(1u, connection_.mtu_probe_count()); QuicStreamOffset stream_offset = packets_between_probes_base; for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts; ++num_probes) { for (QuicPacketCount i = 0; i < (packets_between_probes_base << num_probes) - 1; ++i) { SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr); ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet()); } SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr); ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet()); QuicByteCount new_probe_size; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .WillOnce(SaveArg<3>(&new_probe_size)); connection_.GetMtuDiscoveryAlarm()->Fire(); EXPECT_THAT(new_probe_size, InRange(probe_size, mtu_limit)); EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count()); QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number()); ProcessAckPacket(&probe_ack); EXPECT_EQ(new_probe_size, connection_.max_packet_length()); EXPECT_EQ(0u, connection_.GetBytesInFlight()); probe_size = new_probe_size; } EXPECT_EQ(probe_size, mtu_limit); } TEST_P(QuicConnectionTest, MtuDiscoveryWriterFailed) { MtuDiscoveryTestInit(); const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1; const QuicByteCount initial_mtu = connection_.max_packet_length(); EXPECT_LT(initial_mtu, mtu_limit); writer_->set_max_packet_size(mtu_limit); const QuicPacketCount packets_between_probes_base = 5; set_packets_between_probes_base(packets_between_probes_base); connection_.EnablePathMtuDiscovery(send_algorithm_); for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) { SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr); ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet()); } SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN, nullptr); ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet()); writer_->SimulateNextPacketTooLarge(); connection_.GetMtuDiscoveryAlarm()->Fire(); ASSERT_TRUE(connection_.connected()); QuicPacketNumber probe_number = creator_->packet_number(); QuicPacketCount extra_packets = packets_between_probes_base * 3; for (QuicPacketCount i = 0; i < extra_packets; i++) { connection_.EnsureWritableAndSendStreamData5(); ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet()); } QuicAckFrame probe_ack = ConstructAckFrame(creator_->packet_number(), probe_number); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); ProcessAckPacket(&probe_ack); EXPECT_EQ(initial_mtu, connection_.max_packet_length()); for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) { connection_.EnsureWritableAndSendStreamData5(); ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet()); } EXPECT_EQ(initial_mtu, connection_.max_packet_length()); EXPECT_EQ(1u, connection_.mtu_probe_count()); } TEST_P(QuicConnectionTest, NoMtuDiscoveryAfterConnectionClosed) { MtuDiscoveryTestInit(); const QuicPacketCount packets_between_probes_base = 10; set_packets_between_probes_base(packets_between_probes_base); connection_.EnablePathMtuDiscovery(send_algorithm_); for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) { SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr); ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet()); } SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN, nullptr); EXPECT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet()); EXPECT_CALL(visitor_, OnConnectionClosed(_, _)); connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason", ConnectionCloseBehavior::SILENT_CLOSE); EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet()); } TEST_P(QuicConnectionTest, TimeoutAfterSendDuringHandshake) { EXPECT_TRUE(connection_.connected()); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; connection_.SetFromConfig(config); const QuicTime::Delta initial_idle_timeout = QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1); const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5); QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout; clock_.AdvanceTime(five_ms); SendStreamDataToPeer( GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo", 0, FIN, nullptr); EXPECT_EQ(default_timeout + five_ms, connection_.GetTimeoutAlarm()->deadline()); clock_.AdvanceTime(five_ms); SendStreamDataToPeer( GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo", 3, FIN, nullptr); EXPECT_EQ(default_timeout + five_ms, connection_.GetTimeoutAlarm()->deadline()); clock_.AdvanceTime(initial_idle_timeout - five_ms - five_ms); EXPECT_EQ(default_timeout, clock_.ApproximateNow()); EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet()); EXPECT_TRUE(connection_.connected()); EXPECT_EQ(default_timeout + five_ms, connection_.GetTimeoutAlarm()->deadline()); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1)); clock_.AdvanceTime(five_ms); EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow()); connection_.GetTimeoutAlarm()->Fire(); EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet()); EXPECT_FALSE(connection_.connected()); TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT); } TEST_P(QuicConnectionTest, TimeoutAfterSendAfterHandshake) { EXPECT_TRUE(connection_.connected()); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; CryptoHandshakeMessage msg; std::string error_details; QuicConfig client_config; client_config.SetInitialStreamFlowControlWindowToSend( kInitialStreamFlowControlWindowForTest); client_config.SetInitialSessionFlowControlWindowToSend( kInitialSessionFlowControlWindowForTest); client_config.SetIdleNetworkTimeout( QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs)); client_config.ToHandshakeMessage(&msg, connection_.transport_version()); const QuicErrorCode error = config.ProcessPeerHello(msg, CLIENT, &error_details); EXPECT_THAT(error, IsQuicNoError()); if (connection_.version().UsesTls()) { QuicConfigPeer::SetReceivedOriginalConnectionId( &config, connection_.connection_id()); QuicConfigPeer::SetReceivedInitialSourceConnectionId( &config, connection_.connection_id()); } connection_.SetFromConfig(config); const QuicTime::Delta default_idle_timeout = QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1); const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5); QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout; clock_.AdvanceTime(five_ms); SendStreamDataToPeer( GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo", 0, FIN, nullptr); EXPECT_EQ(default_timeout + five_ms, connection_.GetTimeoutAlarm()->deadline()); clock_.AdvanceTime(five_ms); SendStreamDataToPeer( GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo", 3, FIN, nullptr); EXPECT_EQ(default_timeout + five_ms, connection_.GetTimeoutAlarm()->deadline()); clock_.AdvanceTime(default_idle_timeout - five_ms - five_ms); EXPECT_EQ(default_timeout, clock_.ApproximateNow()); EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet()); EXPECT_TRUE(connection_.connected()); EXPECT_EQ(default_timeout + five_ms, connection_.GetTimeoutAlarm()->deadline()); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)) .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame)); clock_.AdvanceTime(five_ms); EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow()); connection_.GetTimeoutAlarm()->Fire(); EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet()); EXPECT_FALSE(connection_.connected()); EXPECT_EQ(1, connection_close_frame_count_); EXPECT_THAT(saved_connection_close_frame_.quic_error_code, IsError(QUIC_NETWORK_IDLE_TIMEOUT)); } TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseWithOpenStreams) { EXPECT_TRUE(connection_.connected()); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; CryptoHandshakeMessage msg; std::string error_details; QuicConfig client_config; client_config.SetInitialStreamFlowControlWindowToSend( kInitialStreamFlowControlWindowForTest); client_config.SetInitialSessionFlowControlWindowToSend( kInitialSessionFlowControlWindowForTest); client_config.SetIdleNetworkTimeout( QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs)); client_config.ToHandshakeMessage(&msg, connection_.transport_version()); const QuicErrorCode error = config.ProcessPeerHello(msg, CLIENT, &error_details); EXPECT_THAT(error, IsQuicNoError()); if (connection_.version().UsesTls()) { QuicConfigPeer::SetReceivedOriginalConnectionId( &config, connection_.connection_id()); QuicConfigPeer::SetReceivedInitialSourceConnectionId( &config, connection_.connection_id()); } connection_.SetFromConfig(config); const QuicTime::Delta default_idle_timeout = QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1); const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5); QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout; clock_.AdvanceTime(five_ms); SendStreamDataToPeer( GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo", 0, FIN, nullptr); EXPECT_EQ(default_timeout + five_ms, connection_.GetTimeoutAlarm()->deadline()); EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()) .WillRepeatedly(Return(true)); if (GetQuicReloadableFlag(quic_add_stream_info_to_idle_close_detail)) { EXPECT_CALL(visitor_, GetStreamsInfoForLogging()).WillOnce(Return("")); } EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1)); clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() - clock_.ApproximateNow() + five_ms); connection_.GetTimeoutAlarm()->Fire(); EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet()); EXPECT_FALSE(connection_.connected()); TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT); } TEST_P(QuicConnectionTest, TimeoutAfterReceive) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_TRUE(connection_.connected()); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; connection_.SetFromConfig(config); const QuicTime::Delta initial_idle_timeout = QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1); const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5); QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout; connection_.SendStreamDataWithString( GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo", 0, NO_FIN); connection_.SendStreamDataWithString( GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo", 3, NO_FIN); EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline()); clock_.AdvanceTime(five_ms); QuicAckFrame ack = InitAckFrame(2); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); ProcessAckPacket(&ack); clock_.AdvanceTime(initial_idle_timeout - five_ms); EXPECT_EQ(default_timeout, clock_.ApproximateNow()); EXPECT_TRUE(connection_.connected()); EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet()); EXPECT_EQ(default_timeout + five_ms, connection_.GetTimeoutAlarm()->deadline()); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1)); clock_.AdvanceTime(five_ms); EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow()); connection_.GetTimeoutAlarm()->Fire(); EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet()); EXPECT_FALSE(connection_.connected()); TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT); } TEST_P(QuicConnectionTest, TimeoutAfterReceiveNotSendWhenUnacked) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_TRUE(connection_.connected()); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; connection_.SetFromConfig(config); const QuicTime::Delta initial_idle_timeout = QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1); connection_.SetNetworkTimeouts( QuicTime::Delta::Infinite(), initial_idle_timeout + QuicTime::Delta::FromSeconds(1)); const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5); QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)); connection_.SendStreamDataWithString( GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo", 0, NO_FIN); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)); connection_.SendStreamDataWithString( GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo", 3, NO_FIN); EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline()); clock_.AdvanceTime(five_ms); QuicAckFrame ack = InitAckFrame(2); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); ProcessAckPacket(&ack); clock_.AdvanceTime(initial_idle_timeout - five_ms); EXPECT_EQ(default_timeout, clock_.ApproximateNow()); EXPECT_TRUE(connection_.connected()); EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet()); EXPECT_EQ(default_timeout + five_ms, connection_.GetTimeoutAlarm()->deadline()); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber()); for (int i = 0; i < 100 && connection_.connected(); ++i) { QUIC_LOG(INFO) << "sending data packet"; connection_.SendStreamDataWithString( GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo", 0, NO_FIN); connection_.GetTimeoutAlarm()->Fire(); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1)); } EXPECT_FALSE(connection_.connected()); EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet()); TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT); } TEST_P(QuicConnectionTest, SendScheduler) { QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT); std::unique_ptr<QuicPacket> packet = ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL); QuicPacketCreatorPeer::SetPacketNumber(creator_, 1); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)); connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet), HAS_RETRANSMITTABLE_DATA, false, false); EXPECT_EQ(0u, connection_.NumQueuedPackets()); } TEST_P(QuicConnectionTest, FailToSendFirstPacket) { QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT); EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1); std::unique_ptr<QuicPacket> packet = ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL); QuicPacketCreatorPeer::SetPacketNumber(creator_, 1); writer_->SetShouldWriteFail(); connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet), HAS_RETRANSMITTABLE_DATA, false, false); } TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) { QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT); std::unique_ptr<QuicPacket> packet = ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL); QuicPacketCreatorPeer::SetPacketNumber(creator_, 1); BlockOnNextWrite(); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _)) .Times(0); connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet), HAS_RETRANSMITTABLE_DATA, false, false); EXPECT_EQ(1u, connection_.NumQueuedPackets()); } TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) { size_t payload_length = connection_.max_packet_length(); EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(testing::Return(false)); const std::string payload(payload_length, 'a'); QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId( connection_.version().transport_version, Perspective::IS_CLIENT)); EXPECT_EQ(0u, connection_ .SendStreamDataWithString(first_bidi_stream_id, payload, 0, NO_FIN) .bytes_consumed); EXPECT_EQ(0u, connection_.NumQueuedPackets()); } TEST_P(QuicConnectionTest, SendingThreePackets) { size_t total_payload_length = 2 * connection_.max_packet_length(); const std::string payload(total_payload_length, 'a'); QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId( connection_.version().transport_version, Perspective::IS_CLIENT)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3); EXPECT_EQ(payload.size(), connection_ .SendStreamDataWithString(first_bidi_stream_id, payload, 0, NO_FIN) .bytes_consumed); } TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) { set_perspective(Perspective::IS_SERVER); const std::string payload(connection_.max_packet_length(), 'a'); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2); EXPECT_EQ(payload.size(), connection_.SendStreamDataWithString(3, payload, 0, NO_FIN) .bytes_consumed); size_t non_truncated_packet_size = writer_->last_packet_size(); QuicConfig config; QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0); connection_.SetFromConfig(config); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2); EXPECT_EQ(payload.size(), connection_.SendStreamDataWithString(3, payload, 1350, NO_FIN) .bytes_consumed); EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() - 2); } TEST_P(QuicConnectionTest, SendDelayedAck) { QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime(); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_FALSE(connection_.HasPendingAcks()); SetDecrypter(ENCRYPTION_ZERO_RTT, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT)); peer_framer_.SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT)); frame1_.stream_id = 3; EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT); EXPECT_TRUE(connection_.HasPendingAcks()); EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline()); clock_.AdvanceTime(DefaultDelayedAckTime()); connection_.GetAckAlarm()->Fire(); size_t padding_frame_count = writer_->padding_frames().size(); EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count()); EXPECT_TRUE(writer_->stop_waiting_frames().empty()); EXPECT_FALSE(writer_->ack_frames().empty()); EXPECT_FALSE(connection_.HasPendingAcks()); } TEST_P(QuicConnectionTest, SendDelayedAckDecimation) { EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber()); const size_t kMinRttMs = 40; RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats()); rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs), QuicTime::Delta::Zero(), QuicTime::Zero()); QuicTime ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(kMinRttMs / 4); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_FALSE(connection_.HasPendingAcks()); SetDecrypter(ENCRYPTION_ZERO_RTT, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT)); peer_framer_.SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT)); frame1_.stream_id = 3; uint64_t kFirstDecimatedPacket = 101; for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) { EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT); } EXPECT_FALSE(connection_.HasPendingAcks()); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting, ENCRYPTION_ZERO_RTT); EXPECT_TRUE(connection_.HasPendingAcks()); EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline()); for (int i = 0; i < 9; ++i) { EXPECT_TRUE(connection_.HasPendingAcks()); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT); } size_t padding_frame_count = writer_->padding_frames().size(); EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count()); EXPECT_TRUE(writer_->stop_waiting_frames().empty()); EXPECT_FALSE(writer_->ack_frames().empty()); EXPECT_FALSE(connection_.HasPendingAcks()); } TEST_P(QuicConnectionTest, SendDelayedAckDecimationUnlimitedAggregation) { EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber()); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; QuicTagVector connection_options; connection_options.push_back(kAKDU); config.SetConnectionOptionsToSend(connection_options); connection_.SetFromConfig(config); const size_t kMinRttMs = 40; RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats()); rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs), QuicTime::Delta::Zero(), QuicTime::Zero()); QuicTime ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(kMinRttMs / 4); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_FALSE(connection_.HasPendingAcks()); SetDecrypter(ENCRYPTION_ZERO_RTT, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT)); peer_framer_.SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT)); frame1_.stream_id = 3; uint64_t kFirstDecimatedPacket = 101; for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) { EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT); } EXPECT_FALSE(connection_.HasPendingAcks()); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting, ENCRYPTION_ZERO_RTT); EXPECT_TRUE(connection_.HasPendingAcks()); EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline()); for (int i = 0; i < 18; ++i) { EXPECT_TRUE(connection_.HasPendingAcks()); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT); } EXPECT_TRUE(connection_.HasPendingAcks()); EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline()); } TEST_P(QuicConnectionTest, SendDelayedAckDecimationEighthRtt) { EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber()); QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125); const size_t kMinRttMs = 40; RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats()); rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs), QuicTime::Delta::Zero(), QuicTime::Zero()); QuicTime ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(kMinRttMs / 8); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_FALSE(connection_.HasPendingAcks()); SetDecrypter(ENCRYPTION_ZERO_RTT, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT)); peer_framer_.SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT)); frame1_.stream_id = 3; uint64_t kFirstDecimatedPacket = 101; for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) { EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT); } EXPECT_FALSE(connection_.HasPendingAcks()); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting, ENCRYPTION_ZERO_RTT); EXPECT_TRUE(connection_.HasPendingAcks()); EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline()); for (int i = 0; i < 9; ++i) { EXPECT_TRUE(connection_.HasPendingAcks()); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT); } size_t padding_frame_count = writer_->padding_frames().size(); EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count()); EXPECT_TRUE(writer_->stop_waiting_frames().empty()); EXPECT_FALSE(writer_->ack_frames().empty()); EXPECT_FALSE(connection_.HasPendingAcks()); } TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); ProcessPacket(1); EXPECT_TRUE(connection_.HasPendingAcks()); QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime(); EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline()); QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER); connection_.OnHandshakeComplete(); EXPECT_TRUE(connection_.HasPendingAcks()); EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline()); QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT); connection_.OnHandshakeComplete(); EXPECT_TRUE(connection_.HasPendingAcks()); if (connection_.SupportsMultiplePacketNumberSpaces()) { EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(), connection_.GetAckAlarm()->deadline()); } else { EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline()); } } TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); ProcessPacket(1); ProcessPacket(2); size_t padding_frame_count = writer_->padding_frames().size(); EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count()); EXPECT_TRUE(writer_->stop_waiting_frames().empty()); EXPECT_FALSE(writer_->ack_frames().empty()); EXPECT_FALSE(connection_.HasPendingAcks()); } TEST_P(QuicConnectionTest, NoAckOnOldNacks) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); ProcessPacket(2); size_t frames_per_ack = 1; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); ProcessPacket(3); size_t padding_frame_count = writer_->padding_frames().size(); EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count()); EXPECT_FALSE(writer_->ack_frames().empty()); writer_->Reset(); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); ProcessPacket(4); EXPECT_EQ(0u, writer_->frame_count()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); ProcessPacket(5); padding_frame_count = writer_->padding_frames().size(); EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count()); EXPECT_FALSE(writer_->ack_frames().empty()); writer_->Reset(); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); ProcessPacket(6); padding_frame_count = writer_->padding_frames().size(); EXPECT_EQ(padding_frame_count, writer_->frame_count()); EXPECT_TRUE(connection_.HasPendingAcks()); } TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(visitor_, OnStreamFrame(_)); peer_framer_.SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE)); SetDecrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE)); ProcessDataPacket(1); connection_.SendStreamDataWithString( GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo", 0, NO_FIN); EXPECT_EQ(2u, writer_->frame_count()); EXPECT_TRUE(writer_->stop_waiting_frames().empty()); EXPECT_FALSE(writer_->ack_frames().empty()); EXPECT_FALSE(connection_.HasPendingAcks()); } TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1); } else { EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); } ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL); connection_.SendCryptoDataWithString("foo", 0); EXPECT_EQ(3u, writer_->frame_count()); EXPECT_TRUE(writer_->stop_waiting_frames().empty()); EXPECT_FALSE(connection_.HasPendingAcks()); } TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); ProcessPacket(1); BlockOnNextWrite(); writer_->set_is_write_blocked_data_buffered(true); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); } else { EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2); } connection_.SendCryptoDataWithString("foo", 0); EXPECT_TRUE(writer_->IsWriteBlocked()); EXPECT_FALSE(connection_.HasQueuedData()); connection_.SendCryptoDataWithString("bar", 3); EXPECT_TRUE(writer_->IsWriteBlocked()); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_FALSE(connection_.HasQueuedData()); } else { EXPECT_TRUE(connection_.HasQueuedData()); } } TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_FALSE(connection_.HasPendingAcks()); EXPECT_CALL(visitor_, OnCanWrite()) .WillOnce(IgnoreResult(InvokeWithoutArgs( &connection_, &TestConnection::SendCryptoStreamData))); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1); } else { EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); } ForceWillingAndAbleToWriteOnceForDeferSending(); ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL); EXPECT_EQ(3u, writer_->frame_count()); EXPECT_TRUE(writer_->stop_waiting_frames().empty()); if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_EQ(1u, writer_->stream_frames().size()); } else { EXPECT_EQ(1u, writer_->crypto_frames().size()); } EXPECT_EQ(1u, writer_->padding_frames().size()); ASSERT_FALSE(writer_->ack_frames().empty()); EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front())); EXPECT_FALSE(connection_.HasPendingAcks()); } TEST_P(QuicConnectionTest, BundleAckForSecondCHLOTwoPacketReject) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_FALSE(connection_.HasPendingAcks()); { if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1); } else { EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); } ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)) .WillOnce(IgnoreResult(InvokeWithoutArgs( &connection_, &TestConnection::SendCryptoStreamData))); } else { EXPECT_CALL(visitor_, OnStreamFrame(_)) .WillOnce(IgnoreResult(InvokeWithoutArgs( &connection_, &TestConnection::SendCryptoStreamData))); } ForceWillingAndAbleToWriteOnceForDeferSending(); ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL); } EXPECT_EQ(3u, writer_->frame_count()); EXPECT_TRUE(writer_->stop_waiting_frames().empty()); if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_EQ(1u, writer_->stream_frames().size()); } else { EXPECT_EQ(1u, writer_->crypto_frames().size()); } EXPECT_EQ(1u, writer_->padding_frames().size()); ASSERT_FALSE(writer_->ack_frames().empty()); EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front())); EXPECT_FALSE(connection_.HasPendingAcks()); } TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); connection_.SendStreamDataWithString( GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo", 0, NO_FIN); connection_.SendStreamDataWithString( GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo", 3, NO_FIN); QuicAckFrame ack = ConstructAckFrame(2, 1); LostPacketVector lost_packets; lost_packets.push_back( LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize)); EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _)) .WillOnce(DoAll(SetArgPointee<5>(lost_packets), Return(LossDetectionInterface::DetectionStats()))); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); ProcessAckPacket(&ack); size_t padding_frame_count = writer_->padding_frames().size(); EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count()); EXPECT_EQ(1u, writer_->stream_frames().size()); writer_->Reset(); ack = ConstructAckFrame(3, 1); EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); ProcessAckPacket(&ack); EXPECT_EQ(0u, writer_->frame_count()); EXPECT_FALSE(connection_.HasPendingAcks()); writer_->Reset(); ack = ConstructAckFrame(3, 1); EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _)); EXPECT_CALL(visitor_, OnCanWrite()) .WillOnce(IgnoreResult(InvokeWithoutArgs( &connection_, &TestConnection::EnsureWritableAndSendStreamData5))); ForceWillingAndAbleToWriteOnceForDeferSending(); ProcessAckPacket(&ack); EXPECT_EQ(1u, writer_->frame_count()); EXPECT_TRUE(writer_->ack_frames().empty()); EXPECT_EQ(1u, writer_->stream_frames().size()); EXPECT_FALSE(connection_.HasPendingAcks()); } TEST_P(QuicConnectionTest, NoAckSentForClose) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); ProcessPacket(1); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER)) .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); ProcessClosePacket(2); EXPECT_EQ(1, connection_close_frame_count_); EXPECT_THAT(saved_connection_close_frame_.quic_error_code, IsError(QUIC_PEER_GOING_AWAY)); } TEST_P(QuicConnectionTest, SendWhenDisconnected) { EXPECT_TRUE(connection_.connected()); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)) .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame)); connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason", ConnectionCloseBehavior::SILENT_CLOSE); EXPECT_FALSE(connection_.connected()); EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA)); EXPECT_EQ(DISCARD, connection_.GetSerializedPacketFate( false, ENCRYPTION_INITIAL)); } TEST_P(QuicConnectionTest, SendConnectivityProbingWhenDisconnected) { if (!IsDefaultTestConfiguration()) { return; } EXPECT_TRUE(connection_.connected()); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)) .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame)); connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason", ConnectionCloseBehavior::SILENT_CLOSE); EXPECT_FALSE(connection_.connected()); EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _)) .Times(0); EXPECT_QUIC_BUG(connection_.SendConnectivityProbingPacket( writer_.get(), connection_.peer_address()), "Not sending connectivity probing packet as connection is " "disconnected."); EXPECT_EQ(1, connection_close_frame_count_); EXPECT_THAT(saved_connection_close_frame_.quic_error_code, IsError(QUIC_PEER_GOING_AWAY)); } TEST_P(QuicConnectionTest, WriteBlockedAfterClientSendsConnectivityProbe) { PathProbeTestInit(Perspective::IS_CLIENT); TestPacketWriter probing_writer(version(), &clock_, Perspective::IS_CLIENT); probing_writer.BlockOnNextWrite(); EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _)) .Times(1); connection_.SendConnectivityProbingPacket(&probing_writer, connection_.peer_address()); } TEST_P(QuicConnectionTest, WriterBlockedAfterServerSendsConnectivityProbe) { PathProbeTestInit(Perspective::IS_SERVER); if (version().SupportsAntiAmplificationLimit()) { QuicConnectionPeer::SetAddressValidated(&connection_); } writer_->BlockOnNextWrite(); EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _)) .Times(1); if (VersionHasIetfQuicFrames(GetParam().version.transport_version)) { QuicPathFrameBuffer payload{ {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}}; QuicConnection::ScopedPacketFlusher flusher(&connection_); connection_.SendPathChallenge( payload, connection_.self_address(), connection_.peer_address(), connection_.effective_peer_address(), writer_.get()); } else { connection_.SendConnectivityProbingPacket(writer_.get(), connection_.peer_address()); } } TEST_P(QuicConnectionTest, WriterErrorWhenClientSendsConnectivityProbe) { PathProbeTestInit(Perspective::IS_CLIENT); TestPacketWriter probing_writer(version(), &clock_, Perspective::IS_CLIENT); probing_writer.SetShouldWriteFail(); EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _)) .Times(0); connection_.SendConnectivityProbingPacket(&probing_writer, connection_.peer_address()); } TEST_P(QuicConnectionTest, WriterErrorWhenServerSendsConnectivityProbe) { PathProbeTestInit(Perspective::IS_SERVER); writer_->SetShouldWriteFail(); EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _)) .Times(0); connection_.SendConnectivityProbingPacket(writer_.get(), connection_.peer_address()); } TEST_P(QuicConnectionTest, IetfStatelessReset) { QuicConfig config; QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestStatelessResetToken); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); std::unique_ptr<QuicEncryptedPacket> packet( QuicFramer::BuildIetfStatelessResetPacket(connection_id_, 100, kTestStatelessResetToken)); std::unique_ptr<QuicReceivedPacket> received( ConstructReceivedPacket(*packet, QuicTime::Zero())); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER)) .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame)); connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received); EXPECT_EQ(1, connection_close_frame_count_); EXPECT_THAT(saved_connection_close_frame_.quic_error_code, IsError(QUIC_PUBLIC_RESET)); } TEST_P(QuicConnectionTest, GoAway) { if (VersionHasIetfQuicFrames(GetParam().version.transport_version)) { return; } EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); QuicGoAwayFrame* goaway = new QuicGoAwayFrame(); goaway->last_good_stream_id = 1; goaway->error_code = QUIC_PEER_GOING_AWAY; goaway->reason_phrase = "Going away."; EXPECT_CALL(visitor_, OnGoAway(_)); ProcessGoAwayPacket(goaway); } TEST_P(QuicConnectionTest, WindowUpdate) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); QuicWindowUpdateFrame window_update; window_update.stream_id = 3; window_update.max_data = 1234; EXPECT_CALL(visitor_, OnWindowUpdateFrame(_)); ProcessFramePacket(QuicFrame(window_update)); } TEST_P(QuicConnectionTest, Blocked) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); QuicBlockedFrame blocked; blocked.stream_id = 3; EXPECT_CALL(visitor_, OnBlockedFrame(_)); ProcessFramePacket(QuicFrame(blocked)); EXPECT_EQ(1u, connection_.GetStats().blocked_frames_received); EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent); } TEST_P(QuicConnectionTest, ZeroBytePacket) { EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0); QuicReceivedPacket encrypted(nullptr, 0, QuicTime::Zero()); connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, encrypted); } TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) { ParsedQuicVersionVector versions; for (auto version : AllSupportedVersions()) { if (version != connection_.version()) { versions.push_back(version); } } std::unique_ptr<QuicEncryptedPacket> encrypted( QuicFramer::BuildVersionNegotiationPacket( connection_id_, EmptyQuicConnectionId(), true, connection_.version().HasLengthPrefixedConnectionIds(), versions)); std::unique_ptr<QuicReceivedPacket> received( ConstructReceivedPacket(*encrypted, QuicTime::Zero())); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)) .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received); EXPECT_FALSE(connection_.connected()); EXPECT_EQ(1, connection_close_frame_count_); EXPECT_THAT(saved_connection_close_frame_.quic_error_code, IsError(QUIC_INVALID_VERSION)); } TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiationWithConnectionClose) { EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; QuicTagVector connection_options; connection_options.push_back(kINVC); config.SetClientConnectionOptions(connection_options); connection_.SetFromConfig(config); ParsedQuicVersionVector versions; for (auto version : AllSupportedVersions()) { if (version != connection_.version()) { versions.push_back(version); } } std::unique_ptr<QuicEncryptedPacket> encrypted( QuicFramer::BuildVersionNegotiationPacket( connection_id_, EmptyQuicConnectionId(), true, connection_.version().HasLengthPrefixedConnectionIds(), versions)); std::unique_ptr<QuicReceivedPacket> received( ConstructReceivedPacket(*encrypted, QuicTime::Zero())); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)) .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1u)); connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received); EXPECT_FALSE(connection_.connected()); EXPECT_EQ(1, connection_close_frame_count_); EXPECT_THAT(saved_connection_close_frame_.quic_error_code, IsError(QUIC_INVALID_VERSION)); } TEST_P(QuicConnectionTest, BadVersionNegotiation) { EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)) .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame)); std::unique_ptr<QuicEncryptedPacket> encrypted( QuicFramer::BuildVersionNegotiationPacket( connection_id_, EmptyQuicConnectionId(), true, connection_.version().HasLengthPrefixedConnectionIds(), AllSupportedVersions())); std::unique_ptr<QuicReceivedPacket> received( ConstructReceivedPacket(*encrypted, QuicTime::Zero())); connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received); EXPECT_EQ(1, connection_close_frame_count_); EXPECT_THAT(saved_connection_close_frame_.quic_error_code, IsError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET)); } TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) { QuicPacketHeader header; if (peer_framer_.perspective() == Perspective::IS_SERVER) { header.source_connection_id = connection_id_; header.destination_connection_id_included = CONNECTION_ID_ABSENT; } else { header.destination_connection_id = connection_id_; header.destination_connection_id_included = CONNECTION_ID_ABSENT; } header.packet_number = QuicPacketNumber(1); header.version_flag = false; QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY; QuicConnectionCloseFrame qccf(peer_framer_.transport_version(), kQuicErrorCode, NO_IETF_QUIC_ERROR, "", 0); QuicFrames frames; frames.push_back(QuicFrame(frame1_)); frames.push_back(QuicFrame(&qccf)); std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames)); EXPECT_TRUE(nullptr != packet); char buffer[kMaxOutgoingPacketSize]; size_t encrypted_length = peer_framer_.EncryptPayload( ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer, kMaxOutgoingPacketSize); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER)) .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame)); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); connection_.ProcessUdpPacket( kSelfAddress, kPeerAddress, QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false)); EXPECT_EQ(1, connection_close_frame_count_); EXPECT_THAT(saved_connection_close_frame_.quic_error_code, IsError(QUIC_PEER_GOING_AWAY)); } TEST_P(QuicConnectionTest, SelectMutualVersion) { connection_.SetSupportedVersions(AllSupportedVersions()); connection_.set_version(QuicVersionMin()); EXPECT_EQ(QuicVersionMin(), connection_.version()); ParsedQuicVersionVector supported_versions = AllSupportedVersions(); EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions)); EXPECT_EQ(QuicVersionMax(), connection_.version()); ParsedQuicVersionVector lowest_version_vector; lowest_version_vector.push_back(QuicVersionMin()); EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector)); EXPECT_EQ(QuicVersionMin(), connection_.version()); ParsedQuicVersionVector unsupported_version; unsupported_version.push_back(UnsupportedQuicVersion()); EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version)); } TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) { EXPECT_FALSE(writer_->IsWriteBlocked()); connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN); EXPECT_EQ(0u, connection_.NumQueuedPackets()); EXPECT_EQ(1u, writer_->packets_write_attempts()); TriggerConnectionClose(); EXPECT_LE(2u, writer_->packets_write_attempts()); } TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) { BlockOnNextWrite(); TriggerConnectionClose(); EXPECT_EQ(1u, writer_->packets_write_attempts()); EXPECT_TRUE(writer_->IsWriteBlocked()); } TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) { BlockOnNextWrite(); connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN); EXPECT_EQ(1u, connection_.NumQueuedPackets()); EXPECT_EQ(1u, writer_->packets_write_attempts()); EXPECT_TRUE(writer_->IsWriteBlocked()); TriggerConnectionClose(); EXPECT_EQ(1u, writer_->packets_write_attempts()); } TEST_P(QuicConnectionTest, OnPacketSentDebugVisitor) { PathProbeTestInit(Perspective::IS_CLIENT); MockQuicConnectionDebugVisitor debug_visitor; connection_.set_debug_visitor(&debug_visitor); EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(1); connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN); EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(1); connection_.SendConnectivityProbingPacket(writer_.get(), connection_.peer_address()); } TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) { QuicPacketHeader header; header.packet_number = QuicPacketNumber(1); header.form = IETF_QUIC_LONG_HEADER_PACKET; MockQuicConnectionDebugVisitor debug_visitor; connection_.set_debug_visitor(&debug_visitor); EXPECT_CALL(debug_visitor, OnPacketHeader(Ref(header), _, _)).Times(1); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(1); EXPECT_CALL(debug_visitor, OnSuccessfulVersionNegotiation(_)).Times(1); connection_.OnPacketHeader(header); } TEST_P(QuicConnectionTest, Pacing) { TestConnection server(connection_id_, kPeerAddress, kSelfAddress, helper_.get(), alarm_factory_.get(), writer_.get(), Perspective::IS_SERVER, version(), connection_id_generator_); TestConnection client(connection_id_, kSelfAddress, kPeerAddress, helper_.get(), alarm_factory_.get(), writer_.get(), Perspective::IS_CLIENT, version(), connection_id_generator_); EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing( static_cast<const QuicSentPacketManager*>( &client.sent_packet_manager()))); EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing( static_cast<const QuicSentPacketManager*>( &server.sent_packet_manager()))); } TEST_P(QuicConnectionTest, WindowUpdateInstigateAcks) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); QuicWindowUpdateFrame window_update; window_update.stream_id = 3; window_update.max_data = 1234; EXPECT_CALL(visitor_, OnWindowUpdateFrame(_)); ProcessFramePacket(QuicFrame(window_update)); EXPECT_TRUE(connection_.HasPendingAcks()); } TEST_P(QuicConnectionTest, BlockedFrameInstigateAcks) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); QuicBlockedFrame blocked; blocked.stream_id = 3; EXPECT_CALL(visitor_, OnBlockedFrame(_)); ProcessFramePacket(QuicFrame(blocked)); EXPECT_TRUE(connection_.HasPendingAcks()); } TEST_P(QuicConnectionTest, ReevaluateTimeUntilSendOnAck) { EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; connection_.SetFromConfig(config); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true)); connection_.SendStreamDataWithString( GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo", 0, NO_FIN); connection_.SendStreamDataWithString( GetNthClientInitiatedStreamId(1, connection_.transport_version()), "bar", 3, NO_FIN); connection_.OnCanWrite(); QuicSentPacketManagerPeer::DisablePacerBursts(manager_); QuicTime scheduled_pacing_time = clock_.Now() + QuicTime::Delta::FromMilliseconds(5); QuicSentPacketManagerPeer::SetNextPacedPacketTime(manager_, scheduled_pacing_time); EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false)); connection_.SendStreamDataWithString( GetNthClientInitiatedStreamId(1, connection_.transport_version()), "baz", 6, NO_FIN); EXPECT_FALSE(connection_.GetSendAlarm()->IsSet()); QuicAckFrame ack = InitAckFrame(1); EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true)); ProcessAckPacket(&ack); size_t padding_frame_count = writer_->padding_frames().size(); EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count()); EXPECT_EQ(1u, writer_->stream_frames().size()); EXPECT_TRUE(connection_.GetSendAlarm()->IsSet()); EXPECT_EQ(scheduled_pacing_time, connection_.GetSendAlarm()->deadline()); writer_->Reset(); } TEST_P(QuicConnectionTest, SendAcksImmediately) { if (connection_.SupportsMultiplePacketNumberSpaces()) { return; } EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacket(1); CongestionBlockWrites(); SendAckPacketToPeer(); } TEST_P(QuicConnectionTest, SendPingImmediately) { MockQuicConnectionDebugVisitor debug_visitor; connection_.set_debug_visitor(&debug_visitor); CongestionBlockWrites(); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(1); EXPECT_CALL(debug_visitor, OnPingSent()).Times(1); connection_.SendControlFrame(QuicFrame(QuicPingFrame(1))); EXPECT_FALSE(connection_.HasQueuedData()); } TEST_P(QuicConnectionTest, SendBlockedImmediately) { MockQuicConnectionDebugVisitor debug_visitor; connection_.set_debug_visitor(&debug_visitor); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(1); EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent); connection_.SendControlFrame(QuicFrame(QuicBlockedFrame(1, 3, 0))); EXPECT_EQ(1u, connection_.GetStats().blocked_frames_sent); EXPECT_FALSE(connection_.HasQueuedData()); } TEST_P(QuicConnectionTest, FailedToSendBlockedFrames) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } MockQuicConnectionDebugVisitor debug_visitor; connection_.set_debug_visitor(&debug_visitor); QuicBlockedFrame blocked(1, 3, 0); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(0); EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent); connection_.SendControlFrame(QuicFrame(blocked)); EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent); EXPECT_FALSE(connection_.HasQueuedData()); } TEST_P(QuicConnectionTest, SendingUnencryptedStreamDataFails) { if (!IsDefaultTestConfiguration()) { return; } EXPECT_QUIC_BUG( { EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)) .WillOnce( Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame)); connection_.SaveAndSendStreamData(3, {}, 0, FIN); EXPECT_FALSE(connection_.connected()); EXPECT_EQ(1, connection_close_frame_count_); EXPECT_THAT(saved_connection_close_frame_.quic_error_code, IsError(QUIC_ATTEMPT_TO_SEND_UNENCRYPTED_STREAM_DATA)); }, "Cannot send stream data with level: ENCRYPTION_INITIAL"); } TEST_P(QuicConnectionTest, SetRetransmissionAlarmForCryptoPacket) { EXPECT_TRUE(connection_.connected()); EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.SendCryptoStreamData(); EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); QuicTime retransmission_time = QuicConnectionPeer::GetSentPacketManager(&connection_) ->GetRetransmissionTime(); EXPECT_NE(retransmission_time, clock_.ApproximateNow()); EXPECT_EQ(retransmission_time, connection_.GetRetransmissionAlarm()->deadline()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.GetRetransmissionAlarm()->Fire(); } TEST_P(QuicConnectionTest, PathDegradingDetectionForNonCryptoPackets) { EXPECT_TRUE(connection_.connected()); EXPECT_FALSE(connection_.PathDegradingDetectionInProgress()); EXPECT_FALSE(connection_.IsPathDegrading()); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); connection_.OnHandshakeComplete(); const char data[] = "data"; size_t data_size = strlen(data); QuicStreamOffset offset = 0; for (int i = 0; i < 2; ++i) { connection_.SendStreamDataWithString( GetNthClientInitiatedStreamId(1, connection_.transport_version()), data, offset, NO_FIN); offset += data_size; EXPECT_TRUE(connection_.PathDegradingDetectionInProgress()); QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_) ->GetPathDegradingDelay(); EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline(); connection_.SendStreamDataWithString( GetNthClientInitiatedStreamId(1, connection_.transport_version()), data, offset, NO_FIN); offset += data_size; EXPECT_TRUE(connection_.PathDegradingDetectionInProgress()); EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); if (i == 0) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); } EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); QuicAckFrame frame = InitAckFrame( {{QuicPacketNumber(1u + 2u * i), QuicPacketNumber(2u + 2u * i)}}); ProcessAckPacket(&frame); EXPECT_TRUE(connection_.PathDegradingDetectionInProgress()); delay = QuicConnectionPeer::GetSentPacketManager(&connection_) ->GetPathDegradingDelay(); EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() - clock_.ApproximateNow()); if (i == 0) { clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}}); ProcessAckPacket(&frame); EXPECT_FALSE(connection_.PathDegradingDetectionInProgress()); } else { clock_.AdvanceTime(delay); EXPECT_CALL(visitor_, OnPathDegrading()); connection_.PathDegradingTimeout(); EXPECT_FALSE(connection_.PathDegradingDetectionInProgress()); } } EXPECT_TRUE(connection_.IsPathDegrading()); } TEST_P(QuicConnectionTest, RetransmittableOnWireSetsPingAlarm) { const QuicTime::Delta retransmittable_on_wire_timeout = QuicTime::Delta::FromMilliseconds(50); connection_.set_initial_retransmittable_on_wire_timeout( retransmittable_on_wire_timeout); EXPECT_TRUE(connection_.connected()); EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()) .WillRepeatedly(Return(true)); EXPECT_FALSE(connection_.PathDegradingDetectionInProgress()); EXPECT_FALSE(connection_.IsPathDegrading()); EXPECT_FALSE(connection_.GetPingAlarm()->IsSet()); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); connection_.OnHandshakeComplete(); const char data[] = "data"; size_t data_size = strlen(data); QuicStreamOffset offset = 0; connection_.SendStreamDataWithString(1, data, offset, NO_FIN); offset += data_size; EXPECT_TRUE(connection_.PathDegradingDetectionInProgress()); QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_) ->GetPathDegradingDelay(); EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() - clock_.ApproximateNow()); ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets()); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs); EXPECT_EQ(ping_delay, connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); QuicAckFrame frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}}); ProcessAckPacket(&frame); EXPECT_FALSE(connection_.PathDegradingDetectionInProgress()); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(retransmittable_on_wire_timeout, connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(retransmittable_on_wire_timeout); connection_.GetPingAlarm()->Fire(); ASSERT_TRUE(connection_.PathDegradingDetectionInProgress()); delay = QuicConnectionPeer::GetSentPacketManager(&connection_) ->GetPathDegradingDelay(); EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() - clock_.ApproximateNow()); } TEST_P(QuicConnectionTest, ServerRetransmittableOnWire) { set_perspective(Perspective::IS_SERVER); QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false); SetQuicReloadableFlag(quic_enable_server_on_wire_ping, true); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; QuicTagVector connection_options; connection_options.push_back(kSRWP); config.SetInitialReceivedConnectionOptions(connection_options); connection_.SetFromConfig(config); EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()) .WillRepeatedly(Return(true)); ProcessPacket(1); ASSERT_TRUE(connection_.GetPingAlarm()->IsSet()); QuicTime::Delta ping_delay = QuicTime::Delta::FromMilliseconds(200); EXPECT_EQ(ping_delay, connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10)); connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN); EXPECT_FALSE(connection_.GetPingAlarm()->IsSet()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); QuicAckFrame frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}}); ProcessAckPacket(2, &frame); ASSERT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(ping_delay, connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); } TEST_P(QuicConnectionTest, RetransmittableOnWireSendFirstPacket) { if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) { return; } EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()) .WillRepeatedly(Return(true)); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); const QuicTime::Delta kRetransmittableOnWireTimeout = QuicTime::Delta::FromMilliseconds(200); const QuicTime::Delta kTestRtt = QuicTime::Delta::FromMilliseconds(100); connection_.set_initial_retransmittable_on_wire_timeout( kRetransmittableOnWireTimeout); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; QuicTagVector connection_options; connection_options.push_back(kROWF); config.SetClientConnectionOptions(connection_options); connection_.SetFromConfig(config); connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN); clock_.AdvanceTime(kTestRtt); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); QuicAckFrame frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}}); ProcessAckPacket(&frame); ASSERT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(kRetransmittableOnWireTimeout, connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); EXPECT_EQ(1u, writer_->packets_write_attempts()); clock_.AdvanceTime(kRetransmittableOnWireTimeout); connection_.GetPingAlarm()->Fire(); EXPECT_EQ(2u, writer_->packets_write_attempts()); ASSERT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs), connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); } TEST_P(QuicConnectionTest, RetransmittableOnWireSendRandomBytes) { if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) { return; } EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()) .WillRepeatedly(Return(true)); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); const QuicTime::Delta kRetransmittableOnWireTimeout = QuicTime::Delta::FromMilliseconds(200); const QuicTime::Delta kTestRtt = QuicTime::Delta::FromMilliseconds(100); connection_.set_initial_retransmittable_on_wire_timeout( kRetransmittableOnWireTimeout); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; QuicTagVector connection_options; connection_options.push_back(kROWR); config.SetClientConnectionOptions(connection_options); connection_.SetFromConfig(config); connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN); clock_.AdvanceTime(kTestRtt); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); QuicAckFrame frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}}); ProcessAckPacket(&frame); ASSERT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(kRetransmittableOnWireTimeout, connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); EXPECT_EQ(1u, writer_->packets_write_attempts()); clock_.AdvanceTime(kRetransmittableOnWireTimeout); ExpectNextPacketUnprocessable(); connection_.GetPingAlarm()->Fire(); EXPECT_EQ(2u, writer_->packets_write_attempts()); ASSERT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs), connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); } TEST_P(QuicConnectionTest, RetransmittableOnWireSendRandomBytesWithWriterBlocked) { if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) { return; } EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()) .WillRepeatedly(Return(true)); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); const QuicTime::Delta kRetransmittableOnWireTimeout = QuicTime::Delta::FromMilliseconds(200); const QuicTime::Delta kTestRtt = QuicTime::Delta::FromMilliseconds(100); connection_.set_initial_retransmittable_on_wire_timeout( kRetransmittableOnWireTimeout); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; QuicTagVector connection_options; connection_options.push_back(kROWR); config.SetClientConnectionOptions(connection_options); connection_.SetFromConfig(config); connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN); clock_.AdvanceTime(kTestRtt); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); QuicAckFrame frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}}); ProcessAckPacket(&frame); ASSERT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(kRetransmittableOnWireTimeout, connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); EXPECT_EQ(1u, writer_->packets_write_attempts()); BlockOnNextWrite(); ProcessDataPacket(3); EXPECT_EQ(2u, writer_->packets_write_attempts()); EXPECT_EQ(1u, connection_.NumQueuedPackets()); clock_.AdvanceTime(kRetransmittableOnWireTimeout); connection_.GetPingAlarm()->Fire(); EXPECT_EQ(2u, connection_.NumQueuedPackets()); } TEST_P(QuicConnectionTest, NoPathDegradingDetectionIfPathIsDegrading) { EXPECT_TRUE(connection_.connected()); EXPECT_FALSE(connection_.PathDegradingDetectionInProgress()); EXPECT_FALSE(connection_.IsPathDegrading()); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); connection_.OnHandshakeComplete(); const char data[] = "data"; size_t data_size = strlen(data); QuicStreamOffset offset = 0; connection_.SendStreamDataWithString(1, data, offset, NO_FIN); offset += data_size; EXPECT_TRUE(connection_.PathDegradingDetectionInProgress()); QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_) ->GetPathDegradingDelay(); EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline(); connection_.SendStreamDataWithString(1, data, offset, NO_FIN); offset += data_size; EXPECT_TRUE(connection_.PathDegradingDetectionInProgress()); EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); QuicAckFrame frame = InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}}); ProcessAckPacket(&frame); EXPECT_TRUE(connection_.PathDegradingDetectionInProgress()); delay = QuicConnectionPeer::GetSentPacketManager(&connection_) ->GetPathDegradingDelay(); EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(delay); EXPECT_CALL(visitor_, OnPathDegrading()).Times(1); connection_.PathDegradingTimeout(); EXPECT_FALSE(connection_.PathDegradingDetectionInProgress()); EXPECT_TRUE(connection_.IsPathDegrading()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); EXPECT_FALSE(connection_.PathDegradingDetectionInProgress()); connection_.SendStreamDataWithString(1, data, offset, NO_FIN); offset += data_size; EXPECT_FALSE(connection_.PathDegradingDetectionInProgress()); EXPECT_TRUE(connection_.IsPathDegrading()); } TEST_P(QuicConnectionTest, NoPathDegradingDetectionBeforeHandshakeConfirmed) { EXPECT_TRUE(connection_.connected()); EXPECT_FALSE(connection_.PathDegradingDetectionInProgress()); EXPECT_FALSE(connection_.IsPathDegrading()); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_COMPLETE)); connection_.SendStreamDataWithString(1, "data", 0, NO_FIN); if (GetQuicReloadableFlag( quic_no_path_degrading_before_handshake_confirmed) && connection_.SupportsMultiplePacketNumberSpaces()) { EXPECT_FALSE(connection_.PathDegradingDetectionInProgress()); } else { EXPECT_TRUE(connection_.PathDegradingDetectionInProgress()); } } TEST_P(QuicConnectionTest, UnmarkPathDegradingOnForwardProgress) { EXPECT_TRUE(connection_.connected()); EXPECT_FALSE(connection_.PathDegradingDetectionInProgress()); EXPECT_FALSE(connection_.IsPathDegrading()); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); connection_.OnHandshakeComplete(); const char data[] = "data"; size_t data_size = strlen(data); QuicStreamOffset offset = 0; connection_.SendStreamDataWithString(1, data, offset, NO_FIN); offset += data_size; EXPECT_TRUE(connection_.PathDegradingDetectionInProgress()); QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_) ->GetPathDegradingDelay(); EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline(); connection_.SendStreamDataWithString(1, data, offset, NO_FIN); offset += data_size; EXPECT_TRUE(connection_.PathDegradingDetectionInProgress()); EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); QuicAckFrame frame = InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}}); ProcessAckPacket(&frame); EXPECT_TRUE(connection_.PathDegradingDetectionInProgress()); delay = QuicConnectionPeer::GetSentPacketManager(&connection_) ->GetPathDegradingDelay(); EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(delay); EXPECT_CALL(visitor_, OnPathDegrading()).Times(1); connection_.PathDegradingTimeout(); EXPECT_FALSE(connection_.PathDegradingDetectionInProgress()); EXPECT_TRUE(connection_.IsPathDegrading()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); EXPECT_FALSE(connection_.PathDegradingDetectionInProgress()); connection_.SendStreamDataWithString(1, data, offset, NO_FIN); offset += data_size; EXPECT_FALSE(connection_.PathDegradingDetectionInProgress()); EXPECT_TRUE(connection_.IsPathDegrading()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(1); frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}}); ProcessAckPacket(&frame); EXPECT_EQ(1, connection_.GetStats().num_forward_progress_after_path_degrading); EXPECT_FALSE(connection_.IsPathDegrading()); EXPECT_TRUE(connection_.PathDegradingDetectionInProgress()); } TEST_P(QuicConnectionTest, NoPathDegradingOnServer) { if (connection_.SupportsMultiplePacketNumberSpaces()) { return; } set_perspective(Perspective::IS_SERVER); QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false); EXPECT_FALSE(connection_.IsPathDegrading()); EXPECT_FALSE(connection_.PathDegradingDetectionInProgress()); const char data[] = "data"; connection_.SendStreamDataWithString(1, data, 0, NO_FIN); EXPECT_FALSE(connection_.IsPathDegrading()); EXPECT_FALSE(connection_.PathDegradingDetectionInProgress()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); QuicAckFrame frame = InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}}); ProcessAckPacket(&frame); EXPECT_FALSE(connection_.IsPathDegrading()); EXPECT_FALSE(connection_.PathDegradingDetectionInProgress()); } TEST_P(QuicConnectionTest, NoPathDegradingAfterSendingAck) { if (connection_.SupportsMultiplePacketNumberSpaces()) { return; } EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacket(1); SendAckPacketToPeer(); EXPECT_FALSE(connection_.sent_packet_manager().unacked_packets().empty()); EXPECT_FALSE(connection_.sent_packet_manager().HasInFlightPackets()); EXPECT_FALSE(connection_.IsPathDegrading()); EXPECT_FALSE(connection_.PathDegradingDetectionInProgress()); } TEST_P(QuicConnectionTest, MultipleCallsToCloseConnection) { EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1); connection_.CloseConnection(QUIC_NO_ERROR, "no reason", ConnectionCloseBehavior::SILENT_CLOSE); connection_.CloseConnection(QUIC_NO_ERROR, "no reason", ConnectionCloseBehavior::SILENT_CLOSE); } TEST_P(QuicConnectionTest, ServerReceivesChloOnNonCryptoStream) { set_perspective(Perspective::IS_SERVER); QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false); QuicConnectionPeer::SetAddressValidated(&connection_); CryptoHandshakeMessage message; CryptoFramer framer; message.set_tag(kCHLO); std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message); frame1_.stream_id = 10; frame1_.data_buffer = data->data(); frame1_.data_length = data->length(); if (version().handshake_protocol == PROTOCOL_TLS1_3) { EXPECT_CALL(visitor_, BeforeConnectionCloseSent()); } EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)); ForceProcessFramePacket(QuicFrame(frame1_)); if (VersionHasIetfQuicFrames(version().transport_version)) { TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION); } else { TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY); } } TEST_P(QuicConnectionTest, ClientReceivesRejOnNonCryptoStream) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); CryptoHandshakeMessage message; CryptoFramer framer; message.set_tag(kREJ); std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message); frame1_.stream_id = 10; frame1_.data_buffer = data->data(); frame1_.data_length = data->length(); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)); ForceProcessFramePacket(QuicFrame(frame1_)); if (VersionHasIetfQuicFrames(version().transport_version)) { TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION); } else { TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY); } } TEST_P(QuicConnectionTest, CloseConnectionOnPacketTooLarge) { SimulateNextPacketTooLarge(); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)) .Times(1); connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN); TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR); } TEST_P(QuicConnectionTest, AlwaysGetPacketTooLarge) { AlwaysGetPacketTooLarge(); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)) .Times(1); connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN); TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR); } TEST_P(QuicConnectionTest, CloseConnectionOnQueuedWriteError) { BlockOnNextWrite(); connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN); EXPECT_EQ(1u, connection_.NumQueuedPackets()); AlwaysGetPacketTooLarge(); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)) .Times(1); writer_->SetWritable(); connection_.OnCanWrite(); EXPECT_EQ(0u, connection_.NumQueuedPackets()); TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR); } TEST_P(QuicConnectionTest, SendDataAndBecomeApplicationLimited) { EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1); { InSequence seq; EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)); EXPECT_CALL(visitor_, WillingAndAbleToWrite()) .WillRepeatedly(Return(false)); } connection_.SendStreamData3(); } TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedIfMoreDataAvailable) { EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0); { InSequence seq; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)); EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true)); } connection_.SendStreamData3(); } TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedDueToWriteBlock) { EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0); EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true)); BlockOnNextWrite(); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.SendStreamData3(); writer_->SetWritable(); CongestionBlockWrites(); EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1); connection_.OnCanWrite(); } TEST_P(QuicConnectionTest, DoNotForceSendingAckOnPacketTooLarge) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); ProcessPacket(1); EXPECT_TRUE(connection_.HasPendingAcks()); connection_.GetAckAlarm()->Fire(); EXPECT_CALL(visitor_, OnConnectionClosed(_, _)); SimulateNextPacketTooLarge(); connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN); EXPECT_EQ(1u, writer_->connection_close_frames().size()); EXPECT_TRUE(writer_->ack_frames().empty()); if (writer_->padding_frames().empty()) { EXPECT_EQ(1u, writer_->frame_count()); } else { EXPECT_EQ(2u, writer_->frame_count()); } TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR); } TEST_P(QuicConnectionTest, CloseConnectionAllLevels) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } EXPECT_CALL(visitor_, OnConnectionClosed(_, _)); const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR; connection_.CloseConnection( kQuicErrorCode, "Some random error message", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_)); TestConnectionCloseQuicErrorCode(kQuicErrorCode); EXPECT_EQ(1u, writer_->connection_close_frames().size()); if (!connection_.version().CanSendCoalescedPackets()) { EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_), writer_->connection_close_packets()); EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_), writer_->packets_write_attempts()); return; } EXPECT_EQ(1u, writer_->packets_write_attempts()); EXPECT_EQ(1u, writer_->connection_close_packets()); ASSERT_TRUE(writer_->coalesced_packet() != nullptr); auto packet = writer_->coalesced_packet()->Clone(); writer_->framer()->ProcessPacket(*packet); EXPECT_EQ(1u, writer_->connection_close_packets()); ASSERT_TRUE(writer_->coalesced_packet() == nullptr); } TEST_P(QuicConnectionTest, CloseConnectionOneLevel) { if (connection_.SupportsMultiplePacketNumberSpaces()) { return; } EXPECT_CALL(visitor_, OnConnectionClosed(_, _)); const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR; connection_.CloseConnection( kQuicErrorCode, "Some random error message", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_)); TestConnectionCloseQuicErrorCode(kQuicErrorCode); EXPECT_EQ(1u, writer_->connection_close_frames().size()); EXPECT_EQ(1u, writer_->connection_close_packets()); EXPECT_EQ(1u, writer_->packets_write_attempts()); ASSERT_TRUE(writer_->coalesced_packet() == nullptr); } TEST_P(QuicConnectionTest, DoNotPadServerInitialConnectionClose) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } set_perspective(Perspective::IS_SERVER); EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1); ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL); if (version().handshake_protocol == PROTOCOL_TLS1_3) { EXPECT_CALL(visitor_, BeforeConnectionCloseSent()); } EXPECT_CALL(visitor_, OnConnectionClosed(_, _)); const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR; connection_.CloseConnection( kQuicErrorCode, "Some random error message", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_)); TestConnectionCloseQuicErrorCode(kQuicErrorCode); EXPECT_EQ(1u, writer_->connection_close_frames().size()); EXPECT_TRUE(writer_->padding_frames().empty()); EXPECT_EQ(ENCRYPTION_INITIAL, writer_->framer()->last_decrypted_level()); } TEST_P(QuicConnectionTest, FailedToWriteHandshakePacket) { SimulateNextPacketTooLarge(); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)) .Times(1); connection_.SendCryptoStreamData(); TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR); } TEST_P(QuicConnectionTest, MaxPacingRate) { EXPECT_EQ(0, connection_.MaxPacingRate().ToBytesPerSecond()); connection_.SetMaxPacingRate(QuicBandwidth::FromBytesPerSecond(100)); EXPECT_EQ(100, connection_.MaxPacingRate().ToBytesPerSecond()); } TEST_P(QuicConnectionTest, ClientAlwaysSendConnectionId) { EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN); EXPECT_EQ(CONNECTION_ID_PRESENT, writer_->last_packet_header().destination_connection_id_included); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0); connection_.SetFromConfig(config); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.SendStreamDataWithString(3, "bar", 3, NO_FIN); EXPECT_EQ(CONNECTION_ID_PRESENT, writer_->last_packet_header().destination_connection_id_included); } TEST_P(QuicConnectionTest, PingAfterLastRetransmittablePacketAcked) { const QuicTime::Delta retransmittable_on_wire_timeout = QuicTime::Delta::FromMilliseconds(50); connection_.set_initial_retransmittable_on_wire_timeout( retransmittable_on_wire_timeout); EXPECT_TRUE(connection_.connected()); EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()) .WillRepeatedly(Return(true)); const char data[] = "data"; size_t data_size = strlen(data); QuicStreamOffset offset = 0; clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); EXPECT_FALSE(connection_.GetPingAlarm()->IsSet()); connection_.SendStreamDataWithString(1, data, offset, NO_FIN); offset += data_size; EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets()); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs); EXPECT_EQ(ping_delay, connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); connection_.SendStreamDataWithString(1, data, offset, NO_FIN); offset += data_size; EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); QuicAckFrame frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}}); ProcessAckPacket(&frame); EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets()); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(ping_delay - QuicTime::Delta::FromMilliseconds(10), connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}}); ProcessAckPacket(&frame); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(retransmittable_on_wire_timeout, connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); QuicTime prev_deadline = connection_.GetPingAlarm()->deadline(); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}}); ProcessAckPacket(&frame); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline()); prev_deadline = connection_.GetPingAlarm()->deadline(); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); ProcessPacket(4); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline()); connection_.GetPingAlarm()->Fire(); size_t padding_frame_count = writer_->padding_frames().size(); EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count()); ASSERT_EQ(1u, writer_->ping_frames().size()); } TEST_P(QuicConnectionTest, NoPingIfRetransmittablePacketSent) { const QuicTime::Delta retransmittable_on_wire_timeout = QuicTime::Delta::FromMilliseconds(50); connection_.set_initial_retransmittable_on_wire_timeout( retransmittable_on_wire_timeout); EXPECT_TRUE(connection_.connected()); EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()) .WillRepeatedly(Return(true)); const char data[] = "data"; size_t data_size = strlen(data); QuicStreamOffset offset = 0; clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); EXPECT_FALSE(connection_.GetPingAlarm()->IsSet()); connection_.SendStreamDataWithString(1, data, offset, NO_FIN); offset += data_size; EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets()); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs); EXPECT_EQ(ping_delay, connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); QuicAckFrame frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}}); ProcessAckPacket(&frame); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(retransmittable_on_wire_timeout, connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); connection_.SendStreamDataWithString(1, data, offset, NO_FIN); offset += data_size; EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}}); ProcessAckPacket(&frame); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(retransmittable_on_wire_timeout, connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); writer_->Reset(); connection_.GetPingAlarm()->Fire(); size_t padding_frame_count = writer_->padding_frames().size(); EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count()); ASSERT_EQ(1u, writer_->ping_frames().size()); } TEST_P(QuicConnectionTest, BackOffRetransmittableOnWireTimeout) { int max_aggressive_retransmittable_on_wire_ping_count = 5; SetQuicFlag(quic_max_aggressive_retransmittable_on_wire_ping_count, max_aggressive_retransmittable_on_wire_ping_count); const QuicTime::Delta initial_retransmittable_on_wire_timeout = QuicTime::Delta::FromMilliseconds(200); connection_.set_initial_retransmittable_on_wire_timeout( initial_retransmittable_on_wire_timeout); EXPECT_TRUE(connection_.connected()); EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()) .WillRepeatedly(Return(true)); const char data[] = "data"; clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); EXPECT_FALSE(connection_.GetPingAlarm()->IsSet()); connection_.SendStreamDataWithString(1, data, 0, NO_FIN); EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets()); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs), connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber()); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)) .Times(AnyNumber()); for (int i = 0; i <= max_aggressive_retransmittable_on_wire_ping_count; i++) { clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); QuicPacketNumber ack_num = creator_->packet_number(); QuicAckFrame frame = InitAckFrame( {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}}); ProcessAckPacket(&frame); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(initial_retransmittable_on_wire_timeout, connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); writer_->Reset(); clock_.AdvanceTime(initial_retransmittable_on_wire_timeout); connection_.GetPingAlarm()->Fire(); } QuicTime::Delta retransmittable_on_wire_timeout = initial_retransmittable_on_wire_timeout; while (retransmittable_on_wire_timeout * 2 < QuicTime::Delta::FromSeconds(kPingTimeoutSecs)) { retransmittable_on_wire_timeout = retransmittable_on_wire_timeout * 2; clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); QuicPacketNumber ack_num = creator_->packet_number(); QuicAckFrame frame = InitAckFrame( {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}}); ProcessAckPacket(&frame); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(retransmittable_on_wire_timeout, connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); writer_->Reset(); clock_.AdvanceTime(retransmittable_on_wire_timeout); connection_.GetPingAlarm()->Fire(); } EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs), connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); QuicPacketNumber ack_num = creator_->packet_number(); QuicAckFrame frame = InitAckFrame( {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}}); ProcessAckPacket(&frame); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs) - QuicTime::Delta::FromMilliseconds(5), connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); } TEST_P(QuicConnectionTest, ResetBackOffRetransmitableOnWireTimeout) { int max_aggressive_retransmittable_on_wire_ping_count = 3; SetQuicFlag(quic_max_aggressive_retransmittable_on_wire_ping_count, 3); const QuicTime::Delta initial_retransmittable_on_wire_timeout = QuicTime::Delta::FromMilliseconds(200); connection_.set_initial_retransmittable_on_wire_timeout( initial_retransmittable_on_wire_timeout); EXPECT_TRUE(connection_.connected()); EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()) .WillRepeatedly(Return(true)); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber()); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)) .Times(AnyNumber()); const char data[] = "data"; clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); EXPECT_FALSE(connection_.GetPingAlarm()->IsSet()); connection_.SendStreamDataWithString(1, data, 0, NO_FIN); EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets()); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs), connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); { clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); QuicAckFrame frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}}); ProcessAckPacket(&frame); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(initial_retransmittable_on_wire_timeout, connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); } writer_->Reset(); clock_.AdvanceTime(initial_retransmittable_on_wire_timeout); connection_.GetPingAlarm()->Fire(); { clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); QuicPacketNumber ack_num = creator_->packet_number(); QuicAckFrame frame = InitAckFrame( {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}}); ProcessAckPacket(&frame); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(initial_retransmittable_on_wire_timeout, connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); } EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacket(peer_creator_.packet_number() + 1); QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, peer_creator_.packet_number() + 1); EXPECT_EQ(initial_retransmittable_on_wire_timeout, connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(initial_retransmittable_on_wire_timeout); connection_.GetPingAlarm()->Fire(); for (int i = 0; i < max_aggressive_retransmittable_on_wire_ping_count; i++) { const QuicPacketNumber ack_num = creator_->packet_number(); QuicAckFrame frame = InitAckFrame( {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}}); ProcessAckPacket(&frame); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(initial_retransmittable_on_wire_timeout, connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); writer_->Reset(); clock_.AdvanceTime(initial_retransmittable_on_wire_timeout); connection_.GetPingAlarm()->Fire(); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); } { const QuicPacketNumber ack_num = creator_->packet_number(); QuicAckFrame frame = InitAckFrame( {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}}); ProcessAckPacket(&frame); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(initial_retransmittable_on_wire_timeout * 2, connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); } writer_->Reset(); clock_.AdvanceTime(2 * initial_retransmittable_on_wire_timeout); connection_.GetPingAlarm()->Fire(); { EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); ProcessDataPacket(peer_creator_.packet_number() + 1); QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, peer_creator_.packet_number() + 1); const QuicPacketNumber ack_num = creator_->packet_number(); QuicAckFrame frame = InitAckFrame( {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}}); ProcessAckPacket(&frame); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(initial_retransmittable_on_wire_timeout, connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); } } TEST_P(QuicConnectionTest, RetransmittableOnWirePingLimit) { static constexpr int kMaxRetransmittableOnWirePingCount = 3; SetQuicFlag(quic_max_retransmittable_on_wire_ping_count, kMaxRetransmittableOnWirePingCount); static constexpr QuicTime::Delta initial_retransmittable_on_wire_timeout = QuicTime::Delta::FromMilliseconds(200); static constexpr QuicTime::Delta short_delay = QuicTime::Delta::FromMilliseconds(5); ASSERT_LT(short_delay * 10, initial_retransmittable_on_wire_timeout); connection_.set_initial_retransmittable_on_wire_timeout( initial_retransmittable_on_wire_timeout); EXPECT_TRUE(connection_.connected()); EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()) .WillRepeatedly(Return(true)); const char data[] = "data"; clock_.AdvanceTime(short_delay); EXPECT_FALSE(connection_.GetPingAlarm()->IsSet()); connection_.SendStreamDataWithString(1, data, 0, NO_FIN); EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets()); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs), connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber()); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)) .Times(AnyNumber()); for (int i = 0; i <= kMaxRetransmittableOnWirePingCount; i++) { clock_.AdvanceTime(short_delay); QuicPacketNumber ack_num = creator_->packet_number(); QuicAckFrame frame = InitAckFrame( {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}}); ProcessAckPacket(&frame); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(initial_retransmittable_on_wire_timeout, connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); writer_->Reset(); clock_.AdvanceTime(initial_retransmittable_on_wire_timeout); connection_.GetPingAlarm()->Fire(); } QuicPacketNumber ack_num = creator_->packet_number(); QuicAckFrame frame = InitAckFrame( {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}}); ProcessAckPacket(&frame); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs), connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); } TEST_P(QuicConnectionTest, ValidStatelessResetToken) { const StatelessResetToken kTestToken{0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1}; const StatelessResetToken kWrongTestToken{0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 2}; QuicConfig config; EXPECT_FALSE(connection_.IsValidStatelessResetToken(kTestToken)); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(2); QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken); connection_.SetFromConfig(config); EXPECT_FALSE(connection_.IsValidStatelessResetToken(kWrongTestToken)); QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken); connection_.SetFromConfig(config); EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestToken)); } TEST_P(QuicConnectionTest, WriteBlockedWithInvalidAck) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0); BlockOnNextWrite(); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.SendStreamDataWithString(5, "foo", 0, FIN); QuicAckFrame frame = InitAckFrame(1); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _)); ProcessAckPacket(1, &frame); EXPECT_EQ(0, connection_close_frame_count_); } TEST_P(QuicConnectionTest, SendMessage) { if (connection_.version().UsesTls()) { QuicConfig config; QuicConfigPeer::SetReceivedMaxDatagramFrameSize( &config, kMaxAcceptedDatagramFrameSize); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); } std::string message(connection_.GetCurrentLargestMessagePayload() * 2, 'a'); quiche::QuicheMemSlice slice; { QuicConnection::ScopedPacketFlusher flusher(&connection_); connection_.SendStreamData3(); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2); slice = MemSliceFromString(absl::string_view( message.data(), connection_.GetCurrentLargestMessagePayload())); EXPECT_EQ(MESSAGE_STATUS_SUCCESS, connection_.SendMessage(1, absl::MakeSpan(&slice, 1), false)); } EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false)); slice = MemSliceFromString("message"); EXPECT_EQ(MESSAGE_STATUS_BLOCKED, connection_.SendMessage(2, absl::MakeSpan(&slice, 1), false)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); slice = MemSliceFromString(absl::string_view( message.data(), connection_.GetCurrentLargestMessagePayload() + 1)); EXPECT_EQ(MESSAGE_STATUS_TOO_LARGE, connection_.SendMessage(3, absl::MakeSpan(&slice, 1), false)); } TEST_P(QuicConnectionTest, GetCurrentLargestMessagePayload) { QuicPacketLength expected_largest_payload = 1215; if (connection_.version().SendsVariableLengthPacketNumberInLongHeader()) { expected_largest_payload += 3; } if (connection_.version().HasLongHeaderLengths()) { expected_largest_payload -= 2; } if (connection_.version().HasLengthPrefixedConnectionIds()) { expected_largest_payload -= 1; } if (connection_.version().UsesTls()) { EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0); QuicConfig config; QuicConfigPeer::SetReceivedMaxDatagramFrameSize( &config, kMaxAcceptedDatagramFrameSize); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), expected_largest_payload); } else { EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), expected_largest_payload); } } TEST_P(QuicConnectionTest, GetGuaranteedLargestMessagePayload) { QuicPacketLength expected_largest_payload = 1215; if (connection_.version().HasLongHeaderLengths()) { expected_largest_payload -= 2; } if (connection_.version().HasLengthPrefixedConnectionIds()) { expected_largest_payload -= 1; } if (connection_.version().UsesTls()) { EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0); QuicConfig config; QuicConfigPeer::SetReceivedMaxDatagramFrameSize( &config, kMaxAcceptedDatagramFrameSize); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), expected_largest_payload); } else { EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), expected_largest_payload); } } TEST_P(QuicConnectionTest, LimitedLargestMessagePayload) { if (!connection_.version().UsesTls()) { return; } constexpr QuicPacketLength kFrameSizeLimit = 1000; constexpr QuicPacketLength kPayloadSizeLimit = kFrameSizeLimit - kQuicFrameTypeSize; EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0); EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0); QuicConfig config; QuicConfigPeer::SetReceivedMaxDatagramFrameSize(&config, kFrameSizeLimit); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), kPayloadSizeLimit); EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), kPayloadSizeLimit); } TEST_P(QuicConnectionTest, ServerResponseToPathChallenge) { if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) { return; } PathProbeTestInit(Perspective::IS_SERVER); QuicConnectionPeer::SetAddressValidated(&connection_); QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.SendConnectivityProbingPacket(writer_.get(), connection_.peer_address()); ASSERT_GE(writer_->path_challenge_frames().size(), 1u); QuicPathFrameBuffer challenge_data = writer_->path_challenge_frames().front().data_buffer; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); EXPECT_TRUE(connection_.OnPathChallengeFrame( writer_->path_challenge_frames().front())); EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front())); creator_->FlushCurrentPacket(); EXPECT_EQ(1u, writer_->path_response_frames().size()); EXPECT_EQ(0, memcmp(&challenge_data, &(writer_->path_response_frames().front().data_buffer), sizeof(challenge_data))); } TEST_P(QuicConnectionTest, ClientResponseToPathChallengeOnDefaulSocket) { if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) { return; } PathProbeTestInit(Perspective::IS_CLIENT); QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.SendConnectivityProbingPacket(writer_.get(), connection_.peer_address()); ASSERT_GE(writer_->path_challenge_frames().size(), 1u); QuicPathFrameBuffer challenge_data = writer_->path_challenge_frames().front().data_buffer; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); EXPECT_TRUE(connection_.OnPathChallengeFrame( writer_->path_challenge_frames().front())); EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front())); creator_->FlushCurrentPacket(); EXPECT_EQ(1u, writer_->path_response_frames().size()); EXPECT_EQ(0, memcmp(&challenge_data, &(writer_->path_response_frames().front().data_buffer), sizeof(challenge_data))); } TEST_P(QuicConnectionTest, ClientResponseToPathChallengeOnAlternativeSocket) { if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) { return; } PathProbeTestInit(Perspective::IS_CLIENT); QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false); QuicSocketAddress kNewSelfAddress(QuicIpAddress::Loopback6(), 23456); TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(AtLeast(1u)) .WillOnce(Invoke([&]() { EXPECT_EQ(1u, new_writer.packets_write_attempts()); EXPECT_EQ(1u, new_writer.path_challenge_frames().size()); EXPECT_EQ(1u, new_writer.padding_frames().size()); EXPECT_EQ(kNewSelfAddress.host(), new_writer.last_write_source_address()); })); bool success = false; connection_.ValidatePath( std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress, connection_.peer_address(), &new_writer), std::make_unique<TestValidationResultDelegate>( &connection_, kNewSelfAddress, connection_.peer_address(), &success), PathValidationReason::kReasonUnknown); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(AtLeast(1u)) .WillOnce(Invoke([&]() { EXPECT_EQ(2u, new_writer.packets_write_attempts()); EXPECT_EQ(1u, new_writer.path_response_frames().size()); EXPECT_EQ(1u, new_writer.padding_frames().size()); EXPECT_EQ(kNewSelfAddress.host(), new_writer.last_write_source_address()); })) .WillRepeatedly(DoDefault()); ; std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket(); std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket( QuicEncryptedPacket(probing_packet->encrypted_buffer, probing_packet->encrypted_length), clock_.Now())); ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received); QuicSocketAddress kNewerSelfAddress(QuicIpAddress::Loopback6(), 34567); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u); ProcessReceivedPacket(kNewerSelfAddress, kPeerAddress, *received); } TEST_P(QuicConnectionTest, RestartPathDegradingDetectionAfterMigrationWithProbe) { if (!version().HasIetfQuicFrames() && GetQuicReloadableFlag(quic_ignore_gquic_probing)) { return; } EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); PathProbeTestInit(Perspective::IS_CLIENT); const char data[] = "data"; size_t data_size = strlen(data); QuicStreamOffset offset = 0; connection_.SendStreamDataWithString(1, data, offset, NO_FIN); offset += data_size; EXPECT_TRUE(connection_.PathDegradingDetectionInProgress()); EXPECT_FALSE(connection_.IsPathDegrading()); QuicTime ddl = connection_.GetBlackholeDetectorAlarm()->deadline(); clock_.AdvanceTime(ddl - clock_.ApproximateNow()); EXPECT_CALL(visitor_, OnPathDegrading()).Times(1); connection_.PathDegradingTimeout(); EXPECT_TRUE(connection_.IsPathDegrading()); EXPECT_FALSE(connection_.PathDegradingDetectionInProgress()); if (!GetParam().version.HasIetfQuicFrames()) { clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); TestPacketWriter probing_writer(version(), &clock_, Perspective::IS_CLIENT); connection_.SendConnectivityProbingPacket(&probing_writer, connection_.peer_address()); EXPECT_FALSE(connection_.PathDegradingDetectionInProgress()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20)); EXPECT_CALL(visitor_, OnPacketReceived(_, _, true)) .Times(1); const QuicSocketAddress kNewSelfAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), 23456); std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket(); std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket( QuicEncryptedPacket(probing_packet->encrypted_buffer, probing_packet->encrypted_length), clock_.Now())); uint64_t num_probing_received = connection_.GetStats().num_connectivity_probing_received; ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received); EXPECT_EQ(num_probing_received + (GetQuicReloadableFlag(quic_ignore_gquic_probing) ? 0u : 1u), connection_.GetStats().num_connectivity_probing_received); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); EXPECT_TRUE(connection_.IsPathDegrading()); } EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(1); connection_.OnSuccessfulMigration( true); EXPECT_FALSE(connection_.IsPathDegrading()); EXPECT_TRUE(connection_.PathDegradingDetectionInProgress()); } TEST_P(QuicConnectionTest, ClientsResetCwndAfterConnectionMigration) { if (!GetParam().version.HasIetfQuicFrames()) { return; } EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); PathProbeTestInit(Perspective::IS_CLIENT); EXPECT_EQ(kSelfAddress, connection_.self_address()); 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()); const SendAlgorithmInterface* send_algorithm = manager_->GetSendAlgorithm(); const QuicSocketAddress kNewSelfAddress = QuicSocketAddress(QuicIpAddress::Loopback4(), 23456); TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); connection_.MigratePath(kNewSelfAddress, connection_.peer_address(), &new_writer, false); EXPECT_EQ(default_init_rtt, manager_->GetRttStats()->initial_rtt()); EXPECT_EQ(0u, manager_->GetConsecutivePtoCount()); EXPECT_NE(send_algorithm, manager_->GetSendAlgorithm()); } TEST_P(QuicConnectionTest, DoNotScheduleSpuriousAckAlarm) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1)); writer_->SetWriteBlocked(); ProcessPacket(1); EXPECT_TRUE(connection_.HasPendingAcks()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); connection_.GetAckAlarm()->Fire(); writer_->SetWritable(); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); ProcessPacket(2); EXPECT_FALSE(connection_.HasPendingAcks()); } TEST_P(QuicConnectionTest, DisablePacingOffloadConnectionOptions) { EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_)); writer_->set_supports_release_time(true); QuicConfig config; EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); EXPECT_TRUE(QuicConnectionPeer::SupportsReleaseTime(&connection_)); QuicTagVector connection_options; connection_options.push_back(kNPCO); config.SetConnectionOptionsToSend(connection_options); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_)); } TEST_P(QuicConnectionTest, OrphanPathResponse) { QuicPathFrameBuffer data = {{0, 1, 2, 3, 4, 5, 6, 7}}; QuicPathResponseFrame frame(99, data); EXPECT_TRUE(connection_.OnPathResponseFrame(frame)); EXPECT_NE(QuicConnection::FIRST_FRAME_IS_PING, QuicConnectionPeer::GetCurrentPacketContent(&connection_)); } TEST_P(QuicConnectionTest, AcceptPacketNumberZero) { if (!VersionHasIetfQuicFrames(version().transport_version)) { return; } QuicFramerPeer::SetFirstSendingPacketNumber(writer_->framer()->framer(), 0); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); ProcessPacket(0); EXPECT_EQ(QuicPacketNumber(0), LargestAcked(connection_.ack_frame())); EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals()); ProcessPacket(1); EXPECT_EQ(QuicPacketNumber(1), LargestAcked(connection_.ack_frame())); EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals()); ProcessPacket(2); EXPECT_EQ(QuicPacketNumber(2), LargestAcked(connection_.ack_frame())); EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals()); } TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicSending) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } connection_.SendCryptoStreamData(); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); QuicAckFrame frame1 = InitAckFrame(1); ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4); connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0, NO_FIN); connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4, NO_FIN); connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data", 8, NO_FIN); connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data", 12, FIN); EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); QuicAckFrame frame2 = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}, {QuicPacketNumber(4), QuicPacketNumber(6)}}); ProcessFramePacketAtLevel(30, QuicFrame(&frame2), ENCRYPTION_FORWARD_SECURE); } TEST_P(QuicConnectionTest, PeerAcksPacketsInWrongPacketNumberSpace) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(0x01)); connection_.SendCryptoStreamData(); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); QuicAckFrame frame1 = InitAckFrame(1); ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2); connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0, NO_FIN); connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4, NO_FIN); QuicAckFrame invalid_ack = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(4)}}); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1)); ProcessFramePacketAtLevel(300, QuicFrame(&invalid_ack), ENCRYPTION_INITIAL); TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA); } TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicReceiving) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); } EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber()); ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL); EXPECT_TRUE(connection_.HasPendingAcks()); peer_framer_.SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE)); SetDecrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE)); ProcessDataPacketAtLevel(1000, false, ENCRYPTION_FORWARD_SECURE); EXPECT_TRUE(connection_.HasPendingAcks()); connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data", 0, NO_FIN); EXPECT_EQ(2u, writer_->frame_count()); EXPECT_TRUE(connection_.HasPendingAcks()); ProcessDataPacketAtLevel(1001, false, ENCRYPTION_FORWARD_SECURE); clock_.AdvanceTime(DefaultRetransmissionTime()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2); connection_.SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE)); connection_.GetAckAlarm()->Fire(); EXPECT_FALSE(connection_.HasPendingAcks()); ProcessDataPacketAtLevel(1002, false, ENCRYPTION_FORWARD_SECURE); EXPECT_TRUE(connection_.HasPendingAcks()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); ProcessDataPacket(1003); EXPECT_FALSE(connection_.HasPendingAcks()); } TEST_P(QuicConnectionTest, CancelAckAlarmOnWriteBlocked) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); } EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber()); ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL); EXPECT_TRUE(connection_.HasPendingAcks()); peer_framer_.SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT)); SetDecrypter(ENCRYPTION_ZERO_RTT, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT)); ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT); EXPECT_TRUE(connection_.HasPendingAcks()); writer_->SetWriteBlocked(); EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber()); clock_.AdvanceTime(DefaultDelayedAckTime()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(0x02)); connection_.GetAckAlarm()->Fire(); EXPECT_FALSE(connection_.HasPendingAcks()); writer_->SetWritable(); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2); connection_.OnCanWrite(); EXPECT_FALSE(connection_.HasPendingAcks()); } TEST_P(QuicConnectionTest, ValidClientConnectionId) { if (!framer_.version().SupportsClientConnectionIds()) { return; } EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); SetClientConnectionId(TestConnectionId(0x33)); QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE); header.destination_connection_id = TestConnectionId(0x33); header.destination_connection_id_included = CONNECTION_ID_PRESENT; header.source_connection_id_included = CONNECTION_ID_ABSENT; QuicFrames frames; QuicPingFrame ping_frame; QuicPaddingFrame padding_frame; frames.push_back(QuicFrame(ping_frame)); frames.push_back(QuicFrame(padding_frame)); std::unique_ptr<QuicPacket> packet = BuildUnsizedDataPacket(&peer_framer_, header, frames); char buffer[kMaxOutgoingPacketSize]; size_t encrypted_length = peer_framer_.EncryptPayload( ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer, kMaxOutgoingPacketSize); QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(), false); EXPECT_EQ(0u, connection_.GetStats().packets_dropped); ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet); EXPECT_EQ(0u, connection_.GetStats().packets_dropped); } TEST_P(QuicConnectionTest, InvalidClientConnectionId) { if (!framer_.version().SupportsClientConnectionIds()) { return; } SetClientConnectionId(TestConnectionId(0x33)); QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE); header.destination_connection_id = TestConnectionId(0xbad); header.destination_connection_id_included = CONNECTION_ID_PRESENT; header.source_connection_id_included = CONNECTION_ID_ABSENT; QuicFrames frames; QuicPingFrame ping_frame; QuicPaddingFrame padding_frame; frames.push_back(QuicFrame(ping_frame)); frames.push_back(QuicFrame(padding_frame)); std::unique_ptr<QuicPacket> packet = BuildUnsizedDataPacket(&peer_framer_, header, frames); char buffer[kMaxOutgoingPacketSize]; size_t encrypted_length = peer_framer_.EncryptPayload( ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer, kMaxOutgoingPacketSize); QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(), false); EXPECT_EQ(0u, connection_.GetStats().packets_dropped); ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet); EXPECT_EQ(1u, connection_.GetStats().packets_dropped); } TEST_P(QuicConnectionTest, UpdateClientConnectionIdFromFirstPacket) { if (!framer_.version().SupportsClientConnectionIds()) { return; } set_perspective(Perspective::IS_SERVER); QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL); header.source_connection_id = TestConnectionId(0x33); header.source_connection_id_included = CONNECTION_ID_PRESENT; QuicFrames frames; QuicPingFrame ping_frame; QuicPaddingFrame padding_frame; frames.push_back(QuicFrame(ping_frame)); frames.push_back(QuicFrame(padding_frame)); std::unique_ptr<QuicPacket> packet = BuildUnsizedDataPacket(&peer_framer_, header, frames); char buffer[kMaxOutgoingPacketSize]; size_t encrypted_length = peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1), *packet, buffer, kMaxOutgoingPacketSize); QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(), false); EXPECT_EQ(0u, connection_.GetStats().packets_dropped); ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet); EXPECT_EQ(0u, connection_.GetStats().packets_dropped); EXPECT_EQ(TestConnectionId(0x33), connection_.client_connection_id()); } void QuicConnectionTest::TestReplaceConnectionIdFromInitial() { if (!framer_.version().AllowsVariableLengthConnectionIds()) { return; } EXPECT_TRUE(connection_.connected()); EXPECT_EQ(0u, connection_.GetStats().packets_dropped); EXPECT_NE(TestConnectionId(0x33), connection_.connection_id()); { QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL); header.source_connection_id = TestConnectionId(0x33); header.source_connection_id_included = CONNECTION_ID_PRESENT; QuicFrames frames; QuicPingFrame ping_frame; QuicPaddingFrame padding_frame; frames.push_back(QuicFrame(ping_frame)); frames.push_back(QuicFrame(padding_frame)); std::unique_ptr<QuicPacket> packet = BuildUnsizedDataPacket(&peer_framer_, header, frames); char buffer[kMaxOutgoingPacketSize]; size_t encrypted_length = peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1), *packet, buffer, kMaxOutgoingPacketSize); QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(), false); ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet); } EXPECT_TRUE(connection_.connected()); EXPECT_EQ(0u, connection_.GetStats().packets_dropped); EXPECT_EQ(TestConnectionId(0x33), connection_.connection_id()); { QuicPacketHeader header = ConstructPacketHeader(2, ENCRYPTION_INITIAL); header.source_connection_id = TestConnectionId(0x66); header.source_connection_id_included = CONNECTION_ID_PRESENT; QuicFrames frames; QuicPingFrame ping_frame; QuicPaddingFrame padding_frame; frames.push_back(QuicFrame(ping_frame)); frames.push_back(QuicFrame(padding_frame)); std::unique_ptr<QuicPacket> packet = BuildUnsizedDataPacket(&peer_framer_, header, frames); char buffer[kMaxOutgoingPacketSize]; size_t encrypted_length = peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(2), *packet, buffer, kMaxOutgoingPacketSize); QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(), false); ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet); } EXPECT_TRUE(connection_.connected()); EXPECT_EQ(1u, connection_.GetStats().packets_dropped); EXPECT_EQ(TestConnectionId(0x33), connection_.connection_id()); } TEST_P(QuicConnectionTest, ReplaceServerConnectionIdFromInitial) { TestReplaceConnectionIdFromInitial(); } TEST_P(QuicConnectionTest, ReplaceServerConnectionIdFromRetryAndInitial) { TestClientRetryHandling(false, false, false, false, false); peer_framer_.SetInitialObfuscators(connection_.connection_id()); TestReplaceConnectionIdFromInitial(); } TEST_P(QuicConnectionTest, CheckConnectedBeforeFlush) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(visitor_, OnConnectionClosed(_, _)); EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective()); const QuicErrorCode kErrorCode = QUIC_INTERNAL_ERROR; std::unique_ptr<QuicConnectionCloseFrame> connection_close_frame( new QuicConnectionCloseFrame(connection_.transport_version(), kErrorCode, NO_IETF_QUIC_ERROR, "", 0)); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); } else { EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber()); } ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress, ENCRYPTION_INITIAL); EXPECT_TRUE(connection_.HasPendingAcks()); ProcessFramePacketWithAddresses(QuicFrame(connection_close_frame.release()), kSelfAddress, kPeerAddress, ENCRYPTION_INITIAL); EXPECT_FALSE(connection_.HasPendingAcks()); } TEST_P(QuicConnectionTest, CoalescedPacket) { if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) { return; } EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_TRUE(connection_.connected()); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3); } else { EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3); } uint64_t packet_numbers[3] = {1, 2, 3}; EncryptionLevel encryption_levels[3] = { ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE}; char buffer[kMaxOutgoingPacketSize] = {}; size_t total_encrypted_length = 0; for (int i = 0; i < 3; i++) { QuicPacketHeader header = ConstructPacketHeader(packet_numbers[i], encryption_levels[i]); QuicFrames frames; if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { frames.push_back(QuicFrame(&crypto_frame_)); } else { frames.push_back(QuicFrame(frame1_)); } std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames); peer_creator_.set_encryption_level(encryption_levels[i]); size_t encrypted_length = peer_framer_.EncryptPayload( encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet, buffer + total_encrypted_length, sizeof(buffer) - total_encrypted_length); EXPECT_GT(encrypted_length, 0u); total_encrypted_length += encrypted_length; } connection_.ProcessUdpPacket( kSelfAddress, kPeerAddress, QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false)); if (connection_.GetSendAlarm()->IsSet()) { connection_.GetSendAlarm()->Fire(); } EXPECT_TRUE(connection_.connected()); } TEST_P(QuicConnectionTest, CoalescedPacketThatSavesFrames) { if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) { return; } if (connection_.SupportsMultiplePacketNumberSpaces()) { return; } EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_TRUE(connection_.connected()); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)) .Times(3) .WillRepeatedly([this](const QuicCryptoFrame& ) { connection_.SendControlFrame(QuicFrame(QuicBlockedFrame(1, 3, 0))); }); } else { EXPECT_CALL(visitor_, OnStreamFrame(_)) .Times(3) .WillRepeatedly([this](const QuicStreamFrame& ) { connection_.SendControlFrame(QuicFrame(QuicBlockedFrame(1, 3, 0))); }); } uint64_t packet_numbers[3] = {1, 2, 3}; EncryptionLevel encryption_levels[3] = { ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE}; char buffer[kMaxOutgoingPacketSize] = {}; size_t total_encrypted_length = 0; for (int i = 0; i < 3; i++) { QuicPacketHeader header = ConstructPacketHeader(packet_numbers[i], encryption_levels[i]); QuicFrames frames; if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { frames.push_back(QuicFrame(&crypto_frame_)); } else { frames.push_back(QuicFrame(frame1_)); } std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames); peer_creator_.set_encryption_level(encryption_levels[i]); size_t encrypted_length = peer_framer_.EncryptPayload( encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet, buffer + total_encrypted_length, sizeof(buffer) - total_encrypted_length); EXPECT_GT(encrypted_length, 0u); total_encrypted_length += encrypted_length; } connection_.ProcessUdpPacket( kSelfAddress, kPeerAddress, QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false)); if (connection_.GetSendAlarm()->IsSet()) { connection_.GetSendAlarm()->Fire(); } EXPECT_TRUE(connection_.connected()); SendAckPacketToPeer(); } TEST_P(QuicConnectionTest, RtoAndWriteBlocked) { EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); QuicStreamId stream_id = 2; QuicPacketNumber last_data_packet; SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet); EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); writer_->SetWriteBlocked(); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1)); EXPECT_CALL(visitor_, WillingAndAbleToWrite()) .WillRepeatedly( Invoke(&notifier_, &SimpleSessionNotifier::WillingToWrite)); SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3); connection_.GetRetransmissionAlarm()->Fire(); EXPECT_EQ(0u, connection_.NumQueuedPackets()); } TEST_P(QuicConnectionTest, PtoAndWriteBlocked) { EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); QuicStreamId stream_id = 2; QuicPacketNumber last_data_packet; SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet); SendStreamDataToPeer(4, "foo", 0, NO_FIN, &last_data_packet); EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); writer_->SetWriteBlocked(); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1)); SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.GetRetransmissionAlarm()->Fire(); EXPECT_EQ(1u, connection_.NumQueuedPackets()); } TEST_P(QuicConnectionTest, ProbeTimeout) { QuicConfig config; QuicTagVector connection_options; connection_options.push_back(k2PTO); config.SetConnectionOptionsToSend(connection_options); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); QuicStreamId stream_id = 2; QuicPacketNumber last_packet; SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet); SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet); EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.GetRetransmissionAlarm()->Fire(); EXPECT_EQ(0u, writer_->stream_frames().size()); EXPECT_EQ(1u, writer_->rst_stream_frames().size()); EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); } TEST_P(QuicConnectionTest, CloseConnectionAfter6ClientPTOs) { QuicConfig config; QuicTagVector connection_options; connection_options.push_back(k1PTO); connection_options.push_back(k6PTO); config.SetConnectionOptionsToSend(connection_options); QuicConfigPeer::SetNegotiated(&config, true); if (connection_.version().UsesTls()) { QuicConfigPeer::SetReceivedOriginalConnectionId( &config, connection_.connection_id()); QuicConfigPeer::SetReceivedInitialSourceConnectionId( &config, connection_.connection_id()); } EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) || GetQuicReloadableFlag( quic_no_path_degrading_before_handshake_confirmed)) { EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); } connection_.OnHandshakeComplete(); EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); SendStreamDataToPeer( GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo", 0, FIN, nullptr); for (int i = 0; i < 5; ++i) { EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.GetRetransmissionAlarm()->Fire(); EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet()); EXPECT_TRUE(connection_.connected()); } EXPECT_CALL(visitor_, OnPathDegrading()); connection_.PathDegradingTimeout(); EXPECT_EQ(5u, connection_.sent_packet_manager().GetConsecutivePtoCount()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1)); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)); ASSERT_TRUE(connection_.BlackholeDetectionInProgress()); connection_.GetBlackholeDetectorAlarm()->Fire(); EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet()); EXPECT_FALSE(connection_.connected()); TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS); } TEST_P(QuicConnectionTest, CloseConnectionAfter7ClientPTOs) { QuicConfig config; QuicTagVector connection_options; connection_options.push_back(k2PTO); connection_options.push_back(k7PTO); config.SetConnectionOptionsToSend(connection_options); QuicConfigPeer::SetNegotiated(&config, true); if (connection_.version().UsesTls()) { QuicConfigPeer::SetReceivedOriginalConnectionId( &config, connection_.connection_id()); QuicConfigPeer::SetReceivedInitialSourceConnectionId( &config, connection_.connection_id()); } EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) || GetQuicReloadableFlag( quic_no_path_degrading_before_handshake_confirmed)) { EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); } connection_.OnHandshakeComplete(); EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); SendStreamDataToPeer( GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo", 0, FIN, nullptr); for (int i = 0; i < 6; ++i) { EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)); connection_.GetRetransmissionAlarm()->Fire(); EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet()); EXPECT_TRUE(connection_.connected()); } EXPECT_CALL(visitor_, OnPathDegrading()); connection_.PathDegradingTimeout(); EXPECT_EQ(6u, connection_.sent_packet_manager().GetConsecutivePtoCount()); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1)); ASSERT_TRUE(connection_.BlackholeDetectionInProgress()); connection_.GetBlackholeDetectorAlarm()->Fire(); EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet()); EXPECT_FALSE(connection_.connected()); TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS); } TEST_P(QuicConnectionTest, CloseConnectionAfter8ClientPTOs) { QuicConfig config; QuicTagVector connection_options; connection_options.push_back(k2PTO); connection_options.push_back(k8PTO); QuicConfigPeer::SetNegotiated(&config, true); if (connection_.version().UsesTls()) { QuicConfigPeer::SetReceivedOriginalConnectionId( &config, connection_.connection_id()); QuicConfigPeer::SetReceivedInitialSourceConnectionId( &config, connection_.connection_id()); } config.SetConnectionOptionsToSend(connection_options); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) || GetQuicReloadableFlag( quic_no_path_degrading_before_handshake_confirmed)) { EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); } connection_.OnHandshakeComplete(); EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); SendStreamDataToPeer( GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo", 0, FIN, nullptr); for (int i = 0; i < 7; ++i) { EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)); connection_.GetRetransmissionAlarm()->Fire(); EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet()); EXPECT_TRUE(connection_.connected()); } EXPECT_CALL(visitor_, OnPathDegrading()); connection_.PathDegradingTimeout(); EXPECT_EQ(7u, connection_.sent_packet_manager().GetConsecutivePtoCount()); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1)); ASSERT_TRUE(connection_.BlackholeDetectionInProgress()); connection_.GetBlackholeDetectorAlarm()->Fire(); EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet()); EXPECT_FALSE(connection_.connected()); TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS); } TEST_P(QuicConnectionTest, DeprecateHandshakeMode) { if (!connection_.version().SupportsAntiAmplificationLimit()) { return; } EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); connection_.SendCryptoStreamData(); EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); QuicAckFrame frame1 = InitAckFrame(1); ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL); EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); EXPECT_EQ(0u, connection_.GetStats().pto_count); EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _)); connection_.GetRetransmissionAlarm()->Fire(); EXPECT_EQ(1u, connection_.GetStats().pto_count); EXPECT_EQ(1u, connection_.GetStats().crypto_retransmit_count); EXPECT_EQ(1u, writer_->ping_frames().size()); } TEST_P(QuicConnectionTest, AntiAmplificationLimit) { if (!connection_.version().SupportsAntiAmplificationLimit() || GetQuicFlag(quic_enforce_strict_amplification_factor)) { return; } EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); set_perspective(Perspective::IS_SERVER); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); connection_.SendCryptoDataWithString("foo", 0); EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA)); EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA)); EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); ForceWillingAndAbleToWriteOnceForDeferSending(); ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL); const size_t anti_amplification_factor = GetQuicFlag(quic_anti_amplification_factor); for (size_t i = 1; i < anti_amplification_factor; ++i) { EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.SendCryptoDataWithString("foo", i * 3); EXPECT_EQ(i != anti_amplification_factor - 1, connection_.GetRetransmissionAlarm()->IsSet()); } EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); ForceWillingAndAbleToWriteOnceForDeferSending(); ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL); for (size_t i = anti_amplification_factor + 1; i < anti_amplification_factor * 2; ++i) { EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.SendCryptoDataWithString("foo", i * 3); } EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); connection_.SendCryptoDataWithString("foo", 2 * anti_amplification_factor * 3); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); ForceWillingAndAbleToWriteOnceForDeferSending(); ProcessPacket(3); for (size_t i = 0; i < 100; ++i) { EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN); } } TEST_P(QuicConnectionTest, 3AntiAmplificationLimit) { if (!connection_.version().SupportsAntiAmplificationLimit() || GetQuicFlag(quic_enforce_strict_amplification_factor)) { return; } EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); set_perspective(Perspective::IS_SERVER); QuicConfig config; QuicTagVector connection_options; connection_options.push_back(k3AFF); config.SetInitialReceivedConnectionOptions(connection_options); if (connection_.version().UsesTls()) { QuicConfigPeer::SetReceivedOriginalConnectionId( &config, connection_.connection_id()); QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config, QuicConnectionId()); } EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); connection_.SendCryptoDataWithString("foo", 0); EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA)); EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA)); EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); ForceWillingAndAbleToWriteOnceForDeferSending(); ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL); const size_t anti_amplification_factor = 3; for (size_t i = 1; i < anti_amplification_factor; ++i) { EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.SendCryptoDataWithString("foo", i * 3); EXPECT_EQ(i != anti_amplification_factor - 1, connection_.GetRetransmissionAlarm()->IsSet()); } EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); ForceWillingAndAbleToWriteOnceForDeferSending(); ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL); for (size_t i = anti_amplification_factor + 1; i < anti_amplification_factor * 2; ++i) { EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.SendCryptoDataWithString("foo", i * 3); } EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); connection_.SendCryptoDataWithString("foo", 2 * anti_amplification_factor * 3); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); ForceWillingAndAbleToWriteOnceForDeferSending(); ProcessPacket(3); for (size_t i = 0; i < 100; ++i) { EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN); } } TEST_P(QuicConnectionTest, 10AntiAmplificationLimit) { if (!connection_.version().SupportsAntiAmplificationLimit() || GetQuicFlag(quic_enforce_strict_amplification_factor)) { return; } EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); set_perspective(Perspective::IS_SERVER); QuicConfig config; QuicTagVector connection_options; connection_options.push_back(k10AF); config.SetInitialReceivedConnectionOptions(connection_options); if (connection_.version().UsesTls()) { QuicConfigPeer::SetReceivedOriginalConnectionId( &config, connection_.connection_id()); QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config, QuicConnectionId()); } EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); connection_.SendCryptoDataWithString("foo", 0); EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA)); EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA)); EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); ForceWillingAndAbleToWriteOnceForDeferSending(); ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL); const size_t anti_amplification_factor = 10; for (size_t i = 1; i < anti_amplification_factor; ++i) { EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.SendCryptoDataWithString("foo", i * 3); EXPECT_EQ(i != anti_amplification_factor - 1, connection_.GetRetransmissionAlarm()->IsSet()); } EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); ForceWillingAndAbleToWriteOnceForDeferSending(); ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL); for (size_t i = anti_amplification_factor + 1; i < anti_amplification_factor * 2; ++i) { EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.SendCryptoDataWithString("foo", i * 3); } EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); connection_.SendCryptoDataWithString("foo", 2 * anti_amplification_factor * 3); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); ForceWillingAndAbleToWriteOnceForDeferSending(); ProcessPacket(3); for (size_t i = 0; i < 100; ++i) { EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN); } } TEST_P(QuicConnectionTest, AckPendingWithAmplificationLimited) { if (!connection_.version().SupportsAntiAmplificationLimit()) { return; } EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber()); set_perspective(Perspective::IS_SERVER); connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL); connection_.SetEncrypter( ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); EXPECT_TRUE(connection_.HasPendingAcks()); size_t i = 0; while (connection_.CanWrite(HAS_RETRANSMITTABLE_DATA)) { connection_.SendCryptoDataWithString(std::string(1024, 'a'), i * 1024, ENCRYPTION_HANDSHAKE); ++i; } EXPECT_TRUE(connection_.HasPendingAcks()); clock_.AdvanceTime(connection_.GetAckAlarm()->deadline() - clock_.Now()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); connection_.GetAckAlarm()->Fire(); EXPECT_FALSE(connection_.HasPendingAcks()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL); EXPECT_FALSE(writer_->ack_frames().empty()); } TEST_P(QuicConnectionTest, ConnectionCloseFrameType) { if (!VersionHasIetfQuicFrames(version().transport_version)) { return; } const QuicErrorCode kQuicErrorCode = IETF_QUIC_PROTOCOL_VIOLATION; const uint64_t kTransportCloseFrameType = 9999u; QuicFramerPeer::set_current_received_frame_type( QuicConnectionPeer::GetFramer(&connection_), kTransportCloseFrameType); EXPECT_CALL(visitor_, OnConnectionClosed(_, _)); connection_.CloseConnection( kQuicErrorCode, "Some random error message", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); const std::vector<QuicConnectionCloseFrame>& connection_close_frames = writer_->connection_close_frames(); ASSERT_EQ(1u, connection_close_frames.size()); EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE, connection_close_frames[0].close_type); EXPECT_EQ(kQuicErrorCode, connection_close_frames[0].quic_error_code); EXPECT_EQ(kTransportCloseFrameType, connection_close_frames[0].transport_close_frame_type); } TEST_P(QuicConnectionTest, PtoSkipsPacketNumber) { QuicConfig config; QuicTagVector connection_options; connection_options.push_back(k1PTO); connection_options.push_back(kPTOS); config.SetConnectionOptionsToSend(connection_options); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); QuicStreamId stream_id = 2; QuicPacketNumber last_packet; SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet); SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet); EXPECT_EQ(QuicPacketNumber(2), last_packet); EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.GetRetransmissionAlarm()->Fire(); EXPECT_EQ(1u, writer_->stream_frames().size()); EXPECT_EQ(QuicPacketNumber(4), writer_->last_packet_header().packet_number); EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); } TEST_P(QuicConnectionTest, SendCoalescedPackets) { if (!connection_.version().CanSendCoalescedPackets()) { return; } MockQuicConnectionDebugVisitor debug_visitor; connection_.set_debug_visitor(&debug_visitor); EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(3); EXPECT_CALL(debug_visitor, OnCoalescedPacketSent(_, _)).Times(1); EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1); { QuicConnection::ScopedPacketFlusher flusher(&connection_); connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); connection_.SendCryptoDataWithString("foo", 0); EXPECT_EQ(0u, writer_->packets_write_attempts()); connection_.SetEncrypter(ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(0x02)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); connection_.SendCryptoDataWithString("bar", 3); EXPECT_EQ(0u, writer_->packets_write_attempts()); connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(0x03)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); SendStreamDataToPeer(2, "baz", 3, NO_FIN, nullptr); } EXPECT_EQ(1u, writer_->packets_write_attempts()); EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet()); EXPECT_EQ(connection_.max_packet_length(), writer_->last_packet_size()); EXPECT_EQ(1u, writer_->crypto_frames().size()); EXPECT_EQ(0u, writer_->stream_frames().size()); EXPECT_NE(nullptr, writer_->coalesced_packet()); } TEST_P(QuicConnectionTest, FailToCoalescePacket) { if (!IsDefaultTestConfiguration() || !connection_.version().CanSendCoalescedPackets() || GetQuicFlag(quic_enforce_strict_amplification_factor)) { return; } set_perspective(Perspective::IS_SERVER); auto test_body = [&] { EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)) .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame)); ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_INITIAL); { QuicConnection::ScopedPacketFlusher flusher(&connection_); connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); connection_.SendCryptoDataWithString("foo", 0); EXPECT_EQ(0u, writer_->packets_write_attempts()); connection_.SetEncrypter(ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(0x02)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); connection_.SendCryptoDataWithString("bar", 3); EXPECT_EQ(0u, writer_->packets_write_attempts()); connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(0x03)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); SendStreamDataToPeer(2, "baz", 3, NO_FIN, nullptr); creator_->Flush(); auto& coalesced_packet = QuicConnectionPeer::GetCoalescedPacket(&connection_); QuicPacketLength coalesced_packet_max_length = coalesced_packet.max_packet_length(); QuicCoalescedPacketPeer::SetMaxPacketLength(coalesced_packet, coalesced_packet.length()); *QuicCoalescedPacketPeer::GetMutableEncryptedBuffer( coalesced_packet, ENCRYPTION_FORWARD_SECURE) += "!!! TEST !!!"; QUIC_LOG(INFO) << "Reduced coalesced_packet_max_length from " << coalesced_packet_max_length << " to " << coalesced_packet.max_packet_length() << ", coalesced_packet.length:" << coalesced_packet.length() << ", coalesced_packet.packet_lengths:" << absl::StrJoin(coalesced_packet.packet_lengths(), ":"); } EXPECT_FALSE(connection_.connected()); EXPECT_THAT(saved_connection_close_frame_.quic_error_code, IsError(QUIC_FAILED_TO_SERIALIZE_PACKET)); EXPECT_EQ(saved_connection_close_frame_.error_details, "Failed to serialize coalesced packet."); }; EXPECT_QUIC_BUG(test_body(), "SerializeCoalescedPacket failed."); } TEST_P(QuicConnectionTest, ClientReceivedHandshakeDone) { if (!connection_.version().UsesTls()) { return; } EXPECT_CALL(visitor_, OnHandshakeDoneReceived()); QuicFrames frames; frames.push_back(QuicFrame(QuicHandshakeDoneFrame())); frames.push_back(QuicFrame(QuicPaddingFrame(-1))); ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE); } TEST_P(QuicConnectionTest, ServerReceivedHandshakeDone) { if (!connection_.version().UsesTls()) { return; } set_perspective(Perspective::IS_SERVER); EXPECT_CALL(visitor_, OnHandshakeDoneReceived()).Times(0); if (version().handshake_protocol == PROTOCOL_TLS1_3) { EXPECT_CALL(visitor_, BeforeConnectionCloseSent()); } EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)) .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame)); QuicFrames frames; frames.push_back(QuicFrame(QuicHandshakeDoneFrame())); frames.push_back(QuicFrame(QuicPaddingFrame(-1))); ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(1, connection_close_frame_count_); EXPECT_THAT(saved_connection_close_frame_.quic_error_code, IsError(IETF_QUIC_PROTOCOL_VIOLATION)); } TEST_P(QuicConnectionTest, MultiplePacketNumberSpacePto) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } connection_.SetEncrypter( ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1); connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE); EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet()); connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data", 0, NO_FIN); EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet()); QuicTime retransmission_time = connection_.GetRetransmissionAlarm()->deadline(); EXPECT_NE(QuicTime::Zero(), retransmission_time); clock_.AdvanceTime(retransmission_time - clock_.Now()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _)); connection_.GetRetransmissionAlarm()->Fire(); EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet()); connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data", 4, NO_FIN); EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet()); retransmission_time = connection_.GetRetransmissionAlarm()->deadline(); EXPECT_NE(QuicTime::Zero(), retransmission_time); clock_.AdvanceTime(retransmission_time - clock_.Now()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(9), _, _)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(8), _, _)); connection_.GetRetransmissionAlarm()->Fire(); EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet()); connection_.OnHandshakeComplete(); retransmission_time = connection_.GetRetransmissionAlarm()->deadline(); EXPECT_NE(QuicTime::Zero(), retransmission_time); clock_.AdvanceTime(retransmission_time - clock_.Now()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(11), _, _)); connection_.GetRetransmissionAlarm()->Fire(); EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet()); } void QuicConnectionTest::TestClientRetryHandling( bool invalid_retry_tag, bool missing_original_id_in_config, bool wrong_original_id_in_config, bool missing_retry_id_in_config, bool wrong_retry_id_in_config) { if (invalid_retry_tag) { ASSERT_FALSE(missing_original_id_in_config); ASSERT_FALSE(wrong_original_id_in_config); ASSERT_FALSE(missing_retry_id_in_config); ASSERT_FALSE(wrong_retry_id_in_config); } else { ASSERT_FALSE(missing_original_id_in_config && wrong_original_id_in_config); ASSERT_FALSE(missing_retry_id_in_config && wrong_retry_id_in_config); } if (!version().UsesTls()) { return; } uint8_t retry_packet_rfcv2[] = { 0xcf, 0x6b, 0x33, 0x43, 0xcf, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xc8, 0x64, 0x6c, 0xe8, 0xbf, 0xe3, 0x39, 0x52, 0xd9, 0x55, 0x54, 0x36, 0x65, 0xdc, 0xc7, 0xb6}; uint8_t retry_packet_rfcv1[] = { 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x04, 0xa2, 0x65, 0xba, 0x2e, 0xff, 0x4d, 0x82, 0x90, 0x58, 0xfb, 0x3f, 0x0f, 0x24, 0x96, 0xba}; uint8_t retry_packet29[] = { 0xff, 0xff, 0x00, 0x00, 0x1d, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xd1, 0x69, 0x26, 0xd8, 0x1f, 0x6f, 0x9c, 0xa2, 0x95, 0x3a, 0x8a, 0xa4, 0x57, 0x5e, 0x1e, 0x49}; uint8_t* retry_packet; size_t retry_packet_length; if (version() == ParsedQuicVersion::RFCv2()) { retry_packet = retry_packet_rfcv2; retry_packet_length = ABSL_ARRAYSIZE(retry_packet_rfcv2); } else if (version() == ParsedQuicVersion::RFCv1()) { retry_packet = retry_packet_rfcv1; retry_packet_length = ABSL_ARRAYSIZE(retry_packet_rfcv1); } else if (version() == ParsedQuicVersion::Draft29()) { retry_packet = retry_packet29; retry_packet_length = ABSL_ARRAYSIZE(retry_packet29); } else { return; } uint8_t original_connection_id_bytes[] = {0x83, 0x94, 0xc8, 0xf0, 0x3e, 0x51, 0x57, 0x08}; uint8_t new_connection_id_bytes[] = {0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62, 0xb5}; uint8_t retry_token_bytes[] = {0x74, 0x6f, 0x6b, 0x65, 0x6e}; QuicConnectionId original_connection_id( reinterpret_cast<char*>(original_connection_id_bytes), ABSL_ARRAYSIZE(original_connection_id_bytes)); QuicConnectionId new_connection_id( reinterpret_cast<char*>(new_connection_id_bytes), ABSL_ARRAYSIZE(new_connection_id_bytes)); std::string retry_token(reinterpret_cast<char*>(retry_token_bytes), ABSL_ARRAYSIZE(retry_token_bytes)); if (invalid_retry_tag) { retry_packet[retry_packet_length - 1] ^= 1; } QuicConnectionId config_original_connection_id = original_connection_id; if (wrong_original_id_in_config) { ASSERT_FALSE(config_original_connection_id.IsEmpty()); config_original_connection_id.mutable_data()[0] ^= 0x80; } QuicConnectionId config_retry_source_connection_id = new_connection_id; if (wrong_retry_id_in_config) { ASSERT_FALSE(config_retry_source_connection_id.IsEmpty()); config_retry_source_connection_id.mutable_data()[0] ^= 0x80; } QuicConnectionPeer::SetServerConnectionId(&connection_, original_connection_id); writer_->framer()->framer()->SetInitialObfuscators(new_connection_id); connection_.ProcessUdpPacket( kSelfAddress, kPeerAddress, QuicReceivedPacket(reinterpret_cast<char*>(retry_packet), retry_packet_length, clock_.Now())); if (invalid_retry_tag) { EXPECT_FALSE(connection_.GetStats().retry_packet_processed); EXPECT_EQ(connection_.connection_id(), original_connection_id); EXPECT_TRUE(QuicPacketCreatorPeer::GetRetryToken( QuicConnectionPeer::GetPacketCreator(&connection_)) .empty()); return; } EXPECT_TRUE(connection_.GetStats().retry_packet_processed); EXPECT_EQ(connection_.connection_id(), new_connection_id); EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken( QuicConnectionPeer::GetPacketCreator(&connection_)), retry_token); QuicConfig received_config; QuicConfigPeer::SetNegotiated(&received_config, true); if (connection_.version().UsesTls()) { QuicConfigPeer::SetReceivedInitialSourceConnectionId( &received_config, connection_.connection_id()); if (!missing_retry_id_in_config) { QuicConfigPeer::SetReceivedRetrySourceConnectionId( &received_config, config_retry_source_connection_id); } } if (!missing_original_id_in_config) { QuicConfigPeer::SetReceivedOriginalConnectionId( &received_config, config_original_connection_id); } if (missing_original_id_in_config || wrong_original_id_in_config || missing_retry_id_in_config || wrong_retry_id_in_config) { EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)) .Times(1); } else { EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)) .Times(0); } EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber()); connection_.SetFromConfig(received_config); if (missing_original_id_in_config || wrong_original_id_in_config || missing_retry_id_in_config || wrong_retry_id_in_config) { ASSERT_FALSE(connection_.connected()); TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION); } else { EXPECT_TRUE(connection_.connected()); } } TEST_P(QuicConnectionTest, FixTimeoutsClient) { if (!connection_.version().UsesTls()) { return; } set_perspective(Perspective::IS_CLIENT); if (GetQuicReloadableFlag(quic_fix_timeouts)) { EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_START)); } QuicConfig config; QuicTagVector connection_options; connection_options.push_back(kFTOE); config.SetConnectionOptionsToSend(connection_options); QuicConfigPeer::SetNegotiated(&config, true); QuicConfigPeer::SetReceivedOriginalConnectionId(&config, connection_.connection_id()); QuicConfigPeer::SetReceivedInitialSourceConnectionId( &config, connection_.connection_id()); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(1); connection_.SetFromConfig(config); QuicIdleNetworkDetector& idle_network_detector = QuicConnectionPeer::GetIdleNetworkDetector(&connection_); if (GetQuicReloadableFlag(quic_fix_timeouts)) { EXPECT_NE(idle_network_detector.handshake_timeout(), QuicTime::Delta::Infinite()); } else { EXPECT_EQ(idle_network_detector.handshake_timeout(), QuicTime::Delta::Infinite()); } } TEST_P(QuicConnectionTest, FixTimeoutsServer) { if (!connection_.version().UsesTls()) { return; } set_perspective(Perspective::IS_SERVER); if (GetQuicReloadableFlag(quic_fix_timeouts)) { EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_START)); } QuicConfig config; quic::QuicTagVector initial_received_options; initial_received_options.push_back(quic::kFTOE); ASSERT_TRUE( config.SetInitialReceivedConnectionOptions(initial_received_options)); QuicConfigPeer::SetNegotiated(&config, true); QuicConfigPeer::SetReceivedOriginalConnectionId(&config, connection_.connection_id()); QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config, QuicConnectionId()); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(1); connection_.SetFromConfig(config); QuicIdleNetworkDetector& idle_network_detector = QuicConnectionPeer::GetIdleNetworkDetector(&connection_); if (GetQuicReloadableFlag(quic_fix_timeouts)) { EXPECT_NE(idle_network_detector.handshake_timeout(), QuicTime::Delta::Infinite()); } else { EXPECT_EQ(idle_network_detector.handshake_timeout(), QuicTime::Delta::Infinite()); } } TEST_P(QuicConnectionTest, ClientParsesRetry) { TestClientRetryHandling(false, false, false, false, false); } TEST_P(QuicConnectionTest, ClientParsesRetryInvalidTag) { TestClientRetryHandling(true, false, false, false, false); } TEST_P(QuicConnectionTest, ClientParsesRetryMissingOriginalId) { TestClientRetryHandling(false, true, false, false, false); } TEST_P(QuicConnectionTest, ClientParsesRetryWrongOriginalId) { TestClientRetryHandling(false, false, true, false, false); } TEST_P(QuicConnectionTest, ClientParsesRetryMissingRetryId) { if (!connection_.version().UsesTls()) { return; } TestClientRetryHandling(false, false, false, true, false); } TEST_P(QuicConnectionTest, ClientParsesRetryWrongRetryId) { if (!connection_.version().UsesTls()) { return; } TestClientRetryHandling(false, false, false, false, true); } TEST_P(QuicConnectionTest, ClientRetransmitsInitialPacketsOnRetry) { if (!connection_.version().HasIetfQuicFrames()) { return; } connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); connection_.SendCryptoStreamData(); EXPECT_EQ(1u, writer_->packets_write_attempts()); TestClientRetryHandling(false, false, false, false, false); if (GetParam().ack_response == AckResponse::kImmediate) { EXPECT_EQ(2u, writer_->packets_write_attempts()); EXPECT_EQ(1u, writer_->framer()->crypto_frames().size()); } } TEST_P(QuicConnectionTest, NoInitialPacketsRetransmissionOnInvalidRetry) { if (!connection_.version().HasIetfQuicFrames()) { return; } connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); connection_.SendCryptoStreamData(); EXPECT_EQ(1u, writer_->packets_write_attempts()); TestClientRetryHandling(true, false, false, false, false); EXPECT_EQ(1u, writer_->packets_write_attempts()); } TEST_P(QuicConnectionTest, ClientReceivesOriginalConnectionIdWithoutRetry) { if (!connection_.version().UsesTls()) { return; } if (connection_.version().UsesTls()) { return; } QuicConfig received_config; QuicConfigPeer::SetNegotiated(&received_config, true); QuicConfigPeer::SetReceivedOriginalConnectionId(&received_config, TestConnectionId(0x12345)); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber()); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)) .Times(1); connection_.SetFromConfig(received_config); EXPECT_FALSE(connection_.connected()); TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION); } TEST_P(QuicConnectionTest, ClientReceivesRetrySourceConnectionIdWithoutRetry) { if (!connection_.version().UsesTls()) { return; } QuicConfig received_config; QuicConfigPeer::SetNegotiated(&received_config, true); QuicConfigPeer::SetReceivedRetrySourceConnectionId(&received_config, TestConnectionId(0x12345)); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber()); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)) .Times(1); connection_.SetFromConfig(received_config); EXPECT_FALSE(connection_.connected()); TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION); } TEST_P(QuicConnectionTest, MaxStreamsFrameCausesConnectionClose) { if (!VersionHasIetfQuicFrames(connection_.transport_version())) { return; } EXPECT_CALL(visitor_, OnMaxStreamsFrame(_)) .WillOnce(InvokeWithoutArgs([this]() { EXPECT_CALL(visitor_, OnConnectionClosed(_, _)); connection_.CloseConnection( QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return true; })); QuicFrames frames; frames.push_back(QuicFrame(QuicMaxStreamsFrame())); frames.push_back(QuicFrame(QuicPaddingFrame(-1))); ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE); } TEST_P(QuicConnectionTest, StreamsBlockedFrameCausesConnectionClose) { if (!VersionHasIetfQuicFrames(connection_.transport_version())) { return; } EXPECT_CALL(visitor_, OnStreamsBlockedFrame(_)) .WillOnce(InvokeWithoutArgs([this]() { EXPECT_CALL(visitor_, OnConnectionClosed(_, _)); connection_.CloseConnection( QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return true; })); QuicFrames frames; frames.push_back( QuicFrame(QuicStreamsBlockedFrame(kInvalidControlFrameId, 10, false))); frames.push_back(QuicFrame(QuicPaddingFrame(-1))); ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE); } TEST_P(QuicConnectionTest, BundleAckWithConnectionCloseMultiplePacketNumberSpace) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber()); ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL); ProcessDataPacketAtLevel(2000, false, ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(visitor_, OnConnectionClosed(_, _)); const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR; connection_.CloseConnection( kQuicErrorCode, "Some random error message", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_)); TestConnectionCloseQuicErrorCode(kQuicErrorCode); EXPECT_EQ(1u, writer_->connection_close_frames().size()); EXPECT_EQ(1u, writer_->ack_frames().size()); if (!connection_.version().CanSendCoalescedPackets()) { EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_), writer_->connection_close_packets()); EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_), writer_->packets_write_attempts()); return; } EXPECT_EQ(1u, writer_->packets_write_attempts()); EXPECT_EQ(1u, writer_->connection_close_packets()); ASSERT_TRUE(writer_->coalesced_packet() != nullptr); auto packet = writer_->coalesced_packet()->Clone(); writer_->framer()->ProcessPacket(*packet); EXPECT_EQ(1u, writer_->connection_close_packets()); EXPECT_EQ(1u, writer_->connection_close_frames().size()); EXPECT_EQ(1u, writer_->ack_frames().size()); ASSERT_TRUE(writer_->coalesced_packet() == nullptr); } TEST_P(QuicConnectionTest, SendPingWhenSkipPacketNumberForPto) { QuicConfig config; QuicTagVector connection_options; connection_options.push_back(kPTOS); connection_options.push_back(k1PTO); config.SetConnectionOptionsToSend(connection_options); if (connection_.version().UsesTls()) { QuicConfigPeer::SetReceivedMaxDatagramFrameSize( &config, kMaxAcceptedDatagramFrameSize); } EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); connection_.OnHandshakeComplete(); EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); EXPECT_EQ(MESSAGE_STATUS_SUCCESS, SendMessage("message")); EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _)); connection_.GetRetransmissionAlarm()->Fire(); EXPECT_EQ(1u, connection_.GetStats().pto_count); EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count); EXPECT_EQ(1u, writer_->ping_frames().size()); } TEST_P(QuicConnectionTest, DonotChangeQueuedAcks) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } const size_t kMinRttMs = 40; RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats()); rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.RemoveEncrypter(ENCRYPTION_INITIAL); connection_.NeuterUnencryptedPackets(); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_COMPLETE)); ProcessPacket(2); ProcessPacket(3); ProcessPacket(4); QuicFrames frames; frames.push_back(QuicFrame(QuicStreamFrame( QuicUtils::GetFirstBidirectionalStreamId( connection_.version().transport_version, Perspective::IS_CLIENT), false, 0u, absl::string_view()))); QuicAckFrame ack_frame = InitAckFrame(1); frames.push_back(QuicFrame(&ack_frame)); EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() { connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0))); EXPECT_TRUE(QuicPacketCreatorPeer::QueuedFrames( QuicConnectionPeer::GetPacketCreator(&connection_))[0] .ack_frame->packets.Contains(QuicPacketNumber(2))); })); ProcessFramesPacketAtLevel(9, frames, ENCRYPTION_FORWARD_SECURE); EXPECT_TRUE(writer_->ack_frames()[0].packets.Contains(QuicPacketNumber(2))); } TEST_P(QuicConnectionTest, DoNotExtendIdleTimeOnUndecryptablePackets) { EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; connection_.SetFromConfig(config); QuicTime initial_deadline = clock_.ApproximateNow() + QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1); EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline()); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1)); peer_framer_.SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<quic::NullEncrypter>(Perspective::IS_CLIENT)); ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline()); EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1); QuicTime::Delta delay = initial_deadline - clock_.ApproximateNow(); clock_.AdvanceTime(delay); connection_.GetTimeoutAlarm()->Fire(); EXPECT_FALSE(connection_.connected()); } TEST_P(QuicConnectionTest, BundleAckWithImmediateResponse) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() { notifier_.WriteOrBufferWindowUpate(0, 0); })); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); ProcessDataPacket(1); EXPECT_FALSE(writer_->ack_frames().empty()); EXPECT_FALSE(connection_.HasPendingAcks()); } TEST_P(QuicConnectionTest, AckAlarmFiresEarly) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); } EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber()); ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL); EXPECT_TRUE(connection_.HasPendingAcks()); peer_framer_.SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT)); SetDecrypter(ENCRYPTION_ZERO_RTT, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT)); ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT); EXPECT_TRUE(connection_.HasPendingAcks()); EXPECT_EQ(clock_.ApproximateNow() + kAlarmGranularity, connection_.GetAckAlarm()->deadline()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.GetAckAlarm()->Fire(); EXPECT_TRUE(connection_.HasPendingAcks()); EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(), connection_.GetAckAlarm()->deadline()); } TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionClient) { if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) { return; } QuicConfig config; QuicTagVector connection_options; connection_options.push_back(kCBHD); config.SetConnectionOptionsToSend(connection_options); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); connection_.OnHandshakeComplete(); EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet()); SendStreamDataToPeer( GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo", 0, FIN, nullptr); EXPECT_TRUE(connection_.GetBlackholeDetectorAlarm()->IsSet()); } TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionServer) { if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) { return; } set_perspective(Perspective::IS_SERVER); QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false); if (version().SupportsAntiAmplificationLimit()) { QuicConnectionPeer::SetAddressValidated(&connection_); } QuicConfig config; QuicTagVector connection_options; connection_options.push_back(kCBHD); config.SetInitialReceivedConnectionOptions(connection_options); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_COMPLETE)); EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet()); SendStreamDataToPeer( GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo", 0, FIN, nullptr); EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet()); } TEST_P(QuicConnectionTest, MadeForwardProgressOnDiscardingKeys) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } connection_.SetEncrypter( ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1); QuicConfig config; QuicTagVector connection_options; connection_options.push_back(k5RTO); config.SetConnectionOptionsToSend(connection_options); QuicConfigPeer::SetNegotiated(&config, true); if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) || GetQuicReloadableFlag( quic_no_path_degrading_before_handshake_confirmed)) { EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_COMPLETE)); } if (connection_.version().UsesTls()) { QuicConfigPeer::SetReceivedOriginalConnectionId( &config, connection_.connection_id()); QuicConfigPeer::SetReceivedInitialSourceConnectionId( &config, connection_.connection_id()); } EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE); if (GetQuicReloadableFlag( quic_no_path_degrading_before_handshake_confirmed)) { EXPECT_FALSE(connection_.BlackholeDetectionInProgress()); } else { EXPECT_TRUE(connection_.BlackholeDetectionInProgress()); } EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); connection_.OnHandshakeComplete(); if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) || GetQuicReloadableFlag( quic_no_path_degrading_before_handshake_confirmed)) { EXPECT_FALSE(connection_.BlackholeDetectionInProgress()); } else { EXPECT_TRUE(connection_.BlackholeDetectionInProgress()); } } TEST_P(QuicConnectionTest, ProcessUndecryptablePacketsBasedOnEncryptionLevel) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber()); QuicConfig config; connection_.SetFromConfig(config); connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE); peer_framer_.SetEncrypter( ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE)); peer_framer_.SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE)); for (uint64_t i = 1; i <= 3; ++i) { ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE); } ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE); for (uint64_t j = 5; j <= 7; ++j) { ProcessDataPacketAtLevel(j, !kHasStopWaiting, ENCRYPTION_HANDSHAKE); } EXPECT_EQ(7u, QuicConnectionPeer::NumUndecryptablePackets(&connection_)); EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet()); SetDecrypter(ENCRYPTION_HANDSHAKE, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE)); EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet()); connection_.SetEncrypter( ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); if (!VersionHasIetfQuicFrames(version().transport_version)) { EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(6); } connection_.GetProcessUndecryptablePacketsAlarm()->Fire(); EXPECT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_)); SetDecrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE)); EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet()); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE)); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); connection_.GetProcessUndecryptablePacketsAlarm()->Fire(); EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_)); } TEST_P(QuicConnectionTest, ServerBundlesInitialDataWithInitialAck) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } set_perspective(Perspective::IS_SERVER); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); } EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber()); ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL); EXPECT_TRUE(connection_.HasPendingAcks()); connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL); QuicTime expected_pto_time = connection_.sent_packet_manager().GetRetransmissionTime(); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); connection_.SetEncrypter(ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(0x02)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1); connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE); EXPECT_EQ(expected_pto_time, connection_.sent_packet_manager().GetRetransmissionTime()); ProcessCryptoPacketAtLevel(1001, ENCRYPTION_INITIAL); EXPECT_TRUE(connection_.HasPendingAcks()); ProcessCryptoPacketAtLevel(1002, ENCRYPTION_INITIAL); EXPECT_FALSE(writer_->ack_frames().empty()); EXPECT_FALSE(writer_->crypto_frames().empty()); EXPECT_NE(expected_pto_time, connection_.sent_packet_manager().GetRetransmissionTime()); } TEST_P(QuicConnectionTest, ClientBundlesHandshakeDataWithHandshakeAck) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective()); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); } EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber()); connection_.SetEncrypter( ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); SetDecrypter(ENCRYPTION_HANDSHAKE, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE)); peer_framer_.SetEncrypter( ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE)); ProcessCryptoPacketAtLevel(1000, ENCRYPTION_HANDSHAKE); EXPECT_TRUE(connection_.HasPendingAcks()); EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1); connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE); ProcessCryptoPacketAtLevel(1001, ENCRYPTION_HANDSHAKE); EXPECT_TRUE(connection_.HasPendingAcks()); ProcessCryptoPacketAtLevel(1002, ENCRYPTION_HANDSHAKE); EXPECT_FALSE(writer_->ack_frames().empty()); EXPECT_FALSE(writer_->crypto_frames().empty()); } TEST_P(QuicConnectionTest, CoalescePacketOfLowerEncryptionLevel) { if (!connection_.version().CanSendCoalescedPackets()) { return; } EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1); { QuicConnection::ScopedPacketFlusher flusher(&connection_); connection_.SetEncrypter( ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE)); connection_.SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); SendStreamDataToPeer(2, std::string(1286, 'a'), 0, NO_FIN, nullptr); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); connection_.SendCryptoDataWithString("a", 0, ENCRYPTION_HANDSHAKE); } } TEST_P(QuicConnectionTest, ServerRetransmitsHandshakeDataEarly) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } set_perspective(Perspective::IS_SERVER); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); } EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber()); ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL); EXPECT_TRUE(connection_.HasPendingAcks()); connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL); QuicTime expected_pto_time = connection_.sent_packet_manager().GetRetransmissionTime(); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); connection_.SetEncrypter( ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1); connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE); connection_.SendCryptoDataWithString("bar", 3, ENCRYPTION_HANDSHAKE); EXPECT_EQ(expected_pto_time, connection_.sent_packet_manager().GetRetransmissionTime()); QuicFrames frames; auto ack_frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}}); frames.push_back(QuicFrame(&ack_frame)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _)); ProcessFramesPacketAtLevel(30, frames, ENCRYPTION_HANDSHAKE); connection_.RemoveEncrypter(ENCRYPTION_INITIAL); connection_.NeuterUnencryptedPackets(); frames.clear(); frames.push_back(QuicFrame(QuicPingFrame())); frames.push_back(QuicFrame(QuicPaddingFrame(3))); ProcessFramesPacketAtLevel(31, frames, ENCRYPTION_HANDSHAKE); EXPECT_EQ(clock_.Now() + kAlarmGranularity, connection_.GetAckAlarm()->deadline()); clock_.AdvanceTime(kAlarmGranularity); connection_.GetAckAlarm()->Fire(); EXPECT_FALSE(writer_->ack_frames().empty()); EXPECT_FALSE(writer_->crypto_frames().empty()); } TEST_P(QuicConnectionTest, InflatedRttSample) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30); set_perspective(Perspective::IS_SERVER); RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats()); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); } EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber()); ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL); EXPECT_TRUE(connection_.HasPendingAcks()); connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); std::string initial_crypto_data(512, 'a'); connection_.SendCryptoDataWithString(initial_crypto_data, 0, ENCRYPTION_INITIAL); ASSERT_TRUE(connection_.sent_packet_manager() .GetRetransmissionTime() .IsInitialized()); QuicTime::Delta pto_timeout = connection_.sent_packet_manager().GetRetransmissionTime() - clock_.Now(); connection_.SetEncrypter( ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1); std::string handshake_crypto_data(1024, 'a'); connection_.SendCryptoDataWithString(handshake_crypto_data, 0, ENCRYPTION_HANDSHAKE); clock_.AdvanceTime(pto_timeout); connection_.GetRetransmissionAlarm()->Fire(); clock_.AdvanceTime(kTestRTT); QuicFrames frames; auto ack_frame = InitAckFrame({{QuicPacketNumber(4), QuicPacketNumber(5)}}); frames.push_back(QuicFrame(&ack_frame)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _)) .Times(AnyNumber()); ProcessFramesPacketAtLevel(1001, frames, ENCRYPTION_INITIAL); EXPECT_EQ(kTestRTT, rtt_stats->latest_rtt()); frames.clear(); QuicAckFrame ack_frame2 = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}, {QuicPacketNumber(5), QuicPacketNumber(6)}}); ack_frame2.ack_delay_time = QuicTime::Delta::Zero(); frames.push_back(QuicFrame(&ack_frame2)); ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_HANDSHAKE); EXPECT_EQ(rtt_stats->latest_rtt(), kTestRTT); } TEST_P(QuicConnectionTest, CoalescingPacketCausesInfiniteLoop) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } set_perspective(Perspective::IS_SERVER); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); } EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber()); SetQuicFlag(quic_anti_amplification_factor, 2); ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL); EXPECT_TRUE(connection_.HasPendingAcks()); connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); std::string initial_crypto_data(512, 'a'); connection_.SendCryptoDataWithString(initial_crypto_data, 0, ENCRYPTION_INITIAL); ASSERT_TRUE(connection_.sent_packet_manager() .GetRetransmissionTime() .IsInitialized()); QuicTime::Delta pto_timeout = connection_.sent_packet_manager().GetRetransmissionTime() - clock_.Now(); connection_.SetEncrypter( ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1); std::string handshake_crypto_data(1024, 'a'); connection_.SendCryptoDataWithString(handshake_crypto_data, 0, ENCRYPTION_HANDSHAKE); clock_.AdvanceTime(pto_timeout); connection_.GetRetransmissionAlarm()->Fire(); } TEST_P(QuicConnectionTest, ClientAckDelayForAsyncPacketProcessing) { if (!version().HasIetfQuicFrames()) { return; } EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() { connection_.RemoveEncrypter(ENCRYPTION_INITIAL); connection_.NeuterUnencryptedPackets(); })); QuicConfig config; connection_.SetFromConfig(config); connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); peer_framer_.SetEncrypter( ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE)); EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_)); ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_HANDSHAKE); ASSERT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100)); ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_INITIAL); SetDecrypter(ENCRYPTION_HANDSHAKE, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE)); EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet()); connection_.SetEncrypter( ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); connection_.GetProcessUndecryptablePacketsAlarm()->Fire(); ASSERT_FALSE(connection_.HasPendingAcks()); ASSERT_FALSE(writer_->ack_frames().empty()); EXPECT_EQ(QuicTime::Delta::FromMilliseconds(100), writer_->ack_frames()[0].ack_delay_time); ASSERT_TRUE(writer_->coalesced_packet() == nullptr); } TEST_P(QuicConnectionTest, TestingLiveness) { const size_t kMinRttMs = 40; RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats()); rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; CryptoHandshakeMessage msg; std::string error_details; QuicConfig client_config; client_config.SetInitialStreamFlowControlWindowToSend( kInitialStreamFlowControlWindowForTest); client_config.SetInitialSessionFlowControlWindowToSend( kInitialSessionFlowControlWindowForTest); client_config.SetIdleNetworkTimeout(QuicTime::Delta::FromSeconds(30)); client_config.ToHandshakeMessage(&msg, connection_.transport_version()); const QuicErrorCode error = config.ProcessPeerHello(msg, CLIENT, &error_details); EXPECT_THAT(error, IsQuicNoError()); if (connection_.version().UsesTls()) { QuicConfigPeer::SetReceivedOriginalConnectionId( &config, connection_.connection_id()); QuicConfigPeer::SetReceivedInitialSourceConnectionId( &config, connection_.connection_id()); } connection_.SetFromConfig(config); connection_.OnHandshakeComplete(); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet()); EXPECT_FALSE(connection_.MaybeTestLiveness()); QuicTime deadline = QuicConnectionPeer::GetIdleNetworkDeadline(&connection_); QuicTime::Delta timeout = deadline - clock_.ApproximateNow(); clock_.AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(1)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); EXPECT_TRUE(connection_.MaybeTestLiveness()); EXPECT_EQ(deadline, QuicConnectionPeer::GetIdleNetworkDeadline(&connection_)); } TEST_P(QuicConnectionTest, DisableLivenessTesting) { const size_t kMinRttMs = 40; RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats()); rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; CryptoHandshakeMessage msg; std::string error_details; QuicConfig client_config; client_config.SetInitialStreamFlowControlWindowToSend( kInitialStreamFlowControlWindowForTest); client_config.SetInitialSessionFlowControlWindowToSend( kInitialSessionFlowControlWindowForTest); client_config.SetIdleNetworkTimeout(QuicTime::Delta::FromSeconds(30)); client_config.ToHandshakeMessage(&msg, connection_.transport_version()); const QuicErrorCode error = config.ProcessPeerHello(msg, CLIENT, &error_details); EXPECT_THAT(error, IsQuicNoError()); if (connection_.version().UsesTls()) { QuicConfigPeer::SetReceivedOriginalConnectionId( &config, connection_.connection_id()); QuicConfigPeer::SetReceivedInitialSourceConnectionId( &config, connection_.connection_id()); } connection_.SetFromConfig(config); connection_.OnHandshakeComplete(); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.DisableLivenessTesting(); ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet()); EXPECT_FALSE(connection_.MaybeTestLiveness()); QuicTime deadline = QuicConnectionPeer::GetIdleNetworkDeadline(&connection_); QuicTime::Delta timeout = deadline - clock_.ApproximateNow(); clock_.AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(1)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); EXPECT_FALSE(connection_.MaybeTestLiveness()); } TEST_P(QuicConnectionTest, SilentIdleTimeout) { set_perspective(Perspective::IS_SERVER); QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false); if (version().SupportsAntiAmplificationLimit()) { QuicConnectionPeer::SetAddressValidated(&connection_); } QuicConfig config; QuicConfigPeer::SetNegotiated(&config, true); if (connection_.version().UsesTls()) { QuicConfigPeer::SetReceivedOriginalConnectionId( &config, connection_.connection_id()); QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config, QuicConnectionId()); } EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); EXPECT_TRUE(connection_.connected()); EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet()); if (version().handshake_protocol == PROTOCOL_TLS1_3) { EXPECT_CALL(visitor_, BeforeConnectionCloseSent()); } EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); connection_.GetTimeoutAlarm()->Fire(); EXPECT_NE(nullptr, QuicConnectionPeer::GetConnectionClosePacket(&connection_)); } TEST_P(QuicConnectionTest, DoNotSendPing) { connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.OnHandshakeComplete(); EXPECT_TRUE(connection_.connected()); EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()) .WillRepeatedly(Return(true)); EXPECT_FALSE(connection_.GetPingAlarm()->IsSet()); EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); SendStreamDataToPeer( GetNthClientInitiatedStreamId(0, connection_.transport_version()), "GET /", 0, FIN, nullptr); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(15), connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); QuicFrames frames; QuicAckFrame ack_frame = InitAckFrame(1); frames.push_back(QuicFrame(&ack_frame)); frames.push_back(QuicFrame(QuicStreamFrame( GetNthClientInitiatedStreamId(0, connection_.transport_version()), true, 0u, absl::string_view()))); EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE); EXPECT_TRUE(connection_.GetPingAlarm()->IsSet()); EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); EXPECT_EQ( QuicTime::Delta::FromSeconds(15) - QuicTime::Delta::FromMilliseconds(5), connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow()); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15)); EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()) .WillRepeatedly(Return(false)); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); connection_.GetPingAlarm()->Fire(); } TEST_P(QuicConnectionTest, DuplicateAckCausesLostPackets) { if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) { return; } connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); notifier_.NeuterUnencryptedData(); connection_.NeuterUnencryptedPackets(); connection_.OnHandshakeComplete(); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); std::string data(1200, 'a'); for (size_t i = 0; i < 5; ++i) { SendStreamDataToPeer( GetNthClientInitiatedStreamId(1, connection_.transport_version()), data, i * 1200, i == 4 ? FIN : NO_FIN, nullptr); } ASSERT_TRUE(connection_.BlackholeDetectionInProgress()); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _)) .Times(3); QuicAckFrame frame = InitAckFrame({{QuicPacketNumber(5), QuicPacketNumber(6)}}); LostPacketVector lost_packets; lost_packets.push_back( LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize)); lost_packets.push_back( LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize)); EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _)) .Times(AnyNumber()) .WillOnce(DoAll(SetArgPointee<5>(lost_packets), Return(LossDetectionInterface::DetectionStats()))) .WillRepeatedly(DoDefault()); ; ProcessAckPacket(1, &frame); EXPECT_TRUE(connection_.BlackholeDetectionInProgress()); QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm(); EXPECT_TRUE(retransmission_alarm->IsSet()); QuicAckFrame frame2 = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(6)}, {QuicPacketNumber(7), QuicPacketNumber(8)}}); ProcessAckPacket(2, &frame2); EXPECT_TRUE(connection_.BlackholeDetectionInProgress()); QuicAckFrame frame3 = InitAckFrame({{QuicPacketNumber(7), QuicPacketNumber(8)}}); lost_packets.clear(); lost_packets.push_back( LostPacket(QuicPacketNumber(6), kMaxOutgoingPacketSize)); EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _)) .Times(AnyNumber()) .WillOnce(DoAll(SetArgPointee<5>(lost_packets), Return(LossDetectionInterface::DetectionStats()))); ProcessAckPacket(3, &frame3); EXPECT_FALSE(connection_.BlackholeDetectionInProgress()); } TEST_P(QuicConnectionTest, ShorterIdleTimeoutOnSentPackets) { EXPECT_TRUE(connection_.connected()); RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats()); rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(100), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; config.SetClientConnectionOptions(QuicTagVector{kFIDT}); QuicConfigPeer::SetNegotiated(&config, true); if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) { EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_COMPLETE)); } if (connection_.version().UsesTls()) { QuicConfigPeer::SetReceivedOriginalConnectionId( &config, connection_.connection_id()); QuicConfigPeer::SetReceivedInitialSourceConnectionId( &config, connection_.connection_id()); } connection_.SetFromConfig(config); ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet()); QuicTime::Delta timeout = connection_.GetTimeoutAlarm()->deadline() - clock_.Now(); clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(1)); SendStreamDataToPeer( GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo", 0, FIN, nullptr); ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet()); EXPECT_EQ(QuicTime::Delta::FromSeconds(1), connection_.GetTimeoutAlarm()->deadline() - clock_.Now()); clock_.AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(100)); QuicAckFrame ack = InitAckFrame(1); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); ProcessAckPacket(1, &ack); EXPECT_EQ(clock_.Now() + timeout, connection_.GetTimeoutAlarm()->deadline()); } TEST_P(QuicConnectionTest, ReserializeInitialPacketInCoalescerAfterDiscardingInitialKey) { if (!connection_.version().CanSendCoalescedPackets()) { return; } connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1); ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL); EXPECT_TRUE(connection_.HasPendingAcks()); connection_.SetEncrypter(ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(0x02)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() { connection_.RemoveEncrypter(ENCRYPTION_INITIAL); connection_.NeuterUnencryptedPackets(); })); { QuicConnection::ScopedPacketFlusher flusher(&connection_); connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE); EXPECT_EQ(0u, writer_->packets_write_attempts()); connection_.GetAckAlarm()->Fire(); } EXPECT_FALSE(connection_.packet_creator().HasPendingFrames()); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacketAtLevel(1000, false, ENCRYPTION_FORWARD_SECURE); EXPECT_TRUE(connection_.connected()); } TEST_P(QuicConnectionTest, PathValidationOnNewSocketSuccess) { if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) { return; } PathProbeTestInit(Perspective::IS_CLIENT); const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345); EXPECT_NE(kNewSelfAddress, connection_.self_address()); TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(AtLeast(1u)) .WillOnce(Invoke([&]() { EXPECT_EQ(1u, new_writer.packets_write_attempts()); EXPECT_EQ(1u, new_writer.path_challenge_frames().size()); EXPECT_EQ(1u, new_writer.padding_frames().size()); EXPECT_EQ(kNewSelfAddress.host(), new_writer.last_write_source_address()); })) .WillRepeatedly(DoDefault()); ; bool success = false; connection_.ValidatePath( std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress, connection_.peer_address(), &new_writer), std::make_unique<TestValidationResultDelegate>( &connection_, kNewSelfAddress, connection_.peer_address(), &success), PathValidationReason::kReasonUnknown); EXPECT_EQ(0u, writer_->packets_write_attempts()); QuicFrames frames; frames.push_back(QuicFrame(QuicPathResponseFrame( 99, new_writer.path_challenge_frames().front().data_buffer))); ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_TRUE(success); } TEST_P(QuicConnectionTest, PathValidationOnNewSocketWriteBlocked) { if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) { return; } PathProbeTestInit(Perspective::IS_CLIENT); const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345); EXPECT_NE(kNewSelfAddress, connection_.self_address()); TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); new_writer.SetWriteBlocked(); bool success = false; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); connection_.ValidatePath( std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress, connection_.peer_address(), &new_writer), std::make_unique<TestValidationResultDelegate>( &connection_, kNewSelfAddress, connection_.peer_address(), &success), PathValidationReason::kReasonUnknown); EXPECT_EQ(0u, new_writer.packets_write_attempts()); EXPECT_TRUE(connection_.HasPendingPathValidation()); new_writer.SetWritable(); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs)); static_cast<test::MockRandom*>(helper_->GetRandomGenerator())->ChangeValue(); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .WillOnce(Invoke([&]() { EXPECT_EQ(1u, new_writer.packets_write_attempts()); EXPECT_EQ(1u, new_writer.path_challenge_frames().size()); EXPECT_EQ(1u, new_writer.padding_frames().size()); EXPECT_EQ(kNewSelfAddress.host(), new_writer.last_write_source_address()); })); static_cast<TestAlarmFactory::TestAlarm*>( QuicPathValidatorPeer::retry_timer( QuicConnectionPeer::path_validator(&connection_))) ->Fire(); EXPECT_EQ(1u, new_writer.packets_write_attempts()); QuicFrames frames; QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7}; frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer))); new_writer.SetWriteBlocked(); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .WillRepeatedly(Invoke([&] { EXPECT_EQ(1u, new_writer.packets_write_attempts()); EXPECT_TRUE(new_writer.path_response_frames().empty()); EXPECT_EQ(1u, writer_->packets_write_attempts()); })); ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, connection_.peer_address(), ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(1u, new_writer.packets_write_attempts()); } TEST_P(QuicConnectionTest, NewPathValidationCancelsPreviousOne) { if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) { return; } PathProbeTestInit(Perspective::IS_CLIENT); const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345); EXPECT_NE(kNewSelfAddress, connection_.self_address()); TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(AtLeast(1u)) .WillOnce(Invoke([&]() { EXPECT_EQ(1u, new_writer.packets_write_attempts()); EXPECT_EQ(1u, new_writer.path_challenge_frames().size()); EXPECT_EQ(1u, new_writer.padding_frames().size()); EXPECT_EQ(kNewSelfAddress.host(), new_writer.last_write_source_address()); })); bool success = true; connection_.ValidatePath( std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress, connection_.peer_address(), &new_writer), std::make_unique<TestValidationResultDelegate>( &connection_, kNewSelfAddress, connection_.peer_address(), &success), PathValidationReason::kReasonUnknown); EXPECT_EQ(0u, writer_->packets_write_attempts()); const QuicSocketAddress kNewSelfAddress2(QuicIpAddress::Any4(), 12346); EXPECT_NE(kNewSelfAddress2, connection_.self_address()); TestPacketWriter new_writer2(version(), &clock_, Perspective::IS_CLIENT); bool success2 = false; connection_.ValidatePath( std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress2, connection_.peer_address(), &new_writer2), std::make_unique<TestValidationResultDelegate>( &connection_, kNewSelfAddress2, connection_.peer_address(), &success2), PathValidationReason::kReasonUnknown); EXPECT_FALSE(success); EXPECT_FALSE(connection_.HasPendingPathValidation()); } TEST_P(QuicConnectionTest, PathValidationRetry) { if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) { return; } PathProbeTestInit(Perspective::IS_CLIENT); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(2u) .WillRepeatedly(Invoke([&]() { EXPECT_EQ(1u, writer_->path_challenge_frames().size()); EXPECT_EQ(1u, writer_->padding_frames().size()); })); bool success = true; connection_.ValidatePath(std::make_unique<TestQuicPathValidationContext>( connection_.self_address(), connection_.peer_address(), writer_.get()), std::make_unique<TestValidationResultDelegate>( &connection_, connection_.self_address(), connection_.peer_address(), &success), PathValidationReason::kReasonUnknown); EXPECT_EQ(1u, writer_->packets_write_attempts()); EXPECT_TRUE(connection_.HasPendingPathValidation()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs)); static_cast<test::MockRandom*>(helper_->GetRandomGenerator())->ChangeValue(); static_cast<TestAlarmFactory::TestAlarm*>( QuicPathValidatorPeer::retry_timer( QuicConnectionPeer::path_validator(&connection_))) ->Fire(); EXPECT_EQ(2u, writer_->packets_write_attempts()); } TEST_P(QuicConnectionTest, PathValidationReceivesStatelessReset) { if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) { return; } PathProbeTestInit(Perspective::IS_CLIENT); QuicConfig config; QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestStatelessResetToken); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345); EXPECT_NE(kNewSelfAddress, connection_.self_address()); TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(AtLeast(1u)) .WillOnce(Invoke([&]() { EXPECT_EQ(1u, new_writer.packets_write_attempts()); EXPECT_EQ(1u, new_writer.path_challenge_frames().size()); EXPECT_EQ(1u, new_writer.padding_frames().size()); EXPECT_EQ(kNewSelfAddress.host(), new_writer.last_write_source_address()); })) .WillRepeatedly(DoDefault()); ; bool success = true; connection_.ValidatePath( std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress, connection_.peer_address(), &new_writer), std::make_unique<TestValidationResultDelegate>( &connection_, kNewSelfAddress, connection_.peer_address(), &success), PathValidationReason::kReasonUnknown); EXPECT_EQ(0u, writer_->packets_write_attempts()); EXPECT_TRUE(connection_.HasPendingPathValidation()); std::unique_ptr<QuicEncryptedPacket> packet( QuicFramer::BuildIetfStatelessResetPacket(connection_id_, 100, kTestStatelessResetToken)); std::unique_ptr<QuicReceivedPacket> received( ConstructReceivedPacket(*packet, QuicTime::Zero())); EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0); connection_.ProcessUdpPacket(kNewSelfAddress, kPeerAddress, *received); EXPECT_FALSE(connection_.HasPendingPathValidation()); EXPECT_FALSE(success); } TEST_P(QuicConnectionTest, SendPathChallengeUsingBlockedNewSocket) { if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) { return; } PathProbeTestInit(Perspective::IS_CLIENT); const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345); EXPECT_NE(kNewSelfAddress, connection_.self_address()); TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); new_writer.BlockOnNextWrite(); EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(AtLeast(1)) .WillOnce(Invoke([&]() { EXPECT_EQ(1u, new_writer.packets_write_attempts()); EXPECT_EQ(1u, new_writer.path_challenge_frames().size()); EXPECT_EQ(1u, new_writer.padding_frames().size()); EXPECT_EQ(kNewSelfAddress.host(), new_writer.last_write_source_address()); })) .WillRepeatedly(DoDefault()); ; bool success = false; connection_.ValidatePath( std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress, connection_.peer_address(), &new_writer), std::make_unique<TestValidationResultDelegate>( &connection_, kNewSelfAddress, connection_.peer_address(), &success), PathValidationReason::kReasonUnknown); EXPECT_EQ(0u, writer_->packets_write_attempts()); new_writer.SetWritable(); connection_.OnCanWrite(); EXPECT_EQ(1u, writer_->packets_write_attempts()); EXPECT_EQ(1u, new_writer.packets_write_attempts()); } TEST_P(QuicConnectionTest, SendPathChallengeUsingBlockedDefaultSocket) { if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) { return; } PathProbeTestInit(Perspective::IS_SERVER); const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Any4(), 12345); writer_->BlockOnNextWrite(); EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(2)); QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7}; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(AtLeast(1u)) .WillOnce(Invoke([&]() { EXPECT_EQ(1u, writer_->packets_write_attempts()); EXPECT_EQ(1u, writer_->path_response_frames().size()); EXPECT_EQ(0, memcmp(&path_challenge_payload, &writer_->path_response_frames().front().data_buffer, sizeof(path_challenge_payload))); EXPECT_EQ(1u, writer_->path_challenge_frames().size()); EXPECT_EQ(1u, writer_->padding_frames().size()); EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address()); })) .WillRepeatedly(Invoke([&]() { EXPECT_EQ(0u, writer_->path_challenge_frames().size()); })); QuicFrames frames; frames.push_back( QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload))); ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(1u, writer_->packets_write_attempts()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs)); static_cast<test::MockRandom*>(helper_->GetRandomGenerator())->ChangeValue(); static_cast<TestAlarmFactory::TestAlarm*>( QuicPathValidatorPeer::retry_timer( QuicConnectionPeer::path_validator(&connection_))) ->Fire(); EXPECT_EQ(1u, writer_->packets_write_attempts()); writer_->SetWritable(); connection_.OnCanWrite(); EXPECT_LE(2u, writer_->packets_write_attempts()); } TEST_P(QuicConnectionTest, SendPathChallengeFailOnNewSocket) { if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) { return; } PathProbeTestInit(Perspective::IS_CLIENT); const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345); EXPECT_NE(kNewSelfAddress, connection_.self_address()); TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); new_writer.SetShouldWriteFail(); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)) .Times(0); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u); bool success = false; connection_.ValidatePath( std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress, connection_.peer_address(), &new_writer), std::make_unique<TestValidationResultDelegate>( &connection_, kNewSelfAddress, connection_.peer_address(), &success), PathValidationReason::kReasonUnknown); EXPECT_EQ(1u, new_writer.packets_write_attempts()); EXPECT_EQ(1u, new_writer.path_challenge_frames().size()); EXPECT_EQ(1u, new_writer.padding_frames().size()); EXPECT_EQ(kNewSelfAddress.host(), new_writer.last_write_source_address()); EXPECT_EQ(0u, writer_->packets_write_attempts()); EXPECT_TRUE(connection_.connected()); } TEST_P(QuicConnectionTest, SendPathChallengeFailOnDefaultPath) { if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) { return; } PathProbeTestInit(Perspective::IS_CLIENT); writer_->SetShouldWriteFail(); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)) .WillOnce( Invoke([](QuicConnectionCloseFrame frame, ConnectionCloseSource) { EXPECT_EQ(QUIC_PACKET_WRITE_ERROR, frame.quic_error_code); })); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u); { bool success = false; QuicConnection::ScopedPacketFlusher flusher(&connection_); connection_.ValidatePath(std::make_unique<TestQuicPathValidationContext>( connection_.self_address(), connection_.peer_address(), writer_.get()), std::make_unique<TestValidationResultDelegate>( &connection_, connection_.self_address(), connection_.peer_address(), &success), PathValidationReason::kReasonUnknown); } EXPECT_EQ(1u, writer_->packets_write_attempts()); EXPECT_EQ(1u, writer_->path_challenge_frames().size()); EXPECT_EQ(1u, writer_->padding_frames().size()); EXPECT_EQ(connection_.peer_address(), writer_->last_write_peer_address()); EXPECT_FALSE(connection_.connected()); EXPECT_FALSE(connection_.HasPendingPathValidation()); } TEST_P(QuicConnectionTest, SendPathChallengeFailOnAlternativePeerAddress) { if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) { return; } PathProbeTestInit(Perspective::IS_CLIENT); writer_->SetShouldWriteFail(); const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Any4(), 12345); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)) .WillOnce( Invoke([](QuicConnectionCloseFrame frame, ConnectionCloseSource) { EXPECT_EQ(QUIC_PACKET_WRITE_ERROR, frame.quic_error_code); })); bool success = false; connection_.ValidatePath( std::make_unique<TestQuicPathValidationContext>( connection_.self_address(), kNewPeerAddress, writer_.get()), std::make_unique<TestValidationResultDelegate>( &connection_, connection_.self_address(), kNewPeerAddress, &success), PathValidationReason::kReasonUnknown); EXPECT_EQ(1u, writer_->packets_write_attempts()); EXPECT_FALSE(connection_.HasPendingPathValidation()); EXPECT_EQ(1u, writer_->path_challenge_frames().size()); EXPECT_EQ(1u, writer_->padding_frames().size()); EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address()); EXPECT_FALSE(connection_.connected()); } TEST_P(QuicConnectionTest, SendPathChallengeFailPacketTooBigOnAlternativePeerAddress) { if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) { return; } PathProbeTestInit(Perspective::IS_CLIENT); connection_.OnCanWrite(); uint32_t num_packets_write_attempts = writer_->packets_write_attempts(); writer_->SetShouldWriteFail(); writer_->SetWriteError(*writer_->MessageTooBigErrorCode()); const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Any4(), 12345); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)) .Times(0u); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u); bool success = false; connection_.ValidatePath( std::make_unique<TestQuicPathValidationContext>( connection_.self_address(), kNewPeerAddress, writer_.get()), std::make_unique<TestValidationResultDelegate>( &connection_, connection_.self_address(), kNewPeerAddress, &success), PathValidationReason::kReasonUnknown); EXPECT_TRUE(connection_.HasPendingPathValidation()); EXPECT_TRUE(connection_.connected()); EXPECT_EQ(++num_packets_write_attempts, writer_->packets_write_attempts()); EXPECT_EQ(1u, writer_->path_challenge_frames().size()); EXPECT_EQ(1u, writer_->padding_frames().size()); EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address()); } TEST_P(QuicConnectionTest, ReceiveMultiplePathChallenge) { if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) { return; } PathProbeTestInit(Perspective::IS_SERVER); QuicPathFrameBuffer path_frame_buffer1{0, 1, 2, 3, 4, 5, 6, 7}; QuicPathFrameBuffer path_frame_buffer2{8, 9, 10, 11, 12, 13, 14, 15}; QuicFrames frames; frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer1))); frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer2))); const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(), 23456); EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(2) .WillOnce(Invoke([=, this]() { EXPECT_EQ(1u, writer_->path_response_frames().size()); EXPECT_EQ(0, memcmp(path_frame_buffer1.data(), &(writer_->path_response_frames().front().data_buffer), sizeof(path_frame_buffer1))); EXPECT_EQ(1u, writer_->padding_frames().size()); EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address()); })) .WillOnce(Invoke([=, this]() { EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address()); })); ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress, ENCRYPTION_FORWARD_SECURE); } TEST_P(QuicConnectionTest, ReceiveStreamFrameBeforePathChallenge) { if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) { return; } PathProbeTestInit(Perspective::IS_SERVER); QuicFrames frames; frames.push_back(QuicFrame(frame1_)); QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7}; frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer))); frames.push_back(QuicFrame(QuicPaddingFrame(-1))); const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(), 23456); EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)); EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(0u); EXPECT_CALL(visitor_, OnStreamFrame(_)) .WillOnce(Invoke([=, this](const QuicStreamFrame& frame) { const std::string data{"response body"}; connection_.producer()->SaveStreamData(frame.stream_id, data); return notifier_.WriteOrBufferData(frame.stream_id, data.length(), NO_FIN); })); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u); ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(1u, writer_->stream_frames().size()); EXPECT_EQ(1u, writer_->path_response_frames().size()); EXPECT_EQ(1u, writer_->path_challenge_frames().size()); EXPECT_EQ(0, memcmp(path_frame_buffer.data(), &(writer_->path_response_frames().front().data_buffer), sizeof(path_frame_buffer))); EXPECT_EQ(1u, writer_->path_challenge_frames().size()); EXPECT_EQ(1u, writer_->padding_frames().size()); EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address()); EXPECT_TRUE(connection_.HasPendingPathValidation()); } TEST_P(QuicConnectionTest, ReceiveStreamFrameFollowingPathChallenge) { if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) { return; } PathProbeTestInit(Perspective::IS_SERVER); QuicFrames frames; QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7}; frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer))); frames.push_back(QuicFrame(frame1_)); const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(), 23456); QuicByteCount received_packet_size; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(AtLeast(1u)) .WillOnce(Invoke([=, this, &received_packet_size]() { EXPECT_EQ(0u, writer_->stream_frames().size()); EXPECT_EQ(1u, writer_->path_response_frames().size()); EXPECT_EQ(0, memcmp(path_frame_buffer.data(), &(writer_->path_response_frames().front().data_buffer), sizeof(path_frame_buffer))); EXPECT_EQ(1u, writer_->path_challenge_frames().size()); EXPECT_EQ(1u, writer_->padding_frames().size()); EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address()); received_packet_size = QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_); })); EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)); EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(0u); EXPECT_CALL(visitor_, OnStreamFrame(_)) .WillOnce(Invoke([=, this](const QuicStreamFrame& frame) { const std::string data{"response body"}; connection_.producer()->SaveStreamData(frame.stream_id, data); return notifier_.WriteOrBufferData(frame.stream_id, data.length(), NO_FIN); })); ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_TRUE(connection_.HasPendingPathValidation()); EXPECT_EQ(0u, QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_)); EXPECT_EQ( received_packet_size, QuicConnectionPeer::BytesReceivedBeforeAddressValidation(&connection_)); } TEST_P(QuicConnectionTest, PathChallengeWithDataInOutOfOrderPacket) { if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) { return; } PathProbeTestInit(Perspective::IS_SERVER); QuicFrames frames; frames.push_back(QuicFrame(frame1_)); QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7}; frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer))); frames.push_back(QuicFrame(frame2_)); const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(), 23456); EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0u); EXPECT_CALL(visitor_, OnStreamFrame(_)) .Times(2) .WillRepeatedly(Invoke([=, this](const QuicStreamFrame& frame) { const std::string data{"response body"}; connection_.producer()->SaveStreamData(frame.stream_id, data); return notifier_.WriteOrBufferData(frame.stream_id, data.length(), NO_FIN); })); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .WillOnce(Invoke([=, this]() { EXPECT_EQ(1u, writer_->stream_frames().size()); EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address()); })) .WillOnce(Invoke([=, this]() { EXPECT_EQ(1u, writer_->path_response_frames().size()); EXPECT_EQ(0, memcmp(path_frame_buffer.data(), &(writer_->path_response_frames().front().data_buffer), sizeof(path_frame_buffer))); EXPECT_EQ(1u, writer_->padding_frames().size()); EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address()); })) .WillOnce(Invoke([=, this]() { EXPECT_EQ(1u, writer_->stream_frames().size()); EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address()); })); QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1); ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress, ENCRYPTION_FORWARD_SECURE); } TEST_P(QuicConnectionTest, FailToWritePathResponseAtServer) { if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) { return; } PathProbeTestInit(Perspective::IS_SERVER); QuicFrames frames; QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7}; frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer))); const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(), 23456); EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0u); QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1); EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1)); writer_->SetWriteBlocked(); ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress, ENCRYPTION_FORWARD_SECURE); } TEST_P(QuicConnectionTest, HandshakeDataDoesNotGetPtoed) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } set_perspective(Perspective::IS_SERVER); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); } EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber()); ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL); EXPECT_TRUE(connection_.HasPendingAcks()); connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL); connection_.SetEncrypter( ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); SetDecrypter(ENCRYPTION_HANDSHAKE, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE)); EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1); connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE); connection_.SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN); peer_framer_.SetEncrypter( ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE)); ProcessCryptoPacketAtLevel(1, ENCRYPTION_HANDSHAKE); connection_.RemoveEncrypter(ENCRYPTION_INITIAL); connection_.NeuterUnencryptedPackets(); ASSERT_TRUE(connection_.HasPendingAcks()); connection_.GetSendAlarm()->Set(clock_.ApproximateNow()); connection_.GetAckAlarm()->Fire(); EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet()); connection_.GetSendAlarm()->Fire(); ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); connection_.GetRetransmissionAlarm()->Fire(); EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet()); } TEST_P(QuicConnectionTest, CoalescerHandlesInitialKeyDiscard) { if (!connection_.version().CanSendCoalescedPackets()) { return; } SetQuicReloadableFlag(quic_discard_initial_packet_with_key_dropped, true); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2); EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() { connection_.RemoveEncrypter(ENCRYPTION_INITIAL); connection_.NeuterUnencryptedPackets(); })); EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); EXPECT_EQ(0u, connection_.GetStats().packets_discarded); { QuicConnection::ScopedPacketFlusher flusher(&connection_); ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); connection_.SetEncrypter( ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0); EXPECT_EQ(0u, writer_->packets_write_attempts()); } EXPECT_TRUE(connection_.connected()); } TEST_P(QuicConnectionTest, ZeroRttRejectionAndMissingInitialKeys) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } connection_.set_defer_send_in_response_to_packets(false); EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() { connection_.RemoveEncrypter(ENCRYPTION_INITIAL); connection_.NeuterUnencryptedPackets(); })); EXPECT_CALL(visitor_, OnCryptoFrame(_)) .WillRepeatedly(Invoke([=, this](const QuicCryptoFrame& frame) { if (frame.level == ENCRYPTION_HANDSHAKE) { connection_.MarkZeroRttPacketsForRetransmission(0); connection_.SetEncrypter( ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE); connection_.SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); } })); connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL); connection_.SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN); QuicAckFrame frame1 = InitAckFrame(1); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _)); ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL); EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); connection_.GetRetransmissionAlarm()->Fire(); QuicFrames frames1; frames1.push_back(QuicFrame(&crypto_frame_)); QuicFrames frames2; QuicCryptoFrame crypto_frame(ENCRYPTION_HANDSHAKE, 0, absl::string_view(data1)); frames2.push_back(QuicFrame(&crypto_frame)); ProcessCoalescedPacket( {{2, frames1, ENCRYPTION_INITIAL}, {3, frames2, ENCRYPTION_HANDSHAKE}}); } TEST_P(QuicConnectionTest, OnZeroRttPacketAcked) { if (!connection_.version().UsesTls()) { return; } MockQuicConnectionDebugVisitor debug_visitor; connection_.set_debug_visitor(&debug_visitor); connection_.SendCryptoStreamData(); connection_.SetEncrypter(ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(0x02)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN); connection_.SendStreamDataWithString(4, "bar", 0, NO_FIN); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _)) .Times(AnyNumber()); QuicFrames frames1; QuicAckFrame ack_frame1 = InitAckFrame(1); frames1.push_back(QuicFrame(&ack_frame1)); QuicFrames frames2; QuicCryptoFrame crypto_frame(ENCRYPTION_HANDSHAKE, 0, absl::string_view(data1)); frames2.push_back(QuicFrame(&crypto_frame)); EXPECT_CALL(debug_visitor, OnZeroRttPacketAcked()).Times(0); EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1); ProcessCoalescedPacket( {{1, frames1, ENCRYPTION_INITIAL}, {2, frames2, ENCRYPTION_HANDSHAKE}}); QuicFrames frames3; QuicAckFrame ack_frame2 = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}}); frames3.push_back(QuicFrame(&ack_frame2)); EXPECT_CALL(debug_visitor, OnZeroRttPacketAcked()).Times(1); ProcessCoalescedPacket({{3, frames3, ENCRYPTION_FORWARD_SECURE}}); QuicFrames frames4; QuicAckFrame ack_frame3 = InitAckFrame({{QuicPacketNumber(3), QuicPacketNumber(4)}}); frames4.push_back(QuicFrame(&ack_frame3)); EXPECT_CALL(debug_visitor, OnZeroRttPacketAcked()).Times(0); ProcessCoalescedPacket({{4, frames4, ENCRYPTION_FORWARD_SECURE}}); } TEST_P(QuicConnectionTest, InitiateKeyUpdate) { if (!connection_.version().UsesTls()) { return; } TransportParameters params; QuicConfig config; std::string error_details; EXPECT_THAT(config.ProcessTransportParameters( params, false, &error_details), IsQuicNoError()); QuicConfigPeer::SetNegotiated(&config, true); if (connection_.version().UsesTls()) { QuicConfigPeer::SetReceivedOriginalConnectionId( &config, connection_.connection_id()); QuicConfigPeer::SetReceivedInitialSourceConnectionId( &config, connection_.connection_id()); } EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); EXPECT_FALSE(connection_.IsKeyUpdateAllowed()); MockFramerVisitor peer_framer_visitor_; peer_framer_.set_visitor(&peer_framer_visitor_); uint8_t correct_tag = ENCRYPTION_FORWARD_SECURE; connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(correct_tag)); SetDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(correct_tag)); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); connection_.OnHandshakeComplete(); peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(correct_tag)); EXPECT_FALSE(connection_.IsKeyUpdateAllowed()); EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked()); QuicPacketNumber last_packet; SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); EXPECT_EQ(QuicPacketNumber(1u), last_packet); EXPECT_FALSE(connection_.IsKeyUpdateAllowed()); EXPECT_TRUE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked()); EXPECT_FALSE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet()); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); QuicAckFrame frame1 = InitAckFrame(1); ProcessAckPacket(&frame1); EXPECT_TRUE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet()); EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked()); correct_tag++; EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter()) .WillOnce([&correct_tag]() { return std::make_unique<StrictTaggingDecrypter>(correct_tag); }); EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter()) .WillOnce([&correct_tag]() { return std::make_unique<TaggingEncrypter>(correct_tag); }); EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests)); EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests)); EXPECT_FALSE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet()); EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked()); EXPECT_CALL(peer_framer_visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter()) .WillOnce([&correct_tag]() { return std::make_unique<StrictTaggingDecrypter>(correct_tag); }); EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter()) .WillOnce([&correct_tag]() { return std::make_unique<TaggingEncrypter>(correct_tag); }); peer_framer_.SetKeyUpdateSupportForConnection(true); peer_framer_.DoKeyUpdate(KeyUpdateReason::kRemote); EXPECT_FALSE(connection_.IsKeyUpdateAllowed()); SendStreamDataToPeer(2, "bar", 0, NO_FIN, &last_packet); EXPECT_EQ(QuicPacketNumber(2u), last_packet); EXPECT_TRUE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked()); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); QuicAckFrame frame2 = InitAckFrame(2); ProcessAckPacket(&frame2); EXPECT_TRUE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet()); EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked()); correct_tag++; EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter()) .WillOnce([&correct_tag]() { return std::make_unique<StrictTaggingDecrypter>(correct_tag); }); EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter()) .WillOnce([&correct_tag]() { return std::make_unique<TaggingEncrypter>(correct_tag); }); EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests)); EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests)); EXPECT_CALL(peer_framer_visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter()) .WillOnce([&correct_tag]() { return std::make_unique<StrictTaggingDecrypter>(correct_tag); }); EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter()) .WillOnce([&correct_tag]() { return std::make_unique<TaggingEncrypter>(correct_tag); }); peer_framer_.DoKeyUpdate(KeyUpdateReason::kRemote); EXPECT_FALSE(connection_.IsKeyUpdateAllowed()); SendStreamDataToPeer(3, "baz", 0, NO_FIN, &last_packet); EXPECT_EQ(QuicPacketNumber(3u), last_packet); EXPECT_FALSE(connection_.IsKeyUpdateAllowed()); EXPECT_TRUE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked()); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); QuicAckFrame frame3 = InitAckFrame(3); ProcessAckPacket(&frame3); EXPECT_TRUE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet()); EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked()); correct_tag++; EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter()) .WillOnce([&correct_tag]() { return std::make_unique<StrictTaggingDecrypter>(correct_tag); }); EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter()) .WillOnce([&correct_tag]() { return std::make_unique<TaggingEncrypter>(correct_tag); }); EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests)); EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests)); EXPECT_FALSE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet()); EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked()); } TEST_P(QuicConnectionTest, InitiateKeyUpdateApproachingConfidentialityLimit) { if (!connection_.version().UsesTls()) { return; } SetQuicFlag(quic_key_update_confidentiality_limit, 3U); std::string error_details; TransportParameters params; QuicConfig config; EXPECT_THAT(config.ProcessTransportParameters( params, false, &error_details), IsQuicNoError()); QuicConfigPeer::SetNegotiated(&config, true); if (connection_.version().UsesTls()) { QuicConfigPeer::SetReceivedOriginalConnectionId( &config, connection_.connection_id()); QuicConfigPeer::SetReceivedInitialSourceConnectionId( &config, connection_.connection_id()); } EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); MockFramerVisitor peer_framer_visitor_; peer_framer_.set_visitor(&peer_framer_visitor_); uint8_t current_tag = ENCRYPTION_FORWARD_SECURE; connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(current_tag)); SetDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(current_tag)); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); connection_.OnHandshakeComplete(); peer_framer_.SetKeyUpdateSupportForConnection(true); peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(current_tag)); const QuicConnectionStats& stats = connection_.GetStats(); for (int packet_num = 1; packet_num <= 8; ++packet_num) { if (packet_num == 3 || packet_num == 6) { current_tag++; EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter()) .WillOnce([current_tag]() { return std::make_unique<StrictTaggingDecrypter>(current_tag); }); EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter()) .WillOnce([current_tag]() { return std::make_unique<TaggingEncrypter>(current_tag); }); EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalKeyUpdateLimitOverride)); } QuicPacketNumber last_packet; SendStreamDataToPeer(packet_num, "foo", 0, NO_FIN, &last_packet); EXPECT_EQ(QuicPacketNumber(packet_num), last_packet); if (packet_num >= 6) { EXPECT_EQ(2U, stats.key_update_count); } else if (packet_num >= 3) { EXPECT_EQ(1U, stats.key_update_count); } else { EXPECT_EQ(0U, stats.key_update_count); } if (packet_num == 4 || packet_num == 7) { EXPECT_CALL(peer_framer_visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter()) .WillOnce([current_tag]() { return std::make_unique<StrictTaggingDecrypter>(current_tag); }); EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter()) .WillOnce([current_tag]() { return std::make_unique<TaggingEncrypter>(current_tag); }); peer_framer_.DoKeyUpdate(KeyUpdateReason::kRemote); } EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); QuicAckFrame frame1 = InitAckFrame(packet_num); ProcessAckPacket(&frame1); } } TEST_P(QuicConnectionTest, CloseConnectionOnConfidentialityLimitKeyUpdateNotAllowed) { if (!connection_.version().UsesTls()) { return; } SetQuicFlag(quic_key_update_confidentiality_limit, 1U); constexpr size_t kConfidentialityLimit = 3U; std::string error_details; TransportParameters params; QuicConfig config; EXPECT_THAT(config.ProcessTransportParameters( params, false, &error_details), IsQuicNoError()); QuicConfigPeer::SetNegotiated(&config, true); if (connection_.version().UsesTls()) { QuicConfigPeer::SetReceivedOriginalConnectionId( &config, connection_.connection_id()); QuicConfigPeer::SetReceivedInitialSourceConnectionId( &config, connection_.connection_id()); } EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypterWithConfidentialityLimit>( ENCRYPTION_FORWARD_SECURE, kConfidentialityLimit)); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); connection_.OnHandshakeComplete(); QuicPacketNumber last_packet; SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); EXPECT_TRUE(connection_.connected()); SendStreamDataToPeer(2, "foo", 0, NO_FIN, &last_packet); EXPECT_TRUE(connection_.connected()); EXPECT_CALL(visitor_, OnConnectionClosed(_, _)); SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); EXPECT_FALSE(connection_.connected()); const QuicConnectionStats& stats = connection_.GetStats(); EXPECT_EQ(0U, stats.key_update_count); TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED); } TEST_P(QuicConnectionTest, CloseConnectionOnIntegrityLimitDuringHandshake) { if (!connection_.version().UsesTls()) { return; } constexpr uint8_t correct_tag = ENCRYPTION_HANDSHAKE; constexpr uint8_t wrong_tag = 0xFE; constexpr QuicPacketCount kIntegrityLimit = 3; SetDecrypter(ENCRYPTION_HANDSHAKE, std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>( correct_tag, kIntegrityLimit)); connection_.SetEncrypter(ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(correct_tag)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(wrong_tag)); for (uint64_t i = 1; i <= kIntegrityLimit; ++i) { EXPECT_TRUE(connection_.connected()); if (i == kIntegrityLimit) { EXPECT_CALL(visitor_, OnConnectionClosed(_, _)); EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber()); } ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE); EXPECT_EQ( i, connection_.GetStats().num_failed_authentication_packets_received); } EXPECT_FALSE(connection_.connected()); TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED); } TEST_P(QuicConnectionTest, CloseConnectionOnIntegrityLimitAfterHandshake) { if (!connection_.version().UsesTls()) { return; } constexpr uint8_t correct_tag = ENCRYPTION_FORWARD_SECURE; constexpr uint8_t wrong_tag = 0xFE; constexpr QuicPacketCount kIntegrityLimit = 3; SetDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>( correct_tag, kIntegrityLimit)); connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(correct_tag)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); connection_.OnHandshakeComplete(); connection_.RemoveEncrypter(ENCRYPTION_INITIAL); peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(wrong_tag)); for (uint64_t i = 1; i <= kIntegrityLimit; ++i) { EXPECT_TRUE(connection_.connected()); if (i == kIntegrityLimit) { EXPECT_CALL(visitor_, OnConnectionClosed(_, _)); } ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ( i, connection_.GetStats().num_failed_authentication_packets_received); } EXPECT_FALSE(connection_.connected()); TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED); } TEST_P(QuicConnectionTest, CloseConnectionOnIntegrityLimitAcrossEncryptionLevels) { if (!connection_.version().UsesTls()) { return; } uint8_t correct_tag = ENCRYPTION_HANDSHAKE; constexpr uint8_t wrong_tag = 0xFE; constexpr QuicPacketCount kIntegrityLimit = 4; SetDecrypter(ENCRYPTION_HANDSHAKE, std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>( correct_tag, kIntegrityLimit)); connection_.SetEncrypter(ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(correct_tag)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(wrong_tag)); for (uint64_t i = 1; i <= 2; ++i) { EXPECT_TRUE(connection_.connected()); ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE); EXPECT_EQ( i, connection_.GetStats().num_failed_authentication_packets_received); } correct_tag = ENCRYPTION_FORWARD_SECURE; SetDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>( correct_tag, kIntegrityLimit)); connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(correct_tag)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); connection_.OnHandshakeComplete(); connection_.RemoveEncrypter(ENCRYPTION_INITIAL); connection_.RemoveEncrypter(ENCRYPTION_HANDSHAKE); peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(wrong_tag)); for (uint64_t i = 3; i <= kIntegrityLimit; ++i) { EXPECT_TRUE(connection_.connected()); if (i == kIntegrityLimit) { EXPECT_CALL(visitor_, OnConnectionClosed(_, _)); } ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ( i, connection_.GetStats().num_failed_authentication_packets_received); } EXPECT_FALSE(connection_.connected()); TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED); } TEST_P(QuicConnectionTest, IntegrityLimitDoesNotApplyWithoutDecryptionKey) { if (!connection_.version().UsesTls()) { return; } constexpr uint8_t correct_tag = ENCRYPTION_HANDSHAKE; constexpr uint8_t wrong_tag = 0xFE; constexpr QuicPacketCount kIntegrityLimit = 3; SetDecrypter(ENCRYPTION_HANDSHAKE, std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>( correct_tag, kIntegrityLimit)); connection_.SetEncrypter(ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(correct_tag)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE); peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(wrong_tag)); for (uint64_t i = 1; i <= kIntegrityLimit * 2; ++i) { EXPECT_TRUE(connection_.connected()); ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ( 0u, connection_.GetStats().num_failed_authentication_packets_received); } EXPECT_TRUE(connection_.connected()); } TEST_P(QuicConnectionTest, CloseConnectionOnIntegrityLimitAcrossKeyPhases) { if (!connection_.version().UsesTls()) { return; } constexpr QuicPacketCount kIntegrityLimit = 4; TransportParameters params; QuicConfig config; std::string error_details; EXPECT_THAT(config.ProcessTransportParameters( params, false, &error_details), IsQuicNoError()); QuicConfigPeer::SetNegotiated(&config, true); if (connection_.version().UsesTls()) { QuicConfigPeer::SetReceivedOriginalConnectionId( &config, connection_.connection_id()); QuicConfigPeer::SetReceivedInitialSourceConnectionId( &config, connection_.connection_id()); } EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); MockFramerVisitor peer_framer_visitor_; peer_framer_.set_visitor(&peer_framer_visitor_); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(0x01)); SetDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>( ENCRYPTION_FORWARD_SECURE, kIntegrityLimit)); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); connection_.OnHandshakeComplete(); connection_.RemoveEncrypter(ENCRYPTION_INITIAL); peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(0xFF)); for (uint64_t i = 1; i <= 2; ++i) { EXPECT_TRUE(connection_.connected()); ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ( i, connection_.GetStats().num_failed_authentication_packets_received); } peer_framer_.SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE)); QuicPacketNumber last_packet; SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); EXPECT_EQ(QuicPacketNumber(1u), last_packet); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); QuicAckFrame frame1 = InitAckFrame(1); ProcessAckPacket(&frame1); EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter()) .WillOnce([kIntegrityLimit]() { return std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>( 0x02, kIntegrityLimit); }); EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter()).WillOnce([]() { return std::make_unique<TaggingEncrypter>(0x02); }); EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests)); EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests)); EXPECT_CALL(peer_framer_visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter()) .WillOnce( []() { return std::make_unique<StrictTaggingDecrypter>(0x02); }); EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter()) .WillOnce([]() { return std::make_unique<TaggingEncrypter>(0x02); }); peer_framer_.SetKeyUpdateSupportForConnection(true); peer_framer_.DoKeyUpdate(KeyUpdateReason::kLocalForTests); SendStreamDataToPeer(2, "bar", 0, NO_FIN, &last_packet); EXPECT_EQ(QuicPacketNumber(2u), last_packet); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _)); QuicAckFrame frame2 = InitAckFrame(2); ProcessAckPacket(&frame2); EXPECT_EQ(2u, connection_.GetStats().num_failed_authentication_packets_received); peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(0xFF)); for (uint64_t i = 3; i <= kIntegrityLimit; ++i) { EXPECT_TRUE(connection_.connected()); if (i == kIntegrityLimit) { EXPECT_CALL(visitor_, OnConnectionClosed(_, _)); } ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ( i, connection_.GetStats().num_failed_authentication_packets_received); } EXPECT_FALSE(connection_.connected()); TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED); } TEST_P(QuicConnectionTest, SendAckFrequencyFrame) { if (!version().HasIetfQuicFrames()) { return; } SetQuicReloadableFlag(quic_can_send_ack_frequency, true); set_perspective(Perspective::IS_SERVER); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _)) .Times(AnyNumber()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber()); QuicConfig config; QuicConfigPeer::SetReceivedMinAckDelayMs(&config, 1); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); QuicConnectionPeer::SetAddressValidated(&connection_); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); connection_.OnHandshakeComplete(); writer_->SetWritable(); QuicPacketCreatorPeer::SetPacketNumber(creator_, 99); SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr); QuicAckFrequencyFrame captured_frame; EXPECT_CALL(visitor_, SendAckFrequency(_)) .WillOnce(Invoke([&captured_frame](const QuicAckFrequencyFrame& frame) { captured_frame = frame; })); SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr); EXPECT_EQ(captured_frame.packet_tolerance, 10u); EXPECT_EQ(captured_frame.max_ack_delay, QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs())); SendStreamDataToPeer(1, "baz", 6, NO_FIN, nullptr); } TEST_P(QuicConnectionTest, SendAckFrequencyFrameUponHandshakeCompletion) { if (!version().HasIetfQuicFrames()) { return; } SetQuicReloadableFlag(quic_can_send_ack_frequency, true); set_perspective(Perspective::IS_SERVER); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _)) .Times(AnyNumber()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber()); QuicConfig config; QuicConfigPeer::SetReceivedMinAckDelayMs(&config, 1); QuicTagVector quic_tag_vector; quic_tag_vector.push_back(kAFF2); QuicConfigPeer::SetReceivedConnectionOptions(&config, quic_tag_vector); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); QuicConnectionPeer::SetAddressValidated(&connection_); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); QuicAckFrequencyFrame captured_frame; EXPECT_CALL(visitor_, SendAckFrequency(_)) .WillOnce(Invoke([&captured_frame](const QuicAckFrequencyFrame& frame) { captured_frame = frame; })); connection_.OnHandshakeComplete(); EXPECT_EQ(captured_frame.packet_tolerance, 2u); EXPECT_EQ(captured_frame.max_ack_delay, QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs())); } TEST_P(QuicConnectionTest, FastRecoveryOfLostServerHello) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; connection_.SetFromConfig(config); connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); connection_.SendCryptoStreamData(); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20)); peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(0x02)); ProcessCryptoPacketAtLevel(2, ENCRYPTION_HANDSHAKE); ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); EXPECT_EQ(clock_.ApproximateNow() + kAlarmGranularity, connection_.GetRetransmissionAlarm()->deadline()); } TEST_P(QuicConnectionTest, ServerHelloGetsReordered) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; connection_.SetFromConfig(config); EXPECT_CALL(visitor_, OnCryptoFrame(_)) .WillRepeatedly(Invoke([=, this](const QuicCryptoFrame& frame) { if (frame.level == ENCRYPTION_INITIAL) { SetDecrypter( ENCRYPTION_HANDSHAKE, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE)); connection_.SetEncrypter( ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); } })); connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); connection_.SendCryptoStreamData(); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20)); peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(0x02)); ProcessCryptoPacketAtLevel(2, ENCRYPTION_HANDSHAKE); ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL); EXPECT_EQ(connection_.sent_packet_manager().GetRetransmissionTime(), connection_.GetRetransmissionAlarm()->deadline()); } TEST_P(QuicConnectionTest, MigratePath) { connection_.CreateConnectionIdManager(); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.OnHandshakeComplete(); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); EXPECT_CALL(visitor_, OnPathDegrading()); connection_.OnPathDegradingDetected(); const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345); EXPECT_NE(kNewSelfAddress, connection_.self_address()); EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1); writer_->SetWriteBlocked(); connection_.SendMtuDiscoveryPacket(kMaxOutgoingPacketSize); EXPECT_EQ(1u, connection_.NumQueuedPackets()); if (version().HasIetfQuicFrames()) { QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(1234); ASSERT_NE(frame.connection_id, connection_.connection_id()); frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); frame.retire_prior_to = 0u; frame.sequence_number = 1u; connection_.OnNewConnectionIdFrame(frame); } TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()); EXPECT_TRUE(connection_.MigratePath(kNewSelfAddress, connection_.peer_address(), &new_writer, false)); EXPECT_EQ(kNewSelfAddress, connection_.self_address()); EXPECT_EQ(&new_writer, QuicConnectionPeer::GetWriter(&connection_)); EXPECT_FALSE(connection_.IsPathDegrading()); if (version().HasIetfQuicFrames()) { EXPECT_EQ(0u, connection_.NumQueuedPackets()); } else { EXPECT_EQ(1u, connection_.NumQueuedPackets()); } } TEST_P(QuicConnectionTest, MigrateToNewPathDuringProbing) { if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) { return; } PathProbeTestInit(Perspective::IS_CLIENT); const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345); EXPECT_NE(kNewSelfAddress, connection_.self_address()); TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)); bool success = false; connection_.ValidatePath( std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress, connection_.peer_address(), &new_writer), std::make_unique<TestValidationResultDelegate>( &connection_, kNewSelfAddress, connection_.peer_address(), &success), PathValidationReason::kReasonUnknown); EXPECT_TRUE(connection_.HasPendingPathValidation()); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath( &connection_, kNewSelfAddress, connection_.peer_address())); connection_.MigratePath(kNewSelfAddress, connection_.peer_address(), &new_writer, false); EXPECT_EQ(kNewSelfAddress, connection_.self_address()); EXPECT_TRUE(connection_.HasPendingPathValidation()); EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath( &connection_, kNewSelfAddress, connection_.peer_address())); } TEST_P(QuicConnectionTest, MultiPortConnection) { set_perspective(Perspective::IS_CLIENT); QuicConfig config; config.SetClientConnectionOptions(QuicTagVector{kMPQC}); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); if (!version().HasIetfQuicFrames()) { return; } connection_.CreateConnectionIdManager(); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.OnHandshakeComplete(); EXPECT_CALL(visitor_, OnPathDegrading()); connection_.OnPathDegradingDetected(); auto self_address = connection_.self_address(); const QuicSocketAddress kNewSelfAddress(self_address.host(), self_address.port() + 1); EXPECT_NE(kNewSelfAddress, self_address); TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()).WillOnce(Return(false)); QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(1234); ASSERT_NE(frame.connection_id, connection_.connection_id()); frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); frame.retire_prior_to = 0u; frame.sequence_number = 1u; EXPECT_CALL(visitor_, CreateContextForMultiPortPath) .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) { observer->OnMultiPortPathContextAvailable( std::move(std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress, connection_.peer_address(), &new_writer))); })); connection_.OnNewConnectionIdFrame(frame); EXPECT_TRUE(connection_.HasPendingPathValidation()); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath( &connection_, kNewSelfAddress, connection_.peer_address())); auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_); EXPECT_FALSE(alt_path->validated); EXPECT_EQ(PathValidationReason::kMultiPort, QuicConnectionPeer::path_validator(&connection_) ->GetPathValidationReason()); connection_.OnNewConnectionIdFrame(frame); const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30); clock_.AdvanceTime(kTestRTT); QuicFrames frames; frames.push_back(QuicFrame(QuicPathResponseFrame( 99, new_writer.path_challenge_frames().back().data_buffer))); ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_FALSE(connection_.HasPendingPathValidation()); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath( &connection_, kNewSelfAddress, connection_.peer_address())); EXPECT_TRUE(alt_path->validated); auto stats = connection_.multi_port_stats(); EXPECT_EQ(1, connection_.GetStats().num_path_degrading); EXPECT_EQ(1, stats->num_successful_probes); EXPECT_EQ(1, stats->num_client_probing_attempts); EXPECT_EQ(1, connection_.GetStats().num_client_probing_attempts); EXPECT_EQ(0, stats->num_multi_port_probe_failures_when_path_degrading); EXPECT_EQ(kTestRTT, stats->rtt_stats.latest_rtt()); EXPECT_EQ(kTestRTT, stats->rtt_stats_when_default_path_degrading.latest_rtt()); EXPECT_CALL(visitor_, CreateContextForMultiPortPath).Times(0); connection_.OnNewConnectionIdFrame(frame); EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()).WillOnce(Return(false)); connection_.GetMultiPortProbingAlarm()->Fire(); EXPECT_FALSE(connection_.HasPendingPathValidation()); EXPECT_FALSE(connection_.GetMultiPortProbingAlarm()->IsSet()); EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()) .WillRepeatedly(Return(true)); random_generator_.ChangeValue(); connection_.MaybeProbeMultiPortPath(); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath( &connection_, kNewSelfAddress, connection_.peer_address())); EXPECT_TRUE(alt_path->validated); clock_.AdvanceTime(kTestRTT); QuicFrames frames2; frames2.push_back(QuicFrame(QuicPathResponseFrame( 99, new_writer.path_challenge_frames().back().data_buffer))); ProcessFramesPacketWithAddresses(frames2, kNewSelfAddress, kPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_FALSE(connection_.HasPendingPathValidation()); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath( &connection_, kNewSelfAddress, connection_.peer_address())); EXPECT_TRUE(alt_path->validated); EXPECT_EQ(1, connection_.GetStats().num_path_degrading); EXPECT_EQ(0, stats->num_multi_port_probe_failures_when_path_degrading); EXPECT_EQ(kTestRTT, stats->rtt_stats.latest_rtt()); EXPECT_EQ(kTestRTT, stats->rtt_stats_when_default_path_degrading.latest_rtt()); EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()); QuicConnectionPeer::OnForwardProgressMade(&connection_); EXPECT_TRUE(connection_.GetMultiPortProbingAlarm()->IsSet()); connection_.MaybeProbeMultiPortPath(); EXPECT_FALSE(connection_.HasPendingPathValidation()); EXPECT_CALL(visitor_, OnPathDegrading()); EXPECT_CALL(visitor_, MigrateToMultiPortPath(_)).Times(0); connection_.OnPathDegradingDetected(); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath( &connection_, kNewSelfAddress, connection_.peer_address())); connection_.GetMultiPortProbingAlarm()->Fire(); EXPECT_TRUE(connection_.HasPendingPathValidation()); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath( &connection_, kNewSelfAddress, connection_.peer_address())); for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes + 1; ++i) { clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs)); static_cast<TestAlarmFactory::TestAlarm*>( QuicPathValidatorPeer::retry_timer( QuicConnectionPeer::path_validator(&connection_))) ->Fire(); } EXPECT_FALSE(connection_.HasPendingPathValidation()); EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath( &connection_, kNewSelfAddress, connection_.peer_address())); EXPECT_EQ(2, connection_.GetStats().num_path_degrading); EXPECT_EQ(1, stats->num_multi_port_probe_failures_when_path_degrading); EXPECT_EQ(0, stats->num_multi_port_probe_failures_when_path_not_degrading); EXPECT_EQ(0, connection_.GetStats().num_stateless_resets_on_alternate_path); } TEST_P(QuicConnectionTest, TooManyMultiPortPathCreations) { set_perspective(Perspective::IS_CLIENT); QuicConfig config; config.SetClientConnectionOptions(QuicTagVector{kMPQC}); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); if (!version().HasIetfQuicFrames()) { return; } connection_.CreateConnectionIdManager(); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.OnHandshakeComplete(); EXPECT_CALL(visitor_, OnPathDegrading()); connection_.OnPathDegradingDetected(); auto self_address = connection_.self_address(); const QuicSocketAddress kNewSelfAddress(self_address.host(), self_address.port() + 1); EXPECT_NE(kNewSelfAddress, self_address); TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()) .WillRepeatedly(Return(true)); { QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(1234); ASSERT_NE(frame.connection_id, connection_.connection_id()); frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); frame.retire_prior_to = 0u; frame.sequence_number = 1u; EXPECT_CALL(visitor_, CreateContextForMultiPortPath) .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) { observer->OnMultiPortPathContextAvailable( std::move(std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress, connection_.peer_address(), &new_writer))); })); EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame)); } EXPECT_TRUE(connection_.HasPendingPathValidation()); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath( &connection_, kNewSelfAddress, connection_.peer_address())); auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_); EXPECT_FALSE(alt_path->validated); EXPECT_TRUE(connection_.HasPendingPathValidation()); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath( &connection_, kNewSelfAddress, connection_.peer_address())); for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes + 1; ++i) { clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs)); static_cast<TestAlarmFactory::TestAlarm*>( QuicPathValidatorPeer::retry_timer( QuicConnectionPeer::path_validator(&connection_))) ->Fire(); } auto stats = connection_.multi_port_stats(); EXPECT_FALSE(connection_.HasPendingPathValidation()); EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath( &connection_, kNewSelfAddress, connection_.peer_address())); EXPECT_EQ(1, connection_.GetStats().num_path_degrading); EXPECT_EQ(1, stats->num_multi_port_probe_failures_when_path_degrading); uint64_t connection_id = 1235; for (size_t i = 0; i < kMaxNumMultiPortPaths - 1; ++i) { QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(connection_id + i); ASSERT_NE(frame.connection_id, connection_.connection_id()); frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); frame.retire_prior_to = 0u; frame.sequence_number = i + 2; EXPECT_CALL(visitor_, CreateContextForMultiPortPath) .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) { observer->OnMultiPortPathContextAvailable( std::move(std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress, connection_.peer_address(), &new_writer))); })); EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame)); EXPECT_TRUE(connection_.HasPendingPathValidation()); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath( &connection_, kNewSelfAddress, connection_.peer_address())); EXPECT_FALSE(alt_path->validated); for (size_t j = 0; j < QuicPathValidator::kMaxRetryTimes + 1; ++j) { clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs)); static_cast<TestAlarmFactory::TestAlarm*>( QuicPathValidatorPeer::retry_timer( QuicConnectionPeer::path_validator(&connection_))) ->Fire(); } EXPECT_FALSE(connection_.HasPendingPathValidation()); EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath( &connection_, kNewSelfAddress, connection_.peer_address())); EXPECT_EQ(1, connection_.GetStats().num_path_degrading); EXPECT_EQ(i + 2, stats->num_multi_port_probe_failures_when_path_degrading); } QuicNewConnectionIdFrame frame2; frame2.connection_id = TestConnectionId(1239); ASSERT_NE(frame2.connection_id, connection_.connection_id()); frame2.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame2.connection_id); frame2.retire_prior_to = 0u; frame2.sequence_number = 6u; EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame2)); EXPECT_FALSE(connection_.HasPendingPathValidation()); EXPECT_EQ(kMaxNumMultiPortPaths, stats->num_multi_port_probe_failures_when_path_degrading); } TEST_P(QuicConnectionTest, MultiPortPathReceivesStatelessReset) { set_perspective(Perspective::IS_CLIENT); QuicConfig config; QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestStatelessResetToken); config.SetClientConnectionOptions(QuicTagVector{kMPQC}); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); if (!version().HasIetfQuicFrames()) { return; } connection_.CreateConnectionIdManager(); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.OnHandshakeComplete(); EXPECT_CALL(visitor_, OnPathDegrading()); connection_.OnPathDegradingDetected(); auto self_address = connection_.self_address(); const QuicSocketAddress kNewSelfAddress(self_address.host(), self_address.port() + 1); EXPECT_NE(kNewSelfAddress, self_address); TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(1234); ASSERT_NE(frame.connection_id, connection_.connection_id()); frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); frame.retire_prior_to = 0u; frame.sequence_number = 1u; EXPECT_CALL(visitor_, CreateContextForMultiPortPath) .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) { observer->OnMultiPortPathContextAvailable( std::move(std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress, connection_.peer_address(), &new_writer))); })); connection_.OnNewConnectionIdFrame(frame); EXPECT_TRUE(connection_.HasPendingPathValidation()); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath( &connection_, kNewSelfAddress, connection_.peer_address())); auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_); EXPECT_FALSE(alt_path->validated); EXPECT_EQ(PathValidationReason::kMultiPort, QuicConnectionPeer::path_validator(&connection_) ->GetPathValidationReason()); std::unique_ptr<QuicEncryptedPacket> packet( QuicFramer::BuildIetfStatelessResetPacket(connection_id_, 100, kTestStatelessResetToken)); std::unique_ptr<QuicReceivedPacket> received( ConstructReceivedPacket(*packet, QuicTime::Zero())); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER)) .Times(0); connection_.ProcessUdpPacket(kNewSelfAddress, kPeerAddress, *received); EXPECT_EQ(connection_.GetStats().num_client_probing_attempts, 1); EXPECT_EQ(connection_.GetStats().num_stateless_resets_on_alternate_path, 1); } TEST_P(QuicConnectionTest, MultiPortPathRespectsActiveMigrationConfig) { if (!version().HasIetfQuicFrames()) { return; } set_perspective(Perspective::IS_CLIENT); QuicConfig config; QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestStatelessResetToken); QuicConfigPeer::SetReceivedDisableConnectionMigration(&config); config.SetClientConnectionOptions(QuicTagVector{kMPQC}); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); connection_.CreateConnectionIdManager(); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.OnHandshakeComplete(); EXPECT_CALL(visitor_, OnPathDegrading()); connection_.OnPathDegradingDetected(); QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(1234); ASSERT_NE(frame.connection_id, connection_.connection_id()); frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); frame.retire_prior_to = 0u; frame.sequence_number = 1u; EXPECT_CALL(visitor_, CreateContextForMultiPortPath).Times(0); connection_.OnNewConnectionIdFrame(frame); EXPECT_FALSE(connection_.HasPendingPathValidation()); } TEST_P(QuicConnectionTest, PathDegradingWhenAltPathIsNotReady) { set_perspective(Perspective::IS_CLIENT); QuicConfig config; config.SetClientConnectionOptions(QuicTagVector{kMPQC}); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); if (!version().HasIetfQuicFrames()) { return; } connection_.CreateConnectionIdManager(); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.OnHandshakeComplete(); auto self_address = connection_.self_address(); const QuicSocketAddress kNewSelfAddress(self_address.host(), self_address.port() + 1); EXPECT_NE(kNewSelfAddress, self_address); TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()) .WillRepeatedly(Return(true)); QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(1234); ASSERT_NE(frame.connection_id, connection_.connection_id()); frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); frame.retire_prior_to = 0u; frame.sequence_number = 1u; EXPECT_CALL(visitor_, CreateContextForMultiPortPath) .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) { observer->OnMultiPortPathContextAvailable( std::move(std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress, connection_.peer_address(), &new_writer))); })); EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame)); EXPECT_TRUE(connection_.HasPendingPathValidation()); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath( &connection_, kNewSelfAddress, connection_.peer_address())); auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_); EXPECT_FALSE(alt_path->validated); EXPECT_CALL(visitor_, OnPathDegrading()); EXPECT_CALL(visitor_, MigrateToMultiPortPath(_)).Times(0); connection_.OnPathDegradingDetected(); const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30); clock_.AdvanceTime(kTestRTT); QuicFrames frames; frames.push_back(QuicFrame(QuicPathResponseFrame( 99, new_writer.path_challenge_frames().back().data_buffer))); ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_FALSE(connection_.HasPendingPathValidation()); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath( &connection_, kNewSelfAddress, connection_.peer_address())); EXPECT_TRUE(alt_path->validated); } TEST_P(QuicConnectionTest, PathDegradingWhenAltPathIsReadyAndNotProbing) { EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); set_perspective(Perspective::IS_CLIENT); QuicConfig config; config.SetClientConnectionOptions(QuicTagVector{kMPQC, kMPQM}); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); if (!version().HasIetfQuicFrames()) { return; } connection_.CreateConnectionIdManager(); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.OnHandshakeComplete(); auto self_address = connection_.self_address(); const QuicSocketAddress kNewSelfAddress(self_address.host(), self_address.port() + 1); EXPECT_NE(kNewSelfAddress, self_address); TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()) .WillRepeatedly(Return(true)); QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(1234); ASSERT_NE(frame.connection_id, connection_.connection_id()); frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); frame.retire_prior_to = 0u; frame.sequence_number = 1u; EXPECT_CALL(visitor_, CreateContextForMultiPortPath) .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) { observer->OnMultiPortPathContextAvailable( std::move(std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress, connection_.peer_address(), &new_writer))); })); EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame)); EXPECT_TRUE(connection_.HasPendingPathValidation()); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath( &connection_, kNewSelfAddress, connection_.peer_address())); auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_); EXPECT_FALSE(alt_path->validated); const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30); clock_.AdvanceTime(kTestRTT); QuicFrames frames; frames.push_back(QuicFrame(QuicPathResponseFrame( 99, new_writer.path_challenge_frames().back().data_buffer))); ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_FALSE(connection_.HasPendingPathValidation()); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath( &connection_, kNewSelfAddress, connection_.peer_address())); EXPECT_TRUE(alt_path->validated); EXPECT_CALL(visitor_, OnPathDegrading()); EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(0); EXPECT_CALL(visitor_, MigrateToMultiPortPath(_)) .WillOnce(Invoke([&](std::unique_ptr<QuicPathValidationContext> context) { EXPECT_EQ(context->self_address(), kNewSelfAddress); connection_.MigratePath(context->self_address(), context->peer_address(), context->WriterToUse(), false); })); connection_.OnPathDegradingDetected(); } TEST_P(QuicConnectionTest, PathDegradingWhenAltPathIsReadyAndProbing) { EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); set_perspective(Perspective::IS_CLIENT); QuicConfig config; config.SetClientConnectionOptions(QuicTagVector{kMPQC, kMPQM}); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); if (!version().HasIetfQuicFrames()) { return; } connection_.CreateConnectionIdManager(); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.OnHandshakeComplete(); auto self_address = connection_.self_address(); const QuicSocketAddress kNewSelfAddress(self_address.host(), self_address.port() + 1); EXPECT_NE(kNewSelfAddress, self_address); TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()) .WillRepeatedly(Return(true)); QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(1234); ASSERT_NE(frame.connection_id, connection_.connection_id()); frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); frame.retire_prior_to = 0u; frame.sequence_number = 1u; EXPECT_CALL(visitor_, CreateContextForMultiPortPath) .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) { observer->OnMultiPortPathContextAvailable( std::move(std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress, connection_.peer_address(), &new_writer))); })); EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame)); EXPECT_TRUE(connection_.HasPendingPathValidation()); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath( &connection_, kNewSelfAddress, connection_.peer_address())); auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_); EXPECT_FALSE(alt_path->validated); const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30); clock_.AdvanceTime(kTestRTT); QuicFrames frames; frames.push_back(QuicFrame(QuicPathResponseFrame( 99, new_writer.path_challenge_frames().back().data_buffer))); ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_FALSE(connection_.HasPendingPathValidation()); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath( &connection_, kNewSelfAddress, connection_.peer_address())); EXPECT_TRUE(alt_path->validated); random_generator_.ChangeValue(); connection_.GetMultiPortProbingAlarm()->Fire(); EXPECT_TRUE(connection_.HasPendingPathValidation()); EXPECT_FALSE(connection_.GetMultiPortProbingAlarm()->IsSet()); EXPECT_CALL(visitor_, OnPathDegrading()); EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(0); EXPECT_CALL(visitor_, MigrateToMultiPortPath(_)) .WillOnce(Invoke([&](std::unique_ptr<QuicPathValidationContext> context) { EXPECT_EQ(context->self_address(), kNewSelfAddress); connection_.MigratePath(context->self_address(), context->peer_address(), context->WriterToUse(), false); })); connection_.OnPathDegradingDetected(); EXPECT_FALSE(connection_.HasPendingPathValidation()); auto* path_validator = QuicConnectionPeer::path_validator(&connection_); EXPECT_FALSE(QuicPathValidatorPeer::retry_timer(path_validator)->IsSet()); } TEST_P(QuicConnectionTest, SingleAckInPacket) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); EXPECT_CALL(visitor_, OnConnectionClosed(_, _)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.RemoveEncrypter(ENCRYPTION_INITIAL); connection_.NeuterUnencryptedPackets(); connection_.OnHandshakeComplete(); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_COMPLETE)); EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=, this]() { connection_.SendStreamData3(); connection_.CloseConnection( QUIC_INTERNAL_ERROR, "error", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); })); QuicFrames frames; frames.push_back(QuicFrame(frame1_)); ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress, ENCRYPTION_FORWARD_SECURE); ASSERT_FALSE(writer_->ack_frames().empty()); EXPECT_EQ(1u, writer_->ack_frames().size()); } TEST_P(QuicConnectionTest, ServerReceivedZeroRttPacketAfterOneRttPacketWithRetainedKey) { if (!connection_.version().UsesTls()) { return; } set_perspective(Perspective::IS_SERVER); SetDecrypter(ENCRYPTION_ZERO_RTT, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT)); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); notifier_.NeuterUnencryptedData(); connection_.NeuterUnencryptedPackets(); connection_.OnHandshakeComplete(); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_COMPLETE)); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE); EXPECT_TRUE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet()); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT); EXPECT_EQ( 0u, connection_.GetStats() .num_tls_server_zero_rtt_packets_received_after_discarding_decrypter); connection_.GetDiscardZeroRttDecryptionKeysAlarm()->Fire(); EXPECT_FALSE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet()); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(0); ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT); EXPECT_EQ( 1u, connection_.GetStats() .num_tls_server_zero_rtt_packets_received_after_discarding_decrypter); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacketAtLevel(5, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE); EXPECT_FALSE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet()); } TEST_P(QuicConnectionTest, NewTokenFrameInstigateAcks) { if (!version().HasIetfQuicFrames()) { return; } EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); QuicNewTokenFrame* new_token = new QuicNewTokenFrame(); EXPECT_CALL(visitor_, OnNewTokenReceived(_)); ProcessFramePacket(QuicFrame(new_token)); EXPECT_TRUE(connection_.HasPendingAcks()); } TEST_P(QuicConnectionTest, ServerClosesConnectionOnNewTokenFrame) { if (!version().HasIetfQuicFrames()) { return; } set_perspective(Perspective::IS_SERVER); QuicNewTokenFrame* new_token = new QuicNewTokenFrame(); EXPECT_CALL(visitor_, OnNewTokenReceived(_)).Times(0); EXPECT_CALL(visitor_, OnConnectionClosed(_, _)); EXPECT_CALL(visitor_, BeforeConnectionCloseSent()); ProcessFramePacket(QuicFrame(new_token)); EXPECT_FALSE(connection_.connected()); } TEST_P(QuicConnectionTest, OverrideRetryTokenWithRetryPacket) { if (!version().HasIetfQuicFrames()) { return; } std::string address_token = "TestAddressToken"; connection_.SetSourceAddressTokenToSend(address_token); EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken( QuicConnectionPeer::GetPacketCreator(&connection_)), address_token); TestClientRetryHandling(false, false, false, false, false); } TEST_P(QuicConnectionTest, DonotOverrideRetryTokenWithAddressToken) { if (!version().HasIetfQuicFrames()) { return; } TestClientRetryHandling(false, false, false, false, false); std::string retry_token = QuicPacketCreatorPeer::GetRetryToken( QuicConnectionPeer::GetPacketCreator(&connection_)); std::string address_token = "TestAddressToken"; connection_.SetSourceAddressTokenToSend(address_token); EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken( QuicConnectionPeer::GetPacketCreator(&connection_)), retry_token); } TEST_P(QuicConnectionTest, ServerReceivedZeroRttWithHigherPacketNumberThanOneRtt) { if (!connection_.version().UsesTls()) { return; } std::string error_details; TransportParameters params; QuicConfig config; EXPECT_THAT(config.ProcessTransportParameters( params, false, &error_details), IsQuicNoError()); QuicConfigPeer::SetNegotiated(&config, true); QuicConfigPeer::SetReceivedOriginalConnectionId(&config, connection_.connection_id()); QuicConfigPeer::SetReceivedInitialSourceConnectionId( &config, connection_.connection_id()); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); set_perspective(Perspective::IS_SERVER); SetDecrypter(ENCRYPTION_ZERO_RTT, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT)); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); notifier_.NeuterUnencryptedData(); connection_.NeuterUnencryptedPackets(); connection_.OnHandshakeComplete(); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_COMPLETE)); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE); EXPECT_TRUE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet()); EXPECT_CALL(visitor_, BeforeConnectionCloseSent()); EXPECT_CALL(visitor_, OnConnectionClosed(_, _)); ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT); EXPECT_FALSE(connection_.connected()); TestConnectionCloseQuicErrorCode( QUIC_INVALID_0RTT_PACKET_NUMBER_OUT_OF_ORDER); } TEST_P(QuicConnectionTest, PeerMigrateBeforeHandshakeConfirm) { if (!VersionHasIetfQuicFrames(version().transport_version)) { return; } set_perspective(Perspective::IS_SERVER); QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false); EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective()); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_START)); QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress()); QuicConnectionPeer::SetEffectivePeerAddress(&connection_, QuicSocketAddress()); EXPECT_FALSE(connection_.effective_peer_address().IsInitialized()); const QuicSocketAddress kNewPeerAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), 23456); EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress, ENCRYPTION_INITIAL); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); QuicAckFrame frame = InitAckFrame(1); EXPECT_CALL(visitor_, BeforeConnectionCloseSent()); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)); EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0u); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _)) .Times(0); ProcessFramePacketWithAddresses(QuicFrame(&frame), kSelfAddress, kNewPeerAddress, ENCRYPTION_INITIAL); EXPECT_FALSE(connection_.connected()); } TEST_P(QuicConnectionTest, TryToFlushAckWithAckQueued) { if (!version().HasIetfQuicFrames()) { return; } SetQuicReloadableFlag(quic_can_send_ack_frequency, true); set_perspective(Perspective::IS_SERVER); QuicConfig config; QuicConfigPeer::SetReceivedMinAckDelayMs(&config, 1); EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); connection_.SetFromConfig(config); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.OnHandshakeComplete(); QuicPacketCreatorPeer::SetPacketNumber(creator_, 200); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(visitor_, SendAckFrequency(_)) .WillOnce(Invoke(&notifier_, &SimpleSessionNotifier::WriteOrBufferAckFrequency)); QuicConnectionPeer::SendPing(&connection_); } TEST_P(QuicConnectionTest, PathChallengeBeforePeerIpAddressChangeAtServer) { set_perspective(Perspective::IS_SERVER); if (!version().HasIetfQuicFrames()) { return; } PathProbeTestInit(Perspective::IS_SERVER); SetClientConnectionId(TestConnectionId(1)); connection_.CreateConnectionIdManager(); QuicConnectionId server_cid0 = connection_.connection_id(); QuicConnectionId client_cid0 = connection_.client_connection_id(); QuicConnectionId client_cid1 = TestConnectionId(2); QuicConnectionId server_cid1; if (!connection_.connection_id().IsEmpty()) { EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_)) .WillOnce(Return(TestConnectionId(456))); } EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)) .WillOnce(Invoke([&](const QuicConnectionId& cid) { server_cid1 = cid; return true; })); EXPECT_CALL(visitor_, SendNewConnectionId(_)); connection_.MaybeSendConnectionIdToClient(); QuicNewConnectionIdFrame new_cid_frame; new_cid_frame.connection_id = client_cid1; new_cid_frame.sequence_number = 1u; new_cid_frame.retire_prior_to = 0u; connection_.OnNewConnectionIdFrame(new_cid_frame); auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_); ASSERT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0); ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0); peer_creator_.SetServerConnectionId(server_cid1); const QuicSocketAddress kNewPeerAddress = QuicSocketAddress(QuicIpAddress::Loopback4(), 23456); QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7}; QuicFrames frames1; frames1.push_back( QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload))); QuicPathFrameBuffer payload; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA)) .Times(AtLeast(1)) .WillOnce(Invoke([&]() { EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address()); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); EXPECT_FALSE(writer_->path_response_frames().empty()); EXPECT_FALSE(writer_->path_challenge_frames().empty()); payload = writer_->path_challenge_frames().front().data_buffer; })) .WillRepeatedly(DoDefault()); ; ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); EXPECT_TRUE(connection_.HasPendingPathValidation()); const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_); const auto* alternative_path = QuicConnectionPeer::GetAlternativePath(&connection_); EXPECT_EQ(default_path->client_connection_id, client_cid0); EXPECT_EQ(default_path->server_connection_id, server_cid0); EXPECT_EQ(alternative_path->client_connection_id, client_cid1); EXPECT_EQ(alternative_path->server_connection_id, server_cid1); EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0); EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0); EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1); EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=, this]() { EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); })); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA)) .Times(0); QuicFrames frames2; frames2.push_back(QuicFrame(frame2_)); ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address()); EXPECT_EQ(IPV6_TO_IPV4_CHANGE, connection_.active_effective_peer_migration_type()); EXPECT_TRUE(writer_->path_challenge_frames().empty()); EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(), send_algorithm_); send_algorithm_ = new StrictMock<MockSendAlgorithm>(); EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true)); EXPECT_CALL(*send_algorithm_, GetCongestionWindow()) .WillRepeatedly(Return(kDefaultTCPMSS)); EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber()); 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_, PopulateConnectionStats(_)).Times(AnyNumber()); connection_.SetSendAlgorithm(send_algorithm_); EXPECT_EQ(default_path->client_connection_id, client_cid1); EXPECT_EQ(default_path->server_connection_id, server_cid1); EXPECT_EQ(alternative_path->client_connection_id, client_cid0); EXPECT_EQ(alternative_path->server_connection_id, server_cid0); EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid1); EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid1); EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address()); EXPECT_EQ(IPV6_TO_IPV4_CHANGE, connection_.active_effective_peer_migration_type()); EXPECT_EQ(1u, connection_.GetStats() .num_peer_migration_to_proactively_validated_address); connection_.SendCryptoDataWithString("foo", 0); EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); QuicFrames frames3; frames3.push_back(QuicFrame(QuicPathResponseFrame(99, payload))); EXPECT_CALL(visitor_, MaybeSendAddressToken()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(testing::AtLeast(1u)); ProcessFramesPacketWithAddresses(frames3, kSelfAddress, kNewPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type()); EXPECT_TRUE(alternative_path->client_connection_id.IsEmpty()); EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty()); EXPECT_FALSE(alternative_path->stateless_reset_token.has_value()); auto* retire_peer_issued_cid_alarm = connection_.GetRetirePeerIssuedConnectionIdAlarm(); ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet()); EXPECT_CALL(visitor_, SendRetireConnectionId(0u)); retire_peer_issued_cid_alarm->Fire(); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); EXPECT_CALL(*send_algorithm_, PacingRate(_)) .WillRepeatedly(Return(QuicBandwidth::Zero())); connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0); EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration); EXPECT_EQ(1u, connection_.num_unlinkable_client_migration()); } TEST_P(QuicConnectionTest, PathValidationSucceedsBeforePeerIpAddressChangeAtServer) { set_perspective(Perspective::IS_SERVER); if (!version().HasIetfQuicFrames()) { return; } PathProbeTestInit(Perspective::IS_SERVER); connection_.CreateConnectionIdManager(); QuicConnectionId server_cid0 = connection_.connection_id(); QuicConnectionId server_cid1; if (!connection_.connection_id().IsEmpty()) { EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_)) .WillOnce(Return(TestConnectionId(456))); } EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)) .WillOnce(Invoke([&](const QuicConnectionId& cid) { server_cid1 = cid; return true; })); EXPECT_CALL(visitor_, SendNewConnectionId(_)); connection_.MaybeSendConnectionIdToClient(); auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_); ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0); peer_creator_.SetServerConnectionId(server_cid1); const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(), 23456); QuicPathFrameBuffer payload; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA)) .WillOnce(Invoke([&]() { EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address()); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); EXPECT_FALSE(writer_->path_response_frames().empty()); EXPECT_FALSE(writer_->path_challenge_frames().empty()); payload = writer_->path_challenge_frames().front().data_buffer; })) .WillRepeatedly(Invoke([&]() { EXPECT_TRUE(writer_->path_challenge_frames().empty()); })); QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7}; QuicFrames frames1; frames1.push_back( QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload))); ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_TRUE(connection_.HasPendingPathValidation()); const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_); const auto* alternative_path = QuicConnectionPeer::GetAlternativePath(&connection_); EXPECT_EQ(default_path->server_connection_id, server_cid0); EXPECT_EQ(alternative_path->server_connection_id, server_cid1); EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0); QuicFrames frames3; frames3.push_back(QuicFrame(QuicPathResponseFrame(99, payload))); ProcessFramesPacketWithAddresses(frames3, kSelfAddress, kNewPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA)) .Times(0); const QuicSocketAddress kNewerPeerAddress(QuicIpAddress::Loopback4(), 34567); EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=, this]() { EXPECT_EQ(kNewerPeerAddress, connection_.peer_address()); })); EXPECT_CALL(visitor_, MaybeSendAddressToken()); QuicFrames frames2; frames2.push_back(QuicFrame(frame2_)); ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewerPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(kNewerPeerAddress, connection_.peer_address()); EXPECT_EQ(kNewerPeerAddress, connection_.effective_peer_address()); EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type()); EXPECT_EQ(kNewerPeerAddress, writer_->last_write_peer_address()); EXPECT_EQ(1u, connection_.GetStats() .num_peer_migration_to_proactively_validated_address); EXPECT_FALSE(connection_.HasPendingPathValidation()); EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(), send_algorithm_); EXPECT_EQ(default_path->server_connection_id, server_cid1); EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid1); EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty()); EXPECT_FALSE(alternative_path->stateless_reset_token.has_value()); send_algorithm_ = new StrictMock<MockSendAlgorithm>(); EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true)); EXPECT_CALL(*send_algorithm_, GetCongestionWindow()) .WillRepeatedly(Return(kDefaultTCPMSS)); EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber()); 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_, PopulateConnectionStats(_)).Times(AnyNumber()); connection_.SetSendAlgorithm(send_algorithm_); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)); connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0); EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration); } TEST_P(QuicConnectionTest, NoNonProbingFrameOnAlternativePath) { if (!version().HasIetfQuicFrames()) { return; } PathProbeTestInit(Perspective::IS_SERVER); SetClientConnectionId(TestConnectionId(1)); connection_.CreateConnectionIdManager(); QuicConnectionId server_cid0 = connection_.connection_id(); QuicConnectionId client_cid0 = connection_.client_connection_id(); QuicConnectionId client_cid1 = TestConnectionId(2); QuicConnectionId server_cid1; if (!connection_.connection_id().IsEmpty()) { EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_)) .WillOnce(Return(TestConnectionId(456))); } EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)) .WillOnce(Invoke([&](const QuicConnectionId& cid) { server_cid1 = cid; return true; })); EXPECT_CALL(visitor_, SendNewConnectionId(_)); connection_.MaybeSendConnectionIdToClient(); QuicNewConnectionIdFrame new_cid_frame; new_cid_frame.connection_id = client_cid1; new_cid_frame.sequence_number = 1u; new_cid_frame.retire_prior_to = 0u; connection_.OnNewConnectionIdFrame(new_cid_frame); auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_); ASSERT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0); ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0); peer_creator_.SetServerConnectionId(server_cid1); const QuicSocketAddress kNewPeerAddress = QuicSocketAddress(QuicIpAddress::Loopback4(), 23456); QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7}; QuicFrames frames1; frames1.push_back( QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload))); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA)) .Times(AtLeast(1)) .WillOnce(Invoke([&]() { EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address()); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); EXPECT_FALSE(writer_->path_response_frames().empty()); EXPECT_FALSE(writer_->path_challenge_frames().empty()); })) .WillRepeatedly(DoDefault()); ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); EXPECT_TRUE(connection_.HasPendingPathValidation()); const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_); const auto* alternative_path = QuicConnectionPeer::GetAlternativePath(&connection_); EXPECT_EQ(default_path->client_connection_id, client_cid0); EXPECT_EQ(default_path->server_connection_id, server_cid0); EXPECT_EQ(alternative_path->client_connection_id, client_cid1); EXPECT_EQ(alternative_path->server_connection_id, server_cid1); EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0); EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0); peer_creator_.SetServerConnectionId(server_cid0); EXPECT_CALL(visitor_, OnStreamFrame(_)).WillRepeatedly(Invoke([=, this]() { EXPECT_EQ(kPeerAddress, connection_.peer_address()); })); for (size_t i = 3; i <= 39; ++i) { ProcessDataPacket(i); } EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kPeerAddress, connection_.effective_peer_address()); EXPECT_TRUE(connection_.HasPendingAcks()); QuicTime ack_time = connection_.GetAckAlarm()->deadline(); QuicTime path_validation_retry_time = connection_.GetRetryTimeout(kNewPeerAddress, writer_.get()); clock_.AdvanceTime(std::max(ack_time, path_validation_retry_time) - clock_.ApproximateNow()); EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()) .WillOnce(Invoke([this]() { connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0))); })); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .WillOnce(Invoke([&]() { EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address()); EXPECT_FALSE(writer_->path_challenge_frames().empty()); EXPECT_TRUE(writer_->ack_frames().empty()); })) .WillOnce(Invoke([&]() { EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address()); EXPECT_FALSE(writer_->ack_frames().empty()); EXPECT_FALSE(writer_->window_update_frames().empty()); })); static_cast<TestAlarmFactory::TestAlarm*>( QuicPathValidatorPeer::retry_timer( QuicConnectionPeer::path_validator(&connection_))) ->Fire(); } TEST_P(QuicConnectionTest, DoNotIssueNewCidIfVisitorSaysNo) { set_perspective(Perspective::IS_SERVER); if (!version().HasIetfQuicFrames()) { return; } connection_.CreateConnectionIdManager(); QuicConnectionId server_cid0 = connection_.connection_id(); QuicConnectionId client_cid1 = TestConnectionId(2); QuicConnectionId server_cid1; if (!connection_.connection_id().IsEmpty()) { EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_)) .WillOnce(Return(TestConnectionId(456))); } EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(false)); EXPECT_CALL(visitor_, SendNewConnectionId(_)).Times(0); connection_.MaybeSendConnectionIdToClient(); } TEST_P(QuicConnectionTest, ProbedOnAnotherPathAfterPeerIpAddressChangeAtServer) { PathProbeTestInit(Perspective::IS_SERVER); if (!version().HasIetfQuicFrames()) { return; } const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(), 23456); EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA)) .Times(0); EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=, this]() { EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); })); QuicFrames frames2; frames2.push_back(QuicFrame(frame2_)); ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_)); EXPECT_TRUE(connection_.HasPendingPathValidation()); send_algorithm_ = new StrictMock<MockSendAlgorithm>(); EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true)); EXPECT_CALL(*send_algorithm_, GetCongestionWindow()) .WillRepeatedly(Return(kDefaultTCPMSS)); EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber()); 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_, PopulateConnectionStats(_)).Times(AnyNumber()); connection_.SetSendAlgorithm(send_algorithm_); const QuicSocketAddress kNewerPeerAddress(QuicIpAddress::Loopback4(), 34567); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .WillOnce(Invoke([&]() { EXPECT_EQ(kNewerPeerAddress, writer_->last_write_peer_address()); EXPECT_FALSE(writer_->path_response_frames().empty()); EXPECT_TRUE(writer_->path_challenge_frames().empty()); })); QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7}; QuicFrames frames1; frames1.push_back( QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload))); ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewerPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address()); EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_)); EXPECT_TRUE(connection_.HasPendingPathValidation()); } TEST_P(QuicConnectionTest, PathValidationFailedOnClientDueToLackOfServerConnectionId) { if (!version().HasIetfQuicFrames()) { return; } PathProbeTestInit(Perspective::IS_CLIENT, false); const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Loopback4(), 34567); bool success; connection_.ValidatePath( std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress, connection_.peer_address(), writer_.get()), std::make_unique<TestValidationResultDelegate>( &connection_, kNewSelfAddress, connection_.peer_address(), &success), PathValidationReason::kReasonUnknown); EXPECT_FALSE(success); } TEST_P(QuicConnectionTest, PathValidationFailedOnClientDueToLackOfClientConnectionIdTheSecondTime) { if (!version().HasIetfQuicFrames()) { return; } PathProbeTestInit(Perspective::IS_CLIENT, false); SetClientConnectionId(TestConnectionId(1)); QuicConnectionId server_cid0 = connection_.connection_id(); QuicConnectionId server_cid1 = TestConnectionId(2); QuicConnectionId server_cid2 = TestConnectionId(4); QuicConnectionId client_cid1; QuicNewConnectionIdFrame frame1; frame1.connection_id = server_cid1; frame1.sequence_number = 1u; frame1.retire_prior_to = 0u; frame1.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame1.connection_id); connection_.OnNewConnectionIdFrame(frame1); const auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_); ASSERT_EQ(packet_creator->GetDestinationConnectionId(), server_cid0); EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_)) .WillOnce(Return(TestConnectionId(456))); EXPECT_CALL(visitor_, SendNewConnectionId(_)) .WillOnce(Invoke([&](const QuicNewConnectionIdFrame& frame) { client_cid1 = frame.connection_id; })); const QuicSocketAddress kSelfAddress1(QuicIpAddress::Any4(), 12345); ASSERT_NE(kSelfAddress1, connection_.self_address()); bool success1; connection_.ValidatePath( std::make_unique<TestQuicPathValidationContext>( kSelfAddress1, connection_.peer_address(), writer_.get()), std::make_unique<TestValidationResultDelegate>( &connection_, kSelfAddress1, connection_.peer_address(), &success1), PathValidationReason::kReasonUnknown); TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); ASSERT_TRUE(connection_.MigratePath(kSelfAddress1, connection_.peer_address(), &new_writer, false)); QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_); const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_); EXPECT_EQ(default_path->client_connection_id, client_cid1); EXPECT_EQ(default_path->server_connection_id, server_cid1); EXPECT_EQ(default_path->stateless_reset_token, frame1.stateless_reset_token); const auto* alternative_path = QuicConnectionPeer::GetAlternativePath(&connection_); EXPECT_TRUE(alternative_path->client_connection_id.IsEmpty()); EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty()); EXPECT_FALSE(alternative_path->stateless_reset_token.has_value()); ASSERT_EQ(packet_creator->GetDestinationConnectionId(), server_cid1); auto* retire_peer_issued_cid_alarm = connection_.GetRetirePeerIssuedConnectionIdAlarm(); ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet()); EXPECT_CALL(visitor_, SendRetireConnectionId(0u)); retire_peer_issued_cid_alarm->Fire(); QuicNewConnectionIdFrame frame2; frame2.connection_id = server_cid2; frame2.sequence_number = 2u; frame2.retire_prior_to = 1u; frame2.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame2.connection_id); connection_.OnNewConnectionIdFrame(frame2); const QuicSocketAddress kSelfAddress2(QuicIpAddress::Loopback4(), 45678); bool success2; connection_.ValidatePath( std::make_unique<TestQuicPathValidationContext>( kSelfAddress2, connection_.peer_address(), writer_.get()), std::make_unique<TestValidationResultDelegate>( &connection_, kSelfAddress2, connection_.peer_address(), &success2), PathValidationReason::kReasonUnknown); EXPECT_FALSE(success2); } TEST_P(QuicConnectionTest, ServerConnectionIdRetiredUponPathValidationFailure) { if (!version().HasIetfQuicFrames()) { return; } PathProbeTestInit(Perspective::IS_CLIENT); QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(2); frame.sequence_number = 1u; frame.retire_prior_to = 0u; frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); connection_.OnNewConnectionIdFrame(frame); const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Loopback4(), 34567); bool success; connection_.ValidatePath( std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress, connection_.peer_address(), writer_.get()), std::make_unique<TestValidationResultDelegate>( &connection_, kNewSelfAddress, connection_.peer_address(), &success), PathValidationReason::kReasonUnknown); auto* path_validator = QuicConnectionPeer::path_validator(&connection_); path_validator->CancelPathValidation(); QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_); EXPECT_FALSE(success); const auto* alternative_path = QuicConnectionPeer::GetAlternativePath(&connection_); EXPECT_TRUE(alternative_path->client_connection_id.IsEmpty()); EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty()); EXPECT_FALSE(alternative_path->stateless_reset_token.has_value()); auto* retire_peer_issued_cid_alarm = connection_.GetRetirePeerIssuedConnectionIdAlarm(); ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet()); EXPECT_CALL(visitor_, SendRetireConnectionId(1u)); retire_peer_issued_cid_alarm->Fire(); } TEST_P(QuicConnectionTest, MigratePathDirectlyFailedDueToLackOfServerConnectionId) { if (!version().HasIetfQuicFrames()) { return; } PathProbeTestInit(Perspective::IS_CLIENT, false); const QuicSocketAddress kSelfAddress1(QuicIpAddress::Any4(), 12345); ASSERT_NE(kSelfAddress1, connection_.self_address()); TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); ASSERT_FALSE(connection_.MigratePath(kSelfAddress1, connection_.peer_address(), &new_writer, false)); } TEST_P(QuicConnectionTest, MigratePathDirectlyFailedDueToLackOfClientConnectionIdTheSecondTime) { if (!version().HasIetfQuicFrames()) { return; } PathProbeTestInit(Perspective::IS_CLIENT, false); SetClientConnectionId(TestConnectionId(1)); QuicNewConnectionIdFrame frame1; frame1.connection_id = TestConnectionId(2); frame1.sequence_number = 1u; frame1.retire_prior_to = 0u; frame1.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame1.connection_id); connection_.OnNewConnectionIdFrame(frame1); QuicConnectionId new_client_connection_id; EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_)) .WillOnce(Return(TestConnectionId(456))); EXPECT_CALL(visitor_, SendNewConnectionId(_)) .WillOnce(Invoke([&](const QuicNewConnectionIdFrame& frame) { new_client_connection_id = frame.connection_id; })); const QuicSocketAddress kSelfAddress1(QuicIpAddress::Any4(), 12345); ASSERT_NE(kSelfAddress1, connection_.self_address()); TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); ASSERT_TRUE(connection_.MigratePath(kSelfAddress1, connection_.peer_address(), &new_writer, false)); QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_); const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_); EXPECT_EQ(default_path->client_connection_id, new_client_connection_id); EXPECT_EQ(default_path->server_connection_id, frame1.connection_id); EXPECT_EQ(default_path->stateless_reset_token, frame1.stateless_reset_token); auto* retire_peer_issued_cid_alarm = connection_.GetRetirePeerIssuedConnectionIdAlarm(); ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet()); EXPECT_CALL(visitor_, SendRetireConnectionId(0u)); retire_peer_issued_cid_alarm->Fire(); QuicNewConnectionIdFrame frame2; frame2.connection_id = TestConnectionId(4); frame2.sequence_number = 2u; frame2.retire_prior_to = 1u; frame2.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame2.connection_id); connection_.OnNewConnectionIdFrame(frame2); const QuicSocketAddress kSelfAddress2(QuicIpAddress::Loopback4(), 45678); auto new_writer2 = std::make_unique<TestPacketWriter>(version(), &clock_, Perspective::IS_CLIENT); ASSERT_FALSE(connection_.MigratePath( kSelfAddress2, connection_.peer_address(), new_writer2.release(), true)); } TEST_P(QuicConnectionTest, CloseConnectionAfterReceiveNewConnectionIdFromPeerUsingEmptyCID) { if (!version().HasIetfQuicFrames()) { return; } set_perspective(Perspective::IS_SERVER); ASSERT_TRUE(connection_.client_connection_id().IsEmpty()); EXPECT_CALL(visitor_, BeforeConnectionCloseSent()); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)) .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame)); QuicNewConnectionIdFrame frame; frame.sequence_number = 1u; frame.connection_id = TestConnectionId(1); frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); frame.retire_prior_to = 0u; EXPECT_FALSE(connection_.OnNewConnectionIdFrame(frame)); EXPECT_FALSE(connection_.connected()); EXPECT_THAT(saved_connection_close_frame_.quic_error_code, IsError(IETF_QUIC_PROTOCOL_VIOLATION)); } TEST_P(QuicConnectionTest, NewConnectionIdFrameResultsInError) { if (!version().HasIetfQuicFrames()) { return; } connection_.CreateConnectionIdManager(); ASSERT_FALSE(connection_.connection_id().IsEmpty()); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)) .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame)); QuicNewConnectionIdFrame frame; frame.sequence_number = 1u; frame.connection_id = connection_id_; frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); frame.retire_prior_to = 0u; EXPECT_FALSE(connection_.OnNewConnectionIdFrame(frame)); EXPECT_FALSE(connection_.connected()); EXPECT_THAT(saved_connection_close_frame_.quic_error_code, IsError(IETF_QUIC_PROTOCOL_VIOLATION)); } TEST_P(QuicConnectionTest, ClientRetirePeerIssuedConnectionIdTriggeredByNewConnectionIdFrame) { if (!version().HasIetfQuicFrames()) { return; } connection_.CreateConnectionIdManager(); QuicNewConnectionIdFrame frame; frame.sequence_number = 1u; frame.connection_id = TestConnectionId(1); frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); frame.retire_prior_to = 0u; EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame)); auto* retire_peer_issued_cid_alarm = connection_.GetRetirePeerIssuedConnectionIdAlarm(); ASSERT_FALSE(retire_peer_issued_cid_alarm->IsSet()); frame.sequence_number = 2u; frame.connection_id = TestConnectionId(2); frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); frame.retire_prior_to = 1u; EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame)); ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet()); EXPECT_EQ(connection_.connection_id(), connection_id_); EXPECT_CALL(visitor_, SendRetireConnectionId(0u)); retire_peer_issued_cid_alarm->Fire(); EXPECT_EQ(connection_.connection_id(), TestConnectionId(2)); EXPECT_EQ(connection_.packet_creator().GetDestinationConnectionId(), TestConnectionId(2)); } TEST_P(QuicConnectionTest, ServerRetirePeerIssuedConnectionIdTriggeredByNewConnectionIdFrame) { if (!version().HasIetfQuicFrames()) { return; } set_perspective(Perspective::IS_SERVER); SetClientConnectionId(TestConnectionId(0)); QuicNewConnectionIdFrame frame; frame.sequence_number = 1u; frame.connection_id = TestConnectionId(1); frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); frame.retire_prior_to = 0u; EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame)); auto* retire_peer_issued_cid_alarm = connection_.GetRetirePeerIssuedConnectionIdAlarm(); ASSERT_FALSE(retire_peer_issued_cid_alarm->IsSet()); frame.sequence_number = 2u; frame.connection_id = TestConnectionId(2); frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); frame.retire_prior_to = 1u; EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame)); ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet()); EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(0)); EXPECT_CALL(visitor_, SendRetireConnectionId(0u)); retire_peer_issued_cid_alarm->Fire(); EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(2)); EXPECT_EQ(connection_.packet_creator().GetDestinationConnectionId(), TestConnectionId(2)); } TEST_P( QuicConnectionTest, ReplacePeerIssuedConnectionIdOnBothPathsTriggeredByNewConnectionIdFrame) { if (!version().HasIetfQuicFrames()) { return; } PathProbeTestInit(Perspective::IS_SERVER); SetClientConnectionId(TestConnectionId(0)); std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket(); std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket( QuicEncryptedPacket(probing_packet->encrypted_buffer, probing_packet->encrypted_length), clock_.Now())); QuicIpAddress new_host; new_host.FromString("1.1.1.1"); ProcessReceivedPacket(kSelfAddress, QuicSocketAddress(new_host, 23456), *received); EXPECT_EQ( TestConnectionId(0), QuicConnectionPeer::GetClientConnectionIdOnAlternativePath(&connection_)); QuicNewConnectionIdFrame frame; frame.sequence_number = 1u; frame.connection_id = TestConnectionId(1); frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); frame.retire_prior_to = 0u; EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame)); auto* retire_peer_issued_cid_alarm = connection_.GetRetirePeerIssuedConnectionIdAlarm(); ASSERT_FALSE(retire_peer_issued_cid_alarm->IsSet()); frame.sequence_number = 2u; frame.connection_id = TestConnectionId(2); frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); frame.retire_prior_to = 1u; EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame)); ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet()); EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(0)); EXPECT_CALL(visitor_, SendRetireConnectionId(0u)); retire_peer_issued_cid_alarm->Fire(); EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(2)); EXPECT_EQ(connection_.packet_creator().GetDestinationConnectionId(), TestConnectionId(2)); EXPECT_EQ( TestConnectionId(2), QuicConnectionPeer::GetClientConnectionIdOnAlternativePath(&connection_)); } TEST_P(QuicConnectionTest, CloseConnectionAfterReceiveRetireConnectionIdWhenNoCIDIssued) { if (!version().HasIetfQuicFrames()) { return; } set_perspective(Perspective::IS_SERVER); EXPECT_CALL(visitor_, BeforeConnectionCloseSent()); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)) .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame)); QuicRetireConnectionIdFrame frame; frame.sequence_number = 1u; EXPECT_FALSE(connection_.OnRetireConnectionIdFrame(frame)); EXPECT_FALSE(connection_.connected()); EXPECT_THAT(saved_connection_close_frame_.quic_error_code, IsError(IETF_QUIC_PROTOCOL_VIOLATION)); } TEST_P(QuicConnectionTest, RetireConnectionIdFrameResultsInError) { if (!version().HasIetfQuicFrames()) { return; } set_perspective(Perspective::IS_SERVER); connection_.CreateConnectionIdManager(); if (!connection_.connection_id().IsEmpty()) { EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_)) .WillOnce(Return(TestConnectionId(456))); } EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(true)); EXPECT_CALL(visitor_, SendNewConnectionId(_)); connection_.MaybeSendConnectionIdToClient(); EXPECT_CALL(visitor_, BeforeConnectionCloseSent()); EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF)) .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame)); QuicRetireConnectionIdFrame frame; frame.sequence_number = 2u; EXPECT_FALSE(connection_.OnRetireConnectionIdFrame(frame)); EXPECT_FALSE(connection_.connected()); EXPECT_THAT(saved_connection_close_frame_.quic_error_code, IsError(IETF_QUIC_PROTOCOL_VIOLATION)); } TEST_P(QuicConnectionTest, ServerRetireSelfIssuedConnectionIdWithoutSendingNewConnectionIdBefore) { if (!version().HasIetfQuicFrames()) { return; } set_perspective(Perspective::IS_SERVER); connection_.CreateConnectionIdManager(); auto* retire_self_issued_cid_alarm = connection_.GetRetireSelfIssuedConnectionIdAlarm(); ASSERT_FALSE(retire_self_issued_cid_alarm->IsSet()); QuicConnectionId cid0 = connection_id_; QuicRetireConnectionIdFrame frame; frame.sequence_number = 0u; if (!connection_.connection_id().IsEmpty()) { EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(cid0)) .WillOnce(Return(TestConnectionId(456))); EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(TestConnectionId(456))) .WillOnce(Return(TestConnectionId(789))); } EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)) .Times(2) .WillRepeatedly(Return(true)); EXPECT_CALL(visitor_, SendNewConnectionId(_)).Times(2); EXPECT_TRUE(connection_.OnRetireConnectionIdFrame(frame)); } TEST_P(QuicConnectionTest, ServerRetireSelfIssuedConnectionId) { if (!version().HasIetfQuicFrames()) { return; } set_perspective(Perspective::IS_SERVER); connection_.CreateConnectionIdManager(); QuicConnectionId recorded_cid; auto cid_recorder = [&recorded_cid](const QuicConnectionId& cid) -> bool { recorded_cid = cid; return true; }; QuicConnectionId cid0 = connection_id_; QuicConnectionId cid1; QuicConnectionId cid2; EXPECT_EQ(connection_.connection_id(), cid0); EXPECT_EQ(connection_.GetOneActiveServerConnectionId(), cid0); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); if (!connection_.connection_id().IsEmpty()) { EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_)) .WillOnce(Return(TestConnectionId(456))); } EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)) .WillOnce(Invoke(cid_recorder)); EXPECT_CALL(visitor_, SendNewConnectionId(_)); connection_.MaybeSendConnectionIdToClient(); cid1 = recorded_cid; auto* retire_self_issued_cid_alarm = connection_.GetRetireSelfIssuedConnectionIdAlarm(); ASSERT_FALSE(retire_self_issued_cid_alarm->IsSet()); char buffers[3][kMaxOutgoingPacketSize]; auto packet1 = ConstructPacket({QuicFrame(QuicPingFrame())}, ENCRYPTION_FORWARD_SECURE, buffers[0], kMaxOutgoingPacketSize); peer_creator_.SetServerConnectionId(cid1); auto retire_cid_frame = std::make_unique<QuicRetireConnectionIdFrame>(); retire_cid_frame->sequence_number = 0u; auto packet2 = ConstructPacket({QuicFrame(retire_cid_frame.release())}, ENCRYPTION_FORWARD_SECURE, buffers[1], kMaxOutgoingPacketSize); auto packet3 = ConstructPacket({QuicFrame(QuicPingFrame())}, ENCRYPTION_FORWARD_SECURE, buffers[2], kMaxOutgoingPacketSize); if (!connection_.connection_id().IsEmpty()) { EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_)) .WillOnce(Return(TestConnectionId(456))); } EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)) .WillOnce(Invoke(cid_recorder)); EXPECT_CALL(visitor_, SendNewConnectionId(_)); peer_creator_.SetServerConnectionId(cid1); connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *packet2); cid2 = recorded_cid; EXPECT_THAT(connection_.GetActiveServerConnectionIds(), ElementsAre(cid0, cid1, cid2)); ASSERT_TRUE(retire_self_issued_cid_alarm->IsSet()); EXPECT_EQ(connection_.connection_id(), cid1); EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid0 || connection_.GetOneActiveServerConnectionId() == cid1 || connection_.GetOneActiveServerConnectionId() == cid2); connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *packet1); EXPECT_EQ(connection_.connection_id(), cid0); EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid0 || connection_.GetOneActiveServerConnectionId() == cid1 || connection_.GetOneActiveServerConnectionId() == cid2); EXPECT_CALL(visitor_, OnServerConnectionIdRetired(cid0)); retire_self_issued_cid_alarm->Fire(); EXPECT_THAT(connection_.GetActiveServerConnectionIds(), ElementsAre(cid1, cid2)); EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid1 || connection_.GetOneActiveServerConnectionId() == cid2); connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *packet3); EXPECT_EQ(connection_.connection_id(), cid1); EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid1 || connection_.GetOneActiveServerConnectionId() == cid2); } TEST_P(QuicConnectionTest, PatchMissingClientConnectionIdOntoAlternativePath) { if (!version().HasIetfQuicFrames()) { return; } set_perspective(Perspective::IS_SERVER); connection_.CreateConnectionIdManager(); connection_.set_client_connection_id(TestConnectionId(1)); const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_); auto* alternative_path = QuicConnectionPeer::GetAlternativePath(&connection_); QuicIpAddress new_host; new_host.FromString("12.12.12.12"); alternative_path->self_address = default_path->self_address; alternative_path->peer_address = QuicSocketAddress(new_host, 12345); alternative_path->server_connection_id = TestConnectionId(3); ASSERT_TRUE(alternative_path->client_connection_id.IsEmpty()); ASSERT_FALSE(alternative_path->stateless_reset_token.has_value()); QuicNewConnectionIdFrame frame; frame.sequence_number = 1u; frame.connection_id = TestConnectionId(5); frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); frame.retire_prior_to = 0u; connection_.OnNewConnectionIdFrame(frame); ASSERT_EQ(alternative_path->client_connection_id, frame.connection_id); ASSERT_EQ(alternative_path->stateless_reset_token, frame.stateless_reset_token); } TEST_P(QuicConnectionTest, PatchMissingClientConnectionIdOntoDefaultPath) { if (!version().HasIetfQuicFrames()) { return; } set_perspective(Perspective::IS_SERVER); connection_.CreateConnectionIdManager(); connection_.set_client_connection_id(TestConnectionId(1)); auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_); auto* alternative_path = QuicConnectionPeer::GetAlternativePath(&connection_); auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_); *alternative_path = std::move(*default_path); QuicIpAddress new_host; new_host.FromString("12.12.12.12"); default_path->self_address = default_path->self_address; default_path->peer_address = QuicSocketAddress(new_host, 12345); default_path->server_connection_id = TestConnectionId(3); packet_creator->SetDefaultPeerAddress(default_path->peer_address); packet_creator->SetServerConnectionId(default_path->server_connection_id); packet_creator->SetClientConnectionId(default_path->client_connection_id); ASSERT_FALSE(default_path->validated); ASSERT_TRUE(default_path->client_connection_id.IsEmpty()); ASSERT_FALSE(default_path->stateless_reset_token.has_value()); QuicNewConnectionIdFrame frame; frame.sequence_number = 1u; frame.connection_id = TestConnectionId(5); frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); frame.retire_prior_to = 0u; connection_.OnNewConnectionIdFrame(frame); ASSERT_EQ(default_path->client_connection_id, frame.connection_id); ASSERT_EQ(default_path->stateless_reset_token, frame.stateless_reset_token); ASSERT_EQ(packet_creator->GetDestinationConnectionId(), frame.connection_id); } TEST_P(QuicConnectionTest, ShouldGeneratePacketBlockedByMissingConnectionId) { if (!version().HasIetfQuicFrames()) { return; } set_perspective(Perspective::IS_SERVER); connection_.set_client_connection_id(TestConnectionId(1)); connection_.CreateConnectionIdManager(); if (version().SupportsAntiAmplificationLimit()) { QuicConnectionPeer::SetAddressValidated(&connection_); } ASSERT_TRUE( connection_.ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, NOT_HANDSHAKE)); QuicPacketCreator* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_); QuicIpAddress peer_host1; peer_host1.FromString("12.12.12.12"); QuicSocketAddress peer_address1(peer_host1, 1235); { QuicPacketCreator::ScopedPeerAddressContext context( packet_creator, peer_address1, EmptyQuicConnectionId(), EmptyQuicConnectionId()); ASSERT_FALSE(connection_.ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, NOT_HANDSHAKE)); } ASSERT_TRUE( connection_.ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, NOT_HANDSHAKE)); } TEST_P(QuicConnectionTest, LostDataThenGetAcknowledged) { set_perspective(Perspective::IS_SERVER); if (!version().SupportsAntiAmplificationLimit() || GetQuicFlag(quic_enforce_strict_amplification_factor)) { return; } QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false); if (version().SupportsAntiAmplificationLimit()) { QuicConnectionPeer::SetAddressValidated(&connection_); } connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.RemoveEncrypter(ENCRYPTION_INITIAL); connection_.NeuterUnencryptedPackets(); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); QuicPacketNumber last_packet; SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); SendStreamDataToPeer(3, "foo", 6, NO_FIN, &last_packet); SendStreamDataToPeer(3, "foo", 9, NO_FIN, &last_packet); ProcessFramePacket(QuicFrame(QuicPingFrame())); QuicFrames frames; frames.push_back(QuicFrame(frame1_)); QuicAckFrame ack = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)}}); frames.push_back(QuicFrame(&ack)); QuicIpAddress ip_address; ASSERT_TRUE(ip_address.FromString("127.0.52.223")); EXPECT_QUIC_BUG( { EXPECT_CALL(visitor_, OnConnectionMigration(_)).Times(1); EXPECT_CALL(visitor_, OnStreamFrame(_)) .WillOnce(InvokeWithoutArgs(&notifier_, &SimpleSessionNotifier::OnCanWrite)); ProcessFramesPacketWithAddresses(frames, kSelfAddress, QuicSocketAddress(ip_address, 1000), ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(1u, writer_->path_challenge_frames().size()); EXPECT_TRUE(writer_->stream_frames().empty()); }, "Try to write mid packet processing"); } TEST_P(QuicConnectionTest, PtoSendStreamData) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } set_perspective(Perspective::IS_SERVER); if (QuicVersionUsesCryptoFrames(connection_.transport_version())) { EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); } EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber()); ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL); EXPECT_TRUE(connection_.HasPendingAcks()); connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL); connection_.SetEncrypter( ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); SetDecrypter(ENCRYPTION_HANDSHAKE, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE)); EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1); connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE); connection_.SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false)); connection_.SendStreamDataWithString(2, std::string(1500, 'a'), 0, NO_FIN); ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); connection_.GetRetransmissionAlarm()->Fire(); EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet()); } TEST_P(QuicConnectionTest, SendingZeroRttPacketsDoesNotPostponePTO) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); connection_.SendCryptoStreamData(); ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); connection_.SetEncrypter(ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(0x02)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10)); QuicAckFrame frame1 = InitAckFrame(1); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _)); ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL); ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); QuicTime pto_deadline = connection_.GetRetransmissionAlarm()->deadline(); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); connection_.SetEncrypter(ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(0x02)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN); ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); EXPECT_EQ(pto_deadline, connection_.GetRetransmissionAlarm()->deadline()); } TEST_P(QuicConnectionTest, QueueingUndecryptablePacketsDoesntPostponePTO) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; config.set_max_undecryptable_packets(3); connection_.SetFromConfig(config); connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE); connection_.SendCryptoStreamData(); connection_.SetEncrypter(ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(0x02)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10)); QuicAckFrame frame1 = InitAckFrame(1); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _)); ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL); ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); QuicTime pto_deadline = connection_.GetRetransmissionAlarm()->deadline(); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(0xFF)); ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE); EXPECT_GT(pto_deadline, connection_.GetRetransmissionAlarm()->deadline()); pto_deadline = connection_.GetRetransmissionAlarm()->deadline(); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); clock_.AdvanceTime(pto_deadline - clock_.ApproximateNow()); connection_.GetRetransmissionAlarm()->Fire(); ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); pto_deadline = connection_.GetRetransmissionAlarm()->deadline(); ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(pto_deadline, connection_.GetRetransmissionAlarm()->deadline()); } TEST_P(QuicConnectionTest, QueueUndecryptableHandshakePackets) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; config.set_max_undecryptable_packets(3); connection_.SetFromConfig(config); connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); connection_.RemoveDecrypter(ENCRYPTION_HANDSHAKE); connection_.SendCryptoStreamData(); connection_.SetEncrypter(ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(0x02)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN); EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(0xFF)); ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_HANDSHAKE); EXPECT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_)); } TEST_P(QuicConnectionTest, PingNotSentAt0RTTLevelWhenInitialAvailable) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); connection_.SendCryptoStreamData(); connection_.SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10)); QuicAckFrame frame1 = InitAckFrame(1); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _)); ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL); ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); QuicTime pto_deadline = connection_.GetRetransmissionAlarm()->deadline(); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1); clock_.AdvanceTime(pto_deadline - clock_.ApproximateNow()); connection_.GetRetransmissionAlarm()->Fire(); EXPECT_NE(0x02020202u, writer_->final_bytes_of_last_packet()); } TEST_P(QuicConnectionTest, AckElicitingFrames) { if (!version().HasIetfQuicFrames()) { return; } EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; config.SetReliableStreamReset(true); connection_.SetFromConfig(config); EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(TestConnectionId(12))) .WillOnce(Return(TestConnectionId(456))); EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(TestConnectionId(456))) .WillOnce(Return(TestConnectionId(789))); EXPECT_CALL(visitor_, SendNewConnectionId(_)).Times(2); EXPECT_CALL(visitor_, OnRstStream(_)); EXPECT_CALL(visitor_, OnResetStreamAt(_)); EXPECT_CALL(visitor_, OnWindowUpdateFrame(_)); EXPECT_CALL(visitor_, OnBlockedFrame(_)); EXPECT_CALL(visitor_, OnHandshakeDoneReceived()); EXPECT_CALL(visitor_, OnStreamFrame(_)); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _)); EXPECT_CALL(visitor_, OnMaxStreamsFrame(_)); EXPECT_CALL(visitor_, OnStreamsBlockedFrame(_)); EXPECT_CALL(visitor_, OnStopSendingFrame(_)); EXPECT_CALL(visitor_, OnMessageReceived("")); EXPECT_CALL(visitor_, OnNewTokenReceived("")); SetClientConnectionId(TestConnectionId(12)); connection_.CreateConnectionIdManager(); QuicConnectionPeer::GetSelfIssuedConnectionIdManager(&connection_) ->MaybeSendNewConnectionIds(); connection_.set_can_receive_ack_frequency_frame(); QuicAckFrame ack_frame = InitAckFrame(1); QuicRstStreamFrame rst_stream_frame; QuicWindowUpdateFrame window_update_frame; QuicPathChallengeFrame path_challenge_frame; QuicNewConnectionIdFrame new_connection_id_frame; new_connection_id_frame.sequence_number = 1u; QuicRetireConnectionIdFrame retire_connection_id_frame; retire_connection_id_frame.sequence_number = 1u; QuicStopSendingFrame stop_sending_frame; QuicPathResponseFrame path_response_frame; QuicMessageFrame message_frame; QuicNewTokenFrame new_token_frame; QuicAckFrequencyFrame ack_frequency_frame; QuicResetStreamAtFrame reset_stream_at_frame; QuicBlockedFrame blocked_frame; size_t packet_number = 1; connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); QuicFramer* framer = const_cast<QuicFramer*>(&connection_.framer()); framer->set_process_reset_stream_at(true); peer_framer_.set_process_reset_stream_at(true); for (uint8_t i = 0; i < NUM_FRAME_TYPES; ++i) { QuicFrameType frame_type = static_cast<QuicFrameType>(i); bool skipped = false; QuicFrame frame; QuicFrames frames; frames.push_back(QuicFrame(QuicPaddingFrame(10))); switch (frame_type) { case PADDING_FRAME: frame = QuicFrame(QuicPaddingFrame(10)); break; case MTU_DISCOVERY_FRAME: frame = QuicFrame(QuicMtuDiscoveryFrame()); break; case PING_FRAME: frame = QuicFrame(QuicPingFrame()); break; case MAX_STREAMS_FRAME: frame = QuicFrame(QuicMaxStreamsFrame()); break; case STOP_WAITING_FRAME: skipped = true; break; case STREAMS_BLOCKED_FRAME: frame = QuicFrame(QuicStreamsBlockedFrame()); break; case STREAM_FRAME: frame = QuicFrame(QuicStreamFrame()); break; case HANDSHAKE_DONE_FRAME: frame = QuicFrame(QuicHandshakeDoneFrame()); break; case ACK_FRAME: frame = QuicFrame(&ack_frame); break; case RST_STREAM_FRAME: frame = QuicFrame(&rst_stream_frame); break; case CONNECTION_CLOSE_FRAME: skipped = true; break; case GOAWAY_FRAME: skipped = true; break; case BLOCKED_FRAME: frame = QuicFrame(blocked_frame); break; case WINDOW_UPDATE_FRAME: frame = QuicFrame(window_update_frame); break; case PATH_CHALLENGE_FRAME: frame = QuicFrame(path_challenge_frame); break; case STOP_SENDING_FRAME: frame = QuicFrame(stop_sending_frame); break; case NEW_CONNECTION_ID_FRAME: frame = QuicFrame(&new_connection_id_frame); break; case RETIRE_CONNECTION_ID_FRAME: frame = QuicFrame(&retire_connection_id_frame); break; case PATH_RESPONSE_FRAME: frame = QuicFrame(path_response_frame); break; case MESSAGE_FRAME: frame = QuicFrame(&message_frame); break; case CRYPTO_FRAME: skipped = true; break; case NEW_TOKEN_FRAME: frame = QuicFrame(&new_token_frame); break; case ACK_FREQUENCY_FRAME: frame = QuicFrame(&ack_frequency_frame); break; case RESET_STREAM_AT_FRAME: frame = QuicFrame(&reset_stream_at_frame); break; case NUM_FRAME_TYPES: skipped = true; break; } if (skipped) { continue; } ASSERT_EQ(frame_type, frame.type); frames.push_back(frame); EXPECT_FALSE(connection_.HasPendingAcks()); ProcessFramesPacketAtLevel(packet_number++, frames, ENCRYPTION_FORWARD_SECURE); if (QuicUtils::IsAckElicitingFrame(frame_type)) { ASSERT_TRUE(connection_.HasPendingAcks()) << frame; clock_.AdvanceTime(DefaultDelayedAckTime()); connection_.GetAckAlarm()->Fire(); } EXPECT_FALSE(connection_.HasPendingAcks()); ASSERT_TRUE(connection_.connected()); } } TEST_P(QuicConnectionTest, ReceivedChloAndAck) { if (!version().HasIetfQuicFrames()) { return; } set_perspective(Perspective::IS_SERVER); QuicFrames frames; QuicAckFrame ack_frame = InitAckFrame(1); frames.push_back(MakeCryptoFrame()); frames.push_back(QuicFrame(&ack_frame)); EXPECT_CALL(visitor_, OnCryptoFrame(_)) .WillOnce(IgnoreResult(InvokeWithoutArgs( &connection_, &TestConnection::SendCryptoStreamData))); EXPECT_CALL(visitor_, BeforeConnectionCloseSent()); EXPECT_CALL(visitor_, OnConnectionClosed(_, _)); ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress, ENCRYPTION_INITIAL); } TEST_P(QuicConnectionTest, FailedToRetransmitShlo) { if (!version().SupportsAntiAmplificationLimit() || GetQuicFlag(quic_enforce_strict_amplification_factor)) { return; } set_perspective(Perspective::IS_SERVER); EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber()); ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL); EXPECT_TRUE(connection_.HasPendingAcks()); peer_framer_.SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT)); connection_.SetEncrypter( ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE)); SetDecrypter(ENCRYPTION_HANDSHAKE, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE)); SetDecrypter(ENCRYPTION_ZERO_RTT, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT)); connection_.SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE)); ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT); { QuicConnection::ScopedPacketFlusher flusher(&connection_); connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL); EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.SendStreamDataWithString(0, std::string(100 * 1024, 'a'), 0, NO_FIN); } ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL); ASSERT_TRUE(connection_.HasPendingAcks()); EXPECT_EQ(clock_.Now() + kAlarmGranularity, connection_.GetAckAlarm()->deadline()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3); clock_.AdvanceTime(kAlarmGranularity); connection_.GetAckAlarm()->Fire(); EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet()); EXPECT_EQ(1u, writer_->ack_frames().size()); EXPECT_EQ(1u, writer_->crypto_frames().size()); ASSERT_TRUE(writer_->coalesced_packet() != nullptr); auto packet = writer_->coalesced_packet()->Clone(); writer_->framer()->ProcessPacket(*packet); EXPECT_EQ(0u, writer_->ack_frames().size()); EXPECT_EQ(1u, writer_->crypto_frames().size()); ASSERT_TRUE(writer_->coalesced_packet() != nullptr); packet = writer_->coalesced_packet()->Clone(); writer_->framer()->ProcessPacket(*packet); EXPECT_EQ(0u, writer_->crypto_frames().size()); EXPECT_EQ(1u, writer_->stream_frames().size()); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber()); ProcessCryptoPacketAtLevel(3, ENCRYPTION_INITIAL); EXPECT_TRUE(connection_.HasPendingAcks()); } TEST_P(QuicConnectionTest, FailedToConsumeCryptoData) { if (!version().HasIetfQuicFrames()) { return; } set_perspective(Perspective::IS_SERVER); EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber()); ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL); EXPECT_TRUE(connection_.HasPendingAcks()); peer_framer_.SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT)); connection_.SetEncrypter( ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE)); SetDecrypter(ENCRYPTION_HANDSHAKE, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE)); SetDecrypter(ENCRYPTION_ZERO_RTT, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT)); connection_.SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE)); ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT); { QuicConnection::ScopedPacketFlusher flusher(&connection_); connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL); EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); connection_.SendCryptoDataWithString(std::string(200, 'a'), 0, ENCRYPTION_HANDSHAKE); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.SendStreamDataWithString(0, std::string(40, 'a'), 0, NO_FIN); } peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(0x03)); connection_.RemoveEncrypter(ENCRYPTION_INITIAL); connection_.NeuterUnencryptedPackets(); ProcessCryptoPacketAtLevel(1, ENCRYPTION_HANDSHAKE); clock_.AdvanceTime(kAlarmGranularity); { QuicConnection::ScopedPacketFlusher flusher(&connection_); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.SendStreamDataWithString(0, std::string(1395, 'a'), 40, NO_FIN); } ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); const QuicTime retransmission_time = connection_.GetRetransmissionAlarm()->deadline(); clock_.AdvanceTime(retransmission_time - clock_.Now()); connection_.GetRetransmissionAlarm()->Fire(); EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet()); EXPECT_EQ(1u, writer_->crypto_frames().size()); ASSERT_TRUE(writer_->coalesced_packet() != nullptr); auto packet = writer_->coalesced_packet()->Clone(); writer_->framer()->ProcessPacket(*packet); EXPECT_EQ(1u, writer_->stream_frames().size()); ASSERT_TRUE(writer_->coalesced_packet() == nullptr); ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); } TEST_P(QuicConnectionTest, RTTSampleDoesNotIncludeQueuingDelayWithPostponedAckProcessing) { if (!version().HasIetfQuicFrames()) { return; } EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; config.set_max_undecryptable_packets(3); connection_.SetFromConfig(config); const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30); RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats()); rtt_stats->UpdateRtt(kTestRTT, QuicTime::Delta::Zero(), QuicTime::Zero()); connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE); connection_.SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); connection_.SendStreamDataWithString(0, std::string(10, 'a'), 0, FIN); clock_.AdvanceTime(kTestRTT + QuicTime::Delta::FromMilliseconds( GetDefaultDelayedAckTimeMs())); EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_)); peer_framer_.SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE)); QuicAckFrame ack_frame = InitAckFrame(1); ack_frame.ack_delay_time = QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs()); QuicFrames frames; frames.push_back(QuicFrame(&ack_frame)); QuicPacketHeader header = ConstructPacketHeader(30, ENCRYPTION_FORWARD_SECURE); std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames)); char buffer[kMaxOutgoingPacketSize]; size_t encrypted_length = peer_framer_.EncryptPayload( ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(30), *packet, buffer, kMaxOutgoingPacketSize); connection_.ProcessUdpPacket( kSelfAddress, kPeerAddress, QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false)); if (connection_.GetSendAlarm()->IsSet()) { connection_.GetSendAlarm()->Fire(); } ASSERT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10)); EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet()); SetDecrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE)); ASSERT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet()); EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _)); connection_.GetProcessUndecryptablePacketsAlarm()->Fire(); EXPECT_EQ(rtt_stats->latest_rtt(), kTestRTT); } TEST_P(QuicConnectionTest, NoExtraPaddingInReserializedInitial) { if (!IsDefaultTestConfiguration() || !connection_.version().CanSendCoalescedPackets()) { return; } set_perspective(Perspective::IS_SERVER); MockQuicConnectionDebugVisitor debug_visitor; connection_.set_debug_visitor(&debug_visitor); uint64_t debug_visitor_sent_count = 0; EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)) .WillRepeatedly([&]() { debug_visitor_sent_count++; }); EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber()); ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL); peer_framer_.SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT)); connection_.SetEncrypter( ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE)); SetDecrypter(ENCRYPTION_HANDSHAKE, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE)); SetDecrypter(ENCRYPTION_ZERO_RTT, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT)); connection_.SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE)); ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT); { QuicConnection::ScopedPacketFlusher flusher(&connection_); connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL); EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); connection_.SendCryptoDataWithString(std::string(200, 'a'), 0, ENCRYPTION_HANDSHAKE); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.SendStreamDataWithString(0, std::string(400, 'b'), 0, NO_FIN); } const std::string data4(1000, '4'); const std::string data8(3000, '8'); EXPECT_CALL(visitor_, OnCanWrite()).WillOnce([&]() { connection_.producer()->SaveStreamData(4, data4); connection_.producer()->SaveStreamData(8, data8); notifier_.WriteOrBufferData(4, data4.size(), FIN_AND_PADDING); notifier_.WriteOrBufferData(8, data8.size(), FIN); }); QuicByteCount pending_padding_after_serialize_2nd_1rtt_packet = 0; QuicPacketCount num_1rtt_packets_serialized = 0; EXPECT_CALL(connection_, OnSerializedPacket(_)) .WillRepeatedly([&](SerializedPacket packet) { if (packet.encryption_level == ENCRYPTION_FORWARD_SECURE) { num_1rtt_packets_serialized++; if (num_1rtt_packets_serialized == 2) { pending_padding_after_serialize_2nd_1rtt_packet = connection_.packet_creator().pending_padding_bytes(); } } connection_.QuicConnection::OnSerializedPacket(std::move(packet)); }); ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_INITIAL); EXPECT_EQ( debug_visitor_sent_count, connection_.sent_packet_manager().GetLargestSentPacket().ToUint64()); EXPECT_GT(pending_padding_after_serialize_2nd_1rtt_packet, 0u); EXPECT_TRUE(connection_.connected()); } TEST_P(QuicConnectionTest, ReportedAckDelayIncludesQueuingDelay) { if (!version().HasIetfQuicFrames()) { return; } EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; config.set_max_undecryptable_packets(3); connection_.SetFromConfig(config); connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE); peer_framer_.SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE)); QuicFrames frames; frames.push_back(QuicFrame(QuicPingFrame())); frames.push_back(QuicFrame(QuicPaddingFrame(100))); QuicPacketHeader header = ConstructPacketHeader(30, ENCRYPTION_FORWARD_SECURE); std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames)); char buffer[kMaxOutgoingPacketSize]; size_t encrypted_length = peer_framer_.EncryptPayload( ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(30), *packet, buffer, kMaxOutgoingPacketSize); EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_)); const QuicTime packet_receipt_time = clock_.Now(); connection_.ProcessUdpPacket( kSelfAddress, kPeerAddress, QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false)); if (connection_.GetSendAlarm()->IsSet()) { connection_.GetSendAlarm()->Fire(); } ASSERT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_)); const QuicTime::Delta kQueuingDelay = QuicTime::Delta::FromMilliseconds(10); clock_.AdvanceTime(kQueuingDelay); EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet()); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); SetDecrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE)); ASSERT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet()); connection_.GetProcessUndecryptablePacketsAlarm()->Fire(); ASSERT_TRUE(connection_.HasPendingAcks()); EXPECT_EQ(packet_receipt_time + DefaultDelayedAckTime(), connection_.GetAckAlarm()->deadline()); clock_.AdvanceTime(packet_receipt_time + DefaultDelayedAckTime() - clock_.Now()); connection_.GetAckAlarm()->Fire(); ASSERT_EQ(1u, writer_->ack_frames().size()); EXPECT_EQ(DefaultDelayedAckTime(), writer_->ack_frames()[0].ack_delay_time); } TEST_P(QuicConnectionTest, CoalesceOneRTTPacketWithInitialAndHandshakePackets) { if (!version().HasIetfQuicFrames()) { return; } set_perspective(Perspective::IS_SERVER); EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber()); ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL); peer_framer_.SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT)); connection_.SetEncrypter( ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE)); SetDecrypter(ENCRYPTION_HANDSHAKE, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE)); SetDecrypter(ENCRYPTION_ZERO_RTT, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT)); connection_.SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE)); ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT); { QuicConnection::ScopedPacketFlusher flusher(&connection_); connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL); EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); connection_.SendCryptoDataWithString(std::string(200, 'a'), 0, ENCRYPTION_HANDSHAKE); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.SendStreamDataWithString(0, std::string(2000, 'b'), 0, FIN); } EXPECT_EQ(2u, writer_->packets_write_attempts()); ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_INITIAL); EXPECT_EQ(3u, writer_->packets_write_attempts()); EXPECT_EQ(1u, writer_->ack_frames().size()); EXPECT_EQ(1u, writer_->crypto_frames().size()); ASSERT_TRUE(writer_->coalesced_packet() != nullptr); auto packet = writer_->coalesced_packet()->Clone(); writer_->framer()->ProcessPacket(*packet); EXPECT_EQ(1u, writer_->crypto_frames().size()); ASSERT_TRUE(writer_->coalesced_packet() != nullptr); packet = writer_->coalesced_packet()->Clone(); writer_->framer()->ProcessPacket(*packet); EXPECT_EQ(1u, writer_->stream_frames().size()); } TEST_P(QuicConnectionTest, SendMultipleConnectionCloses) { if (!version().HasIetfQuicFrames() || !GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) { return; } set_perspective(Perspective::IS_SERVER); QuicConnectionPeer::SetAddressValidated(&connection_); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); notifier_.NeuterUnencryptedData(); connection_.NeuterUnencryptedPackets(); connection_.OnHandshakeComplete(); connection_.RemoveEncrypter(ENCRYPTION_INITIAL); connection_.RemoveEncrypter(ENCRYPTION_HANDSHAKE); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr); ASSERT_TRUE(connection_.BlackholeDetectionInProgress()); EXPECT_CALL(visitor_, BeforeConnectionCloseSent()).Times(2); EXPECT_CALL(visitor_, OnConnectionClosed(_, _)); QuicConnectionPeer::SendConnectionClosePacket( &connection_, INTERNAL_ERROR, QUIC_INTERNAL_ERROR, "internal error"); connection_.GetBlackholeDetectorAlarm()->Fire(); } TEST_P(QuicConnectionTest, EarliestSentTimeNotInitializedWhenPtoFires) { if (!connection_.SupportsMultiplePacketNumberSpaces()) { return; } set_perspective(Perspective::IS_SERVER); EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber()); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber()); ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL); connection_.SetEncrypter( ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE)); SetDecrypter(ENCRYPTION_HANDSHAKE, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE)); connection_.SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE)); { QuicConnection::ScopedPacketFlusher flusher(&connection_); connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL); EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); connection_.SendCryptoDataWithString(std::string(200, 'a'), 0, ENCRYPTION_HANDSHAKE); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_.SendStreamDataWithString(0, std::string(2000, 'b'), 0, FIN); } EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _)) .Times(AnyNumber()); QuicFrames frames1; QuicAckFrame ack_frame1 = InitAckFrame(1); frames1.push_back(QuicFrame(&ack_frame1)); QuicFrames frames2; QuicAckFrame ack_frame2 = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}}); frames2.push_back(QuicFrame(&ack_frame2)); ProcessCoalescedPacket( {{2, frames1, ENCRYPTION_INITIAL}, {3, frames2, ENCRYPTION_HANDSHAKE}}); EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); } TEST_P(QuicConnectionTest, CalculateNetworkBlackholeDelay) { if (!IsDefaultTestConfiguration()) { return; } const QuicTime::Delta kOneSec = QuicTime::Delta::FromSeconds(1); const QuicTime::Delta kTwoSec = QuicTime::Delta::FromSeconds(2); const QuicTime::Delta kFourSec = QuicTime::Delta::FromSeconds(4); EXPECT_EQ(QuicConnection::CalculateNetworkBlackholeDelay(kFourSec, kOneSec, kOneSec), kFourSec); EXPECT_EQ(QuicConnection::CalculateNetworkBlackholeDelay(kFourSec, kOneSec, kTwoSec), QuicTime::Delta::FromSeconds(5)); } TEST_P(QuicConnectionTest, FixBytesAccountingForBufferedCoalescedPackets) { if (!connection_.version().CanSendCoalescedPackets()) { return; } EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber()); writer_->SetWriteBlocked(); connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); QuicConnectionPeer::SendPing(&connection_); const QuicConnectionStats& stats = connection_.GetStats(); EXPECT_EQ(stats.bytes_sent, connection_.max_packet_length()); } TEST_P(QuicConnectionTest, StrictAntiAmplificationLimit) { if (!connection_.version().SupportsAntiAmplificationLimit()) { return; } EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber()); set_perspective(Perspective::IS_SERVER); connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); connection_.SendCryptoDataWithString("foo", 0); EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA)); EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA)); EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); const size_t anti_amplification_factor = GetQuicFlag(quic_anti_amplification_factor); EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(anti_amplification_factor); ForceWillingAndAbleToWriteOnceForDeferSending(); ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL); connection_.SetEncrypter(ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(0x02)); connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(0x03)); for (size_t i = 1; i < anti_amplification_factor - 1; ++i) { connection_.SendCryptoDataWithString("foo", i * 3); } connection_.SetMaxPacketLength(connection_.max_packet_length() - 1); connection_.SendCryptoDataWithString("bar", (anti_amplification_factor - 1) * 3); EXPECT_LT(writer_->total_bytes_written(), anti_amplification_factor * QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_)); if (GetQuicFlag(quic_enforce_strict_amplification_factor)) { EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3); EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); } else { EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4); EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet()); } connection_.SetMaxPacketLength(connection_.max_packet_length() + 1); connection_.SendCryptoDataWithString("bar", anti_amplification_factor * 3); EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet()); EXPECT_CALL(visitor_, BeforeConnectionCloseSent()); EXPECT_CALL(visitor_, OnConnectionClosed(_, _)); connection_.CloseConnection( QUIC_INTERNAL_ERROR, "error", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); EXPECT_EQ(0u, connection_.NumQueuedPackets()); if (GetQuicFlag(quic_enforce_strict_amplification_factor)) { EXPECT_LT(writer_->total_bytes_written(), anti_amplification_factor * QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_)); } else { EXPECT_LT(writer_->total_bytes_written(), (anti_amplification_factor + 2) * QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_)); EXPECT_GT(writer_->total_bytes_written(), (anti_amplification_factor + 1) * QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_)); } } TEST_P(QuicConnectionTest, OriginalConnectionId) { set_perspective(Perspective::IS_SERVER); EXPECT_FALSE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet()); EXPECT_EQ(connection_.GetOriginalDestinationConnectionId(), connection_.connection_id()); QuicConnectionId original({0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}); connection_.SetOriginalDestinationConnectionId(original); EXPECT_EQ(original, connection_.GetOriginalDestinationConnectionId()); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessDataPacketAtLevel(1, false, ENCRYPTION_FORWARD_SECURE); if (connection_.version().UsesTls()) { EXPECT_TRUE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet()); EXPECT_CALL(visitor_, OnServerConnectionIdRetired(original)); connection_.GetDiscardZeroRttDecryptionKeysAlarm()->Fire(); EXPECT_EQ(connection_.GetOriginalDestinationConnectionId(), connection_.connection_id()); } else { EXPECT_EQ(connection_.GetOriginalDestinationConnectionId(), original); } } ACTION_P2(InstallKeys, conn, level) { uint8_t crypto_input = (level == ENCRYPTION_FORWARD_SECURE) ? 0x03 : 0x02; conn->SetEncrypter(level, std::make_unique<TaggingEncrypter>(crypto_input)); conn->InstallDecrypter( level, std::make_unique<StrictTaggingDecrypter>(crypto_input)); conn->SetDefaultEncryptionLevel(level); } TEST_P(QuicConnectionTest, ServerConnectionIdChangeWithLateInitial) { if (!connection_.version().HasIetfQuicFrames()) { return; } EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(1); QuicConfig config; connection_.SetFromConfig(config); connection_.RemoveEncrypter(ENCRYPTION_FORWARD_SECURE); connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE); connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); connection_.SendCryptoStreamData(); EXPECT_EQ(1u, writer_->packets_write_attempts()); QuicConnectionId old_id = connection_id_; connection_id_ = TestConnectionId(2); peer_creator_.SetEncrypter(ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(0x02)); ProcessCryptoPacketAtLevel(0, ENCRYPTION_HANDSHAKE); EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 1u); EXPECT_EQ(connection_.connection_id(), old_id); peer_creator_.SetEncrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(0x03)); ProcessDataPacket(0); EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 2u); EXPECT_CALL(visitor_, OnCryptoFrame(_)) .Times(2) .WillOnce(InstallKeys(&connection_, ENCRYPTION_HANDSHAKE)) .WillOnce(InstallKeys(&connection_, ENCRYPTION_FORWARD_SECURE)); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); ProcessCryptoPacketAtLevel(0, ENCRYPTION_INITIAL); EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 0u); EXPECT_EQ(connection_.connection_id(), connection_id_); } TEST_P(QuicConnectionTest, ServerConnectionIdChangeTwiceWithLateInitial) { if (!connection_.version().HasIetfQuicFrames()) { return; } EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(1); QuicConfig config; connection_.SetFromConfig(config); connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL); connection_.SendCryptoStreamData(); EXPECT_EQ(1u, writer_->packets_write_attempts()); QuicConnectionId old_id = connection_id_; connection_id_ = TestConnectionId(2); peer_creator_.SetEncrypter(ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(0x02)); ProcessCryptoPacketAtLevel(0, ENCRYPTION_HANDSHAKE); EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 1u); EXPECT_EQ(connection_.connection_id(), old_id); EXPECT_CALL(visitor_, OnCryptoFrame(_)) .WillOnce(InstallKeys(&connection_, ENCRYPTION_HANDSHAKE)); connection_id_ = TestConnectionId(1); ProcessCryptoPacketAtLevel(0, ENCRYPTION_INITIAL); EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 0u); EXPECT_EQ(connection_.connection_id(), connection_id_); } TEST_P(QuicConnectionTest, ClientValidatedServerPreferredAddress) { if (!connection_.version().HasIetfQuicFrames()) { return; } QuicConfig config; ServerPreferredAddressInit(config); const QuicSocketAddress kNewSelfAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), 23456); TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); const StatelessResetToken kNewStatelessResetToken = QuicUtils::GenerateStatelessResetToken(TestConnectionId(17)); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); EXPECT_CALL(visitor_, OnServerPreferredAddressAvailable(kServerPreferredAddress)) .WillOnce(Invoke([&]() { connection_.ValidatePath( std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress, kServerPreferredAddress, &new_writer), std::make_unique<ServerPreferredAddressTestResultDelegate>( &connection_), PathValidationReason::kReasonUnknown); })); connection_.OnHandshakeComplete(); EXPECT_TRUE(connection_.HasPendingPathValidation()); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath( &connection_, kNewSelfAddress, kServerPreferredAddress)); EXPECT_EQ(TestConnectionId(17), new_writer.last_packet_header().destination_connection_id); EXPECT_EQ(kServerPreferredAddress, new_writer.last_write_peer_address()); ASSERT_FALSE(new_writer.path_challenge_frames().empty()); QuicPathFrameBuffer payload = new_writer.path_challenge_frames().front().data_buffer; connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN); ASSERT_FALSE(writer_->stream_frames().empty()); EXPECT_EQ(TestConnectionId(), writer_->last_packet_header().destination_connection_id); EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address()); EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestStatelessResetToken)); EXPECT_FALSE(connection_.IsValidStatelessResetToken(kNewStatelessResetToken)); QuicFrames frames; frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload))); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0); ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kServerPreferredAddress, ENCRYPTION_FORWARD_SECURE); ASSERT_FALSE(connection_.HasPendingPathValidation()); EXPECT_TRUE(QuicConnectionPeer::IsDefaultPath(&connection_, kNewSelfAddress, kServerPreferredAddress)); ASSERT_FALSE(new_writer.stream_frames().empty()); EXPECT_EQ(TestConnectionId(17), new_writer.last_packet_header().destination_connection_id); EXPECT_EQ(kServerPreferredAddress, new_writer.last_write_peer_address()); EXPECT_FALSE( connection_.IsValidStatelessResetToken(kTestStatelessResetToken)); EXPECT_TRUE(connection_.IsValidStatelessResetToken(kNewStatelessResetToken)); auto* retire_peer_issued_cid_alarm = connection_.GetRetirePeerIssuedConnectionIdAlarm(); ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet()); EXPECT_CALL(visitor_, SendRetireConnectionId(0u)); retire_peer_issued_cid_alarm->Fire(); EXPECT_TRUE(connection_.GetStats().server_preferred_address_validated); EXPECT_FALSE( connection_.GetStats().failed_to_validate_server_preferred_address); } TEST_P(QuicConnectionTest, ClientValidatedServerPreferredAddress2) { if (!connection_.version().HasIetfQuicFrames()) { return; } QuicConfig config; ServerPreferredAddressInit(config); const QuicSocketAddress kNewSelfAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), 23456); TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); EXPECT_CALL(visitor_, OnServerPreferredAddressAvailable(kServerPreferredAddress)) .WillOnce(Invoke([&]() { connection_.ValidatePath( std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress, kServerPreferredAddress, &new_writer), std::make_unique<ServerPreferredAddressTestResultDelegate>( &connection_), PathValidationReason::kReasonUnknown); })); connection_.OnHandshakeComplete(); EXPECT_TRUE(connection_.HasPendingPathValidation()); ASSERT_FALSE(new_writer.path_challenge_frames().empty()); QuicPathFrameBuffer payload = new_writer.path_challenge_frames().front().data_buffer; connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN); ASSERT_FALSE(writer_->stream_frames().empty()); EXPECT_EQ(TestConnectionId(), writer_->last_packet_header().destination_connection_id); EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address()); QuicFrames frames; frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload))); ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress, ENCRYPTION_FORWARD_SECURE); ASSERT_FALSE(connection_.HasPendingPathValidation()); ASSERT_FALSE(new_writer.stream_frames().empty()); EXPECT_EQ(TestConnectionId(17), new_writer.last_packet_header().destination_connection_id); EXPECT_EQ(kServerPreferredAddress, new_writer.last_write_peer_address()); auto* retire_peer_issued_cid_alarm = connection_.GetRetirePeerIssuedConnectionIdAlarm(); ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet()); EXPECT_CALL(visitor_, SendRetireConnectionId(0u)); retire_peer_issued_cid_alarm->Fire(); EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1); frames.clear(); frames.push_back(QuicFrame(frame1_)); ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_TRUE(connection_.GetStats().server_preferred_address_validated); EXPECT_FALSE( connection_.GetStats().failed_to_validate_server_preferred_address); } TEST_P(QuicConnectionTest, ClientFailedToValidateServerPreferredAddress) { if (!connection_.version().HasIetfQuicFrames()) { return; } QuicConfig config; ServerPreferredAddressInit(config); const QuicSocketAddress kNewSelfAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), 23456); TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); EXPECT_CALL(visitor_, OnServerPreferredAddressAvailable(kServerPreferredAddress)) .WillOnce(Invoke([&]() { connection_.ValidatePath( std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress, kServerPreferredAddress, &new_writer), std::make_unique<ServerPreferredAddressTestResultDelegate>( &connection_), PathValidationReason::kReasonUnknown); })); connection_.OnHandshakeComplete(); EXPECT_TRUE(connection_.IsValidatingServerPreferredAddress()); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath( &connection_, kNewSelfAddress, kServerPreferredAddress)); ASSERT_FALSE(new_writer.path_challenge_frames().empty()); QuicFrames frames; frames.push_back( QuicFrame(QuicPathResponseFrame(99, {0, 1, 2, 3, 4, 5, 6, 7}))); ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress, ENCRYPTION_FORWARD_SECURE); ASSERT_TRUE(connection_.HasPendingPathValidation()); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath( &connection_, kNewSelfAddress, kServerPreferredAddress)); for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes + 1; ++i) { clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs)); static_cast<TestAlarmFactory::TestAlarm*>( QuicPathValidatorPeer::retry_timer( QuicConnectionPeer::path_validator(&connection_))) ->Fire(); } EXPECT_FALSE(connection_.HasPendingPathValidation()); EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath( &connection_, kNewSelfAddress, kServerPreferredAddress)); connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN); ASSERT_FALSE(writer_->stream_frames().empty()); EXPECT_EQ(TestConnectionId(), writer_->last_packet_header().destination_connection_id); EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address()); auto* retire_peer_issued_cid_alarm = connection_.GetRetirePeerIssuedConnectionIdAlarm(); ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet()); EXPECT_CALL(visitor_, SendRetireConnectionId(1u)); retire_peer_issued_cid_alarm->Fire(); EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestStatelessResetToken)); EXPECT_FALSE(connection_.GetStats().server_preferred_address_validated); EXPECT_TRUE( connection_.GetStats().failed_to_validate_server_preferred_address); } TEST_P(QuicConnectionTest, OptimizedServerPreferredAddress) { if (!connection_.version().HasIetfQuicFrames()) { return; } const QuicSocketAddress kNewSelfAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), 23456); TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); EXPECT_CALL(visitor_, OnServerPreferredAddressAvailable(kServerPreferredAddress)) .WillOnce(Invoke([&]() { connection_.ValidatePath( std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress, kServerPreferredAddress, &new_writer), std::make_unique<ServerPreferredAddressTestResultDelegate>( &connection_), PathValidationReason::kReasonUnknown); })); QuicConfig config; config.SetClientConnectionOptions(QuicTagVector{kSPA2}); ServerPreferredAddressInit(config); EXPECT_TRUE(connection_.HasPendingPathValidation()); ASSERT_FALSE(new_writer.path_challenge_frames().empty()); connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN); EXPECT_FALSE(writer_->stream_frames().empty()); EXPECT_FALSE(new_writer.stream_frames().empty()); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); connection_.OnHandshakeComplete(); SendPing(); EXPECT_FALSE(writer_->ping_frames().empty()); EXPECT_TRUE(new_writer.ping_frames().empty()); } TEST_P(QuicConnectionTest, OptimizedServerPreferredAddress2) { if (!connection_.version().HasIetfQuicFrames()) { return; } const QuicSocketAddress kNewSelfAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), 23456); TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); EXPECT_CALL(visitor_, OnServerPreferredAddressAvailable(kServerPreferredAddress)) .WillOnce(Invoke([&]() { connection_.ValidatePath( std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress, kServerPreferredAddress, &new_writer), std::make_unique<ServerPreferredAddressTestResultDelegate>( &connection_), PathValidationReason::kReasonUnknown); })); QuicConfig config; config.SetClientConnectionOptions(QuicTagVector{kSPA2}); ServerPreferredAddressInit(config); EXPECT_TRUE(connection_.HasPendingPathValidation()); ASSERT_FALSE(new_writer.path_challenge_frames().empty()); connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN); EXPECT_FALSE(writer_->stream_frames().empty()); EXPECT_FALSE(new_writer.stream_frames().empty()); for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes + 1; ++i) { clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs)); static_cast<TestAlarmFactory::TestAlarm*>( QuicPathValidatorPeer::retry_timer( QuicConnectionPeer::path_validator(&connection_))) ->Fire(); } EXPECT_FALSE(connection_.HasPendingPathValidation()); SendPing(); EXPECT_FALSE(writer_->ping_frames().empty()); EXPECT_TRUE(new_writer.ping_frames().empty()); } TEST_P(QuicConnectionTest, MaxDuplicatedPacketsSentToServerPreferredAddress) { if (!connection_.version().HasIetfQuicFrames()) { return; } const QuicSocketAddress kNewSelfAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), 23456); TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); EXPECT_CALL(visitor_, OnServerPreferredAddressAvailable(kServerPreferredAddress)) .WillOnce(Invoke([&]() { connection_.ValidatePath( std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress, kServerPreferredAddress, &new_writer), std::make_unique<ServerPreferredAddressTestResultDelegate>( &connection_), PathValidationReason::kReasonUnknown); })); QuicConfig config; config.SetClientConnectionOptions(QuicTagVector{kSPA2}); ServerPreferredAddressInit(config); EXPECT_TRUE(connection_.HasPendingPathValidation()); ASSERT_FALSE(new_writer.path_challenge_frames().empty()); size_t write_limit = writer_->packets_write_attempts(); size_t new_write_limit = new_writer.packets_write_attempts(); for (size_t i = 0; i < kMaxDuplicatedPacketsSentToServerPreferredAddress; ++i) { connection_.SendStreamDataWithString(3, "foo", i * 3, NO_FIN); ASSERT_EQ(write_limit + 1, writer_->packets_write_attempts()); ASSERT_EQ(new_write_limit + 1, new_writer.packets_write_attempts()); ++write_limit; ++new_write_limit; EXPECT_FALSE(writer_->stream_frames().empty()); EXPECT_FALSE(new_writer.stream_frames().empty()); } SendPing(); ASSERT_EQ(write_limit + 1, writer_->packets_write_attempts()); ASSERT_EQ(new_write_limit, new_writer.packets_write_attempts()); EXPECT_FALSE(writer_->ping_frames().empty()); EXPECT_TRUE(new_writer.ping_frames().empty()); } TEST_P(QuicConnectionTest, MultiPortCreationAfterServerMigration) { if (!GetParam().version.HasIetfQuicFrames()) { return; } QuicConfig config; config.SetClientConnectionOptions(QuicTagVector{kMPQC}); ServerPreferredAddressInit(config); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); QuicConnectionId cid_for_preferred_address = TestConnectionId(17); const QuicSocketAddress kNewSelfAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), 23456); TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); EXPECT_CALL(visitor_, OnServerPreferredAddressAvailable(kServerPreferredAddress)) .WillOnce(Invoke([&]() { connection_.ValidatePath( std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress, kServerPreferredAddress, &new_writer), std::make_unique<ServerPreferredAddressTestResultDelegate>( &connection_), PathValidationReason::kReasonUnknown); })); QuicPathFrameBuffer payload; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(testing::AtLeast(1u)) .WillOnce(Invoke([&]() { EXPECT_EQ(1u, new_writer.path_challenge_frames().size()); payload = new_writer.path_challenge_frames().front().data_buffer; EXPECT_EQ(kServerPreferredAddress, new_writer.last_write_peer_address()); })); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); connection_.OnHandshakeComplete(); EXPECT_TRUE(connection_.IsValidatingServerPreferredAddress()); QuicFrames frames; frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload))); ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_FALSE(connection_.IsValidatingServerPreferredAddress()); EXPECT_EQ(kServerPreferredAddress, connection_.effective_peer_address()); EXPECT_EQ(kNewSelfAddress, connection_.self_address()); EXPECT_EQ(connection_.connection_id(), cid_for_preferred_address); auto* retire_peer_issued_cid_alarm = connection_.GetRetirePeerIssuedConnectionIdAlarm(); ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet()); EXPECT_CALL(visitor_, SendRetireConnectionId(0u)); retire_peer_issued_cid_alarm->Fire(); const QuicSocketAddress kNewSelfAddress2(kNewSelfAddress.host(), kNewSelfAddress.port() + 1); EXPECT_NE(kNewSelfAddress2, kNewSelfAddress); TestPacketWriter new_writer2(version(), &clock_, Perspective::IS_CLIENT); QuicNewConnectionIdFrame frame; frame.connection_id = TestConnectionId(789); ASSERT_NE(frame.connection_id, connection_.connection_id()); frame.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(frame.connection_id); frame.retire_prior_to = 0u; frame.sequence_number = 2u; EXPECT_CALL(visitor_, CreateContextForMultiPortPath) .WillOnce(testing::WithArgs<0>([&](auto&& observer) { observer->OnMultiPortPathContextAvailable( std::move(std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress2, connection_.peer_address(), &new_writer2))); })); connection_.OnNewConnectionIdFrame(frame); EXPECT_TRUE(connection_.HasPendingPathValidation()); EXPECT_EQ(1u, new_writer.path_challenge_frames().size()); payload = new_writer.path_challenge_frames().front().data_buffer; EXPECT_EQ(kServerPreferredAddress, new_writer.last_write_peer_address()); EXPECT_EQ(kNewSelfAddress2.host(), new_writer.last_write_source_address()); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath( &connection_, kNewSelfAddress2, connection_.peer_address())); auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_); EXPECT_FALSE(alt_path->validated); QuicFrames frames2; frames2.push_back(QuicFrame(QuicPathResponseFrame(99, payload))); ProcessFramesPacketWithAddresses(frames2, kNewSelfAddress2, kPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_TRUE(alt_path->validated); } TEST_P(QuicConnectionTest, ClientReceivePathChallengeAfterServerMigration) { if (!GetParam().version.HasIetfQuicFrames()) { return; } QuicConfig config; ServerPreferredAddressInit(config); QuicConnectionId cid_for_preferred_address = TestConnectionId(17); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(visitor_, OnServerPreferredAddressAvailable(kServerPreferredAddress)) .WillOnce(Invoke([&]() { connection_.AddKnownServerAddress(kServerPreferredAddress); })); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); connection_.OnHandshakeComplete(); const QuicSocketAddress kNewSelfAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), kTestPort + 1); TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); auto context = std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress, kServerPreferredAddress, &new_writer); connection_.OnServerPreferredAddressValidated(*context, false); EXPECT_EQ(kServerPreferredAddress, connection_.effective_peer_address()); EXPECT_EQ(kServerPreferredAddress, connection_.peer_address()); EXPECT_EQ(kNewSelfAddress, connection_.self_address()); EXPECT_EQ(connection_.connection_id(), cid_for_preferred_address); EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(), send_algorithm_); send_algorithm_ = new StrictMock<MockSendAlgorithm>(); EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true)); EXPECT_CALL(*send_algorithm_, GetCongestionWindow()) .WillRepeatedly(Return(kDefaultTCPMSS)); EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber()); 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_, PopulateConnectionStats(_)).Times(AnyNumber()); connection_.SetSendAlgorithm(send_algorithm_); QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_); auto* retire_peer_issued_cid_alarm = connection_.GetRetirePeerIssuedConnectionIdAlarm(); ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet()); EXPECT_CALL(visitor_, SendRetireConnectionId(0u)); retire_peer_issued_cid_alarm->Fire(); QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7}; QuicFrames frames1; frames1.push_back( QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload))); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(AtLeast(1)) .WillOnce(Invoke([&]() { ASSERT_FALSE(new_writer.path_response_frames().empty()); EXPECT_EQ( 0, memcmp(&path_challenge_payload, &(new_writer.path_response_frames().front().data_buffer), sizeof(path_challenge_payload))); EXPECT_EQ(kServerPreferredAddress, new_writer.last_write_peer_address()); EXPECT_EQ(kNewSelfAddress.host(), new_writer.last_write_source_address()); })); ProcessFramesPacketWithAddresses(frames1, kNewSelfAddress, kPeerAddress, ENCRYPTION_FORWARD_SECURE); } TEST_P(QuicConnectionTest, ClientProbesAfterServerMigration) { if (!GetParam().version.HasIetfQuicFrames()) { return; } QuicConfig config; ServerPreferredAddressInit(config); QuicConnectionId cid_for_preferred_address = TestConnectionId(17); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(visitor_, OnServerPreferredAddressAvailable(kServerPreferredAddress)) .WillOnce(Invoke([&]() { connection_.AddKnownServerAddress(kServerPreferredAddress); })); EXPECT_CALL(visitor_, GetHandshakeState()) .WillRepeatedly(Return(HANDSHAKE_CONFIRMED)); connection_.OnHandshakeComplete(); const QuicSocketAddress kNewSelfAddress = QuicSocketAddress(QuicIpAddress::Loopback6(), kTestPort + 1); TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT); auto context = std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress, kServerPreferredAddress, &new_writer); connection_.OnServerPreferredAddressValidated(*context, false); EXPECT_EQ(kServerPreferredAddress, connection_.effective_peer_address()); EXPECT_EQ(kServerPreferredAddress, connection_.peer_address()); EXPECT_EQ(kNewSelfAddress, connection_.self_address()); EXPECT_EQ(connection_.connection_id(), cid_for_preferred_address); EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(), send_algorithm_); send_algorithm_ = new StrictMock<MockSendAlgorithm>(); EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true)); EXPECT_CALL(*send_algorithm_, GetCongestionWindow()) .WillRepeatedly(Return(kDefaultTCPMSS)); EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber()); 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_, PopulateConnectionStats(_)).Times(AnyNumber()); connection_.SetSendAlgorithm(send_algorithm_); EXPECT_CALL(visitor_, OnCryptoFrame(_)); ProcessFramePacketWithAddresses(MakeCryptoFrame(), kNewSelfAddress, kPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(kServerPreferredAddress, connection_.effective_peer_address()); EXPECT_EQ(kServerPreferredAddress, connection_.peer_address()); auto* retire_peer_issued_cid_alarm = connection_.GetRetirePeerIssuedConnectionIdAlarm(); ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet()); EXPECT_CALL(visitor_, SendRetireConnectionId(0u)); retire_peer_issued_cid_alarm->Fire(); QuicNewConnectionIdFrame new_cid_frame1; new_cid_frame1.connection_id = TestConnectionId(456); ASSERT_NE(new_cid_frame1.connection_id, connection_.connection_id()); new_cid_frame1.stateless_reset_token = QuicUtils::GenerateStatelessResetToken(new_cid_frame1.connection_id); new_cid_frame1.retire_prior_to = 0u; new_cid_frame1.sequence_number = 2u; connection_.OnNewConnectionIdFrame(new_cid_frame1); const QuicSocketAddress kNewSelfAddress2 = QuicSocketAddress(QuicIpAddress::Loopback4(), kTestPort + 2); TestPacketWriter new_writer2(version(), &clock_, Perspective::IS_CLIENT); bool success; QuicPathFrameBuffer payload; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(testing::AtLeast(1u)) .WillOnce(Invoke([&]() { EXPECT_EQ(1u, new_writer2.path_challenge_frames().size()); payload = new_writer2.path_challenge_frames().front().data_buffer; EXPECT_EQ(kServerPreferredAddress, new_writer2.last_write_peer_address()); EXPECT_EQ(kNewSelfAddress2.host(), new_writer2.last_write_source_address()); })); connection_.ValidatePath( std::make_unique<TestQuicPathValidationContext>( kNewSelfAddress2, connection_.peer_address(), &new_writer2), std::make_unique<TestValidationResultDelegate>( &connection_, kNewSelfAddress2, connection_.peer_address(), &success), PathValidationReason::kServerPreferredAddressMigration); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath( &connection_, kNewSelfAddress2, kServerPreferredAddress)); QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7}; QuicFrames frames; frames.push_back( QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload))); frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload))); EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(AtLeast(1)) .WillOnce(Invoke([&]() { EXPECT_FALSE(new_writer2.path_response_frames().empty()); EXPECT_EQ( 0, memcmp(&path_challenge_payload, &(new_writer2.path_response_frames().front().data_buffer), sizeof(path_challenge_payload))); EXPECT_EQ(kServerPreferredAddress, new_writer2.last_write_peer_address()); EXPECT_EQ(kNewSelfAddress2.host(), new_writer2.last_write_source_address()); })); ProcessFramesPacketWithAddresses(frames, kNewSelfAddress2, kPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_TRUE(success); } TEST_P(QuicConnectionTest, EcnMarksCorrectlyRecorded) { set_perspective(Perspective::IS_SERVER); QuicFrames frames; frames.push_back(QuicFrame(QuicPingFrame())); frames.push_back(QuicFrame(QuicPaddingFrame(7))); QuicAckFrame ack_frame = connection_.SupportsMultiplePacketNumberSpaces() ? connection_.received_packet_manager().GetAckFrame(APPLICATION_DATA) : connection_.received_packet_manager().ack_frame(); EXPECT_FALSE(ack_frame.ecn_counters.has_value()); ProcessFramesPacketAtLevelWithEcn(1, frames, ENCRYPTION_FORWARD_SECURE, ECN_ECT0); ack_frame = connection_.SupportsMultiplePacketNumberSpaces() ? connection_.received_packet_manager().GetAckFrame(APPLICATION_DATA) : connection_.received_packet_manager().ack_frame(); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); if (connection_.version().HasIetfQuicFrames()) { QuicConnectionPeer::SendPing(&connection_); QuicConnectionPeer::SendPing(&connection_); } QuicConnectionStats stats = connection_.GetStats(); ASSERT_TRUE(ack_frame.ecn_counters.has_value()); EXPECT_EQ(ack_frame.ecn_counters->ect0, 1); EXPECT_EQ(stats.num_ack_frames_sent_with_ecn, connection_.version().HasIetfQuicFrames() ? 1 : 0); EXPECT_EQ(stats.num_ecn_marks_received.ect0, 1); EXPECT_EQ(stats.num_ecn_marks_received.ect1, 0); EXPECT_EQ(stats.num_ecn_marks_received.ce, 0); } TEST_P(QuicConnectionTest, EcnMarksCoalescedPacket) { if (!connection_.version().CanSendCoalescedPackets()) { return; } QuicCryptoFrame crypto_frame1{ENCRYPTION_HANDSHAKE, 0, "foo"}; QuicFrames frames1; frames1.push_back(QuicFrame(&crypto_frame1)); QuicFrames frames2; QuicCryptoFrame crypto_frame2{ENCRYPTION_FORWARD_SECURE, 0, "bar"}; frames2.push_back(QuicFrame(&crypto_frame2)); std::vector<PacketInfo> packets = {{2, frames1, ENCRYPTION_HANDSHAKE}, {3, frames2, ENCRYPTION_FORWARD_SECURE}}; QuicAckFrame ack_frame = connection_.SupportsMultiplePacketNumberSpaces() ? connection_.received_packet_manager().GetAckFrame(APPLICATION_DATA) : connection_.received_packet_manager().ack_frame(); EXPECT_FALSE(ack_frame.ecn_counters.has_value()); ack_frame = connection_.SupportsMultiplePacketNumberSpaces() ? connection_.received_packet_manager().GetAckFrame(HANDSHAKE_DATA) : connection_.received_packet_manager().ack_frame(); EXPECT_FALSE(ack_frame.ecn_counters.has_value()); connection_.SetEncrypter( ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE)); EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(2); ProcessCoalescedPacket(packets, ECN_ECT0); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); if (connection_.version().HasIetfQuicFrames()) { EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1); connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); QuicConnectionPeer::SendPing(&connection_); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); QuicConnectionPeer::SendPing(&connection_); } QuicConnectionStats stats = connection_.GetStats(); ack_frame = connection_.SupportsMultiplePacketNumberSpaces() ? connection_.received_packet_manager().GetAckFrame(HANDSHAKE_DATA) : connection_.received_packet_manager().ack_frame(); ASSERT_TRUE(ack_frame.ecn_counters.has_value()); EXPECT_EQ(ack_frame.ecn_counters->ect0, connection_.SupportsMultiplePacketNumberSpaces() ? 1 : 2); if (connection_.SupportsMultiplePacketNumberSpaces()) { ack_frame = connection_.SupportsMultiplePacketNumberSpaces() ? connection_.received_packet_manager().GetAckFrame( APPLICATION_DATA) : connection_.received_packet_manager().ack_frame(); EXPECT_TRUE(ack_frame.ecn_counters.has_value()); EXPECT_EQ(ack_frame.ecn_counters->ect0, 1); } EXPECT_EQ(stats.num_ecn_marks_received.ect0, 2); EXPECT_EQ(stats.num_ack_frames_sent_with_ecn, connection_.version().HasIetfQuicFrames() ? 2 : 0); EXPECT_EQ(stats.num_ecn_marks_received.ect1, 0); EXPECT_EQ(stats.num_ecn_marks_received.ce, 0); } TEST_P(QuicConnectionTest, EcnMarksUndecryptableCoalescedPacket) { if (!connection_.version().CanSendCoalescedPackets()) { return; } EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; config.set_max_undecryptable_packets(100); connection_.SetFromConfig(config); QuicCryptoFrame crypto_frame1{ENCRYPTION_HANDSHAKE, 0, "foo"}; QuicFrames frames1; frames1.push_back(QuicFrame(&crypto_frame1)); QuicFrames frames2; QuicCryptoFrame crypto_frame2{ENCRYPTION_FORWARD_SECURE, 0, "bar"}; frames2.push_back(QuicFrame(&crypto_frame2)); std::vector<PacketInfo> packets = {{2, frames1, ENCRYPTION_HANDSHAKE}, {3, frames2, ENCRYPTION_FORWARD_SECURE}}; char coalesced_buffer[kMaxOutgoingPacketSize]; size_t coalesced_size = 0; for (const auto& packet : packets) { QuicPacketHeader header = ConstructPacketHeader(packet.packet_number, packet.level); peer_creator_.set_encryption_level(packet.level); peer_framer_.SetEncrypter(packet.level, std::make_unique<TaggingEncrypter>(packet.level)); if (packet.level == ENCRYPTION_HANDSHAKE) { connection_.SetEncrypter( packet.level, std::make_unique<TaggingEncrypter>(packet.level)); connection_.SetDefaultEncryptionLevel(packet.level); SetDecrypter(packet.level, std::make_unique<StrictTaggingDecrypter>(packet.level)); } std::unique_ptr<QuicPacket> constructed_packet( ConstructPacket(header, packet.frames)); char buffer[kMaxOutgoingPacketSize]; size_t encrypted_length = peer_framer_.EncryptPayload( packet.level, QuicPacketNumber(packet.packet_number), *constructed_packet, buffer, kMaxOutgoingPacketSize); QUICHE_DCHECK_LE(coalesced_size + encrypted_length, kMaxOutgoingPacketSize); memcpy(coalesced_buffer + coalesced_size, buffer, encrypted_length); coalesced_size += encrypted_length; } QuicAckFrame ack_frame = connection_.SupportsMultiplePacketNumberSpaces() ? connection_.received_packet_manager().GetAckFrame(APPLICATION_DATA) : connection_.received_packet_manager().ack_frame(); EXPECT_FALSE(ack_frame.ecn_counters.has_value()); ack_frame = connection_.SupportsMultiplePacketNumberSpaces() ? connection_.received_packet_manager().GetAckFrame(HANDSHAKE_DATA) : connection_.received_packet_manager().ack_frame(); EXPECT_FALSE(ack_frame.ecn_counters.has_value()); connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1); EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1); connection_.ProcessUdpPacket( kSelfAddress, kPeerAddress, QuicReceivedPacket(coalesced_buffer, coalesced_size, clock_.Now(), false, 0, true, nullptr, 0, true, ECN_ECT0)); if (connection_.GetSendAlarm()->IsSet()) { connection_.GetSendAlarm()->Fire(); } ack_frame = connection_.SupportsMultiplePacketNumberSpaces() ? connection_.received_packet_manager().GetAckFrame(HANDSHAKE_DATA) : connection_.received_packet_manager().ack_frame(); ASSERT_TRUE(ack_frame.ecn_counters.has_value()); EXPECT_EQ(ack_frame.ecn_counters->ect0, 1); if (connection_.SupportsMultiplePacketNumberSpaces()) { ack_frame = connection_.SupportsMultiplePacketNumberSpaces() ? connection_.received_packet_manager().GetAckFrame( APPLICATION_DATA) : connection_.received_packet_manager().ack_frame(); EXPECT_FALSE(ack_frame.ecn_counters.has_value()); } ProcessFramePacketAtLevelWithEcn(4, QuicFrame(QuicPingFrame()), ENCRYPTION_HANDSHAKE, ECN_CE); ack_frame = connection_.SupportsMultiplePacketNumberSpaces() ? connection_.received_packet_manager().GetAckFrame(HANDSHAKE_DATA) : connection_.received_packet_manager().ack_frame(); ASSERT_TRUE(ack_frame.ecn_counters.has_value()); EXPECT_EQ(ack_frame.ecn_counters->ect0, 1); EXPECT_EQ(ack_frame.ecn_counters->ce, 1); if (connection_.SupportsMultiplePacketNumberSpaces()) { ack_frame = connection_.SupportsMultiplePacketNumberSpaces() ? connection_.received_packet_manager().GetAckFrame( APPLICATION_DATA) : connection_.received_packet_manager().ack_frame(); EXPECT_FALSE(ack_frame.ecn_counters.has_value()); } EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1); SetDecrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE)); connection_.GetProcessUndecryptablePacketsAlarm()->Fire(); ack_frame = connection_.SupportsMultiplePacketNumberSpaces() ? connection_.received_packet_manager().GetAckFrame(APPLICATION_DATA) : connection_.received_packet_manager().ack_frame(); ASSERT_TRUE(ack_frame.ecn_counters.has_value()); EXPECT_EQ(ack_frame.ecn_counters->ect0, connection_.SupportsMultiplePacketNumberSpaces() ? 1 : 2); QuicConnectionStats stats = connection_.GetStats(); EXPECT_EQ(stats.num_ecn_marks_received.ect0, 2); EXPECT_EQ(stats.num_ecn_marks_received.ect1, 0); EXPECT_EQ(stats.num_ecn_marks_received.ce, 1); } TEST_P(QuicConnectionTest, ReceivedPacketInfoDefaults) { EXPECT_TRUE(QuicConnectionPeer::TestLastReceivedPacketInfoDefaults()); } TEST_P(QuicConnectionTest, DetectMigrationToPreferredAddress) { if (!GetParam().version.HasIetfQuicFrames()) { return; } ServerHandlePreferredAddressInit(); QuicConnectionId server_issued_cid_for_preferred_address = TestConnectionId(17); EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(connection_id_)) .WillOnce(Return(server_issued_cid_for_preferred_address)); EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(true)); std::optional<QuicNewConnectionIdFrame> frame = connection_.MaybeIssueNewConnectionIdForPreferredAddress(); ASSERT_TRUE(frame.has_value()); auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_); ASSERT_EQ(packet_creator->GetDestinationConnectionId(), connection_.client_connection_id()); ASSERT_EQ(packet_creator->GetSourceConnectionId(), connection_id_); peer_creator_.SetServerConnectionId(server_issued_cid_for_preferred_address); EXPECT_CALL(visitor_, OnCryptoFrame(_)); ProcessFramePacketWithAddresses(MakeCryptoFrame(), kServerPreferredAddress, kPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kSelfAddress.host(), writer_->last_write_source_address()); EXPECT_EQ(kSelfAddress, connection_.self_address()); QuicRetireConnectionIdFrame retire_cid_frame; retire_cid_frame.sequence_number = 0u; EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(server_issued_cid_for_preferred_address)) .WillOnce(Return(TestConnectionId(456))); EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(true)); EXPECT_CALL(visitor_, SendNewConnectionId(_)); EXPECT_TRUE(connection_.OnRetireConnectionIdFrame(retire_cid_frame)); EXPECT_CALL(visitor_, OnCryptoFrame(_)); ProcessFramePacketWithAddresses(MakeCryptoFrame(), kServerPreferredAddress, kPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kSelfAddress.host(), writer_->last_write_source_address()); EXPECT_EQ(kSelfAddress, connection_.self_address()); } TEST_P(QuicConnectionTest, DetectSimutanuousServerAndClientAddressChangeWithProbe) { if (!GetParam().version.HasIetfQuicFrames()) { return; } ServerHandlePreferredAddressInit(); QuicConnectionId server_issued_cid_for_preferred_address = TestConnectionId(17); EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(connection_id_)) .WillOnce(Return(server_issued_cid_for_preferred_address)); EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(true)); std::optional<QuicNewConnectionIdFrame> frame = connection_.MaybeIssueNewConnectionIdForPreferredAddress(); ASSERT_TRUE(frame.has_value()); auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_); ASSERT_EQ(packet_creator->GetSourceConnectionId(), connection_id_); ASSERT_EQ(packet_creator->GetDestinationConnectionId(), connection_.client_connection_id()); peer_creator_.SetServerConnectionId(server_issued_cid_for_preferred_address); const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(), 34567); std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket(); std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket( QuicEncryptedPacket(probing_packet->encrypted_buffer, probing_packet->encrypted_length), clock_.Now())); uint64_t num_probing_received = connection_.GetStats().num_connectivity_probing_received; EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)) .Times(AtLeast(1u)) .WillOnce(Invoke([&]() { EXPECT_EQ(1u, writer_->path_response_frames().size()); EXPECT_EQ(1u, writer_->path_challenge_frames().size()); EXPECT_EQ(kServerPreferredAddress.host(), writer_->last_write_source_address()); EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address()); })) .WillRepeatedly(DoDefault()); ProcessReceivedPacket(kServerPreferredAddress, kNewPeerAddress, *received); EXPECT_EQ(num_probing_received + 1, connection_.GetStats().num_connectivity_probing_received); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(&connection_, kSelfAddress, kNewPeerAddress)); EXPECT_LT(0u, QuicConnectionPeer::BytesSentOnAlternativePath(&connection_)); EXPECT_EQ(received->length(), QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_)); EXPECT_EQ(kPeerAddress, connection_.peer_address()); EXPECT_EQ(kSelfAddress, connection_.self_address()); EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)); EXPECT_CALL(visitor_, OnCryptoFrame(_)); ProcessFramePacketWithAddresses(MakeCryptoFrame(), kServerPreferredAddress, kNewPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(kSelfAddress.host(), writer_->last_write_source_address()); EXPECT_EQ(kSelfAddress, connection_.self_address()); EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); EXPECT_TRUE(connection_.HasPendingPathValidation()); EXPECT_FALSE(QuicConnectionPeer::GetDefaultPath(&connection_)->validated); EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(&connection_, kSelfAddress, kPeerAddress)); EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_issued_cid_for_preferred_address); EXPECT_CALL(visitor_, OnCryptoFrame(_)); ProcessFramePacketWithAddresses(MakeCryptoFrame(), kServerPreferredAddress, kNewPeerAddress, ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); EXPECT_EQ(kServerPreferredAddress.host(), writer_->last_write_source_address()); EXPECT_EQ(kSelfAddress, connection_.self_address()); } TEST_P(QuicConnectionTest, EcnCodepointsRejected) { SetQuicRestartFlag(quic_support_ect1, true); for (QuicEcnCodepoint ecn : {ECN_NOT_ECT, ECN_ECT0, ECN_ECT1, ECN_CE}) { if (ecn == ECN_ECT0) { EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false)); } else if (ecn == ECN_ECT1) { EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false)); } if (ecn == ECN_NOT_ECT) { EXPECT_TRUE(connection_.set_ecn_codepoint(ecn)); } else { EXPECT_FALSE(connection_.set_ecn_codepoint(ecn)); } EXPECT_EQ(connection_.ecn_codepoint(), ECN_NOT_ECT); EXPECT_CALL(connection_, OnSerializedPacket(_)); SendPing(); EXPECT_EQ(writer_->last_ecn_sent(), ECN_NOT_ECT); } } TEST_P(QuicConnectionTest, EcnCodepointsAccepted) { SetQuicRestartFlag(quic_support_ect1, true); for (QuicEcnCodepoint ecn : {ECN_NOT_ECT, ECN_ECT0, ECN_ECT1, ECN_CE}) { if (ecn == ECN_ECT0) { EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(true)); } else if (ecn == ECN_ECT1) { EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true)); } if (ecn == ECN_CE) { EXPECT_FALSE(connection_.set_ecn_codepoint(ecn)); } else { EXPECT_TRUE(connection_.set_ecn_codepoint(ecn)); } EXPECT_CALL(connection_, OnSerializedPacket(_)); SendPing(); QuicEcnCodepoint expected_codepoint = ecn; if (ecn == ECN_CE) { expected_codepoint = ECN_ECT1; } EXPECT_EQ(connection_.ecn_codepoint(), expected_codepoint); EXPECT_EQ(writer_->last_ecn_sent(), expected_codepoint); } } TEST_P(QuicConnectionTest, EcnCodepointsRejectedIfFlagIsFalse) { SetQuicRestartFlag(quic_support_ect1, false); for (QuicEcnCodepoint ecn : {ECN_NOT_ECT, ECN_ECT0, ECN_ECT1, ECN_CE}) { EXPECT_FALSE(connection_.set_ecn_codepoint(ecn)); EXPECT_CALL(connection_, OnSerializedPacket(_)); SendPing(); EXPECT_EQ(connection_.ecn_codepoint(), ECN_NOT_ECT); EXPECT_EQ(writer_->last_ecn_sent(), ECN_NOT_ECT); } } TEST_P(QuicConnectionTest, EcnValidationDisabled) { SetQuicRestartFlag(quic_support_ect1, true); QuicConnectionPeer::DisableEcnCodepointValidation(&connection_); for (QuicEcnCodepoint ecn : {ECN_NOT_ECT, ECN_ECT0, ECN_ECT1, ECN_CE}) { EXPECT_TRUE(connection_.set_ecn_codepoint(ecn)); EXPECT_CALL(connection_, OnSerializedPacket(_)); SendPing(); EXPECT_EQ(connection_.ecn_codepoint(), ecn); EXPECT_EQ(writer_->last_ecn_sent(), ecn); } } TEST_P(QuicConnectionTest, RtoDisablesEcnMarking) { SetQuicRestartFlag(quic_support_ect1, true); EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true)); EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1)); QuicPacketCreatorPeer::SetPacketNumber( QuicConnectionPeer::GetPacketCreator(&connection_), 1); SendPing(); connection_.OnRetransmissionAlarm(); EXPECT_EQ(writer_->last_ecn_sent(), ECN_NOT_ECT); EXPECT_EQ(connection_.ecn_codepoint(), ECN_ECT1); connection_.OnRetransmissionAlarm(); EXPECT_EQ(writer_->last_ecn_sent(), ECN_NOT_ECT); EXPECT_EQ(connection_.ecn_codepoint(), ECN_NOT_ECT); } TEST_P(QuicConnectionTest, RtoDoesntDisableEcnMarkingIfEcnAcked) { SetQuicRestartFlag(quic_support_ect1, true); EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true)); EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1)); QuicPacketCreatorPeer::SetPacketNumber( QuicConnectionPeer::GetPacketCreator(&connection_), 1); connection_.OnInFlightEcnPacketAcked(); SendPing(); connection_.OnRetransmissionAlarm(); QuicEcnCodepoint expected_codepoint = ECN_ECT1; EXPECT_EQ(writer_->last_ecn_sent(), expected_codepoint); EXPECT_EQ(connection_.ecn_codepoint(), expected_codepoint); connection_.OnRetransmissionAlarm(); EXPECT_EQ(writer_->last_ecn_sent(), expected_codepoint); EXPECT_EQ(connection_.ecn_codepoint(), expected_codepoint); } TEST_P(QuicConnectionTest, InvalidFeedbackCancelsEcn) { SetQuicRestartFlag(quic_support_ect1, true); EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true)); EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1)); EXPECT_EQ(connection_.ecn_codepoint(), ECN_ECT1); connection_.OnInvalidEcnFeedback(); EXPECT_EQ(connection_.ecn_codepoint(), ECN_NOT_ECT); } TEST_P(QuicConnectionTest, StateMatchesSentEcn) { SetQuicRestartFlag(quic_support_ect1, true); EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true)); EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1)); SendPing(); QuicSentPacketManager* sent_packet_manager = QuicConnectionPeer::GetSentPacketManager(&connection_); EXPECT_EQ(writer_->last_ecn_sent(), ECN_ECT1); EXPECT_EQ( QuicSentPacketManagerPeer::GetEct1Sent(sent_packet_manager, INITIAL_DATA), 1); } TEST_P(QuicConnectionTest, CoalescedPacketSplitsEcn) { if (!connection_.version().CanSendCoalescedPackets()) { return; } SetQuicRestartFlag(quic_support_ect1, true); EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true)); EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1)); char buffer[1000]; creator_->set_encryption_level(ENCRYPTION_INITIAL); QuicFrames frames; QuicPingFrame ping; frames.emplace_back(QuicFrame(ping)); SerializedPacket packet1 = QuicPacketCreatorPeer::SerializeAllFrames( creator_, frames, buffer, sizeof(buffer)); connection_.SendOrQueuePacket(std::move(packet1)); creator_->set_encryption_level(ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(true)); EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT0)); EXPECT_EQ(writer_->packets_write_attempts(), 0); SendPing(); EXPECT_EQ(writer_->packets_write_attempts(), 2); EXPECT_EQ(writer_->last_ecn_sent(), ECN_ECT0); } TEST_P(QuicConnectionTest, BufferedPacketRetainsOldEcn) { SetQuicRestartFlag(quic_support_ect1, true); EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true)); EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1)); writer_->SetWriteBlocked(); EXPECT_CALL(visitor_, OnWriteBlocked()).Times(2); SendPing(); EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(true)); EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT0)); writer_->SetWritable(); connection_.OnCanWrite(); EXPECT_EQ(writer_->last_ecn_sent(), ECN_ECT1); } TEST_P(QuicConnectionTest, RejectEcnIfWriterDoesNotSupport) { SetQuicRestartFlag(quic_support_ect1, true); MockPacketWriter mock_writer; QuicConnectionPeer::SetWriter(&connection_, &mock_writer, false); EXPECT_CALL(mock_writer, SupportsEcn()).WillOnce(Return(false)); EXPECT_FALSE(connection_.set_ecn_codepoint(ECN_ECT1)); EXPECT_EQ(connection_.ecn_codepoint(), ECN_NOT_ECT); } TEST_P(QuicConnectionTest, RejectResetStreamAtIfNotNegotiated) { if (!version().HasIetfQuicFrames()) { return; } EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; config.SetReliableStreamReset(false); connection_.SetFromConfig(config); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1); connection_.OnResetStreamAtFrame(QuicResetStreamAtFrame()); } TEST_P(QuicConnectionTest, ResetStreamAt) { if (!version().HasIetfQuicFrames()) { return; } EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)); QuicConfig config; config.SetReliableStreamReset(true); connection_.SetFromConfig(config); connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(visitor_, OnResetStreamAt(QuicResetStreamAtFrame( 0, 0, QUIC_STREAM_NO_ERROR, 20, 10))) .Times(1); connection_.OnResetStreamAtFrame(QuicResetStreamAtFrame(0, 0, 0, 20, 10)); } TEST_P(QuicConnectionTest, OnParsedClientHelloInfoWithDebugVisitor) { const ParsedClientHello parsed_chlo{.sni = "sni", .uaid = "uiad", .supported_groups = {1, 2, 3}, .cert_compression_algos = {4, 5, 6}, .alpns = {"h2", "http/1.1"}, .retry_token = "retry_token"}; MockQuicConnectionDebugVisitor debug_visitor; connection_.set_debug_visitor(&debug_visitor); EXPECT_CALL(debug_visitor, OnParsedClientHelloInfo(parsed_chlo)).Times(1); connection_.OnParsedClientHelloInfo(parsed_chlo); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_connection.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_connection_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
6dca675b-a2d7-4768-a4d6-9fbb377b81d0
cpp
google/quiche
quic_coalesced_packet
quiche/quic/core/quic_coalesced_packet.cc
quiche/quic/core/quic_coalesced_packet_test.cc
#include "quiche/quic/core/quic_coalesced_packet.h" #include <string> #include <vector> #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "quiche/quic/platform/api/quic_bug_tracker.h" namespace quic { QuicCoalescedPacket::QuicCoalescedPacket() : length_(0), max_packet_length_(0), ecn_codepoint_(ECN_NOT_ECT) {} QuicCoalescedPacket::~QuicCoalescedPacket() { Clear(); } bool QuicCoalescedPacket::MaybeCoalescePacket( const SerializedPacket& packet, const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, quiche::QuicheBufferAllocator* allocator, QuicPacketLength current_max_packet_length, QuicEcnCodepoint ecn_codepoint) { if (packet.encrypted_length == 0) { QUIC_BUG(quic_bug_10611_1) << "Trying to coalesce an empty packet"; return true; } if (length_ == 0) { #ifndef NDEBUG for (const auto& buffer : encrypted_buffers_) { QUICHE_DCHECK(buffer.empty()); } #endif QUICHE_DCHECK(initial_packet_ == nullptr); max_packet_length_ = current_max_packet_length; self_address_ = self_address; peer_address_ = peer_address; } else { if (self_address_ != self_address || peer_address_ != peer_address) { QUIC_DLOG(INFO) << "Cannot coalesce packet because self/peer address changed"; return false; } if (max_packet_length_ != current_max_packet_length) { QUIC_BUG(quic_bug_10611_2) << "Max packet length changes in the middle of the write path"; return false; } if (ContainsPacketOfEncryptionLevel(packet.encryption_level)) { return false; } if (ecn_codepoint != ecn_codepoint_) { return false; } } if (length_ + packet.encrypted_length > max_packet_length_) { return false; } QUIC_DVLOG(1) << "Successfully coalesced packet: encryption_level: " << packet.encryption_level << ", encrypted_length: " << packet.encrypted_length << ", current length: " << length_ << ", max_packet_length: " << max_packet_length_; if (length_ > 0) { QUIC_CODE_COUNT(QUIC_SUCCESSFULLY_COALESCED_MULTIPLE_PACKETS); } ecn_codepoint_ = ecn_codepoint; length_ += packet.encrypted_length; transmission_types_[packet.encryption_level] = packet.transmission_type; if (packet.encryption_level == ENCRYPTION_INITIAL) { initial_packet_ = absl::WrapUnique<SerializedPacket>( CopySerializedPacket(packet, allocator, false)); return true; } encrypted_buffers_[packet.encryption_level] = std::string(packet.encrypted_buffer, packet.encrypted_length); return true; } void QuicCoalescedPacket::Clear() { self_address_ = QuicSocketAddress(); peer_address_ = QuicSocketAddress(); length_ = 0; max_packet_length_ = 0; for (auto& packet : encrypted_buffers_) { packet.clear(); } for (size_t i = ENCRYPTION_INITIAL; i < NUM_ENCRYPTION_LEVELS; ++i) { transmission_types_[i] = NOT_RETRANSMISSION; } initial_packet_ = nullptr; } void QuicCoalescedPacket::NeuterInitialPacket() { if (initial_packet_ == nullptr) { return; } if (length_ < initial_packet_->encrypted_length) { QUIC_BUG(quic_bug_10611_3) << "length_: " << length_ << ", is less than initial packet length: " << initial_packet_->encrypted_length; Clear(); return; } length_ -= initial_packet_->encrypted_length; if (length_ == 0) { Clear(); return; } transmission_types_[ENCRYPTION_INITIAL] = NOT_RETRANSMISSION; initial_packet_ = nullptr; } bool QuicCoalescedPacket::CopyEncryptedBuffers(char* buffer, size_t buffer_len, size_t* length_copied) const { *length_copied = 0; for (const auto& packet : encrypted_buffers_) { if (packet.empty()) { continue; } if (packet.length() > buffer_len) { return false; } memcpy(buffer, packet.data(), packet.length()); buffer += packet.length(); buffer_len -= packet.length(); *length_copied += packet.length(); } return true; } bool QuicCoalescedPacket::ContainsPacketOfEncryptionLevel( EncryptionLevel level) const { return !encrypted_buffers_[level].empty() || (level == ENCRYPTION_INITIAL && initial_packet_ != nullptr); } TransmissionType QuicCoalescedPacket::TransmissionTypeOfPacket( EncryptionLevel level) const { if (!ContainsPacketOfEncryptionLevel(level)) { QUIC_BUG(quic_bug_10611_4) << "Coalesced packet does not contain packet of encryption level: " << EncryptionLevelToString(level); return NOT_RETRANSMISSION; } return transmission_types_[level]; } size_t QuicCoalescedPacket::NumberOfPackets() const { size_t num_of_packets = 0; for (int8_t i = ENCRYPTION_INITIAL; i < NUM_ENCRYPTION_LEVELS; ++i) { if (ContainsPacketOfEncryptionLevel(static_cast<EncryptionLevel>(i))) { ++num_of_packets; } } return num_of_packets; } std::string QuicCoalescedPacket::ToString(size_t serialized_length) const { std::string info = absl::StrCat( "total_length: ", serialized_length, " padding_size: ", serialized_length - length_, " packets: {"); bool first_packet = true; for (int8_t i = ENCRYPTION_INITIAL; i < NUM_ENCRYPTION_LEVELS; ++i) { if (ContainsPacketOfEncryptionLevel(static_cast<EncryptionLevel>(i))) { absl::StrAppend(&info, first_packet ? "" : ", ", EncryptionLevelToString(static_cast<EncryptionLevel>(i))); first_packet = false; } } absl::StrAppend(&info, "}"); return info; } std::vector<size_t> QuicCoalescedPacket::packet_lengths() const { std::vector<size_t> lengths; for (const auto& packet : encrypted_buffers_) { if (lengths.empty()) { lengths.push_back( initial_packet_ == nullptr ? 0 : initial_packet_->encrypted_length); } else { lengths.push_back(packet.length()); } } return lengths; } }
#include "quiche/quic/core/quic_coalesced_packet.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/quic_test_utils.h" #include "quiche/common/test_tools/quiche_test_utils.h" namespace quic { namespace test { namespace { TEST(QuicCoalescedPacketTest, MaybeCoalescePacket) { QuicCoalescedPacket coalesced; EXPECT_EQ("total_length: 0 padding_size: 0 packets: {}", coalesced.ToString(0)); quiche::SimpleBufferAllocator allocator; EXPECT_EQ(0u, coalesced.length()); EXPECT_EQ(0u, coalesced.NumberOfPackets()); char buffer[1000]; QuicSocketAddress self_address(QuicIpAddress::Loopback4(), 1); QuicSocketAddress peer_address(QuicIpAddress::Loopback4(), 2); SerializedPacket packet1(QuicPacketNumber(1), PACKET_4BYTE_PACKET_NUMBER, buffer, 500, false, false); packet1.transmission_type = PTO_RETRANSMISSION; QuicAckFrame ack_frame(InitAckFrame(1)); packet1.nonretransmittable_frames.push_back(QuicFrame(&ack_frame)); packet1.retransmittable_frames.push_back( QuicFrame(QuicStreamFrame(1, true, 0, 100))); ASSERT_TRUE(coalesced.MaybeCoalescePacket(packet1, self_address, peer_address, &allocator, 1500, ECN_NOT_ECT)); EXPECT_EQ(PTO_RETRANSMISSION, coalesced.TransmissionTypeOfPacket(ENCRYPTION_INITIAL)); EXPECT_EQ(1500u, coalesced.max_packet_length()); EXPECT_EQ(500u, coalesced.length()); EXPECT_EQ(1u, coalesced.NumberOfPackets()); EXPECT_EQ( "total_length: 1500 padding_size: 1000 packets: {ENCRYPTION_INITIAL}", coalesced.ToString(1500)); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_NOT_ECT); SerializedPacket packet2(QuicPacketNumber(2), PACKET_4BYTE_PACKET_NUMBER, buffer, 500, false, false); EXPECT_FALSE(coalesced.MaybeCoalescePacket( packet2, self_address, peer_address, &allocator, 1500, ECN_NOT_ECT)); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_NOT_ECT); SerializedPacket packet3(QuicPacketNumber(3), PACKET_4BYTE_PACKET_NUMBER, buffer, 500, false, false); packet3.nonretransmittable_frames.push_back(QuicFrame(QuicPaddingFrame(100))); packet3.encryption_level = ENCRYPTION_ZERO_RTT; packet3.transmission_type = LOSS_RETRANSMISSION; ASSERT_TRUE(coalesced.MaybeCoalescePacket(packet3, self_address, peer_address, &allocator, 1500, ECN_NOT_ECT)); EXPECT_EQ(1500u, coalesced.max_packet_length()); EXPECT_EQ(1000u, coalesced.length()); EXPECT_EQ(2u, coalesced.NumberOfPackets()); EXPECT_EQ(LOSS_RETRANSMISSION, coalesced.TransmissionTypeOfPacket(ENCRYPTION_ZERO_RTT)); EXPECT_EQ( "total_length: 1500 padding_size: 500 packets: {ENCRYPTION_INITIAL, " "ENCRYPTION_ZERO_RTT}", coalesced.ToString(1500)); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_NOT_ECT); SerializedPacket packet4(QuicPacketNumber(4), PACKET_4BYTE_PACKET_NUMBER, buffer, 500, false, false); packet4.encryption_level = ENCRYPTION_FORWARD_SECURE; EXPECT_FALSE(coalesced.MaybeCoalescePacket( packet4, QuicSocketAddress(QuicIpAddress::Loopback4(), 3), peer_address, &allocator, 1500, ECN_NOT_ECT)); SerializedPacket packet5(QuicPacketNumber(5), PACKET_4BYTE_PACKET_NUMBER, buffer, 501, false, false); packet5.encryption_level = ENCRYPTION_FORWARD_SECURE; EXPECT_FALSE(coalesced.MaybeCoalescePacket( packet5, self_address, peer_address, &allocator, 1500, ECN_NOT_ECT)); EXPECT_EQ(1500u, coalesced.max_packet_length()); EXPECT_EQ(1000u, coalesced.length()); EXPECT_EQ(2u, coalesced.NumberOfPackets()); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_NOT_ECT); SerializedPacket packet6(QuicPacketNumber(6), PACKET_4BYTE_PACKET_NUMBER, buffer, 100, false, false); packet6.encryption_level = ENCRYPTION_FORWARD_SECURE; EXPECT_QUIC_BUG( coalesced.MaybeCoalescePacket(packet6, self_address, peer_address, &allocator, 1000, ECN_NOT_ECT), "Max packet length changes in the middle of the write path"); EXPECT_EQ(1500u, coalesced.max_packet_length()); EXPECT_EQ(1000u, coalesced.length()); EXPECT_EQ(2u, coalesced.NumberOfPackets()); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_NOT_ECT); } TEST(QuicCoalescedPacketTest, CopyEncryptedBuffers) { QuicCoalescedPacket coalesced; quiche::SimpleBufferAllocator allocator; QuicSocketAddress self_address(QuicIpAddress::Loopback4(), 1); QuicSocketAddress peer_address(QuicIpAddress::Loopback4(), 2); std::string buffer(500, 'a'); std::string buffer2(500, 'b'); SerializedPacket packet1(QuicPacketNumber(1), PACKET_4BYTE_PACKET_NUMBER, buffer.data(), 500, false, false); packet1.encryption_level = ENCRYPTION_ZERO_RTT; SerializedPacket packet2(QuicPacketNumber(2), PACKET_4BYTE_PACKET_NUMBER, buffer2.data(), 500, false, false); packet2.encryption_level = ENCRYPTION_FORWARD_SECURE; ASSERT_TRUE(coalesced.MaybeCoalescePacket(packet1, self_address, peer_address, &allocator, 1500, ECN_NOT_ECT)); ASSERT_TRUE(coalesced.MaybeCoalescePacket(packet2, self_address, peer_address, &allocator, 1500, ECN_NOT_ECT)); EXPECT_EQ(1000u, coalesced.length()); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_NOT_ECT); char copy_buffer[1000]; size_t length_copied = 0; EXPECT_FALSE( coalesced.CopyEncryptedBuffers(copy_buffer, 900, &length_copied)); ASSERT_TRUE( coalesced.CopyEncryptedBuffers(copy_buffer, 1000, &length_copied)); EXPECT_EQ(1000u, length_copied); char expected[1000]; memset(expected, 'a', 500); memset(expected + 500, 'b', 500); quiche::test::CompareCharArraysWithHexError("copied buffers", copy_buffer, length_copied, expected, 1000); } TEST(QuicCoalescedPacketTest, NeuterInitialPacket) { QuicCoalescedPacket coalesced; EXPECT_EQ("total_length: 0 padding_size: 0 packets: {}", coalesced.ToString(0)); coalesced.NeuterInitialPacket(); EXPECT_EQ("total_length: 0 padding_size: 0 packets: {}", coalesced.ToString(0)); quiche::SimpleBufferAllocator allocator; EXPECT_EQ(0u, coalesced.length()); char buffer[1000]; QuicSocketAddress self_address(QuicIpAddress::Loopback4(), 1); QuicSocketAddress peer_address(QuicIpAddress::Loopback4(), 2); SerializedPacket packet1(QuicPacketNumber(1), PACKET_4BYTE_PACKET_NUMBER, buffer, 500, false, false); packet1.transmission_type = PTO_RETRANSMISSION; QuicAckFrame ack_frame(InitAckFrame(1)); packet1.nonretransmittable_frames.push_back(QuicFrame(&ack_frame)); packet1.retransmittable_frames.push_back( QuicFrame(QuicStreamFrame(1, true, 0, 100))); ASSERT_TRUE(coalesced.MaybeCoalescePacket(packet1, self_address, peer_address, &allocator, 1500, ECN_NOT_ECT)); EXPECT_EQ(PTO_RETRANSMISSION, coalesced.TransmissionTypeOfPacket(ENCRYPTION_INITIAL)); EXPECT_EQ(1500u, coalesced.max_packet_length()); EXPECT_EQ(500u, coalesced.length()); EXPECT_EQ( "total_length: 1500 padding_size: 1000 packets: {ENCRYPTION_INITIAL}", coalesced.ToString(1500)); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_NOT_ECT); coalesced.NeuterInitialPacket(); EXPECT_EQ(0u, coalesced.max_packet_length()); EXPECT_EQ(0u, coalesced.length()); EXPECT_EQ("total_length: 0 padding_size: 0 packets: {}", coalesced.ToString(0)); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_NOT_ECT); ASSERT_TRUE(coalesced.MaybeCoalescePacket(packet1, self_address, peer_address, &allocator, 1500, ECN_NOT_ECT)); SerializedPacket packet2(QuicPacketNumber(3), PACKET_4BYTE_PACKET_NUMBER, buffer, 500, false, false); packet2.nonretransmittable_frames.push_back(QuicFrame(QuicPaddingFrame(100))); packet2.encryption_level = ENCRYPTION_ZERO_RTT; packet2.transmission_type = LOSS_RETRANSMISSION; ASSERT_TRUE(coalesced.MaybeCoalescePacket(packet2, self_address, peer_address, &allocator, 1500, ECN_NOT_ECT)); EXPECT_EQ(1500u, coalesced.max_packet_length()); EXPECT_EQ(1000u, coalesced.length()); EXPECT_EQ(LOSS_RETRANSMISSION, coalesced.TransmissionTypeOfPacket(ENCRYPTION_ZERO_RTT)); EXPECT_EQ( "total_length: 1500 padding_size: 500 packets: {ENCRYPTION_INITIAL, " "ENCRYPTION_ZERO_RTT}", coalesced.ToString(1500)); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_NOT_ECT); coalesced.NeuterInitialPacket(); EXPECT_EQ(1500u, coalesced.max_packet_length()); EXPECT_EQ(500u, coalesced.length()); EXPECT_EQ( "total_length: 1500 padding_size: 1000 packets: {ENCRYPTION_ZERO_RTT}", coalesced.ToString(1500)); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_NOT_ECT); SerializedPacket packet3(QuicPacketNumber(5), PACKET_4BYTE_PACKET_NUMBER, buffer, 501, false, false); packet3.encryption_level = ENCRYPTION_FORWARD_SECURE; EXPECT_TRUE(coalesced.MaybeCoalescePacket(packet3, self_address, peer_address, &allocator, 1500, ECN_NOT_ECT)); EXPECT_EQ(1500u, coalesced.max_packet_length()); EXPECT_EQ(1001u, coalesced.length()); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_NOT_ECT); coalesced.NeuterInitialPacket(); EXPECT_EQ(1500u, coalesced.max_packet_length()); EXPECT_EQ(1001u, coalesced.length()); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_NOT_ECT); } TEST(QuicCoalescedPacketTest, DoNotCoalesceDifferentEcn) { QuicCoalescedPacket coalesced; EXPECT_EQ("total_length: 0 padding_size: 0 packets: {}", coalesced.ToString(0)); quiche::SimpleBufferAllocator allocator; EXPECT_EQ(0u, coalesced.length()); EXPECT_EQ(0u, coalesced.NumberOfPackets()); char buffer[1000]; QuicSocketAddress self_address(QuicIpAddress::Loopback4(), 1); QuicSocketAddress peer_address(QuicIpAddress::Loopback4(), 2); SerializedPacket packet1(QuicPacketNumber(1), PACKET_4BYTE_PACKET_NUMBER, buffer, 500, false, false); packet1.transmission_type = PTO_RETRANSMISSION; QuicAckFrame ack_frame(InitAckFrame(1)); packet1.nonretransmittable_frames.push_back(QuicFrame(&ack_frame)); packet1.retransmittable_frames.push_back( QuicFrame(QuicStreamFrame(1, true, 0, 100))); ASSERT_TRUE(coalesced.MaybeCoalescePacket(packet1, self_address, peer_address, &allocator, 1500, ECN_ECT1)); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_ECT1); SerializedPacket packet2(QuicPacketNumber(2), PACKET_4BYTE_PACKET_NUMBER, buffer, 500, false, false); packet2.nonretransmittable_frames.push_back(QuicFrame(QuicPaddingFrame(100))); packet2.encryption_level = ENCRYPTION_ZERO_RTT; packet2.transmission_type = LOSS_RETRANSMISSION; EXPECT_FALSE(coalesced.MaybeCoalescePacket( packet2, self_address, peer_address, &allocator, 1500, ECN_NOT_ECT)); EXPECT_EQ(coalesced.ecn_codepoint(), ECN_ECT1); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_coalesced_packet.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_coalesced_packet_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
da92f8e1-d262-4798-9989-74b9fb5da602
cpp
google/quiche
quic_time_wait_list_manager
quiche/quic/core/quic_time_wait_list_manager.cc
quiche/quic/core/quic_time_wait_list_manager_test.cc
#include "quiche/quic/core/quic_time_wait_list_manager.h" #include <errno.h> #include <memory> #include <ostream> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/crypto/quic_decrypter.h" #include "quiche/quic/core/crypto/quic_encrypter.h" #include "quiche/quic/core/quic_clock.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_framer.h" #include "quiche/quic/core/quic_packets.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" #include "quiche/common/quiche_text_utils.h" namespace quic { class ConnectionIdCleanUpAlarm : public QuicAlarm::DelegateWithoutContext { public: explicit ConnectionIdCleanUpAlarm( QuicTimeWaitListManager* time_wait_list_manager) : time_wait_list_manager_(time_wait_list_manager) {} ConnectionIdCleanUpAlarm(const ConnectionIdCleanUpAlarm&) = delete; ConnectionIdCleanUpAlarm& operator=(const ConnectionIdCleanUpAlarm&) = delete; void OnAlarm() override { time_wait_list_manager_->CleanUpOldConnectionIds(); } private: QuicTimeWaitListManager* time_wait_list_manager_; }; TimeWaitConnectionInfo::TimeWaitConnectionInfo( bool ietf_quic, std::vector<std::unique_ptr<QuicEncryptedPacket>>* termination_packets, std::vector<QuicConnectionId> active_connection_ids) : TimeWaitConnectionInfo(ietf_quic, termination_packets, std::move(active_connection_ids), QuicTime::Delta::Zero()) {} TimeWaitConnectionInfo::TimeWaitConnectionInfo( bool ietf_quic, std::vector<std::unique_ptr<QuicEncryptedPacket>>* termination_packets, std::vector<QuicConnectionId> active_connection_ids, QuicTime::Delta srtt) : ietf_quic(ietf_quic), active_connection_ids(std::move(active_connection_ids)), srtt(srtt) { if (termination_packets != nullptr) { this->termination_packets.swap(*termination_packets); } } QuicTimeWaitListManager::QuicTimeWaitListManager( QuicPacketWriter* writer, Visitor* visitor, const QuicClock* clock, QuicAlarmFactory* alarm_factory) : time_wait_period_(QuicTime::Delta::FromSeconds( GetQuicFlag(quic_time_wait_list_seconds))), connection_id_clean_up_alarm_( alarm_factory->CreateAlarm(new ConnectionIdCleanUpAlarm(this))), clock_(clock), writer_(writer), visitor_(visitor) { SetConnectionIdCleanUpAlarm(); } QuicTimeWaitListManager::~QuicTimeWaitListManager() { connection_id_clean_up_alarm_->Cancel(); } QuicTimeWaitListManager::ConnectionIdMap::iterator QuicTimeWaitListManager::FindConnectionIdDataInMap( const QuicConnectionId& connection_id) { auto it = indirect_connection_id_map_.find(connection_id); if (it == indirect_connection_id_map_.end()) { return connection_id_map_.end(); } return connection_id_map_.find(it->second); } void QuicTimeWaitListManager::AddConnectionIdDataToMap( const QuicConnectionId& canonical_connection_id, int num_packets, TimeWaitAction action, TimeWaitConnectionInfo info) { for (const auto& cid : info.active_connection_ids) { indirect_connection_id_map_[cid] = canonical_connection_id; } ConnectionIdData data(num_packets, clock_->ApproximateNow(), action, std::move(info)); connection_id_map_.emplace( std::make_pair(canonical_connection_id, std::move(data))); } void QuicTimeWaitListManager::RemoveConnectionDataFromMap( ConnectionIdMap::iterator it) { for (const auto& cid : it->second.info.active_connection_ids) { indirect_connection_id_map_.erase(cid); } connection_id_map_.erase(it); } void QuicTimeWaitListManager::AddConnectionIdToTimeWait( TimeWaitAction action, TimeWaitConnectionInfo info) { QUICHE_DCHECK(!info.active_connection_ids.empty()); const QuicConnectionId& canonical_connection_id = info.active_connection_ids.front(); QUICHE_DCHECK(action != SEND_TERMINATION_PACKETS || !info.termination_packets.empty()); QUICHE_DCHECK(action != DO_NOTHING || info.ietf_quic); int num_packets = 0; auto it = FindConnectionIdDataInMap(canonical_connection_id); const bool new_connection_id = it == connection_id_map_.end(); if (!new_connection_id) { num_packets = it->second.num_packets; RemoveConnectionDataFromMap(it); } TrimTimeWaitListIfNeeded(); int64_t max_connections = GetQuicFlag(quic_time_wait_list_max_connections); QUICHE_DCHECK(connection_id_map_.empty() || num_connections() < static_cast<size_t>(max_connections)); if (new_connection_id) { for (const auto& cid : info.active_connection_ids) { visitor_->OnConnectionAddedToTimeWaitList(cid); } } AddConnectionIdDataToMap(canonical_connection_id, num_packets, action, std::move(info)); } bool QuicTimeWaitListManager::IsConnectionIdInTimeWait( QuicConnectionId connection_id) const { return indirect_connection_id_map_.contains(connection_id); } void QuicTimeWaitListManager::OnBlockedWriterCanWrite() { writer_->SetWritable(); while (!pending_packets_queue_.empty()) { QueuedPacket* queued_packet = pending_packets_queue_.front().get(); if (!WriteToWire(queued_packet)) { return; } pending_packets_queue_.pop_front(); } } void QuicTimeWaitListManager::ProcessPacket( const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, QuicConnectionId connection_id, PacketHeaderFormat header_format, size_t received_packet_length, std::unique_ptr<QuicPerPacketContext> packet_context) { QUICHE_DCHECK(IsConnectionIdInTimeWait(connection_id)); auto it = FindConnectionIdDataInMap(connection_id); QUICHE_DCHECK(it != connection_id_map_.end()); ConnectionIdData* connection_data = &it->second; ++(connection_data->num_packets); const QuicTime now = clock_->ApproximateNow(); QuicTime::Delta delta = QuicTime::Delta::Zero(); if (now > connection_data->time_added) { delta = now - connection_data->time_added; } OnPacketReceivedForKnownConnection(connection_data->num_packets, delta, connection_data->info.srtt); if (!ShouldSendResponse(connection_data->num_packets)) { QUIC_DLOG(INFO) << "Processing " << connection_id << " in time wait state: " << "throttled"; return; } QUIC_DLOG(INFO) << "Processing " << connection_id << " in time wait state: " << "header format=" << header_format << " ietf=" << connection_data->info.ietf_quic << ", action=" << connection_data->action << ", number termination packets=" << connection_data->info.termination_packets.size(); switch (connection_data->action) { case SEND_TERMINATION_PACKETS: if (connection_data->info.termination_packets.empty()) { QUIC_BUG(quic_bug_10608_1) << "There are no termination packets."; return; } switch (header_format) { case IETF_QUIC_LONG_HEADER_PACKET: if (!connection_data->info.ietf_quic) { QUIC_CODE_COUNT(quic_received_long_header_packet_for_gquic); } break; case IETF_QUIC_SHORT_HEADER_PACKET: if (!connection_data->info.ietf_quic) { QUIC_CODE_COUNT(quic_received_short_header_packet_for_gquic); } SendPublicReset(self_address, peer_address, connection_id, connection_data->info.ietf_quic, received_packet_length, std::move(packet_context)); return; case GOOGLE_QUIC_PACKET: if (connection_data->info.ietf_quic) { QUIC_CODE_COUNT(quic_received_gquic_packet_for_ietf_quic); } break; } for (const auto& packet : connection_data->info.termination_packets) { SendOrQueuePacket(std::make_unique<QueuedPacket>( self_address, peer_address, packet->Clone()), packet_context.get()); } return; case SEND_CONNECTION_CLOSE_PACKETS: if (connection_data->info.termination_packets.empty()) { QUIC_BUG(quic_bug_10608_2) << "There are no termination packets."; return; } for (const auto& packet : connection_data->info.termination_packets) { SendOrQueuePacket(std::make_unique<QueuedPacket>( self_address, peer_address, packet->Clone()), packet_context.get()); } return; case SEND_STATELESS_RESET: if (header_format == IETF_QUIC_LONG_HEADER_PACKET) { QUIC_CODE_COUNT(quic_stateless_reset_long_header_packet); } SendPublicReset(self_address, peer_address, connection_id, connection_data->info.ietf_quic, received_packet_length, std::move(packet_context)); return; case DO_NOTHING: QUIC_CODE_COUNT(quic_time_wait_list_do_nothing); QUICHE_DCHECK(connection_data->info.ietf_quic); } } void QuicTimeWaitListManager::SendVersionNegotiationPacket( QuicConnectionId server_connection_id, QuicConnectionId client_connection_id, bool ietf_quic, bool use_length_prefix, const ParsedQuicVersionVector& supported_versions, const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, std::unique_ptr<QuicPerPacketContext> packet_context) { std::unique_ptr<QuicEncryptedPacket> version_packet = QuicFramer::BuildVersionNegotiationPacket( server_connection_id, client_connection_id, ietf_quic, use_length_prefix, supported_versions); QUIC_DVLOG(2) << "Dispatcher sending version negotiation packet {" << ParsedQuicVersionVectorToString(supported_versions) << "}, " << (ietf_quic ? "" : "!") << "ietf_quic, " << (use_length_prefix ? "" : "!") << "use_length_prefix:" << std::endl << quiche::QuicheTextUtils::HexDump(absl::string_view( version_packet->data(), version_packet->length())); SendOrQueuePacket(std::make_unique<QueuedPacket>(self_address, peer_address, std::move(version_packet)), packet_context.get()); } bool QuicTimeWaitListManager::ShouldSendResponse(int received_packet_count) { return (received_packet_count & (received_packet_count - 1)) == 0; } void QuicTimeWaitListManager::SendPublicReset( const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, QuicConnectionId connection_id, bool ietf_quic, size_t received_packet_length, std::unique_ptr<QuicPerPacketContext> packet_context) { if (ietf_quic) { std::unique_ptr<QuicEncryptedPacket> ietf_reset_packet = BuildIetfStatelessResetPacket(connection_id, received_packet_length); if (ietf_reset_packet == nullptr) { return; } QUIC_DVLOG(2) << "Dispatcher sending IETF reset packet for " << connection_id << std::endl << quiche::QuicheTextUtils::HexDump( absl::string_view(ietf_reset_packet->data(), ietf_reset_packet->length())); SendOrQueuePacket( std::make_unique<QueuedPacket>(self_address, peer_address, std::move(ietf_reset_packet)), packet_context.get()); return; } QuicPublicResetPacket packet; packet.connection_id = connection_id; packet.nonce_proof = 1010101; packet.client_address = peer_address; GetEndpointId(&packet.endpoint_id); std::unique_ptr<QuicEncryptedPacket> reset_packet = BuildPublicReset(packet); QUIC_DVLOG(2) << "Dispatcher sending reset packet for " << connection_id << std::endl << quiche::QuicheTextUtils::HexDump(absl::string_view( reset_packet->data(), reset_packet->length())); SendOrQueuePacket(std::make_unique<QueuedPacket>(self_address, peer_address, std::move(reset_packet)), packet_context.get()); } void QuicTimeWaitListManager::SendPacket(const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, const QuicEncryptedPacket& packet) { SendOrQueuePacket(std::make_unique<QueuedPacket>(self_address, peer_address, packet.Clone()), nullptr); } std::unique_ptr<QuicEncryptedPacket> QuicTimeWaitListManager::BuildPublicReset( const QuicPublicResetPacket& packet) { return QuicFramer::BuildPublicResetPacket(packet); } std::unique_ptr<QuicEncryptedPacket> QuicTimeWaitListManager::BuildIetfStatelessResetPacket( QuicConnectionId connection_id, size_t received_packet_length) { return QuicFramer::BuildIetfStatelessResetPacket( connection_id, received_packet_length, GetStatelessResetToken(connection_id)); } bool QuicTimeWaitListManager::SendOrQueuePacket( std::unique_ptr<QueuedPacket> packet, const QuicPerPacketContext* ) { if (packet == nullptr) { QUIC_LOG(ERROR) << "Tried to send or queue a null packet"; return true; } if (pending_packets_queue_.size() >= GetQuicFlag(quic_time_wait_list_max_pending_packets)) { QUIC_CODE_COUNT(quic_too_many_pending_packets_in_time_wait); return true; } if (WriteToWire(packet.get())) { return true; } pending_packets_queue_.push_back(std::move(packet)); return false; } bool QuicTimeWaitListManager::WriteToWire(QueuedPacket* queued_packet) { if (writer_->IsWriteBlocked()) { visitor_->OnWriteBlocked(this); return false; } WriteResult result = writer_->WritePacket( queued_packet->packet()->data(), queued_packet->packet()->length(), queued_packet->self_address().host(), queued_packet->peer_address(), nullptr, QuicPacketWriterParams()); if (writer_->IsBatchMode() && result.status == WRITE_STATUS_OK && result.bytes_written == 0) { result = writer_->Flush(); } if (IsWriteBlockedStatus(result.status)) { QUICHE_DCHECK(writer_->IsWriteBlocked()); visitor_->OnWriteBlocked(this); return result.status == WRITE_STATUS_BLOCKED_DATA_BUFFERED; } else if (IsWriteError(result.status)) { QUIC_LOG_FIRST_N(WARNING, 1) << "Received unknown error while sending termination packet to " << queued_packet->peer_address().ToString() << ": " << strerror(result.error_code); } return true; } void QuicTimeWaitListManager::SetConnectionIdCleanUpAlarm() { QuicTime::Delta next_alarm_interval = QuicTime::Delta::Zero(); if (!connection_id_map_.empty()) { QuicTime oldest_connection_id = connection_id_map_.begin()->second.time_added; QuicTime now = clock_->ApproximateNow(); if (now - oldest_connection_id < time_wait_period_) { next_alarm_interval = oldest_connection_id + time_wait_period_ - now; } else { QUIC_LOG(ERROR) << "ConnectionId lingered for longer than time_wait_period_"; } } else { next_alarm_interval = time_wait_period_; } connection_id_clean_up_alarm_->Update( clock_->ApproximateNow() + next_alarm_interval, QuicTime::Delta::Zero()); } bool QuicTimeWaitListManager::MaybeExpireOldestConnection( QuicTime expiration_time) { if (connection_id_map_.empty()) { return false; } auto it = connection_id_map_.begin(); QuicTime oldest_connection_id_time = it->second.time_added; if (oldest_connection_id_time > expiration_time) { return false; } QUIC_DLOG(INFO) << "Connection " << it->first << " expired from time wait list"; RemoveConnectionDataFromMap(it); if (expiration_time == QuicTime::Infinite()) { QUIC_CODE_COUNT(quic_time_wait_list_trim_full); } else { QUIC_CODE_COUNT(quic_time_wait_list_expire_connections); } return true; } void QuicTimeWaitListManager::CleanUpOldConnectionIds() { QuicTime now = clock_->ApproximateNow(); QuicTime expiration = now - time_wait_period_; while (MaybeExpireOldestConnection(expiration)) { } SetConnectionIdCleanUpAlarm(); } void QuicTimeWaitListManager::TrimTimeWaitListIfNeeded() { const int64_t kMaxConnections = GetQuicFlag(quic_time_wait_list_max_connections); if (kMaxConnections < 0) { return; } while (!connection_id_map_.empty() && num_connections() >= static_cast<size_t>(kMaxConnections)) { MaybeExpireOldestConnection(QuicTime::Infinite()); } } QuicTimeWaitListManager::ConnectionIdData::ConnectionIdData( int num_packets, QuicTime time_added, TimeWaitAction action, TimeWaitConnectionInfo info) : num_packets(num_packets), time_added(time_added), action(action), info(std::move(info)) {} QuicTimeWaitListManager::ConnectionIdData::ConnectionIdData( ConnectionIdData&& other) = default; QuicTimeWaitListManager::ConnectionIdData::~ConnectionIdData() = default; StatelessResetToken QuicTimeWaitListManager::GetStatelessResetToken( QuicConnectionId connection_id) const { return QuicUtils::GenerateStatelessResetToken(connection_id); } }
#include "quiche/quic/core/quic_time_wait_list_manager.h" #include <cerrno> #include <memory> #include <ostream> #include <tuple> #include <utility> #include <vector> #include "quiche/quic/core/crypto/crypto_protocol.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/quic_connection_id.h" #include "quiche/quic/core/quic_data_reader.h" #include "quiche/quic/core/quic_framer.h" #include "quiche/quic/core/quic_packet_writer.h" #include "quiche/quic/core/quic_packets.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/mock_quic_session_visitor.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/quic_time_wait_list_manager_peer.h" using testing::_; using testing::Args; using testing::Assign; using testing::DoAll; using testing::Matcher; using testing::NiceMock; using testing::Return; using testing::ReturnPointee; using testing::StrictMock; using testing::Truly; namespace quic { namespace test { namespace { const size_t kTestPacketSize = 100; class FramerVisitorCapturingPublicReset : public NoOpFramerVisitor { public: FramerVisitorCapturingPublicReset(QuicConnectionId connection_id) : connection_id_(connection_id) {} ~FramerVisitorCapturingPublicReset() override = default; bool IsValidStatelessResetToken( const StatelessResetToken& token) const override { return token == QuicUtils::GenerateStatelessResetToken(connection_id_); } void OnAuthenticatedIetfStatelessResetPacket( const QuicIetfStatelessResetPacket& packet) override { stateless_reset_packet_ = packet; } const QuicIetfStatelessResetPacket stateless_reset_packet() { return stateless_reset_packet_; } private: QuicIetfStatelessResetPacket stateless_reset_packet_; QuicConnectionId connection_id_; }; class MockAlarmFactory; class MockAlarm : public QuicAlarm { public: explicit MockAlarm(QuicArenaScopedPtr<Delegate> delegate, int alarm_index, MockAlarmFactory* factory) : QuicAlarm(std::move(delegate)), alarm_index_(alarm_index), factory_(factory) {} virtual ~MockAlarm() {} void SetImpl() override; void CancelImpl() override; private: int alarm_index_; MockAlarmFactory* factory_; }; class MockAlarmFactory : public QuicAlarmFactory { public: ~MockAlarmFactory() override {} QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override { return new MockAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate>(delegate), alarm_index_++, this); } QuicArenaScopedPtr<QuicAlarm> CreateAlarm( QuicArenaScopedPtr<QuicAlarm::Delegate> delegate, QuicConnectionArena* arena) override { if (arena != nullptr) { return arena->New<MockAlarm>(std::move(delegate), alarm_index_++, this); } return QuicArenaScopedPtr<MockAlarm>( new MockAlarm(std::move(delegate), alarm_index_++, this)); } MOCK_METHOD(void, OnAlarmSet, (int, QuicTime), ()); MOCK_METHOD(void, OnAlarmCancelled, (int), ()); private: int alarm_index_ = 0; }; void MockAlarm::SetImpl() { factory_->OnAlarmSet(alarm_index_, deadline()); } void MockAlarm::CancelImpl() { factory_->OnAlarmCancelled(alarm_index_); } class QuicTimeWaitListManagerTest : public QuicTest { protected: QuicTimeWaitListManagerTest() : time_wait_list_manager_(&writer_, &visitor_, &clock_, &alarm_factory_), connection_id_(TestConnectionId(45)), peer_address_(TestPeerIPAddress(), kTestPort), writer_is_blocked_(false) {} ~QuicTimeWaitListManagerTest() override = default; void SetUp() override { EXPECT_CALL(writer_, IsWriteBlocked()) .WillRepeatedly(ReturnPointee(&writer_is_blocked_)); } void AddConnectionId(QuicConnectionId connection_id, QuicTimeWaitListManager::TimeWaitAction action) { AddConnectionId(connection_id, action, nullptr); } void AddStatelessConnectionId(QuicConnectionId connection_id) { std::vector<std::unique_ptr<QuicEncryptedPacket>> termination_packets; termination_packets.push_back(std::unique_ptr<QuicEncryptedPacket>( new QuicEncryptedPacket(nullptr, 0, false))); time_wait_list_manager_.AddConnectionIdToTimeWait( QuicTimeWaitListManager::SEND_TERMINATION_PACKETS, TimeWaitConnectionInfo(false, &termination_packets, {connection_id})); } void AddConnectionId( QuicConnectionId connection_id, QuicTimeWaitListManager::TimeWaitAction action, std::vector<std::unique_ptr<QuicEncryptedPacket>>* packets) { time_wait_list_manager_.AddConnectionIdToTimeWait( action, TimeWaitConnectionInfo(true, packets, {connection_id})); } bool IsConnectionIdInTimeWait(QuicConnectionId connection_id) { return time_wait_list_manager_.IsConnectionIdInTimeWait(connection_id); } void ProcessPacket(QuicConnectionId connection_id) { time_wait_list_manager_.ProcessPacket( self_address_, peer_address_, connection_id, GOOGLE_QUIC_PACKET, kTestPacketSize, std::make_unique<QuicPerPacketContext>()); } QuicEncryptedPacket* ConstructEncryptedPacket( QuicConnectionId destination_connection_id, QuicConnectionId source_connection_id, uint64_t packet_number) { return quic::test::ConstructEncryptedPacket(destination_connection_id, source_connection_id, false, false, packet_number, "data"); } MockClock clock_; MockAlarmFactory alarm_factory_; NiceMock<MockPacketWriter> writer_; StrictMock<MockQuicSessionVisitor> visitor_; QuicTimeWaitListManager time_wait_list_manager_; QuicConnectionId connection_id_; QuicSocketAddress self_address_; QuicSocketAddress peer_address_; bool writer_is_blocked_; }; bool ValidPublicResetPacketPredicate( QuicConnectionId expected_connection_id, const std::tuple<const char*, int>& packet_buffer) { FramerVisitorCapturingPublicReset visitor(expected_connection_id); QuicFramer framer(AllSupportedVersions(), QuicTime::Zero(), Perspective::IS_CLIENT, kQuicDefaultConnectionIdLength); framer.set_visitor(&visitor); QuicEncryptedPacket encrypted(std::get<0>(packet_buffer), std::get<1>(packet_buffer)); framer.ProcessPacket(encrypted); QuicIetfStatelessResetPacket stateless_reset = visitor.stateless_reset_packet(); StatelessResetToken expected_stateless_reset_token = QuicUtils::GenerateStatelessResetToken(expected_connection_id); return stateless_reset.stateless_reset_token == expected_stateless_reset_token; } Matcher<const std::tuple<const char*, int>> PublicResetPacketEq( QuicConnectionId connection_id) { return Truly( [connection_id](const std::tuple<const char*, int> packet_buffer) { return ValidPublicResetPacketPredicate(connection_id, packet_buffer); }); } TEST_F(QuicTimeWaitListManagerTest, CheckConnectionIdInTimeWait) { EXPECT_FALSE(IsConnectionIdInTimeWait(connection_id_)); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_)); AddConnectionId(connection_id_, QuicTimeWaitListManager::DO_NOTHING); EXPECT_EQ(1u, time_wait_list_manager_.num_connections()); EXPECT_TRUE(IsConnectionIdInTimeWait(connection_id_)); } TEST_F(QuicTimeWaitListManagerTest, CheckStatelessConnectionIdInTimeWait) { EXPECT_FALSE(IsConnectionIdInTimeWait(connection_id_)); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_)); AddStatelessConnectionId(connection_id_); EXPECT_EQ(1u, time_wait_list_manager_.num_connections()); EXPECT_TRUE(IsConnectionIdInTimeWait(connection_id_)); } TEST_F(QuicTimeWaitListManagerTest, SendVersionNegotiationPacket) { std::unique_ptr<QuicEncryptedPacket> packet( QuicFramer::BuildVersionNegotiationPacket( connection_id_, EmptyQuicConnectionId(), false, false, AllSupportedVersions())); EXPECT_CALL(writer_, WritePacket(_, packet->length(), self_address_.host(), peer_address_, _, _)) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1))); time_wait_list_manager_.SendVersionNegotiationPacket( connection_id_, EmptyQuicConnectionId(), false, false, AllSupportedVersions(), self_address_, peer_address_, std::make_unique<QuicPerPacketContext>()); EXPECT_EQ(0u, time_wait_list_manager_.num_connections()); } TEST_F(QuicTimeWaitListManagerTest, SendIetfVersionNegotiationPacketWithoutLengthPrefix) { std::unique_ptr<QuicEncryptedPacket> packet( QuicFramer::BuildVersionNegotiationPacket( connection_id_, EmptyQuicConnectionId(), true, false, AllSupportedVersions())); EXPECT_CALL(writer_, WritePacket(_, packet->length(), self_address_.host(), peer_address_, _, _)) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1))); time_wait_list_manager_.SendVersionNegotiationPacket( connection_id_, EmptyQuicConnectionId(), true, false, AllSupportedVersions(), self_address_, peer_address_, std::make_unique<QuicPerPacketContext>()); EXPECT_EQ(0u, time_wait_list_manager_.num_connections()); } TEST_F(QuicTimeWaitListManagerTest, SendIetfVersionNegotiationPacket) { std::unique_ptr<QuicEncryptedPacket> packet( QuicFramer::BuildVersionNegotiationPacket( connection_id_, EmptyQuicConnectionId(), true, true, AllSupportedVersions())); EXPECT_CALL(writer_, WritePacket(_, packet->length(), self_address_.host(), peer_address_, _, _)) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1))); time_wait_list_manager_.SendVersionNegotiationPacket( connection_id_, EmptyQuicConnectionId(), true, true, AllSupportedVersions(), self_address_, peer_address_, std::make_unique<QuicPerPacketContext>()); EXPECT_EQ(0u, time_wait_list_manager_.num_connections()); } TEST_F(QuicTimeWaitListManagerTest, SendIetfVersionNegotiationPacketWithClientConnectionId) { std::unique_ptr<QuicEncryptedPacket> packet( QuicFramer::BuildVersionNegotiationPacket( connection_id_, TestConnectionId(0x33), true, true, AllSupportedVersions())); EXPECT_CALL(writer_, WritePacket(_, packet->length(), self_address_.host(), peer_address_, _, _)) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1))); time_wait_list_manager_.SendVersionNegotiationPacket( connection_id_, TestConnectionId(0x33), true, true, AllSupportedVersions(), self_address_, peer_address_, std::make_unique<QuicPerPacketContext>()); EXPECT_EQ(0u, time_wait_list_manager_.num_connections()); } TEST_F(QuicTimeWaitListManagerTest, SendConnectionClose) { const size_t kConnectionCloseLength = 100; EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_)); std::vector<std::unique_ptr<QuicEncryptedPacket>> termination_packets; termination_packets.push_back( std::unique_ptr<QuicEncryptedPacket>(new QuicEncryptedPacket( new char[kConnectionCloseLength], kConnectionCloseLength, true))); AddConnectionId(connection_id_, QuicTimeWaitListManager::SEND_CONNECTION_CLOSE_PACKETS, &termination_packets); EXPECT_CALL(writer_, WritePacket(_, kConnectionCloseLength, self_address_.host(), peer_address_, _, _)) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1))); ProcessPacket(connection_id_); } TEST_F(QuicTimeWaitListManagerTest, SendTwoConnectionCloses) { const size_t kConnectionCloseLength = 100; EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_)); std::vector<std::unique_ptr<QuicEncryptedPacket>> termination_packets; termination_packets.push_back( std::unique_ptr<QuicEncryptedPacket>(new QuicEncryptedPacket( new char[kConnectionCloseLength], kConnectionCloseLength, true))); termination_packets.push_back( std::unique_ptr<QuicEncryptedPacket>(new QuicEncryptedPacket( new char[kConnectionCloseLength], kConnectionCloseLength, true))); AddConnectionId(connection_id_, QuicTimeWaitListManager::SEND_CONNECTION_CLOSE_PACKETS, &termination_packets); EXPECT_CALL(writer_, WritePacket(_, kConnectionCloseLength, self_address_.host(), peer_address_, _, _)) .Times(2) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1))); ProcessPacket(connection_id_); } TEST_F(QuicTimeWaitListManagerTest, SendPublicReset) { EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_)); AddConnectionId(connection_id_, QuicTimeWaitListManager::SEND_STATELESS_RESET); EXPECT_CALL(writer_, WritePacket(_, _, self_address_.host(), peer_address_, _, _)) .With(Args<0, 1>(PublicResetPacketEq(connection_id_))) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 0))); ProcessPacket(connection_id_); } TEST_F(QuicTimeWaitListManagerTest, SendPublicResetWithExponentialBackOff) { EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_)); AddConnectionId(connection_id_, QuicTimeWaitListManager::SEND_STATELESS_RESET); EXPECT_EQ(1u, time_wait_list_manager_.num_connections()); for (int packet_number = 1; packet_number < 101; ++packet_number) { if ((packet_number & (packet_number - 1)) == 0) { EXPECT_CALL(writer_, WritePacket(_, _, _, _, _, _)) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1))); } ProcessPacket(connection_id_); if ((packet_number & (packet_number - 1)) == 0) { EXPECT_TRUE(QuicTimeWaitListManagerPeer::ShouldSendResponse( &time_wait_list_manager_, packet_number)); } else { EXPECT_FALSE(QuicTimeWaitListManagerPeer::ShouldSendResponse( &time_wait_list_manager_, packet_number)); } } } TEST_F(QuicTimeWaitListManagerTest, NoPublicResetForStatelessConnections) { EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_)); AddStatelessConnectionId(connection_id_); EXPECT_CALL(writer_, WritePacket(_, _, self_address_.host(), peer_address_, _, _)) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1))); ProcessPacket(connection_id_); } TEST_F(QuicTimeWaitListManagerTest, CleanUpOldConnectionIds) { const size_t kConnectionIdCount = 100; const size_t kOldConnectionIdCount = 31; for (uint64_t conn_id = 1; conn_id <= kOldConnectionIdCount; ++conn_id) { QuicConnectionId connection_id = TestConnectionId(conn_id); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id)); AddConnectionId(connection_id, QuicTimeWaitListManager::DO_NOTHING); } EXPECT_EQ(kOldConnectionIdCount, time_wait_list_manager_.num_connections()); const QuicTime::Delta time_wait_period = QuicTimeWaitListManagerPeer::time_wait_period(&time_wait_list_manager_); clock_.AdvanceTime(time_wait_period); for (uint64_t conn_id = kOldConnectionIdCount + 1; conn_id <= kConnectionIdCount; ++conn_id) { QuicConnectionId connection_id = TestConnectionId(conn_id); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id)); AddConnectionId(connection_id, QuicTimeWaitListManager::DO_NOTHING); } EXPECT_EQ(kConnectionIdCount, time_wait_list_manager_.num_connections()); QuicTime::Delta offset = QuicTime::Delta::FromMicroseconds(39); clock_.AdvanceTime(offset); QuicTime next_alarm_time = clock_.Now() + time_wait_period - offset; EXPECT_CALL(alarm_factory_, OnAlarmSet(_, next_alarm_time)); time_wait_list_manager_.CleanUpOldConnectionIds(); for (uint64_t conn_id = 1; conn_id <= kConnectionIdCount; ++conn_id) { QuicConnectionId connection_id = TestConnectionId(conn_id); EXPECT_EQ(conn_id > kOldConnectionIdCount, IsConnectionIdInTimeWait(connection_id)) << "kOldConnectionIdCount: " << kOldConnectionIdCount << " connection_id: " << connection_id; } EXPECT_EQ(kConnectionIdCount - kOldConnectionIdCount, time_wait_list_manager_.num_connections()); } TEST_F(QuicTimeWaitListManagerTest, CleanUpOldConnectionIdsForMultipleConnectionIdsPerConnection) { connection_id_ = TestConnectionId(7); const size_t kConnectionCloseLength = 100; EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_)); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(TestConnectionId(8))); std::vector<std::unique_ptr<QuicEncryptedPacket>> termination_packets; termination_packets.push_back( std::unique_ptr<QuicEncryptedPacket>(new QuicEncryptedPacket( new char[kConnectionCloseLength], kConnectionCloseLength, true))); std::vector<QuicConnectionId> active_connection_ids{connection_id_, TestConnectionId(8)}; time_wait_list_manager_.AddConnectionIdToTimeWait( QuicTimeWaitListManager::SEND_CONNECTION_CLOSE_PACKETS, TimeWaitConnectionInfo(true, &termination_packets, active_connection_ids, QuicTime::Delta::Zero())); EXPECT_TRUE( time_wait_list_manager_.IsConnectionIdInTimeWait(TestConnectionId(7))); EXPECT_TRUE( time_wait_list_manager_.IsConnectionIdInTimeWait(TestConnectionId(8))); const QuicTime::Delta time_wait_period = QuicTimeWaitListManagerPeer::time_wait_period(&time_wait_list_manager_); clock_.AdvanceTime(time_wait_period); time_wait_list_manager_.CleanUpOldConnectionIds(); EXPECT_FALSE( time_wait_list_manager_.IsConnectionIdInTimeWait(TestConnectionId(7))); EXPECT_FALSE( time_wait_list_manager_.IsConnectionIdInTimeWait(TestConnectionId(8))); } TEST_F(QuicTimeWaitListManagerTest, SendQueuedPackets) { QuicConnectionId connection_id = TestConnectionId(1); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id)); AddConnectionId(connection_id, QuicTimeWaitListManager::SEND_STATELESS_RESET); std::unique_ptr<QuicEncryptedPacket> packet(ConstructEncryptedPacket( connection_id, EmptyQuicConnectionId(), 234)); EXPECT_CALL(writer_, WritePacket(_, _, self_address_.host(), peer_address_, _, _)) .With(Args<0, 1>(PublicResetPacketEq(connection_id))) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, packet->length()))); ProcessPacket(connection_id); EXPECT_CALL(writer_, WritePacket(_, _, self_address_.host(), peer_address_, _, _)) .With(Args<0, 1>(PublicResetPacketEq(connection_id))) .WillOnce(DoAll(Assign(&writer_is_blocked_, true), Return(WriteResult(WRITE_STATUS_BLOCKED, EAGAIN)))); EXPECT_CALL(visitor_, OnWriteBlocked(&time_wait_list_manager_)); ProcessPacket(connection_id); ProcessPacket(connection_id); QuicConnectionId other_connection_id = TestConnectionId(2); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(other_connection_id)); AddConnectionId(other_connection_id, QuicTimeWaitListManager::SEND_STATELESS_RESET); std::unique_ptr<QuicEncryptedPacket> other_packet(ConstructEncryptedPacket( other_connection_id, EmptyQuicConnectionId(), 23423)); EXPECT_CALL(writer_, WritePacket(_, _, _, _, _, _)).Times(0); EXPECT_CALL(visitor_, OnWriteBlocked(&time_wait_list_manager_)); ProcessPacket(other_connection_id); EXPECT_EQ(2u, time_wait_list_manager_.num_connections()); writer_is_blocked_ = false; EXPECT_CALL(writer_, WritePacket(_, _, self_address_.host(), peer_address_, _, _)) .With(Args<0, 1>(PublicResetPacketEq(connection_id))) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, packet->length()))); EXPECT_CALL(writer_, WritePacket(_, _, self_address_.host(), peer_address_, _, _)) .With(Args<0, 1>(PublicResetPacketEq(other_connection_id))) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, packet->length()))); time_wait_list_manager_.OnBlockedWriterCanWrite(); } TEST_F(QuicTimeWaitListManagerTest, AddConnectionIdTwice) { EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_)); AddConnectionId(connection_id_, QuicTimeWaitListManager::DO_NOTHING); EXPECT_TRUE(IsConnectionIdInTimeWait(connection_id_)); const size_t kConnectionCloseLength = 100; std::vector<std::unique_ptr<QuicEncryptedPacket>> termination_packets; termination_packets.push_back( std::unique_ptr<QuicEncryptedPacket>(new QuicEncryptedPacket( new char[kConnectionCloseLength], kConnectionCloseLength, true))); AddConnectionId(connection_id_, QuicTimeWaitListManager::SEND_TERMINATION_PACKETS, &termination_packets); EXPECT_TRUE(IsConnectionIdInTimeWait(connection_id_)); EXPECT_EQ(1u, time_wait_list_manager_.num_connections()); EXPECT_CALL(writer_, WritePacket(_, kConnectionCloseLength, self_address_.host(), peer_address_, _, _)) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1))); ProcessPacket(connection_id_); const QuicTime::Delta time_wait_period = QuicTimeWaitListManagerPeer::time_wait_period(&time_wait_list_manager_); QuicTime::Delta offset = QuicTime::Delta::FromMicroseconds(39); clock_.AdvanceTime(offset + time_wait_period); QuicTime next_alarm_time = clock_.Now() + time_wait_period; EXPECT_CALL(alarm_factory_, OnAlarmSet(_, next_alarm_time)); time_wait_list_manager_.CleanUpOldConnectionIds(); EXPECT_FALSE(IsConnectionIdInTimeWait(connection_id_)); EXPECT_EQ(0u, time_wait_list_manager_.num_connections()); } TEST_F(QuicTimeWaitListManagerTest, ConnectionIdsOrderedByTime) { const uint64_t conn_id1 = QuicRandom::GetInstance()->RandUint64() % 2; const QuicConnectionId connection_id1 = TestConnectionId(conn_id1); const QuicConnectionId connection_id2 = TestConnectionId(1 - conn_id1); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id1)); AddConnectionId(connection_id1, QuicTimeWaitListManager::DO_NOTHING); clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(10)); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id2)); AddConnectionId(connection_id2, QuicTimeWaitListManager::DO_NOTHING); EXPECT_EQ(2u, time_wait_list_manager_.num_connections()); const QuicTime::Delta time_wait_period = QuicTimeWaitListManagerPeer::time_wait_period(&time_wait_list_manager_); clock_.AdvanceTime(time_wait_period - QuicTime::Delta::FromMicroseconds(9)); EXPECT_CALL(alarm_factory_, OnAlarmSet(_, _)); time_wait_list_manager_.CleanUpOldConnectionIds(); EXPECT_FALSE(IsConnectionIdInTimeWait(connection_id1)); EXPECT_TRUE(IsConnectionIdInTimeWait(connection_id2)); EXPECT_EQ(1u, time_wait_list_manager_.num_connections()); } TEST_F(QuicTimeWaitListManagerTest, MaxConnectionsTest) { SetQuicFlag(quic_time_wait_list_seconds, 10000000000); SetQuicFlag(quic_time_wait_list_max_connections, 5); uint64_t current_conn_id = 0; const int64_t kMaxConnections = GetQuicFlag(quic_time_wait_list_max_connections); for (int64_t i = 0; i < kMaxConnections; ++i) { ++current_conn_id; QuicConnectionId current_connection_id = TestConnectionId(current_conn_id); EXPECT_FALSE(IsConnectionIdInTimeWait(current_connection_id)); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(current_connection_id)); AddConnectionId(current_connection_id, QuicTimeWaitListManager::DO_NOTHING); EXPECT_EQ(current_conn_id, time_wait_list_manager_.num_connections()); EXPECT_TRUE(IsConnectionIdInTimeWait(current_connection_id)); } for (int64_t i = 0; i < kMaxConnections; ++i) { ++current_conn_id; QuicConnectionId current_connection_id = TestConnectionId(current_conn_id); const QuicConnectionId id_to_evict = TestConnectionId(current_conn_id - kMaxConnections); EXPECT_TRUE(IsConnectionIdInTimeWait(id_to_evict)); EXPECT_FALSE(IsConnectionIdInTimeWait(current_connection_id)); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(current_connection_id)); AddConnectionId(current_connection_id, QuicTimeWaitListManager::DO_NOTHING); EXPECT_EQ(static_cast<size_t>(kMaxConnections), time_wait_list_manager_.num_connections()); EXPECT_FALSE(IsConnectionIdInTimeWait(id_to_evict)); EXPECT_TRUE(IsConnectionIdInTimeWait(current_connection_id)); } } TEST_F(QuicTimeWaitListManagerTest, ZeroMaxConnections) { SetQuicFlag(quic_time_wait_list_seconds, 10000000000); SetQuicFlag(quic_time_wait_list_max_connections, 0); uint64_t current_conn_id = 0; for (int64_t i = 0; i < 10; ++i) { ++current_conn_id; QuicConnectionId current_connection_id = TestConnectionId(current_conn_id); EXPECT_FALSE(IsConnectionIdInTimeWait(current_connection_id)); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(current_connection_id)); AddConnectionId(current_connection_id, QuicTimeWaitListManager::DO_NOTHING); EXPECT_EQ(1u, time_wait_list_manager_.num_connections()); EXPECT_TRUE(IsConnectionIdInTimeWait(current_connection_id)); } } TEST_F(QuicTimeWaitListManagerTest, SendStatelessResetInResponseToShortHeaders) { const size_t kConnectionCloseLength = 100; EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_)); std::vector<std::unique_ptr<QuicEncryptedPacket>> termination_packets; termination_packets.push_back( std::unique_ptr<QuicEncryptedPacket>(new QuicEncryptedPacket( new char[kConnectionCloseLength], kConnectionCloseLength, true))); time_wait_list_manager_.AddConnectionIdToTimeWait( QuicTimeWaitListManager::SEND_TERMINATION_PACKETS, TimeWaitConnectionInfo(true, &termination_packets, {connection_id_})); EXPECT_CALL(writer_, WritePacket(_, _, self_address_.host(), peer_address_, _, _)) .With(Args<0, 1>(PublicResetPacketEq(connection_id_))) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 0))); time_wait_list_manager_.ProcessPacket( self_address_, peer_address_, connection_id_, IETF_QUIC_SHORT_HEADER_PACKET, kTestPacketSize, std::make_unique<QuicPerPacketContext>()); } TEST_F(QuicTimeWaitListManagerTest, SendConnectionClosePacketsInResponseToShortHeaders) { const size_t kConnectionCloseLength = 100; EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_)); std::vector<std::unique_ptr<QuicEncryptedPacket>> termination_packets; termination_packets.push_back( std::unique_ptr<QuicEncryptedPacket>(new QuicEncryptedPacket( new char[kConnectionCloseLength], kConnectionCloseLength, true))); time_wait_list_manager_.AddConnectionIdToTimeWait( QuicTimeWaitListManager::SEND_CONNECTION_CLOSE_PACKETS, TimeWaitConnectionInfo(true, &termination_packets, {connection_id_})); EXPECT_CALL(writer_, WritePacket(_, kConnectionCloseLength, self_address_.host(), peer_address_, _, _)) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1))); time_wait_list_manager_.ProcessPacket( self_address_, peer_address_, connection_id_, IETF_QUIC_SHORT_HEADER_PACKET, kTestPacketSize, std::make_unique<QuicPerPacketContext>()); } TEST_F(QuicTimeWaitListManagerTest, SendConnectionClosePacketsForMultipleConnectionIds) { connection_id_ = TestConnectionId(7); const size_t kConnectionCloseLength = 100; EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_)); EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(TestConnectionId(8))); std::vector<std::unique_ptr<QuicEncryptedPacket>> termination_packets; termination_packets.push_back( std::unique_ptr<QuicEncryptedPacket>(new QuicEncryptedPacket( new char[kConnectionCloseLength], kConnectionCloseLength, true))); std::vector<QuicConnectionId> active_connection_ids{connection_id_, TestConnectionId(8)}; time_wait_list_manager_.AddConnectionIdToTimeWait( QuicTimeWaitListManager::SEND_CONNECTION_CLOSE_PACKETS, TimeWaitConnectionInfo(true, &termination_packets, active_connection_ids, QuicTime::Delta::Zero())); EXPECT_CALL(writer_, WritePacket(_, kConnectionCloseLength, self_address_.host(), peer_address_, _, _)) .Times(2) .WillRepeatedly(Return(WriteResult(WRITE_STATUS_OK, 1))); for (auto const& cid : active_connection_ids) { time_wait_list_manager_.ProcessPacket( self_address_, peer_address_, cid, IETF_QUIC_SHORT_HEADER_PACKET, kTestPacketSize, std::make_unique<QuicPerPacketContext>()); } } TEST_F(QuicTimeWaitListManagerTest, DonotCrashOnNullStatelessReset) { time_wait_list_manager_.SendPublicReset( self_address_, peer_address_, TestConnectionId(1), true, QuicFramer::GetMinStatelessResetPacketLength() - 1, nullptr); } TEST_F(QuicTimeWaitListManagerTest, SendOrQueueNullPacket) { QuicTimeWaitListManagerPeer::SendOrQueuePacket(&time_wait_list_manager_, nullptr, nullptr); } TEST_F(QuicTimeWaitListManagerTest, TooManyPendingPackets) { SetQuicFlag(quic_time_wait_list_max_pending_packets, 5); const size_t kNumOfUnProcessablePackets = 2048; EXPECT_CALL(visitor_, OnWriteBlocked(&time_wait_list_manager_)) .Times(testing::AnyNumber()); EXPECT_CALL(writer_, WritePacket(_, _, self_address_.host(), peer_address_, _, _)) .With(Args<0, 1>(PublicResetPacketEq(TestConnectionId(1)))) .WillOnce(DoAll(Assign(&writer_is_blocked_, true), Return(WriteResult(WRITE_STATUS_BLOCKED, EAGAIN)))); for (size_t i = 0; i < kNumOfUnProcessablePackets; ++i) { time_wait_list_manager_.SendPublicReset( self_address_, peer_address_, TestConnectionId(1), true, QuicFramer::GetMinStatelessResetPacketLength() + 1, nullptr); } EXPECT_EQ(5u, QuicTimeWaitListManagerPeer::PendingPacketsQueueSize( &time_wait_list_manager_)); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_time_wait_list_manager.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_time_wait_list_manager_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
1425c71e-adda-4781-a015-51ddbb051313
cpp
google/quiche
quic_crypto_stream
quiche/quic/core/quic_crypto_stream.cc
quiche/quic/core/quic_crypto_stream_test.cc
#include "quiche/quic/core/quic_crypto_stream.h" #include <algorithm> #include <optional> #include <string> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/crypto_handshake.h" #include "quiche/quic/core/frames/quic_crypto_frame.h" #include "quiche/quic/core/quic_connection.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/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { #define ENDPOINT \ (session()->perspective() == Perspective::IS_SERVER ? "Server: " \ : "Client:" \ " ") QuicCryptoStream::QuicCryptoStream(QuicSession* session) : QuicStream( QuicVersionUsesCryptoFrames(session->transport_version()) ? QuicUtils::GetInvalidStreamId(session->transport_version()) : QuicUtils::GetCryptoStreamId(session->transport_version()), session, true, QuicVersionUsesCryptoFrames(session->transport_version()) ? CRYPTO : BIDIRECTIONAL), substreams_{{{this}, {this}, {this}}} { DisableConnectionFlowControlForThisStream(); } QuicCryptoStream::~QuicCryptoStream() {} QuicByteCount QuicCryptoStream::CryptoMessageFramingOverhead( QuicTransportVersion version, QuicConnectionId connection_id) { QUICHE_DCHECK( QuicUtils::IsConnectionIdValidForVersion(connection_id, version)); quiche::QuicheVariableLengthIntegerLength retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1; quiche::QuicheVariableLengthIntegerLength length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2; if (!QuicVersionHasLongHeaderLengths(version)) { retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0; length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0; } return QuicPacketCreator::StreamFramePacketOverhead( version, connection_id.length(), 0, true, true, PACKET_4BYTE_PACKET_NUMBER, retry_token_length_length, length_length, 0); } void QuicCryptoStream::OnCryptoFrame(const QuicCryptoFrame& frame) { QUIC_BUG_IF(quic_bug_12573_1, !QuicVersionUsesCryptoFrames(session()->transport_version())) << "Versions less than 47 shouldn't receive CRYPTO frames"; EncryptionLevel level = session()->connection()->last_decrypted_level(); if (!IsCryptoFrameExpectedForEncryptionLevel(level)) { OnUnrecoverableError( IETF_QUIC_PROTOCOL_VIOLATION, absl::StrCat("CRYPTO_FRAME is unexpectedly received at level ", level)); return; } CryptoSubstream& substream = substreams_[QuicUtils::GetPacketNumberSpace(level)]; substream.sequencer.OnCryptoFrame(frame); EncryptionLevel frame_level = level; if (substream.sequencer.NumBytesBuffered() > BufferSizeLimitForLevel(frame_level)) { OnUnrecoverableError(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, "Too much crypto data received"); } } void QuicCryptoStream::OnStreamFrame(const QuicStreamFrame& frame) { if (QuicVersionUsesCryptoFrames(session()->transport_version())) { QUIC_PEER_BUG(quic_peer_bug_12573_2) << "Crypto data received in stream frame instead of crypto frame"; OnUnrecoverableError(QUIC_INVALID_STREAM_DATA, "Unexpected stream frame"); } QuicStream::OnStreamFrame(frame); } void QuicCryptoStream::OnDataAvailable() { EncryptionLevel level = session()->connection()->last_decrypted_level(); if (!QuicVersionUsesCryptoFrames(session()->transport_version())) { OnDataAvailableInSequencer(sequencer(), level); return; } OnDataAvailableInSequencer( &substreams_[QuicUtils::GetPacketNumberSpace(level)].sequencer, level); } void QuicCryptoStream::OnDataAvailableInSequencer( QuicStreamSequencer* sequencer, EncryptionLevel level) { struct iovec iov; while (sequencer->GetReadableRegion(&iov)) { absl::string_view data(static_cast<char*>(iov.iov_base), iov.iov_len); if (!crypto_message_parser()->ProcessInput(data, level)) { OnUnrecoverableError(crypto_message_parser()->error(), crypto_message_parser()->error_detail()); return; } sequencer->MarkConsumed(iov.iov_len); if (one_rtt_keys_available() && crypto_message_parser()->InputBytesRemaining() == 0) { sequencer->ReleaseBufferIfEmpty(); } } } void QuicCryptoStream::WriteCryptoData(EncryptionLevel level, absl::string_view data) { if (!QuicVersionUsesCryptoFrames(session()->transport_version())) { WriteOrBufferDataAtLevel(data, false, level, nullptr); return; } if (data.empty()) { QUIC_BUG(quic_bug_10322_1) << "Empty crypto data being written"; return; } const bool had_buffered_data = HasBufferedCryptoFrames(); QuicStreamSendBuffer* send_buffer = &substreams_[QuicUtils::GetPacketNumberSpace(level)].send_buffer; QuicStreamOffset offset = send_buffer->stream_offset(); if (GetQuicFlag(quic_bounded_crypto_send_buffer)) { QUIC_BUG_IF(quic_crypto_stream_offset_lt_bytes_written, offset < send_buffer->stream_bytes_written()); uint64_t current_buffer_size = offset - std::min(offset, send_buffer->stream_bytes_written()); if (current_buffer_size > 0) { QUIC_CODE_COUNT(quic_received_crypto_data_with_non_empty_send_buffer); if (BufferSizeLimitForLevel(level) < (current_buffer_size + data.length())) { QUIC_BUG(quic_crypto_send_buffer_overflow) << absl::StrCat("Too much data for crypto send buffer with level: ", EncryptionLevelToString(level), ", current_buffer_size: ", current_buffer_size, ", data length: ", data.length(), ", SNI: ", crypto_negotiated_params().sni); OnUnrecoverableError(QUIC_INTERNAL_ERROR, "Too much data for crypto send buffer"); return; } } } send_buffer->SaveStreamData(data); if (kMaxStreamLength - offset < data.length()) { QUIC_BUG(quic_bug_10322_2) << "Writing too much crypto handshake data"; OnUnrecoverableError(QUIC_INTERNAL_ERROR, "Writing too much crypto handshake data"); return; } if (had_buffered_data) { return; } size_t bytes_consumed = stream_delegate()->SendCryptoData( level, data.length(), offset, NOT_RETRANSMISSION); send_buffer->OnStreamDataConsumed(bytes_consumed); } size_t QuicCryptoStream::BufferSizeLimitForLevel(EncryptionLevel) const { return GetQuicFlag(quic_max_buffered_crypto_bytes); } bool QuicCryptoStream::OnCryptoFrameAcked(const QuicCryptoFrame& frame, QuicTime::Delta ) { QuicByteCount newly_acked_length = 0; if (!substreams_[QuicUtils::GetPacketNumberSpace(frame.level)] .send_buffer.OnStreamDataAcked(frame.offset, frame.data_length, &newly_acked_length)) { OnUnrecoverableError(QUIC_INTERNAL_ERROR, "Trying to ack unsent crypto data."); return false; } return newly_acked_length > 0; } void QuicCryptoStream::OnStreamReset(const QuicRstStreamFrame& ) { stream_delegate()->OnStreamError(QUIC_INVALID_STREAM_ID, "Attempt to reset crypto stream"); } void QuicCryptoStream::NeuterUnencryptedStreamData() { NeuterStreamDataOfEncryptionLevel(ENCRYPTION_INITIAL); } void QuicCryptoStream::NeuterStreamDataOfEncryptionLevel( EncryptionLevel level) { if (!QuicVersionUsesCryptoFrames(session()->transport_version())) { for (const auto& interval : bytes_consumed_[level]) { QuicByteCount newly_acked_length = 0; send_buffer().OnStreamDataAcked( interval.min(), interval.max() - interval.min(), &newly_acked_length); } return; } QuicStreamSendBuffer* send_buffer = &substreams_[QuicUtils::GetPacketNumberSpace(level)].send_buffer; QuicIntervalSet<QuicStreamOffset> to_ack = send_buffer->bytes_acked(); to_ack.Complement(0, send_buffer->stream_offset()); for (const auto& interval : to_ack) { QuicByteCount newly_acked_length = 0; send_buffer->OnStreamDataAcked( interval.min(), interval.max() - interval.min(), &newly_acked_length); } } void QuicCryptoStream::OnStreamDataConsumed(QuicByteCount bytes_consumed) { if (QuicVersionUsesCryptoFrames(session()->transport_version())) { QUIC_BUG(quic_bug_10322_3) << "Stream data consumed when CRYPTO frames should be in use"; } if (bytes_consumed > 0) { bytes_consumed_[session()->connection()->encryption_level()].Add( stream_bytes_written(), stream_bytes_written() + bytes_consumed); } QuicStream::OnStreamDataConsumed(bytes_consumed); } bool QuicCryptoStream::HasPendingCryptoRetransmission() const { if (!QuicVersionUsesCryptoFrames(session()->transport_version())) { return false; } for (const auto& substream : substreams_) { if (substream.send_buffer.HasPendingRetransmission()) { return true; } } return false; } void QuicCryptoStream::WritePendingCryptoRetransmission() { QUIC_BUG_IF(quic_bug_12573_3, !QuicVersionUsesCryptoFrames(session()->transport_version())) << "Versions less than 47 don't write CRYPTO frames"; for (uint8_t i = INITIAL_DATA; i <= APPLICATION_DATA; ++i) { auto packet_number_space = static_cast<PacketNumberSpace>(i); QuicStreamSendBuffer* send_buffer = &substreams_[packet_number_space].send_buffer; while (send_buffer->HasPendingRetransmission()) { auto pending = send_buffer->NextPendingRetransmission(); size_t bytes_consumed = stream_delegate()->SendCryptoData( GetEncryptionLevelToSendCryptoDataOfSpace(packet_number_space), pending.length, pending.offset, HANDSHAKE_RETRANSMISSION); send_buffer->OnStreamDataRetransmitted(pending.offset, bytes_consumed); if (bytes_consumed < pending.length) { return; } } } } void QuicCryptoStream::WritePendingRetransmission() { while (HasPendingRetransmission()) { StreamPendingRetransmission pending = send_buffer().NextPendingRetransmission(); QuicIntervalSet<QuicStreamOffset> retransmission( pending.offset, pending.offset + pending.length); EncryptionLevel retransmission_encryption_level = ENCRYPTION_INITIAL; for (size_t i = 0; i < NUM_ENCRYPTION_LEVELS; ++i) { if (retransmission.Intersects(bytes_consumed_[i])) { retransmission_encryption_level = static_cast<EncryptionLevel>(i); retransmission.Intersection(bytes_consumed_[i]); break; } } pending.offset = retransmission.begin()->min(); pending.length = retransmission.begin()->max() - retransmission.begin()->min(); QuicConsumedData consumed = RetransmitStreamDataAtLevel( pending.offset, pending.length, retransmission_encryption_level, HANDSHAKE_RETRANSMISSION); if (consumed.bytes_consumed < pending.length) { break; } } } bool QuicCryptoStream::RetransmitStreamData(QuicStreamOffset offset, QuicByteCount data_length, bool , TransmissionType type) { QUICHE_DCHECK(type == HANDSHAKE_RETRANSMISSION || type == PTO_RETRANSMISSION); QuicIntervalSet<QuicStreamOffset> retransmission(offset, offset + data_length); EncryptionLevel send_encryption_level = ENCRYPTION_INITIAL; for (size_t i = 0; i < NUM_ENCRYPTION_LEVELS; ++i) { if (retransmission.Intersects(bytes_consumed_[i])) { send_encryption_level = static_cast<EncryptionLevel>(i); break; } } retransmission.Difference(bytes_acked()); for (const auto& interval : retransmission) { QuicStreamOffset retransmission_offset = interval.min(); QuicByteCount retransmission_length = interval.max() - interval.min(); QuicConsumedData consumed = RetransmitStreamDataAtLevel( retransmission_offset, retransmission_length, send_encryption_level, type); if (consumed.bytes_consumed < retransmission_length) { return false; } } return true; } QuicConsumedData QuicCryptoStream::RetransmitStreamDataAtLevel( QuicStreamOffset retransmission_offset, QuicByteCount retransmission_length, EncryptionLevel encryption_level, TransmissionType type) { QUICHE_DCHECK(type == HANDSHAKE_RETRANSMISSION || type == PTO_RETRANSMISSION); const auto consumed = stream_delegate()->WritevData( id(), retransmission_length, retransmission_offset, NO_FIN, type, encryption_level); QUIC_DVLOG(1) << ENDPOINT << "stream " << id() << " is forced to retransmit stream data [" << retransmission_offset << ", " << retransmission_offset + retransmission_length << "), with encryption level: " << encryption_level << ", consumed: " << consumed; OnStreamFrameRetransmitted(retransmission_offset, consumed.bytes_consumed, consumed.fin_consumed); return consumed; } uint64_t QuicCryptoStream::crypto_bytes_read() const { if (!QuicVersionUsesCryptoFrames(session()->transport_version())) { return stream_bytes_read(); } uint64_t bytes_read = 0; for (const CryptoSubstream& substream : substreams_) { bytes_read += substream.sequencer.NumBytesConsumed(); } return bytes_read; } uint64_t QuicCryptoStream::BytesReadOnLevel(EncryptionLevel level) const { return substreams_[QuicUtils::GetPacketNumberSpace(level)] .sequencer.NumBytesConsumed(); } uint64_t QuicCryptoStream::BytesSentOnLevel(EncryptionLevel level) const { return substreams_[QuicUtils::GetPacketNumberSpace(level)] .send_buffer.stream_bytes_written(); } bool QuicCryptoStream::WriteCryptoFrame(EncryptionLevel level, QuicStreamOffset offset, QuicByteCount data_length, QuicDataWriter* writer) { QUIC_BUG_IF(quic_bug_12573_4, !QuicVersionUsesCryptoFrames(session()->transport_version())) << "Versions less than 47 don't write CRYPTO frames (2)"; return substreams_[QuicUtils::GetPacketNumberSpace(level)] .send_buffer.WriteStreamData(offset, data_length, writer); } void QuicCryptoStream::OnCryptoFrameLost(QuicCryptoFrame* crypto_frame) { QUIC_BUG_IF(quic_bug_12573_5, !QuicVersionUsesCryptoFrames(session()->transport_version())) << "Versions less than 47 don't lose CRYPTO frames"; substreams_[QuicUtils::GetPacketNumberSpace(crypto_frame->level)] .send_buffer.OnStreamDataLost(crypto_frame->offset, crypto_frame->data_length); } bool QuicCryptoStream::RetransmitData(QuicCryptoFrame* crypto_frame, TransmissionType type) { QUIC_BUG_IF(quic_bug_12573_6, !QuicVersionUsesCryptoFrames(session()->transport_version())) << "Versions less than 47 don't retransmit CRYPTO frames"; QuicIntervalSet<QuicStreamOffset> retransmission( crypto_frame->offset, crypto_frame->offset + crypto_frame->data_length); QuicStreamSendBuffer* send_buffer = &substreams_[QuicUtils::GetPacketNumberSpace(crypto_frame->level)] .send_buffer; retransmission.Difference(send_buffer->bytes_acked()); if (retransmission.Empty()) { return true; } for (const auto& interval : retransmission) { size_t retransmission_offset = interval.min(); size_t retransmission_length = interval.max() - interval.min(); EncryptionLevel retransmission_encryption_level = GetEncryptionLevelToSendCryptoDataOfSpace( QuicUtils::GetPacketNumberSpace(crypto_frame->level)); size_t bytes_consumed = stream_delegate()->SendCryptoData( retransmission_encryption_level, retransmission_length, retransmission_offset, type); send_buffer->OnStreamDataRetransmitted(retransmission_offset, bytes_consumed); if (bytes_consumed < retransmission_length) { return false; } } return true; } void QuicCryptoStream::WriteBufferedCryptoFrames() { QUIC_BUG_IF(quic_bug_12573_7, !QuicVersionUsesCryptoFrames(session()->transport_version())) << "Versions less than 47 don't use CRYPTO frames"; for (uint8_t i = INITIAL_DATA; i <= APPLICATION_DATA; ++i) { auto packet_number_space = static_cast<PacketNumberSpace>(i); QuicStreamSendBuffer* send_buffer = &substreams_[packet_number_space].send_buffer; const size_t data_length = send_buffer->stream_offset() - send_buffer->stream_bytes_written(); if (data_length == 0) { continue; } size_t bytes_consumed = stream_delegate()->SendCryptoData( GetEncryptionLevelToSendCryptoDataOfSpace(packet_number_space), data_length, send_buffer->stream_bytes_written(), NOT_RETRANSMISSION); send_buffer->OnStreamDataConsumed(bytes_consumed); if (bytes_consumed < data_length) { break; } } } bool QuicCryptoStream::HasBufferedCryptoFrames() const { QUIC_BUG_IF(quic_bug_12573_8, !QuicVersionUsesCryptoFrames(session()->transport_version())) << "Versions less than 47 don't use CRYPTO frames"; for (const CryptoSubstream& substream : substreams_) { const QuicStreamSendBuffer& send_buffer = substream.send_buffer; QUICHE_DCHECK_GE(send_buffer.stream_offset(), send_buffer.stream_bytes_written()); if (send_buffer.stream_offset() > send_buffer.stream_bytes_written()) { return true; } } return false; } bool QuicCryptoStream::IsFrameOutstanding(EncryptionLevel level, size_t offset, size_t length) const { if (!QuicVersionUsesCryptoFrames(session()->transport_version())) { return false; } return substreams_[QuicUtils::GetPacketNumberSpace(level)] .send_buffer.IsStreamDataOutstanding(offset, length); } bool QuicCryptoStream::IsWaitingForAcks() const { if (!QuicVersionUsesCryptoFrames(session()->transport_version())) { return QuicStream::IsWaitingForAcks(); } for (const CryptoSubstream& substream : substreams_) { if (substream.send_buffer.stream_bytes_outstanding()) { return true; } } return false; } QuicCryptoStream::CryptoSubstream::CryptoSubstream( QuicCryptoStream* crypto_stream) : sequencer(crypto_stream), send_buffer(crypto_stream->session() ->connection() ->helper() ->GetStreamSendBufferAllocator()) {} #undef ENDPOINT }
#include "quiche/quic/core/quic_crypto_stream.h" #include <cstdint> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "quiche/quic/core/crypto/crypto_handshake.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/quic_error_codes.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_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/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_stream_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" using testing::_; using testing::InSequence; using testing::Invoke; using testing::InvokeWithoutArgs; using testing::Return; namespace quic { namespace test { namespace { class MockQuicCryptoStream : public QuicCryptoStream, public QuicCryptoHandshaker { public: explicit MockQuicCryptoStream(QuicSession* session) : QuicCryptoStream(session), QuicCryptoHandshaker(this, session), params_(new QuicCryptoNegotiatedParameters) {} MockQuicCryptoStream(const MockQuicCryptoStream&) = delete; MockQuicCryptoStream& operator=(const MockQuicCryptoStream&) = delete; void OnHandshakeMessage(const CryptoHandshakeMessage& message) override { messages_.push_back(message); } std::vector<CryptoHandshakeMessage>* messages() { return &messages_; } ssl_early_data_reason_t EarlyDataReason() const override { return ssl_early_data_unknown; } bool encryption_established() const override { return false; } bool one_rtt_keys_available() const override { return false; } 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 {} HandshakeState GetHandshakeState() const override { return 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; } 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 QuicCryptoStream::session() ->GetEncryptionLevelToSendApplicationData(); default: QUICHE_DCHECK(false); return NUM_ENCRYPTION_LEVELS; } } private: quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> params_; std::vector<CryptoHandshakeMessage> messages_; }; class QuicCryptoStreamTest : public QuicTest { public: QuicCryptoStreamTest() : connection_(new MockQuicConnection(&helper_, &alarm_factory_, Perspective::IS_CLIENT)), session_(connection_, false) { EXPECT_CALL(*static_cast<MockPacketWriter*>(connection_->writer()), WritePacket(_, _, _, _, _, _)) .WillRepeatedly(Return(WriteResult(WRITE_STATUS_OK, 0))); stream_ = new MockQuicCryptoStream(&session_); session_.SetCryptoStream(stream_); session_.Initialize(); message_.set_tag(kSHLO); message_.SetStringPiece(1, "abc"); message_.SetStringPiece(2, "def"); ConstructHandshakeMessage(); } QuicCryptoStreamTest(const QuicCryptoStreamTest&) = delete; QuicCryptoStreamTest& operator=(const QuicCryptoStreamTest&) = delete; void ConstructHandshakeMessage() { CryptoFramer framer; message_data_ = framer.ConstructHandshakeMessage(message_); } protected: MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; MockQuicConnection* connection_; MockQuicSpdySession session_; MockQuicCryptoStream* stream_; CryptoHandshakeMessage message_; std::unique_ptr<QuicData> message_data_; }; TEST_F(QuicCryptoStreamTest, NotInitiallyConected) { EXPECT_FALSE(stream_->encryption_established()); EXPECT_FALSE(stream_->one_rtt_keys_available()); } TEST_F(QuicCryptoStreamTest, ProcessRawData) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { stream_->OnStreamFrame(QuicStreamFrame( QuicUtils::GetCryptoStreamId(connection_->transport_version()), false, 0, message_data_->AsStringPiece())); } else { stream_->OnCryptoFrame(QuicCryptoFrame(ENCRYPTION_INITIAL, 0, message_data_->AsStringPiece())); } ASSERT_EQ(1u, stream_->messages()->size()); const CryptoHandshakeMessage& message = (*stream_->messages())[0]; EXPECT_EQ(kSHLO, message.tag()); EXPECT_EQ(2u, message.tag_value_map().size()); EXPECT_EQ("abc", crypto_test_utils::GetValueForTag(message, 1)); EXPECT_EQ("def", crypto_test_utils::GetValueForTag(message, 2)); } TEST_F(QuicCryptoStreamTest, ProcessBadData) { std::string bad(message_data_->data(), message_data_->length()); const int kFirstTagIndex = sizeof(uint32_t) + sizeof(uint16_t) + sizeof(uint16_t); EXPECT_EQ(1, bad[kFirstTagIndex]); bad[kFirstTagIndex] = 0x7F; EXPECT_CALL(*connection_, CloseConnection(QUIC_CRYPTO_TAGS_OUT_OF_ORDER, testing::_, testing::_)); if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { stream_->OnStreamFrame(QuicStreamFrame( QuicUtils::GetCryptoStreamId(connection_->transport_version()), false, 0, bad)); } else { stream_->OnCryptoFrame( QuicCryptoFrame(ENCRYPTION_INITIAL, 0, bad)); } } TEST_F(QuicCryptoStreamTest, NoConnectionLevelFlowControl) { EXPECT_FALSE( QuicStreamPeer::StreamContributesToConnectionFlowControl(stream_)); } TEST_F(QuicCryptoStreamTest, RetransmitCryptoData) { if (QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } InSequence s; EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1350, 'a'); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 1350, 0, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); stream_->WriteOrBufferData(data, false, nullptr); connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level()); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 1350, 1350, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); stream_->WriteOrBufferData(data, false, nullptr); connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); stream_->OnStreamFrameLost(0, 1000, false); EXPECT_TRUE(stream_->HasPendingRetransmission()); stream_->OnStreamFrameLost(1200, 800, false); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 1000, 0, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 150, 1200, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 650, 1350, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); stream_->OnCanWrite(); EXPECT_FALSE(stream_->HasPendingRetransmission()); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); } TEST_F(QuicCryptoStreamTest, RetransmitCryptoDataInCryptoFrames) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0); InSequence s; EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1350, 'a'); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_INITIAL, data); std::unique_ptr<NullEncrypter> encrypter = std::make_unique<NullEncrypter>(Perspective::IS_CLIENT); connection_->SetEncrypter(ENCRYPTION_ZERO_RTT, std::move(encrypter)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level()); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 1350, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_ZERO_RTT, data); QuicCryptoFrame lost_frame = QuicCryptoFrame(ENCRYPTION_ZERO_RTT, 0, 650); stream_->OnCryptoFrameLost(&lost_frame); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 650, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WritePendingCryptoRetransmission(); connection_->SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(Perspective::IS_CLIENT)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); lost_frame = QuicCryptoFrame(ENCRYPTION_INITIAL, 0, 1000); stream_->OnCryptoFrameLost(&lost_frame); EXPECT_TRUE(stream_->HasPendingCryptoRetransmission()); lost_frame = QuicCryptoFrame(ENCRYPTION_INITIAL, 1200, 150); stream_->OnCryptoFrameLost(&lost_frame); lost_frame = QuicCryptoFrame(ENCRYPTION_ZERO_RTT, 0, 650); stream_->OnCryptoFrameLost(&lost_frame); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1000, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 150, 1200)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_FORWARD_SECURE, 650, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WritePendingCryptoRetransmission(); EXPECT_FALSE(stream_->HasPendingCryptoRetransmission()); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); } TEST_F(QuicCryptoStreamTest, RetransmitEncryptionHandshakeLevelCryptoFrames) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0); InSequence s; EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1000, 'a'); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1000, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_INITIAL, data); std::unique_ptr<NullEncrypter> encrypter = std::make_unique<NullEncrypter>(Perspective::IS_CLIENT); connection_->SetEncrypter(ENCRYPTION_HANDSHAKE, std::move(encrypter)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE); EXPECT_EQ(ENCRYPTION_HANDSHAKE, connection_->encryption_level()); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_HANDSHAKE, 1000, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_HANDSHAKE, data); connection_->SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(Perspective::IS_CLIENT)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); QuicCryptoFrame lost_frame(ENCRYPTION_HANDSHAKE, 0, 200); stream_->OnCryptoFrameLost(&lost_frame); EXPECT_TRUE(stream_->HasPendingCryptoRetransmission()); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_HANDSHAKE, 200, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WritePendingCryptoRetransmission(); EXPECT_FALSE(stream_->HasPendingCryptoRetransmission()); } TEST_F(QuicCryptoStreamTest, NeuterUnencryptedStreamData) { if (QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1350, 'a'); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 1350, 0, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); stream_->WriteOrBufferData(data, false, nullptr); connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level()); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 1350, 1350, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); stream_->WriteOrBufferData(data, false, nullptr); stream_->OnStreamFrameLost(0, 1350, false); EXPECT_TRUE(stream_->HasPendingRetransmission()); stream_->NeuterUnencryptedStreamData(); EXPECT_FALSE(stream_->HasPendingRetransmission()); stream_->OnStreamFrameLost(0, 1350, false); EXPECT_FALSE(stream_->HasPendingRetransmission()); stream_->OnStreamFrameLost(1350, 650, false); EXPECT_TRUE(stream_->HasPendingRetransmission()); stream_->NeuterUnencryptedStreamData(); EXPECT_TRUE(stream_->HasPendingRetransmission()); } TEST_F(QuicCryptoStreamTest, NeuterUnencryptedCryptoData) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1350, 'a'); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_INITIAL, data); connection_->SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<NullEncrypter>(Perspective::IS_CLIENT)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); std::unique_ptr<NullEncrypter> encrypter = std::make_unique<NullEncrypter>(Perspective::IS_CLIENT); connection_->SetEncrypter(ENCRYPTION_ZERO_RTT, std::move(encrypter)); EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level()); EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 1350, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_ZERO_RTT, data); QuicCryptoFrame lost_frame(ENCRYPTION_INITIAL, 0, 1350); stream_->OnCryptoFrameLost(&lost_frame); EXPECT_TRUE(stream_->HasPendingCryptoRetransmission()); stream_->NeuterUnencryptedStreamData(); EXPECT_FALSE(stream_->HasPendingCryptoRetransmission()); stream_->OnCryptoFrameLost(&lost_frame); EXPECT_FALSE(stream_->HasPendingCryptoRetransmission()); lost_frame = QuicCryptoFrame(ENCRYPTION_ZERO_RTT, 0, 650); stream_->OnCryptoFrameLost(&lost_frame); EXPECT_TRUE(stream_->HasPendingCryptoRetransmission()); stream_->NeuterUnencryptedStreamData(); EXPECT_TRUE(stream_->HasPendingCryptoRetransmission()); } TEST_F(QuicCryptoStreamTest, RetransmitStreamData) { if (QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } InSequence s; EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1350, 'a'); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 1350, 0, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); stream_->WriteOrBufferData(data, false, nullptr); connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level()); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 1350, 1350, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); stream_->WriteOrBufferData(data, false, nullptr); connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); QuicByteCount newly_acked_length = 0; stream_->OnStreamFrameAcked(2000, 500, false, QuicTime::Delta::Zero(), QuicTime::Zero(), &newly_acked_length); EXPECT_EQ(500u, newly_acked_length); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 650, 1350, _, _, _)) .WillOnce(InvokeWithoutArgs([this]() { return session_.ConsumeData( QuicUtils::GetCryptoStreamId(connection_->transport_version()), 150, 1350, NO_FIN, HANDSHAKE_RETRANSMISSION, std::nullopt); })); EXPECT_FALSE(stream_->RetransmitStreamData(1350, 1350, false, HANDSHAKE_RETRANSMISSION)); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 650, 1350, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 200, 2500, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); EXPECT_TRUE(stream_->RetransmitStreamData(1350, 1350, false, HANDSHAKE_RETRANSMISSION)); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); EXPECT_CALL(session_, WritevData(_, _, _, _, _, _)).Times(0); EXPECT_TRUE( stream_->RetransmitStreamData(0, 0, false, HANDSHAKE_RETRANSMISSION)); } TEST_F(QuicCryptoStreamTest, RetransmitStreamDataWithCryptoFrames) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } InSequence s; EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1350, 'a'); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_INITIAL, data); std::unique_ptr<NullEncrypter> encrypter = std::make_unique<NullEncrypter>(Perspective::IS_CLIENT); connection_->SetEncrypter(ENCRYPTION_ZERO_RTT, std::move(encrypter)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level()); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 1350, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_ZERO_RTT, data); connection_->SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(Perspective::IS_CLIENT)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); QuicCryptoFrame acked_frame(ENCRYPTION_ZERO_RTT, 650, 500); EXPECT_TRUE( stream_->OnCryptoFrameAcked(acked_frame, QuicTime::Delta::Zero())); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_FORWARD_SECURE, 150, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); QuicCryptoFrame frame_to_retransmit(ENCRYPTION_ZERO_RTT, 0, 150); stream_->RetransmitData(&frame_to_retransmit, HANDSHAKE_RETRANSMISSION); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_FORWARD_SECURE, 650, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_FORWARD_SECURE, 200, 1150)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); frame_to_retransmit = QuicCryptoFrame(ENCRYPTION_ZERO_RTT, 0, 1350); stream_->RetransmitData(&frame_to_retransmit, HANDSHAKE_RETRANSMISSION); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, connection_->encryption_level()); EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0); QuicCryptoFrame empty_frame(ENCRYPTION_FORWARD_SECURE, 0, 0); stream_->RetransmitData(&empty_frame, HANDSHAKE_RETRANSMISSION); } TEST_F(QuicCryptoStreamTest, HasUnackedCryptoData) { if (QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } std::string data(1350, 'a'); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 1350, 0, _, _, _)) .WillOnce(testing::Return(QuicConsumedData(0, false))); stream_->WriteOrBufferData(data, false, nullptr); EXPECT_FALSE(stream_->IsWaitingForAcks()); EXPECT_TRUE(session_.HasUnackedCryptoData()); EXPECT_CALL( session_, WritevData(QuicUtils::GetCryptoStreamId(connection_->transport_version()), 1350, 0, _, _, _)) .WillOnce(Invoke(&session_, &MockQuicSpdySession::ConsumeData)); stream_->OnCanWrite(); EXPECT_TRUE(stream_->IsWaitingForAcks()); EXPECT_TRUE(session_.HasUnackedCryptoData()); } TEST_F(QuicCryptoStreamTest, HasUnackedCryptoDataWithCryptoFrames) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1350, 'a'); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_INITIAL, data); EXPECT_TRUE(stream_->IsWaitingForAcks()); EXPECT_TRUE(session_.HasUnackedCryptoData()); } TEST_F(QuicCryptoStreamTest, CryptoMessageFramingOverhead) { for (const ParsedQuicVersion& version : AllSupportedVersionsWithQuicCrypto()) { SCOPED_TRACE(version); QuicByteCount expected_overhead = 52; if (version.HasLongHeaderLengths()) { expected_overhead += 3; } if (version.HasLengthPrefixedConnectionIds()) { expected_overhead += 1; } EXPECT_EQ(expected_overhead, QuicCryptoStream::CryptoMessageFramingOverhead( version.transport_version, TestConnectionId())); } } TEST_F(QuicCryptoStreamTest, WriteCryptoDataExceedsSendBufferLimit) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); int32_t buffer_limit = GetQuicFlag(quic_max_buffered_crypto_bytes); EXPECT_FALSE(stream_->HasBufferedCryptoFrames()); int32_t over_limit = buffer_limit + 1; EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, over_limit, 0)) .WillOnce(Return(over_limit)); std::string large_data(over_limit, 'a'); stream_->WriteCryptoData(ENCRYPTION_INITIAL, large_data); EXPECT_FALSE(stream_->HasBufferedCryptoFrames()); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, buffer_limit, over_limit)) .WillOnce(Return(1)); std::string data(buffer_limit, 'a'); stream_->WriteCryptoData(ENCRYPTION_INITIAL, data); EXPECT_TRUE(stream_->HasBufferedCryptoFrames()); EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0); std::string data2(1, 'a'); stream_->WriteCryptoData(ENCRYPTION_INITIAL, data2); EXPECT_TRUE(stream_->HasBufferedCryptoFrames()); if (GetQuicFlag(quic_bounded_crypto_send_buffer)) { EXPECT_CALL(*connection_, CloseConnection(QUIC_INTERNAL_ERROR, _, _)); EXPECT_QUIC_BUG( stream_->WriteCryptoData(ENCRYPTION_INITIAL, data2), "Too much data for crypto send buffer with level: ENCRYPTION_INITIAL, " "current_buffer_size: 16384, data length: 1"); } } TEST_F(QuicCryptoStreamTest, WriteBufferedCryptoFrames) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } EXPECT_FALSE(stream_->HasBufferedCryptoFrames()); InSequence s; EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1350, 'a'); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0)) .WillOnce(Return(1000)); stream_->WriteCryptoData(ENCRYPTION_INITIAL, data); EXPECT_TRUE(stream_->HasBufferedCryptoFrames()); EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0); connection_->SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<NullEncrypter>(Perspective::IS_CLIENT)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); stream_->WriteCryptoData(ENCRYPTION_ZERO_RTT, data); EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level()); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 350, 1000)) .WillOnce(Return(350)); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 1350, 0)) .WillOnce(Return(1000)); stream_->WriteBufferedCryptoFrames(); EXPECT_TRUE(stream_->HasBufferedCryptoFrames()); EXPECT_EQ(ENCRYPTION_ZERO_RTT, connection_->encryption_level()); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_ZERO_RTT, 350, 1000)) .WillOnce(Return(350)); stream_->WriteBufferedCryptoFrames(); EXPECT_FALSE(stream_->HasBufferedCryptoFrames()); } TEST_F(QuicCryptoStreamTest, LimitBufferedCryptoData) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } EXPECT_CALL(*connection_, CloseConnection(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, _, _)); std::string large_frame(2 * GetQuicFlag(quic_max_buffered_crypto_bytes), 'a'); QuicStreamOffset offset = 1; stream_->OnCryptoFrame( QuicCryptoFrame(ENCRYPTION_INITIAL, offset, large_frame)); } TEST_F(QuicCryptoStreamTest, CloseConnectionWithZeroRttCryptoFrame) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } EXPECT_CALL(*connection_, CloseConnection(IETF_QUIC_PROTOCOL_VIOLATION, _, _)); test::QuicConnectionPeer::SetLastDecryptedLevel(connection_, ENCRYPTION_ZERO_RTT); QuicStreamOffset offset = 1; stream_->OnCryptoFrame(QuicCryptoFrame(ENCRYPTION_ZERO_RTT, offset, "data")); } TEST_F(QuicCryptoStreamTest, RetransmitCryptoFramesAndPartialWrite) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0); InSequence s; EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); std::string data(1350, 'a'); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WriteCryptoData(ENCRYPTION_INITIAL, data); QuicCryptoFrame lost_frame(ENCRYPTION_INITIAL, 0, 1000); stream_->OnCryptoFrameLost(&lost_frame); EXPECT_TRUE(stream_->HasPendingCryptoRetransmission()); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1000, 0)) .WillOnce(Return(0)); stream_->WritePendingCryptoRetransmission(); EXPECT_TRUE(stream_->HasPendingCryptoRetransmission()); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1000, 0)) .WillOnce(Invoke(connection_, &MockQuicConnection::QuicConnection_SendCryptoData)); stream_->WritePendingCryptoRetransmission(); EXPECT_FALSE(stream_->HasPendingCryptoRetransmission()); } TEST_F(QuicCryptoStreamTest, EmptyCryptoFrame) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); QuicCryptoFrame empty_crypto_frame(ENCRYPTION_INITIAL, 0, nullptr, 0); stream_->OnCryptoFrame(empty_crypto_frame); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_crypto_stream.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_crypto_stream_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
2be3d92f-9c0f-4d2a-8f13-adbaa9b977ab
cpp
google/quiche
quic_session
quiche/quic/core/quic_session.cc
quiche/quic/core/quic_session_test.cc
#include "quiche/quic/core/quic_session.h" #include <algorithm> #include <cstdint> #include <limits> #include <memory> #include <optional> #include <ostream> #include <sstream> #include <string> #include <utility> #include <vector> #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/frames/quic_ack_frequency_frame.h" #include "quiche/quic/core/frames/quic_reset_stream_at_frame.h" #include "quiche/quic/core/frames/quic_window_update_frame.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_connection_context.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_flow_controller.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/core/quic_write_blocked_list.h" #include "quiche/quic/core/web_transport_write_blocked_list.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_server_stats.h" #include "quiche/quic/platform/api/quic_stack_trace.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_callbacks.h" #include "quiche/common/quiche_text_utils.h" namespace quic { namespace { class ClosedStreamsCleanUpDelegate : public QuicAlarm::Delegate { public: explicit ClosedStreamsCleanUpDelegate(QuicSession* session) : session_(session) {} ClosedStreamsCleanUpDelegate(const ClosedStreamsCleanUpDelegate&) = delete; ClosedStreamsCleanUpDelegate& operator=(const ClosedStreamsCleanUpDelegate&) = delete; QuicConnectionContext* GetConnectionContext() override { return (session_->connection() == nullptr) ? nullptr : session_->connection()->context(); } void OnAlarm() override { session_->CleanUpClosedStreams(); } private: QuicSession* session_; }; class StreamCountResetAlarmDelegate : public QuicAlarm::Delegate { public: explicit StreamCountResetAlarmDelegate(QuicSession* session) : session_(session) {} StreamCountResetAlarmDelegate(const StreamCountResetAlarmDelegate&) = delete; StreamCountResetAlarmDelegate& operator=( const StreamCountResetAlarmDelegate&) = delete; QuicConnectionContext* GetConnectionContext() override { return (session_->connection() == nullptr) ? nullptr : session_->connection()->context(); } void OnAlarm() override { session_->OnStreamCountReset(); } private: QuicSession* session_; }; std::unique_ptr<QuicWriteBlockedListInterface> CreateWriteBlockedList( QuicPriorityType priority_type) { switch (priority_type) { case QuicPriorityType::kHttp: return std::make_unique<QuicWriteBlockedList>(); case QuicPriorityType::kWebTransport: return std::make_unique<WebTransportWriteBlockedList>(); } QUICHE_NOTREACHED(); return nullptr; } } #define ENDPOINT \ (perspective() == Perspective::IS_SERVER ? "Server: " : "Client: ") QuicSession::QuicSession( QuicConnection* connection, Visitor* owner, const QuicConfig& config, const ParsedQuicVersionVector& supported_versions, QuicStreamCount num_expected_unidirectional_static_streams) : QuicSession(connection, owner, config, supported_versions, num_expected_unidirectional_static_streams, nullptr) {} QuicSession::QuicSession( QuicConnection* connection, Visitor* owner, const QuicConfig& config, const ParsedQuicVersionVector& supported_versions, QuicStreamCount num_expected_unidirectional_static_streams, std::unique_ptr<QuicDatagramQueue::Observer> datagram_observer, QuicPriorityType priority_type) : connection_(connection), perspective_(connection->perspective()), visitor_(owner), write_blocked_streams_(CreateWriteBlockedList(priority_type)), config_(config), stream_id_manager_(perspective(), connection->transport_version(), kDefaultMaxStreamsPerConnection, config_.GetMaxBidirectionalStreamsToSend()), ietf_streamid_manager_(perspective(), connection->version(), this, 0, num_expected_unidirectional_static_streams, config_.GetMaxBidirectionalStreamsToSend(), config_.GetMaxUnidirectionalStreamsToSend() + num_expected_unidirectional_static_streams), num_draining_streams_(0), num_outgoing_draining_streams_(0), num_static_streams_(0), num_zombie_streams_(0), flow_controller_( this, QuicUtils::GetInvalidStreamId(connection->transport_version()), true, connection->version().AllowsLowFlowControlLimits() ? 0 : kMinimumFlowControlSendWindow, config_.GetInitialSessionFlowControlWindowToSend(), kSessionReceiveWindowLimit, perspective() == Perspective::IS_SERVER, nullptr), currently_writing_stream_id_(0), transport_goaway_sent_(false), transport_goaway_received_(false), control_frame_manager_(this), last_message_id_(0), datagram_queue_(this, std::move(datagram_observer)), closed_streams_clean_up_alarm_(nullptr), supported_versions_(supported_versions), is_configured_(false), was_zero_rtt_rejected_(false), liveness_testing_in_progress_(false), stream_count_reset_alarm_( absl::WrapUnique<QuicAlarm>(connection->alarm_factory()->CreateAlarm( new StreamCountResetAlarmDelegate(this)))), priority_type_(priority_type) { closed_streams_clean_up_alarm_ = absl::WrapUnique<QuicAlarm>(connection_->alarm_factory()->CreateAlarm( new ClosedStreamsCleanUpDelegate(this))); if (VersionHasIetfQuicFrames(transport_version())) { config_.SetMaxUnidirectionalStreamsToSend( config_.GetMaxUnidirectionalStreamsToSend() + num_expected_unidirectional_static_streams); } } void QuicSession::Initialize() { connection_->set_visitor(this); connection_->SetSessionNotifier(this); connection_->SetDataProducer(this); connection_->SetUnackedMapInitialCapacity(); if (perspective_ == Perspective::IS_CLIENT) { if (config_.HasClientSentConnectionOption(kCHP1, perspective_)) { config_.SetGoogleHandshakeMessageToSend( std::string(kDefaultMaxPacketSize, '0')); } else if (config_.HasClientSentConnectionOption(kCHP2, perspective_)) { config_.SetGoogleHandshakeMessageToSend( std::string(kDefaultMaxPacketSize * 2, '0')); } } connection_->SetFromConfig(config_); if (perspective_ == Perspective::IS_CLIENT) { if (config_.HasClientRequestedIndependentOption(kAFFE, perspective_) && version().HasIetfQuicFrames()) { connection_->set_can_receive_ack_frequency_frame(); config_.SetMinAckDelayMs(kDefaultMinAckDelayTimeMs); } } if (perspective() == Perspective::IS_SERVER && connection_->version().handshake_protocol == PROTOCOL_TLS1_3) { config_.SetStatelessResetTokenToSend(GetStatelessResetToken()); } connection_->CreateConnectionIdManager(); if (perspective() == Perspective::IS_SERVER) { connection_->OnSuccessfulVersionNegotiation(); } if (QuicVersionUsesCryptoFrames(transport_version())) { return; } QUICHE_DCHECK_EQ(QuicUtils::GetCryptoStreamId(transport_version()), GetMutableCryptoStream()->id()); } QuicSession::~QuicSession() { if (closed_streams_clean_up_alarm_ != nullptr) { closed_streams_clean_up_alarm_->PermanentCancel(); } if (stream_count_reset_alarm_ != nullptr) { stream_count_reset_alarm_->PermanentCancel(); } } PendingStream* QuicSession::PendingStreamOnStreamFrame( const QuicStreamFrame& frame) { QUICHE_DCHECK(VersionUsesHttp3(transport_version())); QuicStreamId stream_id = frame.stream_id; PendingStream* pending = GetOrCreatePendingStream(stream_id); if (!pending) { if (frame.fin) { QuicStreamOffset final_byte_offset = frame.offset + frame.data_length; OnFinalByteOffsetReceived(stream_id, final_byte_offset); } return nullptr; } pending->OnStreamFrame(frame); if (!connection()->connected()) { return nullptr; } return pending; } bool QuicSession::MaybeProcessPendingStream(PendingStream* pending) { QUICHE_DCHECK(pending != nullptr && connection()->connected()); if (ExceedsPerLoopStreamLimit()) { QUIC_DLOG(INFO) << "Skip processing pending stream " << pending->id() << " because it exceeds per loop limit."; QUIC_CODE_COUNT_N(quic_pending_stream, 1, 3); return false; } QuicStreamId stream_id = pending->id(); std::optional<QuicResetStreamError> stop_sending_error_code = pending->GetStopSendingErrorCode(); QUIC_DLOG(INFO) << "Process pending stream " << pending->id(); QuicStream* stream = ProcessPendingStream(pending); if (stream != nullptr) { QUICHE_DCHECK(IsClosedStream(stream_id) || IsOpenStream(stream_id)) << "Stream " << stream_id << " not created"; if (!stream->pending_duration().IsZero()) { QUIC_SERVER_HISTOGRAM_TIMES("QuicStream.PendingDurationUs", stream->pending_duration().ToMicroseconds(), 0, 1000 * 100, 20, "Time a stream has been pending at server."); ++connection()->mutable_stats().num_total_pending_streams; } pending_stream_map_.erase(stream_id); if (stop_sending_error_code) { stream->OnStopSending(*stop_sending_error_code); if (!connection()->connected()) { return false; } } stream->OnStreamCreatedFromPendingStream(); return connection()->connected(); } if (pending->sequencer()->IsClosed()) { ClosePendingStream(stream_id); } return connection()->connected(); } void QuicSession::PendingStreamOnWindowUpdateFrame( const QuicWindowUpdateFrame& frame) { QUICHE_DCHECK(VersionUsesHttp3(transport_version())); PendingStream* pending = GetOrCreatePendingStream(frame.stream_id); if (pending) { pending->OnWindowUpdateFrame(frame); } } void QuicSession::PendingStreamOnStopSendingFrame( const QuicStopSendingFrame& frame) { QUICHE_DCHECK(VersionUsesHttp3(transport_version())); PendingStream* pending = GetOrCreatePendingStream(frame.stream_id); if (pending) { pending->OnStopSending(frame.error()); } } void QuicSession::OnStreamFrame(const QuicStreamFrame& frame) { QuicStreamId stream_id = frame.stream_id; if (stream_id == QuicUtils::GetInvalidStreamId(transport_version())) { connection()->CloseConnection( QUIC_INVALID_STREAM_ID, "Received data for an invalid stream", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } if (ShouldProcessFrameByPendingStream(STREAM_FRAME, stream_id)) { PendingStream* pending = PendingStreamOnStreamFrame(frame); if (pending != nullptr && IsEncryptionEstablished()) { MaybeProcessPendingStream(pending); } return; } QuicStream* stream = GetOrCreateStream(stream_id); if (!stream) { if (frame.fin) { QuicStreamOffset final_byte_offset = frame.offset + frame.data_length; OnFinalByteOffsetReceived(stream_id, final_byte_offset); } return; } stream->OnStreamFrame(frame); } void QuicSession::OnCryptoFrame(const QuicCryptoFrame& frame) { GetMutableCryptoStream()->OnCryptoFrame(frame); } void QuicSession::OnStopSendingFrame(const QuicStopSendingFrame& frame) { QUICHE_DCHECK(VersionHasIetfQuicFrames(transport_version())); QUICHE_DCHECK(QuicVersionUsesCryptoFrames(transport_version())); QuicStreamId stream_id = frame.stream_id; if (stream_id == QuicUtils::GetInvalidStreamId(transport_version())) { QUIC_DVLOG(1) << ENDPOINT << "Received STOP_SENDING with invalid stream_id: " << stream_id << " Closing connection"; connection()->CloseConnection( QUIC_INVALID_STREAM_ID, "Received STOP_SENDING for an invalid stream", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } if (QuicUtils::GetStreamType(stream_id, perspective(), IsIncomingStream(stream_id), version()) == READ_UNIDIRECTIONAL) { QUIC_DVLOG(1) << ENDPOINT << "Received STOP_SENDING for a read-only stream_id: " << stream_id << "."; connection()->CloseConnection( QUIC_INVALID_STREAM_ID, "Received STOP_SENDING for a read-only stream", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } if (visitor_) { visitor_->OnStopSendingReceived(frame); } if (ShouldProcessFrameByPendingStream(STOP_SENDING_FRAME, stream_id)) { PendingStreamOnStopSendingFrame(frame); return; } QuicStream* stream = nullptr; if (enable_stop_sending_for_zombie_streams_) { stream = GetStream(stream_id); if (stream != nullptr) { if (stream->IsZombie()) { QUIC_RELOADABLE_FLAG_COUNT_N( quic_deliver_stop_sending_to_zombie_streams, 1, 3); } else { QUIC_RELOADABLE_FLAG_COUNT_N( quic_deliver_stop_sending_to_zombie_streams, 2, 3); } stream->OnStopSending(frame.error()); return; } } stream = GetOrCreateStream(stream_id); if (!stream) { return; } stream->OnStopSending(frame.error()); } void QuicSession::OnPacketDecrypted(EncryptionLevel level) { GetMutableCryptoStream()->OnPacketDecrypted(level); if (liveness_testing_in_progress_) { liveness_testing_in_progress_ = false; OnCanCreateNewOutgoingStream(false); } } void QuicSession::OnOneRttPacketAcknowledged() { GetMutableCryptoStream()->OnOneRttPacketAcknowledged(); } void QuicSession::OnHandshakePacketSent() { GetMutableCryptoStream()->OnHandshakePacketSent(); } std::unique_ptr<QuicDecrypter> QuicSession::AdvanceKeysAndCreateCurrentOneRttDecrypter() { return GetMutableCryptoStream()->AdvanceKeysAndCreateCurrentOneRttDecrypter(); } std::unique_ptr<QuicEncrypter> QuicSession::CreateCurrentOneRttEncrypter() { return GetMutableCryptoStream()->CreateCurrentOneRttEncrypter(); } void QuicSession::PendingStreamOnRstStream(const QuicRstStreamFrame& frame) { QUICHE_DCHECK(VersionUsesHttp3(transport_version())); QuicStreamId stream_id = frame.stream_id; PendingStream* pending = GetOrCreatePendingStream(stream_id); if (!pending) { HandleRstOnValidNonexistentStream(frame); return; } pending->OnRstStreamFrame(frame); ClosePendingStream(stream_id); } void QuicSession::PendingStreamOnResetStreamAt( const QuicResetStreamAtFrame& frame) { QUICHE_DCHECK(VersionUsesHttp3(transport_version())); QuicStreamId stream_id = frame.stream_id; PendingStream* pending = GetOrCreatePendingStream(stream_id); if (!pending) { HandleRstOnValidNonexistentStream(frame.ToRstStream()); return; } pending->OnResetStreamAtFrame(frame); } void QuicSession::OnRstStream(const QuicRstStreamFrame& frame) { QuicStreamId stream_id = frame.stream_id; if (stream_id == QuicUtils::GetInvalidStreamId(transport_version())) { connection()->CloseConnection( QUIC_INVALID_STREAM_ID, "Received data for an invalid stream", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } if (VersionHasIetfQuicFrames(transport_version()) && QuicUtils::GetStreamType(stream_id, perspective(), IsIncomingStream(stream_id), version()) == WRITE_UNIDIRECTIONAL) { connection()->CloseConnection( QUIC_INVALID_STREAM_ID, "Received RESET_STREAM for a write-only stream", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } if (visitor_) { visitor_->OnRstStreamReceived(frame); } if (ShouldProcessFrameByPendingStream(RST_STREAM_FRAME, stream_id)) { PendingStreamOnRstStream(frame); return; } QuicStream* stream = GetOrCreateStream(stream_id); if (!stream) { HandleRstOnValidNonexistentStream(frame); return; } stream->OnStreamReset(frame); } void QuicSession::OnResetStreamAt(const QuicResetStreamAtFrame& frame) { QUICHE_DCHECK(VersionHasIetfQuicFrames(transport_version())); QuicStreamId stream_id = frame.stream_id; if (stream_id == QuicUtils::GetInvalidStreamId(transport_version())) { connection()->CloseConnection( QUIC_INVALID_STREAM_ID, "Received data for an invalid stream", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } if (VersionHasIetfQuicFrames(transport_version()) && QuicUtils::GetStreamType(stream_id, perspective(), IsIncomingStream(stream_id), version()) == WRITE_UNIDIRECTIONAL) { connection()->CloseConnection( QUIC_INVALID_STREAM_ID, "Received RESET_STREAM for a write-only stream", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } if (ShouldProcessFrameByPendingStream(RESET_STREAM_AT_FRAME, stream_id)) { PendingStreamOnResetStreamAt(frame); return; } QuicStream* stream = GetOrCreateStream(stream_id); if (!stream) { HandleRstOnValidNonexistentStream(frame.ToRstStream()); return; } stream->OnResetStreamAtFrame(frame); } void QuicSession::OnGoAway(const QuicGoAwayFrame& ) { QUIC_BUG_IF(quic_bug_12435_1, version().UsesHttp3()) << "gQUIC GOAWAY received on version " << version(); transport_goaway_received_ = true; } void QuicSession::OnMessageReceived(absl::string_view message) { QUIC_DVLOG(1) << ENDPOINT << "Received message of length " << message.length(); QUIC_DVLOG(2) << ENDPOINT << "Contents of message of length " << message.length() << ":" << std::endl << quiche::QuicheTextUtils::HexDump(message); } void QuicSession::OnHandshakeDoneReceived() { QUIC_DVLOG(1) << ENDPOINT << "OnHandshakeDoneReceived"; GetMutableCryptoStream()->OnHandshakeDoneReceived(); } void QuicSession::OnNewTokenReceived(absl::string_view token) { QUICHE_DCHECK_EQ(perspective_, Perspective::IS_CLIENT); GetMutableCryptoStream()->OnNewTokenReceived(token); } void QuicSession::RecordConnectionCloseAtServer(QuicErrorCode error, ConnectionCloseSource source) { if (error != QUIC_NO_ERROR) { if (source == ConnectionCloseSource::FROM_SELF) { QUIC_SERVER_HISTOGRAM_ENUM( "quic_server_connection_close_errors", error, QUIC_LAST_ERROR, "QuicErrorCode for server-closed connections."); } else { QUIC_SERVER_HISTOGRAM_ENUM( "quic_client_connection_close_errors", error, QUIC_LAST_ERROR, "QuicErrorCode for client-closed connections."); } } } void QuicSession::OnConnectionClosed(const QuicConnectionCloseFrame& frame, ConnectionCloseSource source) { QUICHE_DCHECK(!connection_->connected()); if (perspective() == Perspective::IS_SERVER) { RecordConnectionCloseAtServer(frame.quic_error_code, source); } if (on_closed_frame_.quic_error_code == QUIC_NO_ERROR) { on_closed_frame_ = frame; source_ = source; } GetMutableCryptoStream()->OnConnectionClosed(frame, source); PerformActionOnActiveStreams([this, frame, source](QuicStream* stream) { QuicStreamId id = stream->id(); stream->OnConnectionClosed(frame, source); auto it = stream_map_.find(id); if (it != stream_map_.end()) { QUIC_BUG_IF(quic_bug_12435_2, !it->second->IsZombie()) << ENDPOINT << "Non-zombie stream " << id << " failed to close under OnConnectionClosed"; } return true; }); closed_streams_clean_up_alarm_->Cancel(); stream_count_reset_alarm_->Cancel(); if (visitor_) { visitor_->OnConnectionClosed(connection_->GetOneActiveServerConnectionId(), frame.quic_error_code, frame.error_details, source); } } void QuicSession::OnWriteBlocked() { if (!connection_->connected()) { return; } if (visitor_) { visitor_->OnWriteBlocked(connection_); } } void QuicSession::OnSuccessfulVersionNegotiation( const ParsedQuicVersion& ) {} void QuicSession::OnPacketReceived(const QuicSocketAddress& , const QuicSocketAddress& peer_address, bool is_connectivity_probe) { QUICHE_DCHECK(!connection_->ignore_gquic_probing()); if (is_connectivity_probe && perspective() == Perspective::IS_SERVER) { connection_->SendConnectivityProbingPacket(nullptr, peer_address); } } void QuicSession::OnPathDegrading() { if (visitor_) { visitor_->OnPathDegrading(); } } void QuicSession::OnForwardProgressMadeAfterPathDegrading() {} bool QuicSession::AllowSelfAddressChange() const { return false; } void QuicSession::OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) { QuicStreamId stream_id = frame.stream_id; if (stream_id == QuicUtils::GetInvalidStreamId(transport_version())) { QUIC_DVLOG(1) << ENDPOINT << "Received connection level flow control window " "update with max data: " << frame.max_data; flow_controller_.UpdateSendWindowOffset(frame.max_data); return; } if (VersionHasIetfQuicFrames(transport_version()) && QuicUtils::GetStreamType(stream_id, perspective(), IsIncomingStream(stream_id), version()) == READ_UNIDIRECTIONAL) { connection()->CloseConnection( QUIC_WINDOW_UPDATE_RECEIVED_ON_READ_UNIDIRECTIONAL_STREAM, "WindowUpdateFrame received on READ_UNIDIRECTIONAL stream.", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } if (ShouldProcessFrameByPendingStream(WINDOW_UPDATE_FRAME, stream_id)) { PendingStreamOnWindowUpdateFrame(frame); return; } QuicStream* stream = GetOrCreateStream(stream_id); if (stream != nullptr) { stream->OnWindowUpdateFrame(frame); } } void QuicSession::OnBlockedFrame(const QuicBlockedFrame& frame) { QUIC_DLOG(INFO) << ENDPOINT << "Received BLOCKED frame with stream id: " << frame.stream_id << ", offset: " << frame.offset; } bool QuicSession::CheckStreamNotBusyLooping(QuicStream* stream, uint64_t previous_bytes_written, bool previous_fin_sent) { if ( !stream->write_side_closed() && !flow_controller_.IsBlocked() && previous_bytes_written == stream->stream_bytes_written() && previous_fin_sent == stream->fin_sent()) { stream->set_busy_counter(stream->busy_counter() + 1); QUIC_DVLOG(1) << ENDPOINT << "Suspected busy loop on stream id " << stream->id() << " stream_bytes_written " << stream->stream_bytes_written() << " fin " << stream->fin_sent() << " count " << stream->busy_counter(); if (stream->busy_counter() > 20) { QUIC_LOG(ERROR) << ENDPOINT << "Detected busy loop on stream id " << stream->id() << " stream_bytes_written " << stream->stream_bytes_written() << " fin " << stream->fin_sent(); return false; } } else { stream->set_busy_counter(0); } return true; } bool QuicSession::CheckStreamWriteBlocked(QuicStream* stream) const { if (!stream->write_side_closed() && stream->HasBufferedData() && !stream->IsFlowControlBlocked() && !write_blocked_streams_->IsStreamBlocked(stream->id())) { QUIC_DLOG(ERROR) << ENDPOINT << "stream " << stream->id() << " has buffered " << stream->BufferedDataBytes() << " bytes, and is not flow control blocked, " "but it is not in the write block list."; return false; } return true; } void QuicSession::OnCanWrite() { if (connection_->framer().is_processing_packet()) { QUIC_BUG(session_write_mid_packet_processing) << ENDPOINT << "Try to write mid packet processing."; return; } if (!RetransmitLostData()) { QUIC_DVLOG(1) << ENDPOINT << "Cannot finish retransmitting lost data, connection is " "write blocked."; return; } size_t num_writes = flow_controller_.IsBlocked() ? write_blocked_streams_->NumBlockedSpecialStreams() : write_blocked_streams_->NumBlockedStreams(); if (num_writes == 0 && !control_frame_manager_.WillingToWrite() && datagram_queue_.empty() && (!QuicVersionUsesCryptoFrames(transport_version()) || !GetCryptoStream()->HasBufferedCryptoFrames())) { return; } QuicConnection::ScopedPacketFlusher flusher(connection_); if (QuicVersionUsesCryptoFrames(transport_version())) { QuicCryptoStream* crypto_stream = GetMutableCryptoStream(); if (crypto_stream->HasBufferedCryptoFrames()) { crypto_stream->WriteBufferedCryptoFrames(); } if ((GetQuicReloadableFlag( quic_no_write_control_frame_upon_connection_close) && !connection_->connected()) || crypto_stream->HasBufferedCryptoFrames()) { if (!connection_->connected()) { QUIC_RELOADABLE_FLAG_COUNT( quic_no_write_control_frame_upon_connection_close); } return; } } if (control_frame_manager_.WillingToWrite()) { control_frame_manager_.OnCanWrite(); } if (version().UsesTls() && GetHandshakeState() != HANDSHAKE_CONFIRMED && connection_->in_probe_time_out()) { QUIC_CODE_COUNT(quic_donot_pto_stream_data_before_handshake_confirmed); return; } if (!datagram_queue_.empty()) { size_t written = datagram_queue_.SendDatagrams(); QUIC_DVLOG(1) << ENDPOINT << "Sent " << written << " datagrams"; if (!datagram_queue_.empty()) { return; } } std::vector<QuicStreamId> last_writing_stream_ids; for (size_t i = 0; i < num_writes; ++i) { if (!(write_blocked_streams_->HasWriteBlockedSpecialStream() || write_blocked_streams_->HasWriteBlockedDataStreams())) { QUIC_BUG(quic_bug_10866_1) << "WriteBlockedStream is missing, num_writes: " << num_writes << ", finished_writes: " << i << ", connected: " << connection_->connected() << ", connection level flow control blocked: " << flow_controller_.IsBlocked(); for (QuicStreamId id : last_writing_stream_ids) { QUIC_LOG(WARNING) << "last_writing_stream_id: " << id; } connection_->CloseConnection(QUIC_INTERNAL_ERROR, "WriteBlockedStream is missing", ConnectionCloseBehavior::SILENT_CLOSE); return; } if (!CanWriteStreamData()) { return; } currently_writing_stream_id_ = write_blocked_streams_->PopFront(); last_writing_stream_ids.push_back(currently_writing_stream_id_); QUIC_DVLOG(1) << ENDPOINT << "Removing stream " << currently_writing_stream_id_ << " from write-blocked list"; QuicStream* stream = GetOrCreateStream(currently_writing_stream_id_); if (stream != nullptr && !stream->IsFlowControlBlocked()) { uint64_t previous_bytes_written = stream->stream_bytes_written(); bool previous_fin_sent = stream->fin_sent(); QUIC_DVLOG(1) << ENDPOINT << "stream " << stream->id() << " bytes_written " << previous_bytes_written << " fin " << previous_fin_sent; stream->OnCanWrite(); QUICHE_DCHECK(CheckStreamWriteBlocked(stream)); QUICHE_DCHECK(CheckStreamNotBusyLooping(stream, previous_bytes_written, previous_fin_sent)); } currently_writing_stream_id_ = 0; } } bool QuicSession::WillingAndAbleToWrite() const { if (QuicVersionUsesCryptoFrames(transport_version())) { if (HasPendingHandshake()) { return true; } if (!IsEncryptionEstablished()) { return false; } } if (control_frame_manager_.WillingToWrite() || !streams_with_pending_retransmission_.empty()) { return true; } if (flow_controller_.IsBlocked()) { if (VersionUsesHttp3(transport_version())) { return false; } return write_blocked_streams_->HasWriteBlockedSpecialStream(); } return write_blocked_streams_->HasWriteBlockedSpecialStream() || write_blocked_streams_->HasWriteBlockedDataStreams(); } std::string QuicSession::GetStreamsInfoForLogging() const { std::string info = absl::StrCat( "num_active_streams: ", GetNumActiveStreams(), ", num_pending_streams: ", pending_streams_size(), ", num_outgoing_draining_streams: ", num_outgoing_draining_streams(), " "); size_t i = 5; for (const auto& it : stream_map_) { if (it.second->is_static()) { continue; } const QuicTime::Delta delay = connection_->clock()->ApproximateNow() - it.second->creation_time(); absl::StrAppend( &info, "{", it.second->id(), ":", delay.ToDebuggingValue(), ";", it.second->stream_bytes_written(), ",", it.second->fin_sent(), ",", it.second->HasBufferedData(), ",", it.second->fin_buffered(), ";", it.second->stream_bytes_read(), ",", it.second->fin_received(), "}"); --i; if (i == 0) { break; } } return info; } bool QuicSession::HasPendingHandshake() const { if (QuicVersionUsesCryptoFrames(transport_version())) { return GetCryptoStream()->HasPendingCryptoRetransmission() || GetCryptoStream()->HasBufferedCryptoFrames(); } return streams_with_pending_retransmission_.contains( QuicUtils::GetCryptoStreamId(transport_version())) || write_blocked_streams_->IsStreamBlocked( QuicUtils::GetCryptoStreamId(transport_version())); } void QuicSession::ProcessUdpPacket(const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, const QuicReceivedPacket& packet) { QuicConnectionContextSwitcher cs(connection_->context()); connection_->ProcessUdpPacket(self_address, peer_address, packet); } std::string QuicSession::on_closed_frame_string() const { std::stringstream ss; ss << on_closed_frame_; if (source_.has_value()) { ss << " " << ConnectionCloseSourceToString(*source_); } return ss.str(); } QuicConsumedData QuicSession::WritevData(QuicStreamId id, size_t write_length, QuicStreamOffset offset, StreamSendingState state, TransmissionType type, EncryptionLevel level) { QUIC_BUG_IF(session writevdata when disconnected, !connection()->connected()) << ENDPOINT << "Try to write stream data when connection is closed: " << on_closed_frame_string(); if (!IsEncryptionEstablished() && !QuicUtils::IsCryptoStreamId(transport_version(), id)) { if (was_zero_rtt_rejected_ && !OneRttKeysAvailable()) { QUICHE_DCHECK(version().UsesTls() && perspective() == Perspective::IS_CLIENT); QUIC_DLOG(INFO) << ENDPOINT << "Suppress the write while 0-RTT gets rejected and " "1-RTT keys are not available. Version: " << ParsedQuicVersionToString(version()); } else if (version().UsesTls() || perspective() == Perspective::IS_SERVER) { QUIC_BUG(quic_bug_10866_2) << ENDPOINT << "Try to send data of stream " << id << " before encryption is established. Version: " << ParsedQuicVersionToString(version()); } else { QUIC_DLOG(INFO) << ENDPOINT << "Try to send data of stream " << id << " before encryption is established."; } return QuicConsumedData(0, false); } SetTransmissionType(type); QuicConnection::ScopedEncryptionLevelContext context(connection(), level); QuicConsumedData data = connection_->SendStreamData(id, write_length, offset, state); if (type == NOT_RETRANSMISSION) { write_blocked_streams_->UpdateBytesForStream(id, data.bytes_consumed); } return data; } size_t QuicSession::SendCryptoData(EncryptionLevel level, size_t write_length, QuicStreamOffset offset, TransmissionType type) { QUICHE_DCHECK(QuicVersionUsesCryptoFrames(transport_version())); if (!connection()->framer().HasEncrypterOfEncryptionLevel(level)) { const std::string error_details = absl::StrCat( "Try to send crypto data with missing keys of encryption level: ", EncryptionLevelToString(level)); QUIC_BUG(quic_bug_10866_3) << ENDPOINT << error_details; connection()->CloseConnection( QUIC_MISSING_WRITE_KEYS, error_details, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return 0; } SetTransmissionType(type); QuicConnection::ScopedEncryptionLevelContext context(connection(), level); const auto bytes_consumed = connection_->SendCryptoData(level, write_length, offset); return bytes_consumed; } void QuicSession::OnControlFrameManagerError(QuicErrorCode error_code, std::string error_details) { connection_->CloseConnection( error_code, error_details, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); } bool QuicSession::WriteControlFrame(const QuicFrame& frame, TransmissionType type) { QUIC_BUG_IF(quic_bug_12435_11, !connection()->connected()) << ENDPOINT << absl::StrCat("Try to write control frame: ", QuicFrameToString(frame), " when connection is closed: ") << on_closed_frame_string(); if (!IsEncryptionEstablished()) { return false; } SetTransmissionType(type); QuicConnection::ScopedEncryptionLevelContext context( connection(), GetEncryptionLevelToSendApplicationData()); return connection_->SendControlFrame(frame); } void QuicSession::ResetStream(QuicStreamId id, QuicRstStreamErrorCode error) { QuicStream* stream = GetStream(id); if (stream != nullptr && stream->is_static()) { connection()->CloseConnection( QUIC_INVALID_STREAM_ID, "Try to reset a static stream", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } if (stream != nullptr) { stream->Reset(error); return; } QuicConnection::ScopedPacketFlusher flusher(connection()); MaybeSendStopSendingFrame(id, QuicResetStreamError::FromInternal(error)); MaybeSendRstStreamFrame(id, QuicResetStreamError::FromInternal(error), 0); } void QuicSession::MaybeSendRstStreamFrame(QuicStreamId id, QuicResetStreamError error, QuicStreamOffset bytes_written) { if (!connection()->connected()) { return; } if (!VersionHasIetfQuicFrames(transport_version()) || QuicUtils::GetStreamType(id, perspective(), IsIncomingStream(id), version()) != READ_UNIDIRECTIONAL) { control_frame_manager_.WriteOrBufferRstStream(id, error, bytes_written); } connection_->OnStreamReset(id, error.internal_code()); } void QuicSession::MaybeSendStopSendingFrame(QuicStreamId id, QuicResetStreamError error) { if (!connection()->connected()) { return; } if (VersionHasIetfQuicFrames(transport_version()) && QuicUtils::GetStreamType(id, perspective(), IsIncomingStream(id), version()) != WRITE_UNIDIRECTIONAL) { control_frame_manager_.WriteOrBufferStopSending(error, id); } } void QuicSession::SendGoAway(QuicErrorCode error_code, const std::string& reason) { QUICHE_DCHECK(!VersionHasIetfQuicFrames(transport_version())); if (!IsEncryptionEstablished()) { QUIC_CODE_COUNT(quic_goaway_before_encryption_established); connection_->CloseConnection( error_code, reason, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } if (transport_goaway_sent_) { return; } transport_goaway_sent_ = true; QUICHE_DCHECK_EQ(perspective(), Perspective::IS_SERVER); control_frame_manager_.WriteOrBufferGoAway( error_code, QuicUtils::GetMaxClientInitiatedBidirectionalStreamId( transport_version()), reason); } void QuicSession::SendBlocked(QuicStreamId id, QuicStreamOffset byte_offset) { control_frame_manager_.WriteOrBufferBlocked(id, byte_offset); } void QuicSession::SendWindowUpdate(QuicStreamId id, QuicStreamOffset byte_offset) { control_frame_manager_.WriteOrBufferWindowUpdate(id, byte_offset); } void QuicSession::OnStreamError(QuicErrorCode error_code, std::string error_details) { connection_->CloseConnection( error_code, error_details, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); } void QuicSession::OnStreamError(QuicErrorCode error_code, QuicIetfTransportErrorCodes ietf_error, std::string error_details) { connection_->CloseConnection( error_code, ietf_error, error_details, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); } bool QuicSession::CanSendMaxStreams() { return control_frame_manager_.NumBufferedMaxStreams() < 2; } void QuicSession::SendMaxStreams(QuicStreamCount stream_count, bool unidirectional) { if (!is_configured_) { QUIC_BUG(quic_bug_10866_5) << "Try to send max streams before config negotiated."; return; } control_frame_manager_.WriteOrBufferMaxStreams(stream_count, unidirectional); } void QuicSession::InsertLocallyClosedStreamsHighestOffset( const QuicStreamId id, QuicStreamOffset offset) { locally_closed_streams_highest_offset_[id] = offset; } void QuicSession::OnStreamClosed(QuicStreamId stream_id) { QUIC_DVLOG(1) << ENDPOINT << "Closing stream: " << stream_id; StreamMap::iterator it = stream_map_.find(stream_id); if (it == stream_map_.end()) { QUIC_BUG(quic_bug_10866_6) << ENDPOINT << "Stream is already closed: " << stream_id; return; } QuicStream* stream = it->second.get(); StreamType type = stream->type(); const bool stream_waiting_for_acks = stream->IsWaitingForAcks(); if (stream_waiting_for_acks) { ++num_zombie_streams_; } else { closed_streams_.push_back(std::move(it->second)); stream_map_.erase(it); streams_with_pending_retransmission_.erase(stream_id); if (!closed_streams_clean_up_alarm_->IsSet()) { closed_streams_clean_up_alarm_->Set( connection_->clock()->ApproximateNow()); } connection_->QuicBugIfHasPendingFrames(stream_id); } if (!stream->HasReceivedFinalOffset()) { QUICHE_DCHECK(!stream->was_draining()); InsertLocallyClosedStreamsHighestOffset( stream_id, stream->highest_received_byte_offset()); return; } const bool stream_was_draining = stream->was_draining(); QUIC_DVLOG_IF(1, stream_was_draining) << ENDPOINT << "Stream " << stream_id << " was draining"; if (stream_was_draining) { QUIC_BUG_IF(quic_bug_12435_4, num_draining_streams_ == 0); --num_draining_streams_; if (!IsIncomingStream(stream_id)) { QUIC_BUG_IF(quic_bug_12435_5, num_outgoing_draining_streams_ == 0); --num_outgoing_draining_streams_; } return; } if (!VersionHasIetfQuicFrames(transport_version())) { stream_id_manager_.OnStreamClosed( IsIncomingStream(stream_id)); } if (!connection_->connected()) { return; } if (IsIncomingStream(stream_id)) { if (VersionHasIetfQuicFrames(transport_version())) { ietf_streamid_manager_.OnStreamClosed(stream_id); } return; } if (!VersionHasIetfQuicFrames(transport_version())) { OnCanCreateNewOutgoingStream(type != BIDIRECTIONAL); } } void QuicSession::ClosePendingStream(QuicStreamId stream_id) { QUIC_DVLOG(1) << ENDPOINT << "Closing stream " << stream_id; QUICHE_DCHECK(VersionHasIetfQuicFrames(transport_version())); pending_stream_map_.erase(stream_id); if (connection_->connected()) { ietf_streamid_manager_.OnStreamClosed(stream_id); } } bool QuicSession::ShouldProcessFrameByPendingStream(QuicFrameType type, QuicStreamId id) const { return stream_map_.find(id) == stream_map_.end() && ((version().HasIetfQuicFrames() && ExceedsPerLoopStreamLimit()) || UsesPendingStreamForFrame(type, id)); } void QuicSession::OnFinalByteOffsetReceived( QuicStreamId stream_id, QuicStreamOffset final_byte_offset) { auto it = locally_closed_streams_highest_offset_.find(stream_id); if (it == locally_closed_streams_highest_offset_.end()) { return; } QUIC_DVLOG(1) << ENDPOINT << "Received final byte offset " << final_byte_offset << " for stream " << stream_id; QuicByteCount offset_diff = final_byte_offset - it->second; if (flow_controller_.UpdateHighestReceivedOffset( flow_controller_.highest_received_byte_offset() + offset_diff)) { if (flow_controller_.FlowControlViolation()) { connection_->CloseConnection( QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, "Connection level flow control violation", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } } flow_controller_.AddBytesConsumed(offset_diff); locally_closed_streams_highest_offset_.erase(it); if (!VersionHasIetfQuicFrames(transport_version())) { stream_id_manager_.OnStreamClosed( IsIncomingStream(stream_id)); } if (IsIncomingStream(stream_id)) { if (VersionHasIetfQuicFrames(transport_version())) { ietf_streamid_manager_.OnStreamClosed(stream_id); } } else if (!VersionHasIetfQuicFrames(transport_version())) { OnCanCreateNewOutgoingStream(false); } } bool QuicSession::IsEncryptionEstablished() const { if (GetCryptoStream() == nullptr) { return false; } return GetCryptoStream()->encryption_established(); } bool QuicSession::OneRttKeysAvailable() const { if (GetCryptoStream() == nullptr) { return false; } return GetCryptoStream()->one_rtt_keys_available(); } void QuicSession::OnConfigNegotiated() { if (version().UsesTls() && is_configured_ && connection_->encryption_level() != ENCRYPTION_FORWARD_SECURE) { QUIC_BUG(quic_bug_12435_6) << ENDPOINT << "1-RTT keys missing when config is negotiated for the second time."; connection_->CloseConnection( QUIC_INTERNAL_ERROR, "1-RTT keys missing when config is negotiated for the second time.", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } QUIC_DVLOG(1) << ENDPOINT << "OnConfigNegotiated"; connection_->SetFromConfig(config_); if (VersionHasIetfQuicFrames(transport_version())) { uint32_t max_streams = 0; if (config_.HasReceivedMaxBidirectionalStreams()) { max_streams = config_.ReceivedMaxBidirectionalStreams(); } if (was_zero_rtt_rejected_ && max_streams < ietf_streamid_manager_.outgoing_bidirectional_stream_count()) { connection_->CloseConnection( QUIC_ZERO_RTT_UNRETRANSMITTABLE, absl::StrCat( "Server rejected 0-RTT, aborting because new bidirectional " "initial stream limit ", max_streams, " is less than current open streams: ", ietf_streamid_manager_.outgoing_bidirectional_stream_count()), ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } QUIC_DVLOG(1) << ENDPOINT << "Setting Bidirectional outgoing_max_streams_ to " << max_streams; if (perspective_ == Perspective::IS_CLIENT && max_streams < ietf_streamid_manager_.max_outgoing_bidirectional_streams()) { connection_->CloseConnection( was_zero_rtt_rejected_ ? QUIC_ZERO_RTT_REJECTION_LIMIT_REDUCED : QUIC_ZERO_RTT_RESUMPTION_LIMIT_REDUCED, absl::StrCat( was_zero_rtt_rejected_ ? "Server rejected 0-RTT, aborting because " : "", "new bidirectional limit ", max_streams, " decreases the current limit: ", ietf_streamid_manager_.max_outgoing_bidirectional_streams()), ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } if (ietf_streamid_manager_.MaybeAllowNewOutgoingBidirectionalStreams( max_streams)) { OnCanCreateNewOutgoingStream( false); } max_streams = 0; if (config_.HasReceivedMaxUnidirectionalStreams()) { max_streams = config_.ReceivedMaxUnidirectionalStreams(); } if (was_zero_rtt_rejected_ && max_streams < ietf_streamid_manager_.outgoing_unidirectional_stream_count()) { connection_->CloseConnection( QUIC_ZERO_RTT_UNRETRANSMITTABLE, absl::StrCat( "Server rejected 0-RTT, aborting because new unidirectional " "initial stream limit ", max_streams, " is less than current open streams: ", ietf_streamid_manager_.outgoing_unidirectional_stream_count()), ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } if (max_streams < ietf_streamid_manager_.max_outgoing_unidirectional_streams()) { connection_->CloseConnection( was_zero_rtt_rejected_ ? QUIC_ZERO_RTT_REJECTION_LIMIT_REDUCED : QUIC_ZERO_RTT_RESUMPTION_LIMIT_REDUCED, absl::StrCat( was_zero_rtt_rejected_ ? "Server rejected 0-RTT, aborting because " : "", "new unidirectional limit ", max_streams, " decreases the current limit: ", ietf_streamid_manager_.max_outgoing_unidirectional_streams()), ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } QUIC_DVLOG(1) << ENDPOINT << "Setting Unidirectional outgoing_max_streams_ to " << max_streams; if (ietf_streamid_manager_.MaybeAllowNewOutgoingUnidirectionalStreams( max_streams)) { OnCanCreateNewOutgoingStream( true); } } else { uint32_t max_streams = 0; if (config_.HasReceivedMaxBidirectionalStreams()) { max_streams = config_.ReceivedMaxBidirectionalStreams(); } QUIC_DVLOG(1) << ENDPOINT << "Setting max_open_outgoing_streams_ to " << max_streams; if (was_zero_rtt_rejected_ && max_streams < stream_id_manager_.num_open_outgoing_streams()) { connection_->CloseConnection( QUIC_INTERNAL_ERROR, absl::StrCat( "Server rejected 0-RTT, aborting because new stream limit ", max_streams, " is less than current open streams: ", stream_id_manager_.num_open_outgoing_streams()), ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } stream_id_manager_.set_max_open_outgoing_streams(max_streams); } if (perspective() == Perspective::IS_SERVER) { if (config_.HasReceivedConnectionOptions()) { if (ContainsQuicTag(config_.ReceivedConnectionOptions(), kIFW6)) { AdjustInitialFlowControlWindows(64 * 1024); } if (ContainsQuicTag(config_.ReceivedConnectionOptions(), kIFW7)) { AdjustInitialFlowControlWindows(128 * 1024); } if (ContainsQuicTag(config_.ReceivedConnectionOptions(), kIFW8)) { AdjustInitialFlowControlWindows(256 * 1024); } if (ContainsQuicTag(config_.ReceivedConnectionOptions(), kIFW9)) { AdjustInitialFlowControlWindows(512 * 1024); } if (ContainsQuicTag(config_.ReceivedConnectionOptions(), kIFWA)) { AdjustInitialFlowControlWindows(1024 * 1024); } } config_.SetStatelessResetTokenToSend(GetStatelessResetToken()); } if (VersionHasIetfQuicFrames(transport_version())) { ietf_streamid_manager_.SetMaxOpenIncomingBidirectionalStreams( config_.GetMaxBidirectionalStreamsToSend()); ietf_streamid_manager_.SetMaxOpenIncomingUnidirectionalStreams( config_.GetMaxUnidirectionalStreamsToSend()); } else { uint32_t max_incoming_streams_to_send = config_.GetMaxBidirectionalStreamsToSend(); uint32_t max_incoming_streams = std::max(max_incoming_streams_to_send + kMaxStreamsMinimumIncrement, static_cast<uint32_t>(max_incoming_streams_to_send * kMaxStreamsMultiplier)); stream_id_manager_.set_max_open_incoming_streams(max_incoming_streams); } if (connection_->version().handshake_protocol == PROTOCOL_TLS1_3) { if (config_.HasReceivedInitialMaxStreamDataBytesOutgoingBidirectional()) { OnNewStreamOutgoingBidirectionalFlowControlWindow( config_.ReceivedInitialMaxStreamDataBytesOutgoingBidirectional()); } if (config_.HasReceivedInitialMaxStreamDataBytesIncomingBidirectional()) { OnNewStreamIncomingBidirectionalFlowControlWindow( config_.ReceivedInitialMaxStreamDataBytesIncomingBidirectional()); } if (config_.HasReceivedInitialMaxStreamDataBytesUnidirectional()) { OnNewStreamUnidirectionalFlowControlWindow( config_.ReceivedInitialMaxStreamDataBytesUnidirectional()); } } else { if (config_.HasReceivedInitialStreamFlowControlWindowBytes()) { OnNewStreamFlowControlWindow( config_.ReceivedInitialStreamFlowControlWindowBytes()); } } if (config_.HasReceivedInitialSessionFlowControlWindowBytes()) { OnNewSessionFlowControlWindow( config_.ReceivedInitialSessionFlowControlWindowBytes()); } if (perspective_ == Perspective::IS_SERVER && version().HasIetfQuicFrames() && connection_->effective_peer_address().IsInitialized()) { if (config_.SupportsServerPreferredAddress(perspective_)) { quiche::IpAddressFamily address_family = connection_->effective_peer_address() .Normalized() .host() .address_family(); std::optional<QuicSocketAddress> expected_preferred_address = config_.GetMappedAlternativeServerAddress(address_family); if (expected_preferred_address.has_value()) { std::optional<QuicNewConnectionIdFrame> frame = connection_->MaybeIssueNewConnectionIdForPreferredAddress(); if (frame.has_value()) { config_.SetPreferredAddressConnectionIdAndTokenToSend( frame->connection_id, frame->stateless_reset_token); } connection_->set_expected_server_preferred_address( *expected_preferred_address); } config_.ClearAlternateServerAddressToSend( address_family == quiche::IpAddressFamily::IP_V4 ? quiche::IpAddressFamily::IP_V6 : quiche::IpAddressFamily::IP_V4); } else { config_.ClearAlternateServerAddressToSend(quiche::IpAddressFamily::IP_V4); config_.ClearAlternateServerAddressToSend(quiche::IpAddressFamily::IP_V6); } } is_configured_ = true; connection()->OnConfigNegotiated(); if (!connection_->framer().is_processing_packet() && (connection_->version().AllowsLowFlowControlLimits() || version().UsesTls())) { QUIC_CODE_COUNT(quic_session_on_can_write_on_config_negotiated); OnCanWrite(); } } std::optional<std::string> QuicSession::OnAlpsData(const uint8_t* , size_t ) { return std::nullopt; } void QuicSession::AdjustInitialFlowControlWindows(size_t stream_window) { const float session_window_multiplier = config_.GetInitialStreamFlowControlWindowToSend() ? static_cast<float>( config_.GetInitialSessionFlowControlWindowToSend()) / config_.GetInitialStreamFlowControlWindowToSend() : 1.5; QUIC_DVLOG(1) << ENDPOINT << "Set stream receive window to " << stream_window; config_.SetInitialStreamFlowControlWindowToSend(stream_window); size_t session_window = session_window_multiplier * stream_window; QUIC_DVLOG(1) << ENDPOINT << "Set session receive window to " << session_window; config_.SetInitialSessionFlowControlWindowToSend(session_window); flow_controller_.UpdateReceiveWindowSize(session_window); for (auto const& kv : stream_map_) { kv.second->UpdateReceiveWindowSize(stream_window); } if (!QuicVersionUsesCryptoFrames(transport_version())) { GetMutableCryptoStream()->UpdateReceiveWindowSize(stream_window); } } void QuicSession::HandleFrameOnNonexistentOutgoingStream( QuicStreamId stream_id) { QUICHE_DCHECK(!IsClosedStream(stream_id)); if (VersionHasIetfQuicFrames(transport_version())) { connection()->CloseConnection( QUIC_HTTP_STREAM_WRONG_DIRECTION, "Data for nonexistent stream", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } connection()->CloseConnection( QUIC_INVALID_STREAM_ID, "Data for nonexistent stream", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); } void QuicSession::HandleRstOnValidNonexistentStream( const QuicRstStreamFrame& frame) { if (IsClosedStream(frame.stream_id)) { OnFinalByteOffsetReceived(frame.stream_id, frame.byte_offset); } } void QuicSession::OnNewStreamFlowControlWindow(QuicStreamOffset new_window) { QUICHE_DCHECK(version().UsesQuicCrypto()); QUIC_DVLOG(1) << ENDPOINT << "OnNewStreamFlowControlWindow " << new_window; if (new_window < kMinimumFlowControlSendWindow) { QUIC_LOG_FIRST_N(ERROR, 1) << "Peer sent us an invalid stream flow control send window: " << new_window << ", below minimum: " << kMinimumFlowControlSendWindow; connection_->CloseConnection( QUIC_FLOW_CONTROL_INVALID_WINDOW, "New stream window too low", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } for (auto const& kv : stream_map_) { QUIC_DVLOG(1) << ENDPOINT << "Informing stream " << kv.first << " of new stream flow control window " << new_window; if (!kv.second->MaybeConfigSendWindowOffset( new_window, false)) { return; } } if (!QuicVersionUsesCryptoFrames(transport_version())) { QUIC_DVLOG(1) << ENDPOINT << "Informing crypto stream of new stream flow control window " << new_window; GetMutableCryptoStream()->MaybeConfigSendWindowOffset( new_window, false); } } void QuicSession::OnNewStreamUnidirectionalFlowControlWindow( QuicStreamOffset new_window) { QUICHE_DCHECK_EQ(connection_->version().handshake_protocol, PROTOCOL_TLS1_3); QUIC_DVLOG(1) << ENDPOINT << "OnNewStreamUnidirectionalFlowControlWindow " << new_window; for (auto const& kv : stream_map_) { const QuicStreamId id = kv.first; if (!version().HasIetfQuicFrames()) { if (kv.second->type() == BIDIRECTIONAL) { continue; } } else { if (QuicUtils::IsBidirectionalStreamId(id, version())) { continue; } } if (!QuicUtils::IsOutgoingStreamId(connection_->version(), id, perspective())) { continue; } QUIC_DVLOG(1) << ENDPOINT << "Informing unidirectional stream " << id << " of new stream flow control window " << new_window; if (!kv.second->MaybeConfigSendWindowOffset(new_window, was_zero_rtt_rejected_)) { return; } } } void QuicSession::OnNewStreamOutgoingBidirectionalFlowControlWindow( QuicStreamOffset new_window) { QUICHE_DCHECK_EQ(connection_->version().handshake_protocol, PROTOCOL_TLS1_3); QUIC_DVLOG(1) << ENDPOINT << "OnNewStreamOutgoingBidirectionalFlowControlWindow " << new_window; for (auto const& kv : stream_map_) { const QuicStreamId id = kv.first; if (!version().HasIetfQuicFrames()) { if (kv.second->type() != BIDIRECTIONAL) { continue; } } else { if (!QuicUtils::IsBidirectionalStreamId(id, version())) { continue; } } if (!QuicUtils::IsOutgoingStreamId(connection_->version(), id, perspective())) { continue; } QUIC_DVLOG(1) << ENDPOINT << "Informing outgoing bidirectional stream " << id << " of new stream flow control window " << new_window; if (!kv.second->MaybeConfigSendWindowOffset(new_window, was_zero_rtt_rejected_)) { return; } } } void QuicSession::OnNewStreamIncomingBidirectionalFlowControlWindow( QuicStreamOffset new_window) { QUICHE_DCHECK_EQ(connection_->version().handshake_protocol, PROTOCOL_TLS1_3); QUIC_DVLOG(1) << ENDPOINT << "OnNewStreamIncomingBidirectionalFlowControlWindow " << new_window; for (auto const& kv : stream_map_) { const QuicStreamId id = kv.first; if (!version().HasIetfQuicFrames()) { if (kv.second->type() != BIDIRECTIONAL) { continue; } } else { if (!QuicUtils::IsBidirectionalStreamId(id, version())) { continue; } } if (QuicUtils::IsOutgoingStreamId(connection_->version(), id, perspective())) { continue; } QUIC_DVLOG(1) << ENDPOINT << "Informing incoming bidirectional stream " << id << " of new stream flow control window " << new_window; if (!kv.second->MaybeConfigSendWindowOffset(new_window, was_zero_rtt_rejected_)) { return; } } } void QuicSession::OnNewSessionFlowControlWindow(QuicStreamOffset new_window) { QUIC_DVLOG(1) << ENDPOINT << "OnNewSessionFlowControlWindow " << new_window; if (was_zero_rtt_rejected_ && new_window < flow_controller_.bytes_sent()) { std::string error_details = absl::StrCat( "Server rejected 0-RTT. Aborting because the client received session " "flow control send window: ", new_window, ", which is below currently used: ", flow_controller_.bytes_sent()); QUIC_LOG(ERROR) << error_details; connection_->CloseConnection( QUIC_ZERO_RTT_UNRETRANSMITTABLE, error_details, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } if (!connection_->version().AllowsLowFlowControlLimits() && new_window < kMinimumFlowControlSendWindow) { std::string error_details = absl::StrCat( "Peer sent us an invalid session flow control send window: ", new_window, ", below minimum: ", kMinimumFlowControlSendWindow); QUIC_LOG_FIRST_N(ERROR, 1) << error_details; connection_->CloseConnection( QUIC_FLOW_CONTROL_INVALID_WINDOW, error_details, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } if (perspective_ == Perspective::IS_CLIENT && new_window < flow_controller_.send_window_offset()) { std::string error_details = absl::StrCat( was_zero_rtt_rejected_ ? "Server rejected 0-RTT, aborting because " : "", "new session max data ", new_window, " decreases current limit: ", flow_controller_.send_window_offset()); QUIC_LOG(ERROR) << error_details; connection_->CloseConnection( was_zero_rtt_rejected_ ? QUIC_ZERO_RTT_REJECTION_LIMIT_REDUCED : QUIC_ZERO_RTT_RESUMPTION_LIMIT_REDUCED, error_details, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } flow_controller_.UpdateSendWindowOffset(new_window); } bool QuicSession::OnNewDecryptionKeyAvailable( EncryptionLevel level, std::unique_ptr<QuicDecrypter> decrypter, bool set_alternative_decrypter, bool latch_once_used) { if (connection_->version().handshake_protocol == PROTOCOL_TLS1_3 && !connection()->framer().HasEncrypterOfEncryptionLevel( QuicUtils::GetEncryptionLevelToSendAckofSpace( QuicUtils::GetPacketNumberSpace(level)))) { return false; } if (connection()->version().KnowsWhichDecrypterToUse()) { connection()->InstallDecrypter(level, std::move(decrypter)); return true; } if (set_alternative_decrypter) { connection()->SetAlternativeDecrypter(level, std::move(decrypter), latch_once_used); return true; } connection()->SetDecrypter(level, std::move(decrypter)); return true; } void QuicSession::OnNewEncryptionKeyAvailable( EncryptionLevel level, std::unique_ptr<QuicEncrypter> encrypter) { connection()->SetEncrypter(level, std::move(encrypter)); if (connection_->version().handshake_protocol != PROTOCOL_TLS1_3) { return; } bool reset_encryption_level = false; if (IsEncryptionEstablished() && level == ENCRYPTION_HANDSHAKE) { reset_encryption_level = true; } QUIC_DVLOG(1) << ENDPOINT << "Set default encryption level to " << level; connection()->SetDefaultEncryptionLevel(level); if (reset_encryption_level) { connection()->SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT); } QUIC_BUG_IF(quic_bug_12435_7, IsEncryptionEstablished() && (connection()->encryption_level() == ENCRYPTION_INITIAL || connection()->encryption_level() == ENCRYPTION_HANDSHAKE)) << "Encryption is established, but the encryption level " << level << " does not support sending stream data"; } void QuicSession::SetDefaultEncryptionLevel(EncryptionLevel level) { QUICHE_DCHECK_EQ(PROTOCOL_QUIC_CRYPTO, connection_->version().handshake_protocol); QUIC_DVLOG(1) << ENDPOINT << "Set default encryption level to " << level; connection()->SetDefaultEncryptionLevel(level); switch (level) { case ENCRYPTION_INITIAL: break; case ENCRYPTION_ZERO_RTT: if (perspective() == Perspective::IS_CLIENT) { connection_->MarkZeroRttPacketsForRetransmission(0); if (!connection_->framer().is_processing_packet()) { QUIC_CODE_COUNT( quic_session_on_can_write_set_default_encryption_level); OnCanWrite(); } } break; case ENCRYPTION_HANDSHAKE: break; case ENCRYPTION_FORWARD_SECURE: QUIC_BUG_IF(quic_bug_12435_8, !config_.negotiated()) << ENDPOINT << "Handshake confirmed without parameter negotiation."; connection()->mutable_stats().handshake_completion_time = connection()->clock()->ApproximateNow(); break; default: QUIC_BUG(quic_bug_10866_7) << "Unknown encryption level: " << level; } } void QuicSession::OnTlsHandshakeComplete() { QUICHE_DCHECK_EQ(PROTOCOL_TLS1_3, connection_->version().handshake_protocol); QUIC_BUG_IF(quic_bug_12435_9, !GetCryptoStream()->crypto_negotiated_params().cipher_suite) << ENDPOINT << "Handshake completes without cipher suite negotiation."; QUIC_BUG_IF(quic_bug_12435_10, !config_.negotiated()) << ENDPOINT << "Handshake completes without parameter negotiation."; connection()->mutable_stats().handshake_completion_time = connection()->clock()->ApproximateNow(); if (connection()->ShouldFixTimeouts(config_)) { QUIC_RELOADABLE_FLAG_COUNT_N(quic_fix_timeouts, 2, 2); connection()->SetNetworkTimeouts(QuicTime::Delta::Infinite(), config_.IdleNetworkTimeout()); } if (connection()->version().UsesTls() && perspective_ == Perspective::IS_SERVER) { control_frame_manager_.WriteOrBufferHandshakeDone(); if (connection()->version().HasIetfQuicFrames()) { MaybeSendAddressToken(); } } if (perspective_ == Perspective::IS_CLIENT && (config_.HasClientSentConnectionOption(kCHP1, perspective_) || config_.HasClientSentConnectionOption(kCHP2, perspective_))) { config_.ClearGoogleHandshakeMessage(); } } bool QuicSession::MaybeSendAddressToken() { QUICHE_DCHECK(perspective_ == Perspective::IS_SERVER && connection()->version().HasIetfQuicFrames()); std::optional<CachedNetworkParameters> cached_network_params = GenerateCachedNetworkParameters(); std::string address_token = GetCryptoStream()->GetAddressToken( cached_network_params.has_value() ? &*cached_network_params : nullptr); if (address_token.empty()) { return false; } const size_t buf_len = address_token.length() + 1; auto buffer = std::make_unique<char[]>(buf_len); QuicDataWriter writer(buf_len, buffer.get()); writer.WriteUInt8(kAddressTokenPrefix); writer.WriteBytes(address_token.data(), address_token.length()); control_frame_manager_.WriteOrBufferNewToken( absl::string_view(buffer.get(), buf_len)); if (cached_network_params.has_value()) { connection()->OnSendConnectionState(*cached_network_params); } return true; } void QuicSession::DiscardOldDecryptionKey(EncryptionLevel level) { if (!connection()->version().KnowsWhichDecrypterToUse()) { return; } connection()->RemoveDecrypter(level); } void QuicSession::DiscardOldEncryptionKey(EncryptionLevel level) { QUIC_DLOG(INFO) << ENDPOINT << "Discarding " << level << " keys"; if (connection()->version().handshake_protocol == PROTOCOL_TLS1_3) { connection()->RemoveEncrypter(level); } switch (level) { case ENCRYPTION_INITIAL: NeuterUnencryptedData(); break; case ENCRYPTION_HANDSHAKE: NeuterHandshakeData(); break; case ENCRYPTION_ZERO_RTT: break; case ENCRYPTION_FORWARD_SECURE: QUIC_BUG(quic_bug_10866_8) << ENDPOINT << "Discarding 1-RTT keys is not allowed"; break; default: QUIC_BUG(quic_bug_10866_9) << ENDPOINT << "Cannot discard keys for unknown encryption level: " << level; } } void QuicSession::NeuterHandshakeData() { GetMutableCryptoStream()->NeuterStreamDataOfEncryptionLevel( ENCRYPTION_HANDSHAKE); connection()->OnHandshakeComplete(); } void QuicSession::OnZeroRttRejected(int reason) { was_zero_rtt_rejected_ = true; connection_->MarkZeroRttPacketsForRetransmission(reason); if (connection_->encryption_level() == ENCRYPTION_FORWARD_SECURE) { QUIC_BUG(quic_bug_10866_10) << "1-RTT keys already available when 0-RTT is rejected."; connection_->CloseConnection( QUIC_INTERNAL_ERROR, "1-RTT keys already available when 0-RTT is rejected.", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); } } bool QuicSession::FillTransportParameters(TransportParameters* params) { if (version().UsesTls()) { if (perspective() == Perspective::IS_SERVER) { config_.SetOriginalConnectionIdToSend( connection_->GetOriginalDestinationConnectionId()); config_.SetInitialSourceConnectionIdToSend(connection_->connection_id()); } else { config_.SetInitialSourceConnectionIdToSend( connection_->client_connection_id()); } } return config_.FillTransportParameters(params); } QuicErrorCode QuicSession::ProcessTransportParameters( const TransportParameters& params, bool is_resumption, std::string* error_details) { return config_.ProcessTransportParameters(params, is_resumption, error_details); } void QuicSession::OnHandshakeCallbackDone() { if (!connection_->connected()) { return; } if (!connection()->is_processing_packet()) { connection()->MaybeProcessUndecryptablePackets(); } } bool QuicSession::PacketFlusherAttached() const { QUICHE_DCHECK(connection_->connected()); return connection()->packet_creator().PacketFlusherAttached(); } void QuicSession::OnEncryptedClientHelloSent( absl::string_view client_hello) const { connection()->OnEncryptedClientHelloSent(client_hello); } void QuicSession::OnEncryptedClientHelloReceived( absl::string_view client_hello) const { connection()->OnEncryptedClientHelloReceived(client_hello); } void QuicSession::OnCryptoHandshakeMessageSent( const CryptoHandshakeMessage& ) {} void QuicSession::OnCryptoHandshakeMessageReceived( const CryptoHandshakeMessage& ) {} void QuicSession::RegisterStreamPriority(QuicStreamId id, bool is_static, const QuicStreamPriority& priority) { write_blocked_streams()->RegisterStream(id, is_static, priority); } void QuicSession::UnregisterStreamPriority(QuicStreamId id) { write_blocked_streams()->UnregisterStream(id); } void QuicSession::UpdateStreamPriority(QuicStreamId id, const QuicStreamPriority& new_priority) { write_blocked_streams()->UpdateStreamPriority(id, new_priority); } void QuicSession::ActivateStream(std::unique_ptr<QuicStream> stream) { const bool should_keep_alive = ShouldKeepConnectionAlive(); QuicStreamId stream_id = stream->id(); bool is_static = stream->is_static(); QUIC_DVLOG(1) << ENDPOINT << "num_streams: " << stream_map_.size() << ". activating stream " << stream_id; QUICHE_DCHECK(!stream_map_.contains(stream_id)); stream_map_[stream_id] = std::move(stream); if (is_static) { ++num_static_streams_; return; } if (version().HasIetfQuicFrames() && IsIncomingStream(stream_id) && max_streams_accepted_per_loop_ != kMaxQuicStreamCount) { QUICHE_DCHECK(!ExceedsPerLoopStreamLimit()); ++new_incoming_streams_in_current_loop_; if (!stream_count_reset_alarm_->IsSet()) { stream_count_reset_alarm_->Set(connection()->clock()->ApproximateNow()); } } if (!VersionHasIetfQuicFrames(transport_version())) { stream_id_manager_.ActivateStream( IsIncomingStream(stream_id)); } if (perspective() == Perspective::IS_CLIENT && connection()->multi_port_stats() != nullptr && !should_keep_alive && ShouldKeepConnectionAlive()) { connection()->MaybeProbeMultiPortPath(); } } QuicStreamId QuicSession::GetNextOutgoingBidirectionalStreamId() { if (VersionHasIetfQuicFrames(transport_version())) { return ietf_streamid_manager_.GetNextOutgoingBidirectionalStreamId(); } return stream_id_manager_.GetNextOutgoingStreamId(); } QuicStreamId QuicSession::GetNextOutgoingUnidirectionalStreamId() { if (VersionHasIetfQuicFrames(transport_version())) { return ietf_streamid_manager_.GetNextOutgoingUnidirectionalStreamId(); } return stream_id_manager_.GetNextOutgoingStreamId(); } bool QuicSession::CanOpenNextOutgoingBidirectionalStream() { if (liveness_testing_in_progress_) { QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, perspective()); QUIC_CODE_COUNT( quic_client_fails_to_create_stream_liveness_testing_in_progress); return false; } if (!VersionHasIetfQuicFrames(transport_version())) { if (!stream_id_manager_.CanOpenNextOutgoingStream()) { return false; } } else { if (!ietf_streamid_manager_.CanOpenNextOutgoingBidirectionalStream()) { QUIC_CODE_COUNT( quic_fails_to_create_stream_close_too_many_streams_created); if (is_configured_) { control_frame_manager_.WriteOrBufferStreamsBlocked( ietf_streamid_manager_.max_outgoing_bidirectional_streams(), false); } return false; } } if (perspective() == Perspective::IS_CLIENT && connection_->MaybeTestLiveness()) { liveness_testing_in_progress_ = true; QUIC_CODE_COUNT(quic_client_fails_to_create_stream_close_to_idle_timeout); return false; } return true; } bool QuicSession::CanOpenNextOutgoingUnidirectionalStream() { if (!VersionHasIetfQuicFrames(transport_version())) { return stream_id_manager_.CanOpenNextOutgoingStream(); } if (ietf_streamid_manager_.CanOpenNextOutgoingUnidirectionalStream()) { return true; } if (is_configured_) { control_frame_manager_.WriteOrBufferStreamsBlocked( ietf_streamid_manager_.max_outgoing_unidirectional_streams(), true); } return false; } QuicStreamCount QuicSession::GetAdvertisedMaxIncomingBidirectionalStreams() const { QUICHE_DCHECK(VersionHasIetfQuicFrames(transport_version())); return ietf_streamid_manager_.advertised_max_incoming_bidirectional_streams(); } QuicStream* QuicSession::GetOrCreateStream(const QuicStreamId stream_id) { QUICHE_DCHECK(!pending_stream_map_.contains(stream_id)); if (QuicUtils::IsCryptoStreamId(transport_version(), stream_id)) { return GetMutableCryptoStream(); } StreamMap::iterator it = stream_map_.find(stream_id); if (it != stream_map_.end()) { return it->second->IsZombie() ? nullptr : it->second.get(); } if (IsClosedStream(stream_id)) { return nullptr; } if (!IsIncomingStream(stream_id)) { HandleFrameOnNonexistentOutgoingStream(stream_id); return nullptr; } if (!MaybeIncreaseLargestPeerStreamId(stream_id)) { return nullptr; } if (!VersionHasIetfQuicFrames(transport_version()) && !stream_id_manager_.CanOpenIncomingStream()) { ResetStream(stream_id, QUIC_REFUSED_STREAM); return nullptr; } return CreateIncomingStream(stream_id); } void QuicSession::StreamDraining(QuicStreamId stream_id, bool unidirectional) { QUICHE_DCHECK(stream_map_.contains(stream_id)); QUIC_DVLOG(1) << ENDPOINT << "Stream " << stream_id << " is draining"; if (VersionHasIetfQuicFrames(transport_version())) { ietf_streamid_manager_.OnStreamClosed(stream_id); } else { stream_id_manager_.OnStreamClosed( IsIncomingStream(stream_id)); } ++num_draining_streams_; if (!IsIncomingStream(stream_id)) { ++num_outgoing_draining_streams_; if (!VersionHasIetfQuicFrames(transport_version())) { OnCanCreateNewOutgoingStream(unidirectional); } } } bool QuicSession::MaybeIncreaseLargestPeerStreamId( const QuicStreamId stream_id) { if (VersionHasIetfQuicFrames(transport_version())) { std::string error_details; if (ietf_streamid_manager_.MaybeIncreaseLargestPeerStreamId( stream_id, &error_details)) { return true; } connection()->CloseConnection( QUIC_INVALID_STREAM_ID, error_details, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return false; } if (!stream_id_manager_.MaybeIncreaseLargestPeerStreamId(stream_id)) { connection()->CloseConnection( QUIC_TOO_MANY_AVAILABLE_STREAMS, absl::StrCat(stream_id, " exceeds available streams ", stream_id_manager_.MaxAvailableStreams()), ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return false; } return true; } bool QuicSession::ShouldYield(QuicStreamId stream_id) { if (stream_id == currently_writing_stream_id_) { return false; } return write_blocked_streams()->ShouldYield(stream_id); } PendingStream* QuicSession::GetOrCreatePendingStream(QuicStreamId stream_id) { auto it = pending_stream_map_.find(stream_id); if (it != pending_stream_map_.end()) { return it->second.get(); } if (IsClosedStream(stream_id) || !MaybeIncreaseLargestPeerStreamId(stream_id)) { return nullptr; } auto pending = std::make_unique<PendingStream>(stream_id, this); PendingStream* unowned_pending = pending.get(); pending_stream_map_[stream_id] = std::move(pending); return unowned_pending; } void QuicSession::set_largest_peer_created_stream_id( QuicStreamId largest_peer_created_stream_id) { QUICHE_DCHECK(!VersionHasIetfQuicFrames(transport_version())); stream_id_manager_.set_largest_peer_created_stream_id( largest_peer_created_stream_id); } QuicStreamId QuicSession::GetLargestPeerCreatedStreamId( bool unidirectional) const { QUICHE_DCHECK(VersionHasIetfQuicFrames(transport_version())); return ietf_streamid_manager_.GetLargestPeerCreatedStreamId(unidirectional); } void QuicSession::DeleteConnection() { if (connection_) { delete connection_; connection_ = nullptr; } } bool QuicSession::MaybeSetStreamPriority(QuicStreamId stream_id, const QuicStreamPriority& priority) { auto active_stream = stream_map_.find(stream_id); if (active_stream != stream_map_.end()) { active_stream->second->SetPriority(priority); return true; } return false; } bool QuicSession::IsClosedStream(QuicStreamId id) { QUICHE_DCHECK_NE(QuicUtils::GetInvalidStreamId(transport_version()), id); if (IsOpenStream(id)) { return false; } if (VersionHasIetfQuicFrames(transport_version())) { return !ietf_streamid_manager_.IsAvailableStream(id); } return !stream_id_manager_.IsAvailableStream(id); } bool QuicSession::IsOpenStream(QuicStreamId id) { QUICHE_DCHECK_NE(QuicUtils::GetInvalidStreamId(transport_version()), id); const StreamMap::iterator it = stream_map_.find(id); if (it != stream_map_.end()) { return !it->second->IsZombie(); } if (pending_stream_map_.contains(id) || QuicUtils::IsCryptoStreamId(transport_version(), id)) { return true; } return false; } bool QuicSession::IsStaticStream(QuicStreamId id) const { auto it = stream_map_.find(id); if (it == stream_map_.end()) { return false; } return it->second->is_static(); } size_t QuicSession::GetNumActiveStreams() const { QUICHE_DCHECK_GE( static_cast<QuicStreamCount>(stream_map_.size()), num_static_streams_ + num_draining_streams_ + num_zombie_streams_); return stream_map_.size() - num_draining_streams_ - num_static_streams_ - num_zombie_streams_; } void QuicSession::MarkConnectionLevelWriteBlocked(QuicStreamId id) { if (GetOrCreateStream(id) == nullptr) { QUIC_BUG(quic_bug_10866_11) << "Marking unknown stream " << id << " blocked."; QUIC_LOG_FIRST_N(ERROR, 2) << QuicStackTrace(); } QUIC_DVLOG(1) << ENDPOINT << "Adding stream " << id << " to write-blocked list"; write_blocked_streams_->AddStream(id); } bool QuicSession::HasDataToWrite() const { return write_blocked_streams_->HasWriteBlockedSpecialStream() || write_blocked_streams_->HasWriteBlockedDataStreams() || connection_->HasQueuedData() || !streams_with_pending_retransmission_.empty() || control_frame_manager_.WillingToWrite(); } void QuicSession::OnAckNeedsRetransmittableFrame() { flow_controller_.SendWindowUpdate(); } void QuicSession::SendAckFrequency(const QuicAckFrequencyFrame& frame) { control_frame_manager_.WriteOrBufferAckFrequency(frame); } void QuicSession::SendNewConnectionId(const QuicNewConnectionIdFrame& frame) { control_frame_manager_.WriteOrBufferNewConnectionId( frame.connection_id, frame.sequence_number, frame.retire_prior_to, frame.stateless_reset_token); } void QuicSession::SendRetireConnectionId(uint64_t sequence_number) { if (GetQuicReloadableFlag( quic_no_write_control_frame_upon_connection_close2)) { QUIC_RELOADABLE_FLAG_COUNT( quic_no_write_control_frame_upon_connection_close2); if (!connection_->connected()) { return; } } control_frame_manager_.WriteOrBufferRetireConnectionId(sequence_number); } bool QuicSession::MaybeReserveConnectionId( const QuicConnectionId& server_connection_id) { if (visitor_) { return visitor_->TryAddNewConnectionId( connection_->GetOneActiveServerConnectionId(), server_connection_id); } return true; } void QuicSession::OnServerConnectionIdRetired( const QuicConnectionId& server_connection_id) { if (visitor_) { visitor_->OnConnectionIdRetired(server_connection_id); } } bool QuicSession::IsConnectionFlowControlBlocked() const { return flow_controller_.IsBlocked(); } bool QuicSession::IsStreamFlowControlBlocked() { for (auto const& kv : stream_map_) { if (kv.second->IsFlowControlBlocked()) { return true; } } if (!QuicVersionUsesCryptoFrames(transport_version()) && GetMutableCryptoStream()->IsFlowControlBlocked()) { return true; } return false; } size_t QuicSession::MaxAvailableBidirectionalStreams() const { if (VersionHasIetfQuicFrames(transport_version())) { return ietf_streamid_manager_.GetMaxAllowdIncomingBidirectionalStreams(); } return stream_id_manager_.MaxAvailableStreams(); } size_t QuicSession::MaxAvailableUnidirectionalStreams() const { if (VersionHasIetfQuicFrames(transport_version())) { return ietf_streamid_manager_.GetMaxAllowdIncomingUnidirectionalStreams(); } return stream_id_manager_.MaxAvailableStreams(); } bool QuicSession::IsIncomingStream(QuicStreamId id) const { if (VersionHasIetfQuicFrames(transport_version())) { return !QuicUtils::IsOutgoingStreamId(version(), id, perspective_); } return stream_id_manager_.IsIncomingStream(id); } void QuicSession::MaybeCloseZombieStream(QuicStreamId id) { auto it = stream_map_.find(id); if (it == stream_map_.end()) { return; } --num_zombie_streams_; closed_streams_.push_back(std::move(it->second)); stream_map_.erase(it); if (!closed_streams_clean_up_alarm_->IsSet()) { closed_streams_clean_up_alarm_->Set(connection_->clock()->ApproximateNow()); } streams_with_pending_retransmission_.erase(id); connection_->QuicBugIfHasPendingFrames(id); } QuicStream* QuicSession::GetStream(QuicStreamId id) const { auto active_stream = stream_map_.find(id); if (active_stream != stream_map_.end()) { return active_stream->second.get(); } if (QuicUtils::IsCryptoStreamId(transport_version(), id)) { return const_cast<QuicCryptoStream*>(GetCryptoStream()); } return nullptr; } QuicStream* QuicSession::GetActiveStream(QuicStreamId id) const { auto stream = stream_map_.find(id); if (stream != stream_map_.end() && !stream->second->is_static()) { return stream->second.get(); } return nullptr; } bool QuicSession::OnFrameAcked(const QuicFrame& frame, QuicTime::Delta ack_delay_time, QuicTime receive_timestamp) { if (frame.type == MESSAGE_FRAME) { OnMessageAcked(frame.message_frame->message_id, receive_timestamp); return true; } if (frame.type == CRYPTO_FRAME) { return GetMutableCryptoStream()->OnCryptoFrameAcked(*frame.crypto_frame, ack_delay_time); } if (frame.type != STREAM_FRAME) { bool acked = control_frame_manager_.OnControlFrameAcked(frame); if (acked && frame.type == MAX_STREAMS_FRAME) { ietf_streamid_manager_.MaybeSendMaxStreamsFrame(); } return acked; } bool new_stream_data_acked = false; QuicStream* stream = GetStream(frame.stream_frame.stream_id); if (stream != nullptr) { QuicByteCount newly_acked_length = 0; new_stream_data_acked = stream->OnStreamFrameAcked( frame.stream_frame.offset, frame.stream_frame.data_length, frame.stream_frame.fin, ack_delay_time, receive_timestamp, &newly_acked_length); if (!stream->HasPendingRetransmission()) { streams_with_pending_retransmission_.erase(stream->id()); } } return new_stream_data_acked; } void QuicSession::OnStreamFrameRetransmitted(const QuicStreamFrame& frame) { QuicStream* stream = GetStream(frame.stream_id); if (stream == nullptr) { QUIC_BUG(quic_bug_10866_12) << "Stream: " << frame.stream_id << " is closed when " << frame << " is retransmitted."; connection()->CloseConnection( QUIC_INTERNAL_ERROR, "Attempt to retransmit frame of a closed stream", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } stream->OnStreamFrameRetransmitted(frame.offset, frame.data_length, frame.fin); } void QuicSession::OnFrameLost(const QuicFrame& frame) { if (frame.type == MESSAGE_FRAME) { ++total_datagrams_lost_; OnMessageLost(frame.message_frame->message_id); return; } if (frame.type == CRYPTO_FRAME) { GetMutableCryptoStream()->OnCryptoFrameLost(frame.crypto_frame); return; } if (frame.type != STREAM_FRAME) { control_frame_manager_.OnControlFrameLost(frame); return; } QuicStream* stream = GetStream(frame.stream_frame.stream_id); if (stream == nullptr) { return; } stream->OnStreamFrameLost(frame.stream_frame.offset, frame.stream_frame.data_length, frame.stream_frame.fin); if (stream->HasPendingRetransmission() && !streams_with_pending_retransmission_.contains( frame.stream_frame.stream_id)) { streams_with_pending_retransmission_.insert( std::make_pair(frame.stream_frame.stream_id, true)); } } bool QuicSession::RetransmitFrames(const QuicFrames& frames, TransmissionType type) { QuicConnection::ScopedPacketFlusher retransmission_flusher(connection_); for (const QuicFrame& frame : frames) { if (frame.type == MESSAGE_FRAME) { continue; } if (frame.type == CRYPTO_FRAME) { if (!GetMutableCryptoStream()->RetransmitData(frame.crypto_frame, type)) { return false; } continue; } if (frame.type != STREAM_FRAME) { if (!control_frame_manager_.RetransmitControlFrame(frame, type)) { return false; } continue; } QuicStream* stream = GetStream(frame.stream_frame.stream_id); if (stream != nullptr && !stream->RetransmitStreamData(frame.stream_frame.offset, frame.stream_frame.data_length, frame.stream_frame.fin, type)) { return false; } } return true; } bool QuicSession::IsFrameOutstanding(const QuicFrame& frame) const { if (frame.type == MESSAGE_FRAME) { return false; } if (frame.type == CRYPTO_FRAME) { return GetCryptoStream()->IsFrameOutstanding( frame.crypto_frame->level, frame.crypto_frame->offset, frame.crypto_frame->data_length); } if (frame.type != STREAM_FRAME) { return control_frame_manager_.IsControlFrameOutstanding(frame); } QuicStream* stream = GetStream(frame.stream_frame.stream_id); return stream != nullptr && stream->IsStreamFrameOutstanding(frame.stream_frame.offset, frame.stream_frame.data_length, frame.stream_frame.fin); } bool QuicSession::HasUnackedCryptoData() const { const QuicCryptoStream* crypto_stream = GetCryptoStream(); return crypto_stream->IsWaitingForAcks() || crypto_stream->HasBufferedData(); } bool QuicSession::HasUnackedStreamData() const { for (const auto& it : stream_map_) { if (it.second->IsWaitingForAcks()) { return true; } } return false; } HandshakeState QuicSession::GetHandshakeState() const { return GetCryptoStream()->GetHandshakeState(); } QuicByteCount QuicSession::GetFlowControlSendWindowSize(QuicStreamId id) { auto it = stream_map_.find(id); if (it == stream_map_.end()) { return std::numeric_limits<QuicByteCount>::max(); } return it->second->CalculateSendWindowSize(); } WriteStreamDataResult QuicSession::WriteStreamData(QuicStreamId id, QuicStreamOffset offset, QuicByteCount data_length, QuicDataWriter* writer) { QuicStream* stream = GetStream(id); if (stream == nullptr) { QUIC_BUG(quic_bug_10866_13) << "Stream " << id << " does not exist when trying to write data." << " version:" << transport_version(); return STREAM_MISSING; } if (stream->WriteStreamData(offset, data_length, writer)) { return WRITE_SUCCESS; } return WRITE_FAILED; } bool QuicSession::WriteCryptoData(EncryptionLevel level, QuicStreamOffset offset, QuicByteCount data_length, QuicDataWriter* writer) { return GetMutableCryptoStream()->WriteCryptoFrame(level, offset, data_length, writer); } StatelessResetToken QuicSession::GetStatelessResetToken() const { return QuicUtils::GenerateStatelessResetToken(connection_->connection_id()); } bool QuicSession::CanWriteStreamData() const { if (connection_->HasQueuedPackets()) { return false; } if (HasPendingHandshake()) { return true; } return connection_->CanWrite(HAS_RETRANSMITTABLE_DATA); } bool QuicSession::RetransmitLostData() { QuicConnection::ScopedPacketFlusher retransmission_flusher(connection_); bool uses_crypto_frames = QuicVersionUsesCryptoFrames(transport_version()); if (QuicCryptoStream* const crypto_stream = GetMutableCryptoStream(); uses_crypto_frames && crypto_stream->HasPendingCryptoRetransmission()) { crypto_stream->WritePendingCryptoRetransmission(); } if (!uses_crypto_frames && streams_with_pending_retransmission_.contains( QuicUtils::GetCryptoStreamId(transport_version()))) { QuicStream* const crypto_stream = GetStream(QuicUtils::GetCryptoStreamId(transport_version())); crypto_stream->OnCanWrite(); QUICHE_DCHECK(CheckStreamWriteBlocked(crypto_stream)); if (crypto_stream->HasPendingRetransmission()) { return false; } else { streams_with_pending_retransmission_.erase( QuicUtils::GetCryptoStreamId(transport_version())); } } if (control_frame_manager_.HasPendingRetransmission()) { control_frame_manager_.OnCanWrite(); if (control_frame_manager_.HasPendingRetransmission()) { return false; } } while (!streams_with_pending_retransmission_.empty()) { if (!CanWriteStreamData()) { break; } const QuicStreamId id = streams_with_pending_retransmission_.begin()->first; QuicStream* stream = GetStream(id); if (stream != nullptr) { stream->OnCanWrite(); QUICHE_DCHECK(CheckStreamWriteBlocked(stream)); if (stream->HasPendingRetransmission()) { break; } else if (!streams_with_pending_retransmission_.empty() && streams_with_pending_retransmission_.begin()->first == id) { streams_with_pending_retransmission_.pop_front(); } } else { QUIC_BUG(quic_bug_10866_14) << "Try to retransmit data of a closed stream"; streams_with_pending_retransmission_.pop_front(); } } return streams_with_pending_retransmission_.empty(); } void QuicSession::NeuterUnencryptedData() { QuicCryptoStream* crypto_stream = GetMutableCryptoStream(); crypto_stream->NeuterUnencryptedStreamData(); if (!crypto_stream->HasPendingRetransmission() && !QuicVersionUsesCryptoFrames(transport_version())) { streams_with_pending_retransmission_.erase( QuicUtils::GetCryptoStreamId(transport_version())); } connection_->NeuterUnencryptedPackets(); } void QuicSession::SetTransmissionType(TransmissionType type) { connection_->SetTransmissionType(type); } MessageResult QuicSession::SendMessage( absl::Span<quiche::QuicheMemSlice> message) { return SendMessage(message, false); } MessageResult QuicSession::SendMessage(quiche::QuicheMemSlice message) { return SendMessage(absl::MakeSpan(&message, 1), false); } MessageResult QuicSession::SendMessage( absl::Span<quiche::QuicheMemSlice> message, bool flush) { QUICHE_DCHECK(connection_->connected()) << ENDPOINT << "Try to write messages when connection is closed."; if (!IsEncryptionEstablished()) { return {MESSAGE_STATUS_ENCRYPTION_NOT_ESTABLISHED, 0}; } QuicConnection::ScopedEncryptionLevelContext context( connection(), GetEncryptionLevelToSendApplicationData()); MessageStatus result = connection_->SendMessage(last_message_id_ + 1, message, flush); if (result == MESSAGE_STATUS_SUCCESS) { return {result, ++last_message_id_}; } return {result, 0}; } void QuicSession::OnMessageAcked(QuicMessageId message_id, QuicTime ) { QUIC_DVLOG(1) << ENDPOINT << "message " << message_id << " gets acked."; } void QuicSession::OnMessageLost(QuicMessageId message_id) { QUIC_DVLOG(1) << ENDPOINT << "message " << message_id << " is considered lost"; } void QuicSession::CleanUpClosedStreams() { closed_streams_.clear(); } QuicPacketLength QuicSession::GetCurrentLargestMessagePayload() const { return connection_->GetCurrentLargestMessagePayload(); } QuicPacketLength QuicSession::GetGuaranteedLargestMessagePayload() const { return connection_->GetGuaranteedLargestMessagePayload(); } QuicStreamId QuicSession::next_outgoing_bidirectional_stream_id() const { if (VersionHasIetfQuicFrames(transport_version())) { return ietf_streamid_manager_.next_outgoing_bidirectional_stream_id(); } return stream_id_manager_.next_outgoing_stream_id(); } QuicStreamId QuicSession::next_outgoing_unidirectional_stream_id() const { if (VersionHasIetfQuicFrames(transport_version())) { return ietf_streamid_manager_.next_outgoing_unidirectional_stream_id(); } return stream_id_manager_.next_outgoing_stream_id(); } bool QuicSession::OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) { const bool allow_new_streams = frame.unidirectional ? ietf_streamid_manager_.MaybeAllowNewOutgoingUnidirectionalStreams( frame.stream_count) : ietf_streamid_manager_.MaybeAllowNewOutgoingBidirectionalStreams( frame.stream_count); if (allow_new_streams) { OnCanCreateNewOutgoingStream(frame.unidirectional); } return true; } bool QuicSession::OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) { std::string error_details; if (ietf_streamid_manager_.OnStreamsBlockedFrame(frame, &error_details)) { return true; } connection_->CloseConnection( QUIC_STREAMS_BLOCKED_ERROR, error_details, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return false; } size_t QuicSession::max_open_incoming_bidirectional_streams() const { if (VersionHasIetfQuicFrames(transport_version())) { return ietf_streamid_manager_.GetMaxAllowdIncomingBidirectionalStreams(); } return stream_id_manager_.max_open_incoming_streams(); } size_t QuicSession::max_open_incoming_unidirectional_streams() const { if (VersionHasIetfQuicFrames(transport_version())) { return ietf_streamid_manager_.GetMaxAllowdIncomingUnidirectionalStreams(); } return stream_id_manager_.max_open_incoming_streams(); } std::vector<absl::string_view>::const_iterator QuicSession::SelectAlpn( const std::vector<absl::string_view>& alpns) const { const std::string alpn = AlpnForVersion(connection()->version()); return std::find(alpns.cbegin(), alpns.cend(), alpn); } void QuicSession::OnAlpnSelected(absl::string_view alpn) { QUIC_DLOG(INFO) << (perspective() == Perspective::IS_SERVER ? "Server: " : "Client: ") << "ALPN selected: " << alpn; } void QuicSession::NeuterCryptoDataOfEncryptionLevel(EncryptionLevel level) { GetMutableCryptoStream()->NeuterStreamDataOfEncryptionLevel(level); } void QuicSession::PerformActionOnActiveStreams( quiche::UnretainedCallback<bool(QuicStream*)> action) { std::vector<QuicStream*> active_streams; for (const auto& it : stream_map_) { if (!it.second->is_static() && !it.second->IsZombie()) { active_streams.push_back(it.second.get()); } } for (QuicStream* stream : active_streams) { if (!action(stream)) { return; } } } void QuicSession::PerformActionOnActiveStreams( quiche::UnretainedCallback<bool(QuicStream*)> action) const { for (const auto& it : stream_map_) { if (!it.second->is_static() && !it.second->IsZombie() && !action(it.second.get())) { return; } } } EncryptionLevel QuicSession::GetEncryptionLevelToSendApplicationData() const { return connection_->framer().GetEncryptionLevelToSendApplicationData(); } void QuicSession::ProcessAllPendingStreams() { std::vector<PendingStream*> pending_streams; pending_streams.reserve(pending_stream_map_.size()); for (auto it = pending_stream_map_.begin(); it != pending_stream_map_.end(); ++it) { pending_streams.push_back(it->second.get()); } for (auto* pending_stream : pending_streams) { if (!MaybeProcessPendingStream(pending_stream)) { return; } } } void QuicSession::ValidatePath( std::unique_ptr<QuicPathValidationContext> context, std::unique_ptr<QuicPathValidator::ResultDelegate> result_delegate, PathValidationReason reason) { connection_->ValidatePath(std::move(context), std::move(result_delegate), reason); } bool QuicSession::HasPendingPathValidation() const { return connection_->HasPendingPathValidation(); } bool QuicSession::MigratePath(const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, QuicPacketWriter* writer, bool owns_writer) { return connection_->MigratePath(self_address, peer_address, writer, owns_writer); } bool QuicSession::ValidateToken(absl::string_view token) { QUICHE_DCHECK_EQ(perspective_, Perspective::IS_SERVER); if (GetQuicFlag(quic_reject_retry_token_in_initial_packet)) { return false; } if (token.empty() || token[0] != kAddressTokenPrefix) { return false; } const bool valid = GetCryptoStream()->ValidateAddressToken( absl::string_view(token.data() + 1, token.length() - 1)); if (valid) { const CachedNetworkParameters* cached_network_params = GetCryptoStream()->PreviousCachedNetworkParams(); if (cached_network_params != nullptr && cached_network_params->timestamp() > 0) { connection()->OnReceiveConnectionState(*cached_network_params); } } return valid; } void QuicSession::OnServerPreferredAddressAvailable( const QuicSocketAddress& server_preferred_address) { QUICHE_DCHECK_EQ(perspective_, Perspective::IS_CLIENT); if (visitor_ != nullptr) { visitor_->OnServerPreferredAddressAvailable(server_preferred_address); } } QuicStream* QuicSession::ProcessPendingStream(PendingStream* pending) { QUICHE_DCHECK(VersionUsesHttp3(transport_version())); QUICHE_DCHECK(connection()->connected()); QuicStreamId stream_id = pending->id(); QUIC_BUG_IF(bad pending stream, !IsIncomingStream(stream_id)) << "Pending stream " << stream_id << " is not an incoming stream."; StreamType stream_type = QuicUtils::GetStreamType( stream_id, perspective(), true, version()); switch (stream_type) { case BIDIRECTIONAL: { return ProcessBidirectionalPendingStream(pending); } case READ_UNIDIRECTIONAL: { return ProcessReadUnidirectionalPendingStream(pending); } case WRITE_UNIDIRECTIONAL: ABSL_FALLTHROUGH_INTENDED; case CRYPTO: QUICHE_BUG(unexpected pending stream) << "Unexpected pending stream " << stream_id << " with type " << stream_type; return nullptr; } return nullptr; } bool QuicSession::ExceedsPerLoopStreamLimit() const { QUICHE_DCHECK(version().HasIetfQuicFrames()); return new_incoming_streams_in_current_loop_ >= max_streams_accepted_per_loop_; } void QuicSession::OnStreamCountReset() { const bool exceeded_per_loop_stream_limit = ExceedsPerLoopStreamLimit(); new_incoming_streams_in_current_loop_ = 0; if (exceeded_per_loop_stream_limit) { QUIC_CODE_COUNT_N(quic_pending_stream, 2, 3); ProcessAllPendingStreams(); } } #undef ENDPOINT }
#include "quiche/quic/core/quic_session.h" #include <cstdint> #include <memory> #include <optional> #include <set> #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/crypto_protocol.h" #include "quiche/quic/core/crypto/null_decrypter.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/crypto/transport_parameters.h" #include "quiche/quic/core/frames/quic_max_streams_frame.h" #include "quiche/quic/core/frames/quic_reset_stream_at_frame.h" #include "quiche/quic/core/quic_constants.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_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/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_flow_controller_peer.h" #include "quiche/quic/test_tools/quic_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_stream_send_buffer_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/quiche_mem_slice_storage.h" using spdy::kV3HighestPriority; using spdy::SpdyPriority; using ::testing::_; using ::testing::AnyNumber; using ::testing::AtLeast; using ::testing::InSequence; using ::testing::Invoke; using ::testing::NiceMock; using ::testing::Return; using ::testing::StrictMock; using ::testing::WithArg; namespace quic { namespace test { namespace { 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<NullEncrypter>(session()->perspective())); } 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()->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_; } 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 {} HandshakeState GetHandshakeState() const override { return one_rtt_keys_available() ? HANDSHAKE_COMPLETE : HANDSHAKE_START; } void SetServerApplicationStateForResumption( std::unique_ptr<ApplicationState> ) override {} MOCK_METHOD(std::unique_ptr<QuicDecrypter>, AdvanceKeysAndCreateCurrentOneRttDecrypter, (), (override)); MOCK_METHOD(std::unique_ptr<QuicEncrypter>, CreateCurrentOneRttEncrypter, (), (override)); MOCK_METHOD(void, OnCanWrite, (), (override)); bool HasPendingCryptoRetransmission() const override { return false; } MOCK_METHOD(bool, HasPendingRetransmission, (), (const, override)); void OnConnectionClosed(const QuicConnectionCloseFrame& , ConnectionCloseSource ) 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 QuicStream { public: TestStream(QuicStreamId id, QuicSession* session, StreamType type) : TestStream(id, session, false, type) {} TestStream(QuicStreamId id, QuicSession* session, bool is_static, StreamType type) : QuicStream(id, session, is_static, type) {} TestStream(PendingStream* pending, QuicSession* session) : QuicStream(pending, session, false) {} using QuicStream::CloseWriteSide; using QuicStream::WriteMemSlices; void OnDataAvailable() override {} MOCK_METHOD(void, OnCanWrite, (), (override)); MOCK_METHOD(bool, RetransmitStreamData, (QuicStreamOffset, QuicByteCount, bool, TransmissionType), (override)); MOCK_METHOD(bool, HasPendingRetransmission, (), (const, override)); }; class TestSession : public QuicSession { public: explicit TestSession(QuicConnection* connection, MockQuicSessionVisitor* session_visitor) : QuicSession(connection, session_visitor, DefaultQuicConfig(), CurrentSupportedVersions(), 0), crypto_stream_(this), writev_consumes_all_data_(false), uses_pending_streams_(false), num_incoming_streams_created_(0) { set_max_streams_accepted_per_loop(5); Initialize(); this->connection()->SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(connection->perspective())); 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() { QuicStreamId id = GetNextOutgoingBidirectionalStreamId(); if (id == QuicUtils::GetInvalidStreamId(connection()->transport_version())) { return nullptr; } TestStream* stream = new TestStream(id, this, BIDIRECTIONAL); ActivateStream(absl::WrapUnique(stream)); return stream; } TestStream* CreateOutgoingUnidirectionalStream() { 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; } TestStream* stream = new TestStream( id, this, DetermineStreamType(id, connection()->version(), perspective(), true, BIDIRECTIONAL)); ActivateStream(absl::WrapUnique(stream)); ++num_incoming_streams_created_; return stream; } TestStream* CreateIncomingStream(PendingStream* pending) override { TestStream* stream = new TestStream(pending, this); ActivateStream(absl::WrapUnique(stream)); ++num_incoming_streams_created_; return stream; } QuicStream* ProcessBidirectionalPendingStream( PendingStream* pending) override { return CreateIncomingStream(pending); } QuicStream* ProcessReadUnidirectionalPendingStream( PendingStream* pending) override { struct iovec iov; if (pending->sequencer()->GetReadableRegion(&iov)) { return CreateIncomingStream(pending); } return nullptr; } bool IsClosedStream(QuicStreamId id) { return QuicSession::IsClosedStream(id); } QuicStream* GetOrCreateStream(QuicStreamId stream_id) { return QuicSession::GetOrCreateStream(stream_id); } bool ShouldKeepConnectionAlive() const override { return GetNumActiveStreams() > 0; } 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; } MOCK_METHOD(void, OnCanCreateNewOutgoingStream, (bool unidirectional), (override)); 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()) && this->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; } const QuicFrame& save_frame() { return save_frame_; } bool SaveFrame(const QuicFrame& frame) { save_frame_ = frame; DeleteFrame(&const_cast<QuicFrame&>(frame)); return true; } QuicConsumedData SendLargeFakeData(QuicStream* stream, int bytes) { QUICHE_DCHECK(writev_consumes_all_data_); return WritevData(stream->id(), bytes, 0, FIN, NOT_RETRANSMISSION, GetEncryptionLevelToSendApplicationData()); } bool UsesPendingStreamForFrame(QuicFrameType type, QuicStreamId stream_id) const override { if (!uses_pending_streams_) { return false; } bool is_incoming_stream = IsIncomingStream(stream_id); StreamType stream_type = QuicUtils::GetStreamType( stream_id, perspective(), is_incoming_stream, version()); switch (type) { case STREAM_FRAME: ABSL_FALLTHROUGH_INTENDED; case RST_STREAM_FRAME: return is_incoming_stream; case STOP_SENDING_FRAME: ABSL_FALLTHROUGH_INTENDED; case WINDOW_UPDATE_FRAME: return stream_type == BIDIRECTIONAL; default: return false; } } void set_uses_pending_streams(bool uses_pending_streams) { uses_pending_streams_ = uses_pending_streams; } int num_incoming_streams_created() const { return num_incoming_streams_created_; } using QuicSession::ActivateStream; using QuicSession::CanOpenNextOutgoingBidirectionalStream; using QuicSession::CanOpenNextOutgoingUnidirectionalStream; using QuicSession::closed_streams; using QuicSession::GetNextOutgoingBidirectionalStreamId; using QuicSession::GetNextOutgoingUnidirectionalStreamId; private: StrictMock<TestCryptoStream> crypto_stream_; bool writev_consumes_all_data_; bool uses_pending_streams_; QuicFrame save_frame_; int num_incoming_streams_created_; }; MATCHER_P(IsFrame, type, "") { return arg.type == type; } class QuicSessionTestBase : public QuicTestWithParam<ParsedQuicVersion> { protected: QuicSessionTestBase(Perspective perspective, bool configure_session) : connection_(new StrictMock<MockQuicConnection>( &helper_, &alarm_factory_, perspective, SupportedVersions(GetParam()))), session_(connection_, &session_visitor_), configure_session_(configure_session) { session_.config()->SetInitialStreamFlowControlWindowToSend( kInitialStreamFlowControlWindowForTest); session_.config()->SetInitialSessionFlowControlWindowToSend( kInitialSessionFlowControlWindowForTest); if (configure_session) { if (VersionHasIetfQuicFrames(transport_version())) { EXPECT_CALL(session_, OnCanCreateNewOutgoingStream(false)).Times(1); EXPECT_CALL(session_, OnCanCreateNewOutgoingStream(true)).Times(1); } QuicConfigPeer::SetReceivedMaxBidirectionalStreams( session_.config(), kDefaultMaxStreamsPerConnection); QuicConfigPeer::SetReceivedMaxUnidirectionalStreams( session_.config(), kDefaultMaxStreamsPerConnection); QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesUnidirectional( session_.config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesIncomingBidirectional( session_.config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesOutgoingBidirectional( session_.config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedInitialSessionFlowControlWindow( session_.config(), kMinimumFlowControlSendWindow); connection_->AdvanceTime(QuicTime::Delta::FromSeconds(1)); session_.OnConfigNegotiated(); } TestCryptoStream* crypto_stream = session_.GetMutableCryptoStream(); EXPECT_CALL(*crypto_stream, HasPendingRetransmission()) .Times(testing::AnyNumber()); testing::Mock::VerifyAndClearExpectations(&session_); } ~QuicSessionTestBase() { if (configure_session_) { EXPECT_TRUE(session_.is_configured()); } } void CheckClosedStreams() { QuicStreamId first_stream_id = QuicUtils::GetFirstBidirectionalStreamId( connection_->transport_version(), Perspective::IS_CLIENT); if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { first_stream_id = QuicUtils::GetCryptoStreamId(connection_->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())) { if (QuicUtils::GetStreamType( id, session_.perspective(), session_.IsIncomingStream(id), connection_->version()) == READ_UNIDIRECTIONAL) { EXPECT_CALL(*connection_, SendControlFrame(IsFrame(STOP_SENDING_FRAME))) .Times(1) .WillOnce(Invoke(&ClearControlFrame)); EXPECT_CALL(*connection_, OnStreamReset(id, _)).Times(1); } else if (QuicUtils::GetStreamType( id, session_.perspective(), session_.IsIncomingStream(id), connection_->version()) == WRITE_UNIDIRECTIONAL) { EXPECT_CALL(*connection_, SendControlFrame(IsFrame(RST_STREAM_FRAME))) .Times(1) .WillOnce(Invoke(&ClearControlFrame)); EXPECT_CALL(*connection_, OnStreamReset(id, _)); } else { EXPECT_CALL(*connection_, SendControlFrame(IsFrame(RST_STREAM_FRAME))) .WillRepeatedly(Invoke(&ClearControlFrame)); EXPECT_CALL(*connection_, SendControlFrame(IsFrame(STOP_SENDING_FRAME))) .WillRepeatedly(Invoke(&ClearControlFrame)); EXPECT_CALL(*connection_, OnStreamReset(id, _)); } } else { EXPECT_CALL(*connection_, SendControlFrame(_)) .WillOnce(Invoke(&ClearControlFrame)); EXPECT_CALL(*connection_, OnStreamReset(id, _)); } session_.ResetStream(id, QUIC_STREAM_CANCELLED); closed_streams_.insert(id); } void CompleteHandshake() { CryptoHandshakeMessage msg; if (connection_->version().UsesTls() && connection_->perspective() == Perspective::IS_SERVER) { EXPECT_CALL(*connection_, SendControlFrame(_)) .WillOnce(Invoke(&ClearControlFrame)); } session_.GetMutableCryptoStream()->OnHandshakeMessage(msg); } QuicTransportVersion transport_version() const { return connection_->transport_version(); } QuicStreamId GetNthClientInitiatedBidirectionalId(int n) { return QuicUtils::GetFirstBidirectionalStreamId( connection_->transport_version(), Perspective::IS_CLIENT) + QuicUtils::StreamIdDelta(connection_->transport_version()) * n; } QuicStreamId GetNthClientInitiatedUnidirectionalId(int n) { return QuicUtils::GetFirstUnidirectionalStreamId( connection_->transport_version(), Perspective::IS_CLIENT) + QuicUtils::StreamIdDelta(connection_->transport_version()) * n; } QuicStreamId GetNthServerInitiatedBidirectionalId(int n) { return QuicUtils::GetFirstBidirectionalStreamId( connection_->transport_version(), Perspective::IS_SERVER) + QuicUtils::StreamIdDelta(connection_->transport_version()) * n; } QuicStreamId GetNthServerInitiatedUnidirectionalId(int n) { return QuicUtils::GetFirstUnidirectionalStreamId( connection_->transport_version(), Perspective::IS_SERVER) + QuicUtils::StreamIdDelta(connection_->transport_version()) * n; } 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; } MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; NiceMock<MockQuicSessionVisitor> session_visitor_; StrictMock<MockQuicConnection>* connection_; TestSession session_; std::set<QuicStreamId> closed_streams_; bool configure_session_; }; class QuicSessionTestServer : public QuicSessionTestBase { public: WriteResult CheckMultiPathResponse(const char* buffer, size_t buf_len, const QuicIpAddress& , const QuicSocketAddress& , PerPacketOptions* ) { QuicEncryptedPacket packet(buffer, buf_len); { InSequence s; EXPECT_CALL(framer_visitor_, OnPacket()); EXPECT_CALL(framer_visitor_, OnUnauthenticatedPublicHeader(_)); EXPECT_CALL(framer_visitor_, OnUnauthenticatedHeader(_)); EXPECT_CALL(framer_visitor_, OnDecryptedPacket(_, _)); EXPECT_CALL(framer_visitor_, OnPacketHeader(_)); EXPECT_CALL(framer_visitor_, OnPathResponseFrame(_)) .WillOnce( WithArg<0>(Invoke([this](const QuicPathResponseFrame& frame) { EXPECT_EQ(path_frame_buffer1_, frame.data_buffer); return true; }))); EXPECT_CALL(framer_visitor_, OnPathResponseFrame(_)) .WillOnce( WithArg<0>(Invoke([this](const QuicPathResponseFrame& frame) { EXPECT_EQ(path_frame_buffer2_, frame.data_buffer); return true; }))); EXPECT_CALL(framer_visitor_, OnPacketComplete()); } client_framer_.ProcessPacket(packet); return WriteResult(WRITE_STATUS_OK, 0); } protected: QuicSessionTestServer() : QuicSessionTestBase(Perspective::IS_SERVER, true), path_frame_buffer1_({0, 1, 2, 3, 4, 5, 6, 7}), path_frame_buffer2_({8, 9, 10, 11, 12, 13, 14, 15}), client_framer_(SupportedVersions(GetParam()), QuicTime::Zero(), Perspective::IS_CLIENT, kQuicDefaultConnectionIdLength) { client_framer_.set_visitor(&framer_visitor_); client_framer_.SetInitialObfuscators(TestConnectionId()); if (client_framer_.version().KnowsWhichDecrypterToUse()) { client_framer_.InstallDecrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullDecrypter>(Perspective::IS_CLIENT)); } } QuicPathFrameBuffer path_frame_buffer1_; QuicPathFrameBuffer path_frame_buffer2_; StrictMock<MockFramerVisitor> framer_visitor_; QuicFramer client_framer_; }; INSTANTIATE_TEST_SUITE_P(Tests, QuicSessionTestServer, ::testing::ValuesIn(AllSupportedVersions()), ::testing::PrintToStringParamName()); TEST_P(QuicSessionTestServer, PeerAddress) { EXPECT_EQ(QuicSocketAddress(QuicIpAddress::Loopback4(), kTestPort), session_.peer_address()); } TEST_P(QuicSessionTestServer, SelfAddress) { EXPECT_TRUE(session_.self_address().IsInitialized()); } TEST_P(QuicSessionTestServer, DontCallOnWriteBlockedForDisconnectedConnection) { EXPECT_CALL(*connection_, CloseConnection(_, _, _)) .WillOnce( Invoke(connection_, &MockQuicConnection::ReallyCloseConnection)); connection_->CloseConnection(QUIC_NO_ERROR, "Everything is fine.", ConnectionCloseBehavior::SILENT_CLOSE); ASSERT_FALSE(connection_->connected()); EXPECT_CALL(session_visitor_, OnWriteBlocked(_)).Times(0); session_.OnWriteBlocked(); } TEST_P(QuicSessionTestServer, OneRttKeysAvailable) { EXPECT_FALSE(session_.OneRttKeysAvailable()); CompleteHandshake(); EXPECT_TRUE(session_.OneRttKeysAvailable()); } TEST_P(QuicSessionTestServer, IsClosedStreamDefault) { QuicStreamId first_stream_id = QuicUtils::GetFirstBidirectionalStreamId( connection_->transport_version(), Perspective::IS_CLIENT); if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { first_stream_id = QuicUtils::GetCryptoStreamId(connection_->transport_version()); } for (QuicStreamId i = first_stream_id; i < 100; i++) { EXPECT_FALSE(session_.IsClosedStream(i)) << "stream id: " << i; } } TEST_P(QuicSessionTestServer, AvailableBidirectionalStreams) { ASSERT_TRUE(session_.GetOrCreateStream( GetNthClientInitiatedBidirectionalId(3)) != nullptr); EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable( &session_, GetNthClientInitiatedBidirectionalId(1))); EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable( &session_, GetNthClientInitiatedBidirectionalId(2))); ASSERT_TRUE(session_.GetOrCreateStream( GetNthClientInitiatedBidirectionalId(2)) != nullptr); ASSERT_TRUE(session_.GetOrCreateStream( GetNthClientInitiatedBidirectionalId(1)) != nullptr); } TEST_P(QuicSessionTestServer, AvailableUnidirectionalStreams) { ASSERT_TRUE(session_.GetOrCreateStream( GetNthClientInitiatedUnidirectionalId(3)) != nullptr); EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable( &session_, GetNthClientInitiatedUnidirectionalId(1))); EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable( &session_, GetNthClientInitiatedUnidirectionalId(2))); ASSERT_TRUE(session_.GetOrCreateStream( GetNthClientInitiatedUnidirectionalId(2)) != nullptr); ASSERT_TRUE(session_.GetOrCreateStream( GetNthClientInitiatedUnidirectionalId(1)) != nullptr); } TEST_P(QuicSessionTestServer, MaxAvailableBidirectionalStreams) { if (VersionHasIetfQuicFrames(transport_version())) { EXPECT_EQ(session_.max_open_incoming_bidirectional_streams(), session_.MaxAvailableBidirectionalStreams()); } else { EXPECT_EQ(session_.max_open_incoming_bidirectional_streams() * kMaxAvailableStreamsMultiplier, session_.MaxAvailableBidirectionalStreams()); } } TEST_P(QuicSessionTestServer, MaxAvailableUnidirectionalStreams) { if (VersionHasIetfQuicFrames(transport_version())) { EXPECT_EQ(session_.max_open_incoming_unidirectional_streams(), session_.MaxAvailableUnidirectionalStreams()); } else { EXPECT_EQ(session_.max_open_incoming_unidirectional_streams() * kMaxAvailableStreamsMultiplier, session_.MaxAvailableUnidirectionalStreams()); } } TEST_P(QuicSessionTestServer, IsClosedBidirectionalStreamLocallyCreated) { CompleteHandshake(); TestStream* stream2 = session_.CreateOutgoingBidirectionalStream(); EXPECT_EQ(GetNthServerInitiatedBidirectionalId(0), stream2->id()); TestStream* stream4 = session_.CreateOutgoingBidirectionalStream(); EXPECT_EQ(GetNthServerInitiatedBidirectionalId(1), stream4->id()); CheckClosedStreams(); CloseStream(GetNthServerInitiatedBidirectionalId(0)); CheckClosedStreams(); CloseStream(GetNthServerInitiatedBidirectionalId(1)); CheckClosedStreams(); } TEST_P(QuicSessionTestServer, IsClosedUnidirectionalStreamLocallyCreated) { CompleteHandshake(); TestStream* stream2 = session_.CreateOutgoingUnidirectionalStream(); EXPECT_EQ(GetNthServerInitiatedUnidirectionalId(0), stream2->id()); TestStream* stream4 = session_.CreateOutgoingUnidirectionalStream(); EXPECT_EQ(GetNthServerInitiatedUnidirectionalId(1), stream4->id()); CheckClosedStreams(); CloseStream(GetNthServerInitiatedUnidirectionalId(0)); CheckClosedStreams(); CloseStream(GetNthServerInitiatedUnidirectionalId(1)); CheckClosedStreams(); } TEST_P(QuicSessionTestServer, IsClosedBidirectionalStreamPeerCreated) { 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 + 2 * QuicUtils::StreamIdDelta(connection_->transport_version())); CheckClosedStreams(); CloseStream(stream3->id()); CheckClosedStreams(); } TEST_P(QuicSessionTestServer, IsClosedUnidirectionalStreamPeerCreated) { CompleteHandshake(); QuicStreamId stream_id1 = GetNthClientInitiatedUnidirectionalId(0); QuicStreamId stream_id2 = GetNthClientInitiatedUnidirectionalId(1); session_.GetOrCreateStream(stream_id1); session_.GetOrCreateStream(stream_id2); CheckClosedStreams(); CloseStream(stream_id1); CheckClosedStreams(); CloseStream(stream_id2); QuicStream* stream3 = session_.GetOrCreateStream( stream_id2 + 2 * QuicUtils::StreamIdDelta(connection_->transport_version())); CheckClosedStreams(); CloseStream(stream3->id()); CheckClosedStreams(); } TEST_P(QuicSessionTestServer, MaximumAvailableOpenedBidirectionalStreams) { QuicStreamId stream_id = GetNthClientInitiatedBidirectionalId(0); session_.GetOrCreateStream(stream_id); EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); EXPECT_NE(nullptr, session_.GetOrCreateStream(GetNthClientInitiatedBidirectionalId( session_.max_open_incoming_bidirectional_streams() - 1))); } TEST_P(QuicSessionTestServer, MaximumAvailableOpenedUnidirectionalStreams) { QuicStreamId stream_id = GetNthClientInitiatedUnidirectionalId(0); session_.GetOrCreateStream(stream_id); EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); EXPECT_NE(nullptr, session_.GetOrCreateStream(GetNthClientInitiatedUnidirectionalId( session_.max_open_incoming_unidirectional_streams() - 1))); } TEST_P(QuicSessionTestServer, TooManyAvailableBidirectionalStreams) { QuicStreamId stream_id1 = GetNthClientInitiatedBidirectionalId(0); QuicStreamId stream_id2; EXPECT_NE(nullptr, session_.GetOrCreateStream(stream_id1)); stream_id2 = GetNthClientInitiatedBidirectionalId( session_.MaxAvailableBidirectionalStreams() + 2); 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(QuicSessionTestServer, TooManyAvailableUnidirectionalStreams) { QuicStreamId stream_id1 = GetNthClientInitiatedUnidirectionalId(0); QuicStreamId stream_id2; EXPECT_NE(nullptr, session_.GetOrCreateStream(stream_id1)); stream_id2 = GetNthClientInitiatedUnidirectionalId( session_.MaxAvailableUnidirectionalStreams() + 2); 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(QuicSessionTestServer, ManyAvailableBidirectionalStreams) { if (VersionHasIetfQuicFrames(transport_version())) { QuicSessionPeer::SetMaxOpenIncomingBidirectionalStreams(&session_, 200); QuicSessionPeer::SetMaxOpenIncomingUnidirectionalStreams(&session_, 50); } else { QuicSessionPeer::SetMaxOpenIncomingStreams(&session_, 200); } QuicStreamId stream_id = GetNthClientInitiatedBidirectionalId(0); EXPECT_NE(nullptr, session_.GetOrCreateStream(stream_id)); EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); EXPECT_NE(nullptr, session_.GetOrCreateStream( GetNthClientInitiatedBidirectionalId(199))); if (VersionHasIetfQuicFrames(transport_version())) { stream_id = GetNthClientInitiatedUnidirectionalId(0); EXPECT_NE(nullptr, session_.GetOrCreateStream(stream_id)); EXPECT_NE(nullptr, session_.GetOrCreateStream( GetNthClientInitiatedUnidirectionalId(49))); EXPECT_CALL( *connection_, CloseConnection(QUIC_INVALID_STREAM_ID, "Stream id 798 would exceed stream count limit 50", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET)) .Times(1); EXPECT_EQ(nullptr, session_.GetOrCreateStream( GetNthClientInitiatedUnidirectionalId(199))); } } TEST_P(QuicSessionTestServer, ManyAvailableUnidirectionalStreams) { if (VersionHasIetfQuicFrames(transport_version())) { QuicSessionPeer::SetMaxOpenIncomingUnidirectionalStreams(&session_, 200); QuicSessionPeer::SetMaxOpenIncomingBidirectionalStreams(&session_, 50); } else { QuicSessionPeer::SetMaxOpenIncomingStreams(&session_, 200); } QuicStreamId stream_id = GetNthClientInitiatedUnidirectionalId(0); EXPECT_NE(nullptr, session_.GetOrCreateStream(stream_id)); EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); EXPECT_NE(nullptr, session_.GetOrCreateStream( GetNthClientInitiatedUnidirectionalId(199))); if (VersionHasIetfQuicFrames(transport_version())) { stream_id = GetNthClientInitiatedBidirectionalId(0); EXPECT_NE(nullptr, session_.GetOrCreateStream(stream_id)); EXPECT_NE(nullptr, session_.GetOrCreateStream( GetNthClientInitiatedBidirectionalId(49))); std::string error_detail; if (QuicVersionUsesCryptoFrames(transport_version())) { error_detail = "Stream id 796 would exceed stream count limit 50"; } else { error_detail = "Stream id 800 would exceed stream count limit 50"; } EXPECT_CALL( *connection_, CloseConnection(QUIC_INVALID_STREAM_ID, error_detail, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET)) .Times(1); EXPECT_EQ(nullptr, session_.GetOrCreateStream( GetNthClientInitiatedBidirectionalId(199))); } } TEST_P(QuicSessionTestServer, DebugDFatalIfMarkingClosedStreamWriteBlocked) { CompleteHandshake(); 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(QuicSessionTestServer, OnCanWrite) { 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()); InSequence s; EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() { session_.SendStreamData(stream2); session_.MarkConnectionLevelWriteBlocked(stream2->id()); })); if (!GetQuicReloadableFlag(quic_disable_batch_write) || GetQuicReloadableFlag(quic_priority_respect_incremental)) { EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() { session_.SendStreamData(stream2); })); EXPECT_CALL(*stream6, OnCanWrite()).WillOnce(Invoke([this, stream6]() { session_.SendStreamData(stream6); })); } else { EXPECT_CALL(*stream6, OnCanWrite()).WillOnce(Invoke([this, stream6]() { session_.SendStreamData(stream6); })); EXPECT_CALL(*stream4, OnCanWrite()).WillOnce(Invoke([this, stream4]() { session_.SendStreamData(stream4); })); } session_.OnCanWrite(); EXPECT_TRUE(session_.WillingAndAbleToWrite()); } TEST_P(QuicSessionTestServer, TestBatchedWrites) { session_.set_writev_consumes_all_data(true); TestStream* stream2 = session_.CreateOutgoingBidirectionalStream(); TestStream* stream4 = session_.CreateOutgoingBidirectionalStream(); TestStream* stream6 = session_.CreateOutgoingBidirectionalStream(); const QuicStreamPriority priority( HttpStreamPriority{HttpStreamPriority::kDefaultUrgency, true}); stream2->SetPriority(priority); stream4->SetPriority(priority); stream6->SetPriority(priority); session_.set_writev_consumes_all_data(true); session_.MarkConnectionLevelWriteBlocked(stream2->id()); session_.MarkConnectionLevelWriteBlocked(stream4->id()); InSequence s; EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() { session_.SendLargeFakeData(stream2, 6000); session_.MarkConnectionLevelWriteBlocked(stream2->id()); })); if (GetQuicReloadableFlag(quic_disable_batch_write)) { EXPECT_CALL(*stream4, OnCanWrite()).WillOnce(Invoke([this, stream4]() { session_.SendLargeFakeData(stream4, 6000); session_.MarkConnectionLevelWriteBlocked(stream4->id()); })); } else { EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() { session_.SendLargeFakeData(stream2, 6000); session_.MarkConnectionLevelWriteBlocked(stream2->id()); })); } session_.OnCanWrite(); EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() { session_.SendLargeFakeData(stream2, 6000); session_.MarkConnectionLevelWriteBlocked(stream2->id()); })); EXPECT_CALL(*stream4, OnCanWrite()).WillOnce(Invoke([this, stream4]() { session_.SendLargeFakeData(stream4, 6000); session_.MarkConnectionLevelWriteBlocked(stream4->id()); })); session_.OnCanWrite(); stream6->SetPriority(QuicStreamPriority(HttpStreamPriority{ kV3HighestPriority, HttpStreamPriority::kDefaultIncremental})); if (GetQuicReloadableFlag(quic_disable_batch_write)) { EXPECT_CALL(*stream2, OnCanWrite()) .WillOnce(Invoke([this, stream2, stream6]() { session_.SendLargeFakeData(stream2, 6000); session_.MarkConnectionLevelWriteBlocked(stream2->id()); session_.MarkConnectionLevelWriteBlocked(stream6->id()); })); } else { EXPECT_CALL(*stream4, OnCanWrite()) .WillOnce(Invoke([this, stream4, stream6]() { session_.SendLargeFakeData(stream4, 6000); session_.MarkConnectionLevelWriteBlocked(stream4->id()); session_.MarkConnectionLevelWriteBlocked(stream6->id()); })); } EXPECT_CALL(*stream6, OnCanWrite()) .WillOnce(Invoke([this, stream4, stream6]() { session_.SendStreamData(stream6); session_.SendLargeFakeData(stream4, 6000); })); session_.OnCanWrite(); EXPECT_CALL(*stream4, OnCanWrite()).WillOnce(Invoke([this, stream4]() { session_.SendLargeFakeData(stream4, 12000); session_.MarkConnectionLevelWriteBlocked(stream4->id()); })); EXPECT_CALL(*stream2, OnCanWrite()).WillOnce(Invoke([this, stream2]() { session_.SendLargeFakeData(stream2, 6000); session_.MarkConnectionLevelWriteBlocked(stream2->id()); })); session_.OnCanWrite(); } TEST_P(QuicSessionTestServer, OnCanWriteBundlesStreams) { CompleteHandshake(); MockPacketWriter* writer = static_cast<MockPacketWriter*>( QuicConnectionPeer::GetWriter(session_.connection())); 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(QuicSessionTestServer, OnCanWriteCongestionControlBlocks) { 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(QuicSessionTestServer, OnCanWriteWriterBlocks) { CompleteHandshake(); MockSendAlgorithm* send_algorithm = new StrictMock<MockSendAlgorithm>; QuicConnectionPeer::SetSendAlgorithm(session_.connection(), send_algorithm); EXPECT_CALL(*send_algorithm, CanSend(_)).WillRepeatedly(Return(true)); MockPacketWriter* writer = static_cast<MockPacketWriter*>( QuicConnectionPeer::GetWriter(session_.connection())); 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(QuicSessionTestServer, SendStreamsBlocked) { if (!VersionHasIetfQuicFrames(transport_version())) { return; } CompleteHandshake(); for (size_t i = 0; i < kDefaultMaxStreamsPerConnection; ++i) { ASSERT_TRUE(session_.CanOpenNextOutgoingBidirectionalStream()); session_.GetNextOutgoingBidirectionalStreamId(); } EXPECT_CALL(*connection_, SendControlFrame(_)) .WillOnce(Invoke([](const QuicFrame& frame) { EXPECT_FALSE(frame.streams_blocked_frame.unidirectional); EXPECT_EQ(kDefaultMaxStreamsPerConnection, frame.streams_blocked_frame.stream_count); ClearControlFrame(frame); return true; })); EXPECT_FALSE(session_.CanOpenNextOutgoingBidirectionalStream()); for (size_t i = 0; i < kDefaultMaxStreamsPerConnection; ++i) { ASSERT_TRUE(session_.CanOpenNextOutgoingUnidirectionalStream()); session_.GetNextOutgoingUnidirectionalStreamId(); } EXPECT_CALL(*connection_, SendControlFrame(_)) .WillOnce(Invoke([](const QuicFrame& frame) { EXPECT_TRUE(frame.streams_blocked_frame.unidirectional); EXPECT_EQ(kDefaultMaxStreamsPerConnection, frame.streams_blocked_frame.stream_count); ClearControlFrame(frame); return true; })); EXPECT_FALSE(session_.CanOpenNextOutgoingUnidirectionalStream()); } TEST_P(QuicSessionTestServer, LimitMaxStreams) { if (!VersionHasIetfQuicFrames(transport_version())) { return; } CompleteHandshake(); const QuicStreamId kMaxStreams = 4; QuicSessionPeer::SetMaxOpenIncomingBidirectionalStreams(&session_, kMaxStreams); EXPECT_EQ(kMaxStreams, QuicSessionPeer::ietf_streamid_manager(&session_) ->advertised_max_incoming_bidirectional_streams()); std::vector<QuicMaxStreamsFrame> max_stream_frames; EXPECT_CALL(*connection_, SendControlFrame(IsFrame(MAX_STREAMS_FRAME))) .Times(2) .WillRepeatedly(Invoke([&max_stream_frames](const QuicFrame& frame) { max_stream_frames.push_back(frame.max_streams_frame); ClearControlFrame(frame); return true; })); for (size_t i = 0; i < kMaxStreams; ++i) { QuicStreamId stream_id = GetNthClientInitiatedBidirectionalId(i); QuicStreamFrame data1(stream_id, true, 0, absl::string_view("HT")); session_.OnStreamFrame(data1); CloseStream(stream_id); } EXPECT_EQ(2 * kMaxStreams, QuicSessionPeer::ietf_streamid_manager(&session_) ->advertised_max_incoming_bidirectional_streams()); QuicAlarm* alarm = QuicSessionPeer::GetStreamCountResetAlarm(&session_); if (alarm->IsSet()) { alarm_factory_.FireAlarm(alarm); } for (size_t i = 0; i < kMaxStreams; ++i) { QuicStreamId stream_id = GetNthClientInitiatedBidirectionalId(i + kMaxStreams); QuicStreamFrame data1(stream_id, true, 0, absl::string_view("HT")); session_.OnStreamFrame(data1); CloseStream(stream_id); } EXPECT_CALL(*connection_, SendControlFrame(IsFrame(MAX_STREAMS_FRAME))) .WillOnce(Invoke(&ClearControlFrame)); session_.OnFrameAcked(QuicFrame(max_stream_frames[0]), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_EQ(3 * kMaxStreams, QuicSessionPeer::ietf_streamid_manager(&session_) ->advertised_max_incoming_bidirectional_streams()); if (alarm->IsSet()) { alarm_factory_.FireAlarm(alarm); } for (size_t i = 0; i < kMaxStreams; ++i) { QuicStreamId stream_id = GetNthClientInitiatedBidirectionalId(i + 2 * kMaxStreams); QuicStreamFrame data1(stream_id, true, 0, absl::string_view("HT")); session_.OnStreamFrame(data1); } session_.OnFrameAcked(QuicFrame(max_stream_frames[1]), QuicTime::Delta::Zero(), QuicTime::Zero()); } TEST_P(QuicSessionTestServer, BufferedHandshake) { if (QuicVersionUsesCryptoFrames(connection_->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(connection_->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(QuicSessionTestServer, OnCanWriteWithClosedStream) { 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(QuicSessionTestServer, OnCanWriteLimitsNumWritesIfFlowControlBlocked) { 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(connection_->transport_version())) { session_.MarkConnectionLevelWriteBlocked( QuicUtils::GetCryptoStreamId(connection_->transport_version())); } TestStream* stream = session_.CreateOutgoingBidirectionalStream(); session_.MarkConnectionLevelWriteBlocked(stream->id()); EXPECT_CALL(*stream, OnCanWrite()).Times(0); if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { TestCryptoStream* crypto_stream = session_.GetMutableCryptoStream(); EXPECT_CALL(*crypto_stream, OnCanWrite()); } EXPECT_CALL(*send_algorithm, OnApplicationLimited(_)); session_.OnCanWrite(); EXPECT_FALSE(session_.WillingAndAbleToWrite()); } TEST_P(QuicSessionTestServer, SendGoAway) { if (VersionHasIetfQuicFrames(transport_version())) { return; } CompleteHandshake(); connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); MockPacketWriter* writer = static_cast<MockPacketWriter*>( QuicConnectionPeer::GetWriter(session_.connection())); 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_.transport_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(QuicSessionTestServer, DoNotSendGoAwayTwice) { CompleteHandshake(); if (VersionHasIetfQuicFrames(transport_version())) { return; } EXPECT_CALL(*connection_, SendControlFrame(_)) .WillOnce(Invoke(&ClearControlFrame)); session_.SendGoAway(QUIC_PEER_GOING_AWAY, "Going Away."); EXPECT_TRUE(session_.transport_goaway_sent()); session_.SendGoAway(QUIC_PEER_GOING_AWAY, "Going Away."); } TEST_P(QuicSessionTestServer, InvalidGoAway) { 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(QuicSessionTestServer, ServerReplyToConnectivityProbe) { 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); MockPacketWriter* writer = static_cast<MockPacketWriter*>( QuicConnectionPeer::GetWriter(session_.connection())); EXPECT_CALL(*writer, WritePacket(_, _, _, new_peer_address, _, _)) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 0))); EXPECT_CALL(*connection_, SendConnectivityProbingPacket(_, _)) .WillOnce( Invoke(connection_, &MockQuicConnection::ReallySendConnectivityProbingPacket)); session_.OnPacketReceived(session_.self_address(), new_peer_address, true); EXPECT_EQ(old_peer_address, session_.peer_address()); } TEST_P(QuicSessionTestServer, IncreasedTimeoutAfterCryptoHandshake) { EXPECT_EQ(kInitialIdleTimeoutSecs + 3, QuicConnectionPeer::GetNetworkTimeout(connection_).ToSeconds()); CompleteHandshake(); EXPECT_EQ(kMaximumIdleTimeoutSecs + 3, QuicConnectionPeer::GetNetworkTimeout(connection_).ToSeconds()); } TEST_P(QuicSessionTestServer, OnStreamFrameFinStaticStreamId) { if (VersionUsesHttp3(connection_->transport_version())) { return; } QuicStreamId headers_stream_id = QuicUtils::GetHeadersStreamId(connection_->transport_version()); std::unique_ptr<TestStream> fake_headers_stream = std::make_unique<TestStream>(headers_stream_id, &session_, true, BIDIRECTIONAL); QuicSessionPeer::ActivateStream(&session_, std::move(fake_headers_stream)); QuicStreamFrame data1(headers_stream_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(QuicSessionTestServer, OnStreamFrameInvalidStreamId) { QuicStreamFrame data1( QuicUtils::GetInvalidStreamId(connection_->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(QuicSessionTestServer, OnRstStreamInvalidStreamId) { QuicRstStreamFrame rst1( kInvalidControlFrameId, QuicUtils::GetInvalidStreamId(connection_->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(QuicSessionTestServer, OnResetStreamAtInvalidStreamId) { if (connection_->version().handshake_protocol != PROTOCOL_TLS1_3) { return; } QuicResetStreamAtFrame rst1( kInvalidControlFrameId, QuicUtils::GetInvalidStreamId(connection_->transport_version()), QUIC_ERROR_PROCESSING_STREAM, 10, 0); EXPECT_CALL(*connection_, CloseConnection( QUIC_INVALID_STREAM_ID, "Received data for an invalid stream", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET)); session_.OnResetStreamAt(rst1); } TEST_P(QuicSessionTestServer, HandshakeUnblocksFlowControlBlockedStream) { if (connection_->version().handshake_protocol == PROTOCOL_TLS1_3) { return; } session_.set_writev_consumes_all_data(true); session_.GetMutableCryptoStream()->EstablishZeroRttEncryption(); 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->WriteOrBufferData(body, false, nullptr); 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()); } TEST_P(QuicSessionTestServer, ConnectionFlowControlAccountingRstOutOfOrder) { CompleteHandshake(); TestStream* stream = session_.CreateOutgoingBidirectionalStream(); const QuicStreamOffset kByteOffset = 1 + kInitialSessionFlowControlWindowForTest / 2; EXPECT_CALL(*connection_, SendControlFrame(_)) .Times(2) .WillRepeatedly(Invoke(&ClearControlFrame)); EXPECT_CALL(*connection_, OnStreamReset(stream->id(), _)); QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream->id(), QUIC_STREAM_CANCELLED, kByteOffset); session_.OnRstStream(rst_frame); if (VersionHasIetfQuicFrames(transport_version())) { QuicStopSendingFrame frame(kInvalidControlFrameId, stream->id(), QUIC_STREAM_CANCELLED); EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); session_.OnStopSendingFrame(frame); } EXPECT_EQ(kByteOffset, session_.flow_controller()->bytes_consumed()); } TEST_P(QuicSessionTestServer, ConnectionFlowControlAccountingFinAndLocalReset) { CompleteHandshake(); TestStream* stream = session_.CreateOutgoingBidirectionalStream(); const QuicStreamOffset kByteOffset = kInitialSessionFlowControlWindowForTest / 2 - 1; QuicStreamFrame frame(stream->id(), true, kByteOffset, "."); session_.OnStreamFrame(frame); EXPECT_TRUE(connection_->connected()); EXPECT_EQ(0u, session_.flow_controller()->bytes_consumed()); EXPECT_EQ(kByteOffset + frame.data_length, stream->highest_received_byte_offset()); EXPECT_CALL(*connection_, SendControlFrame(_)); EXPECT_CALL(*connection_, OnStreamReset(stream->id(), _)); stream->Reset(QUIC_STREAM_CANCELLED); EXPECT_EQ(kByteOffset + frame.data_length, session_.flow_controller()->bytes_consumed()); } TEST_P(QuicSessionTestServer, ConnectionFlowControlAccountingFinAfterRst) { CompleteHandshake(); const uint64_t kInitialConnectionBytesConsumed = 567; const uint64_t kInitialConnectionHighestReceivedOffset = 1234; EXPECT_LT(kInitialConnectionBytesConsumed, kInitialConnectionHighestReceivedOffset); session_.flow_controller()->UpdateHighestReceivedOffset( kInitialConnectionHighestReceivedOffset); session_.flow_controller()->AddBytesConsumed(kInitialConnectionBytesConsumed); TestStream* stream = session_.CreateOutgoingBidirectionalStream(); EXPECT_CALL(*connection_, SendControlFrame(_)); EXPECT_CALL(*connection_, OnStreamReset(stream->id(), _)); stream->Reset(QUIC_STREAM_CANCELLED); const QuicStreamOffset kByteOffset = 5678; std::string body = "hello"; QuicStreamFrame frame(stream->id(), true, kByteOffset, absl::string_view(body)); session_.OnStreamFrame(frame); QuicStreamOffset total_stream_bytes_sent_by_peer = kByteOffset + body.length(); EXPECT_EQ(kInitialConnectionBytesConsumed + total_stream_bytes_sent_by_peer, session_.flow_controller()->bytes_consumed()); EXPECT_EQ( kInitialConnectionHighestReceivedOffset + total_stream_bytes_sent_by_peer, session_.flow_controller()->highest_received_byte_offset()); } TEST_P(QuicSessionTestServer, ConnectionFlowControlAccountingRstAfterRst) { CompleteHandshake(); const uint64_t kInitialConnectionBytesConsumed = 567; const uint64_t kInitialConnectionHighestReceivedOffset = 1234; EXPECT_LT(kInitialConnectionBytesConsumed, kInitialConnectionHighestReceivedOffset); session_.flow_controller()->UpdateHighestReceivedOffset( kInitialConnectionHighestReceivedOffset); session_.flow_controller()->AddBytesConsumed(kInitialConnectionBytesConsumed); TestStream* stream = session_.CreateOutgoingBidirectionalStream(); EXPECT_CALL(*connection_, SendControlFrame(_)); EXPECT_CALL(*connection_, OnStreamReset(stream->id(), _)); stream->Reset(QUIC_STREAM_CANCELLED); EXPECT_TRUE(QuicStreamPeer::read_side_closed(stream)); const QuicStreamOffset kByteOffset = 5678; QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream->id(), QUIC_STREAM_CANCELLED, kByteOffset); session_.OnRstStream(rst_frame); EXPECT_EQ(kInitialConnectionBytesConsumed + kByteOffset, session_.flow_controller()->bytes_consumed()); EXPECT_EQ(kInitialConnectionHighestReceivedOffset + kByteOffset, session_.flow_controller()->highest_received_byte_offset()); } TEST_P(QuicSessionTestServer, InvalidStreamFlowControlWindowInHandshake) { const uint32_t kInvalidWindow = kMinimumFlowControlSendWindow - 1; QuicConfigPeer::SetReceivedInitialStreamFlowControlWindow(session_.config(), kInvalidWindow); if (connection_->version().handshake_protocol != PROTOCOL_TLS1_3) { EXPECT_CALL(*connection_, CloseConnection(QUIC_FLOW_CONTROL_INVALID_WINDOW, _, _)); } else { EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); } connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); session_.OnConfigNegotiated(); } TEST_P(QuicSessionTestServer, CustomFlowControlWindow) { 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(QuicSessionTestServer, FlowControlWithInvalidFinalOffset) { CompleteHandshake(); const uint64_t kLargeOffset = kInitialSessionFlowControlWindowForTest + 1; EXPECT_CALL(*connection_, CloseConnection(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, _, _)) .Times(2); TestStream* stream = session_.CreateOutgoingBidirectionalStream(); EXPECT_CALL(*connection_, SendControlFrame(_)); EXPECT_CALL(*connection_, OnStreamReset(stream->id(), _)); stream->Reset(QUIC_STREAM_CANCELLED); QuicStreamFrame frame(stream->id(), true, kLargeOffset, absl::string_view()); session_.OnStreamFrame(frame); QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream->id(), QUIC_STREAM_CANCELLED, kLargeOffset); session_.OnRstStream(rst_frame); } TEST_P(QuicSessionTestServer, TooManyUnfinishedStreamsCauseServerRejectStream) { 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); for (QuicStreamId i = kFirstStreamId; i < kFinalStreamId; i += QuicUtils::StreamIdDelta(connection_->transport_version())) { QuicStreamFrame data1(i, false, 0, absl::string_view("HT")); session_.OnStreamFrame(data1); CloseStream(i); } if (VersionHasIetfQuicFrames(transport_version())) { EXPECT_CALL( *connection_, CloseConnection(QUIC_INVALID_STREAM_ID, "Stream id 20 would exceed stream count limit 5", _)); } else { EXPECT_CALL(*connection_, SendControlFrame(_)).Times(1); EXPECT_CALL(*connection_, OnStreamReset(kFinalStreamId, QUIC_REFUSED_STREAM)) .Times(1); } QuicStreamFrame data1(kFinalStreamId, false, 0, absl::string_view("HT")); session_.OnStreamFrame(data1); } TEST_P(QuicSessionTestServer, DrainingStreamsDoNotCountAsOpenedOutgoing) { CompleteHandshake(); TestStream* stream = session_.CreateOutgoingBidirectionalStream(); QuicStreamId stream_id = stream->id(); QuicStreamFrame data1(stream_id, true, 0, absl::string_view("HT")); session_.OnStreamFrame(data1); if (!VersionHasIetfQuicFrames(transport_version())) { EXPECT_CALL(session_, OnCanCreateNewOutgoingStream(false)).Times(1); } session_.StreamDraining(stream_id, false); } TEST_P(QuicSessionTestServer, NoPendingStreams) { session_.set_uses_pending_streams(false); QuicStreamId stream_id = QuicUtils::GetFirstUnidirectionalStreamId( transport_version(), Perspective::IS_CLIENT); QuicStreamFrame data1(stream_id, true, 10, absl::string_view("HT")); session_.OnStreamFrame(data1); EXPECT_EQ(1, session_.num_incoming_streams_created()); QuicStreamFrame data2(stream_id, false, 0, absl::string_view("HT")); session_.OnStreamFrame(data2); EXPECT_EQ(1, session_.num_incoming_streams_created()); } TEST_P(QuicSessionTestServer, PendingStreams) { if (!VersionUsesHttp3(transport_version())) { return; } CompleteHandshake(); session_.set_uses_pending_streams(true); QuicStreamId stream_id = QuicUtils::GetFirstUnidirectionalStreamId( transport_version(), Perspective::IS_CLIENT); QuicStreamFrame data1(stream_id, true, 10, absl::string_view("HT")); session_.OnStreamFrame(data1); EXPECT_TRUE(QuicSessionPeer::GetPendingStream(&session_, stream_id)); EXPECT_EQ(0, session_.num_incoming_streams_created()); QuicStreamFrame data2(stream_id, false, 0, absl::string_view("HT")); session_.OnStreamFrame(data2); EXPECT_FALSE(QuicSessionPeer::GetPendingStream(&session_, stream_id)); EXPECT_EQ(1, session_.num_incoming_streams_created()); } TEST_P(QuicSessionTestServer, BufferAllIncomingStreams) { if (!VersionUsesHttp3(transport_version())) { return; } session_.set_uses_pending_streams(true); QuicStreamId stream_id = QuicUtils::GetFirstUnidirectionalStreamId( transport_version(), Perspective::IS_CLIENT); QuicStreamFrame data1(stream_id, true, 10, absl::string_view("HT")); session_.OnStreamFrame(data1); EXPECT_TRUE(QuicSessionPeer::GetPendingStream(&session_, stream_id)); EXPECT_EQ(0, session_.num_incoming_streams_created()); QuicStreamFrame data2(stream_id, false, 0, absl::string_view("HT")); session_.OnStreamFrame(data2); EXPECT_TRUE(QuicSessionPeer::GetPendingStream(&session_, stream_id)); EXPECT_EQ(0, session_.num_incoming_streams_created()); QuicStreamId bidirectional_stream_id = QuicUtils::GetFirstBidirectionalStreamId(transport_version(), Perspective::IS_CLIENT); QuicStreamFrame data3(bidirectional_stream_id, false, 0, absl::string_view("HT")); session_.OnStreamFrame(data3); EXPECT_TRUE( QuicSessionPeer::GetPendingStream(&session_, bidirectional_stream_id)); EXPECT_EQ(0, session_.num_incoming_streams_created()); connection_->AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); session_.ProcessAllPendingStreams(); EXPECT_FALSE(QuicSessionPeer::GetPendingStream(&session_, stream_id)); EXPECT_FALSE( QuicSessionPeer::GetPendingStream(&session_, bidirectional_stream_id)); EXPECT_EQ(2, session_.num_incoming_streams_created()); EXPECT_EQ(1, QuicSessionPeer::GetStream(&session_, stream_id) ->pending_duration() .ToMilliseconds()); EXPECT_EQ(1, QuicSessionPeer::GetStream(&session_, bidirectional_stream_id) ->pending_duration() .ToMilliseconds()); EXPECT_EQ(2, session_.connection()->GetStats().num_total_pending_streams); } TEST_P(QuicSessionTestServer, RstPendingStreams) { if (!VersionUsesHttp3(transport_version())) { return; } session_.set_uses_pending_streams(true); QuicStreamId stream_id = QuicUtils::GetFirstUnidirectionalStreamId( transport_version(), Perspective::IS_CLIENT); QuicStreamFrame data1(stream_id, true, 10, absl::string_view("HT")); session_.OnStreamFrame(data1); EXPECT_TRUE(QuicSessionPeer::GetPendingStream(&session_, stream_id)); EXPECT_EQ(0, session_.num_incoming_streams_created()); EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(&session_)); QuicRstStreamFrame rst1(kInvalidControlFrameId, stream_id, QUIC_ERROR_PROCESSING_STREAM, 12); session_.OnRstStream(rst1); EXPECT_FALSE(QuicSessionPeer::GetPendingStream(&session_, stream_id)); EXPECT_EQ(0, session_.num_incoming_streams_created()); EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(&session_)); QuicStreamFrame data2(stream_id, false, 0, absl::string_view("HT")); session_.OnStreamFrame(data2); EXPECT_FALSE(QuicSessionPeer::GetPendingStream(&session_, stream_id)); EXPECT_EQ(0, session_.num_incoming_streams_created()); EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(&session_)); session_.ProcessAllPendingStreams(); QuicStreamId bidirectional_stream_id = QuicUtils::GetFirstBidirectionalStreamId(transport_version(), Perspective::IS_CLIENT); QuicStreamFrame data3(bidirectional_stream_id, false, 0, absl::string_view("HT")); session_.OnStreamFrame(data3); EXPECT_TRUE( QuicSessionPeer::GetPendingStream(&session_, bidirectional_stream_id)); EXPECT_EQ(0, session_.num_incoming_streams_created()); QuicRstStreamFrame rst2(kInvalidControlFrameId, bidirectional_stream_id, QUIC_ERROR_PROCESSING_STREAM, 12); session_.OnRstStream(rst2); EXPECT_FALSE( QuicSessionPeer::GetPendingStream(&session_, bidirectional_stream_id)); EXPECT_EQ(0, session_.num_incoming_streams_created()); EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(&session_)); } TEST_P(QuicSessionTestServer, OnFinPendingStreamsReadUnidirectional) { if (!VersionUsesHttp3(transport_version())) { return; } CompleteHandshake(); session_.set_uses_pending_streams(true); QuicStreamId stream_id = QuicUtils::GetFirstUnidirectionalStreamId( transport_version(), Perspective::IS_CLIENT); QuicStreamFrame data(stream_id, true, 0, ""); session_.OnStreamFrame(data); EXPECT_FALSE(QuicSessionPeer::GetPendingStream(&session_, stream_id)); EXPECT_EQ(0, session_.num_incoming_streams_created()); EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(&session_)); EXPECT_EQ(nullptr, QuicSessionPeer::GetStream(&session_, stream_id)); } TEST_P(QuicSessionTestServer, OnFinPendingStreamsBidirectional) { if (!VersionUsesHttp3(transport_version())) { return; } session_.set_uses_pending_streams(true); QuicStreamId bidirectional_stream_id = QuicUtils::GetFirstBidirectionalStreamId(transport_version(), Perspective::IS_CLIENT); QuicStreamFrame data2(bidirectional_stream_id, true, 0, absl::string_view("HT")); session_.OnStreamFrame(data2); EXPECT_TRUE( QuicSessionPeer::GetPendingStream(&session_, bidirectional_stream_id)); EXPECT_EQ(0, session_.num_incoming_streams_created()); session_.ProcessAllPendingStreams(); EXPECT_FALSE( QuicSessionPeer::GetPendingStream(&session_, bidirectional_stream_id)); EXPECT_EQ(1, session_.num_incoming_streams_created()); QuicStream* bidirectional_stream = QuicSessionPeer::GetStream(&session_, bidirectional_stream_id); EXPECT_TRUE(bidirectional_stream->fin_received()); } TEST_P(QuicSessionTestServer, UnidirectionalPendingStreamOnWindowUpdate) { if (!VersionUsesHttp3(transport_version())) { return; } session_.set_uses_pending_streams(true); QuicStreamId stream_id = QuicUtils::GetFirstUnidirectionalStreamId( transport_version(), Perspective::IS_CLIENT); QuicStreamFrame data1(stream_id, true, 10, absl::string_view("HT")); session_.OnStreamFrame(data1); EXPECT_TRUE(QuicSessionPeer::GetPendingStream(&session_, stream_id)); EXPECT_EQ(0, session_.num_incoming_streams_created()); QuicWindowUpdateFrame window_update_frame(kInvalidControlFrameId, stream_id, 0); EXPECT_CALL( *connection_, CloseConnection( QUIC_WINDOW_UPDATE_RECEIVED_ON_READ_UNIDIRECTIONAL_STREAM, "WindowUpdateFrame received on READ_UNIDIRECTIONAL stream.", _)); session_.OnWindowUpdateFrame(window_update_frame); } TEST_P(QuicSessionTestServer, BidirectionalPendingStreamOnWindowUpdate) { if (!VersionUsesHttp3(transport_version())) { return; } session_.set_uses_pending_streams(true); QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId( transport_version(), Perspective::IS_CLIENT); QuicStreamFrame data(stream_id, true, 10, absl::string_view("HT")); session_.OnStreamFrame(data); QuicWindowUpdateFrame window_update_frame(kInvalidControlFrameId, stream_id, kDefaultFlowControlSendWindow * 2); session_.OnWindowUpdateFrame(window_update_frame); EXPECT_TRUE(QuicSessionPeer::GetPendingStream(&session_, stream_id)); EXPECT_EQ(0, session_.num_incoming_streams_created()); session_.ProcessAllPendingStreams(); EXPECT_FALSE(QuicSessionPeer::GetPendingStream(&session_, stream_id)); EXPECT_EQ(1, session_.num_incoming_streams_created()); QuicStream* bidirectional_stream = QuicSessionPeer::GetStream(&session_, stream_id); QuicByteCount send_window = QuicStreamPeer::SendWindowSize(bidirectional_stream); EXPECT_EQ(send_window, kDefaultFlowControlSendWindow * 2); } TEST_P(QuicSessionTestServer, UnidirectionalPendingStreamOnStopSending) { if (!VersionUsesHttp3(transport_version())) { return; } session_.set_uses_pending_streams(true); QuicStreamId stream_id = QuicUtils::GetFirstUnidirectionalStreamId( transport_version(), Perspective::IS_CLIENT); QuicStreamFrame data1(stream_id, true, 10, absl::string_view("HT")); session_.OnStreamFrame(data1); EXPECT_TRUE(QuicSessionPeer::GetPendingStream(&session_, stream_id)); EXPECT_EQ(0, session_.num_incoming_streams_created()); QuicStopSendingFrame stop_sending_frame(kInvalidControlFrameId, stream_id, QUIC_STREAM_CANCELLED); EXPECT_CALL( *connection_, CloseConnection(QUIC_INVALID_STREAM_ID, "Received STOP_SENDING for a read-only stream", _)); session_.OnStopSendingFrame(stop_sending_frame); } TEST_P(QuicSessionTestServer, BidirectionalPendingStreamOnStopSending) { if (!VersionUsesHttp3(transport_version())) { return; } session_.set_uses_pending_streams(true); QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId( transport_version(), Perspective::IS_CLIENT); QuicStreamFrame data(stream_id, true, 0, absl::string_view("HT")); session_.OnStreamFrame(data); QuicStopSendingFrame stop_sending_frame(kInvalidControlFrameId, stream_id, QUIC_STREAM_CANCELLED); session_.OnStopSendingFrame(stop_sending_frame); EXPECT_TRUE(QuicSessionPeer::GetPendingStream(&session_, stream_id)); EXPECT_EQ(0, session_.num_incoming_streams_created()); EXPECT_CALL(*connection_, OnStreamReset(stream_id, _)); session_.ProcessAllPendingStreams(); EXPECT_FALSE(QuicSessionPeer::GetPendingStream(&session_, stream_id)); EXPECT_EQ(1, session_.num_incoming_streams_created()); QuicStream* bidirectional_stream = QuicSessionPeer::GetStream(&session_, stream_id); EXPECT_TRUE(bidirectional_stream->write_side_closed()); } TEST_P(QuicSessionTestServer, DrainingStreamsDoNotCountAsOpened) { CompleteHandshake(); if (VersionHasIetfQuicFrames(transport_version())) { 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(2 * kMaxStreams + 1); for (QuicStreamId i = kFirstStreamId; i < kFinalStreamId; i += QuicUtils::StreamIdDelta(connection_->transport_version())) { 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_)); QuicAlarm* alarm = QuicSessionPeer::GetStreamCountResetAlarm(&session_); if (alarm->IsSet()) { alarm_factory_.FireAlarm(alarm); } } } class QuicSessionTestClient : public QuicSessionTestBase { protected: QuicSessionTestClient() : QuicSessionTestBase(Perspective::IS_CLIENT, true) {} }; INSTANTIATE_TEST_SUITE_P(Tests, QuicSessionTestClient, ::testing::ValuesIn(AllSupportedVersions()), ::testing::PrintToStringParamName()); TEST_P(QuicSessionTestClient, AvailableBidirectionalStreamsClient) { 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(1))); } TEST_P(QuicSessionTestClient, DonotSendRetireCIDFrameWhenConnectionClosed) { if (!VersionHasIetfQuicFrames(transport_version())) { return; } connection_->ReallyCloseConnection(QUIC_NO_ERROR, "closing", ConnectionCloseBehavior::SILENT_CLOSE); EXPECT_FALSE(connection_->connected()); if (!GetQuicReloadableFlag( quic_no_write_control_frame_upon_connection_close2)) { EXPECT_QUIC_BUG(session_.SendRetireConnectionId(20), "Try to write control frame"); } else { session_.SendRetireConnectionId(20); } } TEST_P(QuicSessionTestClient, NewStreamCreationResumesMultiPortProbing) { if (!VersionHasIetfQuicFrames(transport_version())) { return; } session_.config()->SetClientConnectionOptions({kMPQC}); session_.Initialize(); connection_->CreateConnectionIdManager(); connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); connection_->OnHandshakeComplete(); session_.OnConfigNegotiated(); EXPECT_CALL(*connection_, MaybeProbeMultiPortPath()); session_.CreateOutgoingBidirectionalStream(); } TEST_P(QuicSessionTestClient, InvalidSessionFlowControlWindowInHandshake) { const uint32_t kInvalidWindow = kMinimumFlowControlSendWindow - 1; QuicConfigPeer::SetReceivedInitialSessionFlowControlWindow(session_.config(), kInvalidWindow); EXPECT_CALL( *connection_, CloseConnection(connection_->version().AllowsLowFlowControlLimits() ? QUIC_ZERO_RTT_RESUMPTION_LIMIT_REDUCED : QUIC_FLOW_CONTROL_INVALID_WINDOW, _, _)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); session_.OnConfigNegotiated(); } TEST_P(QuicSessionTestClient, InvalidBidiStreamLimitInHandshake) { if (!VersionHasIetfQuicFrames(transport_version())) { return; } QuicConfigPeer::SetReceivedMaxBidirectionalStreams( session_.config(), kDefaultMaxStreamsPerConnection - 1); EXPECT_CALL(*connection_, CloseConnection(QUIC_ZERO_RTT_RESUMPTION_LIMIT_REDUCED, _, _)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); session_.OnConfigNegotiated(); } TEST_P(QuicSessionTestClient, InvalidUniStreamLimitInHandshake) { if (!VersionHasIetfQuicFrames(transport_version())) { return; } QuicConfigPeer::SetReceivedMaxUnidirectionalStreams( session_.config(), kDefaultMaxStreamsPerConnection - 1); EXPECT_CALL(*connection_, CloseConnection(QUIC_ZERO_RTT_RESUMPTION_LIMIT_REDUCED, _, _)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); session_.OnConfigNegotiated(); } TEST_P(QuicSessionTestClient, InvalidStreamFlowControlWindowInHandshake) { if (!VersionHasIetfQuicFrames(transport_version())) { return; } session_.CreateOutgoingBidirectionalStream(); session_.CreateOutgoingBidirectionalStream(); QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesOutgoingBidirectional( session_.config(), kMinimumFlowControlSendWindow - 1); EXPECT_CALL(*connection_, CloseConnection(_, _, _)) .WillOnce( Invoke(connection_, &MockQuicConnection::ReallyCloseConnection)); EXPECT_CALL(*connection_, SendConnectionClosePacket(_, _, _)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); session_.OnConfigNegotiated(); } TEST_P(QuicSessionTestClient, OnMaxStreamFrame) { if (!VersionUsesHttp3(transport_version())) { return; } QuicMaxStreamsFrame frame; frame.unidirectional = false; frame.stream_count = 120; EXPECT_CALL(session_, OnCanCreateNewOutgoingStream(false)).Times(1); session_.OnMaxStreamsFrame(frame); QuicMaxStreamsFrame frame2; frame2.unidirectional = false; frame2.stream_count = 110; EXPECT_CALL(session_, OnCanCreateNewOutgoingStream(false)).Times(0); session_.OnMaxStreamsFrame(frame2); } TEST_P(QuicSessionTestClient, AvailableUnidirectionalStreamsClient) { ASSERT_TRUE(session_.GetOrCreateStream( GetNthServerInitiatedUnidirectionalId(2)) != nullptr); EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable( &session_, GetNthServerInitiatedUnidirectionalId(0))); EXPECT_TRUE(QuicSessionPeer::IsStreamAvailable( &session_, GetNthServerInitiatedUnidirectionalId(1))); ASSERT_TRUE(session_.GetOrCreateStream( GetNthServerInitiatedUnidirectionalId(0)) != nullptr); ASSERT_TRUE(session_.GetOrCreateStream( GetNthServerInitiatedUnidirectionalId(1)) != nullptr); EXPECT_FALSE(QuicSessionPeer::IsStreamAvailable( &session_, GetNthClientInitiatedUnidirectionalId(1))); } TEST_P(QuicSessionTestClient, RecordFinAfterReadSideClosed) { 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(QuicSessionTestClient, IncomingStreamWithClientInitiatedStreamId) { const QuicErrorCode expected_error = VersionHasIetfQuicFrames(transport_version()) ? QUIC_HTTP_STREAM_WRONG_DIRECTION : QUIC_INVALID_STREAM_ID; EXPECT_CALL( *connection_, CloseConnection(expected_error, "Data for nonexistent stream", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET)); QuicStreamFrame frame(GetNthClientInitiatedBidirectionalId(1), false, 0, absl::string_view("foo")); session_.OnStreamFrame(frame); } TEST_P(QuicSessionTestClient, MinAckDelaySetOnTheClientQuicConfig) { if (!session_.version().HasIetfQuicFrames()) { return; } session_.config()->SetClientConnectionOptions({kAFFE}); session_.Initialize(); ASSERT_EQ(session_.config()->GetMinAckDelayToSendMs(), kDefaultMinAckDelayTimeMs); ASSERT_TRUE(session_.connection()->can_receive_ack_frequency_frame()); } TEST_P(QuicSessionTestClient, FailedToCreateStreamIfTooCloseToIdleTimeout) { connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); EXPECT_TRUE(session_.CanOpenNextOutgoingBidirectionalStream()); QuicTime deadline = QuicConnectionPeer::GetIdleNetworkDeadline(connection_); ASSERT_TRUE(deadline.IsInitialized()); QuicTime::Delta timeout = deadline - helper_.GetClock()->ApproximateNow(); connection_->AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(1)); EXPECT_CALL(*connection_, SendConnectivityProbingPacket(_, _)).Times(1); EXPECT_FALSE(session_.CanOpenNextOutgoingBidirectionalStream()); EXPECT_CALL(session_, OnCanCreateNewOutgoingStream(false)); QuicConnectionPeer::GetIdleNetworkDetector(connection_) .OnPacketReceived(helper_.GetClock()->ApproximateNow()); session_.OnPacketDecrypted(ENCRYPTION_FORWARD_SECURE); EXPECT_TRUE(session_.CanOpenNextOutgoingBidirectionalStream()); } TEST_P(QuicSessionTestServer, ZombieStreams) { CompleteHandshake(); TestStream* stream2 = session_.CreateOutgoingBidirectionalStream(); QuicStreamPeer::SetStreamBytesWritten(3, stream2); EXPECT_TRUE(stream2->IsWaitingForAcks()); CloseStream(stream2->id()); ASSERT_EQ(1u, session_.closed_streams()->size()); EXPECT_EQ(stream2->id(), session_.closed_streams()->front()->id()); session_.MaybeCloseZombieStream(stream2->id()); EXPECT_EQ(1u, session_.closed_streams()->size()); EXPECT_EQ(stream2->id(), session_.closed_streams()->front()->id()); } TEST_P(QuicSessionTestServer, RstStreamReceivedAfterRstStreamSent) { CompleteHandshake(); TestStream* stream2 = session_.CreateOutgoingBidirectionalStream(); QuicStreamPeer::SetStreamBytesWritten(3, stream2); EXPECT_TRUE(stream2->IsWaitingForAcks()); EXPECT_CALL(*connection_, SendControlFrame(_)); EXPECT_CALL(*connection_, OnStreamReset(stream2->id(), _)); EXPECT_CALL(session_, OnCanCreateNewOutgoingStream(false)).Times(0); stream2->Reset(quic::QUIC_STREAM_CANCELLED); QuicRstStreamFrame rst1(kInvalidControlFrameId, stream2->id(), QUIC_ERROR_PROCESSING_STREAM, 0); if (!VersionHasIetfQuicFrames(transport_version())) { EXPECT_CALL(session_, OnCanCreateNewOutgoingStream(false)).Times(1); } session_.OnRstStream(rst1); } TEST_P(QuicSessionTestServer, TestZombieStreams) { CompleteHandshake(); session_.set_writev_consumes_all_data(true); TestStream* stream2 = session_.CreateOutgoingBidirectionalStream(); std::string body(100, '.'); stream2->WriteOrBufferData(body, false, nullptr); EXPECT_TRUE(stream2->IsWaitingForAcks()); EXPECT_EQ(1u, QuicStreamPeer::SendBuffer(stream2).size()); QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream2->id(), QUIC_STREAM_CANCELLED, 1234); EXPECT_CALL(*connection_, SendControlFrame(_)) .WillOnce(Invoke(&ClearControlFrame)); if (VersionHasIetfQuicFrames(transport_version())) { EXPECT_CALL(*connection_, OnStreamReset(stream2->id(), QUIC_STREAM_CANCELLED)); } else { EXPECT_CALL(*connection_, OnStreamReset(stream2->id(), QUIC_RST_ACKNOWLEDGEMENT)); } stream2->OnStreamReset(rst_frame); if (VersionHasIetfQuicFrames(transport_version())) { QuicStopSendingFrame frame(kInvalidControlFrameId, stream2->id(), QUIC_STREAM_CANCELLED); EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); session_.OnStopSendingFrame(frame); } ASSERT_EQ(1u, session_.closed_streams()->size()); EXPECT_EQ(stream2->id(), session_.closed_streams()->front()->id()); TestStream* stream4 = session_.CreateOutgoingBidirectionalStream(); if (VersionHasIetfQuicFrames(transport_version())) { EXPECT_CALL(*connection_, SendControlFrame(_)) .Times(2) .WillRepeatedly(Invoke(&ClearControlFrame)); } else { EXPECT_CALL(*connection_, SendControlFrame(_)).Times(1); } EXPECT_CALL(*connection_, OnStreamReset(stream4->id(), QUIC_STREAM_CANCELLED)); stream4->WriteOrBufferData(body, false, nullptr); stream4->Reset(QUIC_STREAM_CANCELLED); EXPECT_EQ(2u, session_.closed_streams()->size()); } TEST_P(QuicSessionTestServer, OnStreamFrameLost) { 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 frame1; if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { frame1 = QuicStreamFrame( QuicUtils::GetCryptoStreamId(connection_->transport_version()), false, 0, 1300); } QuicStreamFrame frame2(stream2->id(), false, 0, 9); QuicStreamFrame frame3(stream4->id(), false, 0, 9); EXPECT_CALL(*stream4, HasPendingRetransmission()).WillOnce(Return(true)); if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { EXPECT_CALL(*crypto_stream, HasPendingRetransmission()) .WillOnce(Return(true)); } EXPECT_CALL(*stream2, HasPendingRetransmission()).WillOnce(Return(true)); session_.OnFrameLost(QuicFrame(frame3)); if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { 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(connection_->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(QuicSessionTestServer, DonotRetransmitDataOfClosedStreams) { CompleteHandshake(); 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(QuicSessionTestServer, RetransmitFrames) { 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(QuicSessionTestServer, RetransmitLostDataCausesConnectionClose) { CompleteHandshake(); TestStream* stream = session_.CreateOutgoingBidirectionalStream(); QuicStreamFrame frame(stream->id(), false, 0, 9); EXPECT_CALL(*stream, HasPendingRetransmission()) .Times(2) .WillOnce(Return(true)) .WillOnce(Return(false)); session_.OnFrameLost(QuicFrame(frame)); EXPECT_CALL(*stream, OnCanWrite()).WillOnce(Invoke([this, stream]() { session_.ResetStream(stream->id(), QUIC_STREAM_CANCELLED); })); if (VersionHasIetfQuicFrames(transport_version())) { EXPECT_CALL(*connection_, SendControlFrame(_)) .Times(2) .WillRepeatedly(Invoke(&session_, &TestSession::SaveFrame)); } else { EXPECT_CALL(*connection_, SendControlFrame(_)) .WillOnce(Invoke(&session_, &TestSession::SaveFrame)); } EXPECT_CALL(*connection_, OnStreamReset(stream->id(), _)); session_.OnCanWrite(); } TEST_P(QuicSessionTestServer, SendMessage) { EXPECT_FALSE(session_.OneRttKeysAvailable()); EXPECT_EQ(MessageResult(MESSAGE_STATUS_ENCRYPTION_NOT_ESTABLISHED, 0), session_.SendMessage(MemSliceFromString(""))); CompleteHandshake(); EXPECT_TRUE(session_.OneRttKeysAvailable()); EXPECT_CALL(*connection_, SendMessage(1, _, false)) .WillOnce(Return(MESSAGE_STATUS_SUCCESS)); EXPECT_EQ(MessageResult(MESSAGE_STATUS_SUCCESS, 1), session_.SendMessage(MemSliceFromString(""))); EXPECT_CALL(*connection_, SendMessage(2, _, false)) .WillOnce(Return(MESSAGE_STATUS_TOO_LARGE)); EXPECT_EQ(MessageResult(MESSAGE_STATUS_TOO_LARGE, 0), session_.SendMessage(MemSliceFromString(""))); EXPECT_CALL(*connection_, SendMessage(2, _, false)) .WillOnce(Return(MESSAGE_STATUS_SUCCESS)); EXPECT_EQ(MessageResult(MESSAGE_STATUS_SUCCESS, 2), session_.SendMessage(MemSliceFromString(""))); QuicMessageFrame frame(1); QuicMessageFrame frame2(2); EXPECT_FALSE(session_.IsFrameOutstanding(QuicFrame(&frame))); EXPECT_FALSE(session_.IsFrameOutstanding(QuicFrame(&frame2))); session_.OnMessageLost(2); EXPECT_FALSE(session_.IsFrameOutstanding(QuicFrame(&frame2))); session_.OnMessageAcked(1, QuicTime::Zero()); EXPECT_FALSE(session_.IsFrameOutstanding(QuicFrame(&frame))); } TEST_P(QuicSessionTestServer, LocallyResetZombieStreams) { CompleteHandshake(); session_.set_writev_consumes_all_data(true); TestStream* stream2 = session_.CreateOutgoingBidirectionalStream(); std::string body(100, '.'); QuicStreamPeer::CloseReadSide(stream2); stream2->WriteOrBufferData(body, true, nullptr); EXPECT_TRUE(stream2->IsWaitingForAcks()); auto& stream_map = QuicSessionPeer::stream_map(&session_); ASSERT_TRUE(stream_map.contains(stream2->id())); auto* stream = stream_map.find(stream2->id())->second.get(); EXPECT_TRUE(stream->IsZombie()); QuicStreamFrame frame(stream2->id(), true, 0, 100); EXPECT_CALL(*stream2, HasPendingRetransmission()) .WillRepeatedly(Return(true)); session_.OnFrameLost(QuicFrame(frame)); EXPECT_CALL(*connection_, SendControlFrame(_)) .WillRepeatedly(Invoke(&ClearControlFrame)); EXPECT_CALL(*connection_, OnStreamReset(stream2->id(), _)); stream2->Reset(QUIC_STREAM_CANCELLED); EXPECT_TRUE(session_.IsClosedStream(stream2->id())); EXPECT_CALL(*stream2, OnCanWrite()).Times(0); session_.OnCanWrite(); } TEST_P(QuicSessionTestServer, CleanUpClosedStreamsAlarm) { CompleteHandshake(); EXPECT_FALSE( QuicSessionPeer::GetCleanUpClosedStreamsAlarm(&session_)->IsSet()); session_.set_writev_consumes_all_data(true); TestStream* stream2 = session_.CreateOutgoingBidirectionalStream(); EXPECT_FALSE(stream2->IsWaitingForAcks()); CloseStream(stream2->id()); EXPECT_EQ(1u, session_.closed_streams()->size()); EXPECT_TRUE( QuicSessionPeer::GetCleanUpClosedStreamsAlarm(&session_)->IsSet()); alarm_factory_.FireAlarm( QuicSessionPeer::GetCleanUpClosedStreamsAlarm(&session_)); EXPECT_TRUE(session_.closed_streams()->empty()); } TEST_P(QuicSessionTestServer, WriteUnidirectionalStream) { session_.set_writev_consumes_all_data(true); TestStream* stream4 = new TestStream(GetNthServerInitiatedUnidirectionalId(1), &session_, WRITE_UNIDIRECTIONAL); session_.ActivateStream(absl::WrapUnique(stream4)); std::string body(100, '.'); stream4->WriteOrBufferData(body, false, nullptr); stream4->WriteOrBufferData(body, true, nullptr); auto& stream_map = QuicSessionPeer::stream_map(&session_); ASSERT_TRUE(stream_map.contains(stream4->id())); auto* stream = stream_map.find(stream4->id())->second.get(); EXPECT_TRUE(stream->IsZombie()); } TEST_P(QuicSessionTestServer, ReceivedDataOnWriteUnidirectionalStream) { TestStream* stream4 = new TestStream(GetNthServerInitiatedUnidirectionalId(1), &session_, WRITE_UNIDIRECTIONAL); session_.ActivateStream(absl::WrapUnique(stream4)); EXPECT_CALL( *connection_, CloseConnection(QUIC_DATA_RECEIVED_ON_WRITE_UNIDIRECTIONAL_STREAM, _, _)) .Times(1); QuicStreamFrame stream_frame(GetNthServerInitiatedUnidirectionalId(1), false, 0, 2); session_.OnStreamFrame(stream_frame); } TEST_P(QuicSessionTestServer, ReadUnidirectionalStream) { TestStream* stream4 = new TestStream(GetNthClientInitiatedUnidirectionalId(1), &session_, READ_UNIDIRECTIONAL); session_.ActivateStream(absl::WrapUnique(stream4)); EXPECT_FALSE(stream4->IsWaitingForAcks()); stream4->StopReading(); std::string data(100, '.'); QuicStreamFrame stream_frame(GetNthClientInitiatedUnidirectionalId(1), false, 0, data); stream4->OnStreamFrame(stream_frame); EXPECT_TRUE(session_.closed_streams()->empty()); QuicStreamFrame stream_frame2(GetNthClientInitiatedUnidirectionalId(1), true, 100, data); stream4->OnStreamFrame(stream_frame2); EXPECT_EQ(1u, session_.closed_streams()->size()); } TEST_P(QuicSessionTestServer, WriteOrBufferDataOnReadUnidirectionalStream) { TestStream* stream4 = new TestStream(GetNthClientInitiatedUnidirectionalId(1), &session_, READ_UNIDIRECTIONAL); session_.ActivateStream(absl::WrapUnique(stream4)); EXPECT_CALL(*connection_, CloseConnection( QUIC_TRY_TO_WRITE_DATA_ON_READ_UNIDIRECTIONAL_STREAM, _, _)) .Times(1); std::string body(100, '.'); stream4->WriteOrBufferData(body, false, nullptr); } TEST_P(QuicSessionTestServer, WritevDataOnReadUnidirectionalStream) { TestStream* stream4 = new TestStream(GetNthClientInitiatedUnidirectionalId(1), &session_, READ_UNIDIRECTIONAL); session_.ActivateStream(absl::WrapUnique(stream4)); EXPECT_CALL(*connection_, CloseConnection( QUIC_TRY_TO_WRITE_DATA_ON_READ_UNIDIRECTIONAL_STREAM, _, _)) .Times(1); std::string body(100, '.'); struct iovec iov = {const_cast<char*>(body.data()), body.length()}; quiche::QuicheMemSliceStorage storage( &iov, 1, session_.connection()->helper()->GetStreamSendBufferAllocator(), 1024); stream4->WriteMemSlices(storage.ToSpan(), false); } TEST_P(QuicSessionTestServer, WriteMemSlicesOnReadUnidirectionalStream) { TestStream* stream4 = new TestStream(GetNthClientInitiatedUnidirectionalId(1), &session_, READ_UNIDIRECTIONAL); session_.ActivateStream(absl::WrapUnique(stream4)); EXPECT_CALL(*connection_, CloseConnection( QUIC_TRY_TO_WRITE_DATA_ON_READ_UNIDIRECTIONAL_STREAM, _, _)) .Times(1); std::string data(1024, 'a'); std::vector<quiche::QuicheMemSlice> buffers; buffers.push_back(MemSliceFromString(data)); buffers.push_back(MemSliceFromString(data)); stream4->WriteMemSlices(absl::MakeSpan(buffers), false); } TEST_P(QuicSessionTestServer, NewStreamIdBelowLimit) { if (!VersionHasIetfQuicFrames(transport_version())) { return; } QuicStreamId bidirectional_stream_id = StreamCountToId( QuicSessionPeer::ietf_streamid_manager(&session_) ->advertised_max_incoming_bidirectional_streams() - 1, Perspective::IS_CLIENT, true); QuicStreamFrame bidirectional_stream_frame(bidirectional_stream_id, false, 0, "Random String"); EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); session_.OnStreamFrame(bidirectional_stream_frame); QuicStreamId unidirectional_stream_id = StreamCountToId( QuicSessionPeer::ietf_streamid_manager(&session_) ->advertised_max_incoming_unidirectional_streams() - 1, Perspective::IS_CLIENT, false); QuicStreamFrame unidirectional_stream_frame(unidirectional_stream_id, false, 0, "Random String"); EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); session_.OnStreamFrame(unidirectional_stream_frame); } TEST_P(QuicSessionTestServer, NewStreamIdAtLimit) { if (!VersionHasIetfQuicFrames(transport_version())) { return; } QuicStreamId bidirectional_stream_id = StreamCountToId(QuicSessionPeer::ietf_streamid_manager(&session_) ->advertised_max_incoming_bidirectional_streams(), Perspective::IS_CLIENT, true); QuicStreamFrame bidirectional_stream_frame(bidirectional_stream_id, false, 0, "Random String"); EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); session_.OnStreamFrame(bidirectional_stream_frame); QuicStreamId unidirectional_stream_id = StreamCountToId(QuicSessionPeer::ietf_streamid_manager(&session_) ->advertised_max_incoming_unidirectional_streams(), Perspective::IS_CLIENT, false); QuicStreamFrame unidirectional_stream_frame(unidirectional_stream_id, false, 0, "Random String"); EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); session_.OnStreamFrame(unidirectional_stream_frame); } TEST_P(QuicSessionTestServer, NewStreamIdAboveLimit) { if (!VersionHasIetfQuicFrames(transport_version())) { return; } QuicStreamId bidirectional_stream_id = StreamCountToId( QuicSessionPeer::ietf_streamid_manager(&session_) ->advertised_max_incoming_bidirectional_streams() + 1, Perspective::IS_CLIENT, true); QuicStreamFrame bidirectional_stream_frame(bidirectional_stream_id, false, 0, "Random String"); EXPECT_CALL( *connection_, CloseConnection(QUIC_INVALID_STREAM_ID, "Stream id 400 would exceed stream count limit 100", _)); session_.OnStreamFrame(bidirectional_stream_frame); QuicStreamId unidirectional_stream_id = StreamCountToId( QuicSessionPeer::ietf_streamid_manager(&session_) ->advertised_max_incoming_unidirectional_streams() + 1, Perspective::IS_CLIENT, false); QuicStreamFrame unidirectional_stream_frame(unidirectional_stream_id, false, 0, "Random String"); EXPECT_CALL( *connection_, CloseConnection(QUIC_INVALID_STREAM_ID, "Stream id 402 would exceed stream count limit 100", _)); session_.OnStreamFrame(unidirectional_stream_frame); } TEST_P(QuicSessionTestServer, OnStopSendingInvalidStreamId) { if (!VersionHasIetfQuicFrames(transport_version())) { return; } QuicStopSendingFrame frame(1, -1, QUIC_STREAM_CANCELLED); EXPECT_CALL( *connection_, CloseConnection(QUIC_INVALID_STREAM_ID, "Received STOP_SENDING for an invalid stream", _)); session_.OnStopSendingFrame(frame); } TEST_P(QuicSessionTestServer, OnStopSendingReadUnidirectional) { if (!VersionHasIetfQuicFrames(transport_version())) { return; } QuicStopSendingFrame frame(1, GetNthClientInitiatedUnidirectionalId(1), QUIC_STREAM_CANCELLED); EXPECT_CALL( *connection_, CloseConnection(QUIC_INVALID_STREAM_ID, "Received STOP_SENDING for a read-only stream", _)); session_.OnStopSendingFrame(frame); } TEST_P(QuicSessionTestServer, OnStopSendingStaticStreams) { if (!VersionHasIetfQuicFrames(transport_version())) { return; } QuicStreamId stream_id = 0; std::unique_ptr<TestStream> fake_static_stream = std::make_unique<TestStream>( stream_id, &session_, true, BIDIRECTIONAL); QuicSessionPeer::ActivateStream(&session_, std::move(fake_static_stream)); QuicStopSendingFrame frame(1, stream_id, QUIC_STREAM_CANCELLED); EXPECT_CALL(*connection_, CloseConnection(QUIC_INVALID_STREAM_ID, "Received STOP_SENDING for a static stream", _)); session_.OnStopSendingFrame(frame); } TEST_P(QuicSessionTestServer, OnStopSendingForWriteClosedStream) { if (!VersionHasIetfQuicFrames(transport_version())) { return; } TestStream* stream = session_.CreateOutgoingBidirectionalStream(); QuicStreamId stream_id = stream->id(); QuicStreamPeer::SetFinSent(stream); stream->CloseWriteSide(); EXPECT_TRUE(stream->write_side_closed()); QuicStopSendingFrame frame(1, stream_id, QUIC_STREAM_CANCELLED); EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); session_.OnStopSendingFrame(frame); } TEST_P(QuicSessionTestServer, OnStopSendingForZombieStreams) { if (!VersionHasIetfQuicFrames(transport_version())) { return; } CompleteHandshake(); session_.set_writev_consumes_all_data(true); TestStream* stream = session_.CreateOutgoingBidirectionalStream(); std::string body(100, '.'); QuicStreamPeer::CloseReadSide(stream); stream->WriteOrBufferData(body, true, nullptr); EXPECT_TRUE(stream->IsWaitingForAcks()); EXPECT_TRUE(stream->IsZombie()); ASSERT_EQ(0u, session_.closed_streams()->size()); QuicStopSendingFrame frame(1, stream->id(), QUIC_STREAM_CANCELLED); EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); if (GetQuicReloadableFlag(quic_deliver_stop_sending_to_zombie_streams)) { EXPECT_CALL(*connection_, SendControlFrame(_)).Times(1); EXPECT_CALL(*connection_, OnStreamReset(_, _)).Times(1); } else { EXPECT_CALL(*connection_, SendControlFrame(_)).Times(0); EXPECT_CALL(*connection_, OnStreamReset(_, _)).Times(0); } session_.OnStopSendingFrame(frame); if (GetQuicReloadableFlag(quic_deliver_stop_sending_to_zombie_streams)) { EXPECT_FALSE(stream->IsZombie()); EXPECT_EQ(1u, session_.closed_streams()->size()); } else { EXPECT_TRUE(stream->IsZombie()); EXPECT_EQ(0u, session_.closed_streams()->size()); } } TEST_P(QuicSessionTestServer, OnStopSendingClosedStream) { if (!VersionHasIetfQuicFrames(transport_version())) { return; } CompleteHandshake(); TestStream* stream = session_.CreateOutgoingBidirectionalStream(); QuicStreamId stream_id = stream->id(); CloseStream(stream_id); QuicStopSendingFrame frame(1, stream_id, QUIC_STREAM_CANCELLED); EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); session_.OnStopSendingFrame(frame); } TEST_P(QuicSessionTestServer, OnStopSendingInputNonExistentLocalStream) { if (!VersionHasIetfQuicFrames(transport_version())) { return; } QuicStopSendingFrame frame(1, GetNthServerInitiatedBidirectionalId(123456), QUIC_STREAM_CANCELLED); EXPECT_CALL(*connection_, CloseConnection(QUIC_HTTP_STREAM_WRONG_DIRECTION, "Data for nonexistent stream", _)) .Times(1); session_.OnStopSendingFrame(frame); } TEST_P(QuicSessionTestServer, OnStopSendingNewStream) { CompleteHandshake(); if (!VersionHasIetfQuicFrames(transport_version())) { return; } QuicStopSendingFrame frame(1, GetNthClientInitiatedBidirectionalId(1), QUIC_STREAM_CANCELLED); EXPECT_CALL(*connection_, SendControlFrame(_)).Times(1); EXPECT_CALL(*connection_, OnStreamReset(_, _)).Times(1); session_.OnStopSendingFrame(frame); QuicStream* stream = session_.GetOrCreateStream(GetNthClientInitiatedBidirectionalId(1)); EXPECT_TRUE(stream); EXPECT_TRUE(stream->write_side_closed()); } TEST_P(QuicSessionTestServer, OnStopSendingInputValidStream) { CompleteHandshake(); if (!VersionHasIetfQuicFrames(transport_version())) { return; } TestStream* stream = session_.CreateOutgoingBidirectionalStream(); EXPECT_FALSE(stream->write_side_closed()); EXPECT_FALSE(QuicStreamPeer::read_side_closed(stream)); QuicStreamId stream_id = stream->id(); QuicStopSendingFrame frame(1, stream_id, QUIC_STREAM_CANCELLED); EXPECT_CALL(*connection_, SendControlFrame(_)); EXPECT_CALL(*connection_, OnStreamReset(stream_id, QUIC_STREAM_CANCELLED)); EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); session_.OnStopSendingFrame(frame); EXPECT_FALSE(QuicStreamPeer::read_side_closed(stream)); EXPECT_TRUE(stream->write_side_closed()); } TEST_P(QuicSessionTestServer, WriteBufferedCryptoFrames) { if (!QuicVersionUsesCryptoFrames(connection_->transport_version())) { return; } std::string data(1350, 'a'); TestCryptoStream* crypto_stream = session_.GetMutableCryptoStream(); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0)) .WillOnce(Return(1000)); crypto_stream->WriteCryptoData(ENCRYPTION_INITIAL, data); EXPECT_TRUE(session_.HasPendingHandshake()); EXPECT_TRUE(session_.WillingAndAbleToWrite()); EXPECT_CALL(*connection_, SendCryptoData(_, _, _)).Times(0); connection_->SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<NullEncrypter>(connection_->perspective())); crypto_stream->WriteCryptoData(ENCRYPTION_ZERO_RTT, data); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 350, 1000)) .WillOnce(Return(350)); EXPECT_CALL( *connection_, SendCryptoData(crypto_stream->GetEncryptionLevelToSendCryptoDataOfSpace( QuicUtils::GetPacketNumberSpace(ENCRYPTION_ZERO_RTT)), 1350, 0)) .WillOnce(Return(1350)); session_.OnCanWrite(); EXPECT_FALSE(session_.HasPendingHandshake()); EXPECT_FALSE(session_.WillingAndAbleToWrite()); } TEST_P(QuicSessionTestServer, StreamFrameReceivedAfterFin) { TestStream* stream = session_.CreateOutgoingBidirectionalStream(); QuicStreamFrame frame(stream->id(), true, 0, ","); session_.OnStreamFrame(frame); QuicStreamFrame frame1(stream->id(), false, 1, ","); EXPECT_CALL(*connection_, CloseConnection(QUIC_STREAM_DATA_BEYOND_CLOSE_OFFSET, _, _)); session_.OnStreamFrame(frame1); } TEST_P(QuicSessionTestServer, ResetForIETFStreamTypes) { CompleteHandshake(); if (!VersionHasIetfQuicFrames(transport_version())) { return; } QuicStreamId read_only = GetNthClientInitiatedUnidirectionalId(0); EXPECT_CALL(*connection_, SendControlFrame(_)) .Times(1) .WillOnce(Invoke(&ClearControlFrame)); EXPECT_CALL(*connection_, OnStreamReset(read_only, _)); session_.ResetStream(read_only, QUIC_STREAM_CANCELLED); QuicStreamId write_only = GetNthServerInitiatedUnidirectionalId(0); EXPECT_CALL(*connection_, SendControlFrame(_)) .Times(1) .WillOnce(Invoke(&ClearControlFrame)); EXPECT_CALL(*connection_, OnStreamReset(write_only, _)); session_.ResetStream(write_only, QUIC_STREAM_CANCELLED); QuicStreamId bidirectional = GetNthClientInitiatedBidirectionalId(0); EXPECT_CALL(*connection_, SendControlFrame(_)) .Times(2) .WillRepeatedly(Invoke(&ClearControlFrame)); EXPECT_CALL(*connection_, OnStreamReset(bidirectional, _)); session_.ResetStream(bidirectional, QUIC_STREAM_CANCELLED); } TEST_P(QuicSessionTestServer, DecryptionKeyAvailableBeforeEncryptionKey) { if (connection_->version().handshake_protocol != PROTOCOL_TLS1_3) { return; } ASSERT_FALSE(connection_->framer().HasEncrypterOfEncryptionLevel( ENCRYPTION_HANDSHAKE)); EXPECT_FALSE(session_.OnNewDecryptionKeyAvailable( ENCRYPTION_HANDSHAKE, nullptr, false, false)); } TEST_P(QuicSessionTestServer, IncomingStreamWithServerInitiatedStreamId) { const QuicErrorCode expected_error = VersionHasIetfQuicFrames(transport_version()) ? QUIC_HTTP_STREAM_WRONG_DIRECTION : QUIC_INVALID_STREAM_ID; EXPECT_CALL( *connection_, CloseConnection(expected_error, "Data for nonexistent stream", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET)); QuicStreamFrame frame(GetNthServerInitiatedBidirectionalId(1), false, 0, absl::string_view("foo")); session_.OnStreamFrame(frame); } TEST_P(QuicSessionTestServer, BlockedFrameCausesWriteError) { CompleteHandshake(); MockPacketWriter* writer = static_cast<MockPacketWriter*>( QuicConnectionPeer::GetWriter(session_.connection())); EXPECT_CALL(*writer, WritePacket(_, _, _, _, _, _)) .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 0))); const uint64_t kWindow = 36; QuicFlowControllerPeer::SetSendWindowOffset(session_.flow_controller(), kWindow); auto stream = session_.GetOrCreateStream(GetNthClientInitiatedBidirectionalId(0)); const uint64_t kOverflow = 15; std::string body(kWindow + kOverflow, 'a'); EXPECT_CALL(*connection_, SendControlFrame(_)) .WillOnce(testing::InvokeWithoutArgs([this]() { connection_->ReallyCloseConnection( QUIC_PACKET_WRITE_ERROR, "write error", ConnectionCloseBehavior::SILENT_CLOSE); return false; })); stream->WriteOrBufferData(body, false, nullptr); } TEST_P(QuicSessionTestServer, BufferedCryptoFrameCausesWriteError) { if (!VersionHasIetfQuicFrames(transport_version())) { return; } std::string data(1350, 'a'); TestCryptoStream* crypto_stream = session_.GetMutableCryptoStream(); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_FORWARD_SECURE, 1350, 0)) .WillOnce(Return(1000)); crypto_stream->WriteCryptoData(ENCRYPTION_FORWARD_SECURE, data); EXPECT_TRUE(session_.HasPendingHandshake()); EXPECT_TRUE(session_.WillingAndAbleToWrite()); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_FORWARD_SECURE, 350, 1000)) .WillOnce(Return(0)); EXPECT_CALL(*connection_, SendControlFrame(_)).WillOnce(Return(false)); CryptoHandshakeMessage msg; session_.GetMutableCryptoStream()->OnHandshakeMessage(msg); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_FORWARD_SECURE, 350, 1000)) .WillOnce(testing::InvokeWithoutArgs([this]() { connection_->ReallyCloseConnection( QUIC_PACKET_WRITE_ERROR, "write error", ConnectionCloseBehavior::SILENT_CLOSE); return 350; })); if (!GetQuicReloadableFlag( quic_no_write_control_frame_upon_connection_close)) { EXPECT_CALL(*connection_, SendControlFrame(_)).WillOnce(Return(false)); EXPECT_QUIC_BUG(session_.OnCanWrite(), "Try to write control frame"); } else { session_.OnCanWrite(); } } TEST_P(QuicSessionTestServer, DonotPtoStreamDataBeforeHandshakeConfirmed) { if (!session_.version().UsesTls()) { return; } EXPECT_NE(HANDSHAKE_CONFIRMED, session_.GetHandshakeState()); TestCryptoStream* crypto_stream = session_.GetMutableCryptoStream(); EXPECT_FALSE(crypto_stream->HasBufferedCryptoFrames()); std::string data(1350, 'a'); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, 1350, 0)) .WillOnce(Return(1000)); crypto_stream->WriteCryptoData(ENCRYPTION_INITIAL, data); ASSERT_TRUE(crypto_stream->HasBufferedCryptoFrames()); TestStream* stream = session_.CreateOutgoingBidirectionalStream(); session_.MarkConnectionLevelWriteBlocked(stream->id()); EXPECT_CALL(*connection_, SendCryptoData(ENCRYPTION_INITIAL, _, _)) .WillOnce(Return(350)); EXPECT_CALL(*stream, OnCanWrite()).Times(0); QuicConnectionPeer::SetInProbeTimeOut(connection_, true); session_.OnCanWrite(); EXPECT_FALSE(crypto_stream->HasBufferedCryptoFrames()); } TEST_P(QuicSessionTestServer, SetStatelessResetTokenToSend) { if (!session_.version().HasIetfQuicFrames()) { return; } EXPECT_TRUE(session_.config()->HasStatelessResetTokenToSend()); } TEST_P(QuicSessionTestServer, SetServerPreferredAddressAccordingToAddressFamily) { if (!session_.version().HasIetfQuicFrames()) { return; } EXPECT_EQ(quiche::IpAddressFamily::IP_V4, connection_->peer_address().host().address_family()); QuicConnectionPeer::SetEffectivePeerAddress(connection_, connection_->peer_address()); QuicTagVector copt; copt.push_back(kSPAD); QuicConfigPeer::SetReceivedConnectionOptions(session_.config(), copt); QuicSocketAddress preferred_address(QuicIpAddress::Loopback4(), 12345); session_.config()->SetIPv4AlternateServerAddressToSend(preferred_address); session_.config()->SetIPv6AlternateServerAddressToSend( QuicSocketAddress(QuicIpAddress::Loopback6(), 12345)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); session_.OnConfigNegotiated(); EXPECT_EQ(QuicSocketAddress(QuicIpAddress::Loopback4(), 12345), session_.config() ->GetPreferredAddressToSend(quiche::IpAddressFamily::IP_V4) .value()); EXPECT_FALSE(session_.config() ->GetPreferredAddressToSend(quiche::IpAddressFamily::IP_V6) .has_value()); EXPECT_EQ(preferred_address, connection_->expected_server_preferred_address()); } TEST_P(QuicSessionTestServer, SetDNatServerPreferredAddressAccordingToAddressFamily) { if (!session_.version().HasIetfQuicFrames()) { return; } EXPECT_EQ(quiche::IpAddressFamily::IP_V4, connection_->peer_address().host().address_family()); QuicConnectionPeer::SetEffectivePeerAddress(connection_, connection_->peer_address()); QuicTagVector copt; copt.push_back(kSPAD); QuicConfigPeer::SetReceivedConnectionOptions(session_.config(), copt); QuicSocketAddress sent_preferred_address(QuicIpAddress::Loopback4(), 12345); QuicSocketAddress expected_preferred_address(QuicIpAddress::Loopback4(), 12346); session_.config()->SetIPv4AlternateServerAddressForDNat( sent_preferred_address, expected_preferred_address); session_.config()->SetIPv6AlternateServerAddressForDNat( QuicSocketAddress(QuicIpAddress::Loopback6(), 12345), QuicSocketAddress(QuicIpAddress::Loopback6(), 12346)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); session_.OnConfigNegotiated(); EXPECT_EQ(QuicSocketAddress(QuicIpAddress::Loopback4(), 12345), session_.config() ->GetPreferredAddressToSend(quiche::IpAddressFamily::IP_V4) .value()); EXPECT_FALSE(session_.config() ->GetPreferredAddressToSend(quiche::IpAddressFamily::IP_V6) .has_value()); EXPECT_EQ(expected_preferred_address, connection_->expected_server_preferred_address()); } TEST_P(QuicSessionTestServer, NoServerPreferredAddressIfAddressFamilyMismatch) { if (!session_.version().HasIetfQuicFrames()) { return; } EXPECT_EQ(quiche::IpAddressFamily::IP_V4, connection_->peer_address().host().address_family()); QuicConnectionPeer::SetEffectivePeerAddress(connection_, connection_->peer_address()); QuicTagVector copt; copt.push_back(kSPAD); QuicConfigPeer::SetReceivedConnectionOptions(session_.config(), copt); session_.config()->SetIPv6AlternateServerAddressToSend( QuicSocketAddress(QuicIpAddress::Loopback6(), 12345)); connection_->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE); session_.OnConfigNegotiated(); EXPECT_FALSE(session_.config() ->GetPreferredAddressToSend(quiche::IpAddressFamily::IP_V4) .has_value()); EXPECT_FALSE(session_.config() ->GetPreferredAddressToSend(quiche::IpAddressFamily::IP_V6) .has_value()); EXPECT_FALSE( connection_->expected_server_preferred_address().IsInitialized()); } TEST_P(QuicSessionTestServer, OpenStreamLimitPerEventLoop) { if (!VersionHasIetfQuicFrames(transport_version())) { return; } session_.set_uses_pending_streams(true); CompleteHandshake(); QuicStreamId unidirectional_stream_id = QuicUtils::GetFirstUnidirectionalStreamId(transport_version(), Perspective::IS_CLIENT); QuicStreamFrame data1(unidirectional_stream_id, false, 10, absl::string_view("HT")); session_.OnStreamFrame(data1); EXPECT_TRUE( QuicSessionPeer::GetPendingStream(&session_, unidirectional_stream_id)); EXPECT_EQ(0, session_.num_incoming_streams_created()); size_t i = 0u; for (; i < 10u; ++i) { QuicStreamId bidi_stream_id = GetNthClientInitiatedBidirectionalId(i); QuicStreamFrame data(bidi_stream_id, false, 0, "aaaa"); session_.OnStreamFrame(data); if (i > 4u) { EXPECT_TRUE(QuicSessionPeer::GetPendingStream(&session_, bidi_stream_id)); } } EXPECT_EQ(5u, session_.num_incoming_streams_created()); EXPECT_EQ(GetNthClientInitiatedBidirectionalId(i - 1), QuicSessionPeer::GetLargestPeerCreatedStreamId(&session_, false)); EXPECT_TRUE(session_.GetActiveStream(GetNthClientInitiatedBidirectionalId(4)) ->pending_duration() .IsZero()); QuicStreamFrame data2(unidirectional_stream_id, false, 0, absl::string_view("HT")); session_.OnStreamFrame(data2); EXPECT_TRUE( QuicSessionPeer::GetPendingStream(&session_, unidirectional_stream_id)); helper_.GetClock()->AdvanceTime(QuicTime::Delta::FromMicroseconds(100)); QuicAlarm* alarm = QuicSessionPeer::GetStreamCountResetAlarm(&session_); EXPECT_TRUE(alarm->IsSet()); alarm_factory_.FireAlarm(alarm); EXPECT_EQ(10u, session_.num_incoming_streams_created()); EXPECT_NE(nullptr, session_.GetActiveStream(unidirectional_stream_id)); EXPECT_EQ(100, session_.GetActiveStream(unidirectional_stream_id) ->pending_duration() .ToMicroseconds()); EXPECT_EQ( 100, session_.GetActiveStream(GetNthClientInitiatedBidirectionalId(i - 2)) ->pending_duration() .ToMicroseconds()); EXPECT_EQ(nullptr, session_.GetActiveStream( GetNthClientInitiatedBidirectionalId(i - 1))); } class QuicSessionTestClientUnconfigured : public QuicSessionTestBase { protected: QuicSessionTestClientUnconfigured() : QuicSessionTestBase(Perspective::IS_CLIENT, false) {} }; INSTANTIATE_TEST_SUITE_P(Tests, QuicSessionTestClientUnconfigured, ::testing::ValuesIn(AllSupportedVersions()), ::testing::PrintToStringParamName()); TEST_P(QuicSessionTestClientUnconfigured, StreamInitiallyBlockedThenUnblocked) { if (!connection_->version().AllowsLowFlowControlLimits()) { return; } QuicSessionPeer::SetMaxOpenOutgoingBidirectionalStreams(&session_, 10); TestStream* stream2 = session_.CreateOutgoingBidirectionalStream(); EXPECT_TRUE(stream2->IsFlowControlBlocked()); EXPECT_TRUE(session_.IsConnectionFlowControlBlocked()); EXPECT_TRUE(session_.IsStreamFlowControlBlocked()); QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesOutgoingBidirectional( session_.config(), kMinimumFlowControlSendWindow); QuicConfigPeer::SetReceivedInitialSessionFlowControlWindow( session_.config(), kMinimumFlowControlSendWindow); session_.OnConfigNegotiated(); EXPECT_FALSE(stream2->IsFlowControlBlocked()); EXPECT_FALSE(session_.IsConnectionFlowControlBlocked()); EXPECT_FALSE(session_.IsStreamFlowControlBlocked()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_session.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_session_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
2f058503-baa8-4700-a459-d8c3e15d575e
cpp
google/quiche
quic_framer
quiche/quic/core/quic_framer.cc
quiche/quic/core/quic_framer_test.cc
#include "quiche/quic/core/quic_framer.h" #include <sys/types.h> #include <algorithm> #include <cstddef> #include <cstdint> #include <limits> #include <memory> #include <optional> #include <string> #include <type_traits> #include <utility> #include <vector> #include "absl/base/attributes.h" #include "absl/base/macros.h" #include "absl/base/optimization.h" #include "absl/status/status.h" #include "absl/strings/escaping.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/crypto_framer.h" #include "quiche/quic/core/crypto/crypto_handshake.h" #include "quiche/quic/core/crypto/crypto_handshake_message.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/crypto/crypto_utils.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_random.h" #include "quiche/quic/core/frames/quic_ack_frequency_frame.h" #include "quiche/quic/core/frames/quic_reset_stream_at_frame.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_constants.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_packets.h" #include "quiche/quic/core/quic_socket_address_coder.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_utils.h" #include "quiche/quic/core/quic_versions.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_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_ip_address_family.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_stack_trace.h" #include "quiche/common/quiche_text_utils.h" #include "quiche/common/wire_serialization.h" namespace quic { namespace { #define ENDPOINT \ (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ") const uint8_t kQuicFrameTypeSpecialMask = 0xC0; const uint8_t kQuicFrameTypeStreamMask = 0x80; const uint8_t kQuicFrameTypeAckMask = 0x40; static_assert(kQuicFrameTypeSpecialMask == (kQuicFrameTypeStreamMask | kQuicFrameTypeAckMask), "Invalid kQuicFrameTypeSpecialMask"); const uint8_t kQuicStreamIdShift = 2; const uint8_t kQuicStreamIDLengthMask = 0x03; const uint8_t kQuicStreamShift = 3; const uint8_t kQuicStreamOffsetMask = 0x07; const uint8_t kQuicStreamDataLengthShift = 1; const uint8_t kQuicStreamDataLengthMask = 0x01; const uint8_t kQuicStreamFinShift = 1; const uint8_t kQuicStreamFinMask = 0x01; const uint8_t kQuicSequenceNumberLengthNumBits = 2; const uint8_t kActBlockLengthOffset = 0; const uint8_t kLargestAckedOffset = 2; const uint8_t kQuicHasMultipleAckBlocksOffset = 5; const uint8_t kQuicNumTimestampsLength = 1; const uint8_t kQuicFirstTimestampLength = 4; const uint8_t kQuicTimestampLength = 2; const uint8_t kQuicTimestampPacketNumberGapLength = 1; const int kMaxErrorStringLength = 256; const uint8_t kConnectionIdLengthAdjustment = 3; const uint8_t kDestinationConnectionIdLengthMask = 0xF0; const uint8_t kSourceConnectionIdLengthMask = 0x0F; uint64_t Delta(uint64_t a, uint64_t b) { if (a < b) { return b - a; } return a - b; } uint64_t ClosestTo(uint64_t target, uint64_t a, uint64_t b) { return (Delta(target, a) < Delta(target, b)) ? a : b; } QuicPacketNumberLength ReadAckPacketNumberLength(uint8_t flags) { switch (flags & PACKET_FLAGS_8BYTE_PACKET) { case PACKET_FLAGS_8BYTE_PACKET: return PACKET_6BYTE_PACKET_NUMBER; case PACKET_FLAGS_4BYTE_PACKET: return PACKET_4BYTE_PACKET_NUMBER; case PACKET_FLAGS_2BYTE_PACKET: return PACKET_2BYTE_PACKET_NUMBER; case PACKET_FLAGS_1BYTE_PACKET: return PACKET_1BYTE_PACKET_NUMBER; default: QUIC_BUG(quic_bug_10850_2) << "Unreachable case statement."; return PACKET_6BYTE_PACKET_NUMBER; } } uint8_t PacketNumberLengthToOnWireValue( QuicPacketNumberLength packet_number_length) { return packet_number_length - 1; } QuicPacketNumberLength GetShortHeaderPacketNumberLength(uint8_t type) { QUICHE_DCHECK(!(type & FLAGS_LONG_HEADER)); return static_cast<QuicPacketNumberLength>((type & 0x03) + 1); } uint8_t LongHeaderTypeToOnWireValue(QuicLongHeaderType type, const ParsedQuicVersion& version) { switch (type) { case INITIAL: return version.UsesV2PacketTypes() ? (1 << 4) : 0; case ZERO_RTT_PROTECTED: return version.UsesV2PacketTypes() ? (2 << 4) : (1 << 4); case HANDSHAKE: return version.UsesV2PacketTypes() ? (3 << 4) : (2 << 4); case RETRY: return version.UsesV2PacketTypes() ? 0 : (3 << 4); case VERSION_NEGOTIATION: return 0xF0; default: QUIC_BUG(quic_bug_10850_3) << "Invalid long header type: " << type; return 0xFF; } } QuicLongHeaderType GetLongHeaderType(uint8_t type, const ParsedQuicVersion& version) { QUICHE_DCHECK((type & FLAGS_LONG_HEADER)); switch ((type & 0x30) >> 4) { case 0: return version.UsesV2PacketTypes() ? RETRY : INITIAL; case 1: return version.UsesV2PacketTypes() ? INITIAL : ZERO_RTT_PROTECTED; case 2: return version.UsesV2PacketTypes() ? ZERO_RTT_PROTECTED : HANDSHAKE; case 3: return version.UsesV2PacketTypes() ? HANDSHAKE : RETRY; default: QUIC_BUG(quic_bug_10850_4) << "Unreachable statement"; return INVALID_PACKET_TYPE; } } QuicPacketNumberLength GetLongHeaderPacketNumberLength(uint8_t type) { return static_cast<QuicPacketNumberLength>((type & 0x03) + 1); } PacketNumberSpace GetPacketNumberSpace(const QuicPacketHeader& header) { switch (header.form) { case GOOGLE_QUIC_PACKET: QUIC_BUG(quic_bug_10850_5) << "Try to get packet number space of Google QUIC packet"; break; case IETF_QUIC_SHORT_HEADER_PACKET: return APPLICATION_DATA; case IETF_QUIC_LONG_HEADER_PACKET: switch (header.long_packet_type) { case INITIAL: return INITIAL_DATA; case HANDSHAKE: return HANDSHAKE_DATA; case ZERO_RTT_PROTECTED: return APPLICATION_DATA; case VERSION_NEGOTIATION: case RETRY: case INVALID_PACKET_TYPE: QUIC_BUG(quic_bug_10850_6) << "Try to get packet number space of long header type: " << QuicUtils::QuicLongHeaderTypetoString(header.long_packet_type); break; } } return NUM_PACKET_NUMBER_SPACES; } EncryptionLevel GetEncryptionLevel(const QuicPacketHeader& header) { switch (header.form) { case GOOGLE_QUIC_PACKET: QUIC_BUG(quic_bug_10850_7) << "Cannot determine EncryptionLevel from Google QUIC header"; break; case IETF_QUIC_SHORT_HEADER_PACKET: return ENCRYPTION_FORWARD_SECURE; case IETF_QUIC_LONG_HEADER_PACKET: switch (header.long_packet_type) { case INITIAL: return ENCRYPTION_INITIAL; case HANDSHAKE: return ENCRYPTION_HANDSHAKE; case ZERO_RTT_PROTECTED: return ENCRYPTION_ZERO_RTT; case VERSION_NEGOTIATION: case RETRY: case INVALID_PACKET_TYPE: QUIC_BUG(quic_bug_10850_8) << "No encryption used with type " << QuicUtils::QuicLongHeaderTypetoString(header.long_packet_type); } } return NUM_ENCRYPTION_LEVELS; } absl::string_view TruncateErrorString(absl::string_view error) { if (error.length() <= kMaxErrorStringLength) { return error; } return absl::string_view(error.data(), kMaxErrorStringLength); } size_t TruncatedErrorStringSize(const absl::string_view& error) { if (error.length() < kMaxErrorStringLength) { return error.length(); } return kMaxErrorStringLength; } uint8_t GetConnectionIdLengthValue(uint8_t length) { if (length == 0) { return 0; } return static_cast<uint8_t>(length - kConnectionIdLengthAdjustment); } bool IsValidPacketNumberLength(QuicPacketNumberLength packet_number_length) { size_t length = packet_number_length; return length == 1 || length == 2 || length == 4 || length == 6 || length == 8; } bool IsValidFullPacketNumber(uint64_t full_packet_number, ParsedQuicVersion version) { return full_packet_number > 0 || version.HasIetfQuicFrames(); } bool AppendIetfConnectionIds(bool version_flag, bool use_length_prefix, QuicConnectionId destination_connection_id, QuicConnectionId source_connection_id, QuicDataWriter* writer) { if (!version_flag) { return writer->WriteConnectionId(destination_connection_id); } if (use_length_prefix) { return writer->WriteLengthPrefixedConnectionId(destination_connection_id) && writer->WriteLengthPrefixedConnectionId(source_connection_id); } uint8_t dcil = GetConnectionIdLengthValue(destination_connection_id.length()); uint8_t scil = GetConnectionIdLengthValue(source_connection_id.length()); uint8_t connection_id_length = dcil << 4 | scil; return writer->WriteUInt8(connection_id_length) && writer->WriteConnectionId(destination_connection_id) && writer->WriteConnectionId(source_connection_id); } enum class DroppedPacketReason { INVALID_PUBLIC_HEADER, VERSION_MISMATCH, INVALID_VERSION_NEGOTIATION_PACKET, INVALID_PUBLIC_RESET_PACKET, INVALID_PACKET_NUMBER, INVALID_DIVERSIFICATION_NONCE, DECRYPTION_FAILURE, NUM_REASONS, }; void RecordDroppedPacketReason(DroppedPacketReason reason) { QUIC_CLIENT_HISTOGRAM_ENUM("QuicDroppedPacketReason", reason, DroppedPacketReason::NUM_REASONS, "The reason a packet was not processed. Recorded " "each time such a packet is dropped"); } PacketHeaderFormat GetIetfPacketHeaderFormat(uint8_t type_byte) { return type_byte & FLAGS_LONG_HEADER ? IETF_QUIC_LONG_HEADER_PACKET : IETF_QUIC_SHORT_HEADER_PACKET; } std::string GenerateErrorString(std::string initial_error_string, QuicErrorCode quic_error_code) { if (quic_error_code == QUIC_IETF_GQUIC_ERROR_MISSING) { return initial_error_string; } return absl::StrCat(std::to_string(static_cast<unsigned>(quic_error_code)), ":", initial_error_string); } size_t AckEcnCountSize(const QuicAckFrame& ack_frame) { if (!ack_frame.ecn_counters.has_value()) { return 0; } return (QuicDataWriter::GetVarInt62Len(ack_frame.ecn_counters->ect0) + QuicDataWriter::GetVarInt62Len(ack_frame.ecn_counters->ect1) + QuicDataWriter::GetVarInt62Len(ack_frame.ecn_counters->ce)); } } QuicFramer::QuicFramer(const ParsedQuicVersionVector& supported_versions, QuicTime creation_time, Perspective perspective, uint8_t expected_server_connection_id_length) : visitor_(nullptr), error_(QUIC_NO_ERROR), last_serialized_server_connection_id_(EmptyQuicConnectionId()), version_(ParsedQuicVersion::Unsupported()), supported_versions_(supported_versions), decrypter_level_(ENCRYPTION_INITIAL), alternative_decrypter_level_(NUM_ENCRYPTION_LEVELS), alternative_decrypter_latch_(false), perspective_(perspective), validate_flags_(true), process_timestamps_(false), max_receive_timestamps_per_ack_(std::numeric_limits<uint32_t>::max()), receive_timestamps_exponent_(0), process_reset_stream_at_(false), creation_time_(creation_time), last_timestamp_(QuicTime::Delta::Zero()), support_key_update_for_connection_(false), current_key_phase_bit_(false), potential_peer_key_update_attempt_count_(0), first_sending_packet_number_(FirstSendingPacketNumber()), data_producer_(nullptr), expected_server_connection_id_length_( expected_server_connection_id_length), expected_client_connection_id_length_(0), supports_multiple_packet_number_spaces_(false), last_written_packet_number_length_(0), peer_ack_delay_exponent_(kDefaultAckDelayExponent), local_ack_delay_exponent_(kDefaultAckDelayExponent), current_received_frame_type_(0), previously_received_frame_type_(0) { QUICHE_DCHECK(!supported_versions.empty()); version_ = supported_versions_[0]; QUICHE_DCHECK(version_.IsKnown()) << ParsedQuicVersionVectorToString(supported_versions_); } QuicFramer::~QuicFramer() {} size_t QuicFramer::GetMinStreamFrameSize(QuicTransportVersion version, QuicStreamId stream_id, QuicStreamOffset offset, bool last_frame_in_packet, size_t data_length) { if (VersionHasIetfQuicFrames(version)) { return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(stream_id) + (last_frame_in_packet ? 0 : QuicDataWriter::GetVarInt62Len(data_length)) + (offset != 0 ? QuicDataWriter::GetVarInt62Len(offset) : 0); } return kQuicFrameTypeSize + GetStreamIdSize(stream_id) + GetStreamOffsetSize(offset) + (last_frame_in_packet ? 0 : kQuicStreamPayloadLengthSize); } size_t QuicFramer::GetMinCryptoFrameSize(QuicStreamOffset offset, QuicPacketLength data_length) { return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(offset) + QuicDataWriter::GetVarInt62Len(data_length); } size_t QuicFramer::GetMessageFrameSize(bool last_frame_in_packet, QuicByteCount length) { return kQuicFrameTypeSize + (last_frame_in_packet ? 0 : QuicDataWriter::GetVarInt62Len(length)) + length; } size_t QuicFramer::GetMinAckFrameSize( QuicTransportVersion version, const QuicAckFrame& ack_frame, uint32_t local_ack_delay_exponent, bool use_ietf_ack_with_receive_timestamp) { if (VersionHasIetfQuicFrames(version)) { size_t min_size = kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(LargestAcked(ack_frame).ToUint64()); min_size += QuicDataWriter::GetVarInt62Len( ack_frame.ack_delay_time.ToMicroseconds() >> local_ack_delay_exponent); min_size += QuicDataWriter::GetVarInt62Len(0); min_size += QuicDataWriter::GetVarInt62Len( ack_frame.packets.Empty() ? 0 : ack_frame.packets.rbegin()->Length() - 1); if (use_ietf_ack_with_receive_timestamp) { min_size += QuicDataWriter::GetVarInt62Len(0); } else { min_size += AckEcnCountSize(ack_frame); } return min_size; } return kQuicFrameTypeSize + GetMinPacketNumberLength(LargestAcked(ack_frame)) + kQuicDeltaTimeLargestObservedSize + kQuicNumTimestampsSize; } size_t QuicFramer::GetStopWaitingFrameSize( QuicPacketNumberLength packet_number_length) { size_t min_size = kQuicFrameTypeSize + packet_number_length; return min_size; } size_t QuicFramer::GetRstStreamFrameSize(QuicTransportVersion version, const QuicRstStreamFrame& frame) { if (VersionHasIetfQuicFrames(version)) { return QuicDataWriter::GetVarInt62Len(frame.stream_id) + QuicDataWriter::GetVarInt62Len(frame.byte_offset) + kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.ietf_error_code); } return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize + kQuicErrorCodeSize; } size_t QuicFramer::GetConnectionCloseFrameSize( QuicTransportVersion version, const QuicConnectionCloseFrame& frame) { if (!VersionHasIetfQuicFrames(version)) { return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize + TruncatedErrorStringSize(frame.error_details); } const size_t truncated_error_string_size = TruncatedErrorStringSize( GenerateErrorString(frame.error_details, frame.quic_error_code)); const size_t frame_size = truncated_error_string_size + QuicDataWriter::GetVarInt62Len(truncated_error_string_size) + kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.wire_error_code); if (frame.close_type == IETF_QUIC_APPLICATION_CONNECTION_CLOSE) { return frame_size; } return frame_size + QuicDataWriter::GetVarInt62Len(frame.transport_close_frame_type); } size_t QuicFramer::GetMinGoAwayFrameSize() { return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize + kQuicMaxStreamIdSize; } size_t QuicFramer::GetWindowUpdateFrameSize( QuicTransportVersion version, const QuicWindowUpdateFrame& frame) { if (!VersionHasIetfQuicFrames(version)) { return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize; } if (frame.stream_id == QuicUtils::GetInvalidStreamId(version)) { return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.max_data); } return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.max_data) + QuicDataWriter::GetVarInt62Len(frame.stream_id); } size_t QuicFramer::GetMaxStreamsFrameSize(QuicTransportVersion version, const QuicMaxStreamsFrame& frame) { if (!VersionHasIetfQuicFrames(version)) { QUIC_BUG(quic_bug_10850_9) << "In version " << version << ", which does not support IETF Frames, and tried to serialize " "MaxStreams Frame."; } return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.stream_count); } size_t QuicFramer::GetStreamsBlockedFrameSize( QuicTransportVersion version, const QuicStreamsBlockedFrame& frame) { if (!VersionHasIetfQuicFrames(version)) { QUIC_BUG(quic_bug_10850_10) << "In version " << version << ", which does not support IETF frames, and tried to serialize " "StreamsBlocked Frame."; } return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.stream_count); } size_t QuicFramer::GetBlockedFrameSize(QuicTransportVersion version, const QuicBlockedFrame& frame) { if (!VersionHasIetfQuicFrames(version)) { return kQuicFrameTypeSize + kQuicMaxStreamIdSize; } if (frame.stream_id == QuicUtils::GetInvalidStreamId(version)) { return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.offset); } return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.offset) + QuicDataWriter::GetVarInt62Len(frame.stream_id); } size_t QuicFramer::GetStopSendingFrameSize(const QuicStopSendingFrame& frame) { return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.stream_id) + QuicDataWriter::GetVarInt62Len(frame.ietf_error_code); } size_t QuicFramer::GetAckFrequencyFrameSize( const QuicAckFrequencyFrame& frame) { return QuicDataWriter::GetVarInt62Len(IETF_ACK_FREQUENCY) + QuicDataWriter::GetVarInt62Len(frame.sequence_number) + QuicDataWriter::GetVarInt62Len(frame.packet_tolerance) + QuicDataWriter::GetVarInt62Len(frame.max_ack_delay.ToMicroseconds()) + 1; } size_t QuicFramer::GetResetStreamAtFrameSize( const QuicResetStreamAtFrame& frame) { return QuicDataWriter::GetVarInt62Len(IETF_RESET_STREAM_AT) + QuicDataWriter::GetVarInt62Len(frame.stream_id) + QuicDataWriter::GetVarInt62Len(frame.error) + QuicDataWriter::GetVarInt62Len(frame.final_offset) + QuicDataWriter::GetVarInt62Len(frame.reliable_offset); } size_t QuicFramer::GetPathChallengeFrameSize( const QuicPathChallengeFrame& frame) { return kQuicFrameTypeSize + sizeof(frame.data_buffer); } size_t QuicFramer::GetPathResponseFrameSize( const QuicPathResponseFrame& frame) { return kQuicFrameTypeSize + sizeof(frame.data_buffer); } size_t QuicFramer::GetRetransmittableControlFrameSize( QuicTransportVersion version, const QuicFrame& frame) { switch (frame.type) { case PING_FRAME: return kQuicFrameTypeSize; case RST_STREAM_FRAME: return GetRstStreamFrameSize(version, *frame.rst_stream_frame); case CONNECTION_CLOSE_FRAME: return GetConnectionCloseFrameSize(version, *frame.connection_close_frame); case GOAWAY_FRAME: return GetMinGoAwayFrameSize() + TruncatedErrorStringSize(frame.goaway_frame->reason_phrase); case WINDOW_UPDATE_FRAME: return GetWindowUpdateFrameSize(version, frame.window_update_frame); case BLOCKED_FRAME: return GetBlockedFrameSize(version, frame.blocked_frame); case NEW_CONNECTION_ID_FRAME: return GetNewConnectionIdFrameSize(*frame.new_connection_id_frame); case RETIRE_CONNECTION_ID_FRAME: return GetRetireConnectionIdFrameSize(*frame.retire_connection_id_frame); case NEW_TOKEN_FRAME: return GetNewTokenFrameSize(*frame.new_token_frame); case MAX_STREAMS_FRAME: return GetMaxStreamsFrameSize(version, frame.max_streams_frame); case STREAMS_BLOCKED_FRAME: return GetStreamsBlockedFrameSize(version, frame.streams_blocked_frame); case PATH_RESPONSE_FRAME: return GetPathResponseFrameSize(frame.path_response_frame); case PATH_CHALLENGE_FRAME: return GetPathChallengeFrameSize(frame.path_challenge_frame); case STOP_SENDING_FRAME: return GetStopSendingFrameSize(frame.stop_sending_frame); case HANDSHAKE_DONE_FRAME: return kQuicFrameTypeSize; case ACK_FREQUENCY_FRAME: return GetAckFrequencyFrameSize(*frame.ack_frequency_frame); case RESET_STREAM_AT_FRAME: return GetResetStreamAtFrameSize(*frame.reset_stream_at_frame); case STREAM_FRAME: case ACK_FRAME: case STOP_WAITING_FRAME: case MTU_DISCOVERY_FRAME: case PADDING_FRAME: case MESSAGE_FRAME: case CRYPTO_FRAME: case NUM_FRAME_TYPES: QUICHE_DCHECK(false); return 0; } QUICHE_DCHECK(false); return 0; } size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id) { for (int i = 1; i <= 4; ++i) { stream_id >>= 8; if (stream_id == 0) { return i; } } QUIC_BUG(quic_bug_10850_11) << "Failed to determine StreamIDSize."; return 4; } size_t QuicFramer::GetStreamOffsetSize(QuicStreamOffset offset) { if (offset == 0) { return 0; } offset >>= 8; for (int i = 2; i <= 8; ++i) { offset >>= 8; if (offset == 0) { return i; } } QUIC_BUG(quic_bug_10850_12) << "Failed to determine StreamOffsetSize."; return 8; } size_t QuicFramer::GetNewConnectionIdFrameSize( const QuicNewConnectionIdFrame& frame) { return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.sequence_number) + QuicDataWriter::GetVarInt62Len(frame.retire_prior_to) + kConnectionIdLengthSize + frame.connection_id.length() + sizeof(frame.stateless_reset_token); } size_t QuicFramer::GetRetireConnectionIdFrameSize( const QuicRetireConnectionIdFrame& frame) { return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.sequence_number); } size_t QuicFramer::GetNewTokenFrameSize(const QuicNewTokenFrame& frame) { return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.token.length()) + frame.token.length(); } bool QuicFramer::IsSupportedVersion(const ParsedQuicVersion version) const { for (const ParsedQuicVersion& supported_version : supported_versions_) { if (version == supported_version) { return true; } } return false; } size_t QuicFramer::GetSerializedFrameLength( const QuicFrame& frame, size_t free_bytes, bool first_frame, bool last_frame, QuicPacketNumberLength packet_number_length) { if (frame.type == ACK_FRAME && frame.ack_frame == nullptr) { QUIC_BUG(quic_bug_10850_13) << "Cannot compute the length of a null ack frame. free_bytes:" << free_bytes << " first_frame:" << first_frame << " last_frame:" << last_frame << " seq num length:" << packet_number_length; set_error(QUIC_INTERNAL_ERROR); visitor_->OnError(this); return 0; } if (frame.type == PADDING_FRAME) { if (frame.padding_frame.num_padding_bytes == -1) { return free_bytes; } else { return free_bytes < static_cast<size_t>(frame.padding_frame.num_padding_bytes) ? free_bytes : frame.padding_frame.num_padding_bytes; } } size_t frame_len = ComputeFrameLength(frame, last_frame, packet_number_length); if (frame_len <= free_bytes) { return frame_len; } if (!first_frame) { return 0; } bool can_truncate = frame.type == ACK_FRAME && free_bytes >= GetMinAckFrameSize(version_.transport_version, *frame.ack_frame, local_ack_delay_exponent_, UseIetfAckWithReceiveTimestamp(*frame.ack_frame)); if (can_truncate) { QUIC_DLOG(INFO) << ENDPOINT << "Truncating large frame, free bytes: " << free_bytes; return free_bytes; } return 0; } QuicFramer::AckFrameInfo::AckFrameInfo() : max_block_length(0), first_block_length(0), num_ack_blocks(0) {} QuicFramer::AckFrameInfo::AckFrameInfo(const AckFrameInfo& other) = default; QuicFramer::AckFrameInfo::~AckFrameInfo() {} bool QuicFramer::WriteIetfLongHeaderLength(const QuicPacketHeader& header, QuicDataWriter* writer, size_t length_field_offset, EncryptionLevel level) { if (!QuicVersionHasLongHeaderLengths(transport_version()) || !header.version_flag || length_field_offset == 0) { return true; } if (writer->length() < length_field_offset || writer->length() - length_field_offset < quiche::kQuicheDefaultLongHeaderLengthLength) { set_detailed_error("Invalid length_field_offset."); QUIC_BUG(quic_bug_10850_14) << "Invalid length_field_offset."; return false; } size_t length_to_write = writer->length() - length_field_offset - quiche::kQuicheDefaultLongHeaderLengthLength; length_to_write = GetCiphertextSize(level, length_to_write); QuicDataWriter length_writer(writer->length() - length_field_offset, writer->data() + length_field_offset); if (!length_writer.WriteVarInt62WithForcedLength( length_to_write, quiche::kQuicheDefaultLongHeaderLengthLength)) { set_detailed_error("Failed to overwrite long header length."); QUIC_BUG(quic_bug_10850_15) << "Failed to overwrite long header length."; return false; } return true; } size_t QuicFramer::BuildDataPacket(const QuicPacketHeader& header, const QuicFrames& frames, char* buffer, size_t packet_length, EncryptionLevel level) { QUIC_BUG_IF(quic_bug_12975_2, header.version_flag && header.long_packet_type == RETRY && !frames.empty()) << "IETF RETRY packets cannot contain frames " << header; QuicDataWriter writer(packet_length, buffer); size_t length_field_offset = 0; if (!AppendIetfPacketHeader(header, &writer, &length_field_offset)) { QUIC_BUG(quic_bug_10850_16) << "AppendPacketHeader failed"; return 0; } if (VersionHasIetfQuicFrames(transport_version())) { if (AppendIetfFrames(frames, &writer) == 0) { return 0; } if (!WriteIetfLongHeaderLength(header, &writer, length_field_offset, level)) { return 0; } return writer.length(); } size_t i = 0; for (const QuicFrame& frame : frames) { const bool last_frame_in_packet = i == frames.size() - 1; if (!AppendTypeByte(frame, last_frame_in_packet, &writer)) { QUIC_BUG(quic_bug_10850_17) << "AppendTypeByte failed"; return 0; } switch (frame.type) { case PADDING_FRAME: if (!AppendPaddingFrame(frame.padding_frame, &writer)) { QUIC_BUG(quic_bug_10850_18) << "AppendPaddingFrame of " << frame.padding_frame.num_padding_bytes << " failed"; return 0; } break; case STREAM_FRAME: if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet, &writer)) { QUIC_BUG(quic_bug_10850_19) << "AppendStreamFrame failed"; return 0; } break; case ACK_FRAME: if (!AppendAckFrameAndTypeByte(*frame.ack_frame, &writer)) { QUIC_BUG(quic_bug_10850_20) << "AppendAckFrameAndTypeByte failed: " << detailed_error_; return 0; } break; case MTU_DISCOVERY_FRAME: ABSL_FALLTHROUGH_INTENDED; case PING_FRAME: break; case RST_STREAM_FRAME: if (!AppendRstStreamFrame(*frame.rst_stream_frame, &writer)) { QUIC_BUG(quic_bug_10850_22) << "AppendRstStreamFrame failed"; return 0; } break; case CONNECTION_CLOSE_FRAME: if (!AppendConnectionCloseFrame(*frame.connection_close_frame, &writer)) { QUIC_BUG(quic_bug_10850_23) << "AppendConnectionCloseFrame failed"; return 0; } break; case GOAWAY_FRAME: if (!AppendGoAwayFrame(*frame.goaway_frame, &writer)) { QUIC_BUG(quic_bug_10850_24) << "AppendGoAwayFrame failed"; return 0; } break; case WINDOW_UPDATE_FRAME: if (!AppendWindowUpdateFrame(frame.window_update_frame, &writer)) { QUIC_BUG(quic_bug_10850_25) << "AppendWindowUpdateFrame failed"; return 0; } break; case BLOCKED_FRAME: if (!AppendBlockedFrame(frame.blocked_frame, &writer)) { QUIC_BUG(quic_bug_10850_26) << "AppendBlockedFrame failed"; return 0; } break; case NEW_CONNECTION_ID_FRAME: set_detailed_error( "Attempt to append NEW_CONNECTION_ID frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case RETIRE_CONNECTION_ID_FRAME: set_detailed_error( "Attempt to append RETIRE_CONNECTION_ID frame and not in IETF " "QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case NEW_TOKEN_FRAME: set_detailed_error( "Attempt to append NEW_TOKEN_ID frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case MAX_STREAMS_FRAME: set_detailed_error( "Attempt to append MAX_STREAMS frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case STREAMS_BLOCKED_FRAME: set_detailed_error( "Attempt to append STREAMS_BLOCKED frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case PATH_RESPONSE_FRAME: set_detailed_error( "Attempt to append PATH_RESPONSE frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case PATH_CHALLENGE_FRAME: set_detailed_error( "Attempt to append PATH_CHALLENGE frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case STOP_SENDING_FRAME: set_detailed_error( "Attempt to append STOP_SENDING frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case MESSAGE_FRAME: if (!AppendMessageFrameAndTypeByte(*frame.message_frame, last_frame_in_packet, &writer)) { QUIC_BUG(quic_bug_10850_27) << "AppendMessageFrame failed"; return 0; } break; case CRYPTO_FRAME: if (!QuicVersionUsesCryptoFrames(version_.transport_version)) { set_detailed_error( "Attempt to append CRYPTO frame in version prior to 47."); return RaiseError(QUIC_INTERNAL_ERROR); } if (!AppendCryptoFrame(*frame.crypto_frame, &writer)) { QUIC_BUG(quic_bug_10850_28) << "AppendCryptoFrame failed"; return 0; } break; case HANDSHAKE_DONE_FRAME: break; default: RaiseError(QUIC_INVALID_FRAME_DATA); QUIC_BUG(quic_bug_10850_29) << "QUIC_INVALID_FRAME_DATA"; return 0; } ++i; } if (!WriteIetfLongHeaderLength(header, &writer, length_field_offset, level)) { return 0; } return writer.length(); } size_t QuicFramer::AppendIetfFrames(const QuicFrames& frames, QuicDataWriter* writer) { size_t i = 0; for (const QuicFrame& frame : frames) { const bool last_frame_in_packet = i == frames.size() - 1; if (!AppendIetfFrameType(frame, last_frame_in_packet, writer)) { QUIC_BUG(quic_bug_10850_30) << "AppendIetfFrameType failed: " << detailed_error(); return 0; } switch (frame.type) { case PADDING_FRAME: if (!AppendPaddingFrame(frame.padding_frame, writer)) { QUIC_BUG(quic_bug_10850_31) << "AppendPaddingFrame of " << frame.padding_frame.num_padding_bytes << " failed: " << detailed_error(); return 0; } break; case STREAM_FRAME: if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet, writer)) { QUIC_BUG(quic_bug_10850_32) << "AppendStreamFrame " << frame.stream_frame << " failed: " << detailed_error(); return 0; } break; case ACK_FRAME: if (!AppendIetfAckFrameAndTypeByte(*frame.ack_frame, writer)) { QUIC_BUG(quic_bug_10850_33) << "AppendIetfAckFrameAndTypeByte failed: " << detailed_error(); return 0; } break; case STOP_WAITING_FRAME: set_detailed_error( "Attempt to append STOP WAITING frame in IETF QUIC."); RaiseError(QUIC_INTERNAL_ERROR); QUIC_BUG(quic_bug_10850_34) << detailed_error(); return 0; case MTU_DISCOVERY_FRAME: ABSL_FALLTHROUGH_INTENDED; case PING_FRAME: break; case RST_STREAM_FRAME: if (!AppendRstStreamFrame(*frame.rst_stream_frame, writer)) { QUIC_BUG(quic_bug_10850_35) << "AppendRstStreamFrame failed: " << detailed_error(); return 0; } break; case CONNECTION_CLOSE_FRAME: if (!AppendIetfConnectionCloseFrame(*frame.connection_close_frame, writer)) { QUIC_BUG(quic_bug_10850_36) << "AppendIetfConnectionCloseFrame failed: " << detailed_error(); return 0; } break; case GOAWAY_FRAME: set_detailed_error("Attempt to append GOAWAY frame in IETF QUIC."); RaiseError(QUIC_INTERNAL_ERROR); QUIC_BUG(quic_bug_10850_37) << detailed_error(); return 0; case WINDOW_UPDATE_FRAME: if (frame.window_update_frame.stream_id == QuicUtils::GetInvalidStreamId(transport_version())) { if (!AppendMaxDataFrame(frame.window_update_frame, writer)) { QUIC_BUG(quic_bug_10850_38) << "AppendMaxDataFrame failed: " << detailed_error(); return 0; } } else { if (!AppendMaxStreamDataFrame(frame.window_update_frame, writer)) { QUIC_BUG(quic_bug_10850_39) << "AppendMaxStreamDataFrame failed: " << detailed_error(); return 0; } } break; case BLOCKED_FRAME: if (!AppendBlockedFrame(frame.blocked_frame, writer)) { QUIC_BUG(quic_bug_10850_40) << "AppendBlockedFrame failed: " << detailed_error(); return 0; } break; case MAX_STREAMS_FRAME: if (!AppendMaxStreamsFrame(frame.max_streams_frame, writer)) { QUIC_BUG(quic_bug_10850_41) << "AppendMaxStreamsFrame failed: " << detailed_error(); return 0; } break; case STREAMS_BLOCKED_FRAME: if (!AppendStreamsBlockedFrame(frame.streams_blocked_frame, writer)) { QUIC_BUG(quic_bug_10850_42) << "AppendStreamsBlockedFrame failed: " << detailed_error(); return 0; } break; case NEW_CONNECTION_ID_FRAME: if (!AppendNewConnectionIdFrame(*frame.new_connection_id_frame, writer)) { QUIC_BUG(quic_bug_10850_43) << "AppendNewConnectionIdFrame failed: " << detailed_error(); return 0; } break; case RETIRE_CONNECTION_ID_FRAME: if (!AppendRetireConnectionIdFrame(*frame.retire_connection_id_frame, writer)) { QUIC_BUG(quic_bug_10850_44) << "AppendRetireConnectionIdFrame failed: " << detailed_error(); return 0; } break; case NEW_TOKEN_FRAME: if (!AppendNewTokenFrame(*frame.new_token_frame, writer)) { QUIC_BUG(quic_bug_10850_45) << "AppendNewTokenFrame failed: " << detailed_error(); return 0; } break; case STOP_SENDING_FRAME: if (!AppendStopSendingFrame(frame.stop_sending_frame, writer)) { QUIC_BUG(quic_bug_10850_46) << "AppendStopSendingFrame failed: " << detailed_error(); return 0; } break; case PATH_CHALLENGE_FRAME: if (!AppendPathChallengeFrame(frame.path_challenge_frame, writer)) { QUIC_BUG(quic_bug_10850_47) << "AppendPathChallengeFrame failed: " << detailed_error(); return 0; } break; case PATH_RESPONSE_FRAME: if (!AppendPathResponseFrame(frame.path_response_frame, writer)) { QUIC_BUG(quic_bug_10850_48) << "AppendPathResponseFrame failed: " << detailed_error(); return 0; } break; case MESSAGE_FRAME: if (!AppendMessageFrameAndTypeByte(*frame.message_frame, last_frame_in_packet, writer)) { QUIC_BUG(quic_bug_10850_49) << "AppendMessageFrame failed: " << detailed_error(); return 0; } break; case CRYPTO_FRAME: if (!AppendCryptoFrame(*frame.crypto_frame, writer)) { QUIC_BUG(quic_bug_10850_50) << "AppendCryptoFrame failed: " << detailed_error(); return 0; } break; case HANDSHAKE_DONE_FRAME: break; case ACK_FREQUENCY_FRAME: if (!AppendAckFrequencyFrame(*frame.ack_frequency_frame, writer)) { QUIC_BUG(quic_bug_10850_51) << "AppendAckFrequencyFrame failed: " << detailed_error(); return 0; } break; case RESET_STREAM_AT_FRAME: QUIC_BUG_IF(reset_stream_at_appended_while_disabled, !process_reset_stream_at_) << "Requested serialization of RESET_STREAM_AT_FRAME while it is " "not explicitly enabled in the framer"; if (!AppendResetFrameAtFrame(*frame.reset_stream_at_frame, *writer)) { QUIC_BUG(cannot_append_reset_stream_at) << "AppendResetStreamAtFram failed: " << detailed_error(); return 0; } break; default: set_detailed_error("Tried to append unknown frame type."); RaiseError(QUIC_INVALID_FRAME_DATA); QUIC_BUG(quic_bug_10850_52) << "QUIC_INVALID_FRAME_DATA: " << frame.type; return 0; } ++i; } return writer->length(); } std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildPublicResetPacket( const QuicPublicResetPacket& packet) { CryptoHandshakeMessage reset; reset.set_tag(kPRST); reset.SetValue(kRNON, packet.nonce_proof); if (packet.client_address.host().address_family() != IpAddressFamily::IP_UNSPEC) { QuicSocketAddressCoder address_coder(packet.client_address); std::string serialized_address = address_coder.Encode(); if (serialized_address.empty()) { return nullptr; } reset.SetStringPiece(kCADR, serialized_address); } if (!packet.endpoint_id.empty()) { reset.SetStringPiece(kEPID, packet.endpoint_id); } const QuicData& reset_serialized = reset.GetSerialized(); size_t len = kPublicFlagsSize + packet.connection_id.length() + reset_serialized.length(); std::unique_ptr<char[]> buffer(new char[len]); QuicDataWriter writer(len, buffer.get()); uint8_t flags = static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_RST | PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID); flags |= static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD); if (!writer.WriteUInt8(flags)) { return nullptr; } if (!writer.WriteConnectionId(packet.connection_id)) { return nullptr; } if (!writer.WriteBytes(reset_serialized.data(), reset_serialized.length())) { return nullptr; } return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true); } size_t QuicFramer::GetMinStatelessResetPacketLength() { return 5 + kStatelessResetTokenLength; } std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildIetfStatelessResetPacket( QuicConnectionId connection_id, size_t received_packet_length, StatelessResetToken stateless_reset_token) { return BuildIetfStatelessResetPacket(connection_id, received_packet_length, stateless_reset_token, QuicRandom::GetInstance()); } std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildIetfStatelessResetPacket( QuicConnectionId , size_t received_packet_length, StatelessResetToken stateless_reset_token, QuicRandom* random) { QUIC_DVLOG(1) << "Building IETF stateless reset packet."; if (received_packet_length <= GetMinStatelessResetPacketLength()) { QUICHE_DLOG(ERROR) << "Tried to build stateless reset packet with received packet " "length " << received_packet_length; return nullptr; } size_t len = std::min(received_packet_length - 1, GetMinStatelessResetPacketLength() + 1 + kQuicMaxConnectionIdWithLengthPrefixLength); std::unique_ptr<char[]> buffer(new char[len]); QuicDataWriter writer(len, buffer.get()); const size_t random_bytes_size = len - kStatelessResetTokenLength; if (!writer.WriteInsecureRandomBytes(random, random_bytes_size)) { QUIC_BUG(362045737_2) << "Failed to append random bytes of length: " << random_bytes_size; return nullptr; } buffer[0] &= ~FLAGS_LONG_HEADER; buffer[0] |= FLAGS_FIXED_BIT; if (!writer.WriteBytes(&stateless_reset_token, sizeof(stateless_reset_token))) { QUIC_BUG(362045737_3) << "Failed to write stateless reset token"; return nullptr; } return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true); } std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildVersionNegotiationPacket( QuicConnectionId server_connection_id, QuicConnectionId client_connection_id, bool ietf_quic, bool use_length_prefix, const ParsedQuicVersionVector& versions) { QUIC_CODE_COUNT(quic_build_version_negotiation); if (use_length_prefix) { QUICHE_DCHECK(ietf_quic); QUIC_CODE_COUNT(quic_build_version_negotiation_ietf); } else if (ietf_quic) { QUIC_CODE_COUNT(quic_build_version_negotiation_old_ietf); } else { QUIC_CODE_COUNT(quic_build_version_negotiation_old_gquic); } ParsedQuicVersionVector wire_versions = versions; if (wire_versions.empty()) { wire_versions = {QuicVersionReservedForNegotiation(), QuicVersionReservedForNegotiation()}; } else { size_t version_index = 0; const bool disable_randomness = GetQuicFlag(quic_disable_version_negotiation_grease_randomness); if (!disable_randomness) { version_index = QuicRandom::GetInstance()->RandUint64() % (wire_versions.size() + 1); } wire_versions.insert(wire_versions.begin() + version_index, QuicVersionReservedForNegotiation()); } if (ietf_quic) { return BuildIetfVersionNegotiationPacket( use_length_prefix, server_connection_id, client_connection_id, wire_versions); } QUICHE_DCHECK(client_connection_id.IsEmpty()); QUICHE_DCHECK(!use_length_prefix); QUICHE_DCHECK(!wire_versions.empty()); size_t len = kPublicFlagsSize + server_connection_id.length() + wire_versions.size() * kQuicVersionSize; std::unique_ptr<char[]> buffer(new char[len]); QuicDataWriter writer(len, buffer.get()); uint8_t flags = static_cast<uint8_t>( PACKET_PUBLIC_FLAGS_VERSION | PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID | PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD); if (!writer.WriteUInt8(flags)) { return nullptr; } if (!writer.WriteConnectionId(server_connection_id)) { return nullptr; } for (const ParsedQuicVersion& version : wire_versions) { if (!writer.WriteUInt32(CreateQuicVersionLabel(version))) { return nullptr; } } return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true); } std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildIetfVersionNegotiationPacket( bool use_length_prefix, QuicConnectionId server_connection_id, QuicConnectionId client_connection_id, const ParsedQuicVersionVector& versions) { QUIC_DVLOG(1) << "Building IETF version negotiation packet with" << (use_length_prefix ? "" : "out") << " length prefix, server_connection_id " << server_connection_id << " client_connection_id " << client_connection_id << " versions " << ParsedQuicVersionVectorToString(versions); QUICHE_DCHECK(!versions.empty()); size_t len = kPacketHeaderTypeSize + kConnectionIdLengthSize + client_connection_id.length() + server_connection_id.length() + (versions.size() + 1) * kQuicVersionSize; if (use_length_prefix) { len += kConnectionIdLengthSize; } std::unique_ptr<char[]> buffer(new char[len]); QuicDataWriter writer(len, buffer.get()); uint8_t type = static_cast<uint8_t>(FLAGS_LONG_HEADER | FLAGS_FIXED_BIT); if (!writer.WriteUInt8(type)) { return nullptr; } if (!writer.WriteUInt32(0)) { return nullptr; } if (!AppendIetfConnectionIds(true, use_length_prefix, client_connection_id, server_connection_id, &writer)) { return nullptr; } for (const ParsedQuicVersion& version : versions) { if (!writer.WriteUInt32(CreateQuicVersionLabel(version))) { return nullptr; } } return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true); } bool QuicFramer::ProcessPacket(const QuicEncryptedPacket& packet) { QUICHE_DCHECK(!is_processing_packet_) << ENDPOINT << "Nested ProcessPacket"; is_processing_packet_ = true; bool result = ProcessPacketInternal(packet); is_processing_packet_ = false; return result; } bool QuicFramer::ProcessPacketInternal(const QuicEncryptedPacket& packet) { QuicDataReader reader(packet.data(), packet.length()); QUIC_DVLOG(1) << ENDPOINT << "Processing IETF QUIC packet."; visitor_->OnPacket(); QuicPacketHeader header; if (!ProcessIetfPacketHeader(&reader, &header)) { QUICHE_DCHECK_NE("", detailed_error_); QUIC_DVLOG(1) << ENDPOINT << "Unable to process public header. Error: " << detailed_error_; QUICHE_DCHECK_NE("", detailed_error_); RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_HEADER); return RaiseError(QUIC_INVALID_PACKET_HEADER); } if (!visitor_->OnUnauthenticatedPublicHeader(header)) { return true; } if (IsVersionNegotiation(header)) { if (perspective_ == Perspective::IS_CLIENT) { QUIC_DVLOG(1) << "Client received version negotiation packet"; return ProcessVersionNegotiationPacket(&reader, header); } else { QUIC_DLOG(ERROR) << "Server received version negotiation packet"; set_detailed_error("Server received version negotiation packet."); return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET); } } if (header.version_flag && header.version != version_) { if (perspective_ == Perspective::IS_SERVER) { if (!visitor_->OnProtocolVersionMismatch(header.version)) { RecordDroppedPacketReason(DroppedPacketReason::VERSION_MISMATCH); return true; } } else { QUIC_DLOG(ERROR) << "Client received unexpected version " << ParsedQuicVersionToString(header.version) << " instead of " << ParsedQuicVersionToString(version_); set_detailed_error("Client received unexpected version."); return RaiseError(QUIC_PACKET_WRONG_VERSION); } } bool rv; if (header.long_packet_type == RETRY) { rv = ProcessRetryPacket(&reader, header); } else if (packet.length() <= kMaxIncomingPacketSize) { ABSL_CACHELINE_ALIGNED char buffer[kMaxIncomingPacketSize]; rv = ProcessIetfDataPacket(&reader, &header, packet, buffer, ABSL_ARRAYSIZE(buffer)); } else { std::unique_ptr<char[]> large_buffer(new char[packet.length()]); rv = ProcessIetfDataPacket(&reader, &header, packet, large_buffer.get(), packet.length()); QUIC_BUG_IF(quic_bug_10850_53, rv) << "QUIC should never successfully process packets larger" << "than kMaxIncomingPacketSize. packet size:" << packet.length(); } return rv; } bool QuicFramer::ProcessVersionNegotiationPacket( QuicDataReader* reader, const QuicPacketHeader& header) { QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, perspective_); QuicVersionNegotiationPacket packet( GetServerConnectionIdAsRecipient(header, perspective_)); do { QuicVersionLabel version_label; if (!ProcessVersionLabel(reader, &version_label)) { set_detailed_error("Unable to read supported version in negotiation."); RecordDroppedPacketReason( DroppedPacketReason::INVALID_VERSION_NEGOTIATION_PACKET); return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET); } ParsedQuicVersion parsed_version = ParseQuicVersionLabel(version_label); if (parsed_version != UnsupportedQuicVersion()) { packet.versions.push_back(parsed_version); } } while (!reader->IsDoneReading()); QUIC_DLOG(INFO) << ENDPOINT << "parsed version negotiation: " << ParsedQuicVersionVectorToString(packet.versions); visitor_->OnVersionNegotiationPacket(packet); return true; } bool QuicFramer::ProcessRetryPacket(QuicDataReader* reader, const QuicPacketHeader& header) { QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, perspective_); if (drop_incoming_retry_packets_) { QUIC_DLOG(INFO) << "Ignoring received RETRY packet"; return true; } if (version_.UsesTls()) { QUICHE_DCHECK(version_.HasLengthPrefixedConnectionIds()) << version_; const size_t bytes_remaining = reader->BytesRemaining(); if (bytes_remaining <= kRetryIntegrityTagLength) { set_detailed_error("Retry packet too short to parse integrity tag."); return false; } const size_t retry_token_length = bytes_remaining - kRetryIntegrityTagLength; QUICHE_DCHECK_GT(retry_token_length, 0u); absl::string_view retry_token; if (!reader->ReadStringPiece(&retry_token, retry_token_length)) { set_detailed_error("Failed to read retry token."); return false; } absl::string_view retry_without_tag = reader->PreviouslyReadPayload(); absl::string_view integrity_tag = reader->ReadRemainingPayload(); QUICHE_DCHECK_EQ(integrity_tag.length(), kRetryIntegrityTagLength); visitor_->OnRetryPacket(EmptyQuicConnectionId(), header.source_connection_id, retry_token, integrity_tag, retry_without_tag); return true; } QuicConnectionId original_destination_connection_id; if (version_.HasLengthPrefixedConnectionIds()) { if (!reader->ReadLengthPrefixedConnectionId( &original_destination_connection_id)) { set_detailed_error("Unable to read Original Destination ConnectionId."); return false; } } else { uint8_t odcil = header.type_byte & 0xf; if (odcil != 0) { odcil += kConnectionIdLengthAdjustment; } if (!reader->ReadConnectionId(&original_destination_connection_id, odcil)) { set_detailed_error("Unable to read Original Destination ConnectionId."); return false; } } if (!QuicUtils::IsConnectionIdValidForVersion( original_destination_connection_id, transport_version())) { set_detailed_error( "Received Original Destination ConnectionId with invalid length."); return false; } absl::string_view retry_token = reader->ReadRemainingPayload(); visitor_->OnRetryPacket(original_destination_connection_id, header.source_connection_id, retry_token, absl::string_view(), absl::string_view()); return true; } void QuicFramer::MaybeProcessCoalescedPacket( const QuicDataReader& encrypted_reader, uint64_t remaining_bytes_length, const QuicPacketHeader& header) { if (header.remaining_packet_length >= remaining_bytes_length) { return; } absl::string_view remaining_data = encrypted_reader.PeekRemainingPayload(); QUICHE_DCHECK_EQ(remaining_data.length(), remaining_bytes_length); const char* coalesced_data = remaining_data.data() + header.remaining_packet_length; uint64_t coalesced_data_length = remaining_bytes_length - header.remaining_packet_length; QuicDataReader coalesced_reader(coalesced_data, coalesced_data_length); QuicPacketHeader coalesced_header; if (!ProcessIetfPacketHeader(&coalesced_reader, &coalesced_header)) { QUIC_DLOG(INFO) << ENDPOINT << "Failed to parse received coalesced header of length " << coalesced_data_length << " with error: " << detailed_error_ << ": " << absl::BytesToHexString(absl::string_view( coalesced_data, coalesced_data_length)) << " previous header was " << header; return; } if (coalesced_header.destination_connection_id != header.destination_connection_id) { QUIC_DLOG(INFO) << ENDPOINT << "Received mismatched coalesced header " << coalesced_header << " previous header was " << header; QUIC_CODE_COUNT( quic_received_coalesced_packets_with_mismatched_connection_id); return; } QuicEncryptedPacket coalesced_packet(coalesced_data, coalesced_data_length, false); visitor_->OnCoalescedPacket(coalesced_packet); } bool QuicFramer::MaybeProcessIetfLength(QuicDataReader* encrypted_reader, QuicPacketHeader* header) { if (!QuicVersionHasLongHeaderLengths(header->version.transport_version) || header->form != IETF_QUIC_LONG_HEADER_PACKET || (header->long_packet_type != INITIAL && header->long_packet_type != HANDSHAKE && header->long_packet_type != ZERO_RTT_PROTECTED)) { return true; } header->length_length = encrypted_reader->PeekVarInt62Length(); if (!encrypted_reader->ReadVarInt62(&header->remaining_packet_length)) { set_detailed_error("Unable to read long header payload length."); return RaiseError(QUIC_INVALID_PACKET_HEADER); } uint64_t remaining_bytes_length = encrypted_reader->BytesRemaining(); if (header->remaining_packet_length > remaining_bytes_length) { set_detailed_error("Long header payload length longer than packet."); return RaiseError(QUIC_INVALID_PACKET_HEADER); } MaybeProcessCoalescedPacket(*encrypted_reader, remaining_bytes_length, *header); if (!encrypted_reader->TruncateRemaining(header->remaining_packet_length)) { set_detailed_error("Length TruncateRemaining failed."); QUIC_BUG(quic_bug_10850_54) << "Length TruncateRemaining failed."; return RaiseError(QUIC_INVALID_PACKET_HEADER); } return true; } bool QuicFramer::ProcessIetfDataPacket(QuicDataReader* encrypted_reader, QuicPacketHeader* header, const QuicEncryptedPacket& packet, char* decrypted_buffer, size_t buffer_length) { QUICHE_DCHECK_NE(GOOGLE_QUIC_PACKET, header->form); QUICHE_DCHECK(!header->has_possible_stateless_reset_token); header->length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0; header->remaining_packet_length = 0; if (header->form == IETF_QUIC_SHORT_HEADER_PACKET && perspective_ == Perspective::IS_CLIENT) { absl::string_view remaining = encrypted_reader->PeekRemainingPayload(); if (remaining.length() >= sizeof(header->possible_stateless_reset_token)) { header->has_possible_stateless_reset_token = true; memcpy(&header->possible_stateless_reset_token, &remaining.data()[remaining.length() - sizeof(header->possible_stateless_reset_token)], sizeof(header->possible_stateless_reset_token)); } } if (!MaybeProcessIetfLength(encrypted_reader, header)) { return false; } absl::string_view associated_data; AssociatedDataStorage ad_storage; QuicPacketNumber base_packet_number; if (header->form == IETF_QUIC_SHORT_HEADER_PACKET || header->long_packet_type != VERSION_NEGOTIATION) { QUICHE_DCHECK(header->form == IETF_QUIC_SHORT_HEADER_PACKET || header->long_packet_type == INITIAL || header->long_packet_type == HANDSHAKE || header->long_packet_type == ZERO_RTT_PROTECTED); if (supports_multiple_packet_number_spaces_) { PacketNumberSpace pn_space = GetPacketNumberSpace(*header); if (pn_space == NUM_PACKET_NUMBER_SPACES) { return RaiseError(QUIC_INVALID_PACKET_HEADER); } base_packet_number = largest_decrypted_packet_numbers_[pn_space]; } else { base_packet_number = largest_packet_number_; } uint64_t full_packet_number; bool hp_removal_failed = false; if (version_.HasHeaderProtection()) { EncryptionLevel expected_decryption_level = GetEncryptionLevel(*header); QuicDecrypter* decrypter = decrypter_[expected_decryption_level].get(); if (decrypter == nullptr) { QUIC_DVLOG(1) << ENDPOINT << "No decrypter available for removing header protection at level " << expected_decryption_level; hp_removal_failed = true; } else if (!RemoveHeaderProtection(encrypted_reader, packet, *decrypter, perspective_, version_, base_packet_number, header, &full_packet_number, ad_storage)) { hp_removal_failed = true; } associated_data = absl::string_view(ad_storage.data(), ad_storage.size()); } else if (!ProcessAndCalculatePacketNumber( encrypted_reader, header->packet_number_length, base_packet_number, &full_packet_number)) { set_detailed_error("Unable to read packet number."); RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER); return RaiseError(QUIC_INVALID_PACKET_HEADER); } if (hp_removal_failed || !IsValidFullPacketNumber(full_packet_number, version())) { if (IsIetfStatelessResetPacket(*header)) { QuicIetfStatelessResetPacket reset_packet( *header, header->possible_stateless_reset_token); visitor_->OnAuthenticatedIetfStatelessResetPacket(reset_packet); return true; } if (hp_removal_failed) { const EncryptionLevel decryption_level = GetEncryptionLevel(*header); const bool has_decryption_key = decrypter_[decryption_level] != nullptr; visitor_->OnUndecryptablePacket( QuicEncryptedPacket(encrypted_reader->FullPayload()), decryption_level, has_decryption_key); RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE); set_detailed_error(absl::StrCat( "Unable to decrypt ", EncryptionLevelToString(decryption_level), " header protection", has_decryption_key ? "" : " (missing key)", ".")); return RaiseError(QUIC_DECRYPTION_FAILURE); } RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER); set_detailed_error("packet numbers cannot be 0."); return RaiseError(QUIC_INVALID_PACKET_HEADER); } header->packet_number = QuicPacketNumber(full_packet_number); } if (header->form == IETF_QUIC_LONG_HEADER_PACKET && header->long_packet_type == ZERO_RTT_PROTECTED && perspective_ == Perspective::IS_CLIENT && version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO) { if (!encrypted_reader->ReadBytes( reinterpret_cast<uint8_t*>(last_nonce_.data()), last_nonce_.size())) { set_detailed_error("Unable to read nonce."); RecordDroppedPacketReason( DroppedPacketReason::INVALID_DIVERSIFICATION_NONCE); return RaiseError(QUIC_INVALID_PACKET_HEADER); } header->nonce = &last_nonce_; } else { header->nonce = nullptr; } if (!visitor_->OnUnauthenticatedHeader(*header)) { set_detailed_error( "Visitor asked to stop processing of unauthenticated header."); return false; } absl::string_view encrypted = encrypted_reader->ReadRemainingPayload(); if (!version_.HasHeaderProtection()) { associated_data = GetAssociatedDataFromEncryptedPacket( version_.transport_version, packet, 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 decrypted_length = 0; EncryptionLevel decrypted_level; if (!DecryptPayload(packet.length(), encrypted, associated_data, *header, decrypted_buffer, buffer_length, &decrypted_length, &decrypted_level)) { if (IsIetfStatelessResetPacket(*header)) { QuicIetfStatelessResetPacket reset_packet( *header, header->possible_stateless_reset_token); visitor_->OnAuthenticatedIetfStatelessResetPacket(reset_packet); return true; } const EncryptionLevel decryption_level = GetEncryptionLevel(*header); const bool has_decryption_key = version_.KnowsWhichDecrypterToUse() && decrypter_[decryption_level] != nullptr; visitor_->OnUndecryptablePacket( QuicEncryptedPacket(encrypted_reader->FullPayload()), decryption_level, has_decryption_key); set_detailed_error(absl::StrCat( "Unable to decrypt ", EncryptionLevelToString(decryption_level), " payload with reconstructed packet number ", header->packet_number.ToString(), " (largest decrypted was ", base_packet_number.ToString(), ")", has_decryption_key || !version_.KnowsWhichDecrypterToUse() ? "" : " (missing key)", ".")); RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE); return RaiseError(QUIC_DECRYPTION_FAILURE); } if (packet.length() > kMaxIncomingPacketSize) { set_detailed_error("Packet too large."); return RaiseError(QUIC_PACKET_TOO_LARGE); } QuicDataReader reader(decrypted_buffer, decrypted_length); if (supports_multiple_packet_number_spaces_) { largest_decrypted_packet_numbers_[QuicUtils::GetPacketNumberSpace( decrypted_level)] .UpdateMax(header->packet_number); } else { largest_packet_number_.UpdateMax(header->packet_number); } if (!visitor_->OnPacketHeader(*header)) { RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER); return true; } if (VersionHasIetfQuicFrames(version_.transport_version)) { current_received_frame_type_ = 0; previously_received_frame_type_ = 0; if (!ProcessIetfFrameData(&reader, *header, decrypted_level)) { current_received_frame_type_ = 0; previously_received_frame_type_ = 0; QUICHE_DCHECK_NE(QUIC_NO_ERROR, error_); QUICHE_DCHECK_NE("", detailed_error_); QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: " << detailed_error_; return false; } current_received_frame_type_ = 0; previously_received_frame_type_ = 0; } else { if (!ProcessFrameData(&reader, *header)) { QUICHE_DCHECK_NE(QUIC_NO_ERROR, error_); QUICHE_DCHECK_NE("", detailed_error_); QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: " << detailed_error_; return false; } } visitor_->OnPacketComplete(); return true; } bool QuicFramer::IsIetfStatelessResetPacket( const QuicPacketHeader& header) const { QUIC_BUG_IF(quic_bug_12975_3, header.has_possible_stateless_reset_token && perspective_ != Perspective::IS_CLIENT) << "has_possible_stateless_reset_token can only be true at client side."; return header.form == IETF_QUIC_SHORT_HEADER_PACKET && header.has_possible_stateless_reset_token && visitor_->IsValidStatelessResetToken( header.possible_stateless_reset_token); } bool QuicFramer::HasEncrypterOfEncryptionLevel(EncryptionLevel level) const { return encrypter_[level] != nullptr; } bool QuicFramer::HasDecrypterOfEncryptionLevel(EncryptionLevel level) const { return decrypter_[level] != nullptr; } bool QuicFramer::HasAnEncrypterForSpace(PacketNumberSpace space) const { switch (space) { case INITIAL_DATA: return HasEncrypterOfEncryptionLevel(ENCRYPTION_INITIAL); case HANDSHAKE_DATA: return HasEncrypterOfEncryptionLevel(ENCRYPTION_HANDSHAKE); case APPLICATION_DATA: return HasEncrypterOfEncryptionLevel(ENCRYPTION_ZERO_RTT) || HasEncrypterOfEncryptionLevel(ENCRYPTION_FORWARD_SECURE); case NUM_PACKET_NUMBER_SPACES: break; } QUIC_BUG(quic_bug_10850_55) << ENDPOINT << "Try to send data of space: " << PacketNumberSpaceToString(space); return false; } EncryptionLevel QuicFramer::GetEncryptionLevelToSendApplicationData() const { if (!HasAnEncrypterForSpace(APPLICATION_DATA)) { QUIC_BUG(quic_bug_12975_4) << "Tried to get encryption level to send application data with no " "encrypter available."; return NUM_ENCRYPTION_LEVELS; } if (HasEncrypterOfEncryptionLevel(ENCRYPTION_FORWARD_SECURE)) { return ENCRYPTION_FORWARD_SECURE; } QUICHE_DCHECK(HasEncrypterOfEncryptionLevel(ENCRYPTION_ZERO_RTT)); return ENCRYPTION_ZERO_RTT; } bool QuicFramer::AppendIetfHeaderTypeByte(const QuicPacketHeader& header, QuicDataWriter* writer) { uint8_t type = 0; if (header.version_flag) { type = static_cast<uint8_t>( FLAGS_LONG_HEADER | FLAGS_FIXED_BIT | LongHeaderTypeToOnWireValue(header.long_packet_type, version_) | PacketNumberLengthToOnWireValue(header.packet_number_length)); } else { type = static_cast<uint8_t>( FLAGS_FIXED_BIT | (current_key_phase_bit_ ? FLAGS_KEY_PHASE_BIT : 0) | PacketNumberLengthToOnWireValue(header.packet_number_length)); } return writer->WriteUInt8(type); } bool QuicFramer::AppendIetfPacketHeader(const QuicPacketHeader& header, QuicDataWriter* writer, size_t* length_field_offset) { QUIC_DVLOG(1) << ENDPOINT << "Appending IETF header: " << header; QuicConnectionId server_connection_id = GetServerConnectionIdAsSender(header, perspective_); QUIC_BUG_IF(quic_bug_12975_6, !QuicUtils::IsConnectionIdValidForVersion( server_connection_id, transport_version())) << "AppendIetfPacketHeader: attempted to use connection ID " << server_connection_id << " which is invalid with version " << version(); if (!AppendIetfHeaderTypeByte(header, writer)) { return false; } if (header.version_flag) { QUICHE_DCHECK_NE(VERSION_NEGOTIATION, header.long_packet_type) << "QuicFramer::AppendIetfPacketHeader does not support sending " "version negotiation packets, use " "QuicFramer::BuildVersionNegotiationPacket instead " << header; QuicVersionLabel version_label = CreateQuicVersionLabel(version_); if (!writer->WriteUInt32(version_label)) { return false; } } if (!AppendIetfConnectionIds( header.version_flag, version_.HasLengthPrefixedConnectionIds(), header.destination_connection_id_included != CONNECTION_ID_ABSENT ? header.destination_connection_id : EmptyQuicConnectionId(), header.source_connection_id_included != CONNECTION_ID_ABSENT ? header.source_connection_id : EmptyQuicConnectionId(), writer)) { return false; } last_serialized_server_connection_id_ = server_connection_id; QUIC_BUG_IF(quic_bug_12975_7, header.version_flag && header.long_packet_type == RETRY) << "Sending IETF RETRY packets is not currently supported " << header; if (QuicVersionHasLongHeaderLengths(transport_version()) && header.version_flag) { if (header.long_packet_type == INITIAL) { QUICHE_DCHECK_NE(quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0, header.retry_token_length_length) << ENDPOINT << ParsedQuicVersionToString(version_) << " bad retry token length length in header: " << header; if (!writer->WriteVarInt62WithForcedLength( header.retry_token.length(), header.retry_token_length_length)) { return false; } if (!header.retry_token.empty() && !writer->WriteStringPiece(header.retry_token)) { return false; } } if (length_field_offset != nullptr) { *length_field_offset = writer->length(); } writer->WriteVarInt62(256); } else if (length_field_offset != nullptr) { *length_field_offset = 0; } if (!AppendPacketNumber(header.packet_number_length, header.packet_number, writer)) { return false; } last_written_packet_number_length_ = header.packet_number_length; if (!header.version_flag) { return true; } if (header.nonce != nullptr) { QUICHE_DCHECK(header.version_flag); QUICHE_DCHECK_EQ(ZERO_RTT_PROTECTED, header.long_packet_type); QUICHE_DCHECK_EQ(Perspective::IS_SERVER, perspective_); if (!writer->WriteBytes(header.nonce, kDiversificationNonceSize)) { return false; } } return true; } const QuicTime::Delta QuicFramer::CalculateTimestampFromWire( uint32_t time_delta_us) { const uint64_t epoch_delta = UINT64_C(1) << 32; uint64_t epoch = last_timestamp_.ToMicroseconds() & ~(epoch_delta - 1); uint64_t prev_epoch = epoch - epoch_delta; uint64_t next_epoch = epoch + epoch_delta; uint64_t time = ClosestTo( last_timestamp_.ToMicroseconds(), epoch + time_delta_us, ClosestTo(last_timestamp_.ToMicroseconds(), prev_epoch + time_delta_us, next_epoch + time_delta_us)); return QuicTime::Delta::FromMicroseconds(time); } uint64_t QuicFramer::CalculatePacketNumberFromWire( QuicPacketNumberLength packet_number_length, QuicPacketNumber base_packet_number, uint64_t packet_number) { if (!base_packet_number.IsInitialized()) { return packet_number; } const uint64_t epoch_delta = UINT64_C(1) << (8 * packet_number_length); uint64_t next_packet_number = base_packet_number.ToUint64() + 1; uint64_t epoch = base_packet_number.ToUint64() & ~(epoch_delta - 1); uint64_t prev_epoch = epoch - epoch_delta; uint64_t next_epoch = epoch + epoch_delta; return ClosestTo(next_packet_number, epoch + packet_number, ClosestTo(next_packet_number, prev_epoch + packet_number, next_epoch + packet_number)); } QuicPacketNumberLength QuicFramer::GetMinPacketNumberLength( QuicPacketNumber packet_number) { QUICHE_DCHECK(packet_number.IsInitialized()); if (packet_number < QuicPacketNumber(1 << (PACKET_1BYTE_PACKET_NUMBER * 8))) { return PACKET_1BYTE_PACKET_NUMBER; } else if (packet_number < QuicPacketNumber(1 << (PACKET_2BYTE_PACKET_NUMBER * 8))) { return PACKET_2BYTE_PACKET_NUMBER; } else if (packet_number < QuicPacketNumber(UINT64_C(1) << (PACKET_4BYTE_PACKET_NUMBER * 8))) { return PACKET_4BYTE_PACKET_NUMBER; } else { return PACKET_6BYTE_PACKET_NUMBER; } } uint8_t QuicFramer::GetPacketNumberFlags( QuicPacketNumberLength packet_number_length) { switch (packet_number_length) { case PACKET_1BYTE_PACKET_NUMBER: return PACKET_FLAGS_1BYTE_PACKET; case PACKET_2BYTE_PACKET_NUMBER: return PACKET_FLAGS_2BYTE_PACKET; case PACKET_4BYTE_PACKET_NUMBER: return PACKET_FLAGS_4BYTE_PACKET; case PACKET_6BYTE_PACKET_NUMBER: case PACKET_8BYTE_PACKET_NUMBER: return PACKET_FLAGS_8BYTE_PACKET; default: QUIC_BUG(quic_bug_10850_56) << "Unreachable case statement."; return PACKET_FLAGS_8BYTE_PACKET; } } QuicFramer::AckFrameInfo QuicFramer::GetAckFrameInfo( const QuicAckFrame& frame) { AckFrameInfo new_ack_info; if (frame.packets.Empty()) { return new_ack_info; } new_ack_info.first_block_length = frame.packets.LastIntervalLength(); auto itr = frame.packets.rbegin(); QuicPacketNumber previous_start = itr->min(); new_ack_info.max_block_length = itr->Length(); ++itr; for (; itr != frame.packets.rend() && new_ack_info.num_ack_blocks < std::numeric_limits<uint8_t>::max(); previous_start = itr->min(), ++itr) { const auto& interval = *itr; const QuicPacketCount total_gap = previous_start - interval.max(); new_ack_info.num_ack_blocks += (total_gap + std::numeric_limits<uint8_t>::max() - 1) / std::numeric_limits<uint8_t>::max(); new_ack_info.max_block_length = std::max(new_ack_info.max_block_length, interval.Length()); } return new_ack_info; } bool QuicFramer::ProcessIetfHeaderTypeByte(QuicDataReader* reader, QuicPacketHeader* header) { uint8_t type; if (!reader->ReadBytes(&type, 1)) { set_detailed_error("Unable to read first byte."); return false; } header->type_byte = type; header->form = GetIetfPacketHeaderFormat(type); if (header->form == IETF_QUIC_LONG_HEADER_PACKET) { header->version_flag = true; header->destination_connection_id_included = (perspective_ == Perspective::IS_SERVER || version_.SupportsClientConnectionIds()) ? CONNECTION_ID_PRESENT : CONNECTION_ID_ABSENT; header->source_connection_id_included = (perspective_ == Perspective::IS_CLIENT || version_.SupportsClientConnectionIds()) ? CONNECTION_ID_PRESENT : CONNECTION_ID_ABSENT; QuicVersionLabel version_label; if (!ProcessVersionLabel(reader, &version_label)) { set_detailed_error("Unable to read protocol version."); return false; } if (!version_label) { header->long_packet_type = VERSION_NEGOTIATION; } else { header->version = ParseQuicVersionLabel(version_label); if (header->version.IsKnown()) { if (!(type & FLAGS_FIXED_BIT)) { set_detailed_error("Fixed bit is 0 in long header."); return false; } header->long_packet_type = GetLongHeaderType(type, header->version); switch (header->long_packet_type) { case INVALID_PACKET_TYPE: set_detailed_error("Illegal long header type value."); return false; case RETRY: if (!version().SupportsRetry()) { set_detailed_error("RETRY not supported in this version."); return false; } if (perspective_ == Perspective::IS_SERVER) { set_detailed_error("Client-initiated RETRY is invalid."); return false; } break; default: if (!header->version.HasHeaderProtection()) { header->packet_number_length = GetLongHeaderPacketNumberLength(type); } break; } } } QUIC_DVLOG(1) << ENDPOINT << "Received IETF long header: " << QuicUtils::QuicLongHeaderTypetoString( header->long_packet_type); return true; } QUIC_DVLOG(1) << ENDPOINT << "Received IETF short header"; header->version_flag = false; header->destination_connection_id_included = (perspective_ == Perspective::IS_SERVER || version_.SupportsClientConnectionIds()) ? CONNECTION_ID_PRESENT : CONNECTION_ID_ABSENT; header->source_connection_id_included = CONNECTION_ID_ABSENT; if (!(type & FLAGS_FIXED_BIT)) { set_detailed_error("Fixed bit is 0 in short header."); return false; } if (!version_.HasHeaderProtection()) { header->packet_number_length = GetShortHeaderPacketNumberLength(type); } QUIC_DVLOG(1) << "packet_number_length = " << header->packet_number_length; return true; } bool QuicFramer::ProcessVersionLabel(QuicDataReader* reader, QuicVersionLabel* version_label) { if (!reader->ReadUInt32(version_label)) { return false; } return true; } bool QuicFramer::ProcessAndValidateIetfConnectionIdLength( QuicDataReader* reader, ParsedQuicVersion version, Perspective perspective, bool should_update_expected_server_connection_id_length, uint8_t* expected_server_connection_id_length, uint8_t* destination_connection_id_length, uint8_t* source_connection_id_length, std::string* detailed_error) { uint8_t connection_id_lengths_byte; if (!reader->ReadBytes(&connection_id_lengths_byte, 1)) { *detailed_error = "Unable to read ConnectionId length."; return false; } uint8_t dcil = (connection_id_lengths_byte & kDestinationConnectionIdLengthMask) >> 4; if (dcil != 0) { dcil += kConnectionIdLengthAdjustment; } uint8_t scil = connection_id_lengths_byte & kSourceConnectionIdLengthMask; if (scil != 0) { scil += kConnectionIdLengthAdjustment; } if (should_update_expected_server_connection_id_length) { uint8_t server_connection_id_length = perspective == Perspective::IS_SERVER ? dcil : scil; if (*expected_server_connection_id_length != server_connection_id_length) { QUIC_DVLOG(1) << "Updating expected_server_connection_id_length: " << static_cast<int>(*expected_server_connection_id_length) << " -> " << static_cast<int>(server_connection_id_length); *expected_server_connection_id_length = server_connection_id_length; } } if (!should_update_expected_server_connection_id_length && (dcil != *destination_connection_id_length || scil != *source_connection_id_length) && version.IsKnown() && !version.AllowsVariableLengthConnectionIds()) { QUIC_DVLOG(1) << "dcil: " << static_cast<uint32_t>(dcil) << ", scil: " << static_cast<uint32_t>(scil); *detailed_error = "Invalid ConnectionId length."; return false; } *destination_connection_id_length = dcil; *source_connection_id_length = scil; return true; } bool QuicFramer::ValidateReceivedConnectionIds(const QuicPacketHeader& header) { bool skip_server_connection_id_validation = perspective_ == Perspective::IS_CLIENT && header.form == IETF_QUIC_SHORT_HEADER_PACKET; if (!skip_server_connection_id_validation && !QuicUtils::IsConnectionIdValidForVersion( GetServerConnectionIdAsRecipient(header, perspective_), transport_version())) { set_detailed_error("Received server connection ID with invalid length."); return false; } bool skip_client_connection_id_validation = perspective_ == Perspective::IS_SERVER && header.form == IETF_QUIC_SHORT_HEADER_PACKET; if (!skip_client_connection_id_validation && version_.SupportsClientConnectionIds() && !QuicUtils::IsConnectionIdValidForVersion( GetClientConnectionIdAsRecipient(header, perspective_), transport_version())) { set_detailed_error("Received client connection ID with invalid length."); return false; } return true; } bool QuicFramer::ProcessIetfPacketHeader(QuicDataReader* reader, QuicPacketHeader* header) { if (version_.HasLengthPrefixedConnectionIds()) { uint8_t expected_destination_connection_id_length = perspective_ == Perspective::IS_CLIENT ? expected_client_connection_id_length_ : expected_server_connection_id_length_; QuicVersionLabel version_label; bool has_length_prefix; std::string detailed_error; QuicErrorCode parse_result = QuicFramer::ParsePublicHeader( reader, expected_destination_connection_id_length, true, &header->type_byte, &header->form, &header->version_flag, &has_length_prefix, &version_label, &header->version, &header->destination_connection_id, &header->source_connection_id, &header->long_packet_type, &header->retry_token_length_length, &header->retry_token, &detailed_error); if (parse_result != QUIC_NO_ERROR) { set_detailed_error(detailed_error); return false; } header->destination_connection_id_included = CONNECTION_ID_PRESENT; header->source_connection_id_included = header->version_flag ? CONNECTION_ID_PRESENT : CONNECTION_ID_ABSENT; if (!ValidateReceivedConnectionIds(*header)) { return false; } if (header->version_flag && header->long_packet_type != VERSION_NEGOTIATION && !(header->type_byte & FLAGS_FIXED_BIT)) { set_detailed_error("Fixed bit is 0 in long header."); return false; } if (!header->version_flag && !(header->type_byte & FLAGS_FIXED_BIT)) { set_detailed_error("Fixed bit is 0 in short header."); return false; } if (!header->version_flag) { if (!version_.HasHeaderProtection()) { header->packet_number_length = GetShortHeaderPacketNumberLength(header->type_byte); } return true; } if (header->long_packet_type == RETRY) { if (!version().SupportsRetry()) { set_detailed_error("RETRY not supported in this version."); return false; } if (perspective_ == Perspective::IS_SERVER) { set_detailed_error("Client-initiated RETRY is invalid."); return false; } return true; } if (header->version.IsKnown() && !header->version.HasHeaderProtection()) { header->packet_number_length = GetLongHeaderPacketNumberLength(header->type_byte); } return true; } if (!ProcessIetfHeaderTypeByte(reader, header)) { return false; } uint8_t destination_connection_id_length = header->destination_connection_id_included == CONNECTION_ID_PRESENT ? (perspective_ == Perspective::IS_SERVER ? expected_server_connection_id_length_ : expected_client_connection_id_length_) : 0; uint8_t source_connection_id_length = header->source_connection_id_included == CONNECTION_ID_PRESENT ? (perspective_ == Perspective::IS_CLIENT ? expected_server_connection_id_length_ : expected_client_connection_id_length_) : 0; if (header->form == IETF_QUIC_LONG_HEADER_PACKET) { if (!ProcessAndValidateIetfConnectionIdLength( reader, header->version, perspective_, false, &expected_server_connection_id_length_, &destination_connection_id_length, &source_connection_id_length, &detailed_error_)) { return false; } } if (!reader->ReadConnectionId(&header->destination_connection_id, destination_connection_id_length)) { set_detailed_error("Unable to read destination connection ID."); return false; } if (!reader->ReadConnectionId(&header->source_connection_id, source_connection_id_length)) { set_detailed_error("Unable to read source connection ID."); return false; } if (header->source_connection_id_included == CONNECTION_ID_ABSENT) { if (!header->source_connection_id.IsEmpty()) { QUICHE_DCHECK(!version_.SupportsClientConnectionIds()); set_detailed_error("Client connection ID not supported in this version."); return false; } } return ValidateReceivedConnectionIds(*header); } bool QuicFramer::ProcessAndCalculatePacketNumber( QuicDataReader* reader, QuicPacketNumberLength packet_number_length, QuicPacketNumber base_packet_number, uint64_t* packet_number) { uint64_t wire_packet_number; if (!reader->ReadBytesToUInt64(packet_number_length, &wire_packet_number)) { return false; } *packet_number = CalculatePacketNumberFromWire( packet_number_length, base_packet_number, wire_packet_number); return true; } bool QuicFramer::ProcessFrameData(QuicDataReader* reader, const QuicPacketHeader& header) { QUICHE_DCHECK(!VersionHasIetfQuicFrames(version_.transport_version)) << "IETF QUIC Framing negotiated but attempting to process frames as " "non-IETF QUIC."; if (reader->IsDoneReading()) { set_detailed_error("Packet has no frames."); return RaiseError(QUIC_MISSING_PAYLOAD); } QUIC_DVLOG(2) << ENDPOINT << "Processing packet with header " << header; while (!reader->IsDoneReading()) { uint8_t frame_type; if (!reader->ReadBytes(&frame_type, 1)) { set_detailed_error("Unable to read frame type."); return RaiseError(QUIC_INVALID_FRAME_DATA); } if (frame_type & kQuicFrameTypeSpecialMask) { if (frame_type & kQuicFrameTypeStreamMask) { QuicStreamFrame frame; if (!ProcessStreamFrame(reader, frame_type, &frame)) { return RaiseError(QUIC_INVALID_STREAM_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing stream frame " << frame; if (!visitor_->OnStreamFrame(frame)) { QUIC_DVLOG(1) << ENDPOINT << "Visitor asked to stop further processing."; return true; } continue; } if (frame_type & kQuicFrameTypeAckMask) { if (!ProcessAckFrame(reader, frame_type)) { return RaiseError(QUIC_INVALID_ACK_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing ACK frame"; continue; } set_detailed_error("Illegal frame type."); QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: " << static_cast<int>(frame_type); return RaiseError(QUIC_INVALID_FRAME_DATA); } switch (frame_type) { case PADDING_FRAME: { QuicPaddingFrame frame; ProcessPaddingFrame(reader, &frame); QUIC_DVLOG(2) << ENDPOINT << "Processing padding frame " << frame; if (!visitor_->OnPaddingFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; return true; } continue; } case RST_STREAM_FRAME: { QuicRstStreamFrame frame; if (!ProcessRstStreamFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_RST_STREAM_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing reset stream frame " << frame; if (!visitor_->OnRstStreamFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; return true; } continue; } case CONNECTION_CLOSE_FRAME: { QuicConnectionCloseFrame frame; if (!ProcessConnectionCloseFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing connection close frame " << frame; if (!visitor_->OnConnectionCloseFrame(frame)) { QUIC_DVLOG(1) << ENDPOINT << "Visitor asked to stop further processing."; return true; } continue; } case GOAWAY_FRAME: { QuicGoAwayFrame goaway_frame; if (!ProcessGoAwayFrame(reader, &goaway_frame)) { return RaiseError(QUIC_INVALID_GOAWAY_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing go away frame " << goaway_frame; if (!visitor_->OnGoAwayFrame(goaway_frame)) { QUIC_DVLOG(1) << ENDPOINT << "Visitor asked to stop further processing."; return true; } continue; } case WINDOW_UPDATE_FRAME: { QuicWindowUpdateFrame window_update_frame; if (!ProcessWindowUpdateFrame(reader, &window_update_frame)) { return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing window update frame " << window_update_frame; if (!visitor_->OnWindowUpdateFrame(window_update_frame)) { QUIC_DVLOG(1) << ENDPOINT << "Visitor asked to stop further processing."; return true; } continue; } case BLOCKED_FRAME: { QuicBlockedFrame blocked_frame; if (!ProcessBlockedFrame(reader, &blocked_frame)) { return RaiseError(QUIC_INVALID_BLOCKED_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing blocked frame " << blocked_frame; if (!visitor_->OnBlockedFrame(blocked_frame)) { QUIC_DVLOG(1) << ENDPOINT << "Visitor asked to stop further processing."; return true; } continue; } case STOP_WAITING_FRAME: { QuicStopWaitingFrame stop_waiting_frame; if (!ProcessStopWaitingFrame(reader, header, &stop_waiting_frame)) { return RaiseError(QUIC_INVALID_STOP_WAITING_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing stop waiting frame " << stop_waiting_frame; if (!visitor_->OnStopWaitingFrame(stop_waiting_frame)) { QUIC_DVLOG(1) << ENDPOINT << "Visitor asked to stop further processing."; return true; } continue; } case PING_FRAME: { QuicPingFrame ping_frame; if (!visitor_->OnPingFrame(ping_frame)) { QUIC_DVLOG(1) << ENDPOINT << "Visitor asked to stop further processing."; return true; } QUIC_DVLOG(2) << ENDPOINT << "Processing ping frame " << ping_frame; continue; } case IETF_EXTENSION_MESSAGE_NO_LENGTH: ABSL_FALLTHROUGH_INTENDED; case IETF_EXTENSION_MESSAGE: { QUIC_CODE_COUNT(quic_legacy_message_frame_codepoint_read); QuicMessageFrame message_frame; if (!ProcessMessageFrame(reader, frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH, &message_frame)) { return RaiseError(QUIC_INVALID_MESSAGE_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing message frame " << message_frame; if (!visitor_->OnMessageFrame(message_frame)) { QUIC_DVLOG(1) << ENDPOINT << "Visitor asked to stop further processing."; return true; } break; } case CRYPTO_FRAME: { if (!QuicVersionUsesCryptoFrames(version_.transport_version)) { set_detailed_error("Illegal frame type."); return RaiseError(QUIC_INVALID_FRAME_DATA); } QuicCryptoFrame frame; if (!ProcessCryptoFrame(reader, GetEncryptionLevel(header), &frame)) { return RaiseError(QUIC_INVALID_FRAME_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing crypto frame " << frame; if (!visitor_->OnCryptoFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; return true; } break; } case HANDSHAKE_DONE_FRAME: { QuicHandshakeDoneFrame handshake_done_frame; QUIC_DVLOG(2) << ENDPOINT << "Processing handshake done frame " << handshake_done_frame; if (!visitor_->OnHandshakeDoneFrame(handshake_done_frame)) { QUIC_DVLOG(1) << ENDPOINT << "Visitor asked to stop further processing."; return true; } break; } default: set_detailed_error("Illegal frame type."); QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: " << static_cast<int>(frame_type); return RaiseError(QUIC_INVALID_FRAME_DATA); } } return true; } bool QuicFramer::IsIetfFrameTypeExpectedForEncryptionLevel( uint64_t frame_type, EncryptionLevel level) { switch (level) { case ENCRYPTION_INITIAL: case ENCRYPTION_HANDSHAKE: return frame_type == IETF_CRYPTO || frame_type == IETF_ACK || frame_type == IETF_ACK_ECN || frame_type == IETF_ACK_RECEIVE_TIMESTAMPS || frame_type == IETF_PING || frame_type == IETF_PADDING || frame_type == IETF_CONNECTION_CLOSE; case ENCRYPTION_ZERO_RTT: return !(frame_type == IETF_ACK || frame_type == IETF_ACK_ECN || frame_type == IETF_ACK_RECEIVE_TIMESTAMPS || frame_type == IETF_HANDSHAKE_DONE || frame_type == IETF_NEW_TOKEN || frame_type == IETF_PATH_RESPONSE || frame_type == IETF_RETIRE_CONNECTION_ID); case ENCRYPTION_FORWARD_SECURE: return true; default: QUIC_BUG(quic_bug_10850_57) << "Unknown encryption level: " << level; } return false; } bool QuicFramer::ProcessIetfFrameData(QuicDataReader* reader, const QuicPacketHeader& header, EncryptionLevel decrypted_level) { QUICHE_DCHECK(VersionHasIetfQuicFrames(version_.transport_version)) << "Attempt to process frames as IETF frames but version (" << version_.transport_version << ") does not support IETF Framing."; if (reader->IsDoneReading()) { set_detailed_error("Packet has no frames."); return RaiseError(QUIC_MISSING_PAYLOAD); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF packet with header " << header; while (!reader->IsDoneReading()) { uint64_t frame_type; size_t encoded_bytes = reader->BytesRemaining(); if (!reader->ReadVarInt62(&frame_type)) { set_detailed_error("Unable to read frame type."); return RaiseError(QUIC_INVALID_FRAME_DATA); } if (!IsIetfFrameTypeExpectedForEncryptionLevel(frame_type, decrypted_level)) { set_detailed_error(absl::StrCat( "IETF frame type ", QuicIetfFrameTypeString(static_cast<QuicIetfFrameType>(frame_type)), " is unexpected at encryption level ", EncryptionLevelToString(decrypted_level))); return RaiseError(IETF_QUIC_PROTOCOL_VIOLATION); } previously_received_frame_type_ = current_received_frame_type_; current_received_frame_type_ = frame_type; encoded_bytes -= reader->BytesRemaining(); if (encoded_bytes != static_cast<size_t>(QuicDataWriter::GetVarInt62Len(frame_type))) { set_detailed_error("Frame type not minimally encoded."); return RaiseError(IETF_QUIC_PROTOCOL_VIOLATION); } if (IS_IETF_STREAM_FRAME(frame_type)) { QuicStreamFrame frame; if (!ProcessIetfStreamFrame(reader, frame_type, &frame)) { return RaiseError(QUIC_INVALID_STREAM_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stream frame " << frame; if (!visitor_->OnStreamFrame(frame)) { QUIC_DVLOG(1) << ENDPOINT << "Visitor asked to stop further processing."; return true; } } else { switch (frame_type) { case IETF_PADDING: { QuicPaddingFrame frame; ProcessPaddingFrame(reader, &frame); QUIC_DVLOG(2) << ENDPOINT << "Processing IETF padding frame " << frame; if (!visitor_->OnPaddingFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; return true; } break; } case IETF_RST_STREAM: { QuicRstStreamFrame frame; if (!ProcessIetfResetStreamFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_RST_STREAM_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF reset stream frame " << frame; if (!visitor_->OnRstStreamFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; return true; } break; } case IETF_APPLICATION_CLOSE: case IETF_CONNECTION_CLOSE: { QuicConnectionCloseFrame frame; if (!ProcessIetfConnectionCloseFrame( reader, (frame_type == IETF_CONNECTION_CLOSE) ? IETF_QUIC_TRANSPORT_CONNECTION_CLOSE : IETF_QUIC_APPLICATION_CONNECTION_CLOSE, &frame)) { return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF connection close frame " << frame; if (!visitor_->OnConnectionCloseFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; return true; } break; } case IETF_MAX_DATA: { QuicWindowUpdateFrame frame; if (!ProcessMaxDataFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_MAX_DATA_FRAME_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max data frame " << frame; if (!visitor_->OnWindowUpdateFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; return true; } break; } case IETF_MAX_STREAM_DATA: { QuicWindowUpdateFrame frame; if (!ProcessMaxStreamDataFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_MAX_STREAM_DATA_FRAME_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max stream data frame " << frame; if (!visitor_->OnWindowUpdateFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; return true; } break; } case IETF_MAX_STREAMS_BIDIRECTIONAL: case IETF_MAX_STREAMS_UNIDIRECTIONAL: { QuicMaxStreamsFrame frame; if (!ProcessMaxStreamsFrame(reader, &frame, frame_type)) { return RaiseError(QUIC_MAX_STREAMS_DATA); } QUIC_CODE_COUNT_N(quic_max_streams_received, 1, 2); QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max streams frame " << frame; if (!visitor_->OnMaxStreamsFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; return true; } break; } case IETF_PING: { QuicPingFrame ping_frame; QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ping frame " << ping_frame; if (!visitor_->OnPingFrame(ping_frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; return true; } break; } case IETF_DATA_BLOCKED: { QuicBlockedFrame frame; if (!ProcessDataBlockedFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_BLOCKED_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF blocked frame " << frame; if (!visitor_->OnBlockedFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; return true; } break; } case IETF_STREAM_DATA_BLOCKED: { QuicBlockedFrame frame; if (!ProcessStreamDataBlockedFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_STREAM_BLOCKED_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stream blocked frame " << frame; if (!visitor_->OnBlockedFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; return true; } break; } case IETF_STREAMS_BLOCKED_UNIDIRECTIONAL: case IETF_STREAMS_BLOCKED_BIDIRECTIONAL: { QuicStreamsBlockedFrame frame; if (!ProcessStreamsBlockedFrame(reader, &frame, frame_type)) { return RaiseError(QUIC_STREAMS_BLOCKED_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF streams blocked frame " << frame; if (!visitor_->OnStreamsBlockedFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; return true; } break; } case IETF_NEW_CONNECTION_ID: { QuicNewConnectionIdFrame frame; if (!ProcessNewConnectionIdFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_NEW_CONNECTION_ID_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF new connection ID frame " << frame; if (!visitor_->OnNewConnectionIdFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; return true; } break; } case IETF_RETIRE_CONNECTION_ID: { QuicRetireConnectionIdFrame frame; if (!ProcessRetireConnectionIdFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_RETIRE_CONNECTION_ID_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF retire connection ID frame " << frame; if (!visitor_->OnRetireConnectionIdFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; return true; } break; } case IETF_NEW_TOKEN: { QuicNewTokenFrame frame; if (!ProcessNewTokenFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_NEW_TOKEN); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF new token frame " << frame; if (!visitor_->OnNewTokenFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; return true; } break; } case IETF_STOP_SENDING: { QuicStopSendingFrame frame; if (!ProcessStopSendingFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_STOP_SENDING_FRAME_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stop sending frame " << frame; if (!visitor_->OnStopSendingFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; return true; } break; } case IETF_ACK_RECEIVE_TIMESTAMPS: if (!process_timestamps_) { set_detailed_error("Unsupported frame type."); QUIC_DLOG(WARNING) << ENDPOINT << "IETF_ACK_RECEIVE_TIMESTAMPS not supported"; return RaiseError(QUIC_INVALID_FRAME_DATA); } ABSL_FALLTHROUGH_INTENDED; case IETF_ACK_ECN: case IETF_ACK: { QuicAckFrame frame; if (!ProcessIetfAckFrame(reader, frame_type, &frame)) { return RaiseError(QUIC_INVALID_ACK_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ACK frame " << frame; break; } case IETF_PATH_CHALLENGE: { QuicPathChallengeFrame frame; if (!ProcessPathChallengeFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_PATH_CHALLENGE_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF path challenge frame " << frame; if (!visitor_->OnPathChallengeFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; return true; } break; } case IETF_PATH_RESPONSE: { QuicPathResponseFrame frame; if (!ProcessPathResponseFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_PATH_RESPONSE_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF path response frame " << frame; if (!visitor_->OnPathResponseFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; return true; } break; } case IETF_EXTENSION_MESSAGE_NO_LENGTH_V99: ABSL_FALLTHROUGH_INTENDED; case IETF_EXTENSION_MESSAGE_V99: { QuicMessageFrame message_frame; if (!ProcessMessageFrame( reader, frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH_V99, &message_frame)) { return RaiseError(QUIC_INVALID_MESSAGE_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF message frame " << message_frame; if (!visitor_->OnMessageFrame(message_frame)) { QUIC_DVLOG(1) << ENDPOINT << "Visitor asked to stop further processing."; return true; } break; } case IETF_CRYPTO: { QuicCryptoFrame frame; if (!ProcessCryptoFrame(reader, GetEncryptionLevel(header), &frame)) { return RaiseError(QUIC_INVALID_FRAME_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF crypto frame " << frame; if (!visitor_->OnCryptoFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; return true; } break; } case IETF_HANDSHAKE_DONE: { QuicHandshakeDoneFrame handshake_done_frame; if (!visitor_->OnHandshakeDoneFrame(handshake_done_frame)) { QUIC_DVLOG(1) << ENDPOINT << "Visitor asked to stop further processing."; return true; } QUIC_DVLOG(2) << ENDPOINT << "Processing handshake done frame " << handshake_done_frame; break; } case IETF_ACK_FREQUENCY: { QuicAckFrequencyFrame frame; if (!ProcessAckFrequencyFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_FRAME_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ack frequency frame " << frame; if (!visitor_->OnAckFrequencyFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; return true; } break; } case IETF_RESET_STREAM_AT: { if (!process_reset_stream_at_) { set_detailed_error("RESET_STREAM_AT not enabled."); return RaiseError(QUIC_INVALID_FRAME_DATA); } QuicResetStreamAtFrame frame; if (!ProcessResetStreamAtFrame(*reader, frame)) { return RaiseError(QUIC_INVALID_FRAME_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing RESET_STREAM_AT frame " << frame; if (!visitor_->OnResetStreamAtFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; return true; } break; } default: set_detailed_error("Illegal frame type."); QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: " << static_cast<int>(frame_type); return RaiseError(QUIC_INVALID_FRAME_DATA); } } } return true; } namespace { inline uint8_t GetMaskFromNumBits(uint8_t num_bits) { return (1u << num_bits) - 1; } uint8_t ExtractBits(uint8_t flags, uint8_t num_bits, uint8_t offset) { return (flags >> offset) & GetMaskFromNumBits(num_bits); } bool ExtractBit(uint8_t flags, uint8_t offset) { return ((flags >> offset) & GetMaskFromNumBits(1)) != 0; } void SetBits(uint8_t* flags, uint8_t val, uint8_t num_bits, uint8_t offset) { QUICHE_DCHECK_LE(val, GetMaskFromNumBits(num_bits)); *flags |= val << offset; } void SetBit(uint8_t* flags, bool val, uint8_t offset) { SetBits(flags, val ? 1 : 0, 1, offset); } } bool QuicFramer::ProcessStreamFrame(QuicDataReader* reader, uint8_t frame_type, QuicStreamFrame* frame) { uint8_t stream_flags = frame_type; uint8_t stream_id_length = 0; uint8_t offset_length = 4; bool has_data_length = true; stream_flags &= ~kQuicFrameTypeStreamMask; stream_id_length = (stream_flags & kQuicStreamIDLengthMask) + 1; stream_flags >>= kQuicStreamIdShift; offset_length = (stream_flags & kQuicStreamOffsetMask); if (offset_length > 0) { offset_length += 1; } stream_flags >>= kQuicStreamShift; has_data_length = (stream_flags & kQuicStreamDataLengthMask) == kQuicStreamDataLengthMask; stream_flags >>= kQuicStreamDataLengthShift; frame->fin = (stream_flags & kQuicStreamFinMask) == kQuicStreamFinShift; uint64_t stream_id; if (!reader->ReadBytesToUInt64(stream_id_length, &stream_id)) { set_detailed_error("Unable to read stream_id."); return false; } frame->stream_id = static_cast<QuicStreamId>(stream_id); if (!reader->ReadBytesToUInt64(offset_length, &frame->offset)) { set_detailed_error("Unable to read offset."); return false; } absl::string_view data; if (has_data_length) { if (!reader->ReadStringPiece16(&data)) { set_detailed_error("Unable to read frame data."); return false; } } else { if (!reader->ReadStringPiece(&data, reader->BytesRemaining())) { set_detailed_error("Unable to read frame data."); return false; } } frame->data_buffer = data.data(); frame->data_length = static_cast<uint16_t>(data.length()); return true; } bool QuicFramer::ProcessIetfStreamFrame(QuicDataReader* reader, uint8_t frame_type, QuicStreamFrame* frame) { if (!ReadUint32FromVarint62(reader, IETF_STREAM, &frame->stream_id)) { return false; } if (frame_type & IETF_STREAM_FRAME_OFF_BIT) { if (!reader->ReadVarInt62(&frame->offset)) { set_detailed_error("Unable to read stream data offset."); return false; } } else { frame->offset = 0; } if (frame_type & IETF_STREAM_FRAME_LEN_BIT) { uint64_t length; if (!reader->ReadVarInt62(&length)) { set_detailed_error("Unable to read stream data length."); return false; } if (length > std::numeric_limits<decltype(frame->data_length)>::max()) { set_detailed_error("Stream data length is too large."); return false; } frame->data_length = length; } else { frame->data_length = reader->BytesRemaining(); } if (frame_type & IETF_STREAM_FRAME_FIN_BIT) { frame->fin = true; } else { frame->fin = false; } absl::string_view data; if (!reader->ReadStringPiece(&data, frame->data_length)) { set_detailed_error("Unable to read frame data."); return false; } frame->data_buffer = data.data(); QUICHE_DCHECK_EQ(frame->data_length, data.length()); return true; } bool QuicFramer::ProcessCryptoFrame(QuicDataReader* reader, EncryptionLevel encryption_level, QuicCryptoFrame* frame) { frame->level = encryption_level; if (!reader->ReadVarInt62(&frame->offset)) { set_detailed_error("Unable to read crypto data offset."); return false; } uint64_t len; if (!reader->ReadVarInt62(&len) || len > std::numeric_limits<QuicPacketLength>::max()) { set_detailed_error("Invalid data length."); return false; } frame->data_length = len; absl::string_view data; if (!reader->ReadStringPiece(&data, frame->data_length)) { set_detailed_error("Unable to read frame data."); return false; } frame->data_buffer = data.data(); return true; } bool QuicFramer::ProcessAckFrequencyFrame(QuicDataReader* reader, QuicAckFrequencyFrame* frame) { if (!reader->ReadVarInt62(&frame->sequence_number)) { set_detailed_error("Unable to read sequence number."); return false; } if (!reader->ReadVarInt62(&frame->packet_tolerance)) { set_detailed_error("Unable to read packet tolerance."); return false; } if (frame->packet_tolerance == 0) { set_detailed_error("Invalid packet tolerance."); return false; } uint64_t max_ack_delay_us; if (!reader->ReadVarInt62(&max_ack_delay_us)) { set_detailed_error("Unable to read max_ack_delay_us."); return false; } constexpr uint64_t kMaxAckDelayUsBound = 1u << 24; if (max_ack_delay_us > kMaxAckDelayUsBound) { set_detailed_error("Invalid max_ack_delay_us."); return false; } frame->max_ack_delay = QuicTime::Delta::FromMicroseconds(max_ack_delay_us); uint8_t ignore_order; if (!reader->ReadUInt8(&ignore_order)) { set_detailed_error("Unable to read ignore_order."); return false; } if (ignore_order > 1) { set_detailed_error("Invalid ignore_order."); return false; } frame->ignore_order = ignore_order; return true; } bool QuicFramer::ProcessResetStreamAtFrame(QuicDataReader& reader, QuicResetStreamAtFrame& frame) { if (!ReadUint32FromVarint62(&reader, IETF_RESET_STREAM_AT, &frame.stream_id)) { return false; } if (!reader.ReadVarInt62(&frame.error)) { set_detailed_error("Failed to read the error code."); return false; } if (!reader.ReadVarInt62(&frame.final_offset)) { set_detailed_error("Failed to read the final offset."); return false; } if (!reader.ReadVarInt62(&frame.reliable_offset)) { set_detailed_error("Failed to read the reliable offset."); return false; } if (frame.reliable_offset > frame.final_offset) { set_detailed_error("reliable_offset > final_offset"); return false; } return true; } bool QuicFramer::ProcessAckFrame(QuicDataReader* reader, uint8_t frame_type) { const bool has_ack_blocks = ExtractBit(frame_type, kQuicHasMultipleAckBlocksOffset); uint8_t num_ack_blocks = 0; uint8_t num_received_packets = 0; const QuicPacketNumberLength ack_block_length = ReadAckPacketNumberLength(ExtractBits( frame_type, kQuicSequenceNumberLengthNumBits, kActBlockLengthOffset)); const QuicPacketNumberLength largest_acked_length = ReadAckPacketNumberLength(ExtractBits( frame_type, kQuicSequenceNumberLengthNumBits, kLargestAckedOffset)); uint64_t largest_acked; if (!reader->ReadBytesToUInt64(largest_acked_length, &largest_acked)) { set_detailed_error("Unable to read largest acked."); return false; } if (largest_acked < first_sending_packet_number_.ToUint64()) { set_detailed_error("Largest acked is 0."); return false; } uint64_t ack_delay_time_us; if (!reader->ReadUFloat16(&ack_delay_time_us)) { set_detailed_error("Unable to read ack delay time."); return false; } if (!visitor_->OnAckFrameStart( QuicPacketNumber(largest_acked), ack_delay_time_us == kUFloat16MaxValue ? QuicTime::Delta::Infinite() : QuicTime::Delta::FromMicroseconds(ack_delay_time_us))) { set_detailed_error("Visitor suppresses further processing of ack frame."); return false; } if (has_ack_blocks && !reader->ReadUInt8(&num_ack_blocks)) { set_detailed_error("Unable to read num of ack blocks."); return false; } uint64_t first_block_length; if (!reader->ReadBytesToUInt64(ack_block_length, &first_block_length)) { set_detailed_error("Unable to read first ack block length."); return false; } if (first_block_length == 0) { set_detailed_error("First block length is zero."); return false; } bool first_ack_block_underflow = first_block_length > largest_acked + 1; if (first_block_length + first_sending_packet_number_.ToUint64() > largest_acked + 1) { first_ack_block_underflow = true; } if (first_ack_block_underflow) { set_detailed_error(absl::StrCat("Underflow with first ack block length ", first_block_length, " largest acked is ", largest_acked, ".") .c_str()); return false; } uint64_t first_received = largest_acked + 1 - first_block_length; if (!visitor_->OnAckRange(QuicPacketNumber(first_received), QuicPacketNumber(largest_acked + 1))) { set_detailed_error("Visitor suppresses further processing of ack frame."); return false; } if (num_ack_blocks > 0) { for (size_t i = 0; i < num_ack_blocks; ++i) { uint8_t gap = 0; if (!reader->ReadUInt8(&gap)) { set_detailed_error("Unable to read gap to next ack block."); return false; } uint64_t current_block_length; if (!reader->ReadBytesToUInt64(ack_block_length, &current_block_length)) { set_detailed_error("Unable to ack block length."); return false; } bool ack_block_underflow = first_received < gap + current_block_length; if (first_received < gap + current_block_length + first_sending_packet_number_.ToUint64()) { ack_block_underflow = true; } if (ack_block_underflow) { set_detailed_error(absl::StrCat("Underflow with ack block length ", current_block_length, ", end of block is ", first_received - gap, ".") .c_str()); return false; } first_received -= (gap + current_block_length); if (current_block_length > 0) { if (!visitor_->OnAckRange( QuicPacketNumber(first_received), QuicPacketNumber(first_received) + current_block_length)) { set_detailed_error( "Visitor suppresses further processing of ack frame."); return false; } } } } if (!reader->ReadUInt8(&num_received_packets)) { set_detailed_error("Unable to read num received packets."); return false; } if (!ProcessTimestampsInAckFrame(num_received_packets, QuicPacketNumber(largest_acked), reader)) { return false; } std::optional<QuicEcnCounts> ecn_counts = std::nullopt; if (!visitor_->OnAckFrameEnd(QuicPacketNumber(first_received), ecn_counts)) { set_detailed_error( "Error occurs when visitor finishes processing the ACK frame."); return false; } return true; } bool QuicFramer::ProcessTimestampsInAckFrame(uint8_t num_received_packets, QuicPacketNumber largest_acked, QuicDataReader* reader) { if (num_received_packets == 0) { return true; } uint8_t delta_from_largest_observed; if (!reader->ReadUInt8(&delta_from_largest_observed)) { set_detailed_error("Unable to read sequence delta in received packets."); return false; } if (largest_acked.ToUint64() <= delta_from_largest_observed) { set_detailed_error( absl::StrCat("delta_from_largest_observed too high: ", delta_from_largest_observed, ", largest_acked: ", largest_acked.ToUint64()) .c_str()); return false; } uint32_t time_delta_us; if (!reader->ReadUInt32(&time_delta_us)) { set_detailed_error("Unable to read time delta in received packets."); return false; } QuicPacketNumber seq_num = largest_acked - delta_from_largest_observed; if (process_timestamps_) { last_timestamp_ = CalculateTimestampFromWire(time_delta_us); visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_); } for (uint8_t i = 1; i < num_received_packets; ++i) { if (!reader->ReadUInt8(&delta_from_largest_observed)) { set_detailed_error("Unable to read sequence delta in received packets."); return false; } if (largest_acked.ToUint64() <= delta_from_largest_observed) { set_detailed_error( absl::StrCat("delta_from_largest_observed too high: ", delta_from_largest_observed, ", largest_acked: ", largest_acked.ToUint64()) .c_str()); return false; } seq_num = largest_acked - delta_from_largest_observed; uint64_t incremental_time_delta_us; if (!reader->ReadUFloat16(&incremental_time_delta_us)) { set_detailed_error( "Unable to read incremental time delta in received packets."); return false; } if (process_timestamps_) { last_timestamp_ = last_timestamp_ + QuicTime::Delta::FromMicroseconds( incremental_time_delta_us); visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_); } } return true; } bool QuicFramer::ProcessIetfAckFrame(QuicDataReader* reader, uint64_t frame_type, QuicAckFrame* ack_frame) { uint64_t largest_acked; if (!reader->ReadVarInt62(&largest_acked)) { set_detailed_error("Unable to read largest acked."); return false; } if (largest_acked < first_sending_packet_number_.ToUint64()) { set_detailed_error("Largest acked is 0."); return false; } ack_frame->largest_acked = static_cast<QuicPacketNumber>(largest_acked); uint64_t ack_delay_time_in_us; if (!reader->ReadVarInt62(&ack_delay_time_in_us)) { set_detailed_error("Unable to read ack delay time."); return false; } if (ack_delay_time_in_us >= (quiche::kVarInt62MaxValue >> peer_ack_delay_exponent_)) { ack_frame->ack_delay_time = QuicTime::Delta::Infinite(); } else { ack_delay_time_in_us = (ack_delay_time_in_us << peer_ack_delay_exponent_); ack_frame->ack_delay_time = QuicTime::Delta::FromMicroseconds(ack_delay_time_in_us); } if (!visitor_->OnAckFrameStart(QuicPacketNumber(largest_acked), ack_frame->ack_delay_time)) { set_detailed_error("Visitor suppresses further processing of ACK frame."); return false; } uint64_t ack_block_count; if (!reader->ReadVarInt62(&ack_block_count)) { set_detailed_error("Unable to read ack block count."); return false; } uint64_t ack_block_value; if (!reader->ReadVarInt62(&ack_block_value)) { set_detailed_error("Unable to read first ack block length."); return false; } uint64_t block_high = largest_acked + 1; uint64_t block_low = largest_acked - ack_block_value; if (ack_block_value + first_sending_packet_number_.ToUint64() > largest_acked) { set_detailed_error(absl::StrCat("Underflow with first ack block length ", ack_block_value + 1, " largest acked is ", largest_acked, ".") .c_str()); return false; } if (!visitor_->OnAckRange(QuicPacketNumber(block_low), QuicPacketNumber(block_high))) { set_detailed_error("Visitor suppresses further processing of ACK frame."); return false; } while (ack_block_count != 0) { uint64_t gap_block_value; if (!reader->ReadVarInt62(&gap_block_value)) { set_detailed_error("Unable to read gap block value."); return false; } if ((gap_block_value + 2) > block_low) { set_detailed_error( absl::StrCat("Underflow with gap block length ", gap_block_value + 1, " previous ack block start is ", block_low, ".") .c_str()); return false; } block_high = block_low - 1 - gap_block_value; if (!reader->ReadVarInt62(&ack_block_value)) { set_detailed_error("Unable to read ack block value."); return false; } if (ack_block_value + first_sending_packet_number_.ToUint64() > (block_high - 1)) { set_detailed_error( absl::StrCat("Underflow with ack block length ", ack_block_value + 1, " latest ack block end is ", block_high - 1, ".") .c_str()); return false; } block_low = block_high - 1 - ack_block_value; if (!visitor_->OnAckRange(QuicPacketNumber(block_low), QuicPacketNumber(block_high))) { set_detailed_error("Visitor suppresses further processing of ACK frame."); return false; } ack_block_count--; } QUICHE_DCHECK(!ack_frame->ecn_counters.has_value()); if (frame_type == IETF_ACK_RECEIVE_TIMESTAMPS) { QUICHE_DCHECK(process_timestamps_); if (!ProcessIetfTimestampsInAckFrame(ack_frame->largest_acked, reader)) { return false; } } else if (frame_type == IETF_ACK_ECN) { ack_frame->ecn_counters = QuicEcnCounts(); if (!reader->ReadVarInt62(&ack_frame->ecn_counters->ect0)) { set_detailed_error("Unable to read ack ect_0_count."); return false; } if (!reader->ReadVarInt62(&ack_frame->ecn_counters->ect1)) { set_detailed_error("Unable to read ack ect_1_count."); return false; } if (!reader->ReadVarInt62(&ack_frame->ecn_counters->ce)) { set_detailed_error("Unable to read ack ecn_ce_count."); return false; } } if (!visitor_->OnAckFrameEnd(QuicPacketNumber(block_low), ack_frame->ecn_counters)) { set_detailed_error( "Error occurs when visitor finishes processing the ACK frame."); return false; } return true; } bool QuicFramer::ProcessIetfTimestampsInAckFrame(QuicPacketNumber largest_acked, QuicDataReader* reader) { uint64_t timestamp_range_count; if (!reader->ReadVarInt62(&timestamp_range_count)) { set_detailed_error("Unable to read receive timestamp range count."); return false; } if (timestamp_range_count == 0) { return true; } QuicPacketNumber packet_number = largest_acked; for (uint64_t i = 0; i < timestamp_range_count; i++) { uint64_t gap; if (!reader->ReadVarInt62(&gap)) { set_detailed_error("Unable to read receive timestamp gap."); return false; } if (packet_number.ToUint64() < gap) { set_detailed_error("Receive timestamp gap too high."); return false; } packet_number = packet_number - gap; uint64_t timestamp_count; if (!reader->ReadVarInt62(&timestamp_count)) { set_detailed_error("Unable to read receive timestamp count."); return false; } if (packet_number.ToUint64() < timestamp_count) { set_detailed_error("Receive timestamp count too high."); return false; } for (uint64_t j = 0; j < timestamp_count; j++) { uint64_t timestamp_delta; if (!reader->ReadVarInt62(&timestamp_delta)) { set_detailed_error("Unable to read receive timestamp delta."); return false; } timestamp_delta = timestamp_delta << receive_timestamps_exponent_; if (i == 0 && j == 0) { last_timestamp_ = QuicTime::Delta::FromMicroseconds(timestamp_delta); } else { last_timestamp_ = last_timestamp_ - QuicTime::Delta::FromMicroseconds(timestamp_delta); if (last_timestamp_ < QuicTime::Delta::Zero()) { set_detailed_error("Receive timestamp delta too high."); return false; } } visitor_->OnAckTimestamp(packet_number, creation_time_ + last_timestamp_); packet_number--; } packet_number--; } return true; } bool QuicFramer::ProcessStopWaitingFrame(QuicDataReader* reader, const QuicPacketHeader& header, QuicStopWaitingFrame* stop_waiting) { uint64_t least_unacked_delta; if (!reader->ReadBytesToUInt64(header.packet_number_length, &least_unacked_delta)) { set_detailed_error("Unable to read least unacked delta."); return false; } if (header.packet_number.ToUint64() <= least_unacked_delta) { set_detailed_error("Invalid unacked delta."); return false; } stop_waiting->least_unacked = header.packet_number - least_unacked_delta; return true; } bool QuicFramer::ProcessRstStreamFrame(QuicDataReader* reader, QuicRstStreamFrame* frame) { if (!reader->ReadUInt32(&frame->stream_id)) { set_detailed_error("Unable to read stream_id."); return false; } if (!reader->ReadUInt64(&frame->byte_offset)) { set_detailed_error("Unable to read rst stream sent byte offset."); return false; } uint32_t error_code; if (!reader->ReadUInt32(&error_code)) { set_detailed_error("Unable to read rst stream error code."); return false; } if (error_code >= QUIC_STREAM_LAST_ERROR) { error_code = QUIC_STREAM_LAST_ERROR; } frame->error_code = static_cast<QuicRstStreamErrorCode>(error_code); return true; } bool QuicFramer::ProcessConnectionCloseFrame(QuicDataReader* reader, QuicConnectionCloseFrame* frame) { uint32_t error_code; frame->close_type = GOOGLE_QUIC_CONNECTION_CLOSE; if (!reader->ReadUInt32(&error_code)) { set_detailed_error("Unable to read connection close error code."); return false; } frame->wire_error_code = error_code; frame->quic_error_code = static_cast<QuicErrorCode>(error_code); absl::string_view error_details; if (!reader->ReadStringPiece16(&error_details)) { set_detailed_error("Unable to read connection close error details."); return false; } frame->error_details = std::string(error_details); return true; } bool QuicFramer::ProcessGoAwayFrame(QuicDataReader* reader, QuicGoAwayFrame* frame) { uint32_t error_code; if (!reader->ReadUInt32(&error_code)) { set_detailed_error("Unable to read go away error code."); return false; } frame->error_code = static_cast<QuicErrorCode>(error_code); uint32_t stream_id; if (!reader->ReadUInt32(&stream_id)) { set_detailed_error("Unable to read last good stream id."); return false; } frame->last_good_stream_id = static_cast<QuicStreamId>(stream_id); absl::string_view reason_phrase; if (!reader->ReadStringPiece16(&reason_phrase)) { set_detailed_error("Unable to read goaway reason."); return false; } frame->reason_phrase = std::string(reason_phrase); return true; } bool QuicFramer::ProcessWindowUpdateFrame(QuicDataReader* reader, QuicWindowUpdateFrame* frame) { if (!reader->ReadUInt32(&frame->stream_id)) { set_detailed_error("Unable to read stream_id."); return false; } if (!reader->ReadUInt64(&frame->max_data)) { set_detailed_error("Unable to read window byte_offset."); return false; } return true; } bool QuicFramer::ProcessBlockedFrame(QuicDataReader* reader, QuicBlockedFrame* frame) { QUICHE_DCHECK(!VersionHasIetfQuicFrames(version_.transport_version)) << "Attempt to process non-IETF QUIC frames in an IETF QUIC version."; if (!reader->ReadUInt32(&frame->stream_id)) { set_detailed_error("Unable to read stream_id."); return false; } return true; } void QuicFramer::ProcessPaddingFrame(QuicDataReader* reader, QuicPaddingFrame* frame) { frame->num_padding_bytes = 1; uint8_t next_byte; while (!reader->IsDoneReading() && reader->PeekByte() == 0x00) { reader->ReadBytes(&next_byte, 1); QUICHE_DCHECK_EQ(0x00, next_byte); ++frame->num_padding_bytes; } } bool QuicFramer::ProcessMessageFrame(QuicDataReader* reader, bool no_message_length, QuicMessageFrame* frame) { if (no_message_length) { absl::string_view remaining(reader->ReadRemainingPayload()); frame->data = remaining.data(); frame->message_length = remaining.length(); return true; } uint64_t message_length; if (!reader->ReadVarInt62(&message_length)) { set_detailed_error("Unable to read message length"); return false; } absl::string_view message_piece; if (!reader->ReadStringPiece(&message_piece, message_length)) { set_detailed_error("Unable to read message data"); return false; } frame->data = message_piece.data(); frame->message_length = message_length; return true; } absl::string_view QuicFramer::GetAssociatedDataFromEncryptedPacket( QuicTransportVersion version, const QuicEncryptedPacket& encrypted, 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, uint64_t retry_token_length, quiche::QuicheVariableLengthIntegerLength length_length) { return absl::string_view( 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)); } void QuicFramer::SetDecrypter(EncryptionLevel level, std::unique_ptr<QuicDecrypter> decrypter) { QUICHE_DCHECK_GE(level, decrypter_level_); QUICHE_DCHECK(!version_.KnowsWhichDecrypterToUse()); QUIC_DVLOG(1) << ENDPOINT << "Setting decrypter from level " << decrypter_level_ << " to " << level; decrypter_[decrypter_level_] = nullptr; decrypter_[level] = std::move(decrypter); decrypter_level_ = level; } void QuicFramer::SetAlternativeDecrypter( EncryptionLevel level, std::unique_ptr<QuicDecrypter> decrypter, bool latch_once_used) { QUICHE_DCHECK_NE(level, decrypter_level_); QUICHE_DCHECK(!version_.KnowsWhichDecrypterToUse()); QUIC_DVLOG(1) << ENDPOINT << "Setting alternative decrypter from level " << alternative_decrypter_level_ << " to " << level; if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) { decrypter_[alternative_decrypter_level_] = nullptr; } decrypter_[level] = std::move(decrypter); alternative_decrypter_level_ = level; alternative_decrypter_latch_ = latch_once_used; } void QuicFramer::InstallDecrypter(EncryptionLevel level, std::unique_ptr<QuicDecrypter> decrypter) { QUICHE_DCHECK(version_.KnowsWhichDecrypterToUse()); QUIC_DVLOG(1) << ENDPOINT << "Installing decrypter at level " << level; decrypter_[level] = std::move(decrypter); } void QuicFramer::RemoveDecrypter(EncryptionLevel level) { QUICHE_DCHECK(version_.KnowsWhichDecrypterToUse()); QUIC_DVLOG(1) << ENDPOINT << "Removing decrypter at level " << level; decrypter_[level] = nullptr; } void QuicFramer::SetKeyUpdateSupportForConnection(bool enabled) { QUIC_DVLOG(1) << ENDPOINT << "SetKeyUpdateSupportForConnection: " << enabled; support_key_update_for_connection_ = enabled; } void QuicFramer::DiscardPreviousOneRttKeys() { QUICHE_DCHECK(support_key_update_for_connection_); QUIC_DVLOG(1) << ENDPOINT << "Discarding previous set of 1-RTT keys"; previous_decrypter_ = nullptr; } bool QuicFramer::DoKeyUpdate(KeyUpdateReason reason) { QUICHE_DCHECK(support_key_update_for_connection_); if (!next_decrypter_) { next_decrypter_ = visitor_->AdvanceKeysAndCreateCurrentOneRttDecrypter(); } std::unique_ptr<QuicEncrypter> next_encrypter = visitor_->CreateCurrentOneRttEncrypter(); if (!next_decrypter_ || !next_encrypter) { QUIC_BUG(quic_bug_10850_58) << "Failed to create next crypters"; return false; } key_update_performed_ = true; current_key_phase_bit_ = !current_key_phase_bit_; QUIC_DLOG(INFO) << ENDPOINT << "DoKeyUpdate: new current_key_phase_bit_=" << current_key_phase_bit_; current_key_phase_first_received_packet_number_.Clear(); previous_decrypter_ = std::move(decrypter_[ENCRYPTION_FORWARD_SECURE]); decrypter_[ENCRYPTION_FORWARD_SECURE] = std::move(next_decrypter_); encrypter_[ENCRYPTION_FORWARD_SECURE] = std::move(next_encrypter); switch (reason) { case KeyUpdateReason::kInvalid: QUIC_CODE_COUNT(quic_key_update_invalid); break; case KeyUpdateReason::kRemote: QUIC_CODE_COUNT(quic_key_update_remote); break; case KeyUpdateReason::kLocalForTests: QUIC_CODE_COUNT(quic_key_update_local_for_tests); break; case KeyUpdateReason::kLocalForInteropRunner: QUIC_CODE_COUNT(quic_key_update_local_for_interop_runner); break; case KeyUpdateReason::kLocalAeadConfidentialityLimit: QUIC_CODE_COUNT(quic_key_update_local_aead_confidentiality_limit); break; case KeyUpdateReason::kLocalKeyUpdateLimitOverride: QUIC_CODE_COUNT(quic_key_update_local_limit_override); break; } visitor_->OnKeyUpdate(reason); return true; } QuicPacketCount QuicFramer::PotentialPeerKeyUpdateAttemptCount() const { return potential_peer_key_update_attempt_count_; } const QuicDecrypter* QuicFramer::GetDecrypter(EncryptionLevel level) const { QUICHE_DCHECK(version_.KnowsWhichDecrypterToUse()); return decrypter_[level].get(); } const QuicDecrypter* QuicFramer::decrypter() const { return decrypter_[decrypter_level_].get(); } const QuicDecrypter* QuicFramer::alternative_decrypter() const { if (alternative_decrypter_level_ == NUM_ENCRYPTION_LEVELS) { return nullptr; } return decrypter_[alternative_decrypter_level_].get(); } void QuicFramer::SetEncrypter(EncryptionLevel level, std::unique_ptr<QuicEncrypter> encrypter) { QUICHE_DCHECK_GE(level, 0); QUICHE_DCHECK_LT(level, NUM_ENCRYPTION_LEVELS); QUIC_DVLOG(1) << ENDPOINT << "Setting encrypter at level " << level; encrypter_[level] = std::move(encrypter); } void QuicFramer::RemoveEncrypter(EncryptionLevel level) { QUIC_DVLOG(1) << ENDPOINT << "Removing encrypter of " << level; encrypter_[level] = nullptr; } void QuicFramer::SetInitialObfuscators(QuicConnectionId connection_id) { CrypterPair crypters; CryptoUtils::CreateInitialObfuscators(perspective_, version_, connection_id, &crypters); encrypter_[ENCRYPTION_INITIAL] = std::move(crypters.encrypter); decrypter_[ENCRYPTION_INITIAL] = std::move(crypters.decrypter); } size_t QuicFramer::EncryptInPlace(EncryptionLevel level, QuicPacketNumber packet_number, size_t ad_len, size_t total_len, size_t buffer_len, char* buffer) { QUICHE_DCHECK(packet_number.IsInitialized()); if (encrypter_[level] == nullptr) { QUIC_BUG(quic_bug_10850_59) << ENDPOINT << "Attempted to encrypt in place without encrypter at level " << level; RaiseError(QUIC_ENCRYPTION_FAILURE); return 0; } size_t output_length = 0; if (!encrypter_[level]->EncryptPacket( packet_number.ToUint64(), absl::string_view(buffer, ad_len), absl::string_view(buffer + ad_len, total_len - ad_len), buffer + ad_len, &output_length, buffer_len - ad_len)) { RaiseError(QUIC_ENCRYPTION_FAILURE); return 0; } if (version_.HasHeaderProtection() && !ApplyHeaderProtection(level, buffer, ad_len + output_length, ad_len)) { QUIC_DLOG(ERROR) << "Applying header protection failed."; RaiseError(QUIC_ENCRYPTION_FAILURE); return 0; } return ad_len + output_length; } namespace { const size_t kHPSampleLen = 16; constexpr bool IsLongHeader(uint8_t type_byte) { return (type_byte & FLAGS_LONG_HEADER) != 0; } } bool QuicFramer::ApplyHeaderProtection(EncryptionLevel level, char* buffer, size_t buffer_len, size_t ad_len) { QuicDataReader buffer_reader(buffer, buffer_len); QuicDataWriter buffer_writer(buffer_len, buffer); if (ad_len < last_written_packet_number_length_) { return false; } size_t pn_offset = ad_len - last_written_packet_number_length_; size_t sample_offset = pn_offset + 4; QuicDataReader sample_reader(buffer, buffer_len); absl::string_view sample; if (!sample_reader.Seek(sample_offset) || !sample_reader.ReadStringPiece(&sample, kHPSampleLen)) { QUIC_BUG(quic_bug_10850_60) << "Not enough bytes to sample: sample_offset " << sample_offset << ", sample len: " << kHPSampleLen << ", buffer len: " << buffer_len; return false; } if (encrypter_[level] == nullptr) { QUIC_BUG(quic_bug_12975_8) << ENDPOINT << "Attempted to apply header protection without encrypter at level " << level << " using " << version_; return false; } std::string mask = encrypter_[level]->GenerateHeaderProtectionMask(sample); if (mask.empty()) { QUIC_BUG(quic_bug_10850_61) << "Unable to generate header protection mask."; return false; } QuicDataReader mask_reader(mask.data(), mask.size()); uint8_t bitmask = 0x1f; uint8_t type_byte; if (!buffer_reader.ReadUInt8(&type_byte)) { return false; } QuicLongHeaderType header_type; if (IsLongHeader(type_byte)) { bitmask = 0x0f; header_type = GetLongHeaderType(type_byte, version_); if (header_type == INVALID_PACKET_TYPE) { return false; } } uint8_t mask_byte; if (!mask_reader.ReadUInt8(&mask_byte) || !buffer_writer.WriteUInt8(type_byte ^ (mask_byte & bitmask))) { return false; } if (IsLongHeader(type_byte) && header_type == ZERO_RTT_PROTECTED && perspective_ == Perspective::IS_SERVER && version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO) { if (pn_offset <= kDiversificationNonceSize) { QUIC_BUG(quic_bug_10850_62) << "Expected diversification nonce, but not enough bytes"; return false; } pn_offset -= kDiversificationNonceSize; } if (!buffer_writer.Seek(pn_offset - 1) || !buffer_reader.Seek(pn_offset - 1)) { return false; } for (size_t i = 0; i < last_written_packet_number_length_; ++i) { uint8_t buffer_byte; uint8_t pn_mask_byte; if (!mask_reader.ReadUInt8(&pn_mask_byte) || !buffer_reader.ReadUInt8(&buffer_byte) || !buffer_writer.WriteUInt8(buffer_byte ^ pn_mask_byte)) { return false; } } return true; } bool QuicFramer::RemoveHeaderProtection( QuicDataReader* reader, const QuicEncryptedPacket& packet, QuicDecrypter& decrypter, Perspective perspective, const ParsedQuicVersion& version, QuicPacketNumber base_packet_number, QuicPacketHeader* header, uint64_t* full_packet_number, AssociatedDataStorage& associated_data) { bool has_diversification_nonce = header->form == IETF_QUIC_LONG_HEADER_PACKET && header->long_packet_type == ZERO_RTT_PROTECTED && perspective == Perspective::IS_CLIENT && version.handshake_protocol == PROTOCOL_QUIC_CRYPTO; absl::string_view remaining_packet = reader->PeekRemainingPayload(); QuicDataReader sample_reader(remaining_packet); absl::string_view pn; if (!sample_reader.ReadStringPiece(&pn, 4)) { QUIC_DVLOG(1) << "Not enough data to sample"; return false; } if (has_diversification_nonce) { if (!sample_reader.Seek(kDiversificationNonceSize)) { QUIC_DVLOG(1) << "No diversification nonce to skip over"; return false; } } std::string mask = decrypter.GenerateHeaderProtectionMask(&sample_reader); QuicDataReader mask_reader(mask.data(), mask.size()); if (mask.empty()) { QUIC_DVLOG(1) << "Failed to compute mask"; return false; } uint8_t bitmask = 0x1f; if (IsLongHeader(header->type_byte)) { bitmask = 0x0f; } uint8_t mask_byte; if (!mask_reader.ReadUInt8(&mask_byte)) { QUIC_DVLOG(1) << "No first byte to read from mask"; return false; } header->type_byte ^= (mask_byte & bitmask); header->packet_number_length = static_cast<QuicPacketNumberLength>((header->type_byte & 0x03) + 1); char pn_buffer[IETF_MAX_PACKET_NUMBER_LENGTH] = {}; QuicDataWriter pn_writer(ABSL_ARRAYSIZE(pn_buffer), pn_buffer); for (size_t i = 0; i < header->packet_number_length; ++i) { uint8_t protected_pn_byte, pn_mask_byte; if (!mask_reader.ReadUInt8(&pn_mask_byte) || !reader->ReadUInt8(&protected_pn_byte) || !pn_writer.WriteUInt8(protected_pn_byte ^ pn_mask_byte)) { QUIC_DVLOG(1) << "Failed to unmask packet number"; return false; } } QuicDataReader packet_number_reader(pn_writer.data(), pn_writer.length()); if (!ProcessAndCalculatePacketNumber( &packet_number_reader, header->packet_number_length, base_packet_number, full_packet_number)) { return false; } absl::string_view ad = GetAssociatedDataFromEncryptedPacket( version.transport_version, packet, GetIncludedDestinationConnectionIdLength(*header), GetIncludedSourceConnectionIdLength(*header), header->version_flag, has_diversification_nonce, header->packet_number_length, header->retry_token_length_length, header->retry_token.length(), header->length_length); associated_data.assign(ad.begin(), ad.end()); QuicDataWriter ad_writer(associated_data.size(), associated_data.data()); if (!ad_writer.WriteUInt8(header->type_byte)) { return false; } size_t seek_len = ad_writer.remaining() - header->packet_number_length; if (has_diversification_nonce) { seek_len -= kDiversificationNonceSize; } if (!ad_writer.Seek(seek_len) || !ad_writer.WriteBytes(pn_writer.data(), pn_writer.length())) { QUIC_DVLOG(1) << "Failed to apply unmasking operations to AD"; return false; } return true; } size_t QuicFramer::EncryptPayload(EncryptionLevel level, QuicPacketNumber packet_number, const QuicPacket& packet, char* buffer, size_t buffer_len) { QUICHE_DCHECK(packet_number.IsInitialized()); if (encrypter_[level] == nullptr) { QUIC_BUG(quic_bug_10850_63) << ENDPOINT << "Attempted to encrypt without encrypter at level " << level; RaiseError(QUIC_ENCRYPTION_FAILURE); return 0; } absl::string_view associated_data = packet.AssociatedData(version_.transport_version); const size_t ad_len = associated_data.length(); if (packet.length() < ad_len) { QUIC_BUG(quic_bug_10850_64) << ENDPOINT << "packet is shorter than associated data length. version:" << version() << ", packet length:" << packet.length() << ", associated data length:" << ad_len; RaiseError(QUIC_ENCRYPTION_FAILURE); return 0; } memmove(buffer, associated_data.data(), ad_len); size_t output_length = 0; if (!encrypter_[level]->EncryptPacket( packet_number.ToUint64(), associated_data, packet.Plaintext(version_.transport_version), buffer + ad_len, &output_length, buffer_len - ad_len)) { RaiseError(QUIC_ENCRYPTION_FAILURE); return 0; } if (version_.HasHeaderProtection() && !ApplyHeaderProtection(level, buffer, ad_len + output_length, ad_len)) { QUIC_DLOG(ERROR) << "Applying header protection failed."; RaiseError(QUIC_ENCRYPTION_FAILURE); return 0; } return ad_len + output_length; } size_t QuicFramer::GetCiphertextSize(EncryptionLevel level, size_t plaintext_size) const { if (encrypter_[level] == nullptr) { QUIC_BUG(quic_bug_10850_65) << ENDPOINT << "Attempted to get ciphertext size without encrypter at level " << level << " using " << version_; return plaintext_size; } return encrypter_[level]->GetCiphertextSize(plaintext_size); } size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size) { size_t min_plaintext_size = ciphertext_size; for (int i = ENCRYPTION_INITIAL; i < NUM_ENCRYPTION_LEVELS; i++) { if (encrypter_[i] != nullptr) { size_t size = encrypter_[i]->GetMaxPlaintextSize(ciphertext_size); if (size < min_plaintext_size) { min_plaintext_size = size; } } } return min_plaintext_size; } QuicPacketCount QuicFramer::GetOneRttEncrypterConfidentialityLimit() const { if (!encrypter_[ENCRYPTION_FORWARD_SECURE]) { QUIC_BUG(quic_bug_10850_66) << "1-RTT encrypter not set"; return 0; } return encrypter_[ENCRYPTION_FORWARD_SECURE]->GetConfidentialityLimit(); } bool QuicFramer::DecryptPayload(size_t udp_packet_length, absl::string_view encrypted, absl::string_view associated_data, const QuicPacketHeader& header, char* decrypted_buffer, size_t buffer_length, size_t* decrypted_length, EncryptionLevel* decrypted_level) { if (!EncryptionLevelIsValid(decrypter_level_)) { QUIC_BUG(quic_bug_10850_67) << "Attempted to decrypt with bad decrypter_level_"; return false; } EncryptionLevel level = decrypter_level_; QuicDecrypter* decrypter = decrypter_[level].get(); QuicDecrypter* alternative_decrypter = nullptr; bool key_phase_parsed = false; bool key_phase; bool attempt_key_update = false; if (version().KnowsWhichDecrypterToUse()) { if (header.form == GOOGLE_QUIC_PACKET) { QUIC_BUG(quic_bug_10850_68) << "Attempted to decrypt GOOGLE_QUIC_PACKET with a version that " "knows which decrypter to use"; return false; } level = GetEncryptionLevel(header); if (!EncryptionLevelIsValid(level)) { QUIC_BUG(quic_bug_10850_69) << "Attempted to decrypt with bad level"; return false; } decrypter = decrypter_[level].get(); if (decrypter == nullptr) { return false; } if (level == ENCRYPTION_ZERO_RTT && perspective_ == Perspective::IS_CLIENT && header.nonce != nullptr) { decrypter->SetDiversificationNonce(*header.nonce); } if (support_key_update_for_connection_ && header.form == IETF_QUIC_SHORT_HEADER_PACKET) { QUICHE_DCHECK(version().UsesTls()); QUICHE_DCHECK_EQ(level, ENCRYPTION_FORWARD_SECURE); key_phase = (header.type_byte & FLAGS_KEY_PHASE_BIT) != 0; key_phase_parsed = true; QUIC_DVLOG(1) << ENDPOINT << "packet " << header.packet_number << " received key_phase=" << key_phase << " current_key_phase_bit_=" << current_key_phase_bit_; if (key_phase != current_key_phase_bit_) { if ((current_key_phase_first_received_packet_number_.IsInitialized() && header.packet_number > current_key_phase_first_received_packet_number_) || (!current_key_phase_first_received_packet_number_.IsInitialized() && !key_update_performed_)) { if (!next_decrypter_) { next_decrypter_ = visitor_->AdvanceKeysAndCreateCurrentOneRttDecrypter(); if (!next_decrypter_) { QUIC_BUG(quic_bug_10850_70) << "Failed to create next_decrypter"; return false; } } QUIC_DVLOG(1) << ENDPOINT << "packet " << header.packet_number << " attempt_key_update=true"; attempt_key_update = true; potential_peer_key_update_attempt_count_++; decrypter = next_decrypter_.get(); } else { if (previous_decrypter_) { QUIC_DVLOG(1) << ENDPOINT << "trying previous_decrypter_ for packet " << header.packet_number; decrypter = previous_decrypter_.get(); } else { QUIC_DVLOG(1) << ENDPOINT << "dropping packet " << header.packet_number << " with old key phase"; return false; } } } } } else if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) { if (!EncryptionLevelIsValid(alternative_decrypter_level_)) { QUIC_BUG(quic_bug_10850_71) << "Attempted to decrypt with bad alternative_decrypter_level_"; return false; } alternative_decrypter = decrypter_[alternative_decrypter_level_].get(); } if (decrypter == nullptr) { QUIC_BUG(quic_bug_10850_72) << "Attempting to decrypt without decrypter, encryption level:" << level << " version:" << version(); return false; } bool success = decrypter->DecryptPacket( header.packet_number.ToUint64(), associated_data, encrypted, decrypted_buffer, decrypted_length, buffer_length); if (success) { visitor_->OnDecryptedPacket(udp_packet_length, level); if (level == ENCRYPTION_ZERO_RTT && current_key_phase_first_received_packet_number_.IsInitialized() && header.packet_number > current_key_phase_first_received_packet_number_) { set_detailed_error(absl::StrCat( "Decrypted a 0-RTT packet with a packet number ", header.packet_number.ToString(), " which is higher than a 1-RTT packet number ", current_key_phase_first_received_packet_number_.ToString())); return RaiseError(QUIC_INVALID_0RTT_PACKET_NUMBER_OUT_OF_ORDER); } *decrypted_level = level; potential_peer_key_update_attempt_count_ = 0; if (attempt_key_update) { if (!DoKeyUpdate(KeyUpdateReason::kRemote)) { set_detailed_error("Key update failed due to internal error"); return RaiseError(QUIC_INTERNAL_ERROR); } QUICHE_DCHECK_EQ(current_key_phase_bit_, key_phase); } if (key_phase_parsed && !current_key_phase_first_received_packet_number_.IsInitialized() && key_phase == current_key_phase_bit_) { QUIC_DVLOG(1) << ENDPOINT << "current_key_phase_first_received_packet_number_ = " << header.packet_number; current_key_phase_first_received_packet_number_ = header.packet_number; visitor_->OnDecryptedFirstPacketInKeyPhase(); } } else if (alternative_decrypter != nullptr) { if (header.nonce != nullptr) { QUICHE_DCHECK_EQ(perspective_, Perspective::IS_CLIENT); alternative_decrypter->SetDiversificationNonce(*header.nonce); } bool try_alternative_decryption = true; if (alternative_decrypter_level_ == ENCRYPTION_ZERO_RTT) { if (perspective_ == Perspective::IS_CLIENT) { if (header.nonce == nullptr) { try_alternative_decryption = false; } } else { QUICHE_DCHECK(header.nonce == nullptr); } } if (try_alternative_decryption) { success = alternative_decrypter->DecryptPacket( header.packet_number.ToUint64(), associated_data, encrypted, decrypted_buffer, decrypted_length, buffer_length); } if (success) { visitor_->OnDecryptedPacket(udp_packet_length, alternative_decrypter_level_); *decrypted_level = decrypter_level_; if (alternative_decrypter_latch_) { if (!EncryptionLevelIsValid(alternative_decrypter_level_)) { QUIC_BUG(quic_bug_10850_73) << "Attempted to latch alternate decrypter with bad " "alternative_decrypter_level_"; return false; } decrypter_level_ = alternative_decrypter_level_; alternative_decrypter_level_ = NUM_ENCRYPTION_LEVELS; } else { EncryptionLevel alt_level = alternative_decrypter_level_; alternative_decrypter_level_ = decrypter_level_; decrypter_level_ = alt_level; } } } if (!success) { QUIC_DVLOG(1) << ENDPOINT << "DecryptPacket failed for: " << header; return false; } return true; } size_t QuicFramer::GetIetfAckFrameSize(const QuicAckFrame& frame) { size_t ack_frame_size = kQuicFrameTypeSize; QuicPacketNumber largest_acked = LargestAcked(frame); ack_frame_size += QuicDataWriter::GetVarInt62Len(largest_acked.ToUint64()); uint64_t ack_delay_time_us; ack_delay_time_us = frame.ack_delay_time.ToMicroseconds(); ack_delay_time_us = ack_delay_time_us >> local_ack_delay_exponent_; ack_frame_size += QuicDataWriter::GetVarInt62Len(ack_delay_time_us); if (frame.packets.Empty() || frame.packets.Max() != largest_acked) { QUIC_BUG(quic_bug_10850_74) << "Malformed ack frame"; return ack_frame_size; } ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.packets.NumIntervals() - 1); auto iter = frame.packets.rbegin(); ack_frame_size += QuicDataWriter::GetVarInt62Len(iter->Length() - 1); QuicPacketNumber previous_smallest = iter->min(); ++iter; for (; iter != frame.packets.rend(); ++iter) { const uint64_t gap = previous_smallest - iter->max() - 1; const uint64_t ack_range = iter->Length() - 1; ack_frame_size += (QuicDataWriter::GetVarInt62Len(gap) + QuicDataWriter::GetVarInt62Len(ack_range)); previous_smallest = iter->min(); } if (UseIetfAckWithReceiveTimestamp(frame)) { ack_frame_size += GetIetfAckFrameTimestampSize(frame); } else { ack_frame_size += AckEcnCountSize(frame); } return ack_frame_size; } size_t QuicFramer::GetIetfAckFrameTimestampSize(const QuicAckFrame& ack) { QUICHE_DCHECK(!ack.received_packet_times.empty()); std::string detailed_error; absl::InlinedVector<AckTimestampRange, 2> timestamp_ranges = GetAckTimestampRanges(ack, detailed_error); if (!detailed_error.empty()) { return 0; } int64_t size = FrameAckTimestampRanges(ack, timestamp_ranges, nullptr); return std::max<int64_t>(0, size); } size_t QuicFramer::GetAckFrameSize( const QuicAckFrame& ack, QuicPacketNumberLength ) { QUICHE_DCHECK(!ack.packets.Empty()); size_t ack_size = 0; if (VersionHasIetfQuicFrames(version_.transport_version)) { return GetIetfAckFrameSize(ack); } AckFrameInfo ack_info = GetAckFrameInfo(ack); QuicPacketNumberLength ack_block_length = GetMinPacketNumberLength(QuicPacketNumber(ack_info.max_block_length)); ack_size = GetMinAckFrameSize(version_.transport_version, ack, local_ack_delay_exponent_, UseIetfAckWithReceiveTimestamp(ack)); ack_size += ack_block_length; if (ack_info.num_ack_blocks != 0) { ack_size += kNumberOfAckBlocksSize; ack_size += std::min(ack_info.num_ack_blocks, kMaxAckBlocks) * (ack_block_length + PACKET_1BYTE_PACKET_NUMBER); } if (process_timestamps_) { ack_size += GetAckFrameTimeStampSize(ack); } return ack_size; } size_t QuicFramer::GetAckFrameTimeStampSize(const QuicAckFrame& ack) { if (ack.received_packet_times.empty()) { return 0; } return kQuicNumTimestampsLength + kQuicFirstTimestampLength + (kQuicTimestampLength + kQuicTimestampPacketNumberGapLength) * (ack.received_packet_times.size() - 1); } size_t QuicFramer::ComputeFrameLength( const QuicFrame& frame, bool last_frame_in_packet, QuicPacketNumberLength packet_number_length) { switch (frame.type) { case STREAM_FRAME: return GetMinStreamFrameSize( version_.transport_version, frame.stream_frame.stream_id, frame.stream_frame.offset, last_frame_in_packet, frame.stream_frame.data_length) + frame.stream_frame.data_length; case CRYPTO_FRAME: return GetMinCryptoFrameSize(frame.crypto_frame->offset, frame.crypto_frame->data_length) + frame.crypto_frame->data_length; case ACK_FRAME: { return GetAckFrameSize(*frame.ack_frame, packet_number_length); } case STOP_WAITING_FRAME: return GetStopWaitingFrameSize(packet_number_length); case MTU_DISCOVERY_FRAME: return kQuicFrameTypeSize; case MESSAGE_FRAME: return GetMessageFrameSize(last_frame_in_packet, frame.message_frame->message_length); case PADDING_FRAME: QUICHE_DCHECK(false); return 0; default: return GetRetransmittableControlFrameSize(version_.transport_version, frame); } } bool QuicFramer::AppendTypeByte(const QuicFrame& frame, bool last_frame_in_packet, QuicDataWriter* writer) { if (VersionHasIetfQuicFrames(version_.transport_version)) { return AppendIetfFrameType(frame, last_frame_in_packet, writer); } uint8_t type_byte = 0; switch (frame.type) { case STREAM_FRAME: type_byte = GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet); break; case ACK_FRAME: return true; case MTU_DISCOVERY_FRAME: type_byte = static_cast<uint8_t>(PING_FRAME); break; case NEW_CONNECTION_ID_FRAME: set_detailed_error( "Attempt to append NEW_CONNECTION_ID frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case RETIRE_CONNECTION_ID_FRAME: set_detailed_error( "Attempt to append RETIRE_CONNECTION_ID frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case NEW_TOKEN_FRAME: set_detailed_error( "Attempt to append NEW_TOKEN frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case MAX_STREAMS_FRAME: set_detailed_error( "Attempt to append MAX_STREAMS frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case STREAMS_BLOCKED_FRAME: set_detailed_error( "Attempt to append STREAMS_BLOCKED frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case PATH_RESPONSE_FRAME: set_detailed_error( "Attempt to append PATH_RESPONSE frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case PATH_CHALLENGE_FRAME: set_detailed_error( "Attempt to append PATH_CHALLENGE frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case STOP_SENDING_FRAME: set_detailed_error( "Attempt to append STOP_SENDING frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case MESSAGE_FRAME: return true; default: type_byte = static_cast<uint8_t>(frame.type); break; } return writer->WriteUInt8(type_byte); } bool QuicFramer::AppendIetfFrameType(const QuicFrame& frame, bool last_frame_in_packet, QuicDataWriter* writer) { uint8_t type_byte = 0; switch (frame.type) { case PADDING_FRAME: type_byte = IETF_PADDING; break; case RST_STREAM_FRAME: type_byte = IETF_RST_STREAM; break; case CONNECTION_CLOSE_FRAME: switch (frame.connection_close_frame->close_type) { case IETF_QUIC_APPLICATION_CONNECTION_CLOSE: type_byte = IETF_APPLICATION_CLOSE; break; case IETF_QUIC_TRANSPORT_CONNECTION_CLOSE: type_byte = IETF_CONNECTION_CLOSE; break; default: set_detailed_error(absl::StrCat( "Invalid QuicConnectionCloseFrame type: ", static_cast<int>(frame.connection_close_frame->close_type))); return RaiseError(QUIC_INTERNAL_ERROR); } break; case GOAWAY_FRAME: set_detailed_error( "Attempt to create non-IETF QUIC GOAWAY frame in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case WINDOW_UPDATE_FRAME: if (frame.window_update_frame.stream_id == QuicUtils::GetInvalidStreamId(transport_version())) { type_byte = IETF_MAX_DATA; } else { type_byte = IETF_MAX_STREAM_DATA; } break; case BLOCKED_FRAME: if (frame.blocked_frame.stream_id == QuicUtils::GetInvalidStreamId(transport_version())) { type_byte = IETF_DATA_BLOCKED; } else { type_byte = IETF_STREAM_DATA_BLOCKED; } break; case STOP_WAITING_FRAME: set_detailed_error( "Attempt to append type byte of STOP WAITING frame in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case PING_FRAME: type_byte = IETF_PING; break; case STREAM_FRAME: type_byte = GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet); break; case ACK_FRAME: return true; case MTU_DISCOVERY_FRAME: type_byte = IETF_PING; break; case NEW_CONNECTION_ID_FRAME: type_byte = IETF_NEW_CONNECTION_ID; break; case RETIRE_CONNECTION_ID_FRAME: type_byte = IETF_RETIRE_CONNECTION_ID; break; case NEW_TOKEN_FRAME: type_byte = IETF_NEW_TOKEN; break; case MAX_STREAMS_FRAME: if (frame.max_streams_frame.unidirectional) { type_byte = IETF_MAX_STREAMS_UNIDIRECTIONAL; } else { type_byte = IETF_MAX_STREAMS_BIDIRECTIONAL; } break; case STREAMS_BLOCKED_FRAME: if (frame.streams_blocked_frame.unidirectional) { type_byte = IETF_STREAMS_BLOCKED_UNIDIRECTIONAL; } else { type_byte = IETF_STREAMS_BLOCKED_BIDIRECTIONAL; } break; case PATH_RESPONSE_FRAME: type_byte = IETF_PATH_RESPONSE; break; case PATH_CHALLENGE_FRAME: type_byte = IETF_PATH_CHALLENGE; break; case STOP_SENDING_FRAME: type_byte = IETF_STOP_SENDING; break; case MESSAGE_FRAME: return true; case CRYPTO_FRAME: type_byte = IETF_CRYPTO; break; case HANDSHAKE_DONE_FRAME: type_byte = IETF_HANDSHAKE_DONE; break; case ACK_FREQUENCY_FRAME: type_byte = IETF_ACK_FREQUENCY; break; case RESET_STREAM_AT_FRAME: type_byte = IETF_RESET_STREAM_AT; break; default: QUIC_BUG(quic_bug_10850_75) << "Attempt to generate a frame type for an unsupported value: " << frame.type; return false; } return writer->WriteVarInt62(type_byte); } bool QuicFramer::AppendPacketNumber(QuicPacketNumberLength packet_number_length, QuicPacketNumber packet_number, QuicDataWriter* writer) { QUICHE_DCHECK(packet_number.IsInitialized()); if (!IsValidPacketNumberLength(packet_number_length)) { QUIC_BUG(quic_bug_10850_76) << "Invalid packet_number_length: " << packet_number_length; return false; } return writer->WriteBytesToUInt64(packet_number_length, packet_number.ToUint64()); } bool QuicFramer::AppendStreamId(size_t stream_id_length, QuicStreamId stream_id, QuicDataWriter* writer) { if (stream_id_length == 0 || stream_id_length > 4) { QUIC_BUG(quic_bug_10850_77) << "Invalid stream_id_length: " << stream_id_length; return false; } return writer->WriteBytesToUInt64(stream_id_length, stream_id); } bool QuicFramer::AppendStreamOffset(size_t offset_length, QuicStreamOffset offset, QuicDataWriter* writer) { if (offset_length == 1 || offset_length > 8) { QUIC_BUG(quic_bug_10850_78) << "Invalid stream_offset_length: " << offset_length; return false; } return writer->WriteBytesToUInt64(offset_length, offset); } bool QuicFramer::AppendAckBlock(uint8_t gap, QuicPacketNumberLength length_length, uint64_t length, QuicDataWriter* writer) { if (length == 0) { if (!IsValidPacketNumberLength(length_length)) { QUIC_BUG(quic_bug_10850_79) << "Invalid packet_number_length: " << length_length; return false; } return writer->WriteUInt8(gap) && writer->WriteBytesToUInt64(length_length, length); } return writer->WriteUInt8(gap) && AppendPacketNumber(length_length, QuicPacketNumber(length), writer); } bool QuicFramer::AppendStreamFrame(const QuicStreamFrame& frame, bool no_stream_frame_length, QuicDataWriter* writer) { if (VersionHasIetfQuicFrames(version_.transport_version)) { return AppendIetfStreamFrame(frame, no_stream_frame_length, writer); } if (!AppendStreamId(GetStreamIdSize(frame.stream_id), frame.stream_id, writer)) { QUIC_BUG(quic_bug_10850_80) << "Writing stream id size failed."; return false; } if (!AppendStreamOffset(GetStreamOffsetSize(frame.offset), frame.offset, writer)) { QUIC_BUG(quic_bug_10850_81) << "Writing offset size failed."; return false; } if (!no_stream_frame_length) { static_assert( std::numeric_limits<decltype(frame.data_length)>::max() <= std::numeric_limits<uint16_t>::max(), "If frame.data_length can hold more than a uint16_t than we need to " "check that frame.data_length <= std::numeric_limits<uint16_t>::max()"); if (!writer->WriteUInt16(static_cast<uint16_t>(frame.data_length))) { QUIC_BUG(quic_bug_10850_82) << "Writing stream frame length failed"; return false; } } if (data_producer_ != nullptr) { QUICHE_DCHECK_EQ(nullptr, frame.data_buffer); if (frame.data_length == 0) { return true; } if (data_producer_->WriteStreamData(frame.stream_id, frame.offset, frame.data_length, writer) != WRITE_SUCCESS) { QUIC_BUG(quic_bug_10850_83) << "Writing frame data failed."; return false; } return true; } if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) { QUIC_BUG(quic_bug_10850_84) << "Writing frame data failed."; return false; } return true; } bool QuicFramer::AppendNewTokenFrame(const QuicNewTokenFrame& frame, QuicDataWriter* writer) { if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.token.length()))) { set_detailed_error("Writing token length failed."); return false; } if (!writer->WriteBytes(frame.token.data(), frame.token.length())) { set_detailed_error("Writing token buffer failed."); return false; } return true; } bool QuicFramer::ProcessNewTokenFrame(QuicDataReader* reader, QuicNewTokenFrame* frame) { uint64_t length; if (!reader->ReadVarInt62(&length)) { set_detailed_error("Unable to read new token length."); return false; } if (length > kMaxNewTokenTokenLength) { set_detailed_error("Token length larger than maximum."); return false; } absl::string_view data; if (!reader->ReadStringPiece(&data, length)) { set_detailed_error("Unable to read new token data."); return false; } frame->token = std::string(data); return true; } bool QuicFramer::AppendIetfStreamFrame(const QuicStreamFrame& frame, bool last_frame_in_packet, QuicDataWriter* writer) { if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) { set_detailed_error("Writing stream id failed."); return false; } if (frame.offset != 0) { if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) { set_detailed_error("Writing data offset failed."); return false; } } if (!last_frame_in_packet) { if (!writer->WriteVarInt62(frame.data_length)) { set_detailed_error("Writing data length failed."); return false; } } if (frame.data_length == 0) { return true; } if (data_producer_ == nullptr) { if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) { set_detailed_error("Writing frame data failed."); return false; } } else { QUICHE_DCHECK_EQ(nullptr, frame.data_buffer); if (data_producer_->WriteStreamData(frame.stream_id, frame.offset, frame.data_length, writer) != WRITE_SUCCESS) { set_detailed_error("Writing frame data from producer failed."); return false; } } return true; } bool QuicFramer::AppendCryptoFrame(const QuicCryptoFrame& frame, QuicDataWriter* writer) { if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) { set_detailed_error("Writing data offset failed."); return false; } if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.data_length))) { set_detailed_error("Writing data length failed."); return false; } if (data_producer_ == nullptr) { if (frame.data_buffer == nullptr || !writer->WriteBytes(frame.data_buffer, frame.data_length)) { set_detailed_error("Writing frame data failed."); return false; } } else { QUICHE_DCHECK_EQ(nullptr, frame.data_buffer); if (!data_producer_->WriteCryptoData(frame.level, frame.offset, frame.data_length, writer)) { return false; } } return true; } bool QuicFramer::AppendAckFrequencyFrame(const QuicAckFrequencyFrame& frame, QuicDataWriter* writer) { if (!writer->WriteVarInt62(frame.sequence_number)) { set_detailed_error("Writing sequence number failed."); return false; } if (!writer->WriteVarInt62(frame.packet_tolerance)) { set_detailed_error("Writing packet tolerance failed."); return false; } if (!writer->WriteVarInt62( static_cast<uint64_t>(frame.max_ack_delay.ToMicroseconds()))) { set_detailed_error("Writing max_ack_delay_us failed."); return false; } if (!writer->WriteUInt8(static_cast<uint8_t>(frame.ignore_order))) { set_detailed_error("Writing ignore_order failed."); return false; } return true; } bool QuicFramer::AppendResetFrameAtFrame(const QuicResetStreamAtFrame& frame, QuicDataWriter& writer) { if (frame.reliable_offset > frame.final_offset) { QUIC_BUG(AppendResetFrameAtFrame_offset_mismatch) << "reliable_offset > final_offset"; set_detailed_error("reliable_offset > final_offset"); return false; } absl::Status status = quiche::SerializeIntoWriter(writer, quiche::WireVarInt62(frame.stream_id), quiche::WireVarInt62(frame.error), quiche::WireVarInt62(frame.final_offset), quiche::WireVarInt62(frame.reliable_offset)); if (!status.ok()) { set_detailed_error(std::string(status.message())); return false; } return true; } void QuicFramer::set_version(const ParsedQuicVersion version) { QUICHE_DCHECK(IsSupportedVersion(version)) << ParsedQuicVersionToString(version); version_ = version; } bool QuicFramer::AppendAckFrameAndTypeByte(const QuicAckFrame& frame, QuicDataWriter* writer) { if (VersionHasIetfQuicFrames(transport_version())) { return AppendIetfAckFrameAndTypeByte(frame, writer); } const AckFrameInfo new_ack_info = GetAckFrameInfo(frame); QuicPacketNumber largest_acked = LargestAcked(frame); QuicPacketNumberLength largest_acked_length = GetMinPacketNumberLength(largest_acked); QuicPacketNumberLength ack_block_length = GetMinPacketNumberLength(QuicPacketNumber(new_ack_info.max_block_length)); int32_t available_timestamp_and_ack_block_bytes = writer->capacity() - writer->length() - ack_block_length - GetMinAckFrameSize(version_.transport_version, frame, local_ack_delay_exponent_, UseIetfAckWithReceiveTimestamp(frame)) - (new_ack_info.num_ack_blocks != 0 ? kNumberOfAckBlocksSize : 0); QUICHE_DCHECK_LE(0, available_timestamp_and_ack_block_bytes); uint8_t type_byte = 0; SetBit(&type_byte, new_ack_info.num_ack_blocks != 0, kQuicHasMultipleAckBlocksOffset); SetBits(&type_byte, GetPacketNumberFlags(largest_acked_length), kQuicSequenceNumberLengthNumBits, kLargestAckedOffset); SetBits(&type_byte, GetPacketNumberFlags(ack_block_length), kQuicSequenceNumberLengthNumBits, kActBlockLengthOffset); type_byte |= kQuicFrameTypeAckMask; if (!writer->WriteUInt8(type_byte)) { return false; } size_t max_num_ack_blocks = available_timestamp_and_ack_block_bytes / (ack_block_length + PACKET_1BYTE_PACKET_NUMBER); size_t num_ack_blocks = std::min(new_ack_info.num_ack_blocks, max_num_ack_blocks); if (num_ack_blocks > std::numeric_limits<uint8_t>::max()) { num_ack_blocks = std::numeric_limits<uint8_t>::max(); } if (!AppendPacketNumber(largest_acked_length, largest_acked, writer)) { return false; } uint64_t ack_delay_time_us = kUFloat16MaxValue; if (!frame.ack_delay_time.IsInfinite()) { QUICHE_DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds()); ack_delay_time_us = frame.ack_delay_time.ToMicroseconds(); } if (!writer->WriteUFloat16(ack_delay_time_us)) { return false; } if (num_ack_blocks > 0) { if (!writer->WriteBytes(&num_ack_blocks, 1)) { return false; } } if (!AppendPacketNumber(ack_block_length, QuicPacketNumber(new_ack_info.first_block_length), writer)) { return false; } if (num_ack_blocks > 0) { size_t num_ack_blocks_written = 0; auto itr = frame.packets.rbegin(); QuicPacketNumber previous_start = itr->min(); ++itr; for (; itr != frame.packets.rend() && num_ack_blocks_written < num_ack_blocks; previous_start = itr->min(), ++itr) { const auto& interval = *itr; const uint64_t total_gap = previous_start - interval.max(); const size_t num_encoded_gaps = (total_gap + std::numeric_limits<uint8_t>::max() - 1) / std::numeric_limits<uint8_t>::max(); for (size_t i = 1; i < num_encoded_gaps && num_ack_blocks_written < num_ack_blocks; ++i) { if (!AppendAckBlock(std::numeric_limits<uint8_t>::max(), ack_block_length, 0, writer)) { return false; } ++num_ack_blocks_written; } if (num_ack_blocks_written >= num_ack_blocks) { if (ABSL_PREDICT_FALSE(num_ack_blocks_written != num_ack_blocks)) { QUIC_BUG(quic_bug_10850_85) << "Wrote " << num_ack_blocks_written << ", expected to write " << num_ack_blocks; } break; } const uint8_t last_gap = total_gap - (num_encoded_gaps - 1) * std::numeric_limits<uint8_t>::max(); if (!AppendAckBlock(last_gap, ack_block_length, interval.Length(), writer)) { return false; } ++num_ack_blocks_written; } QUICHE_DCHECK_EQ(num_ack_blocks, num_ack_blocks_written); } if (process_timestamps_ && writer->capacity() - writer->length() >= GetAckFrameTimeStampSize(frame)) { if (!AppendTimestampsToAckFrame(frame, writer)) { return false; } } else { uint8_t num_received_packets = 0; if (!writer->WriteBytes(&num_received_packets, 1)) { return false; } } return true; } bool QuicFramer::AppendTimestampsToAckFrame(const QuicAckFrame& frame, QuicDataWriter* writer) { QUICHE_DCHECK_GE(std::numeric_limits<uint8_t>::max(), frame.received_packet_times.size()); if (frame.received_packet_times.size() > std::numeric_limits<uint8_t>::max()) { return false; } uint8_t num_received_packets = frame.received_packet_times.size(); if (!writer->WriteBytes(&num_received_packets, 1)) { return false; } if (num_received_packets == 0) { return true; } auto it = frame.received_packet_times.begin(); QuicPacketNumber packet_number = it->first; uint64_t delta_from_largest_observed = LargestAcked(frame) - packet_number; QUICHE_DCHECK_GE(std::numeric_limits<uint8_t>::max(), delta_from_largest_observed); if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) { return false; } if (!writer->WriteUInt8(delta_from_largest_observed)) { return false; } const uint64_t time_epoch_delta_us = UINT64_C(1) << 32; uint32_t time_delta_us = static_cast<uint32_t>((it->second - creation_time_).ToMicroseconds() & (time_epoch_delta_us - 1)); if (!writer->WriteUInt32(time_delta_us)) { return false; } QuicTime prev_time = it->second; for (++it; it != frame.received_packet_times.end(); ++it) { packet_number = it->first; delta_from_largest_observed = LargestAcked(frame) - packet_number; if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) { return false; } if (!writer->WriteUInt8(delta_from_largest_observed)) { return false; } uint64_t frame_time_delta_us = (it->second - prev_time).ToMicroseconds(); prev_time = it->second; if (!writer->WriteUFloat16(frame_time_delta_us)) { return false; } } return true; } absl::InlinedVector<QuicFramer::AckTimestampRange, 2> QuicFramer::GetAckTimestampRanges(const QuicAckFrame& frame, std::string& detailed_error) const { detailed_error = ""; if (frame.received_packet_times.empty()) { return {}; } absl::InlinedVector<AckTimestampRange, 2> timestamp_ranges; for (size_t r = 0; r < std::min<size_t>(max_receive_timestamps_per_ack_, frame.received_packet_times.size()); ++r) { const size_t i = frame.received_packet_times.size() - 1 - r; const QuicPacketNumber packet_number = frame.received_packet_times[i].first; const QuicTime receive_timestamp = frame.received_packet_times[i].second; if (timestamp_ranges.empty()) { if (receive_timestamp < creation_time_ || LargestAcked(frame) < packet_number) { detailed_error = "The first packet is either received earlier than framer creation " "time, or larger than largest acked packet."; QUIC_BUG(quic_framer_ack_ts_first_packet_bad) << detailed_error << " receive_timestamp:" << receive_timestamp << ", framer_creation_time:" << creation_time_ << ", packet_number:" << packet_number << ", largest_acked:" << LargestAcked(frame); return {}; } timestamp_ranges.push_back(AckTimestampRange()); timestamp_ranges.back().gap = LargestAcked(frame) - packet_number; timestamp_ranges.back().range_begin = i; timestamp_ranges.back().range_end = i; continue; } const size_t prev_i = timestamp_ranges.back().range_end; const QuicPacketNumber prev_packet_number = frame.received_packet_times[prev_i].first; const QuicTime prev_receive_timestamp = frame.received_packet_times[prev_i].second; QUIC_DVLOG(3) << "prev_packet_number:" << prev_packet_number << ", packet_number:" << packet_number; if (prev_receive_timestamp < receive_timestamp || prev_packet_number <= packet_number) { detailed_error = "Packet number and/or receive time not in order."; QUIC_BUG(quic_framer_ack_ts_packet_out_of_order) << detailed_error << " packet_number:" << packet_number << ", receive_timestamp:" << receive_timestamp << ", prev_packet_number:" << prev_packet_number << ", prev_receive_timestamp:" << prev_receive_timestamp; return {}; } if (prev_packet_number == packet_number + 1) { timestamp_ranges.back().range_end = i; } else { timestamp_ranges.push_back(AckTimestampRange()); timestamp_ranges.back().gap = prev_packet_number - 2 - packet_number; timestamp_ranges.back().range_begin = i; timestamp_ranges.back().range_end = i; } } return timestamp_ranges; } int64_t QuicFramer::FrameAckTimestampRanges( const QuicAckFrame& frame, const absl::InlinedVector<AckTimestampRange, 2>& timestamp_ranges, QuicDataWriter* writer) const { int64_t size = 0; auto maybe_write_var_int62 = [&](uint64_t value) { size += QuicDataWriter::GetVarInt62Len(value); if (writer != nullptr && !writer->WriteVarInt62(value)) { return false; } return true; }; if (!maybe_write_var_int62(timestamp_ranges.size())) { return -1; } std::optional<QuicTime> effective_prev_time; for (const AckTimestampRange& range : timestamp_ranges) { QUIC_DVLOG(3) << "Range: gap:" << range.gap << ", beg:" << range.range_begin << ", end:" << range.range_end; if (!maybe_write_var_int62(range.gap)) { return -1; } if (!maybe_write_var_int62(range.range_begin - range.range_end + 1)) { return -1; } for (int64_t i = range.range_begin; i >= range.range_end; --i) { const QuicTime receive_timestamp = frame.received_packet_times[i].second; uint64_t time_delta; if (effective_prev_time.has_value()) { time_delta = (*effective_prev_time - receive_timestamp).ToMicroseconds(); QUIC_DVLOG(3) << "time_delta:" << time_delta << ", exponent:" << receive_timestamps_exponent_ << ", effective_prev_time:" << *effective_prev_time << ", recv_time:" << receive_timestamp; time_delta = time_delta >> receive_timestamps_exponent_; effective_prev_time = *effective_prev_time - QuicTime::Delta::FromMicroseconds( time_delta << receive_timestamps_exponent_); } else { time_delta = (receive_timestamp - creation_time_).ToMicroseconds(); QUIC_DVLOG(3) << "First time_delta:" << time_delta << ", exponent:" << receive_timestamps_exponent_ << ", recv_time:" << receive_timestamp << ", creation_time:" << creation_time_; time_delta = ((time_delta - 1) >> receive_timestamps_exponent_) + 1; effective_prev_time = creation_time_ + QuicTime::Delta::FromMicroseconds( time_delta << receive_timestamps_exponent_); } if (!maybe_write_var_int62(time_delta)) { return -1; } } } return size; } bool QuicFramer::AppendIetfTimestampsToAckFrame(const QuicAckFrame& frame, QuicDataWriter* writer) { QUICHE_DCHECK(!frame.received_packet_times.empty()); std::string detailed_error; const absl::InlinedVector<AckTimestampRange, 2> timestamp_ranges = GetAckTimestampRanges(frame, detailed_error); if (!detailed_error.empty()) { set_detailed_error(std::move(detailed_error)); return false; } int64_t size = FrameAckTimestampRanges(frame, timestamp_ranges, nullptr); if (size > static_cast<int64_t>(writer->capacity() - writer->length())) { QUIC_DVLOG(1) << "Insufficient room to write IETF ack receive timestamps. " "size_remain:" << (writer->capacity() - writer->length()) << ", size_needed:" << size; return writer->WriteVarInt62(0); } return FrameAckTimestampRanges(frame, timestamp_ranges, writer) > 0; } bool QuicFramer::AppendIetfAckFrameAndTypeByte(const QuicAckFrame& frame, QuicDataWriter* writer) { uint8_t type = IETF_ACK; uint64_t ecn_size = 0; if (UseIetfAckWithReceiveTimestamp(frame)) { type = IETF_ACK_RECEIVE_TIMESTAMPS; } else if (frame.ecn_counters.has_value()) { type = IETF_ACK_ECN; ecn_size = AckEcnCountSize(frame); } if (!writer->WriteVarInt62(type)) { set_detailed_error("No room for frame-type"); return false; } QuicPacketNumber largest_acked = LargestAcked(frame); if (!writer->WriteVarInt62(largest_acked.ToUint64())) { set_detailed_error("No room for largest-acked in ack frame"); return false; } uint64_t ack_delay_time_us = quiche::kVarInt62MaxValue; if (!frame.ack_delay_time.IsInfinite()) { QUICHE_DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds()); ack_delay_time_us = frame.ack_delay_time.ToMicroseconds(); ack_delay_time_us = ack_delay_time_us >> local_ack_delay_exponent_; } if (!writer->WriteVarInt62(ack_delay_time_us)) { set_detailed_error("No room for ack-delay in ack frame"); return false; } if (frame.packets.Empty() || frame.packets.Max() != largest_acked) { QUIC_BUG(quic_bug_10850_88) << "Malformed ack frame: " << frame; set_detailed_error("Malformed ack frame"); return false; } const uint64_t ack_block_count = frame.packets.NumIntervals() - 1; QuicDataWriter count_writer(QuicDataWriter::GetVarInt62Len(ack_block_count), writer->data() + writer->length()); if (!writer->WriteVarInt62(ack_block_count)) { set_detailed_error("No room for ack block count in ack frame"); return false; } auto iter = frame.packets.rbegin(); if (!writer->WriteVarInt62(iter->Length() - 1)) { set_detailed_error("No room for first ack block in ack frame"); return false; } QuicPacketNumber previous_smallest = iter->min(); ++iter; uint64_t appended_ack_blocks = 0; for (; iter != frame.packets.rend(); ++iter) { const uint64_t gap = previous_smallest - iter->max() - 1; const uint64_t ack_range = iter->Length() - 1; if (type == IETF_ACK_RECEIVE_TIMESTAMPS && writer->remaining() < static_cast<size_t>(QuicDataWriter::GetVarInt62Len(gap) + QuicDataWriter::GetVarInt62Len(ack_range) + QuicDataWriter::GetVarInt62Len(0))) { break; } else if (writer->remaining() < ecn_size || writer->remaining() - ecn_size < static_cast<size_t>( QuicDataWriter::GetVarInt62Len(gap) + QuicDataWriter::GetVarInt62Len(ack_range))) { break; } const bool success = writer->WriteVarInt62(gap) && writer->WriteVarInt62(ack_range); QUICHE_DCHECK(success); previous_smallest = iter->min(); ++appended_ack_blocks; } if (appended_ack_blocks < ack_block_count) { if (QuicDataWriter::GetVarInt62Len(appended_ack_blocks) != QuicDataWriter::GetVarInt62Len(ack_block_count) || !count_writer.WriteVarInt62(appended_ack_blocks)) { QUIC_BUG(quic_bug_10850_89) << "Ack frame truncation fails. ack_block_count: " << ack_block_count << ", appended count: " << appended_ack_blocks; set_detailed_error("ACK frame truncation fails"); return false; } QUIC_DLOG(INFO) << ENDPOINT << "ACK ranges get truncated from " << ack_block_count << " to " << appended_ack_blocks; } if (type == IETF_ACK_ECN) { if (!writer->WriteVarInt62(frame.ecn_counters->ect0)) { set_detailed_error("No room for ect_0_count in ack frame"); return false; } if (!writer->WriteVarInt62(frame.ecn_counters->ect1)) { set_detailed_error("No room for ect_1_count in ack frame"); return false; } if (!writer->WriteVarInt62(frame.ecn_counters->ce)) { set_detailed_error("No room for ecn_ce_count in ack frame"); return false; } } if (type == IETF_ACK_RECEIVE_TIMESTAMPS) { if (!AppendIetfTimestampsToAckFrame(frame, writer)) { return false; } } return true; } bool QuicFramer::AppendRstStreamFrame(const QuicRstStreamFrame& frame, QuicDataWriter* writer) { if (VersionHasIetfQuicFrames(version_.transport_version)) { return AppendIetfResetStreamFrame(frame, writer); } if (!writer->WriteUInt32(frame.stream_id)) { return false; } if (!writer->WriteUInt64(frame.byte_offset)) { return false; } uint32_t error_code = static_cast<uint32_t>(frame.error_code); if (!writer->WriteUInt32(error_code)) { return false; } return true; } bool QuicFramer::AppendConnectionCloseFrame( const QuicConnectionCloseFrame& frame, QuicDataWriter* writer) { if (VersionHasIetfQuicFrames(version_.transport_version)) { return AppendIetfConnectionCloseFrame(frame, writer); } uint32_t error_code = static_cast<uint32_t>(frame.wire_error_code); if (!writer->WriteUInt32(error_code)) { return false; } if (!writer->WriteStringPiece16(TruncateErrorString(frame.error_details))) { return false; } return true; } bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame& frame, QuicDataWriter* writer) { uint32_t error_code = static_cast<uint32_t>(frame.error_code); if (!writer->WriteUInt32(error_code)) { return false; } uint32_t stream_id = static_cast<uint32_t>(frame.last_good_stream_id); if (!writer->WriteUInt32(stream_id)) { return false; } if (!writer->WriteStringPiece16(TruncateErrorString(frame.reason_phrase))) { return false; } return true; } bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame& frame, QuicDataWriter* writer) { uint32_t stream_id = static_cast<uint32_t>(frame.stream_id); if (!writer->WriteUInt32(stream_id)) { return false; } if (!writer->WriteUInt64(frame.max_data)) { return false; } return true; } bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame& frame, QuicDataWriter* writer) { if (VersionHasIetfQuicFrames(version_.transport_version)) { if (frame.stream_id == QuicUtils::GetInvalidStreamId(transport_version())) { return AppendDataBlockedFrame(frame, writer); } return AppendStreamDataBlockedFrame(frame, writer); } uint32_t stream_id = static_cast<uint32_t>(frame.stream_id); if (!writer->WriteUInt32(stream_id)) { return false; } return true; } bool QuicFramer::AppendPaddingFrame(const QuicPaddingFrame& frame, QuicDataWriter* writer) { if (frame.num_padding_bytes == 0) { return false; } if (frame.num_padding_bytes < 0) { QUIC_BUG_IF(quic_bug_12975_9, frame.num_padding_bytes != -1); writer->WritePadding(); return true; } return writer->WritePaddingBytes(frame.num_padding_bytes - 1); } bool QuicFramer::AppendMessageFrameAndTypeByte(const QuicMessageFrame& frame, bool last_frame_in_packet, QuicDataWriter* writer) { uint8_t type_byte; if (VersionHasIetfQuicFrames(version_.transport_version)) { type_byte = last_frame_in_packet ? IETF_EXTENSION_MESSAGE_NO_LENGTH_V99 : IETF_EXTENSION_MESSAGE_V99; } else { QUIC_CODE_COUNT(quic_legacy_message_frame_codepoint_write); type_byte = last_frame_in_packet ? IETF_EXTENSION_MESSAGE_NO_LENGTH : IETF_EXTENSION_MESSAGE; } if (!writer->WriteUInt8(type_byte)) { return false; } if (!last_frame_in_packet && !writer->WriteVarInt62(frame.message_length)) { return false; } for (const auto& slice : frame.message_data) { if (!writer->WriteBytes(slice.data(), slice.length())) { return false; } } return true; } bool QuicFramer::RaiseError(QuicErrorCode error) { QUIC_DLOG(INFO) << ENDPOINT << "Error: " << QuicErrorCodeToString(error) << " detail: " << detailed_error_; set_error(error); if (visitor_) { visitor_->OnError(this); } return false; } bool QuicFramer::IsVersionNegotiation(const QuicPacketHeader& header) const { return header.form == IETF_QUIC_LONG_HEADER_PACKET && header.long_packet_type == VERSION_NEGOTIATION; } bool QuicFramer::AppendIetfConnectionCloseFrame( const QuicConnectionCloseFrame& frame, QuicDataWriter* writer) { if (frame.close_type != IETF_QUIC_TRANSPORT_CONNECTION_CLOSE && frame.close_type != IETF_QUIC_APPLICATION_CONNECTION_CLOSE) { QUIC_BUG(quic_bug_10850_90) << "Invalid close_type for writing IETF CONNECTION CLOSE."; set_detailed_error("Invalid close_type for writing IETF CONNECTION CLOSE."); return false; } if (!writer->WriteVarInt62(frame.wire_error_code)) { set_detailed_error("Can not write connection close frame error code"); return false; } if (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) { if (!writer->WriteVarInt62(frame.transport_close_frame_type)) { set_detailed_error("Writing frame type failed."); return false; } } std::string final_error_string = GenerateErrorString(frame.error_details, frame.quic_error_code); if (!writer->WriteStringPieceVarInt62( TruncateErrorString(final_error_string))) { set_detailed_error("Can not write connection close phrase"); return false; } return true; } bool QuicFramer::ProcessIetfConnectionCloseFrame( QuicDataReader* reader, QuicConnectionCloseType type, QuicConnectionCloseFrame* frame) { frame->close_type = type; uint64_t error_code; if (!reader->ReadVarInt62(&error_code)) { set_detailed_error("Unable to read connection close error code."); return false; } frame->wire_error_code = error_code; if (type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) { if (!reader->ReadVarInt62(&frame->transport_close_frame_type)) { set_detailed_error("Unable to read connection close frame type."); return false; } } uint64_t phrase_length; if (!reader->ReadVarInt62(&phrase_length)) { set_detailed_error("Unable to read connection close error details."); return false; } absl::string_view phrase; if (!reader->ReadStringPiece(&phrase, static_cast<size_t>(phrase_length))) { set_detailed_error("Unable to read connection close error details."); return false; } frame->error_details = std::string(phrase); MaybeExtractQuicErrorCode(frame); return true; } bool QuicFramer::ProcessPathChallengeFrame(QuicDataReader* reader, QuicPathChallengeFrame* frame) { if (!reader->ReadBytes(frame->data_buffer.data(), frame->data_buffer.size())) { set_detailed_error("Can not read path challenge data."); return false; } return true; } bool QuicFramer::ProcessPathResponseFrame(QuicDataReader* reader, QuicPathResponseFrame* frame) { if (!reader->ReadBytes(frame->data_buffer.data(), frame->data_buffer.size())) { set_detailed_error("Can not read path response data."); return false; } return true; } bool QuicFramer::AppendPathChallengeFrame(const QuicPathChallengeFrame& frame, QuicDataWriter* writer) { if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) { set_detailed_error("Writing Path Challenge data failed."); return false; } return true; } bool QuicFramer::AppendPathResponseFrame(const QuicPathResponseFrame& frame, QuicDataWriter* writer) { if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) { set_detailed_error("Writing Path Response data failed."); return false; } return true; } bool QuicFramer::AppendIetfResetStreamFrame(const QuicRstStreamFrame& frame, QuicDataWriter* writer) { if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) { set_detailed_error("Writing reset-stream stream id failed."); return false; } if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.ietf_error_code))) { set_detailed_error("Writing reset-stream error code failed."); return false; } if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.byte_offset))) { set_detailed_error("Writing reset-stream final-offset failed."); return false; } return true; } bool QuicFramer::ProcessIetfResetStreamFrame(QuicDataReader* reader, QuicRstStreamFrame* frame) { if (!ReadUint32FromVarint62(reader, IETF_RST_STREAM, &frame->stream_id)) { return false; } if (!reader->ReadVarInt62(&frame->ietf_error_code)) { set_detailed_error("Unable to read rst stream error code."); return false; } frame->error_code = IetfResetStreamErrorCodeToRstStreamErrorCode(frame->ietf_error_code); if (!reader->ReadVarInt62(&frame->byte_offset)) { set_detailed_error("Unable to read rst stream sent byte offset."); return false; } return true; } bool QuicFramer::ProcessStopSendingFrame( QuicDataReader* reader, QuicStopSendingFrame* stop_sending_frame) { if (!ReadUint32FromVarint62(reader, IETF_STOP_SENDING, &stop_sending_frame->stream_id)) { return false; } if (!reader->ReadVarInt62(&stop_sending_frame->ietf_error_code)) { set_detailed_error("Unable to read stop sending application error code."); return false; } stop_sending_frame->error_code = IetfResetStreamErrorCodeToRstStreamErrorCode( stop_sending_frame->ietf_error_code); return true; } bool QuicFramer::AppendStopSendingFrame( const QuicStopSendingFrame& stop_sending_frame, QuicDataWriter* writer) { if (!writer->WriteVarInt62(stop_sending_frame.stream_id)) { set_detailed_error("Can not write stop sending stream id"); return false; } if (!writer->WriteVarInt62( static_cast<uint64_t>(stop_sending_frame.ietf_error_code))) { set_detailed_error("Can not write application error code"); return false; } return true; } bool QuicFramer::AppendMaxDataFrame(const QuicWindowUpdateFrame& frame, QuicDataWriter* writer) { if (!writer->WriteVarInt62(frame.max_data)) { set_detailed_error("Can not write MAX_DATA byte-offset"); return false; } return true; } bool QuicFramer::ProcessMaxDataFrame(QuicDataReader* reader, QuicWindowUpdateFrame* frame) { frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version()); if (!reader->ReadVarInt62(&frame->max_data)) { set_detailed_error("Can not read MAX_DATA byte-offset"); return false; } return true; } bool QuicFramer::AppendMaxStreamDataFrame(const QuicWindowUpdateFrame& frame, QuicDataWriter* writer) { if (!writer->WriteVarInt62(frame.stream_id)) { set_detailed_error("Can not write MAX_STREAM_DATA stream id"); return false; } if (!writer->WriteVarInt62(frame.max_data)) { set_detailed_error("Can not write MAX_STREAM_DATA byte-offset"); return false; } return true; } bool QuicFramer::ProcessMaxStreamDataFrame(QuicDataReader* reader, QuicWindowUpdateFrame* frame) { if (!ReadUint32FromVarint62(reader, IETF_MAX_STREAM_DATA, &frame->stream_id)) { return false; } if (!reader->ReadVarInt62(&frame->max_data)) { set_detailed_error("Can not read MAX_STREAM_DATA byte-count"); return false; } return true; } bool QuicFramer::AppendMaxStreamsFrame(const QuicMaxStreamsFrame& frame, QuicDataWriter* writer) { if (!writer->WriteVarInt62(frame.stream_count)) { set_detailed_error("Can not write MAX_STREAMS stream count"); return false; } return true; } bool QuicFramer::ProcessMaxStreamsFrame(QuicDataReader* reader, QuicMaxStreamsFrame* frame, uint64_t frame_type) { if (!ReadUint32FromVarint62(reader, static_cast<QuicIetfFrameType>(frame_type), &frame->stream_count)) { return false; } frame->unidirectional = (frame_type == IETF_MAX_STREAMS_UNIDIRECTIONAL); return true; } bool QuicFramer::AppendDataBlockedFrame(const QuicBlockedFrame& frame, QuicDataWriter* writer) { if (!writer->WriteVarInt62(frame.offset)) { set_detailed_error("Can not write blocked offset."); return false; } return true; } bool QuicFramer::ProcessDataBlockedFrame(QuicDataReader* reader, QuicBlockedFrame* frame) { frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version()); if (!reader->ReadVarInt62(&frame->offset)) { set_detailed_error("Can not read blocked offset."); return false; } return true; } bool QuicFramer::AppendStreamDataBlockedFrame(const QuicBlockedFrame& frame, QuicDataWriter* writer) { if (!writer->WriteVarInt62(frame.stream_id)) { set_detailed_error("Can not write stream blocked stream id."); return false; } if (!writer->WriteVarInt62(frame.offset)) { set_detailed_error("Can not write stream blocked offset."); return false; } return true; } bool QuicFramer::ProcessStreamDataBlockedFrame(QuicDataReader* reader, QuicBlockedFrame* frame) { if (!ReadUint32FromVarint62(reader, IETF_STREAM_DATA_BLOCKED, &frame->stream_id)) { return false; } if (!reader->ReadVarInt62(&frame->offset)) { set_detailed_error("Can not read stream blocked offset."); return false; } return true; } bool QuicFramer::AppendStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame, QuicDataWriter* writer) { if (!writer->WriteVarInt62(frame.stream_count)) { set_detailed_error("Can not write STREAMS_BLOCKED stream count"); return false; } return true; } bool QuicFramer::ProcessStreamsBlockedFrame(QuicDataReader* reader, QuicStreamsBlockedFrame* frame, uint64_t frame_type) { if (!ReadUint32FromVarint62(reader, static_cast<QuicIetfFrameType>(frame_type), &frame->stream_count)) { return false; } if (frame->stream_count > QuicUtils::GetMaxStreamCount()) { set_detailed_error( "STREAMS_BLOCKED stream count exceeds implementation limit."); return false; } frame->unidirectional = (frame_type == IETF_STREAMS_BLOCKED_UNIDIRECTIONAL); return true; } bool QuicFramer::AppendNewConnectionIdFrame( const QuicNewConnectionIdFrame& frame, QuicDataWriter* writer) { if (!writer->WriteVarInt62(frame.sequence_number)) { set_detailed_error("Can not write New Connection ID sequence number"); return false; } if (!writer->WriteVarInt62(frame.retire_prior_to)) { set_detailed_error("Can not write New Connection ID retire_prior_to"); return false; } if (!writer->WriteLengthPrefixedConnectionId(frame.connection_id)) { set_detailed_error("Can not write New Connection ID frame connection ID"); return false; } if (!writer->WriteBytes( static_cast<const void*>(&frame.stateless_reset_token), sizeof(frame.stateless_reset_token))) { set_detailed_error("Can not write New Connection ID Reset Token"); return false; } return true; } bool QuicFramer::ProcessNewConnectionIdFrame(QuicDataReader* reader, QuicNewConnectionIdFrame* frame) { if (!reader->ReadVarInt62(&frame->sequence_number)) { set_detailed_error( "Unable to read new connection ID frame sequence number."); return false; } if (!reader->ReadVarInt62(&frame->retire_prior_to)) { set_detailed_error( "Unable to read new connection ID frame retire_prior_to."); return false; } if (frame->retire_prior_to > frame->sequence_number) { set_detailed_error("Retire_prior_to > sequence_number."); return false; } if (!reader->ReadLengthPrefixedConnectionId(&frame->connection_id)) { set_detailed_error("Unable to read new connection ID frame connection id."); return false; } if (!QuicUtils::IsConnectionIdValidForVersion(frame->connection_id, transport_version())) { set_detailed_error("Invalid new connection ID length for version."); return false; } if (!reader->ReadBytes(&frame->stateless_reset_token, sizeof(frame->stateless_reset_token))) { set_detailed_error("Can not read new connection ID frame reset token."); return false; } return true; } bool QuicFramer::AppendRetireConnectionIdFrame( const QuicRetireConnectionIdFrame& frame, QuicDataWriter* writer) { if (!writer->WriteVarInt62(frame.sequence_number)) { set_detailed_error("Can not write Retire Connection ID sequence number"); return false; } return true; } bool QuicFramer::ProcessRetireConnectionIdFrame( QuicDataReader* reader, QuicRetireConnectionIdFrame* frame) { if (!reader->ReadVarInt62(&frame->sequence_number)) { set_detailed_error( "Unable to read retire connection ID frame sequence number."); return false; } return true; } bool QuicFramer::ReadUint32FromVarint62(QuicDataReader* reader, QuicIetfFrameType type, QuicStreamId* id) { uint64_t temp_uint64; if (!reader->ReadVarInt62(&temp_uint64)) { set_detailed_error("Unable to read " + QuicIetfFrameTypeString(type) + " frame stream id/count."); return false; } if (temp_uint64 > kMaxQuicStreamId) { set_detailed_error("Stream id/count of " + QuicIetfFrameTypeString(type) + "frame is too large."); return false; } *id = static_cast<uint32_t>(temp_uint64); return true; } uint8_t QuicFramer::GetStreamFrameTypeByte(const QuicStreamFrame& frame, bool last_frame_in_packet) const { if (VersionHasIetfQuicFrames(version_.transport_version)) { return GetIetfStreamFrameTypeByte(frame, last_frame_in_packet); } uint8_t type_byte = 0; type_byte |= frame.fin ? kQuicStreamFinMask : 0; type_byte <<= kQuicStreamDataLengthShift; type_byte |= last_frame_in_packet ? 0 : kQuicStreamDataLengthMask; type_byte <<= kQuicStreamShift; const size_t offset_len = GetStreamOffsetSize(frame.offset); if (offset_len > 0) { type_byte |= offset_len - 1; } type_byte <<= kQuicStreamIdShift; type_byte |= GetStreamIdSize(frame.stream_id) - 1; type_byte |= kQuicFrameTypeStreamMask; return type_byte; } uint8_t QuicFramer::GetIetfStreamFrameTypeByte( const QuicStreamFrame& frame, bool last_frame_in_packet) const { QUICHE_DCHECK(VersionHasIetfQuicFrames(version_.transport_version)); uint8_t type_byte = IETF_STREAM; if (!last_frame_in_packet) { type_byte |= IETF_STREAM_FRAME_LEN_BIT; } if (frame.offset != 0) { type_byte |= IETF_STREAM_FRAME_OFF_BIT; } if (frame.fin) { type_byte |= IETF_STREAM_FRAME_FIN_BIT; } return type_byte; } void QuicFramer::EnableMultiplePacketNumberSpacesSupport() { if (supports_multiple_packet_number_spaces_) { QUIC_BUG(quic_bug_10850_91) << "Multiple packet number spaces has already been enabled"; return; } if (largest_packet_number_.IsInitialized()) { QUIC_BUG(quic_bug_10850_92) << "Try to enable multiple packet number spaces support after any " "packet has been received."; return; } supports_multiple_packet_number_spaces_ = true; } QuicErrorCode QuicFramer::ParsePublicHeaderDispatcher( const QuicEncryptedPacket& packet, uint8_t expected_destination_connection_id_length, PacketHeaderFormat* format, QuicLongHeaderType* long_packet_type, bool* version_present, bool* has_length_prefix, QuicVersionLabel* version_label, ParsedQuicVersion* parsed_version, QuicConnectionId* destination_connection_id, QuicConnectionId* source_connection_id, std::optional<absl::string_view>* retry_token, std::string* detailed_error) { QuicDataReader reader(packet.data(), packet.length()); if (reader.IsDoneReading()) { *detailed_error = "Unable to read first byte."; return QUIC_INVALID_PACKET_HEADER; } const uint8_t first_byte = reader.PeekByte(); if ((first_byte & FLAGS_LONG_HEADER) == 0 && (first_byte & FLAGS_FIXED_BIT) == 0 && (first_byte & FLAGS_DEMULTIPLEXING_BIT) == 0) { *detailed_error = "Invalid flags."; return QUIC_INVALID_PACKET_HEADER; } const bool ietf_format = QuicUtils::IsIetfPacketHeader(first_byte); uint8_t unused_first_byte; quiche::QuicheVariableLengthIntegerLength retry_token_length_length; absl::string_view maybe_retry_token; QuicErrorCode error_code = ParsePublicHeader( &reader, expected_destination_connection_id_length, ietf_format, &unused_first_byte, format, version_present, has_length_prefix, version_label, parsed_version, destination_connection_id, source_connection_id, long_packet_type, &retry_token_length_length, &maybe_retry_token, detailed_error); if (retry_token_length_length != quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0) { *retry_token = maybe_retry_token; } else { retry_token->reset(); } return error_code; } QuicErrorCode QuicFramer::ParsePublicHeaderDispatcherShortHeaderLengthUnknown( const QuicEncryptedPacket& packet, PacketHeaderFormat* format, QuicLongHeaderType* long_packet_type, bool* version_present, bool* has_length_prefix, QuicVersionLabel* version_label, ParsedQuicVersion* parsed_version, QuicConnectionId* destination_connection_id, QuicConnectionId* source_connection_id, std::optional<absl::string_view>* retry_token, std::string* detailed_error, ConnectionIdGeneratorInterface& generator) { QuicDataReader reader(packet.data(), packet.length()); if (reader.BytesRemaining() < 2) { *detailed_error = "Unable to read first two bytes."; return QUIC_INVALID_PACKET_HEADER; } uint8_t two_bytes[2]; reader.ReadBytes(two_bytes, 2); uint8_t expected_destination_connection_id_length = (!QuicUtils::IsIetfPacketHeader(two_bytes[0]) || two_bytes[0] & FLAGS_LONG_HEADER) ? 0 : generator.ConnectionIdLength(two_bytes[1]); return ParsePublicHeaderDispatcher( packet, expected_destination_connection_id_length, format, long_packet_type, version_present, has_length_prefix, version_label, parsed_version, destination_connection_id, source_connection_id, retry_token, detailed_error); } QuicErrorCode QuicFramer::TryDecryptInitialPacketDispatcher( const QuicEncryptedPacket& packet, const ParsedQuicVersion& version, PacketHeaderFormat format, QuicLongHeaderType long_packet_type, const QuicConnectionId& destination_connection_id, const QuicConnectionId& source_connection_id, const std::optional<absl::string_view>& retry_token, QuicPacketNumber largest_decrypted_inital_packet_number, QuicDecrypter& decrypter, std::optional<uint64_t>* packet_number) { QUICHE_DCHECK(packet_number != nullptr); packet_number->reset(); if (version != ParsedQuicVersion::RFCv1() && version != ParsedQuicVersion::Draft29()) { return QUIC_NO_ERROR; } if (packet.length() == 0 || format != IETF_QUIC_LONG_HEADER_PACKET || !VersionHasIetfQuicFrames(version.transport_version) || long_packet_type != INITIAL) { return QUIC_NO_ERROR; } QuicPacketHeader header; header.destination_connection_id = destination_connection_id; header.destination_connection_id_included = destination_connection_id.IsEmpty() ? CONNECTION_ID_ABSENT : CONNECTION_ID_PRESENT; header.source_connection_id = source_connection_id; header.source_connection_id_included = source_connection_id.IsEmpty() ? CONNECTION_ID_ABSENT : CONNECTION_ID_PRESENT; header.reset_flag = false; header.version_flag = true; header.has_possible_stateless_reset_token = false; header.type_byte = packet.data()[0]; header.version = version; header.form = IETF_QUIC_LONG_HEADER_PACKET; header.long_packet_type = INITIAL; header.nonce = nullptr; header.retry_token = retry_token.value_or(absl::string_view()); header.retry_token_length_length = QuicDataWriter::GetVarInt62Len(header.retry_token.length()); header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0; header.packet_number_length = PACKET_1BYTE_PACKET_NUMBER; size_t remaining_packet_length_offset = GetStartOfEncryptedData(version.transport_version, header) - header.packet_number_length; if (packet.length() <= remaining_packet_length_offset) { return QUIC_INVALID_PACKET_HEADER; } QuicDataReader reader(packet.data() + remaining_packet_length_offset, packet.length() - remaining_packet_length_offset); if (!reader.ReadVarInt62(&header.remaining_packet_length) || !reader.TruncateRemaining(header.remaining_packet_length)) { return QUIC_INVALID_PACKET_HEADER; } header.length_length = QuicDataWriter::GetVarInt62Len(header.remaining_packet_length); AssociatedDataStorage associated_data; uint64_t full_packet_number; if (!RemoveHeaderProtection(&reader, packet, decrypter, Perspective::IS_SERVER, version, largest_decrypted_inital_packet_number, &header, &full_packet_number, associated_data)) { return QUIC_INVALID_PACKET_HEADER; } ABSL_CACHELINE_ALIGNED char stack_buffer[kMaxIncomingPacketSize]; std::unique_ptr<char[]> heap_buffer; char* decrypted_buffer; size_t decrypted_buffer_length; if (packet.length() <= kMaxIncomingPacketSize) { decrypted_buffer = stack_buffer; decrypted_buffer_length = kMaxIncomingPacketSize; } else { heap_buffer = std::make_unique<char[]>(packet.length()); decrypted_buffer = heap_buffer.get(); decrypted_buffer_length = packet.length(); } size_t decrypted_length = 0; if (!decrypter.DecryptPacket( full_packet_number, absl::string_view(associated_data.data(), associated_data.size()), reader.ReadRemainingPayload(), decrypted_buffer, &decrypted_length, decrypted_buffer_length)) { return QUIC_DECRYPTION_FAILURE; } (*packet_number) = full_packet_number; return QUIC_NO_ERROR; } QuicErrorCode QuicFramer::ParsePublicHeaderGoogleQuic( QuicDataReader* reader, uint8_t* first_byte, PacketHeaderFormat* format, bool* version_present, QuicVersionLabel* version_label, ParsedQuicVersion* parsed_version, QuicConnectionId* destination_connection_id, std::string* detailed_error) { *format = GOOGLE_QUIC_PACKET; *version_present = (*first_byte & PACKET_PUBLIC_FLAGS_VERSION) != 0; uint8_t destination_connection_id_length = 0; if ((*first_byte & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) != 0) { destination_connection_id_length = kQuicDefaultConnectionIdLength; } if (!reader->ReadConnectionId(destination_connection_id, destination_connection_id_length)) { *detailed_error = "Unable to read ConnectionId."; return QUIC_INVALID_PACKET_HEADER; } if (*version_present) { if (!ProcessVersionLabel(reader, version_label)) { *detailed_error = "Unable to read protocol version."; return QUIC_INVALID_PACKET_HEADER; } *parsed_version = ParseQuicVersionLabel(*version_label); } return QUIC_NO_ERROR; } namespace { const QuicVersionLabel kProxVersionLabel = 0x50524F58; inline bool PacketHasLengthPrefixedConnectionIds( const QuicDataReader& reader, ParsedQuicVersion parsed_version, QuicVersionLabel version_label, uint8_t first_byte) { if (parsed_version.IsKnown()) { return parsed_version.HasLengthPrefixedConnectionIds(); } if (QuicVersionLabelUses4BitConnectionIdLength(version_label)) { return false; } if (reader.IsDoneReading()) { return true; } const uint8_t connection_id_length_byte = reader.PeekByte(); if (first_byte == 0xc0 && (connection_id_length_byte & 0x0f) == 0 && connection_id_length_byte >= 0x50 && version_label == 0xcabadaba) { return false; } if ((connection_id_length_byte & 0x0f) == 0 && connection_id_length_byte >= 0x20 && version_label == kProxVersionLabel) { return false; } return true; } inline bool ParseLongHeaderConnectionIds( QuicDataReader& reader, bool has_length_prefix, QuicVersionLabel version_label, QuicConnectionId& destination_connection_id, QuicConnectionId& source_connection_id, std::string& detailed_error) { if (has_length_prefix) { if (!reader.ReadLengthPrefixedConnectionId(&destination_connection_id)) { detailed_error = "Unable to read destination connection ID."; return false; } if (!reader.ReadLengthPrefixedConnectionId(&source_connection_id)) { if (version_label == kProxVersionLabel) { return true; } detailed_error = "Unable to read source connection ID."; return false; } } else { uint8_t connection_id_lengths_byte; if (!reader.ReadUInt8(&connection_id_lengths_byte)) { detailed_error = "Unable to read connection ID lengths."; return false; } uint8_t destination_connection_id_length = (connection_id_lengths_byte & kDestinationConnectionIdLengthMask) >> 4; if (destination_connection_id_length != 0) { destination_connection_id_length += kConnectionIdLengthAdjustment; } uint8_t source_connection_id_length = connection_id_lengths_byte & kSourceConnectionIdLengthMask; if (source_connection_id_length != 0) { source_connection_id_length += kConnectionIdLengthAdjustment; } if (!reader.ReadConnectionId(&destination_connection_id, destination_connection_id_length)) { detailed_error = "Unable to read destination connection ID."; return false; } if (!reader.ReadConnectionId(&source_connection_id, source_connection_id_length)) { detailed_error = "Unable to read source connection ID."; return false; } } return true; } } QuicErrorCode QuicFramer::ParsePublicHeader( QuicDataReader* reader, uint8_t expected_destination_connection_id_length, bool ietf_format, uint8_t* first_byte, PacketHeaderFormat* format, bool* version_present, bool* has_length_prefix, QuicVersionLabel* version_label, ParsedQuicVersion* parsed_version, QuicConnectionId* destination_connection_id, QuicConnectionId* source_connection_id, QuicLongHeaderType* long_packet_type, quiche::QuicheVariableLengthIntegerLength* retry_token_length_length, absl::string_view* retry_token, std::string* detailed_error) { *version_present = false; *has_length_prefix = false; *version_label = 0; *parsed_version = UnsupportedQuicVersion(); *source_connection_id = EmptyQuicConnectionId(); *long_packet_type = INVALID_PACKET_TYPE; *retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0; *retry_token = absl::string_view(); *detailed_error = ""; if (!reader->ReadUInt8(first_byte)) { *detailed_error = "Unable to read first byte."; return QUIC_INVALID_PACKET_HEADER; } if (!ietf_format) { return ParsePublicHeaderGoogleQuic( reader, first_byte, format, version_present, version_label, parsed_version, destination_connection_id, detailed_error); } *format = GetIetfPacketHeaderFormat(*first_byte); if (*format == IETF_QUIC_SHORT_HEADER_PACKET) { if (!reader->ReadConnectionId(destination_connection_id, expected_destination_connection_id_length)) { *detailed_error = "Unable to read destination connection ID."; return QUIC_INVALID_PACKET_HEADER; } return QUIC_NO_ERROR; } QUICHE_DCHECK_EQ(IETF_QUIC_LONG_HEADER_PACKET, *format); *version_present = true; if (!ProcessVersionLabel(reader, version_label)) { *detailed_error = "Unable to read protocol version."; return QUIC_INVALID_PACKET_HEADER; } if (*version_label == 0) { *long_packet_type = VERSION_NEGOTIATION; } *parsed_version = ParseQuicVersionLabel(*version_label); *has_length_prefix = PacketHasLengthPrefixedConnectionIds( *reader, *parsed_version, *version_label, *first_byte); if (!ParseLongHeaderConnectionIds(*reader, *has_length_prefix, *version_label, *destination_connection_id, *source_connection_id, *detailed_error)) { return QUIC_INVALID_PACKET_HEADER; } if (!parsed_version->IsKnown()) { return QUIC_NO_ERROR; } *long_packet_type = GetLongHeaderType(*first_byte, *parsed_version); switch (*long_packet_type) { case INVALID_PACKET_TYPE: *detailed_error = "Unable to parse long packet type."; return QUIC_INVALID_PACKET_HEADER; case INITIAL: if (!parsed_version->SupportsRetry()) { return QUIC_NO_ERROR; } break; default: return QUIC_NO_ERROR; } *retry_token_length_length = reader->PeekVarInt62Length(); uint64_t retry_token_length; if (!reader->ReadVarInt62(&retry_token_length)) { *retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0; *detailed_error = "Unable to read retry token length."; return QUIC_INVALID_PACKET_HEADER; } if (!reader->ReadStringPiece(retry_token, retry_token_length)) { *detailed_error = "Unable to read retry token."; return QUIC_INVALID_PACKET_HEADER; } return QUIC_NO_ERROR; } bool QuicFramer::WriteClientVersionNegotiationProbePacket( char* packet_bytes, QuicByteCount packet_length, const char* destination_connection_id_bytes, uint8_t destination_connection_id_length) { if (packet_bytes == nullptr) { QUIC_BUG(quic_bug_10850_93) << "Invalid packet_bytes"; return false; } if (packet_length < kMinPacketSizeForVersionNegotiation || packet_length > 65535) { QUIC_BUG(quic_bug_10850_94) << "Invalid packet_length"; return false; } if (destination_connection_id_length > kQuicMaxConnectionId4BitLength || destination_connection_id_length < kQuicDefaultConnectionIdLength) { QUIC_BUG(quic_bug_10850_95) << "Invalid connection_id_length"; return false; } const unsigned char packet_start_bytes[] = { 0xc0, 0xca, 0xba, 0xda, 0xda, }; static_assert(sizeof(packet_start_bytes) == 5, "bad packet_start_bytes size"); QuicDataWriter writer(packet_length, packet_bytes); if (!writer.WriteBytes(packet_start_bytes, sizeof(packet_start_bytes))) { QUIC_BUG(quic_bug_10850_96) << "Failed to write packet start"; return false; } QuicConnectionId destination_connection_id(destination_connection_id_bytes, destination_connection_id_length); if (!AppendIetfConnectionIds( true, true, destination_connection_id, EmptyQuicConnectionId(), &writer)) { QUIC_BUG(quic_bug_10850_97) << "Failed to write connection IDs"; return false; } if (!writer.WriteUInt64(0) || !writer.WriteUInt64(std::numeric_limits<uint64_t>::max())) { QUIC_BUG(quic_bug_10850_98) << "Failed to write 18 bytes"; return false; } while (writer.length() % 16 != 0) { if (!writer.WriteUInt8(0)) { QUIC_BUG(quic_bug_10850_99) << "Failed to write padding byte"; return false; } } static const char polite_greeting[] = "This packet only exists to trigger IETF QUIC version negotiation. " "Please respond with a Version Negotiation packet indicating what " "versions you support. Thank you and have a nice day."; if (!writer.WriteBytes(polite_greeting, sizeof(polite_greeting))) { QUIC_BUG(quic_bug_10850_100) << "Failed to write polite greeting"; return false; } writer.WritePadding(); QUICHE_DCHECK_EQ(0u, writer.remaining()); return true; } bool QuicFramer::ParseServerVersionNegotiationProbeResponse( const char* packet_bytes, QuicByteCount packet_length, char* source_connection_id_bytes, uint8_t* source_connection_id_length_out, std::string* detailed_error) { if (detailed_error == nullptr) { QUIC_BUG(quic_bug_10850_101) << "Invalid error_details"; return false; } *detailed_error = ""; if (packet_bytes == nullptr) { *detailed_error = "Invalid packet_bytes"; return false; } if (packet_length < 6) { *detailed_error = "Invalid packet_length"; return false; } if (source_connection_id_bytes == nullptr) { *detailed_error = "Invalid source_connection_id_bytes"; return false; } if (source_connection_id_length_out == nullptr) { *detailed_error = "Invalid source_connection_id_length_out"; return false; } QuicDataReader reader(packet_bytes, packet_length); uint8_t type_byte = 0; if (!reader.ReadUInt8(&type_byte)) { *detailed_error = "Failed to read type byte"; return false; } if ((type_byte & 0x80) == 0) { *detailed_error = "Packet does not have long header"; return false; } uint32_t version = 0; if (!reader.ReadUInt32(&version)) { *detailed_error = "Failed to read version"; return false; } if (version != 0) { *detailed_error = "Packet is not a version negotiation packet"; return false; } QuicConnectionId destination_connection_id, source_connection_id; if (!reader.ReadLengthPrefixedConnectionId(&destination_connection_id)) { *detailed_error = "Failed to read destination connection ID"; return false; } if (!reader.ReadLengthPrefixedConnectionId(&source_connection_id)) { *detailed_error = "Failed to read source connection ID"; return false; } if (destination_connection_id.length() != 0) { *detailed_error = "Received unexpected destination connection ID length"; return false; } if (*source_connection_id_length_out < source_connection_id.length()) { *detailed_error = absl::StrCat("*source_connection_id_length_out too small ", static_cast<int>(*source_connection_id_length_out), " < ", static_cast<int>(source_connection_id.length())); return false; } memcpy(source_connection_id_bytes, source_connection_id.data(), source_connection_id.length()); *source_connection_id_length_out = source_connection_id.length(); return true; } void MaybeExtractQuicErrorCode(QuicConnectionCloseFrame* frame) { std::vector<absl::string_view> ed = absl::StrSplit(frame->error_details, ':'); uint64_t extracted_error_code; if (ed.size() < 2 || !quiche::QuicheTextUtils::IsAllDigits(ed[0]) || !absl::SimpleAtoi(ed[0], &extracted_error_code) || extracted_error_code > std::numeric_limits< std::underlying_type<QuicErrorCode>::type>::max()) { if (frame->close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE && frame->wire_error_code == NO_IETF_QUIC_ERROR) { frame->quic_error_code = QUIC_NO_ERROR; } else { frame->quic_error_code = QUIC_IETF_GQUIC_ERROR_MISSING; } return; } absl::string_view x = absl::string_view(frame->error_details); x.remove_prefix(ed[0].length() + 1); frame->error_details = std::string(x); frame->quic_error_code = static_cast<QuicErrorCode>(extracted_error_code); } #undef ENDPOINT }
#include "quiche/quic/core/quic_framer.h" #include <algorithm> #include <cstdint> #include <cstring> #include <limits> #include <map> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/memory/memory.h" #include "absl/strings/escaping.h" #include "absl/strings/match.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/crypto/quic_decrypter.h" #include "quiche/quic/core/crypto/quic_encrypter.h" #include "quiche/quic/core/frames/quic_reset_stream_at_frame.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_error_codes.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/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_ip_address.h" #include "quiche/quic/platform/api/quic_ip_address_family.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_framer_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simple_data_producer.h" #include "quiche/common/test_tools/quiche_test_utils.h" using testing::_; using testing::ContainerEq; using testing::Optional; using testing::Return; namespace quic { namespace test { namespace { const uint64_t kEpoch = UINT64_C(1) << 32; const uint64_t kMask = kEpoch - 1; const uint8_t kPacket0ByteConnectionId = 0; const uint8_t kPacket8ByteConnectionId = 8; constexpr size_t kTagSize = 16; const StatelessResetToken kTestStatelessResetToken{ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f}; QuicConnectionId FramerTestConnectionId() { return TestConnectionId(UINT64_C(0xFEDCBA9876543210)); } QuicConnectionId FramerTestConnectionIdPlusOne() { return TestConnectionId(UINT64_C(0xFEDCBA9876543211)); } QuicConnectionId FramerTestConnectionIdNineBytes() { uint8_t connection_id_bytes[9] = {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x42}; return QuicConnectionId(reinterpret_cast<char*>(connection_id_bytes), sizeof(connection_id_bytes)); } const QuicPacketNumber kPacketNumber = QuicPacketNumber(UINT64_C(0x12345678)); const QuicPacketNumber kSmallLargestObserved = QuicPacketNumber(UINT16_C(0x1234)); const QuicPacketNumber kSmallMissingPacket = QuicPacketNumber(UINT16_C(0x1233)); const QuicPacketNumber kLeastUnacked = QuicPacketNumber(UINT64_C(0x012345670)); const QuicStreamId kStreamId = UINT64_C(0x01020304); const QuicStreamOffset kStreamOffset = UINT64_C(0x3A98FEDC32107654); const QuicPublicResetNonceProof kNonceProof = UINT64_C(0xABCDEF0123456789); const QuicPacketNumber kLargestIetfLargestObserved = QuicPacketNumber(UINT64_C(0x3fffffffffffffff)); const uint8_t kVarInt62OneByte = 0x00; const uint8_t kVarInt62TwoBytes = 0x40; const uint8_t kVarInt62FourBytes = 0x80; const uint8_t kVarInt62EightBytes = 0xc0; class TestEncrypter : public QuicEncrypter { public: ~TestEncrypter() override {} bool SetKey(absl::string_view ) override { return true; } bool SetNoncePrefix(absl::string_view ) override { return true; } bool SetIV(absl::string_view ) override { return true; } bool SetHeaderProtectionKey(absl::string_view ) override { return true; } bool EncryptPacket(uint64_t packet_number, absl::string_view associated_data, absl::string_view plaintext, char* output, size_t* output_length, size_t ) override { packet_number_ = QuicPacketNumber(packet_number); associated_data_ = std::string(associated_data); plaintext_ = std::string(plaintext); memcpy(output, plaintext.data(), plaintext.length()); *output_length = plaintext.length(); return true; } std::string GenerateHeaderProtectionMask( absl::string_view ) override { return std::string(5, 0); } size_t GetKeySize() const override { return 0; } size_t GetNoncePrefixSize() const override { return 0; } size_t GetIVSize() const override { return 0; } size_t GetMaxPlaintextSize(size_t ciphertext_size) const override { return ciphertext_size; } size_t GetCiphertextSize(size_t plaintext_size) const override { return plaintext_size; } QuicPacketCount GetConfidentialityLimit() const override { return std::numeric_limits<QuicPacketCount>::max(); } absl::string_view GetKey() const override { return absl::string_view(); } absl::string_view GetNoncePrefix() const override { return absl::string_view(); } QuicPacketNumber packet_number_; std::string associated_data_; std::string plaintext_; }; class TestDecrypter : public QuicDecrypter { public: ~TestDecrypter() override {} bool SetKey(absl::string_view ) override { return true; } bool SetNoncePrefix(absl::string_view ) override { return true; } bool SetIV(absl::string_view ) override { return true; } bool SetHeaderProtectionKey(absl::string_view ) override { return true; } bool SetPreliminaryKey(absl::string_view ) override { QUIC_BUG(quic_bug_10486_1) << "should not be called"; return false; } bool SetDiversificationNonce(const DiversificationNonce& ) override { return true; } bool DecryptPacket(uint64_t packet_number, absl::string_view associated_data, absl::string_view ciphertext, char* output, size_t* output_length, size_t ) override { packet_number_ = QuicPacketNumber(packet_number); associated_data_ = std::string(associated_data); ciphertext_ = std::string(ciphertext); memcpy(output, ciphertext.data(), ciphertext.length()); *output_length = ciphertext.length(); return true; } std::string GenerateHeaderProtectionMask( QuicDataReader* ) override { return std::string(5, 0); } size_t GetKeySize() const override { return 0; } size_t GetNoncePrefixSize() const override { return 0; } size_t GetIVSize() const override { return 0; } absl::string_view GetKey() const override { return absl::string_view(); } absl::string_view GetNoncePrefix() const override { return absl::string_view(); } uint32_t cipher_id() const override { return 0xFFFFFFF2; } QuicPacketCount GetIntegrityLimit() const override { return std::numeric_limits<QuicPacketCount>::max(); } QuicPacketNumber packet_number_; std::string associated_data_; std::string ciphertext_; }; std::unique_ptr<QuicEncryptedPacket> EncryptPacketWithTagAndPhase( const QuicPacket& packet, uint8_t tag, bool phase) { std::string packet_data = std::string(packet.AsStringPiece()); if (phase) { packet_data[0] |= FLAGS_KEY_PHASE_BIT; } else { packet_data[0] &= ~FLAGS_KEY_PHASE_BIT; } TaggingEncrypter crypter(tag); const size_t packet_size = crypter.GetCiphertextSize(packet_data.size()); char* buffer = new char[packet_size]; size_t buf_len = 0; if (!crypter.EncryptPacket(0, absl::string_view(), packet_data, buffer, &buf_len, packet_size)) { delete[] buffer; return nullptr; } return std::make_unique<QuicEncryptedPacket>(buffer, buf_len, true); } class TestQuicVisitor : public QuicFramerVisitorInterface { public: TestQuicVisitor() : error_count_(0), version_mismatch_(0), packet_count_(0), frame_count_(0), complete_packets_(0), derive_next_key_count_(0), decrypted_first_packet_in_key_phase_count_(0), accept_packet_(true), accept_public_header_(true) {} ~TestQuicVisitor() override {} void OnError(QuicFramer* f) override { QUIC_DLOG(INFO) << "QuicFramer Error: " << QuicErrorCodeToString(f->error()) << " (" << f->error() << ")"; ++error_count_; } void OnPacket() override {} void OnVersionNegotiationPacket( const QuicVersionNegotiationPacket& packet) override { version_negotiation_packet_ = std::make_unique<QuicVersionNegotiationPacket>((packet)); EXPECT_EQ(0u, framer_->current_received_frame_type()); } void OnRetryPacket(QuicConnectionId original_connection_id, QuicConnectionId new_connection_id, absl::string_view retry_token, absl::string_view retry_integrity_tag, absl::string_view retry_without_tag) override { on_retry_packet_called_ = true; retry_original_connection_id_ = std::make_unique<QuicConnectionId>(original_connection_id); retry_new_connection_id_ = std::make_unique<QuicConnectionId>(new_connection_id); retry_token_ = std::make_unique<std::string>(std::string(retry_token)); retry_token_integrity_tag_ = std::make_unique<std::string>(std::string(retry_integrity_tag)); retry_without_tag_ = std::make_unique<std::string>(std::string(retry_without_tag)); EXPECT_EQ(0u, framer_->current_received_frame_type()); } bool OnProtocolVersionMismatch(ParsedQuicVersion received_version) override { QUIC_DLOG(INFO) << "QuicFramer Version Mismatch, version: " << received_version; ++version_mismatch_; EXPECT_EQ(0u, framer_->current_received_frame_type()); return false; } bool OnUnauthenticatedPublicHeader(const QuicPacketHeader& header) override { header_ = std::make_unique<QuicPacketHeader>((header)); EXPECT_EQ(0u, framer_->current_received_frame_type()); return accept_public_header_; } bool OnUnauthenticatedHeader(const QuicPacketHeader& ) override { EXPECT_EQ(0u, framer_->current_received_frame_type()); return true; } void OnDecryptedPacket(size_t , EncryptionLevel ) override { EXPECT_EQ(0u, framer_->current_received_frame_type()); } bool OnPacketHeader(const QuicPacketHeader& header) override { ++packet_count_; header_ = std::make_unique<QuicPacketHeader>((header)); EXPECT_EQ(0u, framer_->current_received_frame_type()); return accept_packet_; } void OnCoalescedPacket(const QuicEncryptedPacket& packet) override { coalesced_packets_.push_back(packet.Clone()); } void OnUndecryptablePacket(const QuicEncryptedPacket& packet, EncryptionLevel decryption_level, bool has_decryption_key) override { undecryptable_packets_.push_back(packet.Clone()); undecryptable_decryption_levels_.push_back(decryption_level); undecryptable_has_decryption_keys_.push_back(has_decryption_key); } bool OnStreamFrame(const QuicStreamFrame& frame) override { ++frame_count_; std::string* string_data = new std::string(frame.data_buffer, frame.data_length); stream_data_.push_back(absl::WrapUnique(string_data)); stream_frames_.push_back(std::make_unique<QuicStreamFrame>( frame.stream_id, frame.fin, frame.offset, *string_data)); if (VersionHasIetfQuicFrames(transport_version_)) { EXPECT_TRUE(IS_IETF_STREAM_FRAME(framer_->current_received_frame_type())); } else { EXPECT_EQ(0u, framer_->current_received_frame_type()); } return true; } bool OnCryptoFrame(const QuicCryptoFrame& frame) override { ++frame_count_; std::string* string_data = new std::string(frame.data_buffer, frame.data_length); crypto_data_.push_back(absl::WrapUnique(string_data)); crypto_frames_.push_back(std::make_unique<QuicCryptoFrame>( frame.level, frame.offset, *string_data)); if (VersionHasIetfQuicFrames(transport_version_)) { EXPECT_EQ(IETF_CRYPTO, framer_->current_received_frame_type()); } else { EXPECT_EQ(0u, framer_->current_received_frame_type()); } return true; } bool OnAckFrameStart(QuicPacketNumber largest_acked, QuicTime::Delta ack_delay_time) override { ++frame_count_; QuicAckFrame ack_frame; ack_frame.largest_acked = largest_acked; ack_frame.ack_delay_time = ack_delay_time; ack_frames_.push_back(std::make_unique<QuicAckFrame>(ack_frame)); if (VersionHasIetfQuicFrames(transport_version_)) { EXPECT_TRUE(IETF_ACK == framer_->current_received_frame_type() || IETF_ACK_ECN == framer_->current_received_frame_type() || IETF_ACK_RECEIVE_TIMESTAMPS == framer_->current_received_frame_type()); } else { EXPECT_EQ(0u, framer_->current_received_frame_type()); } return true; } bool OnAckRange(QuicPacketNumber start, QuicPacketNumber end) override { QUICHE_DCHECK(!ack_frames_.empty()); ack_frames_[ack_frames_.size() - 1]->packets.AddRange(start, end); if (VersionHasIetfQuicFrames(transport_version_)) { EXPECT_TRUE(IETF_ACK == framer_->current_received_frame_type() || IETF_ACK_ECN == framer_->current_received_frame_type() || IETF_ACK_RECEIVE_TIMESTAMPS == framer_->current_received_frame_type()); } else { EXPECT_EQ(0u, framer_->current_received_frame_type()); } return true; } bool OnAckTimestamp(QuicPacketNumber packet_number, QuicTime timestamp) override { ack_frames_[ack_frames_.size() - 1]->received_packet_times.push_back( std::make_pair(packet_number, timestamp)); if (VersionHasIetfQuicFrames(transport_version_)) { EXPECT_TRUE(IETF_ACK == framer_->current_received_frame_type() || IETF_ACK_ECN == framer_->current_received_frame_type() || IETF_ACK_RECEIVE_TIMESTAMPS == framer_->current_received_frame_type()); } else { EXPECT_EQ(0u, framer_->current_received_frame_type()); } return true; } bool OnAckFrameEnd( QuicPacketNumber , const std::optional<QuicEcnCounts>& ) override { return true; } bool OnStopWaitingFrame(const QuicStopWaitingFrame& frame) override { ++frame_count_; stop_waiting_frames_.push_back( std::make_unique<QuicStopWaitingFrame>(frame)); EXPECT_EQ(0u, framer_->current_received_frame_type()); return true; } bool OnPaddingFrame(const QuicPaddingFrame& frame) override { padding_frames_.push_back(std::make_unique<QuicPaddingFrame>(frame)); if (VersionHasIetfQuicFrames(transport_version_)) { EXPECT_EQ(IETF_PADDING, framer_->current_received_frame_type()); } else { EXPECT_EQ(0u, framer_->current_received_frame_type()); } return true; } bool OnPingFrame(const QuicPingFrame& frame) override { ++frame_count_; ping_frames_.push_back(std::make_unique<QuicPingFrame>(frame)); if (VersionHasIetfQuicFrames(transport_version_)) { EXPECT_EQ(IETF_PING, framer_->current_received_frame_type()); } else { EXPECT_EQ(0u, framer_->current_received_frame_type()); } return true; } bool OnMessageFrame(const QuicMessageFrame& frame) override { ++frame_count_; message_frames_.push_back( std::make_unique<QuicMessageFrame>(frame.data, frame.message_length)); if (VersionHasIetfQuicFrames(transport_version_)) { EXPECT_TRUE(IETF_EXTENSION_MESSAGE_NO_LENGTH_V99 == framer_->current_received_frame_type() || IETF_EXTENSION_MESSAGE_V99 == framer_->current_received_frame_type()); } else { EXPECT_EQ(0u, framer_->current_received_frame_type()); } return true; } bool OnHandshakeDoneFrame(const QuicHandshakeDoneFrame& frame) override { ++frame_count_; handshake_done_frames_.push_back( std::make_unique<QuicHandshakeDoneFrame>(frame)); QUICHE_DCHECK(VersionHasIetfQuicFrames(transport_version_)); EXPECT_EQ(IETF_HANDSHAKE_DONE, framer_->current_received_frame_type()); return true; } bool OnAckFrequencyFrame(const QuicAckFrequencyFrame& frame) override { ++frame_count_; ack_frequency_frames_.emplace_back( std::make_unique<QuicAckFrequencyFrame>(frame)); QUICHE_DCHECK(VersionHasIetfQuicFrames(transport_version_)); EXPECT_EQ(IETF_ACK_FREQUENCY, framer_->current_received_frame_type()); return true; } bool OnResetStreamAtFrame(const QuicResetStreamAtFrame& frame) override { ++frame_count_; reset_stream_at_frames_.push_back( std::make_unique<QuicResetStreamAtFrame>(frame)); EXPECT_TRUE(VersionHasIetfQuicFrames(transport_version_)); EXPECT_EQ(IETF_RESET_STREAM_AT, framer_->current_received_frame_type()); return true; } void OnPacketComplete() override { ++complete_packets_; } bool OnRstStreamFrame(const QuicRstStreamFrame& frame) override { rst_stream_frame_ = frame; if (VersionHasIetfQuicFrames(transport_version_)) { EXPECT_EQ(IETF_RST_STREAM, framer_->current_received_frame_type()); } else { EXPECT_EQ(0u, framer_->current_received_frame_type()); } return true; } bool OnConnectionCloseFrame(const QuicConnectionCloseFrame& frame) override { connection_close_frame_ = frame; if (VersionHasIetfQuicFrames(transport_version_)) { EXPECT_NE(GOOGLE_QUIC_CONNECTION_CLOSE, frame.close_type); if (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) { EXPECT_EQ(IETF_CONNECTION_CLOSE, framer_->current_received_frame_type()); } else { EXPECT_EQ(IETF_APPLICATION_CLOSE, framer_->current_received_frame_type()); } } else { EXPECT_EQ(0u, framer_->current_received_frame_type()); } return true; } bool OnStopSendingFrame(const QuicStopSendingFrame& frame) override { stop_sending_frame_ = frame; EXPECT_EQ(IETF_STOP_SENDING, framer_->current_received_frame_type()); EXPECT_TRUE(VersionHasIetfQuicFrames(transport_version_)); return true; } bool OnPathChallengeFrame(const QuicPathChallengeFrame& frame) override { path_challenge_frame_ = frame; EXPECT_EQ(IETF_PATH_CHALLENGE, framer_->current_received_frame_type()); EXPECT_TRUE(VersionHasIetfQuicFrames(transport_version_)); return true; } bool OnPathResponseFrame(const QuicPathResponseFrame& frame) override { path_response_frame_ = frame; EXPECT_EQ(IETF_PATH_RESPONSE, framer_->current_received_frame_type()); EXPECT_TRUE(VersionHasIetfQuicFrames(transport_version_)); return true; } bool OnGoAwayFrame(const QuicGoAwayFrame& frame) override { goaway_frame_ = frame; EXPECT_FALSE(VersionHasIetfQuicFrames(transport_version_)); EXPECT_EQ(0u, framer_->current_received_frame_type()); return true; } bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) override { max_streams_frame_ = frame; EXPECT_TRUE(VersionHasIetfQuicFrames(transport_version_)); EXPECT_TRUE(IETF_MAX_STREAMS_UNIDIRECTIONAL == framer_->current_received_frame_type() || IETF_MAX_STREAMS_BIDIRECTIONAL == framer_->current_received_frame_type()); return true; } bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) override { streams_blocked_frame_ = frame; EXPECT_TRUE(VersionHasIetfQuicFrames(transport_version_)); EXPECT_TRUE(IETF_STREAMS_BLOCKED_UNIDIRECTIONAL == framer_->current_received_frame_type() || IETF_STREAMS_BLOCKED_BIDIRECTIONAL == framer_->current_received_frame_type()); return true; } bool OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) override { window_update_frame_ = frame; if (VersionHasIetfQuicFrames(transport_version_)) { EXPECT_TRUE(IETF_MAX_DATA == framer_->current_received_frame_type() || IETF_MAX_STREAM_DATA == framer_->current_received_frame_type()); } else { EXPECT_EQ(0u, framer_->current_received_frame_type()); } return true; } bool OnBlockedFrame(const QuicBlockedFrame& frame) override { blocked_frame_ = frame; if (VersionHasIetfQuicFrames(transport_version_)) { EXPECT_TRUE(IETF_DATA_BLOCKED == framer_->current_received_frame_type() || IETF_STREAM_DATA_BLOCKED == framer_->current_received_frame_type()); } else { EXPECT_EQ(0u, framer_->current_received_frame_type()); } return true; } bool OnNewConnectionIdFrame(const QuicNewConnectionIdFrame& frame) override { new_connection_id_ = frame; EXPECT_EQ(IETF_NEW_CONNECTION_ID, framer_->current_received_frame_type()); EXPECT_TRUE(VersionHasIetfQuicFrames(transport_version_)); return true; } bool OnRetireConnectionIdFrame( const QuicRetireConnectionIdFrame& frame) override { EXPECT_EQ(IETF_RETIRE_CONNECTION_ID, framer_->current_received_frame_type()); EXPECT_TRUE(VersionHasIetfQuicFrames(transport_version_)); retire_connection_id_ = frame; return true; } bool OnNewTokenFrame(const QuicNewTokenFrame& frame) override { new_token_ = frame; EXPECT_EQ(IETF_NEW_TOKEN, framer_->current_received_frame_type()); EXPECT_TRUE(VersionHasIetfQuicFrames(transport_version_)); return true; } bool IsValidStatelessResetToken( const StatelessResetToken& token) const override { EXPECT_EQ(0u, framer_->current_received_frame_type()); return token == kTestStatelessResetToken; } void OnAuthenticatedIetfStatelessResetPacket( const QuicIetfStatelessResetPacket& packet) override { stateless_reset_packet_ = std::make_unique<QuicIetfStatelessResetPacket>(packet); EXPECT_EQ(0u, framer_->current_received_frame_type()); } void OnKeyUpdate(KeyUpdateReason reason) override { key_update_reasons_.push_back(reason); } void OnDecryptedFirstPacketInKeyPhase() override { decrypted_first_packet_in_key_phase_count_++; } std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter() override { derive_next_key_count_++; return std::make_unique<StrictTaggingDecrypter>(derive_next_key_count_); } std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override { return std::make_unique<TaggingEncrypter>(derive_next_key_count_); } void set_framer(QuicFramer* framer) { framer_ = framer; transport_version_ = framer->transport_version(); } size_t key_update_count() const { return key_update_reasons_.size(); } int error_count_; int version_mismatch_; int packet_count_; int frame_count_; int complete_packets_; std::vector<KeyUpdateReason> key_update_reasons_; int derive_next_key_count_; int decrypted_first_packet_in_key_phase_count_; bool accept_packet_; bool accept_public_header_; std::unique_ptr<QuicPacketHeader> header_; std::unique_ptr<QuicIetfStatelessResetPacket> stateless_reset_packet_; std::unique_ptr<QuicVersionNegotiationPacket> version_negotiation_packet_; std::unique_ptr<QuicConnectionId> retry_original_connection_id_; std::unique_ptr<QuicConnectionId> retry_new_connection_id_; std::unique_ptr<std::string> retry_token_; std::unique_ptr<std::string> retry_token_integrity_tag_; std::unique_ptr<std::string> retry_without_tag_; bool on_retry_packet_called_ = false; std::vector<std::unique_ptr<QuicStreamFrame>> stream_frames_; std::vector<std::unique_ptr<QuicCryptoFrame>> crypto_frames_; std::vector<std::unique_ptr<QuicAckFrame>> ack_frames_; std::vector<std::unique_ptr<QuicStopWaitingFrame>> stop_waiting_frames_; std::vector<std::unique_ptr<QuicPaddingFrame>> padding_frames_; std::vector<std::unique_ptr<QuicPingFrame>> ping_frames_; std::vector<std::unique_ptr<QuicMessageFrame>> message_frames_; std::vector<std::unique_ptr<QuicHandshakeDoneFrame>> handshake_done_frames_; std::vector<std::unique_ptr<QuicAckFrequencyFrame>> ack_frequency_frames_; std::vector<std::unique_ptr<QuicResetStreamAtFrame>> reset_stream_at_frames_; std::vector<std::unique_ptr<QuicEncryptedPacket>> coalesced_packets_; std::vector<std::unique_ptr<QuicEncryptedPacket>> undecryptable_packets_; std::vector<EncryptionLevel> undecryptable_decryption_levels_; std::vector<bool> undecryptable_has_decryption_keys_; QuicRstStreamFrame rst_stream_frame_; QuicConnectionCloseFrame connection_close_frame_; QuicStopSendingFrame stop_sending_frame_; QuicGoAwayFrame goaway_frame_; QuicPathChallengeFrame path_challenge_frame_; QuicPathResponseFrame path_response_frame_; QuicWindowUpdateFrame window_update_frame_; QuicBlockedFrame blocked_frame_; QuicStreamsBlockedFrame streams_blocked_frame_; QuicMaxStreamsFrame max_streams_frame_; QuicNewConnectionIdFrame new_connection_id_; QuicRetireConnectionIdFrame retire_connection_id_; QuicNewTokenFrame new_token_; std::vector<std::unique_ptr<std::string>> stream_data_; std::vector<std::unique_ptr<std::string>> crypto_data_; QuicTransportVersion transport_version_; QuicFramer* framer_; }; struct PacketFragment { std::string error_if_missing; std::vector<unsigned char> fragment; }; using PacketFragments = std::vector<struct PacketFragment>; class QuicFramerTest : public QuicTestWithParam<ParsedQuicVersion> { public: QuicFramerTest() : encrypter_(new test::TestEncrypter()), decrypter_(new test::TestDecrypter()), version_(GetParam()), start_(QuicTime::Zero() + QuicTime::Delta::FromMicroseconds(0x10)), framer_(AllSupportedVersions(), start_, Perspective::IS_SERVER, kQuicDefaultConnectionIdLength) { framer_.set_version(version_); if (framer_.version().KnowsWhichDecrypterToUse()) { framer_.InstallDecrypter(ENCRYPTION_INITIAL, std::unique_ptr<QuicDecrypter>(decrypter_)); } else { framer_.SetDecrypter(ENCRYPTION_INITIAL, std::unique_ptr<QuicDecrypter>(decrypter_)); } framer_.SetEncrypter(ENCRYPTION_INITIAL, std::unique_ptr<QuicEncrypter>(encrypter_)); framer_.set_visitor(&visitor_); visitor_.set_framer(&framer_); } void SetDecrypterLevel(EncryptionLevel level) { if (!framer_.version().KnowsWhichDecrypterToUse()) { return; } decrypter_ = new TestDecrypter(); framer_.InstallDecrypter(level, std::unique_ptr<QuicDecrypter>(decrypter_)); } unsigned char GetQuicVersionByte(int pos) { return (CreateQuicVersionLabel(version_) >> 8 * (3 - pos)) & 0xff; } inline void ReviseFirstByteByVersion(unsigned char packet_ietf[]) { if (version_.UsesV2PacketTypes() && (packet_ietf[0] >= 0x80)) { packet_ietf[0] = (packet_ietf[0] + 0x10) | 0xc0; } } inline void ReviseFirstByteByVersion(PacketFragments& packet_ietf) { ReviseFirstByteByVersion(&packet_ietf[0].fragment[0]); } bool CheckEncryption(QuicPacketNumber packet_number, QuicPacket* packet) { if (packet_number != encrypter_->packet_number_) { QUIC_LOG(ERROR) << "Encrypted incorrect packet number. expected " << packet_number << " actual: " << encrypter_->packet_number_; return false; } if (packet->AssociatedData(framer_.transport_version()) != encrypter_->associated_data_) { QUIC_LOG(ERROR) << "Encrypted incorrect associated data. expected " << packet->AssociatedData(framer_.transport_version()) << " actual: " << encrypter_->associated_data_; return false; } if (packet->Plaintext(framer_.transport_version()) != encrypter_->plaintext_) { QUIC_LOG(ERROR) << "Encrypted incorrect plaintext data. expected " << packet->Plaintext(framer_.transport_version()) << " actual: " << encrypter_->plaintext_; return false; } return true; } bool CheckDecryption(const QuicEncryptedPacket& encrypted, bool includes_version, bool includes_diversification_nonce, uint8_t destination_connection_id_length, uint8_t source_connection_id_length) { return CheckDecryption( encrypted, includes_version, includes_diversification_nonce, destination_connection_id_length, source_connection_id_length, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0, 0, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0); } bool CheckDecryption( const QuicEncryptedPacket& encrypted, bool includes_version, bool includes_diversification_nonce, uint8_t destination_connection_id_length, uint8_t source_connection_id_length, quiche::QuicheVariableLengthIntegerLength retry_token_length_length, size_t retry_token_length, quiche::QuicheVariableLengthIntegerLength length_length) { if (visitor_.header_->packet_number != decrypter_->packet_number_) { QUIC_LOG(ERROR) << "Decrypted incorrect packet number. expected " << visitor_.header_->packet_number << " actual: " << decrypter_->packet_number_; return false; } absl::string_view associated_data = QuicFramer::GetAssociatedDataFromEncryptedPacket( framer_.transport_version(), encrypted, destination_connection_id_length, source_connection_id_length, includes_version, includes_diversification_nonce, PACKET_4BYTE_PACKET_NUMBER, retry_token_length_length, retry_token_length, length_length); if (associated_data != decrypter_->associated_data_) { QUIC_LOG(ERROR) << "Decrypted incorrect associated data. expected " << absl::BytesToHexString(associated_data) << " actual: " << absl::BytesToHexString(decrypter_->associated_data_); return false; } absl::string_view ciphertext( encrypted.AsStringPiece().substr(GetStartOfEncryptedData( framer_.transport_version(), destination_connection_id_length, source_connection_id_length, includes_version, includes_diversification_nonce, PACKET_4BYTE_PACKET_NUMBER, retry_token_length_length, retry_token_length, length_length))); if (ciphertext != decrypter_->ciphertext_) { QUIC_LOG(ERROR) << "Decrypted incorrect ciphertext data. expected " << absl::BytesToHexString(ciphertext) << " actual: " << absl::BytesToHexString(decrypter_->ciphertext_) << " associated data: " << absl::BytesToHexString(associated_data); return false; } return true; } char* AsChars(unsigned char* data) { return reinterpret_cast<char*>(data); } std::unique_ptr<QuicEncryptedPacket> AssemblePacketFromFragments( const PacketFragments& fragments) { char* buffer = new char[kMaxOutgoingPacketSize + 1]; size_t len = 0; for (const auto& fragment : fragments) { memcpy(buffer + len, fragment.fragment.data(), fragment.fragment.size()); len += fragment.fragment.size(); } return std::make_unique<QuicEncryptedPacket>(buffer, len, true); } void CheckFramingBoundaries(const PacketFragments& fragments, QuicErrorCode error_code) { std::unique_ptr<QuicEncryptedPacket> packet( AssemblePacketFromFragments(fragments)); for (size_t i = 0; i < packet->length(); ++i) { std::string expected_error; size_t len = 0; for (const auto& fragment : fragments) { len += fragment.fragment.size(); if (i < len) { expected_error = fragment.error_if_missing; break; } } if (expected_error.empty()) continue; CheckProcessingFails(*packet, i, expected_error, error_code); } } void CheckProcessingFails(const QuicEncryptedPacket& packet, size_t len, std::string expected_error, QuicErrorCode error_code) { QuicEncryptedPacket encrypted(packet.data(), len, false); EXPECT_FALSE(framer_.ProcessPacket(encrypted)) << "len: " << len; EXPECT_EQ(expected_error, framer_.detailed_error()) << "len: " << len; EXPECT_EQ(error_code, framer_.error()) << "len: " << len; } void CheckProcessingFails(unsigned char* packet, size_t len, std::string expected_error, QuicErrorCode error_code) { QuicEncryptedPacket encrypted(AsChars(packet), len, false); EXPECT_FALSE(framer_.ProcessPacket(encrypted)) << "len: " << len; EXPECT_EQ(expected_error, framer_.detailed_error()) << "len: " << len; EXPECT_EQ(error_code, framer_.error()) << "len: " << len; } void CheckStreamFrameData(std::string str, QuicStreamFrame* frame) { EXPECT_EQ(str, std::string(frame->data_buffer, frame->data_length)); } void CheckCalculatePacketNumber(uint64_t expected_packet_number, QuicPacketNumber last_packet_number) { uint64_t wire_packet_number = expected_packet_number & kMask; EXPECT_EQ(expected_packet_number, QuicFramerPeer::CalculatePacketNumberFromWire( &framer_, PACKET_4BYTE_PACKET_NUMBER, last_packet_number, wire_packet_number)) << "last_packet_number: " << last_packet_number << " wire_packet_number: " << wire_packet_number; } std::unique_ptr<QuicPacket> BuildDataPacket(const QuicPacketHeader& header, const QuicFrames& frames) { return BuildUnsizedDataPacket(&framer_, header, frames); } std::unique_ptr<QuicPacket> BuildDataPacket(const QuicPacketHeader& header, const QuicFrames& frames, size_t packet_size) { return BuildUnsizedDataPacket(&framer_, header, frames, packet_size); } QuicStreamId GetNthStreamid(QuicTransportVersion transport_version, Perspective perspective, bool bidirectional, int n) { if (bidirectional) { return QuicUtils::GetFirstBidirectionalStreamId(transport_version, perspective) + ((n - 1) * QuicUtils::StreamIdDelta(transport_version)); } return QuicUtils::GetFirstUnidirectionalStreamId(transport_version, perspective) + ((n - 1) * QuicUtils::StreamIdDelta(transport_version)); } QuicTime CreationTimePlus(uint64_t offset_us) { return framer_.creation_time() + QuicTime::Delta::FromMicroseconds(offset_us); } test::TestEncrypter* encrypter_; test::TestDecrypter* decrypter_; ParsedQuicVersion version_; QuicTime start_; QuicFramer framer_; test::TestQuicVisitor visitor_; quiche::SimpleBufferAllocator allocator_; }; #define QUIC_VERSION_BYTES \ GetQuicVersionByte(0), GetQuicVersionByte(1), GetQuicVersionByte(2), \ GetQuicVersionByte(3) INSTANTIATE_TEST_SUITE_P(QuicFramerTests, QuicFramerTest, ::testing::ValuesIn(AllSupportedVersions()), ::testing::PrintToStringParamName()); TEST_P(QuicFramerTest, CalculatePacketNumberFromWireNearEpochStart) { CheckCalculatePacketNumber(UINT64_C(1), QuicPacketNumber()); CheckCalculatePacketNumber(kEpoch + 1, QuicPacketNumber(kMask)); CheckCalculatePacketNumber(kEpoch, QuicPacketNumber(kMask)); for (uint64_t j = 0; j < 10; j++) { CheckCalculatePacketNumber(j, QuicPacketNumber()); CheckCalculatePacketNumber(kEpoch - 1 - j, QuicPacketNumber()); } for (QuicPacketNumber last = QuicPacketNumber(1); last < QuicPacketNumber(10); last++) { for (uint64_t j = 0; j < 10; j++) { CheckCalculatePacketNumber(j, last); } for (uint64_t j = 0; j < 10; j++) { CheckCalculatePacketNumber(kEpoch - 1 - j, last); } } } TEST_P(QuicFramerTest, CalculatePacketNumberFromWireNearEpochEnd) { for (uint64_t i = 0; i < 10; i++) { QuicPacketNumber last = QuicPacketNumber(kEpoch - i); for (uint64_t j = 0; j < 10; j++) { CheckCalculatePacketNumber(kEpoch + j, last); } for (uint64_t j = 0; j < 10; j++) { CheckCalculatePacketNumber(kEpoch - 1 - j, last); } } } TEST_P(QuicFramerTest, CalculatePacketNumberFromWireNearPrevEpoch) { const uint64_t prev_epoch = 1 * kEpoch; const uint64_t cur_epoch = 2 * kEpoch; for (uint64_t i = 0; i < 10; i++) { QuicPacketNumber last = QuicPacketNumber(cur_epoch + i); for (uint64_t j = 0; j < 10; j++) { CheckCalculatePacketNumber(cur_epoch + j, last); } for (uint64_t j = 0; j < 10; j++) { uint64_t num = kEpoch - 1 - j; CheckCalculatePacketNumber(prev_epoch + num, last); } } } TEST_P(QuicFramerTest, CalculatePacketNumberFromWireNearNextEpoch) { const uint64_t cur_epoch = 2 * kEpoch; const uint64_t next_epoch = 3 * kEpoch; for (uint64_t i = 0; i < 10; i++) { QuicPacketNumber last = QuicPacketNumber(next_epoch - 1 - i); for (uint64_t j = 0; j < 10; j++) { CheckCalculatePacketNumber(next_epoch + j, last); } for (uint64_t j = 0; j < 10; j++) { uint64_t num = kEpoch - 1 - j; CheckCalculatePacketNumber(cur_epoch + num, last); } } } TEST_P(QuicFramerTest, CalculatePacketNumberFromWireNearNextMax) { const uint64_t max_number = std::numeric_limits<uint64_t>::max(); const uint64_t max_epoch = max_number & ~kMask; for (uint64_t i = 0; i < 10; i++) { QuicPacketNumber last = QuicPacketNumber(max_number - i - 1); for (uint64_t j = 0; j < 10; j++) { CheckCalculatePacketNumber(max_epoch + j, last); } for (uint64_t j = 0; j < 10; j++) { uint64_t num = kEpoch - 1 - j; CheckCalculatePacketNumber(max_epoch + num, last); } } } TEST_P(QuicFramerTest, EmptyPacket) { char packet[] = {0x00}; QuicEncryptedPacket encrypted(packet, 0, false); EXPECT_FALSE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsError(QUIC_INVALID_PACKET_HEADER)); } TEST_P(QuicFramerTest, LargePacket) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); unsigned char packet[kMaxIncomingPacketSize + 1] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x78, 0x56, 0x34, 0x12, }; const size_t header_size = GetPacketHeaderSize( framer_.transport_version(), kPacket8ByteConnectionId, kPacket0ByteConnectionId, !kIncludeVersion, !kIncludeDiversificationNonce, PACKET_4BYTE_PACKET_NUMBER, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0, 0, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0); memset(packet + header_size, 0, kMaxIncomingPacketSize - header_size); QuicEncryptedPacket encrypted(AsChars(packet), ABSL_ARRAYSIZE(packet), false); EXPECT_FALSE(framer_.ProcessPacket(encrypted)); ASSERT_TRUE(visitor_.header_.get()); EXPECT_EQ(FramerTestConnectionId(), visitor_.header_->destination_connection_id); EXPECT_THAT(framer_.error(), IsError(QUIC_PACKET_TOO_LARGE)); EXPECT_EQ("Packet too large.", framer_.detailed_error()); EXPECT_EQ(0, visitor_.packet_count_); } TEST_P(QuicFramerTest, LongPacketHeader) { PacketFragments packet = { {"Unable to read first byte.", {0xD3}}, {"Unable to read protocol version.", {QUIC_VERSION_BYTES}}, {"Unable to read ConnectionId length.", {0x50}}, {"Unable to read destination connection ID.", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"Unable to read packet number.", {0x12, 0x34, 0x56, 0x78}}, }; if (QuicVersionHasLongHeaderLengths(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_ZERO_RTT); std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet)); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsError(QUIC_MISSING_PAYLOAD)); ASSERT_TRUE(visitor_.header_.get()); EXPECT_EQ(FramerTestConnectionId(), visitor_.header_->destination_connection_id); EXPECT_FALSE(visitor_.header_->reset_flag); EXPECT_TRUE(visitor_.header_->version_flag); EXPECT_EQ(kPacketNumber, visitor_.header_->packet_number); CheckFramingBoundaries(packet, QUIC_INVALID_PACKET_HEADER); PacketHeaderFormat format; QuicLongHeaderType long_packet_type = INVALID_PACKET_TYPE; bool version_flag; QuicConnectionId destination_connection_id, source_connection_id; QuicVersionLabel version_label; std::string detailed_error; bool use_length_prefix; std::optional<absl::string_view> retry_token; ParsedQuicVersion parsed_version = UnsupportedQuicVersion(); const QuicErrorCode error_code = QuicFramer::ParsePublicHeaderDispatcher( *encrypted, kQuicDefaultConnectionIdLength, &format, &long_packet_type, &version_flag, &use_length_prefix, &version_label, &parsed_version, &destination_connection_id, &source_connection_id, &retry_token, &detailed_error); EXPECT_THAT(error_code, IsQuicNoError()); EXPECT_EQ("", detailed_error); EXPECT_FALSE(retry_token.has_value()); EXPECT_FALSE(use_length_prefix); EXPECT_EQ(IETF_QUIC_LONG_HEADER_PACKET, format); EXPECT_TRUE(version_flag); EXPECT_EQ(kQuicDefaultConnectionIdLength, destination_connection_id.length()); EXPECT_EQ(FramerTestConnectionId(), destination_connection_id); EXPECT_EQ(EmptyQuicConnectionId(), source_connection_id); } TEST_P(QuicFramerTest, LongPacketHeaderWithBothConnectionIds) { SetDecrypterLevel(ENCRYPTION_ZERO_RTT); unsigned char packet[] = { 0xD3, QUIC_VERSION_BYTES, 0x55, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x11, 0x12, 0x34, 0x56, 0x00, 0x00, }; unsigned char packet49[] = { 0xD3, QUIC_VERSION_BYTES, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x11, 0x05, 0x12, 0x34, 0x56, 0x00, 0x00, }; unsigned char* p = packet; size_t p_length = ABSL_ARRAYSIZE(packet); if (framer_.version().HasLongHeaderLengths()) { ReviseFirstByteByVersion(packet49); p = packet49; p_length = ABSL_ARRAYSIZE(packet49); } QuicEncryptedPacket encrypted(AsChars(p), p_length, false); PacketHeaderFormat format = GOOGLE_QUIC_PACKET; QuicLongHeaderType long_packet_type = INVALID_PACKET_TYPE; bool version_flag = false; QuicConnectionId destination_connection_id, source_connection_id; QuicVersionLabel version_label = 0; std::string detailed_error = ""; bool use_length_prefix; std::optional<absl::string_view> retry_token; ParsedQuicVersion parsed_version = UnsupportedQuicVersion(); const QuicErrorCode error_code = QuicFramer::ParsePublicHeaderDispatcher( encrypted, kQuicDefaultConnectionIdLength, &format, &long_packet_type, &version_flag, &use_length_prefix, &version_label, &parsed_version, &destination_connection_id, &source_connection_id, &retry_token, &detailed_error); EXPECT_THAT(error_code, IsQuicNoError()); EXPECT_FALSE(retry_token.has_value()); EXPECT_EQ(framer_.version().HasLengthPrefixedConnectionIds(), use_length_prefix); EXPECT_EQ("", detailed_error); EXPECT_EQ(IETF_QUIC_LONG_HEADER_PACKET, format); EXPECT_TRUE(version_flag); EXPECT_EQ(FramerTestConnectionId(), destination_connection_id); EXPECT_EQ(FramerTestConnectionIdPlusOne(), source_connection_id); } TEST_P(QuicFramerTest, AllZeroPacketParsingFails) { unsigned char packet[1200] = {}; QuicEncryptedPacket encrypted(AsChars(packet), ABSL_ARRAYSIZE(packet), false); PacketHeaderFormat format = GOOGLE_QUIC_PACKET; QuicLongHeaderType long_packet_type = INVALID_PACKET_TYPE; bool version_flag = false; QuicConnectionId destination_connection_id, source_connection_id; QuicVersionLabel version_label = 0; std::string detailed_error = ""; bool use_length_prefix; std::optional<absl::string_view> retry_token; ParsedQuicVersion parsed_version = UnsupportedQuicVersion(); const QuicErrorCode error_code = QuicFramer::ParsePublicHeaderDispatcher( encrypted, kQuicDefaultConnectionIdLength, &format, &long_packet_type, &version_flag, &use_length_prefix, &version_label, &parsed_version, &destination_connection_id, &source_connection_id, &retry_token, &detailed_error); EXPECT_EQ(error_code, QUIC_INVALID_PACKET_HEADER); EXPECT_EQ(detailed_error, "Invalid flags."); } TEST_P(QuicFramerTest, ParsePublicHeader) { unsigned char packet[] = { 0xE3, QUIC_VERSION_BYTES, 0x50, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x05, 0x12, 0x34, 0x56, 0x78, 0x00, }; unsigned char packet49[] = { 0xE3, QUIC_VERSION_BYTES, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x05, 0x12, 0x34, 0x56, 0x78, 0x00, }; unsigned char* p = packet; size_t p_length = ABSL_ARRAYSIZE(packet); if (framer_.version().HasLongHeaderLengths()) { ReviseFirstByteByVersion(packet49); p = packet49; p_length = ABSL_ARRAYSIZE(packet49); } uint8_t first_byte = 0x33; PacketHeaderFormat format = GOOGLE_QUIC_PACKET; bool version_present = false, has_length_prefix = false; QuicVersionLabel version_label = 0; ParsedQuicVersion parsed_version = UnsupportedQuicVersion(); QuicConnectionId destination_connection_id = EmptyQuicConnectionId(), source_connection_id = EmptyQuicConnectionId(); QuicLongHeaderType long_packet_type = INVALID_PACKET_TYPE; quiche::QuicheVariableLengthIntegerLength retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_4; absl::string_view retry_token; std::string detailed_error = "foobar"; QuicDataReader reader(AsChars(p), p_length); const QuicErrorCode parse_error = QuicFramer::ParsePublicHeader( &reader, kQuicDefaultConnectionIdLength, true, &first_byte, &format, &version_present, &has_length_prefix, &version_label, &parsed_version, &destination_connection_id, &source_connection_id, &long_packet_type, &retry_token_length_length, &retry_token, &detailed_error); EXPECT_THAT(parse_error, IsQuicNoError()); EXPECT_EQ("", detailed_error); EXPECT_EQ(p[0], first_byte); EXPECT_TRUE(version_present); EXPECT_EQ(framer_.version().HasLengthPrefixedConnectionIds(), has_length_prefix); EXPECT_EQ(CreateQuicVersionLabel(framer_.version()), version_label); EXPECT_EQ(framer_.version(), parsed_version); EXPECT_EQ(FramerTestConnectionId(), destination_connection_id); EXPECT_EQ(EmptyQuicConnectionId(), source_connection_id); EXPECT_EQ(quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0, retry_token_length_length); EXPECT_EQ(absl::string_view(), retry_token); EXPECT_EQ(IETF_QUIC_LONG_HEADER_PACKET, format); EXPECT_EQ(HANDSHAKE, long_packet_type); } TEST_P(QuicFramerTest, ParsePublicHeaderProxBadSourceConnectionIdLength) { if (!framer_.version().HasLengthPrefixedConnectionIds()) { return; } unsigned char packet[] = { 0xE3, 'P', 'R', 'O', 'X', 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0xEE, 0x05, 0x12, 0x34, 0x56, 0x78, 0x00, }; unsigned char* p = packet; size_t p_length = ABSL_ARRAYSIZE(packet); uint8_t first_byte = 0x33; PacketHeaderFormat format = GOOGLE_QUIC_PACKET; bool version_present = false, has_length_prefix = false; QuicVersionLabel version_label = 0; ParsedQuicVersion parsed_version = UnsupportedQuicVersion(); QuicConnectionId destination_connection_id = EmptyQuicConnectionId(), source_connection_id = EmptyQuicConnectionId(); QuicLongHeaderType long_packet_type = INVALID_PACKET_TYPE; quiche::QuicheVariableLengthIntegerLength retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_4; absl::string_view retry_token; std::string detailed_error = "foobar"; QuicDataReader reader(AsChars(p), p_length); const QuicErrorCode parse_error = QuicFramer::ParsePublicHeader( &reader, kQuicDefaultConnectionIdLength, true, &first_byte, &format, &version_present, &has_length_prefix, &version_label, &parsed_version, &destination_connection_id, &source_connection_id, &long_packet_type, &retry_token_length_length, &retry_token, &detailed_error); EXPECT_THAT(parse_error, IsQuicNoError()); EXPECT_EQ("", detailed_error); EXPECT_EQ(p[0], first_byte); EXPECT_TRUE(version_present); EXPECT_TRUE(has_length_prefix); EXPECT_EQ(0x50524F58u, version_label); EXPECT_EQ(UnsupportedQuicVersion(), parsed_version); EXPECT_EQ(FramerTestConnectionId(), destination_connection_id); EXPECT_EQ(EmptyQuicConnectionId(), source_connection_id); EXPECT_EQ(quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0, retry_token_length_length); EXPECT_EQ(absl::string_view(), retry_token); EXPECT_EQ(IETF_QUIC_LONG_HEADER_PACKET, format); } TEST_P(QuicFramerTest, ClientConnectionIdFromShortHeaderToClient) { if (!framer_.version().SupportsClientConnectionIds()) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); QuicFramerPeer::SetLastSerializedServerConnectionId(&framer_, TestConnectionId(0x33)); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); framer_.SetExpectedClientConnectionIdLength(kQuicDefaultConnectionIdLength); unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x13, 0x37, 0x42, 0x33, 0x00, }; QuicEncryptedPacket encrypted(AsChars(packet), ABSL_ARRAYSIZE(packet), false); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); EXPECT_EQ("", framer_.detailed_error()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_EQ(FramerTestConnectionId(), visitor_.header_->destination_connection_id); } TEST_P(QuicFramerTest, ClientConnectionIdFromShortHeaderToServer) { if (!framer_.version().SupportsClientConnectionIds()) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x13, 0x37, 0x42, 0x33, 0x00, }; QuicEncryptedPacket encrypted(AsChars(packet), ABSL_ARRAYSIZE(packet), false); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); EXPECT_EQ("", framer_.detailed_error()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_EQ(FramerTestConnectionId(), visitor_.header_->destination_connection_id); } TEST_P(QuicFramerTest, PacketHeaderWith0ByteConnectionId) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); QuicFramerPeer::SetLastSerializedServerConnectionId(&framer_, FramerTestConnectionId()); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); PacketFragments packet = { {"Unable to read first byte.", {0x43}}, {"Unable to read packet number.", {0x12, 0x34, 0x56, 0x78}}, }; PacketFragments packet_hp = { {"Unable to read first byte.", {0x43}}, {"", {0x12, 0x34, 0x56, 0x78}}, }; PacketFragments& fragments = framer_.version().HasHeaderProtection() ? packet_hp : packet; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(fragments)); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsError(QUIC_MISSING_PAYLOAD)); ASSERT_TRUE(visitor_.header_.get()); EXPECT_FALSE(visitor_.header_->reset_flag); EXPECT_FALSE(visitor_.header_->version_flag); EXPECT_EQ(kPacketNumber, visitor_.header_->packet_number); CheckFramingBoundaries(fragments, QUIC_INVALID_PACKET_HEADER); } TEST_P(QuicFramerTest, PacketHeaderWithVersionFlag) { SetDecrypterLevel(ENCRYPTION_ZERO_RTT); PacketFragments packet = { {"Unable to read first byte.", {0xD3}}, {"Unable to read protocol version.", {QUIC_VERSION_BYTES}}, {"Unable to read ConnectionId length.", {0x50}}, {"Unable to read destination connection ID.", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"Unable to read packet number.", {0x12, 0x34, 0x56, 0x78}}, }; PacketFragments packet49 = { {"Unable to read first byte.", {0xD3}}, {"Unable to read protocol version.", {QUIC_VERSION_BYTES}}, {"Unable to read destination connection ID.", {0x08}}, {"Unable to read destination connection ID.", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"Unable to read source connection ID.", {0x00}}, {"Unable to read long header payload length.", {0x04}}, {"Long header payload length longer than packet.", {0x12, 0x34, 0x56, 0x78}}, }; ReviseFirstByteByVersion(packet49); PacketFragments& fragments = framer_.version().HasLongHeaderLengths() ? packet49 : packet; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(fragments)); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsError(QUIC_MISSING_PAYLOAD)); ASSERT_TRUE(visitor_.header_.get()); EXPECT_EQ(FramerTestConnectionId(), visitor_.header_->destination_connection_id); EXPECT_FALSE(visitor_.header_->reset_flag); EXPECT_TRUE(visitor_.header_->version_flag); EXPECT_EQ(GetParam(), visitor_.header_->version); EXPECT_EQ(kPacketNumber, visitor_.header_->packet_number); CheckFramingBoundaries(fragments, QUIC_INVALID_PACKET_HEADER); } TEST_P(QuicFramerTest, PacketHeaderWith4BytePacketNumber) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); QuicFramerPeer::SetLargestPacketNumber(&framer_, kPacketNumber - 2); PacketFragments packet = { {"Unable to read first byte.", {0x43}}, {"Unable to read destination connection ID.", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"Unable to read packet number.", {0x12, 0x34, 0x56, 0x78}}, }; PacketFragments packet_hp = { {"Unable to read first byte.", {0x43}}, {"Unable to read destination connection ID.", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, }; PacketFragments& fragments = framer_.version().HasHeaderProtection() ? packet_hp : packet; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(fragments)); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsError(QUIC_MISSING_PAYLOAD)); ASSERT_TRUE(visitor_.header_.get()); EXPECT_EQ(FramerTestConnectionId(), visitor_.header_->destination_connection_id); EXPECT_FALSE(visitor_.header_->reset_flag); EXPECT_FALSE(visitor_.header_->version_flag); EXPECT_EQ(kPacketNumber, visitor_.header_->packet_number); CheckFramingBoundaries(fragments, QUIC_INVALID_PACKET_HEADER); } TEST_P(QuicFramerTest, PacketHeaderWith2BytePacketNumber) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); QuicFramerPeer::SetLargestPacketNumber(&framer_, kPacketNumber - 2); PacketFragments packet = { {"Unable to read first byte.", {0x41}}, {"Unable to read destination connection ID.", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"Unable to read packet number.", {0x56, 0x78}}, }; PacketFragments packet_hp = { {"Unable to read first byte.", {0x41}}, {"Unable to read destination connection ID.", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x56, 0x78}}, {"", {0x00, 0x00}}, }; PacketFragments& fragments = framer_.version().HasHeaderProtection() ? packet_hp : packet; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(fragments)); if (framer_.version().HasHeaderProtection()) { EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); } else { EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsError(QUIC_MISSING_PAYLOAD)); } ASSERT_TRUE(visitor_.header_.get()); EXPECT_EQ(FramerTestConnectionId(), visitor_.header_->destination_connection_id); EXPECT_FALSE(visitor_.header_->reset_flag); EXPECT_FALSE(visitor_.header_->version_flag); EXPECT_EQ(PACKET_2BYTE_PACKET_NUMBER, visitor_.header_->packet_number_length); EXPECT_EQ(kPacketNumber, visitor_.header_->packet_number); CheckFramingBoundaries(fragments, QUIC_INVALID_PACKET_HEADER); } TEST_P(QuicFramerTest, PacketHeaderWith1BytePacketNumber) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); QuicFramerPeer::SetLargestPacketNumber(&framer_, kPacketNumber - 2); PacketFragments packet = { {"Unable to read first byte.", {0x40}}, {"Unable to read destination connection ID.", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"Unable to read packet number.", {0x78}}, }; PacketFragments packet_hp = { {"Unable to read first byte.", {0x40}}, {"Unable to read destination connection ID.", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x78}}, {"", {0x00, 0x00, 0x00}}, }; PacketFragments& fragments = framer_.version().HasHeaderProtection() ? packet_hp : packet; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(fragments)); if (framer_.version().HasHeaderProtection()) { EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); } else { EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsError(QUIC_MISSING_PAYLOAD)); } ASSERT_TRUE(visitor_.header_.get()); EXPECT_EQ(FramerTestConnectionId(), visitor_.header_->destination_connection_id); EXPECT_FALSE(visitor_.header_->reset_flag); EXPECT_FALSE(visitor_.header_->version_flag); EXPECT_EQ(PACKET_1BYTE_PACKET_NUMBER, visitor_.header_->packet_number_length); EXPECT_EQ(kPacketNumber, visitor_.header_->packet_number); CheckFramingBoundaries(fragments, QUIC_INVALID_PACKET_HEADER); } TEST_P(QuicFramerTest, PacketNumberDecreasesThenIncreases) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber - 2; QuicFrames frames = {QuicFrame(QuicPaddingFrame())}; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); QuicEncryptedPacket encrypted(data->data(), data->length(), false); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); ASSERT_TRUE(visitor_.header_.get()); EXPECT_EQ(FramerTestConnectionId(), visitor_.header_->destination_connection_id); EXPECT_EQ(PACKET_4BYTE_PACKET_NUMBER, visitor_.header_->packet_number_length); EXPECT_EQ(kPacketNumber - 2, visitor_.header_->packet_number); header.packet_number = kPacketNumber; header.packet_number_length = PACKET_1BYTE_PACKET_NUMBER; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); data = BuildDataPacket(header, frames); QuicEncryptedPacket encrypted1(data->data(), data->length(), false); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(encrypted1)); ASSERT_TRUE(visitor_.header_.get()); EXPECT_EQ(FramerTestConnectionId(), visitor_.header_->destination_connection_id); EXPECT_EQ(PACKET_1BYTE_PACKET_NUMBER, visitor_.header_->packet_number_length); EXPECT_EQ(kPacketNumber, visitor_.header_->packet_number); header.packet_number = kPacketNumber - 256; header.packet_number_length = PACKET_2BYTE_PACKET_NUMBER; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); data = BuildDataPacket(header, frames); QuicEncryptedPacket encrypted2(data->data(), data->length(), false); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(encrypted2)); ASSERT_TRUE(visitor_.header_.get()); EXPECT_EQ(FramerTestConnectionId(), visitor_.header_->destination_connection_id); EXPECT_EQ(PACKET_2BYTE_PACKET_NUMBER, visitor_.header_->packet_number_length); EXPECT_EQ(kPacketNumber - 256, visitor_.header_->packet_number); header.packet_number = kPacketNumber - 1; header.packet_number_length = PACKET_1BYTE_PACKET_NUMBER; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); data = BuildDataPacket(header, frames); QuicEncryptedPacket encrypted3(data->data(), data->length(), false); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(encrypted3)); ASSERT_TRUE(visitor_.header_.get()); EXPECT_EQ(FramerTestConnectionId(), visitor_.header_->destination_connection_id); EXPECT_EQ(PACKET_1BYTE_PACKET_NUMBER, visitor_.header_->packet_number_length); EXPECT_EQ(kPacketNumber - 1, visitor_.header_->packet_number); } TEST_P(QuicFramerTest, PacketWithDiversificationNonce) { SetDecrypterLevel(ENCRYPTION_ZERO_RTT); unsigned char packet[] = { 0xD0, QUIC_VERSION_BYTES, 0x05, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x78, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00 }; unsigned char packet49[] = { 0xD0, QUIC_VERSION_BYTES, 0x00, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x26, 0x78, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00 }; if (framer_.version().handshake_protocol != PROTOCOL_QUIC_CRYPTO) { return; } unsigned char* p = packet; size_t p_size = ABSL_ARRAYSIZE(packet); if (framer_.version().HasLongHeaderLengths()) { p = packet49; p_size = ABSL_ARRAYSIZE(packet49); } QuicEncryptedPacket encrypted(AsChars(p), p_size, false); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); ASSERT_TRUE(visitor_.header_->nonce != nullptr); for (char i = 0; i < 32; ++i) { EXPECT_EQ(i, (*visitor_.header_->nonce)[static_cast<size_t>(i)]); } EXPECT_EQ(1u, visitor_.padding_frames_.size()); EXPECT_EQ(5, visitor_.padding_frames_[0]->num_padding_bytes); } TEST_P(QuicFramerTest, LargePublicFlagWithMismatchedVersions) { unsigned char packet[] = { 0xD3, 'Q', '0', '0', '0', 0x50, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00 }; unsigned char packet49[] = { 0xD3, 'Q', '0', '0', '0', 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x12, 0x34, 0x56, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00 }; unsigned char* p = packet; size_t p_size = ABSL_ARRAYSIZE(packet); if (framer_.version().HasLongHeaderLengths()) { p = packet49; p_size = ABSL_ARRAYSIZE(packet49); } QuicEncryptedPacket encrypted(AsChars(p), p_size, false); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_EQ(0, visitor_.frame_count_); EXPECT_EQ(1, visitor_.version_mismatch_); } TEST_P(QuicFramerTest, PaddingFrame) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x00, 0x00, 0xFF, 0x01, 0x02, 0x03, 0x04, 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, 0x00, 0x0c, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', 0x00, 0x00, }; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x00, 0x00, 0x08 | 0x01 | 0x02 | 0x04, kVarInt62FourBytes + 0x01, 0x02, 0x03, 0x04, kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, kVarInt62OneByte + 0x0c, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', 0x00, 0x00, }; unsigned char* p = packet; size_t p_size = ABSL_ARRAYSIZE(packet); if (VersionHasIetfQuicFrames(framer_.transport_version())) { p = packet_ietf; p_size = ABSL_ARRAYSIZE(packet_ietf); } QuicEncryptedPacket encrypted(AsChars(p), p_size, false); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); ASSERT_EQ(1u, visitor_.stream_frames_.size()); EXPECT_EQ(0u, visitor_.ack_frames_.size()); EXPECT_EQ(2u, visitor_.padding_frames_.size()); EXPECT_EQ(2, visitor_.padding_frames_[0]->num_padding_bytes); EXPECT_EQ(2, visitor_.padding_frames_[1]->num_padding_bytes); EXPECT_EQ(kStreamId, visitor_.stream_frames_[0]->stream_id); EXPECT_TRUE(visitor_.stream_frames_[0]->fin); EXPECT_EQ(kStreamOffset, visitor_.stream_frames_[0]->offset); CheckStreamFrameData("hello world!", visitor_.stream_frames_[0].get()); } TEST_P(QuicFramerTest, StreamFrame) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0xFF}}, {"Unable to read stream_id.", {0x01, 0x02, 0x03, 0x04}}, {"Unable to read offset.", {0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54}}, {"Unable to read frame data.", { 0x00, 0x0c, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!'}}, }; PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", { 0x08 | 0x01 | 0x02 | 0x04 }}, {"Unable to read IETF_STREAM frame stream id/count.", {kVarInt62FourBytes + 0x01, 0x02, 0x03, 0x04}}, {"Unable to read stream data offset.", {kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54}}, {"Unable to read stream data length.", {kVarInt62OneByte + 0x0c}}, {"Unable to read frame data.", { 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!'}}, }; PacketFragments& fragments = VersionHasIetfQuicFrames(framer_.transport_version()) ? packet_ietf : packet; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(fragments)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); ASSERT_EQ(1u, visitor_.stream_frames_.size()); EXPECT_EQ(0u, visitor_.ack_frames_.size()); EXPECT_EQ(kStreamId, visitor_.stream_frames_[0]->stream_id); EXPECT_TRUE(visitor_.stream_frames_[0]->fin); EXPECT_EQ(kStreamOffset, visitor_.stream_frames_[0]->offset); CheckStreamFrameData("hello world!", visitor_.stream_frames_[0].get()); CheckFramingBoundaries(fragments, QUIC_INVALID_STREAM_DATA); } TEST_P(QuicFramerTest, EmptyStreamFrame) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", { 0x08 | 0x01 | 0x02 | 0x04 }}, {"Unable to read IETF_STREAM frame stream id/count.", {kVarInt62FourBytes + 0x01, 0x02, 0x03, 0x04}}, {"Unable to read stream data offset.", {kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54}}, {"Unable to read stream data length.", {kVarInt62OneByte + 0x00}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); ASSERT_EQ(1u, visitor_.stream_frames_.size()); EXPECT_EQ(0u, visitor_.ack_frames_.size()); EXPECT_EQ(kStreamId, visitor_.stream_frames_[0]->stream_id); EXPECT_TRUE(visitor_.stream_frames_[0]->fin); EXPECT_EQ(kStreamOffset, visitor_.stream_frames_[0]->offset); EXPECT_EQ(visitor_.stream_frames_[0].get()->data_length, 0u); CheckFramingBoundaries(packet, QUIC_INVALID_STREAM_DATA); } TEST_P(QuicFramerTest, MissingDiversificationNonce) { if (framer_.version().handshake_protocol != PROTOCOL_QUIC_CRYPTO) { return; } QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); decrypter_ = new test::TestDecrypter(); if (framer_.version().KnowsWhichDecrypterToUse()) { framer_.InstallDecrypter( ENCRYPTION_INITIAL, std::make_unique<NullDecrypter>(Perspective::IS_CLIENT)); framer_.InstallDecrypter(ENCRYPTION_ZERO_RTT, std::unique_ptr<QuicDecrypter>(decrypter_)); } else { framer_.SetDecrypter(ENCRYPTION_INITIAL, std::make_unique<NullDecrypter>( Perspective::IS_CLIENT)); framer_.SetAlternativeDecrypter( ENCRYPTION_ZERO_RTT, std::unique_ptr<QuicDecrypter>(decrypter_), false); } unsigned char packet[] = { 0xD3, QUIC_VERSION_BYTES, 0x05, 0x10, 0x32, 0x54, 0x76, 0x98, 0xBA, 0xDC, 0xFE, 0x12, 0x34, 0x56, 0x78, 0x00, }; unsigned char packet49[] = { 0xD3, QUIC_VERSION_BYTES, 0x00, 0x08, 0x10, 0x32, 0x54, 0x76, 0x98, 0xBA, 0xDC, 0xFE, 0x05, 0x12, 0x34, 0x56, 0x78, 0x00, }; unsigned char* p = packet; size_t p_length = ABSL_ARRAYSIZE(packet); if (framer_.version().HasLongHeaderLengths()) { p = packet49; p_length = ABSL_ARRAYSIZE(packet49); } QuicEncryptedPacket encrypted(AsChars(p), p_length, false); EXPECT_FALSE(framer_.ProcessPacket(encrypted)); if (framer_.version().HasHeaderProtection()) { EXPECT_THAT(framer_.error(), IsError(QUIC_DECRYPTION_FAILURE)); EXPECT_EQ("Unable to decrypt ENCRYPTION_ZERO_RTT header protection.", framer_.detailed_error()); } else { EXPECT_THAT(framer_.error(), IsError(QUIC_INVALID_PACKET_HEADER)); EXPECT_EQ("Unable to read nonce.", framer_.detailed_error()); } } TEST_P(QuicFramerTest, StreamFrame2ByteStreamId) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0xFD}}, {"Unable to read stream_id.", {0x03, 0x04}}, {"Unable to read offset.", {0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54}}, {"Unable to read frame data.", { 0x00, 0x0c, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!'}}, }; PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x08 | 0x01 | 0x02 | 0x04}}, {"Unable to read IETF_STREAM frame stream id/count.", {kVarInt62TwoBytes + 0x03, 0x04}}, {"Unable to read stream data offset.", {kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54}}, {"Unable to read stream data length.", {kVarInt62OneByte + 0x0c}}, {"Unable to read frame data.", { 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!'}}, }; PacketFragments& fragments = VersionHasIetfQuicFrames(framer_.transport_version()) ? packet_ietf : packet; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(fragments)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); ASSERT_EQ(1u, visitor_.stream_frames_.size()); EXPECT_EQ(0u, visitor_.ack_frames_.size()); EXPECT_EQ(0x0000FFFF & kStreamId, visitor_.stream_frames_[0]->stream_id); EXPECT_TRUE(visitor_.stream_frames_[0]->fin); EXPECT_EQ(kStreamOffset, visitor_.stream_frames_[0]->offset); CheckStreamFrameData("hello world!", visitor_.stream_frames_[0].get()); CheckFramingBoundaries(fragments, QUIC_INVALID_STREAM_DATA); } TEST_P(QuicFramerTest, StreamFrame1ByteStreamId) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0xFC}}, {"Unable to read stream_id.", {0x04}}, {"Unable to read offset.", {0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54}}, {"Unable to read frame data.", { 0x00, 0x0c, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!'}}, }; PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x08 | 0x01 | 0x02 | 0x04}}, {"Unable to read IETF_STREAM frame stream id/count.", {kVarInt62OneByte + 0x04}}, {"Unable to read stream data offset.", {kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54}}, {"Unable to read stream data length.", {kVarInt62OneByte + 0x0c}}, {"Unable to read frame data.", { 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!'}}, }; PacketFragments& fragments = VersionHasIetfQuicFrames(framer_.transport_version()) ? packet_ietf : packet; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(fragments)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); ASSERT_EQ(1u, visitor_.stream_frames_.size()); EXPECT_EQ(0u, visitor_.ack_frames_.size()); EXPECT_EQ(0x000000FF & kStreamId, visitor_.stream_frames_[0]->stream_id); EXPECT_TRUE(visitor_.stream_frames_[0]->fin); EXPECT_EQ(kStreamOffset, visitor_.stream_frames_[0]->offset); CheckStreamFrameData("hello world!", visitor_.stream_frames_[0].get()); CheckFramingBoundaries(fragments, QUIC_INVALID_STREAM_DATA); } TEST_P(QuicFramerTest, StreamFrameWithVersion) { SetDecrypterLevel(ENCRYPTION_ZERO_RTT); PacketFragments packet = { {"", {0xD3}}, {"", {QUIC_VERSION_BYTES}}, {"", {0x50}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0xFE}}, {"Unable to read stream_id.", {0x02, 0x03, 0x04}}, {"Unable to read offset.", {0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54}}, {"Unable to read frame data.", { 0x00, 0x0c, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!'}}, }; PacketFragments packet49 = { {"", {0xD3}}, {"", {QUIC_VERSION_BYTES}}, {"", {0x08}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x00}}, {"", {0x1E}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0xFE}}, {"Long header payload length longer than packet.", {0x02, 0x03, 0x04}}, {"Long header payload length longer than packet.", {0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54}}, {"Long header payload length longer than packet.", { 0x00, 0x0c, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!'}}, }; PacketFragments packet_ietf = { {"", {0xD3}}, {"", {QUIC_VERSION_BYTES}}, {"", {0x08}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x00}}, {"", {0x1E}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x08 | 0x01 | 0x02 | 0x04}}, {"Long header payload length longer than packet.", {kVarInt62FourBytes + 0x00, 0x02, 0x03, 0x04}}, {"Long header payload length longer than packet.", {kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54}}, {"Long header payload length longer than packet.", {kVarInt62OneByte + 0x0c}}, {"Long header payload length longer than packet.", { 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!'}}, }; quiche::QuicheVariableLengthIntegerLength retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0; size_t retry_token_length = 0; quiche::QuicheVariableLengthIntegerLength length_length = QuicVersionHasLongHeaderLengths(framer_.transport_version()) ? quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1 : quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0; ReviseFirstByteByVersion(packet_ietf); PacketFragments& fragments = VersionHasIetfQuicFrames(framer_.transport_version()) ? packet_ietf : (framer_.version().HasLongHeaderLengths() ? packet49 : packet); std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(fragments)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId, retry_token_length_length, retry_token_length, length_length)); ASSERT_EQ(1u, visitor_.stream_frames_.size()); EXPECT_EQ(0u, visitor_.ack_frames_.size()); EXPECT_EQ(0x00FFFFFF & kStreamId, visitor_.stream_frames_[0]->stream_id); EXPECT_TRUE(visitor_.stream_frames_[0]->fin); EXPECT_EQ(kStreamOffset, visitor_.stream_frames_[0]->offset); CheckStreamFrameData("hello world!", visitor_.stream_frames_[0].get()); CheckFramingBoundaries(fragments, framer_.version().HasLongHeaderLengths() ? QUIC_INVALID_PACKET_HEADER : QUIC_INVALID_STREAM_DATA); } TEST_P(QuicFramerTest, RejectPacket) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); visitor_.accept_packet_ = false; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x10 | 0x01 | 0x02 | 0x04, kVarInt62FourBytes + 0x01, 0x02, 0x03, 0x04, kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, kVarInt62OneByte + 0x0c, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', }; QuicEncryptedPacket encrypted(AsChars(packet), ABSL_ARRAYSIZE(packet), false); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); ASSERT_EQ(0u, visitor_.stream_frames_.size()); EXPECT_EQ(0u, visitor_.ack_frames_.size()); } TEST_P(QuicFramerTest, RejectPublicHeader) { visitor_.accept_public_header_ = false; unsigned char packet[] = { 0x40, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x01, }; QuicEncryptedPacket encrypted(AsChars(packet), ABSL_ARRAYSIZE(packet), false); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_FALSE(visitor_.header_->packet_number.IsInitialized()); } TEST_P(QuicFramerTest, AckFrameOneAckBlock) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x45}}, {"Unable to read largest acked.", {0x12, 0x34}}, {"Unable to read ack delay time.", {0x00, 0x00}}, {"Unable to read first ack block length.", {0x12, 0x34}}, {"Unable to read num received packets.", {0x00}} }; PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x02}}, {"Unable to read largest acked.", {kVarInt62TwoBytes + 0x12, 0x34}}, {"Unable to read ack delay time.", {kVarInt62OneByte + 0x00}}, {"Unable to read ack block count.", {kVarInt62OneByte + 0x00}}, {"Unable to read first ack block length.", {kVarInt62TwoBytes + 0x12, 0x33}} }; PacketFragments& fragments = VersionHasIetfQuicFrames(framer_.transport_version()) ? packet_ietf : packet; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(fragments)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(0u, visitor_.stream_frames_.size()); ASSERT_EQ(1u, visitor_.ack_frames_.size()); const QuicAckFrame& frame = *visitor_.ack_frames_[0]; EXPECT_EQ(kSmallLargestObserved, LargestAcked(frame)); ASSERT_EQ(4660u, frame.packets.NumPacketsSlow()); CheckFramingBoundaries(fragments, QUIC_INVALID_ACK_DATA); } TEST_P(QuicFramerTest, FirstAckFrameUnderflow) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x45}}, {"Unable to read largest acked.", {0x12, 0x34}}, {"Unable to read ack delay time.", {0x00, 0x00}}, {"Unable to read first ack block length.", {0x88, 0x88}}, {"Underflow with first ack block length 34952 largest acked is 4660.", {0x00}} }; PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x02}}, {"Unable to read largest acked.", {kVarInt62TwoBytes + 0x12, 0x34}}, {"Unable to read ack delay time.", {kVarInt62OneByte + 0x00}}, {"Unable to read ack block count.", {kVarInt62OneByte + 0x00}}, {"Unable to read first ack block length.", {kVarInt62TwoBytes + 0x28, 0x88}} }; PacketFragments& fragments = VersionHasIetfQuicFrames(framer_.transport_version()) ? packet_ietf : packet; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(fragments)); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); CheckFramingBoundaries(fragments, QUIC_INVALID_ACK_DATA); } TEST_P(QuicFramerTest, ThirdAckBlockUnderflowGap) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x02}}, {"Unable to read largest acked.", {kVarInt62OneByte + 63}}, {"Unable to read ack delay time.", {kVarInt62OneByte + 0x00}}, {"Unable to read ack block count.", {kVarInt62OneByte + 0x02}}, {"Unable to read first ack block length.", {kVarInt62OneByte + 13}}, {"Unable to read gap block value.", {kVarInt62OneByte + 9}}, {"Unable to read ack block value.", {kVarInt62OneByte + 9}}, {"Unable to read gap block value.", {kVarInt62OneByte + 29}}, {"Underflow with gap block length 30 previous ack block start is 30.", {kVarInt62OneByte + 10}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ( framer_.detailed_error(), "Underflow with gap block length 30 previous ack block start is 30."); CheckFramingBoundaries(packet_ietf, QUIC_INVALID_ACK_DATA); } TEST_P(QuicFramerTest, ThirdAckBlockUnderflowAck) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x02}}, {"Unable to read largest acked.", {kVarInt62OneByte + 63}}, {"Unable to read ack delay time.", {kVarInt62OneByte + 0x00}}, {"Unable to read ack block count.", {kVarInt62OneByte + 0x02}}, {"Unable to read first ack block length.", {kVarInt62OneByte + 13}}, {"Unable to read gap block value.", {kVarInt62OneByte + 10}}, {"Unable to read ack block value.", {kVarInt62OneByte + 10}}, {"Unable to read gap block value.", {kVarInt62OneByte + 1}}, {"Unable to read ack block value.", {kVarInt62OneByte + 30}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(framer_.detailed_error(), "Underflow with ack block length 31 latest ack block end is 25."); CheckFramingBoundaries(packet_ietf, QUIC_INVALID_ACK_DATA); } TEST_P(QuicFramerTest, AckBlockUnderflowGapWrap) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x02}}, {"Unable to read largest acked.", {kVarInt62OneByte + 10}}, {"Unable to read ack delay time.", {kVarInt62OneByte + 0x00}}, {"Unable to read ack block count.", {kVarInt62OneByte + 1}}, {"Unable to read first ack block length.", {kVarInt62OneByte + 9}}, {"Unable to read gap block value.", {kVarInt62OneByte + 1}}, {"Underflow with gap block length 2 previous ack block start is 1.", {kVarInt62OneByte + 9}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(framer_.detailed_error(), "Underflow with gap block length 2 previous ack block start is 1."); CheckFramingBoundaries(packet_ietf, QUIC_INVALID_ACK_DATA); } TEST_P(QuicFramerTest, AckBlockUnderflowAckWrap) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x02}}, {"Unable to read largest acked.", {kVarInt62OneByte + 10}}, {"Unable to read ack delay time.", {kVarInt62OneByte + 0x00}}, {"Unable to read ack block count.", {kVarInt62OneByte + 1}}, {"Unable to read first ack block length.", {kVarInt62OneByte + 6}}, {"Unable to read gap block value.", {kVarInt62OneByte + 1}}, {"Unable to read ack block value.", {kVarInt62OneByte + 9}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(framer_.detailed_error(), "Underflow with ack block length 10 latest ack block end is 1."); CheckFramingBoundaries(packet_ietf, QUIC_INVALID_ACK_DATA); } TEST_P(QuicFramerTest, AckBlockAcksEverything) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x02}}, {"Unable to read largest acked.", {kVarInt62EightBytes + 0x3f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}, {"Unable to read ack delay time.", {kVarInt62OneByte + 0x00}}, {"Unable to read ack block count.", {kVarInt62OneByte + 0}}, {"Unable to read first ack block length.", {kVarInt62EightBytes + 0x3f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(1u, visitor_.ack_frames_.size()); const QuicAckFrame& frame = *visitor_.ack_frames_[0]; EXPECT_EQ(1u, frame.packets.NumIntervals()); EXPECT_EQ(kLargestIetfLargestObserved, LargestAcked(frame)); EXPECT_EQ(kLargestIetfLargestObserved.ToUint64(), frame.packets.NumPacketsSlow()); } TEST_P(QuicFramerTest, AckFrameFirstAckBlockLengthZero) { if (VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet = { {"", { 0x43 }}, {"", { 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10 }}, {"", { 0x12, 0x34, 0x56, 0x78 }}, {"", { 0x65 }}, {"Unable to read largest acked.", { 0x12, 0x34 }}, {"Unable to read ack delay time.", { 0x00, 0x00 }}, {"Unable to read num of ack blocks.", { 0x01 }}, {"Unable to read first ack block length.", { 0x00, 0x00 }}, { "First block length is zero.", { 0x01 }}, { "First block length is zero.", { 0x0e, 0xaf }}, { "First block length is zero.", { 0x00 }}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet)); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsError(QUIC_INVALID_ACK_DATA)); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(0u, visitor_.stream_frames_.size()); ASSERT_EQ(1u, visitor_.ack_frames_.size()); CheckFramingBoundaries(packet, QUIC_INVALID_ACK_DATA); } TEST_P(QuicFramerTest, AckFrameOneAckBlockMaxLength) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x56, 0x78, 0x9A, 0xBC}}, {"", {0x49}}, {"Unable to read largest acked.", {0x12, 0x34, 0x56, 0x78}}, {"Unable to read ack delay time.", {0x00, 0x00}}, {"Unable to read first ack block length.", {0x12, 0x34}}, {"Unable to read num received packets.", {0x00}} }; PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x56, 0x78, 0x9A, 0xBC}}, {"", {0x02}}, {"Unable to read largest acked.", {kVarInt62FourBytes + 0x12, 0x34, 0x56, 0x78}}, {"Unable to read ack delay time.", {kVarInt62OneByte + 0x00}}, {"Unable to read ack block count.", {kVarInt62OneByte + 0x00}}, {"Unable to read first ack block length.", {kVarInt62TwoBytes + 0x12, 0x33}} }; PacketFragments& fragments = VersionHasIetfQuicFrames(framer_.transport_version()) ? packet_ietf : packet; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(fragments)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(0u, visitor_.stream_frames_.size()); ASSERT_EQ(1u, visitor_.ack_frames_.size()); const QuicAckFrame& frame = *visitor_.ack_frames_[0]; EXPECT_EQ(kPacketNumber, LargestAcked(frame)); ASSERT_EQ(4660u, frame.packets.NumPacketsSlow()); CheckFramingBoundaries(fragments, QUIC_INVALID_ACK_DATA); } TEST_P(QuicFramerTest, AckFrameTwoTimeStampsMultipleAckBlocks) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet = { {"", { 0x43 }}, {"", { 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10 }}, {"", { 0x12, 0x34, 0x56, 0x78 }}, {"", { 0x65 }}, {"Unable to read largest acked.", { 0x12, 0x34 }}, {"Unable to read ack delay time.", { 0x00, 0x00 }}, {"Unable to read num of ack blocks.", { 0x04 }}, {"Unable to read first ack block length.", { 0x00, 0x01 }}, { "Unable to read gap to next ack block.", { 0x01 }}, { "Unable to ack block length.", { 0x0e, 0xaf }}, { "Unable to read gap to next ack block.", { 0xff }}, { "Unable to ack block length.", { 0x00, 0x00 }}, { "Unable to read gap to next ack block.", { 0x91 }}, { "Unable to ack block length.", { 0x01, 0xea }}, { "Unable to read gap to next ack block.", { 0x05 }}, { "Unable to ack block length.", { 0x00, 0x04 }}, { "Unable to read num received packets.", { 0x02 }}, { "Unable to read sequence delta in received packets.", { 0x01 }}, { "Unable to read time delta in received packets.", { 0x76, 0x54, 0x32, 0x10 }}, { "Unable to read sequence delta in received packets.", { 0x02 }}, { "Unable to read incremental time delta in received packets.", { 0x32, 0x10 }}, }; PacketFragments packet_ietf = { {"", { 0x43 }}, {"", { 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10 }}, {"", { 0x12, 0x34, 0x56, 0x78 }}, {"", { 0x22 }}, {"Unable to read largest acked.", { kVarInt62TwoBytes + 0x12, 0x34 }}, {"Unable to read ack delay time.", { kVarInt62OneByte + 0x00 }}, {"Unable to read ack block count.", { kVarInt62OneByte + 0x03 }}, {"Unable to read first ack block length.", { kVarInt62OneByte + 0x00 }}, { "Unable to read gap block value.", { kVarInt62OneByte + 0x00 }}, { "Unable to read ack block value.", { kVarInt62TwoBytes + 0x0e, 0xae }}, { "Unable to read gap block value.", { kVarInt62TwoBytes + 0x01, 0x8f }}, { "Unable to read ack block value.", { kVarInt62TwoBytes + 0x01, 0xe9 }}, { "Unable to read gap block value.", { kVarInt62OneByte + 0x04 }}, { "Unable to read ack block value.", { kVarInt62OneByte + 0x03 }}, { "Unable to read receive timestamp range count.", { kVarInt62OneByte + 0x01 }}, { "Unable to read receive timestamp gap.", { kVarInt62OneByte + 0x01 }}, { "Unable to read receive timestamp count.", { kVarInt62OneByte + 0x02 }}, { "Unable to read receive timestamp delta.", { kVarInt62FourBytes + 0x36, 0x54, 0x32, 0x10 }}, { "Unable to read receive timestamp delta.", { kVarInt62TwoBytes + 0x32, 0x10 }}, }; PacketFragments& fragments = VersionHasIetfQuicFrames(framer_.transport_version()) ? packet_ietf : packet; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(fragments)); framer_.set_process_timestamps(true); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(0u, visitor_.stream_frames_.size()); ASSERT_EQ(1u, visitor_.ack_frames_.size()); const QuicAckFrame& frame = *visitor_.ack_frames_[0]; EXPECT_EQ(kSmallLargestObserved, LargestAcked(frame)); ASSERT_EQ(4254u, frame.packets.NumPacketsSlow()); EXPECT_EQ(4u, frame.packets.NumIntervals()); EXPECT_EQ(2u, frame.received_packet_times.size()); } TEST_P(QuicFramerTest, AckFrameMultipleReceiveTimestampRanges) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", { 0x43 }}, {"", { 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10 }}, {"", { 0x12, 0x34, 0x56, 0x78 }}, {"", { 0x22 }}, {"Unable to read largest acked.", { kVarInt62TwoBytes + 0x12, 0x34 }}, {"Unable to read ack delay time.", { kVarInt62OneByte + 0x00 }}, {"Unable to read ack block count.", { kVarInt62OneByte + 0x00 }}, {"Unable to read first ack block length.", { kVarInt62OneByte + 0x00 }}, { "Unable to read receive timestamp range count.", { kVarInt62OneByte + 0x03 }}, { "Unable to read receive timestamp gap.", { kVarInt62OneByte + 0x02 }}, { "Unable to read receive timestamp count.", { kVarInt62OneByte + 0x03 }}, { "Unable to read receive timestamp delta.", { kVarInt62FourBytes + 0x29, 0xff, 0xff, 0xff}}, { "Unable to read receive timestamp delta.", { kVarInt62TwoBytes + 0x11, 0x11 }}, { "Unable to read receive timestamp delta.", { kVarInt62OneByte + 0x01}}, { "Unable to read receive timestamp gap.", { kVarInt62OneByte + 0x05 }}, { "Unable to read receive timestamp count.", { kVarInt62OneByte + 0x01 }}, { "Unable to read receive timestamp delta.", { kVarInt62TwoBytes + 0x10, 0x00 }}, { "Unable to read receive timestamp gap.", { kVarInt62OneByte + 0x08 }}, { "Unable to read receive timestamp count.", { kVarInt62OneByte + 0x02 }}, { "Unable to read receive timestamp delta.", { kVarInt62OneByte + 0x10 }}, { "Unable to read receive timestamp delta.", { kVarInt62TwoBytes + 0x01, 0x00 }}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); framer_.set_process_timestamps(true); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); const QuicAckFrame& frame = *visitor_.ack_frames_[0]; EXPECT_THAT(frame.received_packet_times, ContainerEq(PacketTimeVector{ {LargestAcked(frame) - 2, CreationTimePlus(0x29ffffff)}, {LargestAcked(frame) - 3, CreationTimePlus(0x29ffeeee)}, {LargestAcked(frame) - 4, CreationTimePlus(0x29ffeeed)}, {LargestAcked(frame) - 11, CreationTimePlus(0x29ffdeed)}, {LargestAcked(frame) - 21, CreationTimePlus(0x29ffdedd)}, {LargestAcked(frame) - 22, CreationTimePlus(0x29ffdddd)}, })); } TEST_P(QuicFramerTest, AckFrameReceiveTimestampWithExponent) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", { 0x43 }}, {"", { 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10 }}, {"", { 0x12, 0x34, 0x56, 0x78 }}, {"", { 0x22 }}, {"Unable to read largest acked.", { kVarInt62TwoBytes + 0x12, 0x34 }}, {"Unable to read ack delay time.", { kVarInt62OneByte + 0x00 }}, {"Unable to read ack block count.", { kVarInt62OneByte + 0x00 }}, {"Unable to read first ack block length.", { kVarInt62OneByte + 0x00 }}, { "Unable to read receive timestamp range count.", { kVarInt62OneByte + 0x01 }}, { "Unable to read receive timestamp gap.", { kVarInt62OneByte + 0x00 }}, { "Unable to read receive timestamp count.", { kVarInt62OneByte + 0x03 }}, { "Unable to read receive timestamp delta.", { kVarInt62TwoBytes + 0x29, 0xff}}, { "Unable to read receive timestamp delta.", { kVarInt62TwoBytes + 0x11, 0x11 }}, { "Unable to read receive timestamp delta.", { kVarInt62OneByte + 0x01}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); framer_.set_receive_timestamps_exponent(3); framer_.set_process_timestamps(true); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); const QuicAckFrame& frame = *visitor_.ack_frames_[0]; EXPECT_THAT(frame.received_packet_times, ContainerEq(PacketTimeVector{ {LargestAcked(frame), CreationTimePlus(0x29ff << 3)}, {LargestAcked(frame) - 1, CreationTimePlus(0x18ee << 3)}, {LargestAcked(frame) - 2, CreationTimePlus(0x18ed << 3)}, })); } TEST_P(QuicFramerTest, AckFrameReceiveTimestampGapTooHigh) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", { 0x43 }}, {"", { 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10 }}, {"", { 0x12, 0x34, 0x56, 0x78 }}, {"", { 0x22 }}, {"Unable to read largest acked.", { kVarInt62TwoBytes + 0x12, 0x34 }}, {"Unable to read ack delay time.", { kVarInt62OneByte + 0x00 }}, {"Unable to read ack block count.", { kVarInt62OneByte + 0x00 }}, {"Unable to read first ack block length.", { kVarInt62OneByte + 0x00 }}, { "Unable to read receive timestamp range count.", { kVarInt62OneByte + 0x01 }}, { "Unable to read receive timestamp gap.", { kVarInt62FourBytes + 0x12, 0x34, 0x56, 0x79 }}, { "Unable to read receive timestamp count.", { kVarInt62OneByte + 0x01 }}, { "Unable to read receive timestamp delta.", { kVarInt62TwoBytes + 0x29, 0xff}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); framer_.set_process_timestamps(true); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_TRUE(absl::StartsWith(framer_.detailed_error(), "Receive timestamp gap too high.")); } TEST_P(QuicFramerTest, AckFrameReceiveTimestampCountTooHigh) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", { 0x43 }}, {"", { 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10 }}, {"", { 0x12, 0x34, 0x56, 0x78 }}, {"", { 0x22 }}, {"Unable to read largest acked.", { kVarInt62TwoBytes + 0x12, 0x34 }}, {"Unable to read ack delay time.", { kVarInt62OneByte + 0x00 }}, {"Unable to read ack block count.", { kVarInt62OneByte + 0x00 }}, {"Unable to read first ack block length.", { kVarInt62OneByte + 0x00 }}, { "Unable to read receive timestamp range count.", { kVarInt62OneByte + 0x01 }}, { "Unable to read receive timestamp gap.", { kVarInt62OneByte + 0x02 }}, { "Unable to read receive timestamp count.", { kVarInt62OneByte + 0x02 }}, { "Unable to read receive timestamp delta.", { kVarInt62OneByte + 0x0a}}, { "Unable to read receive timestamp delta.", { kVarInt62OneByte + 0x0b}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); framer_.set_process_timestamps(true); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_TRUE(absl::StartsWith(framer_.detailed_error(), "Receive timestamp delta too high.")); } TEST_P(QuicFramerTest, AckFrameReceiveTimestampDeltaTooHigh) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", { 0x43 }}, {"", { 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10 }}, {"", { 0x12, 0x34, 0x56, 0x78 }}, {"", { 0x22 }}, {"Unable to read largest acked.", { kVarInt62TwoBytes + 0x12, 0x34 }}, {"Unable to read ack delay time.", { kVarInt62OneByte + 0x00 }}, {"Unable to read ack block count.", { kVarInt62OneByte + 0x00 }}, {"Unable to read first ack block length.", { kVarInt62OneByte + 0x00 }}, { "Unable to read receive timestamp range count.", { kVarInt62OneByte + 0x01 }}, { "Unable to read receive timestamp gap.", { kVarInt62OneByte + 0x02 }}, { "Unable to read receive timestamp count.", { kVarInt62FourBytes + 0x12, 0x34, 0x56, 0x77 }}, { "Unable to read receive timestamp delta.", { kVarInt62TwoBytes + 0x29, 0xff}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); framer_.set_process_timestamps(true); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_TRUE(absl::StartsWith(framer_.detailed_error(), "Receive timestamp count too high.")); } TEST_P(QuicFramerTest, AckFrameTimeStampDeltaTooHigh) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x40, 0x01, 0x00, 0x00, 0x01, 0x01, 0x01, 0x10, 0x32, 0x54, 0x76, }; if (VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicEncryptedPacket encrypted(AsChars(packet), ABSL_ARRAYSIZE(packet), false); EXPECT_FALSE(framer_.ProcessPacket(encrypted)); EXPECT_TRUE(absl::StartsWith(framer_.detailed_error(), "delta_from_largest_observed too high")); } TEST_P(QuicFramerTest, AckFrameTimeStampSecondDeltaTooHigh) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x40, 0x03, 0x00, 0x00, 0x03, 0x02, 0x01, 0x10, 0x32, 0x54, 0x76, 0x03, 0x10, 0x32, }; if (VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicEncryptedPacket encrypted(AsChars(packet), ABSL_ARRAYSIZE(packet), false); EXPECT_FALSE(framer_.ProcessPacket(encrypted)); EXPECT_TRUE(absl::StartsWith(framer_.detailed_error(), "delta_from_largest_observed too high")); } TEST_P(QuicFramerTest, NewStopWaitingFrame) { if (VersionHasIetfQuicFrames(version_.transport_version)) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x06}}, {"Unable to read least unacked delta.", {0x00, 0x00, 0x00, 0x08}} }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(0u, visitor_.stream_frames_.size()); ASSERT_EQ(1u, visitor_.stop_waiting_frames_.size()); const QuicStopWaitingFrame& frame = *visitor_.stop_waiting_frames_[0]; EXPECT_EQ(kLeastUnacked, frame.least_unacked); CheckFramingBoundaries(packet, QUIC_INVALID_STOP_WAITING_DATA); } TEST_P(QuicFramerTest, InvalidNewStopWaitingFrame) { if (VersionHasIetfQuicFrames(version_.transport_version)) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x06, 0x57, 0x78, 0x9A, 0xA8, }; QuicEncryptedPacket encrypted(AsChars(packet), ABSL_ARRAYSIZE(packet), false); EXPECT_FALSE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsError(QUIC_INVALID_STOP_WAITING_DATA)); EXPECT_EQ("Invalid unacked delta.", framer_.detailed_error()); } TEST_P(QuicFramerTest, RstStreamFrame) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x01}}, {"Unable to read stream_id.", {0x01, 0x02, 0x03, 0x04}}, {"Unable to read rst stream sent byte offset.", {0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54}}, {"Unable to read rst stream error code.", {0x00, 0x00, 0x00, 0x06}} }; PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x04}}, {"Unable to read IETF_RST_STREAM frame stream id/count.", {kVarInt62FourBytes + 0x01, 0x02, 0x03, 0x04}}, {"Unable to read rst stream error code.", {kVarInt62TwoBytes + 0x01, 0x0c}}, {"Unable to read rst stream sent byte offset.", {kVarInt62EightBytes + 0x3a, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54}} }; PacketFragments& fragments = VersionHasIetfQuicFrames(framer_.transport_version()) ? packet_ietf : packet; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(fragments)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(kStreamId, visitor_.rst_stream_frame_.stream_id); EXPECT_EQ(QUIC_STREAM_CANCELLED, visitor_.rst_stream_frame_.error_code); EXPECT_EQ(kStreamOffset, visitor_.rst_stream_frame_.byte_offset); CheckFramingBoundaries(fragments, QUIC_INVALID_RST_STREAM_DATA); } TEST_P(QuicFramerTest, ConnectionCloseFrame) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x02}}, {"Unable to read connection close error code.", {0x00, 0x00, 0x00, 0x11}}, {"Unable to read connection close error details.", { 0x0, 0x0d, 'b', 'e', 'c', 'a', 'u', 's', 'e', ' ', 'I', ' ', 'c', 'a', 'n'} } }; PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x1c}}, {"Unable to read connection close error code.", {kVarInt62TwoBytes + 0x00, 0x11}}, {"Unable to read connection close frame type.", {kVarInt62TwoBytes + 0x12, 0x34 }}, {"Unable to read connection close error details.", { kVarInt62OneByte + 0x11, '1', '1', '5', ':', 'b', 'e', 'c', 'a', 'u', 's', 'e', ' ', 'I', ' ', 'c', 'a', 'n'} } }; PacketFragments& fragments = VersionHasIetfQuicFrames(framer_.transport_version()) ? packet_ietf : packet; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(fragments)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(0u, visitor_.stream_frames_.size()); EXPECT_EQ(0x11u, static_cast<unsigned>( visitor_.connection_close_frame_.wire_error_code)); EXPECT_EQ("because I can", visitor_.connection_close_frame_.error_details); if (VersionHasIetfQuicFrames(framer_.transport_version())) { EXPECT_EQ(0x1234u, visitor_.connection_close_frame_.transport_close_frame_type); EXPECT_EQ(115u, visitor_.connection_close_frame_.quic_error_code); } else { EXPECT_EQ(0x11u, static_cast<unsigned>( visitor_.connection_close_frame_.quic_error_code)); } ASSERT_EQ(0u, visitor_.ack_frames_.size()); CheckFramingBoundaries(fragments, QUIC_INVALID_CONNECTION_CLOSE_DATA); } TEST_P(QuicFramerTest, ConnectionCloseFrameWithUnknownErrorCode) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x02}}, {"Unable to read connection close error code.", {0x00, 0x00, 0xC0, 0xDE}}, {"Unable to read connection close error details.", { 0x0, 0x0d, 'b', 'e', 'c', 'a', 'u', 's', 'e', ' ', 'I', ' ', 'c', 'a', 'n'} } }; PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x1c}}, {"Unable to read connection close error code.", {kVarInt62FourBytes + 0x00, 0x00, 0xC0, 0xDE}}, {"Unable to read connection close frame type.", {kVarInt62TwoBytes + 0x12, 0x34 }}, {"Unable to read connection close error details.", { kVarInt62OneByte + 0x11, '8', '4', '9', ':', 'b', 'e', 'c', 'a', 'u', 's', 'e', ' ', 'I', ' ', 'c', 'a', 'n'} } }; PacketFragments& fragments = VersionHasIetfQuicFrames(framer_.transport_version()) ? packet_ietf : packet; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(fragments)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(0u, visitor_.stream_frames_.size()); EXPECT_EQ("because I can", visitor_.connection_close_frame_.error_details); if (VersionHasIetfQuicFrames(framer_.transport_version())) { EXPECT_EQ(0x1234u, visitor_.connection_close_frame_.transport_close_frame_type); EXPECT_EQ(0xC0DEu, visitor_.connection_close_frame_.wire_error_code); EXPECT_EQ(849u, visitor_.connection_close_frame_.quic_error_code); } else { EXPECT_EQ(0xC0DEu, visitor_.connection_close_frame_.wire_error_code); EXPECT_EQ(0xC0DEu, visitor_.connection_close_frame_.quic_error_code); } ASSERT_EQ(0u, visitor_.ack_frames_.size()); CheckFramingBoundaries(fragments, QUIC_INVALID_CONNECTION_CLOSE_DATA); } TEST_P(QuicFramerTest, ConnectionCloseFrameWithExtractedInfoIgnoreGCuic) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x02}}, {"Unable to read connection close error code.", {0x00, 0x00, 0x00, 0x11}}, {"Unable to read connection close error details.", { 0x0, 0x13, '1', '7', '7', '6', '7', ':', 'b', 'e', 'c', 'a', 'u', 's', 'e', ' ', 'I', ' ', 'c', 'a', 'n'} } }; PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x1c}}, {"Unable to read connection close error code.", {kVarInt62OneByte + 0x11}}, {"Unable to read connection close frame type.", {kVarInt62TwoBytes + 0x12, 0x34 }}, {"Unable to read connection close error details.", { kVarInt62OneByte + 0x13, '1', '7', '7', '6', '7', ':', 'b', 'e', 'c', 'a', 'u', 's', 'e', ' ', 'I', ' ', 'c', 'a', 'n'} } }; PacketFragments& fragments = VersionHasIetfQuicFrames(framer_.transport_version()) ? packet_ietf : packet; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(fragments)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(0u, visitor_.stream_frames_.size()); EXPECT_EQ(0x11u, static_cast<unsigned>( visitor_.connection_close_frame_.wire_error_code)); if (VersionHasIetfQuicFrames(framer_.transport_version())) { EXPECT_EQ(0x1234u, visitor_.connection_close_frame_.transport_close_frame_type); EXPECT_EQ(17767u, visitor_.connection_close_frame_.quic_error_code); EXPECT_EQ("because I can", visitor_.connection_close_frame_.error_details); } else { EXPECT_EQ(0x11u, visitor_.connection_close_frame_.quic_error_code); EXPECT_EQ("17767:because I can", visitor_.connection_close_frame_.error_details); } ASSERT_EQ(0u, visitor_.ack_frames_.size()); CheckFramingBoundaries(fragments, QUIC_INVALID_CONNECTION_CLOSE_DATA); } TEST_P(QuicFramerTest, ApplicationCloseFrame) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x1d}}, {"Unable to read connection close error code.", {kVarInt62TwoBytes + 0x00, 0x11}}, {"Unable to read connection close error details.", { kVarInt62OneByte + 0x0d, 'b', 'e', 'c', 'a', 'u', 's', 'e', ' ', 'I', ' ', 'c', 'a', 'n'} } }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(0u, visitor_.stream_frames_.size()); EXPECT_EQ(IETF_QUIC_APPLICATION_CONNECTION_CLOSE, visitor_.connection_close_frame_.close_type); EXPECT_EQ(122u, visitor_.connection_close_frame_.quic_error_code); EXPECT_EQ(0x11u, visitor_.connection_close_frame_.wire_error_code); EXPECT_EQ("because I can", visitor_.connection_close_frame_.error_details); ASSERT_EQ(0u, visitor_.ack_frames_.size()); CheckFramingBoundaries(packet_ietf, QUIC_INVALID_CONNECTION_CLOSE_DATA); } TEST_P(QuicFramerTest, ApplicationCloseFrameExtract) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x1d}}, {"Unable to read connection close error code.", {kVarInt62OneByte + 0x11}}, {"Unable to read connection close error details.", { kVarInt62OneByte + 0x13, '1', '7', '7', '6', '7', ':', 'b', 'e', 'c', 'a', 'u', 's', 'e', ' ', 'I', ' ', 'c', 'a', 'n'} } }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(0u, visitor_.stream_frames_.size()); EXPECT_EQ(IETF_QUIC_APPLICATION_CONNECTION_CLOSE, visitor_.connection_close_frame_.close_type); EXPECT_EQ(17767u, visitor_.connection_close_frame_.quic_error_code); EXPECT_EQ(0x11u, visitor_.connection_close_frame_.wire_error_code); EXPECT_EQ("because I can", visitor_.connection_close_frame_.error_details); ASSERT_EQ(0u, visitor_.ack_frames_.size()); CheckFramingBoundaries(packet_ietf, QUIC_INVALID_CONNECTION_CLOSE_DATA); } TEST_P(QuicFramerTest, GoAwayFrame) { if (VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x03}}, {"Unable to read go away error code.", {0x00, 0x00, 0x00, 0x09}}, {"Unable to read last good stream id.", {0x01, 0x02, 0x03, 0x04}}, {"Unable to read goaway reason.", { 0x0, 0x0d, 'b', 'e', 'c', 'a', 'u', 's', 'e', ' ', 'I', ' ', 'c', 'a', 'n'} } }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(kStreamId, visitor_.goaway_frame_.last_good_stream_id); EXPECT_EQ(0x9u, visitor_.goaway_frame_.error_code); EXPECT_EQ("because I can", visitor_.goaway_frame_.reason_phrase); CheckFramingBoundaries(packet, QUIC_INVALID_GOAWAY_DATA); } TEST_P(QuicFramerTest, GoAwayFrameWithUnknownErrorCode) { if (VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x03}}, {"Unable to read go away error code.", {0x00, 0x00, 0xC0, 0xDE}}, {"Unable to read last good stream id.", {0x01, 0x02, 0x03, 0x04}}, {"Unable to read goaway reason.", { 0x0, 0x0d, 'b', 'e', 'c', 'a', 'u', 's', 'e', ' ', 'I', ' ', 'c', 'a', 'n'} } }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(kStreamId, visitor_.goaway_frame_.last_good_stream_id); EXPECT_EQ(0xC0DE, visitor_.goaway_frame_.error_code); EXPECT_EQ("because I can", visitor_.goaway_frame_.reason_phrase); CheckFramingBoundaries(packet, QUIC_INVALID_GOAWAY_DATA); } TEST_P(QuicFramerTest, WindowUpdateFrame) { if (VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x04}}, {"Unable to read stream_id.", {0x01, 0x02, 0x03, 0x04}}, {"Unable to read window byte_offset.", {0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(kStreamId, visitor_.window_update_frame_.stream_id); EXPECT_EQ(kStreamOffset, visitor_.window_update_frame_.max_data); CheckFramingBoundaries(packet, QUIC_INVALID_WINDOW_UPDATE_DATA); } TEST_P(QuicFramerTest, MaxDataFrame) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x10}}, {"Can not read MAX_DATA byte-offset", {kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(QuicUtils::GetInvalidStreamId(framer_.transport_version()), visitor_.window_update_frame_.stream_id); EXPECT_EQ(kStreamOffset, visitor_.window_update_frame_.max_data); CheckFramingBoundaries(packet_ietf, QUIC_INVALID_MAX_DATA_FRAME_DATA); } TEST_P(QuicFramerTest, MaxStreamDataFrame) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x11}}, {"Unable to read IETF_MAX_STREAM_DATA frame stream id/count.", {kVarInt62FourBytes + 0x01, 0x02, 0x03, 0x04}}, {"Can not read MAX_STREAM_DATA byte-count", {kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(kStreamId, visitor_.window_update_frame_.stream_id); EXPECT_EQ(kStreamOffset, visitor_.window_update_frame_.max_data); CheckFramingBoundaries(packet_ietf, QUIC_INVALID_MAX_STREAM_DATA_FRAME_DATA); } TEST_P(QuicFramerTest, BlockedFrame) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x05}}, {"Unable to read stream_id.", {0x01, 0x02, 0x03, 0x04}}, }; PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x15}}, {"Unable to read IETF_STREAM_DATA_BLOCKED frame stream id/count.", {kVarInt62FourBytes + 0x01, 0x02, 0x03, 0x04}}, {"Can not read stream blocked offset.", {kVarInt62EightBytes + 0x3a, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54}}, }; PacketFragments& fragments = VersionHasIetfQuicFrames(framer_.transport_version()) ? packet_ietf : packet; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(fragments)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); if (VersionHasIetfQuicFrames(framer_.transport_version())) { EXPECT_EQ(kStreamOffset, visitor_.blocked_frame_.offset); } else { EXPECT_EQ(0u, visitor_.blocked_frame_.offset); } EXPECT_EQ(kStreamId, visitor_.blocked_frame_.stream_id); if (VersionHasIetfQuicFrames(framer_.transport_version())) { CheckFramingBoundaries(fragments, QUIC_INVALID_STREAM_BLOCKED_DATA); } else { CheckFramingBoundaries(fragments, QUIC_INVALID_BLOCKED_DATA); } } TEST_P(QuicFramerTest, PingFrame) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x07, }; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x01, }; QuicEncryptedPacket encrypted( AsChars(VersionHasIetfQuicFrames(framer_.transport_version()) ? packet_ietf : packet), VersionHasIetfQuicFrames(framer_.transport_version()) ? ABSL_ARRAYSIZE(packet_ietf) : ABSL_ARRAYSIZE(packet), false); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(1u, visitor_.ping_frames_.size()); } TEST_P(QuicFramerTest, HandshakeDoneFrame) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x1e, }; if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicEncryptedPacket encrypted(AsChars(packet), ABSL_ARRAYSIZE(packet), false); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(1u, visitor_.handshake_done_frames_.size()); } TEST_P(QuicFramerTest, ParseAckFrequencyFrame) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x40, 0xAF, 0x11, 0x02, 0x80, 0x00, 0x61, 0xA8, 0x01 }; if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicEncryptedPacket encrypted(AsChars(packet), ABSL_ARRAYSIZE(packet), false); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); ASSERT_EQ(1u, visitor_.ack_frequency_frames_.size()); const auto& frame = visitor_.ack_frequency_frames_.front(); EXPECT_EQ(17u, frame->sequence_number); EXPECT_EQ(2u, frame->packet_tolerance); EXPECT_EQ(2'5000u, frame->max_ack_delay.ToMicroseconds()); EXPECT_EQ(true, frame->ignore_order); } TEST_P(QuicFramerTest, ParseResetStreamAtFrame) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x24, 0x00, 0x1e, 0x20, 0x10, }; if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } framer_.set_process_reset_stream_at(true); QuicEncryptedPacket encrypted(AsChars(packet), ABSL_ARRAYSIZE(packet), false); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); ASSERT_EQ(visitor_.reset_stream_at_frames_.size(), 1); const QuicResetStreamAtFrame& frame = *visitor_.reset_stream_at_frames_[0]; EXPECT_EQ(frame.stream_id, 0x00); EXPECT_EQ(frame.error, 0x1e); EXPECT_EQ(frame.final_offset, 0x20); EXPECT_EQ(frame.reliable_offset, 0x10); } TEST_P(QuicFramerTest, ParseInvalidResetStreamAtFrame) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x24, 0x00, 0x1e, 0x20, 0x30, }; if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } framer_.set_process_reset_stream_at(true); QuicEncryptedPacket encrypted(AsChars(packet), ABSL_ARRAYSIZE(packet), false); EXPECT_FALSE(framer_.ProcessPacket(encrypted)); EXPECT_EQ(framer_.error(), QUIC_INVALID_FRAME_DATA); EXPECT_EQ(visitor_.reset_stream_at_frames_.size(), 0); } TEST_P(QuicFramerTest, MessageFrame) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", { 0x21 }}, {"Unable to read message length", {0x07}}, {"Unable to read message data", {'m', 'e', 's', 's', 'a', 'g', 'e'}}, {"", { 0x20 }}, {{}, {'m', 'e', 's', 's', 'a', 'g', 'e', '2'}}, }; PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", { 0x31 }}, {"Unable to read message length", {0x07}}, {"Unable to read message data", {'m', 'e', 's', 's', 'a', 'g', 'e'}}, {"", { 0x30 }}, {{}, {'m', 'e', 's', 's', 'a', 'g', 'e', '2'}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted; if (VersionHasIetfQuicFrames(framer_.transport_version())) { encrypted = AssemblePacketFromFragments(packet_ietf); } else { encrypted = AssemblePacketFromFragments(packet); } EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); ASSERT_EQ(2u, visitor_.message_frames_.size()); EXPECT_EQ(7u, visitor_.message_frames_[0]->message_length); EXPECT_EQ(8u, visitor_.message_frames_[1]->message_length); if (VersionHasIetfQuicFrames(framer_.transport_version())) { CheckFramingBoundaries(packet_ietf, QUIC_INVALID_MESSAGE_DATA); } else { CheckFramingBoundaries(packet, QUIC_INVALID_MESSAGE_DATA); } } TEST_P(QuicFramerTest, IetfStatelessResetPacket) { unsigned char packet[] = { 0x50, 0x01, 0x11, 0x02, 0x22, 0x03, 0x33, 0x04, 0x44, 0x01, 0x11, 0x02, 0x22, 0x03, 0x33, 0x04, 0x44, 0x01, 0x11, 0x02, 0x22, 0x03, 0x33, 0x04, 0x44, 0x01, 0x11, 0x02, 0x22, 0x03, 0x33, 0x04, 0x44, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, }; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicFramerPeer::SetLastSerializedServerConnectionId(&framer_, TestConnectionId(0x33)); decrypter_ = new test::TestDecrypter(); if (framer_.version().KnowsWhichDecrypterToUse()) { framer_.InstallDecrypter( ENCRYPTION_INITIAL, std::make_unique<NullDecrypter>(Perspective::IS_CLIENT)); framer_.InstallDecrypter(ENCRYPTION_ZERO_RTT, std::unique_ptr<QuicDecrypter>(decrypter_)); } else { framer_.SetDecrypter(ENCRYPTION_INITIAL, std::make_unique<NullDecrypter>( Perspective::IS_CLIENT)); framer_.SetAlternativeDecrypter( ENCRYPTION_ZERO_RTT, std::unique_ptr<QuicDecrypter>(decrypter_), false); } QuicEncryptedPacket encrypted(AsChars(packet), ABSL_ARRAYSIZE(packet), false); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); ASSERT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.stateless_reset_packet_.get()); EXPECT_EQ(kTestStatelessResetToken, visitor_.stateless_reset_packet_->stateless_reset_token); } TEST_P(QuicFramerTest, IetfStatelessResetPacketInvalidStatelessResetToken) { unsigned char packet[] = { 0x50, 0x01, 0x11, 0x02, 0x22, 0x03, 0x33, 0x04, 0x44, 0x01, 0x11, 0x02, 0x22, 0x03, 0x33, 0x04, 0x44, 0x01, 0x11, 0x02, 0x22, 0x03, 0x33, 0x04, 0x44, 0x01, 0x11, 0x02, 0x22, 0x03, 0x33, 0x04, 0x44, 0xB6, 0x69, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; QuicFramerPeer::SetLastSerializedServerConnectionId(&framer_, TestConnectionId(0x33)); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); decrypter_ = new test::TestDecrypter(); if (framer_.version().KnowsWhichDecrypterToUse()) { framer_.InstallDecrypter( ENCRYPTION_INITIAL, std::make_unique<NullDecrypter>(Perspective::IS_CLIENT)); framer_.InstallDecrypter(ENCRYPTION_ZERO_RTT, std::unique_ptr<QuicDecrypter>(decrypter_)); } else { framer_.SetDecrypter(ENCRYPTION_INITIAL, std::make_unique<NullDecrypter>( Perspective::IS_CLIENT)); framer_.SetAlternativeDecrypter( ENCRYPTION_ZERO_RTT, std::unique_ptr<QuicDecrypter>(decrypter_), false); } QuicEncryptedPacket encrypted(AsChars(packet), ABSL_ARRAYSIZE(packet), false); EXPECT_FALSE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsError(QUIC_DECRYPTION_FAILURE)); ASSERT_FALSE(visitor_.stateless_reset_packet_); } TEST_P(QuicFramerTest, VersionNegotiationPacketClient) { PacketFragments packet = { {"", {0x8F}}, {"", {0x00, 0x00, 0x00, 0x00}}, {"", {0x05}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"Unable to read supported version in negotiation.", {QUIC_VERSION_BYTES, 'Q', '2', '.', '0'}}, }; PacketFragments packet49 = { {"", {0x8F}}, {"", {0x00, 0x00, 0x00, 0x00}}, {"", {0x08}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x00}}, {"Unable to read supported version in negotiation.", {QUIC_VERSION_BYTES, 'Q', '2', '.', '0'}}, }; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); PacketFragments& fragments = framer_.version().HasLongHeaderLengths() ? packet49 : packet; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(fragments)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); ASSERT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.version_negotiation_packet_.get()); EXPECT_EQ(1u, visitor_.version_negotiation_packet_->versions.size()); EXPECT_EQ(GetParam(), visitor_.version_negotiation_packet_->versions[0]); for (size_t i = 0; i < 4; ++i) { fragments.back().fragment.pop_back(); } CheckFramingBoundaries(fragments, QUIC_INVALID_VERSION_NEGOTIATION_PACKET); } TEST_P(QuicFramerTest, VersionNegotiationPacketServer) { QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); unsigned char packet[] = { 0xFF, 0x00, 0x00, 0x00, 0x00, 0x50, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x11, QUIC_VERSION_BYTES, 'Q', '2', '.', '0', }; unsigned char packet2[] = { 0xFF, 0x00, 0x00, 0x00, 0x00, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x11, 0x00, QUIC_VERSION_BYTES, 'Q', '2', '.', '0', }; unsigned char* p = packet; size_t p_length = ABSL_ARRAYSIZE(packet); if (framer_.version().HasLengthPrefixedConnectionIds()) { p = packet2; p_length = ABSL_ARRAYSIZE(packet2); } QuicEncryptedPacket encrypted(AsChars(p), p_length, false); EXPECT_FALSE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET)); EXPECT_EQ("Server received version negotiation packet.", framer_.detailed_error()); EXPECT_FALSE(visitor_.version_negotiation_packet_.get()); } TEST_P(QuicFramerTest, ParseIetfRetryPacket) { if (!framer_.version().SupportsRetry()) { return; } QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); unsigned char packet[] = { 0xF5, QUIC_VERSION_BYTES, 0x05, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x11, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 'H', 'e', 'l', 'l', 'o', ' ', 't', 'h', 'i', 's', ' ', 'i', 's', ' ', 'R', 'E', 'T', 'R', 'Y', '!', }; unsigned char packet49[] = { 0xF0, QUIC_VERSION_BYTES, 0x00, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x11, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 'H', 'e', 'l', 'l', 'o', ' ', 't', 'h', 'i', 's', ' ', 'i', 's', ' ', 'R', 'E', 'T', 'R', 'Y', '!', }; unsigned char packet_with_tag[] = { 0xF0, QUIC_VERSION_BYTES, 0x00, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x11, 'H', 'e', 'l', 'l', 'o', ' ', 't', 'h', 'i', 's', ' ', 'i', 's', ' ', 'R', 'E', 'T', 'R', 'Y', '!', 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, }; unsigned char* p = packet; size_t p_length = ABSL_ARRAYSIZE(packet); if (framer_.version().UsesTls()) { ReviseFirstByteByVersion(packet_with_tag); p = packet_with_tag; p_length = ABSL_ARRAYSIZE(packet_with_tag); } else if (framer_.version().HasLongHeaderLengths()) { p = packet49; p_length = ABSL_ARRAYSIZE(packet49); } QuicEncryptedPacket encrypted(AsChars(p), p_length, false); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); ASSERT_TRUE(visitor_.on_retry_packet_called_); ASSERT_TRUE(visitor_.retry_new_connection_id_.get()); ASSERT_TRUE(visitor_.retry_token_.get()); if (framer_.version().UsesTls()) { ASSERT_TRUE(visitor_.retry_token_integrity_tag_.get()); static const unsigned char expected_integrity_tag[16] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, }; quiche::test::CompareCharArraysWithHexError( "retry integrity tag", visitor_.retry_token_integrity_tag_->data(), visitor_.retry_token_integrity_tag_->length(), reinterpret_cast<const char*>(expected_integrity_tag), ABSL_ARRAYSIZE(expected_integrity_tag)); ASSERT_TRUE(visitor_.retry_without_tag_.get()); quiche::test::CompareCharArraysWithHexError( "retry without tag", visitor_.retry_without_tag_->data(), visitor_.retry_without_tag_->length(), reinterpret_cast<const char*>(packet_with_tag), 35); } else { ASSERT_TRUE(visitor_.retry_original_connection_id_.get()); EXPECT_EQ(FramerTestConnectionId(), *visitor_.retry_original_connection_id_.get()); } EXPECT_EQ(FramerTestConnectionIdPlusOne(), *visitor_.retry_new_connection_id_.get()); EXPECT_EQ("Hello this is RETRY!", *visitor_.retry_token_.get()); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); visitor_.retry_original_connection_id_.reset(); visitor_.retry_new_connection_id_.reset(); visitor_.retry_token_.reset(); visitor_.retry_token_integrity_tag_.reset(); visitor_.retry_without_tag_.reset(); visitor_.on_retry_packet_called_ = false; EXPECT_FALSE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsError(QUIC_INVALID_PACKET_HEADER)); EXPECT_EQ("Client-initiated RETRY is invalid.", framer_.detailed_error()); EXPECT_FALSE(visitor_.on_retry_packet_called_); EXPECT_FALSE(visitor_.retry_new_connection_id_.get()); EXPECT_FALSE(visitor_.retry_token_.get()); EXPECT_FALSE(visitor_.retry_token_integrity_tag_.get()); EXPECT_FALSE(visitor_.retry_without_tag_.get()); } TEST_P(QuicFramerTest, BuildPaddingFramePacket) { QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicFrames frames = {QuicFrame(QuicPaddingFrame())}; unsigned char packet[kMaxOutgoingPacketSize] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00 }; unsigned char packet_ietf[kMaxOutgoingPacketSize] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00 }; unsigned char* p = packet; if (VersionHasIetfQuicFrames(framer_.transport_version())) { p = packet_ietf; } uint64_t header_size = GetPacketHeaderSize( framer_.transport_version(), kPacket8ByteConnectionId, kPacket0ByteConnectionId, !kIncludeVersion, !kIncludeDiversificationNonce, PACKET_4BYTE_PACKET_NUMBER, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0, 0, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0); memset(p + header_size + 1, 0x00, kMaxOutgoingPacketSize - header_size - 1); std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(p), ABSL_ARRAYSIZE(packet)); } TEST_P(QuicFramerTest, BuildStreamFramePacketWithNewPaddingFrame) { QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicStreamFrame stream_frame(kStreamId, true, kStreamOffset, absl::string_view("hello world!")); QuicPaddingFrame padding_frame(2); QuicFrames frames = {QuicFrame(padding_frame), QuicFrame(stream_frame), QuicFrame(padding_frame)}; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x00, 0x00, 0xFF, 0x01, 0x02, 0x03, 0x04, 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, 0x00, 0x0c, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', 0x00, 0x00, }; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x00, 0x00, 0x08 | 0x01 | 0x02 | 0x04, kVarInt62FourBytes + 0x01, 0x02, 0x03, 0x04, kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, kVarInt62OneByte + 0x0c, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', 0x00, 0x00, }; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); unsigned char* p = packet; size_t p_size = ABSL_ARRAYSIZE(packet); if (VersionHasIetfQuicFrames(framer_.transport_version())) { p = packet_ietf; p_size = ABSL_ARRAYSIZE(packet_ietf); } QuicEncryptedPacket encrypted(AsChars(p), p_size, false); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(p), p_size); } TEST_P(QuicFramerTest, Build4ByteSequenceNumberPaddingFramePacket) { QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number_length = PACKET_4BYTE_PACKET_NUMBER; header.packet_number = kPacketNumber; QuicFrames frames = {QuicFrame(QuicPaddingFrame())}; unsigned char packet[kMaxOutgoingPacketSize] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00 }; unsigned char packet_ietf[kMaxOutgoingPacketSize] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00 }; unsigned char* p = packet; if (VersionHasIetfQuicFrames(framer_.transport_version())) { p = packet_ietf; } uint64_t header_size = GetPacketHeaderSize( framer_.transport_version(), kPacket8ByteConnectionId, kPacket0ByteConnectionId, !kIncludeVersion, !kIncludeDiversificationNonce, PACKET_4BYTE_PACKET_NUMBER, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0, 0, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0); memset(p + header_size + 1, 0x00, kMaxOutgoingPacketSize - header_size - 1); std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(p), ABSL_ARRAYSIZE(packet)); } TEST_P(QuicFramerTest, Build2ByteSequenceNumberPaddingFramePacket) { QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number_length = PACKET_2BYTE_PACKET_NUMBER; header.packet_number = kPacketNumber; QuicFrames frames = {QuicFrame(QuicPaddingFrame())}; unsigned char packet[kMaxOutgoingPacketSize] = { 0x41, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x56, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00 }; unsigned char packet_ietf[kMaxOutgoingPacketSize] = { 0x41, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x56, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00 }; unsigned char* p = packet; if (VersionHasIetfQuicFrames(framer_.transport_version())) { p = packet_ietf; } uint64_t header_size = GetPacketHeaderSize( framer_.transport_version(), kPacket8ByteConnectionId, kPacket0ByteConnectionId, !kIncludeVersion, !kIncludeDiversificationNonce, PACKET_2BYTE_PACKET_NUMBER, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0, 0, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0); memset(p + header_size + 1, 0x00, kMaxOutgoingPacketSize - header_size - 1); std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(p), ABSL_ARRAYSIZE(packet)); } TEST_P(QuicFramerTest, Build1ByteSequenceNumberPaddingFramePacket) { QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number_length = PACKET_1BYTE_PACKET_NUMBER; header.packet_number = kPacketNumber; QuicFrames frames = {QuicFrame(QuicPaddingFrame())}; unsigned char packet[kMaxOutgoingPacketSize] = { 0x40, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00 }; unsigned char packet_ietf[kMaxOutgoingPacketSize] = { 0x40, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00 }; unsigned char* p = packet; if (VersionHasIetfQuicFrames(framer_.transport_version())) { p = packet_ietf; } uint64_t header_size = GetPacketHeaderSize( framer_.transport_version(), kPacket8ByteConnectionId, kPacket0ByteConnectionId, !kIncludeVersion, !kIncludeDiversificationNonce, PACKET_1BYTE_PACKET_NUMBER, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0, 0, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0); memset(p + header_size + 1, 0x00, kMaxOutgoingPacketSize - header_size - 1); std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(p), ABSL_ARRAYSIZE(packet)); } TEST_P(QuicFramerTest, BuildStreamFramePacket) { QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; if (QuicVersionHasLongHeaderLengths(framer_.transport_version())) { header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2; } QuicStreamFrame stream_frame(kStreamId, true, kStreamOffset, absl::string_view("hello world!")); QuicFrames frames = {QuicFrame(stream_frame)}; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0xDF, 0x01, 0x02, 0x03, 0x04, 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', }; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x08 | 0x01 | 0x04, kVarInt62FourBytes + 0x01, 0x02, 0x03, 0x04, kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', }; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); unsigned char* p = packet; size_t p_size = ABSL_ARRAYSIZE(packet); if (VersionHasIetfQuicFrames(framer_.transport_version())) { p = packet_ietf; p_size = ABSL_ARRAYSIZE(packet_ietf); } quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(p), p_size); } TEST_P(QuicFramerTest, BuildStreamFramePacketWithVersionFlag) { QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = true; header.long_packet_type = ZERO_RTT_PROTECTED; header.packet_number = kPacketNumber; if (QuicVersionHasLongHeaderLengths(framer_.transport_version())) { header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2; } QuicStreamFrame stream_frame(kStreamId, true, kStreamOffset, absl::string_view("hello world!")); QuicFrames frames = {QuicFrame(stream_frame)}; unsigned char packet[] = { 0xD3, QUIC_VERSION_BYTES, 0x50, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0xDF, 0x01, 0x02, 0x03, 0x04, 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', }; unsigned char packet49[] = { 0xD3, QUIC_VERSION_BYTES, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x40, 0x1D, 0x12, 0x34, 0x56, 0x78, 0xDF, 0x01, 0x02, 0x03, 0x04, 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', }; unsigned char packet_ietf[] = { 0xD3, QUIC_VERSION_BYTES, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x40, 0x1D, 0x12, 0x34, 0x56, 0x78, 0x08 | 0x01 | 0x04, kVarInt62FourBytes + 0x01, 0x02, 0x03, 0x04, kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', }; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); unsigned char* p = packet; size_t p_size = ABSL_ARRAYSIZE(packet); if (VersionHasIetfQuicFrames(framer_.transport_version())) { ReviseFirstByteByVersion(packet_ietf); p = packet_ietf; p_size = ABSL_ARRAYSIZE(packet_ietf); } else if (framer_.version().HasLongHeaderLengths()) { p = packet49; p_size = ABSL_ARRAYSIZE(packet49); } quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(p), p_size); } TEST_P(QuicFramerTest, BuildCryptoFramePacket) { if (!QuicVersionUsesCryptoFrames(framer_.transport_version())) { return; } QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; SimpleDataProducer data_producer; framer_.set_data_producer(&data_producer); absl::string_view crypto_frame_contents("hello world!"); QuicCryptoFrame crypto_frame(ENCRYPTION_INITIAL, kStreamOffset, crypto_frame_contents.length()); data_producer.SaveCryptoData(ENCRYPTION_INITIAL, kStreamOffset, crypto_frame_contents); QuicFrames frames = {QuicFrame(&crypto_frame)}; unsigned char packet48[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x08, kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, kVarInt62OneByte + 12, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', }; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x06, kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, kVarInt62OneByte + 12, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', }; unsigned char* packet = packet48; size_t packet_size = ABSL_ARRAYSIZE(packet48); if (framer_.version().HasIetfQuicFrames()) { packet = packet_ietf; packet_size = ABSL_ARRAYSIZE(packet_ietf); } std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError("constructed packet", data->data(), data->length(), AsChars(packet), packet_size); } TEST_P(QuicFramerTest, CryptoFrame) { if (!QuicVersionUsesCryptoFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet48 = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x08}}, {"", {kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54}}, {"Invalid data length.", {kVarInt62OneByte + 12}}, {"Unable to read frame data.", {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!'}}, }; PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x06}}, {"", {kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54}}, {"Invalid data length.", {kVarInt62OneByte + 12}}, {"Unable to read frame data.", {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!'}}, }; PacketFragments& fragments = framer_.version().HasIetfQuicFrames() ? packet_ietf : packet48; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(fragments)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); ASSERT_EQ(1u, visitor_.crypto_frames_.size()); QuicCryptoFrame* frame = visitor_.crypto_frames_[0].get(); EXPECT_EQ(ENCRYPTION_FORWARD_SECURE, frame->level); EXPECT_EQ(kStreamOffset, frame->offset); EXPECT_EQ("hello world!", std::string(frame->data_buffer, frame->data_length)); CheckFramingBoundaries(fragments, QUIC_INVALID_FRAME_DATA); } TEST_P(QuicFramerTest, BuildOldVersionNegotiationPacket) { SetQuicFlag(quic_disable_version_negotiation_grease_randomness, true); unsigned char packet[] = { 0x0D, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0xDA, 0x5A, 0x3A, 0x3A, QUIC_VERSION_BYTES, }; QuicConnectionId connection_id = FramerTestConnectionId(); std::unique_ptr<QuicEncryptedPacket> data( QuicFramer::BuildVersionNegotiationPacket( connection_id, EmptyQuicConnectionId(), false, false, SupportedVersions(GetParam()))); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet), ABSL_ARRAYSIZE(packet)); } TEST_P(QuicFramerTest, BuildVersionNegotiationPacket) { SetQuicFlag(quic_disable_version_negotiation_grease_randomness, true); unsigned char packet[] = { 0xC0, 0x00, 0x00, 0x00, 0x00, 0x05, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0xDA, 0x5A, 0x3A, 0x3A, QUIC_VERSION_BYTES, }; unsigned char packet49[] = { 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0xDA, 0x5A, 0x3A, 0x3A, QUIC_VERSION_BYTES, }; unsigned char* p = packet; size_t p_size = ABSL_ARRAYSIZE(packet); if (framer_.version().HasLongHeaderLengths()) { p = packet49; p_size = ABSL_ARRAYSIZE(packet49); } QuicConnectionId connection_id = FramerTestConnectionId(); std::unique_ptr<QuicEncryptedPacket> data( QuicFramer::BuildVersionNegotiationPacket( connection_id, EmptyQuicConnectionId(), true, framer_.version().HasLengthPrefixedConnectionIds(), SupportedVersions(GetParam()))); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(p), p_size); } TEST_P(QuicFramerTest, BuildVersionNegotiationPacketWithClientConnectionId) { if (!framer_.version().SupportsClientConnectionIds()) { return; } SetQuicFlag(quic_disable_version_negotiation_grease_randomness, true); unsigned char packet[] = { 0xC0, 0x00, 0x00, 0x00, 0x00, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x11, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0xDA, 0x5A, 0x3A, 0x3A, QUIC_VERSION_BYTES, }; QuicConnectionId server_connection_id = FramerTestConnectionId(); QuicConnectionId client_connection_id = FramerTestConnectionIdPlusOne(); std::unique_ptr<QuicEncryptedPacket> data( QuicFramer::BuildVersionNegotiationPacket( server_connection_id, client_connection_id, true, true, SupportedVersions(GetParam()))); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet), ABSL_ARRAYSIZE(packet)); } TEST_P(QuicFramerTest, BuildAckFramePacketOneAckBlock) { QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicAckFrame ack_frame = InitAckFrame(kSmallLargestObserved); ack_frame.ack_delay_time = QuicTime::Delta::Zero(); QuicFrames frames = {QuicFrame(&ack_frame)}; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x45, 0x12, 0x34, 0x00, 0x00, 0x12, 0x34, 0x00, }; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x02, kVarInt62TwoBytes + 0x12, 0x34, kVarInt62OneByte + 0x00, kVarInt62OneByte + 0x00, kVarInt62TwoBytes + 0x12, 0x33, }; unsigned char* p = packet; size_t p_size = ABSL_ARRAYSIZE(packet); if (VersionHasIetfQuicFrames(framer_.transport_version())) { p = packet_ietf; p_size = ABSL_ARRAYSIZE(packet_ietf); } std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(p), p_size); } TEST_P(QuicFramerTest, BuildAckReceiveTimestampsFrameMultipleRanges) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicAckFrame ack_frame = InitAckFrame(kSmallLargestObserved); ack_frame.received_packet_times = PacketTimeVector{ {kSmallLargestObserved - 22, CreationTimePlus(0x29ffdddd)}, {kSmallLargestObserved - 21, CreationTimePlus(0x29ffdedd)}, {kSmallLargestObserved - 11, CreationTimePlus(0x29ffdeed)}, {kSmallLargestObserved - 4, CreationTimePlus(0x29ffeeed)}, {kSmallLargestObserved - 3, CreationTimePlus(0x29ffeeee)}, {kSmallLargestObserved - 2, CreationTimePlus(0x29ffffff)}, }; ack_frame.ack_delay_time = QuicTime::Delta::Zero(); QuicFrames frames = {QuicFrame(&ack_frame)}; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x22, kVarInt62TwoBytes + 0x12, 0x34, kVarInt62OneByte + 0x00, kVarInt62OneByte + 0x00, kVarInt62TwoBytes + 0x12, 0x33, kVarInt62OneByte + 0x03, kVarInt62OneByte + 0x02, kVarInt62OneByte + 0x03, kVarInt62FourBytes + 0x29, 0xff, 0xff, 0xff, kVarInt62TwoBytes + 0x11, 0x11, kVarInt62OneByte + 0x01, kVarInt62OneByte + 0x05, kVarInt62OneByte + 0x01, kVarInt62TwoBytes + 0x10, 0x00, kVarInt62OneByte + 0x08, kVarInt62OneByte + 0x02, kVarInt62OneByte + 0x10, kVarInt62TwoBytes + 0x01, 0x00, }; framer_.set_process_timestamps(true); framer_.set_max_receive_timestamps_per_ack(8); std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet_ietf), ABSL_ARRAYSIZE(packet_ietf)); } TEST_P(QuicFramerTest, BuildAckReceiveTimestampsFrameExceedsMaxTimestamps) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicAckFrame ack_frame = InitAckFrame(kSmallLargestObserved); ack_frame.received_packet_times = PacketTimeVector{ {kSmallLargestObserved - 20, CreationTimePlus(0x29ffdddd)}, {kSmallLargestObserved - 10, CreationTimePlus(0x29ffdedd)}, {kSmallLargestObserved - 9, CreationTimePlus(0x29ffdeed)}, {kSmallLargestObserved - 2, CreationTimePlus(0x29ffeeed)}, {kSmallLargestObserved - 1, CreationTimePlus(0x29ffeeee)}, {kSmallLargestObserved, CreationTimePlus(0x29ffffff)}, }; ack_frame.ack_delay_time = QuicTime::Delta::Zero(); QuicFrames frames = {QuicFrame(&ack_frame)}; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x22, kVarInt62TwoBytes + 0x12, 0x34, kVarInt62OneByte + 0x00, kVarInt62OneByte + 0x00, kVarInt62TwoBytes + 0x12, 0x33, kVarInt62OneByte + 0x02, kVarInt62OneByte + 0x00, kVarInt62OneByte + 0x03, kVarInt62FourBytes + 0x29, 0xff, 0xff, 0xff, kVarInt62TwoBytes + 0x11, 0x11, kVarInt62OneByte + 0x01, kVarInt62OneByte + 0x05, kVarInt62OneByte + 0x01, kVarInt62TwoBytes + 0x10, 0x00, }; framer_.set_process_timestamps(true); framer_.set_max_receive_timestamps_per_ack(4); std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet_ietf), ABSL_ARRAYSIZE(packet_ietf)); } TEST_P(QuicFramerTest, BuildAckReceiveTimestampsFrameWithExponentEncoding) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicAckFrame ack_frame = InitAckFrame(kSmallLargestObserved); ack_frame.received_packet_times = PacketTimeVector{ {kSmallLargestObserved - 12, CreationTimePlus((0x06c00 << 3) + 0x03)}, {kSmallLargestObserved - 11, CreationTimePlus((0x28e00 << 3) + 0x00)}, {kSmallLargestObserved - 5, CreationTimePlus((0x29f00 << 3) + 0x00)}, {kSmallLargestObserved - 4, CreationTimePlus((0x29f00 << 3) + 0x01)}, {kSmallLargestObserved - 3, CreationTimePlus((0x29f00 << 3) + 0x02)}, {kSmallLargestObserved - 2, CreationTimePlus((0x29f00 << 3) + 0x03)}, }; ack_frame.ack_delay_time = QuicTime::Delta::Zero(); QuicFrames frames = {QuicFrame(&ack_frame)}; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x22, kVarInt62TwoBytes + 0x12, 0x34, kVarInt62OneByte + 0x00, kVarInt62OneByte + 0x00, kVarInt62TwoBytes + 0x12, 0x33, kVarInt62OneByte + 0x02, kVarInt62OneByte + 0x02, kVarInt62OneByte + 0x04, kVarInt62FourBytes + 0x00, 0x02, 0x9f, 0x01, kVarInt62OneByte + 0x00, kVarInt62OneByte + 0x00, kVarInt62OneByte + 0x01, kVarInt62OneByte + 0x04, kVarInt62OneByte + 0x02, kVarInt62TwoBytes + 0x11, 0x00, kVarInt62FourBytes + 0x00, 0x02, 0x21, 0xff, }; framer_.set_process_timestamps(true); framer_.set_max_receive_timestamps_per_ack(8); framer_.set_receive_timestamps_exponent(3); std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet_ietf), ABSL_ARRAYSIZE(packet_ietf)); } TEST_P(QuicFramerTest, BuildAndProcessAckReceiveTimestampsWithMultipleRanges) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } framer_.InstallDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(0)); framer_.SetKeyUpdateSupportForConnection(true); framer_.set_process_timestamps(true); framer_.set_max_receive_timestamps_per_ack(8); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicAckFrame ack_frame = InitAckFrame(kSmallLargestObserved); ack_frame.received_packet_times = PacketTimeVector{ {kSmallLargestObserved - 1201, CreationTimePlus(0x8bcaef234)}, {kSmallLargestObserved - 1200, CreationTimePlus(0x8bcdef123)}, {kSmallLargestObserved - 1000, CreationTimePlus(0xaacdef123)}, {kSmallLargestObserved - 4, CreationTimePlus(0xabcdea125)}, {kSmallLargestObserved - 2, CreationTimePlus(0xabcdee124)}, {kSmallLargestObserved - 1, CreationTimePlus(0xabcdef123)}, {kSmallLargestObserved, CreationTimePlus(0xabcdef123)}, }; ack_frame.ack_delay_time = QuicTime::Delta::Zero(); QuicFrames frames = {QuicFrame(&ack_frame)}; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); std::unique_ptr<QuicEncryptedPacket> encrypted( EncryptPacketWithTagAndPhase(*data, 0, false)); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); const QuicAckFrame& frame = *visitor_.ack_frames_[0]; EXPECT_THAT(frame.received_packet_times, ContainerEq(PacketTimeVector{ {kSmallLargestObserved, CreationTimePlus(0xabcdef123)}, {kSmallLargestObserved - 1, CreationTimePlus(0xabcdef123)}, {kSmallLargestObserved - 2, CreationTimePlus(0xabcdee124)}, {kSmallLargestObserved - 4, CreationTimePlus(0xabcdea125)}, {kSmallLargestObserved - 1000, CreationTimePlus(0xaacdef123)}, {kSmallLargestObserved - 1200, CreationTimePlus(0x8bcdef123)}, {kSmallLargestObserved - 1201, CreationTimePlus(0x8bcaef234)}, })); } TEST_P(QuicFramerTest, BuildAndProcessAckReceiveTimestampsExceedsMaxTimestamps) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } framer_.InstallDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(0)); framer_.SetKeyUpdateSupportForConnection(true); framer_.set_process_timestamps(true); framer_.set_max_receive_timestamps_per_ack(2); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicAckFrame ack_frame = InitAckFrame(kSmallLargestObserved); ack_frame.received_packet_times = PacketTimeVector{ {kSmallLargestObserved - 1201, CreationTimePlus(0x8bcaef234)}, {kSmallLargestObserved - 1200, CreationTimePlus(0x8bcdef123)}, {kSmallLargestObserved - 1000, CreationTimePlus(0xaacdef123)}, {kSmallLargestObserved - 5, CreationTimePlus(0xabcdea125)}, {kSmallLargestObserved - 3, CreationTimePlus(0xabcded124)}, {kSmallLargestObserved - 2, CreationTimePlus(0xabcdee124)}, {kSmallLargestObserved - 1, CreationTimePlus(0xabcdef123)}, }; ack_frame.ack_delay_time = QuicTime::Delta::Zero(); QuicFrames frames = {QuicFrame(&ack_frame)}; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); std::unique_ptr<QuicEncryptedPacket> encrypted( EncryptPacketWithTagAndPhase(*data, 0, false)); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); const QuicAckFrame& frame = *visitor_.ack_frames_[0]; EXPECT_THAT(frame.received_packet_times, ContainerEq(PacketTimeVector{ {kSmallLargestObserved - 1, CreationTimePlus(0xabcdef123)}, {kSmallLargestObserved - 2, CreationTimePlus(0xabcdee124)}, })); } TEST_P(QuicFramerTest, BuildAndProcessAckReceiveTimestampsWithExponentNoTruncation) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } framer_.InstallDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(0)); framer_.SetKeyUpdateSupportForConnection(true); framer_.set_process_timestamps(true); framer_.set_max_receive_timestamps_per_ack(8); framer_.set_receive_timestamps_exponent(3); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicAckFrame ack_frame = InitAckFrame(kSmallLargestObserved); ack_frame.received_packet_times = PacketTimeVector{ {kSmallLargestObserved - 8, CreationTimePlus(0x1add << 3)}, {kSmallLargestObserved - 7, CreationTimePlus(0x29ed << 3)}, {kSmallLargestObserved - 3, CreationTimePlus(0x29fe << 3)}, {kSmallLargestObserved - 2, CreationTimePlus(0x29ff << 3)}, }; ack_frame.ack_delay_time = QuicTime::Delta::Zero(); QuicFrames frames = {QuicFrame(&ack_frame)}; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); std::unique_ptr<QuicEncryptedPacket> encrypted( EncryptPacketWithTagAndPhase(*data, 0, false)); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); const QuicAckFrame& frame = *visitor_.ack_frames_[0]; EXPECT_THAT(frame.received_packet_times, ContainerEq(PacketTimeVector{ {kSmallLargestObserved - 2, CreationTimePlus(0x29ff << 3)}, {kSmallLargestObserved - 3, CreationTimePlus(0x29fe << 3)}, {kSmallLargestObserved - 7, CreationTimePlus(0x29ed << 3)}, {kSmallLargestObserved - 8, CreationTimePlus(0x1add << 3)}, })); } TEST_P(QuicFramerTest, BuildAndProcessAckReceiveTimestampsWithExponentTruncation) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } framer_.InstallDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(0)); framer_.SetKeyUpdateSupportForConnection(true); framer_.set_process_timestamps(true); framer_.set_max_receive_timestamps_per_ack(8); framer_.set_receive_timestamps_exponent(3); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicAckFrame ack_frame = InitAckFrame(kSmallLargestObserved); ack_frame.received_packet_times = PacketTimeVector{ {kSmallLargestObserved - 10, CreationTimePlus((0x1001 << 3) + 1)}, {kSmallLargestObserved - 9, CreationTimePlus((0x2995 << 3) - 1)}, {kSmallLargestObserved - 8, CreationTimePlus((0x2995 << 3) + 0)}, {kSmallLargestObserved - 7, CreationTimePlus((0x2995 << 3) + 1)}, {kSmallLargestObserved - 6, CreationTimePlus((0x2995 << 3) + 2)}, {kSmallLargestObserved - 3, CreationTimePlus((0x2995 << 3) + 3)}, {kSmallLargestObserved - 2, CreationTimePlus((0x2995 << 3) + 4)}, }; ack_frame.ack_delay_time = QuicTime::Delta::Zero(); QuicFrames frames = {QuicFrame(&ack_frame)}; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); std::unique_ptr<QuicEncryptedPacket> encrypted( EncryptPacketWithTagAndPhase(*data, 0, false)); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); const QuicAckFrame& frame = *visitor_.ack_frames_[0]; EXPECT_THAT(frame.received_packet_times, ContainerEq(PacketTimeVector{ {kSmallLargestObserved - 2, CreationTimePlus(0x2996 << 3)}, {kSmallLargestObserved - 3, CreationTimePlus(0x2996 << 3)}, {kSmallLargestObserved - 6, CreationTimePlus(0x2996 << 3)}, {kSmallLargestObserved - 7, CreationTimePlus(0x2996 << 3)}, {kSmallLargestObserved - 8, CreationTimePlus(0x2995 << 3)}, {kSmallLargestObserved - 9, CreationTimePlus(0x2995 << 3)}, {kSmallLargestObserved - 10, CreationTimePlus(0x1002 << 3)}, })); } TEST_P(QuicFramerTest, AckReceiveTimestamps) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } framer_.InstallDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(0)); framer_.SetKeyUpdateSupportForConnection(true); framer_.set_process_timestamps(true); framer_.set_max_receive_timestamps_per_ack(8); framer_.set_receive_timestamps_exponent(3); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicAckFrame ack_frame = InitAckFrame(kSmallLargestObserved); ack_frame.received_packet_times = PacketTimeVector{ {kSmallLargestObserved - 5, CreationTimePlus((0x29ff << 3))}, {kSmallLargestObserved - 4, CreationTimePlus((0x29ff << 3))}, {kSmallLargestObserved - 3, CreationTimePlus((0x29ff << 3))}, {kSmallLargestObserved - 2, CreationTimePlus((0x29ff << 3))}, }; ack_frame.ack_delay_time = QuicTime::Delta::Zero(); QuicFrames frames = {QuicFrame(&ack_frame)}; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); std::unique_ptr<QuicEncryptedPacket> encrypted( EncryptPacketWithTagAndPhase(*data, 0, false)); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); const QuicAckFrame& frame = *visitor_.ack_frames_[0]; EXPECT_THAT(frame.received_packet_times, ContainerEq(PacketTimeVector{ {kSmallLargestObserved - 2, CreationTimePlus(0x29ff << 3)}, {kSmallLargestObserved - 3, CreationTimePlus(0x29ff << 3)}, {kSmallLargestObserved - 4, CreationTimePlus(0x29ff << 3)}, {kSmallLargestObserved - 5, CreationTimePlus(0x29ff << 3)}, })); } TEST_P(QuicFramerTest, AckReceiveTimestampsPacketOutOfOrder) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } framer_.InstallDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(0)); framer_.SetKeyUpdateSupportForConnection(true); framer_.set_process_timestamps(true); framer_.set_max_receive_timestamps_per_ack(8); framer_.set_receive_timestamps_exponent(3); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicAckFrame ack_frame = InitAckFrame(kSmallLargestObserved); ack_frame.received_packet_times = PacketTimeVector{ {kSmallLargestObserved - 5, CreationTimePlus((0x29ff << 3))}, {kSmallLargestObserved - 2, CreationTimePlus((0x29ff << 3))}, {kSmallLargestObserved - 4, CreationTimePlus((0x29ff << 3))}, {kSmallLargestObserved - 3, CreationTimePlus((0x29ff << 3))}, }; ack_frame.ack_delay_time = QuicTime::Delta::Zero(); QuicFrames frames = {QuicFrame(&ack_frame)}; EXPECT_QUIC_BUG(BuildDataPacket(header, frames), "Packet number and/or receive time not in order."); } TEST_P(QuicFramerTest, IetfAckReceiveTimestampsTruncate) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } framer_.InstallDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(0)); framer_.SetKeyUpdateSupportForConnection(true); framer_.set_process_timestamps(true); framer_.set_max_receive_timestamps_per_ack(8192); framer_.set_receive_timestamps_exponent(3); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicAckFrame ack_frame = InitAckFrame(kSmallLargestObserved); for (QuicPacketNumber i(1); i <= kSmallLargestObserved; i += 2) { ack_frame.received_packet_times.push_back( {i, CreationTimePlus((0x29ff << 3))}); } ack_frame.ack_delay_time = QuicTime::Delta::Zero(); QuicFrames frames = {QuicFrame(&ack_frame)}; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); std::unique_ptr<QuicEncryptedPacket> encrypted( EncryptPacketWithTagAndPhase(*data, 0, false)); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); const QuicAckFrame& frame = *visitor_.ack_frames_[0]; EXPECT_TRUE(frame.received_packet_times.empty()); } TEST_P(QuicFramerTest, IetfAckReceiveTimestampsAckRangeTruncation) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); framer_.set_process_timestamps(true); framer_.set_max_receive_timestamps_per_ack(8); framer_.set_receive_timestamps_exponent(3); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicAckFrame ack_frame; ack_frame = MakeAckFrameWithGaps(0xffffffff, 200, kMaxIetfVarInt); ack_frame.received_packet_times = PacketTimeVector{ {QuicPacketNumber(kMaxIetfVarInt) - 2, CreationTimePlus((0x29ff << 3))}, }; QuicFrames frames = {QuicFrame(&ack_frame)}; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); std::unique_ptr<QuicPacket> raw_ack_packet(BuildDataPacket(header, frames)); ASSERT_TRUE(raw_ack_packet != nullptr); char buffer[kMaxOutgoingPacketSize]; size_t encrypted_length = framer_.EncryptPayload(ENCRYPTION_INITIAL, header.packet_number, *raw_ack_packet, buffer, kMaxOutgoingPacketSize); ASSERT_NE(0u, encrypted_length); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); ASSERT_TRUE(framer_.ProcessPacket( QuicEncryptedPacket(buffer, encrypted_length, false))); ASSERT_EQ(1u, visitor_.ack_frames_.size()); QuicAckFrame& processed_ack_frame = *visitor_.ack_frames_[0]; EXPECT_EQ(QuicPacketNumber(kMaxIetfVarInt), LargestAcked(processed_ack_frame)); ASSERT_LT(processed_ack_frame.packets.NumPacketsSlow(), ack_frame.packets.NumIntervals()); EXPECT_EQ(158u, processed_ack_frame.packets.NumPacketsSlow()); EXPECT_LT(processed_ack_frame.packets.NumIntervals(), ack_frame.packets.NumIntervals()); EXPECT_EQ(QuicPacketNumber(kMaxIetfVarInt), processed_ack_frame.packets.Max()); EXPECT_FALSE(processed_ack_frame.received_packet_times.empty()); } TEST_P(QuicFramerTest, BuildAckFramePacketOneAckBlockMaxLength) { QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicAckFrame ack_frame = InitAckFrame(kPacketNumber); ack_frame.ack_delay_time = QuicTime::Delta::Zero(); QuicFrames frames = {QuicFrame(&ack_frame)}; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x4A, 0x12, 0x34, 0x56, 0x78, 0x00, 0x00, 0x12, 0x34, 0x56, 0x78, 0x00, }; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x02, kVarInt62FourBytes + 0x12, 0x34, 0x56, 0x78, kVarInt62OneByte + 0x00, kVarInt62OneByte + 0x00, kVarInt62FourBytes + 0x12, 0x34, 0x56, 0x77, }; unsigned char* p = packet; size_t p_size = ABSL_ARRAYSIZE(packet); if (VersionHasIetfQuicFrames(framer_.transport_version())) { p = packet_ietf; p_size = ABSL_ARRAYSIZE(packet_ietf); } std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(p), p_size); } TEST_P(QuicFramerTest, BuildAckFramePacketMultipleAckBlocks) { QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicAckFrame ack_frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)}, {QuicPacketNumber(10), QuicPacketNumber(500)}, {QuicPacketNumber(900), kSmallMissingPacket}, {kSmallMissingPacket + 1, kSmallLargestObserved + 1}}); ack_frame.ack_delay_time = QuicTime::Delta::Zero(); QuicFrames frames = {QuicFrame(&ack_frame)}; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x65, 0x12, 0x34, 0x00, 0x00, 0x04, 0x00, 0x01, 0x01, 0x0e, 0xaf, 0xff, 0x00, 0x00, 0x91, 0x01, 0xea, 0x05, 0x00, 0x04, 0x00, }; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x02, kVarInt62TwoBytes + 0x12, 0x34, kVarInt62OneByte + 0x00, kVarInt62OneByte + 0x03, kVarInt62OneByte + 0x00, kVarInt62OneByte + 0x00, kVarInt62TwoBytes + 0x0e, 0xae, kVarInt62TwoBytes + 0x01, 0x8f, kVarInt62TwoBytes + 0x01, 0xe9, kVarInt62OneByte + 0x04, kVarInt62OneByte + 0x03, }; unsigned char* p = packet; size_t p_size = ABSL_ARRAYSIZE(packet); if (VersionHasIetfQuicFrames(framer_.transport_version())) { p = packet_ietf; p_size = ABSL_ARRAYSIZE(packet_ietf); } std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(p), p_size); } TEST_P(QuicFramerTest, BuildAckFramePacketMaxAckBlocks) { QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicAckFrame ack_frame; ack_frame.largest_acked = kSmallLargestObserved; ack_frame.ack_delay_time = QuicTime::Delta::Zero(); for (size_t i = 2; i < 2 * 300; i += 2) { ack_frame.packets.Add(QuicPacketNumber(i)); } ack_frame.packets.AddRange(QuicPacketNumber(600), kSmallLargestObserved + 1); QuicFrames frames = {QuicFrame(&ack_frame)}; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x65, 0x12, 0x34, 0x00, 0x00, 0xff, 0x0f, 0xdd, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x01, 0x00, 0x01, 0x00, }; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x02, kVarInt62TwoBytes + 0x12, 0x34, kVarInt62OneByte + 0x00, kVarInt62TwoBytes + 0x01, 0x2b, kVarInt62TwoBytes + 0x0f, 0xdc, #define V99AddedBLOCK kVarInt62OneByte + 0x00, kVarInt62OneByte + 0x00 V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, V99AddedBLOCK, #undef V99AddedBLOCK }; unsigned char* p = packet; size_t p_size = ABSL_ARRAYSIZE(packet); if (VersionHasIetfQuicFrames(framer_.transport_version())) { p = packet_ietf; p_size = ABSL_ARRAYSIZE(packet_ietf); } std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(p), p_size); } TEST_P(QuicFramerTest, BuildRstFramePacketQuic) { QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicRstStreamFrame rst_frame; rst_frame.stream_id = kStreamId; if (VersionHasIetfQuicFrames(framer_.transport_version())) { rst_frame.ietf_error_code = 0x01; } else { rst_frame.error_code = static_cast<QuicRstStreamErrorCode>(0x05060708); } rst_frame.byte_offset = 0x0807060504030201; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x01, 0x01, 0x02, 0x03, 0x04, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x05, 0x06, 0x07, 0x08, }; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x04, kVarInt62FourBytes + 0x01, 0x02, 0x03, 0x04, kVarInt62OneByte + 0x01, kVarInt62EightBytes + 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01 }; QuicFrames frames = {QuicFrame(&rst_frame)}; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); unsigned char* p = packet; size_t p_size = ABSL_ARRAYSIZE(packet); if (VersionHasIetfQuicFrames(framer_.transport_version())) { p = packet_ietf; p_size = ABSL_ARRAYSIZE(packet_ietf); } QuicEncryptedPacket encrypted(AsChars(p), p_size, false); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(p), p_size); } TEST_P(QuicFramerTest, BuildCloseFramePacket) { QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicConnectionCloseFrame close_frame(framer_.transport_version(), QUIC_INTERNAL_ERROR, NO_IETF_QUIC_ERROR, "because I can", 0x05); QuicFrames frames = {QuicFrame(&close_frame)}; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x0d, 'b', 'e', 'c', 'a', 'u', 's', 'e', ' ', 'I', ' ', 'c', 'a', 'n', }; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x1c, kVarInt62OneByte + 0x01, kVarInt62OneByte + 0x05, kVarInt62OneByte + 0x0f, '1', ':', 'b', 'e', 'c', 'a', 'u', 's', 'e', ' ', 'I', ' ', 'c', 'a', 'n', }; unsigned char* p = packet; size_t p_size = ABSL_ARRAYSIZE(packet); if (VersionHasIetfQuicFrames(framer_.transport_version())) { p = packet_ietf; p_size = ABSL_ARRAYSIZE(packet_ietf); } std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(p), p_size); } TEST_P(QuicFramerTest, BuildCloseFramePacketExtendedInfo) { QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicConnectionCloseFrame close_frame( framer_.transport_version(), static_cast<QuicErrorCode>( VersionHasIetfQuicFrames(framer_.transport_version()) ? 0x01 : 0x05060708), NO_IETF_QUIC_ERROR, "because I can", 0x05); close_frame.quic_error_code = static_cast<QuicErrorCode>(0x4567); QuicFrames frames = {QuicFrame(&close_frame)}; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x02, 0x05, 0x06, 0x07, 0x08, 0x00, 0x0d, 'b', 'e', 'c', 'a', 'u', 's', 'e', ' ', 'I', ' ', 'c', 'a', 'n', }; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x1c, kVarInt62OneByte + 0x01, kVarInt62OneByte + 0x05, kVarInt62OneByte + 0x13, '1', '7', '7', '6', '7', ':', 'b', 'e', 'c', 'a', 'u', 's', 'e', ' ', 'I', ' ', 'c', 'a', 'n' }; unsigned char* p = packet; size_t p_size = ABSL_ARRAYSIZE(packet); if (VersionHasIetfQuicFrames(framer_.transport_version())) { p = packet_ietf; p_size = ABSL_ARRAYSIZE(packet_ietf); } std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(p), p_size); } TEST_P(QuicFramerTest, BuildTruncatedCloseFramePacket) { QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicConnectionCloseFrame close_frame(framer_.transport_version(), QUIC_INTERNAL_ERROR, NO_IETF_QUIC_ERROR, std::string(2048, 'A'), 0x05); QuicFrames frames = {QuicFrame(&close_frame)}; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x02, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', }; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x1c, kVarInt62OneByte + 0x01, kVarInt62OneByte + 0x05, kVarInt62TwoBytes + 0x01, 0x00, '1', ':', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', }; unsigned char* p = packet; size_t p_size = ABSL_ARRAYSIZE(packet); if (VersionHasIetfQuicFrames(framer_.transport_version())) { p = packet_ietf; p_size = ABSL_ARRAYSIZE(packet_ietf); } std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(p), p_size); } TEST_P(QuicFramerTest, BuildApplicationCloseFramePacket) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicConnectionCloseFrame app_close_frame; app_close_frame.wire_error_code = 0x11; app_close_frame.error_details = "because I can"; app_close_frame.close_type = IETF_QUIC_APPLICATION_CONNECTION_CLOSE; QuicFrames frames = {QuicFrame(&app_close_frame)}; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x1d, kVarInt62OneByte + 0x11, kVarInt62OneByte + 0x0f, '0', ':', 'b', 'e', 'c', 'a', 'u', 's', 'e', ' ', 'I', ' ', 'c', 'a', 'n', }; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet_ietf), ABSL_ARRAYSIZE(packet_ietf)); } TEST_P(QuicFramerTest, BuildTruncatedApplicationCloseFramePacket) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicConnectionCloseFrame app_close_frame; app_close_frame.wire_error_code = 0x11; app_close_frame.error_details = std::string(2048, 'A'); app_close_frame.close_type = IETF_QUIC_APPLICATION_CONNECTION_CLOSE; app_close_frame.quic_error_code = QUIC_IETF_GQUIC_ERROR_MISSING; QuicFrames frames = {QuicFrame(&app_close_frame)}; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x1d, kVarInt62OneByte + 0x11, kVarInt62TwoBytes + 0x01, 0x00, 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', }; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet_ietf), ABSL_ARRAYSIZE(packet_ietf)); } TEST_P(QuicFramerTest, BuildGoAwayPacket) { if (VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicGoAwayFrame goaway_frame; goaway_frame.error_code = static_cast<QuicErrorCode>(0x05060708); goaway_frame.last_good_stream_id = kStreamId; goaway_frame.reason_phrase = "because I can"; QuicFrames frames = {QuicFrame(&goaway_frame)}; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x03, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x00, 0x0d, 'b', 'e', 'c', 'a', 'u', 's', 'e', ' ', 'I', ' ', 'c', 'a', 'n', }; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet), ABSL_ARRAYSIZE(packet)); } TEST_P(QuicFramerTest, BuildTruncatedGoAwayPacket) { if (VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicGoAwayFrame goaway_frame; goaway_frame.error_code = static_cast<QuicErrorCode>(0x05060708); goaway_frame.last_good_stream_id = kStreamId; goaway_frame.reason_phrase = std::string(2048, 'A'); QuicFrames frames = {QuicFrame(&goaway_frame)}; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x03, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x01, 0x00, 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', }; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet), ABSL_ARRAYSIZE(packet)); } TEST_P(QuicFramerTest, BuildWindowUpdatePacket) { QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicWindowUpdateFrame window_update_frame; window_update_frame.stream_id = kStreamId; window_update_frame.max_data = 0x1122334455667788; QuicFrames frames = {QuicFrame(window_update_frame)}; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x04, 0x01, 0x02, 0x03, 0x04, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, }; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x11, kVarInt62FourBytes + 0x01, 0x02, 0x03, 0x04, kVarInt62EightBytes + 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, }; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); unsigned char* p = packet; size_t p_size = ABSL_ARRAYSIZE(packet); if (VersionHasIetfQuicFrames(framer_.transport_version())) { p = packet_ietf; p_size = ABSL_ARRAYSIZE(packet_ietf); } quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(p), p_size); } TEST_P(QuicFramerTest, BuildMaxStreamDataPacket) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicWindowUpdateFrame window_update_frame; window_update_frame.stream_id = kStreamId; window_update_frame.max_data = 0x1122334455667788; QuicFrames frames = {QuicFrame(window_update_frame)}; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x11, kVarInt62FourBytes + 0x01, 0x02, 0x03, 0x04, kVarInt62EightBytes + 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, }; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet_ietf), ABSL_ARRAYSIZE(packet_ietf)); } TEST_P(QuicFramerTest, BuildMaxDataPacket) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicWindowUpdateFrame window_update_frame; window_update_frame.stream_id = QuicUtils::GetInvalidStreamId(framer_.transport_version()); window_update_frame.max_data = 0x1122334455667788; QuicFrames frames = {QuicFrame(window_update_frame)}; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x10, kVarInt62EightBytes + 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, }; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet_ietf), ABSL_ARRAYSIZE(packet_ietf)); } TEST_P(QuicFramerTest, BuildBlockedPacket) { QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicBlockedFrame blocked_frame; if (VersionHasIetfQuicFrames(framer_.transport_version())) { blocked_frame.stream_id = QuicUtils::GetInvalidStreamId(framer_.transport_version()); } else { blocked_frame.stream_id = kStreamId; } blocked_frame.offset = kStreamOffset; QuicFrames frames = {QuicFrame(blocked_frame)}; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x05, 0x01, 0x02, 0x03, 0x04, }; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x14, kVarInt62EightBytes + 0x3a, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54 }; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); unsigned char* p = packet; size_t p_size = ABSL_ARRAYSIZE(packet); if (VersionHasIetfQuicFrames(framer_.transport_version())) { p = packet_ietf; p_size = ABSL_ARRAYSIZE(packet_ietf); } quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(p), p_size); } TEST_P(QuicFramerTest, BuildPingPacket) { QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicFrames frames = {QuicFrame(QuicPingFrame())}; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x07, }; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x01, }; unsigned char* p = packet; if (VersionHasIetfQuicFrames(framer_.transport_version())) { p = packet_ietf; } std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(p), ABSL_ARRAYSIZE(packet)); } TEST_P(QuicFramerTest, BuildHandshakeDonePacket) { QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicFrames frames = {QuicFrame(QuicHandshakeDoneFrame())}; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x1e, }; if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet), ABSL_ARRAYSIZE(packet)); } TEST_P(QuicFramerTest, BuildAckFrequencyPacket) { QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicAckFrequencyFrame ack_frequency_frame; ack_frequency_frame.sequence_number = 3; ack_frequency_frame.packet_tolerance = 5; ack_frequency_frame.max_ack_delay = QuicTime::Delta::FromMicroseconds(0x3fff); ack_frequency_frame.ignore_order = false; QuicFrames frames = {QuicFrame(&ack_frequency_frame)}; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x40, 0xaf, 0x03, 0x05, 0x7f, 0xff, 0x00 }; if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet), ABSL_ARRAYSIZE(packet)); } TEST_P(QuicFramerTest, BuildResetStreamAtPacket) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicResetStreamAtFrame frame; frame.stream_id = 0x00; frame.error = 0x1e; frame.final_offset = 0x20; frame.reliable_offset = 0x10; QuicFrames frames = {QuicFrame(&frame)}; framer_.set_process_reset_stream_at(true); std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x24, 0x00, 0x1e, 0x20, 0x10, }; quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet), ABSL_ARRAYSIZE(packet)); } TEST_P(QuicFramerTest, BuildMessagePacket) { QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicMessageFrame frame(1, MemSliceFromString("message")); QuicMessageFrame frame2(2, MemSliceFromString("message2")); QuicFrames frames = {QuicFrame(&frame), QuicFrame(&frame2)}; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x21, 0x07, 'm', 'e', 's', 's', 'a', 'g', 'e', 0x20, 'm', 'e', 's', 's', 'a', 'g', 'e', '2' }; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x31, 0x07, 'm', 'e', 's', 's', 'a', 'g', 'e', 0x30, 'm', 'e', 's', 's', 'a', 'g', 'e', '2' }; unsigned char* p = packet; if (VersionHasIetfQuicFrames(framer_.transport_version())) { p = packet_ietf; } std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(p), ABSL_ARRAYSIZE(packet)); } TEST_P(QuicFramerTest, BuildMtuDiscoveryPacket) { QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicFrames frames = {QuicFrame(QuicMtuDiscoveryFrame())}; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x07, }; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x01, }; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); unsigned char* p = packet; if (VersionHasIetfQuicFrames(framer_.transport_version())) { p = packet_ietf; } quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(p), ABSL_ARRAYSIZE(packet)); } TEST_P(QuicFramerTest, BuildPublicResetPacket) { QuicPublicResetPacket reset_packet; reset_packet.connection_id = FramerTestConnectionId(); reset_packet.nonce_proof = kNonceProof; unsigned char packet[] = { 0x0E, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 'P', 'R', 'S', 'T', 0x01, 0x00, 0x00, 0x00, 'R', 'N', 'O', 'N', 0x08, 0x00, 0x00, 0x00, 0x89, 0x67, 0x45, 0x23, 0x01, 0xEF, 0xCD, 0xAB, }; std::unique_ptr<QuicEncryptedPacket> data( framer_.BuildPublicResetPacket(reset_packet)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet), ABSL_ARRAYSIZE(packet)); } TEST_P(QuicFramerTest, BuildPublicResetPacketWithClientAddress) { QuicPublicResetPacket reset_packet; reset_packet.connection_id = FramerTestConnectionId(); reset_packet.nonce_proof = kNonceProof; reset_packet.client_address = QuicSocketAddress(QuicIpAddress::Loopback4(), 0x1234); unsigned char packet[] = { 0x0E, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 'P', 'R', 'S', 'T', 0x02, 0x00, 0x00, 0x00, 'R', 'N', 'O', 'N', 0x08, 0x00, 0x00, 0x00, 'C', 'A', 'D', 'R', 0x10, 0x00, 0x00, 0x00, 0x89, 0x67, 0x45, 0x23, 0x01, 0xEF, 0xCD, 0xAB, 0x02, 0x00, 0x7F, 0x00, 0x00, 0x01, 0x34, 0x12, }; std::unique_ptr<QuicEncryptedPacket> data( framer_.BuildPublicResetPacket(reset_packet)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet), ABSL_ARRAYSIZE(packet)); } TEST_P(QuicFramerTest, BuildPublicResetPacketWithEndpointId) { QuicPublicResetPacket reset_packet; reset_packet.connection_id = FramerTestConnectionId(); reset_packet.nonce_proof = kNonceProof; reset_packet.endpoint_id = "FakeServerId"; unsigned char packet_variant1[] = { 0x0E, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 'P', 'R', 'S', 'T', 0x02, 0x00, 0x00, 0x00, 'R', 'N', 'O', 'N', 0x08, 0x00, 0x00, 0x00, 'E', 'P', 'I', 'D', 0x14, 0x00, 0x00, 0x00, 0x89, 0x67, 0x45, 0x23, 0x01, 0xEF, 0xCD, 0xAB, 'F', 'a', 'k', 'e', 'S', 'e', 'r', 'v', 'e', 'r', 'I', 'd', }; unsigned char packet_variant2[] = { 0x0E, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 'P', 'R', 'S', 'T', 0x02, 0x00, 0x00, 0x00, 'E', 'P', 'I', 'D', 0x0C, 0x00, 0x00, 0x00, 'R', 'N', 'O', 'N', 0x14, 0x00, 0x00, 0x00, 'F', 'a', 'k', 'e', 'S', 'e', 'r', 'v', 'e', 'r', 'I', 'd', 0x89, 0x67, 0x45, 0x23, 0x01, 0xEF, 0xCD, 0xAB, }; std::unique_ptr<QuicEncryptedPacket> data( framer_.BuildPublicResetPacket(reset_packet)); ASSERT_TRUE(data != nullptr); if ('d' == data->data()[data->length() - 1]) { quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet_variant1), ABSL_ARRAYSIZE(packet_variant1)); } else { quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet_variant2), ABSL_ARRAYSIZE(packet_variant2)); } } TEST_P(QuicFramerTest, BuildIetfStatelessResetPacket) { unsigned char packet[] = { 0x40, 0x00, 0x00, 0x00, 0x00, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f }; std::unique_ptr<QuicEncryptedPacket> data( framer_.BuildIetfStatelessResetPacket( FramerTestConnectionId(), QuicFramer::GetMinStatelessResetPacketLength() + 1, kTestStatelessResetToken)); ASSERT_TRUE(data); EXPECT_EQ(QuicFramer::GetMinStatelessResetPacketLength(), data->length()); EXPECT_FALSE(data->data()[0] & FLAGS_LONG_HEADER); EXPECT_TRUE(data->data()[0] & FLAGS_FIXED_BIT); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data() + data->length() - kStatelessResetTokenLength, kStatelessResetTokenLength, AsChars(packet) + ABSL_ARRAYSIZE(packet) - kStatelessResetTokenLength, kStatelessResetTokenLength); std::unique_ptr<QuicEncryptedPacket> data2( framer_.BuildIetfStatelessResetPacket( FramerTestConnectionId(), QuicFramer::GetMinStatelessResetPacketLength(), kTestStatelessResetToken)); ASSERT_FALSE(data2); std::unique_ptr<QuicEncryptedPacket> data3( framer_.BuildIetfStatelessResetPacket(FramerTestConnectionId(), 1000, kTestStatelessResetToken)); ASSERT_TRUE(data3); EXPECT_EQ(QuicFramer::GetMinStatelessResetPacketLength() + 1 + kQuicMaxConnectionIdWithLengthPrefixLength, data3->length()); } TEST_P(QuicFramerTest, BuildIetfStatelessResetPacketCallerProvidedRandomBytes) { unsigned char packet[] = { 0x7c, 0x7c, 0x7c, 0x7c, 0x7c, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f }; MockRandom random; auto generate_random_bytes = [](void* data, size_t len) { std::string bytes(len, 0x7c); memcpy(data, bytes.data(), bytes.size()); }; EXPECT_CALL(random, InsecureRandBytes(_, _)) .WillOnce(testing::Invoke(generate_random_bytes)); std::unique_ptr<QuicEncryptedPacket> data( framer_.BuildIetfStatelessResetPacket( FramerTestConnectionId(), QuicFramer::GetMinStatelessResetPacketLength() + 1, kTestStatelessResetToken, &random)); ASSERT_TRUE(data); EXPECT_EQ(QuicFramer::GetMinStatelessResetPacketLength(), data->length()); EXPECT_FALSE(data->data()[0] & FLAGS_LONG_HEADER); EXPECT_TRUE(data->data()[0] & FLAGS_FIXED_BIT); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet), ABSL_ARRAYSIZE(packet)); } TEST_P(QuicFramerTest, EncryptPacket) { QuicPacketNumber packet_number = kPacketNumber; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', }; unsigned char packet50[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', }; unsigned char* p = packet; size_t p_size = ABSL_ARRAYSIZE(packet); if (framer_.version().HasHeaderProtection()) { p = packet50; p_size = ABSL_ARRAYSIZE(packet50); } std::unique_ptr<QuicPacket> raw(new QuicPacket( AsChars(p), p_size, false, kPacket8ByteConnectionId, kPacket0ByteConnectionId, !kIncludeVersion, !kIncludeDiversificationNonce, PACKET_4BYTE_PACKET_NUMBER, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0, 0, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0)); char buffer[kMaxOutgoingPacketSize]; size_t encrypted_length = framer_.EncryptPayload( ENCRYPTION_INITIAL, packet_number, *raw, buffer, kMaxOutgoingPacketSize); ASSERT_NE(0u, encrypted_length); EXPECT_TRUE(CheckEncryption(packet_number, raw.get())); } TEST_P(QuicFramerTest, EncryptEmptyPacket) { auto packet = std::make_unique<QuicPacket>( new char[100], 0, true, kPacket8ByteConnectionId, kPacket0ByteConnectionId, true, true, PACKET_1BYTE_PACKET_NUMBER, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0, 0, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0); char buffer[kMaxOutgoingPacketSize]; size_t encrypted_length = 1; EXPECT_QUIC_BUG( { encrypted_length = framer_.EncryptPayload(ENCRYPTION_INITIAL, kPacketNumber, *packet, buffer, kMaxOutgoingPacketSize); EXPECT_EQ(0u, encrypted_length); }, "packet is shorter than associated data length"); } TEST_P(QuicFramerTest, EncryptPacketWithVersionFlag) { QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketNumber packet_number = kPacketNumber; unsigned char packet[] = { 0xD3, 'Q', '.', '1', '0', 0x50, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', }; unsigned char packet50[] = { 0xD3, 'Q', '.', '1', '0', 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x12, 0x34, 0x56, 0x78, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', }; unsigned char* p = packet; size_t p_size = ABSL_ARRAYSIZE(packet); if (framer_.version().HasHeaderProtection()) { p = packet50; p_size = ABSL_ARRAYSIZE(packet50); } std::unique_ptr<QuicPacket> raw(new QuicPacket( AsChars(p), p_size, false, kPacket8ByteConnectionId, kPacket0ByteConnectionId, kIncludeVersion, !kIncludeDiversificationNonce, PACKET_4BYTE_PACKET_NUMBER, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0, 0, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0)); char buffer[kMaxOutgoingPacketSize]; size_t encrypted_length = framer_.EncryptPayload( ENCRYPTION_INITIAL, packet_number, *raw, buffer, kMaxOutgoingPacketSize); ASSERT_NE(0u, encrypted_length); EXPECT_TRUE(CheckEncryption(packet_number, raw.get())); } TEST_P(QuicFramerTest, AckTruncationLargePacket) { if (VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicAckFrame ack_frame; ack_frame = MakeAckFrameWithAckBlocks(300, 0u); QuicFrames frames = {QuicFrame(&ack_frame)}; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); std::unique_ptr<QuicPacket> raw_ack_packet(BuildDataPacket(header, frames)); ASSERT_TRUE(raw_ack_packet != nullptr); char buffer[kMaxOutgoingPacketSize]; size_t encrypted_length = framer_.EncryptPayload(ENCRYPTION_INITIAL, header.packet_number, *raw_ack_packet, buffer, kMaxOutgoingPacketSize); ASSERT_NE(0u, encrypted_length); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); ASSERT_TRUE(framer_.ProcessPacket( QuicEncryptedPacket(buffer, encrypted_length, false))); ASSERT_EQ(1u, visitor_.ack_frames_.size()); QuicAckFrame& processed_ack_frame = *visitor_.ack_frames_[0]; EXPECT_EQ(QuicPacketNumber(600u), LargestAcked(processed_ack_frame)); ASSERT_EQ(256u, processed_ack_frame.packets.NumPacketsSlow()); EXPECT_EQ(QuicPacketNumber(90u), processed_ack_frame.packets.Min()); EXPECT_EQ(QuicPacketNumber(600u), processed_ack_frame.packets.Max()); } TEST_P(QuicFramerTest, IetfAckFrameTruncation) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicAckFrame ack_frame; ack_frame = MakeAckFrameWithGaps(0xffffffff, 200, kMaxIetfVarInt); ack_frame.ecn_counters = QuicEcnCounts(100, 10000, 1000000); QuicFrames frames = {QuicFrame(&ack_frame)}; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); std::unique_ptr<QuicPacket> raw_ack_packet(BuildDataPacket(header, frames)); ASSERT_TRUE(raw_ack_packet != nullptr); char buffer[kMaxOutgoingPacketSize]; size_t encrypted_length = framer_.EncryptPayload(ENCRYPTION_INITIAL, header.packet_number, *raw_ack_packet, buffer, kMaxOutgoingPacketSize); ASSERT_NE(0u, encrypted_length); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); ASSERT_TRUE(framer_.ProcessPacket( QuicEncryptedPacket(buffer, encrypted_length, false))); ASSERT_EQ(1u, visitor_.ack_frames_.size()); QuicAckFrame& processed_ack_frame = *visitor_.ack_frames_[0]; EXPECT_EQ(QuicPacketNumber(kMaxIetfVarInt), LargestAcked(processed_ack_frame)); ASSERT_LT(processed_ack_frame.packets.NumPacketsSlow(), ack_frame.packets.NumIntervals()); EXPECT_EQ(157u, processed_ack_frame.packets.NumPacketsSlow()); EXPECT_LT(processed_ack_frame.packets.NumIntervals(), ack_frame.packets.NumIntervals()); EXPECT_EQ(QuicPacketNumber(kMaxIetfVarInt), processed_ack_frame.packets.Max()); } TEST_P(QuicFramerTest, AckTruncationSmallPacket) { if (VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicAckFrame ack_frame; ack_frame = MakeAckFrameWithAckBlocks(300, 0u); QuicFrames frames = {QuicFrame(&ack_frame)}; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); std::unique_ptr<QuicPacket> raw_ack_packet( BuildDataPacket(header, frames, 500)); ASSERT_TRUE(raw_ack_packet != nullptr); char buffer[kMaxOutgoingPacketSize]; size_t encrypted_length = framer_.EncryptPayload(ENCRYPTION_INITIAL, header.packet_number, *raw_ack_packet, buffer, kMaxOutgoingPacketSize); ASSERT_NE(0u, encrypted_length); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); ASSERT_TRUE(framer_.ProcessPacket( QuicEncryptedPacket(buffer, encrypted_length, false))); ASSERT_EQ(1u, visitor_.ack_frames_.size()); QuicAckFrame& processed_ack_frame = *visitor_.ack_frames_[0]; EXPECT_EQ(QuicPacketNumber(600u), LargestAcked(processed_ack_frame)); ASSERT_EQ(240u, processed_ack_frame.packets.NumPacketsSlow()); EXPECT_EQ(QuicPacketNumber(122u), processed_ack_frame.packets.Min()); EXPECT_EQ(QuicPacketNumber(600u), processed_ack_frame.packets.Max()); } TEST_P(QuicFramerTest, CleanTruncation) { if (VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicAckFrame ack_frame = InitAckFrame(201); QuicFrames frames = {QuicFrame(&ack_frame)}; if (framer_.version().HasHeaderProtection()) { frames.push_back(QuicFrame(QuicPaddingFrame(12))); } QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); std::unique_ptr<QuicPacket> raw_ack_packet(BuildDataPacket(header, frames)); ASSERT_TRUE(raw_ack_packet != nullptr); char buffer[kMaxOutgoingPacketSize]; size_t encrypted_length = framer_.EncryptPayload(ENCRYPTION_INITIAL, header.packet_number, *raw_ack_packet, buffer, kMaxOutgoingPacketSize); ASSERT_NE(0u, encrypted_length); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); ASSERT_TRUE(framer_.ProcessPacket( QuicEncryptedPacket(buffer, encrypted_length, false))); frames.clear(); frames.push_back(QuicFrame(visitor_.ack_frames_[0].get())); if (framer_.version().HasHeaderProtection()) { frames.push_back(QuicFrame(*visitor_.padding_frames_[0].get())); } size_t original_raw_length = raw_ack_packet->length(); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); raw_ack_packet = BuildDataPacket(header, frames); ASSERT_TRUE(raw_ack_packet != nullptr); EXPECT_EQ(original_raw_length, raw_ack_packet->length()); ASSERT_TRUE(raw_ack_packet != nullptr); } TEST_P(QuicFramerTest, StopPacketProcessing) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0xFF, 0x01, 0x02, 0x03, 0x04, 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, 0x00, 0x0c, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', 0x40, 0x12, 0x34, 0x56, 0x78, 0x9A, 0xA0, 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBF, 0x01, 0x12, 0x34, 0x56, 0x78, 0x9A, 0xBE, }; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x08 | 0x01 | 0x02 | 0x04, kVarInt62FourBytes + 0x01, 0x02, 0x03, 0x04, kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, kVarInt62TwoBytes + 0x00, 0x0c, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', 0x0d, kVarInt62FourBytes + 0x12, 0x34, 0x56, 0x78, kVarInt62OneByte + 0x00, kVarInt62OneByte + 0x01, kVarInt62OneByte + 0x00, kVarInt62FourBytes + 0x12, 0x34, 0x56, 0x77, kVarInt62OneByte + 0x00, }; MockFramerVisitor visitor; framer_.set_visitor(&visitor); EXPECT_CALL(visitor, OnPacket()); EXPECT_CALL(visitor, OnPacketHeader(_)); EXPECT_CALL(visitor, OnStreamFrame(_)).WillOnce(Return(false)); EXPECT_CALL(visitor, OnPacketComplete()); EXPECT_CALL(visitor, OnUnauthenticatedPublicHeader(_)).WillOnce(Return(true)); EXPECT_CALL(visitor, OnUnauthenticatedHeader(_)).WillOnce(Return(true)); EXPECT_CALL(visitor, OnDecryptedPacket(_, _)); unsigned char* p = packet; size_t p_size = ABSL_ARRAYSIZE(packet); if (VersionHasIetfQuicFrames(framer_.transport_version())) { p = packet_ietf; p_size = ABSL_ARRAYSIZE(packet_ietf); } QuicEncryptedPacket encrypted(AsChars(p), p_size, false); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); } static char kTestString[] = "At least 20 characters."; static QuicStreamId kTestQuicStreamId = 1; MATCHER_P(ExpectedStreamFrame, version, "") { return (arg.stream_id == kTestQuicStreamId || QuicUtils::IsCryptoStreamId(version.transport_version, arg.stream_id)) && !arg.fin && arg.offset == 0 && std::string(arg.data_buffer, arg.data_length) == kTestString; } TEST_P(QuicFramerTest, ConstructEncryptedPacket) { if (framer_.version().KnowsWhichDecrypterToUse()) { framer_.InstallDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>( (uint8_t)ENCRYPTION_FORWARD_SECURE)); } else { framer_.SetDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>( (uint8_t)ENCRYPTION_FORWARD_SECURE)); } ParsedQuicVersionVector versions; versions.push_back(framer_.version()); std::unique_ptr<QuicEncryptedPacket> packet(ConstructEncryptedPacket( TestConnectionId(), EmptyQuicConnectionId(), false, false, kTestQuicStreamId, kTestString, CONNECTION_ID_PRESENT, CONNECTION_ID_ABSENT, PACKET_4BYTE_PACKET_NUMBER, &versions)); MockFramerVisitor visitor; framer_.set_visitor(&visitor); EXPECT_CALL(visitor, OnPacket()).Times(1); EXPECT_CALL(visitor, OnUnauthenticatedPublicHeader(_)) .Times(1) .WillOnce(Return(true)); EXPECT_CALL(visitor, OnUnauthenticatedHeader(_)) .Times(1) .WillOnce(Return(true)); EXPECT_CALL(visitor, OnPacketHeader(_)).Times(1).WillOnce(Return(true)); EXPECT_CALL(visitor, OnDecryptedPacket(_, _)).Times(1); EXPECT_CALL(visitor, OnError(_)).Times(0); EXPECT_CALL(visitor, OnStreamFrame(_)).Times(0); if (!QuicVersionUsesCryptoFrames(framer_.version().transport_version)) { EXPECT_CALL(visitor, OnStreamFrame(ExpectedStreamFrame(framer_.version()))) .Times(1); } else { EXPECT_CALL(visitor, OnCryptoFrame(_)).Times(1); } EXPECT_CALL(visitor, OnPacketComplete()).Times(1); EXPECT_TRUE(framer_.ProcessPacket(*packet)); EXPECT_THAT(framer_.error(), IsQuicNoError()); } TEST_P(QuicFramerTest, ConstructMisFramedEncryptedPacket) { if (framer_.version().KnowsWhichDecrypterToUse()) { framer_.InstallDecrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE)); } std::unique_ptr<QuicEncryptedPacket> packet(ConstructMisFramedEncryptedPacket( TestConnectionId(), EmptyQuicConnectionId(), false, false, kTestQuicStreamId, kTestString, CONNECTION_ID_PRESENT, CONNECTION_ID_ABSENT, PACKET_4BYTE_PACKET_NUMBER, framer_.version(), Perspective::IS_CLIENT)); MockFramerVisitor visitor; framer_.set_visitor(&visitor); EXPECT_CALL(visitor, OnPacket()).Times(1); EXPECT_CALL(visitor, OnUnauthenticatedPublicHeader(_)) .Times(1) .WillOnce(Return(true)); EXPECT_CALL(visitor, OnUnauthenticatedHeader(_)) .Times(1) .WillOnce(Return(true)); EXPECT_CALL(visitor, OnPacketHeader(_)).Times(1); EXPECT_CALL(visitor, OnDecryptedPacket(_, _)).Times(1); EXPECT_CALL(visitor, OnError(_)).Times(1); EXPECT_CALL(visitor, OnStreamFrame(_)).Times(0); EXPECT_CALL(visitor, OnPacketComplete()).Times(0); EXPECT_FALSE(framer_.ProcessPacket(*packet)); EXPECT_THAT(framer_.error(), IsError(QUIC_INVALID_FRAME_DATA)); } TEST_P(QuicFramerTest, IetfBlockedFrame) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {0x14}}, {"Can not read blocked offset.", {kVarInt62EightBytes + 0x3a, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(kStreamOffset, visitor_.blocked_frame_.offset); CheckFramingBoundaries(packet_ietf, QUIC_INVALID_BLOCKED_DATA); } TEST_P(QuicFramerTest, BuildIetfBlockedPacket) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicBlockedFrame frame; frame.stream_id = QuicUtils::GetInvalidStreamId(framer_.transport_version()); frame.offset = kStreamOffset; QuicFrames frames = {QuicFrame(frame)}; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x14, kVarInt62EightBytes + 0x3a, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54 }; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet_ietf), ABSL_ARRAYSIZE(packet_ietf)); } TEST_P(QuicFramerTest, IetfStreamBlockedFrame) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {0x15}}, {"Unable to read IETF_STREAM_DATA_BLOCKED frame stream id/count.", {kVarInt62FourBytes + 0x01, 0x02, 0x03, 0x04}}, {"Can not read stream blocked offset.", {kVarInt62EightBytes + 0x3a, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(kStreamId, visitor_.blocked_frame_.stream_id); EXPECT_EQ(kStreamOffset, visitor_.blocked_frame_.offset); CheckFramingBoundaries(packet_ietf, QUIC_INVALID_STREAM_BLOCKED_DATA); } TEST_P(QuicFramerTest, BuildIetfStreamBlockedPacket) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicBlockedFrame frame; frame.stream_id = kStreamId; frame.offset = kStreamOffset; QuicFrames frames = {QuicFrame(frame)}; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x15, kVarInt62FourBytes + 0x01, 0x02, 0x03, 0x04, kVarInt62EightBytes + 0x3a, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54 }; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet_ietf), ABSL_ARRAYSIZE(packet_ietf)); } TEST_P(QuicFramerTest, BiDiMaxStreamsFrame) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {0x12}}, {"Unable to read IETF_MAX_STREAMS_BIDIRECTIONAL frame stream id/count.", {kVarInt62OneByte + 0x03}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(3u, visitor_.max_streams_frame_.stream_count); EXPECT_FALSE(visitor_.max_streams_frame_.unidirectional); CheckFramingBoundaries(packet_ietf, QUIC_MAX_STREAMS_DATA); } TEST_P(QuicFramerTest, UniDiMaxStreamsFrame) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {0x13}}, {"Unable to read IETF_MAX_STREAMS_UNIDIRECTIONAL frame stream id/count.", {kVarInt62OneByte + 0x03}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket0ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(3u, visitor_.max_streams_frame_.stream_count); EXPECT_TRUE(visitor_.max_streams_frame_.unidirectional); CheckFramingBoundaries(packet_ietf, QUIC_MAX_STREAMS_DATA); } TEST_P(QuicFramerTest, ServerUniDiMaxStreamsFrame) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {0x13}}, {"Unable to read IETF_MAX_STREAMS_UNIDIRECTIONAL frame stream id/count.", {kVarInt62OneByte + 0x03}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(3u, visitor_.max_streams_frame_.stream_count); EXPECT_TRUE(visitor_.max_streams_frame_.unidirectional); CheckFramingBoundaries(packet_ietf, QUIC_MAX_STREAMS_DATA); } TEST_P(QuicFramerTest, ClientUniDiMaxStreamsFrame) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {0x13}}, {"Unable to read IETF_MAX_STREAMS_UNIDIRECTIONAL frame stream id/count.", {kVarInt62OneByte + 0x03}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket0ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(3u, visitor_.max_streams_frame_.stream_count); EXPECT_TRUE(visitor_.max_streams_frame_.unidirectional); CheckFramingBoundaries(packet_ietf, QUIC_MAX_STREAMS_DATA); } TEST_P(QuicFramerTest, BiDiMaxStreamsFrameTooBig) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x9A, 0xBC, 0x12, kVarInt62EightBytes + 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00 }; QuicEncryptedPacket encrypted(AsChars(packet_ietf), ABSL_ARRAYSIZE(packet_ietf), false); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(0x40000000u, visitor_.max_streams_frame_.stream_count); EXPECT_FALSE(visitor_.max_streams_frame_.unidirectional); } TEST_P(QuicFramerTest, ClientBiDiMaxStreamsFrameTooBig) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); unsigned char packet_ietf[] = { 0x43, 0x12, 0x34, 0x9A, 0xBC, 0x12, kVarInt62EightBytes + 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00 }; QuicEncryptedPacket encrypted(AsChars(packet_ietf), ABSL_ARRAYSIZE(packet_ietf), false); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket0ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(0x40000000u, visitor_.max_streams_frame_.stream_count); EXPECT_FALSE(visitor_.max_streams_frame_.unidirectional); } TEST_P(QuicFramerTest, ServerUniDiMaxStreamsFrameTooBig) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x9A, 0xBC, 0x13, kVarInt62EightBytes + 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00 }; QuicEncryptedPacket encrypted(AsChars(packet_ietf), ABSL_ARRAYSIZE(packet_ietf), false); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(0x40000000u, visitor_.max_streams_frame_.stream_count); EXPECT_TRUE(visitor_.max_streams_frame_.unidirectional); } TEST_P(QuicFramerTest, ClientUniDiMaxStreamsFrameTooBig) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); unsigned char packet_ietf[] = { 0x43, 0x12, 0x34, 0x9A, 0xBC, 0x13, kVarInt62EightBytes + 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00 }; QuicEncryptedPacket encrypted(AsChars(packet_ietf), ABSL_ARRAYSIZE(packet_ietf), false); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket0ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(0x40000000u, visitor_.max_streams_frame_.stream_count); EXPECT_TRUE(visitor_.max_streams_frame_.unidirectional); } TEST_P(QuicFramerTest, MaxStreamsFrameZeroCount) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x9A, 0xBC, 0x12, kVarInt62OneByte + 0x00 }; QuicEncryptedPacket encrypted(AsChars(packet_ietf), ABSL_ARRAYSIZE(packet_ietf), false); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); } TEST_P(QuicFramerTest, ServerBiDiStreamsBlockedFrame) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {0x13}}, {"Unable to read IETF_MAX_STREAMS_UNIDIRECTIONAL frame stream id/count.", {kVarInt62OneByte + 0x00}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(0u, visitor_.max_streams_frame_.stream_count); EXPECT_TRUE(visitor_.max_streams_frame_.unidirectional); CheckFramingBoundaries(packet_ietf, QUIC_MAX_STREAMS_DATA); } TEST_P(QuicFramerTest, BiDiStreamsBlockedFrame) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {0x16}}, {"Unable to read IETF_STREAMS_BLOCKED_BIDIRECTIONAL " "frame stream id/count.", {kVarInt62OneByte + 0x03}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(3u, visitor_.streams_blocked_frame_.stream_count); EXPECT_FALSE(visitor_.streams_blocked_frame_.unidirectional); CheckFramingBoundaries(packet_ietf, QUIC_STREAMS_BLOCKED_DATA); } TEST_P(QuicFramerTest, UniDiStreamsBlockedFrame) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {0x17}}, {"Unable to read IETF_STREAMS_BLOCKED_UNIDIRECTIONAL " "frame stream id/count.", {kVarInt62OneByte + 0x03}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(3u, visitor_.streams_blocked_frame_.stream_count); EXPECT_TRUE(visitor_.streams_blocked_frame_.unidirectional); CheckFramingBoundaries(packet_ietf, QUIC_STREAMS_BLOCKED_DATA); } TEST_P(QuicFramerTest, ClientUniDiStreamsBlockedFrame) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {0x17}}, {"Unable to read IETF_STREAMS_BLOCKED_UNIDIRECTIONAL " "frame stream id/count.", {kVarInt62OneByte + 0x03}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket0ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(3u, visitor_.streams_blocked_frame_.stream_count); EXPECT_TRUE(visitor_.streams_blocked_frame_.unidirectional); CheckFramingBoundaries(packet_ietf, QUIC_STREAMS_BLOCKED_DATA); } TEST_P(QuicFramerTest, StreamsBlockedFrameTooBig) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); unsigned char packet_ietf[] = { 0x43, 0x12, 0x34, 0x9A, 0xBC, 0x16, kVarInt62EightBytes + 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x01 }; QuicEncryptedPacket encrypted(AsChars(packet_ietf), ABSL_ARRAYSIZE(packet_ietf), false); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); EXPECT_FALSE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsError(QUIC_STREAMS_BLOCKED_DATA)); EXPECT_EQ(framer_.detailed_error(), "STREAMS_BLOCKED stream count exceeds implementation limit."); } TEST_P(QuicFramerTest, StreamsBlockedFrameZeroCount) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {0x17}}, {"Unable to read IETF_STREAMS_BLOCKED_UNIDIRECTIONAL " "frame stream id/count.", {kVarInt62OneByte + 0x00}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(0u, visitor_.streams_blocked_frame_.stream_count); EXPECT_TRUE(visitor_.streams_blocked_frame_.unidirectional); CheckFramingBoundaries(packet_ietf, QUIC_STREAMS_BLOCKED_DATA); } TEST_P(QuicFramerTest, BuildBiDiStreamsBlockedPacket) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicStreamsBlockedFrame frame; frame.stream_count = 3; frame.unidirectional = false; QuicFrames frames = {QuicFrame(frame)}; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x16, kVarInt62OneByte + 0x03 }; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet_ietf), ABSL_ARRAYSIZE(packet_ietf)); } TEST_P(QuicFramerTest, BuildUniStreamsBlockedPacket) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicStreamsBlockedFrame frame; frame.stream_count = 3; frame.unidirectional = true; QuicFrames frames = {QuicFrame(frame)}; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x17, kVarInt62OneByte + 0x03 }; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet_ietf), ABSL_ARRAYSIZE(packet_ietf)); } TEST_P(QuicFramerTest, BuildBiDiMaxStreamsPacket) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicMaxStreamsFrame frame; frame.stream_count = 3; frame.unidirectional = false; QuicFrames frames = {QuicFrame(frame)}; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x12, kVarInt62OneByte + 0x03 }; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet_ietf), ABSL_ARRAYSIZE(packet_ietf)); } TEST_P(QuicFramerTest, BuildUniDiMaxStreamsPacket) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicMaxStreamsFrame frame; frame.stream_count = 3; frame.unidirectional = true; QuicFrames frames = {QuicFrame(frame)}; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x13, kVarInt62OneByte + 0x03 }; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet_ietf), ABSL_ARRAYSIZE(packet_ietf)); } TEST_P(QuicFramerTest, NewConnectionIdFrame) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x18}}, {"Unable to read new connection ID frame sequence number.", {kVarInt62OneByte + 0x11}}, {"Unable to read new connection ID frame retire_prior_to.", {kVarInt62OneByte + 0x09}}, {"Unable to read new connection ID frame connection id.", {0x08}}, {"Unable to read new connection ID frame connection id.", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x11}}, {"Can not read new connection ID frame reset token.", {0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f}} }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(0u, visitor_.stream_frames_.size()); EXPECT_EQ(FramerTestConnectionIdPlusOne(), visitor_.new_connection_id_.connection_id); EXPECT_EQ(0x11u, visitor_.new_connection_id_.sequence_number); EXPECT_EQ(0x09u, visitor_.new_connection_id_.retire_prior_to); EXPECT_EQ(kTestStatelessResetToken, visitor_.new_connection_id_.stateless_reset_token); ASSERT_EQ(0u, visitor_.ack_frames_.size()); CheckFramingBoundaries(packet_ietf, QUIC_INVALID_NEW_CONNECTION_ID_DATA); } TEST_P(QuicFramerTest, NewConnectionIdFrameVariableLength) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x18}}, {"Unable to read new connection ID frame sequence number.", {kVarInt62OneByte + 0x11}}, {"Unable to read new connection ID frame retire_prior_to.", {kVarInt62OneByte + 0x0a}}, {"Unable to read new connection ID frame connection id.", {0x09}}, {"Unable to read new connection ID frame connection id.", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x42}}, {"Can not read new connection ID frame reset token.", {0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f}} }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(0u, visitor_.stream_frames_.size()); EXPECT_EQ(FramerTestConnectionIdNineBytes(), visitor_.new_connection_id_.connection_id); EXPECT_EQ(0x11u, visitor_.new_connection_id_.sequence_number); EXPECT_EQ(0x0au, visitor_.new_connection_id_.retire_prior_to); EXPECT_EQ(kTestStatelessResetToken, visitor_.new_connection_id_.stateless_reset_token); ASSERT_EQ(0u, visitor_.ack_frames_.size()); CheckFramingBoundaries(packet_ietf, QUIC_INVALID_NEW_CONNECTION_ID_DATA); } TEST_P(QuicFramerTest, InvalidLongNewConnectionIdFrame) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x18}}, {"Unable to read new connection ID frame sequence number.", {kVarInt62OneByte + 0x11}}, {"Unable to read new connection ID frame retire_prior_to.", {kVarInt62OneByte + 0x0b}}, {"Unable to read new connection ID frame connection id.", {0x40}}, {"Unable to read new connection ID frame connection id.", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0xF0, 0xD2, 0xB4, 0x96, 0x78, 0x5A, 0x3C, 0x1E, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0xF0, 0xD2, 0xB4, 0x96, 0x78, 0x5A, 0x3C, 0x1E, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0xF0, 0xD2, 0xB4, 0x96, 0x78, 0x5A, 0x3C, 0x1E, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0xF0, 0xD2, 0xB4, 0x96, 0x78, 0x5A, 0x3C, 0x1E}}, {"Can not read new connection ID frame reset token.", {0xb5, 0x69, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}} }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsError(QUIC_INVALID_NEW_CONNECTION_ID_DATA)); EXPECT_EQ("Invalid new connection ID length for version.", framer_.detailed_error()); } TEST_P(QuicFramerTest, InvalidRetirePriorToNewConnectionIdFrame) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x18}}, {"Unable to read new connection ID frame sequence number.", {kVarInt62OneByte + 0x11}}, {"Unable to read new connection ID frame retire_prior_to.", {kVarInt62OneByte + 0x1b}}, {"Unable to read new connection ID frame connection id length.", {0x08}}, {"Unable to read new connection ID frame connection id.", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x11}}, {"Can not read new connection ID frame reset token.", {0xb5, 0x69, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}} }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsError(QUIC_INVALID_NEW_CONNECTION_ID_DATA)); EXPECT_EQ("Retire_prior_to > sequence_number.", framer_.detailed_error()); } TEST_P(QuicFramerTest, BuildNewConnectionIdFramePacket) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicNewConnectionIdFrame frame; frame.sequence_number = 0x11; frame.retire_prior_to = 0x0c; frame.connection_id = FramerTestConnectionIdPlusOne(); frame.stateless_reset_token = kTestStatelessResetToken; QuicFrames frames = {QuicFrame(&frame)}; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x18, kVarInt62OneByte + 0x11, kVarInt62OneByte + 0x0c, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x11, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, }; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet_ietf), ABSL_ARRAYSIZE(packet_ietf)); } TEST_P(QuicFramerTest, NewTokenFrame) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x07}}, {"Unable to read new token length.", {kVarInt62OneByte + 0x08}}, {"Unable to read new token data.", {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}} }; uint8_t expected_token_value[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(0u, visitor_.stream_frames_.size()); EXPECT_EQ(sizeof(expected_token_value), visitor_.new_token_.token.length()); EXPECT_EQ(0, memcmp(expected_token_value, visitor_.new_token_.token.data(), sizeof(expected_token_value))); CheckFramingBoundaries(packet, QUIC_INVALID_NEW_TOKEN); } TEST_P(QuicFramerTest, BuildNewTokenFramePacket) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; uint8_t expected_token_value[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}; QuicNewTokenFrame frame(0, absl::string_view((const char*)(expected_token_value), sizeof(expected_token_value))); QuicFrames frames = {QuicFrame(&frame)}; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x07, kVarInt62OneByte + 0x08, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet), ABSL_ARRAYSIZE(packet)); } TEST_P(QuicFramerTest, IetfStopSendingFrame) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {0x05}}, {"Unable to read IETF_STOP_SENDING frame stream id/count.", {kVarInt62FourBytes + 0x01, 0x02, 0x03, 0x04}}, {"Unable to read stop sending application error code.", {kVarInt62FourBytes + 0x00, 0x00, 0x76, 0x54}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(kStreamId, visitor_.stop_sending_frame_.stream_id); EXPECT_EQ(QUIC_STREAM_UNKNOWN_APPLICATION_ERROR_CODE, visitor_.stop_sending_frame_.error_code); EXPECT_EQ(static_cast<uint64_t>(0x7654), visitor_.stop_sending_frame_.ietf_error_code); CheckFramingBoundaries(packet_ietf, QUIC_INVALID_STOP_SENDING_FRAME_DATA); } TEST_P(QuicFramerTest, BuildIetfStopSendingPacket) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicStopSendingFrame frame; frame.stream_id = kStreamId; frame.error_code = QUIC_STREAM_ENCODER_STREAM_ERROR; frame.ietf_error_code = static_cast<uint64_t>(QuicHttpQpackErrorCode::ENCODER_STREAM_ERROR); QuicFrames frames = {QuicFrame(frame)}; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x05, kVarInt62FourBytes + 0x01, 0x02, 0x03, 0x04, kVarInt62TwoBytes + 0x02, 0x01, }; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet_ietf), ABSL_ARRAYSIZE(packet_ietf)); } TEST_P(QuicFramerTest, IetfPathChallengeFrame) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {0x1a}}, {"Can not read path challenge data.", {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(QuicPathFrameBuffer({{0, 1, 2, 3, 4, 5, 6, 7}}), visitor_.path_challenge_frame_.data_buffer); CheckFramingBoundaries(packet_ietf, QUIC_INVALID_PATH_CHALLENGE_DATA); } TEST_P(QuicFramerTest, BuildIetfPathChallengePacket) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicPathChallengeFrame frame; frame.data_buffer = QuicPathFrameBuffer({{0, 1, 2, 3, 4, 5, 6, 7}}); QuicFrames frames = {QuicFrame(frame)}; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x1a, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet_ietf), ABSL_ARRAYSIZE(packet_ietf)); } TEST_P(QuicFramerTest, IetfPathResponseFrame) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {0x1b}}, {"Can not read path response data.", {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(QuicPathFrameBuffer({{0, 1, 2, 3, 4, 5, 6, 7}}), visitor_.path_response_frame_.data_buffer); CheckFramingBoundaries(packet_ietf, QUIC_INVALID_PATH_RESPONSE_DATA); } TEST_P(QuicFramerTest, BuildIetfPathResponsePacket) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicPathResponseFrame frame; frame.data_buffer = QuicPathFrameBuffer({{0, 1, 2, 3, 4, 5, 6, 7}}); QuicFrames frames = {QuicFrame(frame)}; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x1b, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet_ietf), ABSL_ARRAYSIZE(packet_ietf)); } TEST_P(QuicFramerTest, GetRetransmittableControlFrameSize) { QuicRstStreamFrame rst_stream(1, 3, QUIC_STREAM_CANCELLED, 1024); EXPECT_EQ(QuicFramer::GetRstStreamFrameSize(framer_.transport_version(), rst_stream), QuicFramer::GetRetransmittableControlFrameSize( framer_.transport_version(), QuicFrame(&rst_stream))); std::string error_detail(2048, 'e'); QuicConnectionCloseFrame connection_close(framer_.transport_version(), QUIC_NETWORK_IDLE_TIMEOUT, NO_IETF_QUIC_ERROR, error_detail, 0); EXPECT_EQ(QuicFramer::GetConnectionCloseFrameSize(framer_.transport_version(), connection_close), QuicFramer::GetRetransmittableControlFrameSize( framer_.transport_version(), QuicFrame(&connection_close))); QuicGoAwayFrame goaway(2, QUIC_PEER_GOING_AWAY, 3, error_detail); EXPECT_EQ(QuicFramer::GetMinGoAwayFrameSize() + 256, QuicFramer::GetRetransmittableControlFrameSize( framer_.transport_version(), QuicFrame(&goaway))); QuicWindowUpdateFrame window_update(3, 3, 1024); EXPECT_EQ(QuicFramer::GetWindowUpdateFrameSize(framer_.transport_version(), window_update), QuicFramer::GetRetransmittableControlFrameSize( framer_.transport_version(), QuicFrame(window_update))); QuicBlockedFrame blocked(4, 3, 1024); EXPECT_EQ( QuicFramer::GetBlockedFrameSize(framer_.transport_version(), blocked), QuicFramer::GetRetransmittableControlFrameSize( framer_.transport_version(), QuicFrame(blocked))); if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicNewConnectionIdFrame new_connection_id(5, TestConnectionId(), 1, kTestStatelessResetToken, 1); EXPECT_EQ(QuicFramer::GetNewConnectionIdFrameSize(new_connection_id), QuicFramer::GetRetransmittableControlFrameSize( framer_.transport_version(), QuicFrame(&new_connection_id))); QuicMaxStreamsFrame max_streams(6, 3, false); EXPECT_EQ(QuicFramer::GetMaxStreamsFrameSize(framer_.transport_version(), max_streams), QuicFramer::GetRetransmittableControlFrameSize( framer_.transport_version(), QuicFrame(max_streams))); QuicStreamsBlockedFrame streams_blocked(7, 3, false); EXPECT_EQ(QuicFramer::GetStreamsBlockedFrameSize(framer_.transport_version(), streams_blocked), QuicFramer::GetRetransmittableControlFrameSize( framer_.transport_version(), QuicFrame(streams_blocked))); QuicPathFrameBuffer buffer = { {0x80, 0x91, 0xa2, 0xb3, 0xc4, 0xd5, 0xe5, 0xf7}}; QuicPathResponseFrame path_response_frame(8, buffer); EXPECT_EQ(QuicFramer::GetPathResponseFrameSize(path_response_frame), QuicFramer::GetRetransmittableControlFrameSize( framer_.transport_version(), QuicFrame(path_response_frame))); QuicPathChallengeFrame path_challenge_frame(9, buffer); EXPECT_EQ(QuicFramer::GetPathChallengeFrameSize(path_challenge_frame), QuicFramer::GetRetransmittableControlFrameSize( framer_.transport_version(), QuicFrame(path_challenge_frame))); QuicStopSendingFrame stop_sending_frame(10, 3, QUIC_STREAM_CANCELLED); EXPECT_EQ(QuicFramer::GetStopSendingFrameSize(stop_sending_frame), QuicFramer::GetRetransmittableControlFrameSize( framer_.transport_version(), QuicFrame(stop_sending_frame))); } TEST_P(QuicFramerTest, IetfFrameTypeEncodingErrorUnknown1Byte) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {0x38}} }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet)); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsError(QUIC_INVALID_FRAME_DATA)); EXPECT_EQ("Illegal frame type.", framer_.detailed_error()); } TEST_P(QuicFramerTest, IetfFrameTypeEncodingErrorUnknown2Bytes) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x01, 0x38}} }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet)); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsError(QUIC_INVALID_FRAME_DATA)); EXPECT_EQ("Illegal frame type.", framer_.detailed_error()); } TEST_P(QuicFramerTest, IetfFrameTypeEncodingErrorUnknown4Bytes) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62FourBytes + 0x01, 0x00, 0x00, 0x38}} }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet)); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsError(QUIC_INVALID_FRAME_DATA)); EXPECT_EQ("Illegal frame type.", framer_.detailed_error()); } TEST_P(QuicFramerTest, IetfFrameTypeEncodingErrorUnknown8Bytes) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62EightBytes + 0x01, 0x00, 0x00, 0x01, 0x02, 0x34, 0x56, 0x38}} }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet)); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsError(QUIC_INVALID_FRAME_DATA)); EXPECT_EQ("Illegal frame type.", framer_.detailed_error()); } TEST_P(QuicFramerTest, IetfFrameTypeEncodingErrorKnown2Bytes) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x08}} }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet)); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsError(IETF_QUIC_PROTOCOL_VIOLATION)); EXPECT_EQ("Frame type not minimally encoded.", framer_.detailed_error()); } TEST_P(QuicFramerTest, IetfFrameTypeEncodingErrorKnown4Bytes) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62FourBytes + 0x00, 0x00, 0x00, 0x08}} }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet)); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsError(IETF_QUIC_PROTOCOL_VIOLATION)); EXPECT_EQ("Frame type not minimally encoded.", framer_.detailed_error()); } TEST_P(QuicFramerTest, IetfFrameTypeEncodingErrorKnown8Bytes) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62EightBytes + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08}} }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet)); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsError(IETF_QUIC_PROTOCOL_VIOLATION)); EXPECT_EQ("Frame type not minimally encoded.", framer_.detailed_error()); } TEST_P(QuicFramerTest, IetfFrameTypeEncodingErrorKnown2BytesAllTypes) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packets[] = { { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x00}} }, { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x01}} }, { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x02}} }, { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x03}} }, { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x04}} }, { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x05}} }, { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x06}} }, { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x07}} }, { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x08}} }, { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x09}} }, { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x0a}} }, { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x0b}} }, { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x0c}} }, { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x0d}} }, { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x0e}} }, { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x0f}} }, { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x10}} }, { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x11}} }, { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x12}} }, { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x13}} }, { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x14}} }, { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x15}} }, { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x16}} }, { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x17}} }, { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x18}} }, { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x20}} }, { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x9A, 0xBC}}, {"", {kVarInt62TwoBytes + 0x00, 0x21}} }, }; for (PacketFragments& packet : packets) { std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet)); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsError(IETF_QUIC_PROTOCOL_VIOLATION)); EXPECT_EQ("Frame type not minimally encoded.", framer_.detailed_error()); } } TEST_P(QuicFramerTest, RetireConnectionIdFrame) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); PacketFragments packet_ietf = { {"", {0x43}}, {"", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}}, {"", {0x12, 0x34, 0x56, 0x78}}, {"", {0x19}}, {"Unable to read retire connection ID frame sequence number.", {kVarInt62TwoBytes + 0x11, 0x22}} }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet_ietf)); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_TRUE(CheckDecryption( *encrypted, !kIncludeVersion, !kIncludeDiversificationNonce, kPacket8ByteConnectionId, kPacket0ByteConnectionId)); EXPECT_EQ(0u, visitor_.stream_frames_.size()); EXPECT_EQ(0x1122u, visitor_.retire_connection_id_.sequence_number); ASSERT_EQ(0u, visitor_.ack_frames_.size()); CheckFramingBoundaries(packet_ietf, QUIC_INVALID_RETIRE_CONNECTION_ID_DATA); } TEST_P(QuicFramerTest, BuildRetireConnectionIdFramePacket) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicRetireConnectionIdFrame frame; frame.sequence_number = 0x1122; QuicFrames frames = {QuicFrame(&frame)}; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x19, kVarInt62TwoBytes + 0x11, 0x22 }; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); quiche::test::CompareCharArraysWithHexError( "constructed packet", data->data(), data->length(), AsChars(packet_ietf), ABSL_ARRAYSIZE(packet_ietf)); } TEST_P(QuicFramerTest, AckFrameWithInvalidLargestObserved) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x45, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x02, kVarInt62OneByte + 0x00, kVarInt62OneByte + 0x00, kVarInt62OneByte + 0x00, kVarInt62OneByte + 0x00, }; unsigned char* p = packet; size_t p_size = ABSL_ARRAYSIZE(packet); if (VersionHasIetfQuicFrames(framer_.transport_version())) { p = packet_ietf; p_size = ABSL_ARRAYSIZE(packet_ietf); } QuicEncryptedPacket encrypted(AsChars(p), p_size, false); EXPECT_FALSE(framer_.ProcessPacket(encrypted)); EXPECT_EQ(framer_.detailed_error(), "Largest acked is 0."); } TEST_P(QuicFramerTest, FirstAckBlockJustUnderFlow) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x45, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00 }; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x02, kVarInt62OneByte + 0x02, kVarInt62OneByte + 0x00, kVarInt62OneByte + 0x00, kVarInt62OneByte + 0x02, }; unsigned char* p = packet; size_t p_size = ABSL_ARRAYSIZE(packet); if (VersionHasIetfQuicFrames(framer_.transport_version())) { p = packet_ietf; p_size = ABSL_ARRAYSIZE(packet_ietf); } QuicEncryptedPacket encrypted(AsChars(p), p_size, false); EXPECT_FALSE(framer_.ProcessPacket(encrypted)); EXPECT_EQ(framer_.detailed_error(), "Underflow with first ack block length 3 largest acked is 2."); } TEST_P(QuicFramerTest, ThirdAckBlockJustUnderflow) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x60, 0x0A, 0x00, 0x00, 0x02, 0x02, 0x01, 0x01, 0x01, 0x06, 0x00 }; unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x02, kVarInt62OneByte + 0x0A, kVarInt62OneByte + 0x00, kVarInt62OneByte + 0x02, kVarInt62OneByte + 0x01, kVarInt62OneByte + 0x00, kVarInt62OneByte + 0x00, kVarInt62OneByte + 0x00, kVarInt62OneByte + 0x05, }; unsigned char* p = packet; size_t p_size = ABSL_ARRAYSIZE(packet); if (VersionHasIetfQuicFrames(framer_.transport_version())) { p = packet_ietf; p_size = ABSL_ARRAYSIZE(packet_ietf); } QuicEncryptedPacket encrypted(AsChars(p), p_size, false); EXPECT_FALSE(framer_.ProcessPacket(encrypted)); if (VersionHasIetfQuicFrames(framer_.transport_version())) { EXPECT_EQ(framer_.detailed_error(), "Underflow with ack block length 6 latest ack block end is 5."); } else { EXPECT_EQ(framer_.detailed_error(), "Underflow with ack block length 6, end of block is 6."); } } TEST_P(QuicFramerTest, CoalescedPacket) { if (!QuicVersionHasLongHeaderLengths(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_ZERO_RTT); unsigned char packet[] = { 0xD3, QUIC_VERSION_BYTES, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x1E, 0x12, 0x34, 0x56, 0x78, 0xFE, 0x02, 0x03, 0x04, 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, 0x00, 0x0c, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', 0xD3, QUIC_VERSION_BYTES, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x1E, 0x12, 0x34, 0x56, 0x79, 0xFE, 0x02, 0x03, 0x04, 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, 0x00, 0x0c, 'H', 'E', 'L', 'L', 'O', '_', 'W', 'O', 'R', 'L', 'D', '?', }; unsigned char packet_ietf[] = { 0xD3, QUIC_VERSION_BYTES, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x1E, 0x12, 0x34, 0x56, 0x78, 0x08 | 0x01 | 0x02 | 0x04, kVarInt62FourBytes + 0x00, 0x02, 0x03, 0x04, kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, kVarInt62OneByte + 0x0c, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', 0xD3, QUIC_VERSION_BYTES, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x1E, 0x12, 0x34, 0x56, 0x79, 0x08 | 0x01 | 0x02 | 0x04, kVarInt62FourBytes + 0x00, 0x02, 0x03, 0x04, kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, kVarInt62OneByte + 0x0c, 'H', 'E', 'L', 'L', 'O', '_', 'W', 'O', 'R', 'L', 'D', '?', }; const size_t first_packet_ietf_size = 46; EXPECT_EQ(packet_ietf[first_packet_ietf_size], 0xD3); unsigned char* p = packet; size_t p_length = ABSL_ARRAYSIZE(packet); if (framer_.version().HasIetfQuicFrames()) { ReviseFirstByteByVersion(packet_ietf); ReviseFirstByteByVersion(&packet_ietf[first_packet_ietf_size]); p = packet_ietf; p_length = ABSL_ARRAYSIZE(packet_ietf); } QuicEncryptedPacket encrypted(AsChars(p), p_length, false); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); ASSERT_EQ(1u, visitor_.stream_frames_.size()); EXPECT_EQ(0u, visitor_.ack_frames_.size()); EXPECT_EQ(0x00FFFFFF & kStreamId, visitor_.stream_frames_[0]->stream_id); EXPECT_TRUE(visitor_.stream_frames_[0]->fin); EXPECT_EQ(kStreamOffset, visitor_.stream_frames_[0]->offset); CheckStreamFrameData("hello world!", visitor_.stream_frames_[0].get()); ASSERT_EQ(visitor_.coalesced_packets_.size(), 1u); EXPECT_TRUE(framer_.ProcessPacket(*visitor_.coalesced_packets_[0].get())); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); ASSERT_EQ(2u, visitor_.stream_frames_.size()); EXPECT_EQ(0u, visitor_.ack_frames_.size()); EXPECT_EQ(0x00FFFFFF & kStreamId, visitor_.stream_frames_[1]->stream_id); EXPECT_TRUE(visitor_.stream_frames_[1]->fin); EXPECT_EQ(kStreamOffset, visitor_.stream_frames_[1]->offset); CheckStreamFrameData("HELLO_WORLD?", visitor_.stream_frames_[1].get()); } TEST_P(QuicFramerTest, CoalescedPacketWithUdpPadding) { if (!framer_.version().HasLongHeaderLengths()) { return; } SetDecrypterLevel(ENCRYPTION_ZERO_RTT); unsigned char packet[] = { 0xD3, QUIC_VERSION_BYTES, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x1E, 0x12, 0x34, 0x56, 0x78, 0xFE, 0x02, 0x03, 0x04, 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, 0x00, 0x0c, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; unsigned char packet_ietf[] = { 0xD3, QUIC_VERSION_BYTES, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x1E, 0x12, 0x34, 0x56, 0x78, 0x08 | 0x01 | 0x02 | 0x04, kVarInt62FourBytes + 0x00, 0x02, 0x03, 0x04, kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, kVarInt62OneByte + 0x0c, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; unsigned char* p = packet; size_t p_length = ABSL_ARRAYSIZE(packet); if (framer_.version().HasIetfQuicFrames()) { ReviseFirstByteByVersion(packet_ietf); p = packet_ietf; p_length = ABSL_ARRAYSIZE(packet_ietf); } QuicEncryptedPacket encrypted(AsChars(p), p_length, false); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); ASSERT_EQ(1u, visitor_.stream_frames_.size()); EXPECT_EQ(0u, visitor_.ack_frames_.size()); EXPECT_EQ(0x00FFFFFF & kStreamId, visitor_.stream_frames_[0]->stream_id); EXPECT_TRUE(visitor_.stream_frames_[0]->fin); EXPECT_EQ(kStreamOffset, visitor_.stream_frames_[0]->offset); CheckStreamFrameData("hello world!", visitor_.stream_frames_[0].get()); EXPECT_EQ(visitor_.coalesced_packets_.size(), 0u); } TEST_P(QuicFramerTest, CoalescedPacketWithDifferentVersion) { if (!QuicVersionHasLongHeaderLengths(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_ZERO_RTT); unsigned char packet[] = { 0xD3, QUIC_VERSION_BYTES, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x1E, 0x12, 0x34, 0x56, 0x78, 0xFE, 0x02, 0x03, 0x04, 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, 0x00, 0x0c, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', 0xD3, 'G', 'A', 'B', 'G', 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x1E, 0x12, 0x34, 0x56, 0x79, 0xFE, 0x02, 0x03, 0x04, 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, 0x00, 0x0c, 'H', 'E', 'L', 'L', 'O', '_', 'W', 'O', 'R', 'L', 'D', '?', }; unsigned char packet_ietf[] = { 0xD3, QUIC_VERSION_BYTES, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x1E, 0x12, 0x34, 0x56, 0x78, 0x08 | 0x01 | 0x02 | 0x04, kVarInt62FourBytes + 0x00, 0x02, 0x03, 0x04, kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, kVarInt62OneByte + 0x0c, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', 0xD3, 'G', 'A', 'B', 'G', 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x1E, 0x12, 0x34, 0x56, 0x79, 0x08 | 0x01 | 0x02 | 0x04, kVarInt62FourBytes + 0x00, 0x02, 0x03, 0x04, kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, kVarInt62OneByte + 0x0c, 'H', 'E', 'L', 'L', 'O', '_', 'W', 'O', 'R', 'L', 'D', '?', }; const size_t first_packet_ietf_size = 46; EXPECT_EQ(packet_ietf[first_packet_ietf_size], 0xD3); unsigned char* p = packet; size_t p_length = ABSL_ARRAYSIZE(packet); if (framer_.version().HasIetfQuicFrames()) { ReviseFirstByteByVersion(packet_ietf); ReviseFirstByteByVersion(&packet_ietf[first_packet_ietf_size]); p = packet_ietf; p_length = ABSL_ARRAYSIZE(packet_ietf); } QuicEncryptedPacket encrypted(AsChars(p), p_length, false); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); ASSERT_EQ(1u, visitor_.stream_frames_.size()); EXPECT_EQ(0u, visitor_.ack_frames_.size()); EXPECT_EQ(0x00FFFFFF & kStreamId, visitor_.stream_frames_[0]->stream_id); EXPECT_TRUE(visitor_.stream_frames_[0]->fin); EXPECT_EQ(kStreamOffset, visitor_.stream_frames_[0]->offset); CheckStreamFrameData("hello world!", visitor_.stream_frames_[0].get()); ASSERT_EQ(visitor_.coalesced_packets_.size(), 1u); EXPECT_TRUE(framer_.ProcessPacket(*visitor_.coalesced_packets_[0].get())); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); ASSERT_EQ(1u, visitor_.stream_frames_.size()); EXPECT_EQ(1, visitor_.version_mismatch_); } TEST_P(QuicFramerTest, UndecryptablePacketWithoutDecrypter) { QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); if (!framer_.version().KnowsWhichDecrypterToUse()) { QuicConnectionId bogus_connection_id = TestConnectionId(0xbad); CrypterPair bogus_crypters; CryptoUtils::CreateInitialObfuscators(Perspective::IS_CLIENT, framer_.version(), bogus_connection_id, &bogus_crypters); framer_.SetDecrypter(ENCRYPTION_FORWARD_SECURE, std::move(bogus_crypters.decrypter)); } unsigned char packet[] = { 0xE3, QUIC_VERSION_BYTES, 0x05, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x05, 0x12, 0x34, 0x56, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; unsigned char packet49[] = { 0xE3, QUIC_VERSION_BYTES, 0x00, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x24, 0x12, 0x34, 0x56, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; unsigned char* p = packet; size_t p_length = ABSL_ARRAYSIZE(packet); if (framer_.version().HasLongHeaderLengths()) { ReviseFirstByteByVersion(packet49); p = packet49; p_length = ABSL_ARRAYSIZE(packet49); } EXPECT_FALSE( framer_.ProcessPacket(QuicEncryptedPacket(AsChars(p), p_length, false))); EXPECT_THAT(framer_.error(), IsError(QUIC_DECRYPTION_FAILURE)); ASSERT_EQ(1u, visitor_.undecryptable_packets_.size()); ASSERT_EQ(1u, visitor_.undecryptable_decryption_levels_.size()); ASSERT_EQ(1u, visitor_.undecryptable_has_decryption_keys_.size()); quiche::test::CompareCharArraysWithHexError( "undecryptable packet", visitor_.undecryptable_packets_[0]->data(), visitor_.undecryptable_packets_[0]->length(), AsChars(p), p_length); if (framer_.version().KnowsWhichDecrypterToUse()) { EXPECT_EQ(ENCRYPTION_HANDSHAKE, visitor_.undecryptable_decryption_levels_[0]); } EXPECT_FALSE(visitor_.undecryptable_has_decryption_keys_[0]); } TEST_P(QuicFramerTest, UndecryptablePacketWithDecrypter) { QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicConnectionId bogus_connection_id = TestConnectionId(0xbad); CrypterPair bad_handshake_crypters; CryptoUtils::CreateInitialObfuscators(Perspective::IS_CLIENT, framer_.version(), bogus_connection_id, &bad_handshake_crypters); if (framer_.version().KnowsWhichDecrypterToUse()) { framer_.InstallDecrypter(ENCRYPTION_HANDSHAKE, std::move(bad_handshake_crypters.decrypter)); } else { framer_.SetDecrypter(ENCRYPTION_HANDSHAKE, std::move(bad_handshake_crypters.decrypter)); } unsigned char packet[] = { 0xE3, QUIC_VERSION_BYTES, 0x05, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x05, 0x12, 0x34, 0x56, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; unsigned char packet49[] = { 0xE3, QUIC_VERSION_BYTES, 0x00, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x24, 0x12, 0x34, 0x56, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; unsigned char* p = packet; size_t p_length = ABSL_ARRAYSIZE(packet); if (framer_.version().HasLongHeaderLengths()) { ReviseFirstByteByVersion(packet49); p = packet49; p_length = ABSL_ARRAYSIZE(packet49); } EXPECT_FALSE( framer_.ProcessPacket(QuicEncryptedPacket(AsChars(p), p_length, false))); EXPECT_THAT(framer_.error(), IsError(QUIC_DECRYPTION_FAILURE)); ASSERT_EQ(1u, visitor_.undecryptable_packets_.size()); ASSERT_EQ(1u, visitor_.undecryptable_decryption_levels_.size()); ASSERT_EQ(1u, visitor_.undecryptable_has_decryption_keys_.size()); quiche::test::CompareCharArraysWithHexError( "undecryptable packet", visitor_.undecryptable_packets_[0]->data(), visitor_.undecryptable_packets_[0]->length(), AsChars(p), p_length); if (framer_.version().KnowsWhichDecrypterToUse()) { EXPECT_EQ(ENCRYPTION_HANDSHAKE, visitor_.undecryptable_decryption_levels_[0]); } EXPECT_EQ(framer_.version().KnowsWhichDecrypterToUse(), visitor_.undecryptable_has_decryption_keys_[0]); } TEST_P(QuicFramerTest, UndecryptableCoalescedPacket) { if (!QuicVersionHasLongHeaderLengths(framer_.transport_version())) { return; } ASSERT_TRUE(framer_.version().KnowsWhichDecrypterToUse()); SetDecrypterLevel(ENCRYPTION_ZERO_RTT); QuicConnectionId bogus_connection_id = TestConnectionId(0xbad); CrypterPair bad_handshake_crypters; CryptoUtils::CreateInitialObfuscators(Perspective::IS_CLIENT, framer_.version(), bogus_connection_id, &bad_handshake_crypters); framer_.InstallDecrypter(ENCRYPTION_HANDSHAKE, std::move(bad_handshake_crypters.decrypter)); unsigned char packet[] = { 0xE3, QUIC_VERSION_BYTES, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x1E, 0x12, 0x34, 0x56, 0x78, 0xFE, 0x02, 0x03, 0x04, 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, 0x00, 0x0c, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', 0xD3, QUIC_VERSION_BYTES, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x1E, 0x12, 0x34, 0x56, 0x79, 0xFE, 0x02, 0x03, 0x04, 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, 0x00, 0x0c, 'H', 'E', 'L', 'L', 'O', '_', 'W', 'O', 'R', 'L', 'D', '?', }; unsigned char packet_ietf[] = { 0xE3, QUIC_VERSION_BYTES, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x1E, 0x12, 0x34, 0x56, 0x78, 0x08 | 0x01 | 0x02 | 0x04, kVarInt62FourBytes + 0x00, 0x02, 0x03, 0x04, kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, kVarInt62OneByte + 0x0c, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', 0xD3, QUIC_VERSION_BYTES, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x1E, 0x12, 0x34, 0x56, 0x79, 0x08 | 0x01 | 0x02 | 0x04, kVarInt62FourBytes + 0x00, 0x02, 0x03, 0x04, kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, kVarInt62OneByte + 0x0c, 'H', 'E', 'L', 'L', 'O', '_', 'W', 'O', 'R', 'L', 'D', '?', }; const size_t length_of_first_coalesced_packet = 46; EXPECT_EQ(packet_ietf[length_of_first_coalesced_packet], 0xD3); unsigned char* p = packet; size_t p_length = ABSL_ARRAYSIZE(packet); if (framer_.version().HasIetfQuicFrames()) { ReviseFirstByteByVersion(packet_ietf); ReviseFirstByteByVersion(&packet_ietf[length_of_first_coalesced_packet]); p = packet_ietf; p_length = ABSL_ARRAYSIZE(packet_ietf); } QuicEncryptedPacket encrypted(AsChars(p), p_length, false); EXPECT_FALSE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsError(QUIC_DECRYPTION_FAILURE)); ASSERT_EQ(1u, visitor_.undecryptable_packets_.size()); ASSERT_EQ(1u, visitor_.undecryptable_decryption_levels_.size()); ASSERT_EQ(1u, visitor_.undecryptable_has_decryption_keys_.size()); quiche::test::CompareCharArraysWithHexError( "undecryptable packet", visitor_.undecryptable_packets_[0]->data(), visitor_.undecryptable_packets_[0]->length(), AsChars(p), length_of_first_coalesced_packet); EXPECT_EQ(ENCRYPTION_HANDSHAKE, visitor_.undecryptable_decryption_levels_[0]); EXPECT_TRUE(visitor_.undecryptable_has_decryption_keys_[0]); ASSERT_EQ(visitor_.coalesced_packets_.size(), 1u); EXPECT_TRUE(framer_.ProcessPacket(*visitor_.coalesced_packets_[0].get())); ASSERT_TRUE(visitor_.header_.get()); ASSERT_EQ(1u, visitor_.stream_frames_.size()); EXPECT_EQ(0u, visitor_.ack_frames_.size()); EXPECT_EQ(0x00FFFFFF & kStreamId, visitor_.stream_frames_[0]->stream_id); EXPECT_TRUE(visitor_.stream_frames_[0]->fin); EXPECT_EQ(kStreamOffset, visitor_.stream_frames_[0]->offset); CheckStreamFrameData("HELLO_WORLD?", visitor_.stream_frames_[0].get()); } TEST_P(QuicFramerTest, MismatchedCoalescedPacket) { if (!QuicVersionHasLongHeaderLengths(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_ZERO_RTT); unsigned char packet[] = { 0xD3, QUIC_VERSION_BYTES, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x1E, 0x12, 0x34, 0x56, 0x78, 0xFE, 0x02, 0x03, 0x04, 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, 0x00, 0x0c, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', 0xD3, QUIC_VERSION_BYTES, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x11, 0x00, 0x1E, 0x12, 0x34, 0x56, 0x79, 0xFE, 0x02, 0x03, 0x04, 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, 0x00, 0x0c, 'H', 'E', 'L', 'L', 'O', '_', 'W', 'O', 'R', 'L', 'D', '?', }; unsigned char packet_ietf[] = { 0xD3, QUIC_VERSION_BYTES, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x1E, 0x12, 0x34, 0x56, 0x78, 0x08 | 0x01 | 0x02 | 0x04, kVarInt62FourBytes + 0x00, 0x02, 0x03, 0x04, kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, kVarInt62OneByte + 0x0c, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', 0xD3, QUIC_VERSION_BYTES, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x11, 0x00, 0x1E, 0x12, 0x34, 0x56, 0x79, 0x08 | 0x01 | 0x02 | 0x04, kVarInt62FourBytes + 0x00, 0x02, 0x03, 0x04, kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, kVarInt62OneByte + 0x0c, 'H', 'E', 'L', 'L', 'O', '_', 'W', 'O', 'R', 'L', 'D', '?', }; const size_t length_of_first_coalesced_packet = 46; EXPECT_EQ(packet_ietf[length_of_first_coalesced_packet], 0xD3); unsigned char* p = packet; size_t p_length = ABSL_ARRAYSIZE(packet); if (framer_.version().HasIetfQuicFrames()) { ReviseFirstByteByVersion(packet_ietf); ReviseFirstByteByVersion(&packet_ietf[length_of_first_coalesced_packet]); p = packet_ietf; p_length = ABSL_ARRAYSIZE(packet_ietf); } QuicEncryptedPacket encrypted(AsChars(p), p_length, false); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); ASSERT_EQ(1u, visitor_.stream_frames_.size()); EXPECT_EQ(0u, visitor_.ack_frames_.size()); EXPECT_EQ(0x00FFFFFF & kStreamId, visitor_.stream_frames_[0]->stream_id); EXPECT_TRUE(visitor_.stream_frames_[0]->fin); EXPECT_EQ(kStreamOffset, visitor_.stream_frames_[0]->offset); CheckStreamFrameData("hello world!", visitor_.stream_frames_[0].get()); ASSERT_EQ(visitor_.coalesced_packets_.size(), 0u); } TEST_P(QuicFramerTest, InvalidCoalescedPacket) { if (!QuicVersionHasLongHeaderLengths(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_ZERO_RTT); unsigned char packet[] = { 0xD3, QUIC_VERSION_BYTES, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x1E, 0x12, 0x34, 0x56, 0x78, 0xFE, 0x02, 0x03, 0x04, 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, 0x00, 0x0c, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', 0xD3, }; unsigned char packet_ietf[] = { 0xD3, QUIC_VERSION_BYTES, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x1E, 0x12, 0x34, 0x56, 0x78, 0x08 | 0x01 | 0x02 | 0x04, kVarInt62FourBytes + 0x00, 0x02, 0x03, 0x04, kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, kVarInt62OneByte + 0x0c, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', 0xD3, }; const size_t length_of_first_coalesced_packet = 46; EXPECT_EQ(packet_ietf[length_of_first_coalesced_packet], 0xD3); unsigned char* p = packet; size_t p_length = ABSL_ARRAYSIZE(packet); if (framer_.version().HasIetfQuicFrames()) { ReviseFirstByteByVersion(packet_ietf); ReviseFirstByteByVersion(&packet_ietf[length_of_first_coalesced_packet]); p = packet_ietf; p_length = ABSL_ARRAYSIZE(packet_ietf); } QuicEncryptedPacket encrypted(AsChars(p), p_length, false); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); ASSERT_TRUE(visitor_.header_.get()); ASSERT_EQ(1u, visitor_.stream_frames_.size()); EXPECT_EQ(0u, visitor_.ack_frames_.size()); EXPECT_EQ(0x00FFFFFF & kStreamId, visitor_.stream_frames_[0]->stream_id); EXPECT_TRUE(visitor_.stream_frames_[0]->fin); EXPECT_EQ(kStreamOffset, visitor_.stream_frames_[0]->offset); CheckStreamFrameData("hello world!", visitor_.stream_frames_[0].get()); ASSERT_EQ(visitor_.coalesced_packets_.size(), 0u); } TEST_P(QuicFramerTest, CoalescedPacketWithZeroesRoundTrip) { if (!QuicVersionHasLongHeaderLengths(framer_.transport_version()) || !framer_.version().UsesInitialObfuscators()) { return; } ASSERT_TRUE(framer_.version().KnowsWhichDecrypterToUse()); QuicConnectionId connection_id = FramerTestConnectionId(); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); CrypterPair client_crypters; CryptoUtils::CreateInitialObfuscators(Perspective::IS_CLIENT, framer_.version(), connection_id, &client_crypters); framer_.SetEncrypter(ENCRYPTION_INITIAL, std::move(client_crypters.encrypter)); QuicPacketHeader header; header.destination_connection_id = connection_id; header.version_flag = true; header.packet_number = kPacketNumber; header.packet_number_length = PACKET_4BYTE_PACKET_NUMBER; header.long_packet_type = INITIAL; header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2; header.retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1; QuicFrames frames = {QuicFrame(QuicPingFrame()), QuicFrame(QuicPaddingFrame(3))}; std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_NE(nullptr, data); unsigned char packet[kMaxOutgoingPacketSize] = {}; size_t encrypted_length = framer_.EncryptPayload(ENCRYPTION_INITIAL, header.packet_number, *data, AsChars(packet), ABSL_ARRAYSIZE(packet)); ASSERT_NE(0u, encrypted_length); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); CrypterPair server_crypters; CryptoUtils::CreateInitialObfuscators(Perspective::IS_SERVER, framer_.version(), connection_id, &server_crypters); framer_.InstallDecrypter(ENCRYPTION_INITIAL, std::move(server_crypters.decrypter)); QuicEncryptedPacket encrypted(AsChars(packet), ABSL_ARRAYSIZE(packet), false); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); EXPECT_TRUE(visitor_.coalesced_packets_.empty()); } TEST_P(QuicFramerTest, ClientReceivesWrongVersion) { QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); unsigned char packet[] = { 0xC3, 'Q', '0', '4', '3', 0x05, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x01, 0x00, }; QuicEncryptedPacket encrypted(AsChars(packet), ABSL_ARRAYSIZE(packet), false); EXPECT_FALSE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsError(QUIC_PACKET_WRONG_VERSION)); EXPECT_EQ("Client received unexpected version.", framer_.detailed_error()); } TEST_P(QuicFramerTest, PacketHeaderWithVariableLengthConnectionId) { if (!framer_.version().AllowsVariableLengthConnectionIds()) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); uint8_t connection_id_bytes[9] = {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x42}; QuicConnectionId connection_id(reinterpret_cast<char*>(connection_id_bytes), sizeof(connection_id_bytes)); QuicFramerPeer::SetLargestPacketNumber(&framer_, kPacketNumber - 2); QuicFramerPeer::SetExpectedServerConnectionIDLength(&framer_, connection_id.length()); PacketFragments packet = { {"Unable to read first byte.", {0x40}}, {"Unable to read destination connection ID.", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x42}}, {"Unable to read packet number.", {0x78}}, }; PacketFragments packet_with_padding = { {"Unable to read first byte.", {0x40}}, {"Unable to read destination connection ID.", {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x42}}, {"", {0x78}}, {"", {0x00, 0x00, 0x00}}, }; PacketFragments& fragments = framer_.version().HasHeaderProtection() ? packet_with_padding : packet; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(fragments)); if (framer_.version().HasHeaderProtection()) { EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); } else { EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsError(QUIC_MISSING_PAYLOAD)); } ASSERT_TRUE(visitor_.header_.get()); EXPECT_EQ(connection_id, visitor_.header_->destination_connection_id); EXPECT_FALSE(visitor_.header_->reset_flag); EXPECT_FALSE(visitor_.header_->version_flag); EXPECT_EQ(PACKET_1BYTE_PACKET_NUMBER, visitor_.header_->packet_number_length); EXPECT_EQ(kPacketNumber, visitor_.header_->packet_number); CheckFramingBoundaries(fragments, QUIC_INVALID_PACKET_HEADER); } TEST_P(QuicFramerTest, MultiplePacketNumberSpaces) { framer_.EnableMultiplePacketNumberSpacesSupport(); unsigned char long_header_packet[] = { 0xD3, QUIC_VERSION_BYTES, 0x50, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x00, }; unsigned char long_header_packet_ietf[] = { 0xD3, QUIC_VERSION_BYTES, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x05, 0x12, 0x34, 0x56, 0x78, 0x00, }; if (framer_.version().KnowsWhichDecrypterToUse()) { framer_.InstallDecrypter(ENCRYPTION_ZERO_RTT, std::make_unique<TestDecrypter>()); framer_.RemoveDecrypter(ENCRYPTION_INITIAL); } else { framer_.SetDecrypter(ENCRYPTION_ZERO_RTT, std::make_unique<TestDecrypter>()); } if (!QuicVersionHasLongHeaderLengths(framer_.transport_version())) { EXPECT_TRUE(framer_.ProcessPacket( QuicEncryptedPacket(AsChars(long_header_packet), ABSL_ARRAYSIZE(long_header_packet), false))); } else { ReviseFirstByteByVersion(long_header_packet_ietf); EXPECT_TRUE(framer_.ProcessPacket( QuicEncryptedPacket(AsChars(long_header_packet_ietf), ABSL_ARRAYSIZE(long_header_packet_ietf), false))); } EXPECT_THAT(framer_.error(), IsQuicNoError()); EXPECT_FALSE( QuicFramerPeer::GetLargestDecryptedPacketNumber(&framer_, INITIAL_DATA) .IsInitialized()); EXPECT_FALSE( QuicFramerPeer::GetLargestDecryptedPacketNumber(&framer_, HANDSHAKE_DATA) .IsInitialized()); EXPECT_EQ(kPacketNumber, QuicFramerPeer::GetLargestDecryptedPacketNumber( &framer_, APPLICATION_DATA)); unsigned char short_header_packet[] = { 0x40, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x79, 0x00, 0x00, 0x00, }; QuicEncryptedPacket short_header_encrypted( AsChars(short_header_packet), ABSL_ARRAYSIZE(short_header_packet), false); if (framer_.version().KnowsWhichDecrypterToUse()) { framer_.InstallDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<TestDecrypter>()); framer_.RemoveDecrypter(ENCRYPTION_ZERO_RTT); } else { framer_.SetDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<TestDecrypter>()); } EXPECT_TRUE(framer_.ProcessPacket(short_header_encrypted)); EXPECT_THAT(framer_.error(), IsQuicNoError()); EXPECT_FALSE( QuicFramerPeer::GetLargestDecryptedPacketNumber(&framer_, INITIAL_DATA) .IsInitialized()); EXPECT_FALSE( QuicFramerPeer::GetLargestDecryptedPacketNumber(&framer_, HANDSHAKE_DATA) .IsInitialized()); EXPECT_EQ(kPacketNumber + 1, QuicFramerPeer::GetLargestDecryptedPacketNumber( &framer_, APPLICATION_DATA)); } TEST_P(QuicFramerTest, IetfRetryPacketRejected) { if (!framer_.version().KnowsWhichDecrypterToUse() || framer_.version().SupportsRetry()) { return; } PacketFragments packet = { {"Unable to read first byte.", {0xf0}}, {"Unable to read protocol version.", {QUIC_VERSION_BYTES}}, {"RETRY not supported in this version.", {0x00}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet)); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsError(QUIC_INVALID_PACKET_HEADER)); CheckFramingBoundaries(packet, QUIC_INVALID_PACKET_HEADER); } TEST_P(QuicFramerTest, RetryPacketRejectedWithMultiplePacketNumberSpaces) { if (framer_.version().SupportsRetry()) { return; } framer_.EnableMultiplePacketNumberSpacesSupport(); PacketFragments packet = { {"Unable to read first byte.", {0xf0}}, {"Unable to read protocol version.", {QUIC_VERSION_BYTES}}, {"RETRY not supported in this version.", {0x00}}, }; std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet)); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_THAT(framer_.error(), IsError(QUIC_INVALID_PACKET_HEADER)); CheckFramingBoundaries(packet, QUIC_INVALID_PACKET_HEADER); } TEST_P(QuicFramerTest, WriteClientVersionNegotiationProbePacket) { static const uint8_t expected_packet[1200] = { 0xc0, 0xca, 0xba, 0xda, 0xda, 0x08, 0x56, 0x4e, 0x20, 0x70, 0x6c, 0x7a, 0x20, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x54, 0x68, 0x69, 0x73, 0x20, 0x70, 0x61, 0x63, 0x6b, 0x65, 0x74, 0x20, 0x6f, 0x6e, 0x6c, 0x79, 0x20, 0x65, 0x78, 0x69, 0x73, 0x74, 0x73, 0x20, 0x74, 0x6f, 0x20, 0x74, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x20, 0x49, 0x45, 0x54, 0x46, 0x20, 0x51, 0x55, 0x49, 0x43, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x6e, 0x65, 0x67, 0x6f, 0x74, 0x69, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x20, 0x50, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x20, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x61, 0x20, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x4e, 0x65, 0x67, 0x6f, 0x74, 0x69, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x70, 0x61, 0x63, 0x6b, 0x65, 0x74, 0x20, 0x69, 0x6e, 0x64, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x77, 0x68, 0x61, 0x74, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x20, 0x79, 0x6f, 0x75, 0x20, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x20, 0x54, 0x68, 0x61, 0x6e, 0x6b, 0x20, 0x79, 0x6f, 0x75, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x68, 0x61, 0x76, 0x65, 0x20, 0x61, 0x20, 0x6e, 0x69, 0x63, 0x65, 0x20, 0x64, 0x61, 0x79, 0x2e, 0x00, }; char packet[1200]; char destination_connection_id_bytes[] = {0x56, 0x4e, 0x20, 0x70, 0x6c, 0x7a, 0x20, 0x21}; EXPECT_TRUE(QuicFramer::WriteClientVersionNegotiationProbePacket( packet, sizeof(packet), destination_connection_id_bytes, sizeof(destination_connection_id_bytes))); quiche::test::CompareCharArraysWithHexError( "constructed packet", packet, sizeof(packet), reinterpret_cast<const char*>(expected_packet), sizeof(expected_packet)); QuicEncryptedPacket encrypted(reinterpret_cast<const char*>(packet), sizeof(packet), false); if (!framer_.version().HasLengthPrefixedConnectionIds()) { EXPECT_FALSE(framer_.ProcessPacket(encrypted)); return; } EXPECT_TRUE(framer_.ProcessPacket(encrypted)); ASSERT_TRUE(visitor_.header_.get()); QuicConnectionId probe_payload_connection_id( reinterpret_cast<const char*>(destination_connection_id_bytes), sizeof(destination_connection_id_bytes)); EXPECT_EQ(probe_payload_connection_id, visitor_.header_.get()->destination_connection_id); } TEST_P(QuicFramerTest, DispatcherParseOldClientVersionNegotiationProbePacket) { static const uint8_t packet[1200] = { 0xc0, 0xca, 0xba, 0xda, 0xba, 0x50, 0x56, 0x4e, 0x20, 0x70, 0x6c, 0x7a, 0x20, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x54, 0x68, 0x69, 0x73, 0x20, 0x70, 0x61, 0x63, 0x6b, 0x65, 0x74, 0x20, 0x6f, 0x6e, 0x6c, 0x79, 0x20, 0x65, 0x78, 0x69, 0x73, 0x74, 0x73, 0x20, 0x74, 0x6f, 0x20, 0x74, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x20, 0x49, 0x45, 0x54, 0x46, 0x20, 0x51, 0x55, 0x49, 0x43, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x6e, 0x65, 0x67, 0x6f, 0x74, 0x69, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x20, 0x50, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x20, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x61, 0x20, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x4e, 0x65, 0x67, 0x6f, 0x74, 0x69, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x70, 0x61, 0x63, 0x6b, 0x65, 0x74, 0x20, 0x69, 0x6e, 0x64, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x77, 0x68, 0x61, 0x74, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x20, 0x79, 0x6f, 0x75, 0x20, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x20, 0x54, 0x68, 0x61, 0x6e, 0x6b, 0x20, 0x79, 0x6f, 0x75, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x68, 0x61, 0x76, 0x65, 0x20, 0x61, 0x20, 0x6e, 0x69, 0x63, 0x65, 0x20, 0x64, 0x61, 0x79, 0x2e, 0x00, }; char expected_destination_connection_id_bytes[] = {0x56, 0x4e, 0x20, 0x70, 0x6c, 0x7a, 0x20, 0x21}; QuicConnectionId expected_destination_connection_id( reinterpret_cast<const char*>(expected_destination_connection_id_bytes), sizeof(expected_destination_connection_id_bytes)); QuicEncryptedPacket encrypted(reinterpret_cast<const char*>(packet), sizeof(packet)); PacketHeaderFormat format = GOOGLE_QUIC_PACKET; QuicLongHeaderType long_packet_type = INVALID_PACKET_TYPE; bool version_present = false, has_length_prefix = true; QuicVersionLabel version_label = 33; ParsedQuicVersion parsed_version = UnsupportedQuicVersion(); QuicConnectionId destination_connection_id = TestConnectionId(1); QuicConnectionId source_connection_id = TestConnectionId(2); std::optional<absl::string_view> retry_token; std::string detailed_error = "foobar"; QuicErrorCode header_parse_result = QuicFramer::ParsePublicHeaderDispatcher( encrypted, kQuicDefaultConnectionIdLength, &format, &long_packet_type, &version_present, &has_length_prefix, &version_label, &parsed_version, &destination_connection_id, &source_connection_id, &retry_token, &detailed_error); EXPECT_THAT(header_parse_result, IsQuicNoError()); EXPECT_EQ(IETF_QUIC_LONG_HEADER_PACKET, format); EXPECT_TRUE(version_present); EXPECT_FALSE(has_length_prefix); EXPECT_EQ(0xcabadaba, version_label); EXPECT_EQ(expected_destination_connection_id, destination_connection_id); EXPECT_EQ(EmptyQuicConnectionId(), source_connection_id); EXPECT_FALSE(retry_token.has_value()); EXPECT_EQ("", detailed_error); } TEST_P(QuicFramerTest, DispatcherParseClientVersionNegotiationProbePacket) { static const uint8_t packet[1200] = { 0xc0, 0xca, 0xba, 0xda, 0xba, 0x08, 0x56, 0x4e, 0x20, 0x70, 0x6c, 0x7a, 0x20, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x54, 0x68, 0x69, 0x73, 0x20, 0x70, 0x61, 0x63, 0x6b, 0x65, 0x74, 0x20, 0x6f, 0x6e, 0x6c, 0x79, 0x20, 0x65, 0x78, 0x69, 0x73, 0x74, 0x73, 0x20, 0x74, 0x6f, 0x20, 0x74, 0x72, 0x69, 0x67, 0x67, 0x65, 0x72, 0x20, 0x49, 0x45, 0x54, 0x46, 0x20, 0x51, 0x55, 0x49, 0x43, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x6e, 0x65, 0x67, 0x6f, 0x74, 0x69, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x20, 0x50, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x20, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x61, 0x20, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x4e, 0x65, 0x67, 0x6f, 0x74, 0x69, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x70, 0x61, 0x63, 0x6b, 0x65, 0x74, 0x20, 0x69, 0x6e, 0x64, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x77, 0x68, 0x61, 0x74, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x20, 0x79, 0x6f, 0x75, 0x20, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x20, 0x54, 0x68, 0x61, 0x6e, 0x6b, 0x20, 0x79, 0x6f, 0x75, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x68, 0x61, 0x76, 0x65, 0x20, 0x61, 0x20, 0x6e, 0x69, 0x63, 0x65, 0x20, 0x64, 0x61, 0x79, 0x2e, 0x00, }; char expected_destination_connection_id_bytes[] = {0x56, 0x4e, 0x20, 0x70, 0x6c, 0x7a, 0x20, 0x21}; QuicConnectionId expected_destination_connection_id( reinterpret_cast<const char*>(expected_destination_connection_id_bytes), sizeof(expected_destination_connection_id_bytes)); QuicEncryptedPacket encrypted(reinterpret_cast<const char*>(packet), sizeof(packet)); PacketHeaderFormat format = GOOGLE_QUIC_PACKET; QuicLongHeaderType long_packet_type = INVALID_PACKET_TYPE; bool version_present = false, has_length_prefix = false; QuicVersionLabel version_label = 33; ParsedQuicVersion parsed_version = UnsupportedQuicVersion(); QuicConnectionId destination_connection_id = TestConnectionId(1); QuicConnectionId source_connection_id = TestConnectionId(2); std::optional<absl::string_view> retry_token; std::string detailed_error = "foobar"; QuicErrorCode header_parse_result = QuicFramer::ParsePublicHeaderDispatcher( encrypted, kQuicDefaultConnectionIdLength, &format, &long_packet_type, &version_present, &has_length_prefix, &version_label, &parsed_version, &destination_connection_id, &source_connection_id, &retry_token, &detailed_error); EXPECT_THAT(header_parse_result, IsQuicNoError()); EXPECT_EQ(IETF_QUIC_LONG_HEADER_PACKET, format); EXPECT_TRUE(version_present); EXPECT_TRUE(has_length_prefix); EXPECT_EQ(0xcabadaba, version_label); EXPECT_EQ(expected_destination_connection_id, destination_connection_id); EXPECT_EQ(EmptyQuicConnectionId(), source_connection_id); EXPECT_EQ("", detailed_error); } TEST_P(QuicFramerTest, DispatcherParseClientInitialPacketNumber) { PacketFragments packet = { {"Unable to read first byte.", {0xC1}}, {"Unable to read protocol version.", {QUIC_VERSION_BYTES}}, {"Unable to read destination connection ID.", {0x08, 0x56, 0x4e, 0x20, 0x70, 0x6c, 0x7a, 0x20, 0x21}}, {"Unable to read source connection ID.", {0x00}}, {"", {0x00}}, {"", {kVarInt62TwoBytes + 0x03, 0x04}}, {"Unable to read packet number.", {0x00, 0x02}}, {"", std::vector<uint8_t>(static_cast<size_t>(kDefaultMaxPacketSize - 20), 0)} }; SetDecrypterLevel(ENCRYPTION_INITIAL); std::unique_ptr<QuicEncryptedPacket> encrypted( AssemblePacketFromFragments(packet)); ASSERT_EQ(encrypted->length(), kDefaultMaxPacketSize); PacketHeaderFormat format; QuicLongHeaderType long_packet_type = INVALID_PACKET_TYPE; bool version_flag; bool use_length_prefix; QuicVersionLabel version_label; std::optional<absl::string_view> retry_token; ParsedQuicVersion parsed_version = UnsupportedQuicVersion(); QuicConnectionId destination_connection_id, source_connection_id; std::string detailed_error; MockConnectionIdGenerator generator; EXPECT_CALL(generator, ConnectionIdLength(_)).Times(0); EXPECT_EQ(QUIC_NO_ERROR, QuicFramer::ParsePublicHeaderDispatcherShortHeaderLengthUnknown( *encrypted, &format, &long_packet_type, &version_flag, &use_length_prefix, &version_label, &parsed_version, &destination_connection_id, &source_connection_id, &retry_token, &detailed_error, generator)); EXPECT_EQ(parsed_version, version_); if (parsed_version != ParsedQuicVersion::RFCv1() && parsed_version != ParsedQuicVersion::Draft29()) { return; } EXPECT_EQ(format, IETF_QUIC_LONG_HEADER_PACKET); EXPECT_EQ(destination_connection_id.length(), 8); EXPECT_EQ(long_packet_type, INITIAL); EXPECT_TRUE(version_flag); EXPECT_TRUE(use_length_prefix); EXPECT_EQ(version_label, CreateQuicVersionLabel(version_)); EXPECT_EQ(source_connection_id.length(), 0); EXPECT_TRUE(retry_token.value_or("").empty()); EXPECT_EQ(detailed_error, ""); std::optional<uint64_t> packet_number; EXPECT_EQ(QUIC_NO_ERROR, QuicFramer::TryDecryptInitialPacketDispatcher( *encrypted, parsed_version, format, long_packet_type, destination_connection_id, source_connection_id, retry_token, QuicPacketNumber(), *decrypter_, &packet_number)); EXPECT_THAT(packet_number, Optional(2)); } TEST_P(QuicFramerTest, DispatcherParseClientInitialPacketNumberFromCoalescedPacket) { if (!QuicVersionHasLongHeaderLengths(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_INITIAL); unsigned char packet[] = { 0xC3, QUIC_VERSION_BYTES, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x00, 0x1E, 0x12, 0x34, 0x56, 0x78, 0x08 | 0x01 | 0x02 | 0x04, kVarInt62FourBytes + 0x00, 0x02, 0x03, 0x04, kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, kVarInt62OneByte + 0x0c, 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', 0xD3, QUIC_VERSION_BYTES, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x1E, 0x12, 0x34, 0x56, 0x79, 0x08 | 0x01 | 0x02 | 0x04, kVarInt62FourBytes + 0x00, 0x02, 0x03, 0x04, kVarInt62EightBytes + 0x3A, 0x98, 0xFE, 0xDC, 0x32, 0x10, 0x76, 0x54, kVarInt62OneByte + 0x0c, 'H', 'E', 'L', 'L', 'O', '_', 'W', 'O', 'R', 'L', 'D', '?', }; const size_t first_packet_size = 47; ASSERT_EQ(packet[first_packet_size], 0xD3); ReviseFirstByteByVersion(packet); ReviseFirstByteByVersion(&packet[first_packet_size]); unsigned char* p = packet; size_t p_length = ABSL_ARRAYSIZE(packet); QuicEncryptedPacket encrypted(AsChars(p), p_length, false); PacketHeaderFormat format; QuicLongHeaderType long_packet_type = INVALID_PACKET_TYPE; bool version_flag; bool use_length_prefix; QuicVersionLabel version_label; std::optional<absl::string_view> retry_token; ParsedQuicVersion parsed_version = UnsupportedQuicVersion(); QuicConnectionId destination_connection_id, source_connection_id; std::string detailed_error; MockConnectionIdGenerator generator; EXPECT_CALL(generator, ConnectionIdLength(_)).Times(0); EXPECT_EQ(QUIC_NO_ERROR, QuicFramer::ParsePublicHeaderDispatcherShortHeaderLengthUnknown( encrypted, &format, &long_packet_type, &version_flag, &use_length_prefix, &version_label, &parsed_version, &destination_connection_id, &source_connection_id, &retry_token, &detailed_error, generator)); EXPECT_EQ(parsed_version, version_); if (parsed_version != ParsedQuicVersion::RFCv1() && parsed_version != ParsedQuicVersion::Draft29()) { return; } EXPECT_EQ(format, IETF_QUIC_LONG_HEADER_PACKET); EXPECT_EQ(destination_connection_id.length(), 8); EXPECT_EQ(long_packet_type, INITIAL); EXPECT_TRUE(version_flag); EXPECT_TRUE(use_length_prefix); EXPECT_EQ(version_label, CreateQuicVersionLabel(version_)); EXPECT_EQ(source_connection_id.length(), 0); EXPECT_TRUE(retry_token.value_or("").empty()); EXPECT_EQ(detailed_error, ""); std::optional<uint64_t> packet_number; EXPECT_EQ(QUIC_NO_ERROR, QuicFramer::TryDecryptInitialPacketDispatcher( encrypted, parsed_version, format, long_packet_type, destination_connection_id, source_connection_id, retry_token, QuicPacketNumber(), *decrypter_, &packet_number)); EXPECT_THAT(packet_number, Optional(0x12345678)); } TEST_P(QuicFramerTest, ParseServerVersionNegotiationProbeResponse) { const uint8_t packet[] = { 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x56, 0x4e, 0x20, 0x70, 0x6c, 0x7a, 0x20, 0x21, 0xaa, 0xaa, 0xaa, 0xaa, QUIC_VERSION_BYTES, }; char probe_payload_bytes[] = {0x56, 0x4e, 0x20, 0x70, 0x6c, 0x7a, 0x20, 0x21}; char parsed_probe_payload_bytes[255] = {}; uint8_t parsed_probe_payload_length = sizeof(parsed_probe_payload_bytes); std::string parse_detailed_error = ""; EXPECT_TRUE(QuicFramer::ParseServerVersionNegotiationProbeResponse( reinterpret_cast<const char*>(packet), sizeof(packet), reinterpret_cast<char*>(parsed_probe_payload_bytes), &parsed_probe_payload_length, &parse_detailed_error)); EXPECT_EQ("", parse_detailed_error); quiche::test::CompareCharArraysWithHexError( "parsed probe", parsed_probe_payload_bytes, parsed_probe_payload_length, probe_payload_bytes, sizeof(probe_payload_bytes)); } TEST_P(QuicFramerTest, ParseClientVersionNegotiationProbePacket) { char packet[1200]; char input_destination_connection_id_bytes[] = {0x56, 0x4e, 0x20, 0x70, 0x6c, 0x7a, 0x20, 0x21}; ASSERT_TRUE(QuicFramer::WriteClientVersionNegotiationProbePacket( packet, sizeof(packet), input_destination_connection_id_bytes, sizeof(input_destination_connection_id_bytes))); char parsed_destination_connection_id_bytes[255] = {0}; uint8_t parsed_destination_connection_id_length = sizeof(parsed_destination_connection_id_bytes); ASSERT_TRUE(ParseClientVersionNegotiationProbePacket( packet, sizeof(packet), parsed_destination_connection_id_bytes, &parsed_destination_connection_id_length)); quiche::test::CompareCharArraysWithHexError( "parsed destination connection ID", parsed_destination_connection_id_bytes, parsed_destination_connection_id_length, input_destination_connection_id_bytes, sizeof(input_destination_connection_id_bytes)); } TEST_P(QuicFramerTest, WriteServerVersionNegotiationProbeResponse) { char packet[1200]; size_t packet_length = sizeof(packet); char input_source_connection_id_bytes[] = {0x56, 0x4e, 0x20, 0x70, 0x6c, 0x7a, 0x20, 0x21}; ASSERT_TRUE(WriteServerVersionNegotiationProbeResponse( packet, &packet_length, input_source_connection_id_bytes, sizeof(input_source_connection_id_bytes))); char parsed_source_connection_id_bytes[255] = {0}; uint8_t parsed_source_connection_id_length = sizeof(parsed_source_connection_id_bytes); std::string detailed_error; ASSERT_TRUE(QuicFramer::ParseServerVersionNegotiationProbeResponse( packet, packet_length, parsed_source_connection_id_bytes, &parsed_source_connection_id_length, &detailed_error)) << detailed_error; quiche::test::CompareCharArraysWithHexError( "parsed destination connection ID", parsed_source_connection_id_bytes, parsed_source_connection_id_length, input_source_connection_id_bytes, sizeof(input_source_connection_id_bytes)); } TEST_P(QuicFramerTest, ClientConnectionIdFromLongHeaderToClient) { SetDecrypterLevel(ENCRYPTION_HANDSHAKE); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); unsigned char packet[] = { 0xE3, QUIC_VERSION_BYTES, 0x50, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x05, 0x12, 0x34, 0x56, 0x00, 0x00, }; unsigned char packet49[] = { 0xE3, QUIC_VERSION_BYTES, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x05, 0x12, 0x34, 0x56, 0x00, 0x00, }; unsigned char* p = packet; size_t p_length = ABSL_ARRAYSIZE(packet); if (framer_.version().HasLongHeaderLengths()) { ReviseFirstByteByVersion(packet49); p = packet49; p_length = ABSL_ARRAYSIZE(packet49); } const bool parse_success = framer_.ProcessPacket(QuicEncryptedPacket(AsChars(p), p_length, false)); if (!framer_.version().AllowsVariableLengthConnectionIds()) { EXPECT_FALSE(parse_success); EXPECT_THAT(framer_.error(), IsError(QUIC_INVALID_PACKET_HEADER)); EXPECT_EQ("Invalid ConnectionId length.", framer_.detailed_error()); return; } EXPECT_TRUE(parse_success); EXPECT_THAT(framer_.error(), IsQuicNoError()); EXPECT_EQ("", framer_.detailed_error()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_EQ(FramerTestConnectionId(), visitor_.header_.get()->destination_connection_id); } TEST_P(QuicFramerTest, ClientConnectionIdFromLongHeaderToServer) { SetDecrypterLevel(ENCRYPTION_HANDSHAKE); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); unsigned char packet[] = { 0xE3, QUIC_VERSION_BYTES, 0x05, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x05, 0x12, 0x34, 0x56, 0x00, 0x00, }; unsigned char packet49[] = { 0xE3, QUIC_VERSION_BYTES, 0x00, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x05, 0x12, 0x34, 0x56, 0x00, 0x00, }; unsigned char* p = packet; size_t p_length = ABSL_ARRAYSIZE(packet); if (framer_.version().HasLongHeaderLengths()) { ReviseFirstByteByVersion(packet49); p = packet49; p_length = ABSL_ARRAYSIZE(packet49); } const bool parse_success = framer_.ProcessPacket(QuicEncryptedPacket(AsChars(p), p_length, false)); if (!framer_.version().AllowsVariableLengthConnectionIds()) { EXPECT_FALSE(parse_success); EXPECT_THAT(framer_.error(), IsError(QUIC_INVALID_PACKET_HEADER)); EXPECT_EQ("Invalid ConnectionId length.", framer_.detailed_error()); return; } if (!framer_.version().SupportsClientConnectionIds()) { EXPECT_FALSE(parse_success); EXPECT_THAT(framer_.error(), IsError(QUIC_INVALID_PACKET_HEADER)); EXPECT_EQ("Client connection ID not supported in this version.", framer_.detailed_error()); return; } EXPECT_TRUE(parse_success); EXPECT_THAT(framer_.error(), IsQuicNoError()); EXPECT_EQ("", framer_.detailed_error()); ASSERT_TRUE(visitor_.header_.get()); EXPECT_EQ(FramerTestConnectionId(), visitor_.header_.get()->source_connection_id); } TEST_P(QuicFramerTest, ProcessAndValidateIetfConnectionIdLengthClient) { char connection_id_lengths = 0x05; QuicDataReader reader(&connection_id_lengths, 1); bool should_update_expected_server_connection_id_length = false; uint8_t expected_server_connection_id_length = 8; uint8_t destination_connection_id_length = 0; uint8_t source_connection_id_length = 8; std::string detailed_error = ""; EXPECT_TRUE(QuicFramerPeer::ProcessAndValidateIetfConnectionIdLength( &reader, framer_.version(), Perspective::IS_CLIENT, should_update_expected_server_connection_id_length, &expected_server_connection_id_length, &destination_connection_id_length, &source_connection_id_length, &detailed_error)); EXPECT_EQ(8, expected_server_connection_id_length); EXPECT_EQ(0, destination_connection_id_length); EXPECT_EQ(8, source_connection_id_length); EXPECT_EQ("", detailed_error); QuicDataReader reader2(&connection_id_lengths, 1); should_update_expected_server_connection_id_length = true; expected_server_connection_id_length = 33; EXPECT_TRUE(QuicFramerPeer::ProcessAndValidateIetfConnectionIdLength( &reader2, framer_.version(), Perspective::IS_CLIENT, should_update_expected_server_connection_id_length, &expected_server_connection_id_length, &destination_connection_id_length, &source_connection_id_length, &detailed_error)); EXPECT_EQ(8, expected_server_connection_id_length); EXPECT_EQ(0, destination_connection_id_length); EXPECT_EQ(8, source_connection_id_length); EXPECT_EQ("", detailed_error); } TEST_P(QuicFramerTest, ProcessAndValidateIetfConnectionIdLengthServer) { char connection_id_lengths = 0x50; QuicDataReader reader(&connection_id_lengths, 1); bool should_update_expected_server_connection_id_length = false; uint8_t expected_server_connection_id_length = 8; uint8_t destination_connection_id_length = 8; uint8_t source_connection_id_length = 0; std::string detailed_error = ""; EXPECT_TRUE(QuicFramerPeer::ProcessAndValidateIetfConnectionIdLength( &reader, framer_.version(), Perspective::IS_SERVER, should_update_expected_server_connection_id_length, &expected_server_connection_id_length, &destination_connection_id_length, &source_connection_id_length, &detailed_error)); EXPECT_EQ(8, expected_server_connection_id_length); EXPECT_EQ(8, destination_connection_id_length); EXPECT_EQ(0, source_connection_id_length); EXPECT_EQ("", detailed_error); QuicDataReader reader2(&connection_id_lengths, 1); should_update_expected_server_connection_id_length = true; expected_server_connection_id_length = 33; EXPECT_TRUE(QuicFramerPeer::ProcessAndValidateIetfConnectionIdLength( &reader2, framer_.version(), Perspective::IS_SERVER, should_update_expected_server_connection_id_length, &expected_server_connection_id_length, &destination_connection_id_length, &source_connection_id_length, &detailed_error)); EXPECT_EQ(8, expected_server_connection_id_length); EXPECT_EQ(8, destination_connection_id_length); EXPECT_EQ(0, source_connection_id_length); EXPECT_EQ("", detailed_error); } TEST_P(QuicFramerTest, TestExtendedErrorCodeParser) { if (VersionHasIetfQuicFrames(framer_.transport_version())) { return; } QuicConnectionCloseFrame frame; frame.error_details = "this has no error code info in it"; MaybeExtractQuicErrorCode(&frame); EXPECT_THAT(frame.quic_error_code, IsError(QUIC_IETF_GQUIC_ERROR_MISSING)); EXPECT_EQ("this has no error code info in it", frame.error_details); frame.error_details = "1234this does not have the colon in it"; MaybeExtractQuicErrorCode(&frame); EXPECT_THAT(frame.quic_error_code, IsError(QUIC_IETF_GQUIC_ERROR_MISSING)); EXPECT_EQ("1234this does not have the colon in it", frame.error_details); frame.error_details = "1a234:this has a colon, but a malformed error number"; MaybeExtractQuicErrorCode(&frame); EXPECT_THAT(frame.quic_error_code, IsError(QUIC_IETF_GQUIC_ERROR_MISSING)); EXPECT_EQ("1a234:this has a colon, but a malformed error number", frame.error_details); frame.error_details = "1234:this is good"; MaybeExtractQuicErrorCode(&frame); EXPECT_EQ(1234u, frame.quic_error_code); EXPECT_EQ("this is good", frame.error_details); frame.error_details = "1234 :this is not good, space between last digit and colon"; MaybeExtractQuicErrorCode(&frame); EXPECT_THAT(frame.quic_error_code, IsError(QUIC_IETF_GQUIC_ERROR_MISSING)); EXPECT_EQ("1234 :this is not good, space between last digit and colon", frame.error_details); frame.error_details = "123456789"; MaybeExtractQuicErrorCode(&frame); EXPECT_THAT( frame.quic_error_code, IsError(QUIC_IETF_GQUIC_ERROR_MISSING)); EXPECT_EQ("123456789", frame.error_details); frame.error_details = "1234:"; MaybeExtractQuicErrorCode(&frame); EXPECT_EQ(1234u, frame.quic_error_code); EXPECT_EQ("", frame.error_details); frame.error_details = "1234:5678"; MaybeExtractQuicErrorCode(&frame); EXPECT_EQ(1234u, frame.quic_error_code); EXPECT_EQ("5678", frame.error_details); frame.error_details = "12345 6789:"; MaybeExtractQuicErrorCode(&frame); EXPECT_THAT(frame.quic_error_code, IsError(QUIC_IETF_GQUIC_ERROR_MISSING)); EXPECT_EQ("12345 6789:", frame.error_details); frame.error_details = ":no numbers, is not good"; MaybeExtractQuicErrorCode(&frame); EXPECT_THAT(frame.quic_error_code, IsError(QUIC_IETF_GQUIC_ERROR_MISSING)); EXPECT_EQ(":no numbers, is not good", frame.error_details); frame.error_details = "qwer:also no numbers, is not good"; MaybeExtractQuicErrorCode(&frame); EXPECT_THAT(frame.quic_error_code, IsError(QUIC_IETF_GQUIC_ERROR_MISSING)); EXPECT_EQ("qwer:also no numbers, is not good", frame.error_details); frame.error_details = " 1234:this is not good, space before first digit"; MaybeExtractQuicErrorCode(&frame); EXPECT_THAT(frame.quic_error_code, IsError(QUIC_IETF_GQUIC_ERROR_MISSING)); EXPECT_EQ(" 1234:this is not good, space before first digit", frame.error_details); frame.error_details = "1234:"; MaybeExtractQuicErrorCode(&frame); EXPECT_EQ(1234u, frame.quic_error_code); EXPECT_EQ("", frame.error_details); frame.error_details = "12345678901:"; MaybeExtractQuicErrorCode(&frame); EXPECT_THAT(frame.quic_error_code, IsError(QUIC_IETF_GQUIC_ERROR_MISSING)); EXPECT_EQ("12345678901:", frame.error_details); } TEST_P(QuicFramerTest, OverlyLargeAckDelay) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); unsigned char packet_ietf[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x02, kVarInt62FourBytes + 0x12, 0x34, 0x56, 0x78, kVarInt62EightBytes + 0x31, 0x00, 0x00, 0x00, 0xF3, 0xA0, 0x81, 0xE0, kVarInt62OneByte + 0x00, kVarInt62FourBytes + 0x12, 0x34, 0x56, 0x77, }; framer_.ProcessPacket(QuicEncryptedPacket( AsChars(packet_ietf), ABSL_ARRAYSIZE(packet_ietf), false)); ASSERT_EQ(1u, visitor_.ack_frames_.size()); EXPECT_EQ(QuicTime::Delta::Infinite(), visitor_.ack_frames_[0]->ack_delay_time); } TEST_P(QuicFramerTest, KeyUpdate) { if (!framer_.version().UsesTls()) { return; } ASSERT_TRUE(framer_.version().KnowsWhichDecrypterToUse()); framer_.InstallDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(0)); framer_.SetKeyUpdateSupportForConnection(true); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicFrames frames = {QuicFrame(QuicPaddingFrame())}; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); std::unique_ptr<QuicEncryptedPacket> encrypted( EncryptPacketWithTagAndPhase(*data, 0, false)); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(0u, visitor_.key_update_count()); EXPECT_EQ(0, visitor_.derive_next_key_count_); EXPECT_EQ(1, visitor_.decrypted_first_packet_in_key_phase_count_); header.packet_number += 1; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); data = BuildDataPacket(header, frames); ASSERT_TRUE(data != nullptr); encrypted = EncryptPacketWithTagAndPhase(*data, 1, true); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); ASSERT_EQ(1u, visitor_.key_update_count()); EXPECT_EQ(KeyUpdateReason::kRemote, visitor_.key_update_reasons_[0]); EXPECT_EQ(1, visitor_.derive_next_key_count_); EXPECT_EQ(2, visitor_.decrypted_first_packet_in_key_phase_count_); header.packet_number += 1; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); data = BuildDataPacket(header, frames); ASSERT_TRUE(data != nullptr); encrypted = EncryptPacketWithTagAndPhase(*data, 1, true); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(1u, visitor_.key_update_count()); EXPECT_EQ(1, visitor_.derive_next_key_count_); EXPECT_EQ(2, visitor_.decrypted_first_packet_in_key_phase_count_); header.packet_number += 1; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); data = BuildDataPacket(header, frames); ASSERT_TRUE(data != nullptr); encrypted = EncryptPacketWithTagAndPhase(*data, 2, false); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); ASSERT_EQ(2u, visitor_.key_update_count()); EXPECT_EQ(KeyUpdateReason::kRemote, visitor_.key_update_reasons_[1]); EXPECT_EQ(2, visitor_.derive_next_key_count_); EXPECT_EQ(3, visitor_.decrypted_first_packet_in_key_phase_count_); } TEST_P(QuicFramerTest, KeyUpdateOldPacketAfterUpdate) { if (!framer_.version().UsesTls()) { return; } ASSERT_TRUE(framer_.version().KnowsWhichDecrypterToUse()); framer_.InstallDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(0)); framer_.SetKeyUpdateSupportForConnection(true); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicFrames frames = {QuicFrame(QuicPaddingFrame())}; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); std::unique_ptr<QuicEncryptedPacket> encrypted( EncryptPacketWithTagAndPhase(*data, 0, false)); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(0u, visitor_.key_update_count()); EXPECT_EQ(0, visitor_.derive_next_key_count_); EXPECT_EQ(1, visitor_.decrypted_first_packet_in_key_phase_count_); header.packet_number = kPacketNumber + 2; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); data = BuildDataPacket(header, frames); ASSERT_TRUE(data != nullptr); encrypted = EncryptPacketWithTagAndPhase(*data, 1, true); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(1u, visitor_.key_update_count()); EXPECT_EQ(1, visitor_.derive_next_key_count_); EXPECT_EQ(2, visitor_.decrypted_first_packet_in_key_phase_count_); header.packet_number = kPacketNumber + 1; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); data = BuildDataPacket(header, frames); ASSERT_TRUE(data != nullptr); encrypted = EncryptPacketWithTagAndPhase(*data, 0, false); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(1u, visitor_.key_update_count()); EXPECT_EQ(1, visitor_.derive_next_key_count_); EXPECT_EQ(2, visitor_.decrypted_first_packet_in_key_phase_count_); } TEST_P(QuicFramerTest, KeyUpdateOldPacketAfterDiscardPreviousOneRttKeys) { if (!framer_.version().UsesTls()) { return; } ASSERT_TRUE(framer_.version().KnowsWhichDecrypterToUse()); framer_.InstallDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(0)); framer_.SetKeyUpdateSupportForConnection(true); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicFrames frames = {QuicFrame(QuicPaddingFrame())}; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); std::unique_ptr<QuicEncryptedPacket> encrypted( EncryptPacketWithTagAndPhase(*data, 0, false)); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(0u, visitor_.key_update_count()); EXPECT_EQ(0, visitor_.derive_next_key_count_); EXPECT_EQ(1, visitor_.decrypted_first_packet_in_key_phase_count_); header.packet_number = kPacketNumber + 2; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); data = BuildDataPacket(header, frames); ASSERT_TRUE(data != nullptr); encrypted = EncryptPacketWithTagAndPhase(*data, 1, true); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(1u, visitor_.key_update_count()); EXPECT_EQ(1, visitor_.derive_next_key_count_); EXPECT_EQ(2, visitor_.decrypted_first_packet_in_key_phase_count_); framer_.DiscardPreviousOneRttKeys(); header.packet_number = kPacketNumber + 1; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); data = BuildDataPacket(header, frames); ASSERT_TRUE(data != nullptr); encrypted = EncryptPacketWithTagAndPhase(*data, 0, false); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(1u, visitor_.key_update_count()); EXPECT_EQ(1, visitor_.derive_next_key_count_); EXPECT_EQ(2, visitor_.decrypted_first_packet_in_key_phase_count_); } TEST_P(QuicFramerTest, KeyUpdatePacketsOutOfOrder) { if (!framer_.version().UsesTls()) { return; } ASSERT_TRUE(framer_.version().KnowsWhichDecrypterToUse()); framer_.InstallDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(0)); framer_.SetKeyUpdateSupportForConnection(true); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicFrames frames = {QuicFrame(QuicPaddingFrame())}; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); std::unique_ptr<QuicEncryptedPacket> encrypted( EncryptPacketWithTagAndPhase(*data, 0, false)); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(0u, visitor_.key_update_count()); EXPECT_EQ(0, visitor_.derive_next_key_count_); EXPECT_EQ(1, visitor_.decrypted_first_packet_in_key_phase_count_); header.packet_number = kPacketNumber + 2; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); data = BuildDataPacket(header, frames); ASSERT_TRUE(data != nullptr); encrypted = EncryptPacketWithTagAndPhase(*data, 1, true); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(1u, visitor_.key_update_count()); EXPECT_EQ(1, visitor_.derive_next_key_count_); EXPECT_EQ(2, visitor_.decrypted_first_packet_in_key_phase_count_); header.packet_number = kPacketNumber + 1; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); data = BuildDataPacket(header, frames); ASSERT_TRUE(data != nullptr); encrypted = EncryptPacketWithTagAndPhase(*data, 1, true); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(1u, visitor_.key_update_count()); EXPECT_EQ(1, visitor_.derive_next_key_count_); EXPECT_EQ(2, visitor_.decrypted_first_packet_in_key_phase_count_); } TEST_P(QuicFramerTest, KeyUpdateWrongKey) { if (!framer_.version().UsesTls()) { return; } ASSERT_TRUE(framer_.version().KnowsWhichDecrypterToUse()); framer_.InstallDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(0)); framer_.SetKeyUpdateSupportForConnection(true); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicFrames frames = {QuicFrame(QuicPaddingFrame())}; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); std::unique_ptr<QuicEncryptedPacket> encrypted( EncryptPacketWithTagAndPhase(*data, 0, false)); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(0u, visitor_.key_update_count()); EXPECT_EQ(0, visitor_.derive_next_key_count_); EXPECT_EQ(1, visitor_.decrypted_first_packet_in_key_phase_count_); EXPECT_EQ(0u, framer_.PotentialPeerKeyUpdateAttemptCount()); header.packet_number += 1; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); data = BuildDataPacket(header, frames); ASSERT_TRUE(data != nullptr); encrypted = EncryptPacketWithTagAndPhase(*data, 2, true); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(0u, visitor_.key_update_count()); EXPECT_EQ(1, visitor_.derive_next_key_count_); EXPECT_EQ(1, visitor_.decrypted_first_packet_in_key_phase_count_); EXPECT_EQ(1u, framer_.PotentialPeerKeyUpdateAttemptCount()); header.packet_number += 1; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); data = BuildDataPacket(header, frames); ASSERT_TRUE(data != nullptr); encrypted = EncryptPacketWithTagAndPhase(*data, 0, true); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(0u, visitor_.key_update_count()); EXPECT_EQ(1, visitor_.derive_next_key_count_); EXPECT_EQ(1, visitor_.decrypted_first_packet_in_key_phase_count_); EXPECT_EQ(2u, framer_.PotentialPeerKeyUpdateAttemptCount()); header.packet_number += 1; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); data = BuildDataPacket(header, frames); ASSERT_TRUE(data != nullptr); encrypted = EncryptPacketWithTagAndPhase(*data, 1, false); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(0u, visitor_.key_update_count()); EXPECT_EQ(1, visitor_.derive_next_key_count_); EXPECT_EQ(1, visitor_.decrypted_first_packet_in_key_phase_count_); EXPECT_EQ(2u, framer_.PotentialPeerKeyUpdateAttemptCount()); header.packet_number += 1; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); data = BuildDataPacket(header, frames); ASSERT_TRUE(data != nullptr); encrypted = EncryptPacketWithTagAndPhase(*data, 0, false); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(0u, visitor_.key_update_count()); EXPECT_EQ(1, visitor_.derive_next_key_count_); EXPECT_EQ(1, visitor_.decrypted_first_packet_in_key_phase_count_); EXPECT_EQ(0u, framer_.PotentialPeerKeyUpdateAttemptCount()); } TEST_P(QuicFramerTest, KeyUpdateReceivedWhenNotEnabled) { if (!framer_.version().UsesTls()) { return; } ASSERT_TRUE(framer_.version().KnowsWhichDecrypterToUse()); framer_.InstallDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(0)); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicFrames frames = {QuicFrame(QuicPaddingFrame())}; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); std::unique_ptr<QuicEncryptedPacket> encrypted( EncryptPacketWithTagAndPhase(*data, 1, true)); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(0u, visitor_.key_update_count()); EXPECT_EQ(0, visitor_.derive_next_key_count_); EXPECT_EQ(0, visitor_.decrypted_first_packet_in_key_phase_count_); } TEST_P(QuicFramerTest, KeyUpdateLocallyInitiated) { if (!framer_.version().UsesTls()) { return; } ASSERT_TRUE(framer_.version().KnowsWhichDecrypterToUse()); framer_.InstallDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(0)); framer_.SetKeyUpdateSupportForConnection(true); EXPECT_TRUE(framer_.DoKeyUpdate(KeyUpdateReason::kLocalForTests)); ASSERT_EQ(1u, visitor_.key_update_count()); EXPECT_EQ(KeyUpdateReason::kLocalForTests, visitor_.key_update_reasons_[0]); EXPECT_EQ(1, visitor_.derive_next_key_count_); EXPECT_EQ(0, visitor_.decrypted_first_packet_in_key_phase_count_); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicFrames frames = {QuicFrame(QuicPaddingFrame())}; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); std::unique_ptr<QuicEncryptedPacket> encrypted( EncryptPacketWithTagAndPhase(*data, 1, true)); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(1u, visitor_.key_update_count()); EXPECT_EQ(1, visitor_.derive_next_key_count_); EXPECT_EQ(1, visitor_.decrypted_first_packet_in_key_phase_count_); header.packet_number = kPacketNumber - 1; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); data = BuildDataPacket(header, frames); ASSERT_TRUE(data != nullptr); encrypted = EncryptPacketWithTagAndPhase(*data, 0, false); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(1u, visitor_.key_update_count()); EXPECT_EQ(1, visitor_.derive_next_key_count_); EXPECT_EQ(1, visitor_.decrypted_first_packet_in_key_phase_count_); header.packet_number = kPacketNumber + 1; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); data = BuildDataPacket(header, frames); ASSERT_TRUE(data != nullptr); encrypted = EncryptPacketWithTagAndPhase(*data, 0, false); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(1u, visitor_.key_update_count()); EXPECT_EQ(2, visitor_.derive_next_key_count_); EXPECT_EQ(1, visitor_.decrypted_first_packet_in_key_phase_count_); } TEST_P(QuicFramerTest, KeyUpdateLocallyInitiatedReceivedOldPacket) { if (!framer_.version().UsesTls()) { return; } ASSERT_TRUE(framer_.version().KnowsWhichDecrypterToUse()); framer_.InstallDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(0)); framer_.SetKeyUpdateSupportForConnection(true); EXPECT_TRUE(framer_.DoKeyUpdate(KeyUpdateReason::kLocalForTests)); EXPECT_EQ(1u, visitor_.key_update_count()); EXPECT_EQ(1, visitor_.derive_next_key_count_); EXPECT_EQ(0, visitor_.decrypted_first_packet_in_key_phase_count_); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicFrames frames = {QuicFrame(QuicPaddingFrame())}; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); std::unique_ptr<QuicPacket> data = BuildDataPacket(header, frames); ASSERT_TRUE(data != nullptr); std::unique_ptr<QuicEncryptedPacket> encrypted = EncryptPacketWithTagAndPhase(*data, 0, false); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(1u, visitor_.key_update_count()); EXPECT_EQ(1, visitor_.derive_next_key_count_); EXPECT_EQ(0, visitor_.decrypted_first_packet_in_key_phase_count_); header.packet_number = kPacketNumber + 1; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); data = BuildDataPacket(header, frames); ASSERT_TRUE(data != nullptr); encrypted = EncryptPacketWithTagAndPhase(*data, 1, true); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(1u, visitor_.key_update_count()); EXPECT_EQ(1, visitor_.derive_next_key_count_); EXPECT_EQ(1, visitor_.decrypted_first_packet_in_key_phase_count_); header.packet_number = kPacketNumber + 2; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); data = BuildDataPacket(header, frames); ASSERT_TRUE(data != nullptr); encrypted = EncryptPacketWithTagAndPhase(*data, 0, false); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_FALSE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(1u, visitor_.key_update_count()); EXPECT_EQ(2, visitor_.derive_next_key_count_); EXPECT_EQ(1, visitor_.decrypted_first_packet_in_key_phase_count_); } TEST_P(QuicFramerTest, KeyUpdateOnFirstReceivedPacket) { if (!framer_.version().UsesTls()) { return; } ASSERT_TRUE(framer_.version().KnowsWhichDecrypterToUse()); framer_.InstallDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<StrictTaggingDecrypter>(0)); framer_.SetKeyUpdateSupportForConnection(true); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = QuicPacketNumber(123); QuicFrames frames = {QuicFrame(QuicPaddingFrame())}; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); std::unique_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr); std::unique_ptr<QuicEncryptedPacket> encrypted( EncryptPacketWithTagAndPhase(*data, 1, true)); ASSERT_TRUE(encrypted); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); EXPECT_TRUE(framer_.ProcessPacket(*encrypted)); EXPECT_EQ(1u, visitor_.key_update_count()); EXPECT_EQ(1, visitor_.derive_next_key_count_); EXPECT_EQ(1, visitor_.decrypted_first_packet_in_key_phase_count_); } TEST_P(QuicFramerTest, ErrorWhenUnexpectedFrameTypeEncountered) { if (!VersionHasIetfQuicFrames(framer_.transport_version()) || !QuicVersionHasLongHeaderLengths(framer_.transport_version()) || !framer_.version().HasLongHeaderLengths()) { return; } SetDecrypterLevel(ENCRYPTION_ZERO_RTT); unsigned char packet[] = { 0xD3, QUIC_VERSION_BYTES, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x11, 0x05, 0x12, 0x34, 0x56, 0x00, 0x02, }; ReviseFirstByteByVersion(packet); QuicEncryptedPacket encrypted(AsChars(packet), ABSL_ARRAYSIZE(packet), false); EXPECT_FALSE(framer_.ProcessPacket(encrypted)); EXPECT_THAT(framer_.error(), IsError(IETF_QUIC_PROTOCOL_VIOLATION)); EXPECT_EQ( "IETF frame type IETF_ACK is unexpected at encryption level " "ENCRYPTION_ZERO_RTT", framer_.detailed_error()); } TEST_P(QuicFramerTest, ShortHeaderWithNonDefaultConnectionIdLength) { SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); unsigned char packet[kMaxIncomingPacketSize + 1] = { 0x43, 0x28, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x48, 0x12, 0x34, 0x56, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00 }; MockConnectionIdGenerator generator; EXPECT_CALL(generator, ConnectionIdLength(0x28)).WillOnce(Return(9)); unsigned char* p = packet; size_t p_size = ABSL_ARRAYSIZE(packet); const size_t header_size = GetPacketHeaderSize( framer_.transport_version(), kPacket8ByteConnectionId + 1, kPacket0ByteConnectionId, !kIncludeVersion, !kIncludeDiversificationNonce, PACKET_4BYTE_PACKET_NUMBER, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0, 0, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0) + 1; memset(p + header_size, 0, kMaxIncomingPacketSize - header_size); QuicEncryptedPacket encrypted(AsChars(p), p_size, false); PacketHeaderFormat format; QuicLongHeaderType long_packet_type = INVALID_PACKET_TYPE; bool version_flag; QuicConnectionId destination_connection_id, source_connection_id; QuicVersionLabel version_label; std::string detailed_error; bool use_length_prefix; std::optional<absl::string_view> retry_token; ParsedQuicVersion parsed_version = UnsupportedQuicVersion(); EXPECT_EQ(QUIC_NO_ERROR, QuicFramer::ParsePublicHeaderDispatcherShortHeaderLengthUnknown( encrypted, &format, &long_packet_type, &version_flag, &use_length_prefix, &version_label, &parsed_version, &destination_connection_id, &source_connection_id, &retry_token, &detailed_error, generator)); EXPECT_EQ(format, IETF_QUIC_SHORT_HEADER_PACKET); EXPECT_EQ(destination_connection_id.length(), 9); EXPECT_EQ(long_packet_type, INVALID_PACKET_TYPE); EXPECT_FALSE(version_flag); EXPECT_FALSE(use_length_prefix); EXPECT_EQ(version_label, 0); EXPECT_EQ(parsed_version, UnsupportedQuicVersion()); EXPECT_EQ(source_connection_id.length(), 0); EXPECT_FALSE(retry_token.has_value()); EXPECT_EQ(detailed_error, ""); } TEST_P(QuicFramerTest, ReportEcnCountsIfPresent) { if (!VersionHasIetfQuicFrames(framer_.transport_version())) { return; } SetDecrypterLevel(ENCRYPTION_FORWARD_SECURE); QuicPacketHeader header; header.destination_connection_id = FramerTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; for (bool ecn_marks : { false, true }) { QuicPaddingFrame padding_frame(kTagSize); QuicAckFrame ack_frame = InitAckFrame(5); if (ecn_marks) { ack_frame.ecn_counters = QuicEcnCounts(100, 10000, 1000000); } else { ack_frame.ecn_counters = std::nullopt; } QuicFrames frames = {QuicFrame(padding_frame), QuicFrame(&ack_frame)}; QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); std::unique_ptr<QuicPacket> raw_ack_packet(BuildDataPacket(header, frames)); ASSERT_TRUE(raw_ack_packet != nullptr); char buffer[kMaxOutgoingPacketSize]; size_t encrypted_length = framer_.EncryptPayload(ENCRYPTION_INITIAL, header.packet_number, *raw_ack_packet, buffer, kMaxOutgoingPacketSize); ASSERT_NE(0u, encrypted_length); QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); MockFramerVisitor visitor; framer_.set_visitor(&visitor); EXPECT_CALL(visitor, OnPacket()).Times(1); EXPECT_CALL(visitor, OnUnauthenticatedPublicHeader(_)) .Times(1) .WillOnce(Return(true)); EXPECT_CALL(visitor, OnUnauthenticatedHeader(_)) .Times(1) .WillOnce(Return(true)); EXPECT_CALL(visitor, OnPacketHeader(_)).Times(1); EXPECT_CALL(visitor, OnDecryptedPacket(_, _)).Times(1); EXPECT_CALL(visitor, OnAckFrameStart(_, _)).Times(1).WillOnce(Return(true)); EXPECT_CALL(visitor, OnAckRange(_, _)).Times(1).WillOnce(Return(true)); EXPECT_CALL(visitor, OnAckFrameEnd(_, ack_frame.ecn_counters)) .Times(1).WillOnce(Return(true)); EXPECT_CALL(visitor, OnPacketComplete()).Times(1); ASSERT_TRUE(framer_.ProcessPacket( QuicEncryptedPacket(buffer, encrypted_length, false))); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_framer.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_framer_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
9bb0b3de-0357-4a36-8c66-0271864550b4
cpp
google/quiche
quic_flow_controller
quiche/quic/core/quic_flow_controller.cc
quiche/quic/core/quic_flow_controller_test.cc
#include "quiche/quic/core/quic_flow_controller.h" #include <algorithm> #include <cstdint> #include <string> #include "absl/strings/str_cat.h" #include "quiche/quic/core/quic_connection.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/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 { #define ENDPOINT \ (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ") std::string QuicFlowController::LogLabel() { if (is_connection_flow_controller_) { return "connection"; } return absl::StrCat("stream ", id_); } QuicFlowController::QuicFlowController( QuicSession* session, QuicStreamId id, bool is_connection_flow_controller, QuicStreamOffset send_window_offset, QuicStreamOffset receive_window_offset, QuicByteCount receive_window_size_limit, bool should_auto_tune_receive_window, QuicFlowControllerInterface* session_flow_controller) : session_(session), connection_(session->connection()), id_(id), is_connection_flow_controller_(is_connection_flow_controller), perspective_(session->perspective()), bytes_sent_(0), send_window_offset_(send_window_offset), bytes_consumed_(0), highest_received_byte_offset_(0), receive_window_offset_(receive_window_offset), receive_window_size_(receive_window_offset), receive_window_size_limit_(receive_window_size_limit), auto_tune_receive_window_(should_auto_tune_receive_window), session_flow_controller_(session_flow_controller), last_blocked_send_window_offset_(0), prev_window_update_time_(QuicTime::Zero()) { QUICHE_DCHECK_LE(receive_window_size_, receive_window_size_limit_); QUICHE_DCHECK_EQ( is_connection_flow_controller_, QuicUtils::GetInvalidStreamId(session_->transport_version()) == id_); QUIC_DVLOG(1) << ENDPOINT << "Created flow controller for " << LogLabel() << ", setting initial receive window offset to: " << receive_window_offset_ << ", max receive window to: " << receive_window_size_ << ", max receive window limit to: " << receive_window_size_limit_ << ", setting send window offset to: " << send_window_offset_; } void QuicFlowController::AddBytesConsumed(QuicByteCount bytes_consumed) { bytes_consumed_ += bytes_consumed; QUIC_DVLOG(1) << ENDPOINT << LogLabel() << " consumed " << bytes_consumed_ << " bytes."; MaybeSendWindowUpdate(); } bool QuicFlowController::UpdateHighestReceivedOffset( QuicStreamOffset new_offset) { if (new_offset <= highest_received_byte_offset_) { return false; } QUIC_DVLOG(1) << ENDPOINT << LogLabel() << " highest byte offset increased from " << highest_received_byte_offset_ << " to " << new_offset; highest_received_byte_offset_ = new_offset; return true; } void QuicFlowController::AddBytesSent(QuicByteCount bytes_sent) { if (bytes_sent_ + bytes_sent > send_window_offset_) { QUIC_BUG(quic_bug_10836_1) << ENDPOINT << LogLabel() << " Trying to send an extra " << bytes_sent << " bytes, when bytes_sent = " << bytes_sent_ << ", and send_window_offset_ = " << send_window_offset_; bytes_sent_ = send_window_offset_; connection_->CloseConnection( QUIC_FLOW_CONTROL_SENT_TOO_MUCH_DATA, absl::StrCat(send_window_offset_ - (bytes_sent_ + bytes_sent), "bytes over send window offset"), ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } bytes_sent_ += bytes_sent; QUIC_DVLOG(1) << ENDPOINT << LogLabel() << " sent " << bytes_sent_ << " bytes."; } bool QuicFlowController::FlowControlViolation() { if (highest_received_byte_offset_ > receive_window_offset_) { QUIC_DLOG(INFO) << ENDPOINT << "Flow control violation on " << LogLabel() << ", receive window offset: " << receive_window_offset_ << ", highest received byte offset: " << highest_received_byte_offset_; return true; } return false; } void QuicFlowController::MaybeIncreaseMaxWindowSize() { QuicTime now = connection_->clock()->ApproximateNow(); QuicTime prev = prev_window_update_time_; prev_window_update_time_ = now; if (!prev.IsInitialized()) { QUIC_DVLOG(1) << ENDPOINT << "first window update for " << LogLabel(); return; } if (!auto_tune_receive_window_) { return; } QuicTime::Delta rtt = connection_->sent_packet_manager().GetRttStats()->smoothed_rtt(); if (rtt.IsZero()) { QUIC_DVLOG(1) << ENDPOINT << "rtt zero for " << LogLabel(); return; } QuicTime::Delta since_last = now - prev; QuicTime::Delta two_rtt = 2 * rtt; if (since_last >= two_rtt) { return; } QuicByteCount old_window = receive_window_size_; IncreaseWindowSize(); if (receive_window_size_ > old_window) { QUIC_DVLOG(1) << ENDPOINT << "New max window increase for " << LogLabel() << " after " << since_last.ToMicroseconds() << " us, and RTT is " << rtt.ToMicroseconds() << "us. max wndw: " << receive_window_size_; if (session_flow_controller_ != nullptr) { session_flow_controller_->EnsureWindowAtLeast( kSessionFlowControlMultiplier * receive_window_size_); } } else { QUIC_LOG_FIRST_N(INFO, 1) << ENDPOINT << "Max window at limit for " << LogLabel() << " after " << since_last.ToMicroseconds() << " us, and RTT is " << rtt.ToMicroseconds() << "us. Limit size: " << receive_window_size_; } } void QuicFlowController::IncreaseWindowSize() { receive_window_size_ *= 2; receive_window_size_ = std::min(receive_window_size_, receive_window_size_limit_); } QuicByteCount QuicFlowController::WindowUpdateThreshold() { return receive_window_size_ / 2; } void QuicFlowController::MaybeSendWindowUpdate() { if (!session_->connection()->connected()) { return; } QUICHE_DCHECK_LE(bytes_consumed_, receive_window_offset_); QuicStreamOffset available_window = receive_window_offset_ - bytes_consumed_; QuicByteCount threshold = WindowUpdateThreshold(); if (!prev_window_update_time_.IsInitialized()) { prev_window_update_time_ = connection_->clock()->ApproximateNow(); } if (available_window >= threshold) { QUIC_DVLOG(1) << ENDPOINT << "Not sending WindowUpdate for " << LogLabel() << ", available window: " << available_window << " >= threshold: " << threshold; return; } MaybeIncreaseMaxWindowSize(); UpdateReceiveWindowOffsetAndSendWindowUpdate(available_window); } void QuicFlowController::UpdateReceiveWindowOffsetAndSendWindowUpdate( QuicStreamOffset available_window) { receive_window_offset_ += (receive_window_size_ - available_window); QUIC_DVLOG(1) << ENDPOINT << "Sending WindowUpdate frame for " << LogLabel() << ", consumed bytes: " << bytes_consumed_ << ", available window: " << available_window << ", and threshold: " << WindowUpdateThreshold() << ", and receive window size: " << receive_window_size_ << ". New receive window offset is: " << receive_window_offset_; SendWindowUpdate(); } void QuicFlowController::MaybeSendBlocked() { if (SendWindowSize() != 0 || last_blocked_send_window_offset_ >= send_window_offset_) { return; } QUIC_DLOG(INFO) << ENDPOINT << LogLabel() << " is flow control blocked. " << "Send window: " << SendWindowSize() << ", bytes sent: " << bytes_sent_ << ", send limit: " << send_window_offset_; last_blocked_send_window_offset_ = send_window_offset_; session_->SendBlocked(id_, last_blocked_send_window_offset_); } bool QuicFlowController::UpdateSendWindowOffset( QuicStreamOffset new_send_window_offset) { if (new_send_window_offset <= send_window_offset_) { return false; } QUIC_DVLOG(1) << ENDPOINT << "UpdateSendWindowOffset for " << LogLabel() << " with new offset " << new_send_window_offset << " current offset: " << send_window_offset_ << " bytes_sent: " << bytes_sent_; const bool was_previously_blocked = IsBlocked(); send_window_offset_ = new_send_window_offset; return was_previously_blocked; } void QuicFlowController::EnsureWindowAtLeast(QuicByteCount window_size) { if (receive_window_size_limit_ >= window_size) { return; } QuicStreamOffset available_window = receive_window_offset_ - bytes_consumed_; IncreaseWindowSize(); UpdateReceiveWindowOffsetAndSendWindowUpdate(available_window); } bool QuicFlowController::IsBlocked() const { return SendWindowSize() == 0; } uint64_t QuicFlowController::SendWindowSize() const { if (bytes_sent_ > send_window_offset_) { return 0; } return send_window_offset_ - bytes_sent_; } void QuicFlowController::UpdateReceiveWindowSize(QuicStreamOffset size) { QUICHE_DCHECK_LE(size, receive_window_size_limit_); QUIC_DVLOG(1) << ENDPOINT << "UpdateReceiveWindowSize for " << LogLabel() << ": " << size; if (receive_window_size_ != receive_window_offset_) { QUIC_BUG(quic_bug_10836_2) << "receive_window_size_:" << receive_window_size_ << " != receive_window_offset:" << receive_window_offset_; return; } receive_window_size_ = size; receive_window_offset_ = size; } void QuicFlowController::SendWindowUpdate() { QuicStreamId id = id_; if (is_connection_flow_controller_) { id = QuicUtils::GetInvalidStreamId(connection_->transport_version()); } session_->SendWindowUpdate(id, receive_window_offset_); } }
#include "quiche/quic/core/quic_flow_controller.h" #include <memory> #include <utility> #include "absl/strings/str_cat.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/platform/api/quic_expect_bug.h" #include "quiche/quic/platform/api/quic_test.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_sent_packet_manager_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" using testing::_; using testing::Invoke; using testing::StrictMock; namespace quic { namespace test { const int64_t kRtt = 100; class MockFlowController : public QuicFlowControllerInterface { public: MockFlowController() {} MockFlowController(const MockFlowController&) = delete; MockFlowController& operator=(const MockFlowController&) = delete; ~MockFlowController() override {} MOCK_METHOD(void, EnsureWindowAtLeast, (QuicByteCount), (override)); }; class QuicFlowControllerTest : public QuicTest { public: void Initialize() { connection_ = new MockQuicConnection(&helper_, &alarm_factory_, Perspective::IS_CLIENT); connection_->SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(connection_->perspective())); session_ = std::make_unique<StrictMock<MockQuicSession>>(connection_); flow_controller_ = std::make_unique<QuicFlowController>( session_.get(), stream_id_, false, send_window_, receive_window_, kStreamReceiveWindowLimit, should_auto_tune_receive_window_, &session_flow_controller_); } protected: QuicStreamId stream_id_ = 1234; QuicByteCount send_window_ = kInitialSessionFlowControlWindowForTest; QuicByteCount receive_window_ = kInitialSessionFlowControlWindowForTest; std::unique_ptr<QuicFlowController> flow_controller_; MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; MockQuicConnection* connection_; std::unique_ptr<StrictMock<MockQuicSession>> session_; MockFlowController session_flow_controller_; bool should_auto_tune_receive_window_ = false; }; TEST_F(QuicFlowControllerTest, SendingBytes) { Initialize(); EXPECT_FALSE(flow_controller_->IsBlocked()); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(send_window_, flow_controller_->SendWindowSize()); flow_controller_->AddBytesSent(send_window_ / 2); EXPECT_FALSE(flow_controller_->IsBlocked()); EXPECT_EQ(send_window_ / 2, flow_controller_->SendWindowSize()); flow_controller_->AddBytesSent(send_window_ / 2); EXPECT_TRUE(flow_controller_->IsBlocked()); EXPECT_EQ(0u, flow_controller_->SendWindowSize()); EXPECT_CALL(*session_, SendBlocked(_, _)).Times(1); flow_controller_->MaybeSendBlocked(); EXPECT_TRUE(flow_controller_->UpdateSendWindowOffset(2 * send_window_)); EXPECT_FALSE(flow_controller_->IsBlocked()); EXPECT_EQ(send_window_, flow_controller_->SendWindowSize()); EXPECT_FALSE(flow_controller_->UpdateSendWindowOffset(send_window_ / 10)); EXPECT_EQ(send_window_, flow_controller_->SendWindowSize()); EXPECT_QUIC_BUG( { EXPECT_CALL( *connection_, CloseConnection(QUIC_FLOW_CONTROL_SENT_TOO_MUCH_DATA, _, _)); flow_controller_->AddBytesSent(send_window_ * 10); EXPECT_TRUE(flow_controller_->IsBlocked()); EXPECT_EQ(0u, flow_controller_->SendWindowSize()); }, absl::StrCat("Trying to send an extra ", send_window_ * 10, " bytes")); } TEST_F(QuicFlowControllerTest, ReceivingBytes) { Initialize(); EXPECT_FALSE(flow_controller_->IsBlocked()); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(kInitialSessionFlowControlWindowForTest, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); EXPECT_TRUE( flow_controller_->UpdateHighestReceivedOffset(1 + receive_window_ / 2)); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ((receive_window_ / 2) - 1, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); EXPECT_CALL(*session_, WriteControlFrame(_, _)).Times(1); flow_controller_->AddBytesConsumed(1 + receive_window_ / 2); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(kInitialSessionFlowControlWindowForTest, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); } TEST_F(QuicFlowControllerTest, Move) { Initialize(); flow_controller_->AddBytesSent(send_window_ / 2); EXPECT_FALSE(flow_controller_->IsBlocked()); EXPECT_EQ(send_window_ / 2, flow_controller_->SendWindowSize()); EXPECT_TRUE( flow_controller_->UpdateHighestReceivedOffset(1 + receive_window_ / 2)); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ((receive_window_ / 2) - 1, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); QuicFlowController flow_controller2(std::move(*flow_controller_)); EXPECT_EQ(send_window_ / 2, flow_controller2.SendWindowSize()); EXPECT_FALSE(flow_controller2.FlowControlViolation()); EXPECT_EQ((receive_window_ / 2) - 1, QuicFlowControllerPeer::ReceiveWindowSize(&flow_controller2)); } TEST_F(QuicFlowControllerTest, OnlySendBlockedFrameOncePerOffset) { Initialize(); EXPECT_FALSE(flow_controller_->IsBlocked()); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(send_window_, flow_controller_->SendWindowSize()); flow_controller_->AddBytesSent(send_window_); EXPECT_TRUE(flow_controller_->IsBlocked()); EXPECT_EQ(0u, flow_controller_->SendWindowSize()); EXPECT_CALL(*session_, SendBlocked(_, _)).Times(1); flow_controller_->MaybeSendBlocked(); EXPECT_CALL(*session_, SendBlocked(_, _)).Times(0); flow_controller_->MaybeSendBlocked(); flow_controller_->MaybeSendBlocked(); flow_controller_->MaybeSendBlocked(); flow_controller_->MaybeSendBlocked(); flow_controller_->MaybeSendBlocked(); EXPECT_TRUE(flow_controller_->UpdateSendWindowOffset(2 * send_window_)); EXPECT_FALSE(flow_controller_->IsBlocked()); EXPECT_EQ(send_window_, flow_controller_->SendWindowSize()); flow_controller_->AddBytesSent(send_window_); EXPECT_TRUE(flow_controller_->IsBlocked()); EXPECT_EQ(0u, flow_controller_->SendWindowSize()); EXPECT_CALL(*session_, SendBlocked(_, _)).Times(1); flow_controller_->MaybeSendBlocked(); } TEST_F(QuicFlowControllerTest, ReceivingBytesFastIncreasesFlowWindow) { should_auto_tune_receive_window_ = true; Initialize(); EXPECT_CALL(*session_, WriteControlFrame(_, _)).Times(1); EXPECT_TRUE(flow_controller_->auto_tune_receive_window()); connection_->AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); QuicSentPacketManager* manager = QuicConnectionPeer::GetSentPacketManager(connection_); RttStats* rtt_stats = const_cast<RttStats*>(manager->GetRttStats()); rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kRtt), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_FALSE(flow_controller_->IsBlocked()); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(kInitialSessionFlowControlWindowForTest, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); QuicByteCount threshold = QuicFlowControllerPeer::WindowUpdateThreshold(flow_controller_.get()); QuicStreamOffset receive_offset = threshold + 1; EXPECT_TRUE(flow_controller_->UpdateHighestReceivedOffset(receive_offset)); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(kInitialSessionFlowControlWindowForTest - receive_offset, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); EXPECT_CALL( session_flow_controller_, EnsureWindowAtLeast(kInitialSessionFlowControlWindowForTest * 2 * 1.5)); flow_controller_->AddBytesConsumed(threshold + 1); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(2 * kInitialSessionFlowControlWindowForTest, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); connection_->AdvanceTime(QuicTime::Delta::FromMilliseconds(2 * kRtt - 1)); receive_offset += threshold + 1; EXPECT_TRUE(flow_controller_->UpdateHighestReceivedOffset(receive_offset)); flow_controller_->AddBytesConsumed(threshold + 1); EXPECT_FALSE(flow_controller_->FlowControlViolation()); QuicByteCount new_threshold = QuicFlowControllerPeer::WindowUpdateThreshold(flow_controller_.get()); EXPECT_GT(new_threshold, threshold); } TEST_F(QuicFlowControllerTest, ReceivingBytesFastNoAutoTune) { Initialize(); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .Times(2) .WillRepeatedly(Invoke(&ClearControlFrameWithTransmissionType)); EXPECT_FALSE(flow_controller_->auto_tune_receive_window()); connection_->AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); QuicSentPacketManager* manager = QuicConnectionPeer::GetSentPacketManager(connection_); RttStats* rtt_stats = const_cast<RttStats*>(manager->GetRttStats()); rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kRtt), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_FALSE(flow_controller_->IsBlocked()); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(kInitialSessionFlowControlWindowForTest, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); QuicByteCount threshold = QuicFlowControllerPeer::WindowUpdateThreshold(flow_controller_.get()); QuicStreamOffset receive_offset = threshold + 1; EXPECT_TRUE(flow_controller_->UpdateHighestReceivedOffset(receive_offset)); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(kInitialSessionFlowControlWindowForTest - receive_offset, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); flow_controller_->AddBytesConsumed(threshold + 1); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(kInitialSessionFlowControlWindowForTest, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); connection_->AdvanceTime(QuicTime::Delta::FromMilliseconds(2 * kRtt - 1)); receive_offset += threshold + 1; EXPECT_TRUE(flow_controller_->UpdateHighestReceivedOffset(receive_offset)); flow_controller_->AddBytesConsumed(threshold + 1); EXPECT_FALSE(flow_controller_->FlowControlViolation()); QuicByteCount new_threshold = QuicFlowControllerPeer::WindowUpdateThreshold(flow_controller_.get()); EXPECT_EQ(new_threshold, threshold); } TEST_F(QuicFlowControllerTest, ReceivingBytesNormalStableFlowWindow) { should_auto_tune_receive_window_ = true; Initialize(); EXPECT_CALL(*session_, WriteControlFrame(_, _)).Times(1); EXPECT_TRUE(flow_controller_->auto_tune_receive_window()); connection_->AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); QuicSentPacketManager* manager = QuicConnectionPeer::GetSentPacketManager(connection_); RttStats* rtt_stats = const_cast<RttStats*>(manager->GetRttStats()); rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kRtt), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_FALSE(flow_controller_->IsBlocked()); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(kInitialSessionFlowControlWindowForTest, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); QuicByteCount threshold = QuicFlowControllerPeer::WindowUpdateThreshold(flow_controller_.get()); QuicStreamOffset receive_offset = threshold + 1; EXPECT_TRUE(flow_controller_->UpdateHighestReceivedOffset(receive_offset)); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(kInitialSessionFlowControlWindowForTest - receive_offset, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); EXPECT_CALL( session_flow_controller_, EnsureWindowAtLeast(kInitialSessionFlowControlWindowForTest * 2 * 1.5)); flow_controller_->AddBytesConsumed(threshold + 1); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(2 * kInitialSessionFlowControlWindowForTest, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); connection_->AdvanceTime(QuicTime::Delta::FromMilliseconds(2 * kRtt + 1)); receive_offset += threshold + 1; EXPECT_TRUE(flow_controller_->UpdateHighestReceivedOffset(receive_offset)); flow_controller_->AddBytesConsumed(threshold + 1); EXPECT_FALSE(flow_controller_->FlowControlViolation()); QuicByteCount new_threshold = QuicFlowControllerPeer::WindowUpdateThreshold(flow_controller_.get()); EXPECT_EQ(new_threshold, 2 * threshold); } TEST_F(QuicFlowControllerTest, ReceivingBytesNormalNoAutoTune) { Initialize(); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .Times(2) .WillRepeatedly(Invoke(&ClearControlFrameWithTransmissionType)); EXPECT_FALSE(flow_controller_->auto_tune_receive_window()); connection_->AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); QuicSentPacketManager* manager = QuicConnectionPeer::GetSentPacketManager(connection_); RttStats* rtt_stats = const_cast<RttStats*>(manager->GetRttStats()); rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kRtt), QuicTime::Delta::Zero(), QuicTime::Zero()); EXPECT_FALSE(flow_controller_->IsBlocked()); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(kInitialSessionFlowControlWindowForTest, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); QuicByteCount threshold = QuicFlowControllerPeer::WindowUpdateThreshold(flow_controller_.get()); QuicStreamOffset receive_offset = threshold + 1; EXPECT_TRUE(flow_controller_->UpdateHighestReceivedOffset(receive_offset)); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(kInitialSessionFlowControlWindowForTest - receive_offset, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); flow_controller_->AddBytesConsumed(threshold + 1); EXPECT_FALSE(flow_controller_->FlowControlViolation()); EXPECT_EQ(kInitialSessionFlowControlWindowForTest, QuicFlowControllerPeer::ReceiveWindowSize(flow_controller_.get())); connection_->AdvanceTime(QuicTime::Delta::FromMilliseconds(2 * kRtt + 1)); receive_offset += threshold + 1; EXPECT_TRUE(flow_controller_->UpdateHighestReceivedOffset(receive_offset)); flow_controller_->AddBytesConsumed(threshold + 1); EXPECT_FALSE(flow_controller_->FlowControlViolation()); QuicByteCount new_threshold = QuicFlowControllerPeer::WindowUpdateThreshold(flow_controller_.get()); EXPECT_EQ(new_threshold, threshold); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_flow_controller.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_flow_controller_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
03d1f556-a605-4615-a23e-2c5adb2cbce3
cpp
google/quiche
quic_idle_network_detector
quiche/quic/core/quic_idle_network_detector.cc
quiche/quic/core/quic_idle_network_detector_test.cc
#include "quiche/quic/core/quic_idle_network_detector.h" #include <algorithm> #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_time.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 { namespace { } QuicIdleNetworkDetector::QuicIdleNetworkDetector(Delegate* delegate, QuicTime now, QuicAlarm* alarm) : delegate_(delegate), start_time_(now), handshake_timeout_(QuicTime::Delta::Infinite()), time_of_last_received_packet_(now), time_of_first_packet_sent_after_receiving_(QuicTime::Zero()), idle_network_timeout_(QuicTime::Delta::Infinite()), alarm_(*alarm) {} void QuicIdleNetworkDetector::OnAlarm() { if (handshake_timeout_.IsInfinite()) { delegate_->OnIdleNetworkDetected(); return; } if (idle_network_timeout_.IsInfinite()) { delegate_->OnHandshakeTimeout(); return; } if (last_network_activity_time() + idle_network_timeout_ > start_time_ + handshake_timeout_) { delegate_->OnHandshakeTimeout(); return; } delegate_->OnIdleNetworkDetected(); } void QuicIdleNetworkDetector::SetTimeouts( QuicTime::Delta handshake_timeout, QuicTime::Delta idle_network_timeout) { handshake_timeout_ = handshake_timeout; idle_network_timeout_ = idle_network_timeout; SetAlarm(); } void QuicIdleNetworkDetector::StopDetection() { alarm_.PermanentCancel(); handshake_timeout_ = QuicTime::Delta::Infinite(); idle_network_timeout_ = QuicTime::Delta::Infinite(); handshake_timeout_ = QuicTime::Delta::Infinite(); stopped_ = true; } void QuicIdleNetworkDetector::OnPacketSent(QuicTime now, QuicTime::Delta pto_delay) { if (time_of_first_packet_sent_after_receiving_ > time_of_last_received_packet_) { return; } time_of_first_packet_sent_after_receiving_ = std::max(time_of_first_packet_sent_after_receiving_, now); if (shorter_idle_timeout_on_sent_packet_) { MaybeSetAlarmOnSentPacket(pto_delay); return; } SetAlarm(); } void QuicIdleNetworkDetector::OnPacketReceived(QuicTime now) { time_of_last_received_packet_ = std::max(time_of_last_received_packet_, now); SetAlarm(); } void QuicIdleNetworkDetector::SetAlarm() { if (stopped_) { QUIC_BUG(quic_idle_detector_set_alarm_after_stopped) << "SetAlarm called after stopped"; return; } QuicTime new_deadline = QuicTime::Zero(); if (!handshake_timeout_.IsInfinite()) { new_deadline = start_time_ + handshake_timeout_; } if (!idle_network_timeout_.IsInfinite()) { const QuicTime idle_network_deadline = GetIdleNetworkDeadline(); if (new_deadline.IsInitialized()) { new_deadline = std::min(new_deadline, idle_network_deadline); } else { new_deadline = idle_network_deadline; } } alarm_.Update(new_deadline, kAlarmGranularity); } void QuicIdleNetworkDetector::MaybeSetAlarmOnSentPacket( QuicTime::Delta pto_delay) { QUICHE_DCHECK(shorter_idle_timeout_on_sent_packet_); if (!handshake_timeout_.IsInfinite() || !alarm_.IsSet()) { SetAlarm(); return; } const QuicTime deadline = alarm_.deadline(); const QuicTime min_deadline = last_network_activity_time() + pto_delay; if (deadline > min_deadline) { return; } alarm_.Update(min_deadline, kAlarmGranularity); } QuicTime QuicIdleNetworkDetector::GetIdleNetworkDeadline() const { if (idle_network_timeout_.IsInfinite()) { return QuicTime::Zero(); } return last_network_activity_time() + idle_network_timeout_; } }
#include "quiche/quic/core/quic_idle_network_detector.h" #include "quiche/quic/core/quic_connection_alarms.h" #include "quiche/quic/core/quic_one_block_arena.h" #include "quiche/quic/core/quic_time.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/mock_quic_connection_alarms.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { namespace test { class QuicIdleNetworkDetectorTestPeer { public: static QuicAlarm& GetAlarm(QuicIdleNetworkDetector* detector) { return detector->alarm_; } }; namespace { class MockDelegate : public QuicIdleNetworkDetector::Delegate { public: MOCK_METHOD(void, OnHandshakeTimeout, (), (override)); MOCK_METHOD(void, OnIdleNetworkDetected, (), (override)); }; class QuicIdleNetworkDetectorTest : public QuicTest { public: QuicIdleNetworkDetectorTest() : alarms_(&connection_alarms_delegate_, alarm_factory_, arena_), detector_(&delegate_, clock_.Now() + QuicTimeDelta::FromSeconds(1), &alarms_.idle_network_detector_alarm()) { clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1)); alarm_ = static_cast<MockAlarmFactory::TestAlarm*>( &alarms_.idle_network_detector_alarm()); ON_CALL(connection_alarms_delegate_, OnIdleDetectorAlarm()) .WillByDefault([&] { detector_.OnAlarm(); }); } protected: testing::StrictMock<MockDelegate> delegate_; MockConnectionAlarmsDelegate connection_alarms_delegate_; QuicConnectionArena arena_; MockAlarmFactory alarm_factory_; QuicConnectionAlarms alarms_; MockClock clock_; QuicIdleNetworkDetector detector_; MockAlarmFactory::TestAlarm* alarm_; }; TEST_F(QuicIdleNetworkDetectorTest, IdleNetworkDetectedBeforeHandshakeCompletes) { EXPECT_FALSE(alarm_->IsSet()); detector_.SetTimeouts( QuicTime::Delta::FromSeconds(30), QuicTime::Delta::FromSeconds(20)); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(clock_.Now() + QuicTime::Delta::FromSeconds(20), alarm_->deadline()); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20)); EXPECT_CALL(delegate_, OnIdleNetworkDetected()); alarm_->Fire(); } TEST_F(QuicIdleNetworkDetectorTest, HandshakeTimeout) { EXPECT_FALSE(alarm_->IsSet()); detector_.SetTimeouts( QuicTime::Delta::FromSeconds(30), QuicTime::Delta::FromSeconds(20)); EXPECT_TRUE(alarm_->IsSet()); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15)); detector_.OnPacketReceived(clock_.Now()); EXPECT_EQ(clock_.Now() + QuicTime::Delta::FromSeconds(15), alarm_->deadline()); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15)); EXPECT_CALL(delegate_, OnHandshakeTimeout()); alarm_->Fire(); } TEST_F(QuicIdleNetworkDetectorTest, IdleNetworkDetectedAfterHandshakeCompletes) { EXPECT_FALSE(alarm_->IsSet()); detector_.SetTimeouts( QuicTime::Delta::FromSeconds(30), QuicTime::Delta::FromSeconds(20)); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(clock_.Now() + QuicTime::Delta::FromSeconds(20), alarm_->deadline()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(200)); detector_.OnPacketReceived(clock_.Now()); detector_.SetTimeouts( QuicTime::Delta::Infinite(), QuicTime::Delta::FromSeconds(600)); EXPECT_EQ(clock_.Now() + QuicTime::Delta::FromSeconds(600), alarm_->deadline()); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(600)); EXPECT_CALL(delegate_, OnIdleNetworkDetected()); alarm_->Fire(); } TEST_F(QuicIdleNetworkDetectorTest, DoNotExtendIdleDeadlineOnConsecutiveSentPackets) { EXPECT_FALSE(alarm_->IsSet()); detector_.SetTimeouts( QuicTime::Delta::FromSeconds(30), QuicTime::Delta::FromSeconds(20)); EXPECT_TRUE(alarm_->IsSet()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(200)); detector_.OnPacketReceived(clock_.Now()); detector_.SetTimeouts( QuicTime::Delta::Infinite(), QuicTime::Delta::FromSeconds(600)); EXPECT_EQ(clock_.Now() + QuicTime::Delta::FromSeconds(600), alarm_->deadline()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(200)); detector_.OnPacketSent(clock_.Now(), QuicTime::Delta::Zero()); const QuicTime packet_sent_time = clock_.Now(); EXPECT_EQ(packet_sent_time + QuicTime::Delta::FromSeconds(600), alarm_->deadline()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(200)); detector_.OnPacketSent(clock_.Now(), QuicTime::Delta::Zero()); EXPECT_EQ(packet_sent_time + QuicTime::Delta::FromSeconds(600), alarm_->deadline()); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(600) - QuicTime::Delta::FromMilliseconds(200)); EXPECT_CALL(delegate_, OnIdleNetworkDetected()); alarm_->Fire(); } TEST_F(QuicIdleNetworkDetectorTest, ShorterIdleTimeoutOnSentPacket) { detector_.enable_shorter_idle_timeout_on_sent_packet(); QuicTime::Delta idle_network_timeout = QuicTime::Delta::Zero(); idle_network_timeout = QuicTime::Delta::FromSeconds(30); detector_.SetTimeouts( QuicTime::Delta::Infinite(), idle_network_timeout); EXPECT_TRUE(alarm_->IsSet()); const QuicTime deadline = alarm_->deadline(); EXPECT_EQ(clock_.Now() + QuicTime::Delta::FromSeconds(30), deadline); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15)); detector_.OnPacketSent(clock_.Now(), QuicTime::Delta::FromSeconds(2)); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(deadline, alarm_->deadline()); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(14)); detector_.OnPacketSent(clock_.Now(), QuicTime::Delta::FromSeconds(2)); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(deadline, alarm_->deadline()); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1)); detector_.OnPacketReceived(clock_.Now()); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(clock_.Now() + QuicTime::Delta::FromSeconds(30), alarm_->deadline()); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(29)); detector_.OnPacketSent(clock_.Now(), QuicTime::Delta::FromSeconds(2)); EXPECT_TRUE(alarm_->IsSet()); EXPECT_EQ(clock_.Now() + QuicTime::Delta::FromSeconds(2), alarm_->deadline()); } TEST_F(QuicIdleNetworkDetectorTest, NoAlarmAfterStopped) { detector_.StopDetection(); EXPECT_QUIC_BUG( detector_.SetTimeouts( QuicTime::Delta::FromSeconds(30), QuicTime::Delta::FromSeconds(20)), "SetAlarm called after stopped"); EXPECT_FALSE(alarm_->IsSet()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_idle_network_detector.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_idle_network_detector_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
7e021945-fa0a-45dd-bdad-66d1e9d09bc0
cpp
google/quiche
quic_data_writer
quiche/quic/core/quic_data_writer.cc
quiche/quic/core/quic_data_writer_test.cc
#include "quiche/quic/core/quic_data_writer.h" #include <algorithm> #include <limits> #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/quic_random.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/common/quiche_endian.h" namespace quic { QuicDataWriter::QuicDataWriter(size_t size, char* buffer) : quiche::QuicheDataWriter(size, buffer) {} QuicDataWriter::QuicDataWriter(size_t size, char* buffer, quiche::Endianness endianness) : quiche::QuicheDataWriter(size, buffer, endianness) {} QuicDataWriter::~QuicDataWriter() {} bool QuicDataWriter::WriteUFloat16(uint64_t value) { uint16_t result; if (value < (UINT64_C(1) << kUFloat16MantissaEffectiveBits)) { result = static_cast<uint16_t>(value); } else if (value >= kUFloat16MaxValue) { result = std::numeric_limits<uint16_t>::max(); } else { uint16_t exponent = 0; for (uint16_t offset = 16; offset > 0; offset /= 2) { if (value >= (UINT64_C(1) << (kUFloat16MantissaBits + offset))) { exponent += offset; value >>= offset; } } QUICHE_DCHECK_GE(exponent, 1); QUICHE_DCHECK_LE(exponent, kUFloat16MaxExponent); QUICHE_DCHECK_GE(value, UINT64_C(1) << kUFloat16MantissaBits); QUICHE_DCHECK_LT(value, UINT64_C(1) << kUFloat16MantissaEffectiveBits); result = static_cast<uint16_t>(value + (exponent << kUFloat16MantissaBits)); } if (endianness() == quiche::NETWORK_BYTE_ORDER) { result = quiche::QuicheEndian::HostToNet16(result); } return WriteBytes(&result, sizeof(result)); } bool QuicDataWriter::WriteConnectionId(QuicConnectionId connection_id) { if (connection_id.IsEmpty()) { return true; } return WriteBytes(connection_id.data(), connection_id.length()); } bool QuicDataWriter::WriteLengthPrefixedConnectionId( QuicConnectionId connection_id) { return WriteUInt8(connection_id.length()) && WriteConnectionId(connection_id); } bool QuicDataWriter::WriteRandomBytes(QuicRandom* random, size_t length) { char* dest = BeginWrite(length); if (!dest) { return false; } random->RandBytes(dest, length); IncreaseLength(length); return true; } bool QuicDataWriter::WriteInsecureRandomBytes(QuicRandom* random, size_t length) { char* dest = BeginWrite(length); if (!dest) { return false; } random->InsecureRandBytes(dest, length); IncreaseLength(length); return true; } }
#include "quiche/quic/core/quic_data_writer.h" #include <cstdint> #include <cstring> #include <string> #include <vector> #include "absl/base/macros.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_data_reader.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_flags.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/quiche_endian.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); } struct TestParams { explicit TestParams(quiche::Endianness endianness) : endianness(endianness) {} quiche::Endianness endianness; }; std::string PrintToString(const TestParams& p) { return absl::StrCat( (p.endianness == quiche::NETWORK_BYTE_ORDER ? "Network" : "Host"), "ByteOrder"); } std::vector<TestParams> GetTestParams() { std::vector<TestParams> params; for (quiche::Endianness endianness : {quiche::NETWORK_BYTE_ORDER, quiche::HOST_BYTE_ORDER}) { params.push_back(TestParams(endianness)); } return params; } class QuicDataWriterTest : public QuicTestWithParam<TestParams> {}; INSTANTIATE_TEST_SUITE_P(QuicDataWriterTests, QuicDataWriterTest, ::testing::ValuesIn(GetTestParams()), ::testing::PrintToStringParamName()); TEST_P(QuicDataWriterTest, SanityCheckUFloat16Consts) { EXPECT_EQ(30, kUFloat16MaxExponent); EXPECT_EQ(11, kUFloat16MantissaBits); EXPECT_EQ(12, kUFloat16MantissaEffectiveBits); EXPECT_EQ(UINT64_C(0x3FFC0000000), kUFloat16MaxValue); } TEST_P(QuicDataWriterTest, WriteUFloat16) { struct TestCase { uint64_t decoded; uint16_t encoded; }; TestCase test_cases[] = { {0, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}, {6, 6}, {7, 7}, {15, 15}, {31, 31}, {42, 42}, {123, 123}, {1234, 1234}, {2046, 2046}, {2047, 2047}, {2048, 2048}, {2049, 2049}, {4094, 4094}, {4095, 4095}, {4096, 4096}, {4097, 4096}, {4098, 4097}, {4099, 4097}, {4100, 4098}, {4101, 4098}, {8190, 6143}, {8191, 6143}, {8192, 6144}, {8193, 6144}, {8194, 6144}, {8195, 6144}, {8196, 6145}, {8197, 6145}, {0x7FF8000, 0x87FF}, {0x7FFFFFF, 0x87FF}, {0x8000000, 0x8800}, {0xFFF0000, 0x8FFF}, {0xFFFFFFF, 0x8FFF}, {0x10000000, 0x9000}, {0x1FFFFFFFFFE, 0xF7FF}, {0x1FFFFFFFFFF, 0xF7FF}, {0x20000000000, 0xF800}, {0x20000000001, 0xF800}, {0x2003FFFFFFE, 0xF800}, {0x2003FFFFFFF, 0xF800}, {0x20040000000, 0xF801}, {0x20040000001, 0xF801}, {0x3FF80000000, 0xFFFE}, {0x3FFBFFFFFFF, 0xFFFE}, {0x3FFC0000000, 0xFFFF}, {0x3FFC0000001, 0xFFFF}, {0x3FFFFFFFFFF, 0xFFFF}, {0x40000000000, 0xFFFF}, {0xFFFFFFFFFFFFFFFF, 0xFFFF}, }; int num_test_cases = sizeof(test_cases) / sizeof(test_cases[0]); for (int i = 0; i < num_test_cases; ++i) { char buffer[2]; QuicDataWriter writer(2, buffer, GetParam().endianness); EXPECT_TRUE(writer.WriteUFloat16(test_cases[i].decoded)); uint16_t result = *reinterpret_cast<uint16_t*>(writer.data()); if (GetParam().endianness == quiche::NETWORK_BYTE_ORDER) { result = quiche::QuicheEndian::HostToNet16(result); } EXPECT_EQ(test_cases[i].encoded, result); } } TEST_P(QuicDataWriterTest, ReadUFloat16) { struct TestCase { uint64_t decoded; uint16_t encoded; }; TestCase test_cases[] = { {0, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}, {6, 6}, {7, 7}, {15, 15}, {31, 31}, {42, 42}, {123, 123}, {1234, 1234}, {2046, 2046}, {2047, 2047}, {2048, 2048}, {2049, 2049}, {4094, 4094}, {4095, 4095}, {4096, 4096}, {4098, 4097}, {4100, 4098}, {8190, 6143}, {8192, 6144}, {8196, 6145}, {0x7FF8000, 0x87FF}, {0x8000000, 0x8800}, {0xFFF0000, 0x8FFF}, {0x10000000, 0x9000}, {0x1FFE0000000, 0xF7FF}, {0x20000000000, 0xF800}, {0x20040000000, 0xF801}, {0x3FF80000000, 0xFFFE}, {0x3FFC0000000, 0xFFFF}, }; int num_test_cases = sizeof(test_cases) / sizeof(test_cases[0]); for (int i = 0; i < num_test_cases; ++i) { uint16_t encoded_ufloat = test_cases[i].encoded; if (GetParam().endianness == quiche::NETWORK_BYTE_ORDER) { encoded_ufloat = quiche::QuicheEndian::HostToNet16(encoded_ufloat); } QuicDataReader reader(reinterpret_cast<char*>(&encoded_ufloat), 2, GetParam().endianness); uint64_t value; EXPECT_TRUE(reader.ReadUFloat16(&value)); EXPECT_EQ(test_cases[i].decoded, value); } } TEST_P(QuicDataWriterTest, RoundTripUFloat16) { uint64_t previous_value = 0; for (uint16_t i = 1; i < 0xFFFF; ++i) { uint16_t read_number = i; if (GetParam().endianness == quiche::NETWORK_BYTE_ORDER) { read_number = quiche::QuicheEndian::HostToNet16(read_number); } QuicDataReader reader(reinterpret_cast<char*>(&read_number), 2, GetParam().endianness); uint64_t value; EXPECT_TRUE(reader.ReadUFloat16(&value)); if (i < 4097) { EXPECT_EQ(i, value); } EXPECT_LT(previous_value, value); if (i > 2000) { EXPECT_GT(previous_value * 1005, value * 1000); } EXPECT_LT(value, UINT64_C(0x3FFC0000000)); previous_value = value; char buffer[6]; QuicDataWriter writer(6, buffer, GetParam().endianness); EXPECT_TRUE(writer.WriteUFloat16(value - 1)); EXPECT_TRUE(writer.WriteUFloat16(value)); EXPECT_TRUE(writer.WriteUFloat16(value + 1)); uint16_t encoded1 = *reinterpret_cast<uint16_t*>(writer.data()); uint16_t encoded2 = *reinterpret_cast<uint16_t*>(writer.data() + 2); uint16_t encoded3 = *reinterpret_cast<uint16_t*>(writer.data() + 4); if (GetParam().endianness == quiche::NETWORK_BYTE_ORDER) { encoded1 = quiche::QuicheEndian::NetToHost16(encoded1); encoded2 = quiche::QuicheEndian::NetToHost16(encoded2); encoded3 = quiche::QuicheEndian::NetToHost16(encoded3); } EXPECT_EQ(i - 1, encoded1); EXPECT_EQ(i, encoded2); EXPECT_EQ(i < 4096 ? i + 1 : i, encoded3); } } TEST_P(QuicDataWriterTest, WriteConnectionId) { QuicConnectionId connection_id = TestConnectionId(UINT64_C(0x0011223344556677)); char big_endian[] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, }; EXPECT_EQ(connection_id.length(), ABSL_ARRAYSIZE(big_endian)); ASSERT_LE(connection_id.length(), 255); char buffer[255]; QuicDataWriter writer(connection_id.length(), buffer, GetParam().endianness); EXPECT_TRUE(writer.WriteConnectionId(connection_id)); quiche::test::CompareCharArraysWithHexError( "connection_id", buffer, connection_id.length(), big_endian, connection_id.length()); QuicConnectionId read_connection_id; QuicDataReader reader(buffer, connection_id.length(), GetParam().endianness); EXPECT_TRUE( reader.ReadConnectionId(&read_connection_id, ABSL_ARRAYSIZE(big_endian))); EXPECT_EQ(connection_id, read_connection_id); } TEST_P(QuicDataWriterTest, LengthPrefixedConnectionId) { QuicConnectionId connection_id = TestConnectionId(UINT64_C(0x0011223344556677)); char length_prefixed_connection_id[] = { 0x08, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, }; EXPECT_EQ(ABSL_ARRAYSIZE(length_prefixed_connection_id), kConnectionIdLengthSize + connection_id.length()); char buffer[kConnectionIdLengthSize + 255] = {}; QuicDataWriter writer(ABSL_ARRAYSIZE(buffer), buffer); EXPECT_TRUE(writer.WriteLengthPrefixedConnectionId(connection_id)); quiche::test::CompareCharArraysWithHexError( "WriteLengthPrefixedConnectionId", buffer, writer.length(), length_prefixed_connection_id, ABSL_ARRAYSIZE(length_prefixed_connection_id)); memset(buffer, 0, ABSL_ARRAYSIZE(buffer)); QuicDataWriter writer2(ABSL_ARRAYSIZE(buffer), buffer); EXPECT_TRUE(writer2.WriteUInt8(connection_id.length())); EXPECT_TRUE(writer2.WriteConnectionId(connection_id)); quiche::test::CompareCharArraysWithHexError( "Write length then ConnectionId", buffer, writer2.length(), length_prefixed_connection_id, ABSL_ARRAYSIZE(length_prefixed_connection_id)); QuicConnectionId read_connection_id; QuicDataReader reader(buffer, ABSL_ARRAYSIZE(buffer)); EXPECT_TRUE(reader.ReadLengthPrefixedConnectionId(&read_connection_id)); EXPECT_EQ(connection_id, read_connection_id); uint8_t read_connection_id_length2 = 33; QuicConnectionId read_connection_id2; QuicDataReader reader2(buffer, ABSL_ARRAYSIZE(buffer)); ASSERT_TRUE(reader2.ReadUInt8(&read_connection_id_length2)); EXPECT_EQ(connection_id.length(), read_connection_id_length2); EXPECT_TRUE(reader2.ReadConnectionId(&read_connection_id2, read_connection_id_length2)); EXPECT_EQ(connection_id, read_connection_id2); } TEST_P(QuicDataWriterTest, EmptyConnectionIds) { QuicConnectionId empty_connection_id = EmptyQuicConnectionId(); char buffer[2]; QuicDataWriter writer(ABSL_ARRAYSIZE(buffer), buffer, GetParam().endianness); EXPECT_TRUE(writer.WriteConnectionId(empty_connection_id)); EXPECT_TRUE(writer.WriteUInt8(1)); EXPECT_TRUE(writer.WriteConnectionId(empty_connection_id)); EXPECT_TRUE(writer.WriteUInt8(2)); EXPECT_TRUE(writer.WriteConnectionId(empty_connection_id)); EXPECT_FALSE(writer.WriteUInt8(3)); EXPECT_EQ(buffer[0], 1); EXPECT_EQ(buffer[1], 2); QuicConnectionId read_connection_id = TestConnectionId(); uint8_t read_byte; QuicDataReader reader(buffer, ABSL_ARRAYSIZE(buffer), GetParam().endianness); EXPECT_TRUE(reader.ReadConnectionId(&read_connection_id, 0)); EXPECT_EQ(read_connection_id, empty_connection_id); EXPECT_TRUE(reader.ReadUInt8(&read_byte)); EXPECT_EQ(read_byte, 1); read_connection_id = TestConnectionId(); EXPECT_TRUE(reader.ReadConnectionId(&read_connection_id, 0)); EXPECT_EQ(read_connection_id, empty_connection_id); EXPECT_TRUE(reader.ReadUInt8(&read_byte)); EXPECT_EQ(read_byte, 2); read_connection_id = TestConnectionId(); EXPECT_TRUE(reader.ReadConnectionId(&read_connection_id, 0)); EXPECT_EQ(read_connection_id, empty_connection_id); EXPECT_FALSE(reader.ReadUInt8(&read_byte)); } TEST_P(QuicDataWriterTest, WriteTag) { char CHLO[] = { 'C', 'H', 'L', 'O', }; const int kBufferLength = sizeof(QuicTag); char buffer[kBufferLength]; QuicDataWriter writer(kBufferLength, buffer, GetParam().endianness); writer.WriteTag(kCHLO); quiche::test::CompareCharArraysWithHexError("CHLO", buffer, kBufferLength, CHLO, kBufferLength); QuicTag read_chlo; QuicDataReader reader(buffer, kBufferLength, GetParam().endianness); reader.ReadTag(&read_chlo); EXPECT_EQ(kCHLO, read_chlo); } TEST_P(QuicDataWriterTest, Write16BitUnsignedIntegers) { char little_endian16[] = {0x22, 0x11}; char big_endian16[] = {0x11, 0x22}; char buffer16[2]; { uint16_t in_memory16 = 0x1122; QuicDataWriter writer(2, buffer16, GetParam().endianness); writer.WriteUInt16(in_memory16); quiche::test::CompareCharArraysWithHexError( "uint16_t", buffer16, 2, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian16 : little_endian16, 2); uint16_t read_number16; QuicDataReader reader(buffer16, 2, GetParam().endianness); reader.ReadUInt16(&read_number16); EXPECT_EQ(in_memory16, read_number16); } { uint64_t in_memory16 = 0x0000000000001122; QuicDataWriter writer(2, buffer16, GetParam().endianness); writer.WriteBytesToUInt64(2, in_memory16); quiche::test::CompareCharArraysWithHexError( "uint16_t", buffer16, 2, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian16 : little_endian16, 2); uint64_t read_number16; QuicDataReader reader(buffer16, 2, GetParam().endianness); reader.ReadBytesToUInt64(2, &read_number16); EXPECT_EQ(in_memory16, read_number16); } } TEST_P(QuicDataWriterTest, Write24BitUnsignedIntegers) { char little_endian24[] = {0x33, 0x22, 0x11}; char big_endian24[] = {0x11, 0x22, 0x33}; char buffer24[3]; uint64_t in_memory24 = 0x0000000000112233; QuicDataWriter writer(3, buffer24, GetParam().endianness); writer.WriteBytesToUInt64(3, in_memory24); quiche::test::CompareCharArraysWithHexError( "uint24", buffer24, 3, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian24 : little_endian24, 3); uint64_t read_number24; QuicDataReader reader(buffer24, 3, GetParam().endianness); reader.ReadBytesToUInt64(3, &read_number24); EXPECT_EQ(in_memory24, read_number24); } TEST_P(QuicDataWriterTest, Write32BitUnsignedIntegers) { char little_endian32[] = {0x44, 0x33, 0x22, 0x11}; char big_endian32[] = {0x11, 0x22, 0x33, 0x44}; char buffer32[4]; { uint32_t in_memory32 = 0x11223344; QuicDataWriter writer(4, buffer32, GetParam().endianness); writer.WriteUInt32(in_memory32); quiche::test::CompareCharArraysWithHexError( "uint32_t", buffer32, 4, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian32 : little_endian32, 4); uint32_t read_number32; QuicDataReader reader(buffer32, 4, GetParam().endianness); reader.ReadUInt32(&read_number32); EXPECT_EQ(in_memory32, read_number32); } { uint64_t in_memory32 = 0x11223344; QuicDataWriter writer(4, buffer32, GetParam().endianness); writer.WriteBytesToUInt64(4, in_memory32); quiche::test::CompareCharArraysWithHexError( "uint32_t", buffer32, 4, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian32 : little_endian32, 4); uint64_t read_number32; QuicDataReader reader(buffer32, 4, GetParam().endianness); reader.ReadBytesToUInt64(4, &read_number32); EXPECT_EQ(in_memory32, read_number32); } } TEST_P(QuicDataWriterTest, Write40BitUnsignedIntegers) { uint64_t in_memory40 = 0x0000001122334455; char little_endian40[] = {0x55, 0x44, 0x33, 0x22, 0x11}; char big_endian40[] = {0x11, 0x22, 0x33, 0x44, 0x55}; char buffer40[5]; QuicDataWriter writer(5, buffer40, GetParam().endianness); writer.WriteBytesToUInt64(5, in_memory40); quiche::test::CompareCharArraysWithHexError( "uint40", buffer40, 5, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian40 : little_endian40, 5); uint64_t read_number40; QuicDataReader reader(buffer40, 5, GetParam().endianness); reader.ReadBytesToUInt64(5, &read_number40); EXPECT_EQ(in_memory40, read_number40); } TEST_P(QuicDataWriterTest, Write48BitUnsignedIntegers) { uint64_t in_memory48 = 0x0000112233445566; char little_endian48[] = {0x66, 0x55, 0x44, 0x33, 0x22, 0x11}; char big_endian48[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66}; char buffer48[6]; QuicDataWriter writer(6, buffer48, GetParam().endianness); writer.WriteBytesToUInt64(6, in_memory48); quiche::test::CompareCharArraysWithHexError( "uint48", buffer48, 6, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian48 : little_endian48, 6); uint64_t read_number48; QuicDataReader reader(buffer48, 6, GetParam().endianness); reader.ReadBytesToUInt64(6., &read_number48); EXPECT_EQ(in_memory48, read_number48); } TEST_P(QuicDataWriterTest, Write56BitUnsignedIntegers) { uint64_t in_memory56 = 0x0011223344556677; char little_endian56[] = {0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11}; char big_endian56[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77}; char buffer56[7]; QuicDataWriter writer(7, buffer56, GetParam().endianness); writer.WriteBytesToUInt64(7, in_memory56); quiche::test::CompareCharArraysWithHexError( "uint56", buffer56, 7, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? big_endian56 : little_endian56, 7); uint64_t read_number56; QuicDataReader reader(buffer56, 7, GetParam().endianness); reader.ReadBytesToUInt64(7, &read_number56); EXPECT_EQ(in_memory56, read_number56); } TEST_P(QuicDataWriterTest, Write64BitUnsignedIntegers) { uint64_t in_memory64 = 0x1122334455667788; unsigned char little_endian64[] = {0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11}; unsigned char big_endian64[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}; char buffer64[8]; QuicDataWriter writer(8, buffer64, GetParam().endianness); writer.WriteBytesToUInt64(8, in_memory64); quiche::test::CompareCharArraysWithHexError( "uint64_t", buffer64, 8, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? AsChars(big_endian64) : AsChars(little_endian64), 8); uint64_t read_number64; QuicDataReader reader(buffer64, 8, GetParam().endianness); reader.ReadBytesToUInt64(8, &read_number64); EXPECT_EQ(in_memory64, read_number64); QuicDataWriter writer2(8, buffer64, GetParam().endianness); writer2.WriteUInt64(in_memory64); quiche::test::CompareCharArraysWithHexError( "uint64_t", buffer64, 8, GetParam().endianness == quiche::NETWORK_BYTE_ORDER ? AsChars(big_endian64) : AsChars(little_endian64), 8); read_number64 = 0u; QuicDataReader reader2(buffer64, 8, GetParam().endianness); reader2.ReadUInt64(&read_number64); EXPECT_EQ(in_memory64, read_number64); } TEST_P(QuicDataWriterTest, WriteIntegers) { char buf[43]; uint8_t i8 = 0x01; uint16_t i16 = 0x0123; uint32_t i32 = 0x01234567; uint64_t i64 = 0x0123456789ABCDEF; QuicDataWriter writer(46, buf, GetParam().endianness); for (size_t i = 0; i < 10; ++i) { switch (i) { case 0u: EXPECT_TRUE(writer.WriteBytesToUInt64(i, i64)); break; case 1u: EXPECT_TRUE(writer.WriteUInt8(i8)); EXPECT_TRUE(writer.WriteBytesToUInt64(i, i64)); break; case 2u: EXPECT_TRUE(writer.WriteUInt16(i16)); EXPECT_TRUE(writer.WriteBytesToUInt64(i, i64)); break; case 3u: EXPECT_TRUE(writer.WriteBytesToUInt64(i, i64)); break; case 4u: EXPECT_TRUE(writer.WriteUInt32(i32)); EXPECT_TRUE(writer.WriteBytesToUInt64(i, i64)); break; case 5u: case 6u: case 7u: case 8u: EXPECT_TRUE(writer.WriteBytesToUInt64(i, i64)); break; default: EXPECT_FALSE(writer.WriteBytesToUInt64(i, i64)); } } QuicDataReader reader(buf, 46, GetParam().endianness); for (size_t i = 0; i < 10; ++i) { uint8_t read8; uint16_t read16; uint32_t read32; uint64_t read64; switch (i) { case 0u: EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(0u, read64); break; case 1u: EXPECT_TRUE(reader.ReadUInt8(&read8)); EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(i8, read8); EXPECT_EQ(0xEFu, read64); break; case 2u: EXPECT_TRUE(reader.ReadUInt16(&read16)); EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(i16, read16); EXPECT_EQ(0xCDEFu, read64); break; case 3u: EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(0xABCDEFu, read64); break; case 4u: EXPECT_TRUE(reader.ReadUInt32(&read32)); EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(i32, read32); EXPECT_EQ(0x89ABCDEFu, read64); break; case 5u: EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(0x6789ABCDEFu, read64); break; case 6u: EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(0x456789ABCDEFu, read64); break; case 7u: EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(0x23456789ABCDEFu, read64); break; case 8u: EXPECT_TRUE(reader.ReadBytesToUInt64(i, &read64)); EXPECT_EQ(0x0123456789ABCDEFu, read64); break; default: EXPECT_FALSE(reader.ReadBytesToUInt64(i, &read64)); } } } TEST_P(QuicDataWriterTest, WriteBytes) { char bytes[] = {0, 1, 2, 3, 4, 5, 6, 7, 8}; char buf[ABSL_ARRAYSIZE(bytes)]; QuicDataWriter writer(ABSL_ARRAYSIZE(buf), buf, GetParam().endianness); EXPECT_TRUE(writer.WriteBytes(bytes, ABSL_ARRAYSIZE(bytes))); for (unsigned int i = 0; i < ABSL_ARRAYSIZE(bytes); ++i) { EXPECT_EQ(bytes[i], buf[i]); } } const int kMultiVarCount = 1000; void EncodeDecodeStreamId(uint64_t value_in) { char buffer[1 * kMultiVarCount]; memset(buffer, 0, sizeof(buffer)); QuicDataWriter writer(sizeof(buffer), static_cast<char*>(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); EXPECT_TRUE(writer.WriteVarInt62(value_in)); QuicDataReader reader(buffer, sizeof(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); QuicStreamId received_stream_id; uint64_t temp; EXPECT_TRUE(reader.ReadVarInt62(&temp)); received_stream_id = static_cast<QuicStreamId>(temp); EXPECT_EQ(value_in, received_stream_id); } TEST_P(QuicDataWriterTest, StreamId1) { EncodeDecodeStreamId(UINT64_C(0x15)); EncodeDecodeStreamId(UINT64_C(0x1567)); EncodeDecodeStreamId(UINT64_C(0x34567890)); EncodeDecodeStreamId(UINT64_C(0xf4567890)); } TEST_P(QuicDataWriterTest, WriteRandomBytes) { char buffer[20]; char expected[20]; for (size_t i = 0; i < 20; ++i) { expected[i] = 'r'; } MockRandom random; QuicDataWriter writer(20, buffer, GetParam().endianness); EXPECT_FALSE(writer.WriteRandomBytes(&random, 30)); EXPECT_TRUE(writer.WriteRandomBytes(&random, 20)); quiche::test::CompareCharArraysWithHexError("random", buffer, 20, expected, 20); } TEST_P(QuicDataWriterTest, WriteInsecureRandomBytes) { char buffer[20]; char expected[20]; for (size_t i = 0; i < 20; ++i) { expected[i] = 'r'; } MockRandom random; QuicDataWriter writer(20, buffer, GetParam().endianness); EXPECT_FALSE(writer.WriteInsecureRandomBytes(&random, 30)); EXPECT_TRUE(writer.WriteInsecureRandomBytes(&random, 20)); quiche::test::CompareCharArraysWithHexError("random", buffer, 20, expected, 20); } TEST_P(QuicDataWriterTest, PeekVarInt62Length) { char buffer[20]; QuicDataWriter writer(20, buffer, quiche::NETWORK_BYTE_ORDER); EXPECT_TRUE(writer.WriteVarInt62(50)); QuicDataReader reader(buffer, 20, quiche::NETWORK_BYTE_ORDER); EXPECT_EQ(1, reader.PeekVarInt62Length()); char buffer2[20]; QuicDataWriter writer2(20, buffer2, quiche::NETWORK_BYTE_ORDER); EXPECT_TRUE(writer2.WriteVarInt62(100)); QuicDataReader reader2(buffer2, 20, quiche::NETWORK_BYTE_ORDER); EXPECT_EQ(2, reader2.PeekVarInt62Length()); char buffer3[20]; QuicDataWriter writer3(20, buffer3, quiche::NETWORK_BYTE_ORDER); EXPECT_TRUE(writer3.WriteVarInt62(20000)); QuicDataReader reader3(buffer3, 20, quiche::NETWORK_BYTE_ORDER); EXPECT_EQ(4, reader3.PeekVarInt62Length()); char buffer4[20]; QuicDataWriter writer4(20, buffer4, quiche::NETWORK_BYTE_ORDER); EXPECT_TRUE(writer4.WriteVarInt62(2000000000)); QuicDataReader reader4(buffer4, 20, quiche::NETWORK_BYTE_ORDER); EXPECT_EQ(8, reader4.PeekVarInt62Length()); } TEST_P(QuicDataWriterTest, ValidStreamCount) { char buffer[1024]; memset(buffer, 0, sizeof(buffer)); QuicDataWriter writer(sizeof(buffer), static_cast<char*>(buffer), quiche::Endianness::NETWORK_BYTE_ORDER); QuicDataReader reader(buffer, sizeof(buffer)); const QuicStreamCount write_stream_count = 0xffeeddcc; EXPECT_TRUE(writer.WriteVarInt62(write_stream_count)); QuicStreamCount read_stream_count; uint64_t temp; EXPECT_TRUE(reader.ReadVarInt62(&temp)); read_stream_count = static_cast<QuicStreamId>(temp); EXPECT_EQ(write_stream_count, read_stream_count); } TEST_P(QuicDataWriterTest, Seek) { char buffer[3] = {}; QuicDataWriter writer(ABSL_ARRAYSIZE(buffer), buffer, GetParam().endianness); EXPECT_TRUE(writer.WriteUInt8(42)); EXPECT_TRUE(writer.Seek(1)); EXPECT_TRUE(writer.WriteUInt8(3)); char expected[] = {42, 0, 3}; for (size_t i = 0; i < ABSL_ARRAYSIZE(expected); ++i) { EXPECT_EQ(buffer[i], expected[i]); } } TEST_P(QuicDataWriterTest, SeekTooFarFails) { char buffer[20]; { QuicDataWriter writer(ABSL_ARRAYSIZE(buffer), buffer, GetParam().endianness); EXPECT_TRUE(writer.Seek(20)); EXPECT_FALSE(writer.Seek(1)); } { QuicDataWriter writer(ABSL_ARRAYSIZE(buffer), buffer, GetParam().endianness); EXPECT_FALSE(writer.Seek(100)); } { QuicDataWriter writer(ABSL_ARRAYSIZE(buffer), buffer, GetParam().endianness); EXPECT_TRUE(writer.Seek(10)); EXPECT_FALSE(writer.Seek(std::numeric_limits<size_t>::max())); } } TEST_P(QuicDataWriterTest, PayloadReads) { char buffer[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; char expected_first_read[4] = {1, 2, 3, 4}; char expected_remaining[12] = {5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; QuicDataReader reader(buffer, sizeof(buffer)); char first_read_buffer[4] = {}; EXPECT_TRUE(reader.ReadBytes(first_read_buffer, sizeof(first_read_buffer))); quiche::test::CompareCharArraysWithHexError( "first read", first_read_buffer, sizeof(first_read_buffer), expected_first_read, sizeof(expected_first_read)); absl::string_view peeked_remaining_payload = reader.PeekRemainingPayload(); quiche::test::CompareCharArraysWithHexError( "peeked_remaining_payload", peeked_remaining_payload.data(), peeked_remaining_payload.length(), expected_remaining, sizeof(expected_remaining)); absl::string_view full_payload = reader.FullPayload(); quiche::test::CompareCharArraysWithHexError( "full_payload", full_payload.data(), full_payload.length(), buffer, sizeof(buffer)); absl::string_view read_remaining_payload = reader.ReadRemainingPayload(); quiche::test::CompareCharArraysWithHexError( "read_remaining_payload", read_remaining_payload.data(), read_remaining_payload.length(), expected_remaining, sizeof(expected_remaining)); EXPECT_TRUE(reader.IsDoneReading()); absl::string_view full_payload2 = reader.FullPayload(); quiche::test::CompareCharArraysWithHexError( "full_payload2", full_payload2.data(), full_payload2.length(), buffer, sizeof(buffer)); } TEST_P(QuicDataWriterTest, StringPieceVarInt62) { char inner_buffer[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; absl::string_view inner_payload_write(inner_buffer, sizeof(inner_buffer)); char buffer[sizeof(inner_buffer) + sizeof(uint8_t)] = {}; QuicDataWriter writer(sizeof(buffer), buffer); EXPECT_TRUE(writer.WriteStringPieceVarInt62(inner_payload_write)); EXPECT_EQ(0u, writer.remaining()); QuicDataReader reader(buffer, sizeof(buffer)); absl::string_view inner_payload_read; EXPECT_TRUE(reader.ReadStringPieceVarInt62(&inner_payload_read)); quiche::test::CompareCharArraysWithHexError( "inner_payload", inner_payload_write.data(), inner_payload_write.length(), inner_payload_read.data(), inner_payload_read.length()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_data_writer.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_data_writer_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
d3449137-bd0a-42dc-b8f7-95502deb4561
cpp
google/quiche
uber_quic_stream_id_manager
quiche/quic/core/uber_quic_stream_id_manager.cc
quiche/quic/core/uber_quic_stream_id_manager_test.cc
#include "quiche/quic/core/uber_quic_stream_id_manager.h" #include <string> #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_utils.h" namespace quic { UberQuicStreamIdManager::UberQuicStreamIdManager( Perspective perspective, ParsedQuicVersion version, QuicStreamIdManager::DelegateInterface* delegate, QuicStreamCount max_open_outgoing_bidirectional_streams, QuicStreamCount max_open_outgoing_unidirectional_streams, QuicStreamCount max_open_incoming_bidirectional_streams, QuicStreamCount max_open_incoming_unidirectional_streams) : version_(version), bidirectional_stream_id_manager_(delegate, false, perspective, version, max_open_outgoing_bidirectional_streams, max_open_incoming_bidirectional_streams), unidirectional_stream_id_manager_( delegate, true, perspective, version, max_open_outgoing_unidirectional_streams, max_open_incoming_unidirectional_streams) {} bool UberQuicStreamIdManager::MaybeAllowNewOutgoingBidirectionalStreams( QuicStreamCount max_open_streams) { return bidirectional_stream_id_manager_.MaybeAllowNewOutgoingStreams( max_open_streams); } bool UberQuicStreamIdManager::MaybeAllowNewOutgoingUnidirectionalStreams( QuicStreamCount max_open_streams) { return unidirectional_stream_id_manager_.MaybeAllowNewOutgoingStreams( max_open_streams); } void UberQuicStreamIdManager::SetMaxOpenIncomingBidirectionalStreams( QuicStreamCount max_open_streams) { bidirectional_stream_id_manager_.SetMaxOpenIncomingStreams(max_open_streams); } void UberQuicStreamIdManager::SetMaxOpenIncomingUnidirectionalStreams( QuicStreamCount max_open_streams) { unidirectional_stream_id_manager_.SetMaxOpenIncomingStreams(max_open_streams); } bool UberQuicStreamIdManager::CanOpenNextOutgoingBidirectionalStream() const { return bidirectional_stream_id_manager_.CanOpenNextOutgoingStream(); } bool UberQuicStreamIdManager::CanOpenNextOutgoingUnidirectionalStream() const { return unidirectional_stream_id_manager_.CanOpenNextOutgoingStream(); } QuicStreamId UberQuicStreamIdManager::GetNextOutgoingBidirectionalStreamId() { return bidirectional_stream_id_manager_.GetNextOutgoingStreamId(); } QuicStreamId UberQuicStreamIdManager::GetNextOutgoingUnidirectionalStreamId() { return unidirectional_stream_id_manager_.GetNextOutgoingStreamId(); } bool UberQuicStreamIdManager::MaybeIncreaseLargestPeerStreamId( QuicStreamId id, std::string* error_details) { if (QuicUtils::IsBidirectionalStreamId(id, version_)) { return bidirectional_stream_id_manager_.MaybeIncreaseLargestPeerStreamId( id, error_details); } return unidirectional_stream_id_manager_.MaybeIncreaseLargestPeerStreamId( id, error_details); } void UberQuicStreamIdManager::OnStreamClosed(QuicStreamId id) { if (QuicUtils::IsBidirectionalStreamId(id, version_)) { bidirectional_stream_id_manager_.OnStreamClosed(id); return; } unidirectional_stream_id_manager_.OnStreamClosed(id); } bool UberQuicStreamIdManager::OnStreamsBlockedFrame( const QuicStreamsBlockedFrame& frame, std::string* error_details) { if (frame.unidirectional) { return unidirectional_stream_id_manager_.OnStreamsBlockedFrame( frame, error_details); } return bidirectional_stream_id_manager_.OnStreamsBlockedFrame(frame, error_details); } bool UberQuicStreamIdManager::IsAvailableStream(QuicStreamId id) const { if (QuicUtils::IsBidirectionalStreamId(id, version_)) { return bidirectional_stream_id_manager_.IsAvailableStream(id); } return unidirectional_stream_id_manager_.IsAvailableStream(id); } void UberQuicStreamIdManager::StopIncreasingIncomingMaxStreams() { unidirectional_stream_id_manager_.StopIncreasingIncomingMaxStreams(); bidirectional_stream_id_manager_.StopIncreasingIncomingMaxStreams(); } void UberQuicStreamIdManager::MaybeSendMaxStreamsFrame() { unidirectional_stream_id_manager_.MaybeSendMaxStreamsFrame(); bidirectional_stream_id_manager_.MaybeSendMaxStreamsFrame(); } QuicStreamCount UberQuicStreamIdManager::GetMaxAllowdIncomingBidirectionalStreams() const { return bidirectional_stream_id_manager_.incoming_initial_max_open_streams(); } QuicStreamCount UberQuicStreamIdManager::GetMaxAllowdIncomingUnidirectionalStreams() const { return unidirectional_stream_id_manager_.incoming_initial_max_open_streams(); } QuicStreamId UberQuicStreamIdManager::GetLargestPeerCreatedStreamId( bool unidirectional) const { if (unidirectional) { return unidirectional_stream_id_manager_.largest_peer_created_stream_id(); } return bidirectional_stream_id_manager_.largest_peer_created_stream_id(); } QuicStreamId UberQuicStreamIdManager::next_outgoing_bidirectional_stream_id() const { return bidirectional_stream_id_manager_.next_outgoing_stream_id(); } QuicStreamId UberQuicStreamIdManager::next_outgoing_unidirectional_stream_id() const { return unidirectional_stream_id_manager_.next_outgoing_stream_id(); } QuicStreamCount UberQuicStreamIdManager::max_outgoing_bidirectional_streams() const { return bidirectional_stream_id_manager_.outgoing_max_streams(); } QuicStreamCount UberQuicStreamIdManager::max_outgoing_unidirectional_streams() const { return unidirectional_stream_id_manager_.outgoing_max_streams(); } QuicStreamCount UberQuicStreamIdManager::max_incoming_bidirectional_streams() const { return bidirectional_stream_id_manager_.incoming_actual_max_streams(); } QuicStreamCount UberQuicStreamIdManager::max_incoming_unidirectional_streams() const { return unidirectional_stream_id_manager_.incoming_actual_max_streams(); } QuicStreamCount UberQuicStreamIdManager::advertised_max_incoming_bidirectional_streams() const { return bidirectional_stream_id_manager_.incoming_advertised_max_streams(); } QuicStreamCount UberQuicStreamIdManager::advertised_max_incoming_unidirectional_streams() const { return unidirectional_stream_id_manager_.incoming_advertised_max_streams(); } QuicStreamCount UberQuicStreamIdManager::outgoing_bidirectional_stream_count() const { return bidirectional_stream_id_manager_.outgoing_stream_count(); } QuicStreamCount UberQuicStreamIdManager::outgoing_unidirectional_stream_count() const { return unidirectional_stream_id_manager_.outgoing_stream_count(); } }
#include "quiche/quic/core/uber_quic_stream_id_manager.h" #include <string> #include <vector> #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_stream_id_manager_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" using testing::_; using testing::StrictMock; namespace quic { namespace test { namespace { struct TestParams { explicit 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 (const ParsedQuicVersion& version : AllSupportedVersions()) { if (!version.HasIetfQuicFrames()) { continue; } params.push_back(TestParams(version, Perspective::IS_CLIENT)); params.push_back(TestParams(version, Perspective::IS_SERVER)); } return params; } class MockDelegate : public QuicStreamIdManager::DelegateInterface { public: MOCK_METHOD(bool, CanSendMaxStreams, (), (override)); MOCK_METHOD(void, SendMaxStreams, (QuicStreamCount stream_count, bool unidirectional), (override)); }; class UberQuicStreamIdManagerTest : public QuicTestWithParam<TestParams> { protected: UberQuicStreamIdManagerTest() : manager_(perspective(), version(), &delegate_, 0, 0, kDefaultMaxStreamsPerConnection, kDefaultMaxStreamsPerConnection) {} QuicStreamId GetNthClientInitiatedBidirectionalId(int n) { return QuicUtils::GetFirstBidirectionalStreamId(transport_version(), Perspective::IS_CLIENT) + QuicUtils::StreamIdDelta(transport_version()) * n; } QuicStreamId GetNthClientInitiatedUnidirectionalId(int n) { return QuicUtils::GetFirstUnidirectionalStreamId(transport_version(), Perspective::IS_CLIENT) + QuicUtils::StreamIdDelta(transport_version()) * n; } QuicStreamId GetNthServerInitiatedBidirectionalId(int n) { return QuicUtils::GetFirstBidirectionalStreamId(transport_version(), Perspective::IS_SERVER) + QuicUtils::StreamIdDelta(transport_version()) * n; } QuicStreamId GetNthServerInitiatedUnidirectionalId(int n) { return QuicUtils::GetFirstUnidirectionalStreamId(transport_version(), Perspective::IS_SERVER) + QuicUtils::StreamIdDelta(transport_version()) * n; } QuicStreamId GetNthPeerInitiatedBidirectionalStreamId(int n) { return ((perspective() == Perspective::IS_SERVER) ? GetNthClientInitiatedBidirectionalId(n) : GetNthServerInitiatedBidirectionalId(n)); } QuicStreamId GetNthPeerInitiatedUnidirectionalStreamId(int n) { return ((perspective() == Perspective::IS_SERVER) ? GetNthClientInitiatedUnidirectionalId(n) : GetNthServerInitiatedUnidirectionalId(n)); } QuicStreamId GetNthSelfInitiatedBidirectionalStreamId(int n) { return ((perspective() == Perspective::IS_CLIENT) ? GetNthClientInitiatedBidirectionalId(n) : GetNthServerInitiatedBidirectionalId(n)); } QuicStreamId GetNthSelfInitiatedUnidirectionalStreamId(int n) { return ((perspective() == Perspective::IS_CLIENT) ? GetNthClientInitiatedUnidirectionalId(n) : GetNthServerInitiatedUnidirectionalId(n)); } QuicStreamId StreamCountToId(QuicStreamCount stream_count, Perspective perspective, bool bidirectional) { return ((bidirectional) ? QuicUtils::GetFirstBidirectionalStreamId( transport_version(), perspective) : QuicUtils::GetFirstUnidirectionalStreamId( transport_version(), perspective)) + ((stream_count - 1) * QuicUtils::StreamIdDelta(transport_version())); } ParsedQuicVersion version() { return GetParam().version; } QuicTransportVersion transport_version() { return version().transport_version; } Perspective perspective() { return GetParam().perspective; } testing::StrictMock<MockDelegate> delegate_; UberQuicStreamIdManager manager_; }; INSTANTIATE_TEST_SUITE_P(Tests, UberQuicStreamIdManagerTest, ::testing::ValuesIn(GetTestParams()), ::testing::PrintToStringParamName()); TEST_P(UberQuicStreamIdManagerTest, Initialization) { EXPECT_EQ(GetNthSelfInitiatedBidirectionalStreamId(0), manager_.next_outgoing_bidirectional_stream_id()); EXPECT_EQ(GetNthSelfInitiatedUnidirectionalStreamId(0), manager_.next_outgoing_unidirectional_stream_id()); } TEST_P(UberQuicStreamIdManagerTest, SetMaxOpenOutgoingStreams) { const size_t kNumMaxOutgoingStream = 123; EXPECT_TRUE(manager_.MaybeAllowNewOutgoingBidirectionalStreams( kNumMaxOutgoingStream)); EXPECT_TRUE(manager_.MaybeAllowNewOutgoingUnidirectionalStreams( kNumMaxOutgoingStream + 1)); EXPECT_EQ(kNumMaxOutgoingStream, manager_.max_outgoing_bidirectional_streams()); EXPECT_EQ(kNumMaxOutgoingStream + 1, manager_.max_outgoing_unidirectional_streams()); int i = kNumMaxOutgoingStream; while (i) { EXPECT_TRUE(manager_.CanOpenNextOutgoingBidirectionalStream()); manager_.GetNextOutgoingBidirectionalStreamId(); EXPECT_TRUE(manager_.CanOpenNextOutgoingUnidirectionalStream()); manager_.GetNextOutgoingUnidirectionalStreamId(); i--; } EXPECT_TRUE(manager_.CanOpenNextOutgoingUnidirectionalStream()); manager_.GetNextOutgoingUnidirectionalStreamId(); EXPECT_FALSE(manager_.CanOpenNextOutgoingUnidirectionalStream()); EXPECT_FALSE(manager_.CanOpenNextOutgoingBidirectionalStream()); } TEST_P(UberQuicStreamIdManagerTest, SetMaxOpenIncomingStreams) { const size_t kNumMaxIncomingStreams = 456; manager_.SetMaxOpenIncomingUnidirectionalStreams(kNumMaxIncomingStreams); manager_.SetMaxOpenIncomingBidirectionalStreams(kNumMaxIncomingStreams + 1); EXPECT_EQ(kNumMaxIncomingStreams + 1, manager_.GetMaxAllowdIncomingBidirectionalStreams()); EXPECT_EQ(kNumMaxIncomingStreams, manager_.GetMaxAllowdIncomingUnidirectionalStreams()); EXPECT_EQ(manager_.max_incoming_bidirectional_streams(), manager_.advertised_max_incoming_bidirectional_streams()); EXPECT_EQ(manager_.max_incoming_unidirectional_streams(), manager_.advertised_max_incoming_unidirectional_streams()); size_t i; for (i = 0; i < kNumMaxIncomingStreams; i++) { EXPECT_TRUE(manager_.MaybeIncreaseLargestPeerStreamId( GetNthPeerInitiatedUnidirectionalStreamId(i), nullptr)); EXPECT_TRUE(manager_.MaybeIncreaseLargestPeerStreamId( GetNthPeerInitiatedBidirectionalStreamId(i), nullptr)); } EXPECT_TRUE(manager_.MaybeIncreaseLargestPeerStreamId( GetNthPeerInitiatedBidirectionalStreamId(i), nullptr)); std::string error_details; EXPECT_FALSE(manager_.MaybeIncreaseLargestPeerStreamId( GetNthPeerInitiatedUnidirectionalStreamId(i), &error_details)); EXPECT_EQ(error_details, absl::StrCat( "Stream id ", GetNthPeerInitiatedUnidirectionalStreamId(i), " would exceed stream count limit ", kNumMaxIncomingStreams)); EXPECT_FALSE(manager_.MaybeIncreaseLargestPeerStreamId( GetNthPeerInitiatedBidirectionalStreamId(i + 1), &error_details)); EXPECT_EQ(error_details, absl::StrCat("Stream id ", GetNthPeerInitiatedBidirectionalStreamId(i + 1), " would exceed stream count limit ", kNumMaxIncomingStreams + 1)); } TEST_P(UberQuicStreamIdManagerTest, GetNextOutgoingStreamId) { EXPECT_TRUE(manager_.MaybeAllowNewOutgoingBidirectionalStreams(10)); EXPECT_TRUE(manager_.MaybeAllowNewOutgoingUnidirectionalStreams(10)); EXPECT_EQ(GetNthSelfInitiatedBidirectionalStreamId(0), manager_.GetNextOutgoingBidirectionalStreamId()); EXPECT_EQ(GetNthSelfInitiatedBidirectionalStreamId(1), manager_.GetNextOutgoingBidirectionalStreamId()); EXPECT_EQ(GetNthSelfInitiatedUnidirectionalStreamId(0), manager_.GetNextOutgoingUnidirectionalStreamId()); EXPECT_EQ(GetNthSelfInitiatedUnidirectionalStreamId(1), manager_.GetNextOutgoingUnidirectionalStreamId()); } TEST_P(UberQuicStreamIdManagerTest, AvailableStreams) { EXPECT_TRUE(manager_.MaybeIncreaseLargestPeerStreamId( GetNthPeerInitiatedBidirectionalStreamId(3), nullptr)); EXPECT_TRUE( manager_.IsAvailableStream(GetNthPeerInitiatedBidirectionalStreamId(1))); EXPECT_TRUE( manager_.IsAvailableStream(GetNthPeerInitiatedBidirectionalStreamId(2))); EXPECT_TRUE(manager_.MaybeIncreaseLargestPeerStreamId( GetNthPeerInitiatedUnidirectionalStreamId(3), nullptr)); EXPECT_TRUE( manager_.IsAvailableStream(GetNthPeerInitiatedUnidirectionalStreamId(1))); EXPECT_TRUE( manager_.IsAvailableStream(GetNthPeerInitiatedUnidirectionalStreamId(2))); } TEST_P(UberQuicStreamIdManagerTest, MaybeIncreaseLargestPeerStreamId) { EXPECT_TRUE(manager_.MaybeIncreaseLargestPeerStreamId( StreamCountToId(manager_.max_incoming_bidirectional_streams(), QuicUtils::InvertPerspective(perspective()), true), nullptr)); EXPECT_TRUE(manager_.MaybeIncreaseLargestPeerStreamId( StreamCountToId(manager_.max_incoming_bidirectional_streams(), QuicUtils::InvertPerspective(perspective()), false), nullptr)); std::string expected_error_details = perspective() == Perspective::IS_SERVER ? "Stream id 400 would exceed stream count limit 100" : "Stream id 401 would exceed stream count limit 100"; std::string error_details; EXPECT_FALSE(manager_.MaybeIncreaseLargestPeerStreamId( StreamCountToId(manager_.max_incoming_bidirectional_streams() + 1, QuicUtils::InvertPerspective(perspective()), true), &error_details)); EXPECT_EQ(expected_error_details, error_details); expected_error_details = perspective() == Perspective::IS_SERVER ? "Stream id 402 would exceed stream count limit 100" : "Stream id 403 would exceed stream count limit 100"; EXPECT_FALSE(manager_.MaybeIncreaseLargestPeerStreamId( StreamCountToId(manager_.max_incoming_bidirectional_streams() + 1, QuicUtils::InvertPerspective(perspective()), false), &error_details)); EXPECT_EQ(expected_error_details, error_details); } TEST_P(UberQuicStreamIdManagerTest, OnStreamsBlockedFrame) { QuicStreamCount stream_count = manager_.advertised_max_incoming_bidirectional_streams() - 1; QuicStreamsBlockedFrame frame(kInvalidControlFrameId, stream_count, false); EXPECT_CALL(delegate_, SendMaxStreams(manager_.max_incoming_bidirectional_streams(), frame.unidirectional)) .Times(0); EXPECT_TRUE(manager_.OnStreamsBlockedFrame(frame, nullptr)); stream_count = manager_.advertised_max_incoming_unidirectional_streams() - 1; frame.stream_count = stream_count; frame.unidirectional = true; EXPECT_CALL(delegate_, SendMaxStreams(manager_.max_incoming_unidirectional_streams(), frame.unidirectional)) .Times(0); EXPECT_TRUE(manager_.OnStreamsBlockedFrame(frame, nullptr)); } TEST_P(UberQuicStreamIdManagerTest, SetMaxOpenOutgoingStreamsPlusFrame) { const size_t kNumMaxOutgoingStream = 123; EXPECT_TRUE(manager_.MaybeAllowNewOutgoingBidirectionalStreams( kNumMaxOutgoingStream)); EXPECT_TRUE(manager_.MaybeAllowNewOutgoingUnidirectionalStreams( kNumMaxOutgoingStream + 1)); EXPECT_EQ(kNumMaxOutgoingStream, manager_.max_outgoing_bidirectional_streams()); EXPECT_EQ(kNumMaxOutgoingStream + 1, manager_.max_outgoing_unidirectional_streams()); int i = kNumMaxOutgoingStream; while (i) { EXPECT_TRUE(manager_.CanOpenNextOutgoingBidirectionalStream()); manager_.GetNextOutgoingBidirectionalStreamId(); EXPECT_TRUE(manager_.CanOpenNextOutgoingUnidirectionalStream()); manager_.GetNextOutgoingUnidirectionalStreamId(); i--; } EXPECT_TRUE(manager_.CanOpenNextOutgoingUnidirectionalStream()); manager_.GetNextOutgoingUnidirectionalStreamId(); EXPECT_FALSE(manager_.CanOpenNextOutgoingUnidirectionalStream()); EXPECT_FALSE(manager_.CanOpenNextOutgoingBidirectionalStream()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/uber_quic_stream_id_manager.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/uber_quic_stream_id_manager_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
90cb4a88-68ac-45e0-b6bf-8f90d5dc4cb1
cpp
google/quiche
quic_crypto_client_stream
quiche/quic/core/quic_crypto_client_stream.cc
quiche/quic/core/quic_crypto_client_stream_test.cc
#include "quiche/quic/core/quic_crypto_client_stream.h" #include <memory> #include <string> #include <utility> #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/crypto/crypto_utils.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/crypto/quic_crypto_client_config.h" #include "quiche/quic/core/quic_crypto_client_handshaker.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/tls_client_handshaker.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_logging.h" namespace quic { const int QuicCryptoClientStream::kMaxClientHellos; QuicCryptoClientStreamBase::QuicCryptoClientStreamBase(QuicSession* session) : QuicCryptoStream(session) {} QuicCryptoClientStream::QuicCryptoClientStream( const QuicServerId& server_id, QuicSession* session, std::unique_ptr<ProofVerifyContext> verify_context, QuicCryptoClientConfig* crypto_config, ProofHandler* proof_handler, bool has_application_state) : QuicCryptoClientStreamBase(session) { QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, session->connection()->perspective()); switch (session->connection()->version().handshake_protocol) { case PROTOCOL_QUIC_CRYPTO: handshaker_ = std::make_unique<QuicCryptoClientHandshaker>( server_id, this, session, std::move(verify_context), crypto_config, proof_handler); break; case PROTOCOL_TLS1_3: { auto handshaker = std::make_unique<TlsClientHandshaker>( server_id, this, session, std::move(verify_context), crypto_config, proof_handler, has_application_state); tls_handshaker_ = handshaker.get(); handshaker_ = std::move(handshaker); break; } case PROTOCOL_UNSUPPORTED: QUIC_BUG(quic_bug_10296_1) << "Attempting to create QuicCryptoClientStream for unknown " "handshake protocol"; } } QuicCryptoClientStream::~QuicCryptoClientStream() {} bool QuicCryptoClientStream::CryptoConnect() { return handshaker_->CryptoConnect(); } int QuicCryptoClientStream::num_sent_client_hellos() const { return handshaker_->num_sent_client_hellos(); } bool QuicCryptoClientStream::ResumptionAttempted() const { return handshaker_->ResumptionAttempted(); } bool QuicCryptoClientStream::IsResumption() const { return handshaker_->IsResumption(); } bool QuicCryptoClientStream::EarlyDataAccepted() const { return handshaker_->EarlyDataAccepted(); } ssl_early_data_reason_t QuicCryptoClientStream::EarlyDataReason() const { return handshaker_->EarlyDataReason(); } bool QuicCryptoClientStream::ReceivedInchoateReject() const { return handshaker_->ReceivedInchoateReject(); } int QuicCryptoClientStream::num_scup_messages_received() const { return handshaker_->num_scup_messages_received(); } bool QuicCryptoClientStream::encryption_established() const { return handshaker_->encryption_established(); } bool QuicCryptoClientStream::one_rtt_keys_available() const { return handshaker_->one_rtt_keys_available(); } const QuicCryptoNegotiatedParameters& QuicCryptoClientStream::crypto_negotiated_params() const { return handshaker_->crypto_negotiated_params(); } CryptoMessageParser* QuicCryptoClientStream::crypto_message_parser() { return handshaker_->crypto_message_parser(); } HandshakeState QuicCryptoClientStream::GetHandshakeState() const { return handshaker_->GetHandshakeState(); } size_t QuicCryptoClientStream::BufferSizeLimitForLevel( EncryptionLevel level) const { return handshaker_->BufferSizeLimitForLevel(level); } std::unique_ptr<QuicDecrypter> QuicCryptoClientStream::AdvanceKeysAndCreateCurrentOneRttDecrypter() { return handshaker_->AdvanceKeysAndCreateCurrentOneRttDecrypter(); } std::unique_ptr<QuicEncrypter> QuicCryptoClientStream::CreateCurrentOneRttEncrypter() { return handshaker_->CreateCurrentOneRttEncrypter(); } bool QuicCryptoClientStream::ExportKeyingMaterial(absl::string_view label, absl::string_view context, size_t result_len, std::string* result) { return handshaker_->ExportKeyingMaterial(label, context, result_len, result); } std::string QuicCryptoClientStream::chlo_hash() const { return handshaker_->chlo_hash(); } void QuicCryptoClientStream::OnOneRttPacketAcknowledged() { handshaker_->OnOneRttPacketAcknowledged(); } void QuicCryptoClientStream::OnHandshakePacketSent() { handshaker_->OnHandshakePacketSent(); } void QuicCryptoClientStream::OnConnectionClosed( const QuicConnectionCloseFrame& frame, ConnectionCloseSource source) { handshaker_->OnConnectionClosed(frame.quic_error_code, source); } void QuicCryptoClientStream::OnHandshakeDoneReceived() { handshaker_->OnHandshakeDoneReceived(); } void QuicCryptoClientStream::OnNewTokenReceived(absl::string_view token) { handshaker_->OnNewTokenReceived(token); } void QuicCryptoClientStream::SetServerApplicationStateForResumption( std::unique_ptr<ApplicationState> application_state) { handshaker_->SetServerApplicationStateForResumption( std::move(application_state)); } SSL* QuicCryptoClientStream::GetSsl() const { return tls_handshaker_ == nullptr ? nullptr : tls_handshaker_->ssl(); } bool QuicCryptoClientStream::IsCryptoFrameExpectedForEncryptionLevel( EncryptionLevel level) const { return handshaker_->IsCryptoFrameExpectedForEncryptionLevel(level); } EncryptionLevel QuicCryptoClientStream::GetEncryptionLevelToSendCryptoDataOfSpace( PacketNumberSpace space) const { return handshaker_->GetEncryptionLevelToSendCryptoDataOfSpace(space); } }
#include "quiche/quic/core/quic_crypto_client_stream.h" #include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "quiche/quic/core/crypto/aes_128_gcm_12_encrypter.h" #include "quiche/quic/core/crypto/quic_decrypter.h" #include "quiche/quic/core/crypto/quic_encrypter.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_server_id.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/crypto_test_utils.h" #include "quiche/quic/test_tools/quic_stream_peer.h" #include "quiche/quic/test_tools/quic_stream_sequencer_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simple_quic_framer.h" #include "quiche/quic/test_tools/simple_session_cache.h" #include "quiche/common/test_tools/quiche_test_utils.h" using testing::_; namespace quic { namespace test { namespace { const char kServerHostname[] = "test.example.com"; const uint16_t kServerPort = 443; class QuicCryptoClientStreamTest : public QuicTest { public: QuicCryptoClientStreamTest() : supported_versions_(AllSupportedVersionsWithQuicCrypto()), server_id_(kServerHostname, kServerPort), crypto_config_(crypto_test_utils::ProofVerifierForTesting(), 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_); 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() { int proof_verify_details_calls = 1; if (stream()->handshake_protocol() != PROTOCOL_TLS1_3) { EXPECT_CALL(*session_, OnProofValid(testing::_)) .Times(testing::AtLeast(1)); proof_verify_details_calls = 0; } EXPECT_CALL(*session_, OnProofVerifyDetailsAvailable(testing::_)) .Times(testing::AtLeast(proof_verify_details_calls)); stream()->CryptoConnect(); QuicConfig config; crypto_test_utils::HandshakeWithFakeServer( &config, server_crypto_config_.get(), &server_helper_, &alarm_factory_, connection_, stream(), AlpnForVersion(connection_->version())); } QuicCryptoClientStream* stream() { return session_->GetMutableCryptoStream(); } MockQuicConnectionHelper server_helper_; MockQuicConnectionHelper client_helper_; MockAlarmFactory alarm_factory_; PacketSavingConnection* connection_; ParsedQuicVersionVector supported_versions_; std::unique_ptr<TestQuicSpdyClientSession> session_; QuicServerId server_id_; CryptoHandshakeMessage message_; QuicCryptoClientConfig crypto_config_; std::unique_ptr<QuicCryptoServerConfig> server_crypto_config_; }; TEST_F(QuicCryptoClientStreamTest, NotInitiallyConected) { EXPECT_FALSE(stream()->encryption_established()); EXPECT_FALSE(stream()->one_rtt_keys_available()); } TEST_F(QuicCryptoClientStreamTest, ConnectedAfterSHLO) { CompleteCryptoHandshake(); EXPECT_TRUE(stream()->encryption_established()); EXPECT_TRUE(stream()->one_rtt_keys_available()); EXPECT_FALSE(stream()->IsResumption()); EXPECT_EQ(stream()->EarlyDataReason(), ssl_early_data_no_session_offered); } TEST_F(QuicCryptoClientStreamTest, MessageAfterHandshake) { CompleteCryptoHandshake(); EXPECT_CALL( *connection_, CloseConnection(QUIC_CRYPTO_MESSAGE_AFTER_HANDSHAKE_COMPLETE, _, _)); message_.set_tag(kCHLO); crypto_test_utils::SendHandshakeMessageToStream(stream(), message_, Perspective::IS_CLIENT); } TEST_F(QuicCryptoClientStreamTest, BadMessageType) { stream()->CryptoConnect(); message_.set_tag(kCHLO); EXPECT_CALL(*connection_, CloseConnection(QUIC_INVALID_CRYPTO_MESSAGE_TYPE, "Expected REJ", _)); crypto_test_utils::SendHandshakeMessageToStream(stream(), message_, Perspective::IS_CLIENT); } TEST_F(QuicCryptoClientStreamTest, NegotiatedParameters) { CompleteCryptoHandshake(); const QuicConfig* config = session_->config(); EXPECT_EQ(kMaximumIdleTimeoutSecs, config->IdleNetworkTimeout().ToSeconds()); const QuicCryptoNegotiatedParameters& crypto_params( stream()->crypto_negotiated_params()); EXPECT_EQ(crypto_config_.aead[0], crypto_params.aead); EXPECT_EQ(crypto_config_.kexs[0], crypto_params.key_exchange); } TEST_F(QuicCryptoClientStreamTest, ExpiredServerConfig) { CompleteCryptoHandshake(); CreateConnection(); connection_->AdvanceTime( QuicTime::Delta::FromSeconds(60 * 60 * 24 * 365 * 5)); EXPECT_CALL(*session_, OnProofValid(testing::_)); stream()->CryptoConnect(); ASSERT_EQ(1u, connection_->encrypted_packets_.size()); EXPECT_EQ(ENCRYPTION_INITIAL, connection_->encryption_level()); } TEST_F(QuicCryptoClientStreamTest, ClientTurnedOffZeroRtt) { CompleteCryptoHandshake(); CreateConnection(); QuicTagVector options; options.push_back(kQNZ2); session_->config()->SetClientConnectionOptions(options); CompleteCryptoHandshake(); EXPECT_EQ(2, stream()->num_sent_client_hellos()); EXPECT_FALSE(stream()->EarlyDataAccepted()); EXPECT_EQ(stream()->EarlyDataReason(), ssl_early_data_disabled); } TEST_F(QuicCryptoClientStreamTest, ClockSkew) { connection_->AdvanceTime( QuicTime::Delta::FromSeconds(60 * 60 * 24 * 365 * 5)); CompleteCryptoHandshake(); } TEST_F(QuicCryptoClientStreamTest, InvalidCachedServerConfig) { CompleteCryptoHandshake(); CreateConnection(); QuicCryptoClientConfig::CachedState* state = crypto_config_.LookupOrCreate(server_id_); std::vector<std::string> certs = state->certs(); std::string cert_sct = state->cert_sct(); std::string signature = state->signature(); std::string chlo_hash = state->chlo_hash(); state->SetProof(certs, cert_sct, chlo_hash, signature + signature); EXPECT_CALL(*session_, OnProofVerifyDetailsAvailable(testing::_)) .Times(testing::AnyNumber()); stream()->CryptoConnect(); ASSERT_EQ(1u, connection_->encrypted_packets_.size()); } TEST_F(QuicCryptoClientStreamTest, ServerConfigUpdate) { CompleteCryptoHandshake(); QuicCryptoClientConfig::CachedState* state = crypto_config_.LookupOrCreate(server_id_); EXPECT_NE("xstk", state->source_address_token()); unsigned char stk[] = {'x', 's', 't', 'k'}; unsigned char scfg[] = { 0x53, 0x43, 0x46, 0x47, 0x01, 0x00, 0x00, 0x00, 0x45, 0x58, 0x50, 0x59, 0x08, 0x00, 0x00, 0x00, '1', '2', '3', '4', '5', '6', '7', '8'}; CryptoHandshakeMessage server_config_update; server_config_update.set_tag(kSCUP); server_config_update.SetValue(kSourceAddressTokenTag, stk); server_config_update.SetValue(kSCFG, scfg); const uint64_t expiry_seconds = 60 * 60 * 24 * 2; server_config_update.SetValue(kSTTL, expiry_seconds); crypto_test_utils::SendHandshakeMessageToStream( stream(), server_config_update, Perspective::IS_SERVER); EXPECT_EQ("xstk", state->source_address_token()); const std::string& cached_scfg = state->server_config(); quiche::test::CompareCharArraysWithHexError( "scfg", cached_scfg.data(), cached_scfg.length(), reinterpret_cast<char*>(scfg), ABSL_ARRAYSIZE(scfg)); QuicStreamSequencer* sequencer = QuicStreamPeer::sequencer(stream()); EXPECT_FALSE(QuicStreamSequencerPeer::IsUnderlyingBufferAllocated(sequencer)); } TEST_F(QuicCryptoClientStreamTest, ServerConfigUpdateWithCert) { CompleteCryptoHandshake(); QuicCryptoServerConfig crypto_config( QuicCryptoServerConfig::TESTING, QuicRandom::GetInstance(), crypto_test_utils::ProofSourceForTesting(), KeyExchangeSource::Default()); crypto_test_utils::SetupCryptoServerConfigForTest( connection_->clock(), QuicRandom::GetInstance(), &crypto_config); SourceAddressTokens tokens; QuicCompressedCertsCache cache(1); CachedNetworkParameters network_params; CryptoHandshakeMessage server_config_update; class Callback : public BuildServerConfigUpdateMessageResultCallback { public: Callback(bool* ok, CryptoHandshakeMessage* message) : ok_(ok), message_(message) {} void Run(bool ok, const CryptoHandshakeMessage& message) override { *ok_ = ok; *message_ = message; } private: bool* ok_; CryptoHandshakeMessage* message_; }; bool ok = false; crypto_config.BuildServerConfigUpdateMessage( session_->transport_version(), stream()->chlo_hash(), tokens, QuicSocketAddress(QuicIpAddress::Loopback6(), 1234), QuicSocketAddress(QuicIpAddress::Loopback6(), 4321), connection_->clock(), QuicRandom::GetInstance(), &cache, stream()->crypto_negotiated_params(), &network_params, std::unique_ptr<BuildServerConfigUpdateMessageResultCallback>( new Callback(&ok, &server_config_update))); EXPECT_TRUE(ok); EXPECT_CALL(*session_, OnProofValid(testing::_)); crypto_test_utils::SendHandshakeMessageToStream( stream(), server_config_update, Perspective::IS_SERVER); CreateConnection(); EXPECT_CALL(*session_, OnProofValid(testing::_)); EXPECT_CALL(*session_, OnProofVerifyDetailsAvailable(testing::_)) .Times(testing::AnyNumber()); stream()->CryptoConnect(); EXPECT_TRUE(session_->IsEncryptionEstablished()); } TEST_F(QuicCryptoClientStreamTest, ServerConfigUpdateBeforeHandshake) { EXPECT_CALL( *connection_, CloseConnection(QUIC_CRYPTO_UPDATE_BEFORE_HANDSHAKE_COMPLETE, _, _)); CryptoHandshakeMessage server_config_update; server_config_update.set_tag(kSCUP); crypto_test_utils::SendHandshakeMessageToStream( stream(), server_config_update, Perspective::IS_SERVER); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_crypto_client_stream.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_crypto_client_stream_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
b31f75b4-d54b-467f-9dff-33d3a865e33d
cpp
google/quiche
quic_tag
quiche/quic/core/quic_tag.cc
quiche/quic/core/quic_tag_test.cc
#include "quiche/quic/core/quic_tag.h" #include <algorithm> #include <string> #include <vector> #include "absl/base/macros.h" #include "absl/strings/ascii.h" #include "absl/strings/escaping.h" #include "absl/strings/str_split.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 { bool FindMutualQuicTag(const QuicTagVector& our_tags, const QuicTagVector& their_tags, QuicTag* out_result, size_t* out_index) { const size_t num_our_tags = our_tags.size(); const size_t num_their_tags = their_tags.size(); for (size_t i = 0; i < num_our_tags; i++) { for (size_t j = 0; j < num_their_tags; j++) { if (our_tags[i] == their_tags[j]) { *out_result = our_tags[i]; if (out_index != nullptr) { *out_index = j; } return true; } } } return false; } std::string QuicTagToString(QuicTag tag) { if (tag == 0) { return "0"; } char chars[sizeof tag]; bool ascii = true; const QuicTag orig_tag = tag; for (size_t i = 0; i < ABSL_ARRAYSIZE(chars); i++) { chars[i] = static_cast<char>(tag); if ((chars[i] == 0 || chars[i] == '\xff') && i == ABSL_ARRAYSIZE(chars) - 1) { chars[i] = ' '; } if (!absl::ascii_isprint(static_cast<unsigned char>(chars[i]))) { ascii = false; break; } tag >>= 8; } if (ascii) { return std::string(chars, sizeof(chars)); } return absl::BytesToHexString(absl::string_view( reinterpret_cast<const char*>(&orig_tag), sizeof(orig_tag))); } uint32_t MakeQuicTag(uint8_t a, uint8_t b, uint8_t c, uint8_t d) { return static_cast<uint32_t>(a) | static_cast<uint32_t>(b) << 8 | static_cast<uint32_t>(c) << 16 | static_cast<uint32_t>(d) << 24; } bool ContainsQuicTag(const QuicTagVector& tag_vector, QuicTag tag) { return std::find(tag_vector.begin(), tag_vector.end(), tag) != tag_vector.end(); } QuicTag ParseQuicTag(absl::string_view tag_string) { quiche::QuicheTextUtils::RemoveLeadingAndTrailingWhitespace(&tag_string); std::string tag_bytes; if (tag_string.length() == 8) { tag_bytes = absl::HexStringToBytes(tag_string); tag_string = tag_bytes; } QuicTag tag = 0; for (auto it = tag_string.rbegin(); it != tag_string.rend(); ++it) { unsigned char token_char = static_cast<unsigned char>(*it); tag <<= 8; tag |= token_char; } return tag; } QuicTagVector ParseQuicTagVector(absl::string_view tags_string) { QuicTagVector tag_vector; quiche::QuicheTextUtils::RemoveLeadingAndTrailingWhitespace(&tags_string); if (!tags_string.empty()) { std::vector<absl::string_view> tag_strings = absl::StrSplit(tags_string, ','); for (absl::string_view tag_string : tag_strings) { tag_vector.push_back(ParseQuicTag(tag_string)); } } return tag_vector; } }
#include "quiche/quic/core/quic_tag.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace test { namespace { class QuicTagTest : public QuicTest {}; TEST_F(QuicTagTest, TagToString) { EXPECT_EQ("SCFG", QuicTagToString(kSCFG)); EXPECT_EQ("SNO ", QuicTagToString(kServerNonceTag)); EXPECT_EQ("CRT ", QuicTagToString(kCertificateTag)); EXPECT_EQ("CHLO", QuicTagToString(MakeQuicTag('C', 'H', 'L', 'O'))); EXPECT_EQ("43484c1f", QuicTagToString(MakeQuicTag('C', 'H', 'L', '\x1f'))); } TEST_F(QuicTagTest, MakeQuicTag) { QuicTag tag = MakeQuicTag('A', 'B', 'C', 'D'); char bytes[4]; memcpy(bytes, &tag, 4); EXPECT_EQ('A', bytes[0]); EXPECT_EQ('B', bytes[1]); EXPECT_EQ('C', bytes[2]); EXPECT_EQ('D', bytes[3]); } TEST_F(QuicTagTest, ParseQuicTag) { QuicTag tag_abcd = MakeQuicTag('A', 'B', 'C', 'D'); EXPECT_EQ(ParseQuicTag("ABCD"), tag_abcd); EXPECT_EQ(ParseQuicTag("ABCDE"), tag_abcd); QuicTag tag_efgh = MakeQuicTag('E', 'F', 'G', 'H'); EXPECT_EQ(ParseQuicTag("EFGH"), tag_efgh); QuicTag tag_ijk = MakeQuicTag('I', 'J', 'K', 0); EXPECT_EQ(ParseQuicTag("IJK"), tag_ijk); QuicTag tag_l = MakeQuicTag('L', 0, 0, 0); EXPECT_EQ(ParseQuicTag("L"), tag_l); QuicTag tag_hex = MakeQuicTag('M', 'N', 'O', static_cast<char>(255)); EXPECT_EQ(ParseQuicTag("4d4e4fff"), tag_hex); EXPECT_EQ(ParseQuicTag("4D4E4FFF"), tag_hex); QuicTag tag_with_numbers = MakeQuicTag('P', 'Q', '1', '2'); EXPECT_EQ(ParseQuicTag("PQ12"), tag_with_numbers); QuicTag tag_with_custom_chars = MakeQuicTag('r', '$', '_', '7'); EXPECT_EQ(ParseQuicTag("r$_7"), tag_with_custom_chars); QuicTag tag_zero = 0; EXPECT_EQ(ParseQuicTag(""), tag_zero); QuicTagVector tag_vector; EXPECT_EQ(ParseQuicTagVector(""), tag_vector); EXPECT_EQ(ParseQuicTagVector(" "), tag_vector); tag_vector.push_back(tag_abcd); EXPECT_EQ(ParseQuicTagVector("ABCD"), tag_vector); tag_vector.push_back(tag_efgh); EXPECT_EQ(ParseQuicTagVector("ABCD,EFGH"), tag_vector); tag_vector.push_back(tag_ijk); EXPECT_EQ(ParseQuicTagVector("ABCD,EFGH,IJK"), tag_vector); tag_vector.push_back(tag_l); EXPECT_EQ(ParseQuicTagVector("ABCD,EFGH,IJK,L"), tag_vector); tag_vector.push_back(tag_hex); EXPECT_EQ(ParseQuicTagVector("ABCD,EFGH,IJK,L,4d4e4fff"), tag_vector); tag_vector.push_back(tag_with_numbers); EXPECT_EQ(ParseQuicTagVector("ABCD,EFGH,IJK,L,4d4e4fff,PQ12"), tag_vector); tag_vector.push_back(tag_with_custom_chars); EXPECT_EQ(ParseQuicTagVector("ABCD,EFGH,IJK,L,4d4e4fff,PQ12,r$_7"), tag_vector); tag_vector.push_back(tag_zero); EXPECT_EQ(ParseQuicTagVector("ABCD,EFGH,IJK,L,4d4e4fff,PQ12,r$_7,"), tag_vector); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_tag.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_tag_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
882f5924-6129-4a44-a8d7-887231c734e9
cpp
google/quiche
quic_stream_sequencer_buffer
quiche/quic/core/quic_stream_sequencer_buffer.cc
quiche/quic/core/quic_stream_sequencer_buffer_test.cc
#include "quiche/quic/core/quic_stream_sequencer_buffer.h" #include <algorithm> #include <cstddef> #include <memory> #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_interval.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 { size_t CalculateBlockCount(size_t max_capacity_bytes) { return (max_capacity_bytes + QuicStreamSequencerBuffer::kBlockSizeBytes - 1) / QuicStreamSequencerBuffer::kBlockSizeBytes; } const size_t kMaxNumDataIntervalsAllowed = 2 * kMaxPacketGap; constexpr size_t kInitialBlockCount = 8u; constexpr int kBlocksGrowthFactor = 4; } QuicStreamSequencerBuffer::QuicStreamSequencerBuffer(size_t max_capacity_bytes) : max_buffer_capacity_bytes_(max_capacity_bytes), max_blocks_count_(CalculateBlockCount(max_capacity_bytes)), current_blocks_count_(0u), total_bytes_read_(0), blocks_(nullptr) { QUICHE_DCHECK_GE(max_blocks_count_, kInitialBlockCount); Clear(); } QuicStreamSequencerBuffer::~QuicStreamSequencerBuffer() { Clear(); } void QuicStreamSequencerBuffer::Clear() { if (blocks_ != nullptr) { for (size_t i = 0; i < current_blocks_count_; ++i) { if (blocks_[i] != nullptr) { RetireBlock(i); } } } num_bytes_buffered_ = 0; bytes_received_.Clear(); bytes_received_.Add(0, total_bytes_read_); } bool QuicStreamSequencerBuffer::RetireBlock(size_t index) { if (blocks_[index] == nullptr) { QUIC_BUG(quic_bug_10610_1) << "Try to retire block twice"; return false; } delete blocks_[index]; blocks_[index] = nullptr; QUIC_DVLOG(1) << "Retired block with index: " << index; return true; } void QuicStreamSequencerBuffer::MaybeAddMoreBlocks( QuicStreamOffset next_expected_byte) { if (current_blocks_count_ == max_blocks_count_) { return; } QuicStreamOffset last_byte = next_expected_byte - 1; size_t num_of_blocks_needed; if (last_byte < max_buffer_capacity_bytes_) { num_of_blocks_needed = std::max(GetBlockIndex(last_byte) + 1, kInitialBlockCount); } else { num_of_blocks_needed = max_blocks_count_; } if (current_blocks_count_ >= num_of_blocks_needed) { return; } size_t new_block_count = kBlocksGrowthFactor * current_blocks_count_; new_block_count = std::min(std::max(new_block_count, num_of_blocks_needed), max_blocks_count_); auto new_blocks = std::make_unique<BufferBlock*[]>(new_block_count); if (blocks_ != nullptr) { memcpy(new_blocks.get(), blocks_.get(), current_blocks_count_ * sizeof(BufferBlock*)); } blocks_ = std::move(new_blocks); current_blocks_count_ = new_block_count; } QuicErrorCode QuicStreamSequencerBuffer::OnStreamData( QuicStreamOffset starting_offset, absl::string_view data, size_t* const bytes_buffered, std::string* error_details) { *bytes_buffered = 0; size_t size = data.size(); if (size == 0) { *error_details = "Received empty stream frame without FIN."; return QUIC_EMPTY_STREAM_FRAME_NO_FIN; } if (starting_offset + size > total_bytes_read_ + max_buffer_capacity_bytes_ || starting_offset + size < starting_offset) { *error_details = "Received data beyond available range."; return QUIC_INTERNAL_ERROR; } if (bytes_received_.Empty() || starting_offset >= bytes_received_.rbegin()->max() || bytes_received_.IsDisjoint(QuicInterval<QuicStreamOffset>( starting_offset, starting_offset + size))) { bytes_received_.AddOptimizedForAppend(starting_offset, starting_offset + size); if (bytes_received_.Size() >= kMaxNumDataIntervalsAllowed) { *error_details = "Too many data intervals received for this stream."; return QUIC_TOO_MANY_STREAM_DATA_INTERVALS; } MaybeAddMoreBlocks(starting_offset + size); size_t bytes_copy = 0; if (!CopyStreamData(starting_offset, data, &bytes_copy, error_details)) { return QUIC_STREAM_SEQUENCER_INVALID_STATE; } *bytes_buffered += bytes_copy; num_bytes_buffered_ += *bytes_buffered; return QUIC_NO_ERROR; } QuicIntervalSet<QuicStreamOffset> newly_received(starting_offset, starting_offset + size); newly_received.Difference(bytes_received_); if (newly_received.Empty()) { return QUIC_NO_ERROR; } bytes_received_.Add(starting_offset, starting_offset + size); if (bytes_received_.Size() >= kMaxNumDataIntervalsAllowed) { *error_details = "Too many data intervals received for this stream."; return QUIC_TOO_MANY_STREAM_DATA_INTERVALS; } MaybeAddMoreBlocks(starting_offset + size); for (const auto& interval : newly_received) { const QuicStreamOffset copy_offset = interval.min(); const QuicByteCount copy_length = interval.max() - interval.min(); size_t bytes_copy = 0; if (!CopyStreamData(copy_offset, data.substr(copy_offset - starting_offset, copy_length), &bytes_copy, error_details)) { return QUIC_STREAM_SEQUENCER_INVALID_STATE; } *bytes_buffered += bytes_copy; } num_bytes_buffered_ += *bytes_buffered; return QUIC_NO_ERROR; } bool QuicStreamSequencerBuffer::CopyStreamData(QuicStreamOffset offset, absl::string_view data, size_t* bytes_copy, std::string* error_details) { *bytes_copy = 0; size_t source_remaining = data.size(); if (source_remaining == 0) { return true; } const char* source = data.data(); while (source_remaining > 0) { const size_t write_block_num = GetBlockIndex(offset); const size_t write_block_offset = GetInBlockOffset(offset); size_t current_blocks_count = current_blocks_count_; QUICHE_DCHECK_GT(current_blocks_count, write_block_num); size_t block_capacity = GetBlockCapacity(write_block_num); size_t bytes_avail = block_capacity - write_block_offset; if (offset + bytes_avail > total_bytes_read_ + max_buffer_capacity_bytes_) { bytes_avail = total_bytes_read_ + max_buffer_capacity_bytes_ - offset; } if (write_block_num >= current_blocks_count) { *error_details = absl::StrCat( "QuicStreamSequencerBuffer error: OnStreamData() exceed array bounds." "write offset = ", offset, " write_block_num = ", write_block_num, " current_blocks_count_ = ", current_blocks_count); return false; } if (blocks_ == nullptr) { *error_details = "QuicStreamSequencerBuffer error: OnStreamData() blocks_ is null"; return false; } if (blocks_[write_block_num] == nullptr) { blocks_[write_block_num] = new BufferBlock(); } const size_t bytes_to_copy = std::min<size_t>(bytes_avail, source_remaining); char* dest = blocks_[write_block_num]->buffer + write_block_offset; QUIC_DVLOG(1) << "Write at offset: " << offset << " length: " << bytes_to_copy; if (dest == nullptr || source == nullptr) { *error_details = absl::StrCat( "QuicStreamSequencerBuffer error: OnStreamData()" " dest == nullptr: ", (dest == nullptr), " source == nullptr: ", (source == nullptr), " Writing at offset ", offset, " Received frames: ", ReceivedFramesDebugString(), " total_bytes_read_ = ", total_bytes_read_); return false; } memcpy(dest, source, bytes_to_copy); source += bytes_to_copy; source_remaining -= bytes_to_copy; offset += bytes_to_copy; *bytes_copy += bytes_to_copy; } return true; } QuicErrorCode QuicStreamSequencerBuffer::Readv(const iovec* dest_iov, size_t dest_count, size_t* bytes_read, std::string* error_details) { *bytes_read = 0; for (size_t i = 0; i < dest_count && ReadableBytes() > 0; ++i) { char* dest = reinterpret_cast<char*>(dest_iov[i].iov_base); QUICHE_DCHECK(dest != nullptr); size_t dest_remaining = dest_iov[i].iov_len; while (dest_remaining > 0 && ReadableBytes() > 0) { size_t block_idx = NextBlockToRead(); size_t start_offset_in_block = ReadOffset(); size_t block_capacity = GetBlockCapacity(block_idx); size_t bytes_available_in_block = std::min<size_t>( ReadableBytes(), block_capacity - start_offset_in_block); size_t bytes_to_copy = std::min<size_t>(bytes_available_in_block, dest_remaining); QUICHE_DCHECK_GT(bytes_to_copy, 0u); if (blocks_[block_idx] == nullptr || dest == nullptr) { *error_details = absl::StrCat( "QuicStreamSequencerBuffer error:" " Readv() dest == nullptr: ", (dest == nullptr), " blocks_[", block_idx, "] == nullptr: ", (blocks_[block_idx] == nullptr), " Received frames: ", ReceivedFramesDebugString(), " total_bytes_read_ = ", total_bytes_read_); return QUIC_STREAM_SEQUENCER_INVALID_STATE; } memcpy(dest, blocks_[block_idx]->buffer + start_offset_in_block, bytes_to_copy); dest += bytes_to_copy; dest_remaining -= bytes_to_copy; num_bytes_buffered_ -= bytes_to_copy; total_bytes_read_ += bytes_to_copy; *bytes_read += bytes_to_copy; if (bytes_to_copy == bytes_available_in_block) { bool retire_successfully = RetireBlockIfEmpty(block_idx); if (!retire_successfully) { *error_details = absl::StrCat( "QuicStreamSequencerBuffer error: fail to retire block ", block_idx, " as the block is already released, total_bytes_read_ = ", total_bytes_read_, " Received frames: ", ReceivedFramesDebugString()); return QUIC_STREAM_SEQUENCER_INVALID_STATE; } } } } return QUIC_NO_ERROR; } int QuicStreamSequencerBuffer::GetReadableRegions(struct iovec* iov, int iov_len) const { QUICHE_DCHECK(iov != nullptr); QUICHE_DCHECK_GT(iov_len, 0); if (ReadableBytes() == 0) { iov[0].iov_base = nullptr; iov[0].iov_len = 0; return 0; } size_t start_block_idx = NextBlockToRead(); QuicStreamOffset readable_offset_end = FirstMissingByte() - 1; QUICHE_DCHECK_GE(readable_offset_end + 1, total_bytes_read_); size_t end_block_offset = GetInBlockOffset(readable_offset_end); size_t end_block_idx = GetBlockIndex(readable_offset_end); if (start_block_idx == end_block_idx && ReadOffset() <= end_block_offset) { iov[0].iov_base = blocks_[start_block_idx]->buffer + ReadOffset(); iov[0].iov_len = ReadableBytes(); QUIC_DVLOG(1) << "Got only a single block with index: " << start_block_idx; return 1; } iov[0].iov_base = blocks_[start_block_idx]->buffer + ReadOffset(); iov[0].iov_len = GetBlockCapacity(start_block_idx) - ReadOffset(); QUIC_DVLOG(1) << "Got first block " << start_block_idx << " with len " << iov[0].iov_len; QUICHE_DCHECK_GT(readable_offset_end + 1, total_bytes_read_ + iov[0].iov_len) << "there should be more available data"; int iov_used = 1; size_t block_idx = (start_block_idx + iov_used) % max_blocks_count_; while (block_idx != end_block_idx && iov_used < iov_len) { QUICHE_DCHECK(nullptr != blocks_[block_idx]); iov[iov_used].iov_base = blocks_[block_idx]->buffer; iov[iov_used].iov_len = GetBlockCapacity(block_idx); QUIC_DVLOG(1) << "Got block with index: " << block_idx; ++iov_used; block_idx = (start_block_idx + iov_used) % max_blocks_count_; } if (iov_used < iov_len) { QUICHE_DCHECK(nullptr != blocks_[block_idx]); iov[iov_used].iov_base = blocks_[end_block_idx]->buffer; iov[iov_used].iov_len = end_block_offset + 1; QUIC_DVLOG(1) << "Got last block with index: " << end_block_idx; ++iov_used; } return iov_used; } bool QuicStreamSequencerBuffer::GetReadableRegion(iovec* iov) const { return GetReadableRegions(iov, 1) == 1; } bool QuicStreamSequencerBuffer::PeekRegion(QuicStreamOffset offset, iovec* iov) const { QUICHE_DCHECK(iov); if (offset < total_bytes_read_) { return false; } if (offset >= FirstMissingByte()) { return false; } size_t block_idx = GetBlockIndex(offset); size_t block_offset = GetInBlockOffset(offset); iov->iov_base = blocks_[block_idx]->buffer + block_offset; size_t end_block_idx = GetBlockIndex(FirstMissingByte()); if (block_idx == end_block_idx && block_offset < GetInBlockOffset(FirstMissingByte())) { iov->iov_len = GetInBlockOffset(FirstMissingByte()) - block_offset; } else { iov->iov_len = GetBlockCapacity(block_idx) - block_offset; } QUIC_BUG_IF(quic_invalid_peek_region, iov->iov_len > kBlockSizeBytes) << "PeekRegion() at " << offset << " gets bad iov with length " << iov->iov_len; return true; } bool QuicStreamSequencerBuffer::MarkConsumed(size_t bytes_consumed) { if (bytes_consumed > ReadableBytes()) { return false; } size_t bytes_to_consume = bytes_consumed; while (bytes_to_consume > 0) { size_t block_idx = NextBlockToRead(); size_t offset_in_block = ReadOffset(); size_t bytes_available = std::min<size_t>( ReadableBytes(), GetBlockCapacity(block_idx) - offset_in_block); size_t bytes_read = std::min<size_t>(bytes_to_consume, bytes_available); total_bytes_read_ += bytes_read; num_bytes_buffered_ -= bytes_read; bytes_to_consume -= bytes_read; if (bytes_available == bytes_read) { RetireBlockIfEmpty(block_idx); } } return true; } size_t QuicStreamSequencerBuffer::FlushBufferedFrames() { size_t prev_total_bytes_read = total_bytes_read_; total_bytes_read_ = NextExpectedByte(); Clear(); return total_bytes_read_ - prev_total_bytes_read; } void QuicStreamSequencerBuffer::ReleaseWholeBuffer() { Clear(); current_blocks_count_ = 0; blocks_.reset(nullptr); } size_t QuicStreamSequencerBuffer::ReadableBytes() const { return FirstMissingByte() - total_bytes_read_; } bool QuicStreamSequencerBuffer::HasBytesToRead() const { return ReadableBytes() > 0; } QuicStreamOffset QuicStreamSequencerBuffer::BytesConsumed() const { return total_bytes_read_; } size_t QuicStreamSequencerBuffer::BytesBuffered() const { return num_bytes_buffered_; } size_t QuicStreamSequencerBuffer::GetBlockIndex(QuicStreamOffset offset) const { return (offset % max_buffer_capacity_bytes_) / kBlockSizeBytes; } size_t QuicStreamSequencerBuffer::GetInBlockOffset( QuicStreamOffset offset) const { return (offset % max_buffer_capacity_bytes_) % kBlockSizeBytes; } size_t QuicStreamSequencerBuffer::ReadOffset() const { return GetInBlockOffset(total_bytes_read_); } size_t QuicStreamSequencerBuffer::NextBlockToRead() const { return GetBlockIndex(total_bytes_read_); } bool QuicStreamSequencerBuffer::RetireBlockIfEmpty(size_t block_index) { QUICHE_DCHECK(ReadableBytes() == 0 || GetInBlockOffset(total_bytes_read_) == 0) << "RetireBlockIfEmpty() should only be called when advancing to next " << "block or a gap has been reached."; if (Empty()) { return RetireBlock(block_index); } if (GetBlockIndex(NextExpectedByte() - 1) == block_index) { return true; } if (NextBlockToRead() == block_index) { if (bytes_received_.Size() > 1) { auto it = bytes_received_.begin(); ++it; if (GetBlockIndex(it->min()) == block_index) { return true; } } else { QUIC_BUG(quic_bug_10610_2) << "Read stopped at where it shouldn't."; return false; } } return RetireBlock(block_index); } bool QuicStreamSequencerBuffer::Empty() const { return bytes_received_.Empty() || (bytes_received_.Size() == 1 && total_bytes_read_ > 0 && bytes_received_.begin()->max() == total_bytes_read_); } size_t QuicStreamSequencerBuffer::GetBlockCapacity(size_t block_index) const { if ((block_index + 1) == max_blocks_count_) { size_t result = max_buffer_capacity_bytes_ % kBlockSizeBytes; if (result == 0) { result = kBlockSizeBytes; } return result; } else { return kBlockSizeBytes; } } std::string QuicStreamSequencerBuffer::ReceivedFramesDebugString() const { return bytes_received_.ToString(); } QuicStreamOffset QuicStreamSequencerBuffer::FirstMissingByte() const { if (bytes_received_.Empty() || bytes_received_.begin()->min() > 0) { return 0; } return bytes_received_.begin()->max(); } QuicStreamOffset QuicStreamSequencerBuffer::NextExpectedByte() const { if (bytes_received_.Empty()) { return 0; } return bytes_received_.rbegin()->max(); } }
#include "quiche/quic/core/quic_stream_sequencer_buffer.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <list> #include <map> #include <memory> #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_stream_sequencer_buffer_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { namespace test { absl::string_view IovecToStringPiece(iovec iov) { return absl::string_view(reinterpret_cast<const char*>(iov.iov_base), iov.iov_len); } char GetCharFromIOVecs(size_t offset, iovec iov[], size_t count) { size_t start_offset = 0; for (size_t i = 0; i < count; i++) { if (iov[i].iov_len == 0) { continue; } size_t end_offset = start_offset + iov[i].iov_len - 1; if (offset >= start_offset && offset <= end_offset) { const char* buf = reinterpret_cast<const char*>(iov[i].iov_base); return buf[offset - start_offset]; } start_offset += iov[i].iov_len; } QUIC_LOG(ERROR) << "Could not locate char at offset " << offset << " in " << count << " iovecs"; for (size_t i = 0; i < count; ++i) { QUIC_LOG(ERROR) << " iov[" << i << "].iov_len = " << iov[i].iov_len; } return '\0'; } const size_t kMaxNumGapsAllowed = 2 * kMaxPacketGap; static const size_t kBlockSizeBytes = QuicStreamSequencerBuffer::kBlockSizeBytes; using BufferBlock = QuicStreamSequencerBuffer::BufferBlock; namespace { class QuicStreamSequencerBufferTest : public QuicTest { public: void SetUp() override { Initialize(); } void ResetMaxCapacityBytes(size_t max_capacity_bytes) { max_capacity_bytes_ = max_capacity_bytes; Initialize(); } protected: void Initialize() { buffer_ = std::make_unique<QuicStreamSequencerBuffer>((max_capacity_bytes_)); helper_ = std::make_unique<QuicStreamSequencerBufferPeer>((buffer_.get())); } size_t max_capacity_bytes_ = 8.5 * kBlockSizeBytes; std::unique_ptr<QuicStreamSequencerBuffer> buffer_; std::unique_ptr<QuicStreamSequencerBufferPeer> helper_; size_t written_ = 0; std::string error_details_; }; TEST_F(QuicStreamSequencerBufferTest, InitializeWithMaxRecvWindowSize) { ResetMaxCapacityBytes(16 * 1024 * 1024); EXPECT_EQ(2 * 1024u, helper_->max_blocks_count()); EXPECT_EQ(max_capacity_bytes_, helper_->max_buffer_capacity()); EXPECT_TRUE(helper_->CheckInitialState()); } TEST_F(QuicStreamSequencerBufferTest, InitializationWithDifferentSizes) { const size_t kCapacity = 16 * QuicStreamSequencerBuffer::kBlockSizeBytes; ResetMaxCapacityBytes(kCapacity); EXPECT_EQ(max_capacity_bytes_, helper_->max_buffer_capacity()); EXPECT_TRUE(helper_->CheckInitialState()); const size_t kCapacity1 = 32 * QuicStreamSequencerBuffer::kBlockSizeBytes; ResetMaxCapacityBytes(kCapacity1); EXPECT_EQ(kCapacity1, helper_->max_buffer_capacity()); EXPECT_TRUE(helper_->CheckInitialState()); } TEST_F(QuicStreamSequencerBufferTest, ClearOnEmpty) { buffer_->Clear(); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, OnStreamData0length) { QuicErrorCode error = buffer_->OnStreamData(800, "", &written_, &error_details_); EXPECT_THAT(error, IsError(QUIC_EMPTY_STREAM_FRAME_NO_FIN)); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, OnStreamDataWithinBlock) { EXPECT_FALSE(helper_->IsBufferAllocated()); std::string source(1024, 'a'); EXPECT_THAT(buffer_->OnStreamData(800, source, &written_, &error_details_), IsQuicNoError()); BufferBlock* block_ptr = helper_->GetBlock(0); for (size_t i = 0; i < source.size(); ++i) { ASSERT_EQ('a', block_ptr->buffer[helper_->GetInBlockOffset(800) + i]); } EXPECT_EQ(2, helper_->IntervalSize()); EXPECT_EQ(0u, helper_->ReadableBytes()); EXPECT_EQ(1u, helper_->bytes_received().Size()); EXPECT_EQ(800u, helper_->bytes_received().begin()->min()); EXPECT_EQ(1824u, helper_->bytes_received().begin()->max()); EXPECT_TRUE(helper_->CheckBufferInvariants()); EXPECT_TRUE(helper_->IsBufferAllocated()); } TEST_F(QuicStreamSequencerBufferTest, Move) { EXPECT_FALSE(helper_->IsBufferAllocated()); std::string source(1024, 'a'); EXPECT_THAT(buffer_->OnStreamData(800, source, &written_, &error_details_), IsQuicNoError()); BufferBlock* block_ptr = helper_->GetBlock(0); for (size_t i = 0; i < source.size(); ++i) { ASSERT_EQ('a', block_ptr->buffer[helper_->GetInBlockOffset(800) + i]); } QuicStreamSequencerBuffer buffer2(std::move(*buffer_)); QuicStreamSequencerBufferPeer helper2(&buffer2); EXPECT_FALSE(helper_->IsBufferAllocated()); EXPECT_EQ(2, helper2.IntervalSize()); EXPECT_EQ(0u, helper2.ReadableBytes()); EXPECT_EQ(1u, helper2.bytes_received().Size()); EXPECT_EQ(800u, helper2.bytes_received().begin()->min()); EXPECT_EQ(1824u, helper2.bytes_received().begin()->max()); EXPECT_TRUE(helper2.CheckBufferInvariants()); EXPECT_TRUE(helper2.IsBufferAllocated()); } TEST_F(QuicStreamSequencerBufferTest, DISABLED_OnStreamDataInvalidSource) { absl::string_view source; source = absl::string_view(nullptr, 1024); EXPECT_THAT(buffer_->OnStreamData(800, source, &written_, &error_details_), IsError(QUIC_STREAM_SEQUENCER_INVALID_STATE)); EXPECT_EQ(0u, error_details_.find(absl::StrCat( "QuicStreamSequencerBuffer error: OnStreamData() " "dest == nullptr: ", false, " source == nullptr: ", true))); } TEST_F(QuicStreamSequencerBufferTest, OnStreamDataWithOverlap) { std::string source(1024, 'a'); EXPECT_THAT(buffer_->OnStreamData(800, source, &written_, &error_details_), IsQuicNoError()); EXPECT_THAT(buffer_->OnStreamData(0, source, &written_, &error_details_), IsQuicNoError()); EXPECT_THAT(buffer_->OnStreamData(1024, source, &written_, &error_details_), IsQuicNoError()); } TEST_F(QuicStreamSequencerBufferTest, OnStreamDataOverlapAndDuplicateCornerCases) { std::string source(1024, 'a'); buffer_->OnStreamData(800, source, &written_, &error_details_); source = std::string(800, 'b'); std::string one_byte = "c"; EXPECT_THAT(buffer_->OnStreamData(1, source, &written_, &error_details_), IsQuicNoError()); EXPECT_THAT(buffer_->OnStreamData(0, source, &written_, &error_details_), IsQuicNoError()); EXPECT_THAT(buffer_->OnStreamData(1823, one_byte, &written_, &error_details_), IsQuicNoError()); EXPECT_EQ(0u, written_); EXPECT_THAT(buffer_->OnStreamData(1824, one_byte, &written_, &error_details_), IsQuicNoError()); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, OnStreamDataWithoutOverlap) { std::string source(1024, 'a'); EXPECT_THAT(buffer_->OnStreamData(800, source, &written_, &error_details_), IsQuicNoError()); source = std::string(100, 'b'); EXPECT_THAT(buffer_->OnStreamData(kBlockSizeBytes * 2 - 20, source, &written_, &error_details_), IsQuicNoError()); EXPECT_EQ(3, helper_->IntervalSize()); EXPECT_EQ(1024u + 100u, buffer_->BytesBuffered()); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, OnStreamDataInLongStreamWithOverlap) { uint64_t total_bytes_read = pow(2, 32) - 1; helper_->set_total_bytes_read(total_bytes_read); helper_->AddBytesReceived(0, total_bytes_read); const size_t kBytesToWrite = 100; std::string source(kBytesToWrite, 'a'); QuicStreamOffset offset = pow(2, 32) + 500; EXPECT_THAT(buffer_->OnStreamData(offset, source, &written_, &error_details_), IsQuicNoError()); EXPECT_EQ(2, helper_->IntervalSize()); offset = pow(2, 32) + 700; EXPECT_THAT(buffer_->OnStreamData(offset, source, &written_, &error_details_), IsQuicNoError()); EXPECT_EQ(3, helper_->IntervalSize()); offset = pow(2, 32) + 300; EXPECT_THAT(buffer_->OnStreamData(offset, source, &written_, &error_details_), IsQuicNoError()); EXPECT_EQ(4, helper_->IntervalSize()); } TEST_F(QuicStreamSequencerBufferTest, OnStreamDataTillEnd) { const size_t kBytesToWrite = 50; std::string source(kBytesToWrite, 'a'); EXPECT_THAT(buffer_->OnStreamData(max_capacity_bytes_ - kBytesToWrite, source, &written_, &error_details_), IsQuicNoError()); EXPECT_EQ(50u, buffer_->BytesBuffered()); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, OnStreamDataTillEndCorner) { const size_t kBytesToWrite = 1; std::string source(kBytesToWrite, 'a'); EXPECT_THAT(buffer_->OnStreamData(max_capacity_bytes_ - kBytesToWrite, source, &written_, &error_details_), IsQuicNoError()); EXPECT_EQ(1u, buffer_->BytesBuffered()); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, OnStreamDataBeyondCapacity) { std::string source(60, 'a'); EXPECT_THAT(buffer_->OnStreamData(max_capacity_bytes_ - 50, source, &written_, &error_details_), IsError(QUIC_INTERNAL_ERROR)); EXPECT_TRUE(helper_->CheckBufferInvariants()); source = "b"; EXPECT_THAT(buffer_->OnStreamData(max_capacity_bytes_, source, &written_, &error_details_), IsError(QUIC_INTERNAL_ERROR)); EXPECT_TRUE(helper_->CheckBufferInvariants()); EXPECT_THAT(buffer_->OnStreamData(max_capacity_bytes_ * 1000, source, &written_, &error_details_), IsError(QUIC_INTERNAL_ERROR)); EXPECT_TRUE(helper_->CheckBufferInvariants()); EXPECT_THAT(buffer_->OnStreamData(static_cast<QuicStreamOffset>(-1), source, &written_, &error_details_), IsError(QUIC_INTERNAL_ERROR)); EXPECT_TRUE(helper_->CheckBufferInvariants()); source = "bbb"; EXPECT_THAT(buffer_->OnStreamData(static_cast<QuicStreamOffset>(-2), source, &written_, &error_details_), IsError(QUIC_INTERNAL_ERROR)); EXPECT_TRUE(helper_->CheckBufferInvariants()); EXPECT_EQ(0u, buffer_->BytesBuffered()); } TEST_F(QuicStreamSequencerBufferTest, Readv100Bytes) { std::string source(1024, 'a'); buffer_->OnStreamData(kBlockSizeBytes, source, &written_, &error_details_); EXPECT_FALSE(buffer_->HasBytesToRead()); source = std::string(100, 'b'); buffer_->OnStreamData(0, source, &written_, &error_details_); EXPECT_TRUE(buffer_->HasBytesToRead()); char dest[120]; iovec iovecs[3]{iovec{dest, 40}, iovec{dest + 40, 40}, iovec{dest + 80, 40}}; size_t read; EXPECT_THAT(buffer_->Readv(iovecs, 3, &read, &error_details_), IsQuicNoError()); QUIC_LOG(ERROR) << error_details_; EXPECT_EQ(100u, read); EXPECT_EQ(100u, buffer_->BytesConsumed()); EXPECT_EQ(source, absl::string_view(dest, read)); EXPECT_EQ(nullptr, helper_->GetBlock(0)); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, ReadvAcrossBlocks) { std::string source(kBlockSizeBytes + 50, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); EXPECT_EQ(source.size(), helper_->ReadableBytes()); char dest[512]; while (helper_->ReadableBytes()) { std::fill(dest, dest + 512, 0); iovec iovecs[2]{iovec{dest, 256}, iovec{dest + 256, 256}}; size_t read; EXPECT_THAT(buffer_->Readv(iovecs, 2, &read, &error_details_), IsQuicNoError()); } EXPECT_EQ(std::string(50, 'a'), std::string(dest, 50)); EXPECT_EQ(0, dest[50]) << "Dest[50] shouln't be filled."; EXPECT_EQ(source.size(), buffer_->BytesConsumed()); EXPECT_TRUE(buffer_->Empty()); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, ClearAfterRead) { std::string source(kBlockSizeBytes + 50, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[512]{0}; const iovec iov{dest, 512}; size_t read; EXPECT_THAT(buffer_->Readv(&iov, 1, &read, &error_details_), IsQuicNoError()); buffer_->Clear(); EXPECT_TRUE(buffer_->Empty()); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, OnStreamDataAcrossLastBlockAndFillCapacity) { std::string source(kBlockSizeBytes + 50, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[512]{0}; const iovec iov{dest, 512}; size_t read; EXPECT_THAT(buffer_->Readv(&iov, 1, &read, &error_details_), IsQuicNoError()); EXPECT_EQ(source.size(), written_); source = std::string(0.5 * kBlockSizeBytes + 512, 'b'); EXPECT_THAT(buffer_->OnStreamData(2 * kBlockSizeBytes, source, &written_, &error_details_), IsQuicNoError()); EXPECT_EQ(source.size(), written_); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, OnStreamDataAcrossLastBlockAndExceedCapacity) { std::string source(kBlockSizeBytes + 50, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[512]{0}; const iovec iov{dest, 512}; size_t read; EXPECT_THAT(buffer_->Readv(&iov, 1, &read, &error_details_), IsQuicNoError()); source = std::string(0.5 * kBlockSizeBytes + 512 + 1, 'b'); EXPECT_THAT(buffer_->OnStreamData(8 * kBlockSizeBytes, source, &written_, &error_details_), IsError(QUIC_INTERNAL_ERROR)); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, ReadvAcrossLastBlock) { std::string source(max_capacity_bytes_, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[512]{0}; const iovec iov{dest, 512}; size_t read; EXPECT_THAT(buffer_->Readv(&iov, 1, &read, &error_details_), IsQuicNoError()); source = std::string(256, 'b'); buffer_->OnStreamData(max_capacity_bytes_, source, &written_, &error_details_); EXPECT_TRUE(helper_->CheckBufferInvariants()); std::unique_ptr<char[]> dest1{new char[max_capacity_bytes_]}; dest1[0] = 0; const iovec iov1{dest1.get(), max_capacity_bytes_}; EXPECT_THAT(buffer_->Readv(&iov1, 1, &read, &error_details_), IsQuicNoError()); EXPECT_EQ(max_capacity_bytes_ - 512 + 256, read); EXPECT_EQ(max_capacity_bytes_ + 256, buffer_->BytesConsumed()); EXPECT_TRUE(buffer_->Empty()); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, ReadvEmpty) { char dest[512]{0}; iovec iov{dest, 512}; size_t read; EXPECT_THAT(buffer_->Readv(&iov, 1, &read, &error_details_), IsQuicNoError()); EXPECT_EQ(0u, read); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, GetReadableRegionsEmpty) { iovec iovs[2]; int iov_count = buffer_->GetReadableRegions(iovs, 2); EXPECT_EQ(0, iov_count); EXPECT_EQ(nullptr, iovs[iov_count].iov_base); EXPECT_EQ(0u, iovs[iov_count].iov_len); } TEST_F(QuicStreamSequencerBufferTest, ReleaseWholeBuffer) { std::string source(100, 'b'); buffer_->OnStreamData(0, source, &written_, &error_details_); EXPECT_TRUE(buffer_->HasBytesToRead()); char dest[120]; iovec iovecs[3]{iovec{dest, 40}, iovec{dest + 40, 40}, iovec{dest + 80, 40}}; size_t read; EXPECT_THAT(buffer_->Readv(iovecs, 3, &read, &error_details_), IsQuicNoError()); EXPECT_EQ(100u, read); EXPECT_EQ(100u, buffer_->BytesConsumed()); EXPECT_TRUE(helper_->CheckBufferInvariants()); EXPECT_TRUE(helper_->IsBufferAllocated()); buffer_->ReleaseWholeBuffer(); EXPECT_FALSE(helper_->IsBufferAllocated()); } TEST_F(QuicStreamSequencerBufferTest, GetReadableRegionsBlockedByGap) { std::string source(1023, 'a'); buffer_->OnStreamData(1, source, &written_, &error_details_); iovec iovs[2]; int iov_count = buffer_->GetReadableRegions(iovs, 2); EXPECT_EQ(0, iov_count); } TEST_F(QuicStreamSequencerBufferTest, GetReadableRegionsTillEndOfBlock) { std::string source(kBlockSizeBytes, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[256]; helper_->Read(dest, 256); iovec iovs[2]; int iov_count = buffer_->GetReadableRegions(iovs, 2); EXPECT_EQ(1, iov_count); EXPECT_EQ(std::string(kBlockSizeBytes - 256, 'a'), IovecToStringPiece(iovs[0])); } TEST_F(QuicStreamSequencerBufferTest, GetReadableRegionsWithinOneBlock) { std::string source(1024, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[256]; helper_->Read(dest, 256); iovec iovs[2]; int iov_count = buffer_->GetReadableRegions(iovs, 2); EXPECT_EQ(1, iov_count); EXPECT_EQ(std::string(1024 - 256, 'a'), IovecToStringPiece(iovs[0])); } TEST_F(QuicStreamSequencerBufferTest, GetReadableRegionsAcrossBlockWithLongIOV) { std::string source(2 * kBlockSizeBytes + 1024, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[1024]; helper_->Read(dest, 1024); iovec iovs[4]; int iov_count = buffer_->GetReadableRegions(iovs, 4); EXPECT_EQ(3, iov_count); EXPECT_EQ(kBlockSizeBytes - 1024, iovs[0].iov_len); EXPECT_EQ(kBlockSizeBytes, iovs[1].iov_len); EXPECT_EQ(1024u, iovs[2].iov_len); } TEST_F(QuicStreamSequencerBufferTest, GetReadableRegionsWithMultipleIOVsAcrossEnd) { std::string source(8.5 * kBlockSizeBytes - 1024, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[1024]; helper_->Read(dest, 1024); source = std::string(1024 + 512, 'b'); buffer_->OnStreamData(8.5 * kBlockSizeBytes - 1024, source, &written_, &error_details_); iovec iovs[2]; int iov_count = buffer_->GetReadableRegions(iovs, 2); EXPECT_EQ(2, iov_count); EXPECT_EQ(kBlockSizeBytes - 1024, iovs[0].iov_len); EXPECT_EQ(kBlockSizeBytes, iovs[1].iov_len); iovec iovs1[11]; EXPECT_EQ(10, buffer_->GetReadableRegions(iovs1, 11)); EXPECT_EQ(0.5 * kBlockSizeBytes, iovs1[8].iov_len); EXPECT_EQ(512u, iovs1[9].iov_len); EXPECT_EQ(std::string(512, 'b'), IovecToStringPiece(iovs1[9])); } TEST_F(QuicStreamSequencerBufferTest, GetReadableRegionEmpty) { iovec iov; EXPECT_FALSE(buffer_->GetReadableRegion(&iov)); EXPECT_EQ(nullptr, iov.iov_base); EXPECT_EQ(0u, iov.iov_len); } TEST_F(QuicStreamSequencerBufferTest, GetReadableRegionBeforeGap) { std::string source(1023, 'a'); buffer_->OnStreamData(1, source, &written_, &error_details_); iovec iov; EXPECT_FALSE(buffer_->GetReadableRegion(&iov)); } TEST_F(QuicStreamSequencerBufferTest, GetReadableRegionTillEndOfBlock) { std::string source(kBlockSizeBytes + 1, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[256]; helper_->Read(dest, 256); iovec iov; EXPECT_TRUE(buffer_->GetReadableRegion(&iov)); EXPECT_EQ(std::string(kBlockSizeBytes - 256, 'a'), IovecToStringPiece(iov)); } TEST_F(QuicStreamSequencerBufferTest, GetReadableRegionTillGap) { std::string source(kBlockSizeBytes - 1, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[256]; helper_->Read(dest, 256); iovec iov; EXPECT_TRUE(buffer_->GetReadableRegion(&iov)); EXPECT_EQ(std::string(kBlockSizeBytes - 1 - 256, 'a'), IovecToStringPiece(iov)); } TEST_F(QuicStreamSequencerBufferTest, PeekEmptyBuffer) { iovec iov; EXPECT_FALSE(buffer_->PeekRegion(0, &iov)); EXPECT_FALSE(buffer_->PeekRegion(1, &iov)); EXPECT_FALSE(buffer_->PeekRegion(100, &iov)); } TEST_F(QuicStreamSequencerBufferTest, PeekSingleBlock) { std::string source(kBlockSizeBytes, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); iovec iov; EXPECT_TRUE(buffer_->PeekRegion(0, &iov)); EXPECT_EQ(source, IovecToStringPiece(iov)); EXPECT_TRUE(buffer_->PeekRegion(0, &iov)); EXPECT_EQ(source, IovecToStringPiece(iov)); EXPECT_TRUE(buffer_->PeekRegion(100, &iov)); EXPECT_EQ(absl::string_view(source).substr(100), IovecToStringPiece(iov)); EXPECT_FALSE(buffer_->PeekRegion(kBlockSizeBytes, &iov)); EXPECT_FALSE(buffer_->PeekRegion(kBlockSizeBytes + 1, &iov)); } TEST_F(QuicStreamSequencerBufferTest, PeekTwoWritesInSingleBlock) { const size_t length1 = 1024; std::string source1(length1, 'a'); buffer_->OnStreamData(0, source1, &written_, &error_details_); iovec iov; EXPECT_TRUE(buffer_->PeekRegion(0, &iov)); EXPECT_EQ(source1, IovecToStringPiece(iov)); const size_t length2 = 800; std::string source2(length2, 'b'); buffer_->OnStreamData(length1, source2, &written_, &error_details_); EXPECT_TRUE(buffer_->PeekRegion(length1, &iov)); EXPECT_EQ(source2, IovecToStringPiece(iov)); const QuicStreamOffset offset1 = 500; EXPECT_TRUE(buffer_->PeekRegion(offset1, &iov)); EXPECT_EQ(absl::string_view(source1).substr(offset1), IovecToStringPiece(iov).substr(0, length1 - offset1)); EXPECT_EQ(absl::string_view(source2), IovecToStringPiece(iov).substr(length1 - offset1)); const QuicStreamOffset offset2 = 1500; EXPECT_TRUE(buffer_->PeekRegion(offset2, &iov)); EXPECT_EQ(absl::string_view(source2).substr(offset2 - length1), IovecToStringPiece(iov)); EXPECT_FALSE(buffer_->PeekRegion(length1 + length2, &iov)); EXPECT_FALSE(buffer_->PeekRegion(length1 + length2 + 1, &iov)); } TEST_F(QuicStreamSequencerBufferTest, PeekBufferWithMultipleBlocks) { const size_t length1 = 1024; std::string source1(length1, 'a'); buffer_->OnStreamData(0, source1, &written_, &error_details_); iovec iov; EXPECT_TRUE(buffer_->PeekRegion(0, &iov)); EXPECT_EQ(source1, IovecToStringPiece(iov)); const size_t length2 = kBlockSizeBytes + 2; std::string source2(length2, 'b'); buffer_->OnStreamData(length1, source2, &written_, &error_details_); EXPECT_TRUE(buffer_->PeekRegion(0, &iov)); EXPECT_EQ(kBlockSizeBytes, iov.iov_len); EXPECT_EQ(source1, IovecToStringPiece(iov).substr(0, length1)); EXPECT_EQ(absl::string_view(source2).substr(0, kBlockSizeBytes - length1), IovecToStringPiece(iov).substr(length1)); EXPECT_TRUE(buffer_->PeekRegion(length1, &iov)); EXPECT_EQ(absl::string_view(source2).substr(0, kBlockSizeBytes - length1), IovecToStringPiece(iov)); EXPECT_TRUE(buffer_->PeekRegion(kBlockSizeBytes, &iov)); EXPECT_EQ(absl::string_view(source2).substr(kBlockSizeBytes - length1), IovecToStringPiece(iov)); EXPECT_FALSE(buffer_->PeekRegion(length1 + length2, &iov)); EXPECT_FALSE(buffer_->PeekRegion(length1 + length2 + 1, &iov)); } TEST_F(QuicStreamSequencerBufferTest, PeekAfterConsumed) { std::string source1(kBlockSizeBytes, 'a'); buffer_->OnStreamData(0, source1, &written_, &error_details_); iovec iov; EXPECT_TRUE(buffer_->PeekRegion(0, &iov)); EXPECT_EQ(source1, IovecToStringPiece(iov)); EXPECT_TRUE(buffer_->MarkConsumed(1024)); EXPECT_FALSE(buffer_->PeekRegion(0, &iov)); EXPECT_FALSE(buffer_->PeekRegion(512, &iov)); EXPECT_TRUE(buffer_->PeekRegion(1024, &iov)); EXPECT_EQ(absl::string_view(source1).substr(1024), IovecToStringPiece(iov)); EXPECT_TRUE(buffer_->PeekRegion(1500, &iov)); EXPECT_EQ(absl::string_view(source1).substr(1500), IovecToStringPiece(iov)); EXPECT_TRUE(buffer_->MarkConsumed(kBlockSizeBytes - 1024)); std::string source2(300, 'b'); buffer_->OnStreamData(kBlockSizeBytes, source2, &written_, &error_details_); EXPECT_TRUE(buffer_->PeekRegion(kBlockSizeBytes, &iov)); EXPECT_EQ(source2, IovecToStringPiece(iov)); EXPECT_TRUE(buffer_->PeekRegion(kBlockSizeBytes + 128, &iov)); EXPECT_EQ(absl::string_view(source2).substr(128), IovecToStringPiece(iov)); EXPECT_FALSE(buffer_->PeekRegion(0, &iov)); EXPECT_FALSE(buffer_->PeekRegion(512, &iov)); EXPECT_FALSE(buffer_->PeekRegion(1024, &iov)); EXPECT_FALSE(buffer_->PeekRegion(1500, &iov)); } TEST_F(QuicStreamSequencerBufferTest, PeekContinously) { std::string source1(kBlockSizeBytes, 'a'); buffer_->OnStreamData(0, source1, &written_, &error_details_); iovec iov; EXPECT_TRUE(buffer_->PeekRegion(0, &iov)); EXPECT_EQ(source1, IovecToStringPiece(iov)); std::string source2(kBlockSizeBytes, 'b'); buffer_->OnStreamData(kBlockSizeBytes, source2, &written_, &error_details_); EXPECT_TRUE(buffer_->PeekRegion(kBlockSizeBytes, &iov)); EXPECT_EQ(source2, IovecToStringPiece(iov)); EXPECT_TRUE(buffer_->PeekRegion(0, &iov)); EXPECT_EQ(source1, IovecToStringPiece(iov)); } TEST_F(QuicStreamSequencerBufferTest, PeekRegionWithBufferWrapsAround) { ResetMaxCapacityBytes(kBlockSizeBytes * 8); std::string source1(kBlockSizeBytes, 'a'); buffer_->OnStreamData(0, source1, &written_, &error_details_); iovec iov; EXPECT_TRUE(buffer_->PeekRegion(0, &iov)); EXPECT_EQ(source1, IovecToStringPiece(iov)); size_t consumed_bytes = kBlockSizeBytes - 4 * 1024; buffer_->MarkConsumed(consumed_bytes); std::string source2(max_capacity_bytes_ - 4 * 1024 - 1, 'b'); buffer_->OnStreamData(kBlockSizeBytes, source2, &written_, &error_details_); EXPECT_EQ(max_capacity_bytes_ - 1, buffer_->ReadableBytes()); EXPECT_TRUE(buffer_->PeekRegion(consumed_bytes, &iov)); EXPECT_EQ(std::string(4 * 1024, 'a'), IovecToStringPiece(iov)); } TEST_F(QuicStreamSequencerBufferTest, MarkConsumedInOneBlock) { std::string source(1024, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[256]; helper_->Read(dest, 256); EXPECT_TRUE(buffer_->MarkConsumed(512)); EXPECT_EQ(256u + 512u, buffer_->BytesConsumed()); EXPECT_EQ(256u, helper_->ReadableBytes()); buffer_->MarkConsumed(256); EXPECT_TRUE(buffer_->Empty()); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, MarkConsumedNotEnoughBytes) { std::string source(1024, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[256]; helper_->Read(dest, 256); EXPECT_TRUE(buffer_->MarkConsumed(512)); EXPECT_EQ(256u + 512u, buffer_->BytesConsumed()); EXPECT_EQ(256u, helper_->ReadableBytes()); EXPECT_FALSE(buffer_->MarkConsumed(257)); EXPECT_EQ(256u + 512u, buffer_->BytesConsumed()); iovec iov; EXPECT_TRUE(buffer_->GetReadableRegion(&iov)); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, MarkConsumedAcrossBlock) { std::string source(2 * kBlockSizeBytes + 1024, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[1024]; helper_->Read(dest, 1024); buffer_->MarkConsumed(2 * kBlockSizeBytes); EXPECT_EQ(source.size(), buffer_->BytesConsumed()); EXPECT_TRUE(buffer_->Empty()); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, MarkConsumedAcrossEnd) { std::string source(8.5 * kBlockSizeBytes - 1024, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[1024]; helper_->Read(dest, 1024); source = std::string(1024 + 512, 'b'); buffer_->OnStreamData(8.5 * kBlockSizeBytes - 1024, source, &written_, &error_details_); EXPECT_EQ(1024u, buffer_->BytesConsumed()); buffer_->MarkConsumed(8 * kBlockSizeBytes - 1024); EXPECT_EQ(8 * kBlockSizeBytes, buffer_->BytesConsumed()); buffer_->MarkConsumed(0.5 * kBlockSizeBytes + 500); EXPECT_EQ(max_capacity_bytes_ + 500, buffer_->BytesConsumed()); EXPECT_EQ(12u, helper_->ReadableBytes()); buffer_->MarkConsumed(12); EXPECT_EQ(max_capacity_bytes_ + 512, buffer_->BytesConsumed()); EXPECT_TRUE(buffer_->Empty()); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, FlushBufferedFrames) { std::string source(max_capacity_bytes_ - 1024, 'a'); buffer_->OnStreamData(0, source, &written_, &error_details_); char dest[1024]; helper_->Read(dest, 1024); EXPECT_EQ(1024u, buffer_->BytesConsumed()); source = std::string(512, 'b'); buffer_->OnStreamData(max_capacity_bytes_, source, &written_, &error_details_); EXPECT_EQ(512u, written_); EXPECT_EQ(max_capacity_bytes_ - 1024 + 512, buffer_->FlushBufferedFrames()); EXPECT_EQ(max_capacity_bytes_ + 512, buffer_->BytesConsumed()); EXPECT_TRUE(buffer_->Empty()); EXPECT_TRUE(helper_->CheckBufferInvariants()); buffer_->Clear(); EXPECT_EQ(max_capacity_bytes_ + 512, buffer_->BytesConsumed()); EXPECT_TRUE(helper_->CheckBufferInvariants()); } TEST_F(QuicStreamSequencerBufferTest, TooManyGaps) { max_capacity_bytes_ = 3 * kBlockSizeBytes; for (QuicStreamOffset begin = 1; begin <= max_capacity_bytes_; begin += 2) { QuicErrorCode rs = buffer_->OnStreamData(begin, "a", &written_, &error_details_); QuicStreamOffset last_straw = 2 * kMaxNumGapsAllowed - 1; if (begin == last_straw) { EXPECT_THAT(rs, IsError(QUIC_TOO_MANY_STREAM_DATA_INTERVALS)); EXPECT_EQ("Too many data intervals received for this stream.", error_details_); break; } } } class QuicStreamSequencerBufferRandomIOTest : public QuicStreamSequencerBufferTest { public: using OffsetSizePair = std::pair<QuicStreamOffset, size_t>; void SetUp() override { max_capacity_bytes_ = 8.25 * kBlockSizeBytes; bytes_to_buffer_ = 2 * max_capacity_bytes_; Initialize(); uint64_t seed = QuicRandom::GetInstance()->RandUint64(); QUIC_LOG(INFO) << "**** The current seed is " << seed << " ****"; rng_.set_seed(seed); } void CreateSourceAndShuffle(size_t max_chunk_size_bytes) { max_chunk_size_bytes_ = max_chunk_size_bytes; std::unique_ptr<OffsetSizePair[]> chopped_stream( new OffsetSizePair[bytes_to_buffer_]); size_t start_chopping_offset = 0; size_t iterations = 0; while (start_chopping_offset < bytes_to_buffer_) { size_t max_chunk = std::min<size_t>( max_chunk_size_bytes_, bytes_to_buffer_ - start_chopping_offset); size_t chunk_size = rng_.RandUint64() % max_chunk + 1; chopped_stream[iterations] = OffsetSizePair(start_chopping_offset, chunk_size); start_chopping_offset += chunk_size; ++iterations; } QUICHE_DCHECK(start_chopping_offset == bytes_to_buffer_); size_t chunk_num = iterations; for (int i = chunk_num - 1; i >= 0; --i) { size_t random_idx = rng_.RandUint64() % (i + 1); QUIC_DVLOG(1) << "chunk offset " << chopped_stream[random_idx].first << " size " << chopped_stream[random_idx].second; shuffled_buf_.push_front(chopped_stream[random_idx]); chopped_stream[random_idx] = chopped_stream[i]; } } void WriteNextChunkToBuffer() { OffsetSizePair& chunk = shuffled_buf_.front(); QuicStreamOffset offset = chunk.first; const size_t num_to_write = chunk.second; std::unique_ptr<char[]> write_buf{new char[max_chunk_size_bytes_]}; for (size_t i = 0; i < num_to_write; ++i) { write_buf[i] = (offset + i) % 256; } absl::string_view string_piece_w(write_buf.get(), num_to_write); auto result = buffer_->OnStreamData(offset, string_piece_w, &written_, &error_details_); if (result == QUIC_NO_ERROR) { shuffled_buf_.pop_front(); total_bytes_written_ += num_to_write; } else { shuffled_buf_.push_back(chunk); shuffled_buf_.pop_front(); } QUIC_DVLOG(1) << " write at offset: " << offset << " len to write: " << num_to_write << " write result: " << result << " left over: " << shuffled_buf_.size(); } protected: std::list<OffsetSizePair> shuffled_buf_; size_t max_chunk_size_bytes_; QuicStreamOffset bytes_to_buffer_; size_t total_bytes_written_ = 0; size_t total_bytes_read_ = 0; SimpleRandom rng_; }; TEST_F(QuicStreamSequencerBufferRandomIOTest, RandomWriteAndReadv) { const size_t kMaxReadSize = kBlockSizeBytes * 2; const size_t kNumReads = 2; const size_t kMaxWriteSize = kNumReads * kMaxReadSize; size_t iterations = 0; CreateSourceAndShuffle(kMaxWriteSize); while ((!shuffled_buf_.empty() || total_bytes_read_ < bytes_to_buffer_) && iterations <= 2 * bytes_to_buffer_) { uint8_t next_action = shuffled_buf_.empty() ? uint8_t{1} : rng_.RandUint64() % 2; QUIC_DVLOG(1) << "iteration: " << iterations; switch (next_action) { case 0: { WriteNextChunkToBuffer(); ASSERT_TRUE(helper_->CheckBufferInvariants()); break; } case 1: { std::unique_ptr<char[][kMaxReadSize]> read_buf{ new char[kNumReads][kMaxReadSize]}; iovec dest_iov[kNumReads]; size_t num_to_read = 0; for (size_t i = 0; i < kNumReads; ++i) { dest_iov[i].iov_base = reinterpret_cast<void*>(const_cast<char*>(read_buf[i])); dest_iov[i].iov_len = rng_.RandUint64() % kMaxReadSize; num_to_read += dest_iov[i].iov_len; } size_t actually_read; EXPECT_THAT(buffer_->Readv(dest_iov, kNumReads, &actually_read, &error_details_), IsQuicNoError()); ASSERT_LE(actually_read, num_to_read); QUIC_DVLOG(1) << " read from offset: " << total_bytes_read_ << " size: " << num_to_read << " actual read: " << actually_read; for (size_t i = 0; i < actually_read; ++i) { char ch = (i + total_bytes_read_) % 256; ASSERT_EQ(ch, GetCharFromIOVecs(i, dest_iov, kNumReads)) << " at iteration " << iterations; } total_bytes_read_ += actually_read; ASSERT_EQ(total_bytes_read_, buffer_->BytesConsumed()); ASSERT_TRUE(helper_->CheckBufferInvariants()); break; } } ++iterations; ASSERT_LE(total_bytes_read_, total_bytes_written_); } EXPECT_LT(iterations, bytes_to_buffer_) << "runaway test"; EXPECT_LE(bytes_to_buffer_, total_bytes_read_) << "iterations: " << iterations; EXPECT_LE(bytes_to_buffer_, total_bytes_written_); } TEST_F(QuicStreamSequencerBufferRandomIOTest, RandomWriteAndConsumeInPlace) { const size_t kMaxNumReads = 4; const size_t kMaxWriteSize = kMaxNumReads * kBlockSizeBytes; ASSERT_LE(kMaxWriteSize, max_capacity_bytes_); size_t iterations = 0; CreateSourceAndShuffle(kMaxWriteSize); while ((!shuffled_buf_.empty() || total_bytes_read_ < bytes_to_buffer_) && iterations <= 2 * bytes_to_buffer_) { uint8_t next_action = shuffled_buf_.empty() ? uint8_t{1} : rng_.RandUint64() % 2; QUIC_DVLOG(1) << "iteration: " << iterations; switch (next_action) { case 0: { WriteNextChunkToBuffer(); ASSERT_TRUE(helper_->CheckBufferInvariants()); break; } case 1: { size_t num_read = rng_.RandUint64() % kMaxNumReads + 1; iovec dest_iov[kMaxNumReads]; ASSERT_TRUE(helper_->CheckBufferInvariants()); size_t actually_num_read = buffer_->GetReadableRegions(dest_iov, num_read); ASSERT_LE(actually_num_read, num_read); size_t avail_bytes = 0; for (size_t i = 0; i < actually_num_read; ++i) { avail_bytes += dest_iov[i].iov_len; } size_t bytes_to_process = rng_.RandUint64() % (avail_bytes + 1); size_t bytes_processed = 0; for (size_t i = 0; i < actually_num_read; ++i) { size_t bytes_in_block = std::min<size_t>( bytes_to_process - bytes_processed, dest_iov[i].iov_len); if (bytes_in_block == 0) { break; } for (size_t j = 0; j < bytes_in_block; ++j) { ASSERT_LE(bytes_processed, bytes_to_process); char char_expected = (buffer_->BytesConsumed() + bytes_processed) % 256; ASSERT_EQ(char_expected, reinterpret_cast<const char*>(dest_iov[i].iov_base)[j]) << " at iteration " << iterations; ++bytes_processed; } } buffer_->MarkConsumed(bytes_processed); QUIC_DVLOG(1) << "iteration " << iterations << ": try to get " << num_read << " readable regions, actually get " << actually_num_read << " from offset: " << total_bytes_read_ << "\nprocesse bytes: " << bytes_processed; total_bytes_read_ += bytes_processed; ASSERT_EQ(total_bytes_read_, buffer_->BytesConsumed()); ASSERT_TRUE(helper_->CheckBufferInvariants()); break; } } ++iterations; ASSERT_LE(total_bytes_read_, total_bytes_written_); } EXPECT_LT(iterations, bytes_to_buffer_) << "runaway test"; EXPECT_LE(bytes_to_buffer_, total_bytes_read_) << "iterations: " << iterations; EXPECT_LE(bytes_to_buffer_, total_bytes_written_); } TEST_F(QuicStreamSequencerBufferTest, GrowBlockSizeOnDemand) { max_capacity_bytes_ = 1024 * kBlockSizeBytes; std::string source_of_one_block(kBlockSizeBytes, 'a'); Initialize(); ASSERT_EQ(helper_->current_blocks_count(), 0u); buffer_->OnStreamData(0, source_of_one_block, &written_, &error_details_); ASSERT_EQ(helper_->current_blocks_count(), 8u); buffer_->OnStreamData(kBlockSizeBytes * 7, source_of_one_block, &written_, &error_details_); ASSERT_EQ(helper_->current_blocks_count(), 8u); buffer_->OnStreamData(kBlockSizeBytes * 8, "a", &written_, &error_details_); ASSERT_EQ(helper_->current_blocks_count(), 32u); buffer_->OnStreamData(kBlockSizeBytes * 139, source_of_one_block, &written_, &error_details_); ASSERT_EQ(helper_->current_blocks_count(), 140u); buffer_->OnStreamData(kBlockSizeBytes * 140, source_of_one_block, &written_, &error_details_); ASSERT_EQ(helper_->current_blocks_count(), 560u); buffer_->OnStreamData(kBlockSizeBytes * 560, source_of_one_block, &written_, &error_details_); ASSERT_EQ(helper_->current_blocks_count(), 1024u); buffer_->OnStreamData(kBlockSizeBytes * 1025, source_of_one_block, &written_, &error_details_); ASSERT_EQ(helper_->current_blocks_count(), 1024u); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_stream_sequencer_buffer.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_stream_sequencer_buffer_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
b89a5ac0-a504-4299-9d79-cc34ac6e6151
cpp
google/quiche
tls_server_handshaker
quiche/quic/core/tls_server_handshaker.cc
quiche/quic/core/tls_server_handshaker_test.cc
#include "quiche/quic/core/tls_server_handshaker.h" #include <cstddef> #include <cstdint> #include <cstring> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "absl/types/variant.h" #include "openssl/base.h" #include "openssl/bytestring.h" #include "openssl/ssl.h" #include "openssl/tls1.h" #include "quiche/quic/core/crypto/crypto_handshake.h" #include "quiche/quic/core/crypto/crypto_message_parser.h" #include "quiche/quic/core/crypto/crypto_utils.h" #include "quiche/quic/core/crypto/proof_source.h" #include "quiche/quic/core/crypto/proof_verifier.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/transport_parameters.h" #include "quiche/quic/core/http/http_encoder.h" #include "quiche/quic/core/http/http_frames.h" #include "quiche/quic/core/quic_config.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_connection_context.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_connection_stats.h" #include "quiche/quic/core/quic_crypto_server_stream_base.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_time_accumulator.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/core/tls_handshaker.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_server_stats.h" #include "quiche/quic/platform/api/quic_socket_address.h" #define RECORD_LATENCY_IN_US(stat_name, latency, comment) \ do { \ const int64_t latency_in_us = (latency).ToMicroseconds(); \ QUIC_DVLOG(1) << "Recording " stat_name ": " << latency_in_us; \ QUIC_SERVER_HISTOGRAM_COUNTS(stat_name, latency_in_us, 1, 10000000, 50, \ comment); \ } while (0) namespace quic { namespace { uint16_t kDefaultPort = 443; } TlsServerHandshaker::DefaultProofSourceHandle::DefaultProofSourceHandle( TlsServerHandshaker* handshaker, ProofSource* proof_source) : handshaker_(handshaker), proof_source_(proof_source) {} TlsServerHandshaker::DefaultProofSourceHandle::~DefaultProofSourceHandle() { CloseHandle(); } void TlsServerHandshaker::DefaultProofSourceHandle::CloseHandle() { QUIC_DVLOG(1) << "CloseHandle. is_signature_pending=" << (signature_callback_ != nullptr); if (signature_callback_) { signature_callback_->Cancel(); signature_callback_ = nullptr; } } QuicAsyncStatus TlsServerHandshaker::DefaultProofSourceHandle::SelectCertificate( const QuicSocketAddress& server_address, const QuicSocketAddress& client_address, const QuicConnectionId& , absl::string_view , const std::string& hostname, absl::string_view , const std::string& , std::optional<std::string> , const std::vector<uint8_t>& , const std::optional<std::vector<uint8_t>>& , const QuicSSLConfig& ) { if (!handshaker_ || !proof_source_) { QUIC_BUG(quic_bug_10341_1) << "SelectCertificate called on a detached handle"; return QUIC_FAILURE; } bool cert_matched_sni; quiche::QuicheReferenceCountedPointer<ProofSource::Chain> chain = proof_source_->GetCertChain(server_address, client_address, hostname, &cert_matched_sni); handshaker_->OnSelectCertificateDone( true, true, ProofSourceHandleCallback::LocalSSLConfig{chain.get(), QuicDelayedSSLConfig()}, absl::string_view(), cert_matched_sni); if (!handshaker_->select_cert_status().has_value()) { QUIC_BUG(quic_bug_12423_1) << "select_cert_status() has no value after a synchronous select cert"; return QUIC_SUCCESS; } return *handshaker_->select_cert_status(); } QuicAsyncStatus TlsServerHandshaker::DefaultProofSourceHandle::ComputeSignature( const QuicSocketAddress& server_address, const QuicSocketAddress& client_address, const std::string& hostname, uint16_t signature_algorithm, absl::string_view in, size_t max_signature_size) { if (!handshaker_ || !proof_source_) { QUIC_BUG(quic_bug_10341_2) << "ComputeSignature called on a detached handle"; return QUIC_FAILURE; } if (signature_callback_) { QUIC_BUG(quic_bug_10341_3) << "ComputeSignature called while pending"; return QUIC_FAILURE; } signature_callback_ = new DefaultSignatureCallback(this); proof_source_->ComputeTlsSignature( server_address, client_address, hostname, signature_algorithm, in, std::unique_ptr<DefaultSignatureCallback>(signature_callback_)); if (signature_callback_) { QUIC_DVLOG(1) << "ComputeTlsSignature is pending"; signature_callback_->set_is_sync(false); return QUIC_PENDING; } bool success = handshaker_->HasValidSignature(max_signature_size); QUIC_DVLOG(1) << "ComputeTlsSignature completed synchronously. success:" << success; return success ? QUIC_SUCCESS : QUIC_FAILURE; } TlsServerHandshaker::DecryptCallback::DecryptCallback( TlsServerHandshaker* handshaker) : handshaker_(handshaker) {} void TlsServerHandshaker::DecryptCallback::Run(std::vector<uint8_t> plaintext) { if (handshaker_ == nullptr) { return; } TlsServerHandshaker* handshaker = handshaker_; handshaker_ = nullptr; handshaker->decrypted_session_ticket_ = std::move(plaintext); const bool is_async = (handshaker->expected_ssl_error() == SSL_ERROR_PENDING_TICKET); std::optional<QuicConnectionContextSwitcher> context_switcher; if (is_async) { context_switcher.emplace(handshaker->connection_context()); } QUIC_TRACESTRING( absl::StrCat("TLS ticket decryption done. len(decrypted_ticket):", handshaker->decrypted_session_ticket_.size())); if (is_async) { handshaker->AdvanceHandshakeFromCallback(); } handshaker->ticket_decryption_callback_ = nullptr; } void TlsServerHandshaker::DecryptCallback::Cancel() { QUICHE_DCHECK(handshaker_); handshaker_ = nullptr; } TlsServerHandshaker::TlsServerHandshaker( QuicSession* session, const QuicCryptoServerConfig* crypto_config) : TlsHandshaker(this, session), QuicCryptoServerStreamBase(session), proof_source_(crypto_config->proof_source()), pre_shared_key_(crypto_config->pre_shared_key()), crypto_negotiated_params_(new QuicCryptoNegotiatedParameters), tls_connection_(crypto_config->ssl_ctx(), this, session->GetSSLConfig()), crypto_config_(crypto_config) { QUIC_DVLOG(1) << "TlsServerHandshaker: client_cert_mode initial value: " << client_cert_mode(); QUICHE_DCHECK_EQ(PROTOCOL_TLS1_3, session->connection()->version().handshake_protocol); SSL_set_accept_state(ssl()); int use_legacy_extension = 0; if (session->version().UsesLegacyTlsExtension()) { use_legacy_extension = 1; } SSL_set_quic_use_legacy_codepoint(ssl(), use_legacy_extension); if (session->connection()->context()->tracer) { tls_connection_.EnableInfoCallback(); } #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 } TlsServerHandshaker::~TlsServerHandshaker() { CancelOutstandingCallbacks(); } void TlsServerHandshaker::CancelOutstandingCallbacks() { if (proof_source_handle_) { proof_source_handle_->CloseHandle(); } if (ticket_decryption_callback_) { ticket_decryption_callback_->Cancel(); ticket_decryption_callback_ = nullptr; } } void TlsServerHandshaker::InfoCallback(int type, int value) { QuicConnectionTracer* tracer = session()->connection()->context()->tracer.get(); if (tracer == nullptr) { return; } if (type & SSL_CB_LOOP) { tracer->PrintString( absl::StrCat("SSL:ACCEPT_LOOP:", SSL_state_string_long(ssl()))); } else if (type & SSL_CB_ALERT) { const char* prefix = (type & SSL_CB_READ) ? "SSL:READ_ALERT:" : "SSL:WRITE_ALERT:"; tracer->PrintString(absl::StrCat(prefix, SSL_alert_type_string_long(value), ":", SSL_alert_desc_string_long(value))); } else if (type & SSL_CB_EXIT) { const char* prefix = (value == 1) ? "SSL:ACCEPT_EXIT_OK:" : "SSL:ACCEPT_EXIT_FAIL:"; tracer->PrintString(absl::StrCat(prefix, SSL_state_string_long(ssl()))); } else if (type & SSL_CB_HANDSHAKE_START) { tracer->PrintString( absl::StrCat("SSL:HANDSHAKE_START:", SSL_state_string_long(ssl()))); } else if (type & SSL_CB_HANDSHAKE_DONE) { tracer->PrintString( absl::StrCat("SSL:HANDSHAKE_DONE:", SSL_state_string_long(ssl()))); } else { QUIC_DLOG(INFO) << "Unknown event type " << type << ": " << SSL_state_string_long(ssl()); tracer->PrintString( absl::StrCat("SSL:unknown:", value, ":", SSL_state_string_long(ssl()))); } } std::unique_ptr<ProofSourceHandle> TlsServerHandshaker::MaybeCreateProofSourceHandle() { return std::make_unique<DefaultProofSourceHandle>(this, proof_source_); } bool TlsServerHandshaker::GetBase64SHA256ClientChannelID( std::string* ) const { return false; } void TlsServerHandshaker::SendServerConfigUpdate( const CachedNetworkParameters* ) { } bool TlsServerHandshaker::DisableResumption() { if (!can_disable_resumption_ || !session()->connection()->connected()) { return false; } tls_connection_.DisableTicketSupport(); return true; } bool TlsServerHandshaker::IsZeroRtt() const { return SSL_early_data_accepted(ssl()); } bool TlsServerHandshaker::IsResumption() const { return SSL_session_reused(ssl()); } bool TlsServerHandshaker::ResumptionAttempted() const { return ticket_received_; } bool TlsServerHandshaker::EarlyDataAttempted() const { QUIC_BUG_IF(quic_tls_early_data_attempted_too_early, !select_cert_status_.has_value()) << "EarlyDataAttempted must be called after EarlySelectCertCallback is " "started"; return early_data_attempted_; } int TlsServerHandshaker::NumServerConfigUpdateMessagesSent() const { return 0; } const CachedNetworkParameters* TlsServerHandshaker::PreviousCachedNetworkParams() const { return last_received_cached_network_params_.get(); } void TlsServerHandshaker::SetPreviousCachedNetworkParams( CachedNetworkParameters cached_network_params) { last_received_cached_network_params_ = std::make_unique<CachedNetworkParameters>(cached_network_params); } void TlsServerHandshaker::OnPacketDecrypted(EncryptionLevel level) { if (level == ENCRYPTION_HANDSHAKE && state_ < HANDSHAKE_PROCESSED) { state_ = HANDSHAKE_PROCESSED; handshaker_delegate()->DiscardOldEncryptionKey(ENCRYPTION_INITIAL); handshaker_delegate()->DiscardOldDecryptionKey(ENCRYPTION_INITIAL); } } void TlsServerHandshaker::OnHandshakeDoneReceived() { QUICHE_DCHECK(false); } void TlsServerHandshaker::OnNewTokenReceived(absl::string_view ) { QUICHE_DCHECK(false); } std::string TlsServerHandshaker::GetAddressToken( const CachedNetworkParameters* cached_network_params) const { SourceAddressTokens empty_previous_tokens; const QuicConnection* connection = session()->connection(); return crypto_config_->NewSourceAddressToken( crypto_config_->source_address_token_boxer(), empty_previous_tokens, connection->effective_peer_address().host(), connection->random_generator(), connection->clock()->WallNow(), cached_network_params); } bool TlsServerHandshaker::ValidateAddressToken(absl::string_view token) const { SourceAddressTokens tokens; HandshakeFailureReason reason = crypto_config_->ParseSourceAddressToken( crypto_config_->source_address_token_boxer(), token, tokens); if (reason != HANDSHAKE_OK) { QUIC_DLOG(WARNING) << "Failed to parse source address token: " << CryptoUtils::HandshakeFailureReasonToString(reason); return false; } auto cached_network_params = std::make_unique<CachedNetworkParameters>(); reason = crypto_config_->ValidateSourceAddressTokens( tokens, session()->connection()->effective_peer_address().host(), session()->connection()->clock()->WallNow(), cached_network_params.get()); if (reason != HANDSHAKE_OK) { QUIC_DLOG(WARNING) << "Failed to validate source address token: " << CryptoUtils::HandshakeFailureReasonToString(reason); return false; } last_received_cached_network_params_ = std::move(cached_network_params); return true; } bool TlsServerHandshaker::ShouldSendExpectCTHeader() const { return false; } bool TlsServerHandshaker::DidCertMatchSni() const { return cert_matched_sni_; } const ProofSource::Details* TlsServerHandshaker::ProofSourceDetails() const { return proof_source_details_.get(); } bool TlsServerHandshaker::ExportKeyingMaterial(absl::string_view label, absl::string_view context, size_t result_len, std::string* result) { return ExportKeyingMaterialForLabel(label, context, result_len, result); } void TlsServerHandshaker::OnConnectionClosed( const QuicConnectionCloseFrame& frame, ConnectionCloseSource source) { TlsHandshaker::OnConnectionClosed(frame.quic_error_code, source); } ssl_early_data_reason_t TlsServerHandshaker::EarlyDataReason() const { return TlsHandshaker::EarlyDataReason(); } bool TlsServerHandshaker::encryption_established() const { return encryption_established_; } bool TlsServerHandshaker::one_rtt_keys_available() const { return state_ == HANDSHAKE_CONFIRMED; } const QuicCryptoNegotiatedParameters& TlsServerHandshaker::crypto_negotiated_params() const { return *crypto_negotiated_params_; } CryptoMessageParser* TlsServerHandshaker::crypto_message_parser() { return TlsHandshaker::crypto_message_parser(); } HandshakeState TlsServerHandshaker::GetHandshakeState() const { return state_; } void TlsServerHandshaker::SetServerApplicationStateForResumption( std::unique_ptr<ApplicationState> state) { application_state_ = std::move(state); } size_t TlsServerHandshaker::BufferSizeLimitForLevel( EncryptionLevel level) const { return TlsHandshaker::BufferSizeLimitForLevel(level); } std::unique_ptr<QuicDecrypter> TlsServerHandshaker::AdvanceKeysAndCreateCurrentOneRttDecrypter() { return TlsHandshaker::AdvanceKeysAndCreateCurrentOneRttDecrypter(); } std::unique_ptr<QuicEncrypter> TlsServerHandshaker::CreateCurrentOneRttEncrypter() { return TlsHandshaker::CreateCurrentOneRttEncrypter(); } void TlsServerHandshaker::OverrideQuicConfigDefaults(QuicConfig* ) {} void TlsServerHandshaker::AdvanceHandshakeFromCallback() { QuicConnection::ScopedPacketFlusher flusher(session()->connection()); AdvanceHandshake(); if (!is_connection_closed()) { handshaker_delegate()->OnHandshakeCallbackDone(); } } bool TlsServerHandshaker::ProcessTransportParameters( const SSL_CLIENT_HELLO* client_hello, std::string* error_details) { TransportParameters client_params; const uint8_t* client_params_bytes; size_t params_bytes_len; uint16_t extension_type = TLSEXT_TYPE_quic_transport_parameters_standard; if (session()->version().UsesLegacyTlsExtension()) { extension_type = TLSEXT_TYPE_quic_transport_parameters_legacy; } if (!SSL_early_callback_ctx_extension_get(client_hello, extension_type, &client_params_bytes, &params_bytes_len)) { params_bytes_len = 0; } if (params_bytes_len == 0) { *error_details = "Client's transport parameters are missing"; return false; } std::string parse_error_details; if (!ParseTransportParameters(session()->connection()->version(), Perspective::IS_CLIENT, client_params_bytes, params_bytes_len, &client_params, &parse_error_details)) { QUICHE_DCHECK(!parse_error_details.empty()); *error_details = "Unable to parse client's transport parameters: " + parse_error_details; return false; } session()->connection()->OnTransportParametersReceived(client_params); if (client_params.legacy_version_information.has_value() && CryptoUtils::ValidateClientHelloVersion( client_params.legacy_version_information->version, session()->connection()->version(), session()->supported_versions(), error_details) != QUIC_NO_ERROR) { return false; } if (client_params.version_information.has_value() && !CryptoUtils::ValidateChosenVersion( client_params.version_information->chosen_version, session()->version(), error_details)) { QUICHE_DCHECK(!error_details->empty()); return false; } if (handshaker_delegate()->ProcessTransportParameters( client_params, false, error_details) != QUIC_NO_ERROR) { return false; } if (!ProcessAdditionalTransportParameters(client_params)) { *error_details = "Failed to process additional transport parameters"; return false; } return true; } TlsServerHandshaker::SetTransportParametersResult TlsServerHandshaker::SetTransportParameters() { SetTransportParametersResult result; QUICHE_DCHECK(!result.success); server_params_.perspective = Perspective::IS_SERVER; server_params_.legacy_version_information = TransportParameters::LegacyVersionInformation(); server_params_.legacy_version_information->supported_versions = CreateQuicVersionLabelVector(session()->supported_versions()); server_params_.legacy_version_information->version = CreateQuicVersionLabel(session()->connection()->version()); server_params_.version_information = TransportParameters::VersionInformation(); server_params_.version_information->chosen_version = CreateQuicVersionLabel(session()->version()); server_params_.version_information->other_versions = CreateQuicVersionLabelVector(session()->supported_versions()); if (!handshaker_delegate()->FillTransportParameters(&server_params_)) { return result; } session()->connection()->OnTransportParametersSent(server_params_); { std::vector<uint8_t> server_params_bytes; if (!SerializeTransportParameters(server_params_, &server_params_bytes) || SSL_set_quic_transport_params(ssl(), server_params_bytes.data(), server_params_bytes.size()) != 1) { return result; } result.quic_transport_params = std::move(server_params_bytes); } if (application_state_) { std::vector<uint8_t> early_data_context; if (!SerializeTransportParametersForTicket( server_params_, *application_state_, &early_data_context)) { QUIC_BUG(quic_bug_10341_4) << "Failed to serialize Transport Parameters for ticket."; result.early_data_context = std::vector<uint8_t>(); return result; } SSL_set_quic_early_data_context(ssl(), early_data_context.data(), early_data_context.size()); result.early_data_context = std::move(early_data_context); application_state_.reset(nullptr); } result.success = true; return result; } bool TlsServerHandshaker::TransportParametersMatch( absl::Span<const uint8_t> serialized_params) const { TransportParameters params; std::string error_details; bool parse_ok = ParseTransportParameters( session()->version(), Perspective::IS_SERVER, serialized_params.data(), serialized_params.size(), &params, &error_details); if (!parse_ok) { return false; } DegreaseTransportParameters(params); return params == server_params_; } void TlsServerHandshaker::SetWriteSecret( EncryptionLevel level, const SSL_CIPHER* cipher, absl::Span<const uint8_t> write_secret) { if (is_connection_closed()) { return; } if (level == ENCRYPTION_FORWARD_SECURE) { encryption_established_ = true; const SSL_CIPHER* ssl_cipher = SSL_get_current_cipher(ssl()); if (ssl_cipher) { crypto_negotiated_params_->cipher_suite = SSL_CIPHER_get_protocol_id(ssl_cipher); } crypto_negotiated_params_->key_exchange_group = SSL_get_curve_id(ssl()); crypto_negotiated_params_->encrypted_client_hello = SSL_ech_accepted(ssl()); } TlsHandshaker::SetWriteSecret(level, cipher, write_secret); } std::string TlsServerHandshaker::GetAcceptChValueForHostname( const std::string& ) const { return {}; } bool TlsServerHandshaker::UseAlpsNewCodepoint() const { if (!select_cert_status_.has_value()) { QUIC_BUG(quic_tls_check_alps_new_codepoint_too_early) << "UseAlpsNewCodepoint must be called after " "EarlySelectCertCallback is started"; return false; } return alps_new_codepoint_received_; } void TlsServerHandshaker::FinishHandshake() { QUICHE_DCHECK(!SSL_in_early_data(ssl())); if (!valid_alpn_received_) { QUIC_DLOG(ERROR) << "Server: handshake finished without receiving a known ALPN"; CloseConnection(QUIC_HANDSHAKE_FAILED, "Server did not receive a known ALPN"); return; } ssl_early_data_reason_t reason_code = EarlyDataReason(); QUIC_DLOG(INFO) << "Server: handshake finished. Early data reason " << reason_code << " (" << CryptoUtils::EarlyDataReasonToString(reason_code) << ")"; state_ = HANDSHAKE_CONFIRMED; handshaker_delegate()->OnTlsHandshakeComplete(); handshaker_delegate()->DiscardOldEncryptionKey(ENCRYPTION_HANDSHAKE); handshaker_delegate()->DiscardOldDecryptionKey(ENCRYPTION_HANDSHAKE); } QuicAsyncStatus TlsServerHandshaker::VerifyCertChain( const std::vector<std::string>& , std::string* , std::unique_ptr<ProofVerifyDetails>* , uint8_t* , std::unique_ptr<ProofVerifierCallback> ) { QUIC_DVLOG(1) << "VerifyCertChain returning success"; return QUIC_SUCCESS; } void TlsServerHandshaker::OnProofVerifyDetailsAvailable( const ProofVerifyDetails& ) {} ssl_private_key_result_t TlsServerHandshaker::PrivateKeySign( uint8_t* out, size_t* out_len, size_t max_out, uint16_t sig_alg, absl::string_view in) { QUICHE_DCHECK_EQ(expected_ssl_error(), SSL_ERROR_WANT_READ); QuicAsyncStatus status = proof_source_handle_->ComputeSignature( session()->connection()->self_address(), session()->connection()->peer_address(), crypto_negotiated_params_->sni, sig_alg, in, max_out); if (status == QUIC_PENDING) { set_expected_ssl_error(SSL_ERROR_WANT_PRIVATE_KEY_OPERATION); if (async_op_timer_.has_value()) { QUIC_CODE_COUNT( quic_tls_server_computing_signature_while_another_op_pending); } async_op_timer_ = QuicTimeAccumulator(); async_op_timer_->Start(now()); } return PrivateKeyComplete(out, out_len, max_out); } ssl_private_key_result_t TlsServerHandshaker::PrivateKeyComplete( uint8_t* out, size_t* out_len, size_t max_out) { if (expected_ssl_error() == SSL_ERROR_WANT_PRIVATE_KEY_OPERATION) { return ssl_private_key_retry; } const bool success = HasValidSignature(max_out); QuicConnectionStats::TlsServerOperationStats compute_signature_stats; compute_signature_stats.success = success; if (async_op_timer_.has_value()) { async_op_timer_->Stop(now()); compute_signature_stats.async_latency = async_op_timer_->GetTotalElapsedTime(); async_op_timer_.reset(); RECORD_LATENCY_IN_US("tls_server_async_compute_signature_latency_us", compute_signature_stats.async_latency, "Async compute signature latency in microseconds"); } connection_stats().tls_server_compute_signature_stats = std::move(compute_signature_stats); if (!success) { return ssl_private_key_failure; } *out_len = cert_verify_sig_.size(); memcpy(out, cert_verify_sig_.data(), *out_len); cert_verify_sig_.clear(); cert_verify_sig_.shrink_to_fit(); return ssl_private_key_success; } void TlsServerHandshaker::OnComputeSignatureDone( bool ok, bool is_sync, std::string signature, std::unique_ptr<ProofSource::Details> details) { QUIC_DVLOG(1) << "OnComputeSignatureDone. ok:" << ok << ", is_sync:" << is_sync << ", len(signature):" << signature.size(); std::optional<QuicConnectionContextSwitcher> context_switcher; if (!is_sync) { context_switcher.emplace(connection_context()); } QUIC_TRACESTRING(absl::StrCat("TLS compute signature done. ok:", ok, ", len(signature):", signature.size())); if (ok) { cert_verify_sig_ = std::move(signature); proof_source_details_ = std::move(details); } const int last_expected_ssl_error = expected_ssl_error(); set_expected_ssl_error(SSL_ERROR_WANT_READ); if (!is_sync) { QUICHE_DCHECK_EQ(last_expected_ssl_error, SSL_ERROR_WANT_PRIVATE_KEY_OPERATION); AdvanceHandshakeFromCallback(); } } bool TlsServerHandshaker::HasValidSignature(size_t max_signature_size) const { return !cert_verify_sig_.empty() && cert_verify_sig_.size() <= max_signature_size; } size_t TlsServerHandshaker::SessionTicketMaxOverhead() { QUICHE_DCHECK(proof_source_->GetTicketCrypter()); return proof_source_->GetTicketCrypter()->MaxOverhead(); } int TlsServerHandshaker::SessionTicketSeal(uint8_t* out, size_t* out_len, size_t max_out_len, absl::string_view in) { QUICHE_DCHECK(proof_source_->GetTicketCrypter()); std::vector<uint8_t> ticket = proof_source_->GetTicketCrypter()->Encrypt(in, ticket_encryption_key_); if (GetQuicReloadableFlag( quic_send_placeholder_ticket_when_encrypt_ticket_fails) && ticket.empty()) { QUIC_CODE_COUNT(quic_tls_server_handshaker_send_placeholder_ticket); const absl::string_view kTicketFailurePlaceholder = "TICKET FAILURE"; const absl::string_view kTicketWithSizeLimit = kTicketFailurePlaceholder.substr(0, max_out_len); ticket.assign(kTicketWithSizeLimit.begin(), kTicketWithSizeLimit.end()); } if (max_out_len < ticket.size()) { QUIC_BUG(quic_bug_12423_2) << "TicketCrypter returned " << ticket.size() << " bytes of ciphertext, which is larger than its max overhead of " << max_out_len; return 0; } *out_len = ticket.size(); memcpy(out, ticket.data(), ticket.size()); QUIC_CODE_COUNT(quic_tls_server_handshaker_tickets_sealed); return 1; } ssl_ticket_aead_result_t TlsServerHandshaker::SessionTicketOpen( uint8_t* out, size_t* out_len, size_t max_out_len, absl::string_view in) { QUICHE_DCHECK(proof_source_->GetTicketCrypter()); if (ignore_ticket_open_) { QUIC_CODE_COUNT(quic_tls_server_handshaker_tickets_ignored_1); return ssl_ticket_aead_ignore_ticket; } if (!ticket_decryption_callback_) { ticket_decryption_callback_ = std::make_shared<DecryptCallback>(this); proof_source_->GetTicketCrypter()->Decrypt(in, ticket_decryption_callback_); if (ticket_decryption_callback_) { QUICHE_DCHECK(!ticket_decryption_callback_->IsDone()); set_expected_ssl_error(SSL_ERROR_PENDING_TICKET); if (async_op_timer_.has_value()) { QUIC_CODE_COUNT( quic_tls_server_decrypting_ticket_while_another_op_pending); } async_op_timer_ = QuicTimeAccumulator(); async_op_timer_->Start(now()); } } if (ticket_decryption_callback_ && !ticket_decryption_callback_->IsDone()) { return ssl_ticket_aead_retry; } ssl_ticket_aead_result_t result = FinalizeSessionTicketOpen(out, out_len, max_out_len); QuicConnectionStats::TlsServerOperationStats decrypt_ticket_stats; decrypt_ticket_stats.success = (result == ssl_ticket_aead_success); if (async_op_timer_.has_value()) { async_op_timer_->Stop(now()); decrypt_ticket_stats.async_latency = async_op_timer_->GetTotalElapsedTime(); async_op_timer_.reset(); RECORD_LATENCY_IN_US("tls_server_async_decrypt_ticket_latency_us", decrypt_ticket_stats.async_latency, "Async decrypt ticket latency in microseconds"); } connection_stats().tls_server_decrypt_ticket_stats = std::move(decrypt_ticket_stats); return result; } ssl_ticket_aead_result_t TlsServerHandshaker::FinalizeSessionTicketOpen( uint8_t* out, size_t* out_len, size_t max_out_len) { ticket_decryption_callback_ = nullptr; set_expected_ssl_error(SSL_ERROR_WANT_READ); if (decrypted_session_ticket_.empty()) { QUIC_DLOG(ERROR) << "Session ticket decryption failed; ignoring ticket"; QUIC_CODE_COUNT(quic_tls_server_handshaker_tickets_ignored_2); return ssl_ticket_aead_ignore_ticket; } if (max_out_len < decrypted_session_ticket_.size()) { return ssl_ticket_aead_error; } memcpy(out, decrypted_session_ticket_.data(), decrypted_session_ticket_.size()); *out_len = decrypted_session_ticket_.size(); QUIC_CODE_COUNT(quic_tls_server_handshaker_tickets_opened); return ssl_ticket_aead_success; } ssl_select_cert_result_t TlsServerHandshaker::EarlySelectCertCallback( const SSL_CLIENT_HELLO* client_hello) { if (select_cert_status_.has_value()) { QUIC_DVLOG(1) << "EarlySelectCertCallback called to continue handshake, " "returning directly. success:" << (*select_cert_status_ == QUIC_SUCCESS); return (*select_cert_status_ == QUIC_SUCCESS) ? ssl_select_cert_success : ssl_select_cert_error; } select_cert_status_ = QUIC_PENDING; proof_source_handle_ = MaybeCreateProofSourceHandle(); if (!pre_shared_key_.empty()) { QUIC_BUG(quic_bug_10341_6) << "QUIC server pre-shared keys not yet supported with TLS"; set_extra_error_details("select_cert_error: pre-shared keys not supported"); return ssl_select_cert_error; } { const uint8_t* unused_extension_bytes; size_t unused_extension_len; ticket_received_ = SSL_early_callback_ctx_extension_get( client_hello, TLSEXT_TYPE_pre_shared_key, &unused_extension_bytes, &unused_extension_len); early_data_attempted_ = SSL_early_callback_ctx_extension_get( client_hello, TLSEXT_TYPE_early_data, &unused_extension_bytes, &unused_extension_len); int use_alps_new_codepoint = 0; #if BORINGSSL_API_VERSION >= 27 if (GetQuicReloadableFlag(quic_gfe_allow_alps_new_codepoint)) { QUIC_RELOADABLE_FLAG_COUNT(quic_gfe_allow_alps_new_codepoint); alps_new_codepoint_received_ = SSL_early_callback_ctx_extension_get( client_hello, TLSEXT_TYPE_application_settings, &unused_extension_bytes, &unused_extension_len); if (alps_new_codepoint_received_) { QUIC_CODE_COUNT(quic_gfe_alps_use_new_codepoint); use_alps_new_codepoint = 1; } QUIC_DLOG(INFO) << "ALPS use new codepoint: " << use_alps_new_codepoint; SSL_set_alps_use_new_codepoint(ssl(), use_alps_new_codepoint); } #endif if (use_alps_new_codepoint == 0) { QUIC_CODE_COUNT(quic_gfe_alps_use_old_codepoint); } } const char* hostname = SSL_get_servername(ssl(), TLSEXT_NAMETYPE_host_name); if (hostname) { crypto_negotiated_params_->sni = QuicHostnameUtils::NormalizeHostname(hostname); if (!ValidateHostname(hostname)) { if (GetQuicReloadableFlag(quic_new_error_code_for_invalid_hostname)) { QUIC_RELOADABLE_FLAG_COUNT(quic_new_error_code_for_invalid_hostname); CloseConnection(QUIC_HANDSHAKE_FAILED_INVALID_HOSTNAME, "invalid hostname"); } else { set_extra_error_details("select_cert_error: invalid hostname"); } return ssl_select_cert_error; } if (hostname != crypto_negotiated_params_->sni) { QUIC_CODE_COUNT(quic_tls_server_hostname_diff); QUIC_LOG_EVERY_N_SEC(WARNING, 300) << "Raw and normalized hostnames differ, but both are valid SNIs. " "raw hostname:" << hostname << ", normalized:" << crypto_negotiated_params_->sni; } else { QUIC_CODE_COUNT(quic_tls_server_hostname_same); } } else { QUIC_LOG(INFO) << "No hostname indicated in SNI"; } std::string error_details; if (!ProcessTransportParameters(client_hello, &error_details)) { CloseConnection(QUIC_HANDSHAKE_FAILED, error_details); return ssl_select_cert_error; } OverrideQuicConfigDefaults(session()->config()); session()->OnConfigNegotiated(); auto set_transport_params_result = SetTransportParameters(); if (!set_transport_params_result.success) { set_extra_error_details("select_cert_error: set tp failure"); return ssl_select_cert_error; } bssl::UniquePtr<uint8_t> ssl_capabilities; size_t ssl_capabilities_len = 0; absl::string_view ssl_capabilities_view; if (CryptoUtils::GetSSLCapabilities(ssl(), &ssl_capabilities, &ssl_capabilities_len)) { ssl_capabilities_view = absl::string_view(reinterpret_cast<const char*>(ssl_capabilities.get()), ssl_capabilities_len); } SetApplicationSettingsResult alps_result = SetApplicationSettings(AlpnForVersion(session()->version())); if (!alps_result.success) { set_extra_error_details("select_cert_error: set alps failure"); return ssl_select_cert_error; } if (!session()->connection()->connected()) { select_cert_status_ = QUIC_FAILURE; return ssl_select_cert_error; } can_disable_resumption_ = false; const QuicAsyncStatus status = proof_source_handle_->SelectCertificate( session()->connection()->self_address().Normalized(), session()->connection()->peer_address().Normalized(), session()->connection()->GetOriginalDestinationConnectionId(), ssl_capabilities_view, crypto_negotiated_params_->sni, absl::string_view( reinterpret_cast<const char*>(client_hello->client_hello), client_hello->client_hello_len), AlpnForVersion(session()->version()), std::move(alps_result.alps_buffer), set_transport_params_result.quic_transport_params, set_transport_params_result.early_data_context, tls_connection_.ssl_config()); QUICHE_DCHECK_EQ(status, *select_cert_status()); if (status == QUIC_PENDING) { set_expected_ssl_error(SSL_ERROR_PENDING_CERTIFICATE); if (async_op_timer_.has_value()) { QUIC_CODE_COUNT(quic_tls_server_selecting_cert_while_another_op_pending); } async_op_timer_ = QuicTimeAccumulator(); async_op_timer_->Start(now()); return ssl_select_cert_retry; } if (status == QUIC_FAILURE) { set_extra_error_details("select_cert_error: proof_source_handle failure"); return ssl_select_cert_error; } return ssl_select_cert_success; } void TlsServerHandshaker::OnSelectCertificateDone( bool ok, bool is_sync, SSLConfig ssl_config, absl::string_view ticket_encryption_key, bool cert_matched_sni) { QUIC_DVLOG(1) << "OnSelectCertificateDone. ok:" << ok << ", is_sync:" << is_sync << ", len(ticket_encryption_key):" << ticket_encryption_key.size(); std::optional<QuicConnectionContextSwitcher> context_switcher; if (!is_sync) { context_switcher.emplace(connection_context()); } QUIC_TRACESTRING(absl::StrCat( "TLS select certificate done: ok:", ok, ", len(ticket_encryption_key):", ticket_encryption_key.size())); ticket_encryption_key_ = std::string(ticket_encryption_key); select_cert_status_ = QUIC_FAILURE; cert_matched_sni_ = cert_matched_sni; const QuicDelayedSSLConfig& delayed_ssl_config = absl::visit( [](const auto& config) { return config.delayed_ssl_config; }, ssl_config); if (delayed_ssl_config.quic_transport_parameters.has_value()) { if (TransportParametersMatch( absl::MakeSpan(*delayed_ssl_config.quic_transport_parameters))) { if (SSL_set_quic_transport_params( ssl(), delayed_ssl_config.quic_transport_parameters->data(), delayed_ssl_config.quic_transport_parameters->size()) != 1) { QUIC_DVLOG(1) << "SSL_set_quic_transport_params override failed"; } } else { QUIC_DVLOG(1) << "QUIC transport parameters mismatch with ProofSourceHandle"; } } if (delayed_ssl_config.client_cert_mode.has_value()) { tls_connection_.SetClientCertMode(*delayed_ssl_config.client_cert_mode); QUIC_DVLOG(1) << "client_cert_mode after cert selection: " << client_cert_mode(); } if (ok) { if (auto* local_config = absl::get_if<LocalSSLConfig>(&ssl_config); local_config != nullptr) { if (local_config->chain && !local_config->chain->certs.empty()) { tls_connection_.SetCertChain( local_config->chain->ToCryptoBuffers().value); select_cert_status_ = QUIC_SUCCESS; } else { QUIC_DLOG(ERROR) << "No certs provided for host '" << crypto_negotiated_params_->sni << "', server_address:" << session()->connection()->self_address() << ", client_address:" << session()->connection()->peer_address(); } } else if (auto* hints_config = absl::get_if<HintsSSLConfig>(&ssl_config); hints_config != nullptr) { if (hints_config->configure_ssl) { if (const absl::Status status = tls_connection_.ConfigureSSL( std::move(hints_config->configure_ssl)); !status.ok()) { QUIC_CODE_COUNT(quic_tls_server_set_handshake_hints_failed); QUIC_DVLOG(1) << "SSL_set_handshake_hints failed: " << status; } select_cert_status_ = QUIC_SUCCESS; } } else { QUIC_DLOG(FATAL) << "Neither branch hit"; } } QuicConnectionStats::TlsServerOperationStats select_cert_stats; select_cert_stats.success = (select_cert_status_ == QUIC_SUCCESS); if (!select_cert_stats.success) { set_extra_error_details( "select_cert_error: proof_source_handle async failure"); } QUICHE_DCHECK_NE(is_sync, async_op_timer_.has_value()); if (async_op_timer_.has_value()) { async_op_timer_->Stop(now()); select_cert_stats.async_latency = async_op_timer_->GetTotalElapsedTime(); async_op_timer_.reset(); RECORD_LATENCY_IN_US("tls_server_async_select_cert_latency_us", select_cert_stats.async_latency, "Async select cert latency in microseconds"); } connection_stats().tls_server_select_cert_stats = std::move(select_cert_stats); const int last_expected_ssl_error = expected_ssl_error(); set_expected_ssl_error(SSL_ERROR_WANT_READ); if (!is_sync) { QUICHE_DCHECK_EQ(last_expected_ssl_error, SSL_ERROR_PENDING_CERTIFICATE); AdvanceHandshakeFromCallback(); } } bool TlsServerHandshaker::WillNotCallComputeSignature() const { return SSL_can_release_private_key(ssl()); } bool TlsServerHandshaker::ValidateHostname(const std::string& hostname) const { if (!QuicHostnameUtils::IsValidSNI(hostname)) { QUIC_DLOG(ERROR) << "Invalid SNI provided: \"" << hostname << "\""; return false; } return true; } int TlsServerHandshaker::TlsExtServernameCallback(int* ) { return SSL_TLSEXT_ERR_OK; } int TlsServerHandshaker::SelectAlpn(const uint8_t** out, uint8_t* out_len, const uint8_t* in, unsigned in_len) { *out_len = 0; *out = nullptr; if (in_len == 0) { QUIC_DLOG(ERROR) << "No ALPN provided by client"; return SSL_TLSEXT_ERR_NOACK; } CBS all_alpns; CBS_init(&all_alpns, in, in_len); std::vector<absl::string_view> alpns; while (CBS_len(&all_alpns) > 0) { CBS alpn; if (!CBS_get_u8_length_prefixed(&all_alpns, &alpn)) { QUIC_DLOG(ERROR) << "Failed to parse ALPN length"; return SSL_TLSEXT_ERR_NOACK; } const size_t alpn_length = CBS_len(&alpn); if (alpn_length == 0) { QUIC_DLOG(ERROR) << "Received invalid zero-length ALPN"; return SSL_TLSEXT_ERR_NOACK; } alpns.emplace_back(reinterpret_cast<const char*>(CBS_data(&alpn)), alpn_length); } auto selected_alpn = session()->SelectAlpn(alpns); if (selected_alpn == alpns.end()) { QUIC_DLOG(ERROR) << "No known ALPN provided by client"; return SSL_TLSEXT_ERR_NOACK; } session()->OnAlpnSelected(*selected_alpn); valid_alpn_received_ = true; *out_len = selected_alpn->size(); *out = reinterpret_cast<const uint8_t*>(selected_alpn->data()); return SSL_TLSEXT_ERR_OK; } TlsServerHandshaker::SetApplicationSettingsResult TlsServerHandshaker::SetApplicationSettings(absl::string_view alpn) { TlsServerHandshaker::SetApplicationSettingsResult result; const std::string& hostname = crypto_negotiated_params_->sni; std::string accept_ch_value = GetAcceptChValueForHostname(hostname); std::string origin = absl::StrCat("https: uint16_t port = session()->self_address().port(); if (port != kDefaultPort) { QUIC_CODE_COUNT(quic_server_alps_non_default_port); absl::StrAppend(&origin, ":", port); } if (!accept_ch_value.empty()) { AcceptChFrame frame{{{std::move(origin), std::move(accept_ch_value)}}}; result.alps_buffer = HttpEncoder::SerializeAcceptChFrame(frame); } const std::string& alps = result.alps_buffer; if (SSL_add_application_settings( ssl(), reinterpret_cast<const uint8_t*>(alpn.data()), alpn.size(), reinterpret_cast<const uint8_t*>(alps.data()), alps.size()) != 1) { QUIC_DLOG(ERROR) << "Failed to enable ALPS"; result.success = false; } else { result.success = true; } return result; } SSL* TlsServerHandshaker::GetSsl() const { return ssl(); } bool TlsServerHandshaker::IsCryptoFrameExpectedForEncryptionLevel( EncryptionLevel level) const { return level != ENCRYPTION_ZERO_RTT; } EncryptionLevel TlsServerHandshaker::GetEncryptionLevelToSendCryptoDataOfSpace( PacketNumberSpace space) const { 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; } } }
#include "quiche/quic/core/tls_server_handshaker.h" #include <algorithm> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/certificate_util.h" #include "quiche/quic/core/crypto/client_proof_source.h" #include "quiche/quic/core/crypto/proof_source.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_crypto_client_stream.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/core/tls_client_handshaker.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/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/fake_proof_source_handle.h" #include "quiche/quic/test_tools/quic_config_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simple_session_cache.h" #include "quiche/quic/test_tools/test_certificates.h" #include "quiche/quic/test_tools/test_ticket_crypter.h" namespace quic { class QuicConnection; class QuicStream; } using testing::_; using testing::HasSubstr; using testing::NiceMock; using testing::Return; namespace quic { namespace test { namespace { const char kServerHostname[] = "test.example.com"; const uint16_t kServerPort = 443; struct TestParams { ParsedQuicVersion version; bool disable_resumption; }; std::string PrintToString(const TestParams& p) { return absl::StrCat( ParsedQuicVersionToString(p.version), "_", (p.disable_resumption ? "ResumptionDisabled" : "ResumptionEnabled")); } std::vector<TestParams> GetTestParams() { std::vector<TestParams> params; for (const auto& version : AllSupportedVersionsWithTls()) { for (bool disable_resumption : {false, true}) { params.push_back(TestParams{version, disable_resumption}); } } return params; } class TestTlsServerHandshaker : public TlsServerHandshaker { public: static constexpr TransportParameters::TransportParameterId kFailHandshakeParam{0xFFEACA}; TestTlsServerHandshaker(QuicSession* session, const QuicCryptoServerConfig* crypto_config) : TlsServerHandshaker(session, crypto_config), proof_source_(crypto_config->proof_source()) { ON_CALL(*this, MaybeCreateProofSourceHandle()) .WillByDefault(testing::Invoke( this, &TestTlsServerHandshaker::RealMaybeCreateProofSourceHandle)); ON_CALL(*this, OverrideQuicConfigDefaults(_)) .WillByDefault(testing::Invoke( this, &TestTlsServerHandshaker::RealOverrideQuicConfigDefaults)); } MOCK_METHOD(std::unique_ptr<ProofSourceHandle>, MaybeCreateProofSourceHandle, (), (override)); MOCK_METHOD(void, OverrideQuicConfigDefaults, (QuicConfig * config), (override)); void SetupProofSourceHandle( FakeProofSourceHandle::Action select_cert_action, FakeProofSourceHandle::Action compute_signature_action, QuicDelayedSSLConfig dealyed_ssl_config = QuicDelayedSSLConfig()) { EXPECT_CALL(*this, MaybeCreateProofSourceHandle()) .WillOnce( testing::Invoke([this, select_cert_action, compute_signature_action, dealyed_ssl_config]() { auto handle = std::make_unique<FakeProofSourceHandle>( proof_source_, this, select_cert_action, compute_signature_action, dealyed_ssl_config); fake_proof_source_handle_ = handle.get(); return handle; })); } FakeProofSourceHandle* fake_proof_source_handle() { return fake_proof_source_handle_; } bool received_client_cert() const { return received_client_cert_; } using TlsServerHandshaker::AdvanceHandshake; using TlsServerHandshaker::expected_ssl_error; protected: QuicAsyncStatus 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) override { received_client_cert_ = true; return TlsServerHandshaker::VerifyCertChain(certs, error_details, details, out_alert, std::move(callback)); } bool ProcessAdditionalTransportParameters( const TransportParameters& params) override { return !params.custom_parameters.contains(kFailHandshakeParam); } private: std::unique_ptr<ProofSourceHandle> RealMaybeCreateProofSourceHandle() { return TlsServerHandshaker::MaybeCreateProofSourceHandle(); } void RealOverrideQuicConfigDefaults(QuicConfig* config) { return TlsServerHandshaker::OverrideQuicConfigDefaults(config); } FakeProofSourceHandle* fake_proof_source_handle_ = nullptr; ProofSource* proof_source_ = nullptr; bool received_client_cert_ = false; }; class TlsServerHandshakerTestSession : public TestQuicSpdyServerSession { public: using TestQuicSpdyServerSession::TestQuicSpdyServerSession; std::unique_ptr<QuicCryptoServerStreamBase> CreateQuicCryptoServerStream( const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* ) override { if (connection()->version().handshake_protocol == PROTOCOL_TLS1_3) { return std::make_unique<NiceMock<TestTlsServerHandshaker>>(this, crypto_config); } QUICHE_CHECK(false) << "Unsupported handshake protocol: " << connection()->version().handshake_protocol; return nullptr; } }; class TlsServerHandshakerTest : public QuicTestWithParam<TestParams> { public: TlsServerHandshakerTest() : server_compressed_certs_cache_( QuicCompressedCertsCache::kQuicCompressedCertsCacheSize), server_id_(kServerHostname, kServerPort), supported_versions_({GetParam().version}) { SetQuicFlag(quic_disable_server_tls_resumption, GetParam().disable_resumption); client_crypto_config_ = std::make_unique<QuicCryptoClientConfig>( crypto_test_utils::ProofVerifierForTesting(), std::make_unique<test::SimpleSessionCache>()); InitializeServerConfig(); InitializeServer(); InitializeFakeClient(); } ~TlsServerHandshakerTest() override { server_session_.reset(); client_session_.reset(); helpers_.clear(); alarm_factories_.clear(); } void InitializeServerConfig() { auto ticket_crypter = std::make_unique<TestTicketCrypter>(); ticket_crypter_ = ticket_crypter.get(); auto proof_source = std::make_unique<FakeProofSource>(); proof_source_ = proof_source.get(); proof_source_->SetTicketCrypter(std::move(ticket_crypter)); server_crypto_config_ = std::make_unique<QuicCryptoServerConfig>( QuicCryptoServerConfig::TESTING, QuicRandom::GetInstance(), std::move(proof_source), KeyExchangeSource::Default()); } void InitializeServerConfigWithFailingProofSource() { server_crypto_config_ = std::make_unique<QuicCryptoServerConfig>( QuicCryptoServerConfig::TESTING, QuicRandom::GetInstance(), std::make_unique<FailingProofSource>(), KeyExchangeSource::Default()); } void CreateTlsServerHandshakerTestSession(MockQuicConnectionHelper* helper, MockAlarmFactory* alarm_factory) { server_connection_ = new PacketSavingConnection( helper, alarm_factory, Perspective::IS_SERVER, ParsedVersionOfIndex(supported_versions_, 0)); TlsServerHandshakerTestSession* server_session = new TlsServerHandshakerTestSession( server_connection_, DefaultQuicConfig(), supported_versions_, server_crypto_config_.get(), &server_compressed_certs_cache_); server_session->set_client_cert_mode(initial_client_cert_mode_); server_session->Initialize(); server_connection_->AdvanceTime(QuicTime::Delta::FromSeconds(100000)); QUICHE_CHECK(server_session); server_session_.reset(server_session); } void InitializeServerWithFakeProofSourceHandle() { helpers_.push_back(std::make_unique<NiceMock<MockQuicConnectionHelper>>()); alarm_factories_.push_back(std::make_unique<MockAlarmFactory>()); CreateTlsServerHandshakerTestSession(helpers_.back().get(), alarm_factories_.back().get()); server_handshaker_ = static_cast<NiceMock<TestTlsServerHandshaker>*>( server_session_->GetMutableCryptoStream()); 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_.get()); } 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_.get(), &server_compressed_certs_cache_, &server_connection_, &server_session); QUICHE_CHECK(server_session); server_session_.reset(server_session); server_handshaker_ = nullptr; 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_.get()); } 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_.get(), &client_connection_, &client_session); const std::string default_alpn = AlpnForVersion(client_connection_->version()); ON_CALL(*client_session, GetAlpnsToOffer()) .WillByDefault(Return(std::vector<std::string>({default_alpn}))); QUICHE_CHECK(client_session); client_session_.reset(client_session); moved_messages_counts_ = {0, 0}; } void CompleteCryptoHandshake() { while (!client_stream()->one_rtt_keys_available() || !server_stream()->one_rtt_keys_available()) { auto previous_moved_messages_counts = moved_messages_counts_; AdvanceHandshakeWithFakeClient(); ASSERT_NE(previous_moved_messages_counts, moved_messages_counts_); } } 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()); if (moved_messages_counts_.first == 0) { client_stream()->CryptoConnect(); } moved_messages_counts_ = crypto_test_utils::AdvanceHandshake( client_connection_, client_stream(), moved_messages_counts_.first, server_connection_, server_stream(), moved_messages_counts_.second); } void ExpectHandshakeSuccessful() { EXPECT_TRUE(client_stream()->one_rtt_keys_available()); EXPECT_TRUE(client_stream()->encryption_established()); EXPECT_TRUE(server_stream()->one_rtt_keys_available()); EXPECT_TRUE(server_stream()->encryption_established()); EXPECT_EQ(HANDSHAKE_COMPLETE, client_stream()->GetHandshakeState()); EXPECT_EQ(HANDSHAKE_CONFIRMED, server_stream()->GetHandshakeState()); const auto& client_crypto_params = client_stream()->crypto_negotiated_params(); const auto& server_crypto_params = server_stream()->crypto_negotiated_params(); EXPECT_NE(0, client_crypto_params.cipher_suite); EXPECT_NE(0, client_crypto_params.key_exchange_group); EXPECT_NE(0, client_crypto_params.peer_signature_algorithm); EXPECT_EQ(client_crypto_params.cipher_suite, server_crypto_params.cipher_suite); EXPECT_EQ(client_crypto_params.key_exchange_group, server_crypto_params.key_exchange_group); EXPECT_EQ(0, server_crypto_params.peer_signature_algorithm); } FakeProofSourceHandle::SelectCertArgs last_select_cert_args() const { QUICHE_CHECK(server_handshaker_ && server_handshaker_->fake_proof_source_handle()); QUICHE_CHECK(!server_handshaker_->fake_proof_source_handle() ->all_select_cert_args() .empty()); return server_handshaker_->fake_proof_source_handle() ->all_select_cert_args() .back(); } FakeProofSourceHandle::ComputeSignatureArgs last_compute_signature_args() const { QUICHE_CHECK(server_handshaker_ && server_handshaker_->fake_proof_source_handle()); QUICHE_CHECK(!server_handshaker_->fake_proof_source_handle() ->all_compute_signature_args() .empty()); return server_handshaker_->fake_proof_source_handle() ->all_compute_signature_args() .back(); } protected: bool SetupClientCert() { auto client_proof_source = std::make_unique<DefaultClientProofSource>(); CertificatePrivateKey client_cert_key( MakeKeyPairForSelfSignedCertificate()); 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(*client_cert_key.private_key(), options); quiche::QuicheReferenceCountedPointer<ClientProofSource::Chain> client_cert_chain(new ClientProofSource::Chain({der_cert})); if (!client_proof_source->AddCertAndKey({"*"}, client_cert_chain, std::move(client_cert_key))) { return false; } client_crypto_config_->set_proof_source(std::move(client_proof_source)); return true; } std::vector<std::unique_ptr<MockQuicConnectionHelper>> helpers_; std::vector<std::unique_ptr<MockAlarmFactory>> alarm_factories_; PacketSavingConnection* server_connection_; std::unique_ptr<TestQuicSpdyServerSession> server_session_; NiceMock<TestTlsServerHandshaker>* server_handshaker_ = nullptr; TestTicketCrypter* ticket_crypter_; FakeProofSource* proof_source_; std::unique_ptr<QuicCryptoServerConfig> server_crypto_config_; QuicCompressedCertsCache server_compressed_certs_cache_; QuicServerId server_id_; ClientCertMode initial_client_cert_mode_ = ClientCertMode::kNone; PacketSavingConnection* client_connection_; std::unique_ptr<QuicCryptoClientConfig> client_crypto_config_; std::unique_ptr<TestQuicSpdyClientSession> client_session_; crypto_test_utils::FakeClientOptions client_options_; std::pair<size_t, size_t> moved_messages_counts_ = {0, 0}; ParsedQuicVersionVector supported_versions_; }; INSTANTIATE_TEST_SUITE_P(TlsServerHandshakerTests, TlsServerHandshakerTest, ::testing::ValuesIn(GetTestParams()), ::testing::PrintToStringParamName()); TEST_P(TlsServerHandshakerTest, NotInitiallyConected) { EXPECT_FALSE(server_stream()->encryption_established()); EXPECT_FALSE(server_stream()->one_rtt_keys_available()); } TEST_P(TlsServerHandshakerTest, ConnectedAfterTlsHandshake) { CompleteCryptoHandshake(); EXPECT_EQ(PROTOCOL_TLS1_3, server_stream()->handshake_protocol()); ExpectHandshakeSuccessful(); } TEST_P(TlsServerHandshakerTest, HandshakeWithAsyncSelectCertSuccess) { InitializeServerWithFakeProofSourceHandle(); server_handshaker_->SetupProofSourceHandle( FakeProofSourceHandle::Action::DELEGATE_ASYNC, FakeProofSourceHandle::Action:: DELEGATE_SYNC); EXPECT_CALL(*client_connection_, CloseConnection(_, _, _)).Times(0); EXPECT_CALL(*server_connection_, CloseConnection(_, _, _)).Times(0); AdvanceHandshakeWithFakeClient(); ASSERT_TRUE( server_handshaker_->fake_proof_source_handle()->HasPendingOperation()); server_handshaker_->fake_proof_source_handle()->CompletePendingOperation(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); } TEST_P(TlsServerHandshakerTest, HandshakeWithAsyncSelectCertFailure) { InitializeServerWithFakeProofSourceHandle(); server_handshaker_->SetupProofSourceHandle( FakeProofSourceHandle::Action::FAIL_ASYNC, FakeProofSourceHandle::Action:: DELEGATE_SYNC); AdvanceHandshakeWithFakeClient(); ASSERT_TRUE( server_handshaker_->fake_proof_source_handle()->HasPendingOperation()); server_handshaker_->fake_proof_source_handle()->CompletePendingOperation(); EXPECT_EQ(moved_messages_counts_.second, 0u); EXPECT_EQ(server_handshaker_->extra_error_details(), "select_cert_error: proof_source_handle async failure"); } TEST_P(TlsServerHandshakerTest, HandshakeWithAsyncSelectCertAndSignature) { InitializeServerWithFakeProofSourceHandle(); server_handshaker_->SetupProofSourceHandle( FakeProofSourceHandle::Action::DELEGATE_ASYNC, FakeProofSourceHandle::Action:: DELEGATE_ASYNC); EXPECT_CALL(*client_connection_, CloseConnection(_, _, _)).Times(0); EXPECT_CALL(*server_connection_, CloseConnection(_, _, _)).Times(0); AdvanceHandshakeWithFakeClient(); ASSERT_TRUE( server_handshaker_->fake_proof_source_handle()->HasPendingOperation()); EXPECT_EQ(server_handshaker_->expected_ssl_error(), SSL_ERROR_PENDING_CERTIFICATE); server_handshaker_->fake_proof_source_handle()->CompletePendingOperation(); ASSERT_TRUE( server_handshaker_->fake_proof_source_handle()->HasPendingOperation()); EXPECT_EQ(server_handshaker_->expected_ssl_error(), SSL_ERROR_WANT_PRIVATE_KEY_OPERATION); server_handshaker_->fake_proof_source_handle()->CompletePendingOperation(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); } TEST_P(TlsServerHandshakerTest, HandshakeWithAsyncSignature) { EXPECT_CALL(*client_connection_, CloseConnection(_, _, _)).Times(0); EXPECT_CALL(*server_connection_, CloseConnection(_, _, _)).Times(0); proof_source_->Activate(); AdvanceHandshakeWithFakeClient(); ASSERT_EQ(proof_source_->NumPendingCallbacks(), 1); proof_source_->InvokePendingCallback(0); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); } TEST_P(TlsServerHandshakerTest, CancelPendingSelectCert) { InitializeServerWithFakeProofSourceHandle(); server_handshaker_->SetupProofSourceHandle( FakeProofSourceHandle::Action::DELEGATE_ASYNC, FakeProofSourceHandle::Action:: DELEGATE_SYNC); EXPECT_CALL(*client_connection_, CloseConnection(_, _, _)).Times(0); EXPECT_CALL(*server_connection_, CloseConnection(_, _, _)).Times(0); AdvanceHandshakeWithFakeClient(); ASSERT_TRUE( server_handshaker_->fake_proof_source_handle()->HasPendingOperation()); server_handshaker_->CancelOutstandingCallbacks(); ASSERT_FALSE( server_handshaker_->fake_proof_source_handle()->HasPendingOperation()); server_handshaker_->fake_proof_source_handle()->CompletePendingOperation(); } TEST_P(TlsServerHandshakerTest, CancelPendingSignature) { EXPECT_CALL(*client_connection_, CloseConnection(_, _, _)).Times(0); EXPECT_CALL(*server_connection_, CloseConnection(_, _, _)).Times(0); proof_source_->Activate(); AdvanceHandshakeWithFakeClient(); ASSERT_EQ(proof_source_->NumPendingCallbacks(), 1); server_session_ = nullptr; proof_source_->InvokePendingCallback(0); } TEST_P(TlsServerHandshakerTest, ExtractSNI) { CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_EQ(server_stream()->crypto_negotiated_params().sni, "test.example.com"); } TEST_P(TlsServerHandshakerTest, ServerConnectionIdPassedToSelectCert) { InitializeServerWithFakeProofSourceHandle(); server_session_->set_early_data_enabled(false); server_handshaker_->SetupProofSourceHandle( FakeProofSourceHandle::Action::DELEGATE_SYNC, FakeProofSourceHandle::Action:: DELEGATE_SYNC); InitializeFakeClient(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_EQ(last_select_cert_args().original_connection_id, TestConnectionId()); } TEST_P(TlsServerHandshakerTest, HostnameForCertSelectionAndComputeSignature) { server_id_ = QuicServerId("tEsT.EXAMPLE.CoM", kServerPort); InitializeServerWithFakeProofSourceHandle(); server_handshaker_->SetupProofSourceHandle( FakeProofSourceHandle::Action::DELEGATE_SYNC, FakeProofSourceHandle::Action:: DELEGATE_SYNC); InitializeFakeClient(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_EQ(server_stream()->crypto_negotiated_params().sni, "test.example.com"); EXPECT_EQ(last_select_cert_args().hostname, "test.example.com"); EXPECT_EQ(last_compute_signature_args().hostname, "test.example.com"); } TEST_P(TlsServerHandshakerTest, SSLConfigForCertSelection) { InitializeServerWithFakeProofSourceHandle(); server_session_->set_early_data_enabled(false); server_handshaker_->SetupProofSourceHandle( FakeProofSourceHandle::Action::DELEGATE_SYNC, FakeProofSourceHandle::Action:: DELEGATE_SYNC); InitializeFakeClient(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_FALSE(last_select_cert_args().ssl_config.early_data_enabled); } TEST_P(TlsServerHandshakerTest, ConnectionClosedOnTlsError) { EXPECT_CALL(*server_connection_, CloseConnection(QUIC_HANDSHAKE_FAILED, _, _, _)); char bogus_handshake_message[] = { 1, 0, 0, 0, }; QuicConnection::ScopedPacketFlusher flusher(server_connection_); server_stream()->crypto_message_parser()->ProcessInput( absl::string_view(bogus_handshake_message, ABSL_ARRAYSIZE(bogus_handshake_message)), ENCRYPTION_INITIAL); EXPECT_FALSE(server_stream()->one_rtt_keys_available()); } TEST_P(TlsServerHandshakerTest, ClientSendingBadALPN) { const std::string kTestBadClientAlpn = "bad-client-alpn"; EXPECT_CALL(*client_session_, GetAlpnsToOffer()) .WillOnce(Return(std::vector<std::string>({kTestBadClientAlpn}))); 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"), _)); AdvanceHandshakeWithFakeClient(); EXPECT_FALSE(client_stream()->one_rtt_keys_available()); EXPECT_FALSE(client_stream()->encryption_established()); EXPECT_FALSE(server_stream()->one_rtt_keys_available()); EXPECT_FALSE(server_stream()->encryption_established()); } TEST_P(TlsServerHandshakerTest, CustomALPNNegotiation) { EXPECT_CALL(*client_connection_, CloseConnection(_, _, _)).Times(0); EXPECT_CALL(*server_connection_, CloseConnection(_, _, _)).Times(0); const std::string kTestAlpn = "A Custom ALPN Value"; const std::vector<std::string> kTestAlpns( {"foo", "bar", kTestAlpn, "something else"}); EXPECT_CALL(*client_session_, GetAlpnsToOffer()) .WillRepeatedly(Return(kTestAlpns)); EXPECT_CALL(*server_session_, SelectAlpn(_)) .WillOnce( [kTestAlpn, kTestAlpns](const std::vector<absl::string_view>& alpns) { EXPECT_THAT(alpns, testing::ElementsAreArray(kTestAlpns)); return std::find(alpns.cbegin(), alpns.cend(), kTestAlpn); }); EXPECT_CALL(*client_session_, OnAlpnSelected(absl::string_view(kTestAlpn))); EXPECT_CALL(*server_session_, OnAlpnSelected(absl::string_view(kTestAlpn))); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); } TEST_P(TlsServerHandshakerTest, RejectInvalidSNI) { SetQuicFlag(quic_client_allow_invalid_sni_for_test, true); server_id_ = QuicServerId("invalid!.example.com", kServerPort); InitializeFakeClient(); AdvanceHandshakeWithFakeClient(); EXPECT_FALSE(server_stream()->encryption_established()); EXPECT_FALSE(server_stream()->one_rtt_keys_available()); } TEST_P(TlsServerHandshakerTest, Resumption) { InitializeFakeClient(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_FALSE(client_stream()->IsResumption()); EXPECT_FALSE(server_stream()->IsResumption()); EXPECT_FALSE(server_stream()->ResumptionAttempted()); InitializeServer(); InitializeFakeClient(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_NE(client_stream()->IsResumption(), GetParam().disable_resumption); EXPECT_NE(server_stream()->IsResumption(), GetParam().disable_resumption); EXPECT_NE(server_stream()->ResumptionAttempted(), GetParam().disable_resumption); } TEST_P(TlsServerHandshakerTest, ResumptionWithAsyncDecryptCallback) { InitializeFakeClient(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); ticket_crypter_->SetRunCallbacksAsync(true); InitializeServer(); InitializeFakeClient(); AdvanceHandshakeWithFakeClient(); if (GetParam().disable_resumption) { ASSERT_EQ(ticket_crypter_->NumPendingCallbacks(), 0u); return; } ASSERT_EQ(ticket_crypter_->NumPendingCallbacks(), 1u); ticket_crypter_->RunPendingCallback(0); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_TRUE(client_stream()->IsResumption()); EXPECT_TRUE(server_stream()->IsResumption()); EXPECT_TRUE(server_stream()->ResumptionAttempted()); } TEST_P(TlsServerHandshakerTest, ResumptionWithPlaceholderTicket) { InitializeFakeClient(); ticket_crypter_->set_fail_encrypt(true); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_FALSE(client_stream()->IsResumption()); EXPECT_FALSE(server_stream()->IsResumption()); EXPECT_FALSE(server_stream()->ResumptionAttempted()); InitializeServer(); InitializeFakeClient(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_FALSE(client_stream()->IsResumption()); EXPECT_FALSE(server_stream()->IsResumption()); EXPECT_NE(server_stream()->ResumptionAttempted(), GetParam().disable_resumption); } TEST_P(TlsServerHandshakerTest, AdvanceHandshakeDuringAsyncDecryptCallback) { if (GetParam().disable_resumption) { return; } InitializeFakeClient(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); ticket_crypter_->SetRunCallbacksAsync(true); InitializeServerWithFakeProofSourceHandle(); server_handshaker_->SetupProofSourceHandle( FakeProofSourceHandle::Action::DELEGATE_SYNC, FakeProofSourceHandle::Action:: DELEGATE_SYNC); InitializeFakeClient(); AdvanceHandshakeWithFakeClient(); ASSERT_EQ(ticket_crypter_->NumPendingCallbacks(), 1u); { QuicConnection::ScopedPacketFlusher flusher(server_connection_); server_handshaker_->AdvanceHandshake(); } server_session_ = nullptr; ticket_crypter_->RunPendingCallback(0); } TEST_P(TlsServerHandshakerTest, ResumptionWithFailingDecryptCallback) { if (GetParam().disable_resumption) { return; } InitializeFakeClient(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); ticket_crypter_->set_fail_decrypt(true); InitializeServer(); InitializeFakeClient(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_FALSE(client_stream()->IsResumption()); EXPECT_FALSE(server_stream()->IsResumption()); EXPECT_TRUE(server_stream()->ResumptionAttempted()); } TEST_P(TlsServerHandshakerTest, ResumptionWithFailingAsyncDecryptCallback) { if (GetParam().disable_resumption) { return; } InitializeFakeClient(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); ticket_crypter_->set_fail_decrypt(true); ticket_crypter_->SetRunCallbacksAsync(true); InitializeServer(); InitializeFakeClient(); AdvanceHandshakeWithFakeClient(); ASSERT_EQ(ticket_crypter_->NumPendingCallbacks(), 1u); ticket_crypter_->RunPendingCallback(0); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_FALSE(client_stream()->IsResumption()); EXPECT_FALSE(server_stream()->IsResumption()); EXPECT_TRUE(server_stream()->ResumptionAttempted()); } TEST_P(TlsServerHandshakerTest, HandshakeFailsWithFailingProofSource) { InitializeServerConfigWithFailingProofSource(); InitializeServer(); InitializeFakeClient(); AdvanceHandshakeWithFakeClient(); EXPECT_EQ(moved_messages_counts_.second, 0u); } TEST_P(TlsServerHandshakerTest, ZeroRttResumption) { std::vector<uint8_t> application_state = {0, 1, 2, 3}; server_stream()->SetServerApplicationStateForResumption( std::make_unique<ApplicationState>(application_state)); InitializeFakeClient(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_FALSE(client_stream()->IsResumption()); EXPECT_FALSE(server_stream()->IsZeroRtt()); InitializeServer(); server_stream()->SetServerApplicationStateForResumption( std::make_unique<ApplicationState>(application_state)); InitializeFakeClient(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_NE(client_stream()->IsResumption(), GetParam().disable_resumption); EXPECT_NE(server_stream()->IsZeroRtt(), GetParam().disable_resumption); } TEST_P(TlsServerHandshakerTest, ZeroRttRejectOnApplicationStateChange) { std::vector<uint8_t> original_application_state = {1, 2}; std::vector<uint8_t> new_application_state = {3, 4}; server_stream()->SetServerApplicationStateForResumption( std::make_unique<ApplicationState>(original_application_state)); InitializeFakeClient(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_FALSE(client_stream()->IsResumption()); EXPECT_FALSE(server_stream()->IsZeroRtt()); InitializeServer(); server_stream()->SetServerApplicationStateForResumption( std::make_unique<ApplicationState>(new_application_state)); InitializeFakeClient(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_NE(client_stream()->IsResumption(), GetParam().disable_resumption); EXPECT_FALSE(server_stream()->IsZeroRtt()); } TEST_P(TlsServerHandshakerTest, RequestClientCert) { ASSERT_TRUE(SetupClientCert()); InitializeFakeClient(); initial_client_cert_mode_ = ClientCertMode::kRequest; InitializeServerWithFakeProofSourceHandle(); server_handshaker_->SetupProofSourceHandle( FakeProofSourceHandle::Action::DELEGATE_SYNC, FakeProofSourceHandle::Action:: DELEGATE_SYNC); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_TRUE(server_handshaker_->received_client_cert()); } TEST_P(TlsServerHandshakerTest, SetInvalidServerTransportParamsByDelayedSslConfig) { ASSERT_TRUE(SetupClientCert()); InitializeFakeClient(); QuicDelayedSSLConfig delayed_ssl_config; delayed_ssl_config.quic_transport_parameters = {1, 2, 3}; InitializeServerWithFakeProofSourceHandle(); server_handshaker_->SetupProofSourceHandle( FakeProofSourceHandle::Action::DELEGATE_ASYNC, FakeProofSourceHandle::Action::DELEGATE_SYNC, delayed_ssl_config); AdvanceHandshakeWithFakeClient(); ASSERT_TRUE( server_handshaker_->fake_proof_source_handle()->HasPendingOperation()); server_handshaker_->fake_proof_source_handle()->CompletePendingOperation(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_FALSE(server_handshaker_->fake_proof_source_handle() ->all_compute_signature_args() .empty()); } TEST_P(TlsServerHandshakerTest, SetValidServerTransportParamsByDelayedSslConfig) { ParsedQuicVersion version = GetParam().version; TransportParameters server_params; std::string error_details; server_params.perspective = quic::Perspective::IS_SERVER; server_params.legacy_version_information = TransportParameters::LegacyVersionInformation(); server_params.legacy_version_information.value().supported_versions = quic::CreateQuicVersionLabelVector( quic::ParsedQuicVersionVector{version}); server_params.legacy_version_information.value().version = quic::CreateQuicVersionLabel(version); server_params.version_information = TransportParameters::VersionInformation(); server_params.version_information.value().chosen_version = quic::CreateQuicVersionLabel(version); server_params.version_information.value().other_versions = quic::CreateQuicVersionLabelVector( quic::ParsedQuicVersionVector{version}); ASSERT_TRUE(server_params.AreValid(&error_details)) << error_details; std::vector<uint8_t> server_params_bytes; ASSERT_TRUE( SerializeTransportParameters(server_params, &server_params_bytes)); ASSERT_TRUE(SetupClientCert()); InitializeFakeClient(); QuicDelayedSSLConfig delayed_ssl_config; delayed_ssl_config.quic_transport_parameters = server_params_bytes; InitializeServerWithFakeProofSourceHandle(); server_handshaker_->SetupProofSourceHandle( FakeProofSourceHandle::Action::DELEGATE_ASYNC, FakeProofSourceHandle::Action::DELEGATE_SYNC, delayed_ssl_config); AdvanceHandshakeWithFakeClient(); ASSERT_TRUE( server_handshaker_->fake_proof_source_handle()->HasPendingOperation()); server_handshaker_->fake_proof_source_handle()->CompletePendingOperation(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_FALSE(server_handshaker_->fake_proof_source_handle() ->all_compute_signature_args() .empty()); } TEST_P(TlsServerHandshakerTest, RequestClientCertByDelayedSslConfig) { ASSERT_TRUE(SetupClientCert()); InitializeFakeClient(); QuicDelayedSSLConfig delayed_ssl_config; delayed_ssl_config.client_cert_mode = ClientCertMode::kRequest; InitializeServerWithFakeProofSourceHandle(); server_handshaker_->SetupProofSourceHandle( FakeProofSourceHandle::Action::DELEGATE_ASYNC, FakeProofSourceHandle::Action::DELEGATE_SYNC, delayed_ssl_config); AdvanceHandshakeWithFakeClient(); ASSERT_TRUE( server_handshaker_->fake_proof_source_handle()->HasPendingOperation()); server_handshaker_->fake_proof_source_handle()->CompletePendingOperation(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_TRUE(server_handshaker_->received_client_cert()); } TEST_P(TlsServerHandshakerTest, RequestClientCert_NoCert) { initial_client_cert_mode_ = ClientCertMode::kRequest; InitializeServerWithFakeProofSourceHandle(); server_handshaker_->SetupProofSourceHandle( FakeProofSourceHandle::Action::DELEGATE_SYNC, FakeProofSourceHandle::Action:: DELEGATE_SYNC); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_FALSE(server_handshaker_->received_client_cert()); } TEST_P(TlsServerHandshakerTest, RequestAndRequireClientCert) { ASSERT_TRUE(SetupClientCert()); InitializeFakeClient(); initial_client_cert_mode_ = ClientCertMode::kRequire; InitializeServerWithFakeProofSourceHandle(); server_handshaker_->SetupProofSourceHandle( FakeProofSourceHandle::Action::DELEGATE_SYNC, FakeProofSourceHandle::Action:: DELEGATE_SYNC); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_TRUE(server_handshaker_->received_client_cert()); } TEST_P(TlsServerHandshakerTest, RequestAndRequireClientCertByDelayedSslConfig) { ASSERT_TRUE(SetupClientCert()); InitializeFakeClient(); QuicDelayedSSLConfig delayed_ssl_config; delayed_ssl_config.client_cert_mode = ClientCertMode::kRequire; InitializeServerWithFakeProofSourceHandle(); server_handshaker_->SetupProofSourceHandle( FakeProofSourceHandle::Action::DELEGATE_ASYNC, FakeProofSourceHandle::Action::DELEGATE_SYNC, delayed_ssl_config); AdvanceHandshakeWithFakeClient(); ASSERT_TRUE( server_handshaker_->fake_proof_source_handle()->HasPendingOperation()); server_handshaker_->fake_proof_source_handle()->CompletePendingOperation(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_TRUE(server_handshaker_->received_client_cert()); } TEST_P(TlsServerHandshakerTest, RequestAndRequireClientCert_NoCert) { initial_client_cert_mode_ = ClientCertMode::kRequire; InitializeServerWithFakeProofSourceHandle(); server_handshaker_->SetupProofSourceHandle( FakeProofSourceHandle::Action::DELEGATE_SYNC, FakeProofSourceHandle::Action:: DELEGATE_SYNC); EXPECT_CALL(*server_connection_, CloseConnection(QUIC_TLS_CERTIFICATE_REQUIRED, _, _, _)); AdvanceHandshakeWithFakeClient(); AdvanceHandshakeWithFakeClient(); EXPECT_FALSE(server_handshaker_->received_client_cert()); } TEST_P(TlsServerHandshakerTest, CloseConnectionBeforeSelectCert) { InitializeServerWithFakeProofSourceHandle(); server_handshaker_->SetupProofSourceHandle( FakeProofSourceHandle::Action:: FAIL_SYNC_DO_NOT_CHECK_CLOSED, FakeProofSourceHandle::Action:: FAIL_SYNC_DO_NOT_CHECK_CLOSED); EXPECT_CALL(*server_handshaker_, OverrideQuicConfigDefaults(_)) .WillOnce(testing::Invoke([](QuicConfig* config) { QuicConfigPeer::SetReceivedMaxUnidirectionalStreams(config, 0); })); EXPECT_CALL(*server_connection_, CloseConnection(QUIC_ZERO_RTT_RESUMPTION_LIMIT_REDUCED, _, _)) .WillOnce(testing::Invoke( [this](QuicErrorCode error, const std::string& details, ConnectionCloseBehavior connection_close_behavior) { server_connection_->ReallyCloseConnection( error, details, connection_close_behavior); ASSERT_FALSE(server_connection_->connected()); })); AdvanceHandshakeWithFakeClient(); EXPECT_TRUE(server_handshaker_->fake_proof_source_handle() ->all_select_cert_args() .empty()); } TEST_P(TlsServerHandshakerTest, FailUponCustomTranportParam) { client_session_->config()->custom_transport_parameters_to_send().emplace( TestTlsServerHandshaker::kFailHandshakeParam, "Fail handshake upon seeing this."); InitializeServerWithFakeProofSourceHandle(); server_handshaker_->SetupProofSourceHandle( FakeProofSourceHandle::Action::DELEGATE_ASYNC, FakeProofSourceHandle::Action:: DELEGATE_SYNC); EXPECT_CALL( *server_connection_, CloseConnection(QUIC_HANDSHAKE_FAILED, "Failed to process additional transport parameters", _)); AdvanceHandshakeWithFakeClient(); } TEST_P(TlsServerHandshakerTest, SuccessWithCustomTranportParam) { client_session_->config()->custom_transport_parameters_to_send().emplace( TransportParameters::TransportParameterId{0xFFEADD}, "Continue upon seeing this."); InitializeServerWithFakeProofSourceHandle(); server_handshaker_->SetupProofSourceHandle( FakeProofSourceHandle::Action::DELEGATE_ASYNC, FakeProofSourceHandle::Action:: DELEGATE_SYNC); EXPECT_CALL(*server_connection_, CloseConnection(_, _, _)).Times(0); AdvanceHandshakeWithFakeClient(); ASSERT_TRUE( server_handshaker_->fake_proof_source_handle()->HasPendingOperation()); server_handshaker_->fake_proof_source_handle()->CompletePendingOperation(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); } #if BORINGSSL_API_VERSION >= 22 TEST_P(TlsServerHandshakerTest, EnableKyber) { server_crypto_config_->set_preferred_groups( {SSL_GROUP_X25519_KYBER768_DRAFT00}); client_crypto_config_->set_preferred_groups( {SSL_GROUP_X25519_KYBER768_DRAFT00, SSL_GROUP_X25519, SSL_GROUP_SECP256R1, SSL_GROUP_SECP384R1}); InitializeServer(); InitializeFakeClient(); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_EQ(PROTOCOL_TLS1_3, server_stream()->handshake_protocol()); EXPECT_EQ(SSL_GROUP_X25519_KYBER768_DRAFT00, SSL_get_group_id(server_stream()->GetSsl())); } #endif #if BORINGSSL_API_VERSION >= 27 TEST_P(TlsServerHandshakerTest, AlpsUseNewCodepoint) { const struct { bool client_use_alps_new_codepoint; bool server_allow_alps_new_codepoint; } tests[] = { {true, true}, {false, true}, {false, false}, {true, true}, }; for (size_t i = 0; i < ABSL_ARRAYSIZE(tests); i++) { SCOPED_TRACE(absl::StrCat("Test #", i)); const auto& test = tests[i]; client_crypto_config_->set_alps_use_new_codepoint( test.client_use_alps_new_codepoint); SetQuicReloadableFlag(quic_gfe_allow_alps_new_codepoint, test.server_allow_alps_new_codepoint); ASSERT_TRUE(SetupClientCert()); InitializeFakeClient(); InitializeServerWithFakeProofSourceHandle(); server_handshaker_->SetupProofSourceHandle( FakeProofSourceHandle::Action::DELEGATE_SYNC, FakeProofSourceHandle::Action:: DELEGATE_SYNC); AdvanceHandshakeWithFakeClient(); EXPECT_EQ(test.client_use_alps_new_codepoint, server_handshaker_->UseAlpsNewCodepoint()); CompleteCryptoHandshake(); ExpectHandshakeSuccessful(); EXPECT_EQ(PROTOCOL_TLS1_3, server_stream()->handshake_protocol()); } } #endif } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/tls_server_handshaker.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/tls_server_handshaker_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
39e2fabd-d5b9-4fa5-b3f8-37fa255d0c91
cpp
google/quiche
quic_buffered_packet_store
quiche/quic/core/quic_buffered_packet_store.cc
quiche/quic/core/quic_buffered_packet_store_test.cc
#include "quiche/quic/core/quic_buffered_packet_store.h" #include <cstddef> #include <list> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/container/inlined_vector.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/connection_id_generator.h" #include "quiche/quic/core/crypto/crypto_handshake.h" #include "quiche/quic/core/crypto/crypto_utils.h" #include "quiche/quic/core/quic_alarm.h" #include "quiche/quic/core/quic_alarm_factory.h" #include "quiche/quic/core/quic_clock.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_framer.h" #include "quiche/quic/core/quic_packet_creator.h" #include "quiche/quic/core/quic_packet_number.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_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_socket_address.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/print_elements.h" #include "quiche/common/simple_buffer_allocator.h" namespace quic { using BufferedPacket = QuicBufferedPacketStore::BufferedPacket; using BufferedPacketList = QuicBufferedPacketStore::BufferedPacketList; using EnqueuePacketResult = QuicBufferedPacketStore::EnqueuePacketResult; static const size_t kDefaultMaxConnectionsInStore = 100; static const size_t kMaxConnectionsWithoutCHLO = kDefaultMaxConnectionsInStore / 2; namespace { class ConnectionExpireAlarm : public QuicAlarm::DelegateWithoutContext { public: explicit ConnectionExpireAlarm(QuicBufferedPacketStore* store) : connection_store_(store) {} void OnAlarm() override { connection_store_->OnExpirationTimeout(); } ConnectionExpireAlarm(const ConnectionExpireAlarm&) = delete; ConnectionExpireAlarm& operator=(const ConnectionExpireAlarm&) = delete; private: QuicBufferedPacketStore* connection_store_; }; } BufferedPacket::BufferedPacket(std::unique_ptr<QuicReceivedPacket> packet, QuicSocketAddress self_address, QuicSocketAddress peer_address, bool is_ietf_initial_packet) : packet(std::move(packet)), self_address(self_address), peer_address(peer_address), is_ietf_initial_packet(is_ietf_initial_packet) {} BufferedPacket::BufferedPacket(BufferedPacket&& other) = default; BufferedPacket& BufferedPacket::operator=(BufferedPacket&& other) = default; BufferedPacket::~BufferedPacket() {} BufferedPacketList::BufferedPacketList() : creation_time(QuicTime::Zero()), ietf_quic(false), version(ParsedQuicVersion::Unsupported()) {} BufferedPacketList::BufferedPacketList(BufferedPacketList&& other) = default; BufferedPacketList& BufferedPacketList::operator=(BufferedPacketList&& other) = default; BufferedPacketList::~BufferedPacketList() {} QuicBufferedPacketStore::QuicBufferedPacketStore( VisitorInterface* visitor, const QuicClock* clock, QuicAlarmFactory* alarm_factory, QuicDispatcherStats& stats) : stats_(stats), connection_life_span_( QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs)), visitor_(visitor), clock_(clock), expiration_alarm_( alarm_factory->CreateAlarm(new ConnectionExpireAlarm(this))) {} QuicBufferedPacketStore::~QuicBufferedPacketStore() { if (expiration_alarm_ != nullptr) { expiration_alarm_->PermanentCancel(); } } EnqueuePacketResult QuicBufferedPacketStore::EnqueuePacket( const ReceivedPacketInfo& packet_info, std::optional<ParsedClientHello> parsed_chlo, ConnectionIdGeneratorInterface& connection_id_generator) { QuicConnectionId connection_id = packet_info.destination_connection_id; const QuicReceivedPacket& packet = packet_info.packet; const QuicSocketAddress& self_address = packet_info.self_address; const QuicSocketAddress& peer_address = packet_info.peer_address; const ParsedQuicVersion& version = packet_info.version; const bool ietf_quic = packet_info.form != GOOGLE_QUIC_PACKET; const bool is_chlo = parsed_chlo.has_value(); const bool is_ietf_initial_packet = (version.IsKnown() && packet_info.form == IETF_QUIC_LONG_HEADER_PACKET && packet_info.long_packet_type == INITIAL); QUIC_BUG_IF(quic_bug_12410_1, !GetQuicFlag(quic_allow_chlo_buffering)) << "Shouldn't buffer packets if disabled via flag."; QUIC_BUG_IF(quic_bug_12410_4, is_chlo && !version.IsKnown()) << "Should have version for CHLO packet."; auto iter = buffered_session_map_.find(connection_id); const bool is_first_packet = (iter == buffered_session_map_.end()); if (is_first_packet) { if (ShouldNotBufferPacket(is_chlo)) { return TOO_MANY_CONNECTIONS; } iter = buffered_session_map_.emplace_hint( iter, connection_id, std::make_shared<BufferedPacketListNode>()); iter->second->ietf_quic = ietf_quic; iter->second->version = version; iter->second->original_connection_id = connection_id; iter->second->creation_time = clock_->ApproximateNow(); buffered_sessions_.push_back(iter->second.get()); ++num_buffered_sessions_; } QUICHE_DCHECK(buffered_session_map_.contains(connection_id)); BufferedPacketListNode& queue = *iter->second; if (!is_chlo && queue.buffered_packets.size() >= kDefaultMaxUndecryptablePackets) { return TOO_MANY_PACKETS; } BufferedPacket new_entry(std::unique_ptr<QuicReceivedPacket>(packet.Clone()), self_address, peer_address, is_ietf_initial_packet); if (is_chlo) { queue.buffered_packets.push_front(std::move(new_entry)); queue.parsed_chlo = std::move(parsed_chlo); queue.version = version; if (!buffered_sessions_with_chlo_.is_linked(&queue)) { buffered_sessions_with_chlo_.push_back(&queue); ++num_buffered_sessions_with_chlo_; } else { QUIC_BUG(quic_store_session_already_has_chlo) << "Buffered session already has CHLO"; } } else { queue.buffered_packets.push_back(std::move(new_entry)); if (is_first_packet) { queue.tls_chlo_extractor.IngestPacket(version, packet); QUIC_BUG_IF(quic_bug_12410_5, queue.tls_chlo_extractor.HasParsedFullChlo()) << "First packet in list should not contain full CHLO"; } } MaybeSetExpirationAlarm(); if (is_ietf_initial_packet && version.UsesTls() && !queue.HasAttemptedToReplaceConnectionId()) { queue.SetAttemptedToReplaceConnectionId(&connection_id_generator); std::optional<QuicConnectionId> replaced_connection_id = connection_id_generator.MaybeReplaceConnectionId(connection_id, packet_info.version); if (replaced_connection_id.has_value() && (replaced_connection_id->IsEmpty() || *replaced_connection_id == connection_id)) { QUIC_CODE_COUNT(quic_store_replaced_cid_is_empty_or_same_as_original); replaced_connection_id.reset(); } QUIC_DVLOG(1) << "MaybeReplaceConnectionId(" << connection_id << ") = " << (replaced_connection_id.has_value() ? replaced_connection_id->ToString() : "nullopt"); if (replaced_connection_id.has_value()) { switch (visitor_->HandleConnectionIdCollision( connection_id, *replaced_connection_id, self_address, peer_address, version, queue.parsed_chlo.has_value() ? &queue.parsed_chlo.value() : nullptr)) { case VisitorInterface::HandleCidCollisionResult::kOk: queue.replaced_connection_id = *replaced_connection_id; buffered_session_map_.insert( {*replaced_connection_id, queue.shared_from_this()}); break; case VisitorInterface::HandleCidCollisionResult::kCollision: return CID_COLLISION; } } } MaybeAckInitialPacket(packet_info, queue); if (is_chlo) { ++stats_.packets_enqueued_chlo; } else { ++stats_.packets_enqueued_early; } return SUCCESS; } void QuicBufferedPacketStore::MaybeAckInitialPacket( const ReceivedPacketInfo& packet_info, BufferedPacketList& packet_list) { if (!ack_buffered_initial_packets_) { return; } QUIC_RESTART_FLAG_COUNT_N(quic_dispatcher_ack_buffered_initial_packets, 1, 8); if (writer_ == nullptr || writer_->IsWriteBlocked() || !packet_info.version.IsKnown() || !packet_list.HasAttemptedToReplaceConnectionId() || packet_list.parsed_chlo.has_value() || packet_list.dispatcher_sent_packets.size() >= GetQuicFlag(quic_dispatcher_max_ack_sent_per_connection)) { return; } absl::InlinedVector<DispatcherSentPacket, 2>& dispatcher_sent_packets = packet_list.dispatcher_sent_packets; const QuicConnectionId& original_connection_id = packet_list.original_connection_id; CrypterPair crypters; CryptoUtils::CreateInitialObfuscators(Perspective::IS_SERVER, packet_info.version, original_connection_id, &crypters); QuicPacketNumber prior_largest_acked; if (!dispatcher_sent_packets.empty()) { prior_largest_acked = dispatcher_sent_packets.back().largest_acked; } std::optional<uint64_t> packet_number; if (!(QUIC_NO_ERROR == QuicFramer::TryDecryptInitialPacketDispatcher( packet_info.packet, packet_info.version, packet_info.form, packet_info.long_packet_type, packet_info.destination_connection_id, packet_info.source_connection_id, packet_info.retry_token, prior_largest_acked, *crypters.decrypter, &packet_number) && packet_number.has_value())) { QUIC_CODE_COUNT(quic_store_failed_to_decrypt_initial_packet); QUIC_DVLOG(1) << "Failed to decrypt initial packet. " "packet_info.destination_connection_id:" << packet_info.destination_connection_id << ", original_connection_id: " << original_connection_id << ", replaced_connection_id: " << (packet_list.HasReplacedConnectionId() ? packet_list.replaced_connection_id->ToString() : "n/a"); return; } const QuicConnectionId& server_connection_id = packet_list.HasReplacedConnectionId() ? *packet_list.replaced_connection_id : original_connection_id; QuicFramer framer(ParsedQuicVersionVector{packet_info.version}, QuicTime::Zero(), Perspective::IS_SERVER, server_connection_id.length()); framer.SetInitialObfuscators(original_connection_id); quiche::SimpleBufferAllocator send_buffer_allocator; PacketCollector collector(&send_buffer_allocator); QuicPacketCreator creator(server_connection_id, &framer, &collector); if (!dispatcher_sent_packets.empty()) { creator.set_packet_number(dispatcher_sent_packets.back().packet_number); } QuicAckFrame initial_ack_frame; initial_ack_frame.ack_delay_time = QuicTimeDelta::Zero(); initial_ack_frame.packets.Add(QuicPacketNumber(*packet_number)); for (const DispatcherSentPacket& sent_packet : dispatcher_sent_packets) { initial_ack_frame.packets.Add(sent_packet.received_packet_number); } initial_ack_frame.largest_acked = initial_ack_frame.packets.Max(); if (!creator.AddFrame(QuicFrame(&initial_ack_frame), NOT_RETRANSMISSION)) { QUIC_BUG(quic_dispatcher_add_ack_frame_failed) << "Unable to add ack frame to an empty packet while acking packet " << *packet_number; return; } creator.FlushCurrentPacket(); if (collector.packets()->size() != 1) { QUIC_BUG(quic_dispatcher_ack_unexpected_packet_count) << "Expect 1 ack packet created, got " << collector.packets()->size(); return; } std::unique_ptr<QuicEncryptedPacket>& packet = collector.packets()->front(); QUIC_DVLOG(1) << "Server: Sending packet " << creator.packet_number() << " : ack only from dispatcher, encryption_level: " "ENCRYPTION_INITIAL, encrypted length: " << packet->length() << " to peer " << packet_info.peer_address << ". packet_info.destination_connection_id: " << packet_info.destination_connection_id << ", original_connection_id: " << original_connection_id << ", replaced_connection_id: " << (packet_list.HasReplacedConnectionId() ? packet_list.replaced_connection_id->ToString() : "n/a"); WriteResult result = writer_->WritePacket( packet->data(), packet->length(), packet_info.self_address.host(), packet_info.peer_address, nullptr, QuicPacketWriterParams()); writer_->Flush(); QUIC_HISTOGRAM_ENUM("QuicBufferedPacketStore.WritePacketStatus", result.status, WRITE_STATUS_NUM_VALUES, "Status code returned by writer_->WritePacket() in " "QuicBufferedPacketStore."); DispatcherSentPacket sent_packet; sent_packet.packet_number = creator.packet_number(); sent_packet.received_packet_number = QuicPacketNumber(*packet_number); sent_packet.largest_acked = initial_ack_frame.largest_acked; sent_packet.sent_time = clock_->ApproximateNow(); sent_packet.bytes_sent = static_cast<QuicPacketLength>(packet->length()); dispatcher_sent_packets.push_back(sent_packet); ++stats_.packets_sent; } bool QuicBufferedPacketStore::HasBufferedPackets( QuicConnectionId connection_id) const { return buffered_session_map_.contains(connection_id); } bool QuicBufferedPacketStore::HasChlosBuffered() const { return num_buffered_sessions_with_chlo_ != 0; } const BufferedPacketList* QuicBufferedPacketStore::GetPacketList( const QuicConnectionId& connection_id) const { if (!ack_buffered_initial_packets_) { return nullptr; } QUIC_RESTART_FLAG_COUNT_N(quic_dispatcher_ack_buffered_initial_packets, 2, 8); auto it = buffered_session_map_.find(connection_id); if (it == buffered_session_map_.end()) { return nullptr; } QUICHE_DCHECK(CheckInvariants(*it->second)); return it->second.get(); } bool QuicBufferedPacketStore::CheckInvariants( const BufferedPacketList& packet_list) const { auto original_cid_it = buffered_session_map_.find(packet_list.original_connection_id); if (original_cid_it == buffered_session_map_.end()) { return false; } if (original_cid_it->second.get() != &packet_list) { return false; } if (buffered_sessions_with_chlo_.is_linked(original_cid_it->second.get()) != original_cid_it->second->parsed_chlo.has_value()) { return false; } if (packet_list.replaced_connection_id.has_value()) { auto replaced_cid_it = buffered_session_map_.find(*packet_list.replaced_connection_id); if (replaced_cid_it == buffered_session_map_.end()) { return false; } if (replaced_cid_it->second.get() != &packet_list) { return false; } } return true; } BufferedPacketList QuicBufferedPacketStore::DeliverPackets( QuicConnectionId connection_id) { auto it = buffered_session_map_.find(connection_id); if (it == buffered_session_map_.end()) { return BufferedPacketList(); } std::shared_ptr<BufferedPacketListNode> node = it->second->shared_from_this(); RemoveFromStore(*node); std::list<BufferedPacket> initial_packets; std::list<BufferedPacket> other_packets; for (auto& packet : node->buffered_packets) { if (packet.is_ietf_initial_packet) { initial_packets.push_back(std::move(packet)); } else { other_packets.push_back(std::move(packet)); } } initial_packets.splice(initial_packets.end(), other_packets); node->buffered_packets = std::move(initial_packets); BufferedPacketList& packet_list = *node; return std::move(packet_list); } void QuicBufferedPacketStore::DiscardPackets(QuicConnectionId connection_id) { auto it = buffered_session_map_.find(connection_id); if (it == buffered_session_map_.end()) { return; } RemoveFromStore(*it->second); } void QuicBufferedPacketStore::RemoveFromStore(BufferedPacketListNode& node) { QUICHE_DCHECK_EQ(buffered_sessions_with_chlo_.size(), num_buffered_sessions_with_chlo_); QUICHE_DCHECK_EQ(buffered_sessions_.size(), num_buffered_sessions_); QUIC_BUG_IF(quic_store_chlo_state_inconsistent, node.parsed_chlo.has_value() != buffered_sessions_with_chlo_.is_linked(&node)) << "Inconsistent CHLO state for connection " << node.original_connection_id << ", parsed_chlo.has_value:" << node.parsed_chlo.has_value() << ", is_linked:" << buffered_sessions_with_chlo_.is_linked(&node); if (buffered_sessions_with_chlo_.is_linked(&node)) { buffered_sessions_with_chlo_.erase(&node); --num_buffered_sessions_with_chlo_; } if (buffered_sessions_.is_linked(&node)) { buffered_sessions_.erase(&node); --num_buffered_sessions_; } else { QUIC_BUG(quic_store_missing_node_in_main_list) << "Missing node in main buffered session list for connection " << node.original_connection_id; } if (node.HasReplacedConnectionId()) { bool erased = buffered_session_map_.erase(*node.replaced_connection_id) > 0; QUIC_BUG_IF(quic_store_missing_replaced_cid_in_map, !erased) << "Node has replaced CID but it's not in the map. original_cid: " << node.original_connection_id << " replaced_cid: " << *node.replaced_connection_id; } bool erased = buffered_session_map_.erase(node.original_connection_id) > 0; QUIC_BUG_IF(quic_store_missing_original_cid_in_map, !erased) << "Node missing in the map. original_cid: " << node.original_connection_id; } void QuicBufferedPacketStore::DiscardAllPackets() { buffered_sessions_with_chlo_.clear(); num_buffered_sessions_with_chlo_ = 0; buffered_sessions_.clear(); num_buffered_sessions_ = 0; buffered_session_map_.clear(); expiration_alarm_->Cancel(); } void QuicBufferedPacketStore::OnExpirationTimeout() { QuicTime expiration_time = clock_->ApproximateNow() - connection_life_span_; while (!buffered_sessions_.empty()) { BufferedPacketListNode& node = buffered_sessions_.front(); if (node.creation_time > expiration_time) { break; } std::shared_ptr<BufferedPacketListNode> node_ref = node.shared_from_this(); QuicConnectionId connection_id = node.original_connection_id; RemoveFromStore(node); visitor_->OnExpiredPackets(connection_id, std::move(node)); } if (!buffered_sessions_.empty()) { MaybeSetExpirationAlarm(); } } void QuicBufferedPacketStore::MaybeSetExpirationAlarm() { if (!expiration_alarm_->IsSet()) { expiration_alarm_->Set(clock_->ApproximateNow() + connection_life_span_); } } bool QuicBufferedPacketStore::ShouldNotBufferPacket(bool is_chlo) const { const bool is_store_full = num_buffered_sessions_ >= kDefaultMaxConnectionsInStore; if (is_chlo) { return is_store_full; } QUIC_BUG_IF(quic_store_too_many_connections_with_chlo, num_buffered_sessions_ < num_buffered_sessions_with_chlo_) << "num_connections: " << num_buffered_sessions_ << ", num_connections_with_chlo: " << num_buffered_sessions_with_chlo_; size_t num_connections_without_chlo = num_buffered_sessions_ - num_buffered_sessions_with_chlo_; bool reach_non_chlo_limit = num_connections_without_chlo >= kMaxConnectionsWithoutCHLO; return is_store_full || reach_non_chlo_limit; } BufferedPacketList QuicBufferedPacketStore::DeliverPacketsForNextConnection( QuicConnectionId* connection_id) { if (buffered_sessions_with_chlo_.empty()) { return BufferedPacketList(); } *connection_id = buffered_sessions_with_chlo_.front().original_connection_id; BufferedPacketList packet_list = DeliverPackets(*connection_id); QUICHE_DCHECK(!packet_list.buffered_packets.empty() && packet_list.parsed_chlo.has_value()) << "Try to deliver connectons without CHLO. # packets:" << packet_list.buffered_packets.size() << ", has_parsed_chlo:" << packet_list.parsed_chlo.has_value(); return packet_list; } bool QuicBufferedPacketStore::HasChloForConnection( QuicConnectionId connection_id) { auto it = buffered_session_map_.find(connection_id); if (it == buffered_session_map_.end()) { return false; } return it->second->parsed_chlo.has_value(); } bool QuicBufferedPacketStore::IngestPacketForTlsChloExtraction( const QuicConnectionId& connection_id, const ParsedQuicVersion& version, const QuicReceivedPacket& packet, std::vector<uint16_t>* out_supported_groups, std::vector<uint16_t>* out_cert_compression_algos, std::vector<std::string>* out_alpns, std::string* out_sni, bool* out_resumption_attempted, bool* out_early_data_attempted, std::optional<uint8_t>* tls_alert) { QUICHE_DCHECK_NE(out_alpns, nullptr); QUICHE_DCHECK_NE(out_sni, nullptr); QUICHE_DCHECK_NE(tls_alert, nullptr); QUICHE_DCHECK_EQ(version.handshake_protocol, PROTOCOL_TLS1_3); auto it = buffered_session_map_.find(connection_id); if (it == buffered_session_map_.end()) { QUIC_BUG(quic_bug_10838_1) << "Cannot ingest packet for unknown connection ID " << connection_id; return false; } BufferedPacketListNode& node = *it->second; node.tls_chlo_extractor.IngestPacket(version, packet); if (!node.tls_chlo_extractor.HasParsedFullChlo()) { *tls_alert = node.tls_chlo_extractor.tls_alert(); return false; } const TlsChloExtractor& tls_chlo_extractor = node.tls_chlo_extractor; *out_supported_groups = tls_chlo_extractor.supported_groups(); *out_cert_compression_algos = tls_chlo_extractor.cert_compression_algos(); *out_alpns = tls_chlo_extractor.alpns(); *out_sni = tls_chlo_extractor.server_name(); *out_resumption_attempted = tls_chlo_extractor.resumption_attempted(); *out_early_data_attempted = tls_chlo_extractor.early_data_attempted(); return true; } }
#include "quiche/quic/core/quic_buffered_packet_store.h" #include <cstddef> #include <cstdint> #include <list> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/strings/string_view.h" #include "quiche/quic/core/connection_id_generator.h" #include "quiche/quic/core/crypto/transport_parameters.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_dispatcher.h" #include "quiche/quic/core/quic_dispatcher_stats.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_framer.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_versions.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/first_flight.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_buffered_packet_store_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { static const size_t kDefaultMaxConnectionsInStore = 100; static const size_t kMaxConnectionsWithoutCHLO = kDefaultMaxConnectionsInStore / 2; namespace test { namespace { const std::optional<ParsedClientHello> kNoParsedChlo; const std::optional<ParsedClientHello> kDefaultParsedChlo = absl::make_optional<ParsedClientHello>(); using BufferedPacket = QuicBufferedPacketStore::BufferedPacket; using BufferedPacketList = QuicBufferedPacketStore::BufferedPacketList; using EnqueuePacketResult = QuicBufferedPacketStore::EnqueuePacketResult; using ::testing::A; using ::testing::Conditional; using ::testing::Each; using ::testing::ElementsAre; using ::testing::Ne; using ::testing::SizeIs; using ::testing::Truly; EnqueuePacketResult EnqueuePacketToStore( QuicBufferedPacketStore& store, QuicConnectionId connection_id, PacketHeaderFormat form, QuicLongHeaderType long_packet_type, const QuicReceivedPacket& packet, QuicSocketAddress self_address, QuicSocketAddress peer_address, const ParsedQuicVersion& version, std::optional<ParsedClientHello> parsed_chlo, ConnectionIdGeneratorInterface& connection_id_generator) { ReceivedPacketInfo packet_info(self_address, peer_address, packet); packet_info.destination_connection_id = connection_id; packet_info.form = form; packet_info.long_packet_type = long_packet_type; packet_info.version = version; return store.EnqueuePacket(packet_info, std::move(parsed_chlo), connection_id_generator); } class QuicBufferedPacketStoreVisitor : public QuicBufferedPacketStore::VisitorInterface { public: QuicBufferedPacketStoreVisitor() {} ~QuicBufferedPacketStoreVisitor() override {} void OnExpiredPackets(QuicConnectionId , BufferedPacketList early_arrived_packets) override { last_expired_packet_queue_ = std::move(early_arrived_packets); } HandleCidCollisionResult HandleConnectionIdCollision( const QuicConnectionId& , const QuicConnectionId& , const QuicSocketAddress& , const QuicSocketAddress& , ParsedQuicVersion , const ParsedClientHello* ) override { return HandleCidCollisionResult::kOk; } BufferedPacketList last_expired_packet_queue_; }; class QuicBufferedPacketStoreTest : public QuicTest { public: QuicBufferedPacketStoreTest() : store_(&visitor_, &clock_, &alarm_factory_, stats_), self_address_(QuicIpAddress::Any6(), 65535), peer_address_(QuicIpAddress::Any6(), 65535), packet_content_("some encrypted content"), packet_time_(QuicTime::Zero() + QuicTime::Delta::FromMicroseconds(42)), packet_(packet_content_.data(), packet_content_.size(), packet_time_), invalid_version_(UnsupportedQuicVersion()), valid_version_(CurrentSupportedVersions().front()) {} protected: QuicDispatcherStats stats_; QuicBufferedPacketStoreVisitor visitor_; MockClock clock_; MockAlarmFactory alarm_factory_; QuicBufferedPacketStore store_; QuicSocketAddress self_address_; QuicSocketAddress peer_address_; std::string packet_content_; QuicTime packet_time_; QuicReceivedPacket packet_; const ParsedQuicVersion invalid_version_; const ParsedQuicVersion valid_version_; MockConnectionIdGenerator connection_id_generator_; }; TEST_F(QuicBufferedPacketStoreTest, SimpleEnqueueAndDeliverPacket) { QuicConnectionId connection_id = TestConnectionId(1); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, connection_id_generator_); EXPECT_TRUE(store_.HasBufferedPackets(connection_id)); auto packets = store_.DeliverPackets(connection_id); const std::list<BufferedPacket>& queue = packets.buffered_packets; ASSERT_EQ(1u, queue.size()); ASSERT_FALSE(packets.parsed_chlo.has_value()); EXPECT_EQ(invalid_version_, packets.version); EXPECT_EQ(packet_content_, queue.front().packet->AsStringPiece()); EXPECT_EQ(packet_time_, queue.front().packet->receipt_time()); EXPECT_EQ(peer_address_, queue.front().peer_address); EXPECT_EQ(self_address_, queue.front().self_address); EXPECT_TRUE(store_.DeliverPackets(connection_id).buffered_packets.empty()); EXPECT_FALSE(store_.HasBufferedPackets(connection_id)); } TEST_F(QuicBufferedPacketStoreTest, DifferentPacketAddressOnOneConnection) { QuicSocketAddress addr_with_new_port(QuicIpAddress::Any4(), 256); QuicConnectionId connection_id = TestConnectionId(1); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, connection_id_generator_); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, addr_with_new_port, invalid_version_, kNoParsedChlo, connection_id_generator_); std::list<BufferedPacket> queue = store_.DeliverPackets(connection_id).buffered_packets; ASSERT_EQ(2u, queue.size()); EXPECT_EQ(peer_address_, queue.front().peer_address); EXPECT_EQ(addr_with_new_port, queue.back().peer_address); } TEST_F(QuicBufferedPacketStoreTest, EnqueueAndDeliverMultiplePacketsOnMultipleConnections) { size_t num_connections = 10; for (uint64_t conn_id = 1; conn_id <= num_connections; ++conn_id) { QuicConnectionId connection_id = TestConnectionId(conn_id); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, connection_id_generator_); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, connection_id_generator_); } for (uint64_t conn_id = num_connections; conn_id > 0; --conn_id) { QuicConnectionId connection_id = TestConnectionId(conn_id); std::list<BufferedPacket> queue = store_.DeliverPackets(connection_id).buffered_packets; ASSERT_EQ(2u, queue.size()); } } TEST_F(QuicBufferedPacketStoreTest, FailToBufferTooManyPacketsOnExistingConnection) { const size_t kMaxPacketsPerConnection = kDefaultMaxUndecryptablePackets; QuicConnectionId connection_id = TestConnectionId(1); EXPECT_EQ(QuicBufferedPacketStore::SUCCESS, EnqueuePacketToStore(store_, connection_id, IETF_QUIC_LONG_HEADER_PACKET, INITIAL, packet_, self_address_, peer_address_, valid_version_, kDefaultParsedChlo, connection_id_generator_)); for (size_t i = 1; i <= kMaxPacketsPerConnection; ++i) { EnqueuePacketResult result = EnqueuePacketToStore( store_, connection_id, GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, connection_id_generator_); if (i != kMaxPacketsPerConnection) { EXPECT_EQ(EnqueuePacketResult::SUCCESS, result); } else { EXPECT_EQ(EnqueuePacketResult::TOO_MANY_PACKETS, result); } } EXPECT_EQ(store_.DeliverPackets(connection_id).buffered_packets.size(), kMaxPacketsPerConnection); } TEST_F(QuicBufferedPacketStoreTest, ReachNonChloConnectionUpperLimit) { const size_t kNumConnections = kMaxConnectionsWithoutCHLO + 1; for (uint64_t conn_id = 1; conn_id <= kNumConnections; ++conn_id) { QuicConnectionId connection_id = TestConnectionId(conn_id); EnqueuePacketResult result = EnqueuePacketToStore( store_, connection_id, GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, connection_id_generator_); if (conn_id <= kMaxConnectionsWithoutCHLO) { EXPECT_EQ(EnqueuePacketResult::SUCCESS, result); } else { EXPECT_EQ(EnqueuePacketResult::TOO_MANY_CONNECTIONS, result); } } for (uint64_t conn_id = 1; conn_id <= kNumConnections; ++conn_id) { QuicConnectionId connection_id = TestConnectionId(conn_id); std::list<BufferedPacket> queue = store_.DeliverPackets(connection_id).buffered_packets; if (conn_id <= kMaxConnectionsWithoutCHLO) { EXPECT_EQ(1u, queue.size()); } else { EXPECT_EQ(0u, queue.size()); } } } TEST_F(QuicBufferedPacketStoreTest, FullStoreFailToBufferDataPacketOnNewConnection) { size_t num_chlos = kDefaultMaxConnectionsInStore - kMaxConnectionsWithoutCHLO + 1; for (uint64_t conn_id = 1; conn_id <= num_chlos; ++conn_id) { EXPECT_EQ( EnqueuePacketResult::SUCCESS, EnqueuePacketToStore(store_, TestConnectionId(conn_id), GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, peer_address_, valid_version_, kDefaultParsedChlo, connection_id_generator_)); } for (uint64_t conn_id = num_chlos + 1; conn_id <= (kDefaultMaxConnectionsInStore + 1); ++conn_id) { QuicConnectionId connection_id = TestConnectionId(conn_id); EnqueuePacketResult result = EnqueuePacketToStore( store_, connection_id, GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, peer_address_, valid_version_, kDefaultParsedChlo, connection_id_generator_); if (conn_id <= kDefaultMaxConnectionsInStore) { EXPECT_EQ(EnqueuePacketResult::SUCCESS, result); } else { EXPECT_EQ(EnqueuePacketResult::TOO_MANY_CONNECTIONS, result); } } } TEST_F(QuicBufferedPacketStoreTest, BasicGeneratorBuffering) { EXPECT_EQ(EnqueuePacketResult::SUCCESS, EnqueuePacketToStore( store_, TestConnectionId(1), GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, peer_address_, valid_version_, kDefaultParsedChlo, connection_id_generator_)); QuicConnectionId delivered_conn_id; BufferedPacketList packet_list = store_.DeliverPacketsForNextConnection(&delivered_conn_id); EXPECT_EQ(1u, packet_list.buffered_packets.size()); EXPECT_EQ(delivered_conn_id, TestConnectionId(1)); EXPECT_EQ(packet_list.connection_id_generator, nullptr); } TEST_F(QuicBufferedPacketStoreTest, GeneratorIgnoredForNonChlo) { MockConnectionIdGenerator generator2; EXPECT_EQ(EnqueuePacketResult::SUCCESS, EnqueuePacketToStore( store_, TestConnectionId(1), GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, peer_address_, valid_version_, kDefaultParsedChlo, connection_id_generator_)); EXPECT_EQ(EnqueuePacketResult::SUCCESS, EnqueuePacketToStore(store_, TestConnectionId(1), GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, peer_address_, valid_version_, kNoParsedChlo, generator2)); QuicConnectionId delivered_conn_id; BufferedPacketList packet_list = store_.DeliverPacketsForNextConnection(&delivered_conn_id); EXPECT_EQ(2u, packet_list.buffered_packets.size()); EXPECT_EQ(delivered_conn_id, TestConnectionId(1)); EXPECT_EQ(packet_list.connection_id_generator, nullptr); } TEST_F(QuicBufferedPacketStoreTest, EnqueueChloOnTooManyDifferentConnections) { for (uint64_t conn_id = 1; conn_id <= kMaxConnectionsWithoutCHLO; ++conn_id) { QuicConnectionId connection_id = TestConnectionId(conn_id); EXPECT_EQ(EnqueuePacketResult::SUCCESS, EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, connection_id_generator_)); } for (size_t i = kMaxConnectionsWithoutCHLO + 1; i <= kDefaultMaxConnectionsInStore + 1; ++i) { QuicConnectionId connection_id = TestConnectionId(i); EnqueuePacketResult rs = EnqueuePacketToStore( store_, connection_id, GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, peer_address_, valid_version_, kDefaultParsedChlo, connection_id_generator_); if (i <= kDefaultMaxConnectionsInStore) { EXPECT_EQ(EnqueuePacketResult::SUCCESS, rs); EXPECT_TRUE(store_.HasChloForConnection(connection_id)); } else { EXPECT_EQ(EnqueuePacketResult::TOO_MANY_CONNECTIONS, rs); EXPECT_FALSE(store_.HasChloForConnection(connection_id)); } } EXPECT_EQ(EnqueuePacketResult::SUCCESS, EnqueuePacketToStore( store_, TestConnectionId(1), GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, peer_address_, valid_version_, kDefaultParsedChlo, connection_id_generator_)); EXPECT_TRUE(store_.HasChloForConnection(TestConnectionId(1))); QuicConnectionId delivered_conn_id; for (size_t i = 0; i < kDefaultMaxConnectionsInStore - kMaxConnectionsWithoutCHLO + 1; ++i) { BufferedPacketList packet_list = store_.DeliverPacketsForNextConnection(&delivered_conn_id); if (i < kDefaultMaxConnectionsInStore - kMaxConnectionsWithoutCHLO) { EXPECT_EQ(1u, packet_list.buffered_packets.size()); EXPECT_EQ(TestConnectionId(i + kMaxConnectionsWithoutCHLO + 1), delivered_conn_id); } else { EXPECT_EQ(2u, packet_list.buffered_packets.size()); EXPECT_EQ(TestConnectionId(1u), delivered_conn_id); } EXPECT_EQ(packet_list.connection_id_generator, nullptr); } EXPECT_FALSE(store_.HasChlosBuffered()); } TEST_F(QuicBufferedPacketStoreTest, PacketQueueExpiredBeforeDelivery) { QuicConnectionId connection_id = TestConnectionId(1); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, connection_id_generator_); EXPECT_EQ(EnqueuePacketResult::SUCCESS, EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, peer_address_, valid_version_, kDefaultParsedChlo, connection_id_generator_)); QuicConnectionId connection_id2 = TestConnectionId(2); EXPECT_EQ(EnqueuePacketResult::SUCCESS, EnqueuePacketToStore(store_, connection_id2, GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, connection_id_generator_)); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); QuicConnectionId connection_id3 = TestConnectionId(3); QuicSocketAddress another_client_address(QuicIpAddress::Any4(), 255); EnqueuePacketToStore(store_, connection_id3, GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, another_client_address, valid_version_, kDefaultParsedChlo, connection_id_generator_); clock_.AdvanceTime( QuicBufferedPacketStorePeer::expiration_alarm(&store_)->deadline() - clock_.ApproximateNow()); ASSERT_GE(clock_.ApproximateNow(), QuicBufferedPacketStorePeer::expiration_alarm(&store_)->deadline()); alarm_factory_.FireAlarm( QuicBufferedPacketStorePeer::expiration_alarm(&store_)); EXPECT_EQ(1u, visitor_.last_expired_packet_queue_.buffered_packets.size()); EXPECT_FALSE(store_.HasBufferedPackets(connection_id)); EXPECT_FALSE(store_.HasBufferedPackets(connection_id2)); ASSERT_EQ(0u, store_.DeliverPackets(connection_id).buffered_packets.size()); ASSERT_EQ(0u, store_.DeliverPackets(connection_id2).buffered_packets.size()); QuicConnectionId delivered_conn_id; BufferedPacketList packet_list = store_.DeliverPacketsForNextConnection(&delivered_conn_id); EXPECT_EQ(connection_id3, delivered_conn_id); EXPECT_EQ(packet_list.connection_id_generator, nullptr); ASSERT_EQ(1u, packet_list.buffered_packets.size()); EXPECT_EQ(another_client_address, packet_list.buffered_packets.front().peer_address); QuicConnectionId connection_id4 = TestConnectionId(4); EnqueuePacketToStore(store_, connection_id4, GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, connection_id_generator_); EnqueuePacketToStore(store_, connection_id4, GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, connection_id_generator_); clock_.AdvanceTime( QuicBufferedPacketStorePeer::expiration_alarm(&store_)->deadline() - clock_.ApproximateNow()); alarm_factory_.FireAlarm( QuicBufferedPacketStorePeer::expiration_alarm(&store_)); EXPECT_EQ(2u, visitor_.last_expired_packet_queue_.buffered_packets.size()); } TEST_F(QuicBufferedPacketStoreTest, SimpleDiscardPackets) { QuicConnectionId connection_id = TestConnectionId(1); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, connection_id_generator_); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, connection_id_generator_); EXPECT_TRUE(store_.HasBufferedPackets(connection_id)); EXPECT_FALSE(store_.HasChlosBuffered()); store_.DiscardPackets(connection_id); EXPECT_TRUE(store_.DeliverPackets(connection_id).buffered_packets.empty()); EXPECT_FALSE(store_.HasBufferedPackets(connection_id)); EXPECT_FALSE(store_.HasChlosBuffered()); store_.DiscardPackets(connection_id); EXPECT_TRUE(store_.DeliverPackets(connection_id).buffered_packets.empty()); EXPECT_FALSE(store_.HasBufferedPackets(connection_id)); EXPECT_FALSE(store_.HasChlosBuffered()); } TEST_F(QuicBufferedPacketStoreTest, DiscardWithCHLOs) { QuicConnectionId connection_id = TestConnectionId(1); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, connection_id_generator_); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, peer_address_, valid_version_, kDefaultParsedChlo, connection_id_generator_); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, connection_id_generator_); EXPECT_TRUE(store_.HasBufferedPackets(connection_id)); EXPECT_TRUE(store_.HasChlosBuffered()); store_.DiscardPackets(connection_id); EXPECT_TRUE(store_.DeliverPackets(connection_id).buffered_packets.empty()); EXPECT_FALSE(store_.HasBufferedPackets(connection_id)); EXPECT_FALSE(store_.HasChlosBuffered()); store_.DiscardPackets(connection_id); EXPECT_TRUE(store_.DeliverPackets(connection_id).buffered_packets.empty()); EXPECT_FALSE(store_.HasBufferedPackets(connection_id)); EXPECT_FALSE(store_.HasChlosBuffered()); } TEST_F(QuicBufferedPacketStoreTest, MultipleDiscardPackets) { QuicConnectionId connection_id_1 = TestConnectionId(1); QuicConnectionId connection_id_2 = TestConnectionId(2); EnqueuePacketToStore(store_, connection_id_1, GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, connection_id_generator_); EnqueuePacketToStore(store_, connection_id_1, GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, peer_address_, invalid_version_, kNoParsedChlo, connection_id_generator_); ParsedClientHello parsed_chlo; parsed_chlo.alpns.push_back("h3"); parsed_chlo.sni = TestHostname(); EnqueuePacketToStore(store_, connection_id_2, IETF_QUIC_LONG_HEADER_PACKET, INITIAL, packet_, self_address_, peer_address_, valid_version_, parsed_chlo, connection_id_generator_); EXPECT_TRUE(store_.HasBufferedPackets(connection_id_1)); EXPECT_TRUE(store_.HasBufferedPackets(connection_id_2)); EXPECT_TRUE(store_.HasChlosBuffered()); store_.DiscardPackets(connection_id_1); EXPECT_TRUE(store_.DeliverPackets(connection_id_1).buffered_packets.empty()); EXPECT_FALSE(store_.HasBufferedPackets(connection_id_1)); EXPECT_TRUE(store_.HasChlosBuffered()); EXPECT_TRUE(store_.HasBufferedPackets(connection_id_2)); auto packets = store_.DeliverPackets(connection_id_2); EXPECT_EQ(1u, packets.buffered_packets.size()); ASSERT_EQ(1u, packets.parsed_chlo->alpns.size()); EXPECT_EQ("h3", packets.parsed_chlo->alpns[0]); EXPECT_EQ(TestHostname(), packets.parsed_chlo->sni); EXPECT_EQ(valid_version_, packets.version); EXPECT_FALSE(store_.HasChlosBuffered()); store_.DiscardPackets(connection_id_2); EXPECT_FALSE(store_.HasChlosBuffered()); } TEST_F(QuicBufferedPacketStoreTest, DiscardPacketsEmpty) { QuicConnectionId connection_id = TestConnectionId(11235); EXPECT_FALSE(store_.HasBufferedPackets(connection_id)); EXPECT_FALSE(store_.HasChlosBuffered()); store_.DiscardPackets(connection_id); EXPECT_FALSE(store_.HasBufferedPackets(connection_id)); EXPECT_FALSE(store_.HasChlosBuffered()); } TEST_F(QuicBufferedPacketStoreTest, IngestPacketForTlsChloExtraction) { QuicConnectionId connection_id = TestConnectionId(1); std::vector<std::string> alpns; std::vector<uint16_t> supported_groups; std::vector<uint16_t> cert_compression_algos; std::string sni; bool resumption_attempted = false; bool early_data_attempted = false; QuicConfig config; std::optional<uint8_t> tls_alert; EXPECT_FALSE(store_.HasBufferedPackets(connection_id)); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, packet_, self_address_, peer_address_, valid_version_, kNoParsedChlo, connection_id_generator_); EXPECT_TRUE(store_.HasBufferedPackets(connection_id)); EXPECT_FALSE(store_.IngestPacketForTlsChloExtraction( connection_id, valid_version_, packet_, &supported_groups, &cert_compression_algos, &alpns, &sni, &resumption_attempted, &early_data_attempted, &tls_alert)); store_.DiscardPackets(connection_id); constexpr auto kCustomParameterId = static_cast<TransportParameters::TransportParameterId>(0xff33); std::string kCustomParameterValue(2000, '-'); config.custom_transport_parameters_to_send()[kCustomParameterId] = kCustomParameterValue; auto packets = GetFirstFlightOfPackets(valid_version_, config); ASSERT_EQ(packets.size(), 2u); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, *packets[0], self_address_, peer_address_, valid_version_, kNoParsedChlo, connection_id_generator_); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, *packets[1], self_address_, peer_address_, valid_version_, kNoParsedChlo, connection_id_generator_); EXPECT_TRUE(store_.HasBufferedPackets(connection_id)); EXPECT_FALSE(store_.IngestPacketForTlsChloExtraction( connection_id, valid_version_, *packets[0], &supported_groups, &cert_compression_algos, &alpns, &sni, &resumption_attempted, &early_data_attempted, &tls_alert)); EXPECT_TRUE(store_.IngestPacketForTlsChloExtraction( connection_id, valid_version_, *packets[1], &supported_groups, &cert_compression_algos, &alpns, &sni, &resumption_attempted, &early_data_attempted, &tls_alert)); EXPECT_THAT(alpns, ElementsAre(AlpnForVersion(valid_version_))); EXPECT_FALSE(supported_groups.empty()); EXPECT_EQ(sni, TestHostname()); EXPECT_FALSE(resumption_attempted); EXPECT_FALSE(early_data_attempted); } TEST_F(QuicBufferedPacketStoreTest, DeliverInitialPacketsFirst) { QuicConfig config; QuicConnectionId connection_id = TestConnectionId(1); constexpr auto kCustomParameterId = static_cast<TransportParameters::TransportParameterId>(0xff33); std::string custom_parameter_value(2000, '-'); config.custom_transport_parameters_to_send()[kCustomParameterId] = custom_parameter_value; auto initial_packets = GetFirstFlightOfPackets(valid_version_, config); ASSERT_THAT(initial_packets, SizeIs(2)); EXPECT_THAT( initial_packets, Each(Truly([](const std::unique_ptr<QuicReceivedPacket>& packet) { QuicLongHeaderType long_packet_type = INVALID_PACKET_TYPE; PacketHeaderFormat unused_format; bool unused_version_flag; bool unused_use_length_prefix; QuicVersionLabel unused_version_label; ParsedQuicVersion unused_parsed_version = UnsupportedQuicVersion(); QuicConnectionId unused_destination_connection_id; QuicConnectionId unused_source_connection_id; std::optional<absl::string_view> unused_retry_token; std::string unused_detailed_error; QuicErrorCode error_code = QuicFramer::ParsePublicHeaderDispatcher( *packet, kQuicDefaultConnectionIdLength, &unused_format, &long_packet_type, &unused_version_flag, &unused_use_length_prefix, &unused_version_label, &unused_parsed_version, &unused_destination_connection_id, &unused_source_connection_id, &unused_retry_token, &unused_detailed_error); return error_code == QUIC_NO_ERROR && long_packet_type == INITIAL; }))); QuicLongHeaderType long_packet_type = INVALID_PACKET_TYPE; PacketHeaderFormat packet_format; bool unused_version_flag; bool unused_use_length_prefix; QuicVersionLabel unused_version_label; ParsedQuicVersion unused_parsed_version = UnsupportedQuicVersion(); QuicConnectionId unused_destination_connection_id; QuicConnectionId unused_source_connection_id; std::optional<absl::string_view> unused_retry_token; std::string unused_detailed_error; QuicErrorCode error_code = QUIC_NO_ERROR; error_code = QuicFramer::ParsePublicHeaderDispatcher( packet_, kQuicDefaultConnectionIdLength, &packet_format, &long_packet_type, &unused_version_flag, &unused_use_length_prefix, &unused_version_label, &unused_parsed_version, &unused_destination_connection_id, &unused_source_connection_id, &unused_retry_token, &unused_detailed_error); EXPECT_THAT(error_code, IsQuicNoError()); EXPECT_NE(long_packet_type, INITIAL); EnqueuePacketToStore(store_, connection_id, packet_format, long_packet_type, packet_, self_address_, peer_address_, valid_version_, kNoParsedChlo, connection_id_generator_); EnqueuePacketToStore(store_, connection_id, IETF_QUIC_LONG_HEADER_PACKET, INITIAL, *initial_packets[0], self_address_, peer_address_, valid_version_, kNoParsedChlo, connection_id_generator_); EnqueuePacketToStore(store_, connection_id, IETF_QUIC_LONG_HEADER_PACKET, INITIAL, *initial_packets[1], self_address_, peer_address_, valid_version_, kNoParsedChlo, connection_id_generator_); BufferedPacketList delivered_packets = store_.DeliverPackets(connection_id); EXPECT_THAT(delivered_packets.buffered_packets, SizeIs(3)); QuicLongHeaderType previous_packet_type = INITIAL; for (const auto& packet : delivered_packets.buffered_packets) { error_code = QuicFramer::ParsePublicHeaderDispatcher( *packet.packet, kQuicDefaultConnectionIdLength, &packet_format, &long_packet_type, &unused_version_flag, &unused_use_length_prefix, &unused_version_label, &unused_parsed_version, &unused_destination_connection_id, &unused_source_connection_id, &unused_retry_token, &unused_detailed_error); EXPECT_THAT(error_code, IsQuicNoError()); EXPECT_THAT(long_packet_type, Conditional(previous_packet_type == INITIAL, A<QuicLongHeaderType>(), Ne(INITIAL))); previous_packet_type = long_packet_type; } } TEST_F(QuicBufferedPacketStoreTest, BufferedPacketRetainsEcn) { QuicConnectionId connection_id = TestConnectionId(1); QuicReceivedPacket ect1_packet(packet_content_.data(), packet_content_.size(), packet_time_, false, 0, true, nullptr, 0, false, ECN_ECT1); EnqueuePacketToStore(store_, connection_id, GOOGLE_QUIC_PACKET, INVALID_PACKET_TYPE, ect1_packet, self_address_, peer_address_, valid_version_, kNoParsedChlo, connection_id_generator_); BufferedPacketList delivered_packets = store_.DeliverPackets(connection_id); EXPECT_THAT(delivered_packets.buffered_packets, SizeIs(1)); for (const auto& packet : delivered_packets.buffered_packets) { EXPECT_EQ(packet.packet->ecn_codepoint(), ECN_ECT1); } } TEST_F(QuicBufferedPacketStoreTest, EmptyBufferedPacketList) { BufferedPacketList packet_list; EXPECT_TRUE(packet_list.buffered_packets.empty()); EXPECT_FALSE(packet_list.parsed_chlo.has_value()); EXPECT_FALSE(packet_list.version.IsKnown()); EXPECT_TRUE(packet_list.original_connection_id.IsEmpty()); EXPECT_FALSE(packet_list.replaced_connection_id.has_value()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_buffered_packet_store.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_buffered_packet_store_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
0adf63f2-e73f-44bf-be1b-a5882c8dd693
cpp
google/quiche
quic_server_id
quiche/quic/core/quic_server_id.cc
quiche/quic/core/quic_server_id_test.cc
#include "quiche/quic/core/quic_server_id.h" #include <optional> #include <string> #include <tuple> #include <utility> #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/common/platform/api/quiche_googleurl.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quic { std::optional<QuicServerId> QuicServerId::ParseFromHostPortString( absl::string_view host_port_string) { url::Component username_component; url::Component password_component; url::Component host_component; url::Component port_component; url::ParseAuthority(host_port_string.data(), url::Component(0, host_port_string.size()), &username_component, &password_component, &host_component, &port_component); if (username_component.is_valid() || password_component.is_valid() || !host_component.is_nonempty() || !port_component.is_nonempty()) { QUICHE_DVLOG(1) << "QuicServerId could not be parsed: " << host_port_string; return std::nullopt; } std::string hostname(host_port_string.data() + host_component.begin, host_component.len); int parsed_port_number = url::ParsePort(host_port_string.data(), port_component); if (parsed_port_number <= 0) { QUICHE_DVLOG(1) << "Port could not be parsed while parsing QuicServerId from: " << host_port_string; return std::nullopt; } QUICHE_DCHECK_LE(parsed_port_number, std::numeric_limits<uint16_t>::max()); return QuicServerId(std::move(hostname), static_cast<uint16_t>(parsed_port_number)); } QuicServerId::QuicServerId() : QuicServerId("", 0) {} QuicServerId::QuicServerId(std::string host, uint16_t port) : host_(std::move(host)), port_(port) {} QuicServerId::~QuicServerId() {} bool QuicServerId::operator<(const QuicServerId& other) const { return std::tie(port_, host_) < std::tie(other.port_, other.host_); } bool QuicServerId::operator==(const QuicServerId& other) const { return host_ == other.host_ && port_ == other.port_; } bool QuicServerId::operator!=(const QuicServerId& other) const { return !(*this == other); } std::string QuicServerId::ToHostPortString() const { return absl::StrCat(GetHostWithIpv6Brackets(), ":", port_); } absl::string_view QuicServerId::GetHostWithoutIpv6Brackets() const { if (host_.length() > 2 && host_.front() == '[' && host_.back() == ']') { return absl::string_view(host_.data() + 1, host_.length() - 2); } else { return host_; } } std::string QuicServerId::GetHostWithIpv6Brackets() const { if (!absl::StrContains(host_, ':') || host_.length() <= 2 || (host_.front() == '[' && host_.back() == ']')) { return host_; } else { return absl::StrCat("[", host_, "]"); } } }
#include "quiche/quic/core/quic_server_id.h" #include <optional> #include <string> #include "quiche/quic/platform/api/quic_test.h" namespace quic::test { namespace { using ::testing::Optional; using ::testing::Property; class QuicServerIdTest : public QuicTest {}; TEST_F(QuicServerIdTest, Constructor) { QuicServerId google_server_id("google.com", 10); EXPECT_EQ("google.com", google_server_id.host()); EXPECT_EQ(10, google_server_id.port()); QuicServerId private_server_id("mail.google.com", 12); EXPECT_EQ("mail.google.com", private_server_id.host()); EXPECT_EQ(12, private_server_id.port()); } TEST_F(QuicServerIdTest, LessThan) { QuicServerId a_10_https("a.com", 10); QuicServerId a_11_https("a.com", 11); QuicServerId b_10_https("b.com", 10); QuicServerId b_11_https("b.com", 11); EXPECT_FALSE(a_10_https < a_10_https); EXPECT_TRUE(a_10_https < a_11_https); EXPECT_TRUE(a_10_https < a_11_https); EXPECT_TRUE(a_10_https < b_10_https); EXPECT_TRUE(a_10_https < b_11_https); EXPECT_FALSE(a_11_https < a_10_https); EXPECT_FALSE(a_11_https < b_10_https); EXPECT_TRUE(a_11_https < b_11_https); EXPECT_FALSE(b_10_https < a_10_https); EXPECT_TRUE(b_10_https < a_11_https); EXPECT_TRUE(b_10_https < b_11_https); EXPECT_FALSE(b_11_https < a_10_https); EXPECT_FALSE(b_11_https < a_11_https); EXPECT_FALSE(b_11_https < b_10_https); } TEST_F(QuicServerIdTest, Equals) { QuicServerId a_10_https("a.com", 10); QuicServerId a_11_https("a.com", 11); QuicServerId b_10_https("b.com", 10); QuicServerId b_11_https("b.com", 11); EXPECT_NE(a_10_https, a_11_https); EXPECT_NE(a_10_https, b_10_https); EXPECT_NE(a_10_https, b_11_https); QuicServerId new_a_10_https("a.com", 10); QuicServerId new_a_11_https("a.com", 11); QuicServerId new_b_10_https("b.com", 10); QuicServerId new_b_11_https("b.com", 11); EXPECT_EQ(new_a_10_https, a_10_https); EXPECT_EQ(new_a_11_https, a_11_https); EXPECT_EQ(new_b_10_https, b_10_https); EXPECT_EQ(new_b_11_https, b_11_https); } TEST_F(QuicServerIdTest, Parse) { std::optional<QuicServerId> server_id = QuicServerId::ParseFromHostPortString("host.test:500"); EXPECT_THAT(server_id, Optional(Property(&QuicServerId::host, "host.test"))); EXPECT_THAT(server_id, Optional(Property(&QuicServerId::port, 500))); } TEST_F(QuicServerIdTest, CannotParseMissingPort) { std::optional<QuicServerId> server_id = QuicServerId::ParseFromHostPortString("host.test"); EXPECT_EQ(server_id, std::nullopt); } TEST_F(QuicServerIdTest, CannotParseEmptyPort) { std::optional<QuicServerId> server_id = QuicServerId::ParseFromHostPortString("host.test:"); EXPECT_EQ(server_id, std::nullopt); } TEST_F(QuicServerIdTest, CannotParseEmptyHost) { std::optional<QuicServerId> server_id = QuicServerId::ParseFromHostPortString(":500"); EXPECT_EQ(server_id, std::nullopt); } TEST_F(QuicServerIdTest, CannotParseUserInfo) { std::optional<QuicServerId> server_id = QuicServerId::ParseFromHostPortString("[email protected]:500"); EXPECT_EQ(server_id, std::nullopt); } TEST_F(QuicServerIdTest, ParseIpv6Literal) { std::optional<QuicServerId> server_id = QuicServerId::ParseFromHostPortString("[::1]:400"); EXPECT_THAT(server_id, Optional(Property(&QuicServerId::host, "[::1]"))); EXPECT_THAT(server_id, Optional(Property(&QuicServerId::port, 400))); } TEST_F(QuicServerIdTest, ParseUnbracketedIpv6Literal) { std::optional<QuicServerId> server_id = QuicServerId::ParseFromHostPortString("::1:400"); EXPECT_THAT(server_id, Optional(Property(&QuicServerId::host, "::1"))); EXPECT_THAT(server_id, Optional(Property(&QuicServerId::port, 400))); } TEST_F(QuicServerIdTest, AddBracketsToIpv6) { QuicServerId server_id("::1", 100); EXPECT_EQ(server_id.GetHostWithIpv6Brackets(), "[::1]"); EXPECT_EQ(server_id.ToHostPortString(), "[::1]:100"); } TEST_F(QuicServerIdTest, AddBracketsAlreadyIncluded) { QuicServerId server_id("[::1]", 100); EXPECT_EQ(server_id.GetHostWithIpv6Brackets(), "[::1]"); EXPECT_EQ(server_id.ToHostPortString(), "[::1]:100"); } TEST_F(QuicServerIdTest, AddBracketsNotAddedToNonIpv6) { QuicServerId server_id("host.test", 100); EXPECT_EQ(server_id.GetHostWithIpv6Brackets(), "host.test"); EXPECT_EQ(server_id.ToHostPortString(), "host.test:100"); } TEST_F(QuicServerIdTest, RemoveBracketsFromIpv6) { QuicServerId server_id("[::1]", 100); EXPECT_EQ(server_id.GetHostWithoutIpv6Brackets(), "::1"); } TEST_F(QuicServerIdTest, RemoveBracketsNotIncluded) { QuicServerId server_id("::1", 100); EXPECT_EQ(server_id.GetHostWithoutIpv6Brackets(), "::1"); } TEST_F(QuicServerIdTest, RemoveBracketsFromNonIpv6) { QuicServerId server_id("host.test", 100); EXPECT_EQ(server_id.GetHostWithoutIpv6Brackets(), "host.test"); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_server_id.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_server_id_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
60f20ad5-af5f-44be-868d-f9539a658eb7
cpp
google/quiche
quic_path_validator
quiche/quic/core/quic_path_validator.cc
quiche/quic/core/quic_path_validator_test.cc
#include "quiche/quic/core/quic_path_validator.h" #include <memory> #include <ostream> #include <utility> #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/platform/api/quic_socket_address.h" namespace quic { class RetryAlarmDelegate : public QuicAlarm::DelegateWithContext { public: explicit RetryAlarmDelegate(QuicPathValidator* path_validator, QuicConnectionContext* context) : QuicAlarm::DelegateWithContext(context), path_validator_(path_validator) {} RetryAlarmDelegate(const RetryAlarmDelegate&) = delete; RetryAlarmDelegate& operator=(const RetryAlarmDelegate&) = delete; void OnAlarm() override { path_validator_->OnRetryTimeout(); } private: QuicPathValidator* path_validator_; }; std::ostream& operator<<(std::ostream& os, const QuicPathValidationContext& context) { return os << " from " << context.self_address_ << " to " << context.peer_address_; } QuicPathValidator::QuicPathValidator(QuicAlarmFactory* alarm_factory, QuicConnectionArena* arena, SendDelegate* send_delegate, QuicRandom* random, const QuicClock* clock, QuicConnectionContext* context) : send_delegate_(send_delegate), random_(random), clock_(clock), retry_timer_(alarm_factory->CreateAlarm( arena->New<RetryAlarmDelegate>(this, context), arena)), retry_count_(0u) {} void QuicPathValidator::OnPathResponse(const QuicPathFrameBuffer& probing_data, QuicSocketAddress self_address) { if (!HasPendingPathValidation()) { return; } QUIC_DVLOG(1) << "Match PATH_RESPONSE received on " << self_address; QUIC_BUG_IF(quic_bug_12402_1, !path_context_->self_address().IsInitialized()) << "Self address should have been known by now"; if (self_address != path_context_->self_address()) { QUIC_DVLOG(1) << "Expect the response to be received on " << path_context_->self_address(); return; } for (auto it = probing_data_.begin(); it != probing_data_.end(); ++it) { if (it->frame_buffer == probing_data) { result_delegate_->OnPathValidationSuccess(std::move(path_context_), it->send_time); ResetPathValidation(); return; } } QUIC_DVLOG(1) << "PATH_RESPONSE with payload " << probing_data.data() << " doesn't match the probing data."; } void QuicPathValidator::StartPathValidation( std::unique_ptr<QuicPathValidationContext> context, std::unique_ptr<ResultDelegate> result_delegate, PathValidationReason reason) { QUICHE_DCHECK(context); QUIC_DLOG(INFO) << "Start validating path " << *context << " via writer: " << context->WriterToUse(); if (path_context_ != nullptr) { QUIC_BUG(quic_bug_10876_1) << "There is an on-going validation on path " << *path_context_; ResetPathValidation(); } reason_ = reason; path_context_ = std::move(context); result_delegate_ = std::move(result_delegate); SendPathChallengeAndSetAlarm(); } void QuicPathValidator::ResetPathValidation() { path_context_ = nullptr; result_delegate_ = nullptr; retry_timer_->Cancel(); retry_count_ = 0; reason_ = PathValidationReason::kReasonUnknown; } void QuicPathValidator::CancelPathValidation() { if (path_context_ == nullptr) { return; } QUIC_DVLOG(1) << "Cancel validation on path" << *path_context_; result_delegate_->OnPathValidationFailure(std::move(path_context_)); ResetPathValidation(); } bool QuicPathValidator::HasPendingPathValidation() const { return path_context_ != nullptr; } QuicPathValidationContext* QuicPathValidator::GetContext() const { return path_context_.get(); } std::unique_ptr<QuicPathValidationContext> QuicPathValidator::ReleaseContext() { auto ret = std::move(path_context_); ResetPathValidation(); return ret; } const QuicPathFrameBuffer& QuicPathValidator::GeneratePathChallengePayload() { probing_data_.emplace_back(clock_->Now()); random_->RandBytes(probing_data_.back().frame_buffer.data(), sizeof(QuicPathFrameBuffer)); return probing_data_.back().frame_buffer; } void QuicPathValidator::OnRetryTimeout() { ++retry_count_; if (retry_count_ > kMaxRetryTimes) { CancelPathValidation(); return; } QUIC_DVLOG(1) << "Send another PATH_CHALLENGE on path " << *path_context_; SendPathChallengeAndSetAlarm(); } void QuicPathValidator::SendPathChallengeAndSetAlarm() { bool should_continue = send_delegate_->SendPathChallenge( GeneratePathChallengePayload(), path_context_->self_address(), path_context_->peer_address(), path_context_->effective_peer_address(), path_context_->WriterToUse()); if (!should_continue) { CancelPathValidation(); return; } retry_timer_->Set(send_delegate_->GetRetryTimeout( path_context_->peer_address(), path_context_->WriterToUse())); } bool QuicPathValidator::IsValidatingPeerAddress( const QuicSocketAddress& effective_peer_address) { return path_context_ != nullptr && path_context_->effective_peer_address() == effective_peer_address; } void QuicPathValidator::MaybeWritePacketToAddress( const char* buffer, size_t buf_len, const QuicSocketAddress& peer_address) { if (!HasPendingPathValidation() || path_context_->peer_address() != peer_address) { return; } QUIC_DVLOG(1) << "Path validator is sending packet of size " << buf_len << " from " << path_context_->self_address() << " to " << path_context_->peer_address(); path_context_->WriterToUse()->WritePacket( buffer, buf_len, path_context_->self_address().host(), path_context_->peer_address(), nullptr, QuicPacketWriterParams()); } }
#include "quiche/quic/core/quic_path_validator.h" #include <memory> #include "quiche/quic/core/frames/quic_path_challenge_frame.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_types.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/mock_clock.h" #include "quiche/quic/test_tools/mock_random.h" #include "quiche/quic/test_tools/quic_path_validator_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" using testing::_; using testing::Invoke; using testing::Return; namespace quic { namespace test { class MockSendDelegate : public QuicPathValidator::SendDelegate { public: MOCK_METHOD(bool, SendPathChallenge, (const QuicPathFrameBuffer&, const QuicSocketAddress&, const QuicSocketAddress&, const QuicSocketAddress&, QuicPacketWriter*), (override)); MOCK_METHOD(QuicTime, GetRetryTimeout, (const QuicSocketAddress&, QuicPacketWriter*), (const, override)); }; class QuicPathValidatorTest : public QuicTest { public: QuicPathValidatorTest() : path_validator_(&alarm_factory_, &arena_, &send_delegate_, &random_, &clock_, nullptr), context_(new MockQuicPathValidationContext( self_address_, peer_address_, effective_peer_address_, &writer_)), result_delegate_( new testing::StrictMock<MockQuicPathValidationResultDelegate>()) { clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1)); ON_CALL(send_delegate_, GetRetryTimeout(_, _)) .WillByDefault( Return(clock_.ApproximateNow() + 3 * QuicTime::Delta::FromMilliseconds(kInitialRttMs))); } protected: quic::test::MockAlarmFactory alarm_factory_; MockSendDelegate send_delegate_; MockRandom random_; MockClock clock_; QuicConnectionArena arena_; QuicPathValidator path_validator_; QuicSocketAddress self_address_{QuicIpAddress::Any4(), 443}; QuicSocketAddress peer_address_{QuicIpAddress::Loopback4(), 443}; QuicSocketAddress effective_peer_address_{QuicIpAddress::Loopback4(), 12345}; MockPacketWriter writer_; MockQuicPathValidationContext* context_; MockQuicPathValidationResultDelegate* result_delegate_; }; TEST_F(QuicPathValidatorTest, PathValidationSuccessOnFirstRound) { QuicPathFrameBuffer challenge_data; EXPECT_CALL(send_delegate_, SendPathChallenge(_, self_address_, peer_address_, effective_peer_address_, &writer_)) .WillOnce(Invoke([&](const QuicPathFrameBuffer& payload, const QuicSocketAddress&, const QuicSocketAddress&, const QuicSocketAddress&, QuicPacketWriter*) { memcpy(challenge_data.data(), payload.data(), payload.size()); return true; })); EXPECT_CALL(send_delegate_, GetRetryTimeout(peer_address_, &writer_)); const QuicTime expected_start_time = clock_.Now(); path_validator_.StartPathValidation( std::unique_ptr<QuicPathValidationContext>(context_), std::unique_ptr<MockQuicPathValidationResultDelegate>(result_delegate_), PathValidationReason::kMultiPort); EXPECT_TRUE(path_validator_.HasPendingPathValidation()); EXPECT_EQ(PathValidationReason::kMultiPort, path_validator_.GetPathValidationReason()); EXPECT_TRUE(path_validator_.IsValidatingPeerAddress(effective_peer_address_)); EXPECT_CALL(*result_delegate_, OnPathValidationSuccess(_, _)) .WillOnce( Invoke([=, this](std::unique_ptr<QuicPathValidationContext> context, QuicTime start_time) { EXPECT_EQ(context.get(), context_); EXPECT_EQ(start_time, expected_start_time); })); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(kInitialRttMs)); path_validator_.OnPathResponse(challenge_data, self_address_); EXPECT_FALSE(path_validator_.HasPendingPathValidation()); EXPECT_EQ(PathValidationReason::kReasonUnknown, path_validator_.GetPathValidationReason()); } TEST_F(QuicPathValidatorTest, RespondWithDifferentSelfAddress) { QuicPathFrameBuffer challenge_data; EXPECT_CALL(send_delegate_, SendPathChallenge(_, self_address_, peer_address_, effective_peer_address_, &writer_)) .WillOnce(Invoke([&](const QuicPathFrameBuffer payload, const QuicSocketAddress&, const QuicSocketAddress&, const QuicSocketAddress&, QuicPacketWriter*) { memcpy(challenge_data.data(), payload.data(), payload.size()); return true; })); EXPECT_CALL(send_delegate_, GetRetryTimeout(peer_address_, &writer_)); const QuicTime expected_start_time = clock_.Now(); path_validator_.StartPathValidation( std::unique_ptr<QuicPathValidationContext>(context_), std::unique_ptr<MockQuicPathValidationResultDelegate>(result_delegate_), PathValidationReason::kMultiPort); const QuicSocketAddress kAlternativeSelfAddress(QuicIpAddress::Any6(), 54321); EXPECT_NE(kAlternativeSelfAddress, self_address_); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(kInitialRttMs)); path_validator_.OnPathResponse(challenge_data, kAlternativeSelfAddress); EXPECT_CALL(*result_delegate_, OnPathValidationSuccess(_, _)) .WillOnce( Invoke([=, this](std::unique_ptr<QuicPathValidationContext> context, QuicTime start_time) { EXPECT_EQ(context->self_address(), self_address_); EXPECT_EQ(start_time, expected_start_time); })); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(kInitialRttMs)); path_validator_.OnPathResponse(challenge_data, self_address_); EXPECT_EQ(PathValidationReason::kReasonUnknown, path_validator_.GetPathValidationReason()); } TEST_F(QuicPathValidatorTest, RespondAfter1stRetry) { QuicPathFrameBuffer challenge_data; EXPECT_CALL(send_delegate_, SendPathChallenge(_, self_address_, peer_address_, effective_peer_address_, &writer_)) .WillOnce(Invoke([&](const QuicPathFrameBuffer& payload, const QuicSocketAddress&, const QuicSocketAddress&, const QuicSocketAddress&, QuicPacketWriter*) { memcpy(challenge_data.data(), payload.data(), payload.size()); return true; })) .WillOnce(Invoke([&](const QuicPathFrameBuffer& payload, const QuicSocketAddress&, const QuicSocketAddress&, const QuicSocketAddress&, QuicPacketWriter*) { EXPECT_NE(payload, challenge_data); return true; })); EXPECT_CALL(send_delegate_, GetRetryTimeout(peer_address_, &writer_)) .Times(2u); const QuicTime start_time = clock_.Now(); path_validator_.StartPathValidation( std::unique_ptr<QuicPathValidationContext>(context_), std::unique_ptr<MockQuicPathValidationResultDelegate>(result_delegate_), PathValidationReason::kMultiPort); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs)); random_.ChangeValue(); alarm_factory_.FireAlarm( QuicPathValidatorPeer::retry_timer(&path_validator_)); EXPECT_CALL(*result_delegate_, OnPathValidationSuccess(_, start_time)); path_validator_.OnPathResponse(challenge_data, self_address_); EXPECT_FALSE(path_validator_.HasPendingPathValidation()); } TEST_F(QuicPathValidatorTest, RespondToRetryChallenge) { QuicPathFrameBuffer challenge_data; EXPECT_CALL(send_delegate_, SendPathChallenge(_, self_address_, peer_address_, effective_peer_address_, &writer_)) .WillOnce(Invoke([&](const QuicPathFrameBuffer& payload, const QuicSocketAddress&, const QuicSocketAddress&, const QuicSocketAddress&, QuicPacketWriter*) { memcpy(challenge_data.data(), payload.data(), payload.size()); return true; })) .WillOnce(Invoke([&](const QuicPathFrameBuffer& payload, const QuicSocketAddress&, const QuicSocketAddress&, const QuicSocketAddress&, QuicPacketWriter*) { EXPECT_NE(challenge_data, payload); memcpy(challenge_data.data(), payload.data(), payload.size()); return true; })); EXPECT_CALL(send_delegate_, GetRetryTimeout(peer_address_, &writer_)) .Times(2u); path_validator_.StartPathValidation( std::unique_ptr<QuicPathValidationContext>(context_), std::unique_ptr<MockQuicPathValidationResultDelegate>(result_delegate_), PathValidationReason::kMultiPort); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs)); const QuicTime start_time = clock_.Now(); random_.ChangeValue(); alarm_factory_.FireAlarm( QuicPathValidatorPeer::retry_timer(&path_validator_)); EXPECT_CALL(*result_delegate_, OnPathValidationSuccess(_, start_time)); path_validator_.OnPathResponse(challenge_data, self_address_); EXPECT_FALSE(path_validator_.HasPendingPathValidation()); } TEST_F(QuicPathValidatorTest, ValidationTimeOut) { EXPECT_CALL(send_delegate_, SendPathChallenge(_, self_address_, peer_address_, effective_peer_address_, &writer_)) .Times(3u) .WillRepeatedly(Return(true)); EXPECT_CALL(send_delegate_, GetRetryTimeout(peer_address_, &writer_)) .Times(3u); path_validator_.StartPathValidation( std::unique_ptr<QuicPathValidationContext>(context_), std::unique_ptr<MockQuicPathValidationResultDelegate>(result_delegate_), PathValidationReason::kMultiPort); QuicPathFrameBuffer challenge_data; memset(challenge_data.data(), 'a', challenge_data.size()); path_validator_.OnPathResponse(challenge_data, self_address_); EXPECT_CALL(*result_delegate_, OnPathValidationFailure(_)) .WillOnce( Invoke([=, this](std::unique_ptr<QuicPathValidationContext> context) { EXPECT_EQ(context_, context.get()); })); for (size_t i = 0; i <= QuicPathValidator::kMaxRetryTimes; ++i) { clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs)); alarm_factory_.FireAlarm( QuicPathValidatorPeer::retry_timer(&path_validator_)); } EXPECT_EQ(PathValidationReason::kReasonUnknown, path_validator_.GetPathValidationReason()); } TEST_F(QuicPathValidatorTest, SendPathChallengeError) { EXPECT_CALL(send_delegate_, SendPathChallenge(_, self_address_, peer_address_, effective_peer_address_, &writer_)) .WillOnce(Invoke([&](const QuicPathFrameBuffer&, const QuicSocketAddress&, const QuicSocketAddress&, const QuicSocketAddress&, QuicPacketWriter*) { path_validator_.CancelPathValidation(); return false; })); EXPECT_CALL(send_delegate_, GetRetryTimeout(peer_address_, &writer_)) .Times(0u); EXPECT_CALL(*result_delegate_, OnPathValidationFailure(_)); path_validator_.StartPathValidation( std::unique_ptr<QuicPathValidationContext>(context_), std::unique_ptr<MockQuicPathValidationResultDelegate>(result_delegate_), PathValidationReason::kMultiPort); EXPECT_FALSE(path_validator_.HasPendingPathValidation()); EXPECT_FALSE(QuicPathValidatorPeer::retry_timer(&path_validator_)->IsSet()); EXPECT_EQ(PathValidationReason::kReasonUnknown, path_validator_.GetPathValidationReason()); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_path_validator.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_path_validator_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
21de3764-d775-4eb2-95c1-d92abb056bcf
cpp
google/quiche
quic_network_blackhole_detector
quiche/quic/core/quic_network_blackhole_detector.cc
quiche/quic/core/quic_network_blackhole_detector_test.cc
#include "quiche/quic/core/quic_network_blackhole_detector.h" #include <algorithm> #include "quiche/quic/core/quic_constants.h" namespace quic { QuicNetworkBlackholeDetector::QuicNetworkBlackholeDetector(Delegate* delegate, QuicAlarm* alarm) : delegate_(delegate), alarm_(*alarm) {} void QuicNetworkBlackholeDetector::OnAlarm() { QuicTime next_deadline = GetEarliestDeadline(); if (!next_deadline.IsInitialized()) { QUIC_BUG(quic_bug_10328_1) << "BlackholeDetector alarm fired unexpectedly"; return; } QUIC_DVLOG(1) << "BlackholeDetector alarm firing. next_deadline:" << next_deadline << ", path_degrading_deadline_:" << path_degrading_deadline_ << ", path_mtu_reduction_deadline_:" << path_mtu_reduction_deadline_ << ", blackhole_deadline_:" << blackhole_deadline_; if (path_degrading_deadline_ == next_deadline) { path_degrading_deadline_ = QuicTime::Zero(); delegate_->OnPathDegradingDetected(); } if (path_mtu_reduction_deadline_ == next_deadline) { path_mtu_reduction_deadline_ = QuicTime::Zero(); delegate_->OnPathMtuReductionDetected(); } if (blackhole_deadline_ == next_deadline) { blackhole_deadline_ = QuicTime::Zero(); delegate_->OnBlackholeDetected(); } UpdateAlarm(); } void QuicNetworkBlackholeDetector::StopDetection(bool permanent) { if (permanent) { alarm_.PermanentCancel(); } else { alarm_.Cancel(); } path_degrading_deadline_ = QuicTime::Zero(); blackhole_deadline_ = QuicTime::Zero(); path_mtu_reduction_deadline_ = QuicTime::Zero(); } void QuicNetworkBlackholeDetector::RestartDetection( QuicTime path_degrading_deadline, QuicTime blackhole_deadline, QuicTime path_mtu_reduction_deadline) { path_degrading_deadline_ = path_degrading_deadline; blackhole_deadline_ = blackhole_deadline; path_mtu_reduction_deadline_ = path_mtu_reduction_deadline; QUIC_BUG_IF(quic_bug_12708_1, blackhole_deadline_.IsInitialized() && blackhole_deadline_ != GetLastDeadline()) << "Blackhole detection deadline should be the last deadline."; UpdateAlarm(); } QuicTime QuicNetworkBlackholeDetector::GetEarliestDeadline() const { QuicTime result = QuicTime::Zero(); for (QuicTime t : {path_degrading_deadline_, blackhole_deadline_, path_mtu_reduction_deadline_}) { if (!t.IsInitialized()) { continue; } if (!result.IsInitialized() || t < result) { result = t; } } return result; } QuicTime QuicNetworkBlackholeDetector::GetLastDeadline() const { return std::max({path_degrading_deadline_, blackhole_deadline_, path_mtu_reduction_deadline_}); } void QuicNetworkBlackholeDetector::UpdateAlarm() const { if (alarm_.IsPermanentlyCancelled()) { return; } QuicTime next_deadline = GetEarliestDeadline(); QUIC_DVLOG(1) << "Updating alarm. next_deadline:" << next_deadline << ", path_degrading_deadline_:" << path_degrading_deadline_ << ", path_mtu_reduction_deadline_:" << path_mtu_reduction_deadline_ << ", blackhole_deadline_:" << blackhole_deadline_; alarm_.Update(next_deadline, kAlarmGranularity); } bool QuicNetworkBlackholeDetector::IsDetectionInProgress() const { return alarm_.IsSet(); } }
#include "quiche/quic/core/quic_network_blackhole_detector.h" #include "quiche/quic/core/quic_connection_alarms.h" #include "quiche/quic/core/quic_one_block_arena.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/mock_quic_connection_alarms.h" #include "quiche/quic/test_tools/quic_test_utils.h" namespace quic { namespace test { class QuicNetworkBlackholeDetectorPeer { public: static QuicAlarm* GetAlarm(QuicNetworkBlackholeDetector* detector) { return &detector->alarm_; } }; namespace { class MockDelegate : public QuicNetworkBlackholeDetector::Delegate { public: MOCK_METHOD(void, OnPathDegradingDetected, (), (override)); MOCK_METHOD(void, OnBlackholeDetected, (), (override)); MOCK_METHOD(void, OnPathMtuReductionDetected, (), (override)); }; const size_t kPathDegradingDelayInSeconds = 5; const size_t kPathMtuReductionDelayInSeconds = 7; const size_t kBlackholeDelayInSeconds = 10; class QuicNetworkBlackholeDetectorTest : public QuicTest { public: QuicNetworkBlackholeDetectorTest() : alarms_(&connection_alarms_delegate_, alarm_factory_, arena_), detector_(&delegate_, &alarms_.network_blackhole_detector_alarm()), alarm_(static_cast<MockAlarmFactory::TestAlarm*>( QuicNetworkBlackholeDetectorPeer::GetAlarm(&detector_))), path_degrading_delay_( QuicTime::Delta::FromSeconds(kPathDegradingDelayInSeconds)), path_mtu_reduction_delay_( QuicTime::Delta::FromSeconds(kPathMtuReductionDelayInSeconds)), blackhole_delay_( QuicTime::Delta::FromSeconds(kBlackholeDelayInSeconds)) { clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1)); ON_CALL(connection_alarms_delegate_, OnNetworkBlackholeDetectorAlarm()) .WillByDefault([&] { detector_.OnAlarm(); }); } protected: void RestartDetection() { detector_.RestartDetection(clock_.Now() + path_degrading_delay_, clock_.Now() + blackhole_delay_, clock_.Now() + path_mtu_reduction_delay_); } testing::StrictMock<MockDelegate> delegate_; MockConnectionAlarmsDelegate connection_alarms_delegate_; QuicConnectionArena arena_; MockAlarmFactory alarm_factory_; QuicConnectionAlarms alarms_; QuicNetworkBlackholeDetector detector_; MockAlarmFactory::TestAlarm* alarm_; MockClock clock_; const QuicTime::Delta path_degrading_delay_; const QuicTime::Delta path_mtu_reduction_delay_; const QuicTime::Delta blackhole_delay_; }; TEST_F(QuicNetworkBlackholeDetectorTest, StartAndFire) { EXPECT_FALSE(detector_.IsDetectionInProgress()); RestartDetection(); EXPECT_TRUE(detector_.IsDetectionInProgress()); EXPECT_EQ(clock_.Now() + path_degrading_delay_, alarm_->deadline()); clock_.AdvanceTime(path_degrading_delay_); EXPECT_CALL(delegate_, OnPathDegradingDetected()); alarm_->Fire(); EXPECT_TRUE(detector_.IsDetectionInProgress()); EXPECT_EQ(clock_.Now() + path_mtu_reduction_delay_ - path_degrading_delay_, alarm_->deadline()); clock_.AdvanceTime(path_mtu_reduction_delay_ - path_degrading_delay_); EXPECT_CALL(delegate_, OnPathMtuReductionDetected()); alarm_->Fire(); EXPECT_TRUE(detector_.IsDetectionInProgress()); EXPECT_EQ(clock_.Now() + blackhole_delay_ - path_mtu_reduction_delay_, alarm_->deadline()); clock_.AdvanceTime(blackhole_delay_ - path_mtu_reduction_delay_); EXPECT_CALL(delegate_, OnBlackholeDetected()); alarm_->Fire(); EXPECT_FALSE(detector_.IsDetectionInProgress()); } TEST_F(QuicNetworkBlackholeDetectorTest, RestartAndStop) { RestartDetection(); clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1)); RestartDetection(); EXPECT_EQ(clock_.Now() + path_degrading_delay_, alarm_->deadline()); detector_.StopDetection(false); EXPECT_FALSE(detector_.IsDetectionInProgress()); } TEST_F(QuicNetworkBlackholeDetectorTest, PathDegradingFiresAndRestart) { EXPECT_FALSE(detector_.IsDetectionInProgress()); RestartDetection(); EXPECT_TRUE(detector_.IsDetectionInProgress()); EXPECT_EQ(clock_.Now() + path_degrading_delay_, alarm_->deadline()); clock_.AdvanceTime(path_degrading_delay_); EXPECT_CALL(delegate_, OnPathDegradingDetected()); alarm_->Fire(); EXPECT_TRUE(detector_.IsDetectionInProgress()); EXPECT_EQ(clock_.Now() + path_mtu_reduction_delay_ - path_degrading_delay_, alarm_->deadline()); clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100)); RestartDetection(); EXPECT_EQ(clock_.Now() + path_degrading_delay_, alarm_->deadline()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_network_blackhole_detector.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_network_blackhole_detector_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
ee933ba6-047b-4c1a-ac4f-ae4936556cca
cpp
google/quiche
quic_write_blocked_list
quiche/quic/core/quic_write_blocked_list.cc
quiche/quic/core/quic_write_blocked_list_test.cc
#include "quiche/quic/core/quic_write_blocked_list.h" #include <algorithm> #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" namespace quic { QuicWriteBlockedList::QuicWriteBlockedList() : last_priority_popped_(0), respect_incremental_( GetQuicReloadableFlag(quic_priority_respect_incremental)), disable_batch_write_(GetQuicReloadableFlag(quic_disable_batch_write)) { memset(batch_write_stream_id_, 0, sizeof(batch_write_stream_id_)); memset(bytes_left_for_batch_write_, 0, sizeof(bytes_left_for_batch_write_)); } bool QuicWriteBlockedList::ShouldYield(QuicStreamId id) const { for (const auto& stream : static_stream_collection_) { if (stream.id == id) { return false; } if (stream.is_blocked) { return true; } } return priority_write_scheduler_.ShouldYield(id); } QuicStreamId QuicWriteBlockedList::PopFront() { QuicStreamId static_stream_id; if (static_stream_collection_.UnblockFirstBlocked(&static_stream_id)) { return static_stream_id; } const auto [id, priority] = priority_write_scheduler_.PopNextReadyStreamAndPriority(); const spdy::SpdyPriority urgency = priority.urgency; const bool incremental = priority.incremental; last_priority_popped_ = urgency; if (disable_batch_write_) { QUIC_RELOADABLE_FLAG_COUNT_N(quic_disable_batch_write, 1, 3); if (!respect_incremental_ || !incremental) { batch_write_stream_id_[urgency] = id; } return id; } if (!priority_write_scheduler_.HasReadyStreams()) { batch_write_stream_id_[urgency] = 0; } else if (batch_write_stream_id_[urgency] != id) { batch_write_stream_id_[urgency] = id; bytes_left_for_batch_write_[urgency] = 16000; } return id; } void QuicWriteBlockedList::RegisterStream(QuicStreamId stream_id, bool is_static_stream, const QuicStreamPriority& priority) { QUICHE_DCHECK(!priority_write_scheduler_.StreamRegistered(stream_id)) << "stream " << stream_id << " already registered"; if (is_static_stream) { static_stream_collection_.Register(stream_id); return; } priority_write_scheduler_.RegisterStream(stream_id, priority.http()); } void QuicWriteBlockedList::UnregisterStream(QuicStreamId stream_id) { if (static_stream_collection_.Unregister(stream_id)) { return; } priority_write_scheduler_.UnregisterStream(stream_id); } void QuicWriteBlockedList::UpdateStreamPriority( QuicStreamId stream_id, const QuicStreamPriority& new_priority) { QUICHE_DCHECK(!static_stream_collection_.IsRegistered(stream_id)); priority_write_scheduler_.UpdateStreamPriority(stream_id, new_priority.http()); } void QuicWriteBlockedList::UpdateBytesForStream(QuicStreamId stream_id, size_t bytes) { if (disable_batch_write_) { QUIC_RELOADABLE_FLAG_COUNT_N(quic_disable_batch_write, 2, 3); return; } if (batch_write_stream_id_[last_priority_popped_] == stream_id) { bytes_left_for_batch_write_[last_priority_popped_] -= std::min(bytes_left_for_batch_write_[last_priority_popped_], bytes); } } void QuicWriteBlockedList::AddStream(QuicStreamId stream_id) { if (static_stream_collection_.SetBlocked(stream_id)) { return; } if (respect_incremental_) { QUIC_RELOADABLE_FLAG_COUNT(quic_priority_respect_incremental); if (!priority_write_scheduler_.GetStreamPriority(stream_id).incremental) { const bool push_front = stream_id == batch_write_stream_id_[last_priority_popped_]; priority_write_scheduler_.MarkStreamReady(stream_id, push_front); return; } } if (disable_batch_write_) { QUIC_RELOADABLE_FLAG_COUNT_N(quic_disable_batch_write, 3, 3); priority_write_scheduler_.MarkStreamReady(stream_id, false); return; } const bool push_front = stream_id == batch_write_stream_id_[last_priority_popped_] && bytes_left_for_batch_write_[last_priority_popped_] > 0; priority_write_scheduler_.MarkStreamReady(stream_id, push_front); } bool QuicWriteBlockedList::IsStreamBlocked(QuicStreamId stream_id) const { for (const auto& stream : static_stream_collection_) { if (stream.id == stream_id) { return stream.is_blocked; } } return priority_write_scheduler_.IsStreamReady(stream_id); } void QuicWriteBlockedList::StaticStreamCollection::Register(QuicStreamId id) { QUICHE_DCHECK(!IsRegistered(id)); streams_.push_back({id, false}); } bool QuicWriteBlockedList::StaticStreamCollection::IsRegistered( QuicStreamId id) const { for (const auto& stream : streams_) { if (stream.id == id) { return true; } } return false; } bool QuicWriteBlockedList::StaticStreamCollection::Unregister(QuicStreamId id) { for (auto it = streams_.begin(); it != streams_.end(); ++it) { if (it->id == id) { if (it->is_blocked) { --num_blocked_; } streams_.erase(it); return true; } } return false; } bool QuicWriteBlockedList::StaticStreamCollection::SetBlocked(QuicStreamId id) { for (auto& stream : streams_) { if (stream.id == id) { if (!stream.is_blocked) { stream.is_blocked = true; ++num_blocked_; } return true; } } return false; } bool QuicWriteBlockedList::StaticStreamCollection::UnblockFirstBlocked( QuicStreamId* id) { for (auto& stream : streams_) { if (stream.is_blocked) { --num_blocked_; stream.is_blocked = false; *id = stream.id; return true; } } return false; } }
#include "quiche/quic/core/quic_write_blocked_list.h" #include <optional> #include <tuple> #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/platform/api/quiche_expect_bug.h" using spdy::kV3HighestPriority; using spdy::kV3LowestPriority; namespace quic { namespace test { namespace { constexpr bool kStatic = true; constexpr bool kNotStatic = false; constexpr bool kIncremental = true; constexpr bool kNotIncremental = false; class QuicWriteBlockedListTest : public QuicTest { protected: void SetUp() override { write_blocked_list_.emplace(); } bool HasWriteBlockedDataStreams() const { return write_blocked_list_->HasWriteBlockedDataStreams(); } bool HasWriteBlockedSpecialStream() const { return write_blocked_list_->HasWriteBlockedSpecialStream(); } size_t NumBlockedSpecialStreams() const { return write_blocked_list_->NumBlockedSpecialStreams(); } size_t NumBlockedStreams() const { return write_blocked_list_->NumBlockedStreams(); } bool ShouldYield(QuicStreamId id) const { return write_blocked_list_->ShouldYield(id); } QuicStreamPriority GetPriorityOfStream(QuicStreamId id) const { return write_blocked_list_->GetPriorityOfStream(id); } QuicStreamId PopFront() { return write_blocked_list_->PopFront(); } void RegisterStream(QuicStreamId stream_id, bool is_static_stream, const HttpStreamPriority& priority) { write_blocked_list_->RegisterStream(stream_id, is_static_stream, QuicStreamPriority(priority)); } void UnregisterStream(QuicStreamId stream_id) { write_blocked_list_->UnregisterStream(stream_id); } void UpdateStreamPriority(QuicStreamId stream_id, const HttpStreamPriority& new_priority) { write_blocked_list_->UpdateStreamPriority(stream_id, QuicStreamPriority(new_priority)); } void UpdateBytesForStream(QuicStreamId stream_id, size_t bytes) { write_blocked_list_->UpdateBytesForStream(stream_id, bytes); } void AddStream(QuicStreamId stream_id) { write_blocked_list_->AddStream(stream_id); } bool IsStreamBlocked(QuicStreamId stream_id) const { return write_blocked_list_->IsStreamBlocked(stream_id); } private: std::optional<QuicWriteBlockedList> write_blocked_list_; }; TEST_F(QuicWriteBlockedListTest, PriorityOrder) { RegisterStream(40, kNotStatic, {kV3LowestPriority, kNotIncremental}); RegisterStream(23, kNotStatic, {kV3HighestPriority, kIncremental}); RegisterStream(17, kNotStatic, {kV3HighestPriority, kNotIncremental}); RegisterStream(1, kStatic, {kV3HighestPriority, kNotIncremental}); RegisterStream(3, kStatic, {kV3HighestPriority, kNotIncremental}); EXPECT_EQ(kV3LowestPriority, GetPriorityOfStream(40).http().urgency); EXPECT_EQ(kNotIncremental, GetPriorityOfStream(40).http().incremental); EXPECT_EQ(kV3HighestPriority, GetPriorityOfStream(23).http().urgency); EXPECT_EQ(kIncremental, GetPriorityOfStream(23).http().incremental); EXPECT_EQ(kV3HighestPriority, GetPriorityOfStream(17).http().urgency); EXPECT_EQ(kNotIncremental, GetPriorityOfStream(17).http().incremental); AddStream(40); EXPECT_TRUE(IsStreamBlocked(40)); AddStream(23); EXPECT_TRUE(IsStreamBlocked(23)); AddStream(17); EXPECT_TRUE(IsStreamBlocked(17)); AddStream(3); EXPECT_TRUE(IsStreamBlocked(3)); AddStream(1); EXPECT_TRUE(IsStreamBlocked(1)); EXPECT_EQ(5u, NumBlockedStreams()); EXPECT_TRUE(HasWriteBlockedSpecialStream()); EXPECT_EQ(2u, NumBlockedSpecialStreams()); EXPECT_TRUE(HasWriteBlockedDataStreams()); EXPECT_EQ(1u, PopFront()); EXPECT_EQ(1u, NumBlockedSpecialStreams()); EXPECT_FALSE(IsStreamBlocked(1)); EXPECT_EQ(3u, PopFront()); EXPECT_EQ(0u, NumBlockedSpecialStreams()); EXPECT_FALSE(IsStreamBlocked(3)); EXPECT_EQ(23u, PopFront()); EXPECT_FALSE(IsStreamBlocked(23)); EXPECT_EQ(17u, PopFront()); EXPECT_FALSE(IsStreamBlocked(17)); EXPECT_EQ(40u, PopFront()); EXPECT_FALSE(IsStreamBlocked(40)); EXPECT_EQ(0u, NumBlockedStreams()); EXPECT_FALSE(HasWriteBlockedSpecialStream()); EXPECT_FALSE(HasWriteBlockedDataStreams()); } TEST_F(QuicWriteBlockedListTest, SingleStaticStream) { RegisterStream(5, kStatic, {kV3HighestPriority, kNotIncremental}); AddStream(5); EXPECT_EQ(1u, NumBlockedStreams()); EXPECT_TRUE(HasWriteBlockedSpecialStream()); EXPECT_EQ(5u, PopFront()); EXPECT_EQ(0u, NumBlockedStreams()); EXPECT_FALSE(HasWriteBlockedSpecialStream()); } TEST_F(QuicWriteBlockedListTest, StaticStreamsComeFirst) { RegisterStream(5, kNotStatic, {kV3HighestPriority, kNotIncremental}); RegisterStream(3, kStatic, {kV3LowestPriority, kNotIncremental}); AddStream(5); AddStream(3); EXPECT_EQ(2u, NumBlockedStreams()); EXPECT_TRUE(HasWriteBlockedSpecialStream()); EXPECT_TRUE(HasWriteBlockedDataStreams()); EXPECT_EQ(3u, PopFront()); EXPECT_EQ(5u, PopFront()); EXPECT_EQ(0u, NumBlockedStreams()); EXPECT_FALSE(HasWriteBlockedSpecialStream()); EXPECT_FALSE(HasWriteBlockedDataStreams()); } TEST_F(QuicWriteBlockedListTest, NoDuplicateEntries) { const QuicStreamId kBlockedId = 5; RegisterStream(kBlockedId, kNotStatic, {kV3HighestPriority, kNotIncremental}); AddStream(kBlockedId); AddStream(kBlockedId); AddStream(kBlockedId); EXPECT_EQ(1u, NumBlockedStreams()); EXPECT_TRUE(HasWriteBlockedDataStreams()); EXPECT_EQ(kBlockedId, PopFront()); EXPECT_EQ(0u, NumBlockedStreams()); EXPECT_FALSE(HasWriteBlockedDataStreams()); } TEST_F(QuicWriteBlockedListTest, IncrementalStreamsRoundRobin) { const QuicStreamId id1 = 5; const QuicStreamId id2 = 7; const QuicStreamId id3 = 9; RegisterStream(id1, kNotStatic, {kV3LowestPriority, kIncremental}); RegisterStream(id2, kNotStatic, {kV3LowestPriority, kIncremental}); RegisterStream(id3, kNotStatic, {kV3LowestPriority, kIncremental}); AddStream(id1); AddStream(id2); AddStream(id3); EXPECT_EQ(id1, PopFront()); const size_t kLargeWriteSize = 1000 * 1000 * 1000; UpdateBytesForStream(id1, kLargeWriteSize); AddStream(id1); EXPECT_EQ(id2, PopFront()); UpdateBytesForStream(id2, kLargeWriteSize); EXPECT_EQ(id3, PopFront()); UpdateBytesForStream(id3, kLargeWriteSize); AddStream(id3); AddStream(id2); EXPECT_EQ(id1, PopFront()); UpdateBytesForStream(id1, kLargeWriteSize); EXPECT_EQ(id3, PopFront()); UpdateBytesForStream(id3, kLargeWriteSize); AddStream(id3); EXPECT_EQ(id2, PopFront()); EXPECT_EQ(id3, PopFront()); } class QuicWriteBlockedListParameterizedTest : public QuicWriteBlockedListTest, public ::testing::WithParamInterface<std::tuple<bool, bool>> { protected: QuicWriteBlockedListParameterizedTest() : priority_respect_incremental_(std::get<0>(GetParam())), disable_batch_write_(std::get<1>(GetParam())) { SetQuicReloadableFlag(quic_priority_respect_incremental, priority_respect_incremental_); SetQuicReloadableFlag(quic_disable_batch_write, disable_batch_write_); } const bool priority_respect_incremental_; const bool disable_batch_write_; }; INSTANTIATE_TEST_SUITE_P( BatchWrite, QuicWriteBlockedListParameterizedTest, ::testing::Combine(::testing::Bool(), ::testing::Bool()), [](const testing::TestParamInfo< QuicWriteBlockedListParameterizedTest::ParamType>& info) { return absl::StrCat(std::get<0>(info.param) ? "RespectIncrementalTrue" : "RespectIncrementalFalse", std::get<1>(info.param) ? "DisableBatchWriteTrue" : "DisableBatchWriteFalse"); }); TEST_P(QuicWriteBlockedListParameterizedTest, BatchingWrites) { if (disable_batch_write_) { return; } const QuicStreamId id1 = 5; const QuicStreamId id2 = 7; const QuicStreamId id3 = 9; RegisterStream(id1, kNotStatic, {kV3LowestPriority, kIncremental}); RegisterStream(id2, kNotStatic, {kV3LowestPriority, kIncremental}); RegisterStream(id3, kNotStatic, {kV3HighestPriority, kIncremental}); AddStream(id1); AddStream(id2); EXPECT_EQ(2u, NumBlockedStreams()); EXPECT_EQ(id1, PopFront()); UpdateBytesForStream(id1, 15999); AddStream(id1); EXPECT_EQ(2u, NumBlockedStreams()); EXPECT_EQ(id1, PopFront()); UpdateBytesForStream(id1, 1); AddStream(id1); EXPECT_EQ(2u, NumBlockedStreams()); EXPECT_EQ(id2, PopFront()); UpdateBytesForStream(id2, 15999); AddStream(id2); EXPECT_EQ(2u, NumBlockedStreams()); AddStream(id3); EXPECT_EQ(id3, PopFront()); UpdateBytesForStream(id3, 20000); AddStream(id3); EXPECT_EQ(id3, PopFront()); EXPECT_EQ(id2, PopFront()); UpdateBytesForStream(id2, 1); AddStream(id2); EXPECT_EQ(2u, NumBlockedStreams()); EXPECT_EQ(id1, PopFront()); } TEST_P(QuicWriteBlockedListParameterizedTest, RoundRobin) { if (!disable_batch_write_) { return; } const QuicStreamId id1 = 5; const QuicStreamId id2 = 7; const QuicStreamId id3 = 9; RegisterStream(id1, kNotStatic, {kV3LowestPriority, kIncremental}); RegisterStream(id2, kNotStatic, {kV3LowestPriority, kIncremental}); RegisterStream(id3, kNotStatic, {kV3LowestPriority, kIncremental}); AddStream(id1); AddStream(id2); AddStream(id3); EXPECT_EQ(id1, PopFront()); AddStream(id1); EXPECT_EQ(id2, PopFront()); EXPECT_EQ(id3, PopFront()); AddStream(id3); AddStream(id2); EXPECT_EQ(id1, PopFront()); EXPECT_EQ(id3, PopFront()); AddStream(id3); EXPECT_EQ(id2, PopFront()); EXPECT_EQ(id3, PopFront()); } TEST_P(QuicWriteBlockedListParameterizedTest, NonIncrementalStreamsKeepWriting) { if (!priority_respect_incremental_) { return; } const QuicStreamId id1 = 1; const QuicStreamId id2 = 2; const QuicStreamId id3 = 3; const QuicStreamId id4 = 4; RegisterStream(id1, kNotStatic, {kV3LowestPriority, kNotIncremental}); RegisterStream(id2, kNotStatic, {kV3LowestPriority, kNotIncremental}); RegisterStream(id3, kNotStatic, {kV3LowestPriority, kNotIncremental}); RegisterStream(id4, kNotStatic, {kV3HighestPriority, kNotIncremental}); AddStream(id1); AddStream(id2); AddStream(id3); EXPECT_EQ(id1, PopFront()); const size_t kLargeWriteSize = 1000 * 1000 * 1000; UpdateBytesForStream(id1, kLargeWriteSize); AddStream(id1); EXPECT_EQ(id1, PopFront()); UpdateBytesForStream(id1, kLargeWriteSize); AddStream(id1); EXPECT_EQ(id1, PopFront()); UpdateBytesForStream(id1, kLargeWriteSize); AddStream(id1); EXPECT_EQ(id1, PopFront()); UpdateBytesForStream(id1, kLargeWriteSize); AddStream(id1); AddStream(id4); EXPECT_EQ(id4, PopFront()); EXPECT_EQ(id1, PopFront()); UpdateBytesForStream(id1, kLargeWriteSize); EXPECT_EQ(id2, PopFront()); UpdateBytesForStream(id2, kLargeWriteSize); AddStream(id2); EXPECT_EQ(id2, PopFront()); UpdateBytesForStream(id2, kLargeWriteSize); AddStream(id2); AddStream(id1); EXPECT_EQ(id2, PopFront()); UpdateBytesForStream(id2, kLargeWriteSize); EXPECT_EQ(id3, PopFront()); UpdateBytesForStream(id2, kLargeWriteSize); AddStream(id3); EXPECT_EQ(id3, PopFront()); UpdateBytesForStream(id2, kLargeWriteSize); EXPECT_EQ(id1, PopFront()); UpdateBytesForStream(id1, kLargeWriteSize); } TEST_P(QuicWriteBlockedListParameterizedTest, IncrementalAndNonIncrementalStreams) { if (!priority_respect_incremental_) { return; } const QuicStreamId id1 = 1; const QuicStreamId id2 = 2; RegisterStream(id1, kNotStatic, {kV3LowestPriority, kNotIncremental}); RegisterStream(id2, kNotStatic, {kV3LowestPriority, kIncremental}); AddStream(id1); AddStream(id2); EXPECT_EQ(id1, PopFront()); const size_t kSmallWriteSize = 1000; UpdateBytesForStream(id1, kSmallWriteSize); AddStream(id1); EXPECT_EQ(id1, PopFront()); UpdateBytesForStream(id1, kSmallWriteSize); AddStream(id1); EXPECT_EQ(id1, PopFront()); UpdateBytesForStream(id1, kSmallWriteSize); EXPECT_EQ(id2, PopFront()); UpdateBytesForStream(id2, kSmallWriteSize); AddStream(id2); AddStream(id1); if (!disable_batch_write_) { EXPECT_EQ(id2, PopFront()); UpdateBytesForStream(id2, kSmallWriteSize); AddStream(id2); EXPECT_EQ(id2, PopFront()); UpdateBytesForStream(id2, kSmallWriteSize); } EXPECT_EQ(id1, PopFront()); const size_t kLargeWriteSize = 1000 * 1000 * 1000; UpdateBytesForStream(id1, kLargeWriteSize); AddStream(id1); EXPECT_EQ(id1, PopFront()); UpdateBytesForStream(id1, kLargeWriteSize); AddStream(id1); EXPECT_EQ(id1, PopFront()); UpdateBytesForStream(id1, kLargeWriteSize); AddStream(id2); AddStream(id1); if (!disable_batch_write_) { EXPECT_EQ(id2, PopFront()); UpdateBytesForStream(id2, kLargeWriteSize); AddStream(id2); } EXPECT_EQ(id1, PopFront()); UpdateBytesForStream(id1, kLargeWriteSize); } TEST_F(QuicWriteBlockedListTest, Ceding) { RegisterStream(15, kNotStatic, {kV3HighestPriority, kNotIncremental}); RegisterStream(16, kNotStatic, {kV3HighestPriority, kNotIncremental}); RegisterStream(5, kNotStatic, {5, kNotIncremental}); RegisterStream(4, kNotStatic, {5, kNotIncremental}); RegisterStream(7, kNotStatic, {7, kNotIncremental}); RegisterStream(1, kStatic, {kV3HighestPriority, kNotIncremental}); RegisterStream(3, kStatic, {kV3HighestPriority, kNotIncremental}); EXPECT_FALSE(ShouldYield(5)); AddStream(5); EXPECT_FALSE(ShouldYield(5)); EXPECT_TRUE(ShouldYield(4)); EXPECT_TRUE(ShouldYield(7)); EXPECT_FALSE(ShouldYield(15)); EXPECT_FALSE(ShouldYield(3)); EXPECT_FALSE(ShouldYield(1)); AddStream(15); EXPECT_TRUE(ShouldYield(16)); EXPECT_FALSE(ShouldYield(3)); EXPECT_FALSE(ShouldYield(1)); AddStream(3); EXPECT_TRUE(ShouldYield(16)); EXPECT_TRUE(ShouldYield(15)); EXPECT_FALSE(ShouldYield(3)); EXPECT_FALSE(ShouldYield(1)); AddStream(1); EXPECT_TRUE(ShouldYield(16)); EXPECT_TRUE(ShouldYield(15)); EXPECT_TRUE(ShouldYield(3)); EXPECT_FALSE(ShouldYield(1)); } TEST_F(QuicWriteBlockedListTest, UnregisterStream) { RegisterStream(40, kNotStatic, {kV3LowestPriority, kNotIncremental}); RegisterStream(23, kNotStatic, {6, kNotIncremental}); RegisterStream(12, kNotStatic, {3, kNotIncremental}); RegisterStream(17, kNotStatic, {kV3HighestPriority, kNotIncremental}); RegisterStream(1, kStatic, {kV3HighestPriority, kNotIncremental}); RegisterStream(3, kStatic, {kV3HighestPriority, kNotIncremental}); AddStream(40); AddStream(23); AddStream(12); AddStream(17); AddStream(1); AddStream(3); UnregisterStream(23); UnregisterStream(1); EXPECT_EQ(3u, PopFront()); EXPECT_EQ(17u, PopFront()); EXPECT_EQ(12u, PopFront()); EXPECT_EQ(40, PopFront()); } TEST_F(QuicWriteBlockedListTest, UnregisterNotRegisteredStream) { EXPECT_QUICHE_BUG(UnregisterStream(1), "Stream 1 not registered"); RegisterStream(2, kNotStatic, {kV3HighestPriority, kIncremental}); UnregisterStream(2); EXPECT_QUICHE_BUG(UnregisterStream(2), "Stream 2 not registered"); } TEST_F(QuicWriteBlockedListTest, UpdateStreamPriority) { RegisterStream(40, kNotStatic, {kV3LowestPriority, kNotIncremental}); RegisterStream(23, kNotStatic, {6, kIncremental}); RegisterStream(17, kNotStatic, {kV3HighestPriority, kNotIncremental}); RegisterStream(1, kStatic, {2, kNotIncremental}); RegisterStream(3, kStatic, {kV3HighestPriority, kNotIncremental}); EXPECT_EQ(kV3LowestPriority, GetPriorityOfStream(40).http().urgency); EXPECT_EQ(kNotIncremental, GetPriorityOfStream(40).http().incremental); EXPECT_EQ(6, GetPriorityOfStream(23).http().urgency); EXPECT_EQ(kIncremental, GetPriorityOfStream(23).http().incremental); EXPECT_EQ(kV3HighestPriority, GetPriorityOfStream(17).http().urgency); EXPECT_EQ(kNotIncremental, GetPriorityOfStream(17).http().incremental); UpdateStreamPriority(40, {3, kIncremental}); UpdateStreamPriority(23, {kV3HighestPriority, kNotIncremental}); UpdateStreamPriority(17, {5, kNotIncremental}); EXPECT_EQ(3, GetPriorityOfStream(40).http().urgency); EXPECT_EQ(kIncremental, GetPriorityOfStream(40).http().incremental); EXPECT_EQ(kV3HighestPriority, GetPriorityOfStream(23).http().urgency); EXPECT_EQ(kNotIncremental, GetPriorityOfStream(23).http().incremental); EXPECT_EQ(5, GetPriorityOfStream(17).http().urgency); EXPECT_EQ(kNotIncremental, GetPriorityOfStream(17).http().incremental); AddStream(40); AddStream(23); AddStream(17); AddStream(1); AddStream(3); EXPECT_EQ(1u, PopFront()); EXPECT_EQ(3u, PopFront()); EXPECT_EQ(23u, PopFront()); EXPECT_EQ(40u, PopFront()); EXPECT_EQ(17u, PopFront()); } TEST_F(QuicWriteBlockedListTest, UpdateStaticStreamPriority) { RegisterStream(2, kStatic, {kV3LowestPriority, kNotIncremental}); EXPECT_QUICHE_DEBUG_DEATH( UpdateStreamPriority(2, {kV3HighestPriority, kNotIncremental}), "IsRegistered"); } TEST_F(QuicWriteBlockedListTest, UpdateStreamPrioritySameUrgency) { RegisterStream(1, kNotStatic, {6, kNotIncremental}); RegisterStream(2, kNotStatic, {6, kNotIncremental}); AddStream(1); AddStream(2); EXPECT_EQ(1u, PopFront()); EXPECT_EQ(2u, PopFront()); RegisterStream(3, kNotStatic, {6, kNotIncremental}); RegisterStream(4, kNotStatic, {6, kNotIncremental}); EXPECT_EQ(6, GetPriorityOfStream(3).http().urgency); EXPECT_EQ(kNotIncremental, GetPriorityOfStream(3).http().incremental); UpdateStreamPriority(3, {6, kIncremental}); EXPECT_EQ(6, GetPriorityOfStream(3).http().urgency); EXPECT_EQ(kIncremental, GetPriorityOfStream(3).http().incremental); AddStream(3); AddStream(4); EXPECT_EQ(3u, PopFront()); EXPECT_EQ(4u, PopFront()); RegisterStream(5, kNotStatic, {6, kIncremental}); RegisterStream(6, kNotStatic, {6, kIncremental}); EXPECT_EQ(6, GetPriorityOfStream(6).http().urgency); EXPECT_EQ(kIncremental, GetPriorityOfStream(6).http().incremental); UpdateStreamPriority(6, {6, kNotIncremental}); EXPECT_EQ(6, GetPriorityOfStream(6).http().urgency); EXPECT_EQ(kNotIncremental, GetPriorityOfStream(6).http().incremental); AddStream(5); AddStream(6); EXPECT_EQ(5u, PopFront()); EXPECT_EQ(6u, PopFront()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_write_blocked_list.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_write_blocked_list_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
2c07c255-0780-41f2-aeb9-c626256cbab5
cpp
google/quiche
web_transport_write_blocked_list
quiche/quic/core/web_transport_write_blocked_list.cc
quiche/quic/core/web_transport_write_blocked_list_test.cc
#include "quiche/quic/core/web_transport_write_blocked_list.h" #include <cstddef> #include <optional> #include <string> #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "quiche/quic/core/quic_stream_priority.h" #include "quiche/quic/core/quic_types.h" #include "quiche/common/platform/api/quiche_bug_tracker.h" #include "quiche/common/platform/api/quiche_logging.h" namespace quic { bool WebTransportWriteBlockedList::HasWriteBlockedDataStreams() const { return main_schedule_.NumScheduledInPriorityRange( std::nullopt, RemapUrgency(HttpStreamPriority::kMaximumUrgency, true)) > 0; } size_t WebTransportWriteBlockedList::NumBlockedSpecialStreams() const { return main_schedule_.NumScheduledInPriorityRange( RemapUrgency(kStaticUrgency, false), std::nullopt); } size_t WebTransportWriteBlockedList::NumBlockedStreams() const { size_t num_streams = main_schedule_.NumScheduled(); for (const auto& [key, scheduler] : web_transport_session_schedulers_) { if (scheduler.HasScheduled()) { num_streams += scheduler.NumScheduled(); QUICHE_DCHECK(main_schedule_.IsScheduled(key)); --num_streams; } } return num_streams; } void WebTransportWriteBlockedList::RegisterStream( QuicStreamId stream_id, bool is_static_stream, const QuicStreamPriority& raw_priority) { QuicStreamPriority priority = is_static_stream ? QuicStreamPriority(HttpStreamPriority{kStaticUrgency, true}) : raw_priority; auto [unused, success] = priorities_.emplace(stream_id, priority); if (!success) { QUICHE_BUG(WTWriteBlocked_RegisterStream_already_registered) << "Tried to register stream " << stream_id << " that is already registered"; return; } if (priority.type() == QuicPriorityType::kHttp) { absl::Status status = main_schedule_.Register( ScheduleKey::HttpStream(stream_id), RemapUrgency(priority.http().urgency, true)); QUICHE_BUG_IF(WTWriteBlocked_RegisterStream_http_scheduler, !status.ok()) << status; return; } QUICHE_DCHECK_EQ(priority.type(), QuicPriorityType::kWebTransport); ScheduleKey group_key = ScheduleKey::WebTransportSession(priority); auto [it, created_new] = web_transport_session_schedulers_.try_emplace(group_key); absl::Status status = it->second.Register(stream_id, priority.web_transport().send_order); QUICHE_BUG_IF(WTWriteBlocked_RegisterStream_data_scheduler, !status.ok()) << status; if (created_new) { auto session_priority_it = priorities_.find(priority.web_transport().session_id); QUICHE_DLOG_IF(WARNING, session_priority_it == priorities_.end()) << "Stream " << stream_id << " is associated with session ID " << priority.web_transport().session_id << ", but the session control stream is not registered; assuming " "default urgency."; QuicStreamPriority session_priority = session_priority_it != priorities_.end() ? session_priority_it->second : QuicStreamPriority(); status = main_schedule_.Register( group_key, RemapUrgency(session_priority.http().urgency, false)); QUICHE_BUG_IF(WTWriteBlocked_RegisterStream_main_scheduler, !status.ok()) << status; } } void WebTransportWriteBlockedList::UnregisterStream(QuicStreamId stream_id) { auto map_it = priorities_.find(stream_id); if (map_it == priorities_.end()) { QUICHE_BUG(WTWriteBlocked_UnregisterStream_not_found) << "Stream " << stream_id << " not found"; return; } QuicStreamPriority priority = map_it->second; priorities_.erase(map_it); if (priority.type() != QuicPriorityType::kWebTransport) { absl::Status status = main_schedule_.Unregister(ScheduleKey::HttpStream(stream_id)); QUICHE_BUG_IF(WTWriteBlocked_UnregisterStream_http, !status.ok()) << status; return; } ScheduleKey key = ScheduleKey::WebTransportSession(priority); auto subscheduler_it = web_transport_session_schedulers_.find(key); if (subscheduler_it == web_transport_session_schedulers_.end()) { QUICHE_BUG(WTWriteBlocked_UnregisterStream_no_subscheduler) << "Stream " << stream_id << " is a WebTransport data stream, but has no scheduler for the " "associated group"; return; } Subscheduler& subscheduler = subscheduler_it->second; absl::Status status = subscheduler.Unregister(stream_id); QUICHE_BUG_IF(WTWriteBlocked_UnregisterStream_subscheduler_stream_failed, !status.ok()) << status; if (!subscheduler.HasRegistered()) { status = main_schedule_.Unregister(key); QUICHE_BUG_IF(WTWriteBlocked_UnregisterStream_subscheduler_failed, !status.ok()) << status; web_transport_session_schedulers_.erase(subscheduler_it); } } void WebTransportWriteBlockedList::UpdateStreamPriority( QuicStreamId stream_id, const QuicStreamPriority& new_priority) { QuicStreamPriority old_priority = GetPriorityOfStream(stream_id); if (old_priority == new_priority) { return; } bool was_blocked = IsStreamBlocked(stream_id); UnregisterStream(stream_id); RegisterStream(stream_id, false, new_priority); if (was_blocked) { AddStream(stream_id); } if (new_priority.type() == QuicPriorityType::kHttp) { for (auto& [key, subscheduler] : web_transport_session_schedulers_) { QUICHE_DCHECK(key.has_group()); if (key.stream() == stream_id) { absl::Status status = main_schedule_.UpdatePriority(key, new_priority.http().urgency); QUICHE_BUG_IF(WTWriteBlocked_UpdateStreamPriority_subscheduler_failed, !status.ok()) << status; } } } } QuicStreamId WebTransportWriteBlockedList::PopFront() { absl::StatusOr<ScheduleKey> main_key = main_schedule_.PopFront(); if (!main_key.ok()) { QUICHE_BUG(WTWriteBlocked_PopFront_no_streams) << "PopFront() called when no streams scheduled: " << main_key.status(); return 0; } if (!main_key->has_group()) { return main_key->stream(); } auto it = web_transport_session_schedulers_.find(*main_key); if (it == web_transport_session_schedulers_.end()) { QUICHE_BUG(WTWriteBlocked_PopFront_no_subscheduler) << "Subscheduler for WebTransport group " << main_key->DebugString() << " not found"; return 0; } Subscheduler& subscheduler = it->second; absl::StatusOr<QuicStreamId> result = subscheduler.PopFront(); if (!result.ok()) { QUICHE_BUG(WTWriteBlocked_PopFront_subscheduler_empty) << "Subscheduler for group " << main_key->DebugString() << " is empty while in the main schedule"; return 0; } if (subscheduler.HasScheduled()) { absl::Status status = main_schedule_.Schedule(*main_key); QUICHE_BUG_IF(WTWriteBlocked_PopFront_reschedule_group, !status.ok()) << status; } return *result; } void WebTransportWriteBlockedList::AddStream(QuicStreamId stream_id) { QuicStreamPriority priority = GetPriorityOfStream(stream_id); absl::Status status; switch (priority.type()) { case QuicPriorityType::kHttp: status = main_schedule_.Schedule(ScheduleKey::HttpStream(stream_id)); QUICHE_BUG_IF(WTWriteBlocked_AddStream_http, !status.ok()) << status; break; case QuicPriorityType::kWebTransport: status = main_schedule_.Schedule(ScheduleKey::WebTransportSession(priority)); QUICHE_BUG_IF(WTWriteBlocked_AddStream_wt_main, !status.ok()) << status; auto it = web_transport_session_schedulers_.find( ScheduleKey::WebTransportSession(priority)); if (it == web_transport_session_schedulers_.end()) { QUICHE_BUG(WTWriteBlocked_AddStream_no_subscheduler) << ScheduleKey::WebTransportSession(priority); return; } Subscheduler& subscheduler = it->second; status = subscheduler.Schedule(stream_id); QUICHE_BUG_IF(WTWriteBlocked_AddStream_wt_sub, !status.ok()) << status; break; } } bool WebTransportWriteBlockedList::IsStreamBlocked( QuicStreamId stream_id) const { QuicStreamPriority priority = GetPriorityOfStream(stream_id); switch (priority.type()) { case QuicPriorityType::kHttp: return main_schedule_.IsScheduled(ScheduleKey::HttpStream(stream_id)); case QuicPriorityType::kWebTransport: auto it = web_transport_session_schedulers_.find( ScheduleKey::WebTransportSession(priority)); if (it == web_transport_session_schedulers_.end()) { QUICHE_BUG(WTWriteBlocked_IsStreamBlocked_no_subscheduler) << ScheduleKey::WebTransportSession(priority); return false; } const Subscheduler& subscheduler = it->second; return subscheduler.IsScheduled(stream_id); } QUICHE_NOTREACHED(); return false; } QuicStreamPriority WebTransportWriteBlockedList::GetPriorityOfStream( QuicStreamId id) const { auto it = priorities_.find(id); if (it == priorities_.end()) { QUICHE_BUG(WTWriteBlocked_GetPriorityOfStream_not_found) << "Stream " << id << " not found"; return QuicStreamPriority(); } return it->second; } std::string WebTransportWriteBlockedList::ScheduleKey::DebugString() const { return absl::StrFormat("(%d, %d)", stream_, group_); } bool WebTransportWriteBlockedList::ShouldYield(QuicStreamId id) const { QuicStreamPriority priority = GetPriorityOfStream(id); if (priority.type() == QuicPriorityType::kHttp) { absl::StatusOr<bool> should_yield = main_schedule_.ShouldYield(ScheduleKey::HttpStream(id)); QUICHE_BUG_IF(WTWriteBlocked_ShouldYield_http, !should_yield.ok()) << should_yield.status(); return *should_yield; } QUICHE_DCHECK_EQ(priority.type(), QuicPriorityType::kWebTransport); absl::StatusOr<bool> should_yield = main_schedule_.ShouldYield(ScheduleKey::WebTransportSession(priority)); QUICHE_BUG_IF(WTWriteBlocked_ShouldYield_wt_main, !should_yield.ok()) << should_yield.status(); if (*should_yield) { return true; } auto it = web_transport_session_schedulers_.find( ScheduleKey::WebTransportSession(priority)); if (it == web_transport_session_schedulers_.end()) { QUICHE_BUG(WTWriteBlocked_ShouldYield_subscheduler_not_found) << "Subscheduler not found for " << ScheduleKey::WebTransportSession(priority); return false; } const Subscheduler& subscheduler = it->second; should_yield = subscheduler.ShouldYield(id); QUICHE_BUG_IF(WTWriteBlocked_ShouldYield_wt_subscheduler, !should_yield.ok()) << should_yield.status(); return *should_yield; } }
#include "quiche/quic/core/web_transport_write_blocked_list.h" #include <algorithm> #include <array> #include <cstddef> #include <iterator> #include <vector> #include "absl/algorithm/container.h" #include "quiche/quic/core/quic_stream_priority.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/platform/api/quiche_expect_bug.h" #include "quiche/common/platform/api/quiche_test.h" namespace quic::test { namespace { using ::testing::ElementsAre; using ::testing::ElementsAreArray; class WebTransportWriteBlockedListTest : public ::quiche::test::QuicheTest { protected: void RegisterStaticStream(QuicStreamId id) { list_.RegisterStream(id, true, QuicStreamPriority()); } void RegisterHttpStream(QuicStreamId id, int urgency = HttpStreamPriority::kDefaultUrgency) { HttpStreamPriority priority; priority.urgency = urgency; list_.RegisterStream(id, false, QuicStreamPriority(priority)); } void RegisterWebTransportDataStream(QuicStreamId id, WebTransportStreamPriority priority) { list_.RegisterStream(id, false, QuicStreamPriority(priority)); } std::vector<QuicStreamId> PopAll() { std::vector<QuicStreamId> result; size_t expected_count = list_.NumBlockedStreams(); while (list_.NumBlockedStreams() > 0) { EXPECT_TRUE(list_.HasWriteBlockedDataStreams() || list_.HasWriteBlockedSpecialStream()); result.push_back(list_.PopFront()); EXPECT_EQ(list_.NumBlockedStreams(), --expected_count); } return result; } WebTransportWriteBlockedList list_; }; TEST_F(WebTransportWriteBlockedListTest, BasicHttpStreams) { RegisterHttpStream(1); RegisterHttpStream(2); RegisterHttpStream(3, HttpStreamPriority::kDefaultUrgency + 1); RegisterStaticStream(4); EXPECT_EQ(list_.GetPriorityOfStream(1), QuicStreamPriority()); EXPECT_EQ(list_.GetPriorityOfStream(2), QuicStreamPriority()); EXPECT_EQ(list_.GetPriorityOfStream(3).http().urgency, 4); EXPECT_EQ(list_.NumBlockedStreams(), 0); EXPECT_EQ(list_.NumBlockedSpecialStreams(), 0); list_.AddStream(1); list_.AddStream(2); list_.AddStream(3); list_.AddStream(4); EXPECT_EQ(list_.NumBlockedStreams(), 4); EXPECT_EQ(list_.NumBlockedSpecialStreams(), 1); EXPECT_THAT(PopAll(), ElementsAre(4, 3, 1, 2)); EXPECT_EQ(list_.NumBlockedStreams(), 0); EXPECT_EQ(list_.NumBlockedSpecialStreams(), 0); list_.AddStream(2); list_.AddStream(3); list_.AddStream(4); list_.AddStream(1); EXPECT_THAT(PopAll(), ElementsAre(4, 3, 2, 1)); } TEST_F(WebTransportWriteBlockedListTest, RegisterDuplicateStream) { RegisterHttpStream(1); EXPECT_QUICHE_BUG(RegisterHttpStream(1), "already registered"); } TEST_F(WebTransportWriteBlockedListTest, UnregisterMissingStream) { EXPECT_QUICHE_BUG(list_.UnregisterStream(1), "not found"); } TEST_F(WebTransportWriteBlockedListTest, GetPriorityMissingStream) { EXPECT_QUICHE_BUG(list_.GetPriorityOfStream(1), "not found"); } TEST_F(WebTransportWriteBlockedListTest, PopFrontMissing) { RegisterHttpStream(1); list_.AddStream(1); EXPECT_EQ(list_.PopFront(), 1); EXPECT_QUICHE_BUG(list_.PopFront(), "no streams scheduled"); } TEST_F(WebTransportWriteBlockedListTest, HasWriteBlockedDataStreams) { RegisterStaticStream(1); RegisterHttpStream(2); EXPECT_FALSE(list_.HasWriteBlockedDataStreams()); list_.AddStream(1); EXPECT_FALSE(list_.HasWriteBlockedDataStreams()); list_.AddStream(2); EXPECT_TRUE(list_.HasWriteBlockedDataStreams()); EXPECT_EQ(list_.PopFront(), 1); EXPECT_TRUE(list_.HasWriteBlockedDataStreams()); EXPECT_EQ(list_.PopFront(), 2); EXPECT_FALSE(list_.HasWriteBlockedDataStreams()); } TEST_F(WebTransportWriteBlockedListTest, NestedStreams) { RegisterHttpStream(1); RegisterHttpStream(2); RegisterWebTransportDataStream(3, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(4, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(5, WebTransportStreamPriority{2, 0, 0}); RegisterWebTransportDataStream(6, WebTransportStreamPriority{2, 0, 0}); EXPECT_EQ(list_.NumBlockedStreams(), 0); list_.AddStream(3); list_.AddStream(5); list_.AddStream(4); list_.AddStream(6); EXPECT_EQ(list_.NumBlockedStreams(), 4); EXPECT_THAT(PopAll(), ElementsAre(3, 5, 4, 6)); EXPECT_EQ(list_.NumBlockedStreams(), 0); list_.AddStream(3); list_.AddStream(4); list_.AddStream(5); EXPECT_EQ(list_.NumBlockedStreams(), 3); EXPECT_THAT(PopAll(), ElementsAre(3, 5, 4)); EXPECT_EQ(list_.NumBlockedStreams(), 0); list_.AddStream(4); list_.AddStream(5); list_.AddStream(6); EXPECT_EQ(list_.NumBlockedStreams(), 3); EXPECT_THAT(PopAll(), ElementsAre(4, 5, 6)); EXPECT_EQ(list_.NumBlockedStreams(), 0); list_.AddStream(6); list_.AddStream(3); list_.AddStream(4); list_.AddStream(5); EXPECT_EQ(list_.NumBlockedStreams(), 4); EXPECT_THAT(PopAll(), ElementsAre(6, 3, 5, 4)); EXPECT_EQ(list_.NumBlockedStreams(), 0); list_.AddStream(6); list_.AddStream(5); list_.AddStream(4); list_.AddStream(3); EXPECT_EQ(list_.NumBlockedStreams(), 4); EXPECT_THAT(PopAll(), ElementsAre(6, 4, 5, 3)); EXPECT_EQ(list_.NumBlockedStreams(), 0); } TEST_F(WebTransportWriteBlockedListTest, NestedStreamsWithHigherPriorityGroup) { RegisterHttpStream(1, HttpStreamPriority::kDefaultUrgency + 1); RegisterHttpStream(2); RegisterWebTransportDataStream(3, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(4, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(5, WebTransportStreamPriority{2, 0, 0}); RegisterWebTransportDataStream(6, WebTransportStreamPriority{2, 0, 0}); EXPECT_EQ(list_.NumBlockedStreams(), 0); list_.AddStream(3); list_.AddStream(5); list_.AddStream(4); list_.AddStream(6); EXPECT_EQ(list_.NumBlockedStreams(), 4); EXPECT_THAT(PopAll(), ElementsAre(3, 4, 5, 6)); EXPECT_EQ(list_.NumBlockedStreams(), 0); list_.AddStream(3); list_.AddStream(4); list_.AddStream(5); EXPECT_EQ(list_.NumBlockedStreams(), 3); EXPECT_THAT(PopAll(), ElementsAre(3, 4, 5)); EXPECT_EQ(list_.NumBlockedStreams(), 0); list_.AddStream(4); list_.AddStream(5); list_.AddStream(6); EXPECT_EQ(list_.NumBlockedStreams(), 3); EXPECT_THAT(PopAll(), ElementsAre(4, 5, 6)); EXPECT_EQ(list_.NumBlockedStreams(), 0); list_.AddStream(6); list_.AddStream(3); list_.AddStream(4); list_.AddStream(5); EXPECT_EQ(list_.NumBlockedStreams(), 4); EXPECT_THAT(PopAll(), ElementsAre(3, 4, 6, 5)); EXPECT_EQ(list_.NumBlockedStreams(), 0); list_.AddStream(6); list_.AddStream(5); list_.AddStream(4); list_.AddStream(3); EXPECT_EQ(list_.NumBlockedStreams(), 4); EXPECT_THAT(PopAll(), ElementsAre(4, 3, 6, 5)); EXPECT_EQ(list_.NumBlockedStreams(), 0); } TEST_F(WebTransportWriteBlockedListTest, NestedStreamVsControlStream) { RegisterHttpStream(1); RegisterWebTransportDataStream(2, WebTransportStreamPriority{1, 0, 0}); list_.AddStream(2); list_.AddStream(1); EXPECT_THAT(PopAll(), ElementsAre(1, 2)); list_.AddStream(1); list_.AddStream(2); EXPECT_THAT(PopAll(), ElementsAre(1, 2)); } TEST_F(WebTransportWriteBlockedListTest, NestedStreamsSendOrder) { RegisterHttpStream(1); RegisterWebTransportDataStream(2, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(3, WebTransportStreamPriority{1, 0, 100}); RegisterWebTransportDataStream(4, WebTransportStreamPriority{1, 0, -100}); list_.AddStream(4); list_.AddStream(3); list_.AddStream(2); list_.AddStream(1); EXPECT_THAT(PopAll(), ElementsAre(1, 3, 2, 4)); } TEST_F(WebTransportWriteBlockedListTest, NestedStreamsDifferentGroups) { RegisterHttpStream(1); RegisterWebTransportDataStream(2, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(3, WebTransportStreamPriority{1, 1, 100}); RegisterWebTransportDataStream(4, WebTransportStreamPriority{1, 7, -100}); list_.AddStream(4); list_.AddStream(3); list_.AddStream(2); list_.AddStream(1); EXPECT_THAT(PopAll(), ElementsAre(1, 4, 3, 2)); list_.AddStream(1); list_.AddStream(2); list_.AddStream(3); list_.AddStream(4); EXPECT_THAT(PopAll(), ElementsAre(1, 2, 3, 4)); } TEST_F(WebTransportWriteBlockedListTest, NestedStreamsDifferentSession) { RegisterWebTransportDataStream(1, WebTransportStreamPriority{10, 0, 0}); RegisterWebTransportDataStream(2, WebTransportStreamPriority{11, 0, 100}); RegisterWebTransportDataStream(3, WebTransportStreamPriority{12, 0, -100}); list_.AddStream(3); list_.AddStream(2); list_.AddStream(1); EXPECT_THAT(PopAll(), ElementsAre(3, 2, 1)); list_.AddStream(1); list_.AddStream(2); list_.AddStream(3); EXPECT_THAT(PopAll(), ElementsAre(1, 2, 3)); } TEST_F(WebTransportWriteBlockedListTest, UnregisterScheduledStreams) { RegisterHttpStream(1); RegisterHttpStream(2); RegisterWebTransportDataStream(3, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(4, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(5, WebTransportStreamPriority{2, 0, 0}); RegisterWebTransportDataStream(6, WebTransportStreamPriority{2, 0, 0}); EXPECT_EQ(list_.NumBlockedStreams(), 0); for (QuicStreamId id : {1, 2, 3, 4, 5, 6}) { list_.AddStream(id); } EXPECT_EQ(list_.NumBlockedStreams(), 6); list_.UnregisterStream(1); EXPECT_EQ(list_.NumBlockedStreams(), 5); list_.UnregisterStream(3); EXPECT_EQ(list_.NumBlockedStreams(), 4); list_.UnregisterStream(4); EXPECT_EQ(list_.NumBlockedStreams(), 3); list_.UnregisterStream(5); EXPECT_EQ(list_.NumBlockedStreams(), 2); list_.UnregisterStream(6); EXPECT_EQ(list_.NumBlockedStreams(), 1); list_.UnregisterStream(2); EXPECT_EQ(list_.NumBlockedStreams(), 0); } TEST_F(WebTransportWriteBlockedListTest, UnregisterUnscheduledStreams) { RegisterHttpStream(1); RegisterHttpStream(2); RegisterWebTransportDataStream(3, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(4, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(5, WebTransportStreamPriority{2, 0, 0}); RegisterWebTransportDataStream(6, WebTransportStreamPriority{2, 0, 0}); EXPECT_EQ(list_.NumRegisteredHttpStreams(), 2); EXPECT_EQ(list_.NumRegisteredGroups(), 2); list_.UnregisterStream(1); EXPECT_EQ(list_.NumRegisteredHttpStreams(), 1); EXPECT_EQ(list_.NumRegisteredGroups(), 2); list_.UnregisterStream(3); EXPECT_EQ(list_.NumRegisteredHttpStreams(), 1); EXPECT_EQ(list_.NumRegisteredGroups(), 2); list_.UnregisterStream(4); EXPECT_EQ(list_.NumRegisteredHttpStreams(), 1); EXPECT_EQ(list_.NumRegisteredGroups(), 1); list_.UnregisterStream(5); EXPECT_EQ(list_.NumRegisteredHttpStreams(), 1); EXPECT_EQ(list_.NumRegisteredGroups(), 1); list_.UnregisterStream(6); EXPECT_EQ(list_.NumRegisteredHttpStreams(), 1); EXPECT_EQ(list_.NumRegisteredGroups(), 0); list_.UnregisterStream(2); EXPECT_EQ(list_.NumRegisteredHttpStreams(), 0); EXPECT_EQ(list_.NumRegisteredGroups(), 0); RegisterHttpStream(1); RegisterHttpStream(2); RegisterWebTransportDataStream(3, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(4, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(5, WebTransportStreamPriority{2, 0, 0}); RegisterWebTransportDataStream(6, WebTransportStreamPriority{2, 0, 0}); } TEST_F(WebTransportWriteBlockedListTest, IsStreamBlocked) { RegisterHttpStream(1); RegisterWebTransportDataStream(2, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(3, WebTransportStreamPriority{9, 0, 0}); EXPECT_FALSE(list_.IsStreamBlocked(1)); EXPECT_FALSE(list_.IsStreamBlocked(2)); EXPECT_FALSE(list_.IsStreamBlocked(3)); list_.AddStream(3); EXPECT_FALSE(list_.IsStreamBlocked(1)); EXPECT_FALSE(list_.IsStreamBlocked(2)); EXPECT_TRUE(list_.IsStreamBlocked(3)); list_.AddStream(1); EXPECT_TRUE(list_.IsStreamBlocked(1)); EXPECT_FALSE(list_.IsStreamBlocked(2)); EXPECT_TRUE(list_.IsStreamBlocked(3)); ASSERT_EQ(list_.PopFront(), 1); EXPECT_FALSE(list_.IsStreamBlocked(1)); EXPECT_FALSE(list_.IsStreamBlocked(2)); EXPECT_TRUE(list_.IsStreamBlocked(3)); } TEST_F(WebTransportWriteBlockedListTest, UpdatePriorityHttp) { RegisterHttpStream(1); RegisterHttpStream(2); RegisterHttpStream(3); list_.AddStream(1); list_.AddStream(2); list_.AddStream(3); EXPECT_THAT(PopAll(), ElementsAre(1, 2, 3)); list_.UpdateStreamPriority( 2, QuicStreamPriority( HttpStreamPriority{HttpStreamPriority::kMaximumUrgency, false})); list_.AddStream(1); list_.AddStream(2); list_.AddStream(3); EXPECT_THAT(PopAll(), ElementsAre(2, 1, 3)); } TEST_F(WebTransportWriteBlockedListTest, UpdatePriorityWebTransport) { RegisterWebTransportDataStream(1, WebTransportStreamPriority{0, 0, 0}); RegisterWebTransportDataStream(2, WebTransportStreamPriority{0, 0, 0}); RegisterWebTransportDataStream(3, WebTransportStreamPriority{0, 0, 0}); list_.AddStream(1); list_.AddStream(2); list_.AddStream(3); EXPECT_THAT(PopAll(), ElementsAre(1, 2, 3)); list_.UpdateStreamPriority( 2, QuicStreamPriority(WebTransportStreamPriority{0, 0, 1})); list_.AddStream(1); list_.AddStream(2); list_.AddStream(3); EXPECT_THAT(PopAll(), ElementsAre(2, 1, 3)); } TEST_F(WebTransportWriteBlockedListTest, UpdatePriorityControlStream) { RegisterHttpStream(1); RegisterHttpStream(2); RegisterWebTransportDataStream(3, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(4, WebTransportStreamPriority{2, 0, 0}); list_.AddStream(3); list_.AddStream(4); EXPECT_THAT(PopAll(), ElementsAre(3, 4)); list_.AddStream(4); list_.AddStream(3); EXPECT_THAT(PopAll(), ElementsAre(4, 3)); list_.UpdateStreamPriority( 2, QuicStreamPriority( HttpStreamPriority{HttpStreamPriority::kMaximumUrgency, false})); list_.AddStream(3); list_.AddStream(4); EXPECT_THAT(PopAll(), ElementsAre(4, 3)); list_.AddStream(4); list_.AddStream(3); EXPECT_THAT(PopAll(), ElementsAre(4, 3)); } TEST_F(WebTransportWriteBlockedListTest, ShouldYield) { RegisterHttpStream(1); RegisterWebTransportDataStream(2, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(3, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(4, WebTransportStreamPriority{1, 0, 10}); EXPECT_FALSE(list_.ShouldYield(1)); EXPECT_FALSE(list_.ShouldYield(2)); EXPECT_FALSE(list_.ShouldYield(3)); EXPECT_FALSE(list_.ShouldYield(4)); list_.AddStream(1); EXPECT_FALSE(list_.ShouldYield(1)); EXPECT_TRUE(list_.ShouldYield(2)); EXPECT_TRUE(list_.ShouldYield(3)); EXPECT_TRUE(list_.ShouldYield(4)); PopAll(); list_.AddStream(2); EXPECT_FALSE(list_.ShouldYield(1)); EXPECT_FALSE(list_.ShouldYield(2)); EXPECT_TRUE(list_.ShouldYield(3)); EXPECT_FALSE(list_.ShouldYield(4)); PopAll(); list_.AddStream(4); EXPECT_FALSE(list_.ShouldYield(1)); EXPECT_TRUE(list_.ShouldYield(2)); EXPECT_TRUE(list_.ShouldYield(3)); EXPECT_FALSE(list_.ShouldYield(4)); PopAll(); } TEST_F(WebTransportWriteBlockedListTest, RandomizedTest) { RegisterHttpStream(1); RegisterHttpStream(2, HttpStreamPriority::kMinimumUrgency); RegisterHttpStream(3, HttpStreamPriority::kMaximumUrgency); RegisterWebTransportDataStream(4, WebTransportStreamPriority{1, 0, 0}); RegisterWebTransportDataStream(5, WebTransportStreamPriority{2, 0, +1}); RegisterWebTransportDataStream(6, WebTransportStreamPriority{2, 0, -1}); RegisterWebTransportDataStream(7, WebTransportStreamPriority{3, 8, 0}); RegisterWebTransportDataStream(8, WebTransportStreamPriority{3, 8, 100}); RegisterWebTransportDataStream(9, WebTransportStreamPriority{3, 8, 20000}); RegisterHttpStream(10, HttpStreamPriority::kDefaultUrgency + 1); constexpr std::array<QuicStreamId, 10> order = {3, 9, 8, 7, 10, 1, 4, 2, 5, 6}; SimpleRandom random; for (int i = 0; i < 1000; ++i) { std::vector<QuicStreamId> pushed_streams(order.begin(), order.end()); for (int j = pushed_streams.size() - 1; j > 0; --j) { std::swap(pushed_streams[j], pushed_streams[random.RandUint64() % (j + 1)]); } size_t stream_count = 1 + random.RandUint64() % order.size(); pushed_streams.resize(stream_count); for (QuicStreamId id : pushed_streams) { list_.AddStream(id); } std::vector<QuicStreamId> expected_streams; absl::c_copy_if( order, std::back_inserter(expected_streams), [&](QuicStreamId id) { return absl::c_find(pushed_streams, id) != pushed_streams.end(); }); ASSERT_THAT(PopAll(), ElementsAreArray(expected_streams)); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/web_transport_write_blocked_list.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/web_transport_write_blocked_list_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
6f0401f6-2870-4250-b739-0255b47e45e4
cpp
google/quiche
quic_stream
quiche/quic/core/quic_stream.cc
quiche/quic/core/quic_stream_test.cc
#include "quiche/quic/core/quic_stream.h" #include <algorithm> #include <limits> #include <optional> #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/frames/quic_reset_stream_at_frame.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_flow_controller.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_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" #include "quiche/common/platform/api/quiche_mem_slice.h" using spdy::SpdyPriority; namespace quic { #define ENDPOINT \ (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ") namespace { QuicByteCount DefaultFlowControlWindow(ParsedQuicVersion version) { if (!version.AllowsLowFlowControlLimits()) { return kDefaultFlowControlSendWindow; } return 0; } QuicByteCount GetInitialStreamFlowControlWindowToSend(QuicSession* session, QuicStreamId stream_id) { ParsedQuicVersion version = session->connection()->version(); if (version.handshake_protocol != PROTOCOL_TLS1_3) { return session->config()->GetInitialStreamFlowControlWindowToSend(); } if (VersionHasIetfQuicFrames(version.transport_version) && !QuicUtils::IsBidirectionalStreamId(stream_id, version)) { return session->config() ->GetInitialMaxStreamDataBytesUnidirectionalToSend(); } if (QuicUtils::IsOutgoingStreamId(version, stream_id, session->perspective())) { return session->config() ->GetInitialMaxStreamDataBytesOutgoingBidirectionalToSend(); } return session->config() ->GetInitialMaxStreamDataBytesIncomingBidirectionalToSend(); } QuicByteCount GetReceivedFlowControlWindow(QuicSession* session, QuicStreamId stream_id) { ParsedQuicVersion version = session->connection()->version(); if (version.handshake_protocol != PROTOCOL_TLS1_3) { if (session->config()->HasReceivedInitialStreamFlowControlWindowBytes()) { return session->config()->ReceivedInitialStreamFlowControlWindowBytes(); } return DefaultFlowControlWindow(version); } if (VersionHasIetfQuicFrames(version.transport_version) && !QuicUtils::IsBidirectionalStreamId(stream_id, version)) { if (session->config() ->HasReceivedInitialMaxStreamDataBytesUnidirectional()) { return session->config() ->ReceivedInitialMaxStreamDataBytesUnidirectional(); } return DefaultFlowControlWindow(version); } if (QuicUtils::IsOutgoingStreamId(version, stream_id, session->perspective())) { if (session->config() ->HasReceivedInitialMaxStreamDataBytesOutgoingBidirectional()) { return session->config() ->ReceivedInitialMaxStreamDataBytesOutgoingBidirectional(); } return DefaultFlowControlWindow(version); } if (session->config() ->HasReceivedInitialMaxStreamDataBytesIncomingBidirectional()) { return session->config() ->ReceivedInitialMaxStreamDataBytesIncomingBidirectional(); } return DefaultFlowControlWindow(version); } } PendingStream::PendingStream(QuicStreamId id, QuicSession* session) : id_(id), version_(session->version()), stream_delegate_(session), stream_bytes_read_(0), fin_received_(false), is_bidirectional_(QuicUtils::GetStreamType(id, session->perspective(), true, session->version()) == BIDIRECTIONAL), connection_flow_controller_(session->flow_controller()), flow_controller_(session, id, false, GetReceivedFlowControlWindow(session, id), GetInitialStreamFlowControlWindowToSend(session, id), kStreamReceiveWindowLimit, session->flow_controller()->auto_tune_receive_window(), session->flow_controller()), sequencer_(this), creation_time_(session->GetClock()->ApproximateNow()) { if (is_bidirectional_) { QUIC_CODE_COUNT_N(quic_pending_stream, 3, 3); } } void PendingStream::OnDataAvailable() { } void PendingStream::OnFinRead() { QUICHE_DCHECK(sequencer_.IsClosed()); } void PendingStream::AddBytesConsumed(QuicByteCount bytes) { flow_controller_.AddBytesConsumed(bytes); connection_flow_controller_->AddBytesConsumed(bytes); } void PendingStream::ResetWithError(QuicResetStreamError ) { QUICHE_NOTREACHED(); } void PendingStream::OnUnrecoverableError(QuicErrorCode error, const std::string& details) { stream_delegate_->OnStreamError(error, details); } void PendingStream::OnUnrecoverableError(QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error, const std::string& details) { stream_delegate_->OnStreamError(error, ietf_error, details); } QuicStreamId PendingStream::id() const { return id_; } ParsedQuicVersion PendingStream::version() const { return version_; } void PendingStream::OnStreamFrame(const QuicStreamFrame& frame) { QUICHE_DCHECK_EQ(frame.stream_id, id_); bool is_stream_too_long = (frame.offset > kMaxStreamLength) || (kMaxStreamLength - frame.offset < frame.data_length); if (is_stream_too_long) { QUIC_PEER_BUG(quic_peer_bug_12570_1) << "Receive stream frame reaches max stream length. frame offset " << frame.offset << " length " << frame.data_length; OnUnrecoverableError(QUIC_STREAM_LENGTH_OVERFLOW, "Peer sends more data than allowed on this stream."); return; } if (frame.offset + frame.data_length > sequencer_.close_offset()) { OnUnrecoverableError( QUIC_STREAM_DATA_BEYOND_CLOSE_OFFSET, absl::StrCat( "Stream ", id_, " received data with offset: ", frame.offset + frame.data_length, ", which is beyond close offset: ", sequencer()->close_offset())); return; } if (frame.fin) { fin_received_ = true; } QuicByteCount frame_payload_size = frame.data_length; stream_bytes_read_ += frame_payload_size; if (frame_payload_size > 0 && MaybeIncreaseHighestReceivedOffset(frame.offset + frame_payload_size)) { if (flow_controller_.FlowControlViolation() || connection_flow_controller_->FlowControlViolation()) { OnUnrecoverableError(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, "Flow control violation after increasing offset"); return; } } sequencer_.OnStreamFrame(frame); } void PendingStream::OnRstStreamFrame(const QuicRstStreamFrame& frame) { QUICHE_DCHECK_EQ(frame.stream_id, id_); if (frame.byte_offset > kMaxStreamLength) { OnUnrecoverableError(QUIC_STREAM_LENGTH_OVERFLOW, "Reset frame stream offset overflow."); return; } const QuicStreamOffset kMaxOffset = std::numeric_limits<QuicStreamOffset>::max(); if (sequencer()->close_offset() != kMaxOffset && frame.byte_offset != sequencer()->close_offset()) { OnUnrecoverableError( QUIC_STREAM_MULTIPLE_OFFSET, absl::StrCat("Stream ", id_, " received new final offset: ", frame.byte_offset, ", which is different from close offset: ", sequencer()->close_offset())); return; } MaybeIncreaseHighestReceivedOffset(frame.byte_offset); if (flow_controller_.FlowControlViolation() || connection_flow_controller_->FlowControlViolation()) { OnUnrecoverableError(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, "Flow control violation after increasing offset"); return; } } void PendingStream::OnResetStreamAtFrame(const QuicResetStreamAtFrame& frame) { if (frame.reliable_offset > sequencer()->close_offset()) { OnUnrecoverableError( QUIC_STREAM_MULTIPLE_OFFSET, absl::StrCat( "Stream ", id_, " received reliable reset with offset: ", frame.reliable_offset, " greater than the FIN offset: ", sequencer()->close_offset())); return; } if (buffered_reset_stream_at_.has_value() && (frame.reliable_offset > buffered_reset_stream_at_->reliable_offset)) { return; } buffered_reset_stream_at_ = frame; sequencer_.OnReliableReset(frame.reliable_offset); } void PendingStream::OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) { QUICHE_DCHECK(is_bidirectional_); flow_controller_.UpdateSendWindowOffset(frame.max_data); } bool PendingStream::MaybeIncreaseHighestReceivedOffset( QuicStreamOffset new_offset) { uint64_t increment = new_offset - flow_controller_.highest_received_byte_offset(); if (!flow_controller_.UpdateHighestReceivedOffset(new_offset)) { return false; } connection_flow_controller_->UpdateHighestReceivedOffset( connection_flow_controller_->highest_received_byte_offset() + increment); return true; } void PendingStream::OnStopSending( QuicResetStreamError stop_sending_error_code) { if (!stop_sending_error_code_) { stop_sending_error_code_ = stop_sending_error_code; } } void PendingStream::MarkConsumed(QuicByteCount num_bytes) { sequencer_.MarkConsumed(num_bytes); } void PendingStream::StopReading() { QUIC_DVLOG(1) << "Stop reading from pending stream " << id(); sequencer_.StopReading(); } QuicStream::QuicStream(PendingStream* pending, QuicSession* session, bool is_static) : QuicStream( pending->id_, session, std::move(pending->sequencer_), is_static, QuicUtils::GetStreamType(pending->id_, session->perspective(), true, session->version()), pending->stream_bytes_read_, pending->fin_received_, std::move(pending->flow_controller_), pending->connection_flow_controller_, (session->GetClock()->ApproximateNow() - pending->creation_time())) { QUICHE_DCHECK(session->version().HasIetfQuicFrames()); sequencer_.set_stream(this); buffered_reset_stream_at_ = pending->buffered_reset_stream_at(); } namespace { std::optional<QuicFlowController> FlowController(QuicStreamId id, QuicSession* session, StreamType type) { if (type == CRYPTO) { return std::nullopt; } return QuicFlowController( session, id, false, GetReceivedFlowControlWindow(session, id), GetInitialStreamFlowControlWindowToSend(session, id), kStreamReceiveWindowLimit, session->flow_controller()->auto_tune_receive_window(), session->flow_controller()); } } QuicStream::QuicStream(QuicStreamId id, QuicSession* session, bool is_static, StreamType type) : QuicStream(id, session, QuicStreamSequencer(this), is_static, type, 0, false, FlowController(id, session, type), session->flow_controller(), QuicTime::Delta::Zero()) {} QuicStream::QuicStream(QuicStreamId id, QuicSession* session, QuicStreamSequencer sequencer, bool is_static, StreamType type, uint64_t stream_bytes_read, bool fin_received, std::optional<QuicFlowController> flow_controller, QuicFlowController* connection_flow_controller, QuicTime::Delta pending_duration) : sequencer_(std::move(sequencer)), id_(id), session_(session), stream_delegate_(session), stream_bytes_read_(stream_bytes_read), stream_error_(QuicResetStreamError::NoError()), connection_error_(QUIC_NO_ERROR), read_side_closed_(false), write_side_closed_(false), write_side_data_recvd_state_notified_(false), fin_buffered_(false), fin_sent_(false), fin_outstanding_(false), fin_lost_(false), fin_received_(fin_received), rst_sent_(false), rst_received_(false), stop_sending_sent_(false), flow_controller_(std::move(flow_controller)), connection_flow_controller_(connection_flow_controller), stream_contributes_to_connection_flow_control_(true), busy_counter_(0), add_random_padding_after_fin_(false), send_buffer_( session->connection()->helper()->GetStreamSendBufferAllocator()), buffered_data_threshold_(GetQuicFlag(quic_buffered_data_threshold)), is_static_(is_static), deadline_(QuicTime::Zero()), was_draining_(false), type_(VersionHasIetfQuicFrames(session->transport_version()) && type != CRYPTO ? QuicUtils::GetStreamType(id_, session->perspective(), session->IsIncomingStream(id_), session->version()) : type), creation_time_(session->connection()->clock()->ApproximateNow()), pending_duration_(pending_duration), perspective_(session->perspective()) { if (type_ == WRITE_UNIDIRECTIONAL) { fin_received_ = true; CloseReadSide(); } else if (type_ == READ_UNIDIRECTIONAL) { fin_sent_ = true; CloseWriteSide(); } if (type_ != CRYPTO) { stream_delegate_->RegisterStreamPriority(id, is_static_, priority_); } } QuicStream::~QuicStream() { if (session_ != nullptr && IsWaitingForAcks()) { QUIC_DVLOG(1) << ENDPOINT << "Stream " << id_ << " gets destroyed while waiting for acks. stream_bytes_outstanding = " << send_buffer_.stream_bytes_outstanding() << ", fin_outstanding: " << fin_outstanding_; } if (stream_delegate_ != nullptr && type_ != CRYPTO) { stream_delegate_->UnregisterStreamPriority(id()); } } void QuicStream::OnStreamFrame(const QuicStreamFrame& frame) { QUICHE_DCHECK_EQ(frame.stream_id, id_); QUICHE_DCHECK(!(read_side_closed_ && write_side_closed_)); if (frame.fin && is_static_) { OnUnrecoverableError(QUIC_INVALID_STREAM_ID, "Attempt to close a static stream"); return; } if (type_ == WRITE_UNIDIRECTIONAL) { OnUnrecoverableError(QUIC_DATA_RECEIVED_ON_WRITE_UNIDIRECTIONAL_STREAM, "Data received on write unidirectional stream"); return; } bool is_stream_too_long = (frame.offset > kMaxStreamLength) || (kMaxStreamLength - frame.offset < frame.data_length); if (is_stream_too_long) { QUIC_PEER_BUG(quic_peer_bug_10586_1) << "Receive stream frame on stream " << id_ << " reaches max stream length. frame offset " << frame.offset << " length " << frame.data_length << ". " << sequencer_.DebugString(); OnUnrecoverableError( QUIC_STREAM_LENGTH_OVERFLOW, absl::StrCat("Peer sends more data than allowed on stream ", id_, ". frame: offset = ", frame.offset, ", length = ", frame.data_length, ". ", sequencer_.DebugString())); return; } if (frame.offset + frame.data_length > sequencer_.close_offset()) { OnUnrecoverableError( QUIC_STREAM_DATA_BEYOND_CLOSE_OFFSET, absl::StrCat( "Stream ", id_, " received data with offset: ", frame.offset + frame.data_length, ", which is beyond close offset: ", sequencer_.close_offset())); return; } if (frame.fin && !fin_received_) { fin_received_ = true; if (fin_sent_) { QUICHE_DCHECK(!was_draining_); session_->StreamDraining(id_, type_ != BIDIRECTIONAL); was_draining_ = true; } } if (read_side_closed_) { QUIC_DLOG(INFO) << ENDPOINT << "Stream " << frame.stream_id << " is closed for reading. Ignoring newly received stream data."; return; } QuicByteCount frame_payload_size = frame.data_length; stream_bytes_read_ += frame_payload_size; if (frame_payload_size > 0 && MaybeIncreaseHighestReceivedOffset(frame.offset + frame_payload_size)) { QUIC_BUG_IF(quic_bug_12570_2, !flow_controller_.has_value()) << ENDPOINT << "OnStreamFrame called on stream without flow control"; if ((flow_controller_.has_value() && flow_controller_->FlowControlViolation()) || connection_flow_controller_->FlowControlViolation()) { OnUnrecoverableError(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, "Flow control violation after increasing offset"); return; } } sequencer_.OnStreamFrame(frame); } bool QuicStream::OnStopSending(QuicResetStreamError error) { if (write_side_closed() && !IsWaitingForAcks()) { QUIC_DVLOG(1) << ENDPOINT << "Ignoring STOP_SENDING for a write closed stream, id: " << id_; return false; } if (is_static_) { QUIC_DVLOG(1) << ENDPOINT << "Received STOP_SENDING for a static stream, id: " << id_ << " Closing connection"; OnUnrecoverableError(QUIC_INVALID_STREAM_ID, "Received STOP_SENDING for a static stream"); return false; } stream_error_ = error; MaybeSendRstStream(error); if (session()->enable_stop_sending_for_zombie_streams() && read_side_closed_ && write_side_closed_ && !IsWaitingForAcks()) { QUIC_RELOADABLE_FLAG_COUNT_N(quic_deliver_stop_sending_to_zombie_streams, 3, 3); session()->MaybeCloseZombieStream(id_); } return true; } int QuicStream::num_frames_received() const { return sequencer_.num_frames_received(); } int QuicStream::num_duplicate_frames_received() const { return sequencer_.num_duplicate_frames_received(); } void QuicStream::OnStreamReset(const QuicRstStreamFrame& frame) { rst_received_ = true; if (frame.byte_offset > kMaxStreamLength) { OnUnrecoverableError(QUIC_STREAM_LENGTH_OVERFLOW, "Reset frame stream offset overflow."); return; } const QuicStreamOffset kMaxOffset = std::numeric_limits<QuicStreamOffset>::max(); if (sequencer()->close_offset() != kMaxOffset && frame.byte_offset != sequencer()->close_offset()) { OnUnrecoverableError( QUIC_STREAM_MULTIPLE_OFFSET, absl::StrCat("Stream ", id_, " received new final offset: ", frame.byte_offset, ", which is different from close offset: ", sequencer_.close_offset())); return; } MaybeIncreaseHighestReceivedOffset(frame.byte_offset); QUIC_BUG_IF(quic_bug_12570_3, !flow_controller_.has_value()) << ENDPOINT << "OnStreamReset called on stream without flow control"; if ((flow_controller_.has_value() && flow_controller_->FlowControlViolation()) || connection_flow_controller_->FlowControlViolation()) { OnUnrecoverableError(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, "Flow control violation after increasing offset"); return; } stream_error_ = frame.error(); if (!VersionHasIetfQuicFrames(transport_version())) { CloseWriteSide(); } CloseReadSide(); } void QuicStream::OnResetStreamAtFrame(const QuicResetStreamAtFrame& frame) { if (frame.reliable_offset > sequencer()->close_offset()) { OnUnrecoverableError( QUIC_STREAM_MULTIPLE_OFFSET, absl::StrCat( "Stream ", id_, " received reliable reset with offset: ", frame.reliable_offset, " greater than the FIN offset: ", sequencer()->close_offset())); return; } if (buffered_reset_stream_at_.has_value() && (frame.reliable_offset > buffered_reset_stream_at_->reliable_offset)) { return; } buffered_reset_stream_at_ = frame; MaybeCloseStreamWithBufferedReset(); if (!rst_received_) { sequencer_.OnReliableReset(frame.reliable_offset); } } void QuicStream::OnConnectionClosed(const QuicConnectionCloseFrame& frame, ConnectionCloseSource ) { if (read_side_closed_ && write_side_closed_) { return; } auto error_code = frame.quic_error_code; if (error_code != QUIC_NO_ERROR) { stream_error_ = QuicResetStreamError::FromInternal(QUIC_STREAM_CONNECTION_ERROR); connection_error_ = error_code; } CloseWriteSide(); CloseReadSide(); } void QuicStream::OnFinRead() { QUICHE_DCHECK(sequencer_.IsClosed()); fin_received_ = true; CloseReadSide(); } void QuicStream::SetFinSent() { QUICHE_DCHECK(!VersionUsesHttp3(transport_version())); fin_sent_ = true; } void QuicStream::Reset(QuicRstStreamErrorCode error) { ResetWithError(QuicResetStreamError::FromInternal(error)); } void QuicStream::ResetWithError(QuicResetStreamError error) { stream_error_ = error; QuicConnection::ScopedPacketFlusher flusher(session()->connection()); MaybeSendStopSending(error); MaybeSendRstStream(error); if (read_side_closed_ && write_side_closed_ && !IsWaitingForAcks()) { session()->MaybeCloseZombieStream(id_); } } void QuicStream::ResetWriteSide(QuicResetStreamError error) { stream_error_ = error; MaybeSendRstStream(error); if (read_side_closed_ && write_side_closed_ && !IsWaitingForAcks()) { session()->MaybeCloseZombieStream(id_); } } void QuicStream::SendStopSending(QuicResetStreamError error) { stream_error_ = error; MaybeSendStopSending(error); if (read_side_closed_ && write_side_closed_ && !IsWaitingForAcks()) { session()->MaybeCloseZombieStream(id_); } } void QuicStream::OnUnrecoverableError(QuicErrorCode error, const std::string& details) { stream_delegate_->OnStreamError(error, details); } void QuicStream::OnUnrecoverableError(QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error, const std::string& details) { stream_delegate_->OnStreamError(error, ietf_error, details); } const QuicStreamPriority& QuicStream::priority() const { return priority_; } void QuicStream::SetPriority(const QuicStreamPriority& priority) { priority_ = priority; MaybeSendPriorityUpdateFrame(); stream_delegate_->UpdateStreamPriority(id(), priority); } void QuicStream::WriteOrBufferData( absl::string_view data, bool fin, quiche::QuicheReferenceCountedPointer<QuicAckListenerInterface> ack_listener) { QUIC_BUG_IF(quic_bug_12570_4, QuicUtils::IsCryptoStreamId(transport_version(), id_)) << ENDPOINT << "WriteOrBufferData is used to send application data, use " "WriteOrBufferDataAtLevel to send crypto data."; return WriteOrBufferDataAtLevel( data, fin, session()->GetEncryptionLevelToSendApplicationData(), ack_listener); } void QuicStream::WriteOrBufferDataAtLevel( absl::string_view data, bool fin, EncryptionLevel level, quiche::QuicheReferenceCountedPointer<QuicAckListenerInterface> ack_listener) { if (data.empty() && !fin) { QUIC_BUG(quic_bug_10586_2) << "data.empty() && !fin"; return; } if (fin_buffered_) { QUIC_BUG(quic_bug_10586_3) << "Fin already buffered"; return; } if (write_side_closed_) { QUIC_DLOG(ERROR) << ENDPOINT << "Attempt to write when the write side is closed"; if (type_ == READ_UNIDIRECTIONAL) { OnUnrecoverableError(QUIC_TRY_TO_WRITE_DATA_ON_READ_UNIDIRECTIONAL_STREAM, "Try to send data on read unidirectional stream"); } return; } fin_buffered_ = fin; bool had_buffered_data = HasBufferedData(); if (data.length() > 0) { QuicStreamOffset offset = send_buffer_.stream_offset(); if (kMaxStreamLength - offset < data.length()) { QUIC_BUG(quic_bug_10586_4) << "Write too many data via stream " << id_; OnUnrecoverableError( QUIC_STREAM_LENGTH_OVERFLOW, absl::StrCat("Write too many data via stream ", id_)); return; } send_buffer_.SaveStreamData(data); OnDataBuffered(offset, data.length(), ack_listener); } if (!had_buffered_data && (HasBufferedData() || fin_buffered_)) { WriteBufferedData(level); } } void QuicStream::OnCanWrite() { if (HasDeadlinePassed()) { OnDeadlinePassed(); return; } if (HasPendingRetransmission()) { WritePendingRetransmission(); return; } if (write_side_closed_) { QUIC_DLOG(ERROR) << ENDPOINT << "Stream " << id() << " attempting to write new data when the write side is closed"; return; } if (HasBufferedData() || (fin_buffered_ && !fin_sent_)) { WriteBufferedData(session()->GetEncryptionLevelToSendApplicationData()); } if (!fin_buffered_ && !fin_sent_ && CanWriteNewData()) { OnCanWriteNewData(); } } void QuicStream::MaybeSendBlocked() { if (!flow_controller_.has_value()) { QUIC_BUG(quic_bug_10586_5) << ENDPOINT << "MaybeSendBlocked called on stream without flow control"; return; } flow_controller_->MaybeSendBlocked(); if (!stream_contributes_to_connection_flow_control_) { return; } connection_flow_controller_->MaybeSendBlocked(); if (!write_side_closed_ && connection_flow_controller_->IsBlocked() && !flow_controller_->IsBlocked()) { session_->MarkConnectionLevelWriteBlocked(id()); } } QuicConsumedData QuicStream::WriteMemSlice(quiche::QuicheMemSlice span, bool fin) { return WriteMemSlices(absl::MakeSpan(&span, 1), fin); } QuicConsumedData QuicStream::WriteMemSlices( absl::Span<quiche::QuicheMemSlice> span, bool fin, bool buffer_unconditionally) { QuicConsumedData consumed_data(0, false); if (span.empty() && !fin) { QUIC_BUG(quic_bug_10586_6) << "span.empty() && !fin"; return consumed_data; } if (fin_buffered_) { QUIC_BUG(quic_bug_10586_7) << "Fin already buffered"; return consumed_data; } if (write_side_closed_) { QUIC_DLOG(ERROR) << ENDPOINT << "Stream " << id() << " attempting to write when the write side is closed"; if (type_ == READ_UNIDIRECTIONAL) { OnUnrecoverableError(QUIC_TRY_TO_WRITE_DATA_ON_READ_UNIDIRECTIONAL_STREAM, "Try to send data on read unidirectional stream"); } return consumed_data; } bool had_buffered_data = HasBufferedData(); if (CanWriteNewData() || span.empty() || buffer_unconditionally) { consumed_data.fin_consumed = fin; if (!span.empty()) { QuicStreamOffset offset = send_buffer_.stream_offset(); consumed_data.bytes_consumed = send_buffer_.SaveMemSliceSpan(span); if (offset > send_buffer_.stream_offset() || kMaxStreamLength < send_buffer_.stream_offset()) { QUIC_BUG(quic_bug_10586_8) << "Write too many data via stream " << id_; OnUnrecoverableError( QUIC_STREAM_LENGTH_OVERFLOW, absl::StrCat("Write too many data via stream ", id_)); return consumed_data; } OnDataBuffered(offset, consumed_data.bytes_consumed, nullptr); } } fin_buffered_ = consumed_data.fin_consumed; if (!had_buffered_data && (HasBufferedData() || fin_buffered_)) { WriteBufferedData(session()->GetEncryptionLevelToSendApplicationData()); } return consumed_data; } bool QuicStream::HasPendingRetransmission() const { return send_buffer_.HasPendingRetransmission() || fin_lost_; } bool QuicStream::IsStreamFrameOutstanding(QuicStreamOffset offset, QuicByteCount data_length, bool fin) const { return send_buffer_.IsStreamDataOutstanding(offset, data_length) || (fin && fin_outstanding_); } void QuicStream::CloseReadSide() { if (read_side_closed_) { return; } QUIC_DVLOG(1) << ENDPOINT << "Done reading from stream " << id(); read_side_closed_ = true; sequencer_.ReleaseBuffer(); if (write_side_closed_) { QUIC_DVLOG(1) << ENDPOINT << "Closing stream " << id(); session_->OnStreamClosed(id()); OnClose(); } } void QuicStream::CloseWriteSide() { if (write_side_closed_) { return; } QUIC_DVLOG(1) << ENDPOINT << "Done writing to stream " << id(); write_side_closed_ = true; if (read_side_closed_) { QUIC_DVLOG(1) << ENDPOINT << "Closing stream " << id(); session_->OnStreamClosed(id()); OnClose(); } } void QuicStream::MaybeSendStopSending(QuicResetStreamError error) { if (stop_sending_sent_) { return; } if (!session()->version().UsesHttp3() && !error.ok()) { return; } if (session()->version().UsesHttp3()) { session()->MaybeSendStopSendingFrame(id(), error); } else { QUICHE_DCHECK_EQ(QUIC_STREAM_NO_ERROR, error.internal_code()); session()->MaybeSendRstStreamFrame(id(), QuicResetStreamError::NoError(), stream_bytes_written()); } stop_sending_sent_ = true; CloseReadSide(); } void QuicStream::MaybeSendRstStream(QuicResetStreamError error) { if (rst_sent_) { return; } if (!session()->version().UsesHttp3()) { QUIC_BUG_IF(quic_bug_12570_5, error.ok()); stop_sending_sent_ = true; CloseReadSide(); } session()->MaybeSendRstStreamFrame(id(), error, stream_bytes_written()); rst_sent_ = true; CloseWriteSide(); } bool QuicStream::HasBufferedData() const { QUICHE_DCHECK_GE(send_buffer_.stream_offset(), stream_bytes_written()); return send_buffer_.stream_offset() > stream_bytes_written(); } ParsedQuicVersion QuicStream::version() const { return session_->version(); } QuicTransportVersion QuicStream::transport_version() const { return session_->transport_version(); } HandshakeProtocol QuicStream::handshake_protocol() const { return session_->connection()->version().handshake_protocol; } void QuicStream::StopReading() { QUIC_DVLOG(1) << ENDPOINT << "Stop reading from stream " << id(); sequencer_.StopReading(); } void QuicStream::OnClose() { QUICHE_DCHECK(read_side_closed_ && write_side_closed_); if (!fin_sent_ && !rst_sent_) { QUIC_BUG_IF(quic_bug_12570_6, session()->connection()->connected() && session()->version().UsesHttp3()) << "The stream should've already sent RST in response to " "STOP_SENDING"; MaybeSendRstStream(QUIC_RST_ACKNOWLEDGEMENT); session_->MaybeCloseZombieStream(id_); } if (!flow_controller_.has_value() || flow_controller_->FlowControlViolation() || connection_flow_controller_->FlowControlViolation()) { return; } QuicByteCount bytes_to_consume = flow_controller_->highest_received_byte_offset() - flow_controller_->bytes_consumed(); AddBytesConsumed(bytes_to_consume); } void QuicStream::OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) { if (type_ == READ_UNIDIRECTIONAL) { OnUnrecoverableError( QUIC_WINDOW_UPDATE_RECEIVED_ON_READ_UNIDIRECTIONAL_STREAM, "WindowUpdateFrame received on READ_UNIDIRECTIONAL stream."); return; } if (!flow_controller_.has_value()) { QUIC_BUG(quic_bug_10586_9) << ENDPOINT << "OnWindowUpdateFrame called on stream without flow control"; return; } if (flow_controller_->UpdateSendWindowOffset(frame.max_data)) { session_->MarkConnectionLevelWriteBlocked(id_); } } bool QuicStream::MaybeIncreaseHighestReceivedOffset( QuicStreamOffset new_offset) { if (!flow_controller_.has_value()) { QUIC_BUG(quic_bug_10586_10) << ENDPOINT << "MaybeIncreaseHighestReceivedOffset called on stream without " "flow control"; return false; } uint64_t increment = new_offset - flow_controller_->highest_received_byte_offset(); if (!flow_controller_->UpdateHighestReceivedOffset(new_offset)) { return false; } if (stream_contributes_to_connection_flow_control_) { connection_flow_controller_->UpdateHighestReceivedOffset( connection_flow_controller_->highest_received_byte_offset() + increment); } return true; } void QuicStream::AddBytesSent(QuicByteCount bytes) { if (!flow_controller_.has_value()) { QUIC_BUG(quic_bug_10586_11) << ENDPOINT << "AddBytesSent called on stream without flow control"; return; } flow_controller_->AddBytesSent(bytes); if (stream_contributes_to_connection_flow_control_) { connection_flow_controller_->AddBytesSent(bytes); } } void QuicStream::AddBytesConsumed(QuicByteCount bytes) { if (type_ == CRYPTO) { return; } if (!flow_controller_.has_value()) { QUIC_BUG(quic_bug_12570_7) << ENDPOINT << "AddBytesConsumed called on non-crypto stream without flow control"; return; } if (!read_side_closed_) { flow_controller_->AddBytesConsumed(bytes); } if (stream_contributes_to_connection_flow_control_) { connection_flow_controller_->AddBytesConsumed(bytes); } MaybeCloseStreamWithBufferedReset(); } bool QuicStream::MaybeConfigSendWindowOffset(QuicStreamOffset new_offset, bool was_zero_rtt_rejected) { if (!flow_controller_.has_value()) { QUIC_BUG(quic_bug_10586_12) << ENDPOINT << "ConfigSendWindowOffset called on stream without flow control"; return false; } if (new_offset < flow_controller_->send_window_offset()) { QUICHE_DCHECK(session()->version().UsesTls()); if (was_zero_rtt_rejected && new_offset < flow_controller_->bytes_sent()) { QUIC_BUG_IF(quic_bug_12570_8, perspective_ == Perspective::IS_SERVER) << "Server streams' flow control should never be configured twice."; OnUnrecoverableError( QUIC_ZERO_RTT_UNRETRANSMITTABLE, absl::StrCat( "Server rejected 0-RTT, aborting because new stream max data ", new_offset, " for stream ", id_, " is less than currently used: ", flow_controller_->bytes_sent())); return false; } else if (session()->version().AllowsLowFlowControlLimits()) { QUIC_BUG_IF(quic_bug_12570_9, perspective_ == Perspective::IS_SERVER) << "Server streams' flow control should never be configured twice."; OnUnrecoverableError( was_zero_rtt_rejected ? QUIC_ZERO_RTT_REJECTION_LIMIT_REDUCED : QUIC_ZERO_RTT_RESUMPTION_LIMIT_REDUCED, absl::StrCat( was_zero_rtt_rejected ? "Server rejected 0-RTT, aborting because " : "", "new stream max data ", new_offset, " decreases current limit: ", flow_controller_->send_window_offset())); return false; } } if (flow_controller_->UpdateSendWindowOffset(new_offset)) { session_->MarkConnectionLevelWriteBlocked(id_); } return true; } void QuicStream::AddRandomPaddingAfterFin() { add_random_padding_after_fin_ = true; } bool QuicStream::OnStreamFrameAcked(QuicStreamOffset offset, QuicByteCount data_length, bool fin_acked, QuicTime::Delta , QuicTime , QuicByteCount* newly_acked_length) { QUIC_DVLOG(1) << ENDPOINT << "stream " << id_ << " Acking " << "[" << offset << ", " << offset + data_length << "]" << " fin = " << fin_acked; *newly_acked_length = 0; if (!send_buffer_.OnStreamDataAcked(offset, data_length, newly_acked_length)) { OnUnrecoverableError(QUIC_INTERNAL_ERROR, "Trying to ack unsent data."); return false; } if (!fin_sent_ && fin_acked) { OnUnrecoverableError(QUIC_INTERNAL_ERROR, "Trying to ack unsent fin."); return false; } const bool new_data_acked = *newly_acked_length > 0 || (fin_acked && fin_outstanding_); if (fin_acked) { fin_outstanding_ = false; fin_lost_ = false; } if (!IsWaitingForAcks() && write_side_closed_ && !write_side_data_recvd_state_notified_) { OnWriteSideInDataRecvdState(); write_side_data_recvd_state_notified_ = true; } if (!IsWaitingForAcks() && read_side_closed_ && write_side_closed_) { session_->MaybeCloseZombieStream(id_); } return new_data_acked; } void QuicStream::OnStreamFrameRetransmitted(QuicStreamOffset offset, QuicByteCount data_length, bool fin_retransmitted) { send_buffer_.OnStreamDataRetransmitted(offset, data_length); if (fin_retransmitted) { fin_lost_ = false; } } void QuicStream::OnStreamFrameLost(QuicStreamOffset offset, QuicByteCount data_length, bool fin_lost) { QUIC_DVLOG(1) << ENDPOINT << "stream " << id_ << " Losting " << "[" << offset << ", " << offset + data_length << "]" << " fin = " << fin_lost; if (data_length > 0) { send_buffer_.OnStreamDataLost(offset, data_length); } if (fin_lost && fin_outstanding_) { fin_lost_ = true; } } bool QuicStream::RetransmitStreamData(QuicStreamOffset offset, QuicByteCount data_length, bool fin, TransmissionType type) { QUICHE_DCHECK(type == PTO_RETRANSMISSION); if (HasDeadlinePassed()) { OnDeadlinePassed(); return true; } QuicIntervalSet<QuicStreamOffset> retransmission(offset, offset + data_length); retransmission.Difference(bytes_acked()); bool retransmit_fin = fin && fin_outstanding_; if (retransmission.Empty() && !retransmit_fin) { return true; } QuicConsumedData consumed(0, false); for (const auto& interval : retransmission) { QuicStreamOffset retransmission_offset = interval.min(); QuicByteCount retransmission_length = interval.max() - interval.min(); const bool can_bundle_fin = retransmit_fin && (retransmission_offset + retransmission_length == stream_bytes_written()); consumed = stream_delegate_->WritevData( id_, retransmission_length, retransmission_offset, can_bundle_fin ? FIN : NO_FIN, type, session()->GetEncryptionLevelToSendApplicationData()); QUIC_DVLOG(1) << ENDPOINT << "stream " << id_ << " is forced to retransmit stream data [" << retransmission_offset << ", " << retransmission_offset + retransmission_length << ") and fin: " << can_bundle_fin << ", consumed: " << consumed; OnStreamFrameRetransmitted(retransmission_offset, consumed.bytes_consumed, consumed.fin_consumed); if (can_bundle_fin) { retransmit_fin = !consumed.fin_consumed; } if (consumed.bytes_consumed < retransmission_length || (can_bundle_fin && !consumed.fin_consumed)) { return false; } } if (retransmit_fin) { QUIC_DVLOG(1) << ENDPOINT << "stream " << id_ << " retransmits fin only frame."; consumed = stream_delegate_->WritevData( id_, 0, stream_bytes_written(), FIN, type, session()->GetEncryptionLevelToSendApplicationData()); if (!consumed.fin_consumed) { return false; } } return true; } bool QuicStream::IsWaitingForAcks() const { return (!rst_sent_ || stream_error_.ok()) && (send_buffer_.stream_bytes_outstanding() || fin_outstanding_); } bool QuicStream::WriteStreamData(QuicStreamOffset offset, QuicByteCount data_length, QuicDataWriter* writer) { QUICHE_DCHECK_LT(0u, data_length); QUIC_DVLOG(2) << ENDPOINT << "Write stream " << id_ << " data from offset " << offset << " length " << data_length; return send_buffer_.WriteStreamData(offset, data_length, writer); } void QuicStream::WriteBufferedData(EncryptionLevel level) { QUICHE_DCHECK(!write_side_closed_ && (HasBufferedData() || fin_buffered_)); if (session_->ShouldYield(id())) { session_->MarkConnectionLevelWriteBlocked(id()); return; } QuicByteCount write_length = BufferedDataBytes(); bool fin_with_zero_data = (fin_buffered_ && write_length == 0); bool fin = fin_buffered_; QUIC_BUG_IF(quic_bug_10586_13, !flow_controller_.has_value()) << ENDPOINT << "WriteBufferedData called on stream without flow control"; QuicByteCount send_window = CalculateSendWindowSize(); if (send_window == 0 && !fin_with_zero_data) { MaybeSendBlocked(); return; } if (write_length > send_window) { fin = false; write_length = send_window; QUIC_DVLOG(1) << "stream " << id() << " shortens write length to " << write_length << " due to flow control"; } StreamSendingState state = fin ? FIN : NO_FIN; if (fin && add_random_padding_after_fin_) { state = FIN_AND_PADDING; } QuicConsumedData consumed_data = stream_delegate_->WritevData(id(), write_length, stream_bytes_written(), state, NOT_RETRANSMISSION, level); OnStreamDataConsumed(consumed_data.bytes_consumed); AddBytesSent(consumed_data.bytes_consumed); QUIC_DVLOG(1) << ENDPOINT << "stream " << id_ << " sends " << stream_bytes_written() << " bytes " << " and has buffered data " << BufferedDataBytes() << " bytes." << " fin is sent: " << consumed_data.fin_consumed << " fin is buffered: " << fin_buffered_; if (write_side_closed_) { return; } if (consumed_data.bytes_consumed == write_length) { if (!fin_with_zero_data) { MaybeSendBlocked(); } if (fin && consumed_data.fin_consumed) { QUICHE_DCHECK(!fin_sent_); fin_sent_ = true; fin_outstanding_ = true; if (fin_received_) { QUICHE_DCHECK(!was_draining_); session_->StreamDraining(id_, type_ != BIDIRECTIONAL); was_draining_ = true; } CloseWriteSide(); } else if (fin && !consumed_data.fin_consumed && !write_side_closed_) { session_->MarkConnectionLevelWriteBlocked(id()); } } else { session_->MarkConnectionLevelWriteBlocked(id()); } if (consumed_data.bytes_consumed > 0 || consumed_data.fin_consumed) { busy_counter_ = 0; } } uint64_t QuicStream::BufferedDataBytes() const { QUICHE_DCHECK_GE(send_buffer_.stream_offset(), stream_bytes_written()); return send_buffer_.stream_offset() - stream_bytes_written(); } bool QuicStream::CanWriteNewData() const { return BufferedDataBytes() < buffered_data_threshold_; } bool QuicStream::CanWriteNewDataAfterData(QuicByteCount length) const { return (BufferedDataBytes() + length) < buffered_data_threshold_; } uint64_t QuicStream::stream_bytes_written() const { return send_buffer_.stream_bytes_written(); } const QuicIntervalSet<QuicStreamOffset>& QuicStream::bytes_acked() const { return send_buffer_.bytes_acked(); } void QuicStream::OnStreamDataConsumed(QuicByteCount bytes_consumed) { send_buffer_.OnStreamDataConsumed(bytes_consumed); } void QuicStream::WritePendingRetransmission() { while (HasPendingRetransmission()) { QuicConsumedData consumed(0, false); if (!send_buffer_.HasPendingRetransmission()) { QUIC_DVLOG(1) << ENDPOINT << "stream " << id_ << " retransmits fin only frame."; consumed = stream_delegate_->WritevData( id_, 0, stream_bytes_written(), FIN, LOSS_RETRANSMISSION, session()->GetEncryptionLevelToSendApplicationData()); fin_lost_ = !consumed.fin_consumed; if (fin_lost_) { return; } } else { StreamPendingRetransmission pending = send_buffer_.NextPendingRetransmission(); const bool can_bundle_fin = fin_lost_ && (pending.offset + pending.length == stream_bytes_written()); consumed = stream_delegate_->WritevData( id_, pending.length, pending.offset, can_bundle_fin ? FIN : NO_FIN, LOSS_RETRANSMISSION, session()->GetEncryptionLevelToSendApplicationData()); QUIC_DVLOG(1) << ENDPOINT << "stream " << id_ << " tries to retransmit stream data [" << pending.offset << ", " << pending.offset + pending.length << ") and fin: " << can_bundle_fin << ", consumed: " << consumed; OnStreamFrameRetransmitted(pending.offset, consumed.bytes_consumed, consumed.fin_consumed); if (consumed.bytes_consumed < pending.length || (can_bundle_fin && !consumed.fin_consumed)) { return; } } } } bool QuicStream::MaybeSetTtl(QuicTime::Delta ttl) { if (is_static_) { QUIC_BUG(quic_bug_10586_14) << "Cannot set TTL of a static stream."; return false; } if (deadline_.IsInitialized()) { QUIC_DLOG(WARNING) << "Deadline has already been set."; return false; } QuicTime now = session()->connection()->clock()->ApproximateNow(); deadline_ = now + ttl; return true; } bool QuicStream::HasDeadlinePassed() const { if (!deadline_.IsInitialized()) { return false; } QuicTime now = session()->connection()->clock()->ApproximateNow(); if (now < deadline_) { return false; } QUIC_DVLOG(1) << "stream " << id() << " deadline has passed"; return true; } void QuicStream::MaybeCloseStreamWithBufferedReset() { if (buffered_reset_stream_at_.has_value() && !sequencer_.IsClosed() && NumBytesConsumed() >= buffered_reset_stream_at_->reliable_offset) { OnStreamReset(buffered_reset_stream_at_->ToRstStream()); buffered_reset_stream_at_ = std::nullopt; } } void QuicStream::OnDeadlinePassed() { Reset(QUIC_STREAM_TTL_EXPIRED); } bool QuicStream::IsFlowControlBlocked() const { if (!flow_controller_.has_value()) { QUIC_BUG(quic_bug_10586_15) << "Trying to access non-existent flow controller."; return false; } return flow_controller_->IsBlocked(); } QuicStreamOffset QuicStream::highest_received_byte_offset() const { if (!flow_controller_.has_value()) { QUIC_BUG(quic_bug_10586_16) << "Trying to access non-existent flow controller."; return 0; } return flow_controller_->highest_received_byte_offset(); } void QuicStream::UpdateReceiveWindowSize(QuicStreamOffset size) { if (!flow_controller_.has_value()) { QUIC_BUG(quic_bug_10586_17) << "Trying to access non-existent flow controller."; return; } flow_controller_->UpdateReceiveWindowSize(size); } std::optional<QuicByteCount> QuicStream::GetSendWindow() const { return flow_controller_.has_value() ? std::optional<QuicByteCount>(flow_controller_->SendWindowSize()) : std::nullopt; } std::optional<QuicByteCount> QuicStream::GetReceiveWindow() const { return flow_controller_.has_value() ? std::optional<QuicByteCount>( flow_controller_->receive_window_size()) : std::nullopt; } void QuicStream::OnStreamCreatedFromPendingStream() { sequencer()->SetUnblocked(); } QuicByteCount QuicStream::CalculateSendWindowSize() const { QuicByteCount send_window; if (flow_controller_.has_value()) { send_window = flow_controller_->SendWindowSize(); } else { send_window = std::numeric_limits<QuicByteCount>::max(); } if (stream_contributes_to_connection_flow_control_) { send_window = std::min(send_window, connection_flow_controller_->SendWindowSize()); } return send_window; } }
#include "quiche/quic/core/quic_stream.h" #include <cstddef> #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/memory/memory.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/frames/quic_connection_close_frame.h" #include "quiche/quic/core/frames/quic_reset_stream_at_frame.h" #include "quiche/quic/core/frames/quic_rst_stream_frame.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_error_codes.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/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_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_stream_peer.h" #include "quiche/quic/test_tools/quic_stream_sequencer_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/common/quiche_mem_slice_storage.h" using testing::_; using testing::AnyNumber; using testing::AtLeast; using testing::InSequence; using testing::Invoke; using testing::InvokeWithoutArgs; using testing::Return; using testing::StrictMock; namespace quic { namespace test { namespace { const char kData1[] = "FooAndBar"; const char kData2[] = "EepAndBaz"; const QuicByteCount kDataLen = 9; const uint8_t kPacket0ByteConnectionId = 0; const uint8_t kPacket8ByteConnectionId = 8; class TestStream : public QuicStream { public: TestStream(QuicStreamId id, QuicSession* session, StreamType type) : QuicStream(id, session, false, type) { sequencer()->set_level_triggered(true); } TestStream(PendingStream* pending, QuicSession* session, bool is_static) : QuicStream(pending, session, is_static) {} MOCK_METHOD(void, OnDataAvailable, (), (override)); MOCK_METHOD(void, OnCanWriteNewData, (), (override)); MOCK_METHOD(void, OnWriteSideInDataRecvdState, (), (override)); using QuicStream::CanWriteNewData; using QuicStream::CanWriteNewDataAfterData; using QuicStream::CloseWriteSide; using QuicStream::fin_buffered; using QuicStream::MaybeSendStopSending; using QuicStream::OnClose; using QuicStream::WriteMemSlices; using QuicStream::WriteOrBufferData; void ConsumeData(size_t num_bytes) { char buffer[1024]; ASSERT_GT(ABSL_ARRAYSIZE(buffer), num_bytes); struct iovec iov; iov.iov_base = buffer; iov.iov_len = num_bytes; ASSERT_EQ(num_bytes, QuicStreamPeer::sequencer(this)->Readv(&iov, 1)); } private: std::string data_; }; class QuicStreamTest : public QuicTestWithParam<ParsedQuicVersion> { public: QuicStreamTest() : zero_(QuicTime::Delta::Zero()), supported_versions_(AllSupportedVersions()) {} void Initialize(Perspective perspective = Perspective::IS_SERVER) { ParsedQuicVersionVector version_vector; version_vector.push_back(GetParam()); connection_ = new StrictMock<MockQuicConnection>( &helper_, &alarm_factory_, perspective, version_vector); connection_->AdvanceTime(QuicTime::Delta::FromSeconds(1)); session_ = std::make_unique<StrictMock<MockQuicSession>>(connection_); session_->Initialize(); connection_->SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(connection_->perspective())); 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(); stream_ = new StrictMock<TestStream>(kTestStreamId, session_.get(), BIDIRECTIONAL); EXPECT_NE(nullptr, stream_); EXPECT_CALL(*session_, ShouldKeepConnectionAlive()) .WillRepeatedly(Return(true)); session_->ActivateStream(absl::WrapUnique(stream_)); EXPECT_CALL(*session_, MaybeSendStopSendingFrame(kTestStreamId, _)) .Times(AnyNumber()); EXPECT_CALL(*session_, MaybeSendRstStreamFrame(kTestStreamId, _, _)) .Times(AnyNumber()); write_blocked_list_ = QuicSessionPeer::GetWriteBlockedStreams(session_.get()); } bool fin_sent() { return stream_->fin_sent(); } bool rst_sent() { return stream_->rst_sent(); } bool HasWriteBlockedStreams() { return write_blocked_list_->HasWriteBlockedSpecialStream() || write_blocked_list_->HasWriteBlockedDataStreams(); } QuicConsumedData CloseStreamOnWriteError( QuicStreamId id, QuicByteCount , QuicStreamOffset , StreamSendingState , TransmissionType , std::optional<EncryptionLevel> ) { session_->ResetStream(id, QUIC_STREAM_CANCELLED); return QuicConsumedData(1, false); } bool ClearResetStreamFrame(const QuicFrame& frame) { EXPECT_EQ(RST_STREAM_FRAME, frame.type); DeleteFrame(&const_cast<QuicFrame&>(frame)); return true; } bool ClearStopSendingFrame(const QuicFrame& frame) { EXPECT_EQ(STOP_SENDING_FRAME, frame.type); DeleteFrame(&const_cast<QuicFrame&>(frame)); return true; } protected: MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; MockQuicConnection* connection_; std::unique_ptr<MockQuicSession> session_; StrictMock<TestStream>* stream_; QuicWriteBlockedListInterface* write_blocked_list_; QuicTime::Delta zero_; ParsedQuicVersionVector supported_versions_; QuicStreamId kTestStreamId = GetNthClientInitiatedBidirectionalStreamId( GetParam().transport_version, 1); const QuicStreamId kTestPendingStreamId = GetNthClientInitiatedUnidirectionalStreamId(GetParam().transport_version, 1); }; INSTANTIATE_TEST_SUITE_P(QuicStreamTests, QuicStreamTest, ::testing::ValuesIn(AllSupportedVersions()), ::testing::PrintToStringParamName()); using PendingStreamTest = QuicStreamTest; INSTANTIATE_TEST_SUITE_P(PendingStreamTests, PendingStreamTest, ::testing::ValuesIn(CurrentSupportedHttp3Versions()), ::testing::PrintToStringParamName()); TEST_P(PendingStreamTest, PendingStreamStaticness) { Initialize(); PendingStream pending(kTestPendingStreamId, session_.get()); TestStream stream(&pending, session_.get(), false); EXPECT_FALSE(stream.is_static()); PendingStream pending2(kTestPendingStreamId + 4, session_.get()); TestStream stream2(&pending2, session_.get(), true); EXPECT_TRUE(stream2.is_static()); } TEST_P(PendingStreamTest, PendingStreamType) { Initialize(); PendingStream pending(kTestPendingStreamId, session_.get()); TestStream stream(&pending, session_.get(), false); EXPECT_EQ(stream.type(), READ_UNIDIRECTIONAL); } TEST_P(PendingStreamTest, PendingStreamTypeOnClient) { Initialize(Perspective::IS_CLIENT); QuicStreamId server_initiated_pending_stream_id = GetNthServerInitiatedUnidirectionalStreamId(session_->transport_version(), 1); PendingStream pending(server_initiated_pending_stream_id, session_.get()); TestStream stream(&pending, session_.get(), false); EXPECT_EQ(stream.type(), READ_UNIDIRECTIONAL); } TEST_P(PendingStreamTest, PendingStreamTooMuchData) { Initialize(); PendingStream pending(kTestPendingStreamId, session_.get()); QuicStreamFrame frame(kTestPendingStreamId, false, kInitialSessionFlowControlWindowForTest + 1, "."); EXPECT_CALL(*connection_, CloseConnection(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, _, _)); pending.OnStreamFrame(frame); } TEST_P(PendingStreamTest, PendingStreamTooMuchDataInRstStream) { Initialize(); PendingStream pending1(kTestPendingStreamId, session_.get()); QuicRstStreamFrame frame1(kInvalidControlFrameId, kTestPendingStreamId, QUIC_STREAM_CANCELLED, kInitialSessionFlowControlWindowForTest + 1); EXPECT_CALL(*connection_, CloseConnection(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, _, _)); pending1.OnRstStreamFrame(frame1); QuicStreamId bidirection_stream_id = QuicUtils::GetFirstBidirectionalStreamId( session_->transport_version(), Perspective::IS_CLIENT); PendingStream pending2(bidirection_stream_id, session_.get()); QuicRstStreamFrame frame2(kInvalidControlFrameId, bidirection_stream_id, QUIC_STREAM_CANCELLED, kInitialSessionFlowControlWindowForTest + 1); EXPECT_CALL(*connection_, CloseConnection(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, _, _)); pending2.OnRstStreamFrame(frame2); } TEST_P(PendingStreamTest, PendingStreamRstStream) { Initialize(); PendingStream pending(kTestPendingStreamId, session_.get()); QuicStreamOffset final_byte_offset = 7; QuicRstStreamFrame frame(kInvalidControlFrameId, kTestPendingStreamId, QUIC_STREAM_CANCELLED, final_byte_offset); EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); pending.OnRstStreamFrame(frame); } TEST_P(PendingStreamTest, PendingStreamWindowUpdate) { Initialize(); QuicStreamId bidirection_stream_id = QuicUtils::GetFirstBidirectionalStreamId( session_->transport_version(), Perspective::IS_CLIENT); PendingStream pending(bidirection_stream_id, session_.get()); QuicWindowUpdateFrame frame(kInvalidControlFrameId, bidirection_stream_id, kDefaultFlowControlSendWindow * 2); pending.OnWindowUpdateFrame(frame); TestStream stream(&pending, session_.get(), false); EXPECT_EQ(QuicStreamPeer::SendWindowSize(&stream), kDefaultFlowControlSendWindow * 2); } TEST_P(PendingStreamTest, PendingStreamStopSending) { Initialize(); QuicStreamId bidirection_stream_id = QuicUtils::GetFirstBidirectionalStreamId( session_->transport_version(), Perspective::IS_CLIENT); PendingStream pending(bidirection_stream_id, session_.get()); QuicResetStreamError error = QuicResetStreamError::FromInternal(QUIC_STREAM_INTERNAL_ERROR); pending.OnStopSending(error); EXPECT_TRUE(pending.GetStopSendingErrorCode()); auto actual_error = *pending.GetStopSendingErrorCode(); EXPECT_EQ(actual_error, error); } TEST_P(PendingStreamTest, FromPendingStream) { Initialize(); PendingStream pending(kTestPendingStreamId, session_.get()); QuicStreamFrame frame(kTestPendingStreamId, false, 2, "."); pending.OnStreamFrame(frame); pending.OnStreamFrame(frame); QuicStreamFrame frame2(kTestPendingStreamId, true, 3, "."); pending.OnStreamFrame(frame2); TestStream stream(&pending, session_.get(), false); EXPECT_EQ(3, stream.num_frames_received()); EXPECT_EQ(3u, stream.stream_bytes_read()); EXPECT_EQ(1, stream.num_duplicate_frames_received()); EXPECT_EQ(true, stream.fin_received()); EXPECT_EQ(frame2.offset + 1, stream.highest_received_byte_offset()); EXPECT_EQ(frame2.offset + 1, session_->flow_controller()->highest_received_byte_offset()); } TEST_P(PendingStreamTest, FromPendingStreamThenData) { Initialize(); PendingStream pending(kTestPendingStreamId, session_.get()); QuicStreamFrame frame(kTestPendingStreamId, false, 2, "."); pending.OnStreamFrame(frame); auto stream = new TestStream(&pending, session_.get(), false); session_->ActivateStream(absl::WrapUnique(stream)); QuicStreamFrame frame2(kTestPendingStreamId, true, 3, "."); stream->OnStreamFrame(frame2); EXPECT_EQ(2, stream->num_frames_received()); EXPECT_EQ(2u, stream->stream_bytes_read()); EXPECT_EQ(true, stream->fin_received()); EXPECT_EQ(frame2.offset + 1, stream->highest_received_byte_offset()); EXPECT_EQ(frame2.offset + 1, session_->flow_controller()->highest_received_byte_offset()); } TEST_P(PendingStreamTest, ResetStreamAt) { Initialize(); if (!VersionHasIetfQuicFrames(session_->transport_version())) { return; } PendingStream pending(kTestPendingStreamId, session_.get()); QuicResetStreamAtFrame rst(0, kTestPendingStreamId, QUIC_STREAM_CANCELLED, 100, 3); pending.OnResetStreamAtFrame(rst); QuicStreamFrame frame(kTestPendingStreamId, false, 2, "."); pending.OnStreamFrame(frame); auto stream = new TestStream(&pending, session_.get(), false); session_->ActivateStream(absl::WrapUnique(stream)); EXPECT_FALSE(stream->rst_received()); EXPECT_FALSE(stream->read_side_closed()); EXPECT_CALL(*stream, OnDataAvailable()).WillOnce([&]() { stream->ConsumeData(3); }); QuicStreamFrame frame2(kTestPendingStreamId, false, 0, ".."); stream->OnStreamFrame(frame2); EXPECT_TRUE(stream->read_side_closed()); EXPECT_TRUE(stream->rst_received()); } TEST_P(QuicStreamTest, WriteAllData) { Initialize(); QuicByteCount length = 1 + QuicPacketCreator::StreamFramePacketOverhead( connection_->transport_version(), kPacket8ByteConnectionId, kPacket0ByteConnectionId, !kIncludeVersion, !kIncludeDiversificationNonce, PACKET_4BYTE_PACKET_NUMBER, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0, 0u); connection_->SetMaxPacketLength(length); EXPECT_CALL(*session_, WritevData(kTestStreamId, _, _, _, _, _)) .WillOnce(Invoke(session_.get(), &MockQuicSession::ConsumeData)); stream_->WriteOrBufferData(kData1, false, nullptr); EXPECT_FALSE(HasWriteBlockedStreams()); } TEST_P(QuicStreamTest, NoBlockingIfNoDataOrFin) { Initialize(); EXPECT_QUIC_BUG( stream_->WriteOrBufferData(absl::string_view(), false, nullptr), ""); EXPECT_FALSE(HasWriteBlockedStreams()); } TEST_P(QuicStreamTest, BlockIfOnlySomeDataConsumed) { Initialize(); EXPECT_CALL(*session_, WritevData(kTestStreamId, _, _, _, _, _)) .WillOnce(InvokeWithoutArgs([this]() { return session_->ConsumeData(stream_->id(), 1u, 0u, NO_FIN, NOT_RETRANSMISSION, std::nullopt); })); stream_->WriteOrBufferData(absl::string_view(kData1, 2), false, nullptr); EXPECT_TRUE(session_->HasUnackedStreamData()); ASSERT_EQ(1u, write_blocked_list_->NumBlockedStreams()); EXPECT_EQ(1u, stream_->BufferedDataBytes()); } TEST_P(QuicStreamTest, BlockIfFinNotConsumedWithData) { Initialize(); EXPECT_CALL(*session_, WritevData(kTestStreamId, _, _, _, _, _)) .WillOnce(InvokeWithoutArgs([this]() { return session_->ConsumeData(stream_->id(), 2u, 0u, NO_FIN, NOT_RETRANSMISSION, std::nullopt); })); stream_->WriteOrBufferData(absl::string_view(kData1, 2), true, nullptr); EXPECT_TRUE(session_->HasUnackedStreamData()); ASSERT_EQ(1u, write_blocked_list_->NumBlockedStreams()); } TEST_P(QuicStreamTest, BlockIfSoloFinNotConsumed) { Initialize(); EXPECT_CALL(*session_, WritevData(kTestStreamId, _, _, _, _, _)) .WillOnce(Return(QuicConsumedData(0, false))); stream_->WriteOrBufferData(absl::string_view(), true, nullptr); ASSERT_EQ(1u, write_blocked_list_->NumBlockedStreams()); } TEST_P(QuicStreamTest, CloseOnPartialWrite) { Initialize(); EXPECT_CALL(*session_, WritevData(kTestStreamId, _, _, _, _, _)) .WillOnce(Invoke(this, &QuicStreamTest::CloseStreamOnWriteError)); stream_->WriteOrBufferData(absl::string_view(kData1, 2), false, nullptr); ASSERT_EQ(0u, write_blocked_list_->NumBlockedStreams()); } TEST_P(QuicStreamTest, WriteOrBufferData) { Initialize(); EXPECT_FALSE(HasWriteBlockedStreams()); QuicByteCount length = 1 + QuicPacketCreator::StreamFramePacketOverhead( connection_->transport_version(), kPacket8ByteConnectionId, kPacket0ByteConnectionId, !kIncludeVersion, !kIncludeDiversificationNonce, PACKET_4BYTE_PACKET_NUMBER, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0, 0u); connection_->SetMaxPacketLength(length); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillOnce(InvokeWithoutArgs([this]() { return session_->ConsumeData(stream_->id(), kDataLen - 1, 0u, NO_FIN, NOT_RETRANSMISSION, std::nullopt); })); stream_->WriteOrBufferData(kData1, false, nullptr); EXPECT_TRUE(session_->HasUnackedStreamData()); EXPECT_EQ(1u, stream_->BufferedDataBytes()); EXPECT_TRUE(HasWriteBlockedStreams()); stream_->WriteOrBufferData(kData2, false, nullptr); EXPECT_EQ(10u, stream_->BufferedDataBytes()); InSequence s; EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillOnce(InvokeWithoutArgs([this]() { return session_->ConsumeData(stream_->id(), kDataLen - 1, kDataLen - 1, NO_FIN, NOT_RETRANSMISSION, std::nullopt); })); EXPECT_CALL(*stream_, OnCanWriteNewData()); stream_->OnCanWrite(); EXPECT_TRUE(session_->HasUnackedStreamData()); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillOnce(InvokeWithoutArgs([this]() { return session_->ConsumeData(stream_->id(), 2u, 2 * kDataLen - 2, NO_FIN, NOT_RETRANSMISSION, std::nullopt); })); EXPECT_CALL(*stream_, OnCanWriteNewData()); stream_->OnCanWrite(); EXPECT_TRUE(session_->HasUnackedStreamData()); } TEST_P(QuicStreamTest, WriteOrBufferDataReachStreamLimit) { Initialize(); std::string data("aaaaa"); QuicStreamPeer::SetStreamBytesWritten(kMaxStreamLength - data.length(), stream_); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillOnce(Invoke(session_.get(), &MockQuicSession::ConsumeData)); stream_->WriteOrBufferData(data, false, nullptr); EXPECT_TRUE(session_->HasUnackedStreamData()); EXPECT_QUIC_BUG( { EXPECT_CALL(*connection_, CloseConnection(QUIC_STREAM_LENGTH_OVERFLOW, _, _)); stream_->WriteOrBufferData("a", false, nullptr); }, "Write too many data via stream"); } TEST_P(QuicStreamTest, ConnectionCloseAfterStreamClose) { Initialize(); 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_THAT(stream_->stream_error(), IsStreamError(QUIC_STREAM_CANCELLED)); EXPECT_THAT(stream_->connection_error(), IsQuicNoError()); QuicConnectionCloseFrame frame; frame.quic_error_code = QUIC_INTERNAL_ERROR; stream_->OnConnectionClosed(frame, ConnectionCloseSource::FROM_SELF); EXPECT_THAT(stream_->stream_error(), IsStreamError(QUIC_STREAM_CANCELLED)); EXPECT_THAT(stream_->connection_error(), IsQuicNoError()); } TEST_P(QuicStreamTest, RstAlwaysSentIfNoFinSent) { Initialize(); EXPECT_FALSE(fin_sent()); EXPECT_FALSE(rst_sent()); EXPECT_CALL(*session_, WritevData(kTestStreamId, _, _, _, _, _)) .WillOnce(InvokeWithoutArgs([this]() { return session_->ConsumeData(stream_->id(), 1u, 0u, NO_FIN, NOT_RETRANSMISSION, std::nullopt); })); stream_->WriteOrBufferData(absl::string_view(kData1, 1), false, nullptr); EXPECT_TRUE(session_->HasUnackedStreamData()); EXPECT_FALSE(fin_sent()); EXPECT_FALSE(rst_sent()); EXPECT_CALL(*session_, MaybeSendRstStreamFrame(kTestStreamId, _, _)); 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_FALSE(session_->HasUnackedStreamData()); EXPECT_FALSE(fin_sent()); EXPECT_TRUE(rst_sent()); } TEST_P(QuicStreamTest, RstNotSentIfFinSent) { Initialize(); EXPECT_FALSE(fin_sent()); EXPECT_FALSE(rst_sent()); EXPECT_CALL(*session_, WritevData(kTestStreamId, _, _, _, _, _)) .WillOnce(InvokeWithoutArgs([this]() { return session_->ConsumeData(stream_->id(), 1u, 0u, FIN, NOT_RETRANSMISSION, std::nullopt); })); stream_->WriteOrBufferData(absl::string_view(kData1, 1), true, nullptr); EXPECT_TRUE(fin_sent()); EXPECT_FALSE(rst_sent()); QuicStreamPeer::CloseReadSide(stream_); stream_->CloseWriteSide(); EXPECT_TRUE(fin_sent()); EXPECT_FALSE(rst_sent()); } TEST_P(QuicStreamTest, OnlySendOneRst) { Initialize(); EXPECT_FALSE(fin_sent()); EXPECT_FALSE(rst_sent()); EXPECT_CALL(*session_, MaybeSendRstStreamFrame(kTestStreamId, _, _)).Times(1); stream_->Reset(QUIC_STREAM_CANCELLED); EXPECT_FALSE(fin_sent()); EXPECT_TRUE(rst_sent()); QuicStreamPeer::CloseReadSide(stream_); stream_->CloseWriteSide(); EXPECT_FALSE(fin_sent()); EXPECT_TRUE(rst_sent()); } TEST_P(QuicStreamTest, StreamFlowControlMultipleWindowUpdates) { Initialize(); EXPECT_EQ(kMinimumFlowControlSendWindow, QuicStreamPeer::SendWindowOffset(stream_)); QuicWindowUpdateFrame window_update_1(kInvalidControlFrameId, stream_->id(), kMinimumFlowControlSendWindow + 5); stream_->OnWindowUpdateFrame(window_update_1); EXPECT_EQ(window_update_1.max_data, QuicStreamPeer::SendWindowOffset(stream_)); QuicWindowUpdateFrame window_update_2(kInvalidControlFrameId, stream_->id(), 1); QuicWindowUpdateFrame window_update_3(kInvalidControlFrameId, stream_->id(), kMinimumFlowControlSendWindow + 10); QuicWindowUpdateFrame window_update_4(kInvalidControlFrameId, stream_->id(), 5678); stream_->OnWindowUpdateFrame(window_update_2); stream_->OnWindowUpdateFrame(window_update_3); stream_->OnWindowUpdateFrame(window_update_4); EXPECT_EQ(window_update_3.max_data, QuicStreamPeer::SendWindowOffset(stream_)); } TEST_P(QuicStreamTest, FrameStats) { Initialize(); EXPECT_EQ(0, stream_->num_frames_received()); EXPECT_EQ(0, stream_->num_duplicate_frames_received()); QuicStreamFrame frame(stream_->id(), false, 0, "."); EXPECT_CALL(*stream_, OnDataAvailable()).Times(2); stream_->OnStreamFrame(frame); EXPECT_EQ(1, stream_->num_frames_received()); EXPECT_EQ(0, stream_->num_duplicate_frames_received()); stream_->OnStreamFrame(frame); EXPECT_EQ(2, stream_->num_frames_received()); EXPECT_EQ(1, stream_->num_duplicate_frames_received()); QuicStreamFrame frame2(stream_->id(), false, 1, "abc"); stream_->OnStreamFrame(frame2); } TEST_P(QuicStreamTest, StreamSequencerNeverSeesPacketsViolatingFlowControl) { Initialize(); QuicStreamFrame frame(stream_->id(), false, kInitialSessionFlowControlWindowForTest + 1, "."); EXPECT_GT(frame.offset, QuicStreamPeer::ReceiveWindowOffset(stream_)); EXPECT_CALL(*connection_, CloseConnection(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, _, _)); stream_->OnStreamFrame(frame); } TEST_P(QuicStreamTest, StopReadingSendsFlowControl) { Initialize(); stream_->StopReading(); EXPECT_CALL(*connection_, CloseConnection(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, _, _)) .Times(0); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .Times(AtLeast(1)) .WillRepeatedly(Invoke(&ClearControlFrameWithTransmissionType)); std::string data(1000, 'x'); for (QuicStreamOffset offset = 0; offset < 2 * kInitialStreamFlowControlWindowForTest; offset += data.length()) { QuicStreamFrame frame(stream_->id(), false, offset, data); stream_->OnStreamFrame(frame); } EXPECT_LT(kInitialStreamFlowControlWindowForTest, QuicStreamPeer::ReceiveWindowOffset(stream_)); } TEST_P(QuicStreamTest, FinalByteOffsetFromFin) { Initialize(); EXPECT_FALSE(stream_->HasReceivedFinalOffset()); QuicStreamFrame stream_frame_no_fin(stream_->id(), false, 1234, "."); stream_->OnStreamFrame(stream_frame_no_fin); EXPECT_FALSE(stream_->HasReceivedFinalOffset()); QuicStreamFrame stream_frame_with_fin(stream_->id(), true, 1234, "."); stream_->OnStreamFrame(stream_frame_with_fin); EXPECT_TRUE(stream_->HasReceivedFinalOffset()); } TEST_P(QuicStreamTest, FinalByteOffsetFromRst) { Initialize(); EXPECT_FALSE(stream_->HasReceivedFinalOffset()); QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream_->id(), QUIC_STREAM_CANCELLED, 1234); stream_->OnStreamReset(rst_frame); EXPECT_TRUE(stream_->HasReceivedFinalOffset()); } TEST_P(QuicStreamTest, InvalidFinalByteOffsetFromRst) { Initialize(); EXPECT_FALSE(stream_->HasReceivedFinalOffset()); QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream_->id(), QUIC_STREAM_CANCELLED, 0xFFFFFFFFFFFF); EXPECT_CALL(*connection_, CloseConnection(QUIC_FLOW_CONTROL_RECEIVED_TOO_MUCH_DATA, _, _)); stream_->OnStreamReset(rst_frame); EXPECT_TRUE(stream_->HasReceivedFinalOffset()); } TEST_P(QuicStreamTest, FinalByteOffsetFromZeroLengthStreamFrame) { Initialize(); EXPECT_FALSE(stream_->HasReceivedFinalOffset()); const QuicStreamOffset kByteOffsetExceedingFlowControlWindow = kInitialSessionFlowControlWindowForTest + 1; const QuicStreamOffset current_stream_flow_control_offset = QuicStreamPeer::ReceiveWindowOffset(stream_); const QuicStreamOffset current_connection_flow_control_offset = QuicFlowControllerPeer::ReceiveWindowOffset(session_->flow_controller()); ASSERT_GT(kByteOffsetExceedingFlowControlWindow, current_stream_flow_control_offset); ASSERT_GT(kByteOffsetExceedingFlowControlWindow, current_connection_flow_control_offset); QuicStreamFrame zero_length_stream_frame_with_fin( stream_->id(), true, kByteOffsetExceedingFlowControlWindow, absl::string_view()); EXPECT_EQ(0, zero_length_stream_frame_with_fin.data_length); EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); stream_->OnStreamFrame(zero_length_stream_frame_with_fin); EXPECT_TRUE(stream_->HasReceivedFinalOffset()); EXPECT_EQ(current_stream_flow_control_offset, QuicStreamPeer::ReceiveWindowOffset(stream_)); EXPECT_EQ( current_connection_flow_control_offset, QuicFlowControllerPeer::ReceiveWindowOffset(session_->flow_controller())); } TEST_P(QuicStreamTest, OnStreamResetOffsetOverflow) { Initialize(); QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream_->id(), QUIC_STREAM_CANCELLED, kMaxStreamLength + 1); EXPECT_CALL(*connection_, CloseConnection(QUIC_STREAM_LENGTH_OVERFLOW, _, _)); stream_->OnStreamReset(rst_frame); } TEST_P(QuicStreamTest, OnStreamFrameUpperLimit) { Initialize(); QuicStreamPeer::SetReceiveWindowOffset(stream_, kMaxStreamLength + 5u); QuicFlowControllerPeer::SetReceiveWindowOffset(session_->flow_controller(), kMaxStreamLength + 5u); QuicStreamSequencerPeer::SetFrameBufferTotalBytesRead( QuicStreamPeer::sequencer(stream_), kMaxStreamLength - 10u); EXPECT_CALL(*connection_, CloseConnection(QUIC_STREAM_LENGTH_OVERFLOW, _, _)) .Times(0); QuicStreamFrame stream_frame(stream_->id(), false, kMaxStreamLength - 1, "."); stream_->OnStreamFrame(stream_frame); QuicStreamFrame stream_frame2(stream_->id(), true, kMaxStreamLength, ""); stream_->OnStreamFrame(stream_frame2); } TEST_P(QuicStreamTest, StreamTooLong) { Initialize(); QuicStreamFrame stream_frame(stream_->id(), false, kMaxStreamLength, "."); EXPECT_QUIC_PEER_BUG( { EXPECT_CALL(*connection_, CloseConnection(QUIC_STREAM_LENGTH_OVERFLOW, _, _)) .Times(1); stream_->OnStreamFrame(stream_frame); }, absl::StrCat("Receive stream frame on stream ", stream_->id(), " reaches max stream length")); } TEST_P(QuicStreamTest, SetDrainingIncomingOutgoing) { Initialize(); QuicStreamFrame stream_frame_with_fin(stream_->id(), true, 1234, "."); stream_->OnStreamFrame(stream_frame_with_fin); EXPECT_TRUE(stream_->HasReceivedFinalOffset()); EXPECT_FALSE(QuicStreamPeer::read_side_closed(stream_)); EXPECT_FALSE(stream_->reading_stopped()); EXPECT_EQ(1u, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); EXPECT_CALL(*session_, WritevData(kTestStreamId, _, _, _, _, _)) .WillOnce(InvokeWithoutArgs([this]() { return session_->ConsumeData(stream_->id(), 2u, 0u, FIN, NOT_RETRANSMISSION, std::nullopt); })); stream_->WriteOrBufferData(absl::string_view(kData1, 2), true, nullptr); EXPECT_TRUE(stream_->write_side_closed()); EXPECT_EQ(1u, QuicSessionPeer::GetNumDrainingStreams(session_.get())); EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); } TEST_P(QuicStreamTest, SetDrainingOutgoingIncoming) { Initialize(); EXPECT_CALL(*session_, WritevData(kTestStreamId, _, _, _, _, _)) .WillOnce(InvokeWithoutArgs([this]() { return session_->ConsumeData(stream_->id(), 2u, 0u, FIN, NOT_RETRANSMISSION, std::nullopt); })); stream_->WriteOrBufferData(absl::string_view(kData1, 2), true, nullptr); EXPECT_TRUE(stream_->write_side_closed()); EXPECT_EQ(1u, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); QuicStreamFrame stream_frame_with_fin(stream_->id(), true, 1234, "."); stream_->OnStreamFrame(stream_frame_with_fin); EXPECT_TRUE(stream_->HasReceivedFinalOffset()); EXPECT_FALSE(QuicStreamPeer::read_side_closed(stream_)); EXPECT_FALSE(stream_->reading_stopped()); EXPECT_EQ(1u, QuicSessionPeer::GetNumDrainingStreams(session_.get())); EXPECT_EQ(0u, QuicSessionPeer::GetNumOpenDynamicStreams(session_.get())); } TEST_P(QuicStreamTest, EarlyResponseFinHandling) { Initialize(); EXPECT_CALL(*connection_, CloseConnection(_, _, _)).Times(0); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly(Invoke(session_.get(), &MockQuicSession::ConsumeData)); EXPECT_CALL(*stream_, OnDataAvailable()).Times(1); QuicStreamFrame frame1(stream_->id(), false, 0, "Start"); stream_->OnStreamFrame(frame1); QuicStreamPeer::CloseReadSide(stream_); stream_->WriteOrBufferData(kData1, false, nullptr); EXPECT_TRUE(QuicStreamPeer::read_side_closed(stream_)); QuicStreamFrame frame2(stream_->id(), true, 0, "End"); stream_->OnStreamFrame(frame2); EXPECT_TRUE(stream_->fin_received()); EXPECT_TRUE(stream_->HasReceivedFinalOffset()); } TEST_P(QuicStreamTest, StreamWaitsForAcks) { Initialize(); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly(Invoke(session_.get(), &MockQuicSession::ConsumeData)); EXPECT_FALSE(stream_->IsWaitingForAcks()); EXPECT_EQ(0u, QuicStreamPeer::SendBuffer(stream_).size()); EXPECT_FALSE(session_->HasUnackedStreamData()); stream_->WriteOrBufferData(kData1, false, nullptr); EXPECT_TRUE(session_->HasUnackedStreamData()); EXPECT_EQ(1u, QuicStreamPeer::SendBuffer(stream_).size()); EXPECT_TRUE(stream_->IsWaitingForAcks()); QuicByteCount newly_acked_length = 0; EXPECT_TRUE(stream_->OnStreamFrameAcked(0, 9, false, QuicTime::Delta::Zero(), QuicTime::Zero(), &newly_acked_length)); EXPECT_EQ(9u, newly_acked_length); EXPECT_FALSE(stream_->IsWaitingForAcks()); EXPECT_FALSE(session_->HasUnackedStreamData()); EXPECT_EQ(0u, QuicStreamPeer::SendBuffer(stream_).size()); stream_->WriteOrBufferData(kData2, false, nullptr); EXPECT_TRUE(stream_->IsWaitingForAcks()); EXPECT_TRUE(session_->HasUnackedStreamData()); EXPECT_EQ(1u, QuicStreamPeer::SendBuffer(stream_).size()); stream_->WriteOrBufferData("", true, nullptr); EXPECT_EQ(1u, QuicStreamPeer::SendBuffer(stream_).size()); stream_->OnStreamFrameRetransmitted(9, 9, false); EXPECT_TRUE(stream_->OnStreamFrameAcked(9, 9, false, QuicTime::Delta::Zero(), QuicTime::Zero(), &newly_acked_length)); EXPECT_EQ(9u, newly_acked_length); EXPECT_TRUE(stream_->IsWaitingForAcks()); EXPECT_TRUE(session_->HasUnackedStreamData()); EXPECT_EQ(0u, QuicStreamPeer::SendBuffer(stream_).size()); EXPECT_CALL(*stream_, OnWriteSideInDataRecvdState()); EXPECT_TRUE(stream_->OnStreamFrameAcked(18, 0, true, QuicTime::Delta::Zero(), QuicTime::Zero(), &newly_acked_length)); EXPECT_EQ(0u, newly_acked_length); EXPECT_FALSE(stream_->IsWaitingForAcks()); EXPECT_FALSE(session_->HasUnackedStreamData()); EXPECT_EQ(0u, QuicStreamPeer::SendBuffer(stream_).size()); } TEST_P(QuicStreamTest, StreamDataGetAckedOutOfOrder) { Initialize(); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly(Invoke(session_.get(), &MockQuicSession::ConsumeData)); stream_->WriteOrBufferData(kData1, false, nullptr); stream_->WriteOrBufferData(kData1, false, nullptr); stream_->WriteOrBufferData(kData1, false, nullptr); stream_->WriteOrBufferData("", true, nullptr); EXPECT_EQ(3u, QuicStreamPeer::SendBuffer(stream_).size()); EXPECT_TRUE(stream_->IsWaitingForAcks()); EXPECT_TRUE(session_->HasUnackedStreamData()); QuicByteCount newly_acked_length = 0; EXPECT_TRUE(stream_->OnStreamFrameAcked(9, 9, false, QuicTime::Delta::Zero(), QuicTime::Zero(), &newly_acked_length)); EXPECT_TRUE(session_->HasUnackedStreamData()); EXPECT_EQ(9u, newly_acked_length); EXPECT_EQ(3u, QuicStreamPeer::SendBuffer(stream_).size()); EXPECT_TRUE(stream_->OnStreamFrameAcked(18, 9, false, QuicTime::Delta::Zero(), QuicTime::Zero(), &newly_acked_length)); EXPECT_TRUE(session_->HasUnackedStreamData()); EXPECT_EQ(9u, newly_acked_length); EXPECT_EQ(3u, QuicStreamPeer::SendBuffer(stream_).size()); EXPECT_TRUE(stream_->OnStreamFrameAcked(0, 9, false, QuicTime::Delta::Zero(), QuicTime::Zero(), &newly_acked_length)); EXPECT_TRUE(session_->HasUnackedStreamData()); EXPECT_EQ(9u, newly_acked_length); EXPECT_EQ(0u, QuicStreamPeer::SendBuffer(stream_).size()); EXPECT_TRUE(stream_->IsWaitingForAcks()); EXPECT_TRUE(session_->HasUnackedStreamData()); EXPECT_CALL(*stream_, OnWriteSideInDataRecvdState()); EXPECT_TRUE(stream_->OnStreamFrameAcked(27, 0, true, QuicTime::Delta::Zero(), QuicTime::Zero(), &newly_acked_length)); EXPECT_EQ(0u, newly_acked_length); EXPECT_FALSE(stream_->IsWaitingForAcks()); EXPECT_FALSE(session_->HasUnackedStreamData()); } TEST_P(QuicStreamTest, CancelStream) { Initialize(); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly(Invoke(session_.get(), &MockQuicSession::ConsumeData)); EXPECT_FALSE(stream_->IsWaitingForAcks()); EXPECT_FALSE(session_->HasUnackedStreamData()); EXPECT_EQ(0u, QuicStreamPeer::SendBuffer(stream_).size()); stream_->WriteOrBufferData(kData1, false, nullptr); EXPECT_TRUE(stream_->IsWaitingForAcks()); EXPECT_TRUE(session_->HasUnackedStreamData()); EXPECT_EQ(1u, QuicStreamPeer::SendBuffer(stream_).size()); stream_->MaybeSendStopSending(QUIC_STREAM_NO_ERROR); EXPECT_TRUE(stream_->IsWaitingForAcks()); EXPECT_TRUE(session_->HasUnackedStreamData()); EXPECT_CALL(*connection_, OnStreamReset(stream_->id(), QUIC_STREAM_CANCELLED)); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .Times(AtLeast(1)) .WillRepeatedly(Invoke(&ClearControlFrameWithTransmissionType)); EXPECT_CALL(*session_, MaybeSendRstStreamFrame(_, _, _)) .WillOnce(InvokeWithoutArgs([this]() { session_->ReallyMaybeSendRstStreamFrame( stream_->id(), QUIC_STREAM_CANCELLED, stream_->stream_bytes_written()); })); stream_->Reset(QUIC_STREAM_CANCELLED); EXPECT_EQ(1u, QuicStreamPeer::SendBuffer(stream_).size()); EXPECT_FALSE(stream_->IsWaitingForAcks()); EXPECT_FALSE(session_->HasUnackedStreamData()); } TEST_P(QuicStreamTest, RstFrameReceivedStreamNotFinishSending) { if (VersionHasIetfQuicFrames(GetParam().transport_version)) { return; } Initialize(); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly(Invoke(session_.get(), &MockQuicSession::ConsumeData)); EXPECT_FALSE(stream_->IsWaitingForAcks()); EXPECT_FALSE(session_->HasUnackedStreamData()); EXPECT_EQ(0u, QuicStreamPeer::SendBuffer(stream_).size()); stream_->WriteOrBufferData(kData1, false, nullptr); EXPECT_TRUE(stream_->IsWaitingForAcks()); EXPECT_TRUE(session_->HasUnackedStreamData()); EXPECT_EQ(1u, QuicStreamPeer::SendBuffer(stream_).size()); QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream_->id(), QUIC_STREAM_CANCELLED, 9); EXPECT_CALL( *session_, MaybeSendRstStreamFrame( stream_->id(), QuicResetStreamError::FromInternal(QUIC_RST_ACKNOWLEDGEMENT), 9)); stream_->OnStreamReset(rst_frame); EXPECT_EQ(1u, QuicStreamPeer::SendBuffer(stream_).size()); EXPECT_FALSE(stream_->IsWaitingForAcks()); EXPECT_FALSE(session_->HasUnackedStreamData()); } TEST_P(QuicStreamTest, RstFrameReceivedStreamFinishSending) { Initialize(); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly(Invoke(session_.get(), &MockQuicSession::ConsumeData)); EXPECT_FALSE(stream_->IsWaitingForAcks()); EXPECT_FALSE(session_->HasUnackedStreamData()); EXPECT_EQ(0u, QuicStreamPeer::SendBuffer(stream_).size()); stream_->WriteOrBufferData(kData1, true, nullptr); EXPECT_TRUE(stream_->IsWaitingForAcks()); EXPECT_TRUE(session_->HasUnackedStreamData()); QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream_->id(), QUIC_STREAM_CANCELLED, 1234); stream_->OnStreamReset(rst_frame); EXPECT_TRUE(stream_->IsWaitingForAcks()); EXPECT_TRUE(session_->HasUnackedStreamData()); EXPECT_EQ(1u, QuicStreamPeer::SendBuffer(stream_).size()); } TEST_P(QuicStreamTest, ConnectionClosed) { Initialize(); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly(Invoke(session_.get(), &MockQuicSession::ConsumeData)); EXPECT_FALSE(stream_->IsWaitingForAcks()); EXPECT_FALSE(session_->HasUnackedStreamData()); EXPECT_EQ(0u, QuicStreamPeer::SendBuffer(stream_).size()); stream_->WriteOrBufferData(kData1, false, nullptr); EXPECT_TRUE(stream_->IsWaitingForAcks()); EXPECT_TRUE(session_->HasUnackedStreamData()); EXPECT_CALL( *session_, MaybeSendRstStreamFrame( stream_->id(), QuicResetStreamError::FromInternal(QUIC_RST_ACKNOWLEDGEMENT), 9)); QuicConnectionPeer::SetConnectionClose(connection_); QuicConnectionCloseFrame frame; frame.quic_error_code = QUIC_INTERNAL_ERROR; stream_->OnConnectionClosed(frame, ConnectionCloseSource::FROM_SELF); EXPECT_EQ(1u, QuicStreamPeer::SendBuffer(stream_).size()); EXPECT_FALSE(stream_->IsWaitingForAcks()); EXPECT_FALSE(session_->HasUnackedStreamData()); } TEST_P(QuicStreamTest, CanWriteNewDataAfterData) { SetQuicFlag(quic_buffered_data_threshold, 100); Initialize(); EXPECT_TRUE(stream_->CanWriteNewDataAfterData(99)); EXPECT_FALSE(stream_->CanWriteNewDataAfterData(100)); } TEST_P(QuicStreamTest, WriteBufferedData) { SetQuicFlag(quic_buffered_data_threshold, 100); Initialize(); std::string data(1024, 'a'); EXPECT_TRUE(stream_->CanWriteNewData()); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillOnce(InvokeWithoutArgs([this]() { return session_->ConsumeData(stream_->id(), 100u, 0u, NO_FIN, NOT_RETRANSMISSION, std::nullopt); })); stream_->WriteOrBufferData(data, false, nullptr); stream_->WriteOrBufferData(data, false, nullptr); stream_->WriteOrBufferData(data, false, nullptr); EXPECT_TRUE(stream_->IsWaitingForAcks()); EXPECT_EQ(3 * data.length() - 100, stream_->BufferedDataBytes()); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillOnce(InvokeWithoutArgs([this]() { return session_->ConsumeData(stream_->id(), 100, 100u, NO_FIN, NOT_RETRANSMISSION, std::nullopt); })); EXPECT_CALL(*stream_, OnCanWriteNewData()).Times(0); stream_->OnCanWrite(); EXPECT_EQ(3 * data.length() - 200, stream_->BufferedDataBytes()); EXPECT_FALSE(stream_->CanWriteNewData()); QuicByteCount data_to_write = 3 * data.length() - 200 - GetQuicFlag(quic_buffered_data_threshold) + 1; EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillOnce(InvokeWithoutArgs([this, data_to_write]() { return session_->ConsumeData(stream_->id(), data_to_write, 200u, NO_FIN, NOT_RETRANSMISSION, std::nullopt); })); EXPECT_CALL(*stream_, OnCanWriteNewData()).Times(1); stream_->OnCanWrite(); EXPECT_EQ( static_cast<uint64_t>(GetQuicFlag(quic_buffered_data_threshold) - 1), stream_->BufferedDataBytes()); EXPECT_TRUE(stream_->CanWriteNewData()); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillOnce(Invoke(session_.get(), &MockQuicSession::ConsumeData)); EXPECT_CALL(*stream_, OnCanWriteNewData()).Times(1); stream_->OnCanWrite(); EXPECT_EQ(0u, stream_->BufferedDataBytes()); EXPECT_FALSE(stream_->HasBufferedData()); EXPECT_TRUE(stream_->CanWriteNewData()); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillOnce(Return(QuicConsumedData(0, false))); struct iovec iov = {const_cast<char*>(data.data()), data.length()}; quiche::QuicheMemSliceStorage storage( &iov, 1, session_->connection()->helper()->GetStreamSendBufferAllocator(), 1024); QuicConsumedData consumed = stream_->WriteMemSlices(storage.ToSpan(), false); EXPECT_EQ(data.length(), consumed.bytes_consumed); EXPECT_FALSE(consumed.fin_consumed); EXPECT_EQ(data.length(), stream_->BufferedDataBytes()); EXPECT_FALSE(stream_->CanWriteNewData()); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)).Times(0); quiche::QuicheMemSliceStorage storage2( &iov, 1, session_->connection()->helper()->GetStreamSendBufferAllocator(), 1024); consumed = stream_->WriteMemSlices(storage2.ToSpan(), false); EXPECT_EQ(0u, consumed.bytes_consumed); EXPECT_FALSE(consumed.fin_consumed); EXPECT_EQ(data.length(), stream_->BufferedDataBytes()); data_to_write = data.length() - GetQuicFlag(quic_buffered_data_threshold) + 1; EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillOnce(InvokeWithoutArgs([this, data_to_write]() { return session_->ConsumeData(stream_->id(), data_to_write, 0u, NO_FIN, NOT_RETRANSMISSION, std::nullopt); })); EXPECT_CALL(*stream_, OnCanWriteNewData()).Times(1); stream_->OnCanWrite(); EXPECT_EQ( static_cast<uint64_t>(GetQuicFlag(quic_buffered_data_threshold) - 1), stream_->BufferedDataBytes()); EXPECT_TRUE(stream_->CanWriteNewData()); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)).Times(0); quiche::QuicheMemSliceStorage storage3( &iov, 1, session_->connection()->helper()->GetStreamSendBufferAllocator(), 1024); consumed = stream_->WriteMemSlices(storage3.ToSpan(), false); EXPECT_EQ(data.length(), consumed.bytes_consumed); EXPECT_FALSE(consumed.fin_consumed); EXPECT_EQ(data.length() + GetQuicFlag(quic_buffered_data_threshold) - 1, stream_->BufferedDataBytes()); EXPECT_FALSE(stream_->CanWriteNewData()); } TEST_P(QuicStreamTest, WritevDataReachStreamLimit) { Initialize(); std::string data("aaaaa"); QuicStreamPeer::SetStreamBytesWritten(kMaxStreamLength - data.length(), stream_); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillOnce(Invoke(session_.get(), &MockQuicSession::ConsumeData)); struct iovec iov = {const_cast<char*>(data.data()), 5u}; quiche::QuicheMemSliceStorage storage( &iov, 1, session_->connection()->helper()->GetStreamSendBufferAllocator(), 1024); QuicConsumedData consumed = stream_->WriteMemSlices(storage.ToSpan(), false); EXPECT_EQ(data.length(), consumed.bytes_consumed); struct iovec iov2 = {const_cast<char*>(data.data()), 1u}; quiche::QuicheMemSliceStorage storage2( &iov2, 1, session_->connection()->helper()->GetStreamSendBufferAllocator(), 1024); EXPECT_QUIC_BUG( { EXPECT_CALL(*connection_, CloseConnection(QUIC_STREAM_LENGTH_OVERFLOW, _, _)); stream_->WriteMemSlices(storage2.ToSpan(), false); }, "Write too many data via stream"); } TEST_P(QuicStreamTest, WriteMemSlices) { SetQuicFlag(quic_buffered_data_threshold, 100); Initialize(); constexpr QuicByteCount kDataSize = 1024; quiche::QuicheBufferAllocator* allocator = connection_->helper()->GetStreamSendBufferAllocator(); std::vector<quiche::QuicheMemSlice> vector1; vector1.push_back( quiche::QuicheMemSlice(quiche::QuicheBuffer(allocator, kDataSize))); vector1.push_back( quiche::QuicheMemSlice(quiche::QuicheBuffer(allocator, kDataSize))); std::vector<quiche::QuicheMemSlice> vector2; vector2.push_back( quiche::QuicheMemSlice(quiche::QuicheBuffer(allocator, kDataSize))); vector2.push_back( quiche::QuicheMemSlice(quiche::QuicheBuffer(allocator, kDataSize))); absl::Span<quiche::QuicheMemSlice> span1(vector1); absl::Span<quiche::QuicheMemSlice> span2(vector2); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillOnce(InvokeWithoutArgs([this]() { return session_->ConsumeData(stream_->id(), 100u, 0u, NO_FIN, NOT_RETRANSMISSION, std::nullopt); })); QuicConsumedData consumed = stream_->WriteMemSlices(span1, false); EXPECT_EQ(2048u, consumed.bytes_consumed); EXPECT_FALSE(consumed.fin_consumed); EXPECT_EQ(2 * kDataSize - 100, stream_->BufferedDataBytes()); EXPECT_FALSE(stream_->fin_buffered()); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)).Times(0); consumed = stream_->WriteMemSlices(span2, true); EXPECT_EQ(0u, consumed.bytes_consumed); EXPECT_FALSE(consumed.fin_consumed); EXPECT_EQ(2 * kDataSize - 100, stream_->BufferedDataBytes()); EXPECT_FALSE(stream_->fin_buffered()); QuicByteCount data_to_write = 2 * kDataSize - 100 - GetQuicFlag(quic_buffered_data_threshold) + 1; EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillOnce(InvokeWithoutArgs([this, data_to_write]() { return session_->ConsumeData(stream_->id(), data_to_write, 100u, NO_FIN, NOT_RETRANSMISSION, std::nullopt); })); EXPECT_CALL(*stream_, OnCanWriteNewData()).Times(1); stream_->OnCanWrite(); EXPECT_EQ( static_cast<uint64_t>(GetQuicFlag(quic_buffered_data_threshold) - 1), stream_->BufferedDataBytes()); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)).Times(0); consumed = stream_->WriteMemSlices(span2, true); EXPECT_EQ(2048u, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_EQ(2 * kDataSize + GetQuicFlag(quic_buffered_data_threshold) - 1, stream_->BufferedDataBytes()); EXPECT_TRUE(stream_->fin_buffered()); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillOnce(Invoke(session_.get(), &MockQuicSession::ConsumeData)); stream_->OnCanWrite(); EXPECT_CALL(*stream_, OnCanWriteNewData()).Times(0); EXPECT_FALSE(stream_->HasBufferedData()); EXPECT_TRUE(stream_->write_side_closed()); } TEST_P(QuicStreamTest, WriteMemSlicesReachStreamLimit) { Initialize(); QuicStreamPeer::SetStreamBytesWritten(kMaxStreamLength - 5u, stream_); std::vector<std::pair<char*, size_t>> buffers; quiche::QuicheMemSlice slice1 = MemSliceFromString("12345"); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillOnce(InvokeWithoutArgs([this]() { return session_->ConsumeData(stream_->id(), 5u, 0u, NO_FIN, NOT_RETRANSMISSION, std::nullopt); })); QuicConsumedData consumed = stream_->WriteMemSlice(std::move(slice1), false); EXPECT_EQ(5u, consumed.bytes_consumed); quiche::QuicheMemSlice slice2 = MemSliceFromString("6"); EXPECT_QUIC_BUG( { EXPECT_CALL(*connection_, CloseConnection(QUIC_STREAM_LENGTH_OVERFLOW, _, _)); stream_->WriteMemSlice(std::move(slice2), false); }, "Write too many data via stream"); } TEST_P(QuicStreamTest, StreamDataGetAckedMultipleTimes) { Initialize(); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly(Invoke(session_.get(), &MockQuicSession::ConsumeData)); EXPECT_FALSE(stream_->IsWaitingForAcks()); EXPECT_FALSE(session_->HasUnackedStreamData()); stream_->WriteOrBufferData(kData1, false, nullptr); stream_->WriteOrBufferData(kData1, false, nullptr); stream_->WriteOrBufferData(kData1, true, nullptr); EXPECT_EQ(3u, QuicStreamPeer::SendBuffer(stream_).size()); EXPECT_TRUE(stream_->IsWaitingForAcks()); EXPECT_TRUE(session_->HasUnackedStreamData()); QuicByteCount newly_acked_length = 0; EXPECT_TRUE(stream_->OnStreamFrameAcked(0, 9, false, QuicTime::Delta::Zero(), QuicTime::Zero(), &newly_acked_length)); EXPECT_EQ(9u, newly_acked_length); EXPECT_EQ(2u, QuicStreamPeer::SendBuffer(stream_).size()); EXPECT_TRUE(stream_->OnStreamFrameAcked(5, 17, false, QuicTime::Delta::Zero(), QuicTime::Zero(), &newly_acked_length)); EXPECT_EQ(13u, newly_acked_length); EXPECT_EQ(1u, QuicStreamPeer::SendBuffer(stream_).size()); EXPECT_TRUE(stream_->OnStreamFrameAcked(18, 8, false, QuicTime::Delta::Zero(), QuicTime::Zero(), &newly_acked_length)); EXPECT_EQ(4u, newly_acked_length); EXPECT_EQ(1u, QuicStreamPeer::SendBuffer(stream_).size()); EXPECT_TRUE(stream_->IsWaitingForAcks()); EXPECT_TRUE(session_->HasUnackedStreamData()); EXPECT_TRUE(stream_->OnStreamFrameAcked(26, 1, false, QuicTime::Delta::Zero(), QuicTime::Zero(), &newly_acked_length)); EXPECT_EQ(1u, newly_acked_length); EXPECT_EQ(0u, QuicStreamPeer::SendBuffer(stream_).size()); EXPECT_TRUE(stream_->IsWaitingForAcks()); EXPECT_TRUE(session_->HasUnackedStreamData()); EXPECT_CALL(*stream_, OnWriteSideInDataRecvdState()).Times(1); EXPECT_TRUE(stream_->OnStreamFrameAcked(27, 0, true, QuicTime::Delta::Zero(), QuicTime::Zero(), &newly_acked_length)); EXPECT_EQ(0u, newly_acked_length); EXPECT_EQ(0u, QuicStreamPeer::SendBuffer(stream_).size()); EXPECT_FALSE(stream_->IsWaitingForAcks()); EXPECT_FALSE(session_->HasUnackedStreamData()); EXPECT_FALSE( stream_->OnStreamFrameAcked(10, 17, true, QuicTime::Delta::Zero(), QuicTime::Zero(), &newly_acked_length)); EXPECT_EQ(0u, newly_acked_length); EXPECT_EQ(0u, QuicStreamPeer::SendBuffer(stream_).size()); EXPECT_FALSE(stream_->IsWaitingForAcks()); EXPECT_FALSE(session_->HasUnackedStreamData()); } TEST_P(QuicStreamTest, OnStreamFrameLost) { Initialize(); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillOnce(Invoke(session_.get(), &MockQuicSession::ConsumeData)); stream_->WriteOrBufferData(kData1, false, nullptr); EXPECT_FALSE(stream_->HasBufferedData()); EXPECT_TRUE(stream_->IsStreamFrameOutstanding(0, 9, false)); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillOnce(Return(QuicConsumedData(0, false))); stream_->WriteOrBufferData(kData2, false, nullptr); stream_->WriteOrBufferData(kData2, false, nullptr); EXPECT_TRUE(stream_->HasBufferedData()); EXPECT_FALSE(stream_->HasPendingRetransmission()); stream_->OnStreamFrameLost(0, 9, false); EXPECT_TRUE(stream_->HasPendingRetransmission()); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillOnce(Invoke(session_.get(), &MockQuicSession::ConsumeData)); EXPECT_CALL(*stream_, OnCanWriteNewData()).Times(1); stream_->OnCanWrite(); EXPECT_FALSE(stream_->HasPendingRetransmission()); EXPECT_TRUE(stream_->HasBufferedData()); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillOnce(Invoke(session_.get(), &MockQuicSession::ConsumeData)); stream_->OnCanWrite(); EXPECT_FALSE(stream_->HasBufferedData()); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillOnce(Invoke(session_.get(), &MockQuicSession::ConsumeData)); stream_->WriteOrBufferData("", true, nullptr); stream_->OnStreamFrameLost(9, 18, false); stream_->OnStreamFrameLost(27, 0, true); EXPECT_TRUE(stream_->HasPendingRetransmission()); QuicByteCount newly_acked_length = 0; EXPECT_TRUE(stream_->OnStreamFrameAcked(9, 9, false, QuicTime::Delta::Zero(), QuicTime::Zero(), &newly_acked_length)); EXPECT_EQ(9u, newly_acked_length); EXPECT_FALSE(stream_->IsStreamFrameOutstanding(9, 3, false)); EXPECT_TRUE(stream_->HasPendingRetransmission()); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillOnce(InvokeWithoutArgs([this]() { return session_->ConsumeData(stream_->id(), 9u, 18u, FIN, NOT_RETRANSMISSION, std::nullopt); })); stream_->OnCanWrite(); EXPECT_FALSE(stream_->HasPendingRetransmission()); stream_->OnStreamFrameLost(9, 9, false); EXPECT_FALSE(stream_->HasPendingRetransmission()); EXPECT_TRUE(stream_->IsStreamFrameOutstanding(27, 0, true)); } TEST_P(QuicStreamTest, CannotBundleLostFin) { Initialize(); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly(Invoke(session_.get(), &MockQuicSession::ConsumeData)); stream_->WriteOrBufferData(kData1, false, nullptr); stream_->WriteOrBufferData(kData2, true, nullptr); stream_->OnStreamFrameLost(0, 9, false); stream_->OnStreamFrameLost(18, 0, true); InSequence s; EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillOnce(InvokeWithoutArgs([this]() { return session_->ConsumeData(stream_->id(), 9u, 0u, NO_FIN, NOT_RETRANSMISSION, std::nullopt); })); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillOnce(Return(QuicConsumedData(0, true))); stream_->OnCanWrite(); } TEST_P(QuicStreamTest, MarkConnectionLevelWriteBlockedOnWindowUpdateFrame) { Initialize(); QuicConfigPeer::SetReceivedInitialStreamFlowControlWindow(session_->config(), 100); QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesIncomingBidirectional( session_->config(), 100); auto stream = new TestStream(GetNthClientInitiatedBidirectionalStreamId( GetParam().transport_version, 2), session_.get(), BIDIRECTIONAL); session_->ActivateStream(absl::WrapUnique(stream)); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly(Invoke(session_.get(), &MockQuicSession::ConsumeData)); EXPECT_CALL(*session_, SendBlocked(_, _)).Times(1); std::string data(1024, '.'); stream->WriteOrBufferData(data, false, nullptr); EXPECT_FALSE(HasWriteBlockedStreams()); QuicWindowUpdateFrame window_update(kInvalidControlFrameId, stream_->id(), 1234); stream->OnWindowUpdateFrame(window_update); EXPECT_TRUE(HasWriteBlockedStreams()); EXPECT_TRUE(stream->HasBufferedData()); } TEST_P(QuicStreamTest, MarkConnectionLevelWriteBlockedOnWindowUpdateFrameWithNoBufferedData) { Initialize(); QuicConfigPeer::SetReceivedInitialStreamFlowControlWindow(session_->config(), 100); QuicConfigPeer::SetReceivedInitialMaxStreamDataBytesIncomingBidirectional( session_->config(), 100); auto stream = new TestStream(GetNthClientInitiatedBidirectionalStreamId( GetParam().transport_version, 2), session_.get(), BIDIRECTIONAL); session_->ActivateStream(absl::WrapUnique(stream)); std::string data(100, '.'); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .WillRepeatedly(Invoke(session_.get(), &MockQuicSession::ConsumeData)); EXPECT_CALL(*session_, SendBlocked(_, _)).Times(1); stream->WriteOrBufferData(data, false, nullptr); EXPECT_FALSE(HasWriteBlockedStreams()); QuicWindowUpdateFrame window_update(kInvalidControlFrameId, stream_->id(), 120); stream->OnWindowUpdateFrame(window_update); EXPECT_FALSE(stream->HasBufferedData()); EXPECT_TRUE(HasWriteBlockedStreams()); } TEST_P(QuicStreamTest, RetransmitStreamData) { Initialize(); InSequence s; EXPECT_CALL(*session_, WritevData(stream_->id(), _, _, _, _, _)) .Times(2) .WillRepeatedly(Invoke(session_.get(), &MockQuicSession::ConsumeData)); stream_->WriteOrBufferData(kData1, false, nullptr); stream_->WriteOrBufferData(kData1, true, nullptr); QuicByteCount newly_acked_length = 0; stream_->OnStreamFrameAcked(10, 3, false, QuicTime::Delta::Zero(), QuicTime::Zero(), &newly_acked_length); EXPECT_EQ(3u, newly_acked_length); EXPECT_CALL(*session_, WritevData(stream_->id(), 10, 0, NO_FIN, _, _)) .WillOnce(InvokeWithoutArgs([this]() { return session_->ConsumeData(stream_->id(), 8, 0u, NO_FIN, NOT_RETRANSMISSION, std::nullopt); })); EXPECT_FALSE(stream_->RetransmitStreamData(0, 18, true, PTO_RETRANSMISSION)); EXPECT_CALL(*session_, WritevData(stream_->id(), 10, 0, NO_FIN, _, _)) .WillOnce(Invoke(session_.get(), &MockQuicSession::ConsumeData)); EXPECT_CALL(*session_, WritevData(stream_->id(), 5, 13, FIN, _, _)) .WillOnce(Invoke(session_.get(), &MockQuicSession::ConsumeData)); EXPECT_TRUE(stream_->RetransmitStreamData(0, 18, true, PTO_RETRANSMISSION)); EXPECT_CALL(*session_, WritevData(stream_->id(), 8, 0, NO_FIN, _, _)) .WillOnce(Invoke(session_.get(), &MockQuicSession::ConsumeData)); EXPECT_CALL(*session_, WritevData(stream_->id(), 0, 18, FIN, _, _)) .WillOnce(Invoke(session_.get(), &MockQuicSession::ConsumeData)); EXPECT_TRUE(stream_->RetransmitStreamData(0, 8, true, PTO_RETRANSMISSION)); } TEST_P(QuicStreamTest, ResetStreamOnTtlExpiresRetransmitLostData) { Initialize(); EXPECT_CALL(*session_, WritevData(stream_->id(), 200, 0, FIN, _, _)) .WillOnce(Invoke(session_.get(), &MockQuicSession::ConsumeData)); std::string body(200, 'a'); stream_->WriteOrBufferData(body, true, nullptr); QuicTime::Delta ttl = QuicTime::Delta::FromSeconds(1); ASSERT_TRUE(stream_->MaybeSetTtl(ttl)); EXPECT_CALL(*session_, WritevData(stream_->id(), 100, 0, NO_FIN, _, _)) .WillOnce(Invoke(session_.get(), &MockQuicSession::ConsumeData)); EXPECT_TRUE(stream_->RetransmitStreamData(0, 100, false, PTO_RETRANSMISSION)); stream_->OnStreamFrameLost(100, 100, true); EXPECT_TRUE(stream_->HasPendingRetransmission()); connection_->AdvanceTime(QuicTime::Delta::FromSeconds(1)); if (session_->version().UsesHttp3()) { EXPECT_CALL(*session_, MaybeSendStopSendingFrame(_, QuicResetStreamError::FromInternal( QUIC_STREAM_TTL_EXPIRED))) .Times(1); } EXPECT_CALL( *session_, MaybeSendRstStreamFrame( _, QuicResetStreamError::FromInternal(QUIC_STREAM_TTL_EXPIRED), _)) .Times(1); stream_->OnCanWrite(); } TEST_P(QuicStreamTest, ResetStreamOnTtlExpiresEarlyRetransmitData) { Initialize(); EXPECT_CALL(*session_, WritevData(stream_->id(), 200, 0, FIN, _, _)) .WillOnce(Invoke(session_.get(), &MockQuicSession::ConsumeData)); std::string body(200, 'a'); stream_->WriteOrBufferData(body, true, nullptr); QuicTime::Delta ttl = QuicTime::Delta::FromSeconds(1); ASSERT_TRUE(stream_->MaybeSetTtl(ttl)); connection_->AdvanceTime(QuicTime::Delta::FromSeconds(1)); if (session_->version().UsesHttp3()) { EXPECT_CALL(*session_, MaybeSendStopSendingFrame(_, QuicResetStreamError::FromInternal( QUIC_STREAM_TTL_EXPIRED))) .Times(1); } EXPECT_CALL( *session_, MaybeSendRstStreamFrame( _, QuicResetStreamError::FromInternal(QUIC_STREAM_TTL_EXPIRED), _)) .Times(1); stream_->RetransmitStreamData(0, 100, false, PTO_RETRANSMISSION); } TEST_P(QuicStreamTest, OnStreamResetReadOrReadWrite) { Initialize(); EXPECT_FALSE(stream_->write_side_closed()); EXPECT_FALSE(QuicStreamPeer::read_side_closed(stream_)); QuicRstStreamFrame rst_frame(kInvalidControlFrameId, stream_->id(), QUIC_STREAM_CANCELLED, 1234); stream_->OnStreamReset(rst_frame); if (VersionHasIetfQuicFrames(connection_->transport_version())) { EXPECT_TRUE(QuicStreamPeer::read_side_closed(stream_)); EXPECT_FALSE(stream_->write_side_closed()); } else { EXPECT_TRUE(stream_->write_side_closed()); EXPECT_TRUE(QuicStreamPeer::read_side_closed(stream_)); } } TEST_P(QuicStreamTest, WindowUpdateForReadOnlyStream) { Initialize(); QuicStreamId stream_id = QuicUtils::GetFirstUnidirectionalStreamId( connection_->transport_version(), Perspective::IS_CLIENT); TestStream stream(stream_id, session_.get(), READ_UNIDIRECTIONAL); QuicWindowUpdateFrame window_update_frame(kInvalidControlFrameId, stream_id, 0); EXPECT_CALL( *connection_, CloseConnection( QUIC_WINDOW_UPDATE_RECEIVED_ON_READ_UNIDIRECTIONAL_STREAM, "WindowUpdateFrame received on READ_UNIDIRECTIONAL stream.", _)); stream.OnWindowUpdateFrame(window_update_frame); } TEST_P(QuicStreamTest, RstStreamFrameChangesCloseOffset) { Initialize(); QuicStreamFrame stream_frame(stream_->id(), true, 0, "abc"); EXPECT_CALL(*stream_, OnDataAvailable()); stream_->OnStreamFrame(stream_frame); QuicRstStreamFrame rst(kInvalidControlFrameId, stream_->id(), QUIC_STREAM_CANCELLED, 0u); EXPECT_CALL(*connection_, CloseConnection(QUIC_STREAM_MULTIPLE_OFFSET, _, _)); stream_->OnStreamReset(rst); } TEST_P(QuicStreamTest, EmptyStreamFrameWithNoFin) { Initialize(); QuicStreamFrame empty_stream_frame(stream_->id(), false, 0, ""); if (stream_->version().HasIetfQuicFrames()) { EXPECT_CALL(*connection_, CloseConnection(QUIC_EMPTY_STREAM_FRAME_NO_FIN, _, _)) .Times(0); } else { EXPECT_CALL(*connection_, CloseConnection(QUIC_EMPTY_STREAM_FRAME_NO_FIN, _, _)); } EXPECT_CALL(*stream_, OnDataAvailable()).Times(0); stream_->OnStreamFrame(empty_stream_frame); } TEST_P(QuicStreamTest, SendRstWithCustomIetfCode) { Initialize(); QuicResetStreamError error(QUIC_STREAM_CANCELLED, 0x1234abcd); EXPECT_CALL(*session_, MaybeSendRstStreamFrame(kTestStreamId, error, _)) .Times(1); stream_->ResetWithError(error); EXPECT_TRUE(rst_sent()); } TEST_P(QuicStreamTest, ResetWhenOffsetReached) { Initialize(); if (!VersionHasIetfQuicFrames(session_->transport_version())) { return; } QuicResetStreamAtFrame rst(0, stream_->id(), QUIC_STREAM_CANCELLED, 400, 100); stream_->OnResetStreamAtFrame(rst); char data[100]; EXPECT_CALL(*stream_, OnDataAvailable()).WillOnce([this]() { stream_->ConsumeData(99); }); stream_->OnStreamFrame( QuicStreamFrame(stream_->id(), false, 0, absl::string_view(data, 99))); EXPECT_FALSE(stream_->rst_received()); EXPECT_FALSE(stream_->read_side_closed()); EXPECT_CALL(*stream_, OnDataAvailable()).WillOnce([this]() { stream_->ConsumeData(1); }); stream_->OnStreamFrame(QuicStreamFrame(stream_->id(), false, 99, absl::string_view(data + 99, 1))); EXPECT_TRUE(stream_->rst_received()); EXPECT_TRUE(stream_->read_side_closed()); } TEST_P(QuicStreamTest, ResetWhenOffsetReachedOutOfOrder) { Initialize(); if (!VersionHasIetfQuicFrames(session_->transport_version())) { return; } QuicResetStreamAtFrame rst(0, stream_->id(), QUIC_STREAM_CANCELLED, 400, 100); stream_->OnResetStreamAtFrame(rst); char data[100]; stream_->OnStreamFrame(QuicStreamFrame(stream_->id(), false, 99, absl::string_view(data + 99, 1))); EXPECT_FALSE(stream_->rst_received()); EXPECT_FALSE(stream_->read_side_closed()); EXPECT_CALL(*stream_, OnDataAvailable()).WillOnce([this]() { stream_->ConsumeData(100); }); stream_->OnStreamFrame( QuicStreamFrame(stream_->id(), false, 0, absl::string_view(data, 99))); EXPECT_TRUE(stream_->rst_received()); EXPECT_TRUE(stream_->read_side_closed()); } TEST_P(QuicStreamTest, HigherReliableSizeIgnored) { Initialize(); if (!VersionHasIetfQuicFrames(session_->transport_version())) { return; } QuicResetStreamAtFrame rst(0, stream_->id(), QUIC_STREAM_CANCELLED, 400, 100); stream_->OnResetStreamAtFrame(rst); QuicResetStreamAtFrame rst2(0, stream_->id(), QUIC_STREAM_CANCELLED, 400, 200); stream_->OnResetStreamAtFrame(rst2); char data[100]; EXPECT_CALL(*stream_, OnDataAvailable()).WillOnce([this]() { stream_->ConsumeData(99); }); stream_->OnStreamFrame( QuicStreamFrame(stream_->id(), false, 0, absl::string_view(data, 99))); EXPECT_FALSE(stream_->rst_received()); EXPECT_FALSE(stream_->read_side_closed()); EXPECT_CALL(*stream_, OnDataAvailable()).WillOnce([this]() { stream_->ConsumeData(1); }); stream_->OnStreamFrame(QuicStreamFrame(stream_->id(), false, 99, absl::string_view(data + 99, 1))); EXPECT_TRUE(stream_->rst_received()); EXPECT_TRUE(stream_->read_side_closed()); } TEST_P(QuicStreamTest, InstantReset) { Initialize(); if (!VersionHasIetfQuicFrames(session_->transport_version())) { return; } char data[100]; EXPECT_CALL(*stream_, OnDataAvailable()).WillOnce([this]() { stream_->ConsumeData(100); }); stream_->OnStreamFrame( QuicStreamFrame(stream_->id(), false, 0, absl::string_view(data, 100))); QuicResetStreamAtFrame rst(0, stream_->id(), QUIC_STREAM_CANCELLED, 400, 100); EXPECT_FALSE(stream_->rst_received()); EXPECT_FALSE(stream_->read_side_closed()); stream_->OnResetStreamAtFrame(rst); EXPECT_TRUE(stream_->rst_received()); EXPECT_TRUE(stream_->read_side_closed()); } TEST_P(QuicStreamTest, ResetIgnoredDueToFin) { Initialize(); if (!VersionHasIetfQuicFrames(session_->transport_version())) { return; } char data[100]; EXPECT_CALL(*stream_, OnDataAvailable()).WillOnce([this]() { stream_->ConsumeData(98); }); stream_->OnStreamFrame( QuicStreamFrame(stream_->id(), false, 0, absl::string_view(data, 98))); QuicResetStreamAtFrame rst(0, stream_->id(), QUIC_STREAM_CANCELLED, 100, 99); stream_->OnResetStreamAtFrame(rst); EXPECT_FALSE(stream_->rst_received()); EXPECT_FALSE(stream_->read_side_closed()); EXPECT_CALL(*stream_, OnDataAvailable()).WillOnce([this]() { stream_->ConsumeData(2); stream_->OnFinRead(); }); stream_->OnStreamFrame(QuicStreamFrame(stream_->id(), true, 98, absl::string_view(data + 98, 2))); EXPECT_FALSE(stream_->rst_received()); EXPECT_TRUE(stream_->read_side_closed()); } TEST_P(QuicStreamTest, ReliableOffsetBeyondFin) { Initialize(); if (!VersionHasIetfQuicFrames(session_->transport_version())) { return; } char data[100]; stream_->OnStreamFrame(QuicStreamFrame(stream_->id(), true, 98, absl::string_view(data + 98, 2))); EXPECT_CALL(*connection_, CloseConnection(QUIC_STREAM_MULTIPLE_OFFSET, _, _)) .Times(1); QuicResetStreamAtFrame rst(0, stream_->id(), QUIC_STREAM_CANCELLED, 101, 101); stream_->OnResetStreamAtFrame(rst); } TEST_P(QuicStreamTest, FinBeforeReliableOffset) { Initialize(); if (!VersionHasIetfQuicFrames(session_->transport_version())) { return; } QuicResetStreamAtFrame rst(0, stream_->id(), QUIC_STREAM_CANCELLED, 101, 101); stream_->OnResetStreamAtFrame(rst); char data[100]; EXPECT_CALL(*connection_, CloseConnection(QUIC_STREAM_MULTIPLE_OFFSET, _, _)) .Times(1); stream_->OnStreamFrame( QuicStreamFrame(stream_->id(), true, 0, absl::string_view(data, 100))); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_stream.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_stream_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
96364946-0861-4cb2-be1c-71b60afa30b0
cpp
google/quiche
tls_chlo_extractor
quiche/quic/core/tls_chlo_extractor.cc
quiche/quic/core/tls_chlo_extractor_test.cc
#include "quiche/quic/core/tls_chlo_extractor.h" #include <cstdint> #include <cstring> #include <memory> #include <ostream> #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/frames/quic_crypto_frame.h" #include "quiche/quic/core/quic_data_reader.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_framer.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_bug_tracker.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 { namespace { bool HasExtension(const SSL_CLIENT_HELLO* client_hello, uint16_t extension) { const uint8_t* unused_extension_bytes; size_t unused_extension_len; return 1 == SSL_early_callback_ctx_extension_get(client_hello, extension, &unused_extension_bytes, &unused_extension_len); } std::vector<uint16_t> GetSupportedGroups(const SSL_CLIENT_HELLO* client_hello) { const uint8_t* extension_data; size_t extension_len; int rv = SSL_early_callback_ctx_extension_get( client_hello, TLSEXT_TYPE_supported_groups, &extension_data, &extension_len); if (rv != 1) { return {}; } QuicDataReader named_groups_reader( reinterpret_cast<const char*>(extension_data), extension_len); uint16_t named_groups_len; if (!named_groups_reader.ReadUInt16(&named_groups_len) || named_groups_len + sizeof(uint16_t) != extension_len) { QUIC_CODE_COUNT(quic_chlo_supported_groups_invalid_length); return {}; } std::vector<uint16_t> named_groups; while (!named_groups_reader.IsDoneReading()) { uint16_t named_group; if (!named_groups_reader.ReadUInt16(&named_group)) { QUIC_CODE_COUNT(quic_chlo_supported_groups_odd_length); QUIC_LOG_FIRST_N(WARNING, 10) << "Failed to read named groups"; break; } named_groups.push_back(named_group); } return named_groups; } std::vector<uint16_t> GetCertCompressionAlgos( const SSL_CLIENT_HELLO* client_hello) { const uint8_t* extension_data; size_t extension_len; int rv = SSL_early_callback_ctx_extension_get( client_hello, TLSEXT_TYPE_cert_compression, &extension_data, &extension_len); if (rv != 1) { return {}; } QuicDataReader cert_compression_algos_reader( reinterpret_cast<const char*>(extension_data), extension_len); uint8_t algos_len; if (!cert_compression_algos_reader.ReadUInt8(&algos_len) || algos_len == 0 || algos_len % sizeof(uint16_t) != 0 || algos_len + sizeof(uint8_t) != extension_len) { QUIC_CODE_COUNT(quic_chlo_cert_compression_algos_invalid_length); return {}; } size_t num_algos = algos_len / sizeof(uint16_t); std::vector<uint16_t> cert_compression_algos; cert_compression_algos.reserve(num_algos); for (size_t i = 0; i < num_algos; ++i) { uint16_t cert_compression_algo; if (!cert_compression_algos_reader.ReadUInt16(&cert_compression_algo)) { QUIC_CODE_COUNT(quic_chlo_fail_to_read_cert_compression_algo); return {}; } cert_compression_algos.push_back(cert_compression_algo); } return cert_compression_algos; } } TlsChloExtractor::TlsChloExtractor() : crypto_stream_sequencer_(this), state_(State::kInitial), parsed_crypto_frame_in_this_packet_(false) {} TlsChloExtractor::TlsChloExtractor(TlsChloExtractor&& other) : TlsChloExtractor() { *this = std::move(other); } TlsChloExtractor& TlsChloExtractor::operator=(TlsChloExtractor&& other) { framer_ = std::move(other.framer_); if (framer_) { framer_->set_visitor(this); } crypto_stream_sequencer_ = std::move(other.crypto_stream_sequencer_); crypto_stream_sequencer_.set_stream(this); ssl_ = std::move(other.ssl_); if (ssl_) { std::pair<SSL_CTX*, int> shared_handles = GetSharedSslHandles(); int ex_data_index = shared_handles.second; const int rv = SSL_set_ex_data(ssl_.get(), ex_data_index, this); QUICHE_CHECK_EQ(rv, 1) << "Internal allocation failure in SSL_set_ex_data"; } state_ = other.state_; error_details_ = std::move(other.error_details_); parsed_crypto_frame_in_this_packet_ = other.parsed_crypto_frame_in_this_packet_; supported_groups_ = std::move(other.supported_groups_); cert_compression_algos_ = std::move(other.cert_compression_algos_); alpns_ = std::move(other.alpns_); server_name_ = std::move(other.server_name_); client_hello_bytes_ = std::move(other.client_hello_bytes_); return *this; } void TlsChloExtractor::IngestPacket(const ParsedQuicVersion& version, const QuicReceivedPacket& packet) { if (state_ == State::kUnrecoverableFailure) { QUIC_DLOG(ERROR) << "Not ingesting packet after unrecoverable error"; return; } if (version == UnsupportedQuicVersion()) { QUIC_DLOG(ERROR) << "Not ingesting packet with unsupported version"; return; } if (version.handshake_protocol != PROTOCOL_TLS1_3) { QUIC_DLOG(ERROR) << "Not ingesting packet with non-TLS version " << version; return; } if (framer_) { if (!framer_->IsSupportedVersion(version)) { QUIC_DLOG(ERROR) << "Not ingesting packet with version mismatch, expected " << framer_->version() << ", got " << version; return; } } else { framer_ = std::make_unique<QuicFramer>( ParsedQuicVersionVector{version}, QuicTime::Zero(), Perspective::IS_SERVER, 0); framer_->set_visitor(this); } parsed_crypto_frame_in_this_packet_ = false; const bool parse_success = framer_->ProcessPacket(packet); if (state_ == State::kInitial && parsed_crypto_frame_in_this_packet_) { state_ = State::kParsedPartialChloFragment; } if (!parse_success) { QUIC_DLOG(ERROR) << "Failed to process packet"; return; } } bool TlsChloExtractor::OnUnauthenticatedPublicHeader( const QuicPacketHeader& header) { if (header.form != IETF_QUIC_LONG_HEADER_PACKET) { QUIC_DLOG(ERROR) << "Not parsing non-long-header packet " << header; return false; } if (header.long_packet_type != INITIAL) { QUIC_DLOG(ERROR) << "Not parsing non-initial packet " << header; return false; } if (GetQuicRestartFlag(quic_dispatcher_ack_buffered_initial_packets)) { if (framer_->GetDecrypter(ENCRYPTION_INITIAL) == nullptr) { framer_->SetInitialObfuscators(header.destination_connection_id); } } else { framer_->SetInitialObfuscators(header.destination_connection_id); } return true; } bool TlsChloExtractor::OnProtocolVersionMismatch(ParsedQuicVersion version) { QUIC_BUG(quic_bug_10855_1) << "Unexpected version mismatch, expected " << framer_->version() << ", got " << version; return false; } void TlsChloExtractor::OnUnrecoverableError(QuicErrorCode error, const std::string& details) { HandleUnrecoverableError(absl::StrCat( "Crypto stream error ", QuicErrorCodeToString(error), ": ", details)); } void TlsChloExtractor::OnUnrecoverableError( QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error, const std::string& details) { HandleUnrecoverableError(absl::StrCat( "Crypto stream error ", QuicErrorCodeToString(error), "(", QuicIetfTransportErrorCodeString(ietf_error), "): ", details)); } bool TlsChloExtractor::OnCryptoFrame(const QuicCryptoFrame& frame) { if (frame.level != ENCRYPTION_INITIAL) { QUIC_BUG(quic_bug_10855_2) << "Parsed bad-level CRYPTO frame " << frame; return false; } parsed_crypto_frame_in_this_packet_ = true; crypto_stream_sequencer_.OnCryptoFrame(frame); return true; } void TlsChloExtractor::OnDataAvailable() { SetupSslHandle(); struct iovec iov; while (crypto_stream_sequencer_.GetReadableRegion(&iov)) { const int rv = SSL_provide_quic_data( ssl_.get(), ssl_encryption_initial, reinterpret_cast<const uint8_t*>(iov.iov_base), iov.iov_len); if (rv != 1) { HandleUnrecoverableError("SSL_provide_quic_data failed"); return; } crypto_stream_sequencer_.MarkConsumed(iov.iov_len); } (void)SSL_do_handshake(ssl_.get()); } TlsChloExtractor* TlsChloExtractor::GetInstanceFromSSL(SSL* ssl) { std::pair<SSL_CTX*, int> shared_handles = GetSharedSslHandles(); int ex_data_index = shared_handles.second; return reinterpret_cast<TlsChloExtractor*>( SSL_get_ex_data(ssl, ex_data_index)); } int TlsChloExtractor::SetReadSecretCallback( SSL* ssl, enum ssl_encryption_level_t , const SSL_CIPHER* , const uint8_t* , size_t ) { GetInstanceFromSSL(ssl)->HandleUnexpectedCallback("SetReadSecretCallback"); return 0; } int TlsChloExtractor::SetWriteSecretCallback( SSL* ssl, enum ssl_encryption_level_t , const SSL_CIPHER* , const uint8_t* , size_t ) { GetInstanceFromSSL(ssl)->HandleUnexpectedCallback("SetWriteSecretCallback"); return 0; } int TlsChloExtractor::WriteMessageCallback( SSL* ssl, enum ssl_encryption_level_t , const uint8_t* , size_t ) { GetInstanceFromSSL(ssl)->HandleUnexpectedCallback("WriteMessageCallback"); return 0; } int TlsChloExtractor::FlushFlightCallback(SSL* ssl) { GetInstanceFromSSL(ssl)->HandleUnexpectedCallback("FlushFlightCallback"); return 0; } void TlsChloExtractor::HandleUnexpectedCallback( const std::string& callback_name) { std::string error_details = absl::StrCat("Unexpected callback ", callback_name); QUIC_BUG(quic_bug_10855_3) << error_details; HandleUnrecoverableError(error_details); } int TlsChloExtractor::SendAlertCallback(SSL* ssl, enum ssl_encryption_level_t , uint8_t desc) { GetInstanceFromSSL(ssl)->SendAlert(desc); return 0; } void TlsChloExtractor::SendAlert(uint8_t tls_alert_value) { if (tls_alert_value == SSL3_AD_HANDSHAKE_FAILURE && HasParsedFullChlo()) { return; } HandleUnrecoverableError(absl::StrCat( "BoringSSL attempted to send alert ", static_cast<int>(tls_alert_value), " ", SSL_alert_desc_string_long(tls_alert_value))); if (state_ == State::kUnrecoverableFailure) { tls_alert_ = tls_alert_value; } } enum ssl_select_cert_result_t TlsChloExtractor::SelectCertCallback( const SSL_CLIENT_HELLO* client_hello) { GetInstanceFromSSL(client_hello->ssl)->HandleParsedChlo(client_hello); return ssl_select_cert_error; } void TlsChloExtractor::HandleParsedChlo(const SSL_CLIENT_HELLO* client_hello) { const char* server_name = SSL_get_servername(client_hello->ssl, TLSEXT_NAMETYPE_host_name); if (server_name) { server_name_ = std::string(server_name); } resumption_attempted_ = HasExtension(client_hello, TLSEXT_TYPE_pre_shared_key); early_data_attempted_ = HasExtension(client_hello, TLSEXT_TYPE_early_data); QUICHE_DCHECK(client_hello_bytes_.empty()); client_hello_bytes_.assign( client_hello->client_hello, client_hello->client_hello + client_hello->client_hello_len); const uint8_t* alpn_data; size_t alpn_len; int rv = SSL_early_callback_ctx_extension_get( client_hello, TLSEXT_TYPE_application_layer_protocol_negotiation, &alpn_data, &alpn_len); if (rv == 1) { QuicDataReader alpns_reader(reinterpret_cast<const char*>(alpn_data), alpn_len); absl::string_view alpns_payload; if (!alpns_reader.ReadStringPiece16(&alpns_payload)) { QUIC_CODE_COUNT_N(quic_chlo_alpns_invalid, 1, 2); HandleUnrecoverableError("Failed to read alpns_payload"); return; } QuicDataReader alpns_payload_reader(alpns_payload); while (!alpns_payload_reader.IsDoneReading()) { absl::string_view alpn_payload; if (!alpns_payload_reader.ReadStringPiece8(&alpn_payload)) { QUIC_CODE_COUNT_N(quic_chlo_alpns_invalid, 2, 2); HandleUnrecoverableError("Failed to read alpn_payload"); return; } alpns_.emplace_back(std::string(alpn_payload)); } } supported_groups_ = GetSupportedGroups(client_hello); if (GetQuicReloadableFlag(quic_parse_cert_compression_algos_from_chlo)) { cert_compression_algos_ = GetCertCompressionAlgos(client_hello); if (cert_compression_algos_.empty()) { QUIC_RELOADABLE_FLAG_COUNT_N(quic_parse_cert_compression_algos_from_chlo, 1, 2); } else { QUIC_RELOADABLE_FLAG_COUNT_N(quic_parse_cert_compression_algos_from_chlo, 2, 2); } } if (state_ == State::kInitial) { state_ = State::kParsedFullSinglePacketChlo; } else if (state_ == State::kParsedPartialChloFragment) { state_ = State::kParsedFullMultiPacketChlo; } else { QUIC_BUG(quic_bug_10855_4) << "Unexpected state on successful parse " << StateToString(state_); } } std::pair<SSL_CTX*, int> TlsChloExtractor::GetSharedSslHandles() { static std::pair<SSL_CTX*, int>* shared_handles = []() { CRYPTO_library_init(); SSL_CTX* ssl_ctx = SSL_CTX_new(TLS_with_buffers_method()); SSL_CTX_set_min_proto_version(ssl_ctx, TLS1_3_VERSION); SSL_CTX_set_max_proto_version(ssl_ctx, TLS1_3_VERSION); static const SSL_QUIC_METHOD kQuicCallbacks{ TlsChloExtractor::SetReadSecretCallback, TlsChloExtractor::SetWriteSecretCallback, TlsChloExtractor::WriteMessageCallback, TlsChloExtractor::FlushFlightCallback, TlsChloExtractor::SendAlertCallback}; SSL_CTX_set_quic_method(ssl_ctx, &kQuicCallbacks); SSL_CTX_set_select_certificate_cb(ssl_ctx, TlsChloExtractor::SelectCertCallback); int ex_data_index = SSL_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr); return new std::pair<SSL_CTX*, int>(ssl_ctx, ex_data_index); }(); return *shared_handles; } void TlsChloExtractor::SetupSslHandle() { if (ssl_) { return; } std::pair<SSL_CTX*, int> shared_handles = GetSharedSslHandles(); SSL_CTX* ssl_ctx = shared_handles.first; int ex_data_index = shared_handles.second; ssl_ = bssl::UniquePtr<SSL>(SSL_new(ssl_ctx)); const int rv = SSL_set_ex_data(ssl_.get(), ex_data_index, this); QUICHE_CHECK_EQ(rv, 1) << "Internal allocation failure in SSL_set_ex_data"; SSL_set_accept_state(ssl_.get()); int use_legacy_extension = 0; if (framer_->version().UsesLegacyTlsExtension()) { use_legacy_extension = 1; } SSL_set_quic_use_legacy_codepoint(ssl_.get(), use_legacy_extension); } void TlsChloExtractor::HandleUnrecoverableError( const std::string& error_details) { if (HasParsedFullChlo()) { QUIC_DLOG(ERROR) << "Ignoring error: " << error_details; return; } QUIC_DLOG(ERROR) << "Handling error: " << error_details; state_ = State::kUnrecoverableFailure; if (error_details_.empty()) { error_details_ = error_details; } else { error_details_ = absl::StrCat(error_details_, "; ", error_details); } } std::string TlsChloExtractor::StateToString(State state) { switch (state) { case State::kInitial: return "Initial"; case State::kParsedFullSinglePacketChlo: return "ParsedFullSinglePacketChlo"; case State::kParsedFullMultiPacketChlo: return "ParsedFullMultiPacketChlo"; case State::kParsedPartialChloFragment: return "ParsedPartialChloFragment"; case State::kUnrecoverableFailure: return "UnrecoverableFailure"; } return absl::StrCat("Unknown(", static_cast<int>(state), ")"); } std::ostream& operator<<(std::ostream& os, const TlsChloExtractor::State& state) { os << TlsChloExtractor::StateToString(state); return os; } }
#include "quiche/quic/core/tls_chlo_extractor.h" #include <memory> #include <optional> #include <string> #include <utility> #include <vector> #include "openssl/ssl.h" #include "quiche/quic/core/http/quic_spdy_client_session.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_versions.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/first_flight.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simple_session_cache.h" #include "quiche/common/print_elements.h" namespace quic { namespace test { namespace { static int DummyCompressFunc(SSL* , CBB* , const uint8_t* , size_t ) { return 1; } static int DummyDecompressFunc(SSL* , CRYPTO_BUFFER** , size_t , const uint8_t* , size_t ) { return 1; } using testing::_; using testing::AnyNumber; class TlsChloExtractorTest : public QuicTestWithParam<ParsedQuicVersion> { protected: TlsChloExtractorTest() : version_(GetParam()), server_id_(TestServerId()) {} void Initialize() { tls_chlo_extractor_ = std::make_unique<TlsChloExtractor>(); AnnotatedPackets packets = GetAnnotatedFirstFlightOfPackets(version_, config_); packets_ = std::move(packets.packets); crypto_stream_size_ = packets.crypto_stream_size; QUIC_DLOG(INFO) << "Initialized with " << packets_.size() << " packets with crypto_stream_size:" << crypto_stream_size_; } void Initialize(std::unique_ptr<QuicCryptoClientConfig> crypto_config) { tls_chlo_extractor_ = std::make_unique<TlsChloExtractor>(); AnnotatedPackets packets = GetAnnotatedFirstFlightOfPackets( version_, config_, TestConnectionId(), EmptyQuicConnectionId(), std::move(crypto_config)); packets_ = std::move(packets.packets); crypto_stream_size_ = packets.crypto_stream_size; QUIC_DLOG(INFO) << "Initialized with " << packets_.size() << " packets with crypto_stream_size:" << crypto_stream_size_; } void PerformFullHandshake(QuicCryptoClientConfig* crypto_config) const { ASSERT_NE(crypto_config->session_cache(), nullptr); MockQuicConnectionHelper client_helper, server_helper; MockAlarmFactory alarm_factory; ParsedQuicVersionVector supported_versions = {version_}; PacketSavingConnection* client_connection = new PacketSavingConnection(&client_helper, &alarm_factory, Perspective::IS_CLIENT, supported_versions); client_connection->AdvanceTime(QuicTime::Delta::FromSeconds(1)); QuicSpdyClientSession client_session(config_, supported_versions, client_connection, server_id_, crypto_config); client_session.Initialize(); std::unique_ptr<QuicCryptoServerConfig> server_crypto_config = crypto_test_utils::CryptoServerConfigForTesting(); QuicConfig server_config; EXPECT_CALL(*client_connection, SendCryptoData(_, _, _)).Times(AnyNumber()); client_session.GetMutableCryptoStream()->CryptoConnect(); crypto_test_utils::HandshakeWithFakeServer( &server_config, server_crypto_config.get(), &server_helper, &alarm_factory, client_connection, client_session.GetMutableCryptoStream(), AlpnForVersion(client_connection->version())); SettingsFrame server_settings; server_settings.values[SETTINGS_QPACK_MAX_TABLE_CAPACITY] = kDefaultQpackMaxDynamicTableCapacity; std::string settings_frame = HttpEncoder::SerializeSettingsFrame(server_settings); client_session.GetMutableCryptoStream() ->SetServerApplicationStateForResumption( std::make_unique<ApplicationState>( settings_frame.data(), settings_frame.data() + settings_frame.length())); } void IngestPackets() { for (const std::unique_ptr<QuicReceivedPacket>& packet : packets_) { ReceivedPacketInfo packet_info( QuicSocketAddress(TestPeerIPAddress(), kTestPort), QuicSocketAddress(TestPeerIPAddress(), kTestPort), *packet); std::string detailed_error; std::optional<absl::string_view> retry_token; const QuicErrorCode error = QuicFramer::ParsePublicHeaderDispatcher( *packet, 0, &packet_info.form, &packet_info.long_packet_type, &packet_info.version_flag, &packet_info.use_length_prefix, &packet_info.version_label, &packet_info.version, &packet_info.destination_connection_id, &packet_info.source_connection_id, &retry_token, &detailed_error); ASSERT_THAT(error, IsQuicNoError()) << detailed_error; tls_chlo_extractor_->IngestPacket(packet_info.version, packet_info.packet); } packets_.clear(); } void ValidateChloDetails(const TlsChloExtractor* extractor = nullptr) const { if (extractor == nullptr) { extractor = tls_chlo_extractor_.get(); } EXPECT_TRUE(extractor->HasParsedFullChlo()); std::vector<std::string> alpns = extractor->alpns(); ASSERT_EQ(alpns.size(), 1u); EXPECT_EQ(alpns[0], AlpnForVersion(version_)); EXPECT_EQ(extractor->server_name(), TestHostname()); EXPECT_EQ(extractor->client_hello_bytes().size(), crypto_stream_size_ - 4); } void IncreaseSizeOfChlo() { constexpr auto kCustomParameterId = static_cast<TransportParameters::TransportParameterId>(0xff33); std::string kCustomParameterValue(2000, '-'); config_.custom_transport_parameters_to_send()[kCustomParameterId] = kCustomParameterValue; } ParsedQuicVersion version_; QuicServerId server_id_; std::unique_ptr<TlsChloExtractor> tls_chlo_extractor_; QuicConfig config_; std::vector<std::unique_ptr<QuicReceivedPacket>> packets_; uint64_t crypto_stream_size_; }; INSTANTIATE_TEST_SUITE_P(TlsChloExtractorTests, TlsChloExtractorTest, ::testing::ValuesIn(AllSupportedVersionsWithTls()), ::testing::PrintToStringParamName()); TEST_P(TlsChloExtractorTest, Simple) { Initialize(); EXPECT_EQ(packets_.size(), 1u); IngestPackets(); ValidateChloDetails(); EXPECT_EQ(tls_chlo_extractor_->state(), TlsChloExtractor::State::kParsedFullSinglePacketChlo); EXPECT_FALSE(tls_chlo_extractor_->resumption_attempted()); EXPECT_FALSE(tls_chlo_extractor_->early_data_attempted()); } TEST_P(TlsChloExtractorTest, TlsExtensionInfo_ResumptionOnly) { auto crypto_client_config = std::make_unique<QuicCryptoClientConfig>( crypto_test_utils::ProofVerifierForTesting(), std::make_unique<SimpleSessionCache>()); PerformFullHandshake(crypto_client_config.get()); SSL_CTX_set_early_data_enabled(crypto_client_config->ssl_ctx(), 0); Initialize(std::move(crypto_client_config)); EXPECT_GE(packets_.size(), 1u); IngestPackets(); ValidateChloDetails(); EXPECT_EQ(tls_chlo_extractor_->state(), TlsChloExtractor::State::kParsedFullSinglePacketChlo); EXPECT_TRUE(tls_chlo_extractor_->resumption_attempted()); EXPECT_FALSE(tls_chlo_extractor_->early_data_attempted()); } TEST_P(TlsChloExtractorTest, TlsExtensionInfo_ZeroRtt) { auto crypto_client_config = std::make_unique<QuicCryptoClientConfig>( crypto_test_utils::ProofVerifierForTesting(), std::make_unique<SimpleSessionCache>()); PerformFullHandshake(crypto_client_config.get()); IncreaseSizeOfChlo(); Initialize(std::move(crypto_client_config)); EXPECT_GE(packets_.size(), 1u); IngestPackets(); ValidateChloDetails(); EXPECT_EQ(tls_chlo_extractor_->state(), TlsChloExtractor::State::kParsedFullMultiPacketChlo); EXPECT_TRUE(tls_chlo_extractor_->resumption_attempted()); EXPECT_TRUE(tls_chlo_extractor_->early_data_attempted()); } TEST_P(TlsChloExtractorTest, TlsExtensionInfo_SupportedGroups) { const std::vector<std::vector<uint16_t>> preferred_groups_to_test = { {SSL_GROUP_X25519}, {SSL_GROUP_X25519_KYBER768_DRAFT00, SSL_GROUP_X25519}, }; for (const std::vector<uint16_t>& preferred_groups : preferred_groups_to_test) { auto crypto_client_config = std::make_unique<QuicCryptoClientConfig>( crypto_test_utils::ProofVerifierForTesting()); crypto_client_config->set_preferred_groups(preferred_groups); Initialize(std::move(crypto_client_config)); IngestPackets(); ValidateChloDetails(); EXPECT_EQ(tls_chlo_extractor_->supported_groups(), preferred_groups); } } TEST_P(TlsChloExtractorTest, TlsExtensionInfo_CertCompressionAlgos) { const std::vector<std::vector<uint16_t>> supported_groups_to_test = { {}, {1}, {1, 2}, {1, 2, 3}, {1, 2, 3, 65535}, }; for (const std::vector<uint16_t>& supported_cert_compression_algos : supported_groups_to_test) { auto crypto_client_config = std::make_unique<QuicCryptoClientConfig>( crypto_test_utils::ProofVerifierForTesting()); for (uint16_t cert_compression_algo : supported_cert_compression_algos) { ASSERT_TRUE(SSL_CTX_add_cert_compression_alg( crypto_client_config->ssl_ctx(), cert_compression_algo, DummyCompressFunc, DummyDecompressFunc)); } Initialize(std::move(crypto_client_config)); IngestPackets(); ValidateChloDetails(); if (GetQuicReloadableFlag(quic_parse_cert_compression_algos_from_chlo)) { EXPECT_EQ(tls_chlo_extractor_->cert_compression_algos(), supported_cert_compression_algos) << quiche::PrintElements( tls_chlo_extractor_->cert_compression_algos()); } else { EXPECT_TRUE(tls_chlo_extractor_->cert_compression_algos().empty()); } } } TEST_P(TlsChloExtractorTest, MultiPacket) { IncreaseSizeOfChlo(); Initialize(); EXPECT_EQ(packets_.size(), 2u); IngestPackets(); ValidateChloDetails(); EXPECT_EQ(tls_chlo_extractor_->state(), TlsChloExtractor::State::kParsedFullMultiPacketChlo); } TEST_P(TlsChloExtractorTest, MultiPacketReordered) { IncreaseSizeOfChlo(); Initialize(); ASSERT_EQ(packets_.size(), 2u); std::swap(packets_[0], packets_[1]); IngestPackets(); ValidateChloDetails(); EXPECT_EQ(tls_chlo_extractor_->state(), TlsChloExtractor::State::kParsedFullMultiPacketChlo); } TEST_P(TlsChloExtractorTest, MoveAssignment) { Initialize(); EXPECT_EQ(packets_.size(), 1u); TlsChloExtractor other_extractor; *tls_chlo_extractor_ = std::move(other_extractor); IngestPackets(); ValidateChloDetails(); EXPECT_EQ(tls_chlo_extractor_->state(), TlsChloExtractor::State::kParsedFullSinglePacketChlo); } TEST_P(TlsChloExtractorTest, MoveAssignmentAfterExtraction) { Initialize(); EXPECT_EQ(packets_.size(), 1u); IngestPackets(); ValidateChloDetails(); EXPECT_EQ(tls_chlo_extractor_->state(), TlsChloExtractor::State::kParsedFullSinglePacketChlo); TlsChloExtractor other_extractor = std::move(*tls_chlo_extractor_); EXPECT_EQ(other_extractor.state(), TlsChloExtractor::State::kParsedFullSinglePacketChlo); ValidateChloDetails(&other_extractor); } TEST_P(TlsChloExtractorTest, MoveAssignmentBetweenPackets) { IncreaseSizeOfChlo(); Initialize(); ASSERT_EQ(packets_.size(), 2u); TlsChloExtractor other_extractor; ReceivedPacketInfo packet_info( QuicSocketAddress(TestPeerIPAddress(), kTestPort), QuicSocketAddress(TestPeerIPAddress(), kTestPort), *packets_[0]); std::string detailed_error; std::optional<absl::string_view> retry_token; const QuicErrorCode error = QuicFramer::ParsePublicHeaderDispatcher( *packets_[0], 0, &packet_info.form, &packet_info.long_packet_type, &packet_info.version_flag, &packet_info.use_length_prefix, &packet_info.version_label, &packet_info.version, &packet_info.destination_connection_id, &packet_info.source_connection_id, &retry_token, &detailed_error); ASSERT_THAT(error, IsQuicNoError()) << detailed_error; other_extractor.IngestPacket(packet_info.version, packet_info.packet); packets_.erase(packets_.begin()); EXPECT_EQ(packets_.size(), 1u); *tls_chlo_extractor_ = std::move(other_extractor); IngestPackets(); ValidateChloDetails(); EXPECT_EQ(tls_chlo_extractor_->state(), TlsChloExtractor::State::kParsedFullMultiPacketChlo); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/tls_chlo_extractor.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/tls_chlo_extractor_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
63535286-e4a6-4b54-9d25-9e013a5d5c38
cpp
google/quiche
quic_packet_creator
quiche/quic/core/quic_packet_creator.cc
quiche/quic/core/quic_packet_creator_test.cc
#include "quiche/quic/core/quic_packet_creator.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <limits> #include <memory> #include <optional> #include <string> #include <utility> #include "absl/base/macros.h" #include "absl/base/optimization.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/frames/quic_frame.h" #include "quiche/quic/core/frames/quic_padding_frame.h" #include "quiche/quic/core/frames/quic_path_challenge_frame.h" #include "quiche/quic/core/frames/quic_stream_frame.h" #include "quiche/quic/core/quic_chaos_protector.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_error_codes.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_server_stats.h" #include "quiche/common/print_elements.h" namespace quic { namespace { QuicLongHeaderType EncryptionlevelToLongHeaderType(EncryptionLevel level) { switch (level) { case ENCRYPTION_INITIAL: return INITIAL; case ENCRYPTION_HANDSHAKE: return HANDSHAKE; case ENCRYPTION_ZERO_RTT: return ZERO_RTT_PROTECTED; case ENCRYPTION_FORWARD_SECURE: QUIC_BUG(quic_bug_12398_1) << "Try to derive long header type for packet with encryption level: " << level; return INVALID_PACKET_TYPE; default: QUIC_BUG(quic_bug_10752_1) << level; return INVALID_PACKET_TYPE; } } void LogCoalesceStreamFrameStatus(bool success) { QUIC_HISTOGRAM_BOOL("QuicSession.CoalesceStreamFrameStatus", success, "Success rate of coalesing stream frames attempt."); } class ScopedPacketContextSwitcher { public: ScopedPacketContextSwitcher(QuicPacketNumber packet_number, QuicPacketNumberLength packet_number_length, EncryptionLevel encryption_level, SerializedPacket* packet) : saved_packet_number_(packet->packet_number), saved_packet_number_length_(packet->packet_number_length), saved_encryption_level_(packet->encryption_level), packet_(packet) { packet_->packet_number = packet_number, packet_->packet_number_length = packet_number_length; packet_->encryption_level = encryption_level; } ~ScopedPacketContextSwitcher() { packet_->packet_number = saved_packet_number_; packet_->packet_number_length = saved_packet_number_length_; packet_->encryption_level = saved_encryption_level_; } private: const QuicPacketNumber saved_packet_number_; const QuicPacketNumberLength saved_packet_number_length_; const EncryptionLevel saved_encryption_level_; SerializedPacket* packet_; }; } #define ENDPOINT \ (framer_->perspective() == Perspective::IS_SERVER ? "Server: " : "Client: ") QuicPacketCreator::QuicPacketCreator(QuicConnectionId server_connection_id, QuicFramer* framer, DelegateInterface* delegate) : QuicPacketCreator(server_connection_id, framer, QuicRandom::GetInstance(), delegate) {} QuicPacketCreator::QuicPacketCreator(QuicConnectionId server_connection_id, QuicFramer* framer, QuicRandom* random, DelegateInterface* delegate) : delegate_(delegate), debug_delegate_(nullptr), framer_(framer), random_(random), have_diversification_nonce_(false), max_packet_length_(0), next_max_packet_length_(0), server_connection_id_included_(CONNECTION_ID_PRESENT), packet_size_(0), server_connection_id_(server_connection_id), client_connection_id_(EmptyQuicConnectionId()), packet_(QuicPacketNumber(), PACKET_1BYTE_PACKET_NUMBER, nullptr, 0, false, false), pending_padding_bytes_(0), needs_full_padding_(false), next_transmission_type_(NOT_RETRANSMISSION), flusher_attached_(false), fully_pad_crypto_handshake_packets_(true), latched_hard_max_packet_length_(0), max_datagram_frame_size_(0) { SetMaxPacketLength(kDefaultMaxPacketSize); if (!framer_->version().UsesTls()) { SetMaxDatagramFrameSize(kMaxAcceptedDatagramFrameSize); } } QuicPacketCreator::~QuicPacketCreator() { DeleteFrames(&packet_.retransmittable_frames); } void QuicPacketCreator::SetEncrypter(EncryptionLevel level, std::unique_ptr<QuicEncrypter> encrypter) { framer_->SetEncrypter(level, std::move(encrypter)); max_plaintext_size_ = framer_->GetMaxPlaintextSize(max_packet_length_); } bool QuicPacketCreator::CanSetMaxPacketLength() const { return queued_frames_.empty(); } void QuicPacketCreator::SetMaxPacketLength(QuicByteCount length) { if (!CanSetMaxPacketLength()) { next_max_packet_length_ = length; return; } if (length == max_packet_length_) { return; } QUIC_DVLOG(1) << ENDPOINT << "Updating packet creator max packet length from " << max_packet_length_ << " to " << length; max_packet_length_ = length; max_plaintext_size_ = framer_->GetMaxPlaintextSize(max_packet_length_); QUIC_BUG_IF( quic_bug_12398_2, max_plaintext_size_ - PacketHeaderSize() < MinPlaintextPacketSize(framer_->version(), GetPacketNumberLength())) << ENDPOINT << "Attempted to set max packet length too small"; } void QuicPacketCreator::SetMaxDatagramFrameSize( QuicByteCount max_datagram_frame_size) { constexpr QuicByteCount upper_bound = std::min<QuicByteCount>(std::numeric_limits<QuicPacketLength>::max(), std::numeric_limits<size_t>::max()); if (max_datagram_frame_size > upper_bound) { max_datagram_frame_size = upper_bound; } max_datagram_frame_size_ = max_datagram_frame_size; } void QuicPacketCreator::SetSoftMaxPacketLength(QuicByteCount length) { QUICHE_DCHECK(CanSetMaxPacketLength()) << ENDPOINT; if (length > max_packet_length_) { QUIC_BUG(quic_bug_10752_2) << ENDPOINT << "Try to increase max_packet_length_ in " "SetSoftMaxPacketLength, use SetMaxPacketLength instead."; return; } if (framer_->GetMaxPlaintextSize(length) < PacketHeaderSize() + MinPlaintextPacketSize(framer_->version(), GetPacketNumberLength())) { QUIC_DLOG(INFO) << ENDPOINT << length << " is too small to fit packet header"; RemoveSoftMaxPacketLength(); return; } QUIC_DVLOG(1) << ENDPOINT << "Setting soft max packet length to: " << length; latched_hard_max_packet_length_ = max_packet_length_; max_packet_length_ = length; max_plaintext_size_ = framer_->GetMaxPlaintextSize(length); } void QuicPacketCreator::SetDiversificationNonce( const DiversificationNonce& nonce) { QUICHE_DCHECK(!have_diversification_nonce_) << ENDPOINT; have_diversification_nonce_ = true; diversification_nonce_ = nonce; } void QuicPacketCreator::UpdatePacketNumberLength( QuicPacketNumber least_packet_awaited_by_peer, QuicPacketCount max_packets_in_flight) { if (!queued_frames_.empty()) { QUIC_BUG(quic_bug_10752_3) << ENDPOINT << "Called UpdatePacketNumberLength with " << queued_frames_.size() << " queued_frames. First frame type:" << queued_frames_.front().type << " last frame type:" << queued_frames_.back().type; return; } const QuicPacketNumber next_packet_number = NextSendingPacketNumber(); QUICHE_DCHECK_LE(least_packet_awaited_by_peer, next_packet_number) << ENDPOINT; const uint64_t current_delta = next_packet_number - least_packet_awaited_by_peer; const uint64_t delta = std::max(current_delta, max_packets_in_flight); const QuicPacketNumberLength packet_number_length = QuicFramer::GetMinPacketNumberLength(QuicPacketNumber(delta * 4)); if (packet_.packet_number_length == packet_number_length) { return; } QUIC_DVLOG(1) << ENDPOINT << "Updating packet number length from " << static_cast<int>(packet_.packet_number_length) << " to " << static_cast<int>(packet_number_length) << ", least_packet_awaited_by_peer: " << least_packet_awaited_by_peer << " max_packets_in_flight: " << max_packets_in_flight << " next_packet_number: " << next_packet_number; packet_.packet_number_length = packet_number_length; } void QuicPacketCreator::SkipNPacketNumbers( QuicPacketCount count, QuicPacketNumber least_packet_awaited_by_peer, QuicPacketCount max_packets_in_flight) { if (!queued_frames_.empty()) { QUIC_BUG(quic_bug_10752_4) << ENDPOINT << "Called SkipNPacketNumbers with " << queued_frames_.size() << " queued_frames. First frame type:" << queued_frames_.front().type << " last frame type:" << queued_frames_.back().type; return; } if (packet_.packet_number > packet_.packet_number + count) { QUIC_LOG(WARNING) << ENDPOINT << "Skipping " << count << " packet numbers causes packet number wrapping " "around, least_packet_awaited_by_peer: " << least_packet_awaited_by_peer << " packet_number:" << packet_.packet_number; return; } packet_.packet_number += count; UpdatePacketNumberLength(least_packet_awaited_by_peer, max_packets_in_flight); } bool QuicPacketCreator::ConsumeCryptoDataToFillCurrentPacket( EncryptionLevel level, size_t write_length, QuicStreamOffset offset, bool needs_full_padding, TransmissionType transmission_type, QuicFrame* frame) { QUIC_DVLOG(2) << ENDPOINT << "ConsumeCryptoDataToFillCurrentPacket " << level << " write_length " << write_length << " offset " << offset << (needs_full_padding ? " needs_full_padding" : "") << " " << transmission_type; if (!CreateCryptoFrame(level, write_length, offset, frame)) { return false; } if (needs_full_padding) { needs_full_padding_ = true; } return AddFrame(*frame, transmission_type); } bool QuicPacketCreator::ConsumeDataToFillCurrentPacket( QuicStreamId id, size_t data_size, QuicStreamOffset offset, bool fin, bool needs_full_padding, TransmissionType transmission_type, QuicFrame* frame) { if (!HasRoomForStreamFrame(id, offset, data_size)) { return false; } CreateStreamFrame(id, data_size, offset, fin, frame); if (GetQuicFlag(quic_enforce_single_packet_chlo) && StreamFrameIsClientHello(frame->stream_frame) && frame->stream_frame.data_length < data_size) { const std::string error_details = "Client hello won't fit in a single packet."; QUIC_BUG(quic_bug_10752_5) << ENDPOINT << error_details << " Constructed stream frame length: " << frame->stream_frame.data_length << " CHLO length: " << data_size; delegate_->OnUnrecoverableError(QUIC_CRYPTO_CHLO_TOO_LARGE, error_details); return false; } if (!AddFrame(*frame, transmission_type)) { return false; } if (needs_full_padding) { needs_full_padding_ = true; } return true; } bool QuicPacketCreator::HasRoomForStreamFrame(QuicStreamId id, QuicStreamOffset offset, size_t data_size) { const size_t min_stream_frame_size = QuicFramer::GetMinStreamFrameSize( framer_->transport_version(), id, offset, true, data_size); if (BytesFree() > min_stream_frame_size) { return true; } if (!RemoveSoftMaxPacketLength()) { return false; } return BytesFree() > min_stream_frame_size; } bool QuicPacketCreator::HasRoomForMessageFrame(QuicByteCount length) { const size_t message_frame_size = QuicFramer::GetMessageFrameSize(true, length); if (static_cast<QuicByteCount>(message_frame_size) > max_datagram_frame_size_) { return false; } if (BytesFree() >= message_frame_size) { return true; } if (!RemoveSoftMaxPacketLength()) { return false; } return BytesFree() >= message_frame_size; } size_t QuicPacketCreator::StreamFramePacketOverhead( 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, quiche::QuicheVariableLengthIntegerLength length_length, QuicStreamOffset offset) { return GetPacketHeaderSize(version, destination_connection_id_length, source_connection_id_length, include_version, include_diversification_nonce, packet_number_length, retry_token_length_length, 0, length_length) + QuicFramer::GetMinStreamFrameSize(version, 1u, offset, true, kMaxOutgoingPacketSize ); } void QuicPacketCreator::CreateStreamFrame(QuicStreamId id, size_t data_size, QuicStreamOffset offset, bool fin, QuicFrame* frame) { QUICHE_DCHECK( max_packet_length_ > StreamFramePacketOverhead( framer_->transport_version(), GetDestinationConnectionIdLength(), GetSourceConnectionIdLength(), kIncludeVersion, IncludeNonceInPublicHeader(), PACKET_6BYTE_PACKET_NUMBER, GetRetryTokenLengthLength(), GetLengthLength(), offset) || latched_hard_max_packet_length_ > 0) << ENDPOINT; QUIC_BUG_IF(quic_bug_12398_3, !HasRoomForStreamFrame(id, offset, data_size)) << ENDPOINT << "No room for Stream frame, BytesFree: " << BytesFree() << " MinStreamFrameSize: " << QuicFramer::GetMinStreamFrameSize(framer_->transport_version(), id, offset, true, data_size); QUIC_BUG_IF(quic_bug_12398_4, data_size == 0 && !fin) << ENDPOINT << "Creating a stream frame for stream ID:" << id << " with no data or fin."; size_t min_frame_size = QuicFramer::GetMinStreamFrameSize( framer_->transport_version(), id, offset, true, data_size); size_t bytes_consumed = std::min<size_t>(BytesFree() - min_frame_size, data_size); bool set_fin = fin && bytes_consumed == data_size; *frame = QuicFrame(QuicStreamFrame(id, set_fin, offset, bytes_consumed)); } bool QuicPacketCreator::CreateCryptoFrame(EncryptionLevel level, size_t write_length, QuicStreamOffset offset, QuicFrame* frame) { const size_t min_frame_size = QuicFramer::GetMinCryptoFrameSize(offset, write_length); if (BytesFree() <= min_frame_size && (!RemoveSoftMaxPacketLength() || BytesFree() <= min_frame_size)) { return false; } size_t max_write_length = BytesFree() - min_frame_size; size_t bytes_consumed = std::min<size_t>(max_write_length, write_length); *frame = QuicFrame(new QuicCryptoFrame(level, offset, bytes_consumed)); return true; } void QuicPacketCreator::FlushCurrentPacket() { if (!HasPendingFrames() && pending_padding_bytes_ == 0) { return; } ABSL_CACHELINE_ALIGNED char stack_buffer[kMaxOutgoingPacketSize]; QuicOwnedPacketBuffer external_buffer(delegate_->GetPacketBuffer()); if (external_buffer.buffer == nullptr) { external_buffer.buffer = stack_buffer; external_buffer.release_buffer = nullptr; } QUICHE_DCHECK_EQ(nullptr, packet_.encrypted_buffer) << ENDPOINT; if (!SerializePacket(std::move(external_buffer), kMaxOutgoingPacketSize, true)) { return; } OnSerializedPacket(); } void QuicPacketCreator::OnSerializedPacket() { QUIC_BUG_IF(quic_bug_12398_5, packet_.encrypted_buffer == nullptr) << ENDPOINT; if (packet_.transmission_type == NOT_RETRANSMISSION) { packet_.bytes_not_retransmitted.reset(); } SerializedPacket packet(std::move(packet_)); ClearPacket(); RemoveSoftMaxPacketLength(); delegate_->OnSerializedPacket(std::move(packet)); if (next_max_packet_length_ != 0) { QUICHE_DCHECK(CanSetMaxPacketLength()) << ENDPOINT; SetMaxPacketLength(next_max_packet_length_); next_max_packet_length_ = 0; } } void QuicPacketCreator::ClearPacket() { packet_.has_ack = false; packet_.has_stop_waiting = false; packet_.has_ack_ecn = false; packet_.has_crypto_handshake = NOT_HANDSHAKE; packet_.transmission_type = NOT_RETRANSMISSION; packet_.encrypted_buffer = nullptr; packet_.encrypted_length = 0; packet_.has_ack_frequency = false; packet_.has_message = false; packet_.fate = SEND_TO_WRITER; QUIC_BUG_IF(quic_bug_12398_6, packet_.release_encrypted_buffer != nullptr) << ENDPOINT << "packet_.release_encrypted_buffer should be empty"; packet_.release_encrypted_buffer = nullptr; QUICHE_DCHECK(packet_.retransmittable_frames.empty()) << ENDPOINT; QUICHE_DCHECK(packet_.nonretransmittable_frames.empty()) << ENDPOINT; packet_.largest_acked.Clear(); needs_full_padding_ = false; packet_.bytes_not_retransmitted.reset(); packet_.initial_header.reset(); } size_t QuicPacketCreator::ReserializeInitialPacketInCoalescedPacket( const SerializedPacket& packet, size_t padding_size, char* buffer, size_t buffer_len) { QUIC_BUG_IF(quic_bug_12398_7, packet.encryption_level != ENCRYPTION_INITIAL); QUIC_BUG_IF(quic_bug_12398_8, packet.nonretransmittable_frames.empty() && packet.retransmittable_frames.empty()) << ENDPOINT << "Attempt to serialize empty ENCRYPTION_INITIAL packet in coalesced " "packet"; if (HasPendingFrames()) { QUIC_BUG(quic_packet_creator_unexpected_queued_frames) << "Unexpected queued frames: " << GetPendingFramesInfo(); return 0; } ScopedPacketContextSwitcher switcher( packet.packet_number - 1, packet.packet_number_length, packet.encryption_level, &packet_); for (const QuicFrame& frame : packet.nonretransmittable_frames) { if (!AddFrame(frame, packet.transmission_type)) { QUIC_BUG(quic_bug_10752_6) << ENDPOINT << "Failed to serialize frame: " << frame; return 0; } } for (const QuicFrame& frame : packet.retransmittable_frames) { if (!AddFrame(frame, packet.transmission_type)) { QUIC_BUG(quic_bug_10752_7) << ENDPOINT << "Failed to serialize frame: " << frame; return 0; } } if (padding_size > 0) { QUIC_DVLOG(2) << ENDPOINT << "Add padding of size: " << padding_size; if (!AddFrame(QuicFrame(QuicPaddingFrame(padding_size)), packet.transmission_type)) { QUIC_BUG(quic_bug_10752_8) << ENDPOINT << "Failed to add padding of size " << padding_size << " when serializing ENCRYPTION_INITIAL " "packet in coalesced packet"; return 0; } } if (!SerializePacket(QuicOwnedPacketBuffer(buffer, nullptr), buffer_len, false)) { return 0; } if (!packet.initial_header.has_value() || !packet_.initial_header.has_value()) { QUIC_BUG(missing initial packet header) << "initial serialized packet does not have header populated"; } else if (*packet.initial_header != *packet_.initial_header) { QUIC_BUG(initial packet header changed before reserialization) << ENDPOINT << "original header: " << *packet.initial_header << ", new header: " << *packet_.initial_header; } const size_t encrypted_length = packet_.encrypted_length; packet_.retransmittable_frames.clear(); packet_.nonretransmittable_frames.clear(); ClearPacket(); return encrypted_length; } void QuicPacketCreator::CreateAndSerializeStreamFrame( QuicStreamId id, size_t write_length, QuicStreamOffset iov_offset, QuicStreamOffset stream_offset, bool fin, TransmissionType transmission_type, size_t* num_bytes_consumed) { QUICHE_DCHECK(queued_frames_.empty()) << ENDPOINT; QUICHE_DCHECK(!QuicUtils::IsCryptoStreamId(transport_version(), id)) << ENDPOINT; QuicPacketHeader header; FillPacketHeader(&header); packet_.fate = delegate_->GetSerializedPacketFate( false, packet_.encryption_level); QUIC_DVLOG(1) << ENDPOINT << "fate of packet " << packet_.packet_number << ": " << SerializedPacketFateToString(packet_.fate) << " of " << EncryptionLevelToString(packet_.encryption_level); ABSL_CACHELINE_ALIGNED char stack_buffer[kMaxOutgoingPacketSize]; QuicOwnedPacketBuffer packet_buffer(delegate_->GetPacketBuffer()); if (packet_buffer.buffer == nullptr) { packet_buffer.buffer = stack_buffer; packet_buffer.release_buffer = nullptr; } char* encrypted_buffer = packet_buffer.buffer; QuicDataWriter writer(kMaxOutgoingPacketSize, encrypted_buffer); size_t length_field_offset = 0; if (!framer_->AppendIetfPacketHeader(header, &writer, &length_field_offset)) { QUIC_BUG(quic_bug_10752_9) << ENDPOINT << "AppendPacketHeader failed"; return; } QUIC_BUG_IF(quic_bug_12398_9, iov_offset == write_length && !fin) << ENDPOINT << "Creating a stream frame with no data or fin."; const size_t remaining_data_size = write_length - iov_offset; size_t min_frame_size = QuicFramer::GetMinStreamFrameSize( framer_->transport_version(), id, stream_offset, true, remaining_data_size); size_t available_size = max_plaintext_size_ - writer.length() - min_frame_size; size_t bytes_consumed = std::min<size_t>(available_size, remaining_data_size); size_t plaintext_bytes_written = min_frame_size + bytes_consumed; bool needs_padding = false; const size_t min_plaintext_size = MinPlaintextPacketSize(framer_->version(), GetPacketNumberLength()); if (plaintext_bytes_written < min_plaintext_size) { needs_padding = true; } const bool set_fin = fin && (bytes_consumed == remaining_data_size); QuicStreamFrame frame(id, set_fin, stream_offset, bytes_consumed); if (debug_delegate_ != nullptr) { debug_delegate_->OnFrameAddedToPacket(QuicFrame(frame)); } QUIC_DVLOG(1) << ENDPOINT << "Adding frame: " << frame; QUIC_DVLOG(2) << ENDPOINT << "Serializing stream packet " << header << frame; if (needs_padding) { if (!writer.WritePaddingBytes(min_plaintext_size - plaintext_bytes_written)) { QUIC_BUG(quic_bug_10752_12) << ENDPOINT << "Unable to add padding bytes"; return; } needs_padding = false; } bool omit_frame_length = !needs_padding; if (!framer_->AppendTypeByte(QuicFrame(frame), omit_frame_length, &writer)) { QUIC_BUG(quic_bug_10752_10) << ENDPOINT << "AppendTypeByte failed"; return; } if (!framer_->AppendStreamFrame(frame, omit_frame_length, &writer)) { QUIC_BUG(quic_bug_10752_11) << ENDPOINT << "AppendStreamFrame failed"; return; } if (needs_padding && plaintext_bytes_written < min_plaintext_size && !writer.WritePaddingBytes(min_plaintext_size - plaintext_bytes_written)) { QUIC_BUG(quic_bug_10752_12) << ENDPOINT << "Unable to add padding bytes"; return; } if (!framer_->WriteIetfLongHeaderLength(header, &writer, length_field_offset, packet_.encryption_level)) { return; } packet_.transmission_type = transmission_type; QUICHE_DCHECK(packet_.encryption_level == ENCRYPTION_FORWARD_SECURE || packet_.encryption_level == ENCRYPTION_ZERO_RTT) << ENDPOINT << packet_.encryption_level; size_t encrypted_length = framer_->EncryptInPlace( packet_.encryption_level, packet_.packet_number, GetStartOfEncryptedData(framer_->transport_version(), header), writer.length(), kMaxOutgoingPacketSize, encrypted_buffer); if (encrypted_length == 0) { QUIC_BUG(quic_bug_10752_13) << ENDPOINT << "Failed to encrypt packet number " << header.packet_number; return; } *num_bytes_consumed = bytes_consumed; packet_size_ = 0; packet_.encrypted_buffer = encrypted_buffer; packet_.encrypted_length = encrypted_length; packet_buffer.buffer = nullptr; packet_.release_encrypted_buffer = std::move(packet_buffer).release_buffer; packet_.retransmittable_frames.push_back(QuicFrame(frame)); OnSerializedPacket(); } bool QuicPacketCreator::HasPendingFrames() const { return !queued_frames_.empty(); } std::string QuicPacketCreator::GetPendingFramesInfo() const { return QuicFramesToString(queued_frames_); } bool QuicPacketCreator::HasPendingRetransmittableFrames() const { return !packet_.retransmittable_frames.empty(); } bool QuicPacketCreator::HasPendingStreamFramesOfStream(QuicStreamId id) const { for (const auto& frame : packet_.retransmittable_frames) { if (frame.type == STREAM_FRAME && frame.stream_frame.stream_id == id) { return true; } } return false; } size_t QuicPacketCreator::ExpansionOnNewFrame() const { if (queued_frames_.empty()) { return 0; } return ExpansionOnNewFrameWithLastFrame(queued_frames_.back(), framer_->transport_version()); } size_t QuicPacketCreator::ExpansionOnNewFrameWithLastFrame( const QuicFrame& last_frame, QuicTransportVersion version) { if (last_frame.type == MESSAGE_FRAME) { return QuicDataWriter::GetVarInt62Len( last_frame.message_frame->message_length); } if (last_frame.type != STREAM_FRAME) { return 0; } if (VersionHasIetfQuicFrames(version)) { return QuicDataWriter::GetVarInt62Len(last_frame.stream_frame.data_length); } return kQuicStreamPayloadLengthSize; } size_t QuicPacketCreator::BytesFree() const { return max_plaintext_size_ - std::min(max_plaintext_size_, PacketSize() + ExpansionOnNewFrame()); } size_t QuicPacketCreator::BytesFreeForPadding() const { size_t consumed = PacketSize(); return max_plaintext_size_ - std::min(max_plaintext_size_, consumed); } size_t QuicPacketCreator::PacketSize() const { return queued_frames_.empty() ? PacketHeaderSize() : packet_size_; } bool QuicPacketCreator::AddPaddedSavedFrame( const QuicFrame& frame, TransmissionType transmission_type) { if (AddFrame(frame, transmission_type)) { needs_full_padding_ = true; return true; } return false; } std::optional<size_t> QuicPacketCreator::MaybeBuildDataPacketWithChaosProtection( const QuicPacketHeader& header, char* buffer) { if (!GetQuicFlag(quic_enable_chaos_protection) || framer_->perspective() != Perspective::IS_CLIENT || packet_.encryption_level != ENCRYPTION_INITIAL || !framer_->version().UsesCryptoFrames() || queued_frames_.size() != 2u || queued_frames_[0].type != CRYPTO_FRAME || queued_frames_[1].type != PADDING_FRAME || queued_frames_[1].padding_frame.num_padding_bytes <= 0 || framer_->data_producer() == nullptr) { return std::nullopt; } const QuicCryptoFrame& crypto_frame = *queued_frames_[0].crypto_frame; if (packet_.encryption_level != crypto_frame.level) { QUIC_BUG(chaos frame level) << ENDPOINT << packet_.encryption_level << " != " << crypto_frame.level; return std::nullopt; } QuicChaosProtector chaos_protector( crypto_frame, queued_frames_[1].padding_frame.num_padding_bytes, packet_size_, framer_, random_); return chaos_protector.BuildDataPacket(header, buffer); } bool QuicPacketCreator::SerializePacket(QuicOwnedPacketBuffer encrypted_buffer, size_t encrypted_buffer_len, bool allow_padding) { if (packet_.encrypted_buffer != nullptr) { const std::string error_details = "Packet's encrypted buffer is not empty before serialization"; QUIC_BUG(quic_bug_10752_14) << ENDPOINT << error_details; delegate_->OnUnrecoverableError(QUIC_FAILED_TO_SERIALIZE_PACKET, error_details); return false; } ScopedSerializationFailureHandler handler(this); QUICHE_DCHECK_LT(0u, encrypted_buffer_len) << ENDPOINT; QUIC_BUG_IF(quic_bug_12398_10, queued_frames_.empty() && pending_padding_bytes_ == 0) << ENDPOINT << "Attempt to serialize empty packet"; QuicPacketHeader header; FillPacketHeader(&header); if (packet_.encryption_level == ENCRYPTION_INITIAL) { packet_.initial_header = header; } if (delegate_ != nullptr) { packet_.fate = delegate_->GetSerializedPacketFate( QuicUtils::ContainsFrameType(queued_frames_, MTU_DISCOVERY_FRAME), packet_.encryption_level); QUIC_DVLOG(1) << ENDPOINT << "fate of packet " << packet_.packet_number << ": " << SerializedPacketFateToString(packet_.fate) << " of " << EncryptionLevelToString(packet_.encryption_level); } if (allow_padding) { MaybeAddPadding(); } QUIC_DVLOG(2) << ENDPOINT << "Serializing packet " << header << QuicFramesToString(queued_frames_) << " at encryption_level " << packet_.encryption_level << ", allow_padding:" << allow_padding; if (!framer_->HasEncrypterOfEncryptionLevel(packet_.encryption_level)) { QUIC_BUG(quic_bug_10752_15) << ENDPOINT << "Attempting to serialize " << header << QuicFramesToString(queued_frames_) << " at missing encryption_level " << packet_.encryption_level << " using " << framer_->version(); return false; } QUICHE_DCHECK_GE(max_plaintext_size_, packet_size_) << ENDPOINT; size_t length; std::optional<size_t> length_with_chaos_protection = MaybeBuildDataPacketWithChaosProtection(header, encrypted_buffer.buffer); if (length_with_chaos_protection.has_value()) { length = *length_with_chaos_protection; } else { length = framer_->BuildDataPacket(header, queued_frames_, encrypted_buffer.buffer, packet_size_, packet_.encryption_level); } if (length == 0) { QUIC_BUG(quic_bug_10752_16) << ENDPOINT << "Failed to serialize " << QuicFramesToString(queued_frames_) << " at encryption_level: " << packet_.encryption_level << ", needs_full_padding_: " << needs_full_padding_ << ", pending_padding_bytes_: " << pending_padding_bytes_ << ", latched_hard_max_packet_length_: " << latched_hard_max_packet_length_ << ", max_packet_length_: " << max_packet_length_ << ", header: " << header; return false; } bool possibly_truncated_by_length = packet_size_ == max_plaintext_size_ && queued_frames_.size() == 1 && queued_frames_.back().type == ACK_FRAME; if (!possibly_truncated_by_length) { QUICHE_DCHECK_EQ(packet_size_, length) << ENDPOINT; } const size_t encrypted_length = framer_->EncryptInPlace( packet_.encryption_level, packet_.packet_number, GetStartOfEncryptedData(framer_->transport_version(), header), length, encrypted_buffer_len, encrypted_buffer.buffer); if (encrypted_length == 0) { QUIC_BUG(quic_bug_10752_17) << ENDPOINT << "Failed to encrypt packet number " << packet_.packet_number; return false; } packet_size_ = 0; packet_.encrypted_buffer = encrypted_buffer.buffer; packet_.encrypted_length = encrypted_length; encrypted_buffer.buffer = nullptr; packet_.release_encrypted_buffer = std::move(encrypted_buffer).release_buffer; return true; } std::unique_ptr<SerializedPacket> QuicPacketCreator::SerializeConnectivityProbingPacket() { QUIC_BUG_IF(quic_bug_12398_11, VersionHasIetfQuicFrames(framer_->transport_version())) << ENDPOINT << "Must not be version 99 to serialize padded ping connectivity probe"; RemoveSoftMaxPacketLength(); QuicPacketHeader header; FillPacketHeader(&header); QUIC_DVLOG(2) << ENDPOINT << "Serializing connectivity probing packet " << header; std::unique_ptr<char[]> buffer(new char[kMaxOutgoingPacketSize]); size_t length = BuildConnectivityProbingPacket( header, buffer.get(), max_plaintext_size_, packet_.encryption_level); QUICHE_DCHECK(length) << ENDPOINT; QUICHE_DCHECK_EQ(packet_.encryption_level, ENCRYPTION_FORWARD_SECURE) << ENDPOINT; const size_t encrypted_length = framer_->EncryptInPlace( packet_.encryption_level, packet_.packet_number, GetStartOfEncryptedData(framer_->transport_version(), header), length, kMaxOutgoingPacketSize, buffer.get()); QUICHE_DCHECK(encrypted_length) << ENDPOINT; std::unique_ptr<SerializedPacket> serialize_packet(new SerializedPacket( header.packet_number, header.packet_number_length, buffer.release(), encrypted_length, false, false)); serialize_packet->release_encrypted_buffer = [](const char* p) { delete[] p; }; serialize_packet->encryption_level = packet_.encryption_level; serialize_packet->transmission_type = NOT_RETRANSMISSION; return serialize_packet; } std::unique_ptr<SerializedPacket> QuicPacketCreator::SerializePathChallengeConnectivityProbingPacket( const QuicPathFrameBuffer& payload) { QUIC_BUG_IF(quic_bug_12398_12, !VersionHasIetfQuicFrames(framer_->transport_version())) << ENDPOINT << "Must be version 99 to serialize path challenge connectivity probe, " "is version " << framer_->transport_version(); RemoveSoftMaxPacketLength(); QuicPacketHeader header; FillPacketHeader(&header); QUIC_DVLOG(2) << ENDPOINT << "Serializing path challenge packet " << header; std::unique_ptr<char[]> buffer(new char[kMaxOutgoingPacketSize]); size_t length = BuildPaddedPathChallengePacket(header, buffer.get(), max_plaintext_size_, payload, packet_.encryption_level); QUICHE_DCHECK(length) << ENDPOINT; QUICHE_DCHECK_EQ(packet_.encryption_level, ENCRYPTION_FORWARD_SECURE) << ENDPOINT; const size_t encrypted_length = framer_->EncryptInPlace( packet_.encryption_level, packet_.packet_number, GetStartOfEncryptedData(framer_->transport_version(), header), length, kMaxOutgoingPacketSize, buffer.get()); QUICHE_DCHECK(encrypted_length) << ENDPOINT; std::unique_ptr<SerializedPacket> serialize_packet( new SerializedPacket(header.packet_number, header.packet_number_length, buffer.release(), encrypted_length, false, false)); serialize_packet->release_encrypted_buffer = [](const char* p) { delete[] p; }; serialize_packet->encryption_level = packet_.encryption_level; serialize_packet->transmission_type = NOT_RETRANSMISSION; return serialize_packet; } std::unique_ptr<SerializedPacket> QuicPacketCreator::SerializePathResponseConnectivityProbingPacket( const quiche::QuicheCircularDeque<QuicPathFrameBuffer>& payloads, const bool is_padded) { QUIC_BUG_IF(quic_bug_12398_13, !VersionHasIetfQuicFrames(framer_->transport_version())) << ENDPOINT << "Must be version 99 to serialize path response connectivity probe, is " "version " << framer_->transport_version(); RemoveSoftMaxPacketLength(); QuicPacketHeader header; FillPacketHeader(&header); QUIC_DVLOG(2) << ENDPOINT << "Serializing path response packet " << header; std::unique_ptr<char[]> buffer(new char[kMaxOutgoingPacketSize]); size_t length = BuildPathResponsePacket(header, buffer.get(), max_plaintext_size_, payloads, is_padded, packet_.encryption_level); QUICHE_DCHECK(length) << ENDPOINT; QUICHE_DCHECK_EQ(packet_.encryption_level, ENCRYPTION_FORWARD_SECURE) << ENDPOINT; const size_t encrypted_length = framer_->EncryptInPlace( packet_.encryption_level, packet_.packet_number, GetStartOfEncryptedData(framer_->transport_version(), header), length, kMaxOutgoingPacketSize, buffer.get()); QUICHE_DCHECK(encrypted_length) << ENDPOINT; std::unique_ptr<SerializedPacket> serialize_packet( new SerializedPacket(header.packet_number, header.packet_number_length, buffer.release(), encrypted_length, false, false)); serialize_packet->release_encrypted_buffer = [](const char* p) { delete[] p; }; serialize_packet->encryption_level = packet_.encryption_level; serialize_packet->transmission_type = NOT_RETRANSMISSION; return serialize_packet; } std::unique_ptr<SerializedPacket> QuicPacketCreator::SerializeLargePacketNumberConnectionClosePacket( QuicPacketNumber largest_acked_packet, QuicErrorCode error, const std::string& error_details) { QUICHE_DCHECK_EQ(packet_.encryption_level, ENCRYPTION_FORWARD_SECURE) << ENDPOINT; const QuicPacketNumber largest_packet_number( (largest_acked_packet.IsInitialized() ? largest_acked_packet : framer_->first_sending_packet_number()) + (1L << 31)); ScopedPacketContextSwitcher switcher(largest_packet_number, PACKET_4BYTE_PACKET_NUMBER, ENCRYPTION_FORWARD_SECURE, &packet_); QuicPacketHeader header; FillPacketHeader(&header); QUIC_DVLOG(2) << ENDPOINT << "Serializing connection close packet " << header; QuicFrames frames; QuicConnectionCloseFrame close_frame(transport_version(), error, NO_IETF_QUIC_ERROR, error_details, 0); frames.push_back(QuicFrame(&close_frame)); std::unique_ptr<char[]> buffer(new char[kMaxOutgoingPacketSize]); const size_t length = framer_->BuildDataPacket(header, frames, buffer.get(), max_plaintext_size_, packet_.encryption_level); QUICHE_DCHECK(length) << ENDPOINT; const size_t encrypted_length = framer_->EncryptInPlace( packet_.encryption_level, packet_.packet_number, GetStartOfEncryptedData(framer_->transport_version(), header), length, kMaxOutgoingPacketSize, buffer.get()); QUICHE_DCHECK(encrypted_length) << ENDPOINT; std::unique_ptr<SerializedPacket> serialize_packet( new SerializedPacket(header.packet_number, header.packet_number_length, buffer.release(), encrypted_length, false, false)); serialize_packet->release_encrypted_buffer = [](const char* p) { delete[] p; }; serialize_packet->encryption_level = packet_.encryption_level; serialize_packet->transmission_type = NOT_RETRANSMISSION; return serialize_packet; } size_t QuicPacketCreator::BuildPaddedPathChallengePacket( const QuicPacketHeader& header, char* buffer, size_t packet_length, const QuicPathFrameBuffer& payload, EncryptionLevel level) { QUICHE_DCHECK(VersionHasIetfQuicFrames(framer_->transport_version())) << ENDPOINT; QuicFrames frames; frames.push_back(QuicFrame(QuicPathChallengeFrame(0, payload))); if (debug_delegate_ != nullptr) { debug_delegate_->OnFrameAddedToPacket(frames.back()); } QuicPaddingFrame padding_frame; frames.push_back(QuicFrame(padding_frame)); return framer_->BuildDataPacket(header, frames, buffer, packet_length, level); } size_t QuicPacketCreator::BuildPathResponsePacket( const QuicPacketHeader& header, char* buffer, size_t packet_length, const quiche::QuicheCircularDeque<QuicPathFrameBuffer>& payloads, const bool is_padded, EncryptionLevel level) { if (payloads.empty()) { QUIC_BUG(quic_bug_12398_14) << ENDPOINT << "Attempt to generate connectivity response with no request payloads"; return 0; } QUICHE_DCHECK(VersionHasIetfQuicFrames(framer_->transport_version())) << ENDPOINT; QuicFrames frames; for (const QuicPathFrameBuffer& payload : payloads) { frames.push_back(QuicFrame(QuicPathResponseFrame(0, payload))); if (debug_delegate_ != nullptr) { debug_delegate_->OnFrameAddedToPacket(frames.back()); } } if (is_padded) { QuicPaddingFrame padding_frame; frames.push_back(QuicFrame(padding_frame)); } return framer_->BuildDataPacket(header, frames, buffer, packet_length, level); } size_t QuicPacketCreator::BuildConnectivityProbingPacket( const QuicPacketHeader& header, char* buffer, size_t packet_length, EncryptionLevel level) { QuicFrames frames; QuicPingFrame ping_frame; frames.push_back(QuicFrame(ping_frame)); QuicPaddingFrame padding_frame; frames.push_back(QuicFrame(padding_frame)); return framer_->BuildDataPacket(header, frames, buffer, packet_length, level); } size_t QuicPacketCreator::SerializeCoalescedPacket( const QuicCoalescedPacket& coalesced, char* buffer, size_t buffer_len) { if (HasPendingFrames()) { QUIC_BUG(quic_bug_10752_18) << ENDPOINT << "Try to serialize coalesced packet with pending frames"; return 0; } RemoveSoftMaxPacketLength(); QUIC_BUG_IF(quic_bug_12398_15, coalesced.length() == 0) << ENDPOINT << "Attempt to serialize empty coalesced packet"; size_t packet_length = 0; size_t initial_length = 0; size_t padding_size = 0; if (coalesced.initial_packet() != nullptr) { padding_size = coalesced.max_packet_length() - coalesced.length(); if (framer_->perspective() == Perspective::IS_SERVER && QuicUtils::ContainsFrameType( coalesced.initial_packet()->retransmittable_frames, CONNECTION_CLOSE_FRAME)) { padding_size = 0; } initial_length = ReserializeInitialPacketInCoalescedPacket( *coalesced.initial_packet(), padding_size, buffer, buffer_len); if (initial_length == 0) { QUIC_BUG(quic_bug_10752_19) << ENDPOINT << "Failed to reserialize ENCRYPTION_INITIAL packet in " "coalesced packet"; return 0; } QUIC_BUG_IF(quic_reserialize_initial_packet_unexpected_size, coalesced.initial_packet()->encrypted_length + padding_size != initial_length) << "Reserialize initial packet in coalescer has unexpected size, " "original_length: " << coalesced.initial_packet()->encrypted_length << ", coalesced.max_packet_length: " << coalesced.max_packet_length() << ", coalesced.length: " << coalesced.length() << ", padding_size: " << padding_size << ", serialized_length: " << initial_length << ", retransmittable frames: " << QuicFramesToString( coalesced.initial_packet()->retransmittable_frames) << ", nonretransmittable frames: " << QuicFramesToString( coalesced.initial_packet()->nonretransmittable_frames); buffer += initial_length; buffer_len -= initial_length; packet_length += initial_length; } size_t length_copied = 0; if (!coalesced.CopyEncryptedBuffers(buffer, buffer_len, &length_copied)) { QUIC_BUG(quic_serialize_coalesced_packet_copy_failure) << "SerializeCoalescedPacket failed. buffer_len:" << buffer_len << ", initial_length:" << initial_length << ", padding_size: " << padding_size << ", length_copied:" << length_copied << ", coalesced.length:" << coalesced.length() << ", coalesced.max_packet_length:" << coalesced.max_packet_length() << ", coalesced.packet_lengths:" << absl::StrJoin(coalesced.packet_lengths(), ":"); return 0; } packet_length += length_copied; QUIC_DVLOG(1) << ENDPOINT << "Successfully serialized coalesced packet of length: " << packet_length; return packet_length; } SerializedPacket QuicPacketCreator::NoPacket() { return SerializedPacket(QuicPacketNumber(), PACKET_1BYTE_PACKET_NUMBER, nullptr, 0, false, false); } QuicConnectionId QuicPacketCreator::GetDestinationConnectionId() const { if (framer_->perspective() == Perspective::IS_SERVER) { return client_connection_id_; } return server_connection_id_; } QuicConnectionId QuicPacketCreator::GetSourceConnectionId() const { if (framer_->perspective() == Perspective::IS_CLIENT) { return client_connection_id_; } return server_connection_id_; } QuicConnectionIdIncluded QuicPacketCreator::GetDestinationConnectionIdIncluded() const { return (framer_->perspective() == Perspective::IS_CLIENT || framer_->version().SupportsClientConnectionIds()) ? CONNECTION_ID_PRESENT : CONNECTION_ID_ABSENT; } QuicConnectionIdIncluded QuicPacketCreator::GetSourceConnectionIdIncluded() const { if (HasIetfLongHeader() && (framer_->perspective() == Perspective::IS_SERVER || framer_->version().SupportsClientConnectionIds())) { return CONNECTION_ID_PRESENT; } if (framer_->perspective() == Perspective::IS_SERVER) { return server_connection_id_included_; } return CONNECTION_ID_ABSENT; } uint8_t QuicPacketCreator::GetDestinationConnectionIdLength() const { QUICHE_DCHECK(QuicUtils::IsConnectionIdValidForVersion(server_connection_id_, transport_version())) << ENDPOINT; return GetDestinationConnectionIdIncluded() == CONNECTION_ID_PRESENT ? GetDestinationConnectionId().length() : 0; } uint8_t QuicPacketCreator::GetSourceConnectionIdLength() const { QUICHE_DCHECK(QuicUtils::IsConnectionIdValidForVersion(server_connection_id_, transport_version())) << ENDPOINT; return GetSourceConnectionIdIncluded() == CONNECTION_ID_PRESENT ? GetSourceConnectionId().length() : 0; } QuicPacketNumberLength QuicPacketCreator::GetPacketNumberLength() const { if (HasIetfLongHeader() && !framer_->version().SendsVariableLengthPacketNumberInLongHeader()) { return PACKET_4BYTE_PACKET_NUMBER; } return packet_.packet_number_length; } size_t QuicPacketCreator::PacketHeaderSize() const { return GetPacketHeaderSize( framer_->transport_version(), GetDestinationConnectionIdLength(), GetSourceConnectionIdLength(), IncludeVersionInHeader(), IncludeNonceInPublicHeader(), GetPacketNumberLength(), GetRetryTokenLengthLength(), GetRetryToken().length(), GetLengthLength()); } quiche::QuicheVariableLengthIntegerLength QuicPacketCreator::GetRetryTokenLengthLength() const { if (QuicVersionHasLongHeaderLengths(framer_->transport_version()) && HasIetfLongHeader() && EncryptionlevelToLongHeaderType(packet_.encryption_level) == INITIAL) { return QuicDataWriter::GetVarInt62Len(GetRetryToken().length()); } return quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0; } absl::string_view QuicPacketCreator::GetRetryToken() const { if (QuicVersionHasLongHeaderLengths(framer_->transport_version()) && HasIetfLongHeader() && EncryptionlevelToLongHeaderType(packet_.encryption_level) == INITIAL) { return retry_token_; } return absl::string_view(); } void QuicPacketCreator::SetRetryToken(absl::string_view retry_token) { retry_token_ = std::string(retry_token); } bool QuicPacketCreator::ConsumeRetransmittableControlFrame( const QuicFrame& frame) { QUIC_BUG_IF(quic_bug_12398_16, IsControlFrame(frame.type) && !GetControlFrameId(frame) && frame.type != PING_FRAME) << ENDPOINT << "Adding a control frame with no control frame id: " << frame; QUICHE_DCHECK(QuicUtils::IsRetransmittableFrame(frame.type)) << ENDPOINT << frame; MaybeBundleOpportunistically(); if (HasPendingFrames()) { if (AddFrame(frame, next_transmission_type_)) { return true; } } QUICHE_DCHECK(!HasPendingFrames()) << ENDPOINT; if (frame.type != PING_FRAME && frame.type != CONNECTION_CLOSE_FRAME && !delegate_->ShouldGeneratePacket(HAS_RETRANSMITTABLE_DATA, NOT_HANDSHAKE)) { return false; } const bool success = AddFrame(frame, next_transmission_type_); QUIC_BUG_IF(quic_bug_10752_20, !success) << ENDPOINT << "Failed to add frame:" << frame << " transmission_type:" << next_transmission_type_; return success; } void QuicPacketCreator::MaybeBundleOpportunistically() { const TransmissionType next_transmission_type = next_transmission_type_; delegate_->MaybeBundleOpportunistically(next_transmission_type_); next_transmission_type_ = next_transmission_type; } QuicConsumedData QuicPacketCreator::ConsumeData(QuicStreamId id, size_t write_length, QuicStreamOffset offset, StreamSendingState state) { QUIC_BUG_IF(quic_bug_10752_21, !flusher_attached_) << ENDPOINT << "Packet flusher is not attached when " "generator tries to write stream data."; bool has_handshake = QuicUtils::IsCryptoStreamId(transport_version(), id); const TransmissionType next_transmission_type = next_transmission_type_; MaybeBundleOpportunistically(); const size_t original_write_length = write_length; if (next_transmission_type_ == NOT_RETRANSMISSION) { if (QuicByteCount send_window = delegate_->GetFlowControlSendWindowSize(id); write_length > send_window) { QUIC_DLOG(INFO) << ENDPOINT << "After bundled data, reducing (old) write_length:" << write_length << "to (new) send_window:" << send_window; write_length = send_window; state = NO_FIN; } } bool fin = state != NO_FIN; QUIC_BUG_IF(quic_bug_12398_17, has_handshake && fin) << ENDPOINT << "Handshake packets should never send a fin"; if (has_handshake && HasPendingRetransmittableFrames()) { FlushCurrentPacket(); } size_t total_bytes_consumed = 0; bool fin_consumed = false; if (!HasRoomForStreamFrame(id, offset, write_length)) { FlushCurrentPacket(); } if (!fin && (write_length == 0)) { QUIC_BUG_IF(quic_bug_10752_22, original_write_length == 0) << ENDPOINT << "Attempt to consume empty data without FIN. old transmission type:" << next_transmission_type << ", new transmission type:" << next_transmission_type_; return QuicConsumedData(0, false); } bool run_fast_path = !has_handshake && state != FIN_AND_PADDING && !HasPendingFrames() && write_length - total_bytes_consumed > kMaxOutgoingPacketSize && latched_hard_max_packet_length_ == 0; while (!run_fast_path && (has_handshake || delegate_->ShouldGeneratePacket( HAS_RETRANSMITTABLE_DATA, NOT_HANDSHAKE))) { QuicFrame frame; bool needs_full_padding = has_handshake && fully_pad_crypto_handshake_packets_; if (!ConsumeDataToFillCurrentPacket(id, write_length - total_bytes_consumed, offset + total_bytes_consumed, fin, needs_full_padding, next_transmission_type_, &frame)) { QUIC_BUG(quic_bug_10752_23) << ENDPOINT << "Failed to ConsumeData, stream:" << id; return QuicConsumedData(0, false); } size_t bytes_consumed = frame.stream_frame.data_length; total_bytes_consumed += bytes_consumed; fin_consumed = fin && total_bytes_consumed == write_length; if (fin_consumed && state == FIN_AND_PADDING) { AddRandomPadding(); } QUICHE_DCHECK(total_bytes_consumed == write_length || (bytes_consumed > 0 && HasPendingFrames())) << ENDPOINT; if (total_bytes_consumed == write_length) { break; } FlushCurrentPacket(); run_fast_path = !has_handshake && state != FIN_AND_PADDING && !HasPendingFrames() && write_length - total_bytes_consumed > kMaxOutgoingPacketSize && latched_hard_max_packet_length_ == 0; } if (run_fast_path) { return ConsumeDataFastPath(id, write_length, offset, state != NO_FIN, total_bytes_consumed); } if (has_handshake) { FlushCurrentPacket(); } return QuicConsumedData(total_bytes_consumed, fin_consumed); } QuicConsumedData QuicPacketCreator::ConsumeDataFastPath( QuicStreamId id, size_t write_length, QuicStreamOffset offset, bool fin, size_t total_bytes_consumed) { QUICHE_DCHECK(!QuicUtils::IsCryptoStreamId(transport_version(), id)) << ENDPOINT; if (AttemptingToSendUnencryptedStreamData()) { return QuicConsumedData(total_bytes_consumed, fin && (total_bytes_consumed == write_length)); } while (total_bytes_consumed < write_length && delegate_->ShouldGeneratePacket(HAS_RETRANSMITTABLE_DATA, NOT_HANDSHAKE)) { size_t bytes_consumed = 0; CreateAndSerializeStreamFrame(id, write_length, total_bytes_consumed, offset + total_bytes_consumed, fin, next_transmission_type_, &bytes_consumed); if (bytes_consumed == 0) { const std::string error_details = "Failed in CreateAndSerializeStreamFrame."; QUIC_BUG(quic_bug_10752_24) << ENDPOINT << error_details; delegate_->OnUnrecoverableError(QUIC_FAILED_TO_SERIALIZE_PACKET, error_details); break; } total_bytes_consumed += bytes_consumed; } return QuicConsumedData(total_bytes_consumed, fin && (total_bytes_consumed == write_length)); } size_t QuicPacketCreator::ConsumeCryptoData(EncryptionLevel level, size_t write_length, QuicStreamOffset offset) { QUIC_DVLOG(2) << ENDPOINT << "ConsumeCryptoData " << level << " write_length " << write_length << " offset " << offset; QUIC_BUG_IF(quic_bug_10752_25, !flusher_attached_) << ENDPOINT << "Packet flusher is not attached when " "generator tries to write crypto data."; MaybeBundleOpportunistically(); if (HasPendingRetransmittableFrames()) { FlushCurrentPacket(); } size_t total_bytes_consumed = 0; while ( total_bytes_consumed < write_length && delegate_->ShouldGeneratePacket(HAS_RETRANSMITTABLE_DATA, IS_HANDSHAKE)) { QuicFrame frame; if (!ConsumeCryptoDataToFillCurrentPacket( level, write_length - total_bytes_consumed, offset + total_bytes_consumed, fully_pad_crypto_handshake_packets_, next_transmission_type_, &frame)) { QUIC_BUG_IF(quic_bug_10752_26, !HasSoftMaxPacketLength()) << absl::StrCat( ENDPOINT, "Failed to ConsumeCryptoData at level ", level, ", pending_frames: ", GetPendingFramesInfo(), ", has_soft_max_packet_length: ", HasSoftMaxPacketLength(), ", max_packet_length: ", max_packet_length_, ", transmission_type: ", TransmissionTypeToString(next_transmission_type_), ", packet_number: ", packet_number().ToString()); return 0; } total_bytes_consumed += frame.crypto_frame->data_length; FlushCurrentPacket(); } FlushCurrentPacket(); return total_bytes_consumed; } void QuicPacketCreator::GenerateMtuDiscoveryPacket(QuicByteCount target_mtu) { if (!CanSetMaxPacketLength()) { QUIC_BUG(quic_bug_10752_27) << ENDPOINT << "MTU discovery packets should only be sent when no other " << "frames needs to be sent."; return; } const QuicByteCount current_mtu = max_packet_length(); QuicMtuDiscoveryFrame mtu_discovery_frame; QuicFrame frame(mtu_discovery_frame); SetMaxPacketLength(target_mtu); const bool success = AddPaddedSavedFrame(frame, next_transmission_type_); FlushCurrentPacket(); QUIC_BUG_IF(quic_bug_10752_28, !success) << ENDPOINT << "Failed to send path MTU target_mtu:" << target_mtu << " transmission_type:" << next_transmission_type_; SetMaxPacketLength(current_mtu); } bool QuicPacketCreator::FlushAckFrame(const QuicFrames& frames) { QUIC_BUG_IF(quic_bug_10752_30, !flusher_attached_) << ENDPOINT << "Packet flusher is not attached when " "generator tries to send ACK frame."; QUIC_BUG_IF(quic_bug_12398_18, !frames.empty() && has_ack()) << ENDPOINT << "Trying to flush " << quiche::PrintElements(frames) << " when there is ACK queued"; for (const auto& frame : frames) { QUICHE_DCHECK(frame.type == ACK_FRAME || frame.type == STOP_WAITING_FRAME) << ENDPOINT; if (HasPendingFrames()) { if (AddFrame(frame, next_transmission_type_)) { continue; } } QUICHE_DCHECK(!HasPendingFrames()) << ENDPOINT; if (!delegate_->ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, NOT_HANDSHAKE)) { return false; } const bool success = AddFrame(frame, next_transmission_type_); QUIC_BUG_IF(quic_bug_10752_31, !success) << ENDPOINT << "Failed to flush " << frame; } return true; } void QuicPacketCreator::AddRandomPadding() { AddPendingPadding(random_->RandUint64() % kMaxNumRandomPaddingBytes + 1); } void QuicPacketCreator::AttachPacketFlusher() { flusher_attached_ = true; if (!write_start_packet_number_.IsInitialized()) { write_start_packet_number_ = NextSendingPacketNumber(); } } void QuicPacketCreator::Flush() { FlushCurrentPacket(); SendRemainingPendingPadding(); flusher_attached_ = false; if (GetQuicFlag(quic_export_write_path_stats_at_server)) { if (!write_start_packet_number_.IsInitialized()) { QUIC_BUG(quic_bug_10752_32) << ENDPOINT << "write_start_packet_number is not initialized"; return; } QUIC_SERVER_HISTOGRAM_COUNTS( "quic_server_num_written_packets_per_write", NextSendingPacketNumber() - write_start_packet_number_, 1, 200, 50, "Number of QUIC packets written per write operation"); } write_start_packet_number_.Clear(); } void QuicPacketCreator::SendRemainingPendingPadding() { while ( pending_padding_bytes() > 0 && !HasPendingFrames() && delegate_->ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, NOT_HANDSHAKE)) { FlushCurrentPacket(); } } void QuicPacketCreator::SetServerConnectionIdLength(uint32_t length) { if (length == 0) { SetServerConnectionIdIncluded(CONNECTION_ID_ABSENT); } else { SetServerConnectionIdIncluded(CONNECTION_ID_PRESENT); } } void QuicPacketCreator::SetTransmissionType(TransmissionType type) { next_transmission_type_ = type; } MessageStatus QuicPacketCreator::AddMessageFrame( QuicMessageId message_id, absl::Span<quiche::QuicheMemSlice> message) { QUIC_BUG_IF(quic_bug_10752_33, !flusher_attached_) << ENDPOINT << "Packet flusher is not attached when " "generator tries to add message frame."; MaybeBundleOpportunistically(); const QuicByteCount message_length = MemSliceSpanTotalSize(message); if (message_length > GetCurrentLargestMessagePayload()) { return MESSAGE_STATUS_TOO_LARGE; } if (!HasRoomForMessageFrame(message_length)) { FlushCurrentPacket(); } QuicMessageFrame* frame = new QuicMessageFrame(message_id, message); const bool success = AddFrame(QuicFrame(frame), next_transmission_type_); if (!success) { QUIC_BUG(quic_bug_10752_34) << ENDPOINT << "Failed to send message " << message_id; delete frame; return MESSAGE_STATUS_INTERNAL_ERROR; } QUICHE_DCHECK_EQ(MemSliceSpanTotalSize(message), 0u); return MESSAGE_STATUS_SUCCESS; } quiche::QuicheVariableLengthIntegerLength QuicPacketCreator::GetLengthLength() const { if (QuicVersionHasLongHeaderLengths(framer_->transport_version()) && HasIetfLongHeader()) { QuicLongHeaderType long_header_type = EncryptionlevelToLongHeaderType(packet_.encryption_level); if (long_header_type == INITIAL || long_header_type == ZERO_RTT_PROTECTED || long_header_type == HANDSHAKE) { return quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2; } } return quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0; } void QuicPacketCreator::FillPacketHeader(QuicPacketHeader* header) { header->destination_connection_id = GetDestinationConnectionId(); header->destination_connection_id_included = GetDestinationConnectionIdIncluded(); header->source_connection_id = GetSourceConnectionId(); header->source_connection_id_included = GetSourceConnectionIdIncluded(); header->reset_flag = false; header->version_flag = IncludeVersionInHeader(); if (IncludeNonceInPublicHeader()) { QUICHE_DCHECK_EQ(Perspective::IS_SERVER, framer_->perspective()) << ENDPOINT; header->nonce = &diversification_nonce_; } else { header->nonce = nullptr; } packet_.packet_number = NextSendingPacketNumber(); header->packet_number = packet_.packet_number; header->packet_number_length = GetPacketNumberLength(); header->retry_token_length_length = GetRetryTokenLengthLength(); header->retry_token = GetRetryToken(); header->length_length = GetLengthLength(); header->remaining_packet_length = 0; if (!HasIetfLongHeader()) { return; } header->long_packet_type = EncryptionlevelToLongHeaderType(packet_.encryption_level); } size_t QuicPacketCreator::GetSerializedFrameLength(const QuicFrame& frame) { size_t serialized_frame_length = framer_->GetSerializedFrameLength( frame, BytesFree(), queued_frames_.empty(), true, GetPacketNumberLength()); if (!framer_->version().HasHeaderProtection() || serialized_frame_length == 0) { return serialized_frame_length; } const size_t frame_bytes = PacketSize() - PacketHeaderSize() + ExpansionOnNewFrame() + serialized_frame_length; if (frame_bytes >= MinPlaintextPacketSize(framer_->version(), GetPacketNumberLength())) { return serialized_frame_length; } if (BytesFree() < serialized_frame_length) { QUIC_BUG(quic_bug_10752_35) << ENDPOINT << "Frame does not fit: " << frame; return 0; } size_t bytes_free = BytesFree() - serialized_frame_length; const size_t extra_bytes_needed = std::max( 1 + ExpansionOnNewFrameWithLastFrame(frame, framer_->transport_version()), MinPlaintextPacketSize(framer_->version(), GetPacketNumberLength()) - frame_bytes); if (bytes_free < extra_bytes_needed) { return 0; } return serialized_frame_length; } bool QuicPacketCreator::AddFrame(const QuicFrame& frame, TransmissionType transmission_type) { QUIC_DVLOG(1) << ENDPOINT << "Adding frame with transmission type " << transmission_type << ": " << frame; if (frame.type == STREAM_FRAME && !QuicUtils::IsCryptoStreamId(framer_->transport_version(), frame.stream_frame.stream_id) && AttemptingToSendUnencryptedStreamData()) { return false; } QUICHE_DCHECK( packet_.encryption_level == ENCRYPTION_ZERO_RTT || packet_.encryption_level == ENCRYPTION_FORWARD_SECURE || (frame.type != GOAWAY_FRAME && frame.type != WINDOW_UPDATE_FRAME && frame.type != HANDSHAKE_DONE_FRAME && frame.type != NEW_CONNECTION_ID_FRAME && frame.type != MAX_STREAMS_FRAME && frame.type != STREAMS_BLOCKED_FRAME && frame.type != PATH_RESPONSE_FRAME && frame.type != PATH_CHALLENGE_FRAME && frame.type != STOP_SENDING_FRAME && frame.type != MESSAGE_FRAME && frame.type != NEW_TOKEN_FRAME && frame.type != RETIRE_CONNECTION_ID_FRAME && frame.type != ACK_FREQUENCY_FRAME)) << ENDPOINT << frame.type << " not allowed at " << packet_.encryption_level; if (frame.type == STREAM_FRAME) { if (MaybeCoalesceStreamFrame(frame.stream_frame)) { LogCoalesceStreamFrameStatus(true); return true; } else { LogCoalesceStreamFrameStatus(false); } } QUICHE_DCHECK(frame.type != ACK_FRAME || (!frame.ack_frame->packets.Empty() && frame.ack_frame->packets.Max() == frame.ack_frame->largest_acked)) << ENDPOINT << "Invalid ACK frame: " << frame; size_t frame_len = GetSerializedFrameLength(frame); if (frame_len == 0 && RemoveSoftMaxPacketLength()) { frame_len = GetSerializedFrameLength(frame); } if (frame_len == 0) { QUIC_DVLOG(1) << ENDPOINT << "Flushing because current open packet is full when adding " << frame; FlushCurrentPacket(); return false; } if (queued_frames_.empty()) { packet_size_ = PacketHeaderSize(); } QUICHE_DCHECK_LT(0u, packet_size_) << ENDPOINT; packet_size_ += ExpansionOnNewFrame() + frame_len; if (QuicUtils::IsRetransmittableFrame(frame.type)) { packet_.retransmittable_frames.push_back(frame); queued_frames_.push_back(frame); if (QuicUtils::IsHandshakeFrame(frame, framer_->transport_version())) { packet_.has_crypto_handshake = IS_HANDSHAKE; } } else { if (frame.type == PADDING_FRAME && frame.padding_frame.num_padding_bytes == -1) { packet_.nonretransmittable_frames.push_back( QuicFrame(QuicPaddingFrame(frame_len))); } else { packet_.nonretransmittable_frames.push_back(frame); } queued_frames_.push_back(frame); } if (frame.type == ACK_FRAME) { packet_.has_ack = true; packet_.largest_acked = LargestAcked(*frame.ack_frame); if (frame.ack_frame->ecn_counters.has_value()) { packet_.has_ack_ecn = true; } } else if (frame.type == STOP_WAITING_FRAME) { packet_.has_stop_waiting = true; } else if (frame.type == ACK_FREQUENCY_FRAME) { packet_.has_ack_frequency = true; } else if (frame.type == MESSAGE_FRAME) { packet_.has_message = true; } if (debug_delegate_ != nullptr) { debug_delegate_->OnFrameAddedToPacket(frame); } if (transmission_type == NOT_RETRANSMISSION) { packet_.bytes_not_retransmitted.emplace( packet_.bytes_not_retransmitted.value_or(0) + frame_len); } else if (QuicUtils::IsRetransmittableFrame(frame.type)) { packet_.transmission_type = transmission_type; } return true; } void QuicPacketCreator::MaybeAddExtraPaddingForHeaderProtection() { if (!framer_->version().HasHeaderProtection() || needs_full_padding_) { return; } const size_t frame_bytes = PacketSize() - PacketHeaderSize(); if (frame_bytes >= MinPlaintextPacketSize(framer_->version(), GetPacketNumberLength())) { return; } QuicByteCount min_header_protection_padding = MinPlaintextPacketSize(framer_->version(), GetPacketNumberLength()) - frame_bytes; pending_padding_bytes_ = std::max(pending_padding_bytes_, min_header_protection_padding); } bool QuicPacketCreator::MaybeCoalesceStreamFrame(const QuicStreamFrame& frame) { if (queued_frames_.empty() || queued_frames_.back().type != STREAM_FRAME) { return false; } QuicStreamFrame* candidate = &queued_frames_.back().stream_frame; if (candidate->stream_id != frame.stream_id || candidate->offset + candidate->data_length != frame.offset || frame.data_length > BytesFree()) { return false; } candidate->data_length += frame.data_length; candidate->fin = frame.fin; QUICHE_DCHECK_EQ(packet_.retransmittable_frames.back().type, STREAM_FRAME) << ENDPOINT; QuicStreamFrame* retransmittable = &packet_.retransmittable_frames.back().stream_frame; QUICHE_DCHECK_EQ(retransmittable->stream_id, frame.stream_id) << ENDPOINT; QUICHE_DCHECK_EQ(retransmittable->offset + retransmittable->data_length, frame.offset) << ENDPOINT; retransmittable->data_length = candidate->data_length; retransmittable->fin = candidate->fin; packet_size_ += frame.data_length; if (debug_delegate_ != nullptr) { debug_delegate_->OnStreamFrameCoalesced(*candidate); } return true; } bool QuicPacketCreator::RemoveSoftMaxPacketLength() { if (latched_hard_max_packet_length_ == 0) { return false; } if (!CanSetMaxPacketLength()) { return false; } QUIC_DVLOG(1) << ENDPOINT << "Restoring max packet length to: " << latched_hard_max_packet_length_; SetMaxPacketLength(latched_hard_max_packet_length_); latched_hard_max_packet_length_ = 0; return true; } void QuicPacketCreator::MaybeAddPadding() { if (BytesFreeForPadding() == 0) { return; } if (packet_.fate == COALESCE) { needs_full_padding_ = false; } MaybeAddExtraPaddingForHeaderProtection(); QUIC_DVLOG(3) << "MaybeAddPadding for " << packet_.packet_number << ": transmission_type:" << packet_.transmission_type << ", fate:" << packet_.fate << ", needs_full_padding_:" << needs_full_padding_ << ", pending_padding_bytes_:" << pending_padding_bytes_ << ", BytesFree:" << BytesFree(); if (!needs_full_padding_ && pending_padding_bytes_ == 0) { return; } int padding_bytes = -1; if (!needs_full_padding_) { padding_bytes = std::min<int16_t>(pending_padding_bytes_, BytesFreeForPadding()); pending_padding_bytes_ -= padding_bytes; } if (!queued_frames_.empty()) { if (needs_full_padding_) { padding_bytes = BytesFreeForPadding(); } QuicFrame frame{QuicPaddingFrame(padding_bytes)}; queued_frames_.insert(queued_frames_.begin(), frame); packet_size_ += padding_bytes; packet_.nonretransmittable_frames.push_back(frame); if (packet_.transmission_type == NOT_RETRANSMISSION) { packet_.bytes_not_retransmitted.emplace( packet_.bytes_not_retransmitted.value_or(0) + padding_bytes); } } else { bool success = AddFrame(QuicFrame(QuicPaddingFrame(padding_bytes)), packet_.transmission_type); QUIC_BUG_IF(quic_bug_10752_36, !success) << ENDPOINT << "Failed to add padding_bytes: " << padding_bytes << " transmission_type: " << packet_.transmission_type; } } bool QuicPacketCreator::IncludeNonceInPublicHeader() const { return have_diversification_nonce_ && packet_.encryption_level == ENCRYPTION_ZERO_RTT; } bool QuicPacketCreator::IncludeVersionInHeader() const { return packet_.encryption_level < ENCRYPTION_FORWARD_SECURE; } void QuicPacketCreator::AddPendingPadding(QuicByteCount size) { pending_padding_bytes_ += size; QUIC_DVLOG(3) << "After AddPendingPadding(" << size << "), pending_padding_bytes_:" << pending_padding_bytes_; } bool QuicPacketCreator::StreamFrameIsClientHello( const QuicStreamFrame& frame) const { if (framer_->perspective() == Perspective::IS_SERVER || !QuicUtils::IsCryptoStreamId(framer_->transport_version(), frame.stream_id)) { return false; } return packet_.encryption_level == ENCRYPTION_INITIAL; } void QuicPacketCreator::SetServerConnectionIdIncluded( QuicConnectionIdIncluded server_connection_id_included) { QUICHE_DCHECK(server_connection_id_included == CONNECTION_ID_PRESENT || server_connection_id_included == CONNECTION_ID_ABSENT) << ENDPOINT; QUICHE_DCHECK(framer_->perspective() == Perspective::IS_SERVER || server_connection_id_included != CONNECTION_ID_ABSENT) << ENDPOINT; server_connection_id_included_ = server_connection_id_included; } void QuicPacketCreator::SetServerConnectionId( QuicConnectionId server_connection_id) { server_connection_id_ = server_connection_id; } void QuicPacketCreator::SetClientConnectionId( QuicConnectionId client_connection_id) { QUICHE_DCHECK(client_connection_id.IsEmpty() || framer_->version().SupportsClientConnectionIds()) << ENDPOINT; client_connection_id_ = client_connection_id; } QuicPacketLength QuicPacketCreator::GetCurrentLargestMessagePayload() const { const size_t packet_header_size = GetPacketHeaderSize( framer_->transport_version(), GetDestinationConnectionIdLength(), GetSourceConnectionIdLength(), IncludeVersionInHeader(), IncludeNonceInPublicHeader(), GetPacketNumberLength(), quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0, 0, GetLengthLength()); size_t max_plaintext_size = latched_hard_max_packet_length_ == 0 ? max_plaintext_size_ : framer_->GetMaxPlaintextSize(latched_hard_max_packet_length_); size_t largest_frame = max_plaintext_size - std::min(max_plaintext_size, packet_header_size); if (static_cast<QuicByteCount>(largest_frame) > max_datagram_frame_size_) { largest_frame = static_cast<size_t>(max_datagram_frame_size_); } return largest_frame - std::min(largest_frame, kQuicFrameTypeSize); } QuicPacketLength QuicPacketCreator::GetGuaranteedLargestMessagePayload() const { const bool may_include_nonce = framer_->version().handshake_protocol == PROTOCOL_QUIC_CRYPTO && framer_->perspective() == Perspective::IS_SERVER; quiche::QuicheVariableLengthIntegerLength length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0; if (framer_->perspective() == Perspective::IS_CLIENT) { length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2; } if (!QuicVersionHasLongHeaderLengths(framer_->transport_version())) { length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0; } const size_t packet_header_size = GetPacketHeaderSize( framer_->transport_version(), GetDestinationConnectionIdLength(), GetSourceConnectionIdLength(), kIncludeVersion, may_include_nonce, PACKET_4BYTE_PACKET_NUMBER, quiche::VARIABLE_LENGTH_INTEGER_LENGTH_0, 0, length_length); size_t max_plaintext_size = latched_hard_max_packet_length_ == 0 ? max_plaintext_size_ : framer_->GetMaxPlaintextSize(latched_hard_max_packet_length_); size_t largest_frame = max_plaintext_size - std::min(max_plaintext_size, packet_header_size); if (static_cast<QuicByteCount>(largest_frame) > max_datagram_frame_size_) { largest_frame = static_cast<size_t>(max_datagram_frame_size_); } const QuicPacketLength largest_payload = largest_frame - std::min(largest_frame, kQuicFrameTypeSize); QUICHE_DCHECK_LE(largest_payload, GetCurrentLargestMessagePayload()) << ENDPOINT; return largest_payload; } bool QuicPacketCreator::AttemptingToSendUnencryptedStreamData() { if (packet_.encryption_level == ENCRYPTION_ZERO_RTT || packet_.encryption_level == ENCRYPTION_FORWARD_SECURE) { return false; } const std::string error_details = absl::StrCat("Cannot send stream data with level: ", EncryptionLevelToString(packet_.encryption_level)); QUIC_BUG(quic_bug_10752_37) << ENDPOINT << error_details; delegate_->OnUnrecoverableError(QUIC_ATTEMPT_TO_SEND_UNENCRYPTED_STREAM_DATA, error_details); return true; } bool QuicPacketCreator::HasIetfLongHeader() const { return packet_.encryption_level < ENCRYPTION_FORWARD_SECURE; } size_t QuicPacketCreator::MinPlaintextPacketSize( const ParsedQuicVersion& version, QuicPacketNumberLength packet_number_length) { if (!version.HasHeaderProtection()) { return 0; } return (version.UsesTls() ? 4 : 8) - packet_number_length; } QuicPacketNumber QuicPacketCreator::NextSendingPacketNumber() const { if (!packet_number().IsInitialized()) { return framer_->first_sending_packet_number(); } return packet_number() + 1; } bool QuicPacketCreator::PacketFlusherAttached() const { return flusher_attached_; } bool QuicPacketCreator::HasSoftMaxPacketLength() const { return latched_hard_max_packet_length_ != 0; } void QuicPacketCreator::SetDefaultPeerAddress(QuicSocketAddress address) { if (!packet_.peer_address.IsInitialized()) { packet_.peer_address = address; return; } if (packet_.peer_address != address) { FlushCurrentPacket(); packet_.peer_address = address; } } #define ENDPOINT2 \ (creator_->framer_->perspective() == Perspective::IS_SERVER ? "Server: " \ : "Client: ") QuicPacketCreator::ScopedPeerAddressContext::ScopedPeerAddressContext( QuicPacketCreator* creator, QuicSocketAddress address, const QuicConnectionId& client_connection_id, const QuicConnectionId& server_connection_id) : creator_(creator), old_peer_address_(creator_->packet_.peer_address), old_client_connection_id_(creator_->GetClientConnectionId()), old_server_connection_id_(creator_->GetServerConnectionId()) { QUIC_BUG_IF(quic_bug_12398_19, !old_peer_address_.IsInitialized()) << ENDPOINT2 << "Context is used before serialized packet's peer address is " "initialized."; creator_->SetDefaultPeerAddress(address); if (creator_->version().HasIetfQuicFrames()) { if (address == old_peer_address_ && ((client_connection_id.length() != old_client_connection_id_.length()) || (server_connection_id.length() != old_server_connection_id_.length()))) { creator_->FlushCurrentPacket(); } creator_->SetClientConnectionId(client_connection_id); creator_->SetServerConnectionId(server_connection_id); } } QuicPacketCreator::ScopedPeerAddressContext::~ScopedPeerAddressContext() { creator_->SetDefaultPeerAddress(old_peer_address_); if (creator_->version().HasIetfQuicFrames()) { creator_->SetClientConnectionId(old_client_connection_id_); creator_->SetServerConnectionId(old_server_connection_id_); } } QuicPacketCreator::ScopedSerializationFailureHandler:: ScopedSerializationFailureHandler(QuicPacketCreator* creator) : creator_(creator) {} QuicPacketCreator::ScopedSerializationFailureHandler:: ~ScopedSerializationFailureHandler() { if (creator_ == nullptr) { return; } creator_->queued_frames_.clear(); if (creator_->packet_.encrypted_buffer == nullptr) { const std::string error_details = "Failed to SerializePacket."; QUIC_BUG(quic_bug_10752_38) << ENDPOINT2 << error_details; creator_->delegate_->OnUnrecoverableError(QUIC_FAILED_TO_SERIALIZE_PACKET, error_details); } } #undef ENDPOINT2 void QuicPacketCreator::set_encryption_level(EncryptionLevel level) { QUICHE_DCHECK(level == packet_.encryption_level || !HasPendingFrames()) << ENDPOINT << "Cannot update encryption level from " << packet_.encryption_level << " to " << level << " when we already have pending frames: " << QuicFramesToString(queued_frames_); packet_.encryption_level = level; } void QuicPacketCreator::AddPathChallengeFrame( const QuicPathFrameBuffer& payload) { QUIC_BUG_IF(quic_bug_10752_39, !flusher_attached_) << ENDPOINT << "Packet flusher is not attached when " "generator tries to write stream data."; QuicFrame frame(QuicPathChallengeFrame(0, payload)); if (AddPaddedFrameWithRetry(frame)) { return; } QUIC_DVLOG(1) << ENDPOINT << "Can't send PATH_CHALLENGE now"; } bool QuicPacketCreator::AddPathResponseFrame( const QuicPathFrameBuffer& data_buffer) { QuicFrame frame(QuicPathResponseFrame(kInvalidControlFrameId, data_buffer)); if (AddPaddedFrameWithRetry(frame)) { return true; } QUIC_DVLOG(1) << ENDPOINT << "Can't send PATH_RESPONSE now"; return false; } bool QuicPacketCreator::AddPaddedFrameWithRetry(const QuicFrame& frame) { if (HasPendingFrames()) { if (AddPaddedSavedFrame(frame, NOT_RETRANSMISSION)) { return true; } } QUICHE_DCHECK(!HasPendingFrames()) << ENDPOINT; if (!delegate_->ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, NOT_HANDSHAKE)) { return false; } bool success = AddPaddedSavedFrame(frame, NOT_RETRANSMISSION); QUIC_BUG_IF(quic_bug_12398_20, !success) << ENDPOINT; return true; } bool QuicPacketCreator::HasRetryToken() const { return !retry_token_.empty(); } #undef ENDPOINT }
#include "quiche/quic/core/quic_packet_creator.h" #include <cstdint> #include <limits> #include <memory> #include <ostream> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/crypto/quic_decrypter.h" #include "quiche/quic/core/crypto/quic_encrypter.h" #include "quiche/quic/core/frames/quic_frame.h" #include "quiche/quic/core/frames/quic_stream_frame.h" #include "quiche/quic/core/quic_connection_id.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/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/quic_framer_peer.h" #include "quiche/quic/test_tools/quic_packet_creator_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/test_tools/simple_data_producer.h" #include "quiche/quic/test_tools/simple_quic_framer.h" #include "quiche/common/simple_buffer_allocator.h" #include "quiche/common/test_tools/quiche_test_utils.h" using ::testing::_; using ::testing::AtLeast; using ::testing::DoAll; using ::testing::InSequence; using ::testing::Invoke; using ::testing::Return; using ::testing::SaveArg; using ::testing::StrictMock; namespace quic { namespace test { namespace { const QuicPacketNumber kPacketNumber = QuicPacketNumber(UINT64_C(0x12345678)); QuicConnectionId CreateTestConnectionId() { return TestConnectionId(UINT64_C(0xFEDCBA9876543210)); } struct TestParams { TestParams(ParsedQuicVersion version, bool version_serialization) : version(version), version_serialization(version_serialization) {} ParsedQuicVersion version; bool version_serialization; }; std::string PrintToString(const TestParams& p) { return absl::StrCat(ParsedQuicVersionToString(p.version), "_", (p.version_serialization ? "Include" : "No"), "Version"); } std::vector<TestParams> GetTestParams() { std::vector<TestParams> params; ParsedQuicVersionVector all_supported_versions = AllSupportedVersions(); for (size_t i = 0; i < all_supported_versions.size(); ++i) { params.push_back(TestParams(all_supported_versions[i], true)); params.push_back(TestParams(all_supported_versions[i], false)); } return params; } class MockDebugDelegate : public QuicPacketCreator::DebugDelegate { public: ~MockDebugDelegate() override = default; MOCK_METHOD(void, OnFrameAddedToPacket, (const QuicFrame& frame), (override)); MOCK_METHOD(void, OnStreamFrameCoalesced, (const QuicStreamFrame& frame), (override)); }; class TestPacketCreator : public QuicPacketCreator { public: TestPacketCreator(QuicConnectionId connection_id, QuicFramer* framer, DelegateInterface* delegate, SimpleDataProducer* producer) : QuicPacketCreator(connection_id, framer, delegate), producer_(producer), version_(framer->version()) {} bool ConsumeDataToFillCurrentPacket(QuicStreamId id, absl::string_view data, QuicStreamOffset offset, bool fin, bool needs_full_padding, TransmissionType transmission_type, QuicFrame* frame) { if (!data.empty()) { producer_->SaveStreamData(id, data); } return QuicPacketCreator::ConsumeDataToFillCurrentPacket( id, data.length(), offset, fin, needs_full_padding, transmission_type, frame); } void StopSendingVersion() { set_encryption_level(ENCRYPTION_FORWARD_SECURE); } SimpleDataProducer* producer_; ParsedQuicVersion version_; }; class QuicPacketCreatorTest : public QuicTestWithParam<TestParams> { public: void ClearSerializedPacketForTests(SerializedPacket ) { } void SaveSerializedPacket(SerializedPacket serialized_packet) { serialized_packet_.reset(CopySerializedPacket( serialized_packet, &allocator_, true)); } void DeleteSerializedPacket() { serialized_packet_ = nullptr; } protected: QuicPacketCreatorTest() : connection_id_(TestConnectionId(2)), server_framer_(SupportedVersions(GetParam().version), QuicTime::Zero(), Perspective::IS_SERVER, connection_id_.length()), client_framer_(SupportedVersions(GetParam().version), QuicTime::Zero(), Perspective::IS_CLIENT, connection_id_.length()), data_("foo"), creator_(connection_id_, &client_framer_, &delegate_, &producer_) { EXPECT_CALL(delegate_, GetPacketBuffer()) .WillRepeatedly(Return(QuicPacketBuffer())); EXPECT_CALL(delegate_, GetSerializedPacketFate(_, _)) .WillRepeatedly(Return(SEND_TO_WRITER)); creator_.SetEncrypter( ENCRYPTION_INITIAL, std::make_unique<TaggingEncrypter>(ENCRYPTION_INITIAL)); creator_.SetEncrypter( ENCRYPTION_HANDSHAKE, std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE)); creator_.SetEncrypter( ENCRYPTION_ZERO_RTT, std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT)); creator_.SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE)); client_framer_.set_visitor(&framer_visitor_); server_framer_.set_visitor(&framer_visitor_); client_framer_.set_data_producer(&producer_); if (server_framer_.version().KnowsWhichDecrypterToUse()) { server_framer_.InstallDecrypter(ENCRYPTION_INITIAL, std::make_unique<TaggingDecrypter>()); server_framer_.InstallDecrypter(ENCRYPTION_ZERO_RTT, std::make_unique<TaggingDecrypter>()); server_framer_.InstallDecrypter(ENCRYPTION_HANDSHAKE, std::make_unique<TaggingDecrypter>()); server_framer_.InstallDecrypter(ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingDecrypter>()); } else { server_framer_.SetDecrypter(ENCRYPTION_INITIAL, std::make_unique<TaggingDecrypter>()); server_framer_.SetAlternativeDecrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingDecrypter>(), false); } } ~QuicPacketCreatorTest() override {} SerializedPacket SerializeAllFrames(const QuicFrames& frames) { SerializedPacket packet = QuicPacketCreatorPeer::SerializeAllFrames( &creator_, frames, buffer_, kMaxOutgoingPacketSize); EXPECT_EQ(QuicPacketCreatorPeer::GetEncryptionLevel(&creator_), packet.encryption_level); return packet; } void ProcessPacket(const SerializedPacket& packet) { QuicEncryptedPacket encrypted_packet(packet.encrypted_buffer, packet.encrypted_length); server_framer_.ProcessPacket(encrypted_packet); } void CheckStreamFrame(const QuicFrame& frame, QuicStreamId stream_id, const std::string& data, QuicStreamOffset offset, bool fin) { EXPECT_EQ(STREAM_FRAME, frame.type); EXPECT_EQ(stream_id, frame.stream_frame.stream_id); char buf[kMaxOutgoingPacketSize]; QuicDataWriter writer(kMaxOutgoingPacketSize, buf, quiche::HOST_BYTE_ORDER); if (frame.stream_frame.data_length > 0) { producer_.WriteStreamData(stream_id, frame.stream_frame.offset, frame.stream_frame.data_length, &writer); } EXPECT_EQ(data, absl::string_view(buf, frame.stream_frame.data_length)); EXPECT_EQ(offset, frame.stream_frame.offset); EXPECT_EQ(fin, frame.stream_frame.fin); } size_t GetPacketHeaderOverhead(QuicTransportVersion version) { return GetPacketHeaderSize( version, creator_.GetDestinationConnectionIdLength(), creator_.GetSourceConnectionIdLength(), QuicPacketCreatorPeer::SendVersionInPacket(&creator_), !kIncludeDiversificationNonce, QuicPacketCreatorPeer::GetPacketNumberLength(&creator_), QuicPacketCreatorPeer::GetRetryTokenLengthLength(&creator_), 0, QuicPacketCreatorPeer::GetLengthLength(&creator_)); } size_t GetEncryptionOverhead() { return creator_.max_packet_length() - client_framer_.GetMaxPlaintextSize(creator_.max_packet_length()); } size_t GetStreamFrameOverhead(QuicTransportVersion version) { return QuicFramer::GetMinStreamFrameSize( version, GetNthClientInitiatedStreamId(1), kOffset, true, 0); } bool IsDefaultTestConfiguration() { TestParams p = GetParam(); return p.version == AllSupportedVersions()[0] && p.version_serialization; } QuicStreamId GetNthClientInitiatedStreamId(int n) const { return QuicUtils::GetFirstBidirectionalStreamId( creator_.transport_version(), Perspective::IS_CLIENT) + n * 2; } void TestChaosProtection(bool enabled); static constexpr QuicStreamOffset kOffset = 0u; char buffer_[kMaxOutgoingPacketSize]; QuicConnectionId connection_id_; QuicFrames frames_; QuicFramer server_framer_; QuicFramer client_framer_; StrictMock<MockFramerVisitor> framer_visitor_; StrictMock<MockPacketCreatorDelegate> delegate_; std::string data_; TestPacketCreator creator_; std::unique_ptr<SerializedPacket> serialized_packet_; SimpleDataProducer producer_; quiche::SimpleBufferAllocator allocator_; }; INSTANTIATE_TEST_SUITE_P(QuicPacketCreatorTests, QuicPacketCreatorTest, ::testing::ValuesIn(GetTestParams()), ::testing::PrintToStringParamName()); TEST_P(QuicPacketCreatorTest, SerializeFrames) { ParsedQuicVersion version = client_framer_.version(); for (int i = ENCRYPTION_INITIAL; i < NUM_ENCRYPTION_LEVELS; ++i) { EncryptionLevel level = static_cast<EncryptionLevel>(i); bool has_ack = false, has_stream = false; creator_.set_encryption_level(level); size_t payload_len = 0; if (level != ENCRYPTION_ZERO_RTT) { frames_.push_back(QuicFrame(new QuicAckFrame(InitAckFrame(1)))); has_ack = true; payload_len += version.UsesTls() ? 12 : 6; } if (level != ENCRYPTION_INITIAL && level != ENCRYPTION_HANDSHAKE) { QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId( client_framer_.transport_version(), Perspective::IS_CLIENT); frames_.push_back(QuicFrame( QuicStreamFrame(stream_id, false, 0u, absl::string_view()))); has_stream = true; payload_len += 2; } SerializedPacket serialized = SerializeAllFrames(frames_); EXPECT_EQ(level, serialized.encryption_level); if (level != ENCRYPTION_ZERO_RTT) { delete frames_[0].ack_frame; } frames_.clear(); ASSERT_GT(payload_len, 0); size_t min_payload = version.UsesTls() ? 3 : 7; bool need_padding = (version.HasHeaderProtection() && (payload_len < min_payload)); { InSequence s; EXPECT_CALL(framer_visitor_, OnPacket()); EXPECT_CALL(framer_visitor_, OnUnauthenticatedPublicHeader(_)); EXPECT_CALL(framer_visitor_, OnUnauthenticatedHeader(_)); EXPECT_CALL(framer_visitor_, OnDecryptedPacket(_, _)); EXPECT_CALL(framer_visitor_, OnPacketHeader(_)); if (need_padding) { EXPECT_CALL(framer_visitor_, OnPaddingFrame(_)); } if (has_ack) { EXPECT_CALL(framer_visitor_, OnAckFrameStart(_, _)) .WillOnce(Return(true)); EXPECT_CALL(framer_visitor_, OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2))) .WillOnce(Return(true)); EXPECT_CALL(framer_visitor_, OnAckFrameEnd(QuicPacketNumber(1), _)) .WillOnce(Return(true)); } if (has_stream) { EXPECT_CALL(framer_visitor_, OnStreamFrame(_)); } EXPECT_CALL(framer_visitor_, OnPacketComplete()); } ProcessPacket(serialized); } } TEST_P(QuicPacketCreatorTest, SerializeConnectionClose) { QuicConnectionCloseFrame* frame = new QuicConnectionCloseFrame( creator_.transport_version(), QUIC_NO_ERROR, NO_IETF_QUIC_ERROR, "error", 0); QuicFrames frames; frames.push_back(QuicFrame(frame)); SerializedPacket serialized = SerializeAllFrames(frames); EXPECT_EQ(ENCRYPTION_INITIAL, serialized.encryption_level); ASSERT_EQ(QuicPacketNumber(1u), serialized.packet_number); ASSERT_EQ(QuicPacketNumber(1u), creator_.packet_number()); InSequence s; EXPECT_CALL(framer_visitor_, OnPacket()); EXPECT_CALL(framer_visitor_, OnUnauthenticatedPublicHeader(_)); EXPECT_CALL(framer_visitor_, OnUnauthenticatedHeader(_)); EXPECT_CALL(framer_visitor_, OnDecryptedPacket(_, _)); EXPECT_CALL(framer_visitor_, OnPacketHeader(_)); EXPECT_CALL(framer_visitor_, OnConnectionCloseFrame(_)); EXPECT_CALL(framer_visitor_, OnPacketComplete()); ProcessPacket(serialized); } TEST_P(QuicPacketCreatorTest, SerializePacketWithPadding) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); creator_.AddFrame(QuicFrame(QuicWindowUpdateFrame()), NOT_RETRANSMISSION); creator_.AddFrame(QuicFrame(QuicPaddingFrame()), NOT_RETRANSMISSION); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); creator_.FlushCurrentPacket(); ASSERT_TRUE(serialized_packet_->encrypted_buffer); EXPECT_EQ(kDefaultMaxPacketSize, serialized_packet_->encrypted_length); DeleteSerializedPacket(); } TEST_P(QuicPacketCreatorTest, SerializeLargerPacketWithPadding) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); const QuicByteCount packet_size = 100 + kDefaultMaxPacketSize; creator_.SetMaxPacketLength(packet_size); creator_.AddFrame(QuicFrame(QuicWindowUpdateFrame()), NOT_RETRANSMISSION); creator_.AddFrame(QuicFrame(QuicPaddingFrame()), NOT_RETRANSMISSION); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); creator_.FlushCurrentPacket(); ASSERT_TRUE(serialized_packet_->encrypted_buffer); EXPECT_EQ(packet_size, serialized_packet_->encrypted_length); DeleteSerializedPacket(); } TEST_P(QuicPacketCreatorTest, IncreaseMaxPacketLengthWithFramesPending) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); const QuicByteCount packet_size = 100 + kDefaultMaxPacketSize; creator_.AddFrame(QuicFrame(QuicWindowUpdateFrame()), NOT_RETRANSMISSION); creator_.SetMaxPacketLength(packet_size); creator_.AddFrame(QuicFrame(QuicPaddingFrame()), NOT_RETRANSMISSION); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); creator_.FlushCurrentPacket(); ASSERT_TRUE(serialized_packet_->encrypted_buffer); EXPECT_EQ(kDefaultMaxPacketSize, serialized_packet_->encrypted_length); DeleteSerializedPacket(); creator_.AddFrame(QuicFrame(QuicWindowUpdateFrame()), NOT_RETRANSMISSION); creator_.AddFrame(QuicFrame(QuicPaddingFrame()), NOT_RETRANSMISSION); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); creator_.FlushCurrentPacket(); ASSERT_TRUE(serialized_packet_->encrypted_buffer); EXPECT_EQ(packet_size, serialized_packet_->encrypted_length); EXPECT_EQ(packet_size, serialized_packet_->encrypted_length); DeleteSerializedPacket(); } TEST_P(QuicPacketCreatorTest, ConsumeCryptoDataToFillCurrentPacket) { std::string data = "crypto data"; QuicFrame frame; ASSERT_TRUE(creator_.ConsumeCryptoDataToFillCurrentPacket( ENCRYPTION_INITIAL, data.length(), 0, true, NOT_RETRANSMISSION, &frame)); EXPECT_EQ(frame.crypto_frame->data_length, data.length()); EXPECT_TRUE(creator_.HasPendingFrames()); } TEST_P(QuicPacketCreatorTest, ConsumeDataToFillCurrentPacket) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); QuicFrame frame; QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId( client_framer_.transport_version(), Perspective::IS_CLIENT); const std::string data("test"); ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( stream_id, data, 0u, false, false, NOT_RETRANSMISSION, &frame)); size_t consumed = frame.stream_frame.data_length; EXPECT_EQ(4u, consumed); CheckStreamFrame(frame, stream_id, "test", 0u, false); EXPECT_TRUE(creator_.HasPendingFrames()); } TEST_P(QuicPacketCreatorTest, ConsumeDataFin) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); QuicFrame frame; QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId( client_framer_.transport_version(), Perspective::IS_CLIENT); const std::string data("test"); ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( stream_id, data, 0u, true, false, NOT_RETRANSMISSION, &frame)); size_t consumed = frame.stream_frame.data_length; EXPECT_EQ(4u, consumed); CheckStreamFrame(frame, stream_id, "test", 0u, true); EXPECT_TRUE(creator_.HasPendingFrames()); } TEST_P(QuicPacketCreatorTest, ConsumeDataFinOnly) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); QuicFrame frame; QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId( client_framer_.transport_version(), Perspective::IS_CLIENT); ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( stream_id, {}, 0u, true, false, NOT_RETRANSMISSION, &frame)); size_t consumed = frame.stream_frame.data_length; EXPECT_EQ(0u, consumed); CheckStreamFrame(frame, stream_id, std::string(), 0u, true); EXPECT_TRUE(creator_.HasPendingFrames()); EXPECT_TRUE(absl::StartsWith(creator_.GetPendingFramesInfo(), "type { STREAM_FRAME }")); } TEST_P(QuicPacketCreatorTest, CreateAllFreeBytesForStreamFrames) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); const size_t overhead = GetPacketHeaderOverhead(client_framer_.transport_version()) + GetEncryptionOverhead(); for (size_t i = overhead + QuicPacketCreator::MinPlaintextPacketSize( client_framer_.version(), QuicPacketCreatorPeer::GetPacketNumberLength(&creator_)); i < overhead + 100; ++i) { SCOPED_TRACE(i); creator_.SetMaxPacketLength(i); const bool should_have_room = i > overhead + GetStreamFrameOverhead(client_framer_.transport_version()); ASSERT_EQ(should_have_room, creator_.HasRoomForStreamFrame(GetNthClientInitiatedStreamId(1), kOffset, 0xffff)); if (should_have_room) { QuicFrame frame; const std::string data("testdata"); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillRepeatedly(Invoke( this, &QuicPacketCreatorTest::ClearSerializedPacketForTests)); ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( GetNthClientInitiatedStreamId(1), data, kOffset, false, false, NOT_RETRANSMISSION, &frame)); size_t bytes_consumed = frame.stream_frame.data_length; EXPECT_LT(0u, bytes_consumed); creator_.FlushCurrentPacket(); } } } TEST_P(QuicPacketCreatorTest, StreamFrameConsumption) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); const size_t overhead = GetPacketHeaderOverhead(client_framer_.transport_version()) + GetEncryptionOverhead() + GetStreamFrameOverhead(client_framer_.transport_version()); size_t capacity = kDefaultMaxPacketSize - overhead; for (int delta = -5; delta <= 5; ++delta) { std::string data(capacity + delta, 'A'); size_t bytes_free = delta > 0 ? 0 : 0 - delta; QuicFrame frame; ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( GetNthClientInitiatedStreamId(1), data, kOffset, false, false, NOT_RETRANSMISSION, &frame)); EXPECT_EQ(2u, creator_.ExpansionOnNewFrame()); size_t expected_bytes_free = bytes_free < 3 ? 0 : bytes_free - 2; EXPECT_EQ(expected_bytes_free, creator_.BytesFree()) << "delta: " << delta; EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); creator_.FlushCurrentPacket(); ASSERT_TRUE(serialized_packet_->encrypted_buffer); DeleteSerializedPacket(); } } TEST_P(QuicPacketCreatorTest, CryptoStreamFramePacketPadding) { SetQuicFlag(quic_enforce_single_packet_chlo, false); size_t overhead = GetPacketHeaderOverhead(client_framer_.transport_version()) + GetEncryptionOverhead(); if (QuicVersionUsesCryptoFrames(client_framer_.transport_version())) { overhead += QuicFramer::GetMinCryptoFrameSize(kOffset, kMaxOutgoingPacketSize); } else { overhead += QuicFramer::GetMinStreamFrameSize( client_framer_.transport_version(), GetNthClientInitiatedStreamId(1), kOffset, false, 0); } ASSERT_GT(kMaxOutgoingPacketSize, overhead); size_t capacity = kDefaultMaxPacketSize - overhead; for (int delta = -5; delta <= 5; ++delta) { SCOPED_TRACE(delta); std::string data(capacity + delta, 'A'); size_t bytes_free = delta > 0 ? 0 : 0 - delta; QuicFrame frame; EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillRepeatedly( Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); if (client_framer_.version().CanSendCoalescedPackets()) { EXPECT_CALL(delegate_, GetSerializedPacketFate(_, _)) .WillRepeatedly(Return(COALESCE)); } if (!QuicVersionUsesCryptoFrames(client_framer_.transport_version())) { ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( QuicUtils::GetCryptoStreamId(client_framer_.transport_version()), data, kOffset, false, true, NOT_RETRANSMISSION, &frame)); size_t bytes_consumed = frame.stream_frame.data_length; EXPECT_LT(0u, bytes_consumed); } else { producer_.SaveCryptoData(ENCRYPTION_INITIAL, kOffset, data); ASSERT_TRUE(creator_.ConsumeCryptoDataToFillCurrentPacket( ENCRYPTION_INITIAL, data.length(), kOffset, true, NOT_RETRANSMISSION, &frame)); size_t bytes_consumed = frame.crypto_frame->data_length; EXPECT_LT(0u, bytes_consumed); } creator_.FlushCurrentPacket(); ASSERT_TRUE(serialized_packet_->encrypted_buffer); if (client_framer_.version().CanSendCoalescedPackets()) { EXPECT_EQ(kDefaultMaxPacketSize - bytes_free, serialized_packet_->encrypted_length); } else { EXPECT_EQ(kDefaultMaxPacketSize, serialized_packet_->encrypted_length); } DeleteSerializedPacket(); } } TEST_P(QuicPacketCreatorTest, NonCryptoStreamFramePacketNonPadding) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); const size_t overhead = GetPacketHeaderOverhead(client_framer_.transport_version()) + GetEncryptionOverhead() + GetStreamFrameOverhead(client_framer_.transport_version()); ASSERT_GT(kDefaultMaxPacketSize, overhead); size_t capacity = kDefaultMaxPacketSize - overhead; for (int delta = -5; delta <= 5; ++delta) { std::string data(capacity + delta, 'A'); size_t bytes_free = delta > 0 ? 0 : 0 - delta; QuicFrame frame; EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( GetNthClientInitiatedStreamId(1), data, kOffset, false, false, NOT_RETRANSMISSION, &frame)); size_t bytes_consumed = frame.stream_frame.data_length; EXPECT_LT(0u, bytes_consumed); creator_.FlushCurrentPacket(); ASSERT_TRUE(serialized_packet_->encrypted_buffer); if (bytes_free > 0) { EXPECT_EQ(kDefaultMaxPacketSize - bytes_free, serialized_packet_->encrypted_length); } else { EXPECT_EQ(kDefaultMaxPacketSize, serialized_packet_->encrypted_length); } DeleteSerializedPacket(); } } TEST_P(QuicPacketCreatorTest, BuildPathChallengePacket) { if (!VersionHasIetfQuicFrames(creator_.transport_version())) { return; } QuicPacketHeader header; header.destination_connection_id = CreateTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; MockRandom randomizer; QuicPathFrameBuffer payload; randomizer.RandBytes(payload.data(), payload.size()); unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x1a, 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 0x00, 0x00, 0x00, 0x00, 0x00 }; std::unique_ptr<char[]> buffer(new char[kMaxOutgoingPacketSize]); size_t length = creator_.BuildPaddedPathChallengePacket( header, buffer.get(), ABSL_ARRAYSIZE(packet), payload, ENCRYPTION_INITIAL); EXPECT_EQ(length, ABSL_ARRAYSIZE(packet)); EXPECT_EQ(kQuicPathFrameBufferSize, payload.size()); QuicPacket data(creator_.transport_version(), buffer.release(), length, true, header); quiche::test::CompareCharArraysWithHexError( "constructed packet", data.data(), data.length(), reinterpret_cast<char*>(packet), ABSL_ARRAYSIZE(packet)); } TEST_P(QuicPacketCreatorTest, BuildConnectivityProbingPacket) { QuicPacketHeader header; header.destination_connection_id = CreateTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00 }; unsigned char packet99[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 }; unsigned char* p = packet; size_t packet_size = ABSL_ARRAYSIZE(packet); if (creator_.version().HasIetfQuicFrames()) { p = packet99; packet_size = ABSL_ARRAYSIZE(packet99); } std::unique_ptr<char[]> buffer(new char[kMaxOutgoingPacketSize]); size_t length = creator_.BuildConnectivityProbingPacket( header, buffer.get(), packet_size, ENCRYPTION_INITIAL); EXPECT_NE(0u, length); QuicPacket data(creator_.transport_version(), buffer.release(), length, true, header); quiche::test::CompareCharArraysWithHexError( "constructed packet", data.data(), data.length(), reinterpret_cast<char*>(p), packet_size); } TEST_P(QuicPacketCreatorTest, BuildPathResponsePacket1ResponseUnpadded) { if (!VersionHasIetfQuicFrames(creator_.transport_version())) { return; } QuicPacketHeader header; header.destination_connection_id = CreateTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicPathFrameBuffer payload0 = { {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}}; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x1b, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, }; std::unique_ptr<char[]> buffer(new char[kMaxOutgoingPacketSize]); quiche::QuicheCircularDeque<QuicPathFrameBuffer> payloads; payloads.push_back(payload0); size_t length = creator_.BuildPathResponsePacket( header, buffer.get(), ABSL_ARRAYSIZE(packet), payloads, false, ENCRYPTION_INITIAL); EXPECT_EQ(length, ABSL_ARRAYSIZE(packet)); QuicPacket data(creator_.transport_version(), buffer.release(), length, true, header); quiche::test::CompareCharArraysWithHexError( "constructed packet", data.data(), data.length(), reinterpret_cast<char*>(packet), ABSL_ARRAYSIZE(packet)); } TEST_P(QuicPacketCreatorTest, BuildPathResponsePacket1ResponsePadded) { if (!VersionHasIetfQuicFrames(creator_.transport_version())) { return; } QuicPacketHeader header; header.destination_connection_id = CreateTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicPathFrameBuffer payload0 = { {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}}; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x1b, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00 }; std::unique_ptr<char[]> buffer(new char[kMaxOutgoingPacketSize]); quiche::QuicheCircularDeque<QuicPathFrameBuffer> payloads; payloads.push_back(payload0); size_t length = creator_.BuildPathResponsePacket( header, buffer.get(), ABSL_ARRAYSIZE(packet), payloads, true, ENCRYPTION_INITIAL); EXPECT_EQ(length, ABSL_ARRAYSIZE(packet)); QuicPacket data(creator_.transport_version(), buffer.release(), length, true, header); quiche::test::CompareCharArraysWithHexError( "constructed packet", data.data(), data.length(), reinterpret_cast<char*>(packet), ABSL_ARRAYSIZE(packet)); } TEST_P(QuicPacketCreatorTest, BuildPathResponsePacket3ResponsesUnpadded) { if (!VersionHasIetfQuicFrames(creator_.transport_version())) { return; } QuicPacketHeader header; header.destination_connection_id = CreateTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicPathFrameBuffer payload0 = { {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}}; QuicPathFrameBuffer payload1 = { {0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18}}; QuicPathFrameBuffer payload2 = { {0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28}}; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x1b, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x1b, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x1b, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, }; std::unique_ptr<char[]> buffer(new char[kMaxOutgoingPacketSize]); quiche::QuicheCircularDeque<QuicPathFrameBuffer> payloads; payloads.push_back(payload0); payloads.push_back(payload1); payloads.push_back(payload2); size_t length = creator_.BuildPathResponsePacket( header, buffer.get(), ABSL_ARRAYSIZE(packet), payloads, false, ENCRYPTION_INITIAL); EXPECT_EQ(length, ABSL_ARRAYSIZE(packet)); QuicPacket data(creator_.transport_version(), buffer.release(), length, true, header); quiche::test::CompareCharArraysWithHexError( "constructed packet", data.data(), data.length(), reinterpret_cast<char*>(packet), ABSL_ARRAYSIZE(packet)); } TEST_P(QuicPacketCreatorTest, BuildPathResponsePacket3ResponsesPadded) { if (!VersionHasIetfQuicFrames(creator_.transport_version())) { return; } QuicPacketHeader header; header.destination_connection_id = CreateTestConnectionId(); header.reset_flag = false; header.version_flag = false; header.packet_number = kPacketNumber; QuicPathFrameBuffer payload0 = { {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}}; QuicPathFrameBuffer payload1 = { {0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18}}; QuicPathFrameBuffer payload2 = { {0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28}}; unsigned char packet[] = { 0x43, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x12, 0x34, 0x56, 0x78, 0x1b, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x1b, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x1b, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00 }; std::unique_ptr<char[]> buffer(new char[kMaxOutgoingPacketSize]); quiche::QuicheCircularDeque<QuicPathFrameBuffer> payloads; payloads.push_back(payload0); payloads.push_back(payload1); payloads.push_back(payload2); size_t length = creator_.BuildPathResponsePacket( header, buffer.get(), ABSL_ARRAYSIZE(packet), payloads, true, ENCRYPTION_INITIAL); EXPECT_EQ(length, ABSL_ARRAYSIZE(packet)); QuicPacket data(creator_.transport_version(), buffer.release(), length, true, header); quiche::test::CompareCharArraysWithHexError( "constructed packet", data.data(), data.length(), reinterpret_cast<char*>(packet), ABSL_ARRAYSIZE(packet)); } TEST_P(QuicPacketCreatorTest, SerializeConnectivityProbingPacket) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); std::unique_ptr<SerializedPacket> encrypted; if (VersionHasIetfQuicFrames(creator_.transport_version())) { QuicPathFrameBuffer payload = { {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}}; encrypted = creator_.SerializePathChallengeConnectivityProbingPacket(payload); } else { encrypted = creator_.SerializeConnectivityProbingPacket(); } { InSequence s; EXPECT_CALL(framer_visitor_, OnPacket()); EXPECT_CALL(framer_visitor_, OnUnauthenticatedPublicHeader(_)); EXPECT_CALL(framer_visitor_, OnUnauthenticatedHeader(_)); EXPECT_CALL(framer_visitor_, OnDecryptedPacket(_, _)); EXPECT_CALL(framer_visitor_, OnPacketHeader(_)); if (VersionHasIetfQuicFrames(creator_.transport_version())) { EXPECT_CALL(framer_visitor_, OnPathChallengeFrame(_)); EXPECT_CALL(framer_visitor_, OnPaddingFrame(_)); } else { EXPECT_CALL(framer_visitor_, OnPingFrame(_)); EXPECT_CALL(framer_visitor_, OnPaddingFrame(_)); } EXPECT_CALL(framer_visitor_, OnPacketComplete()); } server_framer_.ProcessPacket(QuicEncryptedPacket( encrypted->encrypted_buffer, encrypted->encrypted_length)); } TEST_P(QuicPacketCreatorTest, SerializePathChallengeProbePacket) { if (!VersionHasIetfQuicFrames(creator_.transport_version())) { return; } QuicPathFrameBuffer payload = { {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xee}}; creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); std::unique_ptr<SerializedPacket> encrypted( creator_.SerializePathChallengeConnectivityProbingPacket(payload)); { InSequence s; EXPECT_CALL(framer_visitor_, OnPacket()); EXPECT_CALL(framer_visitor_, OnUnauthenticatedPublicHeader(_)); EXPECT_CALL(framer_visitor_, OnUnauthenticatedHeader(_)); EXPECT_CALL(framer_visitor_, OnDecryptedPacket(_, _)); EXPECT_CALL(framer_visitor_, OnPacketHeader(_)); EXPECT_CALL(framer_visitor_, OnPathChallengeFrame(_)); EXPECT_CALL(framer_visitor_, OnPaddingFrame(_)); EXPECT_CALL(framer_visitor_, OnPacketComplete()); } server_framer_.ProcessPacket(QuicEncryptedPacket( encrypted->encrypted_buffer, encrypted->encrypted_length)); } TEST_P(QuicPacketCreatorTest, SerializePathResponseProbePacket1PayloadPadded) { if (!VersionHasIetfQuicFrames(creator_.transport_version())) { return; } QuicPathFrameBuffer payload0 = { {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xee}}; creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); quiche::QuicheCircularDeque<QuicPathFrameBuffer> payloads; payloads.push_back(payload0); std::unique_ptr<SerializedPacket> encrypted( creator_.SerializePathResponseConnectivityProbingPacket(payloads, true)); { InSequence s; EXPECT_CALL(framer_visitor_, OnPacket()); EXPECT_CALL(framer_visitor_, OnUnauthenticatedPublicHeader(_)); EXPECT_CALL(framer_visitor_, OnUnauthenticatedHeader(_)); EXPECT_CALL(framer_visitor_, OnDecryptedPacket(_, _)); EXPECT_CALL(framer_visitor_, OnPacketHeader(_)); EXPECT_CALL(framer_visitor_, OnPathResponseFrame(_)); EXPECT_CALL(framer_visitor_, OnPaddingFrame(_)); EXPECT_CALL(framer_visitor_, OnPacketComplete()); } server_framer_.ProcessPacket(QuicEncryptedPacket( encrypted->encrypted_buffer, encrypted->encrypted_length)); } TEST_P(QuicPacketCreatorTest, SerializePathResponseProbePacket1PayloadUnPadded) { if (!VersionHasIetfQuicFrames(creator_.transport_version())) { return; } QuicPathFrameBuffer payload0 = { {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xee}}; creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); quiche::QuicheCircularDeque<QuicPathFrameBuffer> payloads; payloads.push_back(payload0); std::unique_ptr<SerializedPacket> encrypted( creator_.SerializePathResponseConnectivityProbingPacket(payloads, false)); { InSequence s; EXPECT_CALL(framer_visitor_, OnPacket()); EXPECT_CALL(framer_visitor_, OnUnauthenticatedPublicHeader(_)); EXPECT_CALL(framer_visitor_, OnUnauthenticatedHeader(_)); EXPECT_CALL(framer_visitor_, OnDecryptedPacket(_, _)); EXPECT_CALL(framer_visitor_, OnPacketHeader(_)); EXPECT_CALL(framer_visitor_, OnPathResponseFrame(_)); EXPECT_CALL(framer_visitor_, OnPacketComplete()); } server_framer_.ProcessPacket(QuicEncryptedPacket( encrypted->encrypted_buffer, encrypted->encrypted_length)); } TEST_P(QuicPacketCreatorTest, SerializePathResponseProbePacket2PayloadsPadded) { if (!VersionHasIetfQuicFrames(creator_.transport_version())) { return; } QuicPathFrameBuffer payload0 = { {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xee}}; QuicPathFrameBuffer payload1 = { {0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xee, 0xde}}; creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); quiche::QuicheCircularDeque<QuicPathFrameBuffer> payloads; payloads.push_back(payload0); payloads.push_back(payload1); std::unique_ptr<SerializedPacket> encrypted( creator_.SerializePathResponseConnectivityProbingPacket(payloads, true)); { InSequence s; EXPECT_CALL(framer_visitor_, OnPacket()); EXPECT_CALL(framer_visitor_, OnUnauthenticatedPublicHeader(_)); EXPECT_CALL(framer_visitor_, OnUnauthenticatedHeader(_)); EXPECT_CALL(framer_visitor_, OnDecryptedPacket(_, _)); EXPECT_CALL(framer_visitor_, OnPacketHeader(_)); EXPECT_CALL(framer_visitor_, OnPathResponseFrame(_)).Times(2); EXPECT_CALL(framer_visitor_, OnPaddingFrame(_)); EXPECT_CALL(framer_visitor_, OnPacketComplete()); } server_framer_.ProcessPacket(QuicEncryptedPacket( encrypted->encrypted_buffer, encrypted->encrypted_length)); } TEST_P(QuicPacketCreatorTest, SerializePathResponseProbePacket2PayloadsUnPadded) { if (!VersionHasIetfQuicFrames(creator_.transport_version())) { return; } QuicPathFrameBuffer payload0 = { {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xee}}; QuicPathFrameBuffer payload1 = { {0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xee, 0xde}}; creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); quiche::QuicheCircularDeque<QuicPathFrameBuffer> payloads; payloads.push_back(payload0); payloads.push_back(payload1); std::unique_ptr<SerializedPacket> encrypted( creator_.SerializePathResponseConnectivityProbingPacket(payloads, false)); { InSequence s; EXPECT_CALL(framer_visitor_, OnPacket()); EXPECT_CALL(framer_visitor_, OnUnauthenticatedPublicHeader(_)); EXPECT_CALL(framer_visitor_, OnUnauthenticatedHeader(_)); EXPECT_CALL(framer_visitor_, OnDecryptedPacket(_, _)); EXPECT_CALL(framer_visitor_, OnPacketHeader(_)); EXPECT_CALL(framer_visitor_, OnPathResponseFrame(_)).Times(2); EXPECT_CALL(framer_visitor_, OnPacketComplete()); } server_framer_.ProcessPacket(QuicEncryptedPacket( encrypted->encrypted_buffer, encrypted->encrypted_length)); } TEST_P(QuicPacketCreatorTest, SerializePathResponseProbePacket3PayloadsPadded) { if (!VersionHasIetfQuicFrames(creator_.transport_version())) { return; } QuicPathFrameBuffer payload0 = { {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xee}}; QuicPathFrameBuffer payload1 = { {0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xee, 0xde}}; QuicPathFrameBuffer payload2 = { {0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xee, 0xde, 0xad}}; creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); quiche::QuicheCircularDeque<QuicPathFrameBuffer> payloads; payloads.push_back(payload0); payloads.push_back(payload1); payloads.push_back(payload2); std::unique_ptr<SerializedPacket> encrypted( creator_.SerializePathResponseConnectivityProbingPacket(payloads, true)); { InSequence s; EXPECT_CALL(framer_visitor_, OnPacket()); EXPECT_CALL(framer_visitor_, OnUnauthenticatedPublicHeader(_)); EXPECT_CALL(framer_visitor_, OnUnauthenticatedHeader(_)); EXPECT_CALL(framer_visitor_, OnDecryptedPacket(_, _)); EXPECT_CALL(framer_visitor_, OnPacketHeader(_)); EXPECT_CALL(framer_visitor_, OnPathResponseFrame(_)).Times(3); EXPECT_CALL(framer_visitor_, OnPaddingFrame(_)); EXPECT_CALL(framer_visitor_, OnPacketComplete()); } server_framer_.ProcessPacket(QuicEncryptedPacket( encrypted->encrypted_buffer, encrypted->encrypted_length)); } TEST_P(QuicPacketCreatorTest, SerializePathResponseProbePacket3PayloadsUnpadded) { if (!VersionHasIetfQuicFrames(creator_.transport_version())) { return; } QuicPathFrameBuffer payload0 = { {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xee}}; QuicPathFrameBuffer payload1 = { {0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xee, 0xde}}; QuicPathFrameBuffer payload2 = { {0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xee, 0xde, 0xad}}; creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); quiche::QuicheCircularDeque<QuicPathFrameBuffer> payloads; payloads.push_back(payload0); payloads.push_back(payload1); payloads.push_back(payload2); std::unique_ptr<SerializedPacket> encrypted( creator_.SerializePathResponseConnectivityProbingPacket(payloads, false)); InSequence s; EXPECT_CALL(framer_visitor_, OnPacket()); EXPECT_CALL(framer_visitor_, OnUnauthenticatedPublicHeader(_)); EXPECT_CALL(framer_visitor_, OnUnauthenticatedHeader(_)); EXPECT_CALL(framer_visitor_, OnDecryptedPacket(_, _)); EXPECT_CALL(framer_visitor_, OnPacketHeader(_)); EXPECT_CALL(framer_visitor_, OnPathResponseFrame(_)).Times(3); EXPECT_CALL(framer_visitor_, OnPacketComplete()); server_framer_.ProcessPacket(QuicEncryptedPacket( encrypted->encrypted_buffer, encrypted->encrypted_length)); } TEST_P(QuicPacketCreatorTest, SerializeLargePacketNumberConnectionClosePacket) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); std::unique_ptr<SerializedPacket> encrypted( creator_.SerializeLargePacketNumberConnectionClosePacket( QuicPacketNumber(1), QUIC_CLIENT_LOST_NETWORK_ACCESS, "QuicPacketCreatorTest")); InSequence s; EXPECT_CALL(framer_visitor_, OnPacket()); EXPECT_CALL(framer_visitor_, OnUnauthenticatedPublicHeader(_)); EXPECT_CALL(framer_visitor_, OnUnauthenticatedHeader(_)); EXPECT_CALL(framer_visitor_, OnDecryptedPacket(_, _)); EXPECT_CALL(framer_visitor_, OnPacketHeader(_)); EXPECT_CALL(framer_visitor_, OnConnectionCloseFrame(_)); EXPECT_CALL(framer_visitor_, OnPacketComplete()); server_framer_.ProcessPacket(QuicEncryptedPacket( encrypted->encrypted_buffer, encrypted->encrypted_length)); } TEST_P(QuicPacketCreatorTest, UpdatePacketSequenceNumberLengthLeastAwaiting) { if (!GetParam().version.SendsVariableLengthPacketNumberInLongHeader()) { EXPECT_EQ(PACKET_4BYTE_PACKET_NUMBER, QuicPacketCreatorPeer::GetPacketNumberLength(&creator_)); creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); } else { EXPECT_EQ(PACKET_1BYTE_PACKET_NUMBER, QuicPacketCreatorPeer::GetPacketNumberLength(&creator_)); } QuicPacketCreatorPeer::SetPacketNumber(&creator_, 64); creator_.UpdatePacketNumberLength(QuicPacketNumber(2), 10000 / kDefaultMaxPacketSize); EXPECT_EQ(PACKET_1BYTE_PACKET_NUMBER, QuicPacketCreatorPeer::GetPacketNumberLength(&creator_)); QuicPacketCreatorPeer::SetPacketNumber(&creator_, 64 * 256); creator_.UpdatePacketNumberLength(QuicPacketNumber(2), 10000 / kDefaultMaxPacketSize); EXPECT_EQ(PACKET_2BYTE_PACKET_NUMBER, QuicPacketCreatorPeer::GetPacketNumberLength(&creator_)); QuicPacketCreatorPeer::SetPacketNumber(&creator_, 64 * 256 * 256); creator_.UpdatePacketNumberLength(QuicPacketNumber(2), 10000 / kDefaultMaxPacketSize); EXPECT_EQ(PACKET_4BYTE_PACKET_NUMBER, QuicPacketCreatorPeer::GetPacketNumberLength(&creator_)); QuicPacketCreatorPeer::SetPacketNumber(&creator_, UINT64_C(64) * 256 * 256 * 256 * 256); creator_.UpdatePacketNumberLength(QuicPacketNumber(2), 10000 / kDefaultMaxPacketSize); EXPECT_EQ(PACKET_6BYTE_PACKET_NUMBER, QuicPacketCreatorPeer::GetPacketNumberLength(&creator_)); } TEST_P(QuicPacketCreatorTest, UpdatePacketSequenceNumberLengthCwnd) { QuicPacketCreatorPeer::SetPacketNumber(&creator_, 1); if (!GetParam().version.SendsVariableLengthPacketNumberInLongHeader()) { EXPECT_EQ(PACKET_4BYTE_PACKET_NUMBER, QuicPacketCreatorPeer::GetPacketNumberLength(&creator_)); creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); } else { EXPECT_EQ(PACKET_1BYTE_PACKET_NUMBER, QuicPacketCreatorPeer::GetPacketNumberLength(&creator_)); } creator_.UpdatePacketNumberLength(QuicPacketNumber(1), 10000 / kDefaultMaxPacketSize); EXPECT_EQ(PACKET_1BYTE_PACKET_NUMBER, QuicPacketCreatorPeer::GetPacketNumberLength(&creator_)); creator_.UpdatePacketNumberLength(QuicPacketNumber(1), 10000 * 256 / kDefaultMaxPacketSize); EXPECT_EQ(PACKET_2BYTE_PACKET_NUMBER, QuicPacketCreatorPeer::GetPacketNumberLength(&creator_)); creator_.UpdatePacketNumberLength(QuicPacketNumber(1), 10000 * 256 * 256 / kDefaultMaxPacketSize); EXPECT_EQ(PACKET_4BYTE_PACKET_NUMBER, QuicPacketCreatorPeer::GetPacketNumberLength(&creator_)); creator_.UpdatePacketNumberLength( QuicPacketNumber(1), UINT64_C(1000) * 256 * 256 * 256 * 256 / kDefaultMaxPacketSize); EXPECT_EQ(PACKET_6BYTE_PACKET_NUMBER, QuicPacketCreatorPeer::GetPacketNumberLength(&creator_)); } TEST_P(QuicPacketCreatorTest, SkipNPacketNumbers) { QuicPacketCreatorPeer::SetPacketNumber(&creator_, 1); if (!GetParam().version.SendsVariableLengthPacketNumberInLongHeader()) { EXPECT_EQ(PACKET_4BYTE_PACKET_NUMBER, QuicPacketCreatorPeer::GetPacketNumberLength(&creator_)); creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); } else { EXPECT_EQ(PACKET_1BYTE_PACKET_NUMBER, QuicPacketCreatorPeer::GetPacketNumberLength(&creator_)); } creator_.SkipNPacketNumbers(63, QuicPacketNumber(2), 10000 / kDefaultMaxPacketSize); EXPECT_EQ(QuicPacketNumber(64), creator_.packet_number()); EXPECT_EQ(PACKET_1BYTE_PACKET_NUMBER, QuicPacketCreatorPeer::GetPacketNumberLength(&creator_)); creator_.SkipNPacketNumbers(64 * 255, QuicPacketNumber(2), 10000 / kDefaultMaxPacketSize); EXPECT_EQ(QuicPacketNumber(64 * 256), creator_.packet_number()); EXPECT_EQ(PACKET_2BYTE_PACKET_NUMBER, QuicPacketCreatorPeer::GetPacketNumberLength(&creator_)); creator_.SkipNPacketNumbers(64 * 256 * 255, QuicPacketNumber(2), 10000 / kDefaultMaxPacketSize); EXPECT_EQ(QuicPacketNumber(64 * 256 * 256), creator_.packet_number()); EXPECT_EQ(PACKET_4BYTE_PACKET_NUMBER, QuicPacketCreatorPeer::GetPacketNumberLength(&creator_)); } TEST_P(QuicPacketCreatorTest, SerializeFrame) { if (!GetParam().version_serialization) { creator_.StopSendingVersion(); } std::string data("test data"); if (!QuicVersionUsesCryptoFrames(client_framer_.transport_version())) { QuicStreamFrame stream_frame( QuicUtils::GetCryptoStreamId(client_framer_.transport_version()), false, 0u, absl::string_view()); frames_.push_back(QuicFrame(stream_frame)); } else { producer_.SaveCryptoData(ENCRYPTION_INITIAL, 0, data); frames_.push_back( QuicFrame(new QuicCryptoFrame(ENCRYPTION_INITIAL, 0, data.length()))); } SerializedPacket serialized = SerializeAllFrames(frames_); QuicPacketHeader header; { InSequence s; EXPECT_CALL(framer_visitor_, OnPacket()); EXPECT_CALL(framer_visitor_, OnUnauthenticatedPublicHeader(_)); EXPECT_CALL(framer_visitor_, OnUnauthenticatedHeader(_)); EXPECT_CALL(framer_visitor_, OnDecryptedPacket(_, _)); EXPECT_CALL(framer_visitor_, OnPacketHeader(_)) .WillOnce(DoAll(SaveArg<0>(&header), Return(true))); if (QuicVersionUsesCryptoFrames(client_framer_.transport_version())) { EXPECT_CALL(framer_visitor_, OnCryptoFrame(_)); } else { EXPECT_CALL(framer_visitor_, OnStreamFrame(_)); } EXPECT_CALL(framer_visitor_, OnPacketComplete()); } ProcessPacket(serialized); EXPECT_EQ(GetParam().version_serialization, header.version_flag); } TEST_P(QuicPacketCreatorTest, SerializeFrameShortData) { if (!GetParam().version_serialization) { creator_.StopSendingVersion(); } std::string data("Hello World!"); if (!QuicVersionUsesCryptoFrames(client_framer_.transport_version())) { QuicStreamFrame stream_frame( QuicUtils::GetCryptoStreamId(client_framer_.transport_version()), false, 0u, absl::string_view()); frames_.push_back(QuicFrame(stream_frame)); } else { producer_.SaveCryptoData(ENCRYPTION_INITIAL, 0, data); frames_.push_back( QuicFrame(new QuicCryptoFrame(ENCRYPTION_INITIAL, 0, data.length()))); } SerializedPacket serialized = SerializeAllFrames(frames_); QuicPacketHeader header; { InSequence s; EXPECT_CALL(framer_visitor_, OnPacket()); EXPECT_CALL(framer_visitor_, OnUnauthenticatedPublicHeader(_)); EXPECT_CALL(framer_visitor_, OnUnauthenticatedHeader(_)); EXPECT_CALL(framer_visitor_, OnDecryptedPacket(_, _)); EXPECT_CALL(framer_visitor_, OnPacketHeader(_)) .WillOnce(DoAll(SaveArg<0>(&header), Return(true))); if (QuicVersionUsesCryptoFrames(client_framer_.transport_version())) { EXPECT_CALL(framer_visitor_, OnCryptoFrame(_)); } else { EXPECT_CALL(framer_visitor_, OnStreamFrame(_)); } EXPECT_CALL(framer_visitor_, OnPacketComplete()); } ProcessPacket(serialized); EXPECT_EQ(GetParam().version_serialization, header.version_flag); } void QuicPacketCreatorTest::TestChaosProtection(bool enabled) { if (!GetParam().version.UsesCryptoFrames()) { return; } MockRandom mock_random(2); QuicPacketCreatorPeer::SetRandom(&creator_, &mock_random); std::string data("ChAoS_ThEoRy!"); producer_.SaveCryptoData(ENCRYPTION_INITIAL, 0, data); frames_.push_back( QuicFrame(new QuicCryptoFrame(ENCRYPTION_INITIAL, 0, data.length()))); frames_.push_back(QuicFrame(QuicPaddingFrame(33))); SerializedPacket serialized = SerializeAllFrames(frames_); EXPECT_CALL(framer_visitor_, OnPacket()); EXPECT_CALL(framer_visitor_, OnUnauthenticatedPublicHeader(_)); EXPECT_CALL(framer_visitor_, OnUnauthenticatedHeader(_)); EXPECT_CALL(framer_visitor_, OnDecryptedPacket(_, _)); EXPECT_CALL(framer_visitor_, OnPacketHeader(_)); if (enabled) { EXPECT_CALL(framer_visitor_, OnCryptoFrame(_)).Times(AtLeast(2)); EXPECT_CALL(framer_visitor_, OnPaddingFrame(_)).Times(AtLeast(2)); EXPECT_CALL(framer_visitor_, OnPingFrame(_)).Times(AtLeast(1)); } else { EXPECT_CALL(framer_visitor_, OnCryptoFrame(_)).Times(1); EXPECT_CALL(framer_visitor_, OnPaddingFrame(_)).Times(1); EXPECT_CALL(framer_visitor_, OnPingFrame(_)).Times(0); } EXPECT_CALL(framer_visitor_, OnPacketComplete()); ProcessPacket(serialized); } TEST_P(QuicPacketCreatorTest, ChaosProtectionEnabled) { TestChaosProtection(true); } TEST_P(QuicPacketCreatorTest, ChaosProtectionDisabled) { SetQuicFlag(quic_enable_chaos_protection, false); TestChaosProtection(false); } TEST_P(QuicPacketCreatorTest, ConsumeDataLargerThanOneStreamFrame) { if (!GetParam().version_serialization) { creator_.StopSendingVersion(); } creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); QuicFrame frame; size_t payload_length = creator_.max_packet_length(); const std::string too_long_payload(payload_length, 'a'); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId( client_framer_.transport_version(), Perspective::IS_CLIENT); ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( stream_id, too_long_payload, 0u, true, false, NOT_RETRANSMISSION, &frame)); size_t consumed = frame.stream_frame.data_length; EXPECT_GT(payload_length, consumed); creator_.FlushCurrentPacket(); DeleteSerializedPacket(); } TEST_P(QuicPacketCreatorTest, AddFrameAndFlush) { if (!GetParam().version_serialization) { creator_.StopSendingVersion(); } const size_t max_plaintext_size = client_framer_.GetMaxPlaintextSize(creator_.max_packet_length()); EXPECT_FALSE(creator_.HasPendingFrames()); creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId( client_framer_.transport_version(), Perspective::IS_CLIENT); if (!QuicVersionUsesCryptoFrames(client_framer_.transport_version())) { stream_id = QuicUtils::GetCryptoStreamId(client_framer_.transport_version()); } EXPECT_FALSE(creator_.HasPendingStreamFramesOfStream(stream_id)); EXPECT_EQ(max_plaintext_size - GetPacketHeaderSize( client_framer_.transport_version(), creator_.GetDestinationConnectionIdLength(), creator_.GetSourceConnectionIdLength(), QuicPacketCreatorPeer::SendVersionInPacket(&creator_), !kIncludeDiversificationNonce, QuicPacketCreatorPeer::GetPacketNumberLength(&creator_), QuicPacketCreatorPeer::GetRetryTokenLengthLength(&creator_), 0, QuicPacketCreatorPeer::GetLengthLength(&creator_)), creator_.BytesFree()); StrictMock<MockDebugDelegate> debug; creator_.set_debug_delegate(&debug); QuicAckFrame ack_frame(InitAckFrame(10u)); EXPECT_CALL(debug, OnFrameAddedToPacket(_)); EXPECT_TRUE(creator_.AddFrame(QuicFrame(&ack_frame), NOT_RETRANSMISSION)); EXPECT_TRUE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingStreamFramesOfStream(stream_id)); QuicFrame frame; const std::string data("test"); EXPECT_CALL(debug, OnFrameAddedToPacket(_)); ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( stream_id, data, 0u, false, false, NOT_RETRANSMISSION, &frame)); size_t consumed = frame.stream_frame.data_length; EXPECT_EQ(4u, consumed); EXPECT_TRUE(creator_.HasPendingFrames()); EXPECT_TRUE(creator_.HasPendingStreamFramesOfStream(stream_id)); QuicPaddingFrame padding_frame; EXPECT_CALL(debug, OnFrameAddedToPacket(_)); EXPECT_TRUE(creator_.AddFrame(QuicFrame(padding_frame), NOT_RETRANSMISSION)); EXPECT_TRUE(creator_.HasPendingFrames()); EXPECT_EQ(0u, creator_.BytesFree()); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); EXPECT_FALSE(creator_.AddFrame(QuicFrame(&ack_frame), NOT_RETRANSMISSION)); ASSERT_TRUE(serialized_packet_->encrypted_buffer); ASSERT_FALSE(serialized_packet_->retransmittable_frames.empty()); const QuicFrames& retransmittable = serialized_packet_->retransmittable_frames; ASSERT_EQ(1u, retransmittable.size()); EXPECT_EQ(STREAM_FRAME, retransmittable[0].type); EXPECT_TRUE(serialized_packet_->has_ack); EXPECT_EQ(QuicPacketNumber(10u), serialized_packet_->largest_acked); DeleteSerializedPacket(); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingStreamFramesOfStream(stream_id)); EXPECT_EQ(max_plaintext_size - GetPacketHeaderSize( client_framer_.transport_version(), creator_.GetDestinationConnectionIdLength(), creator_.GetSourceConnectionIdLength(), QuicPacketCreatorPeer::SendVersionInPacket(&creator_), !kIncludeDiversificationNonce, QuicPacketCreatorPeer::GetPacketNumberLength(&creator_), QuicPacketCreatorPeer::GetRetryTokenLengthLength(&creator_), 0, QuicPacketCreatorPeer::GetLengthLength(&creator_)), creator_.BytesFree()); } TEST_P(QuicPacketCreatorTest, SerializeAndSendStreamFrame) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); if (!GetParam().version_serialization) { creator_.StopSendingVersion(); } EXPECT_FALSE(creator_.HasPendingFrames()); const std::string data("test"); producer_.SaveStreamData(GetNthClientInitiatedStreamId(0), data); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); size_t num_bytes_consumed; StrictMock<MockDebugDelegate> debug; creator_.set_debug_delegate(&debug); EXPECT_CALL(debug, OnFrameAddedToPacket(_)); creator_.CreateAndSerializeStreamFrame( GetNthClientInitiatedStreamId(0), data.length(), 0, 0, true, NOT_RETRANSMISSION, &num_bytes_consumed); EXPECT_EQ(4u, num_bytes_consumed); ASSERT_TRUE(serialized_packet_->encrypted_buffer); ASSERT_FALSE(serialized_packet_->retransmittable_frames.empty()); const QuicFrames& retransmittable = serialized_packet_->retransmittable_frames; ASSERT_EQ(1u, retransmittable.size()); EXPECT_EQ(STREAM_FRAME, retransmittable[0].type); DeleteSerializedPacket(); EXPECT_FALSE(creator_.HasPendingFrames()); } TEST_P(QuicPacketCreatorTest, SerializeStreamFrameWithPadding) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); if (!GetParam().version_serialization) { creator_.StopSendingVersion(); } EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); size_t num_bytes_consumed; creator_.CreateAndSerializeStreamFrame(GetNthClientInitiatedStreamId(0), 0, 0, 0, true, NOT_RETRANSMISSION, &num_bytes_consumed); EXPECT_EQ(0u, num_bytes_consumed); ASSERT_TRUE(serialized_packet_->encrypted_buffer); ASSERT_FALSE(serialized_packet_->retransmittable_frames.empty()); ASSERT_EQ(serialized_packet_->packet_number_length, PACKET_1BYTE_PACKET_NUMBER); { InSequence s; EXPECT_CALL(framer_visitor_, OnPacket()); EXPECT_CALL(framer_visitor_, OnUnauthenticatedPublicHeader(_)); EXPECT_CALL(framer_visitor_, OnUnauthenticatedHeader(_)); EXPECT_CALL(framer_visitor_, OnDecryptedPacket(_, _)); EXPECT_CALL(framer_visitor_, OnPacketHeader(_)); if (client_framer_.version().HasHeaderProtection()) { EXPECT_CALL(framer_visitor_, OnPaddingFrame(_)); EXPECT_CALL(framer_visitor_, OnStreamFrame(_)); } else { EXPECT_CALL(framer_visitor_, OnStreamFrame(_)); } EXPECT_CALL(framer_visitor_, OnPacketComplete()); } ProcessPacket(*serialized_packet_); } TEST_P(QuicPacketCreatorTest, AddUnencryptedStreamDataClosesConnection) { if (!IsDefaultTestConfiguration()) { return; } creator_.set_encryption_level(ENCRYPTION_INITIAL); QuicStreamFrame stream_frame(GetNthClientInitiatedStreamId(0), false, 0u, absl::string_view()); EXPECT_QUIC_BUG( { EXPECT_CALL(delegate_, OnUnrecoverableError(_, _)); creator_.AddFrame(QuicFrame(stream_frame), NOT_RETRANSMISSION); }, "Cannot send stream data with level: ENCRYPTION_INITIAL"); } TEST_P(QuicPacketCreatorTest, SendStreamDataWithEncryptionHandshake) { if (!IsDefaultTestConfiguration()) { return; } creator_.set_encryption_level(ENCRYPTION_HANDSHAKE); QuicStreamFrame stream_frame(GetNthClientInitiatedStreamId(0), false, 0u, absl::string_view()); EXPECT_QUIC_BUG( { EXPECT_CALL(delegate_, OnUnrecoverableError(_, _)); creator_.AddFrame(QuicFrame(stream_frame), NOT_RETRANSMISSION); }, "Cannot send stream data with level: ENCRYPTION_HANDSHAKE"); } TEST_P(QuicPacketCreatorTest, ChloTooLarge) { if (!IsDefaultTestConfiguration()) { return; } if (QuicVersionUsesCryptoFrames(client_framer_.transport_version())) { return; } CryptoHandshakeMessage message; message.set_tag(kCHLO); message.set_minimum_size(kMaxOutgoingPacketSize); CryptoFramer framer; std::unique_ptr<QuicData> message_data; message_data = framer.ConstructHandshakeMessage(message); QuicFrame frame; EXPECT_CALL(delegate_, OnUnrecoverableError(QUIC_CRYPTO_CHLO_TOO_LARGE, _)); EXPECT_QUIC_BUG( creator_.ConsumeDataToFillCurrentPacket( QuicUtils::GetCryptoStreamId(client_framer_.transport_version()), absl::string_view(message_data->data(), message_data->length()), 0u, false, false, NOT_RETRANSMISSION, &frame), "Client hello won't fit in a single packet."); } TEST_P(QuicPacketCreatorTest, PendingPadding) { EXPECT_EQ(0u, creator_.pending_padding_bytes()); creator_.AddPendingPadding(kMaxNumRandomPaddingBytes * 10); EXPECT_EQ(kMaxNumRandomPaddingBytes * 10, creator_.pending_padding_bytes()); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillRepeatedly( Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); while (creator_.pending_padding_bytes() > 0) { creator_.FlushCurrentPacket(); { InSequence s; EXPECT_CALL(framer_visitor_, OnPacket()); EXPECT_CALL(framer_visitor_, OnUnauthenticatedPublicHeader(_)); EXPECT_CALL(framer_visitor_, OnUnauthenticatedHeader(_)); EXPECT_CALL(framer_visitor_, OnDecryptedPacket(_, _)); EXPECT_CALL(framer_visitor_, OnPacketHeader(_)); EXPECT_CALL(framer_visitor_, OnPaddingFrame(_)); EXPECT_CALL(framer_visitor_, OnPacketComplete()); } ProcessPacket(*serialized_packet_); } EXPECT_EQ(0u, creator_.pending_padding_bytes()); } TEST_P(QuicPacketCreatorTest, FullPaddingDoesNotConsumePendingPadding) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); creator_.AddPendingPadding(kMaxNumRandomPaddingBytes); QuicFrame frame; QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId( client_framer_.transport_version(), Perspective::IS_CLIENT); const std::string data("test"); ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( stream_id, data, 0u, false, true, NOT_RETRANSMISSION, &frame)); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); creator_.FlushCurrentPacket(); EXPECT_EQ(kMaxNumRandomPaddingBytes, creator_.pending_padding_bytes()); } TEST_P(QuicPacketCreatorTest, ConsumeDataAndRandomPadding) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); const QuicByteCount kStreamFramePayloadSize = 100u; QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId( client_framer_.transport_version(), Perspective::IS_CLIENT); size_t length = GetPacketHeaderOverhead(client_framer_.transport_version()) + GetEncryptionOverhead() + QuicFramer::GetMinStreamFrameSize( client_framer_.transport_version(), stream_id, 0, true, kStreamFramePayloadSize + 1) + kStreamFramePayloadSize + 1; creator_.SetMaxPacketLength(length); creator_.AddPendingPadding(kMaxNumRandomPaddingBytes); QuicByteCount pending_padding_bytes = creator_.pending_padding_bytes(); QuicFrame frame; char buf[kStreamFramePayloadSize + 1] = {}; EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillRepeatedly( Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); creator_.ConsumeDataToFillCurrentPacket( stream_id, absl::string_view(buf, kStreamFramePayloadSize), 0u, false, false, NOT_RETRANSMISSION, &frame); creator_.FlushCurrentPacket(); EXPECT_EQ(pending_padding_bytes - 1, creator_.pending_padding_bytes()); creator_.ConsumeDataToFillCurrentPacket( stream_id, absl::string_view(buf, kStreamFramePayloadSize + 1), kStreamFramePayloadSize, false, false, NOT_RETRANSMISSION, &frame); creator_.FlushCurrentPacket(); EXPECT_EQ(pending_padding_bytes - 1, creator_.pending_padding_bytes()); while (creator_.pending_padding_bytes() > 0) { creator_.FlushCurrentPacket(); } EXPECT_EQ(0u, creator_.pending_padding_bytes()); } TEST_P(QuicPacketCreatorTest, FlushWithExternalBuffer) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); char* buffer = new char[kMaxOutgoingPacketSize]; QuicPacketBuffer external_buffer = {buffer, [](const char* p) { delete[] p; }}; EXPECT_CALL(delegate_, GetPacketBuffer()).WillOnce(Return(external_buffer)); QuicFrame frame; QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId( client_framer_.transport_version(), Perspective::IS_CLIENT); const std::string data("test"); ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( stream_id, data, 0u, false, true, NOT_RETRANSMISSION, &frame)); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke([&external_buffer](SerializedPacket serialized_packet) { EXPECT_EQ(external_buffer.buffer, serialized_packet.encrypted_buffer); })); creator_.FlushCurrentPacket(); } TEST_P(QuicPacketCreatorTest, IetfAckGapErrorRegression) { QuicAckFrame ack_frame = InitAckFrame({{QuicPacketNumber(60), QuicPacketNumber(61)}, {QuicPacketNumber(125), QuicPacketNumber(126)}}); frames_.push_back(QuicFrame(&ack_frame)); SerializeAllFrames(frames_); } TEST_P(QuicPacketCreatorTest, AddMessageFrame) { if (client_framer_.version().UsesTls()) { creator_.SetMaxDatagramFrameSize(kMaxAcceptedDatagramFrameSize); } creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .Times(3) .WillRepeatedly( Invoke(this, &QuicPacketCreatorTest::ClearSerializedPacketForTests)); EXPECT_TRUE(creator_.HasRoomForMessageFrame( creator_.GetCurrentLargestMessagePayload())); std::string large_message(creator_.GetCurrentLargestMessagePayload(), 'a'); QuicMessageFrame* message_frame = new QuicMessageFrame(1, MemSliceFromString(large_message)); EXPECT_TRUE(creator_.AddFrame(QuicFrame(message_frame), NOT_RETRANSMISSION)); EXPECT_TRUE(creator_.HasPendingFrames()); creator_.FlushCurrentPacket(); QuicMessageFrame* frame2 = new QuicMessageFrame(2, MemSliceFromString("message")); EXPECT_TRUE(creator_.AddFrame(QuicFrame(frame2), NOT_RETRANSMISSION)); EXPECT_TRUE(creator_.HasPendingFrames()); EXPECT_EQ(1u, creator_.ExpansionOnNewFrame()); QuicMessageFrame* frame3 = new QuicMessageFrame(3, MemSliceFromString("message2")); EXPECT_TRUE(creator_.AddFrame(QuicFrame(frame3), NOT_RETRANSMISSION)); EXPECT_EQ(1u, creator_.ExpansionOnNewFrame()); creator_.FlushCurrentPacket(); QuicFrame frame; QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId( client_framer_.transport_version(), Perspective::IS_CLIENT); const std::string data("test"); EXPECT_TRUE(creator_.ConsumeDataToFillCurrentPacket( stream_id, data, 0u, false, false, NOT_RETRANSMISSION, &frame)); QuicMessageFrame* frame4 = new QuicMessageFrame(4, MemSliceFromString("message")); EXPECT_TRUE(creator_.AddFrame(QuicFrame(frame4), NOT_RETRANSMISSION)); EXPECT_TRUE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasRoomForMessageFrame( creator_.GetCurrentLargestMessagePayload())); QuicMessageFrame frame5(5, MemSliceFromString(large_message)); EXPECT_FALSE(creator_.AddFrame(QuicFrame(&frame5), NOT_RETRANSMISSION)); EXPECT_FALSE(creator_.HasPendingFrames()); } TEST_P(QuicPacketCreatorTest, MessageFrameConsumption) { if (client_framer_.version().UsesTls()) { creator_.SetMaxDatagramFrameSize(kMaxAcceptedDatagramFrameSize); } std::string message_data(kDefaultMaxPacketSize, 'a'); for (EncryptionLevel level : {ENCRYPTION_ZERO_RTT, ENCRYPTION_FORWARD_SECURE}) { creator_.set_encryption_level(level); for (size_t message_size = 0; message_size <= creator_.GetCurrentLargestMessagePayload(); ++message_size) { QuicMessageFrame* frame = new QuicMessageFrame(0, MemSliceFromString(absl::string_view( message_data.data(), message_size))); EXPECT_TRUE(creator_.AddFrame(QuicFrame(frame), NOT_RETRANSMISSION)); EXPECT_TRUE(creator_.HasPendingFrames()); size_t expansion_bytes = message_size >= 64 ? 2 : 1; EXPECT_EQ(expansion_bytes, creator_.ExpansionOnNewFrame()); size_t expected_bytes_free = creator_.GetCurrentLargestMessagePayload() - message_size < expansion_bytes ? 0 : creator_.GetCurrentLargestMessagePayload() - expansion_bytes - message_size; EXPECT_EQ(expected_bytes_free, creator_.BytesFree()); EXPECT_LE(creator_.GetGuaranteedLargestMessagePayload(), creator_.GetCurrentLargestMessagePayload()); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); creator_.FlushCurrentPacket(); ASSERT_TRUE(serialized_packet_->encrypted_buffer); DeleteSerializedPacket(); } } } TEST_P(QuicPacketCreatorTest, GetGuaranteedLargestMessagePayload) { ParsedQuicVersion version = GetParam().version; if (version.UsesTls()) { creator_.SetMaxDatagramFrameSize(kMaxAcceptedDatagramFrameSize); } QuicPacketLength expected_largest_payload = 1215; if (version.HasLongHeaderLengths()) { expected_largest_payload -= 2; } if (version.HasLengthPrefixedConnectionIds()) { expected_largest_payload -= 1; } EXPECT_EQ(expected_largest_payload, creator_.GetGuaranteedLargestMessagePayload()); EXPECT_TRUE(creator_.HasRoomForMessageFrame( creator_.GetGuaranteedLargestMessagePayload())); creator_.SetMaxDatagramFrameSize(expected_largest_payload + 1 + kQuicFrameTypeSize); EXPECT_EQ(expected_largest_payload, creator_.GetGuaranteedLargestMessagePayload()); EXPECT_TRUE(creator_.HasRoomForMessageFrame( creator_.GetGuaranteedLargestMessagePayload())); creator_.SetMaxDatagramFrameSize(expected_largest_payload + kQuicFrameTypeSize); EXPECT_EQ(expected_largest_payload, creator_.GetGuaranteedLargestMessagePayload()); EXPECT_TRUE(creator_.HasRoomForMessageFrame( creator_.GetGuaranteedLargestMessagePayload())); creator_.SetMaxDatagramFrameSize(expected_largest_payload - 1 + kQuicFrameTypeSize); EXPECT_EQ(expected_largest_payload - 1, creator_.GetGuaranteedLargestMessagePayload()); EXPECT_TRUE(creator_.HasRoomForMessageFrame( creator_.GetGuaranteedLargestMessagePayload())); constexpr QuicPacketLength kFrameSizeLimit = 1000; constexpr QuicPacketLength kPayloadSizeLimit = kFrameSizeLimit - kQuicFrameTypeSize; creator_.SetMaxDatagramFrameSize(kFrameSizeLimit); EXPECT_EQ(creator_.GetGuaranteedLargestMessagePayload(), kPayloadSizeLimit); EXPECT_TRUE(creator_.HasRoomForMessageFrame(kPayloadSizeLimit)); EXPECT_FALSE(creator_.HasRoomForMessageFrame(kPayloadSizeLimit + 1)); } TEST_P(QuicPacketCreatorTest, GetCurrentLargestMessagePayload) { ParsedQuicVersion version = GetParam().version; if (version.UsesTls()) { creator_.SetMaxDatagramFrameSize(kMaxAcceptedDatagramFrameSize); } QuicPacketLength expected_largest_payload = 1215; if (version.SendsVariableLengthPacketNumberInLongHeader()) { expected_largest_payload += 3; } if (version.HasLongHeaderLengths()) { expected_largest_payload -= 2; } if (version.HasLengthPrefixedConnectionIds()) { expected_largest_payload -= 1; } EXPECT_EQ(expected_largest_payload, creator_.GetCurrentLargestMessagePayload()); creator_.SetMaxDatagramFrameSize(expected_largest_payload + 1 + kQuicFrameTypeSize); EXPECT_EQ(expected_largest_payload, creator_.GetCurrentLargestMessagePayload()); creator_.SetMaxDatagramFrameSize(expected_largest_payload + kQuicFrameTypeSize); EXPECT_EQ(expected_largest_payload, creator_.GetCurrentLargestMessagePayload()); creator_.SetMaxDatagramFrameSize(expected_largest_payload - 1 + kQuicFrameTypeSize); EXPECT_EQ(expected_largest_payload - 1, creator_.GetCurrentLargestMessagePayload()); } TEST_P(QuicPacketCreatorTest, PacketTransmissionType) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); QuicAckFrame temp_ack_frame = InitAckFrame(1); QuicFrame ack_frame(&temp_ack_frame); ASSERT_FALSE(QuicUtils::IsRetransmittableFrame(ack_frame.type)); QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId( client_framer_.transport_version(), Perspective::IS_CLIENT); QuicFrame stream_frame(QuicStreamFrame(stream_id, false, 0u, absl::string_view())); ASSERT_TRUE(QuicUtils::IsRetransmittableFrame(stream_frame.type)); QuicFrame stream_frame_2(QuicStreamFrame(stream_id, false, 1u, absl::string_view())); QuicFrame padding_frame{QuicPaddingFrame()}; ASSERT_FALSE(QuicUtils::IsRetransmittableFrame(padding_frame.type)); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); EXPECT_TRUE(creator_.AddFrame(ack_frame, LOSS_RETRANSMISSION)); ASSERT_EQ(serialized_packet_, nullptr); EXPECT_TRUE(creator_.AddFrame(stream_frame, PTO_RETRANSMISSION)); ASSERT_EQ(serialized_packet_, nullptr); EXPECT_TRUE(creator_.AddFrame(stream_frame_2, PATH_RETRANSMISSION)); ASSERT_EQ(serialized_packet_, nullptr); EXPECT_TRUE(creator_.AddFrame(padding_frame, PTO_RETRANSMISSION)); creator_.FlushCurrentPacket(); ASSERT_TRUE(serialized_packet_->encrypted_buffer); EXPECT_EQ(serialized_packet_->transmission_type, PATH_RETRANSMISSION); DeleteSerializedPacket(); } TEST_P(QuicPacketCreatorTest, PacketBytesRetransmitted_AddFrame_Retransmission) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); QuicAckFrame temp_ack_frame = InitAckFrame(1); QuicFrame ack_frame(&temp_ack_frame); EXPECT_TRUE(creator_.AddFrame(ack_frame, LOSS_RETRANSMISSION)); QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId( client_framer_.transport_version(), Perspective::IS_CLIENT); QuicFrame stream_frame; const std::string data("data"); ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( stream_id, data, 0u, false, false, PTO_RETRANSMISSION, &stream_frame)); EXPECT_EQ(4u, stream_frame.stream_frame.data_length); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); creator_.FlushCurrentPacket(); ASSERT_TRUE(serialized_packet_->encrypted_buffer); ASSERT_FALSE(serialized_packet_->bytes_not_retransmitted.has_value()); DeleteSerializedPacket(); } TEST_P(QuicPacketCreatorTest, PacketBytesRetransmitted_AddFrame_NotRetransmission) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); QuicAckFrame temp_ack_frame = InitAckFrame(1); QuicFrame ack_frame(&temp_ack_frame); EXPECT_TRUE(creator_.AddFrame(ack_frame, NOT_RETRANSMISSION)); QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId( client_framer_.transport_version(), Perspective::IS_CLIENT); QuicFrame stream_frame; const std::string data("data"); ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( stream_id, data, 0u, false, false, NOT_RETRANSMISSION, &stream_frame)); EXPECT_EQ(4u, stream_frame.stream_frame.data_length); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); creator_.FlushCurrentPacket(); ASSERT_TRUE(serialized_packet_->encrypted_buffer); ASSERT_FALSE(serialized_packet_->bytes_not_retransmitted.has_value()); DeleteSerializedPacket(); } TEST_P(QuicPacketCreatorTest, PacketBytesRetransmitted_AddFrame_MixedFrames) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); QuicAckFrame temp_ack_frame = InitAckFrame(1); QuicFrame ack_frame(&temp_ack_frame); EXPECT_TRUE(creator_.AddFrame(ack_frame, NOT_RETRANSMISSION)); QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId( client_framer_.transport_version(), Perspective::IS_CLIENT); QuicFrame stream_frame; const std::string data("data"); ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( stream_id, data, 0u, false, false, NOT_RETRANSMISSION, &stream_frame)); EXPECT_EQ(4u, stream_frame.stream_frame.data_length); QuicFrame stream_frame2; ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( stream_id, data, 0u, false, false, LOSS_RETRANSMISSION, &stream_frame2)); EXPECT_EQ(4u, stream_frame2.stream_frame.data_length); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); creator_.FlushCurrentPacket(); ASSERT_TRUE(serialized_packet_->encrypted_buffer); ASSERT_TRUE(serialized_packet_->bytes_not_retransmitted.has_value()); ASSERT_GE(serialized_packet_->bytes_not_retransmitted.value(), 4u); DeleteSerializedPacket(); } TEST_P(QuicPacketCreatorTest, PacketBytesRetransmitted_CreateAndSerializeStreamFrame_Retransmission) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); const std::string data("test"); producer_.SaveStreamData(GetNthClientInitiatedStreamId(0), data); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); size_t num_bytes_consumed; creator_.CreateAndSerializeStreamFrame( GetNthClientInitiatedStreamId(0), data.length(), 0, 0, true, LOSS_RETRANSMISSION, &num_bytes_consumed); EXPECT_EQ(4u, num_bytes_consumed); ASSERT_TRUE(serialized_packet_->encrypted_buffer); ASSERT_FALSE(serialized_packet_->bytes_not_retransmitted.has_value()); DeleteSerializedPacket(); EXPECT_FALSE(creator_.HasPendingFrames()); } TEST_P( QuicPacketCreatorTest, PacketBytesRetransmitted_CreateAndSerializeStreamFrame_NotRetransmission) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); const std::string data("test"); producer_.SaveStreamData(GetNthClientInitiatedStreamId(0), data); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); size_t num_bytes_consumed; creator_.CreateAndSerializeStreamFrame( GetNthClientInitiatedStreamId(0), data.length(), 0, 0, true, NOT_RETRANSMISSION, &num_bytes_consumed); EXPECT_EQ(4u, num_bytes_consumed); ASSERT_TRUE(serialized_packet_->encrypted_buffer); ASSERT_FALSE(serialized_packet_->bytes_not_retransmitted.has_value()); DeleteSerializedPacket(); EXPECT_FALSE(creator_.HasPendingFrames()); } TEST_P(QuicPacketCreatorTest, RetryToken) { if (!GetParam().version_serialization || !QuicVersionHasLongHeaderLengths(client_framer_.transport_version())) { return; } char retry_token_bytes[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; creator_.SetRetryToken( std::string(retry_token_bytes, sizeof(retry_token_bytes))); frames_.push_back(QuicFrame(QuicPingFrame())); SerializedPacket serialized = SerializeAllFrames(frames_); QuicPacketHeader header; { InSequence s; EXPECT_CALL(framer_visitor_, OnPacket()); EXPECT_CALL(framer_visitor_, OnUnauthenticatedPublicHeader(_)); EXPECT_CALL(framer_visitor_, OnUnauthenticatedHeader(_)); EXPECT_CALL(framer_visitor_, OnDecryptedPacket(_, _)); EXPECT_CALL(framer_visitor_, OnPacketHeader(_)) .WillOnce(DoAll(SaveArg<0>(&header), Return(true))); if (client_framer_.version().HasHeaderProtection()) { EXPECT_CALL(framer_visitor_, OnPaddingFrame(_)); } EXPECT_CALL(framer_visitor_, OnPingFrame(_)); EXPECT_CALL(framer_visitor_, OnPacketComplete()); } ProcessPacket(serialized); ASSERT_TRUE(header.version_flag); ASSERT_EQ(header.long_packet_type, INITIAL); ASSERT_EQ(header.retry_token.length(), sizeof(retry_token_bytes)); quiche::test::CompareCharArraysWithHexError( "retry token", header.retry_token.data(), header.retry_token.length(), retry_token_bytes, sizeof(retry_token_bytes)); } TEST_P(QuicPacketCreatorTest, GetConnectionId) { EXPECT_EQ(TestConnectionId(2), creator_.GetDestinationConnectionId()); EXPECT_EQ(EmptyQuicConnectionId(), creator_.GetSourceConnectionId()); } TEST_P(QuicPacketCreatorTest, ClientConnectionId) { if (!client_framer_.version().SupportsClientConnectionIds()) { return; } EXPECT_EQ(TestConnectionId(2), creator_.GetDestinationConnectionId()); EXPECT_EQ(EmptyQuicConnectionId(), creator_.GetSourceConnectionId()); creator_.SetClientConnectionId(TestConnectionId(0x33)); EXPECT_EQ(TestConnectionId(2), creator_.GetDestinationConnectionId()); EXPECT_EQ(TestConnectionId(0x33), creator_.GetSourceConnectionId()); } TEST_P(QuicPacketCreatorTest, CoalesceStreamFrames) { InSequence s; if (!GetParam().version_serialization) { creator_.StopSendingVersion(); } const size_t max_plaintext_size = client_framer_.GetMaxPlaintextSize(creator_.max_packet_length()); EXPECT_FALSE(creator_.HasPendingFrames()); creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); QuicStreamId stream_id1 = QuicUtils::GetFirstBidirectionalStreamId( client_framer_.transport_version(), Perspective::IS_CLIENT); QuicStreamId stream_id2 = GetNthClientInitiatedStreamId(1); EXPECT_FALSE(creator_.HasPendingStreamFramesOfStream(stream_id1)); EXPECT_EQ(max_plaintext_size - GetPacketHeaderSize( client_framer_.transport_version(), creator_.GetDestinationConnectionIdLength(), creator_.GetSourceConnectionIdLength(), QuicPacketCreatorPeer::SendVersionInPacket(&creator_), !kIncludeDiversificationNonce, QuicPacketCreatorPeer::GetPacketNumberLength(&creator_), QuicPacketCreatorPeer::GetRetryTokenLengthLength(&creator_), 0, QuicPacketCreatorPeer::GetLengthLength(&creator_)), creator_.BytesFree()); StrictMock<MockDebugDelegate> debug; creator_.set_debug_delegate(&debug); QuicFrame frame; const std::string data1("test"); EXPECT_CALL(debug, OnFrameAddedToPacket(_)); ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( stream_id1, data1, 0u, false, false, NOT_RETRANSMISSION, &frame)); EXPECT_TRUE(creator_.HasPendingFrames()); EXPECT_TRUE(creator_.HasPendingStreamFramesOfStream(stream_id1)); const std::string data2("coalesce"); const auto previous_size = creator_.PacketSize(); QuicStreamFrame target(stream_id1, true, 0, data1.length() + data2.length()); EXPECT_CALL(debug, OnStreamFrameCoalesced(target)); ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( stream_id1, data2, 4u, true, false, NOT_RETRANSMISSION, &frame)); EXPECT_EQ(frame.stream_frame.data_length, creator_.PacketSize() - previous_size); const auto length = creator_.BytesFree() - 10u; const std::string data3(length, 'x'); EXPECT_CALL(debug, OnFrameAddedToPacket(_)); ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( stream_id2, data3, 0u, false, false, NOT_RETRANSMISSION, &frame)); EXPECT_TRUE(creator_.HasPendingStreamFramesOfStream(stream_id2)); EXPECT_CALL(debug, OnStreamFrameCoalesced(_)); const std::string data4("somerandomdata"); ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( stream_id2, data4, length, false, false, NOT_RETRANSMISSION, &frame)); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); creator_.FlushCurrentPacket(); EXPECT_CALL(framer_visitor_, OnPacket()); EXPECT_CALL(framer_visitor_, OnUnauthenticatedPublicHeader(_)); EXPECT_CALL(framer_visitor_, OnUnauthenticatedHeader(_)); EXPECT_CALL(framer_visitor_, OnDecryptedPacket(_, _)); EXPECT_CALL(framer_visitor_, OnPacketHeader(_)); EXPECT_CALL(framer_visitor_, OnStreamFrame(_)); EXPECT_CALL(framer_visitor_, OnStreamFrame(_)); EXPECT_CALL(framer_visitor_, OnPacketComplete()); ProcessPacket(*serialized_packet_); } TEST_P(QuicPacketCreatorTest, SaveNonRetransmittableFrames) { QuicAckFrame ack_frame(InitAckFrame(1)); frames_.push_back(QuicFrame(&ack_frame)); frames_.push_back(QuicFrame(QuicPaddingFrame(-1))); SerializedPacket serialized = SerializeAllFrames(frames_); ASSERT_EQ(2u, serialized.nonretransmittable_frames.size()); EXPECT_EQ(ACK_FRAME, serialized.nonretransmittable_frames[0].type); EXPECT_EQ(PADDING_FRAME, serialized.nonretransmittable_frames[1].type); EXPECT_LT( 0, serialized.nonretransmittable_frames[1].padding_frame.num_padding_bytes); frames_.clear(); SerializedPacket packet = QuicPacketCreatorPeer::SerializeAllFrames( &creator_, serialized.nonretransmittable_frames, buffer_, kMaxOutgoingPacketSize); EXPECT_EQ(serialized.encrypted_length, packet.encrypted_length); } TEST_P(QuicPacketCreatorTest, SerializeCoalescedPacket) { QuicCoalescedPacket coalesced; quiche::SimpleBufferAllocator allocator; QuicSocketAddress self_address(QuicIpAddress::Loopback4(), 1); QuicSocketAddress peer_address(QuicIpAddress::Loopback4(), 2); for (size_t i = ENCRYPTION_INITIAL; i < NUM_ENCRYPTION_LEVELS; ++i) { EncryptionLevel level = static_cast<EncryptionLevel>(i); creator_.set_encryption_level(level); QuicAckFrame ack_frame(InitAckFrame(1)); if (level != ENCRYPTION_ZERO_RTT) { frames_.push_back(QuicFrame(&ack_frame)); } if (level != ENCRYPTION_INITIAL && level != ENCRYPTION_HANDSHAKE) { frames_.push_back( QuicFrame(QuicStreamFrame(1, false, 0u, absl::string_view()))); } SerializedPacket serialized = SerializeAllFrames(frames_); EXPECT_EQ(level, serialized.encryption_level); frames_.clear(); ASSERT_TRUE(coalesced.MaybeCoalescePacket( serialized, self_address, peer_address, &allocator, creator_.max_packet_length(), ECN_NOT_ECT)); } char buffer[kMaxOutgoingPacketSize]; size_t coalesced_length = creator_.SerializeCoalescedPacket( coalesced, buffer, kMaxOutgoingPacketSize); ASSERT_EQ(coalesced.max_packet_length(), coalesced_length); if (!QuicVersionHasLongHeaderLengths(server_framer_.transport_version())) { return; } std::unique_ptr<QuicEncryptedPacket> packets[NUM_ENCRYPTION_LEVELS]; packets[ENCRYPTION_INITIAL] = std::make_unique<QuicEncryptedPacket>(buffer, coalesced_length); for (size_t i = ENCRYPTION_INITIAL; i < NUM_ENCRYPTION_LEVELS; ++i) { InSequence s; EXPECT_CALL(framer_visitor_, OnPacket()); EXPECT_CALL(framer_visitor_, OnUnauthenticatedPublicHeader(_)); if (i < ENCRYPTION_FORWARD_SECURE) { EXPECT_CALL(framer_visitor_, OnCoalescedPacket(_)) .WillOnce(Invoke([i, &packets](const QuicEncryptedPacket& packet) { packets[i + 1] = packet.Clone(); })); } EXPECT_CALL(framer_visitor_, OnUnauthenticatedHeader(_)); EXPECT_CALL(framer_visitor_, OnDecryptedPacket(_, _)); EXPECT_CALL(framer_visitor_, OnPacketHeader(_)); if (i != ENCRYPTION_ZERO_RTT) { if (i != ENCRYPTION_INITIAL) { EXPECT_CALL(framer_visitor_, OnPaddingFrame(_)) .Times(testing::AtMost(1)); } EXPECT_CALL(framer_visitor_, OnAckFrameStart(_, _)) .WillOnce(Return(true)); EXPECT_CALL(framer_visitor_, OnAckRange(QuicPacketNumber(1), QuicPacketNumber(2))) .WillOnce(Return(true)); EXPECT_CALL(framer_visitor_, OnAckFrameEnd(_, _)).WillOnce(Return(true)); } if (i == ENCRYPTION_INITIAL) { EXPECT_CALL(framer_visitor_, OnPaddingFrame(_)); } if (i == ENCRYPTION_ZERO_RTT) { EXPECT_CALL(framer_visitor_, OnPaddingFrame(_)); } if (i != ENCRYPTION_INITIAL && i != ENCRYPTION_HANDSHAKE) { EXPECT_CALL(framer_visitor_, OnStreamFrame(_)); } EXPECT_CALL(framer_visitor_, OnPacketComplete()); server_framer_.ProcessPacket(*packets[i]); } } TEST_P(QuicPacketCreatorTest, SoftMaxPacketLength) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); QuicByteCount previous_max_packet_length = creator_.max_packet_length(); const size_t overhead = GetPacketHeaderOverhead(client_framer_.transport_version()) + QuicPacketCreator::MinPlaintextPacketSize( client_framer_.version(), QuicPacketCreatorPeer::GetPacketNumberLength(&creator_)) + GetEncryptionOverhead(); creator_.SetSoftMaxPacketLength(overhead - 1); EXPECT_EQ(previous_max_packet_length, creator_.max_packet_length()); creator_.SetSoftMaxPacketLength(overhead); EXPECT_EQ(overhead, creator_.max_packet_length()); ASSERT_TRUE(creator_.HasRoomForStreamFrame( GetNthClientInitiatedStreamId(1), kMaxIetfVarInt, std::numeric_limits<uint32_t>::max())); EXPECT_EQ(previous_max_packet_length, creator_.max_packet_length()); creator_.SetSoftMaxPacketLength(overhead); if (client_framer_.version().UsesTls()) { creator_.SetMaxDatagramFrameSize(kMaxAcceptedDatagramFrameSize); } EXPECT_LT(1u, creator_.GetCurrentLargestMessagePayload()); EXPECT_EQ(overhead, creator_.max_packet_length()); ASSERT_TRUE(creator_.HasRoomForMessageFrame( creator_.GetCurrentLargestMessagePayload())); EXPECT_EQ(previous_max_packet_length, creator_.max_packet_length()); creator_.SetSoftMaxPacketLength(overhead); EXPECT_EQ(overhead, creator_.max_packet_length()); const std::string data = "crypto data"; QuicFrame frame; if (!QuicVersionUsesCryptoFrames(client_framer_.transport_version())) { ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( QuicUtils::GetCryptoStreamId(client_framer_.transport_version()), data, kOffset, false, true, NOT_RETRANSMISSION, &frame)); size_t bytes_consumed = frame.stream_frame.data_length; EXPECT_LT(0u, bytes_consumed); } else { producer_.SaveCryptoData(ENCRYPTION_INITIAL, kOffset, data); ASSERT_TRUE(creator_.ConsumeCryptoDataToFillCurrentPacket( ENCRYPTION_INITIAL, data.length(), kOffset, true, NOT_RETRANSMISSION, &frame)); size_t bytes_consumed = frame.crypto_frame->data_length; EXPECT_LT(0u, bytes_consumed); } EXPECT_TRUE(creator_.HasPendingFrames()); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); creator_.FlushCurrentPacket(); creator_.SetSoftMaxPacketLength(overhead); EXPECT_EQ(overhead, creator_.max_packet_length()); QuicAckFrame ack_frame(InitAckFrame(10u)); EXPECT_TRUE(creator_.AddFrame(QuicFrame(&ack_frame), NOT_RETRANSMISSION)); EXPECT_TRUE(creator_.HasPendingFrames()); } TEST_P(QuicPacketCreatorTest, ChangingEncryptionLevelRemovesSoftMaxPacketLength) { if (!client_framer_.version().CanSendCoalescedPackets()) { return; } creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); const QuicByteCount previous_max_packet_length = creator_.max_packet_length(); const size_t min_acceptable_packet_size = GetPacketHeaderOverhead(client_framer_.transport_version()) + QuicPacketCreator::MinPlaintextPacketSize( client_framer_.version(), QuicPacketCreatorPeer::GetPacketNumberLength(&creator_)) + GetEncryptionOverhead(); creator_.SetSoftMaxPacketLength(min_acceptable_packet_size); EXPECT_EQ(creator_.max_packet_length(), min_acceptable_packet_size); creator_.set_encryption_level(ENCRYPTION_HANDSHAKE); QuicAckFrame ack_frame(InitAckFrame(1)); frames_.push_back(QuicFrame(&ack_frame)); SerializedPacket serialized = SerializeAllFrames(frames_); EXPECT_EQ(serialized.encryption_level, ENCRYPTION_HANDSHAKE); EXPECT_EQ(creator_.max_packet_length(), previous_max_packet_length); } TEST_P(QuicPacketCreatorTest, MinPayloadLength) { ParsedQuicVersion version = client_framer_.version(); for (QuicPacketNumberLength pn_length : {PACKET_1BYTE_PACKET_NUMBER, PACKET_2BYTE_PACKET_NUMBER, PACKET_3BYTE_PACKET_NUMBER, PACKET_4BYTE_PACKET_NUMBER}) { if (!version.HasHeaderProtection()) { EXPECT_EQ(creator_.MinPlaintextPacketSize(version, pn_length), 0); } else { EXPECT_EQ(creator_.MinPlaintextPacketSize(version, pn_length), (version.UsesTls() ? 4 : 8) - pn_length); } } } TEST_P(QuicPacketCreatorTest, PadWhenAlmostMaxLength) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); const size_t overhead = GetPacketHeaderOverhead(client_framer_.transport_version()) + GetEncryptionOverhead() + GetStreamFrameOverhead(client_framer_.transport_version()); size_t capacity = kDefaultMaxPacketSize - overhead; for (size_t bytes_free = 1; bytes_free <= 2; bytes_free++) { std::string data(capacity - bytes_free, 'A'); QuicFrame frame; ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( GetNthClientInitiatedStreamId(1), data, kOffset, false, true, NOT_RETRANSMISSION, &frame)); EXPECT_EQ(2u, creator_.ExpansionOnNewFrame()); EXPECT_EQ(0u, creator_.BytesFree()); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); creator_.FlushCurrentPacket(); EXPECT_EQ(serialized_packet_->encrypted_length, kDefaultMaxPacketSize); DeleteSerializedPacket(); } } TEST_P(QuicPacketCreatorTest, MorePendingPaddingThanBytesFree) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); const size_t overhead = GetPacketHeaderOverhead(client_framer_.transport_version()) + GetEncryptionOverhead() + GetStreamFrameOverhead(client_framer_.transport_version()); size_t capacity = kDefaultMaxPacketSize - overhead; const size_t pending_padding = 10; std::string data(capacity - pending_padding, 'A'); QuicFrame frame; ASSERT_TRUE(creator_.ConsumeDataToFillCurrentPacket( GetNthClientInitiatedStreamId(1), data, kOffset, false, false, NOT_RETRANSMISSION, &frame)); creator_.AddPendingPadding(pending_padding); EXPECT_EQ(2u, creator_.ExpansionOnNewFrame()); EXPECT_EQ(pending_padding - 2u, creator_.BytesFree()); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke(this, &QuicPacketCreatorTest::SaveSerializedPacket)); creator_.FlushCurrentPacket(); EXPECT_EQ(serialized_packet_->encrypted_length, kDefaultMaxPacketSize); DeleteSerializedPacket(); } class MockDelegate : public QuicPacketCreator::DelegateInterface { public: MockDelegate() {} MockDelegate(const MockDelegate&) = delete; MockDelegate& operator=(const MockDelegate&) = delete; ~MockDelegate() override {} MOCK_METHOD(bool, ShouldGeneratePacket, (HasRetransmittableData retransmittable, IsHandshake handshake), (override)); MOCK_METHOD(void, MaybeBundleOpportunistically, (TransmissionType transmission_type), (override)); MOCK_METHOD(QuicByteCount, GetFlowControlSendWindowSize, (QuicStreamId), (override)); MOCK_METHOD(QuicPacketBuffer, GetPacketBuffer, (), (override)); MOCK_METHOD(void, OnSerializedPacket, (SerializedPacket), (override)); MOCK_METHOD(void, OnUnrecoverableError, (QuicErrorCode, const std::string&), (override)); MOCK_METHOD(SerializedPacketFate, GetSerializedPacketFate, (bool, EncryptionLevel), (override)); void SetCanWriteAnything() { EXPECT_CALL(*this, ShouldGeneratePacket(_, _)).WillRepeatedly(Return(true)); EXPECT_CALL(*this, ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, _)) .WillRepeatedly(Return(true)); } void SetCanNotWrite() { EXPECT_CALL(*this, ShouldGeneratePacket(_, _)) .WillRepeatedly(Return(false)); EXPECT_CALL(*this, ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, _)) .WillRepeatedly(Return(false)); } void SetCanWriteOnlyNonRetransmittable() { EXPECT_CALL(*this, ShouldGeneratePacket(_, _)) .WillRepeatedly(Return(false)); EXPECT_CALL(*this, ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, _)) .WillRepeatedly(Return(true)); } }; struct PacketContents { PacketContents() : num_ack_frames(0), num_connection_close_frames(0), num_goaway_frames(0), num_rst_stream_frames(0), num_stop_waiting_frames(0), num_stream_frames(0), num_crypto_frames(0), num_ping_frames(0), num_mtu_discovery_frames(0), num_padding_frames(0) {} size_t num_ack_frames; size_t num_connection_close_frames; size_t num_goaway_frames; size_t num_rst_stream_frames; size_t num_stop_waiting_frames; size_t num_stream_frames; size_t num_crypto_frames; size_t num_ping_frames; size_t num_mtu_discovery_frames; size_t num_padding_frames; }; class MultiplePacketsTestPacketCreator : public QuicPacketCreator { public: MultiplePacketsTestPacketCreator( QuicConnectionId connection_id, QuicFramer* framer, QuicRandom* random_generator, QuicPacketCreator::DelegateInterface* delegate, SimpleDataProducer* producer) : QuicPacketCreator(connection_id, framer, random_generator, delegate), ack_frame_(InitAckFrame(1)), delegate_(static_cast<MockDelegate*>(delegate)), producer_(producer) {} bool ConsumeRetransmittableControlFrame(const QuicFrame& frame, bool bundle_ack) { QuicFrames frames; if (bundle_ack) { frames.push_back(QuicFrame(&ack_frame_)); } EXPECT_CALL(*delegate_, MaybeBundleOpportunistically(_)) .WillOnce(Invoke([this, frames = std::move(frames)] { FlushAckFrame(frames); return QuicFrames(); })); return QuicPacketCreator::ConsumeRetransmittableControlFrame(frame); } QuicConsumedData ConsumeDataFastPath(QuicStreamId id, absl::string_view data) { if (!data.empty()) { producer_->SaveStreamData(id, data); } return QuicPacketCreator::ConsumeDataFastPath(id, data.length(), 0, true, 0); } QuicConsumedData ConsumeData(QuicStreamId id, absl::string_view data, QuicStreamOffset offset, StreamSendingState state) { if (!data.empty()) { producer_->SaveStreamData(id, data); } EXPECT_CALL(*delegate_, MaybeBundleOpportunistically(_)).Times(1); return QuicPacketCreator::ConsumeData(id, data.length(), offset, state); } MessageStatus AddMessageFrame(QuicMessageId message_id, quiche::QuicheMemSlice message) { if (!has_ack() && delegate_->ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, NOT_HANDSHAKE)) { EXPECT_CALL(*delegate_, MaybeBundleOpportunistically(_)).Times(1); } return QuicPacketCreator::AddMessageFrame(message_id, absl::MakeSpan(&message, 1)); } size_t ConsumeCryptoData(EncryptionLevel level, absl::string_view data, QuicStreamOffset offset) { producer_->SaveCryptoData(level, offset, data); EXPECT_CALL(*delegate_, MaybeBundleOpportunistically(_)).Times(1); return QuicPacketCreator::ConsumeCryptoData(level, data.length(), offset); } QuicAckFrame ack_frame_; MockDelegate* delegate_; SimpleDataProducer* producer_; }; class QuicPacketCreatorMultiplePacketsTest : public QuicTest { public: QuicPacketCreatorMultiplePacketsTest() : framer_(AllSupportedVersions(), QuicTime::Zero(), Perspective::IS_CLIENT, kQuicDefaultConnectionIdLength), creator_(TestConnectionId(), &framer_, &random_creator_, &delegate_, &producer_), ack_frame_(InitAckFrame(1)) { EXPECT_CALL(delegate_, GetPacketBuffer()) .WillRepeatedly(Return(QuicPacketBuffer())); EXPECT_CALL(delegate_, GetSerializedPacketFate(_, _)) .WillRepeatedly(Return(SEND_TO_WRITER)); EXPECT_CALL(delegate_, GetFlowControlSendWindowSize(_)) .WillRepeatedly(Return(std::numeric_limits<QuicByteCount>::max())); creator_.SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE)); creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); framer_.set_data_producer(&producer_); if (simple_framer_.framer()->version().KnowsWhichDecrypterToUse()) { simple_framer_.framer()->InstallDecrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingDecrypter>()); } creator_.AttachPacketFlusher(); } ~QuicPacketCreatorMultiplePacketsTest() override {} void SavePacket(SerializedPacket packet) { QUICHE_DCHECK(packet.release_encrypted_buffer == nullptr); packet.encrypted_buffer = CopyBuffer(packet); packet.release_encrypted_buffer = [](const char* p) { delete[] p; }; packets_.push_back(std::move(packet)); } protected: QuicRstStreamFrame* CreateRstStreamFrame() { return new QuicRstStreamFrame(1, 1, QUIC_STREAM_NO_ERROR, 0); } QuicGoAwayFrame* CreateGoAwayFrame() { return new QuicGoAwayFrame(2, QUIC_NO_ERROR, 1, std::string()); } void CheckPacketContains(const PacketContents& contents, size_t packet_index) { ASSERT_GT(packets_.size(), packet_index); const SerializedPacket& packet = packets_[packet_index]; size_t num_retransmittable_frames = contents.num_connection_close_frames + contents.num_goaway_frames + contents.num_rst_stream_frames + contents.num_stream_frames + contents.num_crypto_frames + contents.num_ping_frames; size_t num_frames = contents.num_ack_frames + contents.num_stop_waiting_frames + contents.num_mtu_discovery_frames + contents.num_padding_frames + num_retransmittable_frames; if (num_retransmittable_frames == 0) { ASSERT_TRUE(packet.retransmittable_frames.empty()); } else { EXPECT_EQ(num_retransmittable_frames, packet.retransmittable_frames.size()); } ASSERT_TRUE(packet.encrypted_buffer != nullptr); ASSERT_TRUE(simple_framer_.ProcessPacket( QuicEncryptedPacket(packet.encrypted_buffer, packet.encrypted_length))); size_t num_padding_frames = 0; if (contents.num_padding_frames == 0) { num_padding_frames = simple_framer_.padding_frames().size(); } EXPECT_EQ(num_frames + num_padding_frames, simple_framer_.num_frames()); EXPECT_EQ(contents.num_ack_frames, simple_framer_.ack_frames().size()); EXPECT_EQ(contents.num_connection_close_frames, simple_framer_.connection_close_frames().size()); EXPECT_EQ(contents.num_goaway_frames, simple_framer_.goaway_frames().size()); EXPECT_EQ(contents.num_rst_stream_frames, simple_framer_.rst_stream_frames().size()); EXPECT_EQ(contents.num_stream_frames, simple_framer_.stream_frames().size()); EXPECT_EQ(contents.num_crypto_frames, simple_framer_.crypto_frames().size()); EXPECT_EQ(contents.num_stop_waiting_frames, simple_framer_.stop_waiting_frames().size()); if (contents.num_padding_frames != 0) { EXPECT_EQ(contents.num_padding_frames, simple_framer_.padding_frames().size()); } EXPECT_EQ(contents.num_ping_frames + contents.num_mtu_discovery_frames, simple_framer_.ping_frames().size()); } void CheckPacketHasSingleStreamFrame(size_t packet_index) { ASSERT_GT(packets_.size(), packet_index); const SerializedPacket& packet = packets_[packet_index]; ASSERT_FALSE(packet.retransmittable_frames.empty()); EXPECT_EQ(1u, packet.retransmittable_frames.size()); ASSERT_TRUE(packet.encrypted_buffer != nullptr); ASSERT_TRUE(simple_framer_.ProcessPacket( QuicEncryptedPacket(packet.encrypted_buffer, packet.encrypted_length))); EXPECT_EQ(1u, simple_framer_.num_frames()); EXPECT_EQ(1u, simple_framer_.stream_frames().size()); } void CheckAllPacketsHaveSingleStreamFrame() { for (size_t i = 0; i < packets_.size(); i++) { CheckPacketHasSingleStreamFrame(i); } } QuicFramer framer_; MockRandom random_creator_; StrictMock<MockDelegate> delegate_; MultiplePacketsTestPacketCreator creator_; SimpleQuicFramer simple_framer_; std::vector<SerializedPacket> packets_; QuicAckFrame ack_frame_; struct iovec iov_; quiche::SimpleBufferAllocator allocator_; private: std::unique_ptr<char[]> data_array_; SimpleDataProducer producer_; }; TEST_F(QuicPacketCreatorMultiplePacketsTest, AddControlFrame_NotWritable) { delegate_.SetCanNotWrite(); QuicRstStreamFrame* rst_frame = CreateRstStreamFrame(); const bool consumed = creator_.ConsumeRetransmittableControlFrame(QuicFrame(rst_frame), false); EXPECT_FALSE(consumed); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); delete rst_frame; } TEST_F(QuicPacketCreatorMultiplePacketsTest, WrongEncryptionLevelForStreamDataFastPath) { creator_.set_encryption_level(ENCRYPTION_HANDSHAKE); delegate_.SetCanWriteAnything(); const std::string data(10000, '?'); EXPECT_CALL(delegate_, OnSerializedPacket(_)).Times(0); EXPECT_QUIC_BUG( { EXPECT_CALL(delegate_, OnUnrecoverableError(_, _)); creator_.ConsumeDataFastPath( QuicUtils::GetFirstBidirectionalStreamId( framer_.transport_version(), Perspective::IS_CLIENT), data); }, ""); } TEST_F(QuicPacketCreatorMultiplePacketsTest, AddControlFrame_OnlyAckWritable) { delegate_.SetCanWriteOnlyNonRetransmittable(); QuicRstStreamFrame* rst_frame = CreateRstStreamFrame(); const bool consumed = creator_.ConsumeRetransmittableControlFrame(QuicFrame(rst_frame), false); EXPECT_FALSE(consumed); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); delete rst_frame; } TEST_F(QuicPacketCreatorMultiplePacketsTest, AddControlFrame_WritableAndShouldNotFlush) { delegate_.SetCanWriteAnything(); creator_.ConsumeRetransmittableControlFrame(QuicFrame(CreateRstStreamFrame()), false); EXPECT_TRUE(creator_.HasPendingFrames()); EXPECT_TRUE(creator_.HasPendingRetransmittableFrames()); } TEST_F(QuicPacketCreatorMultiplePacketsTest, AddControlFrame_NotWritableBatchThenFlush) { delegate_.SetCanNotWrite(); QuicRstStreamFrame* rst_frame = CreateRstStreamFrame(); const bool consumed = creator_.ConsumeRetransmittableControlFrame(QuicFrame(rst_frame), false); EXPECT_FALSE(consumed); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); delete rst_frame; } TEST_F(QuicPacketCreatorMultiplePacketsTest, AddControlFrame_WritableAndShouldFlush) { delegate_.SetCanWriteAnything(); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce( Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket)); creator_.ConsumeRetransmittableControlFrame(QuicFrame(CreateRstStreamFrame()), false); creator_.Flush(); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); PacketContents contents; contents.num_rst_stream_frames = 1; CheckPacketContains(contents, 0); } TEST_F(QuicPacketCreatorMultiplePacketsTest, ConsumeCryptoData) { delegate_.SetCanWriteAnything(); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce( Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket)); std::string data = "crypto data"; size_t consumed_bytes = creator_.ConsumeCryptoData(ENCRYPTION_INITIAL, data, 0); creator_.Flush(); EXPECT_EQ(data.length(), consumed_bytes); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); PacketContents contents; contents.num_crypto_frames = 1; contents.num_padding_frames = 1; CheckPacketContains(contents, 0); } TEST_F(QuicPacketCreatorMultiplePacketsTest, ConsumeCryptoDataCheckShouldGeneratePacket) { delegate_.SetCanNotWrite(); EXPECT_CALL(delegate_, OnSerializedPacket(_)).Times(0); std::string data = "crypto data"; size_t consumed_bytes = creator_.ConsumeCryptoData(ENCRYPTION_INITIAL, data, 0); creator_.Flush(); EXPECT_EQ(0u, consumed_bytes); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); } TEST_F(QuicPacketCreatorMultiplePacketsTest, ConsumeDataAdjustWriteLengthAfterBundledData) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); creator_.SetTransmissionType(NOT_RETRANSMISSION); delegate_.SetCanWriteAnything(); const std::string data(1000, 'D'); QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId( framer_.transport_version(), Perspective::IS_CLIENT); EXPECT_CALL(delegate_, GetFlowControlSendWindowSize(stream_id)) .WillOnce(Return(data.length() - 1)); QuicConsumedData consumed = creator_.ConsumeData(stream_id, data, 0u, FIN); EXPECT_EQ(consumed.bytes_consumed, data.length() - 1); EXPECT_FALSE(consumed.fin_consumed); } TEST_F(QuicPacketCreatorMultiplePacketsTest, ConsumeDataDoesNotAdjustWriteLengthAfterBundledData) { creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE); creator_.SetTransmissionType(NOT_RETRANSMISSION); delegate_.SetCanWriteAnything(); const std::string data(1000, 'D'); QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId( framer_.transport_version(), Perspective::IS_CLIENT); EXPECT_CALL(delegate_, GetFlowControlSendWindowSize(stream_id)) .WillOnce(Return(data.length())); QuicConsumedData consumed = creator_.ConsumeData(stream_id, data, 0u, FIN); EXPECT_EQ(consumed.bytes_consumed, data.length()); EXPECT_TRUE(consumed.fin_consumed); } TEST_F(QuicPacketCreatorMultiplePacketsTest, ConsumeData_NotWritable) { delegate_.SetCanNotWrite(); QuicConsumedData consumed = creator_.ConsumeData( QuicUtils::GetFirstBidirectionalStreamId(framer_.transport_version(), Perspective::IS_CLIENT), "foo", 0, FIN); EXPECT_EQ(0u, consumed.bytes_consumed); EXPECT_FALSE(consumed.fin_consumed); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); } TEST_F(QuicPacketCreatorMultiplePacketsTest, ConsumeData_WritableAndShouldNotFlush) { delegate_.SetCanWriteAnything(); QuicConsumedData consumed = creator_.ConsumeData( QuicUtils::GetFirstBidirectionalStreamId(framer_.transport_version(), Perspective::IS_CLIENT), "foo", 0, FIN); EXPECT_EQ(3u, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_TRUE(creator_.HasPendingFrames()); EXPECT_TRUE(creator_.HasPendingRetransmittableFrames()); } TEST_F(QuicPacketCreatorMultiplePacketsTest, ConsumeData_WritableAndShouldFlush) { delegate_.SetCanWriteAnything(); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce( Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket)); QuicConsumedData consumed = creator_.ConsumeData( QuicUtils::GetFirstBidirectionalStreamId(framer_.transport_version(), Perspective::IS_CLIENT), "foo", 0, FIN); creator_.Flush(); EXPECT_EQ(3u, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); PacketContents contents; contents.num_stream_frames = 1; CheckPacketContains(contents, 0); } TEST_F(QuicPacketCreatorMultiplePacketsTest, ConsumeData_Handshake) { delegate_.SetCanWriteAnything(); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce( Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket)); const std::string data = "foo bar"; size_t consumed_bytes = 0; if (QuicVersionUsesCryptoFrames(framer_.transport_version())) { consumed_bytes = creator_.ConsumeCryptoData(ENCRYPTION_INITIAL, data, 0); } else { consumed_bytes = creator_ .ConsumeData( QuicUtils::GetCryptoStreamId(framer_.transport_version()), data, 0, NO_FIN) .bytes_consumed; } EXPECT_EQ(7u, consumed_bytes); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); PacketContents contents; if (QuicVersionUsesCryptoFrames(framer_.transport_version())) { contents.num_crypto_frames = 1; } else { contents.num_stream_frames = 1; } contents.num_padding_frames = 1; CheckPacketContains(contents, 0); ASSERT_EQ(1u, packets_.size()); ASSERT_EQ(kDefaultMaxPacketSize, creator_.max_packet_length()); EXPECT_EQ(kDefaultMaxPacketSize, packets_[0].encrypted_length); } TEST_F(QuicPacketCreatorMultiplePacketsTest, ConsumeData_Handshake_PaddingDisabled) { creator_.set_fully_pad_crypto_handshake_packets(false); delegate_.SetCanWriteAnything(); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce( Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket)); const std::string data = "foo"; size_t bytes_consumed = 0; if (QuicVersionUsesCryptoFrames(framer_.transport_version())) { bytes_consumed = creator_.ConsumeCryptoData(ENCRYPTION_INITIAL, data, 0); } else { bytes_consumed = creator_ .ConsumeData( QuicUtils::GetCryptoStreamId(framer_.transport_version()), data, 0, NO_FIN) .bytes_consumed; } EXPECT_EQ(3u, bytes_consumed); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); PacketContents contents; if (QuicVersionUsesCryptoFrames(framer_.transport_version())) { contents.num_crypto_frames = 1; } else { contents.num_stream_frames = 1; } contents.num_padding_frames = 0; CheckPacketContains(contents, 0); ASSERT_EQ(1u, packets_.size()); ASSERT_EQ(kDefaultMaxPacketSize, creator_.max_packet_length()); size_t expected_packet_length = 31; if (QuicVersionUsesCryptoFrames(framer_.transport_version())) { expected_packet_length = 32; } EXPECT_EQ(expected_packet_length, packets_[0].encrypted_length); } TEST_F(QuicPacketCreatorMultiplePacketsTest, ConsumeData_EmptyData) { delegate_.SetCanWriteAnything(); EXPECT_QUIC_BUG(creator_.ConsumeData( QuicUtils::QuicUtils::GetFirstBidirectionalStreamId( framer_.transport_version(), Perspective::IS_CLIENT), {}, 0, NO_FIN), "Attempt to consume empty data without FIN."); } TEST_F(QuicPacketCreatorMultiplePacketsTest, ConsumeDataMultipleTimes_WritableAndShouldNotFlush) { delegate_.SetCanWriteAnything(); creator_.ConsumeData(QuicUtils::GetFirstBidirectionalStreamId( framer_.transport_version(), Perspective::IS_CLIENT), "foo", 0, FIN); QuicConsumedData consumed = creator_.ConsumeData(3, "quux", 3, NO_FIN); EXPECT_EQ(4u, consumed.bytes_consumed); EXPECT_FALSE(consumed.fin_consumed); EXPECT_TRUE(creator_.HasPendingFrames()); EXPECT_TRUE(creator_.HasPendingRetransmittableFrames()); } TEST_F(QuicPacketCreatorMultiplePacketsTest, ConsumeData_BatchOperations) { delegate_.SetCanWriteAnything(); creator_.ConsumeData(QuicUtils::GetFirstBidirectionalStreamId( framer_.transport_version(), Perspective::IS_CLIENT), "foo", 0, NO_FIN); QuicConsumedData consumed = creator_.ConsumeData( QuicUtils::GetFirstBidirectionalStreamId(framer_.transport_version(), Perspective::IS_CLIENT), "quux", 3, FIN); EXPECT_EQ(4u, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_TRUE(creator_.HasPendingFrames()); EXPECT_TRUE(creator_.HasPendingRetransmittableFrames()); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce( Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket)); creator_.Flush(); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); PacketContents contents; contents.num_stream_frames = 1; CheckPacketContains(contents, 0); } TEST_F(QuicPacketCreatorMultiplePacketsTest, ConsumeData_FramesPreviouslyQueued) { size_t length = TaggingEncrypter(0x00).GetCiphertextSize(0) + GetPacketHeaderSize( framer_.transport_version(), creator_.GetDestinationConnectionIdLength(), creator_.GetSourceConnectionIdLength(), QuicPacketCreatorPeer::SendVersionInPacket(&creator_), !kIncludeDiversificationNonce, QuicPacketCreatorPeer::GetPacketNumberLength(&creator_), QuicPacketCreatorPeer::GetRetryTokenLengthLength(&creator_), 0, QuicPacketCreatorPeer::GetLengthLength(&creator_)) + QuicFramer::GetMinStreamFrameSize(framer_.transport_version(), 1, 0, false, 3) + 3 + QuicFramer::GetMinStreamFrameSize(framer_.transport_version(), 1, 0, true, 1) + 1; creator_.SetMaxPacketLength(length); delegate_.SetCanWriteAnything(); { InSequence dummy; EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce( Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket)); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce( Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket)); } QuicConsumedData consumed = creator_.ConsumeData( QuicUtils::GetFirstBidirectionalStreamId(framer_.transport_version(), Perspective::IS_CLIENT), "foo", 0, NO_FIN); EXPECT_EQ(3u, consumed.bytes_consumed); EXPECT_FALSE(consumed.fin_consumed); EXPECT_TRUE(creator_.HasPendingFrames()); EXPECT_TRUE(creator_.HasPendingRetransmittableFrames()); consumed = creator_.ConsumeData( QuicUtils::GetFirstBidirectionalStreamId(framer_.transport_version(), Perspective::IS_CLIENT), "bar", 3, FIN); EXPECT_EQ(3u, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_TRUE(creator_.HasPendingFrames()); EXPECT_TRUE(creator_.HasPendingRetransmittableFrames()); creator_.FlushCurrentPacket(); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); PacketContents contents; contents.num_stream_frames = 1; CheckPacketContains(contents, 0); CheckPacketContains(contents, 1); } TEST_F(QuicPacketCreatorMultiplePacketsTest, ConsumeDataFastPath) { delegate_.SetCanWriteAnything(); creator_.SetTransmissionType(LOSS_RETRANSMISSION); const std::string data(10000, '?'); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillRepeatedly( Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket)); QuicConsumedData consumed = creator_.ConsumeDataFastPath( QuicUtils::GetFirstBidirectionalStreamId(framer_.transport_version(), Perspective::IS_CLIENT), data); EXPECT_EQ(10000u, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); PacketContents contents; contents.num_stream_frames = 1; CheckPacketContains(contents, 0); EXPECT_FALSE(packets_.empty()); SerializedPacket& packet = packets_.back(); EXPECT_TRUE(!packet.retransmittable_frames.empty()); EXPECT_EQ(LOSS_RETRANSMISSION, packet.transmission_type); EXPECT_EQ(STREAM_FRAME, packet.retransmittable_frames.front().type); const QuicStreamFrame& stream_frame = packet.retransmittable_frames.front().stream_frame; EXPECT_EQ(10000u, stream_frame.data_length + stream_frame.offset); } TEST_F(QuicPacketCreatorMultiplePacketsTest, ConsumeDataLarge) { delegate_.SetCanWriteAnything(); const std::string data(10000, '?'); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillRepeatedly( Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket)); QuicConsumedData consumed = creator_.ConsumeData( QuicUtils::GetFirstBidirectionalStreamId(framer_.transport_version(), Perspective::IS_CLIENT), data, 0, FIN); EXPECT_EQ(10000u, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); PacketContents contents; contents.num_stream_frames = 1; CheckPacketContains(contents, 0); EXPECT_FALSE(packets_.empty()); SerializedPacket& packet = packets_.back(); EXPECT_TRUE(!packet.retransmittable_frames.empty()); EXPECT_EQ(STREAM_FRAME, packet.retransmittable_frames.front().type); const QuicStreamFrame& stream_frame = packet.retransmittable_frames.front().stream_frame; EXPECT_EQ(10000u, stream_frame.data_length + stream_frame.offset); } TEST_F(QuicPacketCreatorMultiplePacketsTest, ConsumeDataLargeSendAckFalse) { delegate_.SetCanNotWrite(); QuicRstStreamFrame* rst_frame = CreateRstStreamFrame(); const bool success = creator_.ConsumeRetransmittableControlFrame(QuicFrame(rst_frame), true); EXPECT_FALSE(success); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); delegate_.SetCanWriteAnything(); creator_.ConsumeRetransmittableControlFrame(QuicFrame(rst_frame), false); const std::string data(10000, '?'); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillRepeatedly( Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket)); creator_.ConsumeRetransmittableControlFrame(QuicFrame(CreateRstStreamFrame()), true); QuicConsumedData consumed = creator_.ConsumeData( QuicUtils::GetFirstBidirectionalStreamId(framer_.transport_version(), Perspective::IS_CLIENT), data, 0, FIN); creator_.Flush(); EXPECT_EQ(10000u, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); EXPECT_FALSE(packets_.empty()); SerializedPacket& packet = packets_.back(); EXPECT_TRUE(!packet.retransmittable_frames.empty()); EXPECT_EQ(STREAM_FRAME, packet.retransmittable_frames.front().type); const QuicStreamFrame& stream_frame = packet.retransmittable_frames.front().stream_frame; EXPECT_EQ(10000u, stream_frame.data_length + stream_frame.offset); } TEST_F(QuicPacketCreatorMultiplePacketsTest, ConsumeDataLargeSendAckTrue) { delegate_.SetCanNotWrite(); delegate_.SetCanWriteAnything(); const std::string data(10000, '?'); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillRepeatedly( Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket)); QuicConsumedData consumed = creator_.ConsumeData( QuicUtils::GetFirstBidirectionalStreamId(framer_.transport_version(), Perspective::IS_CLIENT), data, 0, FIN); creator_.Flush(); EXPECT_EQ(10000u, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); EXPECT_FALSE(packets_.empty()); SerializedPacket& packet = packets_.back(); EXPECT_TRUE(!packet.retransmittable_frames.empty()); EXPECT_EQ(STREAM_FRAME, packet.retransmittable_frames.front().type); const QuicStreamFrame& stream_frame = packet.retransmittable_frames.front().stream_frame; EXPECT_EQ(10000u, stream_frame.data_length + stream_frame.offset); } TEST_F(QuicPacketCreatorMultiplePacketsTest, NotWritableThenBatchOperations) { delegate_.SetCanNotWrite(); QuicRstStreamFrame* rst_frame = CreateRstStreamFrame(); const bool consumed = creator_.ConsumeRetransmittableControlFrame(QuicFrame(rst_frame), true); EXPECT_FALSE(consumed); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); EXPECT_FALSE(creator_.HasPendingStreamFramesOfStream(3)); delegate_.SetCanWriteAnything(); EXPECT_TRUE( creator_.ConsumeRetransmittableControlFrame(QuicFrame(rst_frame), false)); creator_.ConsumeData(3, "quux", 0, NO_FIN); if (!VersionHasIetfQuicFrames(framer_.transport_version())) { creator_.ConsumeRetransmittableControlFrame(QuicFrame(CreateGoAwayFrame()), false); } EXPECT_TRUE(creator_.HasPendingStreamFramesOfStream(3)); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce( Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket)); creator_.Flush(); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); EXPECT_FALSE(creator_.HasPendingStreamFramesOfStream(3)); PacketContents contents; contents.num_ack_frames = 0; if (!VersionHasIetfQuicFrames(framer_.transport_version())) { contents.num_goaway_frames = 1; } else { contents.num_goaway_frames = 0; } contents.num_rst_stream_frames = 1; contents.num_stream_frames = 1; CheckPacketContains(contents, 0); } TEST_F(QuicPacketCreatorMultiplePacketsTest, NotWritableThenBatchOperations2) { delegate_.SetCanNotWrite(); QuicRstStreamFrame* rst_frame = CreateRstStreamFrame(); const bool success = creator_.ConsumeRetransmittableControlFrame(QuicFrame(rst_frame), true); EXPECT_FALSE(success); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); delegate_.SetCanWriteAnything(); { InSequence dummy; EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce( Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket)); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce( Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket)); } EXPECT_TRUE( creator_.ConsumeRetransmittableControlFrame(QuicFrame(rst_frame), false)); size_t data_len = kDefaultMaxPacketSize + 100; const std::string data(data_len, '?'); QuicConsumedData consumed = creator_.ConsumeData(3, data, 0, FIN); EXPECT_EQ(data_len, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); if (!VersionHasIetfQuicFrames(framer_.transport_version())) { creator_.ConsumeRetransmittableControlFrame(QuicFrame(CreateGoAwayFrame()), false); } creator_.Flush(); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); PacketContents contents; contents.num_ack_frames = 0; contents.num_rst_stream_frames = 1; contents.num_stream_frames = 1; CheckPacketContains(contents, 0); PacketContents contents2; if (!VersionHasIetfQuicFrames(framer_.transport_version())) { contents2.num_goaway_frames = 1; } else { contents2.num_goaway_frames = 0; } contents2.num_stream_frames = 1; CheckPacketContains(contents2, 1); } TEST_F(QuicPacketCreatorMultiplePacketsTest, PacketTransmissionType) { delegate_.SetCanWriteAnything(); creator_.SetTransmissionType(LOSS_RETRANSMISSION); size_t data_len = 1220; const std::string data(data_len, '?'); QuicStreamId stream1_id = QuicUtils::GetFirstBidirectionalStreamId( framer_.transport_version(), Perspective::IS_CLIENT); QuicConsumedData consumed = creator_.ConsumeData(stream1_id, data, 0, NO_FIN); EXPECT_EQ(data_len, consumed.bytes_consumed); ASSERT_EQ(0u, creator_.BytesFree()) << "Test setup failed: Please increase data_len to " << data_len + creator_.BytesFree() << " bytes."; creator_.SetTransmissionType(NOT_RETRANSMISSION); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce( Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket)); QuicStreamId stream2_id = stream1_id + 4; consumed = creator_.ConsumeData(stream2_id, data, 0, NO_FIN); EXPECT_EQ(data_len, consumed.bytes_consumed); ASSERT_EQ(1u, packets_.size()); ASSERT_TRUE(packets_[0].encrypted_buffer); ASSERT_EQ(1u, packets_[0].retransmittable_frames.size()); EXPECT_EQ(stream1_id, packets_[0].retransmittable_frames[0].stream_frame.stream_id); EXPECT_EQ(packets_[0].transmission_type, LOSS_RETRANSMISSION); } TEST_F(QuicPacketCreatorMultiplePacketsTest, TestConnectionIdLength) { QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_SERVER); creator_.SetServerConnectionIdLength(0); EXPECT_EQ(0, creator_.GetDestinationConnectionIdLength()); for (size_t i = 1; i < 10; i++) { creator_.SetServerConnectionIdLength(i); EXPECT_EQ(0, creator_.GetDestinationConnectionIdLength()); } } TEST_F(QuicPacketCreatorMultiplePacketsTest, SetMaxPacketLength_Initial) { delegate_.SetCanWriteAnything(); size_t data_len = 3 * kDefaultMaxPacketSize + 1; size_t packet_len = kDefaultMaxPacketSize + 100; ASSERT_LE(packet_len, kMaxOutgoingPacketSize); creator_.SetMaxPacketLength(packet_len); EXPECT_EQ(packet_len, creator_.max_packet_length()); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .Times(3) .WillRepeatedly( Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket)); const std::string data(data_len, '?'); QuicConsumedData consumed = creator_.ConsumeData( QuicUtils::GetFirstBidirectionalStreamId(framer_.transport_version(), Perspective::IS_CLIENT), data, 0, FIN); EXPECT_EQ(data_len, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); ASSERT_EQ(3u, packets_.size()); EXPECT_EQ(packet_len, packets_[0].encrypted_length); EXPECT_EQ(packet_len, packets_[1].encrypted_length); CheckAllPacketsHaveSingleStreamFrame(); } TEST_F(QuicPacketCreatorMultiplePacketsTest, SetMaxPacketLength_Middle) { delegate_.SetCanWriteAnything(); size_t data_len = kDefaultMaxPacketSize; size_t packet_len = kDefaultMaxPacketSize + 100; ASSERT_LE(packet_len, kMaxOutgoingPacketSize); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .Times(3) .WillRepeatedly( Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket)); const std::string data(data_len, '?'); QuicConsumedData consumed = creator_.ConsumeData( QuicUtils::GetFirstBidirectionalStreamId(framer_.transport_version(), Perspective::IS_CLIENT), data, 0, NO_FIN); creator_.Flush(); EXPECT_EQ(data_len, consumed.bytes_consumed); EXPECT_FALSE(consumed.fin_consumed); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); ASSERT_EQ(2u, packets_.size()); creator_.SetMaxPacketLength(packet_len); EXPECT_EQ(packet_len, creator_.max_packet_length()); creator_.AttachPacketFlusher(); consumed = creator_.ConsumeData( QuicUtils::GetFirstBidirectionalStreamId(framer_.transport_version(), Perspective::IS_CLIENT), data, data_len, FIN); creator_.Flush(); EXPECT_EQ(data_len, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); ASSERT_EQ(3u, packets_.size()); EXPECT_EQ(kDefaultMaxPacketSize, packets_[0].encrypted_length); EXPECT_LE(kDefaultMaxPacketSize, packets_[2].encrypted_length); CheckAllPacketsHaveSingleStreamFrame(); } TEST_F(QuicPacketCreatorMultiplePacketsTest, SetMaxPacketLength_MidpacketFlush) { delegate_.SetCanWriteAnything(); size_t first_write_len = kDefaultMaxPacketSize / 2; size_t packet_len = kDefaultMaxPacketSize + 100; size_t second_write_len = packet_len + 1; ASSERT_LE(packet_len, kMaxOutgoingPacketSize); const std::string first_write(first_write_len, '?'); QuicConsumedData consumed = creator_.ConsumeData( QuicUtils::GetFirstBidirectionalStreamId(framer_.transport_version(), Perspective::IS_CLIENT), first_write, 0, NO_FIN); EXPECT_EQ(first_write_len, consumed.bytes_consumed); EXPECT_FALSE(consumed.fin_consumed); EXPECT_TRUE(creator_.HasPendingFrames()); EXPECT_TRUE(creator_.HasPendingRetransmittableFrames()); ASSERT_EQ(0u, packets_.size()); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce( Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket)); creator_.FlushCurrentPacket(); creator_.SetMaxPacketLength(packet_len); EXPECT_EQ(packet_len, creator_.max_packet_length()); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce( Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket)); const std::string second_write(second_write_len, '?'); consumed = creator_.ConsumeData( QuicUtils::GetFirstBidirectionalStreamId(framer_.transport_version(), Perspective::IS_CLIENT), second_write, first_write_len, FIN); EXPECT_EQ(second_write_len, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_TRUE(creator_.HasPendingFrames()); EXPECT_TRUE(creator_.HasPendingRetransmittableFrames()); ASSERT_EQ(2u, packets_.size()); EXPECT_GT(kDefaultMaxPacketSize, packets_[0].encrypted_length); EXPECT_EQ(packet_len, packets_[1].encrypted_length); CheckAllPacketsHaveSingleStreamFrame(); } TEST_F(QuicPacketCreatorMultiplePacketsTest, GenerateConnectivityProbingPacket) { delegate_.SetCanWriteAnything(); std::unique_ptr<SerializedPacket> probing_packet; if (VersionHasIetfQuicFrames(framer_.transport_version())) { QuicPathFrameBuffer payload = { {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}}; probing_packet = creator_.SerializePathChallengeConnectivityProbingPacket(payload); } else { probing_packet = creator_.SerializeConnectivityProbingPacket(); } ASSERT_TRUE(simple_framer_.ProcessPacket(QuicEncryptedPacket( probing_packet->encrypted_buffer, probing_packet->encrypted_length))); EXPECT_EQ(2u, simple_framer_.num_frames()); if (VersionHasIetfQuicFrames(framer_.transport_version())) { EXPECT_EQ(1u, simple_framer_.path_challenge_frames().size()); } else { EXPECT_EQ(1u, simple_framer_.ping_frames().size()); } EXPECT_EQ(1u, simple_framer_.padding_frames().size()); } TEST_F(QuicPacketCreatorMultiplePacketsTest, GenerateMtuDiscoveryPacket_Simple) { delegate_.SetCanWriteAnything(); const size_t target_mtu = kDefaultMaxPacketSize + 100; static_assert(target_mtu < kMaxOutgoingPacketSize, "The MTU probe used by the test exceeds maximum packet size"); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce( Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket)); creator_.GenerateMtuDiscoveryPacket(target_mtu); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); ASSERT_EQ(1u, packets_.size()); EXPECT_EQ(target_mtu, packets_[0].encrypted_length); PacketContents contents; contents.num_mtu_discovery_frames = 1; contents.num_padding_frames = 1; CheckPacketContains(contents, 0); } TEST_F(QuicPacketCreatorMultiplePacketsTest, GenerateMtuDiscoveryPacket_SurroundedByData) { delegate_.SetCanWriteAnything(); const size_t target_mtu = kDefaultMaxPacketSize + 100; static_assert(target_mtu < kMaxOutgoingPacketSize, "The MTU probe used by the test exceeds maximum packet size"); const size_t data_len = target_mtu + 1; EXPECT_CALL(delegate_, OnSerializedPacket(_)) .Times(5) .WillRepeatedly( Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket)); const std::string data(data_len, '?'); QuicConsumedData consumed = creator_.ConsumeData( QuicUtils::GetFirstBidirectionalStreamId(framer_.transport_version(), Perspective::IS_CLIENT), data, 0, NO_FIN); creator_.Flush(); EXPECT_EQ(data_len, consumed.bytes_consumed); EXPECT_FALSE(consumed.fin_consumed); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); creator_.GenerateMtuDiscoveryPacket(target_mtu); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); creator_.AttachPacketFlusher(); consumed = creator_.ConsumeData( QuicUtils::GetFirstBidirectionalStreamId(framer_.transport_version(), Perspective::IS_CLIENT), data, data_len, FIN); creator_.Flush(); EXPECT_EQ(data_len, consumed.bytes_consumed); EXPECT_TRUE(consumed.fin_consumed); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); ASSERT_EQ(5u, packets_.size()); EXPECT_EQ(kDefaultMaxPacketSize, packets_[0].encrypted_length); EXPECT_EQ(target_mtu, packets_[2].encrypted_length); EXPECT_EQ(kDefaultMaxPacketSize, packets_[3].encrypted_length); PacketContents probe_contents; probe_contents.num_mtu_discovery_frames = 1; probe_contents.num_padding_frames = 1; CheckPacketHasSingleStreamFrame(0); CheckPacketHasSingleStreamFrame(1); CheckPacketContains(probe_contents, 2); CheckPacketHasSingleStreamFrame(3); CheckPacketHasSingleStreamFrame(4); } TEST_F(QuicPacketCreatorMultiplePacketsTest, ConnectionCloseFrameLargerThanPacketSize) { delegate_.SetCanWriteAnything(); char buf[2000] = {}; absl::string_view error_details(buf, 2000); const QuicErrorCode kQuicErrorCode = QUIC_PACKET_WRITE_ERROR; QuicConnectionCloseFrame* frame = new QuicConnectionCloseFrame( framer_.transport_version(), kQuicErrorCode, NO_IETF_QUIC_ERROR, std::string(error_details), 0); creator_.ConsumeRetransmittableControlFrame(QuicFrame(frame), false); EXPECT_TRUE(creator_.HasPendingFrames()); EXPECT_TRUE(creator_.HasPendingRetransmittableFrames()); } TEST_F(QuicPacketCreatorMultiplePacketsTest, RandomPaddingAfterFinSingleStreamSinglePacket) { const QuicByteCount kStreamFramePayloadSize = 100u; char buf[kStreamFramePayloadSize] = {}; const QuicStreamId kDataStreamId = 5; size_t length = TaggingEncrypter(0x00).GetCiphertextSize(0) + GetPacketHeaderSize( framer_.transport_version(), creator_.GetDestinationConnectionIdLength(), creator_.GetSourceConnectionIdLength(), QuicPacketCreatorPeer::SendVersionInPacket(&creator_), !kIncludeDiversificationNonce, QuicPacketCreatorPeer::GetPacketNumberLength(&creator_), QuicPacketCreatorPeer::GetRetryTokenLengthLength(&creator_), 0, QuicPacketCreatorPeer::GetLengthLength(&creator_)) + QuicFramer::GetMinStreamFrameSize( framer_.transport_version(), kDataStreamId, 0, false, kStreamFramePayloadSize + kMaxNumRandomPaddingBytes) + kStreamFramePayloadSize + kMaxNumRandomPaddingBytes; creator_.SetMaxPacketLength(length); delegate_.SetCanWriteAnything(); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce( Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket)); QuicConsumedData consumed = creator_.ConsumeData( kDataStreamId, absl::string_view(buf, kStreamFramePayloadSize), 0, FIN_AND_PADDING); creator_.Flush(); EXPECT_EQ(kStreamFramePayloadSize, consumed.bytes_consumed); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); EXPECT_EQ(1u, packets_.size()); PacketContents contents; contents.num_padding_frames = 1; contents.num_stream_frames = 1; CheckPacketContains(contents, 0); } TEST_F(QuicPacketCreatorMultiplePacketsTest, RandomPaddingAfterFinSingleStreamMultiplePackets) { const QuicByteCount kStreamFramePayloadSize = 100u; char buf[kStreamFramePayloadSize] = {}; const QuicStreamId kDataStreamId = 5; size_t length = TaggingEncrypter(0x00).GetCiphertextSize(0) + GetPacketHeaderSize( framer_.transport_version(), creator_.GetDestinationConnectionIdLength(), creator_.GetSourceConnectionIdLength(), QuicPacketCreatorPeer::SendVersionInPacket(&creator_), !kIncludeDiversificationNonce, QuicPacketCreatorPeer::GetPacketNumberLength(&creator_), QuicPacketCreatorPeer::GetRetryTokenLengthLength(&creator_), 0, QuicPacketCreatorPeer::GetLengthLength(&creator_)) + QuicFramer::GetMinStreamFrameSize( framer_.transport_version(), kDataStreamId, 0, false, kStreamFramePayloadSize + 1) + kStreamFramePayloadSize + 1; creator_.SetMaxPacketLength(length); delegate_.SetCanWriteAnything(); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillRepeatedly( Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket)); QuicConsumedData consumed = creator_.ConsumeData( kDataStreamId, absl::string_view(buf, kStreamFramePayloadSize), 0, FIN_AND_PADDING); creator_.Flush(); EXPECT_EQ(kStreamFramePayloadSize, consumed.bytes_consumed); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); EXPECT_LE(1u, packets_.size()); PacketContents contents; contents.num_stream_frames = 1; contents.num_padding_frames = 1; CheckPacketContains(contents, 0); for (size_t i = 1; i < packets_.size(); ++i) { contents.num_stream_frames = 0; contents.num_padding_frames = 1; CheckPacketContains(contents, i); } } TEST_F(QuicPacketCreatorMultiplePacketsTest, RandomPaddingAfterFinMultipleStreamsMultiplePackets) { const QuicByteCount kStreamFramePayloadSize = 100u; char buf[kStreamFramePayloadSize] = {}; const QuicStreamId kDataStreamId1 = 5; const QuicStreamId kDataStreamId2 = 6; size_t length = TaggingEncrypter(0x00).GetCiphertextSize(0) + GetPacketHeaderSize( framer_.transport_version(), creator_.GetDestinationConnectionIdLength(), creator_.GetSourceConnectionIdLength(), QuicPacketCreatorPeer::SendVersionInPacket(&creator_), !kIncludeDiversificationNonce, QuicPacketCreatorPeer::GetPacketNumberLength(&creator_), QuicPacketCreatorPeer::GetRetryTokenLengthLength(&creator_), 0, QuicPacketCreatorPeer::GetLengthLength(&creator_)) + QuicFramer::GetMinStreamFrameSize( framer_.transport_version(), kDataStreamId1, 0, false, kStreamFramePayloadSize) + kStreamFramePayloadSize + QuicFramer::GetMinStreamFrameSize(framer_.transport_version(), kDataStreamId1, 0, false, 1) + 1; creator_.SetMaxPacketLength(length); delegate_.SetCanWriteAnything(); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillRepeatedly( Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket)); QuicConsumedData consumed = creator_.ConsumeData( kDataStreamId1, absl::string_view(buf, kStreamFramePayloadSize), 0, FIN_AND_PADDING); EXPECT_EQ(kStreamFramePayloadSize, consumed.bytes_consumed); consumed = creator_.ConsumeData( kDataStreamId2, absl::string_view(buf, kStreamFramePayloadSize), 0, FIN_AND_PADDING); EXPECT_EQ(kStreamFramePayloadSize, consumed.bytes_consumed); creator_.Flush(); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_FALSE(creator_.HasPendingRetransmittableFrames()); EXPECT_LE(2u, packets_.size()); PacketContents contents; contents.num_stream_frames = 2; CheckPacketContains(contents, 0); contents.num_stream_frames = 1; contents.num_padding_frames = 1; CheckPacketContains(contents, 1); for (size_t i = 2; i < packets_.size(); ++i) { contents.num_stream_frames = 0; contents.num_padding_frames = 1; CheckPacketContains(contents, i); } } TEST_F(QuicPacketCreatorMultiplePacketsTest, AddMessageFrame) { if (framer_.version().UsesTls()) { creator_.SetMaxDatagramFrameSize(kMaxAcceptedDatagramFrameSize); } delegate_.SetCanWriteAnything(); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce( Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket)); creator_.ConsumeData(QuicUtils::GetFirstBidirectionalStreamId( framer_.transport_version(), Perspective::IS_CLIENT), "foo", 0, FIN); EXPECT_EQ(MESSAGE_STATUS_SUCCESS, creator_.AddMessageFrame(1, MemSliceFromString("message"))); EXPECT_TRUE(creator_.HasPendingFrames()); EXPECT_TRUE(creator_.HasPendingRetransmittableFrames()); EXPECT_EQ(MESSAGE_STATUS_SUCCESS, creator_.AddMessageFrame( 2, MemSliceFromString(std::string( creator_.GetCurrentLargestMessagePayload(), 'a')))); EXPECT_TRUE(creator_.HasPendingRetransmittableFrames()); EXPECT_EQ(MESSAGE_STATUS_TOO_LARGE, creator_.AddMessageFrame( 3, MemSliceFromString(std::string( creator_.GetCurrentLargestMessagePayload() + 10, 'a')))); } TEST_F(QuicPacketCreatorMultiplePacketsTest, ConnectionId) { creator_.SetServerConnectionId(TestConnectionId(0x1337)); EXPECT_EQ(TestConnectionId(0x1337), creator_.GetDestinationConnectionId()); EXPECT_EQ(EmptyQuicConnectionId(), creator_.GetSourceConnectionId()); if (!framer_.version().SupportsClientConnectionIds()) { return; } creator_.SetClientConnectionId(TestConnectionId(0x33)); EXPECT_EQ(TestConnectionId(0x1337), creator_.GetDestinationConnectionId()); EXPECT_EQ(TestConnectionId(0x33), creator_.GetSourceConnectionId()); } TEST_F(QuicPacketCreatorMultiplePacketsTest, ExtraPaddingNeeded) { if (!framer_.version().HasHeaderProtection()) { return; } delegate_.SetCanWriteAnything(); EXPECT_EQ(QuicPacketCreatorPeer::GetPacketNumberLength(&creator_), PACKET_1BYTE_PACKET_NUMBER); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce( Invoke(this, &QuicPacketCreatorMultiplePacketsTest::SavePacket)); creator_.ConsumeData(QuicUtils::GetFirstBidirectionalStreamId( framer_.transport_version(), Perspective::IS_CLIENT), "", 0, FIN); creator_.Flush(); ASSERT_FALSE(packets_[0].nonretransmittable_frames.empty()); QuicFrame padding = packets_[0].nonretransmittable_frames[0]; EXPECT_EQ(padding.padding_frame.num_padding_bytes, 1); } TEST_F(QuicPacketCreatorMultiplePacketsTest, PeerAddressContextWithSameAddress) { QuicConnectionId client_connection_id = TestConnectionId(1); QuicConnectionId server_connection_id = TestConnectionId(2); QuicSocketAddress peer_addr(QuicIpAddress::Any4(), 12345); creator_.SetDefaultPeerAddress(peer_addr); creator_.SetClientConnectionId(client_connection_id); creator_.SetServerConnectionId(server_connection_id); EXPECT_CALL(delegate_, ShouldGeneratePacket(_, _)) .WillRepeatedly(Return(true)); EXPECT_EQ(3u, creator_ .ConsumeData(QuicUtils::GetFirstBidirectionalStreamId( creator_.transport_version(), Perspective::IS_CLIENT), "foo", 0, NO_FIN) .bytes_consumed); EXPECT_TRUE(creator_.HasPendingFrames()); { QuicPacketCreator::ScopedPeerAddressContext context( &creator_, peer_addr, client_connection_id, server_connection_id); ASSERT_EQ(client_connection_id, creator_.GetClientConnectionId()); ASSERT_EQ(server_connection_id, creator_.GetServerConnectionId()); EXPECT_TRUE(creator_.HasPendingFrames()); EXPECT_EQ(3u, creator_ .ConsumeData(QuicUtils::GetFirstBidirectionalStreamId( creator_.transport_version(), Perspective::IS_CLIENT), "foo", 0, FIN) .bytes_consumed); } EXPECT_TRUE(creator_.HasPendingFrames()); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke([=](SerializedPacket packet) { EXPECT_EQ(peer_addr, packet.peer_address); ASSERT_EQ(2u, packet.retransmittable_frames.size()); EXPECT_EQ(STREAM_FRAME, packet.retransmittable_frames.front().type); EXPECT_EQ(STREAM_FRAME, packet.retransmittable_frames.back().type); })); creator_.FlushCurrentPacket(); } TEST_F(QuicPacketCreatorMultiplePacketsTest, PeerAddressContextWithDifferentAddress) { QuicSocketAddress peer_addr(QuicIpAddress::Any4(), 12345); creator_.SetDefaultPeerAddress(peer_addr); EXPECT_CALL(delegate_, ShouldGeneratePacket(_, _)) .WillRepeatedly(Return(true)); EXPECT_EQ(3u, creator_ .ConsumeData(QuicUtils::GetFirstBidirectionalStreamId( creator_.transport_version(), Perspective::IS_CLIENT), "foo", 0, NO_FIN) .bytes_consumed); QuicSocketAddress peer_addr1(QuicIpAddress::Any4(), 12346); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke([=](SerializedPacket packet) { EXPECT_EQ(peer_addr, packet.peer_address); ASSERT_EQ(1u, packet.retransmittable_frames.size()); EXPECT_EQ(STREAM_FRAME, packet.retransmittable_frames.front().type); })) .WillOnce(Invoke([=](SerializedPacket packet) { EXPECT_EQ(peer_addr1, packet.peer_address); ASSERT_EQ(1u, packet.retransmittable_frames.size()); EXPECT_EQ(STREAM_FRAME, packet.retransmittable_frames.front().type); })); EXPECT_TRUE(creator_.HasPendingFrames()); { QuicConnectionId client_connection_id = TestConnectionId(1); QuicConnectionId server_connection_id = TestConnectionId(2); QuicPacketCreator::ScopedPeerAddressContext context( &creator_, peer_addr1, client_connection_id, server_connection_id); ASSERT_EQ(client_connection_id, creator_.GetClientConnectionId()); ASSERT_EQ(server_connection_id, creator_.GetServerConnectionId()); EXPECT_FALSE(creator_.HasPendingFrames()); EXPECT_EQ(3u, creator_ .ConsumeData(QuicUtils::GetFirstBidirectionalStreamId( creator_.transport_version(), Perspective::IS_CLIENT), "foo", 0, FIN) .bytes_consumed); EXPECT_TRUE(creator_.HasPendingFrames()); } EXPECT_FALSE(creator_.HasPendingFrames()); } TEST_F(QuicPacketCreatorMultiplePacketsTest, NestedPeerAddressContextWithDifferentAddress) { QuicConnectionId client_connection_id1 = creator_.GetClientConnectionId(); QuicConnectionId server_connection_id1 = creator_.GetServerConnectionId(); QuicSocketAddress peer_addr(QuicIpAddress::Any4(), 12345); creator_.SetDefaultPeerAddress(peer_addr); QuicPacketCreator::ScopedPeerAddressContext context( &creator_, peer_addr, client_connection_id1, server_connection_id1); ASSERT_EQ(client_connection_id1, creator_.GetClientConnectionId()); ASSERT_EQ(server_connection_id1, creator_.GetServerConnectionId()); EXPECT_CALL(delegate_, ShouldGeneratePacket(_, _)) .WillRepeatedly(Return(true)); EXPECT_EQ(3u, creator_ .ConsumeData(QuicUtils::GetFirstBidirectionalStreamId( creator_.transport_version(), Perspective::IS_CLIENT), "foo", 0, NO_FIN) .bytes_consumed); EXPECT_TRUE(creator_.HasPendingFrames()); QuicSocketAddress peer_addr1(QuicIpAddress::Any4(), 12346); EXPECT_CALL(delegate_, OnSerializedPacket(_)) .WillOnce(Invoke([=, this](SerializedPacket packet) { EXPECT_EQ(peer_addr, packet.peer_address); ASSERT_EQ(1u, packet.retransmittable_frames.size()); EXPECT_EQ(STREAM_FRAME, packet.retransmittable_frames.front().type); QuicConnectionId client_connection_id2 = TestConnectionId(3); QuicConnectionId server_connection_id2 = TestConnectionId(4); QuicPacketCreator::ScopedPeerAddressContext context( &creator_, peer_addr1, client_connection_id2, server_connection_id2); ASSERT_EQ(client_connection_id2, creator_.GetClientConnectionId()); ASSERT_EQ(server_connection_id2, creator_.GetServerConnectionId()); EXPECT_CALL(delegate_, ShouldGeneratePacket(_, _)) .WillRepeatedly(Return(true)); EXPECT_EQ(3u, creator_ .ConsumeData(QuicUtils::GetFirstBidirectionalStreamId( creator_.transport_version(), Perspective::IS_CLIENT), "foo", 0, NO_FIN) .bytes_consumed); EXPECT_TRUE(creator_.HasPendingFrames()); creator_.FlushCurrentPacket(); })) .WillOnce(Invoke([=](SerializedPacket packet) { EXPECT_EQ(peer_addr1, packet.peer_address); ASSERT_EQ(1u, packet.retransmittable_frames.size()); EXPECT_EQ(STREAM_FRAME, packet.retransmittable_frames.front().type); })); creator_.FlushCurrentPacket(); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_packet_creator.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_packet_creator_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
3fab986a-3313-49b1-a984-9d57a4f12f38
cpp
google/quiche
internet_checksum
quiche/quic/core/internet_checksum.cc
quiche/quic/core/internet_checksum_test.cc
#include "quiche/quic/core/internet_checksum.h" #include <stdint.h> #include <string.h> #include "absl/strings/string_view.h" #include "absl/types/span.h" namespace quic { void InternetChecksum::Update(const char* data, size_t size) { const char* current; for (current = data; current + 1 < data + size; current += 2) { uint16_t v; memcpy(&v, current, sizeof(v)); accumulator_ += v; } if (current < data + size) { accumulator_ += *reinterpret_cast<const unsigned char*>(current); } } void InternetChecksum::Update(const uint8_t* data, size_t size) { Update(reinterpret_cast<const char*>(data), size); } void InternetChecksum::Update(absl::string_view data) { Update(data.data(), data.size()); } void InternetChecksum::Update(absl::Span<const uint8_t> data) { Update(reinterpret_cast<const char*>(data.data()), data.size()); } uint16_t InternetChecksum::Value() const { uint32_t total = accumulator_; while (total & 0xffff0000u) { total = (total >> 16u) + (total & 0xffffu); } return ~static_cast<uint16_t>(total); } }
#include "quiche/quic/core/internet_checksum.h" #include "quiche/quic/platform/api/quic_test.h" namespace quic { namespace { TEST(InternetChecksumTest, MatchesRFC1071Example) { uint8_t data[] = {0x00, 0x01, 0xf2, 0x03, 0xf4, 0xf5, 0xf6, 0xf7}; InternetChecksum checksum; checksum.Update(data, 8); uint16_t result = checksum.Value(); auto* result_bytes = reinterpret_cast<uint8_t*>(&result); ASSERT_EQ(0x22, result_bytes[0]); ASSERT_EQ(0x0d, result_bytes[1]); } TEST(InternetChecksumTest, MatchesRFC1071ExampleWithOddByteCount) { uint8_t data[] = {0x00, 0x01, 0xf2, 0x03, 0xf4, 0xf5, 0xf6}; InternetChecksum checksum; checksum.Update(data, 7); uint16_t result = checksum.Value(); auto* result_bytes = reinterpret_cast<uint8_t*>(&result); ASSERT_EQ(0x23, result_bytes[0]); ASSERT_EQ(0x04, result_bytes[1]); } TEST(InternetChecksumTest, MatchesBerkleyExample) { uint8_t data[] = {0xe3, 0x4f, 0x23, 0x96, 0x44, 0x27, 0x99, 0xf3}; InternetChecksum checksum; checksum.Update(data, 8); uint16_t result = checksum.Value(); auto* result_bytes = reinterpret_cast<uint8_t*>(&result); ASSERT_EQ(0x1a, result_bytes[0]); ASSERT_EQ(0xff, result_bytes[1]); } TEST(InternetChecksumTest, ChecksumRequiringMultipleCarriesInLittleEndian) { uint8_t data[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02, 0x00}; InternetChecksum checksum; checksum.Update(data, 8); uint16_t result = checksum.Value(); auto* result_bytes = reinterpret_cast<uint8_t*>(&result); EXPECT_EQ(0xfd, result_bytes[0]); EXPECT_EQ(0xff, result_bytes[1]); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/internet_checksum.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/internet_checksum_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
d43c021f-cd0c-40a6-968e-a0d750ae4d54
cpp
google/quiche
quic_dispatcher
quiche/quic/core/quic_dispatcher.cc
quiche/quic/core/quic_dispatcher_test.cc
#include "quiche/quic/core/quic_dispatcher.h" #include <openssl/ssl.h> #include <algorithm> #include <cstddef> #include <cstdint> #include <limits> #include <list> #include <memory> #include <optional> #include <ostream> #include <string> #include <utility> #include <vector> #include "absl/base/attributes.h" #include "absl/base/macros.h" #include "absl/base/optimization.h" #include "absl/container/flat_hash_set.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/chlo_extractor.h" #include "quiche/quic/core/connection_id_generator.h" #include "quiche/quic/core/crypto/crypto_handshake_message.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/crypto/quic_compressed_certs_cache.h" #include "quiche/quic/core/frames/quic_connection_close_frame.h" #include "quiche/quic/core/frames/quic_frame.h" #include "quiche/quic/core/frames/quic_rst_stream_frame.h" #include "quiche/quic/core/frames/quic_stop_sending_frame.h" #include "quiche/quic/core/quic_alarm.h" #include "quiche/quic/core/quic_alarm_factory.h" #include "quiche/quic/core/quic_blocked_writer_interface.h" #include "quiche/quic/core/quic_buffered_packet_store.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_crypto_server_stream_base.h" #include "quiche/quic/core/quic_data_writer.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_framer.h" #include "quiche/quic/core/quic_packet_creator.h" #include "quiche/quic/core/quic_packet_number.h" #include "quiche/quic/core/quic_packet_writer.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_session.h" #include "quiche/quic/core/quic_stream_frame_data_producer.h" #include "quiche/quic/core/quic_stream_send_buffer.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_time_wait_list_manager.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_version_manager.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/core/tls_chlo_extractor.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" #include "quiche/quic/platform/api/quic_stack_trace.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/print_elements.h" #include "quiche/common/quiche_buffer_allocator.h" #include "quiche/common/quiche_callbacks.h" #include "quiche/common/quiche_text_utils.h" namespace quic { using BufferedPacket = QuicBufferedPacketStore::BufferedPacket; using BufferedPacketList = QuicBufferedPacketStore::BufferedPacketList; using EnqueuePacketResult = QuicBufferedPacketStore::EnqueuePacketResult; namespace { const QuicPacketLength kMinClientInitialPacketLength = 1200; class DeleteSessionsAlarm : public QuicAlarm::DelegateWithoutContext { public: explicit DeleteSessionsAlarm(QuicDispatcher* dispatcher) : dispatcher_(dispatcher) {} DeleteSessionsAlarm(const DeleteSessionsAlarm&) = delete; DeleteSessionsAlarm& operator=(const DeleteSessionsAlarm&) = delete; void OnAlarm() override { dispatcher_->DeleteSessions(); } private: QuicDispatcher* dispatcher_; }; class ClearStatelessResetAddressesAlarm : public QuicAlarm::DelegateWithoutContext { public: explicit ClearStatelessResetAddressesAlarm(QuicDispatcher* dispatcher) : dispatcher_(dispatcher) {} ClearStatelessResetAddressesAlarm(const DeleteSessionsAlarm&) = delete; ClearStatelessResetAddressesAlarm& operator=(const DeleteSessionsAlarm&) = delete; void OnAlarm() override { dispatcher_->ClearStatelessResetAddresses(); } private: QuicDispatcher* dispatcher_; }; class StatelessConnectionTerminator { public: StatelessConnectionTerminator(QuicConnectionId server_connection_id, QuicConnectionId original_server_connection_id, const ParsedQuicVersion version, QuicPacketNumber last_sent_packet_number, QuicConnectionHelperInterface* helper, QuicTimeWaitListManager* time_wait_list_manager) : server_connection_id_(server_connection_id), framer_(ParsedQuicVersionVector{version}, QuicTime::Zero(), Perspective::IS_SERVER, kQuicDefaultConnectionIdLength), collector_(helper->GetStreamSendBufferAllocator()), creator_(server_connection_id, &framer_, &collector_), time_wait_list_manager_(time_wait_list_manager) { framer_.set_data_producer(&collector_); framer_.SetInitialObfuscators(original_server_connection_id); if (last_sent_packet_number.IsInitialized()) { QUICHE_DCHECK( GetQuicRestartFlag(quic_dispatcher_ack_buffered_initial_packets)); QUIC_RESTART_FLAG_COUNT_N(quic_dispatcher_ack_buffered_initial_packets, 3, 8); creator_.set_packet_number(last_sent_packet_number); } } ~StatelessConnectionTerminator() { framer_.set_data_producer(nullptr); } void CloseConnection(QuicErrorCode error_code, const std::string& error_details, bool ietf_quic, std::vector<QuicConnectionId> active_connection_ids) { SerializeConnectionClosePacket(error_code, error_details); time_wait_list_manager_->AddConnectionIdToTimeWait( QuicTimeWaitListManager::SEND_TERMINATION_PACKETS, TimeWaitConnectionInfo(ietf_quic, collector_.packets(), std::move(active_connection_ids), QuicTime::Delta::Zero())); } private: void SerializeConnectionClosePacket(QuicErrorCode error_code, const std::string& error_details) { QuicConnectionCloseFrame* frame = new QuicConnectionCloseFrame(framer_.transport_version(), error_code, NO_IETF_QUIC_ERROR, error_details, 0); if (!creator_.AddFrame(QuicFrame(frame), NOT_RETRANSMISSION)) { QUIC_BUG(quic_bug_10287_1) << "Unable to add frame to an empty packet"; delete frame; return; } creator_.FlushCurrentPacket(); QUICHE_DCHECK_EQ(1u, collector_.packets()->size()); } QuicConnectionId server_connection_id_; QuicFramer framer_; PacketCollector collector_; QuicPacketCreator creator_; QuicTimeWaitListManager* time_wait_list_manager_; }; class ChloAlpnSniExtractor : public ChloExtractor::Delegate { public: void OnChlo(QuicTransportVersion , QuicConnectionId , const CryptoHandshakeMessage& chlo) override { absl::string_view alpn_value; if (chlo.GetStringPiece(kALPN, &alpn_value)) { alpn_ = std::string(alpn_value); } absl::string_view sni; if (chlo.GetStringPiece(quic::kSNI, &sni)) { sni_ = std::string(sni); } absl::string_view uaid_value; if (chlo.GetStringPiece(quic::kUAID, &uaid_value)) { uaid_ = std::string(uaid_value); } } std::string&& ConsumeAlpn() { return std::move(alpn_); } std::string&& ConsumeSni() { return std::move(sni_); } std::string&& ConsumeUaid() { return std::move(uaid_); } private: std::string alpn_; std::string sni_; std::string uaid_; }; } QuicDispatcher::QuicDispatcher( const QuicConfig* config, const QuicCryptoServerConfig* crypto_config, QuicVersionManager* version_manager, std::unique_ptr<QuicConnectionHelperInterface> helper, std::unique_ptr<QuicCryptoServerStreamBase::Helper> session_helper, std::unique_ptr<QuicAlarmFactory> alarm_factory, uint8_t expected_server_connection_id_length, ConnectionIdGeneratorInterface& connection_id_generator) : config_(config), crypto_config_(crypto_config), compressed_certs_cache_( QuicCompressedCertsCache::kQuicCompressedCertsCacheSize), helper_(std::move(helper)), session_helper_(std::move(session_helper)), alarm_factory_(std::move(alarm_factory)), delete_sessions_alarm_( alarm_factory_->CreateAlarm(new DeleteSessionsAlarm(this))), buffered_packets_(this, helper_->GetClock(), alarm_factory_.get(), stats_), version_manager_(version_manager), last_error_(QUIC_NO_ERROR), new_sessions_allowed_per_event_loop_(0u), accept_new_connections_(true), expected_server_connection_id_length_( expected_server_connection_id_length), clear_stateless_reset_addresses_alarm_(alarm_factory_->CreateAlarm( new ClearStatelessResetAddressesAlarm(this))), connection_id_generator_(connection_id_generator) { QUIC_DLOG(INFO) << "Created QuicDispatcher with versions: " << ParsedQuicVersionVectorToString(GetSupportedVersions()); } QuicDispatcher::~QuicDispatcher() { if (delete_sessions_alarm_ != nullptr) { delete_sessions_alarm_->PermanentCancel(); } if (clear_stateless_reset_addresses_alarm_ != nullptr) { clear_stateless_reset_addresses_alarm_->PermanentCancel(); } reference_counted_session_map_.clear(); closed_session_list_.clear(); num_sessions_in_session_map_ = 0; } void QuicDispatcher::InitializeWithWriter(QuicPacketWriter* writer) { QUICHE_DCHECK(writer_ == nullptr); writer_.reset(writer); buffered_packets_.set_writer(writer); time_wait_list_manager_.reset(CreateQuicTimeWaitListManager()); } void QuicDispatcher::ProcessPacket(const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, const QuicReceivedPacket& packet) { QUIC_DVLOG(2) << "Dispatcher received encrypted " << packet.length() << " bytes:" << std::endl << quiche::QuicheTextUtils::HexDump( absl::string_view(packet.data(), packet.length())); ++stats_.packets_processed; ReceivedPacketInfo packet_info(self_address, peer_address, packet); std::string detailed_error; QuicErrorCode error; error = QuicFramer::ParsePublicHeaderDispatcherShortHeaderLengthUnknown( packet, &packet_info.form, &packet_info.long_packet_type, &packet_info.version_flag, &packet_info.use_length_prefix, &packet_info.version_label, &packet_info.version, &packet_info.destination_connection_id, &packet_info.source_connection_id, &packet_info.retry_token, &detailed_error, connection_id_generator_); if (error != QUIC_NO_ERROR) { SetLastError(error); QUIC_DLOG(ERROR) << detailed_error; return; } if (packet_info.destination_connection_id.length() != expected_server_connection_id_length_ && packet_info.version.IsKnown() && !packet_info.version.AllowsVariableLengthConnectionIds()) { SetLastError(QUIC_INVALID_PACKET_HEADER); QUIC_DLOG(ERROR) << "Invalid Connection Id Length"; return; } if (packet_info.version_flag && IsSupportedVersion(packet_info.version)) { if (!QuicUtils::IsConnectionIdValidForVersion( packet_info.destination_connection_id, packet_info.version.transport_version)) { SetLastError(QUIC_INVALID_PACKET_HEADER); QUIC_DLOG(ERROR) << "Invalid destination connection ID length for version"; return; } if (packet_info.version.SupportsClientConnectionIds() && !QuicUtils::IsConnectionIdValidForVersion( packet_info.source_connection_id, packet_info.version.transport_version)) { SetLastError(QUIC_INVALID_PACKET_HEADER); QUIC_DLOG(ERROR) << "Invalid source connection ID length for version"; return; } } #ifndef NDEBUG if (ack_buffered_initial_packets()) { const BufferedPacketList* packet_list = buffered_packets_.GetPacketList(packet_info.destination_connection_id); if (packet_list != nullptr && packet_list->replaced_connection_id.has_value() && *packet_list->replaced_connection_id == packet_info.destination_connection_id) { QUIC_RESTART_FLAG_COUNT_N(quic_dispatcher_ack_buffered_initial_packets, 4, 8); ++stats_.packets_processed_with_replaced_cid_in_store; } } #endif if (MaybeDispatchPacket(packet_info)) { return; } if (!packet_info.version_flag && IsSupportedVersion(ParsedQuicVersion::Q046())) { ReceivedPacketInfo gquic_packet_info(self_address, peer_address, packet); const QuicErrorCode gquic_error = QuicFramer::ParsePublicHeaderDispatcher( packet, expected_server_connection_id_length_, &gquic_packet_info.form, &gquic_packet_info.long_packet_type, &gquic_packet_info.version_flag, &gquic_packet_info.use_length_prefix, &gquic_packet_info.version_label, &gquic_packet_info.version, &gquic_packet_info.destination_connection_id, &gquic_packet_info.source_connection_id, &gquic_packet_info.retry_token, &detailed_error); if (gquic_error == QUIC_NO_ERROR) { if (MaybeDispatchPacket(gquic_packet_info)) { return; } } else { QUICHE_VLOG(1) << "Tried to parse short header as gQUIC packet: " << detailed_error; } } ProcessHeader(&packet_info); } namespace { constexpr bool IsSourceUdpPortBlocked(uint16_t port) { constexpr uint16_t blocked_ports[] = { 0, 17, 19, 53, 111, 123, 137, 138, 161, 389, 500, 1900, 3702, 5353, 5355, 11211, }; constexpr size_t num_blocked_ports = ABSL_ARRAYSIZE(blocked_ports); constexpr uint16_t highest_blocked_port = blocked_ports[num_blocked_ports - 1]; if (ABSL_PREDICT_TRUE(port > highest_blocked_port)) { return false; } for (size_t i = 0; i < num_blocked_ports; i++) { if (port == blocked_ports[i]) { return true; } } return false; } } bool QuicDispatcher::MaybeDispatchPacket( const ReceivedPacketInfo& packet_info) { if (IsSourceUdpPortBlocked(packet_info.peer_address.port())) { QUIC_CODE_COUNT(quic_dropped_blocked_port); return true; } const QuicConnectionId server_connection_id = packet_info.destination_connection_id; if (packet_info.version_flag && packet_info.version.IsKnown() && IsServerConnectionIdTooShort(server_connection_id)) { QUICHE_DCHECK(packet_info.version_flag); QUICHE_DCHECK(packet_info.version.AllowsVariableLengthConnectionIds()); QUIC_DLOG(INFO) << "Packet with short destination connection ID " << server_connection_id << " expected " << static_cast<int>(expected_server_connection_id_length_); QUIC_CODE_COUNT(quic_dropped_invalid_small_initial_connection_id); return true; } if (packet_info.version_flag && packet_info.version.IsKnown() && !QuicUtils::IsConnectionIdLengthValidForVersion( server_connection_id.length(), packet_info.version.transport_version)) { QUIC_DLOG(INFO) << "Packet with destination connection ID " << server_connection_id << " is invalid with version " << packet_info.version; QUIC_CODE_COUNT(quic_dropped_invalid_initial_connection_id); return true; } auto it = reference_counted_session_map_.find(server_connection_id); if (it != reference_counted_session_map_.end()) { QUICHE_DCHECK(!buffered_packets_.HasBufferedPackets(server_connection_id)); it->second->ProcessUdpPacket(packet_info.self_address, packet_info.peer_address, packet_info.packet); return true; } if (buffered_packets_.HasChloForConnection(server_connection_id)) { EnqueuePacketResult rs = buffered_packets_.EnqueuePacket( packet_info, std::nullopt, ConnectionIdGenerator()); switch (rs) { case EnqueuePacketResult::SUCCESS: break; case EnqueuePacketResult::CID_COLLISION: QUICHE_DCHECK(false) << "Connection " << server_connection_id << " already has a CHLO buffered, but " "EnqueuePacket returned CID_COLLISION."; ABSL_FALLTHROUGH_INTENDED; case EnqueuePacketResult::TOO_MANY_PACKETS: ABSL_FALLTHROUGH_INTENDED; case EnqueuePacketResult::TOO_MANY_CONNECTIONS: OnBufferPacketFailure(rs, packet_info.destination_connection_id); break; } return true; } if (OnFailedToDispatchPacket(packet_info)) { return true; } if (time_wait_list_manager_->IsConnectionIdInTimeWait(server_connection_id)) { time_wait_list_manager_->ProcessPacket( packet_info.self_address, packet_info.peer_address, packet_info.destination_connection_id, packet_info.form, packet_info.packet.length(), GetPerPacketContext()); return true; } if (!accept_new_connections_ && packet_info.version_flag) { StatelesslyTerminateConnection( packet_info.self_address, packet_info.peer_address, packet_info.destination_connection_id, packet_info.form, packet_info.version_flag, packet_info.use_length_prefix, packet_info.version, QUIC_HANDSHAKE_FAILED, "Stop accepting new connections", quic::QuicTimeWaitListManager::SEND_STATELESS_RESET); time_wait_list_manager()->ProcessPacket( packet_info.self_address, packet_info.peer_address, packet_info.destination_connection_id, packet_info.form, packet_info.packet.length(), GetPerPacketContext()); OnNewConnectionRejected(); return true; } if (packet_info.version_flag) { if (!IsSupportedVersion(packet_info.version)) { if (ShouldCreateSessionForUnknownVersion(packet_info)) { return false; } MaybeSendVersionNegotiationPacket(packet_info); return true; } if (crypto_config()->validate_chlo_size() && packet_info.form == IETF_QUIC_LONG_HEADER_PACKET && packet_info.long_packet_type == INITIAL && packet_info.packet.length() < kMinClientInitialPacketLength) { QUIC_DVLOG(1) << "Dropping initial packet which is too short, length: " << packet_info.packet.length(); QUIC_CODE_COUNT(quic_drop_small_initial_packets); return true; } } return false; } void QuicDispatcher::ProcessHeader(ReceivedPacketInfo* packet_info) { ++stats_.packets_processed_with_unknown_cid; QuicConnectionId server_connection_id = packet_info->destination_connection_id; QuicPacketFate fate = ValidityChecks(*packet_info); QuicErrorCode connection_close_error_code = QUIC_HANDSHAKE_FAILED; std::string tls_alert_error_detail; if (fate == kFateProcess) { ExtractChloResult extract_chlo_result = TryExtractChloOrBufferEarlyPacket(*packet_info); auto& parsed_chlo = extract_chlo_result.parsed_chlo; if (extract_chlo_result.tls_alert.has_value()) { QUIC_BUG_IF(quic_dispatcher_parsed_chlo_and_tls_alert_coexist_1, parsed_chlo.has_value()) << "parsed_chlo and tls_alert should not be set at the same time."; fate = kFateTimeWait; uint8_t tls_alert = *extract_chlo_result.tls_alert; connection_close_error_code = TlsAlertToQuicErrorCode(tls_alert); tls_alert_error_detail = absl::StrCat("TLS handshake failure from dispatcher (", EncryptionLevelToString(ENCRYPTION_INITIAL), ") ", static_cast<int>(tls_alert), ": ", SSL_alert_desc_string_long(tls_alert)); } else if (!parsed_chlo.has_value()) { return; } else { fate = ValidityChecksOnFullChlo(*packet_info, *parsed_chlo); if (fate == kFateProcess) { ProcessChlo(*std::move(parsed_chlo), packet_info); return; } } } switch (fate) { case kFateProcess: QUIC_BUG(quic_dispatcher_bad_packet_fate) << fate; break; case kFateTimeWait: { QUIC_DLOG(INFO) << "Adding connection ID " << server_connection_id << " to time-wait list."; QUIC_CODE_COUNT(quic_reject_fate_time_wait); const std::string& connection_close_error_detail = tls_alert_error_detail.empty() ? "Reject connection" : tls_alert_error_detail; StatelesslyTerminateConnection( packet_info->self_address, packet_info->peer_address, server_connection_id, packet_info->form, packet_info->version_flag, packet_info->use_length_prefix, packet_info->version, connection_close_error_code, connection_close_error_detail, quic::QuicTimeWaitListManager::SEND_STATELESS_RESET); QUICHE_DCHECK(time_wait_list_manager_->IsConnectionIdInTimeWait( server_connection_id)); time_wait_list_manager_->ProcessPacket( packet_info->self_address, packet_info->peer_address, server_connection_id, packet_info->form, packet_info->packet.length(), GetPerPacketContext()); buffered_packets_.DiscardPackets(server_connection_id); } break; case kFateDrop: break; } } QuicDispatcher::ExtractChloResult QuicDispatcher::TryExtractChloOrBufferEarlyPacket( const ReceivedPacketInfo& packet_info) { ExtractChloResult result; if (packet_info.version.UsesTls()) { bool has_full_tls_chlo = false; std::string sni; std::vector<uint16_t> supported_groups; std::vector<uint16_t> cert_compression_algos; std::vector<std::string> alpns; bool resumption_attempted = false, early_data_attempted = false; if (buffered_packets_.HasBufferedPackets( packet_info.destination_connection_id)) { has_full_tls_chlo = buffered_packets_.IngestPacketForTlsChloExtraction( packet_info.destination_connection_id, packet_info.version, packet_info.packet, &supported_groups, &cert_compression_algos, &alpns, &sni, &resumption_attempted, &early_data_attempted, &result.tls_alert); } else { TlsChloExtractor tls_chlo_extractor; tls_chlo_extractor.IngestPacket(packet_info.version, packet_info.packet); if (tls_chlo_extractor.HasParsedFullChlo()) { has_full_tls_chlo = true; supported_groups = tls_chlo_extractor.supported_groups(); cert_compression_algos = tls_chlo_extractor.cert_compression_algos(); alpns = tls_chlo_extractor.alpns(); sni = tls_chlo_extractor.server_name(); resumption_attempted = tls_chlo_extractor.resumption_attempted(); early_data_attempted = tls_chlo_extractor.early_data_attempted(); } else { result.tls_alert = tls_chlo_extractor.tls_alert(); } } if (result.tls_alert.has_value()) { QUIC_BUG_IF(quic_dispatcher_parsed_chlo_and_tls_alert_coexist_2, has_full_tls_chlo) << "parsed_chlo and tls_alert should not be set at the same time."; return result; } if (GetQuicFlag(quic_allow_chlo_buffering) && !has_full_tls_chlo) { EnqueuePacketResult rs = buffered_packets_.EnqueuePacket( packet_info, std::nullopt, ConnectionIdGenerator()); switch (rs) { case EnqueuePacketResult::SUCCESS: break; case EnqueuePacketResult::CID_COLLISION: buffered_packets_.DiscardPackets( packet_info.destination_connection_id); ABSL_FALLTHROUGH_INTENDED; case EnqueuePacketResult::TOO_MANY_PACKETS: ABSL_FALLTHROUGH_INTENDED; case EnqueuePacketResult::TOO_MANY_CONNECTIONS: OnBufferPacketFailure(rs, packet_info.destination_connection_id); break; } return result; } ParsedClientHello& parsed_chlo = result.parsed_chlo.emplace(); parsed_chlo.sni = std::move(sni); parsed_chlo.supported_groups = std::move(supported_groups); parsed_chlo.cert_compression_algos = std::move(cert_compression_algos); parsed_chlo.alpns = std::move(alpns); if (packet_info.retry_token.has_value()) { parsed_chlo.retry_token = std::string(*packet_info.retry_token); } parsed_chlo.resumption_attempted = resumption_attempted; parsed_chlo.early_data_attempted = early_data_attempted; return result; } ChloAlpnSniExtractor alpn_extractor; if (GetQuicFlag(quic_allow_chlo_buffering) && !ChloExtractor::Extract(packet_info.packet, packet_info.version, config_->create_session_tag_indicators(), &alpn_extractor, packet_info.destination_connection_id.length())) { EnqueuePacketResult rs = buffered_packets_.EnqueuePacket( packet_info, std::nullopt, ConnectionIdGenerator()); switch (rs) { case EnqueuePacketResult::SUCCESS: break; case EnqueuePacketResult::CID_COLLISION: QUIC_BUG(quic_store_cid_collision_from_gquic_packet); ABSL_FALLTHROUGH_INTENDED; case EnqueuePacketResult::TOO_MANY_PACKETS: ABSL_FALLTHROUGH_INTENDED; case EnqueuePacketResult::TOO_MANY_CONNECTIONS: OnBufferPacketFailure(rs, packet_info.destination_connection_id); break; } return result; } ParsedClientHello& parsed_chlo = result.parsed_chlo.emplace(); parsed_chlo.sni = alpn_extractor.ConsumeSni(); parsed_chlo.uaid = alpn_extractor.ConsumeUaid(); parsed_chlo.alpns = {alpn_extractor.ConsumeAlpn()}; return result; } std::string QuicDispatcher::SelectAlpn(const std::vector<std::string>& alpns) { if (alpns.empty()) { return ""; } if (alpns.size() > 1u) { const std::vector<std::string>& supported_alpns = version_manager_->GetSupportedAlpns(); for (const std::string& alpn : alpns) { if (std::find(supported_alpns.begin(), supported_alpns.end(), alpn) != supported_alpns.end()) { return alpn; } } } return alpns[0]; } QuicDispatcher::QuicPacketFate QuicDispatcher::ValidityChecks( const ReceivedPacketInfo& packet_info) { if (!packet_info.version_flag) { QUIC_DLOG(INFO) << "Packet without version arrived for unknown connection ID " << packet_info.destination_connection_id; MaybeResetPacketsWithNoVersion(packet_info); return kFateDrop; } return kFateProcess; } void QuicDispatcher::CleanUpSession(QuicConnectionId server_connection_id, QuicConnection* connection, QuicErrorCode , const std::string& , ConnectionCloseSource ) { write_blocked_list_.Remove(*connection); QuicTimeWaitListManager::TimeWaitAction action = QuicTimeWaitListManager::SEND_STATELESS_RESET; if (connection->termination_packets() != nullptr && !connection->termination_packets()->empty()) { action = QuicTimeWaitListManager::SEND_CONNECTION_CLOSE_PACKETS; } else { if (!connection->IsHandshakeComplete()) { QUIC_CODE_COUNT(quic_v44_add_to_time_wait_list_with_handshake_failed); StatelessConnectionTerminator terminator( server_connection_id, connection->GetOriginalDestinationConnectionId(), connection->version(), QuicPacketNumber(), helper_.get(), time_wait_list_manager_.get()); terminator.CloseConnection( QUIC_HANDSHAKE_FAILED, "Connection is closed by server before handshake confirmed", true, connection->GetActiveServerConnectionIds()); return; } QUIC_CODE_COUNT(quic_v44_add_to_time_wait_list_with_stateless_reset); } time_wait_list_manager_->AddConnectionIdToTimeWait( action, TimeWaitConnectionInfo( true, connection->termination_packets(), connection->GetActiveServerConnectionIds(), connection->sent_packet_manager().GetRttStats()->smoothed_rtt())); } void QuicDispatcher::StartAcceptingNewConnections() { accept_new_connections_ = true; } void QuicDispatcher::StopAcceptingNewConnections() { accept_new_connections_ = false; buffered_packets_.DiscardAllPackets(); } void QuicDispatcher::PerformActionOnActiveSessions( quiche::UnretainedCallback<void(QuicSession*)> operation) const { absl::flat_hash_set<QuicSession*> visited_session; visited_session.reserve(reference_counted_session_map_.size()); for (auto const& kv : reference_counted_session_map_) { QuicSession* session = kv.second.get(); if (visited_session.insert(session).second) { operation(session); } } } std::vector<std::shared_ptr<QuicSession>> QuicDispatcher::GetSessionsSnapshot() const { std::vector<std::shared_ptr<QuicSession>> snapshot; snapshot.reserve(reference_counted_session_map_.size()); absl::flat_hash_set<QuicSession*> visited_session; visited_session.reserve(reference_counted_session_map_.size()); for (auto const& kv : reference_counted_session_map_) { QuicSession* session = kv.second.get(); if (visited_session.insert(session).second) { snapshot.push_back(kv.second); } } return snapshot; } std::unique_ptr<QuicPerPacketContext> QuicDispatcher::GetPerPacketContext() const { return nullptr; } void QuicDispatcher::DeleteSessions() { if (!write_blocked_list_.Empty()) { for (const auto& session : closed_session_list_) { if (write_blocked_list_.Remove(*session->connection())) { QUIC_BUG(quic_bug_12724_2) << "QuicConnection was in WriteBlockedList before destruction " << session->connection()->connection_id(); } } } closed_session_list_.clear(); } void QuicDispatcher::ClearStatelessResetAddresses() { recent_stateless_reset_addresses_.clear(); } void QuicDispatcher::OnCanWrite() { writer_->SetWritable(); write_blocked_list_.OnWriterUnblocked(); } bool QuicDispatcher::HasPendingWrites() const { return !write_blocked_list_.Empty(); } void QuicDispatcher::Shutdown() { while (!reference_counted_session_map_.empty()) { QuicSession* session = reference_counted_session_map_.begin()->second.get(); session->connection()->CloseConnection( QUIC_PEER_GOING_AWAY, "Server shutdown imminent", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); QUICHE_DCHECK(reference_counted_session_map_.empty() || reference_counted_session_map_.begin()->second.get() != session); } DeleteSessions(); } void QuicDispatcher::OnConnectionClosed(QuicConnectionId server_connection_id, QuicErrorCode error, const std::string& error_details, ConnectionCloseSource source) { auto it = reference_counted_session_map_.find(server_connection_id); if (it == reference_counted_session_map_.end()) { QUIC_BUG(quic_bug_10287_3) << "ConnectionId " << server_connection_id << " does not exist in the session map. Error: " << QuicErrorCodeToString(error); QUIC_BUG(quic_bug_10287_4) << QuicStackTrace(); return; } QUIC_DLOG_IF(INFO, error != QUIC_NO_ERROR) << "Closing connection (" << server_connection_id << ") due to error: " << QuicErrorCodeToString(error) << ", with details: " << error_details; const QuicSession* session = it->second.get(); QuicConnection* connection = it->second->connection(); if (closed_session_list_.empty()) { delete_sessions_alarm_->Update(helper()->GetClock()->ApproximateNow(), QuicTime::Delta::Zero()); } closed_session_list_.push_back(std::move(it->second)); CleanUpSession(it->first, connection, error, error_details, source); bool session_removed = false; for (const QuicConnectionId& cid : connection->GetActiveServerConnectionIds()) { auto it1 = reference_counted_session_map_.find(cid); if (it1 != reference_counted_session_map_.end()) { const QuicSession* session2 = it1->second.get(); if (session2 == session || cid == server_connection_id) { reference_counted_session_map_.erase(it1); session_removed = true; } else { QUIC_BUG(quic_dispatcher_session_mismatch) << "Session is mismatched in the map. server_connection_id: " << server_connection_id << ". Current cid: " << cid << ". Cid of the other session " << (session2 == nullptr ? "null" : session2->connection()->connection_id().ToString()); } } else { QUIC_BUG_IF(quic_dispatcher_session_not_found, cid != connection->GetOriginalDestinationConnectionId()) << "Missing session for cid " << cid << ". server_connection_id: " << server_connection_id; } } QUIC_BUG_IF(quic_session_is_not_removed, !session_removed); --num_sessions_in_session_map_; } void QuicDispatcher::OnWriteBlocked( QuicBlockedWriterInterface* blocked_writer) { write_blocked_list_.Add(*blocked_writer); } void QuicDispatcher::OnRstStreamReceived(const QuicRstStreamFrame& ) {} void QuicDispatcher::OnStopSendingReceived( const QuicStopSendingFrame& ) {} bool QuicDispatcher::TryAddNewConnectionId( const QuicConnectionId& server_connection_id, const QuicConnectionId& new_connection_id) { auto it = reference_counted_session_map_.find(server_connection_id); if (it == reference_counted_session_map_.end()) { QUIC_BUG(quic_bug_10287_7) << "Couldn't locate the session that issues the connection ID in " "reference_counted_session_map_. server_connection_id:" << server_connection_id << " new_connection_id: " << new_connection_id; return false; } auto insertion_result = reference_counted_session_map_.insert( std::make_pair(new_connection_id, it->second)); if (!insertion_result.second) { QUIC_CODE_COUNT(quic_cid_already_in_session_map); } return insertion_result.second; } void QuicDispatcher::OnConnectionIdRetired( const QuicConnectionId& server_connection_id) { reference_counted_session_map_.erase(server_connection_id); } void QuicDispatcher::OnConnectionAddedToTimeWaitList( QuicConnectionId server_connection_id) { QUIC_DLOG(INFO) << "Connection " << server_connection_id << " added to time wait list."; } void QuicDispatcher::StatelesslyTerminateConnection( const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, QuicConnectionId server_connection_id, PacketHeaderFormat format, bool version_flag, bool use_length_prefix, ParsedQuicVersion version, QuicErrorCode error_code, const std::string& error_details, QuicTimeWaitListManager::TimeWaitAction action) { const BufferedPacketList* packet_list = buffered_packets_.GetPacketList(server_connection_id); if (packet_list == nullptr) { StatelesslyTerminateConnection( self_address, peer_address, server_connection_id, format, version_flag, use_length_prefix, version, error_code, error_details, action, std::nullopt, QuicPacketNumber()); return; } QUIC_RESTART_FLAG_COUNT_N(quic_dispatcher_ack_buffered_initial_packets, 5, 8); StatelesslyTerminateConnection( self_address, peer_address, packet_list->original_connection_id, format, version_flag, use_length_prefix, version, error_code, error_details, action, packet_list->replaced_connection_id, packet_list->GetLastSentPacketNumber()); } void QuicDispatcher::StatelesslyTerminateConnection( const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, QuicConnectionId server_connection_id, PacketHeaderFormat format, bool version_flag, bool use_length_prefix, ParsedQuicVersion version, QuicErrorCode error_code, const std::string& error_details, QuicTimeWaitListManager::TimeWaitAction action, const std::optional<QuicConnectionId>& replaced_connection_id, QuicPacketNumber last_sent_packet_number) { if (format != IETF_QUIC_LONG_HEADER_PACKET && !version_flag) { QUIC_DVLOG(1) << "Statelessly terminating " << server_connection_id << " based on a non-ietf-long packet, action:" << action << ", error_code:" << error_code << ", error_details:" << error_details; time_wait_list_manager_->AddConnectionIdToTimeWait( action, TimeWaitConnectionInfo(format != GOOGLE_QUIC_PACKET, nullptr, {server_connection_id})); return; } if (IsSupportedVersion(version)) { QUIC_DVLOG(1) << "Statelessly terminating " << server_connection_id << " based on an ietf-long packet, which has a supported version:" << version << ", error_code:" << error_code << ", error_details:" << error_details << ", replaced_connection_id:" << (replaced_connection_id.has_value() ? replaced_connection_id->ToString() : "n/a"); if (ack_buffered_initial_packets()) { QuicConnectionId original_connection_id = server_connection_id; if (last_sent_packet_number.IsInitialized()) { QUIC_RESTART_FLAG_COUNT_N(quic_dispatcher_ack_buffered_initial_packets, 6, 8); } StatelessConnectionTerminator terminator( replaced_connection_id.value_or(original_connection_id), original_connection_id, version, last_sent_packet_number, helper_.get(), time_wait_list_manager_.get()); std::vector<QuicConnectionId> active_connection_ids = { original_connection_id}; if (replaced_connection_id.has_value()) { active_connection_ids.push_back(*replaced_connection_id); } terminator.CloseConnection(error_code, error_details, format != GOOGLE_QUIC_PACKET, std::move(active_connection_ids)); } else { StatelessConnectionTerminator terminator( server_connection_id, server_connection_id, version, last_sent_packet_number, helper_.get(), time_wait_list_manager_.get()); terminator.CloseConnection( error_code, error_details, format != GOOGLE_QUIC_PACKET, {server_connection_id}); } QUIC_CODE_COUNT(quic_dispatcher_generated_connection_close); QuicSession::RecordConnectionCloseAtServer( error_code, ConnectionCloseSource::FROM_SELF); OnStatelessConnectionCloseGenerated(self_address, peer_address, server_connection_id, version, error_code, error_details); return; } QUIC_DVLOG(1) << "Statelessly terminating " << server_connection_id << " based on an ietf-long packet, which has an unsupported version:" << version << ", error_code:" << error_code << ", error_details:" << error_details; std::vector<std::unique_ptr<QuicEncryptedPacket>> termination_packets; termination_packets.push_back(QuicFramer::BuildVersionNegotiationPacket( server_connection_id, EmptyQuicConnectionId(), format != GOOGLE_QUIC_PACKET, use_length_prefix, {})); time_wait_list_manager()->AddConnectionIdToTimeWait( QuicTimeWaitListManager::SEND_TERMINATION_PACKETS, TimeWaitConnectionInfo(format != GOOGLE_QUIC_PACKET, &termination_packets, {server_connection_id})); } bool QuicDispatcher::ShouldCreateSessionForUnknownVersion( const ReceivedPacketInfo& ) { return false; } void QuicDispatcher::OnExpiredPackets( QuicConnectionId server_connection_id, BufferedPacketList early_arrived_packets) { QUIC_CODE_COUNT(quic_reject_buffered_packets_expired); QuicErrorCode error_code = QUIC_HANDSHAKE_FAILED_PACKETS_BUFFERED_TOO_LONG; QuicSocketAddress self_address, peer_address; if (!early_arrived_packets.buffered_packets.empty()) { self_address = early_arrived_packets.buffered_packets.front().self_address; peer_address = early_arrived_packets.buffered_packets.front().peer_address; } if (ack_buffered_initial_packets()) { QUIC_RESTART_FLAG_COUNT_N(quic_dispatcher_ack_buffered_initial_packets, 7, 8); StatelesslyTerminateConnection( self_address, peer_address, early_arrived_packets.original_connection_id, early_arrived_packets.ietf_quic ? IETF_QUIC_LONG_HEADER_PACKET : GOOGLE_QUIC_PACKET, true, early_arrived_packets.version.HasLengthPrefixedConnectionIds(), early_arrived_packets.version, error_code, "Packets buffered for too long", quic::QuicTimeWaitListManager::SEND_STATELESS_RESET, early_arrived_packets.replaced_connection_id, early_arrived_packets.GetLastSentPacketNumber()); } else { StatelesslyTerminateConnection( self_address, peer_address, server_connection_id, early_arrived_packets.ietf_quic ? IETF_QUIC_LONG_HEADER_PACKET : GOOGLE_QUIC_PACKET, true, early_arrived_packets.version.HasLengthPrefixedConnectionIds(), early_arrived_packets.version, error_code, "Packets buffered for too long", quic::QuicTimeWaitListManager::SEND_STATELESS_RESET); } } void QuicDispatcher::ProcessBufferedChlos(size_t max_connections_to_create) { new_sessions_allowed_per_event_loop_ = max_connections_to_create; for (; new_sessions_allowed_per_event_loop_ > 0; --new_sessions_allowed_per_event_loop_) { QuicConnectionId server_connection_id; BufferedPacketList packet_list = buffered_packets_.DeliverPacketsForNextConnection( &server_connection_id); const std::list<BufferedPacket>& packets = packet_list.buffered_packets; if (packets.empty()) { return; } if (!packet_list.parsed_chlo.has_value()) { QUIC_BUG(quic_dispatcher_no_parsed_chlo_in_buffered_packets) << "Buffered connection has no CHLO. connection_id:" << server_connection_id; continue; } auto session_ptr = CreateSessionFromChlo( server_connection_id, packet_list.replaced_connection_id, *packet_list.parsed_chlo, packet_list.version, packets.front().self_address, packets.front().peer_address, packet_list.tls_chlo_extractor.state(), packet_list.connection_id_generator, packet_list.dispatcher_sent_packets); if (session_ptr != nullptr) { DeliverPacketsToSession(packets, session_ptr.get()); } } } bool QuicDispatcher::HasChlosBuffered() const { return buffered_packets_.HasChlosBuffered(); } bool QuicDispatcher::HasBufferedPackets(QuicConnectionId server_connection_id) { return buffered_packets_.HasBufferedPackets(server_connection_id); } void QuicDispatcher::OnBufferPacketFailure( EnqueuePacketResult result, QuicConnectionId server_connection_id) { QUIC_DLOG(INFO) << "Fail to buffer packet on connection " << server_connection_id << " because of " << result; } QuicTimeWaitListManager* QuicDispatcher::CreateQuicTimeWaitListManager() { return new QuicTimeWaitListManager(writer_.get(), this, helper_->GetClock(), alarm_factory_.get()); } void QuicDispatcher::ProcessChlo(ParsedClientHello parsed_chlo, ReceivedPacketInfo* packet_info) { if (GetQuicFlag(quic_allow_chlo_buffering) && new_sessions_allowed_per_event_loop_ <= 0) { QUIC_BUG_IF(quic_bug_12724_7, buffered_packets_.HasChloForConnection( packet_info->destination_connection_id)); EnqueuePacketResult rs = buffered_packets_.EnqueuePacket( *packet_info, std::move(parsed_chlo), ConnectionIdGenerator()); switch (rs) { case EnqueuePacketResult::SUCCESS: break; case EnqueuePacketResult::CID_COLLISION: buffered_packets_.DiscardPackets( packet_info->destination_connection_id); ABSL_FALLTHROUGH_INTENDED; case EnqueuePacketResult::TOO_MANY_PACKETS: ABSL_FALLTHROUGH_INTENDED; case EnqueuePacketResult::TOO_MANY_CONNECTIONS: OnBufferPacketFailure(rs, packet_info->destination_connection_id); break; } return; } BufferedPacketList packet_list = buffered_packets_.DeliverPackets(packet_info->destination_connection_id); QuicConnectionId original_connection_id = packet_list.buffered_packets.empty() ? packet_info->destination_connection_id : packet_list.original_connection_id; TlsChloExtractor::State chlo_extractor_state = packet_list.buffered_packets.empty() ? TlsChloExtractor::State::kParsedFullSinglePacketChlo : packet_list.tls_chlo_extractor.state(); auto session_ptr = CreateSessionFromChlo( original_connection_id, packet_list.replaced_connection_id, parsed_chlo, packet_info->version, packet_info->self_address, packet_info->peer_address, chlo_extractor_state, packet_list.connection_id_generator, packet_list.dispatcher_sent_packets); if (session_ptr == nullptr) { QUICHE_DCHECK_EQ(packet_list.connection_id_generator, nullptr); return; } session_ptr->ProcessUdpPacket(packet_info->self_address, packet_info->peer_address, packet_info->packet); DeliverPacketsToSession(packet_list.buffered_packets, session_ptr.get()); --new_sessions_allowed_per_event_loop_; } void QuicDispatcher::SetLastError(QuicErrorCode error) { last_error_ = error; } bool QuicDispatcher::OnFailedToDispatchPacket( const ReceivedPacketInfo& ) { return false; } const ParsedQuicVersionVector& QuicDispatcher::GetSupportedVersions() { return version_manager_->GetSupportedVersions(); } void QuicDispatcher::DeliverPacketsToSession( const std::list<BufferedPacket>& packets, QuicSession* session) { for (const BufferedPacket& packet : packets) { session->ProcessUdpPacket(packet.self_address, packet.peer_address, *(packet.packet)); } } bool QuicDispatcher::IsSupportedVersion(const ParsedQuicVersion version) { for (const ParsedQuicVersion& supported_version : version_manager_->GetSupportedVersions()) { if (version == supported_version) { return true; } } return false; } bool QuicDispatcher::IsServerConnectionIdTooShort( QuicConnectionId connection_id) const { if (connection_id.length() >= kQuicMinimumInitialConnectionIdLength || connection_id.length() >= expected_server_connection_id_length_) { return false; } uint8_t generator_output = connection_id.IsEmpty() ? connection_id_generator_.ConnectionIdLength(0x00) : connection_id_generator_.ConnectionIdLength( static_cast<uint8_t>(*connection_id.data())); return connection_id.length() < generator_output; } std::shared_ptr<QuicSession> QuicDispatcher::CreateSessionFromChlo( const QuicConnectionId original_connection_id, const std::optional<QuicConnectionId>& replaced_connection_id, const ParsedClientHello& parsed_chlo, const ParsedQuicVersion version, const QuicSocketAddress self_address, const QuicSocketAddress peer_address, TlsChloExtractor::State chlo_extractor_state, ConnectionIdGeneratorInterface* connection_id_generator, absl::Span<const DispatcherSentPacket> dispatcher_sent_packets) { bool should_generate_cid = false; if (connection_id_generator == nullptr) { should_generate_cid = true; connection_id_generator = &ConnectionIdGenerator(); } std::optional<QuicConnectionId> server_connection_id; if (should_generate_cid) { server_connection_id = connection_id_generator->MaybeReplaceConnectionId( original_connection_id, version); if (server_connection_id.has_value() && (server_connection_id->IsEmpty() || *server_connection_id == original_connection_id)) { server_connection_id.reset(); } QUIC_DVLOG(1) << "MaybeReplaceConnectionId(" << original_connection_id << ") = " << (server_connection_id.has_value() ? server_connection_id->ToString() : "nullopt"); if (server_connection_id.has_value()) { switch (HandleConnectionIdCollision( original_connection_id, *server_connection_id, self_address, peer_address, version, &parsed_chlo)) { case VisitorInterface::HandleCidCollisionResult::kOk: break; case VisitorInterface::HandleCidCollisionResult::kCollision: return nullptr; } } } else { server_connection_id = replaced_connection_id; } const bool connection_id_replaced = server_connection_id.has_value(); if (!connection_id_replaced) { server_connection_id = original_connection_id; } std::string alpn = SelectAlpn(parsed_chlo.alpns); std::unique_ptr<QuicSession> session = CreateQuicSession(*server_connection_id, self_address, peer_address, alpn, version, parsed_chlo, *connection_id_generator); if (ABSL_PREDICT_FALSE(session == nullptr)) { QUIC_BUG(quic_bug_10287_8) << "CreateQuicSession returned nullptr for " << *server_connection_id << " from " << peer_address << " to " << self_address << " ALPN \"" << alpn << "\" version " << version; return nullptr; } ++stats_.sessions_created; if (chlo_extractor_state == TlsChloExtractor::State::kParsedFullMultiPacketChlo) { QUIC_CODE_COUNT(quic_connection_created_multi_packet_chlo); session->connection()->SetMultiPacketClientHello(); } else { QUIC_CODE_COUNT(quic_connection_created_single_packet_chlo); } if (ack_buffered_initial_packets() && !dispatcher_sent_packets.empty()) { QUIC_RESTART_FLAG_COUNT_N(quic_dispatcher_ack_buffered_initial_packets, 8, 8); session->connection()->AddDispatcherSentPackets(dispatcher_sent_packets); } if (connection_id_replaced) { session->connection()->SetOriginalDestinationConnectionId( original_connection_id); } session->connection()->OnParsedClientHelloInfo(parsed_chlo); QUIC_DLOG(INFO) << "Created new session for " << *server_connection_id; auto insertion_result = reference_counted_session_map_.insert(std::make_pair( *server_connection_id, std::shared_ptr<QuicSession>(std::move(session)))); std::shared_ptr<QuicSession> session_ptr = insertion_result.first->second; if (!insertion_result.second) { QUIC_BUG(quic_bug_10287_9) << "Tried to add a session to session_map with existing " "connection id: " << *server_connection_id; } else { ++num_sessions_in_session_map_; if (connection_id_replaced) { auto insertion_result2 = reference_counted_session_map_.insert( std::make_pair(original_connection_id, session_ptr)); QUIC_BUG_IF(quic_460317833_02, !insertion_result2.second) << "Original connection ID already in session_map: " << original_connection_id; } } return session_ptr; } QuicDispatcher::HandleCidCollisionResult QuicDispatcher::HandleConnectionIdCollision( const QuicConnectionId& original_connection_id, const QuicConnectionId& replaced_connection_id, const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, ParsedQuicVersion version, const ParsedClientHello* parsed_chlo) { HandleCidCollisionResult result = HandleCidCollisionResult::kOk; auto existing_session_iter = reference_counted_session_map_.find(replaced_connection_id); if (existing_session_iter != reference_counted_session_map_.end()) { result = HandleCidCollisionResult::kCollision; QUIC_CODE_COUNT(quic_connection_id_collision); QuicConnection* other_connection = existing_session_iter->second->connection(); if (other_connection != nullptr) { QUIC_LOG_EVERY_N_SEC(ERROR, 10) << "QUIC Connection ID collision. original_connection_id:" << original_connection_id << ", replaced_connection_id:" << replaced_connection_id << ", version:" << version << ", self_address:" << self_address << ", peer_address:" << peer_address << ", parsed_chlo:" << (parsed_chlo == nullptr ? "null" : parsed_chlo->ToString()) << ", other peer address: " << other_connection->peer_address() << ", other CIDs: " << quiche::PrintElements( other_connection->GetActiveServerConnectionIds()) << ", other stats: " << other_connection->GetStats(); } } else if (buffered_packets_.HasBufferedPackets(replaced_connection_id)) { result = HandleCidCollisionResult::kCollision; QUIC_CODE_COUNT(quic_connection_id_collision_with_buffered_session); } if (result == HandleCidCollisionResult::kOk) { return result; } const bool collide_with_active_session = existing_session_iter != reference_counted_session_map_.end(); QUIC_DLOG(INFO) << "QUIC Connection ID collision with " << (collide_with_active_session ? "active session" : "buffered session") << " for original_connection_id:" << original_connection_id << ", replaced_connection_id:" << replaced_connection_id; StatelesslyTerminateConnection( self_address, peer_address, original_connection_id, IETF_QUIC_LONG_HEADER_PACKET, true, version.HasLengthPrefixedConnectionIds(), version, QUIC_HANDSHAKE_FAILED, "Connection ID collision, please retry", QuicTimeWaitListManager::SEND_CONNECTION_CLOSE_PACKETS); return result; } void QuicDispatcher::MaybeResetPacketsWithNoVersion( const ReceivedPacketInfo& packet_info) { QUICHE_DCHECK(!packet_info.version_flag); if (recent_stateless_reset_addresses_.contains(packet_info.peer_address)) { QUIC_CODE_COUNT(quic_donot_send_reset_repeatedly); return; } if (packet_info.form != GOOGLE_QUIC_PACKET) { if (packet_info.packet.length() <= QuicFramer::GetMinStatelessResetPacketLength()) { QUIC_CODE_COUNT(quic_drop_too_small_short_header_packets); return; } } else { const size_t MinValidPacketLength = kPacketHeaderTypeSize + expected_server_connection_id_length_ + PACKET_1BYTE_PACKET_NUMBER + 1 + 12; if (packet_info.packet.length() < MinValidPacketLength) { QUIC_CODE_COUNT(drop_too_small_packets); return; } } if (recent_stateless_reset_addresses_.size() >= GetQuicFlag(quic_max_recent_stateless_reset_addresses)) { QUIC_CODE_COUNT(quic_too_many_recent_reset_addresses); return; } if (recent_stateless_reset_addresses_.empty()) { clear_stateless_reset_addresses_alarm_->Update( helper()->GetClock()->ApproximateNow() + QuicTime::Delta::FromMilliseconds( GetQuicFlag(quic_recent_stateless_reset_addresses_lifetime_ms)), QuicTime::Delta::Zero()); } recent_stateless_reset_addresses_.emplace(packet_info.peer_address); time_wait_list_manager()->SendPublicReset( packet_info.self_address, packet_info.peer_address, packet_info.destination_connection_id, packet_info.form != GOOGLE_QUIC_PACKET, packet_info.packet.length(), GetPerPacketContext()); } void QuicDispatcher::MaybeSendVersionNegotiationPacket( const ReceivedPacketInfo& packet_info) { if (crypto_config()->validate_chlo_size() && packet_info.packet.length() < kMinPacketSizeForVersionNegotiation) { return; } time_wait_list_manager()->SendVersionNegotiationPacket( packet_info.destination_connection_id, packet_info.source_connection_id, packet_info.form != GOOGLE_QUIC_PACKET, packet_info.use_length_prefix, GetSupportedVersions(), packet_info.self_address, packet_info.peer_address, GetPerPacketContext()); } size_t QuicDispatcher::NumSessions() const { return num_sessions_in_session_map_; } }
#include "quiche/quic/core/quic_dispatcher.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <list> #include <map> #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 "quiche/quic/core/chlo_extractor.h" #include "quiche/quic/core/connection_id_generator.h" #include "quiche/quic/core/crypto/crypto_protocol.h" #include "quiche/quic/core/crypto/quic_compressed_certs_cache.h" #include "quiche/quic/core/crypto/quic_crypto_client_config.h" #include "quiche/quic/core/crypto/quic_crypto_server_config.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/crypto/transport_parameters.h" #include "quiche/quic/core/frames/quic_connection_close_frame.h" #include "quiche/quic/core/http/quic_server_session_base.h" #include "quiche/quic/core/http/quic_spdy_stream.h" #include "quiche/quic/core/quic_config.h" #include "quiche/quic/core/quic_connection.h" #include "quiche/quic/core/quic_connection_id.h" #include "quiche/quic/core/quic_constants.h" #include "quiche/quic/core/quic_crypto_server_stream_base.h" #include "quiche/quic/core/quic_crypto_stream.h" #include "quiche/quic/core/quic_error_codes.h" #include "quiche/quic/core/quic_packet_writer.h" #include "quiche/quic/core/quic_packet_writer_wrapper.h" #include "quiche/quic/core/quic_packets.h" #include "quiche/quic/core/quic_stream.h" #include "quiche/quic/core/quic_time.h" #include "quiche/quic/core/quic_time_wait_list_manager.h" #include "quiche/quic/core/quic_types.h" #include "quiche/quic/core/quic_utils.h" #include "quiche/quic/core/quic_version_manager.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_ip_address.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/first_flight.h" #include "quiche/quic/test_tools/mock_connection_id_generator.h" #include "quiche/quic/test_tools/mock_quic_time_wait_list_manager.h" #include "quiche/quic/test_tools/quic_buffered_packet_store_peer.h" #include "quiche/quic/test_tools/quic_connection_peer.h" #include "quiche/quic/test_tools/quic_dispatcher_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" #include "quiche/quic/tools/quic_simple_crypto_server_stream_helper.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/test_tools/quiche_test_utils.h" using testing::_; using testing::AllOf; using testing::ByMove; using testing::ElementsAreArray; using testing::Eq; using testing::Field; using testing::InSequence; using testing::Invoke; using testing::IsEmpty; using testing::NiceMock; using testing::Not; using testing::Ref; using testing::Return; using testing::ReturnRef; using testing::WithArg; using testing::WithoutArgs; static const size_t kDefaultMaxConnectionsInStore = 100; static const size_t kMaxConnectionsWithoutCHLO = kDefaultMaxConnectionsInStore / 2; static const int16_t kMaxNumSessionsToCreate = 16; namespace quic { namespace test { namespace { const QuicConnectionId kReturnConnectionId{ {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}}; class TestQuicSpdyServerSession : public QuicServerSessionBase { public: TestQuicSpdyServerSession(const QuicConfig& config, QuicConnection* connection, const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache) : QuicServerSessionBase(config, CurrentSupportedVersions(), connection, nullptr, nullptr, crypto_config, compressed_certs_cache) { Initialize(); } TestQuicSpdyServerSession(const TestQuicSpdyServerSession&) = delete; TestQuicSpdyServerSession& operator=(const TestQuicSpdyServerSession&) = delete; ~TestQuicSpdyServerSession() override { DeleteConnection(); } MOCK_METHOD(void, OnConnectionClosed, (const QuicConnectionCloseFrame& frame, ConnectionCloseSource source), (override)); MOCK_METHOD(QuicSpdyStream*, CreateIncomingStream, (QuicStreamId id), (override)); MOCK_METHOD(QuicSpdyStream*, CreateIncomingStream, (PendingStream*), (override)); MOCK_METHOD(QuicSpdyStream*, CreateOutgoingBidirectionalStream, (), (override)); MOCK_METHOD(QuicSpdyStream*, CreateOutgoingUnidirectionalStream, (), (override)); std::unique_ptr<QuicCryptoServerStreamBase> CreateQuicCryptoServerStream( const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache) override { return CreateCryptoServerStream(crypto_config, compressed_certs_cache, this, stream_helper()); } QuicCryptoServerStreamBase::Helper* stream_helper() { return QuicServerSessionBase::stream_helper(); } }; class TestDispatcher : public QuicDispatcher { public: TestDispatcher(const QuicConfig* config, const QuicCryptoServerConfig* crypto_config, QuicVersionManager* version_manager, QuicRandom* random, ConnectionIdGeneratorInterface& generator) : QuicDispatcher(config, crypto_config, version_manager, std::make_unique<MockQuicConnectionHelper>(), std::unique_ptr<QuicCryptoServerStreamBase::Helper>( new QuicSimpleCryptoServerStreamHelper()), std::make_unique<TestAlarmFactory>(), kQuicDefaultConnectionIdLength, generator), random_(random) { EXPECT_CALL(*this, ConnectionIdGenerator()) .WillRepeatedly(ReturnRef(generator)); } MOCK_METHOD(std::unique_ptr<QuicSession>, CreateQuicSession, (QuicConnectionId connection_id, const QuicSocketAddress& self_address, const QuicSocketAddress& peer_address, absl::string_view alpn, const ParsedQuicVersion& version, const ParsedClientHello& parsed_chlo, ConnectionIdGeneratorInterface& connection_id_generator), (override)); MOCK_METHOD(ConnectionIdGeneratorInterface&, ConnectionIdGenerator, (), (override)); struct TestQuicPerPacketContext : public QuicPerPacketContext { std::string custom_packet_context; }; std::unique_ptr<QuicPerPacketContext> GetPerPacketContext() const override { auto test_context = std::make_unique<TestQuicPerPacketContext>(); test_context->custom_packet_context = custom_packet_context_; return std::move(test_context); } void RestorePerPacketContext( std::unique_ptr<QuicPerPacketContext> context) override { TestQuicPerPacketContext* test_context = static_cast<TestQuicPerPacketContext*>(context.get()); custom_packet_context_ = test_context->custom_packet_context; } std::string custom_packet_context_; using QuicDispatcher::ConnectionIdGenerator; using QuicDispatcher::MaybeDispatchPacket; using QuicDispatcher::writer; QuicRandom* random_; }; class MockServerConnection : public MockQuicConnection { public: MockServerConnection(QuicConnectionId connection_id, MockQuicConnectionHelper* helper, MockAlarmFactory* alarm_factory, QuicDispatcher* dispatcher) : MockQuicConnection(connection_id, helper, alarm_factory, Perspective::IS_SERVER), dispatcher_(dispatcher), active_connection_ids_({connection_id}) {} void AddNewConnectionId(QuicConnectionId id) { if (!dispatcher_->TryAddNewConnectionId(active_connection_ids_.back(), id)) { return; } QuicConnectionPeer::SetServerConnectionId(this, id); active_connection_ids_.push_back(id); } void UnconditionallyAddNewConnectionIdForTest(QuicConnectionId id) { dispatcher_->TryAddNewConnectionId(active_connection_ids_.back(), id); active_connection_ids_.push_back(id); } void RetireConnectionId(QuicConnectionId id) { auto it = std::find(active_connection_ids_.begin(), active_connection_ids_.end(), id); QUICHE_DCHECK(it != active_connection_ids_.end()); dispatcher_->OnConnectionIdRetired(id); active_connection_ids_.erase(it); } std::vector<QuicConnectionId> GetActiveServerConnectionIds() const override { std::vector<QuicConnectionId> result; for (const auto& cid : active_connection_ids_) { result.push_back(cid); } auto original_connection_id = GetOriginalDestinationConnectionId(); if (std::find(result.begin(), result.end(), original_connection_id) == result.end()) { result.push_back(original_connection_id); } return result; } void UnregisterOnConnectionClosed() { QUIC_LOG(ERROR) << "Unregistering " << connection_id(); dispatcher_->OnConnectionClosed(connection_id(), QUIC_NO_ERROR, "Unregistering.", ConnectionCloseSource::FROM_SELF); } private: QuicDispatcher* dispatcher_; std::vector<QuicConnectionId> active_connection_ids_; }; class QuicDispatcherTestBase : public QuicTestWithParam<ParsedQuicVersion> { public: QuicDispatcherTestBase() : QuicDispatcherTestBase(crypto_test_utils::ProofSourceForTesting()) {} explicit QuicDispatcherTestBase(std::unique_ptr<ProofSource> proof_source) : QuicDispatcherTestBase(std::move(proof_source), AllSupportedVersions()) {} explicit QuicDispatcherTestBase( const ParsedQuicVersionVector& supported_versions) : QuicDispatcherTestBase(crypto_test_utils::ProofSourceForTesting(), supported_versions) {} explicit QuicDispatcherTestBase( std::unique_ptr<ProofSource> proof_source, const ParsedQuicVersionVector& supported_versions) : version_(GetParam()), version_manager_(supported_versions), crypto_config_(QuicCryptoServerConfig::TESTING, QuicRandom::GetInstance(), std::move(proof_source), KeyExchangeSource::Default()), server_address_(QuicIpAddress::Any4(), 5), dispatcher_(new NiceMock<TestDispatcher>( &config_, &crypto_config_, &version_manager_, mock_helper_.GetRandomGenerator(), connection_id_generator_)), time_wait_list_manager_(nullptr), session1_(nullptr), session2_(nullptr), store_(nullptr), connection_id_(1) {} void SetUp() override { dispatcher_->InitializeWithWriter(new NiceMock<MockPacketWriter>()); QuicDispatcherPeer::set_new_sessions_allowed_per_event_loop( dispatcher_.get(), kMaxNumSessionsToCreate); } MockQuicConnection* connection1() { if (session1_ == nullptr) { return nullptr; } return reinterpret_cast<MockQuicConnection*>(session1_->connection()); } MockQuicConnection* connection2() { if (session2_ == nullptr) { return nullptr; } return reinterpret_cast<MockQuicConnection*>(session2_->connection()); } void ProcessPacket(QuicSocketAddress peer_address, QuicConnectionId server_connection_id, bool has_version_flag, const std::string& data) { ProcessPacket(peer_address, server_connection_id, has_version_flag, data, CONNECTION_ID_PRESENT, PACKET_4BYTE_PACKET_NUMBER); } void ProcessPacket(QuicSocketAddress peer_address, QuicConnectionId server_connection_id, bool has_version_flag, const std::string& data, QuicConnectionIdIncluded server_connection_id_included, QuicPacketNumberLength packet_number_length) { ProcessPacket(peer_address, server_connection_id, has_version_flag, data, server_connection_id_included, packet_number_length, 1); } void ProcessPacket(QuicSocketAddress peer_address, QuicConnectionId server_connection_id, bool has_version_flag, const std::string& data, QuicConnectionIdIncluded server_connection_id_included, QuicPacketNumberLength packet_number_length, uint64_t packet_number) { ProcessPacket(peer_address, server_connection_id, has_version_flag, version_, data, true, server_connection_id_included, packet_number_length, packet_number); } void ProcessPacket(QuicSocketAddress peer_address, QuicConnectionId server_connection_id, bool has_version_flag, ParsedQuicVersion version, const std::string& data, bool full_padding, QuicConnectionIdIncluded server_connection_id_included, QuicPacketNumberLength packet_number_length, uint64_t packet_number) { ProcessPacket(peer_address, server_connection_id, EmptyQuicConnectionId(), has_version_flag, version, data, full_padding, server_connection_id_included, CONNECTION_ID_ABSENT, packet_number_length, packet_number); } void ProcessPacket(QuicSocketAddress peer_address, QuicConnectionId server_connection_id, QuicConnectionId client_connection_id, bool has_version_flag, ParsedQuicVersion version, const std::string& data, bool full_padding, QuicConnectionIdIncluded server_connection_id_included, QuicConnectionIdIncluded client_connection_id_included, QuicPacketNumberLength packet_number_length, uint64_t packet_number) { ParsedQuicVersionVector versions(SupportedVersions(version)); std::unique_ptr<QuicEncryptedPacket> packet(ConstructEncryptedPacket( server_connection_id, client_connection_id, has_version_flag, false, packet_number, data, full_padding, server_connection_id_included, client_connection_id_included, packet_number_length, &versions)); std::unique_ptr<QuicReceivedPacket> received_packet( ConstructReceivedPacket(*packet, mock_helper_.GetClock()->Now())); if (!has_version_flag || !version.AllowsVariableLengthConnectionIds() || server_connection_id.length() == 0 || server_connection_id_included == CONNECTION_ID_ABSENT) { EXPECT_CALL(connection_id_generator_, ConnectionIdLength(_)) .WillRepeatedly(Return(generated_connection_id_.has_value() ? generated_connection_id_->length() : kQuicDefaultConnectionIdLength)); } ProcessReceivedPacket(std::move(received_packet), peer_address, version, server_connection_id); } void ProcessReceivedPacket( std::unique_ptr<QuicReceivedPacket> received_packet, const QuicSocketAddress& peer_address, const ParsedQuicVersion& version, const QuicConnectionId& server_connection_id) { if (version.UsesQuicCrypto() && ChloExtractor::Extract(*received_packet, version, {}, nullptr, server_connection_id.length())) { data_connection_map_[server_connection_id].push_front( std::string(received_packet->data(), received_packet->length())); } else { data_connection_map_[server_connection_id].push_back( std::string(received_packet->data(), received_packet->length())); } dispatcher_->ProcessPacket(server_address_, peer_address, *received_packet); } void ValidatePacket(QuicConnectionId conn_id, const QuicEncryptedPacket& packet) { EXPECT_EQ(data_connection_map_[conn_id].front().length(), packet.AsStringPiece().length()); EXPECT_EQ(data_connection_map_[conn_id].front(), packet.AsStringPiece()); data_connection_map_[conn_id].pop_front(); } std::unique_ptr<QuicSession> CreateSession( TestDispatcher* dispatcher, const QuicConfig& config, QuicConnectionId connection_id, const QuicSocketAddress& , MockQuicConnectionHelper* helper, MockAlarmFactory* alarm_factory, const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache, TestQuicSpdyServerSession** session_ptr) { MockServerConnection* connection = new MockServerConnection( connection_id, helper, alarm_factory, dispatcher); connection->SetQuicPacketWriter(dispatcher->writer(), false); auto session = std::make_unique<TestQuicSpdyServerSession>( config, connection, crypto_config, compressed_certs_cache); *session_ptr = session.get(); connection->set_visitor(session.get()); ON_CALL(*connection, CloseConnection(_, _, _)) .WillByDefault(WithoutArgs(Invoke( connection, &MockServerConnection::UnregisterOnConnectionClosed))); return session; } void CreateTimeWaitListManager() { time_wait_list_manager_ = new MockTimeWaitListManager( QuicDispatcherPeer::GetWriter(dispatcher_.get()), dispatcher_.get(), mock_helper_.GetClock(), &mock_alarm_factory_); QuicDispatcherPeer::SetTimeWaitListManager(dispatcher_.get(), time_wait_list_manager_); } std::string SerializeCHLO() { CryptoHandshakeMessage client_hello; client_hello.set_tag(kCHLO); client_hello.SetStringPiece(kALPN, ExpectedAlpn()); return std::string(client_hello.GetSerialized().AsStringPiece()); } void ProcessUndecryptableEarlyPacket( const QuicSocketAddress& peer_address, const QuicConnectionId& server_connection_id) { ProcessUndecryptableEarlyPacket(version_, peer_address, server_connection_id); } void ProcessUndecryptableEarlyPacket( const ParsedQuicVersion& version, const QuicSocketAddress& peer_address, const QuicConnectionId& server_connection_id) { std::unique_ptr<QuicEncryptedPacket> encrypted_packet = GetUndecryptableEarlyPacket(version, server_connection_id); std::unique_ptr<QuicReceivedPacket> received_packet(ConstructReceivedPacket( *encrypted_packet, mock_helper_.GetClock()->Now())); ProcessReceivedPacket(std::move(received_packet), peer_address, version, server_connection_id); } void ProcessFirstFlight(const QuicSocketAddress& peer_address, const QuicConnectionId& server_connection_id) { ProcessFirstFlight(version_, peer_address, server_connection_id); } void ProcessFirstFlight(const ParsedQuicVersion& version, const QuicSocketAddress& peer_address, const QuicConnectionId& server_connection_id) { ProcessFirstFlight(version, peer_address, server_connection_id, EmptyQuicConnectionId()); } void ProcessFirstFlight(const ParsedQuicVersion& version, const QuicSocketAddress& peer_address, const QuicConnectionId& server_connection_id, const QuicConnectionId& client_connection_id) { ProcessFirstFlight(version, peer_address, server_connection_id, client_connection_id, TestClientCryptoConfig()); } void ProcessFirstFlight( const ParsedQuicVersion& version, const QuicSocketAddress& peer_address, const QuicConnectionId& server_connection_id, const QuicConnectionId& client_connection_id, std::unique_ptr<QuicCryptoClientConfig> client_crypto_config) { if (expect_generator_is_called_) { if (version.AllowsVariableLengthConnectionIds()) { EXPECT_CALL(connection_id_generator_, MaybeReplaceConnectionId(server_connection_id, version)) .WillOnce(Return(generated_connection_id_)); } else { EXPECT_CALL(connection_id_generator_, MaybeReplaceConnectionId(server_connection_id, version)) .WillOnce(Return(std::nullopt)); } } std::vector<std::unique_ptr<QuicReceivedPacket>> packets = GetFirstFlightOfPackets(version, DefaultQuicConfig(), server_connection_id, client_connection_id, std::move(client_crypto_config)); for (auto&& packet : packets) { ProcessReceivedPacket(std::move(packet), peer_address, version, server_connection_id); } } std::unique_ptr<QuicCryptoClientConfig> TestClientCryptoConfig() { auto client_crypto_config = std::make_unique<QuicCryptoClientConfig>( crypto_test_utils::ProofVerifierForTesting()); if (address_token_.has_value()) { client_crypto_config->LookupOrCreate(TestServerId()) ->set_source_address_token(*address_token_); } return client_crypto_config; } void SetAddressToken(std::string address_token) { address_token_ = std::move(address_token); } std::string ExpectedAlpnForVersion(ParsedQuicVersion version) { return AlpnForVersion(version); } std::string ExpectedAlpn() { return ExpectedAlpnForVersion(version_); } auto MatchParsedClientHello() { if (version_.UsesQuicCrypto()) { return AllOf( Field(&ParsedClientHello::alpns, ElementsAreArray({ExpectedAlpn()})), Field(&ParsedClientHello::sni, Eq(TestHostname())), Field(&ParsedClientHello::supported_groups, IsEmpty())); } return AllOf( Field(&ParsedClientHello::alpns, ElementsAreArray({ExpectedAlpn()})), Field(&ParsedClientHello::sni, Eq(TestHostname())), Field(&ParsedClientHello::supported_groups, Not(IsEmpty()))); } void MarkSession1Deleted() { session1_ = nullptr; } void VerifyVersionSupported(ParsedQuicVersion version) { expect_generator_is_called_ = true; QuicConnectionId connection_id = TestConnectionId(++connection_id_); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL(*dispatcher_, CreateQuicSession(connection_id, _, client_address, Eq(ExpectedAlpnForVersion(version)), _, _, _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, connection_id, client_address, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>( Invoke([this, connection_id](const QuicEncryptedPacket& packet) { ValidatePacket(connection_id, packet); }))); ProcessFirstFlight(version, client_address, connection_id); } void VerifyVersionNotSupported(ParsedQuicVersion version) { QuicConnectionId connection_id = TestConnectionId(++connection_id_); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL(*dispatcher_, CreateQuicSession(connection_id, _, client_address, _, _, _, _)) .Times(0); expect_generator_is_called_ = false; ProcessFirstFlight(version, client_address, connection_id); } void TestTlsMultiPacketClientHello(bool add_reordering, bool long_connection_id); void TestVersionNegotiationForUnknownVersionInvalidShortInitialConnectionId( const QuicConnectionId& server_connection_id, const QuicConnectionId& client_connection_id); TestAlarmFactory::TestAlarm* GetClearResetAddressesAlarm() { return reinterpret_cast<TestAlarmFactory::TestAlarm*>( QuicDispatcherPeer::GetClearResetAddressesAlarm(dispatcher_.get())); } ParsedQuicVersion version_; MockQuicConnectionHelper mock_helper_; MockAlarmFactory mock_alarm_factory_; QuicConfig config_; QuicVersionManager version_manager_; QuicCryptoServerConfig crypto_config_; QuicSocketAddress server_address_; bool expect_generator_is_called_ = true; std::optional<QuicConnectionId> generated_connection_id_; MockConnectionIdGenerator connection_id_generator_; std::unique_ptr<NiceMock<TestDispatcher>> dispatcher_; MockTimeWaitListManager* time_wait_list_manager_; TestQuicSpdyServerSession* session1_; TestQuicSpdyServerSession* session2_; std::map<QuicConnectionId, std::list<std::string>> data_connection_map_; QuicBufferedPacketStore* store_; uint64_t connection_id_; std::optional<std::string> address_token_; }; class QuicDispatcherTestAllVersions : public QuicDispatcherTestBase {}; class QuicDispatcherTestOneVersion : public QuicDispatcherTestBase {}; class QuicDispatcherTestNoVersions : public QuicDispatcherTestBase { public: QuicDispatcherTestNoVersions() : QuicDispatcherTestBase(ParsedQuicVersionVector{}) {} }; INSTANTIATE_TEST_SUITE_P(QuicDispatcherTestsAllVersions, QuicDispatcherTestAllVersions, ::testing::ValuesIn(CurrentSupportedVersions()), ::testing::PrintToStringParamName()); INSTANTIATE_TEST_SUITE_P(QuicDispatcherTestsOneVersion, QuicDispatcherTestOneVersion, ::testing::Values(CurrentSupportedVersions().front()), ::testing::PrintToStringParamName()); INSTANTIATE_TEST_SUITE_P(QuicDispatcherTestsNoVersion, QuicDispatcherTestNoVersions, ::testing::ValuesIn(AllSupportedVersions()), ::testing::PrintToStringParamName()); TEST_P(QuicDispatcherTestAllVersions, TlsClientHelloCreatesSession) { if (version_.UsesQuicCrypto()) { return; } SetAddressToken("hsdifghdsaifnasdpfjdsk"); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL( *dispatcher_, CreateQuicSession(TestConnectionId(1), _, client_address, Eq(ExpectedAlpn()), _, MatchParsedClientHello(), _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, TestConnectionId(1), client_address, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { ValidatePacket(TestConnectionId(1), packet); }))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), OnParsedClientHelloInfo(MatchParsedClientHello())) .Times(1); ProcessFirstFlight(client_address, TestConnectionId(1)); } TEST_P(QuicDispatcherTestAllVersions, TlsClientHelloCreatesSessionWithCorrectConnectionIdGenerator) { if (version_.UsesQuicCrypto()) { return; } SetAddressToken("hsdifghdsaifnasdpfjdsk"); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); MockConnectionIdGenerator mock_connection_id_generator; EXPECT_CALL(*dispatcher_, ConnectionIdGenerator()) .WillRepeatedly(ReturnRef(mock_connection_id_generator)); ConnectionIdGeneratorInterface& expected_generator = mock_connection_id_generator; EXPECT_CALL(mock_connection_id_generator, MaybeReplaceConnectionId(TestConnectionId(1), version_)) .WillOnce(Return(std::nullopt)); EXPECT_CALL(*dispatcher_, CreateQuicSession(TestConnectionId(1), _, client_address, Eq(ExpectedAlpn()), _, MatchParsedClientHello(), Ref(expected_generator))) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, TestConnectionId(1), client_address, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); expect_generator_is_called_ = false; ProcessFirstFlight(client_address, TestConnectionId(1)); } TEST_P(QuicDispatcherTestAllVersions, VariableServerConnectionIdLength) { QuicConnectionId old_id = TestConnectionId(1); if (version_.HasIetfQuicFrames()) { generated_connection_id_ = QuicConnectionId({0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b}); } QuicConnectionId new_id = generated_connection_id_.has_value() ? *generated_connection_id_ : old_id; QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL(*dispatcher_, CreateQuicSession(new_id, _, client_address, Eq(ExpectedAlpn()), _, MatchParsedClientHello(), _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, new_id, client_address, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { ValidatePacket(TestConnectionId(1), packet); }))); ProcessFirstFlight(client_address, old_id); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .Times(1); ProcessPacket(client_address, new_id, false, "foo"); } void QuicDispatcherTestBase::TestTlsMultiPacketClientHello( bool add_reordering, bool long_connection_id) { if (!version_.UsesTls()) { return; } SetAddressToken("857293462398"); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); QuicConnectionId original_connection_id, new_connection_id; if (long_connection_id) { original_connection_id = TestConnectionIdNineBytesLong(1); new_connection_id = kReturnConnectionId; EXPECT_CALL(connection_id_generator_, MaybeReplaceConnectionId(original_connection_id, version_)) .WillOnce(Return(new_connection_id)); } else { original_connection_id = TestConnectionId(); new_connection_id = original_connection_id; EXPECT_CALL(connection_id_generator_, MaybeReplaceConnectionId(original_connection_id, version_)) .WillOnce(Return(std::nullopt)); } QuicConfig client_config = DefaultQuicConfig(); constexpr auto kCustomParameterId = static_cast<TransportParameters::TransportParameterId>(0xff33); std::string kCustomParameterValue(2000, '-'); client_config.custom_transport_parameters_to_send()[kCustomParameterId] = kCustomParameterValue; std::vector<std::unique_ptr<QuicReceivedPacket>> packets = GetFirstFlightOfPackets(version_, client_config, original_connection_id, EmptyQuicConnectionId(), TestClientCryptoConfig()); ASSERT_EQ(packets.size(), 2u); if (add_reordering) { std::swap(packets[0], packets[1]); } ProcessReceivedPacket(std::move(packets[0]), client_address, version_, original_connection_id); EXPECT_EQ(dispatcher_->NumSessions(), 0u) << "No session should be created before the rest of the CHLO arrives."; EXPECT_CALL( *dispatcher_, CreateQuicSession(new_connection_id, _, client_address, Eq(ExpectedAlpn()), _, MatchParsedClientHello(), _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, new_connection_id, client_address, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .Times(2); ProcessReceivedPacket(std::move(packets[1]), client_address, version_, original_connection_id); EXPECT_EQ(dispatcher_->NumSessions(), 1u); } TEST_P(QuicDispatcherTestAllVersions, TlsMultiPacketClientHello) { TestTlsMultiPacketClientHello(false, false); } TEST_P(QuicDispatcherTestAllVersions, TlsMultiPacketClientHelloWithReordering) { TestTlsMultiPacketClientHello(true, false); } TEST_P(QuicDispatcherTestAllVersions, TlsMultiPacketClientHelloWithLongId) { TestTlsMultiPacketClientHello(false, true); } TEST_P(QuicDispatcherTestAllVersions, TlsMultiPacketClientHelloWithReorderingAndLongId) { TestTlsMultiPacketClientHello(true, true); } TEST_P(QuicDispatcherTestAllVersions, ProcessPackets) { QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL( *dispatcher_, CreateQuicSession(TestConnectionId(1), _, client_address, Eq(ExpectedAlpn()), _, MatchParsedClientHello(), _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, TestConnectionId(1), client_address, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { ValidatePacket(TestConnectionId(1), packet); }))); ProcessFirstFlight(client_address, TestConnectionId(1)); EXPECT_CALL( *dispatcher_, CreateQuicSession(TestConnectionId(2), _, client_address, Eq(ExpectedAlpn()), _, MatchParsedClientHello(), _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, TestConnectionId(2), client_address, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session2_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session2_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { ValidatePacket(TestConnectionId(2), packet); }))); ProcessFirstFlight(client_address, TestConnectionId(2)); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .Times(1) .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { ValidatePacket(TestConnectionId(1), packet); }))); ProcessPacket(client_address, TestConnectionId(1), false, "data"); } TEST_P(QuicDispatcherTestAllVersions, DispatcherDoesNotRejectPacketNumberZero) { QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL(*dispatcher_, CreateQuicSession(TestConnectionId(1), _, client_address, Eq(ExpectedAlpn()), _, _, _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, TestConnectionId(1), client_address, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .Times(2) .WillRepeatedly( WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { ValidatePacket(TestConnectionId(1), packet); }))); ProcessFirstFlight(client_address, TestConnectionId(1)); ProcessPacket(client_address, TestConnectionId(1), false, version_, "", true, CONNECTION_ID_PRESENT, PACKET_1BYTE_PACKET_NUMBER, 256); } TEST_P(QuicDispatcherTestOneVersion, StatelessVersionNegotiation) { CreateTimeWaitListManager(); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); EXPECT_CALL( *time_wait_list_manager_, SendVersionNegotiationPacket(TestConnectionId(1), _, _, _, _, _, _, _)) .Times(1); expect_generator_is_called_ = false; ProcessFirstFlight(QuicVersionReservedForNegotiation(), client_address, TestConnectionId(1)); } TEST_P(QuicDispatcherTestOneVersion, StatelessVersionNegotiationWithVeryLongConnectionId) { QuicConnectionId connection_id = QuicUtils::CreateRandomConnectionId(33); CreateTimeWaitListManager(); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); EXPECT_CALL(*time_wait_list_manager_, SendVersionNegotiationPacket(connection_id, _, _, _, _, _, _, _)) .Times(1); expect_generator_is_called_ = false; ProcessFirstFlight(QuicVersionReservedForNegotiation(), client_address, connection_id); } TEST_P(QuicDispatcherTestOneVersion, StatelessVersionNegotiationWithClientConnectionId) { CreateTimeWaitListManager(); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); EXPECT_CALL(*time_wait_list_manager_, SendVersionNegotiationPacket( TestConnectionId(1), TestConnectionId(2), _, _, _, _, _, _)) .Times(1); expect_generator_is_called_ = false; ProcessFirstFlight(QuicVersionReservedForNegotiation(), client_address, TestConnectionId(1), TestConnectionId(2)); } TEST_P(QuicDispatcherTestOneVersion, NoVersionNegotiationWithSmallPacket) { CreateTimeWaitListManager(); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); EXPECT_CALL(*time_wait_list_manager_, SendVersionNegotiationPacket(_, _, _, _, _, _, _, _)) .Times(0); std::string chlo = SerializeCHLO() + std::string(1200, 'a'); QUICHE_DCHECK_LE(1200u, chlo.length()); std::string truncated_chlo = chlo.substr(0, 1100); QUICHE_DCHECK_EQ(1100u, truncated_chlo.length()); ProcessPacket(client_address, TestConnectionId(1), true, QuicVersionReservedForNegotiation(), truncated_chlo, false, CONNECTION_ID_PRESENT, PACKET_4BYTE_PACKET_NUMBER, 1); } TEST_P(QuicDispatcherTestOneVersion, VersionNegotiationWithoutChloSizeValidation) { crypto_config_.set_validate_chlo_size(false); CreateTimeWaitListManager(); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); EXPECT_CALL(*time_wait_list_manager_, SendVersionNegotiationPacket(_, _, _, _, _, _, _, _)) .Times(1); std::string chlo = SerializeCHLO() + std::string(1200, 'a'); QUICHE_DCHECK_LE(1200u, chlo.length()); std::string truncated_chlo = chlo.substr(0, 1100); QUICHE_DCHECK_EQ(1100u, truncated_chlo.length()); ProcessPacket(client_address, TestConnectionId(1), true, QuicVersionReservedForNegotiation(), truncated_chlo, true, CONNECTION_ID_PRESENT, PACKET_4BYTE_PACKET_NUMBER, 1); } TEST_P(QuicDispatcherTestAllVersions, Shutdown) { QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, client_address, Eq(ExpectedAlpn()), _, _, _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, TestConnectionId(1), client_address, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { ValidatePacket(TestConnectionId(1), packet); }))); ProcessFirstFlight(client_address, TestConnectionId(1)); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), CloseConnection(QUIC_PEER_GOING_AWAY, _, _)); dispatcher_->Shutdown(); } TEST_P(QuicDispatcherTestAllVersions, TimeWaitListManager) { CreateTimeWaitListManager(); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); QuicConnectionId connection_id = TestConnectionId(1); EXPECT_CALL(*dispatcher_, CreateQuicSession(connection_id, _, client_address, Eq(ExpectedAlpn()), _, _, _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, connection_id, client_address, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { ValidatePacket(TestConnectionId(1), packet); }))); ProcessFirstFlight(client_address, connection_id); session1_->connection()->CloseConnection( QUIC_INVALID_VERSION, "Server: Packet 2 without version flag before version negotiated.", ConnectionCloseBehavior::SILENT_CLOSE); EXPECT_TRUE(time_wait_list_manager_->IsConnectionIdInTimeWait(connection_id)); EXPECT_CALL(*time_wait_list_manager_, ProcessPacket(_, _, connection_id, _, _, _)) .Times(1); EXPECT_CALL(*time_wait_list_manager_, AddConnectionIdToTimeWait(_, _)) .Times(0); ProcessPacket(client_address, connection_id, true, "data"); } TEST_P(QuicDispatcherTestAllVersions, NoVersionPacketToTimeWaitListManager) { CreateTimeWaitListManager(); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); QuicConnectionId connection_id = TestConnectionId(1); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); EXPECT_CALL(*time_wait_list_manager_, ProcessPacket(_, _, connection_id, _, _, _)) .Times(0); EXPECT_CALL(*time_wait_list_manager_, AddConnectionIdToTimeWait(_, _)) .Times(0); EXPECT_CALL(*time_wait_list_manager_, SendPublicReset(_, _, _, _, _, _)) .Times(1); ProcessPacket(client_address, connection_id, false, "data"); } TEST_P(QuicDispatcherTestAllVersions, DonotTimeWaitPacketsWithUnknownConnectionIdAndNoVersion) { QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); CreateTimeWaitListManager(); uint8_t short_packet[22] = {0x70, 0xa7, 0x02, 0x6b}; uint8_t valid_size_packet[23] = {0x70, 0xa7, 0x02, 0x6c}; size_t short_packet_len = 21; QuicReceivedPacket packet(reinterpret_cast<char*>(short_packet), short_packet_len, QuicTime::Zero()); QuicReceivedPacket packet2(reinterpret_cast<char*>(valid_size_packet), short_packet_len + 1, QuicTime::Zero()); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); EXPECT_CALL(*time_wait_list_manager_, ProcessPacket(_, _, _, _, _, _)) .Times(0); EXPECT_CALL(*time_wait_list_manager_, AddConnectionIdToTimeWait(_, _)) .Times(0); EXPECT_CALL(connection_id_generator_, ConnectionIdLength(0xa7)) .WillOnce(Return(kQuicDefaultConnectionIdLength)); EXPECT_CALL(*time_wait_list_manager_, SendPublicReset(_, _, _, _, _, _)) .Times(0); dispatcher_->ProcessPacket(server_address_, client_address, packet); EXPECT_CALL(connection_id_generator_, ConnectionIdLength(0xa7)) .WillOnce(Return(kQuicDefaultConnectionIdLength)); EXPECT_CALL(*time_wait_list_manager_, SendPublicReset(_, _, _, _, _, _)) .Times(1); dispatcher_->ProcessPacket(server_address_, client_address, packet2); } TEST_P(QuicDispatcherTestOneVersion, DropPacketWithInvalidFlags) { QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); CreateTimeWaitListManager(); uint8_t all_zero_packet[1200] = {}; QuicReceivedPacket packet(reinterpret_cast<char*>(all_zero_packet), sizeof(all_zero_packet), QuicTime::Zero()); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); EXPECT_CALL(*time_wait_list_manager_, ProcessPacket(_, _, _, _, _, _)) .Times(0); EXPECT_CALL(*time_wait_list_manager_, AddConnectionIdToTimeWait(_, _)) .Times(0); EXPECT_CALL(*time_wait_list_manager_, SendPublicReset(_, _, _, _, _, _)) .Times(0); EXPECT_CALL(connection_id_generator_, ConnectionIdLength(_)) .WillOnce(Return(kQuicDefaultConnectionIdLength)); dispatcher_->ProcessPacket(server_address_, client_address, packet); } TEST_P(QuicDispatcherTestAllVersions, LimitResetsToSameClientAddress) { CreateTimeWaitListManager(); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); QuicSocketAddress client_address2(QuicIpAddress::Loopback4(), 2); QuicSocketAddress client_address3(QuicIpAddress::Loopback6(), 1); QuicConnectionId connection_id = TestConnectionId(1); EXPECT_CALL(*time_wait_list_manager_, SendPublicReset(_, _, _, _, _, _)) .Times(1); ProcessPacket(client_address, connection_id, false, "data"); ProcessPacket(client_address, connection_id, false, "data2"); ProcessPacket(client_address, connection_id, false, "data3"); EXPECT_CALL(*time_wait_list_manager_, SendPublicReset(_, _, _, _, _, _)) .Times(2); ProcessPacket(client_address2, connection_id, false, "data"); ProcessPacket(client_address3, connection_id, false, "data"); } TEST_P(QuicDispatcherTestAllVersions, StopSendingResetOnTooManyRecentAddresses) { SetQuicFlag(quic_max_recent_stateless_reset_addresses, 2); const size_t kTestLifeTimeMs = 10; SetQuicFlag(quic_recent_stateless_reset_addresses_lifetime_ms, kTestLifeTimeMs); CreateTimeWaitListManager(); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); QuicSocketAddress client_address2(QuicIpAddress::Loopback4(), 2); QuicSocketAddress client_address3(QuicIpAddress::Loopback6(), 1); QuicConnectionId connection_id = TestConnectionId(1); EXPECT_CALL(*time_wait_list_manager_, SendPublicReset(_, _, _, _, _, _)) .Times(2); EXPECT_FALSE(GetClearResetAddressesAlarm()->IsSet()); ProcessPacket(client_address, connection_id, false, "data"); const QuicTime expected_deadline = mock_helper_.GetClock()->Now() + QuicTime::Delta::FromMilliseconds(kTestLifeTimeMs); ASSERT_TRUE(GetClearResetAddressesAlarm()->IsSet()); EXPECT_EQ(expected_deadline, GetClearResetAddressesAlarm()->deadline()); mock_helper_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); ProcessPacket(client_address2, connection_id, false, "data"); ASSERT_TRUE(GetClearResetAddressesAlarm()->IsSet()); EXPECT_EQ(expected_deadline, GetClearResetAddressesAlarm()->deadline()); EXPECT_CALL(*time_wait_list_manager_, SendPublicReset(_, _, _, _, _, _)) .Times(0); ProcessPacket(client_address3, connection_id, false, "data"); mock_helper_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5)); GetClearResetAddressesAlarm()->Fire(); EXPECT_CALL(*time_wait_list_manager_, SendPublicReset(_, _, _, _, _, _)) .Times(2); ProcessPacket(client_address, connection_id, false, "data"); ProcessPacket(client_address2, connection_id, false, "data"); ProcessPacket(client_address3, connection_id, false, "data"); } TEST_P(QuicDispatcherTestAllVersions, LongConnectionIdLengthReplaced) { if (!version_.AllowsVariableLengthConnectionIds()) { return; } QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); QuicConnectionId bad_connection_id = TestConnectionIdNineBytesLong(2); generated_connection_id_ = kReturnConnectionId; EXPECT_CALL(*dispatcher_, CreateQuicSession(*generated_connection_id_, _, client_address, Eq(ExpectedAlpn()), _, _, _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, *generated_connection_id_, client_address, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>( Invoke([this, bad_connection_id](const QuicEncryptedPacket& packet) { ValidatePacket(bad_connection_id, packet); }))); ProcessFirstFlight(client_address, bad_connection_id); } TEST_P(QuicDispatcherTestAllVersions, MixGoodAndBadConnectionIdLengthPackets) { if (!version_.AllowsVariableLengthConnectionIds()) { return; } QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); QuicConnectionId bad_connection_id = TestConnectionIdNineBytesLong(2); EXPECT_CALL(*dispatcher_, CreateQuicSession(TestConnectionId(1), _, client_address, Eq(ExpectedAlpn()), _, _, _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, TestConnectionId(1), client_address, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { ValidatePacket(TestConnectionId(1), packet); }))); ProcessFirstFlight(client_address, TestConnectionId(1)); generated_connection_id_ = kReturnConnectionId; EXPECT_CALL(*dispatcher_, CreateQuicSession(*generated_connection_id_, _, client_address, Eq(ExpectedAlpn()), _, _, _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, *generated_connection_id_, client_address, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session2_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session2_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>( Invoke([this, bad_connection_id](const QuicEncryptedPacket& packet) { ValidatePacket(bad_connection_id, packet); }))); ProcessFirstFlight(client_address, bad_connection_id); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .Times(1) .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { ValidatePacket(TestConnectionId(1), packet); }))); ProcessPacket(client_address, TestConnectionId(1), false, "data"); } TEST_P(QuicDispatcherTestAllVersions, ProcessPacketWithZeroPort) { CreateTimeWaitListManager(); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 0); EXPECT_CALL(*dispatcher_, CreateQuicSession(TestConnectionId(1), _, client_address, _, _, _, _)) .Times(0); EXPECT_CALL(*time_wait_list_manager_, ProcessPacket(_, _, _, _, _, _)) .Times(0); EXPECT_CALL(*time_wait_list_manager_, AddConnectionIdToTimeWait(_, _)) .Times(0); ProcessPacket(client_address, TestConnectionId(1), true, "data"); } TEST_P(QuicDispatcherTestAllVersions, ProcessPacketWithBlockedPort) { CreateTimeWaitListManager(); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 17); EXPECT_CALL(*dispatcher_, CreateQuicSession(TestConnectionId(1), _, client_address, _, _, _, _)) .Times(0); EXPECT_CALL(*time_wait_list_manager_, ProcessPacket(_, _, _, _, _, _)) .Times(0); EXPECT_CALL(*time_wait_list_manager_, AddConnectionIdToTimeWait(_, _)) .Times(0); ProcessPacket(client_address, TestConnectionId(1), true, "data"); } TEST_P(QuicDispatcherTestAllVersions, ProcessPacketWithNonBlockedPort) { CreateTimeWaitListManager(); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 443); EXPECT_CALL(*dispatcher_, CreateQuicSession(TestConnectionId(1), _, client_address, Eq(ExpectedAlpn()), _, _, _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, TestConnectionId(1), client_address, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); ProcessFirstFlight(client_address, TestConnectionId(1)); } TEST_P(QuicDispatcherTestAllVersions, DropPacketWithKnownVersionAndInvalidShortInitialConnectionId) { if (!version_.AllowsVariableLengthConnectionIds()) { return; } CreateTimeWaitListManager(); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL(connection_id_generator_, ConnectionIdLength(0x00)) .WillOnce(Return(10)); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); EXPECT_CALL(*time_wait_list_manager_, ProcessPacket(_, _, _, _, _, _)) .Times(0); EXPECT_CALL(*time_wait_list_manager_, AddConnectionIdToTimeWait(_, _)) .Times(0); expect_generator_is_called_ = false; ProcessFirstFlight(client_address, EmptyQuicConnectionId()); } TEST_P(QuicDispatcherTestAllVersions, DropPacketWithKnownVersionAndInvalidInitialConnectionId) { CreateTimeWaitListManager(); QuicSocketAddress server_address; QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); EXPECT_CALL(*time_wait_list_manager_, ProcessPacket(_, _, _, _, _, _)) .Times(0); EXPECT_CALL(*time_wait_list_manager_, AddConnectionIdToTimeWait(_, _)) .Times(0); absl::string_view cid_str = "123456789abcdefg123456789abcdefg"; QuicConnectionId invalid_connection_id(cid_str.data(), cid_str.length()); QuicReceivedPacket packet("packet", 6, QuicTime::Zero()); ReceivedPacketInfo packet_info(server_address, client_address, packet); packet_info.version_flag = true; packet_info.version = version_; packet_info.destination_connection_id = invalid_connection_id; ASSERT_TRUE(dispatcher_->MaybeDispatchPacket(packet_info)); } void QuicDispatcherTestBase:: TestVersionNegotiationForUnknownVersionInvalidShortInitialConnectionId( const QuicConnectionId& server_connection_id, const QuicConnectionId& client_connection_id) { CreateTimeWaitListManager(); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); EXPECT_CALL(*time_wait_list_manager_, SendVersionNegotiationPacket( server_connection_id, client_connection_id, true, true, _, _, client_address, _)) .Times(1); expect_generator_is_called_ = false; EXPECT_CALL(connection_id_generator_, ConnectionIdLength(_)).Times(0); ProcessFirstFlight(ParsedQuicVersion::ReservedForNegotiation(), client_address, server_connection_id, client_connection_id); } TEST_P(QuicDispatcherTestOneVersion, VersionNegotiationForUnknownVersionInvalidShortInitialConnectionId) { TestVersionNegotiationForUnknownVersionInvalidShortInitialConnectionId( EmptyQuicConnectionId(), EmptyQuicConnectionId()); } TEST_P(QuicDispatcherTestOneVersion, VersionNegotiationForUnknownVersionInvalidShortInitialConnectionId2) { char server_connection_id_bytes[3] = {1, 2, 3}; QuicConnectionId server_connection_id(server_connection_id_bytes, sizeof(server_connection_id_bytes)); TestVersionNegotiationForUnknownVersionInvalidShortInitialConnectionId( server_connection_id, EmptyQuicConnectionId()); } TEST_P(QuicDispatcherTestOneVersion, VersionNegotiationForUnknownVersionInvalidShortInitialConnectionId3) { char client_connection_id_bytes[8] = {1, 2, 3, 4, 5, 6, 7, 8}; QuicConnectionId client_connection_id(client_connection_id_bytes, sizeof(client_connection_id_bytes)); TestVersionNegotiationForUnknownVersionInvalidShortInitialConnectionId( EmptyQuicConnectionId(), client_connection_id); } TEST_P(QuicDispatcherTestOneVersion, VersionsChangeInFlight) { VerifyVersionNotSupported(QuicVersionReservedForNegotiation()); for (ParsedQuicVersion version : CurrentSupportedVersions()) { VerifyVersionSupported(version); QuicDisableVersion(version); VerifyVersionNotSupported(version); QuicEnableVersion(version); VerifyVersionSupported(version); } } TEST_P(QuicDispatcherTestOneVersion, RejectDeprecatedVersionDraft28WithVersionNegotiation) { QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); CreateTimeWaitListManager(); uint8_t packet[kMinPacketSizeForVersionNegotiation] = { 0xC0, 0xFF, 0x00, 0x00, 28, 0x08}; QuicReceivedPacket received_packet(reinterpret_cast<char*>(packet), ABSL_ARRAYSIZE(packet), QuicTime::Zero()); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); EXPECT_CALL( *time_wait_list_manager_, SendVersionNegotiationPacket(_, _, true, true, _, _, _, _)) .Times(1); dispatcher_->ProcessPacket(server_address_, client_address, received_packet); } TEST_P(QuicDispatcherTestOneVersion, RejectDeprecatedVersionDraft27WithVersionNegotiation) { QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); CreateTimeWaitListManager(); uint8_t packet[kMinPacketSizeForVersionNegotiation] = { 0xC0, 0xFF, 0x00, 0x00, 27, 0x08}; QuicReceivedPacket received_packet(reinterpret_cast<char*>(packet), ABSL_ARRAYSIZE(packet), QuicTime::Zero()); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); EXPECT_CALL( *time_wait_list_manager_, SendVersionNegotiationPacket(_, _, true, true, _, _, _, _)) .Times(1); dispatcher_->ProcessPacket(server_address_, client_address, received_packet); } TEST_P(QuicDispatcherTestOneVersion, RejectDeprecatedVersionDraft25WithVersionNegotiation) { QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); CreateTimeWaitListManager(); uint8_t packet[kMinPacketSizeForVersionNegotiation] = { 0xC0, 0xFF, 0x00, 0x00, 25, 0x08}; QuicReceivedPacket received_packet(reinterpret_cast<char*>(packet), ABSL_ARRAYSIZE(packet), QuicTime::Zero()); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); EXPECT_CALL( *time_wait_list_manager_, SendVersionNegotiationPacket(_, _, true, true, _, _, _, _)) .Times(1); dispatcher_->ProcessPacket(server_address_, client_address, received_packet); } TEST_P(QuicDispatcherTestOneVersion, RejectDeprecatedVersionT050WithVersionNegotiation) { QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); CreateTimeWaitListManager(); uint8_t packet[kMinPacketSizeForVersionNegotiation] = { 0xC0, 'T', '0', '5', '0', 0x08}; QuicReceivedPacket received_packet(reinterpret_cast<char*>(packet), ABSL_ARRAYSIZE(packet), QuicTime::Zero()); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); EXPECT_CALL( *time_wait_list_manager_, SendVersionNegotiationPacket(_, _, true, true, _, _, _, _)) .Times(1); dispatcher_->ProcessPacket(server_address_, client_address, received_packet); } TEST_P(QuicDispatcherTestOneVersion, RejectDeprecatedVersionQ049WithVersionNegotiation) { QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); CreateTimeWaitListManager(); uint8_t packet[kMinPacketSizeForVersionNegotiation] = { 0xC0, 'Q', '0', '4', '9', 0x08}; QuicReceivedPacket received_packet(reinterpret_cast<char*>(packet), ABSL_ARRAYSIZE(packet), QuicTime::Zero()); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); EXPECT_CALL( *time_wait_list_manager_, SendVersionNegotiationPacket(_, _, true, true, _, _, _, _)) .Times(1); dispatcher_->ProcessPacket(server_address_, client_address, received_packet); } TEST_P(QuicDispatcherTestOneVersion, RejectDeprecatedVersionQ048WithVersionNegotiation) { QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); CreateTimeWaitListManager(); uint8_t packet[kMinPacketSizeForVersionNegotiation] = { 0xC0, 'Q', '0', '4', '8', 0x50}; QuicReceivedPacket received_packet(reinterpret_cast<char*>(packet), ABSL_ARRAYSIZE(packet), QuicTime::Zero()); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); EXPECT_CALL( *time_wait_list_manager_, SendVersionNegotiationPacket(_, _, true, false, _, _, _, _)) .Times(1); dispatcher_->ProcessPacket(server_address_, client_address, received_packet); } TEST_P(QuicDispatcherTestOneVersion, RejectDeprecatedVersionQ047WithVersionNegotiation) { QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); CreateTimeWaitListManager(); uint8_t packet[kMinPacketSizeForVersionNegotiation] = { 0xC0, 'Q', '0', '4', '7', 0x50}; QuicReceivedPacket received_packet(reinterpret_cast<char*>(packet), ABSL_ARRAYSIZE(packet), QuicTime::Zero()); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); EXPECT_CALL( *time_wait_list_manager_, SendVersionNegotiationPacket(_, _, true, false, _, _, _, _)) .Times(1); dispatcher_->ProcessPacket(server_address_, client_address, received_packet); } TEST_P(QuicDispatcherTestOneVersion, RejectDeprecatedVersionQ045WithVersionNegotiation) { QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); CreateTimeWaitListManager(); uint8_t packet[kMinPacketSizeForVersionNegotiation] = { 0xC0, 'Q', '0', '4', '5', 0x50}; QuicReceivedPacket received_packet(reinterpret_cast<char*>(packet), ABSL_ARRAYSIZE(packet), QuicTime::Zero()); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); EXPECT_CALL( *time_wait_list_manager_, SendVersionNegotiationPacket(_, _, true, false, _, _, _, _)) .Times(1); dispatcher_->ProcessPacket(server_address_, client_address, received_packet); } TEST_P(QuicDispatcherTestOneVersion, RejectDeprecatedVersionQ044WithVersionNegotiation) { QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); CreateTimeWaitListManager(); uint8_t packet44[kMinPacketSizeForVersionNegotiation] = { 0xFF, 'Q', '0', '4', '4', 0x50}; QuicReceivedPacket received_packet44(reinterpret_cast<char*>(packet44), kMinPacketSizeForVersionNegotiation, QuicTime::Zero()); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); EXPECT_CALL( *time_wait_list_manager_, SendVersionNegotiationPacket(_, _, true, false, _, _, _, _)) .Times(1); dispatcher_->ProcessPacket(server_address_, client_address, received_packet44); } TEST_P(QuicDispatcherTestOneVersion, RejectDeprecatedVersionQ050WithVersionNegotiation) { QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); CreateTimeWaitListManager(); uint8_t packet[kMinPacketSizeForVersionNegotiation] = { 0xFF, 'Q', '0', '5', '0', 0x50}; QuicReceivedPacket received_packet(reinterpret_cast<char*>(packet), kMinPacketSizeForVersionNegotiation, QuicTime::Zero()); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); EXPECT_CALL( *time_wait_list_manager_, SendVersionNegotiationPacket(_, _, true, true, _, _, _, _)) .Times(1); dispatcher_->ProcessPacket(server_address_, client_address, received_packet); } TEST_P(QuicDispatcherTestOneVersion, RejectDeprecatedVersionT051WithVersionNegotiation) { QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); CreateTimeWaitListManager(); uint8_t packet[kMinPacketSizeForVersionNegotiation] = { 0xFF, 'T', '0', '5', '1', 0x08}; QuicReceivedPacket received_packet(reinterpret_cast<char*>(packet), kMinPacketSizeForVersionNegotiation, QuicTime::Zero()); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); EXPECT_CALL( *time_wait_list_manager_, SendVersionNegotiationPacket(_, _, true, true, _, _, _, _)) .Times(1); dispatcher_->ProcessPacket(server_address_, client_address, received_packet); } static_assert(quic::SupportedVersions().size() == 4u, "Please add new RejectDeprecatedVersion tests above this assert " "when deprecating versions"); TEST_P(QuicDispatcherTestOneVersion, VersionNegotiationProbe) { QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); CreateTimeWaitListManager(); char packet[1200]; char destination_connection_id_bytes[] = {0x56, 0x4e, 0x20, 0x70, 0x6c, 0x7a, 0x20, 0x21}; EXPECT_TRUE(QuicFramer::WriteClientVersionNegotiationProbePacket( packet, sizeof(packet), destination_connection_id_bytes, sizeof(destination_connection_id_bytes))); QuicEncryptedPacket encrypted(packet, sizeof(packet), false); std::unique_ptr<QuicReceivedPacket> received_packet( ConstructReceivedPacket(encrypted, mock_helper_.GetClock()->Now())); QuicConnectionId client_connection_id = EmptyQuicConnectionId(); QuicConnectionId server_connection_id( destination_connection_id_bytes, sizeof(destination_connection_id_bytes)); EXPECT_CALL(*time_wait_list_manager_, SendVersionNegotiationPacket( server_connection_id, client_connection_id, true, true, _, _, _, _)) .Times(1); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); dispatcher_->ProcessPacket(server_address_, client_address, *received_packet); } class SavingWriter : public QuicPacketWriterWrapper { public: bool IsWriteBlocked() const override { return false; } WriteResult WritePacket(const char* buffer, size_t buf_len, const QuicIpAddress& , const QuicSocketAddress& , PerPacketOptions* , const QuicPacketWriterParams& ) override { packets_.push_back( QuicEncryptedPacket(buffer, buf_len, false).Clone()); return WriteResult(WRITE_STATUS_OK, buf_len); } std::vector<std::unique_ptr<QuicEncryptedPacket>>* packets() { return &packets_; } private: std::vector<std::unique_ptr<QuicEncryptedPacket>> packets_; }; TEST_P(QuicDispatcherTestOneVersion, VersionNegotiationProbeEndToEnd) { SavingWriter* saving_writer = new SavingWriter(); QuicDispatcherPeer::UseWriter(dispatcher_.get(), saving_writer); QuicTimeWaitListManager* time_wait_list_manager = new QuicTimeWaitListManager( saving_writer, dispatcher_.get(), mock_helper_.GetClock(), &mock_alarm_factory_); QuicDispatcherPeer::SetTimeWaitListManager(dispatcher_.get(), time_wait_list_manager); char packet[1200] = {}; char destination_connection_id_bytes[] = {0x56, 0x4e, 0x20, 0x70, 0x6c, 0x7a, 0x20, 0x21}; EXPECT_TRUE(QuicFramer::WriteClientVersionNegotiationProbePacket( packet, sizeof(packet), destination_connection_id_bytes, sizeof(destination_connection_id_bytes))); QuicEncryptedPacket encrypted(packet, sizeof(packet), false); std::unique_ptr<QuicReceivedPacket> received_packet( ConstructReceivedPacket(encrypted, mock_helper_.GetClock()->Now())); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); dispatcher_->ProcessPacket(server_address_, client_address, *received_packet); ASSERT_EQ(1u, saving_writer->packets()->size()); char source_connection_id_bytes[255] = {}; uint8_t source_connection_id_length = sizeof(source_connection_id_bytes); std::string detailed_error = "foobar"; EXPECT_TRUE(QuicFramer::ParseServerVersionNegotiationProbeResponse( (*(saving_writer->packets()))[0]->data(), (*(saving_writer->packets()))[0]->length(), source_connection_id_bytes, &source_connection_id_length, &detailed_error)); EXPECT_EQ("", detailed_error); quiche::test::CompareCharArraysWithHexError( "parsed probe", source_connection_id_bytes, source_connection_id_length, destination_connection_id_bytes, sizeof(destination_connection_id_bytes)); } TEST_P(QuicDispatcherTestOneVersion, AndroidConformanceTest) { SavingWriter* saving_writer = new SavingWriter(); QuicDispatcherPeer::UseWriter(dispatcher_.get(), saving_writer); QuicTimeWaitListManager* time_wait_list_manager = new QuicTimeWaitListManager( saving_writer, dispatcher_.get(), mock_helper_.GetClock(), &mock_alarm_factory_); QuicDispatcherPeer::SetTimeWaitListManager(dispatcher_.get(), time_wait_list_manager); static const unsigned char packet[1200] = { 0xc0, 0xaa, 0xda, 0xca, 0xca, 0x08, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x00, }; QuicEncryptedPacket encrypted(reinterpret_cast<const char*>(packet), sizeof(packet), false); std::unique_ptr<QuicReceivedPacket> received_packet( ConstructReceivedPacket(encrypted, mock_helper_.GetClock()->Now())); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); dispatcher_->ProcessPacket(server_address_, client_address, *received_packet); ASSERT_EQ(1u, saving_writer->packets()->size()); ASSERT_GE((*(saving_writer->packets()))[0]->length(), 15u); quiche::test::CompareCharArraysWithHexError( "response connection ID", &(*(saving_writer->packets()))[0]->data()[7], 8, reinterpret_cast<const char*>(&packet[6]), 8); } TEST_P(QuicDispatcherTestOneVersion, AndroidConformanceTestOld) { SavingWriter* saving_writer = new SavingWriter(); QuicDispatcherPeer::UseWriter(dispatcher_.get(), saving_writer); QuicTimeWaitListManager* time_wait_list_manager = new QuicTimeWaitListManager( saving_writer, dispatcher_.get(), mock_helper_.GetClock(), &mock_alarm_factory_); QuicDispatcherPeer::SetTimeWaitListManager(dispatcher_.get(), time_wait_list_manager); static const unsigned char packet[1200] = { 0x0d, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0xaa, 0xda, 0xca, 0xaa, 0x01, 0x00, 0x07, }; QuicEncryptedPacket encrypted(reinterpret_cast<const char*>(packet), sizeof(packet), false); std::unique_ptr<QuicReceivedPacket> received_packet( ConstructReceivedPacket(encrypted, mock_helper_.GetClock()->Now())); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); dispatcher_->ProcessPacket(server_address_, client_address, *received_packet); ASSERT_EQ(1u, saving_writer->packets()->size()); static const char connection_id_bytes[] = {0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78}; ASSERT_GE((*(saving_writer->packets()))[0]->length(), 1u + sizeof(connection_id_bytes)); quiche::test::CompareCharArraysWithHexError( "response connection ID", &(*(saving_writer->packets()))[0]->data()[1], sizeof(connection_id_bytes), connection_id_bytes, sizeof(connection_id_bytes)); } TEST_P(QuicDispatcherTestAllVersions, DoNotProcessSmallPacket) { CreateTimeWaitListManager(); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); EXPECT_CALL(*time_wait_list_manager_, SendPacket(_, _, _)).Times(0); EXPECT_CALL(*time_wait_list_manager_, AddConnectionIdToTimeWait(_, _)) .Times(0); ProcessPacket(client_address, TestConnectionId(1), true, version_, SerializeCHLO(), false, CONNECTION_ID_PRESENT, PACKET_4BYTE_PACKET_NUMBER, 1); } TEST_P(QuicDispatcherTestAllVersions, ProcessSmallCoalescedPacket) { CreateTimeWaitListManager(); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL(*time_wait_list_manager_, SendPacket(_, _, _)).Times(0); uint8_t coalesced_packet[1200] = { 0xC3, 'Q', '0', '9', '9', 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x05, 0x12, 0x34, 0x56, 0x78, 0x00, 0xC3, 'Q', '0', '9', '9', 0x08, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10, 0x00, 0x1E, 0x12, 0x34, 0x56, 0x79, }; QuicReceivedPacket packet(reinterpret_cast<char*>(coalesced_packet), 1200, QuicTime::Zero()); dispatcher_->ProcessPacket(server_address_, client_address, packet); } TEST_P(QuicDispatcherTestAllVersions, StopAcceptingNewConnections) { QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL(*dispatcher_, CreateQuicSession(TestConnectionId(1), _, client_address, Eq(ExpectedAlpn()), _, _, _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, TestConnectionId(1), client_address, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { ValidatePacket(TestConnectionId(1), packet); }))); ProcessFirstFlight(client_address, TestConnectionId(1)); dispatcher_->StopAcceptingNewConnections(); EXPECT_FALSE(dispatcher_->accept_new_connections()); EXPECT_CALL(*dispatcher_, CreateQuicSession(TestConnectionId(2), _, client_address, Eq(ExpectedAlpn()), _, _, _)) .Times(0u); expect_generator_is_called_ = false; ProcessFirstFlight(client_address, TestConnectionId(2)); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .Times(1u) .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { ValidatePacket(TestConnectionId(1), packet); }))); ProcessPacket(client_address, TestConnectionId(1), false, "data"); } TEST_P(QuicDispatcherTestAllVersions, StartAcceptingNewConnections) { dispatcher_->StopAcceptingNewConnections(); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL(*dispatcher_, CreateQuicSession(TestConnectionId(2), _, client_address, Eq(ExpectedAlpn()), _, _, _)) .Times(0u); expect_generator_is_called_ = false; ProcessFirstFlight(client_address, TestConnectionId(2)); dispatcher_->StartAcceptingNewConnections(); EXPECT_TRUE(dispatcher_->accept_new_connections()); expect_generator_is_called_ = true; EXPECT_CALL(*dispatcher_, CreateQuicSession(TestConnectionId(1), _, client_address, Eq(ExpectedAlpn()), _, _, _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, TestConnectionId(1), client_address, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { ValidatePacket(TestConnectionId(1), packet); }))); ProcessFirstFlight(client_address, TestConnectionId(1)); } TEST_P(QuicDispatcherTestOneVersion, SelectAlpn) { EXPECT_EQ(QuicDispatcherPeer::SelectAlpn(dispatcher_.get(), {}), ""); EXPECT_EQ(QuicDispatcherPeer::SelectAlpn(dispatcher_.get(), {""}), ""); EXPECT_EQ(QuicDispatcherPeer::SelectAlpn(dispatcher_.get(), {"hq"}), "hq"); QuicEnableVersion(ParsedQuicVersion::Q046()); EXPECT_EQ( QuicDispatcherPeer::SelectAlpn(dispatcher_.get(), {"h3-Q033", "h3-Q046"}), "h3-Q046"); } TEST_P(QuicDispatcherTestNoVersions, VersionNegotiationFromReservedVersion) { CreateTimeWaitListManager(); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); EXPECT_CALL( *time_wait_list_manager_, SendVersionNegotiationPacket(TestConnectionId(1), _, _, _, _, _, _, _)) .Times(1); expect_generator_is_called_ = false; ProcessFirstFlight(QuicVersionReservedForNegotiation(), client_address, TestConnectionId(1)); } TEST_P(QuicDispatcherTestNoVersions, VersionNegotiationFromRealVersion) { CreateTimeWaitListManager(); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); EXPECT_CALL( *time_wait_list_manager_, SendVersionNegotiationPacket(TestConnectionId(1), _, _, _, _, _, _, _)) .Times(1); expect_generator_is_called_ = false; ProcessFirstFlight(version_, client_address, TestConnectionId(1)); } class QuicDispatcherTestStrayPacketConnectionId : public QuicDispatcherTestBase {}; INSTANTIATE_TEST_SUITE_P(QuicDispatcherTestsStrayPacketConnectionId, QuicDispatcherTestStrayPacketConnectionId, ::testing::ValuesIn(CurrentSupportedVersions()), ::testing::PrintToStringParamName()); TEST_P(QuicDispatcherTestStrayPacketConnectionId, StrayPacketTruncatedConnectionId) { CreateTimeWaitListManager(); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); QuicConnectionId connection_id = TestConnectionId(1); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, _, _, _, _, _)).Times(0); EXPECT_CALL(*time_wait_list_manager_, ProcessPacket(_, _, _, _, _, _)) .Times(0); EXPECT_CALL(*time_wait_list_manager_, AddConnectionIdToTimeWait(_, _)) .Times(0); ProcessPacket(client_address, connection_id, true, "data", CONNECTION_ID_ABSENT, PACKET_4BYTE_PACKET_NUMBER); } class BlockingWriter : public QuicPacketWriterWrapper { public: BlockingWriter() : write_blocked_(false) {} bool IsWriteBlocked() const override { return write_blocked_; } void SetWritable() override { write_blocked_ = false; } WriteResult WritePacket(const char* , size_t , const QuicIpAddress& , const QuicSocketAddress& , PerPacketOptions* , const QuicPacketWriterParams& ) override { QUIC_LOG(DFATAL) << "Not supported"; return WriteResult(); } bool write_blocked_; }; class QuicDispatcherWriteBlockedListTest : public QuicDispatcherTestBase { public: void SetUp() override { QuicDispatcherTestBase::SetUp(); writer_ = new BlockingWriter; QuicDispatcherPeer::UseWriter(dispatcher_.get(), writer_); QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, client_address, Eq(ExpectedAlpn()), _, _, _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, TestConnectionId(1), client_address, &helper_, &alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { ValidatePacket(TestConnectionId(1), packet); }))); ProcessFirstFlight(client_address, TestConnectionId(1)); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, client_address, Eq(ExpectedAlpn()), _, _, _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, TestConnectionId(2), client_address, &helper_, &alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session2_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session2_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { ValidatePacket(TestConnectionId(2), packet); }))); ProcessFirstFlight(client_address, TestConnectionId(2)); blocked_list_ = QuicDispatcherPeer::GetWriteBlockedList(dispatcher_.get()); } void TearDown() override { if (connection1() != nullptr) { EXPECT_CALL(*connection1(), CloseConnection(QUIC_PEER_GOING_AWAY, _, _)); } if (connection2() != nullptr) { EXPECT_CALL(*connection2(), CloseConnection(QUIC_PEER_GOING_AWAY, _, _)); } dispatcher_->Shutdown(); } void SetBlocked() { QUIC_LOG(INFO) << "set writer " << writer_ << " to blocked"; writer_->write_blocked_ = true; } void BlockConnection1() { Connection1Writer()->write_blocked_ = true; dispatcher_->OnWriteBlocked(connection1()); } BlockingWriter* Connection1Writer() { return static_cast<BlockingWriter*>(connection1()->writer()); } void BlockConnection2() { Connection2Writer()->write_blocked_ = true; dispatcher_->OnWriteBlocked(connection2()); } BlockingWriter* Connection2Writer() { return static_cast<BlockingWriter*>(connection2()->writer()); } protected: MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; BlockingWriter* writer_; QuicBlockedWriterList* blocked_list_; }; INSTANTIATE_TEST_SUITE_P(QuicDispatcherWriteBlockedListTests, QuicDispatcherWriteBlockedListTest, ::testing::Values(CurrentSupportedVersions().front()), ::testing::PrintToStringParamName()); TEST_P(QuicDispatcherWriteBlockedListTest, BasicOnCanWrite) { dispatcher_->OnCanWrite(); SetBlocked(); dispatcher_->OnWriteBlocked(connection1()); EXPECT_CALL(*connection1(), OnCanWrite()); dispatcher_->OnCanWrite(); EXPECT_CALL(*connection1(), OnCanWrite()).Times(0); dispatcher_->OnCanWrite(); EXPECT_FALSE(dispatcher_->HasPendingWrites()); } TEST_P(QuicDispatcherWriteBlockedListTest, OnCanWriteOrder) { InSequence s; SetBlocked(); dispatcher_->OnWriteBlocked(connection1()); dispatcher_->OnWriteBlocked(connection2()); EXPECT_CALL(*connection1(), OnCanWrite()); EXPECT_CALL(*connection2(), OnCanWrite()); dispatcher_->OnCanWrite(); SetBlocked(); dispatcher_->OnWriteBlocked(connection2()); dispatcher_->OnWriteBlocked(connection1()); EXPECT_CALL(*connection2(), OnCanWrite()); EXPECT_CALL(*connection1(), OnCanWrite()); dispatcher_->OnCanWrite(); } TEST_P(QuicDispatcherWriteBlockedListTest, OnCanWriteRemove) { SetBlocked(); dispatcher_->OnWriteBlocked(connection1()); blocked_list_->Remove(*connection1()); EXPECT_CALL(*connection1(), OnCanWrite()).Times(0); dispatcher_->OnCanWrite(); SetBlocked(); dispatcher_->OnWriteBlocked(connection1()); dispatcher_->OnWriteBlocked(connection2()); blocked_list_->Remove(*connection1()); EXPECT_CALL(*connection2(), OnCanWrite()); dispatcher_->OnCanWrite(); SetBlocked(); dispatcher_->OnWriteBlocked(connection1()); blocked_list_->Remove(*connection1()); dispatcher_->OnWriteBlocked(connection1()); EXPECT_CALL(*connection1(), OnCanWrite()).Times(1); dispatcher_->OnCanWrite(); } TEST_P(QuicDispatcherWriteBlockedListTest, DoubleAdd) { SetBlocked(); dispatcher_->OnWriteBlocked(connection1()); dispatcher_->OnWriteBlocked(connection1()); blocked_list_->Remove(*connection1()); EXPECT_CALL(*connection1(), OnCanWrite()).Times(0); dispatcher_->OnCanWrite(); SetBlocked(); dispatcher_->OnWriteBlocked(connection1()); dispatcher_->OnWriteBlocked(connection1()); EXPECT_CALL(*connection1(), OnCanWrite()).Times(1); dispatcher_->OnCanWrite(); } TEST_P(QuicDispatcherWriteBlockedListTest, OnCanWriteHandleBlockConnection1) { InSequence s; SetBlocked(); dispatcher_->OnWriteBlocked(connection1()); dispatcher_->OnWriteBlocked(connection2()); EXPECT_CALL(*connection1(), OnCanWrite()) .WillOnce( Invoke(this, &QuicDispatcherWriteBlockedListTest::BlockConnection1)); EXPECT_CALL(*connection2(), OnCanWrite()); dispatcher_->OnCanWrite(); EXPECT_TRUE(dispatcher_->HasPendingWrites()); EXPECT_CALL(*connection1(), OnCanWrite()); EXPECT_CALL(*connection2(), OnCanWrite()).Times(0); dispatcher_->OnCanWrite(); EXPECT_FALSE(dispatcher_->HasPendingWrites()); } TEST_P(QuicDispatcherWriteBlockedListTest, OnCanWriteHandleBlockConnection2) { InSequence s; SetBlocked(); dispatcher_->OnWriteBlocked(connection1()); dispatcher_->OnWriteBlocked(connection2()); EXPECT_CALL(*connection1(), OnCanWrite()); EXPECT_CALL(*connection2(), OnCanWrite()) .WillOnce( Invoke(this, &QuicDispatcherWriteBlockedListTest::BlockConnection2)); dispatcher_->OnCanWrite(); EXPECT_TRUE(dispatcher_->HasPendingWrites()); EXPECT_CALL(*connection1(), OnCanWrite()).Times(0); EXPECT_CALL(*connection2(), OnCanWrite()); dispatcher_->OnCanWrite(); EXPECT_FALSE(dispatcher_->HasPendingWrites()); } TEST_P(QuicDispatcherWriteBlockedListTest, OnCanWriteHandleBlockBothConnections) { InSequence s; SetBlocked(); dispatcher_->OnWriteBlocked(connection1()); dispatcher_->OnWriteBlocked(connection2()); EXPECT_CALL(*connection1(), OnCanWrite()) .WillOnce( Invoke(this, &QuicDispatcherWriteBlockedListTest::BlockConnection1)); EXPECT_CALL(*connection2(), OnCanWrite()) .WillOnce( Invoke(this, &QuicDispatcherWriteBlockedListTest::BlockConnection2)); dispatcher_->OnCanWrite(); EXPECT_TRUE(dispatcher_->HasPendingWrites()); EXPECT_CALL(*connection1(), OnCanWrite()); EXPECT_CALL(*connection2(), OnCanWrite()); dispatcher_->OnCanWrite(); EXPECT_FALSE(dispatcher_->HasPendingWrites()); } TEST_P(QuicDispatcherWriteBlockedListTest, PerConnectionWriterBlocked) { EXPECT_EQ(dispatcher_->writer(), connection1()->writer()); EXPECT_EQ(dispatcher_->writer(), connection2()->writer()); connection2()->SetQuicPacketWriter(new BlockingWriter, true); EXPECT_NE(dispatcher_->writer(), connection2()->writer()); BlockConnection2(); EXPECT_TRUE(dispatcher_->HasPendingWrites()); EXPECT_CALL(*connection2(), OnCanWrite()); dispatcher_->OnCanWrite(); EXPECT_FALSE(dispatcher_->HasPendingWrites()); } TEST_P(QuicDispatcherWriteBlockedListTest, RemoveConnectionFromWriteBlockedListWhenDeletingSessions) { EXPECT_QUIC_BUG( { dispatcher_->OnConnectionClosed( connection1()->connection_id(), QUIC_PACKET_WRITE_ERROR, "Closed by test.", ConnectionCloseSource::FROM_SELF); SetBlocked(); ASSERT_FALSE(dispatcher_->HasPendingWrites()); SetBlocked(); dispatcher_->OnWriteBlocked(connection1()); ASSERT_TRUE(dispatcher_->HasPendingWrites()); dispatcher_->DeleteSessions(); MarkSession1Deleted(); }, "QuicConnection was in WriteBlockedList before destruction"); } class QuicDispatcherSupportMultipleConnectionIdPerConnectionTest : public QuicDispatcherTestBase { public: QuicDispatcherSupportMultipleConnectionIdPerConnectionTest() : QuicDispatcherTestBase(crypto_test_utils::ProofSourceForTesting()) { dispatcher_ = std::make_unique<NiceMock<TestDispatcher>>( &config_, &crypto_config_, &version_manager_, mock_helper_.GetRandomGenerator(), connection_id_generator_); } void AddConnection1() { QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 1); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, client_address, Eq(ExpectedAlpn()), _, _, _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, TestConnectionId(1), client_address, &helper_, &alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { ValidatePacket(TestConnectionId(1), packet); }))); ProcessFirstFlight(client_address, TestConnectionId(1)); } void AddConnection2() { QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 2); EXPECT_CALL(*dispatcher_, CreateQuicSession(_, _, client_address, Eq(ExpectedAlpn()), _, _, _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, TestConnectionId(2), client_address, &helper_, &alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session2_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session2_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>(Invoke([this](const QuicEncryptedPacket& packet) { ValidatePacket(TestConnectionId(2), packet); }))); ProcessFirstFlight(client_address, TestConnectionId(2)); } protected: MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; }; INSTANTIATE_TEST_SUITE_P( QuicDispatcherSupportMultipleConnectionIdPerConnectionTests, QuicDispatcherSupportMultipleConnectionIdPerConnectionTest, ::testing::Values(CurrentSupportedVersions().front()), ::testing::PrintToStringParamName()); TEST_P(QuicDispatcherSupportMultipleConnectionIdPerConnectionTest, FailToAddExistingConnectionId) { AddConnection1(); EXPECT_FALSE(dispatcher_->TryAddNewConnectionId(TestConnectionId(1), TestConnectionId(1))); } TEST_P(QuicDispatcherSupportMultipleConnectionIdPerConnectionTest, TryAddNewConnectionId) { AddConnection1(); ASSERT_EQ(dispatcher_->NumSessions(), 1u); ASSERT_THAT(session1_, testing::NotNull()); MockServerConnection* mock_server_connection1 = reinterpret_cast<MockServerConnection*>(connection1()); { mock_server_connection1->AddNewConnectionId(TestConnectionId(3)); EXPECT_EQ(dispatcher_->NumSessions(), 1u); auto* session = QuicDispatcherPeer::FindSession(dispatcher_.get(), TestConnectionId(3)); ASSERT_EQ(session, session1_); } { mock_server_connection1->AddNewConnectionId(TestConnectionId(4)); EXPECT_EQ(dispatcher_->NumSessions(), 1u); auto* session = QuicDispatcherPeer::FindSession(dispatcher_.get(), TestConnectionId(4)); ASSERT_EQ(session, session1_); } EXPECT_CALL(*connection1(), CloseConnection(QUIC_PEER_GOING_AWAY, _, _)); dispatcher_->Shutdown(); } TEST_P(QuicDispatcherSupportMultipleConnectionIdPerConnectionTest, TryAddNewConnectionIdWithCollision) { AddConnection1(); AddConnection2(); ASSERT_EQ(dispatcher_->NumSessions(), 2u); ASSERT_THAT(session1_, testing::NotNull()); ASSERT_THAT(session2_, testing::NotNull()); MockServerConnection* mock_server_connection1 = reinterpret_cast<MockServerConnection*>(connection1()); MockServerConnection* mock_server_connection2 = reinterpret_cast<MockServerConnection*>(connection2()); { mock_server_connection1->UnconditionallyAddNewConnectionIdForTest( TestConnectionId(2)); EXPECT_EQ(dispatcher_->NumSessions(), 2u); auto* session = QuicDispatcherPeer::FindSession(dispatcher_.get(), TestConnectionId(2)); ASSERT_EQ(session, session2_); EXPECT_THAT(mock_server_connection1->GetActiveServerConnectionIds(), testing::ElementsAre(TestConnectionId(1), TestConnectionId(2))); } { mock_server_connection2->AddNewConnectionId(TestConnectionId(3)); EXPECT_EQ(dispatcher_->NumSessions(), 2u); auto* session = QuicDispatcherPeer::FindSession(dispatcher_.get(), TestConnectionId(3)); ASSERT_EQ(session, session2_); EXPECT_THAT(mock_server_connection2->GetActiveServerConnectionIds(), testing::ElementsAre(TestConnectionId(2), TestConnectionId(3))); } dispatcher_->OnConnectionClosed(TestConnectionId(2), QuicErrorCode::QUIC_NO_ERROR, "detail", quic::ConnectionCloseSource::FROM_SELF); EXPECT_QUICHE_BUG(dispatcher_->OnConnectionClosed( TestConnectionId(1), QuicErrorCode::QUIC_NO_ERROR, "detail", quic::ConnectionCloseSource::FROM_SELF), "Missing session for cid"); } TEST_P(QuicDispatcherSupportMultipleConnectionIdPerConnectionTest, MismatchedSessionAfterAddingCollidedConnectionId) { AddConnection1(); AddConnection2(); MockServerConnection* mock_server_connection1 = reinterpret_cast<MockServerConnection*>(connection1()); { mock_server_connection1->UnconditionallyAddNewConnectionIdForTest( TestConnectionId(2)); EXPECT_EQ(dispatcher_->NumSessions(), 2u); auto* session = QuicDispatcherPeer::FindSession(dispatcher_.get(), TestConnectionId(2)); ASSERT_EQ(session, session2_); EXPECT_THAT(mock_server_connection1->GetActiveServerConnectionIds(), testing::ElementsAre(TestConnectionId(1), TestConnectionId(2))); } EXPECT_QUIC_BUG(dispatcher_->OnConnectionClosed( TestConnectionId(1), QuicErrorCode::QUIC_NO_ERROR, "detail", quic::ConnectionCloseSource::FROM_SELF), "Session is mismatched in the map"); } TEST_P(QuicDispatcherSupportMultipleConnectionIdPerConnectionTest, RetireConnectionIdFromSingleConnection) { AddConnection1(); ASSERT_EQ(dispatcher_->NumSessions(), 1u); ASSERT_THAT(session1_, testing::NotNull()); MockServerConnection* mock_server_connection1 = reinterpret_cast<MockServerConnection*>(connection1()); for (int i = 2; i < 10; ++i) { mock_server_connection1->AddNewConnectionId(TestConnectionId(i)); ASSERT_EQ( QuicDispatcherPeer::FindSession(dispatcher_.get(), TestConnectionId(i)), session1_); ASSERT_EQ(QuicDispatcherPeer::FindSession(dispatcher_.get(), TestConnectionId(i - 1)), session1_); EXPECT_EQ(dispatcher_->NumSessions(), 1u); if (i % 2 == 1) { mock_server_connection1->RetireConnectionId(TestConnectionId(i - 2)); mock_server_connection1->RetireConnectionId(TestConnectionId(i - 1)); } } EXPECT_CALL(*connection1(), CloseConnection(QUIC_PEER_GOING_AWAY, _, _)); dispatcher_->Shutdown(); } TEST_P(QuicDispatcherSupportMultipleConnectionIdPerConnectionTest, RetireConnectionIdFromMultipleConnections) { AddConnection1(); AddConnection2(); ASSERT_EQ(dispatcher_->NumSessions(), 2u); MockServerConnection* mock_server_connection1 = reinterpret_cast<MockServerConnection*>(connection1()); MockServerConnection* mock_server_connection2 = reinterpret_cast<MockServerConnection*>(connection2()); for (int i = 2; i < 10; ++i) { mock_server_connection1->AddNewConnectionId(TestConnectionId(2 * i - 1)); mock_server_connection2->AddNewConnectionId(TestConnectionId(2 * i)); ASSERT_EQ(QuicDispatcherPeer::FindSession(dispatcher_.get(), TestConnectionId(2 * i - 1)), session1_); ASSERT_EQ(QuicDispatcherPeer::FindSession(dispatcher_.get(), TestConnectionId(2 * i)), session2_); EXPECT_EQ(dispatcher_->NumSessions(), 2u); mock_server_connection1->RetireConnectionId(TestConnectionId(2 * i - 3)); mock_server_connection2->RetireConnectionId(TestConnectionId(2 * i - 2)); } mock_server_connection1->AddNewConnectionId(TestConnectionId(19)); mock_server_connection2->AddNewConnectionId(TestConnectionId(20)); EXPECT_CALL(*connection1(), CloseConnection(QUIC_PEER_GOING_AWAY, _, _)); EXPECT_CALL(*connection2(), CloseConnection(QUIC_PEER_GOING_AWAY, _, _)); dispatcher_->Shutdown(); } TEST_P(QuicDispatcherSupportMultipleConnectionIdPerConnectionTest, TimeWaitListPoplulateCorrectly) { QuicTimeWaitListManager* time_wait_list_manager = QuicDispatcherPeer::GetTimeWaitListManager(dispatcher_.get()); AddConnection1(); MockServerConnection* mock_server_connection1 = reinterpret_cast<MockServerConnection*>(connection1()); mock_server_connection1->AddNewConnectionId(TestConnectionId(2)); mock_server_connection1->AddNewConnectionId(TestConnectionId(3)); mock_server_connection1->AddNewConnectionId(TestConnectionId(4)); mock_server_connection1->RetireConnectionId(TestConnectionId(1)); mock_server_connection1->RetireConnectionId(TestConnectionId(2)); EXPECT_CALL(*connection1(), CloseConnection(QUIC_PEER_GOING_AWAY, _, _)); connection1()->CloseConnection( QUIC_PEER_GOING_AWAY, "Close for testing", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); EXPECT_FALSE( time_wait_list_manager->IsConnectionIdInTimeWait(TestConnectionId(1))); EXPECT_FALSE( time_wait_list_manager->IsConnectionIdInTimeWait(TestConnectionId(2))); EXPECT_TRUE( time_wait_list_manager->IsConnectionIdInTimeWait(TestConnectionId(3))); EXPECT_TRUE( time_wait_list_manager->IsConnectionIdInTimeWait(TestConnectionId(4))); dispatcher_->Shutdown(); } class BufferedPacketStoreTest : public QuicDispatcherTestBase { public: BufferedPacketStoreTest() : QuicDispatcherTestBase(), client_addr_(QuicIpAddress::Loopback4(), 1234) {} void ProcessFirstFlight(const ParsedQuicVersion& version, const QuicSocketAddress& peer_address, const QuicConnectionId& server_connection_id) { QuicDispatcherTestBase::ProcessFirstFlight(version, peer_address, server_connection_id); } void ProcessFirstFlight(const QuicSocketAddress& peer_address, const QuicConnectionId& server_connection_id) { ProcessFirstFlight(version_, peer_address, server_connection_id); } void ProcessFirstFlight(const QuicConnectionId& server_connection_id) { ProcessFirstFlight(client_addr_, server_connection_id); } void ProcessFirstFlight(const ParsedQuicVersion& version, const QuicConnectionId& server_connection_id) { ProcessFirstFlight(version, client_addr_, server_connection_id); } void ProcessUndecryptableEarlyPacket( const ParsedQuicVersion& version, const QuicSocketAddress& peer_address, const QuicConnectionId& server_connection_id) { QuicDispatcherTestBase::ProcessUndecryptableEarlyPacket( version, peer_address, server_connection_id); } void ProcessUndecryptableEarlyPacket( const QuicSocketAddress& peer_address, const QuicConnectionId& server_connection_id) { ProcessUndecryptableEarlyPacket(version_, peer_address, server_connection_id); } void ProcessUndecryptableEarlyPacket( const QuicConnectionId& server_connection_id) { ProcessUndecryptableEarlyPacket(version_, client_addr_, server_connection_id); } protected: QuicSocketAddress client_addr_; }; INSTANTIATE_TEST_SUITE_P(BufferedPacketStoreTests, BufferedPacketStoreTest, ::testing::ValuesIn(CurrentSupportedVersions()), ::testing::PrintToStringParamName()); TEST_P(BufferedPacketStoreTest, ProcessNonChloPacketBeforeChlo) { InSequence s; QuicConnectionId conn_id = TestConnectionId(1); ProcessUndecryptableEarlyPacket(conn_id); EXPECT_EQ(0u, dispatcher_->NumSessions()) << "No session should be created before CHLO arrives."; EXPECT_CALL(connection_id_generator_, MaybeReplaceConnectionId(conn_id, version_)) .WillOnce(Return(std::nullopt)); EXPECT_CALL(*dispatcher_, CreateQuicSession(conn_id, _, client_addr_, Eq(ExpectedAlpn()), _, MatchParsedClientHello(), _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, conn_id, client_addr_, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .Times(2) .WillRepeatedly( WithArg<2>(Invoke([this, conn_id](const QuicEncryptedPacket& packet) { if (version_.UsesQuicCrypto()) { ValidatePacket(conn_id, packet); } }))); expect_generator_is_called_ = false; ProcessFirstFlight(conn_id); } TEST_P(BufferedPacketStoreTest, ProcessNonChloPacketsUptoLimitAndProcessChlo) { InSequence s; QuicConnectionId conn_id = TestConnectionId(1); for (size_t i = 1; i <= kDefaultMaxUndecryptablePackets + 1; ++i) { ProcessUndecryptableEarlyPacket(conn_id); } EXPECT_EQ(0u, dispatcher_->NumSessions()) << "No session should be created before CHLO arrives."; data_connection_map_[conn_id].pop_back(); EXPECT_CALL(connection_id_generator_, MaybeReplaceConnectionId(conn_id, version_)) .WillOnce(Return(std::nullopt)); EXPECT_CALL(*dispatcher_, CreateQuicSession(conn_id, _, client_addr_, Eq(ExpectedAlpn()), _, _, _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, conn_id, client_addr_, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .Times(kDefaultMaxUndecryptablePackets + 1) .WillRepeatedly( WithArg<2>(Invoke([this, conn_id](const QuicEncryptedPacket& packet) { if (version_.UsesQuicCrypto()) { ValidatePacket(conn_id, packet); } }))); expect_generator_is_called_ = false; ProcessFirstFlight(conn_id); } TEST_P(BufferedPacketStoreTest, ProcessNonChloPacketsForDifferentConnectionsUptoLimit) { InSequence s; size_t kNumConnections = kMaxConnectionsWithoutCHLO + 1; for (size_t i = 1; i <= kNumConnections; ++i) { QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 20000 + i); QuicConnectionId conn_id = TestConnectionId(i); ProcessUndecryptableEarlyPacket(client_address, conn_id); } data_connection_map_[TestConnectionId(kNumConnections)].pop_front(); QuicDispatcherPeer::set_new_sessions_allowed_per_event_loop(dispatcher_.get(), kNumConnections); expect_generator_is_called_ = false; for (size_t i = 1; i <= kNumConnections; ++i) { QuicSocketAddress client_address(QuicIpAddress::Loopback4(), 20000 + i); QuicConnectionId conn_id = TestConnectionId(i); EXPECT_CALL(connection_id_generator_, MaybeReplaceConnectionId(conn_id, version_)) .WillOnce(Return(std::nullopt)); EXPECT_CALL(*dispatcher_, CreateQuicSession(conn_id, _, client_address, Eq(ExpectedAlpn()), _, _, _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, conn_id, client_address, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); size_t num_packet_to_process = i <= kMaxConnectionsWithoutCHLO ? 2u : 1u; EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, client_address, _)) .Times(num_packet_to_process) .WillRepeatedly(WithArg<2>( Invoke([this, conn_id](const QuicEncryptedPacket& packet) { if (version_.UsesQuicCrypto()) { ValidatePacket(conn_id, packet); } }))); ProcessFirstFlight(client_address, conn_id); } } TEST_P(BufferedPacketStoreTest, DeliverEmptyPackets) { QuicConnectionId conn_id = TestConnectionId(1); EXPECT_CALL(*dispatcher_, CreateQuicSession(conn_id, _, client_addr_, Eq(ExpectedAlpn()), _, _, _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, conn_id, client_addr_, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, client_addr_, _)); ProcessFirstFlight(conn_id); } TEST_P(BufferedPacketStoreTest, ReceiveRetransmittedCHLO) { InSequence s; QuicConnectionId conn_id = TestConnectionId(1); ProcessUndecryptableEarlyPacket(conn_id); EXPECT_CALL(connection_id_generator_, MaybeReplaceConnectionId(conn_id, version_)) .WillOnce(Return(std::nullopt)); EXPECT_CALL(*dispatcher_, CreateQuicSession(conn_id, _, client_addr_, Eq(ExpectedAlpn()), _, _, _)) .Times(1) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, conn_id, client_addr_, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .Times(3) .WillRepeatedly( WithArg<2>(Invoke([this, conn_id](const QuicEncryptedPacket& packet) { if (version_.UsesQuicCrypto()) { ValidatePacket(conn_id, packet); } }))); std::vector<std::unique_ptr<QuicReceivedPacket>> packets = GetFirstFlightOfPackets(version_, conn_id); ASSERT_EQ(packets.size(), 1u); ProcessReceivedPacket(packets[0]->Clone(), client_addr_, version_, conn_id); ProcessReceivedPacket(std::move(packets[0]), client_addr_, version_, conn_id); } TEST_P(BufferedPacketStoreTest, ReceiveCHLOAfterExpiration) { InSequence s; CreateTimeWaitListManager(); QuicBufferedPacketStore* store = QuicDispatcherPeer::GetBufferedPackets(dispatcher_.get()); QuicBufferedPacketStorePeer::set_clock(store, mock_helper_.GetClock()); QuicConnectionId conn_id = TestConnectionId(1); ProcessPacket(client_addr_, conn_id, true, absl::StrCat("data packet ", 2), CONNECTION_ID_PRESENT, PACKET_4BYTE_PACKET_NUMBER, 2); mock_helper_.AdvanceTime( QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs)); QuicAlarm* alarm = QuicBufferedPacketStorePeer::expiration_alarm(store); alarm->Cancel(); store->OnExpirationTimeout(); ASSERT_TRUE(time_wait_list_manager_->IsConnectionIdInTimeWait(conn_id)); EXPECT_CALL(*time_wait_list_manager_, ProcessPacket(_, _, conn_id, _, _, _)); expect_generator_is_called_ = false; ProcessFirstFlight(conn_id); } TEST_P(BufferedPacketStoreTest, ProcessCHLOsUptoLimitAndBufferTheRest) { QuicBufferedPacketStore* store = QuicDispatcherPeer::GetBufferedPackets(dispatcher_.get()); const size_t kNumCHLOs = kMaxNumSessionsToCreate + kDefaultMaxConnectionsInStore + 1; for (uint64_t conn_id = 1; conn_id <= kNumCHLOs; ++conn_id) { const bool should_drop = (conn_id > kMaxNumSessionsToCreate + kDefaultMaxConnectionsInStore); if (!should_drop) { EXPECT_CALL(connection_id_generator_, MaybeReplaceConnectionId(TestConnectionId(conn_id), version_)) .WillOnce(Return(std::nullopt)); } if (conn_id <= kMaxNumSessionsToCreate) { EXPECT_CALL( *dispatcher_, CreateQuicSession(TestConnectionId(conn_id), _, client_addr_, Eq(ExpectedAlpn()), _, MatchParsedClientHello(), _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, TestConnectionId(conn_id), client_addr_, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL( *reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>( Invoke([this, conn_id](const QuicEncryptedPacket& packet) { if (version_.UsesQuicCrypto()) { ValidatePacket(TestConnectionId(conn_id), packet); } }))); } expect_generator_is_called_ = false; ProcessFirstFlight(TestConnectionId(conn_id)); if (conn_id <= kMaxNumSessionsToCreate + kDefaultMaxConnectionsInStore && conn_id > kMaxNumSessionsToCreate) { EXPECT_TRUE(store->HasChloForConnection(TestConnectionId(conn_id))); } else { EXPECT_FALSE(store->HasChloForConnection(TestConnectionId(conn_id))); } } for (uint64_t conn_id = kMaxNumSessionsToCreate + 1; conn_id <= kMaxNumSessionsToCreate + kDefaultMaxConnectionsInStore; ++conn_id) { EXPECT_CALL( *dispatcher_, CreateQuicSession(TestConnectionId(conn_id), _, client_addr_, Eq(ExpectedAlpn()), _, MatchParsedClientHello(), _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, TestConnectionId(conn_id), client_addr_, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>( Invoke([this, conn_id](const QuicEncryptedPacket& packet) { if (version_.UsesQuicCrypto()) { ValidatePacket(TestConnectionId(conn_id), packet); } }))); } EXPECT_CALL(connection_id_generator_, MaybeReplaceConnectionId(TestConnectionId(kNumCHLOs), version_)) .Times(0); EXPECT_CALL(*dispatcher_, CreateQuicSession(TestConnectionId(kNumCHLOs), _, client_addr_, Eq(ExpectedAlpn()), _, _, _)) .Times(0); while (store->HasChlosBuffered()) { dispatcher_->ProcessBufferedChlos(kMaxNumSessionsToCreate); } EXPECT_EQ(TestConnectionId(static_cast<size_t>(kMaxNumSessionsToCreate) + kDefaultMaxConnectionsInStore), session1_->connection_id()); } TEST_P(BufferedPacketStoreTest, ProcessCHLOsUptoLimitAndBufferWithDifferentConnectionIdGenerator) { QuicBufferedPacketStore* store = QuicDispatcherPeer::GetBufferedPackets(dispatcher_.get()); const size_t kNumCHLOs = kMaxNumSessionsToCreate + 1; for (uint64_t conn_id = 1; conn_id < kNumCHLOs; ++conn_id) { EXPECT_CALL( *dispatcher_, CreateQuicSession(TestConnectionId(conn_id), _, client_addr_, Eq(ExpectedAlpn()), _, MatchParsedClientHello(), _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, TestConnectionId(conn_id), client_addr_, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>( Invoke([this, conn_id](const QuicEncryptedPacket& packet) { if (version_.UsesQuicCrypto()) { ValidatePacket(TestConnectionId(conn_id), packet); } }))); ProcessFirstFlight(TestConnectionId(conn_id)); } uint64_t conn_id = kNumCHLOs; expect_generator_is_called_ = false; MockConnectionIdGenerator generator2; EXPECT_CALL(*dispatcher_, ConnectionIdGenerator()) .WillRepeatedly(ReturnRef(generator2)); const bool buffered_store_replace_cid = version_.UsesTls(); if (buffered_store_replace_cid) { EXPECT_CALL(generator2, MaybeReplaceConnectionId(TestConnectionId(conn_id), version_)) .WillOnce(Return(std::nullopt)); } ProcessFirstFlight(TestConnectionId(conn_id)); EXPECT_TRUE(store->HasChloForConnection(TestConnectionId(conn_id))); EXPECT_CALL(*dispatcher_, ConnectionIdGenerator()) .WillRepeatedly(ReturnRef(connection_id_generator_)); if (!buffered_store_replace_cid) { EXPECT_CALL(connection_id_generator_, MaybeReplaceConnectionId(TestConnectionId(conn_id), version_)) .WillOnce(Return(std::nullopt)); } EXPECT_CALL(*dispatcher_, CreateQuicSession(TestConnectionId(conn_id), _, client_addr_, Eq(ExpectedAlpn()), _, MatchParsedClientHello(), _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, TestConnectionId(conn_id), client_addr_, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce( WithArg<2>(Invoke([this, conn_id](const QuicEncryptedPacket& packet) { if (version_.UsesQuicCrypto()) { ValidatePacket(TestConnectionId(conn_id), packet); } }))); while (store->HasChlosBuffered()) { dispatcher_->ProcessBufferedChlos(kMaxNumSessionsToCreate); } } TEST_P(BufferedPacketStoreTest, BufferDuplicatedCHLO) { for (uint64_t conn_id = 1; conn_id <= kMaxNumSessionsToCreate + 1; ++conn_id) { if (conn_id <= kMaxNumSessionsToCreate) { EXPECT_CALL(*dispatcher_, CreateQuicSession(TestConnectionId(conn_id), _, client_addr_, Eq(ExpectedAlpn()), _, _, _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, TestConnectionId(conn_id), client_addr_, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL( *reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>( Invoke([this, conn_id](const QuicEncryptedPacket& packet) { if (version_.UsesQuicCrypto()) { ValidatePacket(TestConnectionId(conn_id), packet); } }))); } ProcessFirstFlight(TestConnectionId(conn_id)); } QuicConnectionId last_connection = TestConnectionId(kMaxNumSessionsToCreate + 1); expect_generator_is_called_ = false; ProcessFirstFlight(last_connection); size_t packets_buffered = 2; EXPECT_CALL(*dispatcher_, CreateQuicSession(last_connection, _, client_addr_, Eq(ExpectedAlpn()), _, _, _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, last_connection, client_addr_, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .Times(packets_buffered) .WillRepeatedly(WithArg<2>( Invoke([this, last_connection](const QuicEncryptedPacket& packet) { if (version_.UsesQuicCrypto()) { ValidatePacket(last_connection, packet); } }))); dispatcher_->ProcessBufferedChlos(kMaxNumSessionsToCreate); } TEST_P(BufferedPacketStoreTest, BufferNonChloPacketsUptoLimitWithChloBuffered) { uint64_t last_conn_id = kMaxNumSessionsToCreate + 1; QuicConnectionId last_connection_id = TestConnectionId(last_conn_id); for (uint64_t conn_id = 1; conn_id <= last_conn_id; ++conn_id) { if (conn_id <= kMaxNumSessionsToCreate) { EXPECT_CALL(*dispatcher_, CreateQuicSession(TestConnectionId(conn_id), _, client_addr_, Eq(ExpectedAlpn()), _, _, _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, TestConnectionId(conn_id), client_addr_, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL( *reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillRepeatedly(WithArg<2>( Invoke([this, conn_id](const QuicEncryptedPacket& packet) { if (version_.UsesQuicCrypto()) { ValidatePacket(TestConnectionId(conn_id), packet); } }))); } ProcessFirstFlight(TestConnectionId(conn_id)); } for (uint64_t i = 0; i <= kDefaultMaxUndecryptablePackets; ++i) { ProcessPacket(client_addr_, last_connection_id, false, "data packet"); } EXPECT_CALL(*dispatcher_, CreateQuicSession(last_connection_id, _, client_addr_, Eq(ExpectedAlpn()), _, _, _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, last_connection_id, client_addr_, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); const QuicBufferedPacketStore* store = QuicDispatcherPeer::GetBufferedPackets(dispatcher_.get()); const QuicBufferedPacketStore::BufferedPacketList* last_connection_buffered_packets = QuicBufferedPacketStorePeer::FindBufferedPackets(store, last_connection_id); ASSERT_NE(last_connection_buffered_packets, nullptr); ASSERT_EQ(last_connection_buffered_packets->buffered_packets.size(), kDefaultMaxUndecryptablePackets); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .Times(last_connection_buffered_packets->buffered_packets.size()) .WillRepeatedly(WithArg<2>( Invoke([this, last_connection_id](const QuicEncryptedPacket& packet) { if (version_.UsesQuicCrypto()) { ValidatePacket(last_connection_id, packet); } }))); dispatcher_->ProcessBufferedChlos(kMaxNumSessionsToCreate); } TEST_P(BufferedPacketStoreTest, ReceiveCHLOForBufferedConnection) { QuicBufferedPacketStore* store = QuicDispatcherPeer::GetBufferedPackets(dispatcher_.get()); uint64_t conn_id = 1; ProcessUndecryptableEarlyPacket(TestConnectionId(conn_id)); for (conn_id = 2; conn_id <= kDefaultMaxConnectionsInStore + kMaxNumSessionsToCreate; ++conn_id) { if (conn_id <= kMaxNumSessionsToCreate + 1) { EXPECT_CALL(*dispatcher_, CreateQuicSession(TestConnectionId(conn_id), _, client_addr_, Eq(ExpectedAlpn()), _, _, _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, TestConnectionId(conn_id), client_addr_, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL( *reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillOnce(WithArg<2>( Invoke([this, conn_id](const QuicEncryptedPacket& packet) { if (version_.UsesQuicCrypto()) { ValidatePacket(TestConnectionId(conn_id), packet); } }))); } else if (!version_.UsesTls()) { expect_generator_is_called_ = false; } ProcessFirstFlight(TestConnectionId(conn_id)); } EXPECT_FALSE(store->HasChloForConnection( TestConnectionId(1))); ProcessFirstFlight(TestConnectionId(1)); EXPECT_TRUE(store->HasChloForConnection( TestConnectionId(1))); } TEST_P(BufferedPacketStoreTest, ProcessBufferedChloWithDifferentVersion) { QuicDisableVersion(AllSupportedVersions().front()); uint64_t last_connection_id = kMaxNumSessionsToCreate + 5; ParsedQuicVersionVector supported_versions = CurrentSupportedVersions(); for (uint64_t conn_id = 1; conn_id <= last_connection_id; ++conn_id) { ParsedQuicVersion version = supported_versions[(conn_id - 1) % supported_versions.size()]; if (conn_id <= kMaxNumSessionsToCreate) { EXPECT_CALL( *dispatcher_, CreateQuicSession(TestConnectionId(conn_id), _, client_addr_, Eq(ExpectedAlpnForVersion(version)), version, _, _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, TestConnectionId(conn_id), client_addr_, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL( *reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillRepeatedly(WithArg<2>( Invoke([this, conn_id](const QuicEncryptedPacket& packet) { if (version_.UsesQuicCrypto()) { ValidatePacket(TestConnectionId(conn_id), packet); } }))); } ProcessFirstFlight(version, TestConnectionId(conn_id)); } for (uint64_t conn_id = kMaxNumSessionsToCreate + 1; conn_id <= last_connection_id; ++conn_id) { ParsedQuicVersion version = supported_versions[(conn_id - 1) % supported_versions.size()]; EXPECT_CALL( *dispatcher_, CreateQuicSession(TestConnectionId(conn_id), _, client_addr_, Eq(ExpectedAlpnForVersion(version)), version, _, _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, TestConnectionId(conn_id), client_addr_, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .WillRepeatedly(WithArg<2>( Invoke([this, conn_id](const QuicEncryptedPacket& packet) { if (version_.UsesQuicCrypto()) { ValidatePacket(TestConnectionId(conn_id), packet); } }))); } dispatcher_->ProcessBufferedChlos(kMaxNumSessionsToCreate); } TEST_P(BufferedPacketStoreTest, BufferedChloWithEcn) { if (!version_.HasIetfQuicFrames()) { return; } SetQuicRestartFlag(quic_support_ect1, true); InSequence s; QuicConnectionId conn_id = TestConnectionId(1); std::unique_ptr<QuicEncryptedPacket> encrypted_packet = GetUndecryptableEarlyPacket(version_, conn_id); std::unique_ptr<QuicReceivedPacket> received_packet(ConstructReceivedPacket( *encrypted_packet, mock_helper_.GetClock()->Now(), ECN_ECT1)); ProcessReceivedPacket(std::move(received_packet), client_addr_, version_, conn_id); EXPECT_EQ(0u, dispatcher_->NumSessions()) << "No session should be created before CHLO arrives."; EXPECT_CALL(connection_id_generator_, MaybeReplaceConnectionId(conn_id, version_)) .WillOnce(Return(std::nullopt)); EXPECT_CALL(*dispatcher_, CreateQuicSession(conn_id, _, client_addr_, Eq(ExpectedAlpn()), _, MatchParsedClientHello(), _)) .WillOnce(Return(ByMove(CreateSession( dispatcher_.get(), config_, conn_id, client_addr_, &mock_helper_, &mock_alarm_factory_, &crypto_config_, QuicDispatcherPeer::GetCache(dispatcher_.get()), &session1_)))); bool got_ect1 = false; bool got_ce = false; EXPECT_CALL(*reinterpret_cast<MockQuicConnection*>(session1_->connection()), ProcessUdpPacket(_, _, _)) .Times(2) .WillRepeatedly(WithArg<2>(Invoke([&](const QuicReceivedPacket& packet) { switch (packet.ecn_codepoint()) { case ECN_ECT1: got_ect1 = true; break; case ECN_CE: got_ce = true; break; default: break; } }))); QuicConnectionId client_connection_id = TestConnectionId(2); std::vector<std::unique_ptr<QuicReceivedPacket>> packets = GetFirstFlightOfPackets(version_, DefaultQuicConfig(), conn_id, client_connection_id, TestClientCryptoConfig(), ECN_CE); for (auto&& packet : packets) { ProcessReceivedPacket(std::move(packet), client_addr_, version_, conn_id); } EXPECT_TRUE(got_ect1); EXPECT_TRUE(got_ce); } class DualCIDBufferedPacketStoreTest : public BufferedPacketStoreTest { protected: void SetUp() override { BufferedPacketStoreTest::SetUp(); QuicDispatcherPeer::set_new_sessions_allowed_per_event_loop( dispatcher_.get(), 0); expect_generator_is_called_ = false; EXPECT_CALL(connection_id_generator_, MaybeReplaceConnectionId(_, _)) .WillRepeatedly(Invoke( this, &DualCIDBufferedPacketStoreTest::ReplaceConnectionIdInTest)); } std::optional<QuicConnectionId> ReplaceConnectionIdInTest( const QuicConnectionId& original, const ParsedQuicVersion& version) { auto it = replaced_cid_map_.find(original); if (it == replaced_cid_map_.end()) { ADD_FAILURE() << "Bad test setup: no replacement CID for " << original << ", version " << version; return std::nullopt; } return it->second; } QuicBufferedPacketStore& store() { return *QuicDispatcherPeer::GetBufferedPackets(dispatcher_.get()); } using BufferedPacketList = QuicBufferedPacketStore::BufferedPacketList; const BufferedPacketList* FindBufferedPackets( QuicConnectionId connection_id) { return QuicBufferedPacketStorePeer::FindBufferedPackets(&store(), connection_id); } absl::flat_hash_map<QuicConnectionId, std::optional<QuicConnectionId>> replaced_cid_map_; private: using BufferedPacketStoreTest::expect_generator_is_called_; }; INSTANTIATE_TEST_SUITE_P(DualCIDBufferedPacketStoreTests, DualCIDBufferedPacketStoreTest, ::testing::ValuesIn(CurrentSupportedVersionsWithTls()), ::testing::PrintToStringParamName()); TEST_P(DualCIDBufferedPacketStoreTest, CanLookUpByBothCIDs) { replaced_cid_map_[TestConnectionId(1)] = TestConnectionId(2); ProcessFirstFlight(TestConnectionId(1)); ASSERT_TRUE(store().HasBufferedPackets(TestConnectionId(1))); ASSERT_TRUE(store().HasBufferedPackets(TestConnectionId(2))); const BufferedPacketList* packets1 = FindBufferedPackets(TestConnectionId(1)); const BufferedPacketList* packets2 = FindBufferedPackets(TestConnectionId(2)); EXPECT_EQ(packets1, packets2); EXPECT_EQ(packets1->original_connection_id, TestConnectionId(1)); EXPECT_EQ(packets1->replaced_connection_id, TestConnectionId(2)); } TEST_P(DualCIDBufferedPacketStoreTest, DeliverPacketsByOriginalCID) { replaced_cid_map_[TestConnectionId(1)] = TestConnectionId(2); ProcessFirstFlight(TestConnectionId(1)); ASSERT_TRUE(store().HasBufferedPackets(TestConnectionId(1))); ASSERT_TRUE(store().HasBufferedPackets(TestConnectionId(2))); ASSERT_TRUE(store().HasChloForConnection(TestConnectionId(1))); ASSERT_TRUE(store().HasChloForConnection(TestConnectionId(2))); ASSERT_TRUE(store().HasChlosBuffered()); BufferedPacketList packets = store().DeliverPackets(TestConnectionId(1)); EXPECT_EQ(packets.original_connection_id, TestConnectionId(1)); EXPECT_EQ(packets.replaced_connection_id, TestConnectionId(2)); EXPECT_FALSE(store().HasBufferedPackets(TestConnectionId(1))); EXPECT_FALSE(store().HasBufferedPackets(TestConnectionId(2))); EXPECT_FALSE(store().HasChloForConnection(TestConnectionId(1))); EXPECT_FALSE(store().HasChloForConnection(TestConnectionId(2))); EXPECT_FALSE(store().HasChlosBuffered()); } TEST_P(DualCIDBufferedPacketStoreTest, DeliverPacketsByReplacedCID) { replaced_cid_map_[TestConnectionId(1)] = TestConnectionId(2); replaced_cid_map_[TestConnectionId(3)] = TestConnectionId(4); ProcessFirstFlight(TestConnectionId(1)); ProcessFirstFlight(TestConnectionId(3)); ASSERT_TRUE(store().HasBufferedPackets(TestConnectionId(1))); ASSERT_TRUE(store().HasBufferedPackets(TestConnectionId(3))); ASSERT_TRUE(store().HasChloForConnection(TestConnectionId(1))); ASSERT_TRUE(store().HasChloForConnection(TestConnectionId(3))); ASSERT_TRUE(store().HasChlosBuffered()); BufferedPacketList packets2 = store().DeliverPackets(TestConnectionId(2)); EXPECT_EQ(packets2.original_connection_id, TestConnectionId(1)); EXPECT_EQ(packets2.replaced_connection_id, TestConnectionId(2)); EXPECT_FALSE(store().HasBufferedPackets(TestConnectionId(1))); EXPECT_FALSE(store().HasBufferedPackets(TestConnectionId(2))); EXPECT_TRUE(store().HasBufferedPackets(TestConnectionId(3))); EXPECT_TRUE(store().HasBufferedPackets(TestConnectionId(4))); EXPECT_FALSE(store().HasChloForConnection(TestConnectionId(1))); EXPECT_FALSE(store().HasChloForConnection(TestConnectionId(2))); EXPECT_TRUE(store().HasChloForConnection(TestConnectionId(3))); EXPECT_TRUE(store().HasChloForConnection(TestConnectionId(4))); EXPECT_TRUE(store().HasChlosBuffered()); BufferedPacketList packets4 = store().DeliverPackets(TestConnectionId(4)); EXPECT_EQ(packets4.original_connection_id, TestConnectionId(3)); EXPECT_EQ(packets4.replaced_connection_id, TestConnectionId(4)); EXPECT_FALSE(store().HasBufferedPackets(TestConnectionId(3))); EXPECT_FALSE(store().HasBufferedPackets(TestConnectionId(4))); EXPECT_FALSE(store().HasChloForConnection(TestConnectionId(3))); EXPECT_FALSE(store().HasChloForConnection(TestConnectionId(4))); EXPECT_FALSE(store().HasChlosBuffered()); } TEST_P(DualCIDBufferedPacketStoreTest, DiscardPacketsByOriginalCID) { replaced_cid_map_[TestConnectionId(1)] = TestConnectionId(2); ProcessFirstFlight(TestConnectionId(1)); ASSERT_TRUE(store().HasBufferedPackets(TestConnectionId(1))); store().DiscardPackets(TestConnectionId(1)); EXPECT_FALSE(store().HasBufferedPackets(TestConnectionId(1))); EXPECT_FALSE(store().HasBufferedPackets(TestConnectionId(2))); EXPECT_FALSE(store().HasChloForConnection(TestConnectionId(1))); EXPECT_FALSE(store().HasChloForConnection(TestConnectionId(2))); EXPECT_FALSE(store().HasChlosBuffered()); } TEST_P(DualCIDBufferedPacketStoreTest, DiscardPacketsByReplacedCID) { replaced_cid_map_[TestConnectionId(1)] = TestConnectionId(2); replaced_cid_map_[TestConnectionId(3)] = TestConnectionId(4); ProcessFirstFlight(TestConnectionId(1)); ProcessFirstFlight(TestConnectionId(3)); ASSERT_TRUE(store().HasBufferedPackets(TestConnectionId(2))); ASSERT_TRUE(store().HasBufferedPackets(TestConnectionId(4))); store().DiscardPackets(TestConnectionId(2)); EXPECT_FALSE(store().HasBufferedPackets(TestConnectionId(1))); EXPECT_FALSE(store().HasBufferedPackets(TestConnectionId(2))); EXPECT_TRUE(store().HasBufferedPackets(TestConnectionId(3))); EXPECT_TRUE(store().HasBufferedPackets(TestConnectionId(4))); EXPECT_FALSE(store().HasChloForConnection(TestConnectionId(1))); EXPECT_FALSE(store().HasChloForConnection(TestConnectionId(2))); EXPECT_TRUE(store().HasChloForConnection(TestConnectionId(3))); EXPECT_TRUE(store().HasChloForConnection(TestConnectionId(4))); EXPECT_TRUE(store().HasChlosBuffered()); store().DiscardPackets(TestConnectionId(4)); EXPECT_FALSE(store().HasBufferedPackets(TestConnectionId(3))); EXPECT_FALSE(store().HasBufferedPackets(TestConnectionId(4))); EXPECT_FALSE(store().HasChloForConnection(TestConnectionId(3))); EXPECT_FALSE(store().HasChloForConnection(TestConnectionId(4))); EXPECT_FALSE(store().HasChlosBuffered()); } TEST_P(DualCIDBufferedPacketStoreTest, CIDCollision) { replaced_cid_map_[TestConnectionId(1)] = TestConnectionId(2); replaced_cid_map_[TestConnectionId(3)] = TestConnectionId(2); ProcessFirstFlight(TestConnectionId(1)); ProcessFirstFlight(TestConnectionId(3)); ASSERT_TRUE(store().HasBufferedPackets(TestConnectionId(1))); ASSERT_TRUE(store().HasBufferedPackets(TestConnectionId(2))); ASSERT_FALSE(store().HasBufferedPackets(TestConnectionId(3))); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_dispatcher.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_dispatcher_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
e130505a-4fdf-4412-8ae6-7a6268b668b5
cpp
google/quiche
quic_versions
quiche/quic/core/quic_versions.cc
quiche/quic/core/quic_versions_test.cc
#include "quiche/quic/core/quic_versions.h" #include <algorithm> #include <ostream> #include <string> #include <vector> #include "absl/base/macros.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_split.h" #include "quiche/quic/core/crypto/quic_random.h" #include "quiche/quic/core/quic_tag.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" #include "quiche/common/quiche_endian.h" #include "quiche/common/quiche_text_utils.h" namespace quic { namespace { QuicVersionLabel CreateRandomVersionLabelForNegotiation() { QuicVersionLabel result; if (!GetQuicFlag(quic_disable_version_negotiation_grease_randomness)) { QuicRandom::GetInstance()->RandBytes(&result, sizeof(result)); } else { result = MakeVersionLabel(0xd1, 0x57, 0x38, 0x3f); } result &= 0xf0f0f0f0; result |= 0x0a0a0a0a; return result; } void SetVersionFlag(const ParsedQuicVersion& version, bool should_enable) { static_assert(SupportedVersions().size() == 4u, "Supported versions out of sync"); const bool enable = should_enable; const bool disable = !should_enable; if (version == ParsedQuicVersion::RFCv2()) { SetQuicReloadableFlag(quic_enable_version_rfcv2, enable); } else if (version == ParsedQuicVersion::RFCv1()) { SetQuicReloadableFlag(quic_disable_version_rfcv1, disable); } else if (version == ParsedQuicVersion::Draft29()) { SetQuicReloadableFlag(quic_disable_version_draft_29, disable); } else if (version == ParsedQuicVersion::Q046()) { SetQuicReloadableFlag(quic_disable_version_q046, disable); } else { QUIC_BUG(quic_bug_10589_1) << "Cannot " << (enable ? "en" : "dis") << "able version " << version; } } } bool ParsedQuicVersion::IsKnown() const { QUICHE_DCHECK(ParsedQuicVersionIsValid(handshake_protocol, transport_version)) << QuicVersionToString(transport_version) << " " << HandshakeProtocolToString(handshake_protocol); return transport_version != QUIC_VERSION_UNSUPPORTED; } bool ParsedQuicVersion::KnowsWhichDecrypterToUse() const { QUICHE_DCHECK(IsKnown()); return transport_version > QUIC_VERSION_46; } bool ParsedQuicVersion::UsesInitialObfuscators() const { QUICHE_DCHECK(IsKnown()); return transport_version > QUIC_VERSION_46; } bool ParsedQuicVersion::AllowsLowFlowControlLimits() const { QUICHE_DCHECK(IsKnown()); return UsesHttp3(); } bool ParsedQuicVersion::HasHeaderProtection() const { QUICHE_DCHECK(IsKnown()); return transport_version > QUIC_VERSION_46; } bool ParsedQuicVersion::SupportsRetry() const { QUICHE_DCHECK(IsKnown()); return transport_version > QUIC_VERSION_46; } bool ParsedQuicVersion::SendsVariableLengthPacketNumberInLongHeader() const { QUICHE_DCHECK(IsKnown()); return transport_version > QUIC_VERSION_46; } bool ParsedQuicVersion::AllowsVariableLengthConnectionIds() const { QUICHE_DCHECK(IsKnown()); return VersionAllowsVariableLengthConnectionIds(transport_version); } bool ParsedQuicVersion::SupportsClientConnectionIds() const { QUICHE_DCHECK(IsKnown()); return transport_version > QUIC_VERSION_46; } bool ParsedQuicVersion::HasLengthPrefixedConnectionIds() const { QUICHE_DCHECK(IsKnown()); return VersionHasLengthPrefixedConnectionIds(transport_version); } bool ParsedQuicVersion::SupportsAntiAmplificationLimit() const { QUICHE_DCHECK(IsKnown()); return UsesHttp3(); } bool ParsedQuicVersion::CanSendCoalescedPackets() const { QUICHE_DCHECK(IsKnown()); return HasLongHeaderLengths() && UsesTls(); } bool ParsedQuicVersion::SupportsGoogleAltSvcFormat() const { QUICHE_DCHECK(IsKnown()); return VersionSupportsGoogleAltSvcFormat(transport_version); } bool ParsedQuicVersion::UsesHttp3() const { QUICHE_DCHECK(IsKnown()); return VersionUsesHttp3(transport_version); } bool ParsedQuicVersion::HasLongHeaderLengths() const { QUICHE_DCHECK(IsKnown()); return QuicVersionHasLongHeaderLengths(transport_version); } bool ParsedQuicVersion::UsesCryptoFrames() const { QUICHE_DCHECK(IsKnown()); return QuicVersionUsesCryptoFrames(transport_version); } bool ParsedQuicVersion::HasIetfQuicFrames() const { QUICHE_DCHECK(IsKnown()); return VersionHasIetfQuicFrames(transport_version); } bool ParsedQuicVersion::UsesLegacyTlsExtension() const { QUICHE_DCHECK(IsKnown()); return UsesTls() && transport_version <= QUIC_VERSION_IETF_DRAFT_29; } bool ParsedQuicVersion::UsesTls() const { QUICHE_DCHECK(IsKnown()); return handshake_protocol == PROTOCOL_TLS1_3; } bool ParsedQuicVersion::UsesQuicCrypto() const { QUICHE_DCHECK(IsKnown()); return handshake_protocol == PROTOCOL_QUIC_CRYPTO; } bool ParsedQuicVersion::UsesV2PacketTypes() const { QUICHE_DCHECK(IsKnown()); return transport_version == QUIC_VERSION_IETF_RFC_V2; } bool ParsedQuicVersion::AlpnDeferToRFCv1() const { QUICHE_DCHECK(IsKnown()); return transport_version == QUIC_VERSION_IETF_RFC_V2; } bool VersionHasLengthPrefixedConnectionIds( QuicTransportVersion transport_version) { QUICHE_DCHECK(transport_version != QUIC_VERSION_UNSUPPORTED); return transport_version > QUIC_VERSION_46; } std::ostream& operator<<(std::ostream& os, const ParsedQuicVersion& version) { os << ParsedQuicVersionToString(version); return os; } std::ostream& operator<<(std::ostream& os, const ParsedQuicVersionVector& versions) { os << ParsedQuicVersionVectorToString(versions); return os; } QuicVersionLabel MakeVersionLabel(uint8_t a, uint8_t b, uint8_t c, uint8_t d) { return MakeQuicTag(d, c, b, a); } std::ostream& operator<<(std::ostream& os, const QuicVersionLabelVector& version_labels) { os << QuicVersionLabelVectorToString(version_labels); return os; } std::ostream& operator<<(std::ostream& os, const QuicTransportVersionVector& transport_versions) { os << QuicTransportVersionVectorToString(transport_versions); return os; } QuicVersionLabel CreateQuicVersionLabel(ParsedQuicVersion parsed_version) { static_assert(SupportedVersions().size() == 4u, "Supported versions out of sync"); if (parsed_version == ParsedQuicVersion::RFCv2()) { return MakeVersionLabel(0x6b, 0x33, 0x43, 0xcf); } else if (parsed_version == ParsedQuicVersion::RFCv1()) { return MakeVersionLabel(0x00, 0x00, 0x00, 0x01); } else if (parsed_version == ParsedQuicVersion::Draft29()) { return MakeVersionLabel(0xff, 0x00, 0x00, 29); } else if (parsed_version == ParsedQuicVersion::Q046()) { return MakeVersionLabel('Q', '0', '4', '6'); } else if (parsed_version == ParsedQuicVersion::ReservedForNegotiation()) { return CreateRandomVersionLabelForNegotiation(); } QUIC_BUG(quic_bug_10589_2) << "Unsupported version " << QuicVersionToString(parsed_version.transport_version) << " " << HandshakeProtocolToString(parsed_version.handshake_protocol); return 0; } QuicVersionLabelVector CreateQuicVersionLabelVector( const ParsedQuicVersionVector& versions) { QuicVersionLabelVector out; out.reserve(versions.size()); for (const auto& version : versions) { out.push_back(CreateQuicVersionLabel(version)); } return out; } ParsedQuicVersionVector AllSupportedVersionsWithQuicCrypto() { ParsedQuicVersionVector versions; for (const ParsedQuicVersion& version : AllSupportedVersions()) { if (version.handshake_protocol == PROTOCOL_QUIC_CRYPTO) { versions.push_back(version); } } QUIC_BUG_IF(quic_bug_10589_3, versions.empty()) << "No version with QUIC crypto found."; return versions; } ParsedQuicVersionVector CurrentSupportedVersionsWithQuicCrypto() { ParsedQuicVersionVector versions; for (const ParsedQuicVersion& version : CurrentSupportedVersions()) { if (version.handshake_protocol == PROTOCOL_QUIC_CRYPTO) { versions.push_back(version); } } QUIC_BUG_IF(quic_bug_10589_4, versions.empty()) << "No version with QUIC crypto found."; return versions; } ParsedQuicVersionVector AllSupportedVersionsWithTls() { ParsedQuicVersionVector versions; for (const ParsedQuicVersion& version : AllSupportedVersions()) { if (version.UsesTls()) { versions.push_back(version); } } QUIC_BUG_IF(quic_bug_10589_5, versions.empty()) << "No version with TLS handshake found."; return versions; } ParsedQuicVersionVector CurrentSupportedVersionsWithTls() { ParsedQuicVersionVector versions; for (const ParsedQuicVersion& version : CurrentSupportedVersions()) { if (version.UsesTls()) { versions.push_back(version); } } QUIC_BUG_IF(quic_bug_10589_6, versions.empty()) << "No version with TLS handshake found."; return versions; } ParsedQuicVersionVector ObsoleteSupportedVersions() { return ParsedQuicVersionVector{quic::ParsedQuicVersion::Q046(), quic::ParsedQuicVersion::Draft29()}; } bool IsObsoleteSupportedVersion(ParsedQuicVersion version) { static const ParsedQuicVersionVector obsolete_versions = ObsoleteSupportedVersions(); for (const ParsedQuicVersion& obsolete_version : obsolete_versions) { if (version == obsolete_version) { return true; } } return false; } ParsedQuicVersionVector CurrentSupportedVersionsForClients() { ParsedQuicVersionVector versions; for (const ParsedQuicVersion& version : CurrentSupportedVersionsWithTls()) { QUICHE_DCHECK_EQ(version.handshake_protocol, PROTOCOL_TLS1_3); if (version.transport_version >= QUIC_VERSION_IETF_RFC_V1) { versions.push_back(version); } } QUIC_BUG_IF(quic_bug_10589_8, versions.empty()) << "No supported client versions found."; return versions; } ParsedQuicVersionVector CurrentSupportedHttp3Versions() { ParsedQuicVersionVector versions; for (const ParsedQuicVersion& version : CurrentSupportedVersions()) { if (version.UsesHttp3()) { versions.push_back(version); } } QUIC_BUG_IF(no_version_uses_http3, versions.empty()) << "No version speaking Http3 found."; return versions; } ParsedQuicVersion ParseQuicVersionLabel(QuicVersionLabel version_label) { for (const ParsedQuicVersion& version : AllSupportedVersions()) { if (version_label == CreateQuicVersionLabel(version)) { return version; } } QUIC_DLOG(INFO) << "Unsupported QuicVersionLabel version: " << QuicVersionLabelToString(version_label); return UnsupportedQuicVersion(); } ParsedQuicVersionVector ParseQuicVersionLabelVector( const QuicVersionLabelVector& version_labels) { ParsedQuicVersionVector parsed_versions; for (const QuicVersionLabel& version_label : version_labels) { ParsedQuicVersion parsed_version = ParseQuicVersionLabel(version_label); if (parsed_version.IsKnown()) { parsed_versions.push_back(parsed_version); } } return parsed_versions; } ParsedQuicVersion ParseQuicVersionString(absl::string_view version_string) { if (version_string.empty()) { return UnsupportedQuicVersion(); } const ParsedQuicVersionVector supported_versions = AllSupportedVersions(); for (const ParsedQuicVersion& version : supported_versions) { if (version_string == ParsedQuicVersionToString(version) || (version_string == AlpnForVersion(version) && !version.AlpnDeferToRFCv1()) || (version.handshake_protocol == PROTOCOL_QUIC_CRYPTO && version_string == QuicVersionToString(version.transport_version))) { return version; } } for (const ParsedQuicVersion& version : supported_versions) { if (version.UsesHttp3() && version_string == QuicVersionLabelToString(CreateQuicVersionLabel(version))) { return version; } } int quic_version_number = 0; if (absl::SimpleAtoi(version_string, &quic_version_number) && quic_version_number > 0) { QuicTransportVersion transport_version = static_cast<QuicTransportVersion>(quic_version_number); if (!ParsedQuicVersionIsValid(PROTOCOL_QUIC_CRYPTO, transport_version)) { return UnsupportedQuicVersion(); } ParsedQuicVersion version(PROTOCOL_QUIC_CRYPTO, transport_version); if (std::find(supported_versions.begin(), supported_versions.end(), version) != supported_versions.end()) { return version; } return UnsupportedQuicVersion(); } QUIC_DLOG(INFO) << "Unsupported QUIC version string: \"" << version_string << "\"."; return UnsupportedQuicVersion(); } ParsedQuicVersionVector ParseQuicVersionVectorString( absl::string_view versions_string) { ParsedQuicVersionVector versions; std::vector<absl::string_view> version_strings = absl::StrSplit(versions_string, ','); for (absl::string_view version_string : version_strings) { quiche::QuicheTextUtils::RemoveLeadingAndTrailingWhitespace( &version_string); ParsedQuicVersion version = ParseQuicVersionString(version_string); if (!version.IsKnown() || std::find(versions.begin(), versions.end(), version) != versions.end()) { continue; } versions.push_back(version); } return versions; } QuicTransportVersionVector AllSupportedTransportVersions() { QuicTransportVersionVector transport_versions; for (const ParsedQuicVersion& version : AllSupportedVersions()) { if (std::find(transport_versions.begin(), transport_versions.end(), version.transport_version) == transport_versions.end()) { transport_versions.push_back(version.transport_version); } } return transport_versions; } ParsedQuicVersionVector AllSupportedVersions() { constexpr auto supported_versions = SupportedVersions(); return ParsedQuicVersionVector(supported_versions.begin(), supported_versions.end()); } ParsedQuicVersionVector CurrentSupportedVersions() { return FilterSupportedVersions(AllSupportedVersions()); } ParsedQuicVersionVector FilterSupportedVersions( ParsedQuicVersionVector versions) { static_assert(SupportedVersions().size() == 4u, "Supported versions out of sync"); ParsedQuicVersionVector filtered_versions; filtered_versions.reserve(versions.size()); for (const ParsedQuicVersion& version : versions) { if (version == ParsedQuicVersion::RFCv2()) { if (GetQuicReloadableFlag(quic_enable_version_rfcv2)) { filtered_versions.push_back(version); } } else if (version == ParsedQuicVersion::RFCv1()) { if (!GetQuicReloadableFlag(quic_disable_version_rfcv1)) { filtered_versions.push_back(version); } } else if (version == ParsedQuicVersion::Draft29()) { if (!GetQuicReloadableFlag(quic_disable_version_draft_29)) { filtered_versions.push_back(version); } } else if (version == ParsedQuicVersion::Q046()) { if (!GetQuicReloadableFlag(quic_disable_version_q046)) { filtered_versions.push_back(version); } } else { QUIC_BUG(quic_bug_10589_7) << "QUIC version " << version << " has no flag protection"; filtered_versions.push_back(version); } } return filtered_versions; } ParsedQuicVersionVector ParsedVersionOfIndex( const ParsedQuicVersionVector& versions, int index) { ParsedQuicVersionVector version; int version_count = versions.size(); if (index >= 0 && index < version_count) { version.push_back(versions[index]); } else { version.push_back(UnsupportedQuicVersion()); } return version; } std::string QuicVersionLabelToString(QuicVersionLabel version_label) { return QuicTagToString(quiche::QuicheEndian::HostToNet32(version_label)); } ParsedQuicVersion ParseQuicVersionLabelString( absl::string_view version_label_string) { const ParsedQuicVersionVector supported_versions = AllSupportedVersions(); for (const ParsedQuicVersion& version : supported_versions) { if (version_label_string == QuicVersionLabelToString(CreateQuicVersionLabel(version))) { return version; } } return UnsupportedQuicVersion(); } std::string QuicVersionLabelVectorToString( const QuicVersionLabelVector& version_labels, const std::string& separator, size_t skip_after_nth_version) { std::string result; for (size_t i = 0; i < version_labels.size(); ++i) { if (i != 0) { result.append(separator); } if (i > skip_after_nth_version) { result.append("..."); break; } result.append(QuicVersionLabelToString(version_labels[i])); } return result; } #define RETURN_STRING_LITERAL(x) \ case x: \ return #x std::string QuicVersionToString(QuicTransportVersion transport_version) { switch (transport_version) { RETURN_STRING_LITERAL(QUIC_VERSION_46); RETURN_STRING_LITERAL(QUIC_VERSION_IETF_DRAFT_29); RETURN_STRING_LITERAL(QUIC_VERSION_IETF_RFC_V1); RETURN_STRING_LITERAL(QUIC_VERSION_IETF_RFC_V2); RETURN_STRING_LITERAL(QUIC_VERSION_UNSUPPORTED); RETURN_STRING_LITERAL(QUIC_VERSION_RESERVED_FOR_NEGOTIATION); } return absl::StrCat("QUIC_VERSION_UNKNOWN(", static_cast<int>(transport_version), ")"); } std::string HandshakeProtocolToString(HandshakeProtocol handshake_protocol) { switch (handshake_protocol) { RETURN_STRING_LITERAL(PROTOCOL_UNSUPPORTED); RETURN_STRING_LITERAL(PROTOCOL_QUIC_CRYPTO); RETURN_STRING_LITERAL(PROTOCOL_TLS1_3); } return absl::StrCat("PROTOCOL_UNKNOWN(", static_cast<int>(handshake_protocol), ")"); } std::string ParsedQuicVersionToString(ParsedQuicVersion version) { static_assert(SupportedVersions().size() == 4u, "Supported versions out of sync"); if (version == UnsupportedQuicVersion()) { return "0"; } else if (version == ParsedQuicVersion::RFCv2()) { QUICHE_DCHECK(version.UsesHttp3()); return "RFCv2"; } else if (version == ParsedQuicVersion::RFCv1()) { QUICHE_DCHECK(version.UsesHttp3()); return "RFCv1"; } else if (version == ParsedQuicVersion::Draft29()) { QUICHE_DCHECK(version.UsesHttp3()); return "draft29"; } return QuicVersionLabelToString(CreateQuicVersionLabel(version)); } std::string QuicTransportVersionVectorToString( const QuicTransportVersionVector& versions) { std::string result = ""; for (size_t i = 0; i < versions.size(); ++i) { if (i != 0) { result.append(","); } result.append(QuicVersionToString(versions[i])); } return result; } std::string ParsedQuicVersionVectorToString( const ParsedQuicVersionVector& versions, const std::string& separator, size_t skip_after_nth_version) { std::string result; for (size_t i = 0; i < versions.size(); ++i) { if (i != 0) { result.append(separator); } if (i > skip_after_nth_version) { result.append("..."); break; } result.append(ParsedQuicVersionToString(versions[i])); } return result; } bool VersionSupportsGoogleAltSvcFormat(QuicTransportVersion transport_version) { return transport_version <= QUIC_VERSION_46; } bool VersionAllowsVariableLengthConnectionIds( QuicTransportVersion transport_version) { QUICHE_DCHECK_NE(transport_version, QUIC_VERSION_UNSUPPORTED); return transport_version > QUIC_VERSION_46; } bool QuicVersionLabelUses4BitConnectionIdLength( QuicVersionLabel version_label) { for (uint8_t c = '3'; c <= '8'; ++c) { if (version_label == MakeVersionLabel('Q', '0', '4', c)) { return true; } } if (version_label == MakeVersionLabel('T', '0', '4', '8')) { return true; } for (uint8_t draft_number = 11; draft_number <= 21; ++draft_number) { if (version_label == MakeVersionLabel(0xff, 0x00, 0x00, draft_number)) { return true; } } return false; } ParsedQuicVersion UnsupportedQuicVersion() { return ParsedQuicVersion::Unsupported(); } ParsedQuicVersion QuicVersionReservedForNegotiation() { return ParsedQuicVersion::ReservedForNegotiation(); } std::string AlpnForVersion(ParsedQuicVersion parsed_version) { if (parsed_version == ParsedQuicVersion::RFCv2()) { return "h3"; } else if (parsed_version == ParsedQuicVersion::RFCv1()) { return "h3"; } else if (parsed_version == ParsedQuicVersion::Draft29()) { return "h3-29"; } return "h3-" + ParsedQuicVersionToString(parsed_version); } void QuicEnableVersion(const ParsedQuicVersion& version) { SetVersionFlag(version, true); } void QuicDisableVersion(const ParsedQuicVersion& version) { SetVersionFlag(version, false); } bool QuicVersionIsEnabled(const ParsedQuicVersion& version) { ParsedQuicVersionVector current = CurrentSupportedVersions(); return std::find(current.begin(), current.end(), version) != current.end(); } #undef RETURN_STRING_LITERAL }
#include "quiche/quic/core/quic_versions.h" #include <cstddef> #include <sstream> #include "absl/algorithm/container.h" #include "absl/base/macros.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" namespace quic { namespace test { namespace { using ::testing::ElementsAre; using ::testing::IsEmpty; TEST(QuicVersionsTest, CreateQuicVersionLabelUnsupported) { EXPECT_QUIC_BUG( CreateQuicVersionLabel(UnsupportedQuicVersion()), "Unsupported version QUIC_VERSION_UNSUPPORTED PROTOCOL_UNSUPPORTED"); } TEST(QuicVersionsTest, KnownAndValid) { for (const ParsedQuicVersion& version : AllSupportedVersions()) { EXPECT_TRUE(version.IsKnown()); EXPECT_TRUE(ParsedQuicVersionIsValid(version.handshake_protocol, version.transport_version)); } ParsedQuicVersion unsupported = UnsupportedQuicVersion(); EXPECT_FALSE(unsupported.IsKnown()); EXPECT_TRUE(ParsedQuicVersionIsValid(unsupported.handshake_protocol, unsupported.transport_version)); ParsedQuicVersion reserved = QuicVersionReservedForNegotiation(); EXPECT_TRUE(reserved.IsKnown()); EXPECT_TRUE(ParsedQuicVersionIsValid(reserved.handshake_protocol, reserved.transport_version)); EXPECT_FALSE(ParsedQuicVersionIsValid(PROTOCOL_TLS1_3, QUIC_VERSION_46)); EXPECT_FALSE(ParsedQuicVersionIsValid(PROTOCOL_QUIC_CRYPTO, QUIC_VERSION_IETF_DRAFT_29)); EXPECT_FALSE(ParsedQuicVersionIsValid(PROTOCOL_QUIC_CRYPTO, static_cast<QuicTransportVersion>(33))); EXPECT_FALSE(ParsedQuicVersionIsValid(PROTOCOL_QUIC_CRYPTO, static_cast<QuicTransportVersion>(99))); EXPECT_FALSE(ParsedQuicVersionIsValid(PROTOCOL_TLS1_3, static_cast<QuicTransportVersion>(99))); } TEST(QuicVersionsTest, Features) { ParsedQuicVersion parsed_version_q046 = ParsedQuicVersion::Q046(); ParsedQuicVersion parsed_version_draft_29 = ParsedQuicVersion::Draft29(); EXPECT_TRUE(parsed_version_q046.IsKnown()); EXPECT_FALSE(parsed_version_q046.KnowsWhichDecrypterToUse()); EXPECT_FALSE(parsed_version_q046.UsesInitialObfuscators()); EXPECT_FALSE(parsed_version_q046.AllowsLowFlowControlLimits()); EXPECT_FALSE(parsed_version_q046.HasHeaderProtection()); EXPECT_FALSE(parsed_version_q046.SupportsRetry()); EXPECT_FALSE( parsed_version_q046.SendsVariableLengthPacketNumberInLongHeader()); EXPECT_FALSE(parsed_version_q046.AllowsVariableLengthConnectionIds()); EXPECT_FALSE(parsed_version_q046.SupportsClientConnectionIds()); EXPECT_FALSE(parsed_version_q046.HasLengthPrefixedConnectionIds()); EXPECT_FALSE(parsed_version_q046.SupportsAntiAmplificationLimit()); EXPECT_FALSE(parsed_version_q046.CanSendCoalescedPackets()); EXPECT_TRUE(parsed_version_q046.SupportsGoogleAltSvcFormat()); EXPECT_FALSE(parsed_version_q046.UsesHttp3()); EXPECT_FALSE(parsed_version_q046.HasLongHeaderLengths()); EXPECT_FALSE(parsed_version_q046.UsesCryptoFrames()); EXPECT_FALSE(parsed_version_q046.HasIetfQuicFrames()); EXPECT_FALSE(parsed_version_q046.UsesTls()); EXPECT_TRUE(parsed_version_q046.UsesQuicCrypto()); EXPECT_TRUE(parsed_version_draft_29.IsKnown()); EXPECT_TRUE(parsed_version_draft_29.KnowsWhichDecrypterToUse()); EXPECT_TRUE(parsed_version_draft_29.UsesInitialObfuscators()); EXPECT_TRUE(parsed_version_draft_29.AllowsLowFlowControlLimits()); EXPECT_TRUE(parsed_version_draft_29.HasHeaderProtection()); EXPECT_TRUE(parsed_version_draft_29.SupportsRetry()); EXPECT_TRUE( parsed_version_draft_29.SendsVariableLengthPacketNumberInLongHeader()); EXPECT_TRUE(parsed_version_draft_29.AllowsVariableLengthConnectionIds()); EXPECT_TRUE(parsed_version_draft_29.SupportsClientConnectionIds()); EXPECT_TRUE(parsed_version_draft_29.HasLengthPrefixedConnectionIds()); EXPECT_TRUE(parsed_version_draft_29.SupportsAntiAmplificationLimit()); EXPECT_TRUE(parsed_version_draft_29.CanSendCoalescedPackets()); EXPECT_FALSE(parsed_version_draft_29.SupportsGoogleAltSvcFormat()); EXPECT_TRUE(parsed_version_draft_29.UsesHttp3()); EXPECT_TRUE(parsed_version_draft_29.HasLongHeaderLengths()); EXPECT_TRUE(parsed_version_draft_29.UsesCryptoFrames()); EXPECT_TRUE(parsed_version_draft_29.HasIetfQuicFrames()); EXPECT_TRUE(parsed_version_draft_29.UsesTls()); EXPECT_FALSE(parsed_version_draft_29.UsesQuicCrypto()); } TEST(QuicVersionsTest, ParseQuicVersionLabel) { static_assert(SupportedVersions().size() == 4u, "Supported versions out of sync"); EXPECT_EQ(ParsedQuicVersion::Q046(), ParseQuicVersionLabel(MakeVersionLabel('Q', '0', '4', '6'))); EXPECT_EQ(ParsedQuicVersion::Draft29(), ParseQuicVersionLabel(MakeVersionLabel(0xff, 0x00, 0x00, 0x1d))); EXPECT_EQ(ParsedQuicVersion::RFCv1(), ParseQuicVersionLabel(MakeVersionLabel(0x00, 0x00, 0x00, 0x01))); EXPECT_EQ(ParsedQuicVersion::RFCv2(), ParseQuicVersionLabel(MakeVersionLabel(0x6b, 0x33, 0x43, 0xcf))); EXPECT_EQ((ParsedQuicVersionVector{ParsedQuicVersion::RFCv2(), ParsedQuicVersion::RFCv1(), ParsedQuicVersion::Draft29()}), ParseQuicVersionLabelVector(QuicVersionLabelVector{ MakeVersionLabel(0x6b, 0x33, 0x43, 0xcf), MakeVersionLabel(0x00, 0x00, 0x00, 0x01), MakeVersionLabel(0xaa, 0xaa, 0xaa, 0xaa), MakeVersionLabel(0xff, 0x00, 0x00, 0x1d)})); for (const ParsedQuicVersion& version : AllSupportedVersions()) { EXPECT_EQ(version, ParseQuicVersionLabel(CreateQuicVersionLabel(version))); } } TEST(QuicVersionsTest, ParseQuicVersionString) { static_assert(SupportedVersions().size() == 4u, "Supported versions out of sync"); EXPECT_EQ(ParsedQuicVersion::Q046(), ParseQuicVersionString("QUIC_VERSION_46")); EXPECT_EQ(ParsedQuicVersion::Q046(), ParseQuicVersionString("46")); EXPECT_EQ(ParsedQuicVersion::Q046(), ParseQuicVersionString("Q046")); EXPECT_EQ(UnsupportedQuicVersion(), ParseQuicVersionString("")); EXPECT_EQ(UnsupportedQuicVersion(), ParseQuicVersionString("Q 46")); EXPECT_EQ(UnsupportedQuicVersion(), ParseQuicVersionString("Q046 ")); EXPECT_EQ(UnsupportedQuicVersion(), ParseQuicVersionString("99")); EXPECT_EQ(UnsupportedQuicVersion(), ParseQuicVersionString("70")); EXPECT_EQ(ParsedQuicVersion::Draft29(), ParseQuicVersionString("ff00001d")); EXPECT_EQ(ParsedQuicVersion::Draft29(), ParseQuicVersionString("draft29")); EXPECT_EQ(ParsedQuicVersion::Draft29(), ParseQuicVersionString("h3-29")); EXPECT_EQ(ParsedQuicVersion::RFCv1(), ParseQuicVersionString("00000001")); EXPECT_EQ(ParsedQuicVersion::RFCv1(), ParseQuicVersionString("h3")); for (const ParsedQuicVersion& version : AllSupportedVersions()) { EXPECT_EQ(version, ParseQuicVersionString(ParsedQuicVersionToString(version))); EXPECT_EQ(version, ParseQuicVersionString(QuicVersionLabelToString( CreateQuicVersionLabel(version)))); if (!version.AlpnDeferToRFCv1()) { EXPECT_EQ(version, ParseQuicVersionString(AlpnForVersion(version))); } } } TEST(QuicVersionsTest, ParseQuicVersionVectorString) { ParsedQuicVersion version_q046 = ParsedQuicVersion::Q046(); ParsedQuicVersion version_draft_29 = ParsedQuicVersion::Draft29(); EXPECT_THAT(ParseQuicVersionVectorString(""), IsEmpty()); EXPECT_THAT(ParseQuicVersionVectorString("QUIC_VERSION_46"), ElementsAre(version_q046)); EXPECT_THAT(ParseQuicVersionVectorString("h3-Q046"), ElementsAre(version_q046)); EXPECT_THAT(ParseQuicVersionVectorString("h3-Q046, h3-29"), ElementsAre(version_q046, version_draft_29)); EXPECT_THAT(ParseQuicVersionVectorString("h3-29,h3-Q046,h3-29"), ElementsAre(version_draft_29, version_q046)); EXPECT_THAT(ParseQuicVersionVectorString("h3-29, h3-Q046"), ElementsAre(version_draft_29, version_q046)); EXPECT_THAT(ParseQuicVersionVectorString("QUIC_VERSION_46,h3-29"), ElementsAre(version_q046, version_draft_29)); EXPECT_THAT(ParseQuicVersionVectorString("h3-29,QUIC_VERSION_46"), ElementsAre(version_draft_29, version_q046)); EXPECT_THAT(ParseQuicVersionVectorString("QUIC_VERSION_46, h3-29"), ElementsAre(version_q046, version_draft_29)); EXPECT_THAT(ParseQuicVersionVectorString("h3-29, QUIC_VERSION_46"), ElementsAre(version_draft_29, version_q046)); EXPECT_THAT(ParseQuicVersionVectorString("h3-29,QUIC_VERSION_46"), ElementsAre(version_draft_29, version_q046)); EXPECT_THAT(ParseQuicVersionVectorString("QUIC_VERSION_46,h3-29"), ElementsAre(version_q046, version_draft_29)); EXPECT_THAT(ParseQuicVersionVectorString("QUIC_VERSION_46, QUIC_VERSION_46"), ElementsAre(version_q046)); EXPECT_THAT(ParseQuicVersionVectorString("h3-Q046, h3-Q046"), ElementsAre(version_q046)); EXPECT_THAT(ParseQuicVersionVectorString("h3-Q046, QUIC_VERSION_46"), ElementsAre(version_q046)); EXPECT_THAT(ParseQuicVersionVectorString( "QUIC_VERSION_46, h3-Q046, QUIC_VERSION_46, h3-Q046"), ElementsAre(version_q046)); EXPECT_THAT(ParseQuicVersionVectorString("QUIC_VERSION_46, h3-29, h3-Q046"), ElementsAre(version_q046, version_draft_29)); EXPECT_THAT(ParseQuicVersionVectorString("99"), IsEmpty()); EXPECT_THAT(ParseQuicVersionVectorString("70"), IsEmpty()); EXPECT_THAT(ParseQuicVersionVectorString("h3-01"), IsEmpty()); EXPECT_THAT(ParseQuicVersionVectorString("h3-01,h3-29"), ElementsAre(version_draft_29)); } TEST(QuicVersionsTest, CreateQuicVersionLabel) { static_assert(SupportedVersions().size() == 4u, "Supported versions out of sync"); EXPECT_EQ(0x51303436u, CreateQuicVersionLabel(ParsedQuicVersion::Q046())); EXPECT_EQ(0xff00001du, CreateQuicVersionLabel(ParsedQuicVersion::Draft29())); EXPECT_EQ(0x00000001u, CreateQuicVersionLabel(ParsedQuicVersion::RFCv1())); EXPECT_EQ(0x6b3343cfu, CreateQuicVersionLabel(ParsedQuicVersion::RFCv2())); EXPECT_EQ( 0xda5a3a3au & 0x0f0f0f0f, CreateQuicVersionLabel(ParsedQuicVersion::ReservedForNegotiation()) & 0x0f0f0f0f); SetQuicFlag(quic_disable_version_negotiation_grease_randomness, true); EXPECT_EQ(0xda5a3a3au, CreateQuicVersionLabel( ParsedQuicVersion::ReservedForNegotiation())); } TEST(QuicVersionsTest, QuicVersionLabelToString) { static_assert(SupportedVersions().size() == 4u, "Supported versions out of sync"); EXPECT_EQ("Q046", QuicVersionLabelToString( CreateQuicVersionLabel(ParsedQuicVersion::Q046()))); EXPECT_EQ("ff00001d", QuicVersionLabelToString(CreateQuicVersionLabel( ParsedQuicVersion::Draft29()))); EXPECT_EQ("00000001", QuicVersionLabelToString(CreateQuicVersionLabel( ParsedQuicVersion::RFCv1()))); EXPECT_EQ("6b3343cf", QuicVersionLabelToString(CreateQuicVersionLabel( ParsedQuicVersion::RFCv2()))); QuicVersionLabelVector version_labels = { MakeVersionLabel('Q', '0', '3', '5'), MakeVersionLabel('T', '0', '3', '8'), MakeVersionLabel(0xff, 0, 0, 7), }; EXPECT_EQ("Q035", QuicVersionLabelToString(version_labels[0])); EXPECT_EQ("T038", QuicVersionLabelToString(version_labels[1])); EXPECT_EQ("ff000007", QuicVersionLabelToString(version_labels[2])); EXPECT_EQ("Q035,T038,ff000007", QuicVersionLabelVectorToString(version_labels)); EXPECT_EQ("Q035:T038:ff000007", QuicVersionLabelVectorToString(version_labels, ":", 2)); EXPECT_EQ("Q035|T038|...", QuicVersionLabelVectorToString(version_labels, "|", 1)); std::ostringstream os; os << version_labels; EXPECT_EQ("Q035,T038,ff000007", os.str()); } TEST(QuicVersionsTest, ParseQuicVersionLabelString) { static_assert(SupportedVersions().size() == 4u, "Supported versions out of sync"); EXPECT_EQ(ParsedQuicVersion::Q046(), ParseQuicVersionLabelString("Q046")); EXPECT_EQ(ParsedQuicVersion::Draft29(), ParseQuicVersionLabelString("ff00001d")); EXPECT_EQ(ParsedQuicVersion::RFCv1(), ParseQuicVersionLabelString("00000001")); EXPECT_EQ(ParsedQuicVersion::RFCv2(), ParseQuicVersionLabelString("6b3343cf")); EXPECT_EQ(UnsupportedQuicVersion(), ParseQuicVersionLabelString("1")); EXPECT_EQ(UnsupportedQuicVersion(), ParseQuicVersionLabelString("46")); EXPECT_EQ(UnsupportedQuicVersion(), ParseQuicVersionLabelString("QUIC_VERSION_46")); EXPECT_EQ(UnsupportedQuicVersion(), ParseQuicVersionLabelString("h3")); EXPECT_EQ(UnsupportedQuicVersion(), ParseQuicVersionLabelString("h3-29")); for (const ParsedQuicVersion& version : AllSupportedVersions()) { EXPECT_EQ(version, ParseQuicVersionLabelString(QuicVersionLabelToString( CreateQuicVersionLabel(version)))); } } TEST(QuicVersionsTest, QuicVersionToString) { EXPECT_EQ("QUIC_VERSION_UNSUPPORTED", QuicVersionToString(QUIC_VERSION_UNSUPPORTED)); QuicTransportVersion single_version[] = {QUIC_VERSION_46}; QuicTransportVersionVector versions_vector; for (size_t i = 0; i < ABSL_ARRAYSIZE(single_version); ++i) { versions_vector.push_back(single_version[i]); } EXPECT_EQ("QUIC_VERSION_46", QuicTransportVersionVectorToString(versions_vector)); QuicTransportVersion multiple_versions[] = {QUIC_VERSION_UNSUPPORTED, QUIC_VERSION_46}; versions_vector.clear(); for (size_t i = 0; i < ABSL_ARRAYSIZE(multiple_versions); ++i) { versions_vector.push_back(multiple_versions[i]); } EXPECT_EQ("QUIC_VERSION_UNSUPPORTED,QUIC_VERSION_46", QuicTransportVersionVectorToString(versions_vector)); for (const ParsedQuicVersion& version : AllSupportedVersions()) { EXPECT_NE("QUIC_VERSION_UNSUPPORTED", QuicVersionToString(version.transport_version)); } std::ostringstream os; os << versions_vector; EXPECT_EQ("QUIC_VERSION_UNSUPPORTED,QUIC_VERSION_46", os.str()); } TEST(QuicVersionsTest, ParsedQuicVersionToString) { EXPECT_EQ("0", ParsedQuicVersionToString(ParsedQuicVersion::Unsupported())); EXPECT_EQ("Q046", ParsedQuicVersionToString(ParsedQuicVersion::Q046())); EXPECT_EQ("draft29", ParsedQuicVersionToString(ParsedQuicVersion::Draft29())); EXPECT_EQ("RFCv1", ParsedQuicVersionToString(ParsedQuicVersion::RFCv1())); EXPECT_EQ("RFCv2", ParsedQuicVersionToString(ParsedQuicVersion::RFCv2())); ParsedQuicVersionVector versions_vector = {ParsedQuicVersion::Q046()}; EXPECT_EQ("Q046", ParsedQuicVersionVectorToString(versions_vector)); versions_vector = {ParsedQuicVersion::Unsupported(), ParsedQuicVersion::Q046()}; EXPECT_EQ("0,Q046", ParsedQuicVersionVectorToString(versions_vector)); EXPECT_EQ("0:Q046", ParsedQuicVersionVectorToString(versions_vector, ":", versions_vector.size())); EXPECT_EQ("0|...", ParsedQuicVersionVectorToString(versions_vector, "|", 0)); for (const ParsedQuicVersion& version : AllSupportedVersions()) { EXPECT_NE("0", ParsedQuicVersionToString(version)); } std::ostringstream os; os << versions_vector; EXPECT_EQ("0,Q046", os.str()); } TEST(QuicVersionsTest, FilterSupportedVersionsAllVersions) { for (const ParsedQuicVersion& version : AllSupportedVersions()) { QuicEnableVersion(version); } ParsedQuicVersionVector expected_parsed_versions; for (const ParsedQuicVersion& version : SupportedVersions()) { expected_parsed_versions.push_back(version); } EXPECT_EQ(expected_parsed_versions, FilterSupportedVersions(AllSupportedVersions())); EXPECT_EQ(expected_parsed_versions, AllSupportedVersions()); } TEST(QuicVersionsTest, FilterSupportedVersionsWithoutFirstVersion) { for (const ParsedQuicVersion& version : AllSupportedVersions()) { QuicEnableVersion(version); } QuicDisableVersion(AllSupportedVersions().front()); ParsedQuicVersionVector expected_parsed_versions; for (const ParsedQuicVersion& version : SupportedVersions()) { expected_parsed_versions.push_back(version); } expected_parsed_versions.erase(expected_parsed_versions.begin()); EXPECT_EQ(expected_parsed_versions, FilterSupportedVersions(AllSupportedVersions())); } TEST(QuicVersionsTest, LookUpParsedVersionByIndex) { ParsedQuicVersionVector all_versions = AllSupportedVersions(); int version_count = all_versions.size(); for (int i = -5; i <= version_count + 1; ++i) { ParsedQuicVersionVector index = ParsedVersionOfIndex(all_versions, i); if (i >= 0 && i < version_count) { EXPECT_EQ(all_versions[i], index[0]); } else { EXPECT_EQ(UnsupportedQuicVersion(), index[0]); } } } TEST(QuicVersionsTest, CheckTransportVersionNumbersForTypos) { static_assert(SupportedVersions().size() == 4u, "Supported versions out of sync"); EXPECT_EQ(QUIC_VERSION_46, 46); EXPECT_EQ(QUIC_VERSION_IETF_DRAFT_29, 73); EXPECT_EQ(QUIC_VERSION_IETF_RFC_V1, 80); EXPECT_EQ(QUIC_VERSION_IETF_RFC_V2, 82); } TEST(QuicVersionsTest, AlpnForVersion) { static_assert(SupportedVersions().size() == 4u, "Supported versions out of sync"); EXPECT_EQ("h3-Q046", AlpnForVersion(ParsedQuicVersion::Q046())); EXPECT_EQ("h3-29", AlpnForVersion(ParsedQuicVersion::Draft29())); EXPECT_EQ("h3", AlpnForVersion(ParsedQuicVersion::RFCv1())); EXPECT_EQ("h3", AlpnForVersion(ParsedQuicVersion::RFCv2())); } TEST(QuicVersionsTest, QuicVersionEnabling) { for (const ParsedQuicVersion& version : AllSupportedVersions()) { QuicFlagSaver flag_saver; QuicDisableVersion(version); EXPECT_FALSE(QuicVersionIsEnabled(version)); QuicEnableVersion(version); EXPECT_TRUE(QuicVersionIsEnabled(version)); } } TEST(QuicVersionsTest, ReservedForNegotiation) { EXPECT_EQ(QUIC_VERSION_RESERVED_FOR_NEGOTIATION, QuicVersionReservedForNegotiation().transport_version); for (const ParsedQuicVersion& version : AllSupportedVersions()) { EXPECT_NE(QUIC_VERSION_RESERVED_FOR_NEGOTIATION, version.transport_version); } } TEST(QuicVersionsTest, SupportedVersionsHasCorrectList) { size_t index = 0; for (HandshakeProtocol handshake_protocol : SupportedHandshakeProtocols()) { for (int trans_vers = 255; trans_vers > 0; trans_vers--) { QuicTransportVersion transport_version = static_cast<QuicTransportVersion>(trans_vers); SCOPED_TRACE(index); if (ParsedQuicVersionIsValid(handshake_protocol, transport_version)) { ParsedQuicVersion version = SupportedVersions()[index]; EXPECT_EQ(version, ParsedQuicVersion(handshake_protocol, transport_version)); index++; } } } EXPECT_EQ(SupportedVersions().size(), index); } TEST(QuicVersionsTest, SupportedVersionsAllDistinct) { for (size_t index1 = 0; index1 < SupportedVersions().size(); ++index1) { ParsedQuicVersion version1 = SupportedVersions()[index1]; for (size_t index2 = index1 + 1; index2 < SupportedVersions().size(); ++index2) { ParsedQuicVersion version2 = SupportedVersions()[index2]; EXPECT_NE(version1, version2) << version1 << " " << version2; EXPECT_NE(CreateQuicVersionLabel(version1), CreateQuicVersionLabel(version2)) << version1 << " " << version2; if ((version1 != ParsedQuicVersion::RFCv2()) && (version2 != ParsedQuicVersion::RFCv1())) { EXPECT_NE(AlpnForVersion(version1), AlpnForVersion(version2)) << version1 << " " << version2; } } } } TEST(QuicVersionsTest, CurrentSupportedHttp3Versions) { ParsedQuicVersionVector h3_versions = CurrentSupportedHttp3Versions(); ParsedQuicVersionVector all_current_supported_versions = CurrentSupportedVersions(); for (auto& version : all_current_supported_versions) { bool version_is_h3 = false; for (auto& h3_version : h3_versions) { if (version == h3_version) { EXPECT_TRUE(version.UsesHttp3()); version_is_h3 = true; break; } } if (!version_is_h3) { EXPECT_FALSE(version.UsesHttp3()); } } } TEST(QuicVersionsTest, ObsoleteSupportedVersions) { ParsedQuicVersionVector obsolete_versions = ObsoleteSupportedVersions(); EXPECT_EQ(quic::ParsedQuicVersion::Q046(), obsolete_versions[0]); EXPECT_EQ(quic::ParsedQuicVersion::Draft29(), obsolete_versions[1]); } TEST(QuicVersionsTest, IsObsoleteSupportedVersion) { for (const ParsedQuicVersion& version : AllSupportedVersions()) { bool is_obsolete = version.handshake_protocol != PROTOCOL_TLS1_3 || version.transport_version < QUIC_VERSION_IETF_RFC_V1; EXPECT_EQ(is_obsolete, IsObsoleteSupportedVersion(version)); } } TEST(QuicVersionsTest, CurrentSupportedVersionsForClients) { ParsedQuicVersionVector supported_versions = CurrentSupportedVersions(); ParsedQuicVersionVector client_versions = CurrentSupportedVersionsForClients(); for (auto& version : supported_versions) { const bool is_obsolete = IsObsoleteSupportedVersion(version); const bool is_supported = absl::c_find(client_versions, version) != client_versions.end(); EXPECT_EQ(!is_obsolete, is_supported); } for (auto& version : client_versions) { EXPECT_TRUE(absl::c_find(supported_versions, version) != supported_versions.end()); } } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_versions.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_versions_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
8bad0c0c-8d6b-41ae-9998-79d8a823336e
cpp
google/quiche
quic_connection_id
quiche/quic/core/quic_connection_id.cc
quiche/quic/core/quic_connection_id_test.cc
#include "quiche/quic/core/quic_connection_id.h" #include <cstddef> #include <cstdint> #include <cstring> #include <iomanip> #include <ostream> #include <string> #include "absl/strings/escaping.h" #include "openssl/siphash.h" #include "quiche/quic/core/crypto/quic_random.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" #include "quiche/common/quiche_endian.h" namespace quic { namespace { class QuicConnectionIdHasher { public: inline QuicConnectionIdHasher() : QuicConnectionIdHasher(QuicRandom::GetInstance()) {} explicit inline QuicConnectionIdHasher(QuicRandom* random) { random->RandBytes(&sip_hash_key_, sizeof(sip_hash_key_)); } inline size_t Hash(const char* input, size_t input_len) const { return static_cast<size_t>(SIPHASH_24( sip_hash_key_, reinterpret_cast<const uint8_t*>(input), input_len)); } private: uint64_t sip_hash_key_[2]; }; } QuicConnectionId::QuicConnectionId() : QuicConnectionId(nullptr, 0) { static_assert(offsetof(QuicConnectionId, padding_) == offsetof(QuicConnectionId, length_), "bad offset"); static_assert(sizeof(QuicConnectionId) <= 16, "bad size"); } QuicConnectionId::QuicConnectionId(const char* data, uint8_t length) { length_ = length; if (length_ == 0) { return; } if (length_ <= sizeof(data_short_)) { memcpy(data_short_, data, length_); return; } data_long_ = reinterpret_cast<char*>(malloc(length_)); QUICHE_CHECK_NE(nullptr, data_long_); memcpy(data_long_, data, length_); } QuicConnectionId::QuicConnectionId(const absl::Span<const uint8_t> data) : QuicConnectionId(reinterpret_cast<const char*>(data.data()), data.length()) {} QuicConnectionId::~QuicConnectionId() { if (length_ > sizeof(data_short_)) { free(data_long_); data_long_ = nullptr; } } QuicConnectionId::QuicConnectionId(const QuicConnectionId& other) : QuicConnectionId(other.data(), other.length()) {} QuicConnectionId& QuicConnectionId::operator=(const QuicConnectionId& other) { set_length(other.length()); memcpy(mutable_data(), other.data(), length_); return *this; } const char* QuicConnectionId::data() const { if (length_ <= sizeof(data_short_)) { return data_short_; } return data_long_; } char* QuicConnectionId::mutable_data() { if (length_ <= sizeof(data_short_)) { return data_short_; } return data_long_; } uint8_t QuicConnectionId::length() const { return length_; } void QuicConnectionId::set_length(uint8_t length) { char temporary_data[sizeof(data_short_)]; if (length > sizeof(data_short_)) { if (length_ <= sizeof(data_short_)) { memcpy(temporary_data, data_short_, length_); data_long_ = reinterpret_cast<char*>(malloc(length)); QUICHE_CHECK_NE(nullptr, data_long_); memcpy(data_long_, temporary_data, length_); } else { char* realloc_result = reinterpret_cast<char*>(realloc(data_long_, length)); QUICHE_CHECK_NE(nullptr, realloc_result); data_long_ = realloc_result; } } else if (length_ > sizeof(data_short_)) { memcpy(temporary_data, data_long_, length); free(data_long_); data_long_ = nullptr; memcpy(data_short_, temporary_data, length); } length_ = length; } bool QuicConnectionId::IsEmpty() const { return length_ == 0; } size_t QuicConnectionId::Hash() const { static const QuicConnectionIdHasher hasher = QuicConnectionIdHasher(); return hasher.Hash(data(), length_); } std::string QuicConnectionId::ToString() const { if (IsEmpty()) { return std::string("0"); } return absl::BytesToHexString(absl::string_view(data(), length_)); } std::ostream& operator<<(std::ostream& os, const QuicConnectionId& v) { os << v.ToString(); return os; } bool QuicConnectionId::operator==(const QuicConnectionId& v) const { return length_ == v.length_ && memcmp(data(), v.data(), length_) == 0; } bool QuicConnectionId::operator!=(const QuicConnectionId& v) const { return !(v == *this); } bool QuicConnectionId::operator<(const QuicConnectionId& v) const { if (length_ < v.length_) { return true; } if (length_ > v.length_) { return false; } return memcmp(data(), v.data(), length_) < 0; } QuicConnectionId EmptyQuicConnectionId() { return QuicConnectionId(); } static_assert(kQuicDefaultConnectionIdLength == sizeof(uint64_t), "kQuicDefaultConnectionIdLength changed"); static_assert(kQuicDefaultConnectionIdLength == 8, "kQuicDefaultConnectionIdLength changed"); }
#include "quiche/quic/core/quic_connection_id.h" #include <cstdint> #include <cstring> #include <string> #include "absl/base/macros.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" namespace quic::test { namespace { class QuicConnectionIdTest : public QuicTest {}; TEST_F(QuicConnectionIdTest, Empty) { QuicConnectionId connection_id_empty = EmptyQuicConnectionId(); EXPECT_TRUE(connection_id_empty.IsEmpty()); } TEST_F(QuicConnectionIdTest, DefaultIsEmpty) { QuicConnectionId connection_id_empty = QuicConnectionId(); EXPECT_TRUE(connection_id_empty.IsEmpty()); } TEST_F(QuicConnectionIdTest, NotEmpty) { QuicConnectionId connection_id = test::TestConnectionId(1); EXPECT_FALSE(connection_id.IsEmpty()); } TEST_F(QuicConnectionIdTest, ZeroIsNotEmpty) { QuicConnectionId connection_id = test::TestConnectionId(0); EXPECT_FALSE(connection_id.IsEmpty()); } TEST_F(QuicConnectionIdTest, Data) { char connection_id_data[kQuicDefaultConnectionIdLength]; memset(connection_id_data, 0x42, sizeof(connection_id_data)); QuicConnectionId connection_id1 = QuicConnectionId(connection_id_data, sizeof(connection_id_data)); QuicConnectionId connection_id2 = QuicConnectionId(connection_id_data, sizeof(connection_id_data)); EXPECT_EQ(connection_id1, connection_id2); EXPECT_EQ(connection_id1.length(), kQuicDefaultConnectionIdLength); EXPECT_EQ(connection_id1.data(), connection_id1.mutable_data()); EXPECT_EQ(0, memcmp(connection_id1.data(), connection_id2.data(), sizeof(connection_id_data))); EXPECT_EQ(0, memcmp(connection_id1.data(), connection_id_data, sizeof(connection_id_data))); connection_id2.mutable_data()[0] = 0x33; EXPECT_NE(connection_id1, connection_id2); static const uint8_t kNewLength = 4; connection_id2.set_length(kNewLength); EXPECT_EQ(kNewLength, connection_id2.length()); } TEST_F(QuicConnectionIdTest, SpanData) { QuicConnectionId connection_id = QuicConnectionId({0x01, 0x02, 0x03}); EXPECT_EQ(connection_id.length(), 3); QuicConnectionId empty_connection_id = QuicConnectionId(absl::Span<uint8_t>()); EXPECT_EQ(empty_connection_id.length(), 0); QuicConnectionId connection_id2 = QuicConnectionId({ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, }); EXPECT_EQ(connection_id2.length(), 16); } TEST_F(QuicConnectionIdTest, DoubleConvert) { QuicConnectionId connection_id64_1 = test::TestConnectionId(1); QuicConnectionId connection_id64_2 = test::TestConnectionId(42); QuicConnectionId connection_id64_3 = test::TestConnectionId(UINT64_C(0xfedcba9876543210)); EXPECT_EQ(connection_id64_1, test::TestConnectionId( test::TestConnectionIdToUInt64(connection_id64_1))); EXPECT_EQ(connection_id64_2, test::TestConnectionId( test::TestConnectionIdToUInt64(connection_id64_2))); EXPECT_EQ(connection_id64_3, test::TestConnectionId( test::TestConnectionIdToUInt64(connection_id64_3))); EXPECT_NE(connection_id64_1, connection_id64_2); EXPECT_NE(connection_id64_1, connection_id64_3); EXPECT_NE(connection_id64_2, connection_id64_3); } TEST_F(QuicConnectionIdTest, Hash) { QuicConnectionId connection_id64_1 = test::TestConnectionId(1); QuicConnectionId connection_id64_1b = test::TestConnectionId(1); QuicConnectionId connection_id64_2 = test::TestConnectionId(42); QuicConnectionId connection_id64_3 = test::TestConnectionId(UINT64_C(0xfedcba9876543210)); EXPECT_EQ(connection_id64_1.Hash(), connection_id64_1b.Hash()); EXPECT_NE(connection_id64_1.Hash(), connection_id64_2.Hash()); EXPECT_NE(connection_id64_1.Hash(), connection_id64_3.Hash()); EXPECT_NE(connection_id64_2.Hash(), connection_id64_3.Hash()); const char connection_id_bytes[255] = {}; for (uint8_t i = 0; i < sizeof(connection_id_bytes) - 1; ++i) { QuicConnectionId connection_id_i(connection_id_bytes, i); for (uint8_t j = i + 1; j < sizeof(connection_id_bytes); ++j) { QuicConnectionId connection_id_j(connection_id_bytes, j); EXPECT_NE(connection_id_i.Hash(), connection_id_j.Hash()); } } } TEST_F(QuicConnectionIdTest, AssignAndCopy) { QuicConnectionId connection_id = test::TestConnectionId(1); QuicConnectionId connection_id2 = test::TestConnectionId(2); connection_id = connection_id2; EXPECT_EQ(connection_id, test::TestConnectionId(2)); EXPECT_NE(connection_id, test::TestConnectionId(1)); connection_id = QuicConnectionId(test::TestConnectionId(1)); EXPECT_EQ(connection_id, test::TestConnectionId(1)); EXPECT_NE(connection_id, test::TestConnectionId(2)); } TEST_F(QuicConnectionIdTest, ChangeLength) { QuicConnectionId connection_id64_1 = test::TestConnectionId(1); QuicConnectionId connection_id64_2 = test::TestConnectionId(2); QuicConnectionId connection_id136_2 = test::TestConnectionId(2); connection_id136_2.set_length(17); memset(connection_id136_2.mutable_data() + 8, 0, 9); char connection_id136_2_bytes[17] = {0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0}; QuicConnectionId connection_id136_2b(connection_id136_2_bytes, sizeof(connection_id136_2_bytes)); EXPECT_EQ(connection_id136_2, connection_id136_2b); QuicConnectionId connection_id = connection_id64_1; connection_id.set_length(17); EXPECT_NE(connection_id64_1, connection_id); connection_id.set_length(8); EXPECT_EQ(connection_id64_1, connection_id); connection_id.set_length(17); memset(connection_id.mutable_data(), 0, connection_id.length()); memcpy(connection_id.mutable_data(), connection_id64_2.data(), connection_id64_2.length()); EXPECT_EQ(connection_id136_2, connection_id); EXPECT_EQ(connection_id136_2b, connection_id); QuicConnectionId connection_id120(connection_id136_2_bytes, 15); connection_id.set_length(15); EXPECT_EQ(connection_id120, connection_id); QuicConnectionId connection_id2 = connection_id120; connection_id2.set_length(17); connection_id2.mutable_data()[15] = 0; connection_id2.mutable_data()[16] = 0; EXPECT_EQ(connection_id136_2, connection_id2); EXPECT_EQ(connection_id136_2b, connection_id2); } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_connection_id.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_connection_id_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
f8b4bd87-b3e8-495b-94cb-8b130bd59927
cpp
google/quiche
quic_stream_sequencer
quiche/quic/core/quic_stream_sequencer.cc
quiche/quic/core/quic_stream_sequencer_test.cc
#include "quiche/quic/core/quic_stream_sequencer.h" #include <algorithm> #include <cstddef> #include <limits> #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_clock.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_sequencer_buffer.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_stack_trace.h" namespace quic { QuicStreamSequencer::QuicStreamSequencer(StreamInterface* quic_stream) : stream_(quic_stream), buffered_frames_(kStreamReceiveWindowLimit), highest_offset_(0), close_offset_(std::numeric_limits<QuicStreamOffset>::max()), reliable_offset_(0), blocked_(false), num_frames_received_(0), num_duplicate_frames_received_(0), ignore_read_data_(false), level_triggered_(false) {} QuicStreamSequencer::~QuicStreamSequencer() { if (stream_ == nullptr) { QUIC_BUG(quic_bug_10858_1) << "Double free'ing QuicStreamSequencer at " << this << ". " << QuicStackTrace(); } stream_ = nullptr; } void QuicStreamSequencer::OnStreamFrame(const QuicStreamFrame& frame) { QUICHE_DCHECK_LE(frame.offset + frame.data_length, close_offset_); ++num_frames_received_; const QuicStreamOffset byte_offset = frame.offset; const size_t data_len = frame.data_length; if (frame.fin && (!CloseStreamAtOffset(frame.offset + data_len) || data_len == 0)) { return; } if (stream_->version().HasIetfQuicFrames() && data_len == 0) { QUICHE_DCHECK(!frame.fin); return; } OnFrameData(byte_offset, data_len, frame.data_buffer); } void QuicStreamSequencer::OnCryptoFrame(const QuicCryptoFrame& frame) { ++num_frames_received_; if (frame.data_length == 0) { return; } OnFrameData(frame.offset, frame.data_length, frame.data_buffer); } void QuicStreamSequencer::OnReliableReset(QuicStreamOffset reliable_size) { reliable_offset_ = reliable_size; } void QuicStreamSequencer::OnFrameData(QuicStreamOffset byte_offset, size_t data_len, const char* data_buffer) { highest_offset_ = std::max(highest_offset_, byte_offset + data_len); const size_t previous_readable_bytes = buffered_frames_.ReadableBytes(); size_t bytes_written; std::string error_details; QuicErrorCode result = buffered_frames_.OnStreamData( byte_offset, absl::string_view(data_buffer, data_len), &bytes_written, &error_details); if (result != QUIC_NO_ERROR) { std::string details = absl::StrCat("Stream ", stream_->id(), ": ", QuicErrorCodeToString(result), ": ", error_details); QUIC_LOG_FIRST_N(WARNING, 50) << QuicErrorCodeToString(result); QUIC_LOG_FIRST_N(WARNING, 50) << details; stream_->OnUnrecoverableError(result, details); return; } if (bytes_written == 0) { ++num_duplicate_frames_received_; return; } if (blocked_) { return; } if (level_triggered_) { if (buffered_frames_.ReadableBytes() > previous_readable_bytes) { if (ignore_read_data_) { FlushBufferedFrames(); } else { stream_->OnDataAvailable(); } } return; } const bool stream_unblocked = previous_readable_bytes == 0 && buffered_frames_.ReadableBytes() > 0; if (stream_unblocked) { if (ignore_read_data_) { FlushBufferedFrames(); } else { stream_->OnDataAvailable(); } } } bool QuicStreamSequencer::CloseStreamAtOffset(QuicStreamOffset offset) { const QuicStreamOffset kMaxOffset = std::numeric_limits<QuicStreamOffset>::max(); if (close_offset_ != kMaxOffset && offset != close_offset_) { stream_->OnUnrecoverableError( QUIC_STREAM_SEQUENCER_INVALID_STATE, absl::StrCat( "Stream ", stream_->id(), " received new final offset: ", offset, ", which is different from close offset: ", close_offset_)); return false; } if (offset < highest_offset_) { stream_->OnUnrecoverableError( QUIC_STREAM_SEQUENCER_INVALID_STATE, absl::StrCat( "Stream ", stream_->id(), " received fin with offset: ", offset, ", which reduces current highest offset: ", highest_offset_)); return false; } if (offset < reliable_offset_) { stream_->OnUnrecoverableError( QUIC_STREAM_MULTIPLE_OFFSET, absl::StrCat( "Stream ", stream_->id(), " received fin with offset: ", offset, ", which reduces current reliable offset: ", reliable_offset_)); return false; } close_offset_ = offset; MaybeCloseStream(); return true; } void QuicStreamSequencer::MaybeCloseStream() { if (blocked_ || !IsClosed()) { return; } QUIC_DVLOG(1) << "Passing up termination, as we've processed " << buffered_frames_.BytesConsumed() << " of " << close_offset_ << " bytes."; if (ignore_read_data_) { stream_->OnFinRead(); } else { stream_->OnDataAvailable(); } buffered_frames_.Clear(); } int QuicStreamSequencer::GetReadableRegions(iovec* iov, size_t iov_len) const { QUICHE_DCHECK(!blocked_); return buffered_frames_.GetReadableRegions(iov, iov_len); } bool QuicStreamSequencer::GetReadableRegion(iovec* iov) const { QUICHE_DCHECK(!blocked_); return buffered_frames_.GetReadableRegion(iov); } bool QuicStreamSequencer::PeekRegion(QuicStreamOffset offset, iovec* iov) const { QUICHE_DCHECK(!blocked_); return buffered_frames_.PeekRegion(offset, iov); } void QuicStreamSequencer::Read(std::string* buffer) { QUICHE_DCHECK(!blocked_); buffer->resize(buffer->size() + ReadableBytes()); iovec iov; iov.iov_len = ReadableBytes(); iov.iov_base = &(*buffer)[buffer->size() - iov.iov_len]; Readv(&iov, 1); } size_t QuicStreamSequencer::Readv(const struct iovec* iov, size_t iov_len) { QUICHE_DCHECK(!blocked_); std::string error_details; size_t bytes_read; QuicErrorCode read_error = buffered_frames_.Readv(iov, iov_len, &bytes_read, &error_details); if (read_error != QUIC_NO_ERROR) { std::string details = absl::StrCat("Stream ", stream_->id(), ": ", error_details); stream_->OnUnrecoverableError(read_error, details); return bytes_read; } stream_->AddBytesConsumed(bytes_read); return bytes_read; } bool QuicStreamSequencer::HasBytesToRead() const { return buffered_frames_.HasBytesToRead(); } size_t QuicStreamSequencer::ReadableBytes() const { return buffered_frames_.ReadableBytes(); } bool QuicStreamSequencer::IsClosed() const { return buffered_frames_.BytesConsumed() >= close_offset_; } void QuicStreamSequencer::MarkConsumed(size_t num_bytes_consumed) { QUICHE_DCHECK(!blocked_); bool result = buffered_frames_.MarkConsumed(num_bytes_consumed); if (!result) { QUIC_BUG(quic_bug_10858_2) << "Invalid argument to MarkConsumed." << " expect to consume: " << num_bytes_consumed << ", but not enough bytes available. " << DebugString(); stream_->ResetWithError( QuicResetStreamError::FromInternal(QUIC_ERROR_PROCESSING_STREAM)); return; } stream_->AddBytesConsumed(num_bytes_consumed); } void QuicStreamSequencer::SetBlockedUntilFlush() { blocked_ = true; } void QuicStreamSequencer::SetUnblocked() { blocked_ = false; if (IsClosed() || HasBytesToRead()) { stream_->OnDataAvailable(); } } void QuicStreamSequencer::StopReading() { if (ignore_read_data_) { return; } ignore_read_data_ = true; FlushBufferedFrames(); } void QuicStreamSequencer::ReleaseBuffer() { buffered_frames_.ReleaseWholeBuffer(); } void QuicStreamSequencer::ReleaseBufferIfEmpty() { if (buffered_frames_.Empty()) { buffered_frames_.ReleaseWholeBuffer(); } } void QuicStreamSequencer::FlushBufferedFrames() { QUICHE_DCHECK(ignore_read_data_); size_t bytes_flushed = buffered_frames_.FlushBufferedFrames(); QUIC_DVLOG(1) << "Flushing buffered data at offset " << buffered_frames_.BytesConsumed() << " length " << bytes_flushed << " for stream " << stream_->id(); stream_->AddBytesConsumed(bytes_flushed); MaybeCloseStream(); } size_t QuicStreamSequencer::NumBytesBuffered() const { return buffered_frames_.BytesBuffered(); } QuicStreamOffset QuicStreamSequencer::NumBytesConsumed() const { return buffered_frames_.BytesConsumed(); } bool QuicStreamSequencer::IsAllDataAvailable() const { QUICHE_DCHECK_LE(NumBytesConsumed() + NumBytesBuffered(), close_offset_); return NumBytesConsumed() + NumBytesBuffered() >= close_offset_; } std::string QuicStreamSequencer::DebugString() const { return absl::StrCat( "QuicStreamSequencer: bytes buffered: ", NumBytesBuffered(), "\n bytes consumed: ", NumBytesConsumed(), "\n first missing byte: ", buffered_frames_.FirstMissingByte(), "\n next expected byte: ", buffered_frames_.NextExpectedByte(), "\n received frames: ", buffered_frames_.ReceivedFramesDebugString(), "\n has bytes to read: ", HasBytesToRead() ? "true" : "false", "\n frames received: ", num_frames_received(), "\n close offset bytes: ", close_offset_, "\n is closed: ", IsClosed() ? "true" : "false"); } }
#include "quiche/quic/core/quic_stream_sequencer.h" #include <algorithm> #include <cstdint> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/base/macros.h" #include "absl/strings/string_view.h" #include "quiche/quic/core/quic_stream.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_logging.h" #include "quiche/quic/platform/api/quic_test.h" #include "quiche/quic/test_tools/quic_stream_sequencer_peer.h" #include "quiche/quic/test_tools/quic_test_utils.h" using testing::_; using testing::AnyNumber; using testing::InSequence; namespace quic { namespace test { class MockStream : public QuicStreamSequencer::StreamInterface { public: MOCK_METHOD(void, OnFinRead, (), (override)); MOCK_METHOD(void, OnDataAvailable, (), (override)); MOCK_METHOD(void, OnUnrecoverableError, (QuicErrorCode error, const std::string& details), (override)); MOCK_METHOD(void, OnUnrecoverableError, (QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error, const std::string& details), (override)); MOCK_METHOD(void, ResetWithError, (QuicResetStreamError error), (override)); MOCK_METHOD(void, AddBytesConsumed, (QuicByteCount bytes), (override)); QuicStreamId id() const override { return 1; } ParsedQuicVersion version() const override { return CurrentSupportedVersions()[0]; } }; namespace { static const char kPayload[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; class QuicStreamSequencerTest : public QuicTest { public: void ConsumeData(size_t num_bytes) { char buffer[1024]; ASSERT_GT(ABSL_ARRAYSIZE(buffer), num_bytes); struct iovec iov; iov.iov_base = buffer; iov.iov_len = num_bytes; ASSERT_EQ(num_bytes, sequencer_->Readv(&iov, 1)); } protected: QuicStreamSequencerTest() : stream_(), sequencer_(new QuicStreamSequencer(&stream_)) {} bool VerifyReadableRegion(const std::vector<std::string>& expected) { return VerifyReadableRegion(*sequencer_, expected); } bool VerifyReadableRegions(const std::vector<std::string>& expected) { return VerifyReadableRegions(*sequencer_, expected); } bool VerifyIovecs(iovec* iovecs, size_t num_iovecs, const std::vector<std::string>& expected) { return VerifyIovecs(*sequencer_, iovecs, num_iovecs, expected); } bool VerifyReadableRegion(const QuicStreamSequencer& sequencer, const std::vector<std::string>& expected) { iovec iovecs[1]; if (sequencer.GetReadableRegions(iovecs, 1)) { return (VerifyIovecs(sequencer, iovecs, 1, std::vector<std::string>{expected[0]})); } return false; } bool VerifyReadableRegions(const QuicStreamSequencer& sequencer, const std::vector<std::string>& expected) { iovec iovecs[5]; size_t num_iovecs = sequencer.GetReadableRegions(iovecs, ABSL_ARRAYSIZE(iovecs)); return VerifyReadableRegion(sequencer, expected) && VerifyIovecs(sequencer, iovecs, num_iovecs, expected); } bool VerifyIovecs(const QuicStreamSequencer& , iovec* iovecs, size_t num_iovecs, const std::vector<std::string>& expected) { int start_position = 0; for (size_t i = 0; i < num_iovecs; ++i) { if (!VerifyIovec(iovecs[i], expected[0].substr(start_position, iovecs[i].iov_len))) { return false; } start_position += iovecs[i].iov_len; } return true; } bool VerifyIovec(const iovec& iovec, absl::string_view expected) { if (iovec.iov_len != expected.length()) { QUIC_LOG(ERROR) << "Invalid length: " << iovec.iov_len << " vs " << expected.length(); return false; } if (memcmp(iovec.iov_base, expected.data(), expected.length()) != 0) { QUIC_LOG(ERROR) << "Invalid data: " << static_cast<char*>(iovec.iov_base) << " vs " << expected; return false; } return true; } void OnFinFrame(QuicStreamOffset byte_offset, const char* data) { QuicStreamFrame frame; frame.stream_id = 1; frame.offset = byte_offset; frame.data_buffer = data; frame.data_length = strlen(data); frame.fin = true; sequencer_->OnStreamFrame(frame); } void OnFrame(QuicStreamOffset byte_offset, const char* data) { QuicStreamFrame frame; frame.stream_id = 1; frame.offset = byte_offset; frame.data_buffer = data; frame.data_length = strlen(data); frame.fin = false; sequencer_->OnStreamFrame(frame); } size_t NumBufferedBytes() { return QuicStreamSequencerPeer::GetNumBufferedBytes(sequencer_.get()); } testing::StrictMock<MockStream> stream_; std::unique_ptr<QuicStreamSequencer> sequencer_; }; TEST_F(QuicStreamSequencerTest, RejectOldFrame) { EXPECT_CALL(stream_, AddBytesConsumed(3)); EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() { ConsumeData(3); })); OnFrame(0, "abc"); EXPECT_EQ(0u, NumBufferedBytes()); EXPECT_EQ(3u, sequencer_->NumBytesConsumed()); OnFrame(0, "def"); EXPECT_EQ(0u, NumBufferedBytes()); } TEST_F(QuicStreamSequencerTest, RejectBufferedFrame) { EXPECT_CALL(stream_, OnDataAvailable()); OnFrame(0, "abc"); EXPECT_EQ(3u, NumBufferedBytes()); EXPECT_EQ(0u, sequencer_->NumBytesConsumed()); OnFrame(0, "def"); EXPECT_EQ(3u, NumBufferedBytes()); } TEST_F(QuicStreamSequencerTest, FullFrameConsumed) { EXPECT_CALL(stream_, AddBytesConsumed(3)); EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() { ConsumeData(3); })); OnFrame(0, "abc"); EXPECT_EQ(0u, NumBufferedBytes()); EXPECT_EQ(3u, sequencer_->NumBytesConsumed()); } TEST_F(QuicStreamSequencerTest, BlockedThenFullFrameConsumed) { sequencer_->SetBlockedUntilFlush(); OnFrame(0, "abc"); EXPECT_EQ(3u, NumBufferedBytes()); EXPECT_EQ(0u, sequencer_->NumBytesConsumed()); EXPECT_CALL(stream_, AddBytesConsumed(3)); EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() { ConsumeData(3); })); sequencer_->SetUnblocked(); EXPECT_EQ(0u, NumBufferedBytes()); EXPECT_EQ(3u, sequencer_->NumBytesConsumed()); EXPECT_CALL(stream_, AddBytesConsumed(3)); EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() { ConsumeData(3); })); EXPECT_FALSE(sequencer_->IsClosed()); EXPECT_FALSE(sequencer_->IsAllDataAvailable()); OnFinFrame(3, "def"); EXPECT_TRUE(sequencer_->IsClosed()); EXPECT_TRUE(sequencer_->IsAllDataAvailable()); } TEST_F(QuicStreamSequencerTest, BlockedThenFullFrameAndFinConsumed) { sequencer_->SetBlockedUntilFlush(); OnFinFrame(0, "abc"); EXPECT_EQ(3u, NumBufferedBytes()); EXPECT_EQ(0u, sequencer_->NumBytesConsumed()); EXPECT_CALL(stream_, AddBytesConsumed(3)); EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() { ConsumeData(3); })); EXPECT_FALSE(sequencer_->IsClosed()); EXPECT_TRUE(sequencer_->IsAllDataAvailable()); sequencer_->SetUnblocked(); EXPECT_TRUE(sequencer_->IsClosed()); EXPECT_EQ(0u, NumBufferedBytes()); EXPECT_EQ(3u, sequencer_->NumBytesConsumed()); } TEST_F(QuicStreamSequencerTest, EmptyFrame) { if (!stream_.version().HasIetfQuicFrames()) { EXPECT_CALL(stream_, OnUnrecoverableError(QUIC_EMPTY_STREAM_FRAME_NO_FIN, _)); } OnFrame(0, ""); EXPECT_EQ(0u, NumBufferedBytes()); EXPECT_EQ(0u, sequencer_->NumBytesConsumed()); } TEST_F(QuicStreamSequencerTest, EmptyFinFrame) { EXPECT_CALL(stream_, OnDataAvailable()); OnFinFrame(0, ""); EXPECT_EQ(0u, NumBufferedBytes()); EXPECT_EQ(0u, sequencer_->NumBytesConsumed()); EXPECT_TRUE(sequencer_->IsAllDataAvailable()); } TEST_F(QuicStreamSequencerTest, PartialFrameConsumed) { EXPECT_CALL(stream_, AddBytesConsumed(2)); EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() { ConsumeData(2); })); OnFrame(0, "abc"); EXPECT_EQ(1u, NumBufferedBytes()); EXPECT_EQ(2u, sequencer_->NumBytesConsumed()); } TEST_F(QuicStreamSequencerTest, NextxFrameNotConsumed) { EXPECT_CALL(stream_, OnDataAvailable()); OnFrame(0, "abc"); EXPECT_EQ(3u, NumBufferedBytes()); EXPECT_EQ(0u, sequencer_->NumBytesConsumed()); } TEST_F(QuicStreamSequencerTest, FutureFrameNotProcessed) { OnFrame(3, "abc"); EXPECT_EQ(3u, NumBufferedBytes()); EXPECT_EQ(0u, sequencer_->NumBytesConsumed()); } TEST_F(QuicStreamSequencerTest, OutOfOrderFrameProcessed) { OnFrame(6, "ghi"); EXPECT_EQ(3u, NumBufferedBytes()); EXPECT_EQ(0u, sequencer_->NumBytesConsumed()); EXPECT_EQ(3u, sequencer_->NumBytesBuffered()); OnFrame(3, "def"); EXPECT_EQ(6u, NumBufferedBytes()); EXPECT_EQ(0u, sequencer_->NumBytesConsumed()); EXPECT_EQ(6u, sequencer_->NumBytesBuffered()); EXPECT_CALL(stream_, AddBytesConsumed(9)); EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() { ConsumeData(9); })); OnFrame(0, "abc"); EXPECT_EQ(9u, sequencer_->NumBytesConsumed()); EXPECT_EQ(0u, sequencer_->NumBytesBuffered()); EXPECT_EQ(0u, NumBufferedBytes()); } TEST_F(QuicStreamSequencerTest, BasicHalfCloseOrdered) { InSequence s; EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() { ConsumeData(3); })); EXPECT_CALL(stream_, AddBytesConsumed(3)); OnFinFrame(0, "abc"); EXPECT_EQ(3u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get())); } TEST_F(QuicStreamSequencerTest, BasicHalfCloseUnorderedWithFlush) { OnFinFrame(6, ""); EXPECT_EQ(6u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get())); OnFrame(3, "def"); EXPECT_CALL(stream_, AddBytesConsumed(6)); EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() { ConsumeData(6); })); EXPECT_FALSE(sequencer_->IsClosed()); OnFrame(0, "abc"); EXPECT_TRUE(sequencer_->IsClosed()); } TEST_F(QuicStreamSequencerTest, BasicHalfUnordered) { OnFinFrame(3, ""); EXPECT_EQ(3u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get())); EXPECT_CALL(stream_, AddBytesConsumed(3)); EXPECT_CALL(stream_, OnDataAvailable()).WillOnce(testing::Invoke([this]() { ConsumeData(3); })); EXPECT_FALSE(sequencer_->IsClosed()); OnFrame(0, "abc"); EXPECT_TRUE(sequencer_->IsClosed()); } TEST_F(QuicStreamSequencerTest, TerminateWithReadv) { char buffer[3]; OnFinFrame(3, ""); EXPECT_EQ(3u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get())); EXPECT_FALSE(sequencer_->IsClosed()); EXPECT_CALL(stream_, OnDataAvailable()); OnFrame(0, "abc"); EXPECT_CALL(stream_, AddBytesConsumed(3)); iovec iov = {&buffer[0], 3}; int bytes_read = sequencer_->Readv(&iov, 1); EXPECT_EQ(3, bytes_read); EXPECT_TRUE(sequencer_->IsClosed()); } TEST_F(QuicStreamSequencerTest, MultipleOffsets) { OnFinFrame(3, ""); EXPECT_EQ(3u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get())); EXPECT_CALL(stream_, OnUnrecoverableError( QUIC_STREAM_SEQUENCER_INVALID_STATE, "Stream 1 received new final offset: 1, which is " "different from close offset: 3")); OnFinFrame(1, ""); } class QuicSequencerRandomTest : public QuicStreamSequencerTest { public: using Frame = std::pair<int, std::string>; using FrameList = std::vector<Frame>; void CreateFrames() { int payload_size = ABSL_ARRAYSIZE(kPayload) - 1; int remaining_payload = payload_size; while (remaining_payload != 0) { int size = std::min(OneToN(6), remaining_payload); int index = payload_size - remaining_payload; list_.push_back( std::make_pair(index, std::string(kPayload + index, size))); remaining_payload -= size; } } QuicSequencerRandomTest() { uint64_t seed = QuicRandom::GetInstance()->RandUint64(); QUIC_LOG(INFO) << "**** The current seed is " << seed << " ****"; random_.set_seed(seed); CreateFrames(); } int OneToN(int n) { return random_.RandUint64() % n + 1; } void ReadAvailableData() { char output[ABSL_ARRAYSIZE(kPayload) + 1]; iovec iov; iov.iov_base = output; iov.iov_len = ABSL_ARRAYSIZE(output); int bytes_read = sequencer_->Readv(&iov, 1); EXPECT_NE(0, bytes_read); output_.append(output, bytes_read); } std::string output_; std::string peeked_; SimpleRandom random_; FrameList list_; }; TEST_F(QuicSequencerRandomTest, RandomFramesNoDroppingNoBackup) { EXPECT_CALL(stream_, OnDataAvailable()) .Times(AnyNumber()) .WillRepeatedly( Invoke(this, &QuicSequencerRandomTest::ReadAvailableData)); QuicByteCount total_bytes_consumed = 0; EXPECT_CALL(stream_, AddBytesConsumed(_)) .Times(AnyNumber()) .WillRepeatedly( testing::Invoke([&total_bytes_consumed](QuicByteCount bytes) { total_bytes_consumed += bytes; })); while (!list_.empty()) { int index = OneToN(list_.size()) - 1; QUIC_LOG(ERROR) << "Sending index " << index << " " << list_[index].second; OnFrame(list_[index].first, list_[index].second.data()); list_.erase(list_.begin() + index); } ASSERT_EQ(ABSL_ARRAYSIZE(kPayload) - 1, output_.size()); EXPECT_EQ(kPayload, output_); EXPECT_EQ(ABSL_ARRAYSIZE(kPayload) - 1, total_bytes_consumed); } TEST_F(QuicSequencerRandomTest, RandomFramesNoDroppingBackup) { char buffer[10]; iovec iov[2]; iov[0].iov_base = &buffer[0]; iov[0].iov_len = 5; iov[1].iov_base = &buffer[5]; iov[1].iov_len = 5; EXPECT_CALL(stream_, OnDataAvailable()).Times(AnyNumber()); QuicByteCount total_bytes_consumed = 0; EXPECT_CALL(stream_, AddBytesConsumed(_)) .Times(AnyNumber()) .WillRepeatedly( testing::Invoke([&total_bytes_consumed](QuicByteCount bytes) { total_bytes_consumed += bytes; })); while (output_.size() != ABSL_ARRAYSIZE(kPayload) - 1) { if (!list_.empty() && OneToN(2) == 1) { int index = OneToN(list_.size()) - 1; OnFrame(list_[index].first, list_[index].second.data()); list_.erase(list_.begin() + index); } else { bool has_bytes = sequencer_->HasBytesToRead(); iovec peek_iov[20]; int iovs_peeked = sequencer_->GetReadableRegions(peek_iov, 20); if (has_bytes) { ASSERT_LT(0, iovs_peeked); ASSERT_TRUE(sequencer_->GetReadableRegion(peek_iov)); } else { ASSERT_EQ(0, iovs_peeked); ASSERT_FALSE(sequencer_->GetReadableRegion(peek_iov)); } int total_bytes_to_peek = ABSL_ARRAYSIZE(buffer); for (int i = 0; i < iovs_peeked; ++i) { int bytes_to_peek = std::min<int>(peek_iov[i].iov_len, total_bytes_to_peek); peeked_.append(static_cast<char*>(peek_iov[i].iov_base), bytes_to_peek); total_bytes_to_peek -= bytes_to_peek; if (total_bytes_to_peek == 0) { break; } } int bytes_read = sequencer_->Readv(iov, 2); output_.append(buffer, bytes_read); ASSERT_EQ(output_.size(), peeked_.size()); } } EXPECT_EQ(std::string(kPayload), output_); EXPECT_EQ(std::string(kPayload), peeked_); EXPECT_EQ(ABSL_ARRAYSIZE(kPayload) - 1, total_bytes_consumed); } TEST_F(QuicStreamSequencerTest, MarkConsumed) { InSequence s; EXPECT_CALL(stream_, OnDataAvailable()); OnFrame(0, "abc"); OnFrame(3, "def"); OnFrame(6, "ghi"); EXPECT_EQ(9u, sequencer_->NumBytesBuffered()); std::vector<std::string> expected = {"abcdefghi"}; ASSERT_TRUE(VerifyReadableRegions(expected)); EXPECT_CALL(stream_, AddBytesConsumed(1)); sequencer_->MarkConsumed(1); std::vector<std::string> expected2 = {"bcdefghi"}; ASSERT_TRUE(VerifyReadableRegions(expected2)); EXPECT_EQ(8u, sequencer_->NumBytesBuffered()); EXPECT_CALL(stream_, AddBytesConsumed(2)); sequencer_->MarkConsumed(2); std::vector<std::string> expected3 = {"defghi"}; ASSERT_TRUE(VerifyReadableRegions(expected3)); EXPECT_EQ(6u, sequencer_->NumBytesBuffered()); EXPECT_CALL(stream_, AddBytesConsumed(5)); sequencer_->MarkConsumed(5); std::vector<std::string> expected4{"i"}; ASSERT_TRUE(VerifyReadableRegions(expected4)); EXPECT_EQ(1u, sequencer_->NumBytesBuffered()); } TEST_F(QuicStreamSequencerTest, MarkConsumedError) { EXPECT_CALL(stream_, OnDataAvailable()); OnFrame(0, "abc"); OnFrame(9, "jklmnopqrstuvwxyz"); std::vector<std::string> expected{"abc"}; ASSERT_TRUE(VerifyReadableRegions(expected)); EXPECT_QUIC_BUG( { EXPECT_CALL(stream_, ResetWithError(QuicResetStreamError::FromInternal( QUIC_ERROR_PROCESSING_STREAM))); sequencer_->MarkConsumed(4); }, "Invalid argument to MarkConsumed." " expect to consume: 4, but not enough bytes available."); } TEST_F(QuicStreamSequencerTest, MarkConsumedWithMissingPacket) { InSequence s; EXPECT_CALL(stream_, OnDataAvailable()); OnFrame(0, "abc"); OnFrame(3, "def"); OnFrame(9, "jkl"); std::vector<std::string> expected = {"abcdef"}; ASSERT_TRUE(VerifyReadableRegions(expected)); EXPECT_CALL(stream_, AddBytesConsumed(6)); sequencer_->MarkConsumed(6); } TEST_F(QuicStreamSequencerTest, Move) { InSequence s; EXPECT_CALL(stream_, OnDataAvailable()); OnFrame(0, "abc"); OnFrame(3, "def"); OnFrame(6, "ghi"); EXPECT_EQ(9u, sequencer_->NumBytesBuffered()); std::vector<std::string> expected = {"abcdefghi"}; ASSERT_TRUE(VerifyReadableRegions(expected)); QuicStreamSequencer sequencer2(std::move(*sequencer_)); ASSERT_TRUE(VerifyReadableRegions(sequencer2, expected)); } TEST_F(QuicStreamSequencerTest, OverlappingFramesReceived) { QuicStreamId id = 1; QuicStreamFrame frame1(id, false, 1, absl::string_view("hello")); sequencer_->OnStreamFrame(frame1); QuicStreamFrame frame2(id, false, 2, absl::string_view("hello")); EXPECT_CALL(stream_, OnUnrecoverableError(QUIC_OVERLAPPING_STREAM_DATA, _)) .Times(0); sequencer_->OnStreamFrame(frame2); } TEST_F(QuicStreamSequencerTest, DataAvailableOnOverlappingFrames) { QuicStreamId id = 1; const std::string data(1000, '.'); QuicStreamFrame frame1(id, false, 0, data); EXPECT_CALL(stream_, OnDataAvailable()); sequencer_->OnStreamFrame(frame1); EXPECT_CALL(stream_, AddBytesConsumed(500)); QuicStreamSequencerTest::ConsumeData(500); EXPECT_EQ(500u, sequencer_->NumBytesConsumed()); EXPECT_EQ(500u, sequencer_->NumBytesBuffered()); QuicStreamFrame frame2(id, false, 500, data); EXPECT_CALL(stream_, OnDataAvailable()).Times(0); sequencer_->OnStreamFrame(frame2); EXPECT_CALL(stream_, AddBytesConsumed(1000)); QuicStreamSequencerTest::ConsumeData(1000); EXPECT_EQ(1500u, sequencer_->NumBytesConsumed()); EXPECT_EQ(0u, sequencer_->NumBytesBuffered()); QuicStreamFrame frame3(id, false, 1498, absl::string_view("hello")); EXPECT_CALL(stream_, OnDataAvailable()); sequencer_->OnStreamFrame(frame3); EXPECT_CALL(stream_, AddBytesConsumed(3)); QuicStreamSequencerTest::ConsumeData(3); EXPECT_EQ(1503u, sequencer_->NumBytesConsumed()); EXPECT_EQ(0u, sequencer_->NumBytesBuffered()); QuicStreamFrame frame4(id, false, 1000, absl::string_view("hello")); EXPECT_CALL(stream_, OnDataAvailable()).Times(0); sequencer_->OnStreamFrame(frame4); EXPECT_EQ(1503u, sequencer_->NumBytesConsumed()); EXPECT_EQ(0u, sequencer_->NumBytesBuffered()); } TEST_F(QuicStreamSequencerTest, OnDataAvailableWhenReadableBytesIncrease) { sequencer_->set_level_triggered(true); QuicStreamId id = 1; QuicStreamFrame frame1(id, false, 0, "hello"); EXPECT_CALL(stream_, OnDataAvailable()); sequencer_->OnStreamFrame(frame1); EXPECT_EQ(5u, sequencer_->NumBytesBuffered()); QuicStreamFrame frame2(id, false, 5, " world"); EXPECT_CALL(stream_, OnDataAvailable()); sequencer_->OnStreamFrame(frame2); EXPECT_EQ(11u, sequencer_->NumBytesBuffered()); QuicStreamFrame frame3(id, false, 5, "a"); EXPECT_CALL(stream_, OnDataAvailable()).Times(0); sequencer_->OnStreamFrame(frame3); EXPECT_EQ(11u, sequencer_->NumBytesBuffered()); } TEST_F(QuicStreamSequencerTest, ReadSingleFrame) { EXPECT_CALL(stream_, OnDataAvailable()); OnFrame(0u, "abc"); std::string actual; EXPECT_CALL(stream_, AddBytesConsumed(3)); sequencer_->Read(&actual); EXPECT_EQ("abc", actual); EXPECT_EQ(0u, sequencer_->NumBytesBuffered()); } TEST_F(QuicStreamSequencerTest, ReadMultipleFramesWithMissingFrame) { EXPECT_CALL(stream_, OnDataAvailable()); OnFrame(0u, "abc"); OnFrame(3u, "def"); OnFrame(6u, "ghi"); OnFrame(10u, "xyz"); std::string actual; EXPECT_CALL(stream_, AddBytesConsumed(9)); sequencer_->Read(&actual); EXPECT_EQ("abcdefghi", actual); EXPECT_EQ(3u, sequencer_->NumBytesBuffered()); } TEST_F(QuicStreamSequencerTest, ReadAndAppendToString) { EXPECT_CALL(stream_, OnDataAvailable()); OnFrame(0u, "def"); OnFrame(3u, "ghi"); std::string actual = "abc"; EXPECT_CALL(stream_, AddBytesConsumed(6)); sequencer_->Read(&actual); EXPECT_EQ("abcdefghi", actual); EXPECT_EQ(0u, sequencer_->NumBytesBuffered()); } TEST_F(QuicStreamSequencerTest, StopReading) { EXPECT_CALL(stream_, OnDataAvailable()).Times(0); EXPECT_CALL(stream_, OnFinRead()); EXPECT_CALL(stream_, AddBytesConsumed(0)); sequencer_->StopReading(); EXPECT_CALL(stream_, AddBytesConsumed(3)); OnFrame(0u, "abc"); EXPECT_CALL(stream_, AddBytesConsumed(3)); OnFrame(3u, "def"); EXPECT_CALL(stream_, AddBytesConsumed(3)); OnFinFrame(6u, "ghi"); } TEST_F(QuicStreamSequencerTest, StopReadingWithLevelTriggered) { EXPECT_CALL(stream_, AddBytesConsumed(0)); EXPECT_CALL(stream_, AddBytesConsumed(3)).Times(3); EXPECT_CALL(stream_, OnDataAvailable()).Times(0); EXPECT_CALL(stream_, OnFinRead()); sequencer_->set_level_triggered(true); sequencer_->StopReading(); OnFrame(0u, "abc"); OnFrame(3u, "def"); OnFinFrame(6u, "ghi"); } TEST_F(QuicStreamSequencerTest, CorruptFinFrames) { EXPECT_CALL(stream_, OnUnrecoverableError( QUIC_STREAM_SEQUENCER_INVALID_STATE, "Stream 1 received new final offset: 1, which is " "different from close offset: 2")); OnFinFrame(2u, ""); OnFinFrame(0u, "a"); EXPECT_FALSE(sequencer_->HasBytesToRead()); } TEST_F(QuicStreamSequencerTest, ReceiveFinLessThanHighestOffset) { EXPECT_CALL(stream_, OnDataAvailable()).Times(1); EXPECT_CALL(stream_, OnUnrecoverableError( QUIC_STREAM_SEQUENCER_INVALID_STATE, "Stream 1 received fin with offset: 0, which " "reduces current highest offset: 3")); OnFrame(0u, "abc"); OnFinFrame(0u, ""); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_stream_sequencer.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_stream_sequencer_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
bf439647-1c08-4d9d-aff6-6426f3038b19
cpp
google/quiche
quic_version_manager
quiche/quic/core/quic_version_manager.cc
quiche/quic/core/quic_version_manager_test.cc
#include "quiche/quic/core/quic_version_manager.h" #include <algorithm> #include <string> #include <utility> #include <vector> #include "absl/base/macros.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" namespace quic { QuicVersionManager::QuicVersionManager( ParsedQuicVersionVector supported_versions) : allowed_supported_versions_(std::move(supported_versions)) {} QuicVersionManager::~QuicVersionManager() {} const ParsedQuicVersionVector& QuicVersionManager::GetSupportedVersions() { MaybeRefilterSupportedVersions(); return filtered_supported_versions_; } const ParsedQuicVersionVector& QuicVersionManager::GetSupportedVersionsWithOnlyHttp3() { MaybeRefilterSupportedVersions(); return filtered_supported_versions_with_http3_; } const std::vector<std::string>& QuicVersionManager::GetSupportedAlpns() { MaybeRefilterSupportedVersions(); return filtered_supported_alpns_; } void QuicVersionManager::MaybeRefilterSupportedVersions() { static_assert(SupportedVersions().size() == 4u, "Supported versions out of sync"); if (enable_version_2_draft_08_ != GetQuicReloadableFlag(quic_enable_version_rfcv2) || disable_version_rfcv1_ != GetQuicReloadableFlag(quic_disable_version_rfcv1) || disable_version_draft_29_ != GetQuicReloadableFlag(quic_disable_version_draft_29) || disable_version_q046_ != GetQuicReloadableFlag(quic_disable_version_q046)) { enable_version_2_draft_08_ = GetQuicReloadableFlag(quic_enable_version_rfcv2); disable_version_rfcv1_ = GetQuicReloadableFlag(quic_disable_version_rfcv1); disable_version_draft_29_ = GetQuicReloadableFlag(quic_disable_version_draft_29); disable_version_q046_ = GetQuicReloadableFlag(quic_disable_version_q046); RefilterSupportedVersions(); } } void QuicVersionManager::RefilterSupportedVersions() { filtered_supported_versions_ = FilterSupportedVersions(allowed_supported_versions_); filtered_supported_versions_with_http3_.clear(); filtered_transport_versions_.clear(); filtered_supported_alpns_.clear(); for (const ParsedQuicVersion& version : filtered_supported_versions_) { auto transport_version = version.transport_version; if (std::find(filtered_transport_versions_.begin(), filtered_transport_versions_.end(), transport_version) == filtered_transport_versions_.end()) { filtered_transport_versions_.push_back(transport_version); } if (version.UsesHttp3()) { filtered_supported_versions_with_http3_.push_back(version); } if (std::find(filtered_supported_alpns_.begin(), filtered_supported_alpns_.end(), AlpnForVersion(version)) == filtered_supported_alpns_.end()) { filtered_supported_alpns_.emplace_back(AlpnForVersion(version)); } } } void QuicVersionManager::AddCustomAlpn(const std::string& alpn) { filtered_supported_alpns_.push_back(alpn); } }
#include "quiche/quic/core/quic_version_manager.h" #include "absl/base/macros.h" #include "quiche/quic/core/quic_versions.h" #include "quiche/quic/platform/api/quic_flags.h" #include "quiche/quic/platform/api/quic_test.h" using ::testing::ElementsAre; namespace quic { namespace test { namespace { class QuicVersionManagerTest : public QuicTest {}; TEST_F(QuicVersionManagerTest, QuicVersionManager) { static_assert(SupportedVersions().size() == 4u, "Supported versions out of sync"); for (const ParsedQuicVersion& version : AllSupportedVersions()) { QuicEnableVersion(version); } QuicDisableVersion(ParsedQuicVersion::RFCv2()); QuicDisableVersion(ParsedQuicVersion::RFCv1()); QuicDisableVersion(ParsedQuicVersion::Draft29()); QuicVersionManager manager(AllSupportedVersions()); ParsedQuicVersionVector expected_parsed_versions; expected_parsed_versions.push_back(ParsedQuicVersion::Q046()); EXPECT_EQ(expected_parsed_versions, manager.GetSupportedVersions()); EXPECT_EQ(FilterSupportedVersions(AllSupportedVersions()), manager.GetSupportedVersions()); EXPECT_TRUE(manager.GetSupportedVersionsWithOnlyHttp3().empty()); EXPECT_THAT(manager.GetSupportedAlpns(), ElementsAre("h3-Q046")); QuicEnableVersion(ParsedQuicVersion::Draft29()); expected_parsed_versions.insert(expected_parsed_versions.begin(), ParsedQuicVersion::Draft29()); EXPECT_EQ(expected_parsed_versions, manager.GetSupportedVersions()); EXPECT_EQ(FilterSupportedVersions(AllSupportedVersions()), manager.GetSupportedVersions()); EXPECT_EQ(1u, manager.GetSupportedVersionsWithOnlyHttp3().size()); EXPECT_EQ(CurrentSupportedHttp3Versions(), manager.GetSupportedVersionsWithOnlyHttp3()); EXPECT_THAT(manager.GetSupportedAlpns(), ElementsAre("h3-29", "h3-Q046")); QuicEnableVersion(ParsedQuicVersion::RFCv1()); expected_parsed_versions.insert(expected_parsed_versions.begin(), ParsedQuicVersion::RFCv1()); EXPECT_EQ(expected_parsed_versions, manager.GetSupportedVersions()); EXPECT_EQ(FilterSupportedVersions(AllSupportedVersions()), manager.GetSupportedVersions()); EXPECT_EQ(2u, manager.GetSupportedVersionsWithOnlyHttp3().size()); EXPECT_EQ(CurrentSupportedHttp3Versions(), manager.GetSupportedVersionsWithOnlyHttp3()); EXPECT_THAT(manager.GetSupportedAlpns(), ElementsAre("h3", "h3-29", "h3-Q046")); QuicEnableVersion(ParsedQuicVersion::RFCv2()); expected_parsed_versions.insert(expected_parsed_versions.begin(), ParsedQuicVersion::RFCv2()); EXPECT_EQ(expected_parsed_versions, manager.GetSupportedVersions()); EXPECT_EQ(FilterSupportedVersions(AllSupportedVersions()), manager.GetSupportedVersions()); EXPECT_EQ(3u, manager.GetSupportedVersionsWithOnlyHttp3().size()); EXPECT_EQ(CurrentSupportedHttp3Versions(), manager.GetSupportedVersionsWithOnlyHttp3()); EXPECT_THAT(manager.GetSupportedAlpns(), ElementsAre("h3", "h3-29", "h3-Q046")); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_version_manager.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_version_manager_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6
2da281b4-baf2-4267-a38d-367ed6515e9a
cpp
google/quiche
quic_control_frame_manager
quiche/quic/core/quic_control_frame_manager.cc
quiche/quic/core/quic_control_frame_manager_test.cc
#include "quiche/quic/core/quic_control_frame_manager.h" #include <string> #include "absl/strings/str_cat.h" #include "quiche/quic/core/frames/quic_ack_frequency_frame.h" #include "quiche/quic/core/frames/quic_frame.h" #include "quiche/quic/core/frames/quic_new_connection_id_frame.h" #include "quiche/quic/core/frames/quic_retire_connection_id_frame.h" #include "quiche/quic/core/quic_constants.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_bug_tracker.h" #include "quiche/quic/platform/api/quic_flag_utils.h" #include "quiche/quic/platform/api/quic_flags.h" namespace quic { namespace { const size_t kMaxNumControlFrames = 1000; } QuicControlFrameManager::QuicControlFrameManager(QuicSession* session) : last_control_frame_id_(kInvalidControlFrameId), least_unacked_(1), least_unsent_(1), delegate_(session), num_buffered_max_stream_frames_(0) {} QuicControlFrameManager::~QuicControlFrameManager() { while (!control_frames_.empty()) { DeleteFrame(&control_frames_.front()); control_frames_.pop_front(); } } void QuicControlFrameManager::WriteOrBufferQuicFrame(QuicFrame frame) { const bool had_buffered_frames = HasBufferedFrames(); control_frames_.emplace_back(frame); if (control_frames_.size() > kMaxNumControlFrames) { delegate_->OnControlFrameManagerError( QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, absl::StrCat("More than ", kMaxNumControlFrames, "buffered control frames, least_unacked: ", least_unacked_, ", least_unsent_: ", least_unsent_)); return; } if (had_buffered_frames) { return; } WriteBufferedFrames(); } void QuicControlFrameManager::WriteOrBufferRstStream( QuicStreamId id, QuicResetStreamError error, QuicStreamOffset bytes_written) { QUIC_DVLOG(1) << "Writing RST_STREAM_FRAME"; WriteOrBufferQuicFrame((QuicFrame(new QuicRstStreamFrame( ++last_control_frame_id_, id, error, bytes_written)))); } void QuicControlFrameManager::WriteOrBufferGoAway( QuicErrorCode error, QuicStreamId last_good_stream_id, const std::string& reason) { QUIC_DVLOG(1) << "Writing GOAWAY_FRAME"; WriteOrBufferQuicFrame(QuicFrame(new QuicGoAwayFrame( ++last_control_frame_id_, error, last_good_stream_id, reason))); } void QuicControlFrameManager::WriteOrBufferWindowUpdate( QuicStreamId id, QuicStreamOffset byte_offset) { QUIC_DVLOG(1) << "Writing WINDOW_UPDATE_FRAME"; WriteOrBufferQuicFrame(QuicFrame( QuicWindowUpdateFrame(++last_control_frame_id_, id, byte_offset))); } void QuicControlFrameManager::WriteOrBufferBlocked( QuicStreamId id, QuicStreamOffset byte_offset) { QUIC_DVLOG(1) << "Writing BLOCKED_FRAME"; WriteOrBufferQuicFrame( QuicFrame(QuicBlockedFrame(++last_control_frame_id_, id, byte_offset))); } void QuicControlFrameManager::WriteOrBufferStreamsBlocked(QuicStreamCount count, bool unidirectional) { QUIC_DVLOG(1) << "Writing STREAMS_BLOCKED Frame"; QUIC_CODE_COUNT(quic_streams_blocked_transmits); WriteOrBufferQuicFrame(QuicFrame(QuicStreamsBlockedFrame( ++last_control_frame_id_, count, unidirectional))); } void QuicControlFrameManager::WriteOrBufferMaxStreams(QuicStreamCount count, bool unidirectional) { QUIC_DVLOG(1) << "Writing MAX_STREAMS Frame"; QUIC_CODE_COUNT(quic_max_streams_transmits); WriteOrBufferQuicFrame(QuicFrame( QuicMaxStreamsFrame(++last_control_frame_id_, count, unidirectional))); ++num_buffered_max_stream_frames_; } void QuicControlFrameManager::WriteOrBufferStopSending( QuicResetStreamError error, QuicStreamId stream_id) { QUIC_DVLOG(1) << "Writing STOP_SENDING_FRAME"; WriteOrBufferQuicFrame(QuicFrame( QuicStopSendingFrame(++last_control_frame_id_, stream_id, error))); } void QuicControlFrameManager::WriteOrBufferHandshakeDone() { QUIC_DVLOG(1) << "Writing HANDSHAKE_DONE"; WriteOrBufferQuicFrame( QuicFrame(QuicHandshakeDoneFrame(++last_control_frame_id_))); } void QuicControlFrameManager::WriteOrBufferAckFrequency( const QuicAckFrequencyFrame& ack_frequency_frame) { QUIC_DVLOG(1) << "Writing ACK_FREQUENCY frame"; QuicControlFrameId control_frame_id = ++last_control_frame_id_; WriteOrBufferQuicFrame( QuicFrame(new QuicAckFrequencyFrame(control_frame_id, control_frame_id, ack_frequency_frame.packet_tolerance, ack_frequency_frame.max_ack_delay))); } void QuicControlFrameManager::WriteOrBufferNewConnectionId( const QuicConnectionId& connection_id, uint64_t sequence_number, uint64_t retire_prior_to, const StatelessResetToken& stateless_reset_token) { QUIC_DVLOG(1) << "Writing NEW_CONNECTION_ID frame"; WriteOrBufferQuicFrame(QuicFrame(new QuicNewConnectionIdFrame( ++last_control_frame_id_, connection_id, sequence_number, stateless_reset_token, retire_prior_to))); } void QuicControlFrameManager::WriteOrBufferRetireConnectionId( uint64_t sequence_number) { QUIC_DVLOG(1) << "Writing RETIRE_CONNECTION_ID frame"; WriteOrBufferQuicFrame(QuicFrame(new QuicRetireConnectionIdFrame( ++last_control_frame_id_, sequence_number))); } void QuicControlFrameManager::WriteOrBufferNewToken(absl::string_view token) { QUIC_DVLOG(1) << "Writing NEW_TOKEN frame"; WriteOrBufferQuicFrame( QuicFrame(new QuicNewTokenFrame(++last_control_frame_id_, token))); } void QuicControlFrameManager::OnControlFrameSent(const QuicFrame& frame) { QuicControlFrameId id = GetControlFrameId(frame); if (id == kInvalidControlFrameId) { QUIC_BUG(quic_bug_12727_1) << "Send or retransmit a control frame with invalid control frame id"; return; } if (frame.type == WINDOW_UPDATE_FRAME) { QuicStreamId stream_id = frame.window_update_frame.stream_id; if (window_update_frames_.contains(stream_id) && id > window_update_frames_[stream_id]) { OnControlFrameIdAcked(window_update_frames_[stream_id]); } window_update_frames_[stream_id] = id; } if (pending_retransmissions_.contains(id)) { pending_retransmissions_.erase(id); return; } if (id > least_unsent_) { QUIC_BUG(quic_bug_10517_1) << "Try to send control frames out of order, id: " << id << " least_unsent: " << least_unsent_; delegate_->OnControlFrameManagerError( QUIC_INTERNAL_ERROR, "Try to send control frames out of order"); return; } ++least_unsent_; } bool QuicControlFrameManager::OnControlFrameAcked(const QuicFrame& frame) { QuicControlFrameId id = GetControlFrameId(frame); if (!OnControlFrameIdAcked(id)) { return false; } if (frame.type == WINDOW_UPDATE_FRAME) { QuicStreamId stream_id = frame.window_update_frame.stream_id; if (window_update_frames_.contains(stream_id) && window_update_frames_[stream_id] == id) { window_update_frames_.erase(stream_id); } } if (frame.type == MAX_STREAMS_FRAME) { if (num_buffered_max_stream_frames_ == 0) { QUIC_BUG(invalid_num_buffered_max_stream_frames); } else { --num_buffered_max_stream_frames_; } } return true; } void QuicControlFrameManager::OnControlFrameLost(const QuicFrame& frame) { QuicControlFrameId id = GetControlFrameId(frame); if (id == kInvalidControlFrameId) { return; } if (id >= least_unsent_) { QUIC_BUG(quic_bug_10517_2) << "Try to mark unsent control frame as lost"; delegate_->OnControlFrameManagerError( QUIC_INTERNAL_ERROR, "Try to mark unsent control frame as lost"); return; } if (id < least_unacked_ || GetControlFrameId(control_frames_.at(id - least_unacked_)) == kInvalidControlFrameId) { return; } if (!pending_retransmissions_.contains(id)) { pending_retransmissions_[id] = true; QUIC_BUG_IF(quic_bug_12727_2, pending_retransmissions_.size() > control_frames_.size()) << "least_unacked_: " << least_unacked_ << ", least_unsent_: " << least_unsent_; } } bool QuicControlFrameManager::IsControlFrameOutstanding( const QuicFrame& frame) const { QuicControlFrameId id = GetControlFrameId(frame); if (id == kInvalidControlFrameId) { return false; } return id < least_unacked_ + control_frames_.size() && id >= least_unacked_ && GetControlFrameId(control_frames_.at(id - least_unacked_)) != kInvalidControlFrameId; } bool QuicControlFrameManager::HasPendingRetransmission() const { return !pending_retransmissions_.empty(); } bool QuicControlFrameManager::WillingToWrite() const { return HasPendingRetransmission() || HasBufferedFrames(); } size_t QuicControlFrameManager::NumBufferedMaxStreams() const { return num_buffered_max_stream_frames_; } QuicFrame QuicControlFrameManager::NextPendingRetransmission() const { QUIC_BUG_IF(quic_bug_12727_3, pending_retransmissions_.empty()) << "Unexpected call to NextPendingRetransmission() with empty pending " << "retransmission list."; QuicControlFrameId id = pending_retransmissions_.begin()->first; return control_frames_.at(id - least_unacked_); } void QuicControlFrameManager::OnCanWrite() { if (HasPendingRetransmission()) { WritePendingRetransmission(); return; } WriteBufferedFrames(); } bool QuicControlFrameManager::RetransmitControlFrame(const QuicFrame& frame, TransmissionType type) { QUICHE_DCHECK(type == PTO_RETRANSMISSION); QuicControlFrameId id = GetControlFrameId(frame); if (id == kInvalidControlFrameId) { return true; } if (id >= least_unsent_) { QUIC_BUG(quic_bug_10517_3) << "Try to retransmit unsent control frame"; delegate_->OnControlFrameManagerError( QUIC_INTERNAL_ERROR, "Try to retransmit unsent control frame"); return false; } if (id < least_unacked_ || GetControlFrameId(control_frames_.at(id - least_unacked_)) == kInvalidControlFrameId) { return true; } QuicFrame copy = CopyRetransmittableControlFrame(frame); QUIC_DVLOG(1) << "control frame manager is forced to retransmit frame: " << frame; if (delegate_->WriteControlFrame(copy, type)) { return true; } DeleteFrame(&copy); return false; } void QuicControlFrameManager::WriteBufferedFrames() { while (HasBufferedFrames()) { QuicFrame frame_to_send = control_frames_.at(least_unsent_ - least_unacked_); QuicFrame copy = CopyRetransmittableControlFrame(frame_to_send); if (!delegate_->WriteControlFrame(copy, NOT_RETRANSMISSION)) { DeleteFrame(&copy); break; } OnControlFrameSent(frame_to_send); } } void QuicControlFrameManager::WritePendingRetransmission() { while (HasPendingRetransmission()) { QuicFrame pending = NextPendingRetransmission(); QuicFrame copy = CopyRetransmittableControlFrame(pending); if (!delegate_->WriteControlFrame(copy, LOSS_RETRANSMISSION)) { DeleteFrame(&copy); break; } OnControlFrameSent(pending); } } bool QuicControlFrameManager::OnControlFrameIdAcked(QuicControlFrameId id) { if (id == kInvalidControlFrameId) { return false; } if (id >= least_unsent_) { QUIC_BUG(quic_bug_10517_4) << "Try to ack unsent control frame"; delegate_->OnControlFrameManagerError(QUIC_INTERNAL_ERROR, "Try to ack unsent control frame"); return false; } if (id < least_unacked_ || GetControlFrameId(control_frames_.at(id - least_unacked_)) == kInvalidControlFrameId) { return false; } SetControlFrameId(kInvalidControlFrameId, &control_frames_.at(id - least_unacked_)); pending_retransmissions_.erase(id); while (!control_frames_.empty() && GetControlFrameId(control_frames_.front()) == kInvalidControlFrameId) { DeleteFrame(&control_frames_.front()); control_frames_.pop_front(); ++least_unacked_; } return true; } bool QuicControlFrameManager::HasBufferedFrames() const { return least_unsent_ < least_unacked_ + control_frames_.size(); } }
#include "quiche/quic/core/quic_control_frame_manager.h" #include <memory> #include <utility> #include <vector> #include "quiche/quic/core/crypto/null_encrypter.h" #include "quiche/quic/core/frames/quic_ack_frequency_frame.h" #include "quiche/quic/core/frames/quic_retire_connection_id_frame.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_test_utils.h" using testing::_; using testing::InSequence; using testing::Invoke; using testing::Return; using testing::StrictMock; namespace quic { namespace test { class QuicControlFrameManagerPeer { public: static size_t QueueSize(QuicControlFrameManager* manager) { return manager->control_frames_.size(); } }; namespace { const QuicStreamId kTestStreamId = 5; const QuicRstStreamErrorCode kTestStopSendingCode = QUIC_STREAM_ENCODER_STREAM_ERROR; class QuicControlFrameManagerTest : public QuicTest { public: QuicControlFrameManagerTest() : connection_(new MockQuicConnection(&helper_, &alarm_factory_, Perspective::IS_SERVER)), session_(std::make_unique<StrictMock<MockQuicSession>>(connection_)), manager_(std::make_unique<QuicControlFrameManager>(session_.get())) { connection_->SetEncrypter( ENCRYPTION_FORWARD_SECURE, std::make_unique<NullEncrypter>(connection_->perspective())); } protected: MockQuicConnectionHelper helper_; MockAlarmFactory alarm_factory_; MockQuicConnection* connection_; std::unique_ptr<StrictMock<MockQuicSession>> session_; std::unique_ptr<QuicControlFrameManager> manager_; }; TEST_F(QuicControlFrameManagerTest, InitialState) { EXPECT_EQ(0u, QuicControlFrameManagerPeer::QueueSize(manager_.get())); EXPECT_FALSE(manager_->HasPendingRetransmission()); EXPECT_FALSE(manager_->WillingToWrite()); } TEST_F(QuicControlFrameManagerTest, WriteOrBufferRstStream) { QuicRstStreamFrame rst_stream = {1, kTestStreamId, QUIC_STREAM_CANCELLED, 0}; EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke( [&rst_stream](const QuicFrame& frame, TransmissionType ) { EXPECT_EQ(RST_STREAM_FRAME, frame.type); EXPECT_EQ(rst_stream, *frame.rst_stream_frame); ClearControlFrame(frame); return true; })); manager_->WriteOrBufferRstStream( rst_stream.stream_id, QuicResetStreamError::FromInternal(rst_stream.error_code), rst_stream.byte_offset); EXPECT_EQ(1, QuicControlFrameManagerPeer::QueueSize(manager_.get())); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(&rst_stream))); EXPECT_FALSE(manager_->WillingToWrite()); } TEST_F(QuicControlFrameManagerTest, WriteOrBufferGoAway) { QuicGoAwayFrame goaway = {1, QUIC_PEER_GOING_AWAY, kTestStreamId, "Going away."}; EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce( Invoke([&goaway](const QuicFrame& frame, TransmissionType ) { EXPECT_EQ(GOAWAY_FRAME, frame.type); EXPECT_EQ(goaway, *frame.goaway_frame); ClearControlFrame(frame); return true; })); manager_->WriteOrBufferGoAway(goaway.error_code, goaway.last_good_stream_id, goaway.reason_phrase); EXPECT_EQ(1, QuicControlFrameManagerPeer::QueueSize(manager_.get())); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(&goaway))); EXPECT_FALSE(manager_->WillingToWrite()); } TEST_F(QuicControlFrameManagerTest, WriteOrBufferWindowUpdate) { QuicWindowUpdateFrame window_update = {1, kTestStreamId, 100}; EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke( [&window_update](const QuicFrame& frame, TransmissionType ) { EXPECT_EQ(WINDOW_UPDATE_FRAME, frame.type); EXPECT_EQ(window_update, frame.window_update_frame); ClearControlFrame(frame); return true; })); manager_->WriteOrBufferWindowUpdate(window_update.stream_id, window_update.max_data); EXPECT_EQ(1, QuicControlFrameManagerPeer::QueueSize(manager_.get())); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(window_update))); EXPECT_FALSE(manager_->WillingToWrite()); } TEST_F(QuicControlFrameManagerTest, WriteOrBufferBlocked) { QuicBlockedFrame blocked = {1, kTestStreamId, 10}; EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce( Invoke([&blocked](const QuicFrame& frame, TransmissionType ) { EXPECT_EQ(BLOCKED_FRAME, frame.type); EXPECT_EQ(blocked, frame.blocked_frame); ClearControlFrame(frame); return true; })); manager_->WriteOrBufferBlocked(blocked.stream_id, blocked.offset); EXPECT_EQ(1, QuicControlFrameManagerPeer::QueueSize(manager_.get())); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(blocked))); EXPECT_FALSE(manager_->WillingToWrite()); } TEST_F(QuicControlFrameManagerTest, WriteOrBufferStopSending) { QuicStopSendingFrame stop_sending = {1, kTestStreamId, kTestStopSendingCode}; EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke( [&stop_sending](const QuicFrame& frame, TransmissionType ) { EXPECT_EQ(STOP_SENDING_FRAME, frame.type); EXPECT_EQ(stop_sending, frame.stop_sending_frame); ClearControlFrame(frame); return true; })); manager_->WriteOrBufferStopSending( QuicResetStreamError::FromInternal(stop_sending.error_code), stop_sending.stream_id); EXPECT_EQ(1, QuicControlFrameManagerPeer::QueueSize(manager_.get())); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(stop_sending))); EXPECT_FALSE(manager_->WillingToWrite()); } TEST_F(QuicControlFrameManagerTest, BufferWhenWriteControlFrameReturnsFalse) { QuicBlockedFrame blocked = {1, kTestStreamId, 0}; EXPECT_CALL(*session_, WriteControlFrame(_, _)).WillOnce(Return(false)); manager_->WriteOrBufferBlocked(blocked.stream_id, blocked.offset); EXPECT_TRUE(manager_->WillingToWrite()); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(blocked))); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke(&ClearControlFrameWithTransmissionType)); manager_->OnCanWrite(); EXPECT_FALSE(manager_->WillingToWrite()); } TEST_F(QuicControlFrameManagerTest, BufferThenSendThenBuffer) { InSequence s; QuicBlockedFrame frame1 = {1, kTestStreamId, 0}; QuicBlockedFrame frame2 = {2, kTestStreamId + 1, 1}; EXPECT_CALL(*session_, WriteControlFrame(_, _)).WillOnce(Return(false)); manager_->WriteOrBufferBlocked(frame1.stream_id, frame1.offset); manager_->WriteOrBufferBlocked(frame2.stream_id, frame2.offset); EXPECT_TRUE(manager_->WillingToWrite()); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(frame1))); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(frame2))); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke(&ClearControlFrameWithTransmissionType)); EXPECT_CALL(*session_, WriteControlFrame(_, _)).WillOnce(Return(false)); manager_->OnCanWrite(); EXPECT_TRUE(manager_->WillingToWrite()); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke(&ClearControlFrameWithTransmissionType)); manager_->OnCanWrite(); EXPECT_FALSE(manager_->WillingToWrite()); } TEST_F(QuicControlFrameManagerTest, OnControlFrameAcked) { QuicRstStreamFrame frame1 = {1, kTestStreamId, QUIC_STREAM_CANCELLED, 0}; QuicGoAwayFrame frame2 = {2, QUIC_PEER_GOING_AWAY, kTestStreamId, "Going away."}; QuicWindowUpdateFrame frame3 = {3, kTestStreamId, 100}; QuicBlockedFrame frame4 = {4, kTestStreamId, 0}; QuicStopSendingFrame frame5 = {5, kTestStreamId, kTestStopSendingCode}; InSequence s; EXPECT_CALL(*session_, WriteControlFrame(_, _)) .Times(5) .WillRepeatedly(Invoke(&ClearControlFrameWithTransmissionType)); manager_->WriteOrBufferRstStream( frame1.stream_id, QuicResetStreamError::FromInternal(frame1.error_code), frame1.byte_offset); manager_->WriteOrBufferGoAway(frame2.error_code, frame2.last_good_stream_id, frame2.reason_phrase); manager_->WriteOrBufferWindowUpdate(frame3.stream_id, frame3.max_data); manager_->WriteOrBufferBlocked(frame4.stream_id, frame4.offset); manager_->WriteOrBufferStopSending( QuicResetStreamError::FromInternal(frame5.error_code), frame5.stream_id); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(&frame1))); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(&frame2))); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(frame3))); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(frame4))); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(frame5))); EXPECT_FALSE(manager_->HasPendingRetransmission()); EXPECT_TRUE(manager_->OnControlFrameAcked(QuicFrame(frame3))); EXPECT_FALSE(manager_->IsControlFrameOutstanding(QuicFrame(frame3))); EXPECT_EQ(5, QuicControlFrameManagerPeer::QueueSize(manager_.get())); EXPECT_TRUE(manager_->OnControlFrameAcked(QuicFrame(&frame2))); EXPECT_FALSE(manager_->IsControlFrameOutstanding(QuicFrame(&frame2))); EXPECT_EQ(5, QuicControlFrameManagerPeer::QueueSize(manager_.get())); EXPECT_TRUE(manager_->OnControlFrameAcked(QuicFrame(&frame1))); EXPECT_FALSE(manager_->IsControlFrameOutstanding(QuicFrame(&frame1))); EXPECT_EQ(2, QuicControlFrameManagerPeer::QueueSize(manager_.get())); EXPECT_FALSE(manager_->OnControlFrameAcked(QuicFrame(&frame2))); EXPECT_FALSE(manager_->IsControlFrameOutstanding(QuicFrame(&frame1))); EXPECT_EQ(2, QuicControlFrameManagerPeer::QueueSize(manager_.get())); EXPECT_TRUE(manager_->OnControlFrameAcked(QuicFrame(frame4))); EXPECT_FALSE(manager_->IsControlFrameOutstanding(QuicFrame(frame4))); EXPECT_EQ(1, QuicControlFrameManagerPeer::QueueSize(manager_.get())); EXPECT_TRUE(manager_->OnControlFrameAcked(QuicFrame(frame5))); EXPECT_FALSE(manager_->IsControlFrameOutstanding(QuicFrame(frame5))); EXPECT_EQ(0, QuicControlFrameManagerPeer::QueueSize(manager_.get())); } TEST_F(QuicControlFrameManagerTest, OnControlFrameLost) { QuicRstStreamFrame frame1 = {1, kTestStreamId, QUIC_STREAM_CANCELLED, 0}; QuicGoAwayFrame frame2 = {2, QUIC_PEER_GOING_AWAY, kTestStreamId, "Going away."}; QuicWindowUpdateFrame frame3 = {3, kTestStreamId, 100}; QuicBlockedFrame frame4 = {4, kTestStreamId, 0}; QuicStopSendingFrame frame5 = {5, kTestStreamId, kTestStopSendingCode}; InSequence s; EXPECT_CALL(*session_, WriteControlFrame(_, _)) .Times(3) .WillRepeatedly(Invoke(&ClearControlFrameWithTransmissionType)); manager_->WriteOrBufferRstStream( frame1.stream_id, QuicResetStreamError::FromInternal(frame1.error_code), frame1.byte_offset); manager_->WriteOrBufferGoAway(frame2.error_code, frame2.last_good_stream_id, frame2.reason_phrase); manager_->WriteOrBufferWindowUpdate(frame3.stream_id, frame3.max_data); EXPECT_CALL(*session_, WriteControlFrame(_, _)).WillOnce(Return(false)); manager_->WriteOrBufferBlocked(frame4.stream_id, frame4.offset); manager_->WriteOrBufferStopSending( QuicResetStreamError::FromInternal(frame5.error_code), frame5.stream_id); manager_->OnControlFrameLost(QuicFrame(&frame1)); manager_->OnControlFrameLost(QuicFrame(&frame2)); manager_->OnControlFrameLost(QuicFrame(frame3)); EXPECT_TRUE(manager_->HasPendingRetransmission()); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(&frame1))); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(&frame2))); EXPECT_TRUE(manager_->IsControlFrameOutstanding(QuicFrame(frame3))); manager_->OnControlFrameAcked(QuicFrame(&frame2)); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce( Invoke([&frame1](const QuicFrame& frame, TransmissionType ) { EXPECT_EQ(RST_STREAM_FRAME, frame.type); EXPECT_EQ(frame1, *frame.rst_stream_frame); ClearControlFrame(frame); return true; })); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce( Invoke([&frame3](const QuicFrame& frame, TransmissionType ) { EXPECT_EQ(WINDOW_UPDATE_FRAME, frame.type); EXPECT_EQ(frame3, frame.window_update_frame); ClearControlFrame(frame); return true; })); manager_->OnCanWrite(); EXPECT_FALSE(manager_->HasPendingRetransmission()); EXPECT_TRUE(manager_->WillingToWrite()); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce( Invoke([&frame4](const QuicFrame& frame, TransmissionType ) { EXPECT_EQ(BLOCKED_FRAME, frame.type); EXPECT_EQ(frame4, frame.blocked_frame); ClearControlFrame(frame); return true; })); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce( Invoke([&frame5](const QuicFrame& frame, TransmissionType ) { EXPECT_EQ(STOP_SENDING_FRAME, frame.type); EXPECT_EQ(frame5, frame.stop_sending_frame); ClearControlFrame(frame); return true; })); manager_->OnCanWrite(); EXPECT_FALSE(manager_->WillingToWrite()); } TEST_F(QuicControlFrameManagerTest, RetransmitControlFrame) { QuicRstStreamFrame frame1 = {1, kTestStreamId, QUIC_STREAM_CANCELLED, 0}; QuicGoAwayFrame frame2 = {2, QUIC_PEER_GOING_AWAY, kTestStreamId, "Going away."}; QuicWindowUpdateFrame frame3 = {3, kTestStreamId, 100}; QuicBlockedFrame frame4 = {4, kTestStreamId, 0}; InSequence s; EXPECT_CALL(*session_, WriteControlFrame(_, _)) .Times(4) .WillRepeatedly(Invoke(&ClearControlFrameWithTransmissionType)); manager_->WriteOrBufferRstStream( frame1.stream_id, QuicResetStreamError::FromInternal(frame1.error_code), frame1.byte_offset); manager_->WriteOrBufferGoAway(frame2.error_code, frame2.last_good_stream_id, frame2.reason_phrase); manager_->WriteOrBufferWindowUpdate(frame3.stream_id, frame3.max_data); manager_->WriteOrBufferBlocked(frame4.stream_id, frame4.offset); manager_->OnControlFrameAcked(QuicFrame(&frame2)); EXPECT_CALL(*session_, WriteControlFrame(_, _)).Times(0); EXPECT_TRUE( manager_->RetransmitControlFrame(QuicFrame(&frame2), PTO_RETRANSMISSION)); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce( Invoke([&frame3](const QuicFrame& frame, TransmissionType ) { EXPECT_EQ(WINDOW_UPDATE_FRAME, frame.type); EXPECT_EQ(frame3, frame.window_update_frame); ClearControlFrame(frame); return true; })); EXPECT_TRUE( manager_->RetransmitControlFrame(QuicFrame(frame3), PTO_RETRANSMISSION)); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce( Invoke([&frame4](const QuicFrame& frame, TransmissionType ) { EXPECT_EQ(BLOCKED_FRAME, frame.type); EXPECT_EQ(frame4, frame.blocked_frame); return false; })); EXPECT_FALSE( manager_->RetransmitControlFrame(QuicFrame(frame4), PTO_RETRANSMISSION)); } TEST_F(QuicControlFrameManagerTest, SendAndAckAckFrequencyFrame) { QuicAckFrequencyFrame frame_to_send; frame_to_send.packet_tolerance = 10; frame_to_send.max_ack_delay = QuicTime::Delta::FromMilliseconds(24); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke(&ClearControlFrameWithTransmissionType)); manager_->WriteOrBufferAckFrequency(frame_to_send); QuicAckFrequencyFrame expected_ack_frequency = frame_to_send; expected_ack_frequency.control_frame_id = 1; expected_ack_frequency.sequence_number = 1; EXPECT_TRUE( manager_->OnControlFrameAcked(QuicFrame(&expected_ack_frequency))); } TEST_F(QuicControlFrameManagerTest, NewAndRetireConnectionIdFrames) { EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke(&ClearControlFrameWithTransmissionType)); QuicNewConnectionIdFrame new_connection_id_frame( 1, TestConnectionId(3), 1, {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1}, 1); manager_->WriteOrBufferNewConnectionId( new_connection_id_frame.connection_id, new_connection_id_frame.sequence_number, new_connection_id_frame.retire_prior_to, new_connection_id_frame.stateless_reset_token); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke(&ClearControlFrameWithTransmissionType)); QuicRetireConnectionIdFrame retire_connection_id_frame(2, 0); manager_->WriteOrBufferRetireConnectionId( retire_connection_id_frame.sequence_number); EXPECT_TRUE( manager_->OnControlFrameAcked(QuicFrame(&new_connection_id_frame))); EXPECT_TRUE( manager_->OnControlFrameAcked(QuicFrame(&retire_connection_id_frame))); } TEST_F(QuicControlFrameManagerTest, DonotRetransmitOldWindowUpdates) { QuicWindowUpdateFrame window_update1(1, kTestStreamId, 200); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke(&ClearControlFrameWithTransmissionType)); manager_->WriteOrBufferWindowUpdate(window_update1.stream_id, window_update1.max_data); QuicWindowUpdateFrame window_update2(2, kTestStreamId, 300); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke(&ClearControlFrameWithTransmissionType)); manager_->WriteOrBufferWindowUpdate(window_update2.stream_id, window_update2.max_data); manager_->OnControlFrameLost(QuicFrame(window_update1)); manager_->OnControlFrameLost(QuicFrame(window_update2)); EXPECT_TRUE(manager_->HasPendingRetransmission()); EXPECT_TRUE(manager_->WillingToWrite()); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke( [&window_update2](const QuicFrame& frame, TransmissionType ) { EXPECT_EQ(WINDOW_UPDATE_FRAME, frame.type); EXPECT_EQ(window_update2, frame.window_update_frame); ClearControlFrame(frame); return true; })); manager_->OnCanWrite(); EXPECT_FALSE(manager_->HasPendingRetransmission()); EXPECT_FALSE(manager_->WillingToWrite()); } TEST_F(QuicControlFrameManagerTest, RetransmitWindowUpdateOfDifferentStreams) { QuicWindowUpdateFrame window_update1(1, kTestStreamId + 2, 200); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke(&ClearControlFrameWithTransmissionType)); manager_->WriteOrBufferWindowUpdate(window_update1.stream_id, window_update1.max_data); QuicWindowUpdateFrame window_update2(2, kTestStreamId + 4, 300); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke(&ClearControlFrameWithTransmissionType)); manager_->WriteOrBufferWindowUpdate(window_update2.stream_id, window_update2.max_data); manager_->OnControlFrameLost(QuicFrame(window_update1)); manager_->OnControlFrameLost(QuicFrame(window_update2)); EXPECT_TRUE(manager_->HasPendingRetransmission()); EXPECT_TRUE(manager_->WillingToWrite()); EXPECT_CALL(*session_, WriteControlFrame(_, _)) .Times(2) .WillRepeatedly(Invoke(&ClearControlFrameWithTransmissionType)); manager_->OnCanWrite(); EXPECT_FALSE(manager_->HasPendingRetransmission()); EXPECT_FALSE(manager_->WillingToWrite()); } TEST_F(QuicControlFrameManagerTest, TooManyBufferedControlFrames) { EXPECT_CALL(*session_, WriteControlFrame(_, _)).WillOnce(Return(false)); for (size_t i = 0; i < 1000; ++i) { manager_->WriteOrBufferRstStream( kTestStreamId, QuicResetStreamError::FromInternal(QUIC_STREAM_CANCELLED), 0); } EXPECT_CALL( *connection_, CloseConnection(QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, _, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET)); manager_->WriteOrBufferRstStream( kTestStreamId, QuicResetStreamError::FromInternal(QUIC_STREAM_CANCELLED), 0); } TEST_F(QuicControlFrameManagerTest, NumBufferedMaxStreams) { std::vector<QuicMaxStreamsFrame> max_streams_frames; size_t expected_buffered_frames = 0; for (int i = 0; i < 5; ++i) { EXPECT_CALL(*session_, WriteControlFrame(_, _)) .WillOnce(Invoke([&max_streams_frames](const QuicFrame& frame, TransmissionType ) { max_streams_frames.push_back(frame.max_streams_frame); ClearControlFrame(frame); return true; })); manager_->WriteOrBufferMaxStreams(0, false); EXPECT_EQ(++expected_buffered_frames, manager_->NumBufferedMaxStreams()); } for (const QuicMaxStreamsFrame& frame : max_streams_frames) { manager_->OnControlFrameAcked(QuicFrame(frame)); EXPECT_EQ(--expected_buffered_frames, manager_->NumBufferedMaxStreams()); } EXPECT_EQ(0, manager_->NumBufferedMaxStreams()); } } } }
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_control_frame_manager.cc
https://github.com/google/quiche/blob/6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6/quiche/quic/core/quic_control_frame_manager_test.cc
6fe69b2cf77d5fc175a729bc7a6c322a6388b8b6