xref: /aosp_15_r20/external/cronet/net/third_party/quiche/src/quiche/quic/core/quic_connection_test.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "quiche/quic/core/quic_connection.h"
6 
7 #include <errno.h>
8 
9 #include <cstdint>
10 #include <memory>
11 #include <string>
12 #include <utility>
13 
14 #include "absl/base/macros.h"
15 #include "absl/strings/str_cat.h"
16 #include "absl/strings/str_join.h"
17 #include "absl/strings/string_view.h"
18 #include "quiche/quic/core/congestion_control/loss_detection_interface.h"
19 #include "quiche/quic/core/congestion_control/send_algorithm_interface.h"
20 #include "quiche/quic/core/crypto/null_decrypter.h"
21 #include "quiche/quic/core/crypto/null_encrypter.h"
22 #include "quiche/quic/core/crypto/quic_decrypter.h"
23 #include "quiche/quic/core/frames/quic_connection_close_frame.h"
24 #include "quiche/quic/core/frames/quic_new_connection_id_frame.h"
25 #include "quiche/quic/core/frames/quic_path_response_frame.h"
26 #include "quiche/quic/core/frames/quic_rst_stream_frame.h"
27 #include "quiche/quic/core/quic_connection_id.h"
28 #include "quiche/quic/core/quic_constants.h"
29 #include "quiche/quic/core/quic_error_codes.h"
30 #include "quiche/quic/core/quic_packet_creator.h"
31 #include "quiche/quic/core/quic_packets.h"
32 #include "quiche/quic/core/quic_path_validator.h"
33 #include "quiche/quic/core/quic_types.h"
34 #include "quiche/quic/core/quic_utils.h"
35 #include "quiche/quic/core/quic_versions.h"
36 #include "quiche/quic/platform/api/quic_expect_bug.h"
37 #include "quiche/quic/platform/api/quic_flags.h"
38 #include "quiche/quic/platform/api/quic_ip_address.h"
39 #include "quiche/quic/platform/api/quic_ip_address_family.h"
40 #include "quiche/quic/platform/api/quic_logging.h"
41 #include "quiche/quic/platform/api/quic_socket_address.h"
42 #include "quiche/quic/platform/api/quic_test.h"
43 #include "quiche/quic/test_tools/mock_clock.h"
44 #include "quiche/quic/test_tools/mock_connection_id_generator.h"
45 #include "quiche/quic/test_tools/mock_random.h"
46 #include "quiche/quic/test_tools/quic_coalesced_packet_peer.h"
47 #include "quiche/quic/test_tools/quic_config_peer.h"
48 #include "quiche/quic/test_tools/quic_connection_peer.h"
49 #include "quiche/quic/test_tools/quic_framer_peer.h"
50 #include "quiche/quic/test_tools/quic_packet_creator_peer.h"
51 #include "quiche/quic/test_tools/quic_path_validator_peer.h"
52 #include "quiche/quic/test_tools/quic_sent_packet_manager_peer.h"
53 #include "quiche/quic/test_tools/quic_test_utils.h"
54 #include "quiche/quic/test_tools/simple_data_producer.h"
55 #include "quiche/quic/test_tools/simple_session_notifier.h"
56 #include "quiche/common/simple_buffer_allocator.h"
57 
58 using testing::_;
59 using testing::AnyNumber;
60 using testing::AtLeast;
61 using testing::DoAll;
62 using testing::ElementsAre;
63 using testing::Ge;
64 using testing::IgnoreResult;
65 using testing::InSequence;
66 using testing::Invoke;
67 using testing::InvokeWithoutArgs;
68 using testing::Lt;
69 using testing::Ref;
70 using testing::Return;
71 using testing::SaveArg;
72 using testing::SetArgPointee;
73 using testing::StrictMock;
74 
75 namespace quic {
76 namespace test {
77 namespace {
78 
79 const char data1[] = "foo data";
80 const char data2[] = "bar data";
81 
82 const bool kHasStopWaiting = true;
83 
84 const int kDefaultRetransmissionTimeMs = 500;
85 
86 DiversificationNonce kTestDiversificationNonce = {
87     'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a',
88     'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
89     'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
90 };
91 
92 const StatelessResetToken kTestStatelessResetToken{
93     0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
94     0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f};
95 
96 const QuicSocketAddress kPeerAddress =
97     QuicSocketAddress(QuicIpAddress::Loopback6(),
98                       /*port=*/12345);
99 const QuicSocketAddress kSelfAddress =
100     QuicSocketAddress(QuicIpAddress::Loopback6(),
101                       /*port=*/443);
102 const QuicSocketAddress kServerPreferredAddress = QuicSocketAddress(
__anon7d1f00100202() 103     []() {
104       QuicIpAddress address;
105       address.FromString("2604:31c0::");
106       return address;
107     }(),
108     /*port=*/443);
109 
GetNthClientInitiatedStreamId(int n,QuicTransportVersion version)110 QuicStreamId GetNthClientInitiatedStreamId(int n,
111                                            QuicTransportVersion version) {
112   return QuicUtils::GetFirstBidirectionalStreamId(version,
113                                                   Perspective::IS_CLIENT) +
114          n * 2;
115 }
116 
EncryptionlevelToLongHeaderType(EncryptionLevel level)117 QuicLongHeaderType EncryptionlevelToLongHeaderType(EncryptionLevel level) {
118   switch (level) {
119     case ENCRYPTION_INITIAL:
120       return INITIAL;
121     case ENCRYPTION_HANDSHAKE:
122       return HANDSHAKE;
123     case ENCRYPTION_ZERO_RTT:
124       return ZERO_RTT_PROTECTED;
125     case ENCRYPTION_FORWARD_SECURE:
126       QUICHE_DCHECK(false);
127       return INVALID_PACKET_TYPE;
128     default:
129       QUICHE_DCHECK(false);
130       return INVALID_PACKET_TYPE;
131   }
132 }
133 
134 // A TaggingEncrypterWithConfidentialityLimit is a TaggingEncrypter that allows
135 // specifying the confidentiality limit on the maximum number of packets that
136 // may be encrypted per key phase in TLS+QUIC.
137 class TaggingEncrypterWithConfidentialityLimit : public TaggingEncrypter {
138  public:
TaggingEncrypterWithConfidentialityLimit(uint8_t tag,QuicPacketCount confidentiality_limit)139   TaggingEncrypterWithConfidentialityLimit(
140       uint8_t tag, QuicPacketCount confidentiality_limit)
141       : TaggingEncrypter(tag), confidentiality_limit_(confidentiality_limit) {}
142 
GetConfidentialityLimit() const143   QuicPacketCount GetConfidentialityLimit() const override {
144     return confidentiality_limit_;
145   }
146 
147  private:
148   QuicPacketCount confidentiality_limit_;
149 };
150 
151 class StrictTaggingDecrypterWithIntegrityLimit : public StrictTaggingDecrypter {
152  public:
StrictTaggingDecrypterWithIntegrityLimit(uint8_t tag,QuicPacketCount integrity_limit)153   StrictTaggingDecrypterWithIntegrityLimit(uint8_t tag,
154                                            QuicPacketCount integrity_limit)
155       : StrictTaggingDecrypter(tag), integrity_limit_(integrity_limit) {}
156 
GetIntegrityLimit() const157   QuicPacketCount GetIntegrityLimit() const override {
158     return integrity_limit_;
159   }
160 
161  private:
162   QuicPacketCount integrity_limit_;
163 };
164 
165 class TestConnectionHelper : public QuicConnectionHelperInterface {
166  public:
TestConnectionHelper(MockClock * clock,MockRandom * random_generator)167   TestConnectionHelper(MockClock* clock, MockRandom* random_generator)
168       : clock_(clock), random_generator_(random_generator) {
169     clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
170   }
171   TestConnectionHelper(const TestConnectionHelper&) = delete;
172   TestConnectionHelper& operator=(const TestConnectionHelper&) = delete;
173 
174   // QuicConnectionHelperInterface
GetClock() const175   const QuicClock* GetClock() const override { return clock_; }
176 
GetRandomGenerator()177   QuicRandom* GetRandomGenerator() override { return random_generator_; }
178 
GetStreamSendBufferAllocator()179   quiche::QuicheBufferAllocator* GetStreamSendBufferAllocator() override {
180     return &buffer_allocator_;
181   }
182 
183  private:
184   MockClock* clock_;
185   MockRandom* random_generator_;
186   quiche::SimpleBufferAllocator buffer_allocator_;
187 };
188 
189 class TestConnection : public QuicConnection {
190  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)191   TestConnection(QuicConnectionId connection_id,
192                  QuicSocketAddress initial_self_address,
193                  QuicSocketAddress initial_peer_address,
194                  TestConnectionHelper* helper, TestAlarmFactory* alarm_factory,
195                  TestPacketWriter* writer, Perspective perspective,
196                  ParsedQuicVersion version,
197                  ConnectionIdGeneratorInterface& generator)
198       : QuicConnection(connection_id, initial_self_address,
199                        initial_peer_address, helper, alarm_factory, writer,
200                        /* owns_writer= */ false, perspective,
201                        SupportedVersions(version), generator),
202         notifier_(nullptr) {
203     writer->set_perspective(perspective);
204     SetEncrypter(ENCRYPTION_FORWARD_SECURE,
205                  std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
206     SetDataProducer(&producer_);
207     ON_CALL(*this, OnSerializedPacket(_))
208         .WillByDefault([this](SerializedPacket packet) {
209           QuicConnection::OnSerializedPacket(std::move(packet));
210         });
211   }
212   TestConnection(const TestConnection&) = delete;
213   TestConnection& operator=(const TestConnection&) = delete;
214 
215   MOCK_METHOD(void, OnSerializedPacket, (SerializedPacket packet), (override));
216 
OnEffectivePeerMigrationValidated(bool is_migration_linkable)217   void OnEffectivePeerMigrationValidated(bool is_migration_linkable) override {
218     QuicConnection::OnEffectivePeerMigrationValidated(is_migration_linkable);
219     if (is_migration_linkable) {
220       num_linkable_client_migration_++;
221     } else {
222       num_unlinkable_client_migration_++;
223     }
224   }
225 
num_unlinkable_client_migration() const226   uint32_t num_unlinkable_client_migration() const {
227     return num_unlinkable_client_migration_;
228   }
229 
num_linkable_client_migration() const230   uint32_t num_linkable_client_migration() const {
231     return num_linkable_client_migration_;
232   }
233 
SetSendAlgorithm(SendAlgorithmInterface * send_algorithm)234   void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
235     QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
236   }
237 
SetLossAlgorithm(LossDetectionInterface * loss_algorithm)238   void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
239     QuicConnectionPeer::SetLossAlgorithm(this, loss_algorithm);
240   }
241 
SendPacket(EncryptionLevel,uint64_t packet_number,std::unique_ptr<QuicPacket> packet,HasRetransmittableData retransmittable,bool has_ack,bool has_pending_frames)242   void SendPacket(EncryptionLevel /*level*/, uint64_t packet_number,
243                   std::unique_ptr<QuicPacket> packet,
244                   HasRetransmittableData retransmittable, bool has_ack,
245                   bool has_pending_frames) {
246     ScopedPacketFlusher flusher(this);
247     char buffer[kMaxOutgoingPacketSize];
248     size_t encrypted_length =
249         QuicConnectionPeer::GetFramer(this)->EncryptPayload(
250             ENCRYPTION_INITIAL, QuicPacketNumber(packet_number), *packet,
251             buffer, kMaxOutgoingPacketSize);
252     SerializedPacket serialized_packet(
253         QuicPacketNumber(packet_number), PACKET_4BYTE_PACKET_NUMBER, buffer,
254         encrypted_length, has_ack, has_pending_frames);
255     serialized_packet.peer_address = kPeerAddress;
256     if (retransmittable == HAS_RETRANSMITTABLE_DATA) {
257       serialized_packet.retransmittable_frames.push_back(
258           QuicFrame(QuicPingFrame()));
259     }
260     OnSerializedPacket(std::move(serialized_packet));
261   }
262 
SaveAndSendStreamData(QuicStreamId id,absl::string_view data,QuicStreamOffset offset,StreamSendingState state)263   QuicConsumedData SaveAndSendStreamData(QuicStreamId id,
264                                          absl::string_view data,
265                                          QuicStreamOffset offset,
266                                          StreamSendingState state) {
267     return SaveAndSendStreamData(id, data, offset, state, NOT_RETRANSMISSION);
268   }
269 
SaveAndSendStreamData(QuicStreamId id,absl::string_view data,QuicStreamOffset offset,StreamSendingState state,TransmissionType transmission_type)270   QuicConsumedData SaveAndSendStreamData(QuicStreamId id,
271                                          absl::string_view data,
272                                          QuicStreamOffset offset,
273                                          StreamSendingState state,
274                                          TransmissionType transmission_type) {
275     ScopedPacketFlusher flusher(this);
276     producer_.SaveStreamData(id, data);
277     if (notifier_ != nullptr) {
278       return notifier_->WriteOrBufferData(id, data.length(), state,
279                                           transmission_type);
280     }
281     return QuicConnection::SendStreamData(id, data.length(), offset, state);
282   }
283 
SendStreamDataWithString(QuicStreamId id,absl::string_view data,QuicStreamOffset offset,StreamSendingState state)284   QuicConsumedData SendStreamDataWithString(QuicStreamId id,
285                                             absl::string_view data,
286                                             QuicStreamOffset offset,
287                                             StreamSendingState state) {
288     ScopedPacketFlusher flusher(this);
289     if (!QuicUtils::IsCryptoStreamId(transport_version(), id) &&
290         this->encryption_level() == ENCRYPTION_INITIAL) {
291       this->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
292       if (perspective() == Perspective::IS_CLIENT && !IsHandshakeComplete()) {
293         OnHandshakeComplete();
294       }
295       if (version().SupportsAntiAmplificationLimit()) {
296         QuicConnectionPeer::SetAddressValidated(this);
297       }
298     }
299     return SaveAndSendStreamData(id, data, offset, state);
300   }
301 
SendApplicationDataAtLevel(EncryptionLevel encryption_level,QuicStreamId id,absl::string_view data,QuicStreamOffset offset,StreamSendingState state)302   QuicConsumedData SendApplicationDataAtLevel(EncryptionLevel encryption_level,
303                                               QuicStreamId id,
304                                               absl::string_view data,
305                                               QuicStreamOffset offset,
306                                               StreamSendingState state) {
307     ScopedPacketFlusher flusher(this);
308     QUICHE_DCHECK(encryption_level >= ENCRYPTION_ZERO_RTT);
309     SetEncrypter(encryption_level,
310                  std::make_unique<TaggingEncrypter>(encryption_level));
311     SetDefaultEncryptionLevel(encryption_level);
312     return SaveAndSendStreamData(id, data, offset, state);
313   }
314 
SendStreamData3()315   QuicConsumedData SendStreamData3() {
316     return SendStreamDataWithString(
317         GetNthClientInitiatedStreamId(1, transport_version()), "food", 0,
318         NO_FIN);
319   }
320 
SendStreamData5()321   QuicConsumedData SendStreamData5() {
322     return SendStreamDataWithString(
323         GetNthClientInitiatedStreamId(2, transport_version()), "food2", 0,
324         NO_FIN);
325   }
326 
327   // Ensures the connection can write stream data before writing.
EnsureWritableAndSendStreamData5()328   QuicConsumedData EnsureWritableAndSendStreamData5() {
329     EXPECT_TRUE(CanWrite(HAS_RETRANSMITTABLE_DATA));
330     return SendStreamData5();
331   }
332 
333   // The crypto stream has special semantics so that it is not blocked by a
334   // congestion window limitation, and also so that it gets put into a separate
335   // packet (so that it is easier to reason about a crypto frame not being
336   // split needlessly across packet boundaries).  As a result, we have separate
337   // tests for some cases for this stream.
SendCryptoStreamData()338   QuicConsumedData SendCryptoStreamData() {
339     QuicStreamOffset offset = 0;
340     absl::string_view data("chlo");
341     if (!QuicVersionUsesCryptoFrames(transport_version())) {
342       return SendCryptoDataWithString(data, offset);
343     }
344     producer_.SaveCryptoData(ENCRYPTION_INITIAL, offset, data);
345     size_t bytes_written;
346     if (notifier_) {
347       bytes_written =
348           notifier_->WriteCryptoData(ENCRYPTION_INITIAL, data.length(), offset);
349     } else {
350       bytes_written = QuicConnection::SendCryptoData(ENCRYPTION_INITIAL,
351                                                      data.length(), offset);
352     }
353     return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
354   }
355 
SendCryptoDataWithString(absl::string_view data,QuicStreamOffset offset)356   QuicConsumedData SendCryptoDataWithString(absl::string_view data,
357                                             QuicStreamOffset offset) {
358     return SendCryptoDataWithString(data, offset, ENCRYPTION_INITIAL);
359   }
360 
SendCryptoDataWithString(absl::string_view data,QuicStreamOffset offset,EncryptionLevel encryption_level)361   QuicConsumedData SendCryptoDataWithString(absl::string_view data,
362                                             QuicStreamOffset offset,
363                                             EncryptionLevel encryption_level) {
364     if (!QuicVersionUsesCryptoFrames(transport_version())) {
365       return SendStreamDataWithString(
366           QuicUtils::GetCryptoStreamId(transport_version()), data, offset,
367           NO_FIN);
368     }
369     producer_.SaveCryptoData(encryption_level, offset, data);
370     size_t bytes_written;
371     if (notifier_) {
372       bytes_written =
373           notifier_->WriteCryptoData(encryption_level, data.length(), offset);
374     } else {
375       bytes_written = QuicConnection::SendCryptoData(encryption_level,
376                                                      data.length(), offset);
377     }
378     return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
379   }
380 
set_version(ParsedQuicVersion version)381   void set_version(ParsedQuicVersion version) {
382     QuicConnectionPeer::GetFramer(this)->set_version(version);
383   }
384 
SetSupportedVersions(const ParsedQuicVersionVector & versions)385   void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
386     QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
387     writer()->SetSupportedVersions(versions);
388   }
389 
390   // This should be called before setting customized encrypters/decrypters for
391   // connection and peer creator.
set_perspective(Perspective perspective)392   void set_perspective(Perspective perspective) {
393     writer()->set_perspective(perspective);
394     QuicConnectionPeer::ResetPeerIssuedConnectionIdManager(this);
395     QuicConnectionPeer::SetPerspective(this, perspective);
396     QuicSentPacketManagerPeer::SetPerspective(
397         QuicConnectionPeer::GetSentPacketManager(this), perspective);
398     QuicConnectionPeer::GetFramer(this)->SetInitialObfuscators(
399         TestConnectionId());
400   }
401 
402   // Enable path MTU discovery.  Assumes that the test is performed from the
403   // server perspective and the higher value of MTU target is used.
EnablePathMtuDiscovery(MockSendAlgorithm * send_algorithm)404   void EnablePathMtuDiscovery(MockSendAlgorithm* send_algorithm) {
405     ASSERT_EQ(Perspective::IS_SERVER, perspective());
406 
407     if (GetQuicReloadableFlag(quic_enable_mtu_discovery_at_server)) {
408       OnConfigNegotiated();
409     } else {
410       QuicConfig config;
411       QuicTagVector connection_options;
412       connection_options.push_back(kMTUH);
413       config.SetInitialReceivedConnectionOptions(connection_options);
414       EXPECT_CALL(*send_algorithm, SetFromConfig(_, _));
415       SetFromConfig(config);
416     }
417 
418     // Normally, the pacing would be disabled in the test, but calling
419     // SetFromConfig enables it.  Set nearly-infinite bandwidth to make the
420     // pacing algorithm work.
421     EXPECT_CALL(*send_algorithm, PacingRate(_))
422         .WillRepeatedly(Return(QuicBandwidth::Infinite()));
423   }
424 
GetAckAlarm()425   TestAlarmFactory::TestAlarm* GetAckAlarm() {
426     return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
427         QuicConnectionPeer::GetAckAlarm(this));
428   }
429 
GetPingAlarm()430   TestAlarmFactory::TestAlarm* GetPingAlarm() {
431     return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
432         QuicConnectionPeer::GetPingAlarm(this));
433   }
434 
GetRetransmissionAlarm()435   TestAlarmFactory::TestAlarm* GetRetransmissionAlarm() {
436     return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
437         QuicConnectionPeer::GetRetransmissionAlarm(this));
438   }
439 
GetSendAlarm()440   TestAlarmFactory::TestAlarm* GetSendAlarm() {
441     return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
442         QuicConnectionPeer::GetSendAlarm(this));
443   }
444 
GetTimeoutAlarm()445   TestAlarmFactory::TestAlarm* GetTimeoutAlarm() {
446     return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
447         QuicConnectionPeer::GetIdleNetworkDetectorAlarm(this));
448   }
449 
GetMtuDiscoveryAlarm()450   TestAlarmFactory::TestAlarm* GetMtuDiscoveryAlarm() {
451     return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
452         QuicConnectionPeer::GetMtuDiscoveryAlarm(this));
453   }
454 
GetProcessUndecryptablePacketsAlarm()455   TestAlarmFactory::TestAlarm* GetProcessUndecryptablePacketsAlarm() {
456     return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
457         QuicConnectionPeer::GetProcessUndecryptablePacketsAlarm(this));
458   }
459 
GetDiscardPreviousOneRttKeysAlarm()460   TestAlarmFactory::TestAlarm* GetDiscardPreviousOneRttKeysAlarm() {
461     return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
462         QuicConnectionPeer::GetDiscardPreviousOneRttKeysAlarm(this));
463   }
464 
GetDiscardZeroRttDecryptionKeysAlarm()465   TestAlarmFactory::TestAlarm* GetDiscardZeroRttDecryptionKeysAlarm() {
466     return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
467         QuicConnectionPeer::GetDiscardZeroRttDecryptionKeysAlarm(this));
468   }
469 
GetBlackholeDetectorAlarm()470   TestAlarmFactory::TestAlarm* GetBlackholeDetectorAlarm() {
471     return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
472         QuicConnectionPeer::GetBlackholeDetectorAlarm(this));
473   }
474 
GetRetirePeerIssuedConnectionIdAlarm()475   TestAlarmFactory::TestAlarm* GetRetirePeerIssuedConnectionIdAlarm() {
476     return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
477         QuicConnectionPeer::GetRetirePeerIssuedConnectionIdAlarm(this));
478   }
479 
GetRetireSelfIssuedConnectionIdAlarm()480   TestAlarmFactory::TestAlarm* GetRetireSelfIssuedConnectionIdAlarm() {
481     return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
482         QuicConnectionPeer::GetRetireSelfIssuedConnectionIdAlarm(this));
483   }
484 
GetMultiPortProbingAlarm()485   TestAlarmFactory::TestAlarm* GetMultiPortProbingAlarm() {
486     return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
487         QuicConnectionPeer::GetMultiPortProbingAlarm(this));
488   }
489 
PathDegradingTimeout()490   void PathDegradingTimeout() {
491     QUICHE_DCHECK(PathDegradingDetectionInProgress());
492     GetBlackholeDetectorAlarm()->Fire();
493   }
494 
PathDegradingDetectionInProgress()495   bool PathDegradingDetectionInProgress() {
496     return QuicConnectionPeer::GetPathDegradingDeadline(this).IsInitialized();
497   }
498 
BlackholeDetectionInProgress()499   bool BlackholeDetectionInProgress() {
500     return QuicConnectionPeer::GetBlackholeDetectionDeadline(this)
501         .IsInitialized();
502   }
503 
PathMtuReductionDetectionInProgress()504   bool PathMtuReductionDetectionInProgress() {
505     return QuicConnectionPeer::GetPathMtuReductionDetectionDeadline(this)
506         .IsInitialized();
507   }
508 
GetBytesInFlight()509   QuicByteCount GetBytesInFlight() {
510     return QuicConnectionPeer::GetSentPacketManager(this)->GetBytesInFlight();
511   }
512 
set_notifier(SimpleSessionNotifier * notifier)513   void set_notifier(SimpleSessionNotifier* notifier) { notifier_ = notifier; }
514 
ReturnEffectivePeerAddressForNextPacket(const QuicSocketAddress & addr)515   void ReturnEffectivePeerAddressForNextPacket(const QuicSocketAddress& addr) {
516     next_effective_peer_addr_ = std::make_unique<QuicSocketAddress>(addr);
517   }
518 
SendOrQueuePacket(SerializedPacket packet)519   void SendOrQueuePacket(SerializedPacket packet) override {
520     QuicConnection::SendOrQueuePacket(std::move(packet));
521     self_address_on_default_path_while_sending_packet_ = self_address();
522   }
523 
self_address_on_default_path_while_sending_packet()524   QuicSocketAddress self_address_on_default_path_while_sending_packet() {
525     return self_address_on_default_path_while_sending_packet_;
526   }
527 
producer()528   SimpleDataProducer* producer() { return &producer_; }
529 
530   using QuicConnection::active_effective_peer_migration_type;
531   using QuicConnection::IsCurrentPacketConnectivityProbing;
532   using QuicConnection::SelectMutualVersion;
533   using QuicConnection::set_defer_send_in_response_to_packets;
534 
535  protected:
GetEffectivePeerAddressFromCurrentPacket() const536   QuicSocketAddress GetEffectivePeerAddressFromCurrentPacket() const override {
537     if (next_effective_peer_addr_) {
538       return *std::move(next_effective_peer_addr_);
539     }
540     return QuicConnection::GetEffectivePeerAddressFromCurrentPacket();
541   }
542 
543  private:
writer()544   TestPacketWriter* writer() {
545     return static_cast<TestPacketWriter*>(QuicConnection::writer());
546   }
547 
548   SimpleDataProducer producer_;
549 
550   SimpleSessionNotifier* notifier_;
551 
552   std::unique_ptr<QuicSocketAddress> next_effective_peer_addr_;
553 
554   QuicSocketAddress self_address_on_default_path_while_sending_packet_;
555 
556   uint32_t num_unlinkable_client_migration_ = 0;
557 
558   uint32_t num_linkable_client_migration_ = 0;
559 };
560 
561 enum class AckResponse { kDefer, kImmediate };
562 
563 // Run tests with combinations of {ParsedQuicVersion, AckResponse}.
564 struct TestParams {
TestParamsquic::test::__anon7d1f00100111::TestParams565   TestParams(ParsedQuicVersion version, AckResponse ack_response)
566       : version(version), ack_response(ack_response) {}
567 
568   ParsedQuicVersion version;
569   AckResponse ack_response;
570 };
571 
572 // Used by ::testing::PrintToStringParamName().
PrintToString(const TestParams & p)573 std::string PrintToString(const TestParams& p) {
574   return absl::StrCat(
575       ParsedQuicVersionToString(p.version), "_",
576       (p.ack_response == AckResponse::kDefer ? "defer" : "immediate"));
577 }
578 
579 // Constructs various test permutations.
GetTestParams()580 std::vector<TestParams> GetTestParams() {
581   QuicFlagSaver flags;
582   std::vector<TestParams> params;
583   ParsedQuicVersionVector all_supported_versions = AllSupportedVersions();
584   for (size_t i = 0; i < all_supported_versions.size(); ++i) {
585     for (AckResponse ack_response :
586          {AckResponse::kDefer, AckResponse::kImmediate}) {
587       params.push_back(TestParams(all_supported_versions[i], ack_response));
588     }
589   }
590   return params;
591 }
592 
593 class QuicConnectionTest : public QuicTestWithParam<TestParams> {
594  public:
595   // For tests that do silent connection closes, no such packet is generated. In
596   // order to verify the contents of the OnConnectionClosed upcall, EXPECTs
597   // should invoke this method, saving the frame, and then the test can verify
598   // the contents.
SaveConnectionCloseFrame(const QuicConnectionCloseFrame & frame,ConnectionCloseSource)599   void SaveConnectionCloseFrame(const QuicConnectionCloseFrame& frame,
600                                 ConnectionCloseSource /*source*/) {
601     saved_connection_close_frame_ = frame;
602     connection_close_frame_count_++;
603   }
604 
605  protected:
QuicConnectionTest()606   QuicConnectionTest()
607       : connection_id_(TestConnectionId()),
608         framer_(SupportedVersions(version()), QuicTime::Zero(),
609                 Perspective::IS_CLIENT, connection_id_.length()),
610         send_algorithm_(new StrictMock<MockSendAlgorithm>),
611         loss_algorithm_(new MockLossAlgorithm()),
612         helper_(new TestConnectionHelper(&clock_, &random_generator_)),
613         alarm_factory_(new TestAlarmFactory()),
614         peer_framer_(SupportedVersions(version()), QuicTime::Zero(),
615                      Perspective::IS_SERVER, connection_id_.length()),
616         peer_creator_(connection_id_, &peer_framer_,
617                       /*delegate=*/nullptr),
618         writer_(
619             new TestPacketWriter(version(), &clock_, Perspective::IS_CLIENT)),
620         connection_(connection_id_, kSelfAddress, kPeerAddress, helper_.get(),
621                     alarm_factory_.get(), writer_.get(), Perspective::IS_CLIENT,
622                     version(), connection_id_generator_),
623         creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
624         manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
625         frame1_(0, false, 0, absl::string_view(data1)),
626         frame2_(0, false, 3, absl::string_view(data2)),
627         crypto_frame_(ENCRYPTION_INITIAL, 0, absl::string_view(data1)),
628         packet_number_length_(PACKET_4BYTE_PACKET_NUMBER),
629         connection_id_included_(CONNECTION_ID_PRESENT),
630         notifier_(&connection_),
631         connection_close_frame_count_(0) {
632     QUIC_DVLOG(2) << "QuicConnectionTest(" << PrintToString(GetParam()) << ")";
633     connection_.set_defer_send_in_response_to_packets(GetParam().ack_response ==
634                                                       AckResponse::kDefer);
635     framer_.SetInitialObfuscators(TestConnectionId());
636     connection_.InstallInitialCrypters(TestConnectionId());
637     CrypterPair crypters;
638     CryptoUtils::CreateInitialObfuscators(Perspective::IS_SERVER, version(),
639                                           TestConnectionId(), &crypters);
640     peer_creator_.SetEncrypter(ENCRYPTION_INITIAL,
641                                std::move(crypters.encrypter));
642     if (version().KnowsWhichDecrypterToUse()) {
643       peer_framer_.InstallDecrypter(ENCRYPTION_INITIAL,
644                                     std::move(crypters.decrypter));
645     } else {
646       peer_framer_.SetDecrypter(ENCRYPTION_INITIAL,
647                                 std::move(crypters.decrypter));
648     }
649     for (EncryptionLevel level :
650          {ENCRYPTION_ZERO_RTT, ENCRYPTION_FORWARD_SECURE}) {
651       peer_creator_.SetEncrypter(level,
652                                  std::make_unique<TaggingEncrypter>(level));
653     }
654     QuicFramerPeer::SetLastSerializedServerConnectionId(
655         QuicConnectionPeer::GetFramer(&connection_), connection_id_);
656     QuicFramerPeer::SetLastWrittenPacketNumberLength(
657         QuicConnectionPeer::GetFramer(&connection_), packet_number_length_);
658     QuicStreamId stream_id;
659     if (QuicVersionUsesCryptoFrames(version().transport_version)) {
660       stream_id = QuicUtils::GetFirstBidirectionalStreamId(
661           version().transport_version, Perspective::IS_CLIENT);
662     } else {
663       stream_id = QuicUtils::GetCryptoStreamId(version().transport_version);
664     }
665     frame1_.stream_id = stream_id;
666     frame2_.stream_id = stream_id;
667     connection_.set_visitor(&visitor_);
668     connection_.SetSessionNotifier(&notifier_);
669     connection_.set_notifier(&notifier_);
670     connection_.SetSendAlgorithm(send_algorithm_);
671     connection_.SetLossAlgorithm(loss_algorithm_.get());
672     EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
673     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
674         .Times(AnyNumber());
675     EXPECT_CALL(*send_algorithm_, OnPacketNeutered(_)).Times(AnyNumber());
676     EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
677         .WillRepeatedly(Return(kDefaultTCPMSS));
678     EXPECT_CALL(*send_algorithm_, PacingRate(_))
679         .WillRepeatedly(Return(QuicBandwidth::Zero()));
680     EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
681         .Times(AnyNumber())
682         .WillRepeatedly(Return(QuicBandwidth::Zero()));
683     EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_))
684         .Times(AnyNumber());
685     EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
686     EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
687     EXPECT_CALL(*send_algorithm_, GetCongestionControlType())
688         .Times(AnyNumber());
689     EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
690     EXPECT_CALL(*send_algorithm_, GetCongestionControlType())
691         .Times(AnyNumber());
692     EXPECT_CALL(visitor_, WillingAndAbleToWrite())
693         .WillRepeatedly(
694             Invoke(&notifier_, &SimpleSessionNotifier::WillingToWrite));
695     EXPECT_CALL(visitor_, OnPacketDecrypted(_)).Times(AnyNumber());
696     EXPECT_CALL(visitor_, OnCanWrite())
697         .WillRepeatedly(Invoke(&notifier_, &SimpleSessionNotifier::OnCanWrite));
698     EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
699         .WillRepeatedly(Return(false));
700     EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
701     EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(AnyNumber());
702     EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
703     if (GetQuicRestartFlag(quic_opport_bundle_qpack_decoder_data4)) {
704       EXPECT_CALL(visitor_, MaybeBundleOpportunistically()).Times(AnyNumber());
705       EXPECT_CALL(visitor_, GetFlowControlSendWindowSize(_)).Times(AnyNumber());
706     }
707     EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged())
708         .Times(testing::AtMost(1));
709     EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
710         .WillRepeatedly(Return(QuicTime::Zero()));
711     EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
712         .Times(AnyNumber());
713     EXPECT_CALL(visitor_, GetHandshakeState())
714         .WillRepeatedly(Return(HANDSHAKE_START));
715     if (connection_.version().KnowsWhichDecrypterToUse()) {
716       connection_.InstallDecrypter(
717           ENCRYPTION_FORWARD_SECURE,
718           std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
719     } else {
720       connection_.SetAlternativeDecrypter(
721           ENCRYPTION_FORWARD_SECURE,
722           std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE),
723           false);
724     }
725     peer_creator_.SetDefaultPeerAddress(kSelfAddress);
726   }
727 
728   QuicConnectionTest(const QuicConnectionTest&) = delete;
729   QuicConnectionTest& operator=(const QuicConnectionTest&) = delete;
730 
version()731   ParsedQuicVersion version() { return GetParam().version; }
732 
SetClientConnectionId(const QuicConnectionId & client_connection_id)733   void SetClientConnectionId(const QuicConnectionId& client_connection_id) {
734     connection_.set_client_connection_id(client_connection_id);
735     writer_->framer()->framer()->SetExpectedClientConnectionIdLength(
736         client_connection_id.length());
737   }
738 
SetDecrypter(EncryptionLevel level,std::unique_ptr<QuicDecrypter> decrypter)739   void SetDecrypter(EncryptionLevel level,
740                     std::unique_ptr<QuicDecrypter> decrypter) {
741     if (connection_.version().KnowsWhichDecrypterToUse()) {
742       connection_.InstallDecrypter(level, std::move(decrypter));
743     } else {
744       connection_.SetAlternativeDecrypter(level, std::move(decrypter), false);
745     }
746   }
747 
ProcessPacket(uint64_t number)748   void ProcessPacket(uint64_t number) {
749     EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
750     ProcessDataPacket(number);
751     if (connection_.GetSendAlarm()->IsSet()) {
752       connection_.GetSendAlarm()->Fire();
753     }
754   }
755 
ProcessReceivedPacket(const QuicSocketAddress & self_address,const QuicSocketAddress & peer_address,const QuicReceivedPacket & packet)756   void ProcessReceivedPacket(const QuicSocketAddress& self_address,
757                              const QuicSocketAddress& peer_address,
758                              const QuicReceivedPacket& packet) {
759     connection_.ProcessUdpPacket(self_address, peer_address, packet);
760     if (connection_.GetSendAlarm()->IsSet()) {
761       connection_.GetSendAlarm()->Fire();
762     }
763   }
764 
MakeCryptoFrame() const765   QuicFrame MakeCryptoFrame() const {
766     if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
767       return QuicFrame(new QuicCryptoFrame(crypto_frame_));
768     }
769     return QuicFrame(QuicStreamFrame(
770         QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
771         0u, absl::string_view()));
772   }
773 
ProcessFramePacket(QuicFrame frame)774   void ProcessFramePacket(QuicFrame frame) {
775     ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress,
776                                     ENCRYPTION_FORWARD_SECURE);
777   }
778 
ProcessFramePacketWithAddresses(QuicFrame frame,QuicSocketAddress self_address,QuicSocketAddress peer_address,EncryptionLevel level)779   void ProcessFramePacketWithAddresses(QuicFrame frame,
780                                        QuicSocketAddress self_address,
781                                        QuicSocketAddress peer_address,
782                                        EncryptionLevel level) {
783     QuicFrames frames;
784     frames.push_back(QuicFrame(frame));
785     return ProcessFramesPacketWithAddresses(frames, self_address, peer_address,
786                                             level);
787   }
788 
ConstructPacket(QuicFrames frames,EncryptionLevel level,char * buffer,size_t buffer_len)789   std::unique_ptr<QuicReceivedPacket> ConstructPacket(QuicFrames frames,
790                                                       EncryptionLevel level,
791                                                       char* buffer,
792                                                       size_t buffer_len) {
793     QUICHE_DCHECK(peer_framer_.HasEncrypterOfEncryptionLevel(level));
794     peer_creator_.set_encryption_level(level);
795     QuicPacketCreatorPeer::SetSendVersionInPacket(
796         &peer_creator_,
797         level < ENCRYPTION_FORWARD_SECURE &&
798             connection_.perspective() == Perspective::IS_SERVER);
799 
800     SerializedPacket serialized_packet =
801         QuicPacketCreatorPeer::SerializeAllFrames(&peer_creator_, frames,
802                                                   buffer, buffer_len);
803     return std::make_unique<QuicReceivedPacket>(
804         serialized_packet.encrypted_buffer, serialized_packet.encrypted_length,
805         clock_.Now());
806   }
807 
ProcessFramesPacketWithAddresses(QuicFrames frames,QuicSocketAddress self_address,QuicSocketAddress peer_address,EncryptionLevel level)808   void ProcessFramesPacketWithAddresses(QuicFrames frames,
809                                         QuicSocketAddress self_address,
810                                         QuicSocketAddress peer_address,
811                                         EncryptionLevel level) {
812     char buffer[kMaxOutgoingPacketSize];
813     connection_.ProcessUdpPacket(
814         self_address, peer_address,
815         *ConstructPacket(std::move(frames), level, buffer,
816                          kMaxOutgoingPacketSize));
817     if (connection_.GetSendAlarm()->IsSet()) {
818       connection_.GetSendAlarm()->Fire();
819     }
820   }
821 
822   // Bypassing the packet creator is unrealistic, but allows us to process
823   // packets the QuicPacketCreator won't allow us to create.
ForceProcessFramePacket(QuicFrame frame)824   void ForceProcessFramePacket(QuicFrame frame) {
825     QuicFrames frames;
826     frames.push_back(QuicFrame(frame));
827     bool send_version = connection_.perspective() == Perspective::IS_SERVER;
828     if (connection_.version().KnowsWhichDecrypterToUse()) {
829       send_version = true;
830     }
831     QuicPacketCreatorPeer::SetSendVersionInPacket(&peer_creator_, send_version);
832     QuicPacketHeader header;
833     QuicPacketCreatorPeer::FillPacketHeader(&peer_creator_, &header);
834     char encrypted_buffer[kMaxOutgoingPacketSize];
835     size_t length = peer_framer_.BuildDataPacket(
836         header, frames, encrypted_buffer, kMaxOutgoingPacketSize,
837         ENCRYPTION_INITIAL);
838     QUICHE_DCHECK_GT(length, 0u);
839 
840     const size_t encrypted_length = peer_framer_.EncryptInPlace(
841         ENCRYPTION_INITIAL, header.packet_number,
842         GetStartOfEncryptedData(peer_framer_.version().transport_version,
843                                 header),
844         length, kMaxOutgoingPacketSize, encrypted_buffer);
845     QUICHE_DCHECK_GT(encrypted_length, 0u);
846 
847     connection_.ProcessUdpPacket(
848         kSelfAddress, kPeerAddress,
849         QuicReceivedPacket(encrypted_buffer, encrypted_length, clock_.Now()));
850   }
851 
ProcessFramePacketAtLevel(uint64_t number,QuicFrame frame,EncryptionLevel level)852   size_t ProcessFramePacketAtLevel(uint64_t number, QuicFrame frame,
853                                    EncryptionLevel level) {
854     return ProcessFramePacketAtLevelWithEcn(number, frame, level, ECN_NOT_ECT);
855   }
856 
ProcessFramePacketAtLevelWithEcn(uint64_t number,QuicFrame frame,EncryptionLevel level,QuicEcnCodepoint ecn_codepoint)857   size_t ProcessFramePacketAtLevelWithEcn(uint64_t number, QuicFrame frame,
858                                           EncryptionLevel level,
859                                           QuicEcnCodepoint ecn_codepoint) {
860     QuicFrames frames;
861     frames.push_back(frame);
862     return ProcessFramesPacketAtLevelWithEcn(number, frames, level,
863                                              ecn_codepoint);
864   }
865 
ProcessFramesPacketAtLevel(uint64_t number,QuicFrames frames,EncryptionLevel level)866   size_t ProcessFramesPacketAtLevel(uint64_t number, QuicFrames frames,
867                                     EncryptionLevel level) {
868     return ProcessFramesPacketAtLevelWithEcn(number, frames, level,
869                                              ECN_NOT_ECT);
870   }
871 
ProcessFramesPacketAtLevelWithEcn(uint64_t number,const QuicFrames & frames,EncryptionLevel level,QuicEcnCodepoint ecn_codepoint)872   size_t ProcessFramesPacketAtLevelWithEcn(uint64_t number,
873                                            const QuicFrames& frames,
874                                            EncryptionLevel level,
875                                            QuicEcnCodepoint ecn_codepoint) {
876     QuicPacketHeader header = ConstructPacketHeader(number, level);
877     // Set the correct encryption level and encrypter on peer_creator and
878     // peer_framer, respectively.
879     peer_creator_.set_encryption_level(level);
880     if (level > ENCRYPTION_INITIAL) {
881       peer_framer_.SetEncrypter(level,
882                                 std::make_unique<TaggingEncrypter>(level));
883       // Set the corresponding decrypter.
884       if (connection_.version().KnowsWhichDecrypterToUse()) {
885         connection_.InstallDecrypter(
886             level, std::make_unique<StrictTaggingDecrypter>(level));
887       } else {
888         connection_.SetAlternativeDecrypter(
889             level, std::make_unique<StrictTaggingDecrypter>(level), false);
890       }
891     }
892     std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
893 
894     char buffer[kMaxOutgoingPacketSize];
895     size_t encrypted_length =
896         peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
897                                     buffer, kMaxOutgoingPacketSize);
898     connection_.ProcessUdpPacket(
899         kSelfAddress, kPeerAddress,
900         QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false, 0,
901                            true, nullptr, 0, false, ecn_codepoint));
902     if (connection_.GetSendAlarm()->IsSet()) {
903       connection_.GetSendAlarm()->Fire();
904     }
905     return encrypted_length;
906   }
907 
908   struct PacketInfo {
PacketInfoquic::test::__anon7d1f00100111::QuicConnectionTest::PacketInfo909     PacketInfo(uint64_t packet_number, QuicFrames frames, EncryptionLevel level)
910         : packet_number(packet_number), frames(frames), level(level) {}
911 
912     uint64_t packet_number;
913     QuicFrames frames;
914     EncryptionLevel level;
915   };
916 
ProcessCoalescedPacket(std::vector<PacketInfo> packets)917   size_t ProcessCoalescedPacket(std::vector<PacketInfo> packets) {
918     return ProcessCoalescedPacket(packets, ECN_NOT_ECT);
919   }
920 
ProcessCoalescedPacket(std::vector<PacketInfo> packets,QuicEcnCodepoint ecn_codepoint)921   size_t ProcessCoalescedPacket(std::vector<PacketInfo> packets,
922                                 QuicEcnCodepoint ecn_codepoint) {
923     char coalesced_buffer[kMaxOutgoingPacketSize];
924     size_t coalesced_size = 0;
925     bool contains_initial = false;
926     for (const auto& packet : packets) {
927       QuicPacketHeader header =
928           ConstructPacketHeader(packet.packet_number, packet.level);
929       // Set the correct encryption level and encrypter on peer_creator and
930       // peer_framer, respectively.
931       peer_creator_.set_encryption_level(packet.level);
932       if (packet.level == ENCRYPTION_INITIAL) {
933         contains_initial = true;
934       }
935       EncryptionLevel level =
936           QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_);
937       if (level > ENCRYPTION_INITIAL) {
938         peer_framer_.SetEncrypter(level,
939                                   std::make_unique<TaggingEncrypter>(level));
940         // Set the corresponding decrypter.
941         if (connection_.version().KnowsWhichDecrypterToUse()) {
942           connection_.InstallDecrypter(
943               level, std::make_unique<StrictTaggingDecrypter>(level));
944         } else {
945           connection_.SetDecrypter(
946               level, std::make_unique<StrictTaggingDecrypter>(level));
947         }
948       }
949       std::unique_ptr<QuicPacket> constructed_packet(
950           ConstructPacket(header, packet.frames));
951 
952       char buffer[kMaxOutgoingPacketSize];
953       size_t encrypted_length = peer_framer_.EncryptPayload(
954           packet.level, QuicPacketNumber(packet.packet_number),
955           *constructed_packet, buffer, kMaxOutgoingPacketSize);
956       QUICHE_DCHECK_LE(coalesced_size + encrypted_length,
957                        kMaxOutgoingPacketSize);
958       memcpy(coalesced_buffer + coalesced_size, buffer, encrypted_length);
959       coalesced_size += encrypted_length;
960     }
961     if (contains_initial) {
962       // Padded coalesced packet to full if it contains initial packet.
963       memset(coalesced_buffer + coalesced_size, '0',
964              kMaxOutgoingPacketSize - coalesced_size);
965     }
966     connection_.ProcessUdpPacket(
967         kSelfAddress, kPeerAddress,
968         QuicReceivedPacket(coalesced_buffer, coalesced_size, clock_.Now(),
969                            false, 0, true, nullptr, 0, false, ecn_codepoint));
970     if (connection_.GetSendAlarm()->IsSet()) {
971       connection_.GetSendAlarm()->Fire();
972     }
973     return coalesced_size;
974   }
975 
ProcessDataPacket(uint64_t number)976   size_t ProcessDataPacket(uint64_t number) {
977     return ProcessDataPacketAtLevel(number, false, ENCRYPTION_FORWARD_SECURE);
978   }
979 
ProcessDataPacket(QuicPacketNumber packet_number)980   size_t ProcessDataPacket(QuicPacketNumber packet_number) {
981     return ProcessDataPacketAtLevel(packet_number, false,
982                                     ENCRYPTION_FORWARD_SECURE);
983   }
984 
ProcessDataPacketAtLevel(QuicPacketNumber packet_number,bool has_stop_waiting,EncryptionLevel level)985   size_t ProcessDataPacketAtLevel(QuicPacketNumber packet_number,
986                                   bool has_stop_waiting,
987                                   EncryptionLevel level) {
988     return ProcessDataPacketAtLevel(packet_number.ToUint64(), has_stop_waiting,
989                                     level);
990   }
991 
ProcessCryptoPacketAtLevel(uint64_t number,EncryptionLevel level)992   size_t ProcessCryptoPacketAtLevel(uint64_t number, EncryptionLevel level) {
993     QuicPacketHeader header = ConstructPacketHeader(number, level);
994     QuicFrames frames;
995     if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
996       frames.push_back(QuicFrame(&crypto_frame_));
997     } else {
998       frames.push_back(QuicFrame(frame1_));
999     }
1000     if (level == ENCRYPTION_INITIAL) {
1001       frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
1002     }
1003     std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
1004     char buffer[kMaxOutgoingPacketSize];
1005     peer_creator_.set_encryption_level(level);
1006     size_t encrypted_length =
1007         peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1008                                     buffer, kMaxOutgoingPacketSize);
1009     connection_.ProcessUdpPacket(
1010         kSelfAddress, kPeerAddress,
1011         QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1012     if (connection_.GetSendAlarm()->IsSet()) {
1013       connection_.GetSendAlarm()->Fire();
1014     }
1015     return encrypted_length;
1016   }
1017 
ProcessDataPacketAtLevel(uint64_t number,bool has_stop_waiting,EncryptionLevel level)1018   size_t ProcessDataPacketAtLevel(uint64_t number, bool has_stop_waiting,
1019                                   EncryptionLevel level) {
1020     std::unique_ptr<QuicPacket> packet(
1021         ConstructDataPacket(number, has_stop_waiting, level));
1022     char buffer[kMaxOutgoingPacketSize];
1023     peer_creator_.set_encryption_level(level);
1024     size_t encrypted_length =
1025         peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1026                                     buffer, kMaxOutgoingPacketSize);
1027     connection_.ProcessUdpPacket(
1028         kSelfAddress, kPeerAddress,
1029         QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1030     if (connection_.GetSendAlarm()->IsSet()) {
1031       connection_.GetSendAlarm()->Fire();
1032     }
1033     return encrypted_length;
1034   }
1035 
ProcessClosePacket(uint64_t number)1036   void ProcessClosePacket(uint64_t number) {
1037     std::unique_ptr<QuicPacket> packet(ConstructClosePacket(number));
1038     char buffer[kMaxOutgoingPacketSize];
1039     size_t encrypted_length = peer_framer_.EncryptPayload(
1040         ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(number), *packet, buffer,
1041         kMaxOutgoingPacketSize);
1042     connection_.ProcessUdpPacket(
1043         kSelfAddress, kPeerAddress,
1044         QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
1045   }
1046 
SendStreamDataToPeer(QuicStreamId id,absl::string_view data,QuicStreamOffset offset,StreamSendingState state,QuicPacketNumber * last_packet)1047   QuicByteCount SendStreamDataToPeer(QuicStreamId id, absl::string_view data,
1048                                      QuicStreamOffset offset,
1049                                      StreamSendingState state,
1050                                      QuicPacketNumber* last_packet) {
1051     QuicByteCount packet_size = 0;
1052     // Save the last packet's size.
1053     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1054         .Times(AnyNumber())
1055         .WillRepeatedly(SaveArg<3>(&packet_size));
1056     connection_.SendStreamDataWithString(id, data, offset, state);
1057     if (last_packet != nullptr) {
1058       *last_packet = creator_->packet_number();
1059     }
1060     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1061         .Times(AnyNumber());
1062     return packet_size;
1063   }
1064 
SendAckPacketToPeer()1065   void SendAckPacketToPeer() {
1066     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1067     {
1068       QuicConnection::ScopedPacketFlusher flusher(&connection_);
1069       connection_.SendAck();
1070     }
1071     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1072         .Times(AnyNumber());
1073   }
1074 
SendRstStream(QuicStreamId id,QuicRstStreamErrorCode error,QuicStreamOffset bytes_written)1075   void SendRstStream(QuicStreamId id, QuicRstStreamErrorCode error,
1076                      QuicStreamOffset bytes_written) {
1077     notifier_.WriteOrBufferRstStream(id, error, bytes_written);
1078     connection_.OnStreamReset(id, error);
1079   }
1080 
SendPing()1081   void SendPing() { notifier_.WriteOrBufferPing(); }
1082 
SendMessage(absl::string_view message)1083   MessageStatus SendMessage(absl::string_view message) {
1084     connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1085     quiche::QuicheMemSlice slice(quiche::QuicheBuffer::Copy(
1086         connection_.helper()->GetStreamSendBufferAllocator(), message));
1087     return connection_.SendMessage(1, absl::MakeSpan(&slice, 1), false);
1088   }
1089 
ProcessAckPacket(uint64_t packet_number,QuicAckFrame * frame)1090   void ProcessAckPacket(uint64_t packet_number, QuicAckFrame* frame) {
1091     if (packet_number > 1) {
1092       QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, packet_number - 1);
1093     } else {
1094       QuicPacketCreatorPeer::ClearPacketNumber(&peer_creator_);
1095     }
1096     ProcessFramePacket(QuicFrame(frame));
1097   }
1098 
ProcessAckPacket(QuicAckFrame * frame)1099   void ProcessAckPacket(QuicAckFrame* frame) {
1100     ProcessFramePacket(QuicFrame(frame));
1101   }
1102 
ProcessStopWaitingPacket(QuicStopWaitingFrame frame)1103   void ProcessStopWaitingPacket(QuicStopWaitingFrame frame) {
1104     ProcessFramePacket(QuicFrame(frame));
1105   }
1106 
ProcessStopWaitingPacketAtLevel(uint64_t number,QuicStopWaitingFrame frame,EncryptionLevel)1107   size_t ProcessStopWaitingPacketAtLevel(uint64_t number,
1108                                          QuicStopWaitingFrame frame,
1109                                          EncryptionLevel /*level*/) {
1110     return ProcessFramePacketAtLevel(number, QuicFrame(frame),
1111                                      ENCRYPTION_ZERO_RTT);
1112   }
1113 
ProcessGoAwayPacket(QuicGoAwayFrame * frame)1114   void ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
1115     ProcessFramePacket(QuicFrame(frame));
1116   }
1117 
IsMissing(uint64_t number)1118   bool IsMissing(uint64_t number) {
1119     return IsAwaitingPacket(connection_.ack_frame(), QuicPacketNumber(number),
1120                             QuicPacketNumber());
1121   }
1122 
ConstructPacket(const QuicPacketHeader & header,const QuicFrames & frames)1123   std::unique_ptr<QuicPacket> ConstructPacket(const QuicPacketHeader& header,
1124                                               const QuicFrames& frames) {
1125     auto packet = BuildUnsizedDataPacket(&peer_framer_, header, frames);
1126     EXPECT_NE(nullptr, packet.get());
1127     return packet;
1128   }
1129 
ConstructPacketHeader(uint64_t number,EncryptionLevel level)1130   QuicPacketHeader ConstructPacketHeader(uint64_t number,
1131                                          EncryptionLevel level) {
1132     QuicPacketHeader header;
1133     if (level < ENCRYPTION_FORWARD_SECURE) {
1134       // Set long header type accordingly.
1135       header.version_flag = true;
1136       header.form = IETF_QUIC_LONG_HEADER_PACKET;
1137       header.long_packet_type = EncryptionlevelToLongHeaderType(level);
1138       if (QuicVersionHasLongHeaderLengths(
1139               peer_framer_.version().transport_version)) {
1140         header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2;
1141         if (header.long_packet_type == INITIAL) {
1142           header.retry_token_length_length =
1143               quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1;
1144         }
1145       }
1146     }
1147     // Set connection_id to peer's in memory representation as this data packet
1148     // is created by peer_framer.
1149     if (peer_framer_.perspective() == Perspective::IS_SERVER) {
1150       header.source_connection_id = connection_id_;
1151       header.source_connection_id_included = connection_id_included_;
1152       header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1153     } else {
1154       header.destination_connection_id = connection_id_;
1155       header.destination_connection_id_included = connection_id_included_;
1156     }
1157     if (peer_framer_.perspective() == Perspective::IS_SERVER) {
1158       if (!connection_.client_connection_id().IsEmpty()) {
1159         header.destination_connection_id = connection_.client_connection_id();
1160         header.destination_connection_id_included = CONNECTION_ID_PRESENT;
1161       } else {
1162         header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1163       }
1164       if (header.version_flag) {
1165         header.source_connection_id = connection_id_;
1166         header.source_connection_id_included = CONNECTION_ID_PRESENT;
1167         if (GetParam().version.handshake_protocol == PROTOCOL_QUIC_CRYPTO &&
1168             header.long_packet_type == ZERO_RTT_PROTECTED) {
1169           header.nonce = &kTestDiversificationNonce;
1170         }
1171       }
1172     }
1173     header.packet_number_length = packet_number_length_;
1174     header.packet_number = QuicPacketNumber(number);
1175     return header;
1176   }
1177 
ConstructDataPacket(uint64_t number,bool has_stop_waiting,EncryptionLevel level)1178   std::unique_ptr<QuicPacket> ConstructDataPacket(uint64_t number,
1179                                                   bool has_stop_waiting,
1180                                                   EncryptionLevel level) {
1181     QuicPacketHeader header = ConstructPacketHeader(number, level);
1182     QuicFrames frames;
1183     if (VersionHasIetfQuicFrames(version().transport_version) &&
1184         (level == ENCRYPTION_INITIAL || level == ENCRYPTION_HANDSHAKE)) {
1185       frames.push_back(QuicFrame(QuicPingFrame()));
1186       frames.push_back(QuicFrame(QuicPaddingFrame(100)));
1187     } else {
1188       frames.push_back(QuicFrame(frame1_));
1189       if (has_stop_waiting) {
1190         frames.push_back(QuicFrame(stop_waiting_));
1191       }
1192     }
1193     return ConstructPacket(header, frames);
1194   }
1195 
ConstructProbingPacket()1196   std::unique_ptr<SerializedPacket> ConstructProbingPacket() {
1197     peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1198     if (VersionHasIetfQuicFrames(version().transport_version)) {
1199       QuicPathFrameBuffer payload = {
1200           {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
1201       return QuicPacketCreatorPeer::
1202           SerializePathChallengeConnectivityProbingPacket(&peer_creator_,
1203                                                           payload);
1204     }
1205     QUICHE_DCHECK(!GetQuicReloadableFlag(quic_ignore_gquic_probing));
1206     return QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
1207         &peer_creator_);
1208   }
1209 
ConstructClosePacket(uint64_t number)1210   std::unique_ptr<QuicPacket> ConstructClosePacket(uint64_t number) {
1211     peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1212     QuicPacketHeader header;
1213     // Set connection_id to peer's in memory representation as this connection
1214     // close packet is created by peer_framer.
1215     if (peer_framer_.perspective() == Perspective::IS_SERVER) {
1216       header.source_connection_id = connection_id_;
1217       header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1218     } else {
1219       header.destination_connection_id = connection_id_;
1220       header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1221     }
1222 
1223     header.packet_number = QuicPacketNumber(number);
1224 
1225     QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
1226     QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
1227                                   kQuicErrorCode, NO_IETF_QUIC_ERROR, "",
1228                                   /*transport_close_frame_type=*/0);
1229     QuicFrames frames;
1230     frames.push_back(QuicFrame(&qccf));
1231     return ConstructPacket(header, frames);
1232   }
1233 
DefaultRetransmissionTime()1234   QuicTime::Delta DefaultRetransmissionTime() {
1235     return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
1236   }
1237 
DefaultDelayedAckTime()1238   QuicTime::Delta DefaultDelayedAckTime() {
1239     return QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs);
1240   }
1241 
InitStopWaitingFrame(uint64_t least_unacked)1242   const QuicStopWaitingFrame InitStopWaitingFrame(uint64_t least_unacked) {
1243     QuicStopWaitingFrame frame;
1244     frame.least_unacked = QuicPacketNumber(least_unacked);
1245     return frame;
1246   }
1247 
1248   // Construct a ack_frame that acks all packet numbers between 1 and
1249   // |largest_acked|, except |missing|.
1250   // REQUIRES: 1 <= |missing| < |largest_acked|
ConstructAckFrame(uint64_t largest_acked,uint64_t missing)1251   QuicAckFrame ConstructAckFrame(uint64_t largest_acked, uint64_t missing) {
1252     return ConstructAckFrame(QuicPacketNumber(largest_acked),
1253                              QuicPacketNumber(missing));
1254   }
1255 
ConstructAckFrame(QuicPacketNumber largest_acked,QuicPacketNumber missing)1256   QuicAckFrame ConstructAckFrame(QuicPacketNumber largest_acked,
1257                                  QuicPacketNumber missing) {
1258     if (missing == QuicPacketNumber(1)) {
1259       return InitAckFrame({{missing + 1, largest_acked + 1}});
1260     }
1261     return InitAckFrame(
1262         {{QuicPacketNumber(1), missing}, {missing + 1, largest_acked + 1}});
1263   }
1264 
1265   // Undo nacking a packet within the frame.
AckPacket(QuicPacketNumber arrived,QuicAckFrame * frame)1266   void AckPacket(QuicPacketNumber arrived, QuicAckFrame* frame) {
1267     EXPECT_FALSE(frame->packets.Contains(arrived));
1268     frame->packets.Add(arrived);
1269   }
1270 
TriggerConnectionClose()1271   void TriggerConnectionClose() {
1272     // Send an erroneous packet to close the connection.
1273     EXPECT_CALL(visitor_,
1274                 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
1275         .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
1276 
1277     EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1278     // Triggers a connection by receiving ACK of unsent packet.
1279     QuicAckFrame frame = InitAckFrame(10000);
1280     ProcessAckPacket(1, &frame);
1281     EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1282                  nullptr);
1283     EXPECT_EQ(1, connection_close_frame_count_);
1284     EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
1285                 IsError(QUIC_INVALID_ACK_DATA));
1286   }
1287 
BlockOnNextWrite()1288   void BlockOnNextWrite() {
1289     writer_->BlockOnNextWrite();
1290     EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
1291   }
1292 
SimulateNextPacketTooLarge()1293   void SimulateNextPacketTooLarge() { writer_->SimulateNextPacketTooLarge(); }
1294 
ExpectNextPacketUnprocessable()1295   void ExpectNextPacketUnprocessable() {
1296     writer_->ExpectNextPacketUnprocessable();
1297   }
1298 
AlwaysGetPacketTooLarge()1299   void AlwaysGetPacketTooLarge() { writer_->AlwaysGetPacketTooLarge(); }
1300 
SetWritePauseTimeDelta(QuicTime::Delta delta)1301   void SetWritePauseTimeDelta(QuicTime::Delta delta) {
1302     writer_->SetWritePauseTimeDelta(delta);
1303   }
1304 
CongestionBlockWrites()1305   void CongestionBlockWrites() {
1306     EXPECT_CALL(*send_algorithm_, CanSend(_))
1307         .WillRepeatedly(testing::Return(false));
1308   }
1309 
CongestionUnblockWrites()1310   void CongestionUnblockWrites() {
1311     EXPECT_CALL(*send_algorithm_, CanSend(_))
1312         .WillRepeatedly(testing::Return(true));
1313   }
1314 
set_perspective(Perspective perspective)1315   void set_perspective(Perspective perspective) {
1316     connection_.set_perspective(perspective);
1317     if (perspective == Perspective::IS_SERVER) {
1318       connection_.set_can_truncate_connection_ids(true);
1319       QuicConnectionPeer::SetNegotiatedVersion(&connection_);
1320       connection_.OnSuccessfulVersionNegotiation();
1321     }
1322     QuicFramerPeer::SetPerspective(&peer_framer_,
1323                                    QuicUtils::InvertPerspective(perspective));
1324     peer_framer_.SetInitialObfuscators(TestConnectionId());
1325     for (EncryptionLevel level : {ENCRYPTION_ZERO_RTT, ENCRYPTION_HANDSHAKE,
1326                                   ENCRYPTION_FORWARD_SECURE}) {
1327       if (peer_framer_.HasEncrypterOfEncryptionLevel(level)) {
1328         peer_creator_.SetEncrypter(level,
1329                                    std::make_unique<TaggingEncrypter>(level));
1330       }
1331     }
1332   }
1333 
set_packets_between_probes_base(const QuicPacketCount packets_between_probes_base)1334   void set_packets_between_probes_base(
1335       const QuicPacketCount packets_between_probes_base) {
1336     QuicConnectionPeer::ReInitializeMtuDiscoverer(
1337         &connection_, packets_between_probes_base,
1338         QuicPacketNumber(packets_between_probes_base));
1339   }
1340 
IsDefaultTestConfiguration()1341   bool IsDefaultTestConfiguration() {
1342     TestParams p = GetParam();
1343     return p.ack_response == AckResponse::kImmediate &&
1344            p.version == AllSupportedVersions()[0];
1345   }
1346 
TestConnectionCloseQuicErrorCode(QuicErrorCode expected_code)1347   void TestConnectionCloseQuicErrorCode(QuicErrorCode expected_code) {
1348     // Not strictly needed for this test, but is commonly done.
1349     EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1350                  nullptr);
1351     const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
1352         writer_->connection_close_frames();
1353     ASSERT_EQ(1u, connection_close_frames.size());
1354 
1355     EXPECT_THAT(connection_close_frames[0].quic_error_code,
1356                 IsError(expected_code));
1357 
1358     if (!VersionHasIetfQuicFrames(version().transport_version)) {
1359       EXPECT_THAT(connection_close_frames[0].wire_error_code,
1360                   IsError(expected_code));
1361       EXPECT_EQ(GOOGLE_QUIC_CONNECTION_CLOSE,
1362                 connection_close_frames[0].close_type);
1363       return;
1364     }
1365 
1366     QuicErrorCodeToIetfMapping mapping =
1367         QuicErrorCodeToTransportErrorCode(expected_code);
1368 
1369     if (mapping.is_transport_close) {
1370       // This Google QUIC Error Code maps to a transport close,
1371       EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
1372                 connection_close_frames[0].close_type);
1373     } else {
1374       // This maps to an application close.
1375       EXPECT_EQ(IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
1376                 connection_close_frames[0].close_type);
1377     }
1378     EXPECT_EQ(mapping.error_code, connection_close_frames[0].wire_error_code);
1379   }
1380 
MtuDiscoveryTestInit()1381   void MtuDiscoveryTestInit() {
1382     set_perspective(Perspective::IS_SERVER);
1383     QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1384     if (version().SupportsAntiAmplificationLimit()) {
1385       QuicConnectionPeer::SetAddressValidated(&connection_);
1386     }
1387     connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1388     peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1389     // Prevent packets from being coalesced.
1390     EXPECT_CALL(visitor_, GetHandshakeState())
1391         .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1392     EXPECT_TRUE(connection_.connected());
1393   }
1394 
PathProbeTestInit(Perspective perspective,bool receive_new_server_connection_id=true)1395   void PathProbeTestInit(Perspective perspective,
1396                          bool receive_new_server_connection_id = true) {
1397     set_perspective(perspective);
1398     connection_.CreateConnectionIdManager();
1399     EXPECT_EQ(connection_.perspective(), perspective);
1400     if (perspective == Perspective::IS_SERVER) {
1401       QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1402     }
1403     connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1404     peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1405     // Discard INITIAL key.
1406     connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
1407     connection_.NeuterUnencryptedPackets();
1408     // Prevent packets from being coalesced.
1409     EXPECT_CALL(visitor_, GetHandshakeState())
1410         .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1411     if (version().SupportsAntiAmplificationLimit() &&
1412         perspective == Perspective::IS_SERVER) {
1413       QuicConnectionPeer::SetAddressValidated(&connection_);
1414     }
1415     // Clear direct_peer_address.
1416     QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1417     // Clear effective_peer_address, it is the same as direct_peer_address for
1418     // this test.
1419     QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1420                                                 QuicSocketAddress());
1421     EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1422 
1423     if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1424       EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1425     } else {
1426       EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1427     }
1428     QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
1429     ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1430                                     kPeerAddress, ENCRYPTION_FORWARD_SECURE);
1431     EXPECT_EQ(kPeerAddress, connection_.peer_address());
1432     EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1433     if (perspective == Perspective::IS_CLIENT &&
1434         receive_new_server_connection_id && version().HasIetfQuicFrames()) {
1435       QuicNewConnectionIdFrame frame;
1436       frame.connection_id = TestConnectionId(1234);
1437       ASSERT_NE(frame.connection_id, connection_.connection_id());
1438       frame.stateless_reset_token =
1439           QuicUtils::GenerateStatelessResetToken(frame.connection_id);
1440       frame.retire_prior_to = 0u;
1441       frame.sequence_number = 1u;
1442       connection_.OnNewConnectionIdFrame(frame);
1443     }
1444   }
1445 
ServerHandlePreferredAddressInit()1446   void ServerHandlePreferredAddressInit() {
1447     ASSERT_TRUE(GetParam().version.HasIetfQuicFrames());
1448     set_perspective(Perspective::IS_SERVER);
1449     connection_.CreateConnectionIdManager();
1450     QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1451     SetQuicReloadableFlag(quic_use_received_client_addresses_cache, true);
1452     EXPECT_CALL(visitor_, AllowSelfAddressChange())
1453         .WillRepeatedly(Return(true));
1454 
1455     connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1456     peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1457     // Discard INITIAL key.
1458     connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
1459     connection_.NeuterUnencryptedPackets();
1460     // Prevent packets from being coalesced.
1461     EXPECT_CALL(visitor_, GetHandshakeState())
1462         .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1463     if (version().SupportsAntiAmplificationLimit()) {
1464       QuicConnectionPeer::SetAddressValidated(&connection_);
1465     }
1466     // Clear direct_peer_address.
1467     QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1468     // Clear effective_peer_address, it is the same as direct_peer_address for
1469     // this test.
1470     QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1471                                                 QuicSocketAddress());
1472     EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1473 
1474     if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1475       EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1476     } else {
1477       EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1478     }
1479     QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
1480     ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1481                                     kPeerAddress, ENCRYPTION_FORWARD_SECURE);
1482     EXPECT_EQ(kPeerAddress, connection_.peer_address());
1483     EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1484     QuicConfig config;
1485     EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
1486     connection_.SetFromConfig(config);
1487     connection_.set_expected_server_preferred_address(kServerPreferredAddress);
1488   }
1489 
1490   // Receive server preferred address.
ServerPreferredAddressInit(QuicConfig & config)1491   void ServerPreferredAddressInit(QuicConfig& config) {
1492     ASSERT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1493     ASSERT_TRUE(version().HasIetfQuicFrames());
1494     ASSERT_TRUE(connection_.self_address().host().IsIPv6());
1495     const QuicConnectionId connection_id = TestConnectionId(17);
1496     const StatelessResetToken reset_token =
1497         QuicUtils::GenerateStatelessResetToken(connection_id);
1498 
1499     connection_.CreateConnectionIdManager();
1500 
1501     connection_.SendCryptoStreamData();
1502     EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
1503     EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
1504     QuicAckFrame frame = InitAckFrame(1);
1505     // Received ACK for packet 1.
1506     ProcessFramePacketAtLevel(1, QuicFrame(&frame), ENCRYPTION_INITIAL);
1507     // Discard INITIAL key.
1508     connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
1509     connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1510 
1511     config.SetConnectionOptionsToSend(QuicTagVector{kSPAD});
1512     QuicConfigPeer::SetReceivedStatelessResetToken(&config,
1513                                                    kTestStatelessResetToken);
1514     QuicConfigPeer::SetReceivedAlternateServerAddress(&config,
1515                                                       kServerPreferredAddress);
1516     QuicConfigPeer::SetPreferredAddressConnectionIdAndToken(
1517         &config, connection_id, reset_token);
1518     EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
1519     connection_.SetFromConfig(config);
1520 
1521     ASSERT_TRUE(
1522         QuicConnectionPeer::GetReceivedServerPreferredAddress(&connection_)
1523             .IsInitialized());
1524     EXPECT_EQ(
1525         kServerPreferredAddress,
1526         QuicConnectionPeer::GetReceivedServerPreferredAddress(&connection_));
1527   }
1528 
1529   // If defer sending is enabled, tell |visitor_| to return true on the next
1530   // call to WillingAndAbleToWrite().
1531   // This function can be used before a call to ProcessXxxPacket, to allow the
1532   // process function to schedule and fire the send alarm at the end.
ForceWillingAndAbleToWriteOnceForDeferSending()1533   void ForceWillingAndAbleToWriteOnceForDeferSending() {
1534     if (GetParam().ack_response == AckResponse::kDefer) {
1535       EXPECT_CALL(visitor_, WillingAndAbleToWrite())
1536           .WillOnce(Return(true))
1537           .RetiresOnSaturation();
1538     }
1539   }
1540 
1541   void TestClientRetryHandling(bool invalid_retry_tag,
1542                                bool missing_original_id_in_config,
1543                                bool wrong_original_id_in_config,
1544                                bool missing_retry_id_in_config,
1545                                bool wrong_retry_id_in_config);
1546 
1547   void TestReplaceConnectionIdFromInitial();
1548 
1549   QuicConnectionId connection_id_;
1550   QuicFramer framer_;
1551 
1552   MockSendAlgorithm* send_algorithm_;
1553   std::unique_ptr<MockLossAlgorithm> loss_algorithm_;
1554   MockClock clock_;
1555   MockRandom random_generator_;
1556   quiche::SimpleBufferAllocator buffer_allocator_;
1557   std::unique_ptr<TestConnectionHelper> helper_;
1558   std::unique_ptr<TestAlarmFactory> alarm_factory_;
1559   QuicFramer peer_framer_;
1560   QuicPacketCreator peer_creator_;
1561   std::unique_ptr<TestPacketWriter> writer_;
1562   TestConnection connection_;
1563   QuicPacketCreator* creator_;
1564   QuicSentPacketManager* manager_;
1565   StrictMock<MockQuicConnectionVisitor> visitor_;
1566 
1567   QuicStreamFrame frame1_;
1568   QuicStreamFrame frame2_;
1569   QuicCryptoFrame crypto_frame_;
1570   QuicAckFrame ack_;
1571   QuicStopWaitingFrame stop_waiting_;
1572   QuicPacketNumberLength packet_number_length_;
1573   QuicConnectionIdIncluded connection_id_included_;
1574 
1575   SimpleSessionNotifier notifier_;
1576 
1577   QuicConnectionCloseFrame saved_connection_close_frame_;
1578   int connection_close_frame_count_;
1579   MockConnectionIdGenerator connection_id_generator_;
1580 };
1581 
1582 // Run all end to end tests with all supported versions.
1583 INSTANTIATE_TEST_SUITE_P(QuicConnectionTests, QuicConnectionTest,
1584                          ::testing::ValuesIn(GetTestParams()),
1585                          ::testing::PrintToStringParamName());
1586 
1587 // These two tests ensure that the QuicErrorCode mapping works correctly.
1588 // Both tests expect to see a Google QUIC close if not running IETF QUIC.
1589 // If running IETF QUIC, the first will generate a transport connection
1590 // close, the second an application connection close.
1591 // The connection close codes for the two tests are manually chosen;
1592 // they are expected to always map to transport- and application-
1593 // closes, respectively. If that changes, new codes should be chosen.
TEST_P(QuicConnectionTest,CloseErrorCodeTestTransport)1594 TEST_P(QuicConnectionTest, CloseErrorCodeTestTransport) {
1595   EXPECT_TRUE(connection_.connected());
1596   EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1597   connection_.CloseConnection(
1598       IETF_QUIC_PROTOCOL_VIOLATION, "Should be transport close",
1599       ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1600   EXPECT_FALSE(connection_.connected());
1601   TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
1602 }
1603 
1604 // Test that the IETF QUIC Error code mapping function works
1605 // properly for application connection close codes.
TEST_P(QuicConnectionTest,CloseErrorCodeTestApplication)1606 TEST_P(QuicConnectionTest, CloseErrorCodeTestApplication) {
1607   EXPECT_TRUE(connection_.connected());
1608   EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1609   connection_.CloseConnection(
1610       QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE,
1611       "Should be application close",
1612       ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1613   EXPECT_FALSE(connection_.connected());
1614   TestConnectionCloseQuicErrorCode(QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE);
1615 }
1616 
TEST_P(QuicConnectionTest,SelfAddressChangeAtClient)1617 TEST_P(QuicConnectionTest, SelfAddressChangeAtClient) {
1618   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1619 
1620   EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1621   EXPECT_TRUE(connection_.connected());
1622 
1623   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1624     EXPECT_CALL(visitor_, OnCryptoFrame(_));
1625   } else {
1626     EXPECT_CALL(visitor_, OnStreamFrame(_));
1627   }
1628   ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1629                                   ENCRYPTION_INITIAL);
1630   // Cause change in self_address.
1631   QuicIpAddress host;
1632   host.FromString("1.1.1.1");
1633   QuicSocketAddress self_address(host, 123);
1634   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1635     EXPECT_CALL(visitor_, OnCryptoFrame(_));
1636   } else {
1637     EXPECT_CALL(visitor_, OnStreamFrame(_));
1638   }
1639   ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address, kPeerAddress,
1640                                   ENCRYPTION_INITIAL);
1641   EXPECT_TRUE(connection_.connected());
1642   EXPECT_NE(connection_.self_address(), self_address);
1643 }
1644 
TEST_P(QuicConnectionTest,SelfAddressChangeAtServer)1645 TEST_P(QuicConnectionTest, SelfAddressChangeAtServer) {
1646   set_perspective(Perspective::IS_SERVER);
1647   QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1648 
1649   EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1650   EXPECT_TRUE(connection_.connected());
1651 
1652   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1653     EXPECT_CALL(visitor_, OnCryptoFrame(_));
1654   } else {
1655     EXPECT_CALL(visitor_, OnStreamFrame(_));
1656   }
1657   ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1658                                   ENCRYPTION_INITIAL);
1659   // Cause change in self_address.
1660   QuicIpAddress host;
1661   host.FromString("1.1.1.1");
1662   QuicSocketAddress self_address(host, 123);
1663   EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
1664   EXPECT_CALL(visitor_, AllowSelfAddressChange()).WillOnce(Return(false));
1665   ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address, kPeerAddress,
1666                                   ENCRYPTION_INITIAL);
1667   EXPECT_TRUE(connection_.connected());
1668   EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
1669 }
1670 
TEST_P(QuicConnectionTest,AllowSelfAddressChangeToMappedIpv4AddressAtServer)1671 TEST_P(QuicConnectionTest, AllowSelfAddressChangeToMappedIpv4AddressAtServer) {
1672   set_perspective(Perspective::IS_SERVER);
1673   QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1674 
1675   EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1676   EXPECT_TRUE(connection_.connected());
1677 
1678   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1679     EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
1680   } else {
1681     EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
1682   }
1683   QuicIpAddress host;
1684   host.FromString("1.1.1.1");
1685   QuicSocketAddress self_address1(host, 443);
1686   connection_.SetSelfAddress(self_address1);
1687   ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1,
1688                                   kPeerAddress, ENCRYPTION_INITIAL);
1689   // Cause self_address change to mapped Ipv4 address.
1690   QuicIpAddress host2;
1691   host2.FromString(
1692       absl::StrCat("::ffff:", connection_.self_address().host().ToString()));
1693   QuicSocketAddress self_address2(host2, connection_.self_address().port());
1694   ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address2,
1695                                   kPeerAddress, ENCRYPTION_INITIAL);
1696   EXPECT_TRUE(connection_.connected());
1697   // self_address change back to Ipv4 address.
1698   ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1,
1699                                   kPeerAddress, ENCRYPTION_INITIAL);
1700   EXPECT_TRUE(connection_.connected());
1701 }
1702 
TEST_P(QuicConnectionTest,ClientAddressChangeAndPacketReordered)1703 TEST_P(QuicConnectionTest, ClientAddressChangeAndPacketReordered) {
1704   set_perspective(Perspective::IS_SERVER);
1705   QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1706   EXPECT_CALL(visitor_, GetHandshakeState())
1707       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1708 
1709   // Clear direct_peer_address.
1710   QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1711   // Clear effective_peer_address, it is the same as direct_peer_address for
1712   // this test.
1713   QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1714                                               QuicSocketAddress());
1715 
1716   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1717     EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1718   } else {
1719     EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1720   }
1721   QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
1722   const QuicSocketAddress kNewPeerAddress =
1723       QuicSocketAddress(QuicIpAddress::Loopback6(),
1724                         /*port=*/23456);
1725   ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1726                                   kNewPeerAddress, ENCRYPTION_INITIAL);
1727   EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1728   EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1729 
1730   // Decrease packet number to simulate out-of-order packets.
1731   QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
1732   // This is an old packet, do not migrate.
1733   EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1734   ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1735                                   ENCRYPTION_INITIAL);
1736   EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1737   EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1738 }
1739 
TEST_P(QuicConnectionTest,PeerPortChangeAtServer)1740 TEST_P(QuicConnectionTest, PeerPortChangeAtServer) {
1741   set_perspective(Perspective::IS_SERVER);
1742   QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1743   EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1744   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1745   // Prevent packets from being coalesced.
1746   EXPECT_CALL(visitor_, GetHandshakeState())
1747       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1748   if (version().SupportsAntiAmplificationLimit()) {
1749     QuicConnectionPeer::SetAddressValidated(&connection_);
1750   }
1751 
1752   // Clear direct_peer_address.
1753   QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1754   // Clear effective_peer_address, it is the same as direct_peer_address for
1755   // this test.
1756   QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1757                                               QuicSocketAddress());
1758   EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1759 
1760   RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
1761   QuicTime::Delta default_init_rtt = rtt_stats->initial_rtt();
1762   rtt_stats->set_initial_rtt(default_init_rtt * 2);
1763   EXPECT_EQ(2 * default_init_rtt, rtt_stats->initial_rtt());
1764 
1765   QuicSentPacketManagerPeer::SetConsecutivePtoCount(manager_, 1);
1766   EXPECT_EQ(1u, manager_->GetConsecutivePtoCount());
1767 
1768   const QuicSocketAddress kNewPeerAddress =
1769       QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1770   EXPECT_CALL(visitor_, OnStreamFrame(_))
1771       .WillOnce(Invoke(
1772           [=]() { EXPECT_EQ(kPeerAddress, connection_.peer_address()); }))
1773       .WillOnce(Invoke(
1774           [=]() { EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); }));
1775   QuicFrames frames;
1776   frames.push_back(QuicFrame(frame1_));
1777   ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
1778                                    ENCRYPTION_FORWARD_SECURE);
1779   EXPECT_EQ(kPeerAddress, connection_.peer_address());
1780   EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1781 
1782   // Process another packet with a different peer address on server side will
1783   // start connection migration.
1784   EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
1785   QuicFrames frames2;
1786   frames2.push_back(QuicFrame(frame2_));
1787   ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
1788                                    ENCRYPTION_FORWARD_SECURE);
1789   EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1790   EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1791   // PORT_CHANGE shouldn't state change in sent packet manager.
1792   EXPECT_EQ(2 * default_init_rtt, rtt_stats->initial_rtt());
1793   EXPECT_EQ(1u, manager_->GetConsecutivePtoCount());
1794   EXPECT_EQ(manager_->GetSendAlgorithm(), send_algorithm_);
1795   if (version().HasIetfQuicFrames()) {
1796     EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
1797     EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
1798     EXPECT_EQ(1u, connection_.num_linkable_client_migration());
1799   }
1800 }
1801 
TEST_P(QuicConnectionTest,PeerIpAddressChangeAtServer)1802 TEST_P(QuicConnectionTest, PeerIpAddressChangeAtServer) {
1803   set_perspective(Perspective::IS_SERVER);
1804   if (!version().SupportsAntiAmplificationLimit() ||
1805       GetQuicFlag(quic_enforce_strict_amplification_factor)) {
1806     return;
1807   }
1808   QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1809   EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1810   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1811   // Discard INITIAL key.
1812   connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
1813   connection_.NeuterUnencryptedPackets();
1814   // Prevent packets from being coalesced.
1815   EXPECT_CALL(visitor_, GetHandshakeState())
1816       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1817   QuicConnectionPeer::SetAddressValidated(&connection_);
1818   connection_.OnHandshakeComplete();
1819 
1820   // Enable 5 RTO
1821   QuicConfig config;
1822   QuicTagVector connection_options;
1823   connection_options.push_back(k5RTO);
1824   config.SetInitialReceivedConnectionOptions(connection_options);
1825   QuicConfigPeer::SetNegotiated(&config, true);
1826   QuicConfigPeer::SetReceivedOriginalConnectionId(&config,
1827                                                   connection_.connection_id());
1828   QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
1829                                                        QuicConnectionId());
1830   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
1831   connection_.SetFromConfig(config);
1832 
1833   // Clear direct_peer_address.
1834   QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1835   // Clear effective_peer_address, it is the same as direct_peer_address for
1836   // this test.
1837   QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1838                                               QuicSocketAddress());
1839   EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1840 
1841   const QuicSocketAddress kNewPeerAddress =
1842       QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
1843   EXPECT_CALL(visitor_, OnStreamFrame(_))
1844       .WillOnce(Invoke(
1845           [=]() { EXPECT_EQ(kPeerAddress, connection_.peer_address()); }))
1846       .WillOnce(Invoke(
1847           [=]() { EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); }));
1848   QuicFrames frames;
1849   frames.push_back(QuicFrame(frame1_));
1850   ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
1851                                    ENCRYPTION_FORWARD_SECURE);
1852   EXPECT_EQ(kPeerAddress, connection_.peer_address());
1853   EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1854 
1855   // Send some data to make connection has packets in flight.
1856   connection_.SendStreamData3();
1857   EXPECT_EQ(1u, writer_->packets_write_attempts());
1858   EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
1859   EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
1860 
1861   // Process another packet with a different peer address on server side will
1862   // start connection migration.
1863   EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
1864   // IETF QUIC send algorithm should be changed to a different object, so no
1865   // OnPacketSent() called on the old send algorithm.
1866   EXPECT_CALL(*send_algorithm_,
1867               OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
1868       .Times(0);
1869   // Do not propagate OnCanWrite() to session notifier.
1870   EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
1871 
1872   QuicFrames frames2;
1873   frames2.push_back(QuicFrame(frame2_));
1874   ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
1875                                    ENCRYPTION_FORWARD_SECURE);
1876   EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1877   EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1878   EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
1879             connection_.active_effective_peer_migration_type());
1880   EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
1881   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1882 
1883   EXPECT_EQ(2u, writer_->packets_write_attempts());
1884   EXPECT_FALSE(writer_->path_challenge_frames().empty());
1885   QuicPathFrameBuffer payload =
1886       writer_->path_challenge_frames().front().data_buffer;
1887   EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
1888             send_algorithm_);
1889   // Switch to use the mock send algorithm.
1890   send_algorithm_ = new StrictMock<MockSendAlgorithm>();
1891   EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
1892   EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
1893       .WillRepeatedly(Return(kDefaultTCPMSS));
1894   EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
1895   EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
1896       .Times(AnyNumber())
1897       .WillRepeatedly(Return(QuicBandwidth::Zero()));
1898   EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
1899   EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
1900   EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
1901   connection_.SetSendAlgorithm(send_algorithm_);
1902 
1903   // PATH_CHALLENGE is expanded upto the max packet size which may exceeds the
1904   // anti-amplification limit.
1905   EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
1906   EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1907   EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1908   EXPECT_EQ(1u,
1909             connection_.GetStats().num_reverse_path_validtion_upon_migration);
1910 
1911   // Verify server is throttled by anti-amplification limit.
1912   connection_.SendCryptoDataWithString("foo", 0);
1913   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1914 
1915   // Receiving an ACK to the packet sent after changing peer address doesn't
1916   // finish migration validation.
1917   QuicAckFrame ack_frame = InitAckFrame(2);
1918   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
1919   ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress,
1920                                   kNewPeerAddress, ENCRYPTION_FORWARD_SECURE);
1921   EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1922   EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1923   EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
1924             connection_.active_effective_peer_migration_type());
1925 
1926   // Receiving PATH_RESPONSE should lift the anti-amplification limit.
1927   QuicFrames frames3;
1928   frames3.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
1929   EXPECT_CALL(visitor_, MaybeSendAddressToken());
1930   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1931       .Times(testing::AtLeast(1u));
1932   ProcessFramesPacketWithAddresses(frames3, kSelfAddress, kNewPeerAddress,
1933                                    ENCRYPTION_FORWARD_SECURE);
1934   EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
1935 
1936   // Verify the anti-amplification limit is lifted by sending a packet larger
1937   // than the anti-amplification limit.
1938   connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0);
1939   EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
1940   EXPECT_EQ(1u, connection_.num_linkable_client_migration());
1941 }
1942 
TEST_P(QuicConnectionTest,PeerIpAddressChangeAtServerWithMissingConnectionId)1943 TEST_P(QuicConnectionTest, PeerIpAddressChangeAtServerWithMissingConnectionId) {
1944   set_perspective(Perspective::IS_SERVER);
1945   if (!version().HasIetfQuicFrames()) {
1946     return;
1947   }
1948   QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1949   EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1950 
1951   QuicConnectionId client_cid0 = TestConnectionId(1);
1952   QuicConnectionId client_cid1 = TestConnectionId(3);
1953   QuicConnectionId server_cid1;
1954   SetClientConnectionId(client_cid0);
1955   connection_.CreateConnectionIdManager();
1956   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1957   // Prevent packets from being coalesced.
1958   EXPECT_CALL(visitor_, GetHandshakeState())
1959       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1960   QuicConnectionPeer::SetAddressValidated(&connection_);
1961 
1962   // Sends new server CID to client.
1963   if (!connection_.connection_id().IsEmpty()) {
1964     EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
1965         .WillOnce(Return(TestConnectionId(456)));
1966   }
1967   EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
1968       .WillOnce(Invoke([&](const QuicConnectionId& cid) {
1969         server_cid1 = cid;
1970         return true;
1971       }));
1972   EXPECT_CALL(visitor_, SendNewConnectionId(_));
1973   connection_.OnHandshakeComplete();
1974 
1975   // Clear direct_peer_address.
1976   QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1977   // Clear effective_peer_address, it is the same as direct_peer_address for
1978   // this test.
1979   QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1980                                               QuicSocketAddress());
1981   EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1982 
1983   const QuicSocketAddress kNewPeerAddress =
1984       QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
1985   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
1986   QuicFrames frames;
1987   frames.push_back(QuicFrame(frame1_));
1988   ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
1989                                    ENCRYPTION_FORWARD_SECURE);
1990   EXPECT_EQ(kPeerAddress, connection_.peer_address());
1991   EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1992 
1993   // Send some data to make connection has packets in flight.
1994   connection_.SendStreamData3();
1995   EXPECT_EQ(1u, writer_->packets_write_attempts());
1996 
1997   // Process another packet with a different peer address on server side will
1998   // start connection migration.
1999   peer_creator_.SetServerConnectionId(server_cid1);
2000   EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
2001   // Do not propagate OnCanWrite() to session notifier.
2002   EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
2003 
2004   QuicFrames frames2;
2005   frames2.push_back(QuicFrame(frame2_));
2006   if (GetQuicFlag(quic_enforce_strict_amplification_factor)) {
2007     frames2.push_back(QuicFrame(QuicPaddingFrame(-1)));
2008   }
2009   ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
2010                                    ENCRYPTION_FORWARD_SECURE);
2011   EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2012   EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2013 
2014   // Writing path response & reverse path challenge is blocked due to missing
2015   // client connection ID, i.e., packets_write_attempts is unchanged.
2016   EXPECT_EQ(1u, writer_->packets_write_attempts());
2017 
2018   // Receives new client CID from client would unblock write.
2019   QuicNewConnectionIdFrame new_cid_frame;
2020   new_cid_frame.connection_id = client_cid1;
2021   new_cid_frame.sequence_number = 1u;
2022   new_cid_frame.retire_prior_to = 0u;
2023   connection_.OnNewConnectionIdFrame(new_cid_frame);
2024   connection_.SendStreamData3();
2025 
2026   EXPECT_EQ(2u, writer_->packets_write_attempts());
2027 }
2028 
TEST_P(QuicConnectionTest,EffectivePeerAddressChangeAtServer)2029 TEST_P(QuicConnectionTest, EffectivePeerAddressChangeAtServer) {
2030   if (GetQuicFlag(quic_enforce_strict_amplification_factor)) {
2031     return;
2032   }
2033   set_perspective(Perspective::IS_SERVER);
2034   QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2035   EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2036   if (version().SupportsAntiAmplificationLimit()) {
2037     QuicConnectionPeer::SetAddressValidated(&connection_);
2038   }
2039   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2040   // Discard INITIAL key.
2041   connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
2042   connection_.NeuterUnencryptedPackets();
2043   EXPECT_CALL(visitor_, GetHandshakeState())
2044       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2045 
2046   // Clear direct_peer_address.
2047   QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2048   // Clear effective_peer_address, it is different from direct_peer_address for
2049   // this test.
2050   QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2051                                               QuicSocketAddress());
2052   const QuicSocketAddress kEffectivePeerAddress =
2053       QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/43210);
2054   connection_.ReturnEffectivePeerAddressForNextPacket(kEffectivePeerAddress);
2055 
2056   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2057     EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2058   } else {
2059     EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2060   }
2061   ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2062                                   ENCRYPTION_FORWARD_SECURE);
2063   EXPECT_EQ(kPeerAddress, connection_.peer_address());
2064   EXPECT_EQ(kEffectivePeerAddress, connection_.effective_peer_address());
2065 
2066   // Process another packet with the same direct peer address and different
2067   // effective peer address on server side will start connection migration.
2068   const QuicSocketAddress kNewEffectivePeerAddress =
2069       QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/54321);
2070   connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
2071   EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2072   ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2073                                   ENCRYPTION_FORWARD_SECURE);
2074   EXPECT_EQ(kPeerAddress, connection_.peer_address());
2075   EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
2076   EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
2077   if (GetParam().version.HasIetfQuicFrames()) {
2078     EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
2079     EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
2080     EXPECT_EQ(1u, connection_.num_linkable_client_migration());
2081   }
2082 
2083   // Process another packet with a different direct peer address and the same
2084   // effective peer address on server side will not start connection migration.
2085   const QuicSocketAddress kNewPeerAddress =
2086       QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2087   connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
2088   EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2089 
2090   if (!GetParam().version.HasIetfQuicFrames()) {
2091     // ack_frame is used to complete the migration started by the last packet,
2092     // we need to make sure a new migration does not start after the previous
2093     // one is completed.
2094     QuicAckFrame ack_frame = InitAckFrame(1);
2095     EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
2096     ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress,
2097                                     kNewPeerAddress, ENCRYPTION_FORWARD_SECURE);
2098     EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2099     EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
2100     EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
2101   }
2102 
2103   // Process another packet with different direct peer address and different
2104   // effective peer address on server side will start connection migration.
2105   const QuicSocketAddress kNewerEffectivePeerAddress =
2106       QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/65432);
2107   const QuicSocketAddress kFinalPeerAddress =
2108       QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/34567);
2109   connection_.ReturnEffectivePeerAddressForNextPacket(
2110       kNewerEffectivePeerAddress);
2111   EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2112   ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2113                                   kFinalPeerAddress, ENCRYPTION_FORWARD_SECURE);
2114   EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
2115   EXPECT_EQ(kNewerEffectivePeerAddress, connection_.effective_peer_address());
2116   if (GetParam().version.HasIetfQuicFrames()) {
2117     EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
2118     EXPECT_EQ(send_algorithm_,
2119               connection_.sent_packet_manager().GetSendAlgorithm());
2120     EXPECT_EQ(2u, connection_.GetStats().num_validated_peer_migration);
2121   }
2122 
2123   // While the previous migration is ongoing, process another packet with the
2124   // same direct peer address and different effective peer address on server
2125   // side will start a new connection migration.
2126   const QuicSocketAddress kNewestEffectivePeerAddress =
2127       QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/65430);
2128   connection_.ReturnEffectivePeerAddressForNextPacket(
2129       kNewestEffectivePeerAddress);
2130   EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
2131   if (!GetParam().version.HasIetfQuicFrames()) {
2132     EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(1);
2133   }
2134   ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2135                                   kFinalPeerAddress, ENCRYPTION_FORWARD_SECURE);
2136   EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
2137   EXPECT_EQ(kNewestEffectivePeerAddress, connection_.effective_peer_address());
2138   EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
2139             connection_.active_effective_peer_migration_type());
2140   if (GetParam().version.HasIetfQuicFrames()) {
2141     EXPECT_NE(send_algorithm_,
2142               connection_.sent_packet_manager().GetSendAlgorithm());
2143     EXPECT_EQ(kFinalPeerAddress, writer_->last_write_peer_address());
2144     EXPECT_FALSE(writer_->path_challenge_frames().empty());
2145     EXPECT_EQ(0u, connection_.GetStats()
2146                       .num_peer_migration_while_validating_default_path);
2147     EXPECT_TRUE(connection_.HasPendingPathValidation());
2148   }
2149 }
2150 
2151 // Regression test for b/200020764.
TEST_P(QuicConnectionTest,ConnectionMigrationWithPendingPaddingBytes)2152 TEST_P(QuicConnectionTest, ConnectionMigrationWithPendingPaddingBytes) {
2153   // TODO(haoyuewang) Move these test setup code to a common member function.
2154   set_perspective(Perspective::IS_SERVER);
2155   if (!version().HasIetfQuicFrames()) {
2156     return;
2157   }
2158   QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2159   connection_.CreateConnectionIdManager();
2160   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2161   QuicConnectionPeer::SetPeerAddress(&connection_, kPeerAddress);
2162   QuicConnectionPeer::SetEffectivePeerAddress(&connection_, kPeerAddress);
2163   QuicConnectionPeer::SetAddressValidated(&connection_);
2164 
2165   // Sends new server CID to client.
2166   QuicConnectionId new_cid;
2167   if (!connection_.connection_id().IsEmpty()) {
2168     EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
2169         .WillOnce(Return(TestConnectionId(456)));
2170   }
2171   EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
2172       .WillOnce(Invoke([&](const QuicConnectionId& cid) {
2173         new_cid = cid;
2174         return true;
2175       }));
2176   EXPECT_CALL(visitor_, SendNewConnectionId(_));
2177   // Discard INITIAL key.
2178   connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
2179   connection_.NeuterUnencryptedPackets();
2180   connection_.OnHandshakeComplete();
2181   EXPECT_CALL(visitor_, GetHandshakeState())
2182       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2183 
2184   auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
2185   packet_creator->FlushCurrentPacket();
2186   packet_creator->AddPendingPadding(50u);
2187   const QuicSocketAddress kPeerAddress3 =
2188       QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/56789);
2189   auto ack_frame = InitAckFrame(1);
2190   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
2191   EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2192   ProcessFramesPacketWithAddresses({QuicFrame(&ack_frame)}, kSelfAddress,
2193                                    kPeerAddress3, ENCRYPTION_FORWARD_SECURE);
2194   // Any pending frames/padding should be flushed before default_path_ is
2195   // temporarily reset.
2196   ASSERT_EQ(connection_.self_address_on_default_path_while_sending_packet()
2197                 .host()
2198                 .address_family(),
2199             IpAddressFamily::IP_V6);
2200 }
2201 
2202 // Regression test for b/196208556.
TEST_P(QuicConnectionTest,ReversePathValidationResponseReceivedFromUnexpectedPeerAddress)2203 TEST_P(QuicConnectionTest,
2204        ReversePathValidationResponseReceivedFromUnexpectedPeerAddress) {
2205   set_perspective(Perspective::IS_SERVER);
2206   if (!version().HasIetfQuicFrames() ||
2207       GetQuicFlag(quic_enforce_strict_amplification_factor)) {
2208     return;
2209   }
2210   QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2211   connection_.CreateConnectionIdManager();
2212   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2213   QuicConnectionPeer::SetPeerAddress(&connection_, kPeerAddress);
2214   QuicConnectionPeer::SetEffectivePeerAddress(&connection_, kPeerAddress);
2215   QuicConnectionPeer::SetAddressValidated(&connection_);
2216   EXPECT_EQ(kPeerAddress, connection_.peer_address());
2217   EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2218 
2219   // Sends new server CID to client.
2220   QuicConnectionId new_cid;
2221   if (!connection_.connection_id().IsEmpty()) {
2222     EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
2223         .WillOnce(Return(TestConnectionId(456)));
2224   }
2225   EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
2226       .WillOnce(Invoke([&](const QuicConnectionId& cid) {
2227         new_cid = cid;
2228         return true;
2229       }));
2230   EXPECT_CALL(visitor_, SendNewConnectionId(_));
2231   // Discard INITIAL key.
2232   connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
2233   connection_.NeuterUnencryptedPackets();
2234   connection_.OnHandshakeComplete();
2235   EXPECT_CALL(visitor_, GetHandshakeState())
2236       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2237 
2238   // Process a non-probing packet to migrate to path 2 and kick off reverse path
2239   // validation.
2240   EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
2241   const QuicSocketAddress kPeerAddress2 =
2242       QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
2243   peer_creator_.SetServerConnectionId(new_cid);
2244   ProcessFramesPacketWithAddresses({QuicFrame(QuicPingFrame())}, kSelfAddress,
2245                                    kPeerAddress2, ENCRYPTION_FORWARD_SECURE);
2246   EXPECT_FALSE(writer_->path_challenge_frames().empty());
2247   QuicPathFrameBuffer reverse_path_challenge_payload =
2248       writer_->path_challenge_frames().front().data_buffer;
2249 
2250   // Receiveds a packet from path 3 with PATH_RESPONSE frame intended to
2251   // validate path 2 and a non-probing frame.
2252   {
2253     QuicConnection::ScopedPacketFlusher flusher(&connection_);
2254     const QuicSocketAddress kPeerAddress3 =
2255         QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/56789);
2256     auto ack_frame = InitAckFrame(1);
2257     EXPECT_CALL(visitor_, OnConnectionMigration(IPV4_TO_IPV6_CHANGE)).Times(1);
2258     EXPECT_CALL(visitor_, MaybeSendAddressToken()).WillOnce(Invoke([this]() {
2259       connection_.SendControlFrame(
2260           QuicFrame(new QuicNewTokenFrame(1, "new_token")));
2261       return true;
2262     }));
2263     ProcessFramesPacketWithAddresses(
2264         {QuicFrame(QuicPathResponseFrame(0, reverse_path_challenge_payload)),
2265          QuicFrame(&ack_frame)},
2266         kSelfAddress, kPeerAddress3, ENCRYPTION_FORWARD_SECURE);
2267   }
2268 }
2269 
TEST_P(QuicConnectionTest,ReversePathValidationFailureAtServer)2270 TEST_P(QuicConnectionTest, ReversePathValidationFailureAtServer) {
2271   set_perspective(Perspective::IS_SERVER);
2272   if (!version().HasIetfQuicFrames()) {
2273     return;
2274   }
2275   QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2276   EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2277   SetClientConnectionId(TestConnectionId(1));
2278   connection_.CreateConnectionIdManager();
2279   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2280   // Discard INITIAL key.
2281   connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
2282   connection_.NeuterUnencryptedPackets();
2283   // Prevent packets from being coalesced.
2284   EXPECT_CALL(visitor_, GetHandshakeState())
2285       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2286   QuicConnectionPeer::SetAddressValidated(&connection_);
2287 
2288   QuicConnectionId client_cid0 = connection_.client_connection_id();
2289   QuicConnectionId client_cid1 = TestConnectionId(2);
2290   QuicConnectionId server_cid0 = connection_.connection_id();
2291   QuicConnectionId server_cid1;
2292   // Sends new server CID to client.
2293   if (!connection_.connection_id().IsEmpty()) {
2294     EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
2295         .WillOnce(Return(TestConnectionId(456)));
2296   }
2297   EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
2298       .WillOnce(Invoke([&](const QuicConnectionId& cid) {
2299         server_cid1 = cid;
2300         return true;
2301       }));
2302   EXPECT_CALL(visitor_, SendNewConnectionId(_));
2303   connection_.OnHandshakeComplete();
2304   // Receives new client CID from client.
2305   QuicNewConnectionIdFrame new_cid_frame;
2306   new_cid_frame.connection_id = client_cid1;
2307   new_cid_frame.sequence_number = 1u;
2308   new_cid_frame.retire_prior_to = 0u;
2309   connection_.OnNewConnectionIdFrame(new_cid_frame);
2310   auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
2311   ASSERT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
2312   ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
2313 
2314   // Clear direct_peer_address.
2315   QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2316   // Clear effective_peer_address, it is the same as direct_peer_address for
2317   // this test.
2318   QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2319                                               QuicSocketAddress());
2320   EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2321 
2322   const QuicSocketAddress kNewPeerAddress =
2323       QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
2324   EXPECT_CALL(visitor_, OnStreamFrame(_))
2325       .WillOnce(Invoke(
2326           [=]() { EXPECT_EQ(kPeerAddress, connection_.peer_address()); }))
2327       .WillOnce(Invoke(
2328           [=]() { EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); }));
2329   QuicFrames frames;
2330   frames.push_back(QuicFrame(frame1_));
2331   ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
2332                                    ENCRYPTION_FORWARD_SECURE);
2333   EXPECT_EQ(kPeerAddress, connection_.peer_address());
2334   EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2335 
2336   // Process another packet with a different peer address on server side will
2337   // start connection migration.
2338   EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
2339   // IETF QUIC send algorithm should be changed to a different object, so no
2340   // OnPacketSent() called on the old send algorithm.
2341   EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(0);
2342 
2343   QuicFrames frames2;
2344   frames2.push_back(QuicFrame(frame2_));
2345   QuicPaddingFrame padding;
2346   frames2.push_back(QuicFrame(padding));
2347   peer_creator_.SetServerConnectionId(server_cid1);
2348   ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
2349                                    ENCRYPTION_FORWARD_SECURE);
2350   EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2351   EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2352   EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
2353             connection_.active_effective_peer_migration_type());
2354   EXPECT_LT(0u, writer_->packets_write_attempts());
2355   EXPECT_TRUE(connection_.HasPendingPathValidation());
2356   EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
2357             send_algorithm_);
2358   EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
2359   EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2360   EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2361   const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
2362   const auto* alternative_path =
2363       QuicConnectionPeer::GetAlternativePath(&connection_);
2364   EXPECT_EQ(default_path->client_connection_id, client_cid1);
2365   EXPECT_EQ(default_path->server_connection_id, server_cid1);
2366   EXPECT_EQ(alternative_path->client_connection_id, client_cid0);
2367   EXPECT_EQ(alternative_path->server_connection_id, server_cid0);
2368   EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid1);
2369   EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid1);
2370 
2371   for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes; ++i) {
2372     clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
2373     static_cast<TestAlarmFactory::TestAlarm*>(
2374         QuicPathValidatorPeer::retry_timer(
2375             QuicConnectionPeer::path_validator(&connection_)))
2376         ->Fire();
2377   }
2378   EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
2379             connection_.active_effective_peer_migration_type());
2380 
2381   // Make sure anti-amplification limit is not reached.
2382   ProcessFramesPacketWithAddresses(
2383       {QuicFrame(QuicPingFrame()), QuicFrame(QuicPaddingFrame())}, kSelfAddress,
2384       kNewPeerAddress, ENCRYPTION_FORWARD_SECURE);
2385   SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2386   EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2387 
2388   // Advance the time so that the reverse path validation times out.
2389   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
2390   static_cast<TestAlarmFactory::TestAlarm*>(
2391       QuicPathValidatorPeer::retry_timer(
2392           QuicConnectionPeer::path_validator(&connection_)))
2393       ->Fire();
2394   EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
2395   EXPECT_EQ(kPeerAddress, connection_.peer_address());
2396   EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2397   EXPECT_EQ(connection_.sent_packet_manager().GetSendAlgorithm(),
2398             send_algorithm_);
2399   EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2400 
2401   // Verify that default_path_ is reverted and alternative_path_ is cleared.
2402   EXPECT_EQ(default_path->client_connection_id, client_cid0);
2403   EXPECT_EQ(default_path->server_connection_id, server_cid0);
2404   EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
2405   EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
2406   auto* retire_peer_issued_cid_alarm =
2407       connection_.GetRetirePeerIssuedConnectionIdAlarm();
2408   ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
2409   EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/1u));
2410   retire_peer_issued_cid_alarm->Fire();
2411   EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
2412   EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
2413 }
2414 
TEST_P(QuicConnectionTest,ReceivePathProbeWithNoAddressChangeAtServer)2415 TEST_P(QuicConnectionTest, ReceivePathProbeWithNoAddressChangeAtServer) {
2416   if (!version().HasIetfQuicFrames() &&
2417       GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
2418     return;
2419   }
2420   PathProbeTestInit(Perspective::IS_SERVER);
2421 
2422   EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2423   EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(0);
2424 
2425   // Process a padded PING packet with no peer address change on server side
2426   // will be ignored. But a PATH CHALLENGE packet with no peer address change
2427   // will be considered as path probing.
2428   std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2429 
2430   std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2431       QuicEncryptedPacket(probing_packet->encrypted_buffer,
2432                           probing_packet->encrypted_length),
2433       clock_.Now()));
2434 
2435   uint64_t num_probing_received =
2436       connection_.GetStats().num_connectivity_probing_received;
2437   ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2438 
2439   EXPECT_EQ(
2440       num_probing_received + (GetParam().version.HasIetfQuicFrames() ? 1u : 0u),
2441       connection_.GetStats().num_connectivity_probing_received);
2442   EXPECT_EQ(kPeerAddress, connection_.peer_address());
2443   EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2444 }
2445 
2446 // Regression test for b/150161358.
TEST_P(QuicConnectionTest,BufferedMtuPacketTooBig)2447 TEST_P(QuicConnectionTest, BufferedMtuPacketTooBig) {
2448   EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
2449   writer_->SetWriteBlocked();
2450 
2451   // Send a MTU packet while blocked. It should be buffered.
2452   connection_.SendMtuDiscoveryPacket(kMaxOutgoingPacketSize);
2453   EXPECT_EQ(1u, connection_.NumQueuedPackets());
2454   EXPECT_TRUE(writer_->IsWriteBlocked());
2455 
2456   writer_->AlwaysGetPacketTooLarge();
2457   writer_->SetWritable();
2458   connection_.OnCanWrite();
2459 }
2460 
TEST_P(QuicConnectionTest,WriteOutOfOrderQueuedPackets)2461 TEST_P(QuicConnectionTest, WriteOutOfOrderQueuedPackets) {
2462   // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
2463   if (!IsDefaultTestConfiguration()) {
2464     return;
2465   }
2466 
2467   set_perspective(Perspective::IS_CLIENT);
2468 
2469   BlockOnNextWrite();
2470 
2471   QuicStreamId stream_id = 2;
2472   connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
2473 
2474   EXPECT_EQ(1u, connection_.NumQueuedPackets());
2475 
2476   writer_->SetWritable();
2477   connection_.SendConnectivityProbingPacket(writer_.get(),
2478                                             connection_.peer_address());
2479   EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
2480   connection_.OnCanWrite();
2481 }
2482 
TEST_P(QuicConnectionTest,DiscardQueuedPacketsAfterConnectionClose)2483 TEST_P(QuicConnectionTest, DiscardQueuedPacketsAfterConnectionClose) {
2484   // Regression test for b/74073386.
2485   {
2486     InSequence seq;
2487     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2488         .Times(AtLeast(1));
2489     EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(AtLeast(1));
2490   }
2491 
2492   set_perspective(Perspective::IS_CLIENT);
2493 
2494   writer_->SimulateNextPacketTooLarge();
2495 
2496   // This packet write should fail, which should cause the connection to close
2497   // after sending a connection close packet, then the failed packet should be
2498   // queued.
2499   connection_.SendStreamDataWithString(/*id=*/2, "foo", 0, NO_FIN);
2500 
2501   EXPECT_FALSE(connection_.connected());
2502   // No need to buffer packets.
2503   EXPECT_EQ(0u, connection_.NumQueuedPackets());
2504 
2505   EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
2506   connection_.OnCanWrite();
2507   EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
2508 }
2509 
2510 class TestQuicPathValidationContext : public QuicPathValidationContext {
2511  public:
TestQuicPathValidationContext(const QuicSocketAddress & self_address,const QuicSocketAddress & peer_address,QuicPacketWriter * writer)2512   TestQuicPathValidationContext(const QuicSocketAddress& self_address,
2513                                 const QuicSocketAddress& peer_address,
2514 
2515                                 QuicPacketWriter* writer)
2516       : QuicPathValidationContext(self_address, peer_address),
2517         writer_(writer) {}
2518 
WriterToUse()2519   QuicPacketWriter* WriterToUse() override { return writer_; }
2520 
2521  private:
2522   QuicPacketWriter* writer_;
2523 };
2524 
2525 class TestValidationResultDelegate : public QuicPathValidator::ResultDelegate {
2526  public:
TestValidationResultDelegate(QuicConnection * connection,const QuicSocketAddress & expected_self_address,const QuicSocketAddress & expected_peer_address,bool * success)2527   TestValidationResultDelegate(QuicConnection* connection,
2528                                const QuicSocketAddress& expected_self_address,
2529                                const QuicSocketAddress& expected_peer_address,
2530                                bool* success)
2531       : QuicPathValidator::ResultDelegate(),
2532         connection_(connection),
2533         expected_self_address_(expected_self_address),
2534         expected_peer_address_(expected_peer_address),
2535         success_(success) {}
OnPathValidationSuccess(std::unique_ptr<QuicPathValidationContext> context,QuicTime)2536   void OnPathValidationSuccess(
2537       std::unique_ptr<QuicPathValidationContext> context,
2538       QuicTime /*start_time*/) override {
2539     EXPECT_EQ(expected_self_address_, context->self_address());
2540     EXPECT_EQ(expected_peer_address_, context->peer_address());
2541     *success_ = true;
2542   }
2543 
OnPathValidationFailure(std::unique_ptr<QuicPathValidationContext> context)2544   void OnPathValidationFailure(
2545       std::unique_ptr<QuicPathValidationContext> context) override {
2546     EXPECT_EQ(expected_self_address_, context->self_address());
2547     EXPECT_EQ(expected_peer_address_, context->peer_address());
2548     if (connection_->perspective() == Perspective::IS_CLIENT) {
2549       connection_->OnPathValidationFailureAtClient(/*is_multi_port=*/false,
2550                                                    *context);
2551     }
2552     *success_ = false;
2553   }
2554 
2555  private:
2556   QuicConnection* connection_;
2557   QuicSocketAddress expected_self_address_;
2558   QuicSocketAddress expected_peer_address_;
2559   bool* success_;
2560 };
2561 
2562 // A test implementation which migrates to server preferred address
2563 // on path validation suceeds. Otherwise, client cleans up alternative path.
2564 class ServerPreferredAddressTestResultDelegate
2565     : public QuicPathValidator::ResultDelegate {
2566  public:
ServerPreferredAddressTestResultDelegate(QuicConnection * connection)2567   explicit ServerPreferredAddressTestResultDelegate(QuicConnection* connection)
2568       : connection_(connection) {}
OnPathValidationSuccess(std::unique_ptr<QuicPathValidationContext> context,QuicTime)2569   void OnPathValidationSuccess(
2570       std::unique_ptr<QuicPathValidationContext> context,
2571       QuicTime /*start_time*/) override {
2572     connection_->OnServerPreferredAddressValidated(*context, false);
2573   }
2574 
OnPathValidationFailure(std::unique_ptr<QuicPathValidationContext> context)2575   void OnPathValidationFailure(
2576       std::unique_ptr<QuicPathValidationContext> context) override {
2577     connection_->OnPathValidationFailureAtClient(/*is_multi_port=*/false,
2578                                                  *context);
2579   }
2580 
2581  protected:
connection()2582   QuicConnection* connection() { return connection_; }
2583 
2584  private:
2585   QuicConnection* connection_;
2586 };
2587 
2588 // Receive a path probe request at the server side, in IETF version: receive a
2589 // packet contains PATH CHALLENGE with peer address change.
TEST_P(QuicConnectionTest,ReceivePathProbingFromNewPeerAddressAtServer)2590 TEST_P(QuicConnectionTest, ReceivePathProbingFromNewPeerAddressAtServer) {
2591   if (!version().HasIetfQuicFrames() &&
2592       GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
2593     return;
2594   }
2595   PathProbeTestInit(Perspective::IS_SERVER);
2596 
2597   EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2598   QuicPathFrameBuffer payload;
2599   if (!GetParam().version.HasIetfQuicFrames()) {
2600     EXPECT_CALL(visitor_,
2601                 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2602         .Times(1);
2603   } else {
2604     EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2605     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2606         .Times(AtLeast(1u))
2607         .WillOnce(Invoke([&]() {
2608           EXPECT_EQ(1u, writer_->path_challenge_frames().size());
2609           EXPECT_EQ(1u, writer_->path_response_frames().size());
2610           payload = writer_->path_challenge_frames().front().data_buffer;
2611         }));
2612   }
2613   // Process a probing packet from a new peer address on server side
2614   // is effectively receiving a connectivity probing.
2615   const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
2616                                           /*port=*/23456);
2617 
2618   std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2619   std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2620       QuicEncryptedPacket(probing_packet->encrypted_buffer,
2621                           probing_packet->encrypted_length),
2622       clock_.Now()));
2623   uint64_t num_probing_received =
2624       connection_.GetStats().num_connectivity_probing_received;
2625   ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2626 
2627   EXPECT_EQ(num_probing_received + 1,
2628             connection_.GetStats().num_connectivity_probing_received);
2629   EXPECT_EQ(kPeerAddress, connection_.peer_address());
2630   EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2631   if (GetParam().version.HasIetfQuicFrames()) {
2632     QuicByteCount bytes_sent =
2633         QuicConnectionPeer::BytesSentOnAlternativePath(&connection_);
2634     EXPECT_LT(0u, bytes_sent);
2635     EXPECT_EQ(received->length(),
2636               QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
2637 
2638     // Receiving one more probing packet should update the bytes count.
2639     probing_packet = ConstructProbingPacket();
2640     received.reset(ConstructReceivedPacket(
2641         QuicEncryptedPacket(probing_packet->encrypted_buffer,
2642                             probing_packet->encrypted_length),
2643         clock_.Now()));
2644     ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2645 
2646     EXPECT_EQ(num_probing_received + 2,
2647               connection_.GetStats().num_connectivity_probing_received);
2648     EXPECT_EQ(2 * bytes_sent,
2649               QuicConnectionPeer::BytesSentOnAlternativePath(&connection_));
2650     EXPECT_EQ(2 * received->length(),
2651               QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
2652 
2653     EXPECT_EQ(2 * bytes_sent,
2654               QuicConnectionPeer::BytesSentOnAlternativePath(&connection_));
2655     QuicFrames frames;
2656     frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
2657     ProcessFramesPacketWithAddresses(frames, connection_.self_address(),
2658                                      kNewPeerAddress,
2659                                      ENCRYPTION_FORWARD_SECURE);
2660     EXPECT_LT(2 * received->length(),
2661               QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
2662     EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_));
2663     // Receiving another probing packet from a newer address with a different
2664     // port shouldn't trigger another reverse path validation.
2665     QuicSocketAddress kNewerPeerAddress(QuicIpAddress::Loopback4(),
2666                                         /*port=*/34567);
2667     probing_packet = ConstructProbingPacket();
2668     received.reset(ConstructReceivedPacket(
2669         QuicEncryptedPacket(probing_packet->encrypted_buffer,
2670                             probing_packet->encrypted_length),
2671         clock_.Now()));
2672     ProcessReceivedPacket(kSelfAddress, kNewerPeerAddress, *received);
2673     EXPECT_FALSE(connection_.HasPendingPathValidation());
2674     EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_));
2675   }
2676 
2677   // Process another packet with the old peer address on server side will not
2678   // start peer migration.
2679   EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2680   ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2681                                   ENCRYPTION_INITIAL);
2682   EXPECT_EQ(kPeerAddress, connection_.peer_address());
2683   EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2684 }
2685 
2686 // Receive a packet contains PATH CHALLENGE with self address change.
TEST_P(QuicConnectionTest,ReceivePathProbingToPreferredAddressAtServer)2687 TEST_P(QuicConnectionTest, ReceivePathProbingToPreferredAddressAtServer) {
2688   if (!GetParam().version.HasIetfQuicFrames()) {
2689     return;
2690   }
2691   ServerHandlePreferredAddressInit();
2692 
2693   EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2694   EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2695 
2696   // Process a probing packet to the server preferred address.
2697   std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2698   std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2699       QuicEncryptedPacket(probing_packet->encrypted_buffer,
2700                           probing_packet->encrypted_length),
2701       clock_.Now()));
2702   uint64_t num_probing_received =
2703       connection_.GetStats().num_connectivity_probing_received;
2704   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2705       .Times(AtLeast(1u))
2706       .WillOnce(Invoke([&]() {
2707         EXPECT_EQ(1u, writer_->path_response_frames().size());
2708         // Verify that the PATH_RESPONSE is sent from the original self address.
2709         EXPECT_EQ(kSelfAddress.host(), writer_->last_write_source_address());
2710         EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
2711       }));
2712   ProcessReceivedPacket(kServerPreferredAddress, kPeerAddress, *received);
2713 
2714   EXPECT_EQ(num_probing_received + 1,
2715             connection_.GetStats().num_connectivity_probing_received);
2716   EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
2717       &connection_, kServerPreferredAddress, kPeerAddress));
2718   EXPECT_NE(kServerPreferredAddress, connection_.self_address());
2719 
2720   // Receiving another probing packet from a new client address.
2721   const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
2722                                           /*port=*/34567);
2723   probing_packet = ConstructProbingPacket();
2724   received.reset(ConstructReceivedPacket(
2725       QuicEncryptedPacket(probing_packet->encrypted_buffer,
2726                           probing_packet->encrypted_length),
2727       clock_.Now()));
2728   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2729       .Times(AtLeast(1u))
2730       .WillOnce(Invoke([&]() {
2731         EXPECT_EQ(1u, writer_->path_response_frames().size());
2732         EXPECT_EQ(1u, writer_->path_challenge_frames().size());
2733         EXPECT_EQ(kServerPreferredAddress.host(),
2734                   writer_->last_write_source_address());
2735         // The responses should be sent from preferred address given server
2736         // has not received packet on original address from the new client
2737         // address.
2738         EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
2739       }));
2740   ProcessReceivedPacket(kServerPreferredAddress, kNewPeerAddress, *received);
2741 
2742   EXPECT_EQ(num_probing_received + 2,
2743             connection_.GetStats().num_connectivity_probing_received);
2744   EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(&connection_, kSelfAddress,
2745                                                     kNewPeerAddress));
2746   EXPECT_LT(0u, QuicConnectionPeer::BytesSentOnAlternativePath(&connection_));
2747   EXPECT_EQ(received->length(),
2748             QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
2749 }
2750 
2751 // Receive a padded PING packet with a port change on server side.
TEST_P(QuicConnectionTest,ReceivePaddedPingWithPortChangeAtServer)2752 TEST_P(QuicConnectionTest, ReceivePaddedPingWithPortChangeAtServer) {
2753   set_perspective(Perspective::IS_SERVER);
2754   QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2755   EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2756   if (version().SupportsAntiAmplificationLimit()) {
2757     QuicConnectionPeer::SetAddressValidated(&connection_);
2758   }
2759 
2760   // Clear direct_peer_address.
2761   QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2762   // Clear effective_peer_address, it is the same as direct_peer_address for
2763   // this test.
2764   QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2765                                               QuicSocketAddress());
2766   EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2767 
2768   if (GetParam().version.UsesCryptoFrames()) {
2769     EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2770   } else {
2771     EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2772   }
2773   ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2774                                   ENCRYPTION_INITIAL);
2775   EXPECT_EQ(kPeerAddress, connection_.peer_address());
2776   EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2777 
2778   if (GetParam().version.HasIetfQuicFrames() ||
2779       GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
2780     // In IETF version, a padded PING packet with port change is not taken as
2781     // connectivity probe.
2782     EXPECT_CALL(visitor_, GetHandshakeState())
2783         .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2784     EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2785     EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2786   } else {
2787     // In non-IETF version, process a padded PING packet from a new peer
2788     // address on server side is effectively receiving a connectivity probing.
2789     EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2790     EXPECT_CALL(visitor_,
2791                 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2792         .Times(1);
2793   }
2794   const QuicSocketAddress kNewPeerAddress =
2795       QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2796 
2797   QuicFrames frames;
2798   // Write a PING frame, which has no data payload.
2799   QuicPingFrame ping_frame;
2800   frames.push_back(QuicFrame(ping_frame));
2801 
2802   // Add padding to the rest of the packet.
2803   QuicPaddingFrame padding_frame;
2804   frames.push_back(QuicFrame(padding_frame));
2805 
2806   uint64_t num_probing_received =
2807       connection_.GetStats().num_connectivity_probing_received;
2808 
2809   ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
2810                                    ENCRYPTION_INITIAL);
2811 
2812   if (GetParam().version.HasIetfQuicFrames() ||
2813       GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
2814     // Padded PING with port changen is not considered as connectivity probe but
2815     // a PORT CHANGE.
2816     EXPECT_EQ(num_probing_received,
2817               connection_.GetStats().num_connectivity_probing_received);
2818     EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2819     EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2820   } else {
2821     EXPECT_EQ(num_probing_received + 1,
2822               connection_.GetStats().num_connectivity_probing_received);
2823     EXPECT_EQ(kPeerAddress, connection_.peer_address());
2824     EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2825   }
2826 
2827   if (GetParam().version.HasIetfQuicFrames() ||
2828       GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
2829     EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2830   }
2831   // Process another packet with the old peer address on server side.
2832   ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2833                                   ENCRYPTION_INITIAL);
2834   EXPECT_EQ(kPeerAddress, connection_.peer_address());
2835   EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2836 }
2837 
TEST_P(QuicConnectionTest,ReceiveReorderedPathProbingAtServer)2838 TEST_P(QuicConnectionTest, ReceiveReorderedPathProbingAtServer) {
2839   if (!GetParam().version.HasIetfQuicFrames() &&
2840       GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
2841     return;
2842   }
2843   PathProbeTestInit(Perspective::IS_SERVER);
2844 
2845   // Decrease packet number to simulate out-of-order packets.
2846   QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
2847 
2848   EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2849   if (!GetParam().version.HasIetfQuicFrames()) {
2850     EXPECT_CALL(visitor_,
2851                 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2852         .Times(1);
2853   } else {
2854     EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2855   }
2856 
2857   // Process a padded PING packet from a new peer address on server side
2858   // is effectively receiving a connectivity probing, even if a newer packet has
2859   // been received before this one.
2860   const QuicSocketAddress kNewPeerAddress =
2861       QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2862 
2863   std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2864   std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2865       QuicEncryptedPacket(probing_packet->encrypted_buffer,
2866                           probing_packet->encrypted_length),
2867       clock_.Now()));
2868 
2869   uint64_t num_probing_received =
2870       connection_.GetStats().num_connectivity_probing_received;
2871   ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2872 
2873   EXPECT_EQ(num_probing_received +
2874                 (!version().HasIetfQuicFrames() &&
2875                          GetQuicReloadableFlag(quic_ignore_gquic_probing)
2876                      ? 0u
2877                      : 1u),
2878             connection_.GetStats().num_connectivity_probing_received);
2879   EXPECT_EQ((!version().HasIetfQuicFrames() &&
2880                      GetQuicReloadableFlag(quic_ignore_gquic_probing)
2881                  ? kNewPeerAddress
2882                  : kPeerAddress),
2883             connection_.peer_address());
2884   EXPECT_EQ((!version().HasIetfQuicFrames() &&
2885                      GetQuicReloadableFlag(quic_ignore_gquic_probing)
2886                  ? kNewPeerAddress
2887                  : kPeerAddress),
2888             connection_.effective_peer_address());
2889 }
2890 
TEST_P(QuicConnectionTest,MigrateAfterProbingAtServer)2891 TEST_P(QuicConnectionTest, MigrateAfterProbingAtServer) {
2892   if (!GetParam().version.HasIetfQuicFrames() &&
2893       GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
2894     return;
2895   }
2896   PathProbeTestInit(Perspective::IS_SERVER);
2897 
2898   EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2899   if (!GetParam().version.HasIetfQuicFrames()) {
2900     EXPECT_CALL(visitor_,
2901                 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2902         .Times(1);
2903   } else {
2904     EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2905   }
2906 
2907   // Process a padded PING packet from a new peer address on server side
2908   // is effectively receiving a connectivity probing.
2909   const QuicSocketAddress kNewPeerAddress =
2910       QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2911 
2912   std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2913   std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2914       QuicEncryptedPacket(probing_packet->encrypted_buffer,
2915                           probing_packet->encrypted_length),
2916       clock_.Now()));
2917   ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2918   EXPECT_EQ(kPeerAddress, connection_.peer_address());
2919   EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2920 
2921   // Process another non-probing packet with the new peer address on server
2922   // side will start peer migration.
2923   EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2924 
2925   ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2926                                   kNewPeerAddress, ENCRYPTION_INITIAL);
2927   EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2928   EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2929 }
2930 
TEST_P(QuicConnectionTest,ReceiveConnectivityProbingPacketAtClient)2931 TEST_P(QuicConnectionTest, ReceiveConnectivityProbingPacketAtClient) {
2932   if (!version().HasIetfQuicFrames() &&
2933       GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
2934     return;
2935   }
2936   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2937   PathProbeTestInit(Perspective::IS_CLIENT);
2938 
2939   // Client takes all padded PING packet as speculative connectivity
2940   // probing packet, and reports to visitor.
2941   EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2942 
2943   std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2944   std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2945       QuicEncryptedPacket(probing_packet->encrypted_buffer,
2946                           probing_packet->encrypted_length),
2947       clock_.Now()));
2948   uint64_t num_probing_received =
2949       connection_.GetStats().num_connectivity_probing_received;
2950   ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2951 
2952   EXPECT_EQ(
2953       num_probing_received + (GetParam().version.HasIetfQuicFrames() ? 1u : 0u),
2954       connection_.GetStats().num_connectivity_probing_received);
2955   EXPECT_EQ(kPeerAddress, connection_.peer_address());
2956   EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2957 }
2958 
TEST_P(QuicConnectionTest,ReceiveConnectivityProbingResponseAtClient)2959 TEST_P(QuicConnectionTest, ReceiveConnectivityProbingResponseAtClient) {
2960   if (GetParam().version.HasIetfQuicFrames() ||
2961       GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
2962     return;
2963   }
2964   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2965   PathProbeTestInit(Perspective::IS_CLIENT);
2966 
2967   // Process a padded PING packet with a different self address on client side
2968   // is effectively receiving a connectivity probing.
2969   EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2970   if (!GetParam().version.HasIetfQuicFrames()) {
2971     EXPECT_CALL(visitor_,
2972                 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2973         .Times(1);
2974   } else {
2975     EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2976   }
2977 
2978   const QuicSocketAddress kNewSelfAddress =
2979       QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2980 
2981   std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2982   std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2983       QuicEncryptedPacket(probing_packet->encrypted_buffer,
2984                           probing_packet->encrypted_length),
2985       clock_.Now()));
2986   uint64_t num_probing_received =
2987       connection_.GetStats().num_connectivity_probing_received;
2988   ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
2989 
2990   EXPECT_EQ(num_probing_received + 1,
2991             connection_.GetStats().num_connectivity_probing_received);
2992   EXPECT_EQ(kPeerAddress, connection_.peer_address());
2993   EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2994 }
2995 
TEST_P(QuicConnectionTest,PeerAddressChangeAtClient)2996 TEST_P(QuicConnectionTest, PeerAddressChangeAtClient) {
2997   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2998   set_perspective(Perspective::IS_CLIENT);
2999   EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3000 
3001   // Clear direct_peer_address.
3002   QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
3003   // Clear effective_peer_address, it is the same as direct_peer_address for
3004   // this test.
3005   QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
3006                                               QuicSocketAddress());
3007   EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
3008 
3009   if (connection_.version().HasIetfQuicFrames()) {
3010     // Verify the 2nd packet from unknown server address gets dropped.
3011     EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3012   } else if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3013     EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(2);
3014   } else {
3015     EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
3016   }
3017   ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
3018                                   ENCRYPTION_INITIAL);
3019   EXPECT_EQ(kPeerAddress, connection_.peer_address());
3020   EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
3021   const QuicSocketAddress kNewPeerAddress =
3022       QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
3023   EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
3024   ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
3025                                   kNewPeerAddress, ENCRYPTION_INITIAL);
3026   if (connection_.version().HasIetfQuicFrames()) {
3027     // IETF QUIC disallows server initiated address change.
3028     EXPECT_EQ(kPeerAddress, connection_.peer_address());
3029     EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
3030   } else {
3031     EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
3032     EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
3033   }
3034 }
3035 
TEST_P(QuicConnectionTest,NoNormalizedPeerAddressChangeAtClient)3036 TEST_P(QuicConnectionTest, NoNormalizedPeerAddressChangeAtClient) {
3037   if (!version().HasIetfQuicFrames()) {
3038     return;
3039   }
3040   QuicIpAddress peer_ip;
3041   peer_ip.FromString("1.1.1.1");
3042 
3043   QuicSocketAddress peer_addr = QuicSocketAddress(peer_ip, /*port=*/443);
3044   QuicSocketAddress dualstack_peer_addr =
3045       QuicSocketAddress(peer_addr.host().DualStacked(), peer_addr.port());
3046 
3047   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
3048   set_perspective(Perspective::IS_CLIENT);
3049   EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3050 
3051   QuicConnectionPeer::SetDirectPeerAddress(&connection_, dualstack_peer_addr);
3052 
3053   EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
3054   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
3055   ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, peer_addr,
3056                                   ENCRYPTION_INITIAL);
3057   EXPECT_TRUE(connection_.connected());
3058 
3059   if (GetQuicReloadableFlag(quic_test_peer_addr_change_after_normalize)) {
3060     EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
3061   } else {
3062     EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
3063   }
3064 }
3065 
TEST_P(QuicConnectionTest,ServerAddressChangesToKnownAddress)3066 TEST_P(QuicConnectionTest, ServerAddressChangesToKnownAddress) {
3067   if (!connection_.version().HasIetfQuicFrames()) {
3068     return;
3069   }
3070   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3071   set_perspective(Perspective::IS_CLIENT);
3072   EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3073 
3074   // Clear direct_peer_address.
3075   QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
3076   // Clear effective_peer_address, it is the same as direct_peer_address for
3077   // this test.
3078   QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
3079                                               QuicSocketAddress());
3080   EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
3081 
3082   // Verify all 3 packets get processed.
3083   EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
3084   ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
3085                                   ENCRYPTION_INITIAL);
3086   EXPECT_EQ(kPeerAddress, connection_.peer_address());
3087   EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
3088 
3089   // Process another packet with a different but known server address.
3090   const QuicSocketAddress kNewPeerAddress =
3091       QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
3092   connection_.AddKnownServerAddress(kNewPeerAddress);
3093   EXPECT_CALL(visitor_, OnConnectionMigration(_)).Times(0);
3094   ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
3095                                   kNewPeerAddress, ENCRYPTION_INITIAL);
3096   // Verify peer address does not change.
3097   EXPECT_EQ(kPeerAddress, connection_.peer_address());
3098   EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
3099 
3100   // Process 3rd packet from previous server address.
3101   ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
3102                                   ENCRYPTION_INITIAL);
3103   // Verify peer address does not change.
3104   EXPECT_EQ(kPeerAddress, connection_.peer_address());
3105   EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
3106 }
3107 
TEST_P(QuicConnectionTest,PeerAddressChangesToPreferredAddressBeforeClientInitiates)3108 TEST_P(QuicConnectionTest,
3109        PeerAddressChangesToPreferredAddressBeforeClientInitiates) {
3110   if (!version().HasIetfQuicFrames()) {
3111     return;
3112   }
3113   ASSERT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3114   ASSERT_TRUE(connection_.self_address().host().IsIPv6());
3115   const QuicConnectionId connection_id = TestConnectionId(17);
3116   const StatelessResetToken reset_token =
3117       QuicUtils::GenerateStatelessResetToken(connection_id);
3118 
3119   connection_.CreateConnectionIdManager();
3120 
3121   connection_.SendCryptoStreamData();
3122   EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3123   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
3124   QuicAckFrame frame = InitAckFrame(1);
3125   // Received ACK for packet 1.
3126   ProcessFramePacketAtLevel(1, QuicFrame(&frame), ENCRYPTION_INITIAL);
3127   // Discard INITIAL key.
3128   connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
3129   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3130 
3131   QuicConfig config;
3132   config.SetConnectionOptionsToSend(QuicTagVector{kSPAD});
3133   QuicConfigPeer::SetReceivedStatelessResetToken(&config,
3134                                                  kTestStatelessResetToken);
3135   QuicConfigPeer::SetReceivedAlternateServerAddress(&config,
3136                                                     kServerPreferredAddress);
3137   QuicConfigPeer::SetPreferredAddressConnectionIdAndToken(
3138       &config, connection_id, reset_token);
3139   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3140   connection_.SetFromConfig(config);
3141   EXPECT_EQ(kPeerAddress, connection_.peer_address());
3142   EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
3143   ASSERT_TRUE(
3144       QuicConnectionPeer::GetReceivedServerPreferredAddress(&connection_)
3145           .IsInitialized());
3146   EXPECT_EQ(
3147       kServerPreferredAddress,
3148       QuicConnectionPeer::GetReceivedServerPreferredAddress(&connection_));
3149 
3150   EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(0);
3151   ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
3152                                   kServerPreferredAddress, ENCRYPTION_INITIAL);
3153 }
3154 
TEST_P(QuicConnectionTest,MaxPacketSize)3155 TEST_P(QuicConnectionTest, MaxPacketSize) {
3156   EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3157   EXPECT_EQ(1250u, connection_.max_packet_length());
3158 }
3159 
TEST_P(QuicConnectionTest,PeerLowersMaxPacketSize)3160 TEST_P(QuicConnectionTest, PeerLowersMaxPacketSize) {
3161   EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3162 
3163   // SetFromConfig is always called after construction from InitializeSession.
3164   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3165   constexpr uint32_t kTestMaxPacketSize = 1233u;
3166   QuicConfig config;
3167   QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
3168   connection_.SetFromConfig(config);
3169 
3170   EXPECT_EQ(kTestMaxPacketSize, connection_.max_packet_length());
3171 }
3172 
TEST_P(QuicConnectionTest,PeerCannotRaiseMaxPacketSize)3173 TEST_P(QuicConnectionTest, PeerCannotRaiseMaxPacketSize) {
3174   EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3175 
3176   // SetFromConfig is always called after construction from InitializeSession.
3177   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3178   constexpr uint32_t kTestMaxPacketSize = 1450u;
3179   QuicConfig config;
3180   QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
3181   connection_.SetFromConfig(config);
3182 
3183   EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
3184 }
3185 
TEST_P(QuicConnectionTest,SmallerServerMaxPacketSize)3186 TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
3187   TestConnection connection(TestConnectionId(), kSelfAddress, kPeerAddress,
3188                             helper_.get(), alarm_factory_.get(), writer_.get(),
3189                             Perspective::IS_SERVER, version(),
3190                             connection_id_generator_);
3191   EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
3192   EXPECT_EQ(1000u, connection.max_packet_length());
3193 }
3194 
TEST_P(QuicConnectionTest,LowerServerResponseMtuTest)3195 TEST_P(QuicConnectionTest, LowerServerResponseMtuTest) {
3196   set_perspective(Perspective::IS_SERVER);
3197   connection_.SetMaxPacketLength(1000);
3198   EXPECT_EQ(1000u, connection_.max_packet_length());
3199 
3200   SetQuicFlag(quic_use_lower_server_response_mtu_for_test, true);
3201   EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(::testing::AtMost(1));
3202   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(::testing::AtMost(1));
3203   ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
3204   EXPECT_EQ(1250u, connection_.max_packet_length());
3205 }
3206 
TEST_P(QuicConnectionTest,IncreaseServerMaxPacketSize)3207 TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
3208   set_perspective(Perspective::IS_SERVER);
3209   connection_.SetMaxPacketLength(1000);
3210 
3211   QuicPacketHeader header;
3212   header.destination_connection_id = connection_id_;
3213   header.version_flag = true;
3214   header.packet_number = QuicPacketNumber(12);
3215 
3216   if (QuicVersionHasLongHeaderLengths(
3217           peer_framer_.version().transport_version)) {
3218     header.long_packet_type = INITIAL;
3219     header.retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1;
3220     header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2;
3221   }
3222 
3223   QuicFrames frames;
3224   QuicPaddingFrame padding;
3225   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3226     frames.push_back(QuicFrame(&crypto_frame_));
3227   } else {
3228     frames.push_back(QuicFrame(frame1_));
3229   }
3230   frames.push_back(QuicFrame(padding));
3231   std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
3232   char buffer[kMaxOutgoingPacketSize];
3233   size_t encrypted_length =
3234       peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
3235                                   *packet, buffer, kMaxOutgoingPacketSize);
3236   EXPECT_EQ(kMaxOutgoingPacketSize,
3237             encrypted_length +
3238                 (connection_.version().KnowsWhichDecrypterToUse() ? 0 : 4));
3239 
3240   framer_.set_version(version());
3241   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3242     EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3243   } else {
3244     EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3245   }
3246   connection_.ProcessUdpPacket(
3247       kSelfAddress, kPeerAddress,
3248       QuicReceivedPacket(buffer, encrypted_length, clock_.ApproximateNow(),
3249                          false));
3250 
3251   EXPECT_EQ(kMaxOutgoingPacketSize,
3252             connection_.max_packet_length() +
3253                 (connection_.version().KnowsWhichDecrypterToUse() ? 0 : 4));
3254 }
3255 
TEST_P(QuicConnectionTest,IncreaseServerMaxPacketSizeWhileWriterLimited)3256 TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSizeWhileWriterLimited) {
3257   const QuicByteCount lower_max_packet_size = 1240;
3258   writer_->set_max_packet_size(lower_max_packet_size);
3259   set_perspective(Perspective::IS_SERVER);
3260   connection_.SetMaxPacketLength(1000);
3261   EXPECT_EQ(1000u, connection_.max_packet_length());
3262 
3263   QuicPacketHeader header;
3264   header.destination_connection_id = connection_id_;
3265   header.version_flag = true;
3266   header.packet_number = QuicPacketNumber(12);
3267 
3268   if (QuicVersionHasLongHeaderLengths(
3269           peer_framer_.version().transport_version)) {
3270     header.long_packet_type = INITIAL;
3271     header.retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1;
3272     header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2;
3273   }
3274 
3275   QuicFrames frames;
3276   QuicPaddingFrame padding;
3277   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3278     frames.push_back(QuicFrame(&crypto_frame_));
3279   } else {
3280     frames.push_back(QuicFrame(frame1_));
3281   }
3282   frames.push_back(QuicFrame(padding));
3283   std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
3284   char buffer[kMaxOutgoingPacketSize];
3285   size_t encrypted_length =
3286       peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
3287                                   *packet, buffer, kMaxOutgoingPacketSize);
3288   EXPECT_EQ(kMaxOutgoingPacketSize,
3289             encrypted_length +
3290                 (connection_.version().KnowsWhichDecrypterToUse() ? 0 : 4));
3291 
3292   framer_.set_version(version());
3293   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3294     EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3295   } else {
3296     EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3297   }
3298   connection_.ProcessUdpPacket(
3299       kSelfAddress, kPeerAddress,
3300       QuicReceivedPacket(buffer, encrypted_length, clock_.ApproximateNow(),
3301                          false));
3302 
3303   // Here, the limit imposed by the writer is lower than the size of the packet
3304   // received, so the writer max packet size is used.
3305   EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
3306 }
3307 
TEST_P(QuicConnectionTest,LimitMaxPacketSizeByWriter)3308 TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriter) {
3309   const QuicByteCount lower_max_packet_size = 1240;
3310   writer_->set_max_packet_size(lower_max_packet_size);
3311 
3312   static_assert(lower_max_packet_size < kDefaultMaxPacketSize,
3313                 "Default maximum packet size is too low");
3314   connection_.SetMaxPacketLength(kDefaultMaxPacketSize);
3315 
3316   EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
3317 }
3318 
TEST_P(QuicConnectionTest,LimitMaxPacketSizeByWriterForNewConnection)3319 TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriterForNewConnection) {
3320   const QuicConnectionId connection_id = TestConnectionId(17);
3321   const QuicByteCount lower_max_packet_size = 1240;
3322   writer_->set_max_packet_size(lower_max_packet_size);
3323   TestConnection connection(connection_id, kSelfAddress, kPeerAddress,
3324                             helper_.get(), alarm_factory_.get(), writer_.get(),
3325                             Perspective::IS_CLIENT, version(),
3326                             connection_id_generator_);
3327   EXPECT_EQ(Perspective::IS_CLIENT, connection.perspective());
3328   EXPECT_EQ(lower_max_packet_size, connection.max_packet_length());
3329 }
3330 
TEST_P(QuicConnectionTest,PacketsInOrder)3331 TEST_P(QuicConnectionTest, PacketsInOrder) {
3332   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3333 
3334   ProcessPacket(1);
3335   EXPECT_EQ(QuicPacketNumber(1u), LargestAcked(connection_.ack_frame()));
3336   EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
3337 
3338   ProcessPacket(2);
3339   EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(connection_.ack_frame()));
3340   EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
3341 
3342   ProcessPacket(3);
3343   EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3344   EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
3345 }
3346 
TEST_P(QuicConnectionTest,PacketsOutOfOrder)3347 TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
3348   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3349 
3350   ProcessPacket(3);
3351   EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3352   EXPECT_TRUE(IsMissing(2));
3353   EXPECT_TRUE(IsMissing(1));
3354 
3355   ProcessPacket(2);
3356   EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3357   EXPECT_FALSE(IsMissing(2));
3358   EXPECT_TRUE(IsMissing(1));
3359 
3360   ProcessPacket(1);
3361   EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3362   EXPECT_FALSE(IsMissing(2));
3363   EXPECT_FALSE(IsMissing(1));
3364 }
3365 
TEST_P(QuicConnectionTest,DuplicatePacket)3366 TEST_P(QuicConnectionTest, DuplicatePacket) {
3367   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3368 
3369   ProcessPacket(3);
3370   EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3371   EXPECT_TRUE(IsMissing(2));
3372   EXPECT_TRUE(IsMissing(1));
3373 
3374   // Send packet 3 again, but do not set the expectation that
3375   // the visitor OnStreamFrame() will be called.
3376   ProcessDataPacket(3);
3377   EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3378   EXPECT_TRUE(IsMissing(2));
3379   EXPECT_TRUE(IsMissing(1));
3380 }
3381 
TEST_P(QuicConnectionTest,PacketsOutOfOrderWithAdditionsAndLeastAwaiting)3382 TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
3383   if (connection_.SupportsMultiplePacketNumberSpaces()) {
3384     return;
3385   }
3386   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3387 
3388   ProcessPacket(3);
3389   EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3390   EXPECT_TRUE(IsMissing(2));
3391   EXPECT_TRUE(IsMissing(1));
3392 
3393   ProcessPacket(2);
3394   EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3395   EXPECT_TRUE(IsMissing(1));
3396 
3397   ProcessPacket(5);
3398   EXPECT_EQ(QuicPacketNumber(5u), LargestAcked(connection_.ack_frame()));
3399   EXPECT_TRUE(IsMissing(1));
3400   EXPECT_TRUE(IsMissing(4));
3401 
3402   // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
3403   // packet the peer will not retransmit.  It indicates this by sending 'least
3404   // awaiting' is 4.  The connection should then realize 1 will not be
3405   // retransmitted, and will remove it from the missing list.
3406   QuicAckFrame frame = InitAckFrame(1);
3407   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
3408   ProcessAckPacket(6, &frame);
3409 
3410   // Force an ack to be sent.
3411   SendAckPacketToPeer();
3412   EXPECT_TRUE(IsMissing(4));
3413 }
3414 
TEST_P(QuicConnectionTest,RejectUnencryptedStreamData)3415 TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
3416   // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
3417   if (!IsDefaultTestConfiguration() ||
3418       VersionHasIetfQuicFrames(version().transport_version)) {
3419     return;
3420   }
3421 
3422   // Process an unencrypted packet from the non-crypto stream.
3423   frame1_.stream_id = 3;
3424   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3425   EXPECT_CALL(visitor_,
3426               OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
3427   EXPECT_QUIC_PEER_BUG(ProcessDataPacketAtLevel(1, false, ENCRYPTION_INITIAL),
3428                        "");
3429   TestConnectionCloseQuicErrorCode(QUIC_UNENCRYPTED_STREAM_DATA);
3430 }
3431 
TEST_P(QuicConnectionTest,OutOfOrderReceiptCausesAckSend)3432 TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
3433   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3434 
3435   ProcessPacket(3);
3436   // Should not cause an ack.
3437   EXPECT_EQ(0u, writer_->packets_write_attempts());
3438 
3439   ProcessPacket(2);
3440   // Should ack immediately, since this fills the last hole.
3441   EXPECT_EQ(1u, writer_->packets_write_attempts());
3442 
3443   ProcessPacket(1);
3444   // Should ack immediately, since this fills the last hole.
3445   EXPECT_EQ(2u, writer_->packets_write_attempts());
3446 
3447   ProcessPacket(4);
3448   // Should not cause an ack.
3449   EXPECT_EQ(2u, writer_->packets_write_attempts());
3450 }
3451 
TEST_P(QuicConnectionTest,OutOfOrderAckReceiptCausesNoAck)3452 TEST_P(QuicConnectionTest, OutOfOrderAckReceiptCausesNoAck) {
3453   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3454 
3455   SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3456   SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3457   EXPECT_EQ(2u, writer_->packets_write_attempts());
3458 
3459   QuicAckFrame ack1 = InitAckFrame(1);
3460   QuicAckFrame ack2 = InitAckFrame(2);
3461   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
3462   if (connection_.SupportsMultiplePacketNumberSpaces()) {
3463     EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(1);
3464   }
3465   ProcessAckPacket(2, &ack2);
3466   // Should ack immediately since we have missing packets.
3467   EXPECT_EQ(2u, writer_->packets_write_attempts());
3468 
3469   if (connection_.SupportsMultiplePacketNumberSpaces()) {
3470     EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(0);
3471   }
3472   ProcessAckPacket(1, &ack1);
3473   // Should not ack an ack filling a missing packet.
3474   EXPECT_EQ(2u, writer_->packets_write_attempts());
3475 }
3476 
TEST_P(QuicConnectionTest,AckReceiptCausesAckSend)3477 TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
3478   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3479   QuicPacketNumber original, second;
3480 
3481   QuicByteCount packet_size =
3482       SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original);  // 1st packet.
3483   SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second);        // 2nd packet.
3484 
3485   QuicAckFrame frame = InitAckFrame({{second, second + 1}});
3486   // First nack triggers early retransmit.
3487   LostPacketVector lost_packets;
3488   lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
3489   EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3490       .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3491                       Return(LossDetectionInterface::DetectionStats())));
3492   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
3493   QuicPacketNumber retransmission;
3494   // Packet 1 is short header for IETF QUIC because the encryption level
3495   // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
3496   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, packet_size, _))
3497       .WillOnce(SaveArg<2>(&retransmission));
3498 
3499   ProcessAckPacket(&frame);
3500 
3501   QuicAckFrame frame2 = ConstructAckFrame(retransmission, original);
3502   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
3503   EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3504   ProcessAckPacket(&frame2);
3505 
3506   // Now if the peer sends an ack which still reports the retransmitted packet
3507   // as missing, that will bundle an ack with data after two acks in a row
3508   // indicate the high water mark needs to be raised.
3509   EXPECT_CALL(*send_algorithm_,
3510               OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
3511   connection_.SendStreamDataWithString(3, "foo", 6, NO_FIN);
3512   // No ack sent.
3513   size_t padding_frame_count = writer_->padding_frames().size();
3514   EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
3515   EXPECT_EQ(1u, writer_->stream_frames().size());
3516 
3517   // No more packet loss for the rest of the test.
3518   EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3519       .Times(AnyNumber());
3520   ProcessAckPacket(&frame2);
3521   EXPECT_CALL(*send_algorithm_,
3522               OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
3523   connection_.SendStreamDataWithString(3, "foofoofoo", 9, NO_FIN);
3524   // Ack bundled.
3525   // Do not ACK acks.
3526   EXPECT_EQ(1u, writer_->frame_count());
3527   EXPECT_EQ(1u, writer_->stream_frames().size());
3528   EXPECT_TRUE(writer_->ack_frames().empty());
3529 
3530   // But an ack with no missing packets will not send an ack.
3531   AckPacket(original, &frame2);
3532   ProcessAckPacket(&frame2);
3533   ProcessAckPacket(&frame2);
3534 }
3535 
TEST_P(QuicConnectionTest,AckFrequencyUpdatedFromAckFrequencyFrame)3536 TEST_P(QuicConnectionTest, AckFrequencyUpdatedFromAckFrequencyFrame) {
3537   if (!GetParam().version.HasIetfQuicFrames()) {
3538     return;
3539   }
3540   connection_.set_can_receive_ack_frequency_frame();
3541 
3542   // Expect 13 acks, every 3rd packet including the first packet with
3543   // AckFrequencyFrame.
3544   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(13);
3545   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3546 
3547   QuicAckFrequencyFrame ack_frequency_frame;
3548   ack_frequency_frame.packet_tolerance = 3;
3549   ProcessFramePacketAtLevel(1, QuicFrame(&ack_frequency_frame),
3550                             ENCRYPTION_FORWARD_SECURE);
3551 
3552   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(38);
3553   // Receives packets 2 - 39.
3554   for (size_t i = 2; i <= 39; ++i) {
3555     ProcessDataPacket(i);
3556   }
3557 }
3558 
TEST_P(QuicConnectionTest,AckDecimationReducesAcks)3559 TEST_P(QuicConnectionTest, AckDecimationReducesAcks) {
3560   const size_t kMinRttMs = 40;
3561   RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
3562   rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
3563                        QuicTime::Delta::Zero(), QuicTime::Zero());
3564   EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
3565 
3566   // Start ack decimation from 10th packet.
3567   connection_.set_min_received_before_ack_decimation(10);
3568 
3569   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3570   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(30);
3571 
3572   // Expect 6 acks: 5 acks between packets 1-10, and ack at 20.
3573   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6);
3574   // Receives packets 1 - 29.
3575   for (size_t i = 1; i <= 29; ++i) {
3576     ProcessDataPacket(i);
3577   }
3578 
3579   // We now receive the 30th packet, and so we send an ack.
3580   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3581   ProcessDataPacket(30);
3582 }
3583 
TEST_P(QuicConnectionTest,AckNeedsRetransmittableFrames)3584 TEST_P(QuicConnectionTest, AckNeedsRetransmittableFrames) {
3585   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3586   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3587   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(99);
3588 
3589   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
3590   // Receives packets 1 - 39.
3591   for (size_t i = 1; i <= 39; ++i) {
3592     ProcessDataPacket(i);
3593   }
3594   // Receiving Packet 40 causes 20th ack to send. Session is informed and adds
3595   // WINDOW_UPDATE.
3596   EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3597       .WillOnce(Invoke([this]() {
3598         connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
3599       }));
3600   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3601   EXPECT_EQ(0u, writer_->window_update_frames().size());
3602   ProcessDataPacket(40);
3603   EXPECT_EQ(1u, writer_->window_update_frames().size());
3604 
3605   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
3606   // Receives packets 41 - 59.
3607   for (size_t i = 41; i <= 59; ++i) {
3608     ProcessDataPacket(i);
3609   }
3610   // Send a packet containing stream frame.
3611   SendStreamDataToPeer(
3612       QuicUtils::GetFirstBidirectionalStreamId(
3613           connection_.version().transport_version, Perspective::IS_CLIENT),
3614       "bar", 0, NO_FIN, nullptr);
3615 
3616   // Session will not be informed until receiving another 20 packets.
3617   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
3618   for (size_t i = 60; i <= 98; ++i) {
3619     ProcessDataPacket(i);
3620     EXPECT_EQ(0u, writer_->window_update_frames().size());
3621   }
3622   // Session does not add a retransmittable frame.
3623   EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3624       .WillOnce(Invoke([this]() {
3625         connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
3626       }));
3627   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3628   EXPECT_EQ(0u, writer_->ping_frames().size());
3629   ProcessDataPacket(99);
3630   EXPECT_EQ(0u, writer_->window_update_frames().size());
3631   // A ping frame will be added.
3632   EXPECT_EQ(1u, writer_->ping_frames().size());
3633 }
3634 
TEST_P(QuicConnectionTest,AckNeedsRetransmittableFramesAfterPto)3635 TEST_P(QuicConnectionTest, AckNeedsRetransmittableFramesAfterPto) {
3636   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3637   QuicConfig config;
3638   QuicTagVector connection_options;
3639   connection_options.push_back(kEACK);
3640   config.SetConnectionOptionsToSend(connection_options);
3641   connection_.SetFromConfig(config);
3642 
3643   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3644   connection_.OnHandshakeComplete();
3645 
3646   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3647   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(10);
3648 
3649   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
3650   // Receive packets 1 - 9.
3651   for (size_t i = 1; i <= 9; ++i) {
3652     ProcessDataPacket(i);
3653   }
3654 
3655   // Send a ping and fire the retransmission alarm.
3656   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3657   SendPing();
3658   QuicTime retransmission_time =
3659       connection_.GetRetransmissionAlarm()->deadline();
3660   clock_.AdvanceTime(retransmission_time - clock_.Now());
3661   connection_.GetRetransmissionAlarm()->Fire();
3662   ASSERT_LT(0u, manager_->GetConsecutivePtoCount());
3663 
3664   // Process a packet, which requests a retransmittable frame be bundled
3665   // with the ACK.
3666   EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3667       .WillOnce(Invoke([this]() {
3668         connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
3669       }));
3670   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3671   ProcessDataPacket(11);
3672   EXPECT_EQ(1u, writer_->window_update_frames().size());
3673 }
3674 
TEST_P(QuicConnectionTest,TooManySentPackets)3675 TEST_P(QuicConnectionTest, TooManySentPackets) {
3676   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3677 
3678   QuicPacketCount max_tracked_packets = 50;
3679   QuicConnectionPeer::SetMaxTrackedPackets(&connection_, max_tracked_packets);
3680 
3681   const int num_packets = max_tracked_packets + 5;
3682 
3683   for (int i = 0; i < num_packets; ++i) {
3684     SendStreamDataToPeer(1, "foo", 3 * i, NO_FIN, nullptr);
3685   }
3686 
3687   EXPECT_CALL(visitor_,
3688               OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
3689 
3690   ProcessFramePacket(QuicFrame(QuicPingFrame()));
3691 
3692   TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS);
3693 }
3694 
TEST_P(QuicConnectionTest,LargestObservedLower)3695 TEST_P(QuicConnectionTest, LargestObservedLower) {
3696   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3697 
3698   SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3699   SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3700   SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
3701   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
3702 
3703   // Start out saying the largest observed is 2.
3704   QuicAckFrame frame1 = InitAckFrame(1);
3705   QuicAckFrame frame2 = InitAckFrame(2);
3706   ProcessAckPacket(&frame2);
3707 
3708   EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
3709   ProcessAckPacket(&frame1);
3710 }
3711 
TEST_P(QuicConnectionTest,AckUnsentData)3712 TEST_P(QuicConnectionTest, AckUnsentData) {
3713   // Ack a packet which has not been sent.
3714   EXPECT_CALL(visitor_,
3715               OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
3716   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3717   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
3718   QuicAckFrame frame = InitAckFrame(1);
3719   EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
3720   ProcessAckPacket(&frame);
3721   TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
3722 }
3723 
TEST_P(QuicConnectionTest,BasicSending)3724 TEST_P(QuicConnectionTest, BasicSending) {
3725   if (connection_.SupportsMultiplePacketNumberSpaces()) {
3726     return;
3727   }
3728   const QuicConnectionStats& stats = connection_.GetStats();
3729   EXPECT_FALSE(stats.first_decrypted_packet.IsInitialized());
3730   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3731   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3732   ProcessDataPacket(1);
3733   EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet);
3734   QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3735   QuicPacketNumber last_packet;
3736   SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);  // Packet 1
3737   EXPECT_EQ(QuicPacketNumber(1u), last_packet);
3738   SendAckPacketToPeer();  // Packet 2
3739 
3740   SendAckPacketToPeer();  // Packet 3
3741 
3742   SendStreamDataToPeer(1, "bar", 3, NO_FIN, &last_packet);  // Packet 4
3743   EXPECT_EQ(QuicPacketNumber(4u), last_packet);
3744   SendAckPacketToPeer();  // Packet 5
3745 
3746   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
3747 
3748   // Peer acks up to packet 3.
3749   QuicAckFrame frame = InitAckFrame(3);
3750   ProcessAckPacket(&frame);
3751   SendAckPacketToPeer();  // Packet 6
3752 
3753   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
3754 
3755   // Peer acks up to packet 4, the last packet.
3756   QuicAckFrame frame2 = InitAckFrame(6);
3757   ProcessAckPacket(&frame2);  // Acks don't instigate acks.
3758 
3759   // Verify that we did not send an ack.
3760   EXPECT_EQ(QuicPacketNumber(6u), writer_->header().packet_number);
3761 
3762   // If we force an ack, we shouldn't change our retransmit state.
3763   SendAckPacketToPeer();  // Packet 7
3764 
3765   // But if we send more data it should.
3766   SendStreamDataToPeer(1, "eep", 6, NO_FIN, &last_packet);  // Packet 8
3767   EXPECT_EQ(QuicPacketNumber(8u), last_packet);
3768   SendAckPacketToPeer();  // Packet 9
3769   EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet);
3770 }
3771 
3772 // QuicConnection should record the packet sent-time prior to sending the
3773 // packet.
TEST_P(QuicConnectionTest,RecordSentTimeBeforePacketSent)3774 TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
3775   // We're using a MockClock for the tests, so we have complete control over the
3776   // time.
3777   // Our recorded timestamp for the last packet sent time will be passed in to
3778   // the send_algorithm.  Make sure that it is set to the correct value.
3779   QuicTime actual_recorded_send_time = QuicTime::Zero();
3780   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3781       .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3782 
3783   // First send without any pause and check the result.
3784   QuicTime expected_recorded_send_time = clock_.Now();
3785   connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3786   EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3787       << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3788       << ".  Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3789 
3790   // Now pause during the write, and check the results.
3791   actual_recorded_send_time = QuicTime::Zero();
3792   const QuicTime::Delta write_pause_time_delta =
3793       QuicTime::Delta::FromMilliseconds(5000);
3794   SetWritePauseTimeDelta(write_pause_time_delta);
3795   expected_recorded_send_time = clock_.Now();
3796 
3797   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3798       .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3799   connection_.SendStreamDataWithString(2, "baz", 0, NO_FIN);
3800   EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3801       << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3802       << ".  Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3803 }
3804 
TEST_P(QuicConnectionTest,ConnectionStatsRetransmission_WithRetransmissions)3805 TEST_P(QuicConnectionTest, ConnectionStatsRetransmission_WithRetransmissions) {
3806   // Send two stream frames in 1 packet by queueing them.
3807   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3808 
3809   {
3810     QuicConnection::ScopedPacketFlusher flusher(&connection_);
3811     connection_.SaveAndSendStreamData(
3812         GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3813         "helloworld", 0, NO_FIN, PTO_RETRANSMISSION);
3814     connection_.SaveAndSendStreamData(
3815         GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3816         "helloworld", 0, NO_FIN, LOSS_RETRANSMISSION);
3817     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3818   }
3819 
3820   EXPECT_EQ(0u, connection_.NumQueuedPackets());
3821   EXPECT_FALSE(connection_.HasQueuedData());
3822 
3823   EXPECT_EQ(2u, writer_->frame_count());
3824   for (auto& frame : writer_->stream_frames()) {
3825     EXPECT_EQ(frame->data_length, 10u);
3826   }
3827 
3828   ASSERT_EQ(connection_.GetStats().packets_retransmitted, 1u);
3829   ASSERT_GE(connection_.GetStats().bytes_retransmitted, 20u);
3830 }
3831 
TEST_P(QuicConnectionTest,ConnectionStatsRetransmission_WithMixedFrames)3832 TEST_P(QuicConnectionTest, ConnectionStatsRetransmission_WithMixedFrames) {
3833   // Send two stream frames in 1 packet by queueing them.
3834   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3835 
3836   {
3837     QuicConnection::ScopedPacketFlusher flusher(&connection_);
3838     // First frame is retransmission. Second is NOT_RETRANSMISSION but the
3839     // packet retains the PTO_RETRANSMISSION type.
3840     connection_.SaveAndSendStreamData(
3841         GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3842         "helloworld", 0, NO_FIN, PTO_RETRANSMISSION);
3843     connection_.SaveAndSendStreamData(
3844         GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3845         "helloworld", 0, NO_FIN, NOT_RETRANSMISSION);
3846     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3847   }
3848 
3849   EXPECT_EQ(0u, connection_.NumQueuedPackets());
3850   EXPECT_FALSE(connection_.HasQueuedData());
3851 
3852   EXPECT_EQ(2u, writer_->frame_count());
3853   for (auto& frame : writer_->stream_frames()) {
3854     EXPECT_EQ(frame->data_length, 10u);
3855   }
3856 
3857   ASSERT_EQ(connection_.GetStats().packets_retransmitted, 1u);
3858   ASSERT_GE(connection_.GetStats().bytes_retransmitted, 10u);
3859 }
3860 
TEST_P(QuicConnectionTest,ConnectionStatsRetransmission_NoRetransmission)3861 TEST_P(QuicConnectionTest, ConnectionStatsRetransmission_NoRetransmission) {
3862   // Send two stream frames in 1 packet by queueing them.
3863   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3864 
3865   {
3866     QuicConnection::ScopedPacketFlusher flusher(&connection_);
3867     // Both frames are NOT_RETRANSMISSION
3868     connection_.SaveAndSendStreamData(
3869         GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3870         "helloworld", 0, NO_FIN, NOT_RETRANSMISSION);
3871     connection_.SaveAndSendStreamData(
3872         GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3873         "helloworld", 0, NO_FIN, NOT_RETRANSMISSION);
3874     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3875   }
3876 
3877   EXPECT_EQ(0u, connection_.NumQueuedPackets());
3878   EXPECT_FALSE(connection_.HasQueuedData());
3879 
3880   EXPECT_EQ(2u, writer_->frame_count());
3881   ASSERT_EQ(connection_.GetStats().packets_retransmitted, 0u);
3882   ASSERT_EQ(connection_.GetStats().bytes_retransmitted, 0u);
3883 }
3884 
TEST_P(QuicConnectionTest,FramePacking)3885 TEST_P(QuicConnectionTest, FramePacking) {
3886   // Send two stream frames in 1 packet by queueing them.
3887   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3888   {
3889     QuicConnection::ScopedPacketFlusher flusher(&connection_);
3890     connection_.SendStreamData3();
3891     connection_.SendStreamData5();
3892     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3893   }
3894   EXPECT_EQ(0u, connection_.NumQueuedPackets());
3895   EXPECT_FALSE(connection_.HasQueuedData());
3896 
3897   // Parse the last packet and ensure it's an ack and two stream frames from
3898   // two different streams.
3899   EXPECT_EQ(2u, writer_->frame_count());
3900   EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3901 
3902   EXPECT_TRUE(writer_->ack_frames().empty());
3903 
3904   ASSERT_EQ(2u, writer_->stream_frames().size());
3905   EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3906             writer_->stream_frames()[0]->stream_id);
3907   EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3908             writer_->stream_frames()[1]->stream_id);
3909 }
3910 
TEST_P(QuicConnectionTest,FramePackingNonCryptoThenCrypto)3911 TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
3912   // Send two stream frames (one non-crypto, then one crypto) in 2 packets by
3913   // queueing them.
3914   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3915   {
3916     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3917     QuicConnection::ScopedPacketFlusher flusher(&connection_);
3918     connection_.SendStreamData3();
3919     connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
3920     // Set the crypters for INITIAL packets in the TestPacketWriter.
3921     if (!connection_.version().KnowsWhichDecrypterToUse()) {
3922       writer_->framer()->framer()->SetAlternativeDecrypter(
3923           ENCRYPTION_INITIAL,
3924           std::make_unique<NullDecrypter>(Perspective::IS_SERVER), false);
3925     }
3926     connection_.SendCryptoStreamData();
3927     connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3928   }
3929   EXPECT_EQ(0u, connection_.NumQueuedPackets());
3930   EXPECT_FALSE(connection_.HasQueuedData());
3931 
3932   // Parse the last packet and ensure it contains a crypto stream frame.
3933   EXPECT_LE(2u, writer_->frame_count());
3934   ASSERT_LE(1u, writer_->padding_frames().size());
3935   if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3936     ASSERT_EQ(1u, writer_->stream_frames().size());
3937     EXPECT_EQ(QuicUtils::GetCryptoStreamId(connection_.transport_version()),
3938               writer_->stream_frames()[0]->stream_id);
3939   } else {
3940     EXPECT_LE(1u, writer_->crypto_frames().size());
3941   }
3942 }
3943 
TEST_P(QuicConnectionTest,FramePackingCryptoThenNonCrypto)3944 TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
3945   // Send two stream frames (one crypto, then one non-crypto) in 2 packets by
3946   // queueing them.
3947   {
3948     connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3949     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3950     QuicConnection::ScopedPacketFlusher flusher(&connection_);
3951     connection_.SendCryptoStreamData();
3952     connection_.SendStreamData3();
3953   }
3954   EXPECT_EQ(0u, connection_.NumQueuedPackets());
3955   EXPECT_FALSE(connection_.HasQueuedData());
3956 
3957   // Parse the last packet and ensure it's the stream frame from stream 3.
3958   size_t padding_frame_count = writer_->padding_frames().size();
3959   EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
3960   ASSERT_EQ(1u, writer_->stream_frames().size());
3961   EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3962             writer_->stream_frames()[0]->stream_id);
3963 }
3964 
TEST_P(QuicConnectionTest,FramePackingAckResponse)3965 TEST_P(QuicConnectionTest, FramePackingAckResponse) {
3966   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3967   // Process a data packet to queue up a pending ack.
3968   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3969     EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3970   } else {
3971     EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3972   }
3973   ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
3974 
3975   QuicPacketNumber last_packet;
3976   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3977     connection_.SendCryptoDataWithString("foo", 0);
3978   } else {
3979     SendStreamDataToPeer(
3980         QuicUtils::GetCryptoStreamId(connection_.transport_version()), "foo", 0,
3981         NO_FIN, &last_packet);
3982   }
3983   // Verify ack is bundled with outging packet.
3984   EXPECT_FALSE(writer_->ack_frames().empty());
3985 
3986   EXPECT_CALL(visitor_, OnCanWrite())
3987       .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3988                           &connection_, &TestConnection::SendStreamData3)),
3989                       IgnoreResult(InvokeWithoutArgs(
3990                           &connection_, &TestConnection::SendStreamData5))));
3991 
3992   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3993 
3994   // Process a data packet to cause the visitor's OnCanWrite to be invoked.
3995   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3996   peer_framer_.SetEncrypter(
3997       ENCRYPTION_FORWARD_SECURE,
3998       std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
3999   SetDecrypter(
4000       ENCRYPTION_FORWARD_SECURE,
4001       std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
4002   ForceWillingAndAbleToWriteOnceForDeferSending();
4003   ProcessDataPacket(2);
4004 
4005   EXPECT_EQ(0u, connection_.NumQueuedPackets());
4006   EXPECT_FALSE(connection_.HasQueuedData());
4007 
4008   // Parse the last packet and ensure it's an ack and two stream frames from
4009   // two different streams.
4010   EXPECT_EQ(3u, writer_->frame_count());
4011   EXPECT_TRUE(writer_->stop_waiting_frames().empty());
4012   EXPECT_FALSE(writer_->ack_frames().empty());
4013   ASSERT_EQ(2u, writer_->stream_frames().size());
4014   EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
4015             writer_->stream_frames()[0]->stream_id);
4016   EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
4017             writer_->stream_frames()[1]->stream_id);
4018 }
4019 
TEST_P(QuicConnectionTest,FramePackingSendv)4020 TEST_P(QuicConnectionTest, FramePackingSendv) {
4021   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4022   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4023 
4024   QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
4025       connection_.transport_version(), Perspective::IS_CLIENT);
4026   connection_.SaveAndSendStreamData(stream_id, "ABCDEF", 0, NO_FIN);
4027 
4028   EXPECT_EQ(0u, connection_.NumQueuedPackets());
4029   EXPECT_FALSE(connection_.HasQueuedData());
4030 
4031   // Parse the last packet and ensure multiple iovector blocks have
4032   // been packed into a single stream frame from one stream.
4033   EXPECT_EQ(1u, writer_->frame_count());
4034   EXPECT_EQ(1u, writer_->stream_frames().size());
4035   EXPECT_EQ(0u, writer_->padding_frames().size());
4036   QuicStreamFrame* frame = writer_->stream_frames()[0].get();
4037   EXPECT_EQ(stream_id, frame->stream_id);
4038   EXPECT_EQ("ABCDEF",
4039             absl::string_view(frame->data_buffer, frame->data_length));
4040 }
4041 
TEST_P(QuicConnectionTest,FramePackingSendvQueued)4042 TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
4043   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4044   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4045 
4046   BlockOnNextWrite();
4047   QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
4048       connection_.transport_version(), Perspective::IS_CLIENT);
4049   connection_.SaveAndSendStreamData(stream_id, "ABCDEF", 0, NO_FIN);
4050 
4051   EXPECT_EQ(1u, connection_.NumQueuedPackets());
4052   EXPECT_TRUE(connection_.HasQueuedData());
4053 
4054   // Unblock the writes and actually send.
4055   writer_->SetWritable();
4056   connection_.OnCanWrite();
4057   EXPECT_EQ(0u, connection_.NumQueuedPackets());
4058 
4059   // Parse the last packet and ensure it's one stream frame from one stream.
4060   EXPECT_EQ(1u, writer_->frame_count());
4061   EXPECT_EQ(1u, writer_->stream_frames().size());
4062   EXPECT_EQ(0u, writer_->padding_frames().size());
4063   QuicStreamFrame* frame = writer_->stream_frames()[0].get();
4064   EXPECT_EQ(stream_id, frame->stream_id);
4065   EXPECT_EQ("ABCDEF",
4066             absl::string_view(frame->data_buffer, frame->data_length));
4067 }
4068 
TEST_P(QuicConnectionTest,SendingZeroBytes)4069 TEST_P(QuicConnectionTest, SendingZeroBytes) {
4070   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4071   // Send a zero byte write with a fin using writev.
4072   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4073   QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
4074       connection_.transport_version(), Perspective::IS_CLIENT);
4075   connection_.SaveAndSendStreamData(stream_id, {}, 0, FIN);
4076 
4077   EXPECT_EQ(0u, connection_.NumQueuedPackets());
4078   EXPECT_FALSE(connection_.HasQueuedData());
4079 
4080   // Padding frames are added by v99 to ensure a minimum packet size.
4081   size_t extra_padding_frames = 0;
4082   if (GetParam().version.HasHeaderProtection()) {
4083     extra_padding_frames = 1;
4084   }
4085 
4086   // Parse the last packet and ensure it's one stream frame from one stream.
4087   EXPECT_EQ(1u + extra_padding_frames, writer_->frame_count());
4088   EXPECT_EQ(extra_padding_frames, writer_->padding_frames().size());
4089   ASSERT_EQ(1u, writer_->stream_frames().size());
4090   EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
4091   EXPECT_TRUE(writer_->stream_frames()[0]->fin);
4092 }
4093 
TEST_P(QuicConnectionTest,LargeSendWithPendingAck)4094 TEST_P(QuicConnectionTest, LargeSendWithPendingAck) {
4095   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4096   EXPECT_CALL(visitor_, GetHandshakeState())
4097       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
4098   // Set the ack alarm by processing a ping frame.
4099   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4100 
4101   // Processs a PING frame.
4102   ProcessFramePacket(QuicFrame(QuicPingFrame()));
4103   // Ensure that this has caused the ACK alarm to be set.
4104   EXPECT_TRUE(connection_.HasPendingAcks());
4105 
4106   // Send data and ensure the ack is bundled.
4107   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
4108   const std::string data(10000, '?');
4109   QuicConsumedData consumed = connection_.SaveAndSendStreamData(
4110       GetNthClientInitiatedStreamId(0, connection_.transport_version()), data,
4111       0, FIN);
4112   EXPECT_EQ(data.length(), consumed.bytes_consumed);
4113   EXPECT_TRUE(consumed.fin_consumed);
4114   EXPECT_EQ(0u, connection_.NumQueuedPackets());
4115   EXPECT_FALSE(connection_.HasQueuedData());
4116 
4117   // Parse the last packet and ensure it's one stream frame with a fin.
4118   EXPECT_EQ(1u, writer_->frame_count());
4119   ASSERT_EQ(1u, writer_->stream_frames().size());
4120   EXPECT_EQ(GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4121             writer_->stream_frames()[0]->stream_id);
4122   EXPECT_TRUE(writer_->stream_frames()[0]->fin);
4123   // Ensure the ack alarm was cancelled when the ack was sent.
4124   EXPECT_FALSE(connection_.HasPendingAcks());
4125 }
4126 
TEST_P(QuicConnectionTest,OnCanWrite)4127 TEST_P(QuicConnectionTest, OnCanWrite) {
4128   // Visitor's OnCanWrite will send data, but will have more pending writes.
4129   EXPECT_CALL(visitor_, OnCanWrite())
4130       .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
4131                           &connection_, &TestConnection::SendStreamData3)),
4132                       IgnoreResult(InvokeWithoutArgs(
4133                           &connection_, &TestConnection::SendStreamData5))));
4134   {
4135     InSequence seq;
4136     EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
4137     EXPECT_CALL(visitor_, WillingAndAbleToWrite())
4138         .WillRepeatedly(Return(false));
4139   }
4140 
4141   EXPECT_CALL(*send_algorithm_, CanSend(_))
4142       .WillRepeatedly(testing::Return(true));
4143 
4144   connection_.OnCanWrite();
4145 
4146   // Parse the last packet and ensure it's the two stream frames from
4147   // two different streams.
4148   EXPECT_EQ(2u, writer_->frame_count());
4149   EXPECT_EQ(2u, writer_->stream_frames().size());
4150   EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
4151             writer_->stream_frames()[0]->stream_id);
4152   EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
4153             writer_->stream_frames()[1]->stream_id);
4154 }
4155 
TEST_P(QuicConnectionTest,RetransmitOnNack)4156 TEST_P(QuicConnectionTest, RetransmitOnNack) {
4157   QuicPacketNumber last_packet;
4158   SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet);
4159   SendStreamDataToPeer(3, "foos", 3, NO_FIN, &last_packet);
4160   SendStreamDataToPeer(3, "fooos", 7, NO_FIN, &last_packet);
4161 
4162   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4163 
4164   // Don't lose a packet on an ack, and nothing is retransmitted.
4165   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
4166   QuicAckFrame ack_one = InitAckFrame(1);
4167   ProcessAckPacket(&ack_one);
4168 
4169   // Lose a packet and ensure it triggers retransmission.
4170   QuicAckFrame nack_two = ConstructAckFrame(3, 2);
4171   LostPacketVector lost_packets;
4172   lost_packets.push_back(
4173       LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
4174   EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4175       .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4176                       Return(LossDetectionInterface::DetectionStats())));
4177   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
4178   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4179   EXPECT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
4180   ProcessAckPacket(&nack_two);
4181 }
4182 
TEST_P(QuicConnectionTest,DoNotSendQueuedPacketForResetStream)4183 TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
4184   // Block the connection to queue the packet.
4185   BlockOnNextWrite();
4186 
4187   QuicStreamId stream_id = 2;
4188   connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
4189 
4190   // Now that there is a queued packet, reset the stream.
4191   SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
4192 
4193   // Unblock the connection and verify that only the RST_STREAM is sent.
4194   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4195   writer_->SetWritable();
4196   connection_.OnCanWrite();
4197   size_t padding_frame_count = writer_->padding_frames().size();
4198   EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4199   EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4200 }
4201 
TEST_P(QuicConnectionTest,SendQueuedPacketForQuicRstStreamNoError)4202 TEST_P(QuicConnectionTest, SendQueuedPacketForQuicRstStreamNoError) {
4203   // Block the connection to queue the packet.
4204   BlockOnNextWrite();
4205 
4206   QuicStreamId stream_id = 2;
4207   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4208   connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
4209 
4210   // Now that there is a queued packet, reset the stream.
4211   SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
4212 
4213   // Unblock the connection and verify that the RST_STREAM is sent and the data
4214   // packet is sent.
4215   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
4216   writer_->SetWritable();
4217   connection_.OnCanWrite();
4218   size_t padding_frame_count = writer_->padding_frames().size();
4219   EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4220   EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4221 }
4222 
TEST_P(QuicConnectionTest,DoNotRetransmitForResetStreamOnNack)4223 TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
4224   QuicStreamId stream_id = 2;
4225   QuicPacketNumber last_packet;
4226   SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4227   SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4228   SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
4229 
4230   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4231   SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
4232 
4233   // Lose a packet and ensure it does not trigger retransmission.
4234   QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
4235   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4236   EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
4237   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
4238   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4239   ProcessAckPacket(&nack_two);
4240 }
4241 
TEST_P(QuicConnectionTest,RetransmitForQuicRstStreamNoErrorOnNack)4242 TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnNack) {
4243   QuicStreamId stream_id = 2;
4244   QuicPacketNumber last_packet;
4245   SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4246   SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4247   SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
4248 
4249   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4250   SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
4251 
4252   // Lose a packet, ensure it triggers retransmission.
4253   QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
4254   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4255   LostPacketVector lost_packets;
4256   lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
4257   EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4258       .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4259                       Return(LossDetectionInterface::DetectionStats())));
4260   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
4261   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
4262   ProcessAckPacket(&nack_two);
4263 }
4264 
TEST_P(QuicConnectionTest,DoNotRetransmitForResetStreamOnRTO)4265 TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
4266   QuicStreamId stream_id = 2;
4267   QuicPacketNumber last_packet;
4268   SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4269 
4270   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4271   SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
4272 
4273   // Fire the RTO and verify that the RST_STREAM is resent, not stream data.
4274   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4275   clock_.AdvanceTime(DefaultRetransmissionTime());
4276   connection_.GetRetransmissionAlarm()->Fire();
4277   size_t padding_frame_count = writer_->padding_frames().size();
4278   EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4279   EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4280   EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
4281 }
4282 
4283 // Ensure that if the only data in flight is non-retransmittable, the
4284 // retransmission alarm is not set.
TEST_P(QuicConnectionTest,CancelRetransmissionAlarmAfterResetStream)4285 TEST_P(QuicConnectionTest, CancelRetransmissionAlarmAfterResetStream) {
4286   QuicStreamId stream_id = 2;
4287   QuicPacketNumber last_data_packet;
4288   SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
4289 
4290   // Cancel the stream.
4291   const QuicPacketNumber rst_packet = last_data_packet + 1;
4292   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, rst_packet, _, _)).Times(1);
4293   SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
4294 
4295   // Ack the RST_STREAM frame (since it's retransmittable), but not the data
4296   // packet, which is no longer retransmittable since the stream was cancelled.
4297   QuicAckFrame nack_stream_data =
4298       ConstructAckFrame(rst_packet, last_data_packet);
4299   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4300   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
4301   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4302   ProcessAckPacket(&nack_stream_data);
4303 
4304   // Ensure that the data is still in flight, but the retransmission alarm is no
4305   // longer set.
4306   EXPECT_GT(manager_->GetBytesInFlight(), 0u);
4307   EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4308 }
4309 
TEST_P(QuicConnectionTest,RetransmitForQuicRstStreamNoErrorOnPTO)4310 TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnPTO) {
4311   QuicStreamId stream_id = 2;
4312   QuicPacketNumber last_packet;
4313   SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4314 
4315   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4316   SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
4317 
4318   // Fire the RTO and verify that the RST_STREAM is resent, the stream data
4319   // is sent.
4320   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
4321   clock_.AdvanceTime(DefaultRetransmissionTime());
4322   connection_.GetRetransmissionAlarm()->Fire();
4323   size_t padding_frame_count = writer_->padding_frames().size();
4324   EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4325 }
4326 
TEST_P(QuicConnectionTest,DoNotSendPendingRetransmissionForResetStream)4327 TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
4328   QuicStreamId stream_id = 2;
4329   QuicPacketNumber last_packet;
4330   SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4331   SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4332   BlockOnNextWrite();
4333   connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
4334 
4335   // Lose a packet which will trigger a pending retransmission.
4336   QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
4337   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4338   EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
4339   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
4340   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4341   ProcessAckPacket(&ack);
4342 
4343   SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
4344 
4345   // Unblock the connection and verify that the RST_STREAM is sent but not the
4346   // second data packet nor a retransmit.
4347   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4348   writer_->SetWritable();
4349   connection_.OnCanWrite();
4350   size_t padding_frame_count = writer_->padding_frames().size();
4351   EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4352   ASSERT_EQ(1u, writer_->rst_stream_frames().size());
4353   EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
4354 }
4355 
TEST_P(QuicConnectionTest,SendPendingRetransmissionForQuicRstStreamNoError)4356 TEST_P(QuicConnectionTest, SendPendingRetransmissionForQuicRstStreamNoError) {
4357   QuicStreamId stream_id = 2;
4358   QuicPacketNumber last_packet;
4359   SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4360   SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4361   BlockOnNextWrite();
4362   connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
4363 
4364   // Lose a packet which will trigger a pending retransmission.
4365   QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
4366   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4367   LostPacketVector lost_packets;
4368   lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
4369   EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4370       .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4371                       Return(LossDetectionInterface::DetectionStats())));
4372   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
4373   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4374   ProcessAckPacket(&ack);
4375 
4376   SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
4377 
4378   // Unblock the connection and verify that the RST_STREAM is sent and the
4379   // second data packet or a retransmit is sent.
4380   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
4381   writer_->SetWritable();
4382   connection_.OnCanWrite();
4383   // The RST_STREAM_FRAME is sent after queued packets and pending
4384   // retransmission.
4385   connection_.SendControlFrame(QuicFrame(
4386       new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14)));
4387   size_t padding_frame_count = writer_->padding_frames().size();
4388   EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4389   EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4390 }
4391 
TEST_P(QuicConnectionTest,RetransmitAckedPacket)4392 TEST_P(QuicConnectionTest, RetransmitAckedPacket) {
4393   QuicPacketNumber last_packet;
4394   SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);    // Packet 1
4395   SendStreamDataToPeer(1, "foos", 3, NO_FIN, &last_packet);   // Packet 2
4396   SendStreamDataToPeer(1, "fooos", 7, NO_FIN, &last_packet);  // Packet 3
4397 
4398   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4399 
4400   // Instigate a loss with an ack.
4401   QuicAckFrame nack_two = ConstructAckFrame(3, 2);
4402   // The first nack should trigger a fast retransmission, but we'll be
4403   // write blocked, so the packet will be queued.
4404   BlockOnNextWrite();
4405 
4406   LostPacketVector lost_packets;
4407   lost_packets.push_back(
4408       LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
4409   EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4410       .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4411                       Return(LossDetectionInterface::DetectionStats())));
4412   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
4413   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
4414       .Times(1);
4415   ProcessAckPacket(&nack_two);
4416   EXPECT_EQ(1u, connection_.NumQueuedPackets());
4417 
4418   // Now, ack the previous transmission.
4419   EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
4420   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(false, _, _, _, _, _, _));
4421   QuicAckFrame ack_all = InitAckFrame(3);
4422   ProcessAckPacket(&ack_all);
4423 
4424   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
4425       .Times(0);
4426 
4427   writer_->SetWritable();
4428   connection_.OnCanWrite();
4429 
4430   EXPECT_EQ(0u, connection_.NumQueuedPackets());
4431   // We do not store retransmittable frames of this retransmission.
4432   EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 4));
4433 }
4434 
TEST_P(QuicConnectionTest,RetransmitNackedLargestObserved)4435 TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
4436   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4437   QuicPacketNumber original, second;
4438 
4439   QuicByteCount packet_size =
4440       SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original);  // 1st packet.
4441   SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second);        // 2nd packet.
4442 
4443   QuicAckFrame frame = InitAckFrame({{second, second + 1}});
4444   // The first nack should retransmit the largest observed packet.
4445   LostPacketVector lost_packets;
4446   lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
4447   EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4448       .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4449                       Return(LossDetectionInterface::DetectionStats())));
4450   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
4451   // Packet 1 is short header for IETF QUIC because the encryption level
4452   // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
4453   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, packet_size, _));
4454   ProcessAckPacket(&frame);
4455 }
4456 
TEST_P(QuicConnectionTest,WriteBlockedBufferedThenSent)4457 TEST_P(QuicConnectionTest, WriteBlockedBufferedThenSent) {
4458   BlockOnNextWrite();
4459   writer_->set_is_write_blocked_data_buffered(true);
4460   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4461   connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4462   EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4463 
4464   writer_->SetWritable();
4465   connection_.OnCanWrite();
4466   EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4467 }
4468 
TEST_P(QuicConnectionTest,WriteBlockedThenSent)4469 TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
4470   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4471   BlockOnNextWrite();
4472   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4473   connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4474   EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4475   EXPECT_EQ(1u, connection_.NumQueuedPackets());
4476 
4477   // The second packet should also be queued, in order to ensure packets are
4478   // never sent out of order.
4479   writer_->SetWritable();
4480   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4481   connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4482   EXPECT_EQ(2u, connection_.NumQueuedPackets());
4483 
4484   // Now both are sent in order when we unblock.
4485   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4486   connection_.OnCanWrite();
4487   EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4488   EXPECT_EQ(0u, connection_.NumQueuedPackets());
4489 }
4490 
TEST_P(QuicConnectionTest,RetransmitWriteBlockedAckedOriginalThenSent)4491 TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
4492   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4493   connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4494   EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4495 
4496   BlockOnNextWrite();
4497   writer_->set_is_write_blocked_data_buffered(true);
4498   // Simulate the retransmission alarm firing.
4499   clock_.AdvanceTime(DefaultRetransmissionTime());
4500   connection_.GetRetransmissionAlarm()->Fire();
4501 
4502   // Ack the sent packet before the callback returns, which happens in
4503   // rare circumstances with write blocked sockets.
4504   QuicAckFrame ack = InitAckFrame(1);
4505   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
4506   ProcessAckPacket(&ack);
4507 
4508   writer_->SetWritable();
4509   connection_.OnCanWrite();
4510   EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4511   EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 3));
4512 }
4513 
TEST_P(QuicConnectionTest,AlarmsWhenWriteBlocked)4514 TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
4515   // Block the connection.
4516   BlockOnNextWrite();
4517   connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4518   EXPECT_EQ(1u, writer_->packets_write_attempts());
4519   EXPECT_TRUE(writer_->IsWriteBlocked());
4520 
4521   // Set the send alarm. Fire the alarm and ensure it doesn't attempt to write.
4522   connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
4523   connection_.GetSendAlarm()->Fire();
4524   EXPECT_TRUE(writer_->IsWriteBlocked());
4525   EXPECT_EQ(1u, writer_->packets_write_attempts());
4526 }
4527 
TEST_P(QuicConnectionTest,NoSendAlarmAfterProcessPacketWhenWriteBlocked)4528 TEST_P(QuicConnectionTest, NoSendAlarmAfterProcessPacketWhenWriteBlocked) {
4529   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4530 
4531   // Block the connection.
4532   BlockOnNextWrite();
4533   connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4534   EXPECT_TRUE(writer_->IsWriteBlocked());
4535   EXPECT_EQ(1u, connection_.NumQueuedPackets());
4536   EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4537 
4538   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4539   // Process packet number 1. Can not call ProcessPacket or ProcessDataPacket
4540   // here, because they will fire the alarm after QuicConnection::ProcessPacket
4541   // is returned.
4542   const uint64_t received_packet_num = 1;
4543   const bool has_stop_waiting = false;
4544   const EncryptionLevel level = ENCRYPTION_FORWARD_SECURE;
4545   std::unique_ptr<QuicPacket> packet(
4546       ConstructDataPacket(received_packet_num, has_stop_waiting, level));
4547   char buffer[kMaxOutgoingPacketSize];
4548   size_t encrypted_length =
4549       peer_framer_.EncryptPayload(level, QuicPacketNumber(received_packet_num),
4550                                   *packet, buffer, kMaxOutgoingPacketSize);
4551   connection_.ProcessUdpPacket(
4552       kSelfAddress, kPeerAddress,
4553       QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
4554 
4555   EXPECT_TRUE(writer_->IsWriteBlocked());
4556   EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4557 }
4558 
TEST_P(QuicConnectionTest,SendAlarmNonZeroDelay)4559 TEST_P(QuicConnectionTest, SendAlarmNonZeroDelay) {
4560   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4561   // Set a 10 ms send alarm delay. The send alarm after processing the packet
4562   // should fire after waiting 10ms, not immediately.
4563   connection_.set_defer_send_in_response_to_packets(true);
4564   connection_.sent_packet_manager().SetDeferredSendAlarmDelay(
4565       QuicTime::Delta::FromMilliseconds(10));
4566   EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4567 
4568   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4569   // Process packet number 1. Can not call ProcessPacket or ProcessDataPacket
4570   // here, because they will fire the alarm after QuicConnection::ProcessPacket
4571   // is returned.
4572   const uint64_t received_packet_num = 1;
4573   const bool has_stop_waiting = false;
4574   const EncryptionLevel level = ENCRYPTION_FORWARD_SECURE;
4575   std::unique_ptr<QuicPacket> packet(
4576       ConstructDataPacket(received_packet_num, has_stop_waiting, level));
4577   char buffer[kMaxOutgoingPacketSize];
4578   size_t encrypted_length =
4579       peer_framer_.EncryptPayload(level, QuicPacketNumber(received_packet_num),
4580                                   *packet, buffer, kMaxOutgoingPacketSize);
4581   EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
4582   connection_.ProcessUdpPacket(
4583       kSelfAddress, kPeerAddress,
4584       QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
4585 
4586   EXPECT_TRUE(connection_.GetSendAlarm()->IsSet());
4587   // It was set to be 10 ms in the future, so it should at the least be greater
4588   // than now + 5 ms.
4589   EXPECT_TRUE(connection_.GetSendAlarm()->deadline() >
4590               clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5));
4591 }
4592 
TEST_P(QuicConnectionTest,AddToWriteBlockedListIfWriterBlockedWhenProcessing)4593 TEST_P(QuicConnectionTest, AddToWriteBlockedListIfWriterBlockedWhenProcessing) {
4594   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4595   SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
4596 
4597   // Simulate the case where a shared writer gets blocked by another connection.
4598   writer_->SetWriteBlocked();
4599 
4600   // Process an ACK, make sure the connection calls visitor_->OnWriteBlocked().
4601   QuicAckFrame ack1 = InitAckFrame(1);
4602   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
4603   EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
4604   ProcessAckPacket(1, &ack1);
4605 }
4606 
TEST_P(QuicConnectionTest,DoNotAddToWriteBlockedListAfterDisconnect)4607 TEST_P(QuicConnectionTest, DoNotAddToWriteBlockedListAfterDisconnect) {
4608   writer_->SetBatchMode(true);
4609   EXPECT_TRUE(connection_.connected());
4610   // Have to explicitly grab the OnConnectionClosed frame and check
4611   // its parameters because this is a silent connection close and the
4612   // frame is not also transmitted to the peer.
4613   EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
4614       .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
4615 
4616   EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
4617 
4618   {
4619     QuicConnection::ScopedPacketFlusher flusher(&connection_);
4620     connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
4621                                 ConnectionCloseBehavior::SILENT_CLOSE);
4622 
4623     EXPECT_FALSE(connection_.connected());
4624     writer_->SetWriteBlocked();
4625   }
4626   EXPECT_EQ(1, connection_close_frame_count_);
4627   EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
4628               IsError(QUIC_PEER_GOING_AWAY));
4629 }
4630 
TEST_P(QuicConnectionTest,AddToWriteBlockedListIfBlockedOnFlushPackets)4631 TEST_P(QuicConnectionTest, AddToWriteBlockedListIfBlockedOnFlushPackets) {
4632   writer_->SetBatchMode(true);
4633   writer_->BlockOnNextFlush();
4634 
4635   EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
4636   {
4637     QuicConnection::ScopedPacketFlusher flusher(&connection_);
4638     // flusher's destructor will call connection_.FlushPackets, which should add
4639     // the connection to the write blocked list.
4640   }
4641 }
4642 
TEST_P(QuicConnectionTest,NoLimitPacketsPerNack)4643 TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
4644   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4645   int offset = 0;
4646   // Send packets 1 to 15.
4647   for (int i = 0; i < 15; ++i) {
4648     SendStreamDataToPeer(1, "foo", offset, NO_FIN, nullptr);
4649     offset += 3;
4650   }
4651 
4652   // Ack 15, nack 1-14.
4653 
4654   QuicAckFrame nack =
4655       InitAckFrame({{QuicPacketNumber(15), QuicPacketNumber(16)}});
4656 
4657   // 14 packets have been NACK'd and lost.
4658   LostPacketVector lost_packets;
4659   for (int i = 1; i < 15; ++i) {
4660     lost_packets.push_back(
4661         LostPacket(QuicPacketNumber(i), kMaxOutgoingPacketSize));
4662   }
4663   EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4664       .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4665                       Return(LossDetectionInterface::DetectionStats())));
4666   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
4667   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4668   ProcessAckPacket(&nack);
4669 }
4670 
4671 // Test sending multiple acks from the connection to the session.
TEST_P(QuicConnectionTest,MultipleAcks)4672 TEST_P(QuicConnectionTest, MultipleAcks) {
4673   if (connection_.SupportsMultiplePacketNumberSpaces()) {
4674     return;
4675   }
4676   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4677   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4678   ProcessDataPacket(1);
4679   QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
4680   QuicPacketNumber last_packet;
4681   SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);  // Packet 1
4682   EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4683   SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet);  // Packet 2
4684   EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4685   SendAckPacketToPeer();                                    // Packet 3
4686   SendStreamDataToPeer(5, "foo", 0, NO_FIN, &last_packet);  // Packet 4
4687   EXPECT_EQ(QuicPacketNumber(4u), last_packet);
4688   SendStreamDataToPeer(1, "foo", 3, NO_FIN, &last_packet);  // Packet 5
4689   EXPECT_EQ(QuicPacketNumber(5u), last_packet);
4690   SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet);  // Packet 6
4691   EXPECT_EQ(QuicPacketNumber(6u), last_packet);
4692 
4693   // Client will ack packets 1, 2, [!3], 4, 5.
4694   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
4695   QuicAckFrame frame1 = ConstructAckFrame(5, 3);
4696   ProcessAckPacket(&frame1);
4697 
4698   // Now the client implicitly acks 3, and explicitly acks 6.
4699   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
4700   QuicAckFrame frame2 = InitAckFrame(6);
4701   ProcessAckPacket(&frame2);
4702 }
4703 
TEST_P(QuicConnectionTest,DontLatchUnackedPacket)4704 TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
4705   if (connection_.SupportsMultiplePacketNumberSpaces()) {
4706     return;
4707   }
4708   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4709   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4710   ProcessDataPacket(1);
4711   QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
4712   SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);  // Packet 1;
4713   // From now on, we send acks, so the send algorithm won't mark them pending.
4714   SendAckPacketToPeer();  // Packet 2
4715 
4716   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
4717   QuicAckFrame frame = InitAckFrame(1);
4718   ProcessAckPacket(&frame);
4719 
4720   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
4721   frame = InitAckFrame(2);
4722   ProcessAckPacket(&frame);
4723 
4724   // When we send an ack, we make sure our least-unacked makes sense.  In this
4725   // case since we're not waiting on an ack for 2 and all packets are acked, we
4726   // set it to 3.
4727   SendAckPacketToPeer();  // Packet 3
4728 
4729   // Ack the ack, which updates the rtt and raises the least unacked.
4730   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
4731   frame = InitAckFrame(3);
4732   ProcessAckPacket(&frame);
4733 
4734   SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);  // Packet 4
4735   SendAckPacketToPeer();                               // Packet 5
4736 
4737   // Send two data packets at the end, and ensure if the last one is acked,
4738   // the least unacked is raised above the ack packets.
4739   SendStreamDataToPeer(1, "bar", 6, NO_FIN, nullptr);  // Packet 6
4740   SendStreamDataToPeer(1, "bar", 9, NO_FIN, nullptr);  // Packet 7
4741 
4742   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
4743   frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)},
4744                         {QuicPacketNumber(7), QuicPacketNumber(8)}});
4745   ProcessAckPacket(&frame);
4746 }
4747 
TEST_P(QuicConnectionTest,SendHandshakeMessages)4748 TEST_P(QuicConnectionTest, SendHandshakeMessages) {
4749   // Attempt to send a handshake message and have the socket block.
4750   EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
4751   BlockOnNextWrite();
4752   connection_.SendCryptoDataWithString("foo", 0);
4753   // The packet should be serialized, but not queued.
4754   EXPECT_EQ(1u, connection_.NumQueuedPackets());
4755 
4756   // Switch to the new encrypter.
4757   connection_.SetEncrypter(
4758       ENCRYPTION_ZERO_RTT,
4759       std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
4760   connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4761 
4762   // Now become writeable and flush the packets.
4763   writer_->SetWritable();
4764   EXPECT_CALL(visitor_, OnCanWrite());
4765   connection_.OnCanWrite();
4766   EXPECT_EQ(0u, connection_.NumQueuedPackets());
4767 
4768   // Verify that the handshake packet went out with Initial encryption.
4769   EXPECT_NE(0x02020202u, writer_->final_bytes_of_last_packet());
4770 }
4771 
TEST_P(QuicConnectionTest,DropRetransmitsForInitialPacketAfterForwardSecure)4772 TEST_P(QuicConnectionTest, DropRetransmitsForInitialPacketAfterForwardSecure) {
4773   connection_.SendCryptoStreamData();
4774   // Simulate the retransmission alarm firing and the socket blocking.
4775   BlockOnNextWrite();
4776   clock_.AdvanceTime(DefaultRetransmissionTime());
4777   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4778   connection_.GetRetransmissionAlarm()->Fire();
4779   EXPECT_EQ(1u, connection_.NumQueuedPackets());
4780 
4781   // Go forward secure.
4782   connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
4783                            std::make_unique<TaggingEncrypter>(0x02));
4784   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4785   notifier_.NeuterUnencryptedData();
4786   connection_.NeuterUnencryptedPackets();
4787   connection_.OnHandshakeComplete();
4788 
4789   EXPECT_EQ(QuicTime::Zero(), connection_.GetRetransmissionAlarm()->deadline());
4790   // Unblock the socket and ensure that no packets are sent.
4791   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4792   writer_->SetWritable();
4793   connection_.OnCanWrite();
4794 }
4795 
TEST_P(QuicConnectionTest,RetransmitPacketsWithInitialEncryption)4796 TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
4797   connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
4798 
4799   connection_.SendCryptoDataWithString("foo", 0);
4800 
4801   connection_.SetEncrypter(
4802       ENCRYPTION_ZERO_RTT,
4803       std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
4804   connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4805   if (!connection_.version().KnowsWhichDecrypterToUse()) {
4806     writer_->framer()->framer()->SetAlternativeDecrypter(
4807         ENCRYPTION_ZERO_RTT,
4808         std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT), false);
4809   }
4810 
4811   SendStreamDataToPeer(2, "bar", 0, NO_FIN, nullptr);
4812   EXPECT_FALSE(notifier_.HasLostStreamData());
4813   connection_.MarkZeroRttPacketsForRetransmission(0);
4814   EXPECT_TRUE(notifier_.HasLostStreamData());
4815 }
4816 
TEST_P(QuicConnectionTest,BufferNonDecryptablePackets)4817 TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
4818   if (connection_.SupportsMultiplePacketNumberSpaces()) {
4819     return;
4820   }
4821   // SetFromConfig is always called after construction from InitializeSession.
4822   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4823   QuicConfig config;
4824   connection_.SetFromConfig(config);
4825   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4826 
4827   peer_framer_.SetEncrypter(
4828       ENCRYPTION_ZERO_RTT,
4829       std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
4830   if (!connection_.version().KnowsWhichDecrypterToUse()) {
4831     writer_->framer()->framer()->SetDecrypter(
4832         ENCRYPTION_ZERO_RTT, std::make_unique<TaggingDecrypter>());
4833   }
4834 
4835   // Process an encrypted packet which can not yet be decrypted which should
4836   // result in the packet being buffered.
4837   ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4838 
4839   // Transition to the new encryption state and process another encrypted packet
4840   // which should result in the original packet being processed.
4841   SetDecrypter(ENCRYPTION_ZERO_RTT,
4842                std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
4843   connection_.SetEncrypter(
4844       ENCRYPTION_ZERO_RTT,
4845       std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
4846   connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4847   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
4848   ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4849 
4850   // Finally, process a third packet and note that we do not reprocess the
4851   // buffered packet.
4852   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4853   ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4854 }
4855 
TEST_P(QuicConnectionTest,Buffer100NonDecryptablePacketsThenKeyChange)4856 TEST_P(QuicConnectionTest, Buffer100NonDecryptablePacketsThenKeyChange) {
4857   if (connection_.SupportsMultiplePacketNumberSpaces()) {
4858     return;
4859   }
4860   // SetFromConfig is always called after construction from InitializeSession.
4861   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4862   QuicConfig config;
4863   config.set_max_undecryptable_packets(100);
4864   connection_.SetFromConfig(config);
4865   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4866 
4867   peer_framer_.SetEncrypter(
4868       ENCRYPTION_ZERO_RTT,
4869       std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
4870 
4871   // Process an encrypted packet which can not yet be decrypted which should
4872   // result in the packet being buffered.
4873   for (uint64_t i = 1; i <= 100; ++i) {
4874     ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4875   }
4876 
4877   // Transition to the new encryption state and process another encrypted packet
4878   // which should result in the original packets being processed.
4879   EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4880   SetDecrypter(ENCRYPTION_ZERO_RTT,
4881                std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
4882   EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4883   connection_.SetEncrypter(
4884       ENCRYPTION_ZERO_RTT,
4885       std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
4886   connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4887 
4888   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(100);
4889   if (!connection_.version().KnowsWhichDecrypterToUse()) {
4890     writer_->framer()->framer()->SetDecrypter(
4891         ENCRYPTION_ZERO_RTT, std::make_unique<TaggingDecrypter>());
4892   }
4893   connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
4894 
4895   // Finally, process a third packet and note that we do not reprocess the
4896   // buffered packet.
4897   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4898   ProcessDataPacketAtLevel(102, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4899 }
4900 
TEST_P(QuicConnectionTest,SetRTOAfterWritingToSocket)4901 TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
4902   BlockOnNextWrite();
4903   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4904   connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4905   EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4906 
4907   // Test that RTO is started once we write to the socket.
4908   writer_->SetWritable();
4909   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4910   connection_.OnCanWrite();
4911   EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4912 }
4913 
TEST_P(QuicConnectionTest,TestQueued)4914 TEST_P(QuicConnectionTest, TestQueued) {
4915   EXPECT_EQ(0u, connection_.NumQueuedPackets());
4916   BlockOnNextWrite();
4917   connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4918   EXPECT_EQ(1u, connection_.NumQueuedPackets());
4919 
4920   // Unblock the writes and actually send.
4921   writer_->SetWritable();
4922   connection_.OnCanWrite();
4923   EXPECT_EQ(0u, connection_.NumQueuedPackets());
4924 }
4925 
TEST_P(QuicConnectionTest,InitialTimeout)4926 TEST_P(QuicConnectionTest, InitialTimeout) {
4927   EXPECT_TRUE(connection_.connected());
4928   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4929   EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4930 
4931   // SetFromConfig sets the initial timeouts before negotiation.
4932   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4933   QuicConfig config;
4934   connection_.SetFromConfig(config);
4935   // Subtract a second from the idle timeout on the client side.
4936   QuicTime default_timeout =
4937       clock_.ApproximateNow() +
4938       QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4939   EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
4940 
4941   EXPECT_CALL(visitor_,
4942               OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
4943   // Simulate the timeout alarm firing.
4944   clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
4945   connection_.GetTimeoutAlarm()->Fire();
4946 
4947   EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4948   EXPECT_FALSE(connection_.connected());
4949 
4950   EXPECT_FALSE(connection_.HasPendingAcks());
4951   EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4952   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4953   EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4954   EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4955   EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4956   TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
4957 }
4958 
TEST_P(QuicConnectionTest,IdleTimeoutAfterFirstSentPacket)4959 TEST_P(QuicConnectionTest, IdleTimeoutAfterFirstSentPacket) {
4960   EXPECT_TRUE(connection_.connected());
4961   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4962   EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4963 
4964   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4965   QuicConfig config;
4966   connection_.SetFromConfig(config);
4967   EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4968   QuicTime initial_ddl =
4969       clock_.ApproximateNow() +
4970       QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4971   EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4972   EXPECT_TRUE(connection_.connected());
4973 
4974   // Advance the time and send the first packet to the peer.
4975   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
4976   QuicPacketNumber last_packet;
4977   SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4978   EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4979   // This will be the updated deadline for the connection to idle time out.
4980   QuicTime new_ddl = clock_.ApproximateNow() +
4981                      QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4982 
4983   // Simulate the timeout alarm firing, the connection should not be closed as
4984   // a new packet has been sent.
4985   EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
4986   QuicTime::Delta delay = initial_ddl - clock_.ApproximateNow();
4987   clock_.AdvanceTime(delay);
4988   // Verify the timeout alarm deadline is updated.
4989   EXPECT_TRUE(connection_.connected());
4990   EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4991   EXPECT_EQ(new_ddl, connection_.GetTimeoutAlarm()->deadline());
4992 
4993   // Simulate the timeout alarm firing again, the connection now should be
4994   // closed.
4995   EXPECT_CALL(visitor_,
4996               OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
4997   clock_.AdvanceTime(new_ddl - clock_.ApproximateNow());
4998   connection_.GetTimeoutAlarm()->Fire();
4999   EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5000   EXPECT_FALSE(connection_.connected());
5001 
5002   EXPECT_FALSE(connection_.HasPendingAcks());
5003   EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5004   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
5005   EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
5006   EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5007   TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
5008 }
5009 
TEST_P(QuicConnectionTest,IdleTimeoutAfterSendTwoPackets)5010 TEST_P(QuicConnectionTest, IdleTimeoutAfterSendTwoPackets) {
5011   EXPECT_TRUE(connection_.connected());
5012   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
5013   EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5014 
5015   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5016   QuicConfig config;
5017   connection_.SetFromConfig(config);
5018   EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5019   QuicTime initial_ddl =
5020       clock_.ApproximateNow() +
5021       QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5022   EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
5023   EXPECT_TRUE(connection_.connected());
5024 
5025   // Immediately send the first packet, this is a rare case but test code will
5026   // hit this issue often as MockClock used for tests doesn't move with code
5027   // execution until manually adjusted.
5028   QuicPacketNumber last_packet;
5029   SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
5030   EXPECT_EQ(QuicPacketNumber(1u), last_packet);
5031 
5032   // Advance the time and send the second packet to the peer.
5033   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
5034   SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
5035   EXPECT_EQ(QuicPacketNumber(2u), last_packet);
5036 
5037   // Simulate the timeout alarm firing, the connection will be closed.
5038   EXPECT_CALL(visitor_,
5039               OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5040   clock_.AdvanceTime(initial_ddl - clock_.ApproximateNow());
5041   connection_.GetTimeoutAlarm()->Fire();
5042 
5043   EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5044   EXPECT_FALSE(connection_.connected());
5045 
5046   EXPECT_FALSE(connection_.HasPendingAcks());
5047   EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5048   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
5049   EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
5050   EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5051   TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
5052 }
5053 
TEST_P(QuicConnectionTest,HandshakeTimeout)5054 TEST_P(QuicConnectionTest, HandshakeTimeout) {
5055   // Use a shorter handshake timeout than idle timeout for this test.
5056   const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
5057   connection_.SetNetworkTimeouts(timeout, timeout);
5058   EXPECT_TRUE(connection_.connected());
5059   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
5060 
5061   QuicTime handshake_timeout =
5062       clock_.ApproximateNow() + timeout - QuicTime::Delta::FromSeconds(1);
5063   EXPECT_EQ(handshake_timeout, connection_.GetTimeoutAlarm()->deadline());
5064   EXPECT_TRUE(connection_.connected());
5065 
5066   // Send and ack new data 3 seconds later to lengthen the idle timeout.
5067   SendStreamDataToPeer(
5068       GetNthClientInitiatedStreamId(0, connection_.transport_version()),
5069       "GET /", 0, FIN, nullptr);
5070   clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
5071   QuicAckFrame frame = InitAckFrame(1);
5072   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5073   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
5074   ProcessAckPacket(&frame);
5075 
5076   EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5077   EXPECT_TRUE(connection_.connected());
5078 
5079   clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(2));
5080 
5081   EXPECT_CALL(visitor_,
5082               OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5083   // Simulate the timeout alarm firing.
5084   connection_.GetTimeoutAlarm()->Fire();
5085 
5086   EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5087   EXPECT_FALSE(connection_.connected());
5088 
5089   EXPECT_FALSE(connection_.HasPendingAcks());
5090   EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5091   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
5092   EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
5093   TestConnectionCloseQuicErrorCode(QUIC_HANDSHAKE_TIMEOUT);
5094 }
5095 
TEST_P(QuicConnectionTest,PingAfterSend)5096 TEST_P(QuicConnectionTest, PingAfterSend) {
5097   if (connection_.SupportsMultiplePacketNumberSpaces()) {
5098     return;
5099   }
5100   EXPECT_TRUE(connection_.connected());
5101   EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5102       .WillRepeatedly(Return(true));
5103   EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5104 
5105   // Advance to 5ms, and send a packet to the peer, which will set
5106   // the ping alarm.
5107   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5108   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
5109   SendStreamDataToPeer(
5110       GetNthClientInitiatedStreamId(0, connection_.transport_version()),
5111       "GET /", 0, FIN, nullptr);
5112   EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
5113   EXPECT_EQ(QuicTime::Delta::FromSeconds(15),
5114             connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
5115 
5116   // Now recevie an ACK of the previous packet, which will move the
5117   // ping alarm forward.
5118   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5119   QuicAckFrame frame = InitAckFrame(1);
5120   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5121   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
5122   ProcessAckPacket(&frame);
5123   EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
5124   // The ping timer is set slightly less than 15 seconds in the future, because
5125   // of the 1s ping timer alarm granularity.
5126   EXPECT_EQ(
5127       QuicTime::Delta::FromSeconds(15) - QuicTime::Delta::FromMilliseconds(5),
5128       connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
5129 
5130   writer_->Reset();
5131   clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
5132   connection_.GetPingAlarm()->Fire();
5133   size_t padding_frame_count = writer_->padding_frames().size();
5134   EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
5135   ASSERT_EQ(1u, writer_->ping_frames().size());
5136   writer_->Reset();
5137 
5138   EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5139       .WillRepeatedly(Return(false));
5140   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5141   SendAckPacketToPeer();
5142 
5143   EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5144 }
5145 
TEST_P(QuicConnectionTest,ReducedPingTimeout)5146 TEST_P(QuicConnectionTest, ReducedPingTimeout) {
5147   if (connection_.SupportsMultiplePacketNumberSpaces()) {
5148     return;
5149   }
5150   EXPECT_TRUE(connection_.connected());
5151   EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5152       .WillRepeatedly(Return(true));
5153   EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5154 
5155   // Use a reduced ping timeout for this connection.
5156   connection_.set_keep_alive_ping_timeout(QuicTime::Delta::FromSeconds(10));
5157 
5158   // Advance to 5ms, and send a packet to the peer, which will set
5159   // the ping alarm.
5160   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5161   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
5162   SendStreamDataToPeer(
5163       GetNthClientInitiatedStreamId(0, connection_.transport_version()),
5164       "GET /", 0, FIN, nullptr);
5165   EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
5166   EXPECT_EQ(QuicTime::Delta::FromSeconds(10),
5167             connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
5168 
5169   // Now recevie an ACK of the previous packet, which will move the
5170   // ping alarm forward.
5171   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5172   QuicAckFrame frame = InitAckFrame(1);
5173   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5174   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
5175   ProcessAckPacket(&frame);
5176   EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
5177   // The ping timer is set slightly less than 10 seconds in the future, because
5178   // of the 1s ping timer alarm granularity.
5179   EXPECT_EQ(
5180       QuicTime::Delta::FromSeconds(10) - QuicTime::Delta::FromMilliseconds(5),
5181       connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
5182 
5183   writer_->Reset();
5184   clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
5185   connection_.GetPingAlarm()->Fire();
5186   size_t padding_frame_count = writer_->padding_frames().size();
5187   EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
5188   ASSERT_EQ(1u, writer_->ping_frames().size());
5189   writer_->Reset();
5190 
5191   EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5192       .WillRepeatedly(Return(false));
5193   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5194   SendAckPacketToPeer();
5195 
5196   EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5197 }
5198 
5199 // Tests whether sending an MTU discovery packet to peer successfully causes the
5200 // maximum packet size to increase.
TEST_P(QuicConnectionTest,SendMtuDiscoveryPacket)5201 TEST_P(QuicConnectionTest, SendMtuDiscoveryPacket) {
5202   MtuDiscoveryTestInit();
5203 
5204   // Send an MTU probe.
5205   const size_t new_mtu = kDefaultMaxPacketSize + 100;
5206   QuicByteCount mtu_probe_size;
5207   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5208       .WillOnce(SaveArg<3>(&mtu_probe_size));
5209   connection_.SendMtuDiscoveryPacket(new_mtu);
5210   EXPECT_EQ(new_mtu, mtu_probe_size);
5211   EXPECT_EQ(QuicPacketNumber(1u), creator_->packet_number());
5212 
5213   // Send more than MTU worth of data.  No acknowledgement was received so far,
5214   // so the MTU should be at its old value.
5215   const std::string data(kDefaultMaxPacketSize + 1, '.');
5216   QuicByteCount size_before_mtu_change;
5217   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5218       .Times(2)
5219       .WillOnce(SaveArg<3>(&size_before_mtu_change))
5220       .WillOnce(Return());
5221   connection_.SendStreamDataWithString(3, data, 0, FIN);
5222   EXPECT_EQ(QuicPacketNumber(3u), creator_->packet_number());
5223   EXPECT_EQ(kDefaultMaxPacketSize, size_before_mtu_change);
5224 
5225   // Acknowledge all packets so far.
5226   QuicAckFrame probe_ack = InitAckFrame(3);
5227   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
5228   ProcessAckPacket(&probe_ack);
5229   EXPECT_EQ(new_mtu, connection_.max_packet_length());
5230 
5231   // Send the same data again.  Check that it fits into a single packet now.
5232   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
5233   connection_.SendStreamDataWithString(3, data, 0, FIN);
5234   EXPECT_EQ(QuicPacketNumber(4u), creator_->packet_number());
5235 }
5236 
5237 // Verifies that when a MTU probe packet is sent and buffered in a batch writer,
5238 // the writer is flushed immediately.
TEST_P(QuicConnectionTest,BatchWriterFlushedAfterMtuDiscoveryPacket)5239 TEST_P(QuicConnectionTest, BatchWriterFlushedAfterMtuDiscoveryPacket) {
5240   writer_->SetBatchMode(true);
5241   MtuDiscoveryTestInit();
5242 
5243   // Send an MTU probe.
5244   const size_t target_mtu = kDefaultMaxPacketSize + 100;
5245   QuicByteCount mtu_probe_size;
5246   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5247       .WillOnce(SaveArg<3>(&mtu_probe_size));
5248   const uint32_t prior_flush_attempts = writer_->flush_attempts();
5249   connection_.SendMtuDiscoveryPacket(target_mtu);
5250   EXPECT_EQ(target_mtu, mtu_probe_size);
5251   EXPECT_EQ(writer_->flush_attempts(), prior_flush_attempts + 1);
5252 }
5253 
5254 // Tests whether MTU discovery does not happen when it is not explicitly enabled
5255 // by the connection options.
TEST_P(QuicConnectionTest,MtuDiscoveryDisabled)5256 TEST_P(QuicConnectionTest, MtuDiscoveryDisabled) {
5257   MtuDiscoveryTestInit();
5258 
5259   const QuicPacketCount packets_between_probes_base = 10;
5260   set_packets_between_probes_base(packets_between_probes_base);
5261 
5262   const QuicPacketCount number_of_packets = packets_between_probes_base * 2;
5263   for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5264     SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5265     EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5266     EXPECT_EQ(0u, connection_.mtu_probe_count());
5267   }
5268 }
5269 
5270 // Tests whether MTU discovery works when all probes are acknowledged on the
5271 // first try.
TEST_P(QuicConnectionTest,MtuDiscoveryEnabled)5272 TEST_P(QuicConnectionTest, MtuDiscoveryEnabled) {
5273   MtuDiscoveryTestInit();
5274 
5275   const QuicPacketCount packets_between_probes_base = 5;
5276   set_packets_between_probes_base(packets_between_probes_base);
5277 
5278   connection_.EnablePathMtuDiscovery(send_algorithm_);
5279 
5280   // Send enough packets so that the next one triggers path MTU discovery.
5281   for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5282     SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5283     ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5284   }
5285 
5286   // Trigger the probe.
5287   SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5288                        nullptr);
5289   ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5290   QuicByteCount probe_size;
5291   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5292       .WillOnce(SaveArg<3>(&probe_size));
5293   connection_.GetMtuDiscoveryAlarm()->Fire();
5294 
5295   EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5296                                   kMtuDiscoveryTargetPacketSizeHigh));
5297 
5298   const QuicPacketNumber probe_packet_number =
5299       FirstSendingPacketNumber() + packets_between_probes_base;
5300   ASSERT_EQ(probe_packet_number, creator_->packet_number());
5301 
5302   // Acknowledge all packets sent so far.
5303   {
5304     QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
5305     EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
5306         .Times(AnyNumber());
5307     ProcessAckPacket(&probe_ack);
5308     EXPECT_EQ(probe_size, connection_.max_packet_length());
5309     EXPECT_EQ(0u, connection_.GetBytesInFlight());
5310 
5311     EXPECT_EQ(1u, connection_.mtu_probe_count());
5312   }
5313 
5314   QuicStreamOffset stream_offset = packets_between_probes_base;
5315   QuicByteCount last_probe_size = 0;
5316   for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5317        ++num_probes) {
5318     // Send just enough packets without triggering the next probe.
5319     for (QuicPacketCount i = 0;
5320          i < (packets_between_probes_base << num_probes) - 1; ++i) {
5321       SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5322       ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5323     }
5324 
5325     // Trigger the next probe.
5326     SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5327     ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5328     QuicByteCount new_probe_size;
5329     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5330         .WillOnce(SaveArg<3>(&new_probe_size));
5331     connection_.GetMtuDiscoveryAlarm()->Fire();
5332     EXPECT_THAT(new_probe_size,
5333                 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5334     EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5335 
5336     // Acknowledge all packets sent so far.
5337     QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5338     ProcessAckPacket(&probe_ack);
5339     EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5340     EXPECT_EQ(0u, connection_.GetBytesInFlight());
5341 
5342     last_probe_size = probe_size;
5343     probe_size = new_probe_size;
5344   }
5345 
5346   // The last probe size should be equal to the target.
5347   EXPECT_EQ(probe_size, kMtuDiscoveryTargetPacketSizeHigh);
5348 
5349   writer_->SetShouldWriteFail();
5350 
5351   // Ignore PACKET_WRITE_ERROR once.
5352   SendStreamDataToPeer(3, "(", stream_offset++, NO_FIN, nullptr);
5353   EXPECT_EQ(last_probe_size, connection_.max_packet_length());
5354   EXPECT_TRUE(connection_.connected());
5355 
5356   // Close connection on another PACKET_WRITE_ERROR.
5357   EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
5358       .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5359   SendStreamDataToPeer(3, ")", stream_offset++, NO_FIN, nullptr);
5360   EXPECT_EQ(last_probe_size, connection_.max_packet_length());
5361   EXPECT_FALSE(connection_.connected());
5362   EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5363               IsError(QUIC_PACKET_WRITE_ERROR));
5364 }
5365 
5366 // After a successful MTU probe, one and only one write error should be ignored
5367 // if it happened in QuicConnection::FlushPacket.
TEST_P(QuicConnectionTest,MtuDiscoveryIgnoreOneWriteErrorInFlushAfterSuccessfulProbes)5368 TEST_P(QuicConnectionTest,
5369        MtuDiscoveryIgnoreOneWriteErrorInFlushAfterSuccessfulProbes) {
5370   MtuDiscoveryTestInit();
5371   writer_->SetBatchMode(true);
5372 
5373   const QuicPacketCount packets_between_probes_base = 5;
5374   set_packets_between_probes_base(packets_between_probes_base);
5375 
5376   connection_.EnablePathMtuDiscovery(send_algorithm_);
5377 
5378   const QuicByteCount original_max_packet_length =
5379       connection_.max_packet_length();
5380   // Send enough packets so that the next one triggers path MTU discovery.
5381   for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5382     SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5383     ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5384   }
5385 
5386   // Trigger the probe.
5387   SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5388                        nullptr);
5389   ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5390   QuicByteCount probe_size;
5391   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5392       .WillOnce(SaveArg<3>(&probe_size));
5393   connection_.GetMtuDiscoveryAlarm()->Fire();
5394 
5395   EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5396                                   kMtuDiscoveryTargetPacketSizeHigh));
5397 
5398   const QuicPacketNumber probe_packet_number =
5399       FirstSendingPacketNumber() + packets_between_probes_base;
5400   ASSERT_EQ(probe_packet_number, creator_->packet_number());
5401 
5402   // Acknowledge all packets sent so far.
5403   {
5404     QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
5405     EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
5406         .Times(AnyNumber());
5407     ProcessAckPacket(&probe_ack);
5408     EXPECT_EQ(probe_size, connection_.max_packet_length());
5409     EXPECT_EQ(0u, connection_.GetBytesInFlight());
5410   }
5411 
5412   EXPECT_EQ(1u, connection_.mtu_probe_count());
5413 
5414   writer_->SetShouldWriteFail();
5415 
5416   // Ignore PACKET_WRITE_ERROR once.
5417   {
5418     QuicConnection::ScopedPacketFlusher flusher(&connection_);
5419     // flusher's destructor will call connection_.FlushPackets, which should
5420     // get a WRITE_STATUS_ERROR from the writer and ignore it.
5421   }
5422   EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5423   EXPECT_TRUE(connection_.connected());
5424 
5425   // Close connection on another PACKET_WRITE_ERROR.
5426   EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
5427       .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5428   {
5429     QuicConnection::ScopedPacketFlusher flusher(&connection_);
5430     // flusher's destructor will call connection_.FlushPackets, which should
5431     // get a WRITE_STATUS_ERROR from the writer and ignore it.
5432   }
5433   EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5434   EXPECT_FALSE(connection_.connected());
5435   EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5436               IsError(QUIC_PACKET_WRITE_ERROR));
5437 }
5438 
5439 // Simulate the case where the first attempt to send a probe is write blocked,
5440 // and after unblock, the second attempt returns a MSG_TOO_BIG error.
TEST_P(QuicConnectionTest,MtuDiscoveryWriteBlocked)5441 TEST_P(QuicConnectionTest, MtuDiscoveryWriteBlocked) {
5442   MtuDiscoveryTestInit();
5443 
5444   const QuicPacketCount packets_between_probes_base = 5;
5445   set_packets_between_probes_base(packets_between_probes_base);
5446 
5447   connection_.EnablePathMtuDiscovery(send_algorithm_);
5448 
5449   // Send enough packets so that the next one triggers path MTU discovery.
5450   for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5451     SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5452     ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5453   }
5454 
5455   QuicByteCount original_max_packet_length = connection_.max_packet_length();
5456 
5457   // Trigger the probe.
5458   SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5459                        nullptr);
5460   ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5461   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5462   BlockOnNextWrite();
5463   EXPECT_EQ(0u, connection_.NumQueuedPackets());
5464   connection_.GetMtuDiscoveryAlarm()->Fire();
5465   EXPECT_EQ(1u, connection_.mtu_probe_count());
5466   EXPECT_EQ(1u, connection_.NumQueuedPackets());
5467   ASSERT_TRUE(connection_.connected());
5468 
5469   writer_->SetWritable();
5470   SimulateNextPacketTooLarge();
5471   connection_.OnCanWrite();
5472   EXPECT_EQ(0u, connection_.NumQueuedPackets());
5473   EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5474   EXPECT_TRUE(connection_.connected());
5475 }
5476 
5477 // Tests whether MTU discovery works correctly when the probes never get
5478 // acknowledged.
TEST_P(QuicConnectionTest,MtuDiscoveryFailed)5479 TEST_P(QuicConnectionTest, MtuDiscoveryFailed) {
5480   MtuDiscoveryTestInit();
5481 
5482   // Lower the number of probes between packets in order to make the test go
5483   // much faster.
5484   const QuicPacketCount packets_between_probes_base = 5;
5485   set_packets_between_probes_base(packets_between_probes_base);
5486 
5487   connection_.EnablePathMtuDiscovery(send_algorithm_);
5488 
5489   const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(100);
5490 
5491   EXPECT_EQ(packets_between_probes_base,
5492             QuicConnectionPeer::GetPacketsBetweenMtuProbes(&connection_));
5493 
5494   // This tests sends more packets than strictly necessary to make sure that if
5495   // the connection was to send more discovery packets than needed, those would
5496   // get caught as well.
5497   const QuicPacketCount number_of_packets =
5498       packets_between_probes_base * (1 << (kMtuDiscoveryAttempts + 1));
5499   std::vector<QuicPacketNumber> mtu_discovery_packets;
5500   // Called on many acks.
5501   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
5502       .Times(AnyNumber());
5503   for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5504     SendStreamDataToPeer(3, "!", i, NO_FIN, nullptr);
5505     clock_.AdvanceTime(rtt);
5506 
5507     // Receive an ACK, which marks all data packets as received, and all MTU
5508     // discovery packets as missing.
5509 
5510     QuicAckFrame ack;
5511 
5512     if (!mtu_discovery_packets.empty()) {
5513       QuicPacketNumber min_packet = *min_element(mtu_discovery_packets.begin(),
5514                                                  mtu_discovery_packets.end());
5515       QuicPacketNumber max_packet = *max_element(mtu_discovery_packets.begin(),
5516                                                  mtu_discovery_packets.end());
5517       ack.packets.AddRange(QuicPacketNumber(1), min_packet);
5518       ack.packets.AddRange(QuicPacketNumber(max_packet + 1),
5519                            creator_->packet_number() + 1);
5520       ack.largest_acked = creator_->packet_number();
5521 
5522     } else {
5523       ack.packets.AddRange(QuicPacketNumber(1), creator_->packet_number() + 1);
5524       ack.largest_acked = creator_->packet_number();
5525     }
5526 
5527     ProcessAckPacket(&ack);
5528 
5529     // Trigger MTU probe if it would be scheduled now.
5530     if (!connection_.GetMtuDiscoveryAlarm()->IsSet()) {
5531       continue;
5532     }
5533 
5534     // Fire the alarm.  The alarm should cause a packet to be sent.
5535     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5536     connection_.GetMtuDiscoveryAlarm()->Fire();
5537     // Record the packet number of the MTU discovery packet in order to
5538     // mark it as NACK'd.
5539     mtu_discovery_packets.push_back(creator_->packet_number());
5540   }
5541 
5542   // Ensure the number of packets between probes grows exponentially by checking
5543   // it against the closed-form expression for the packet number.
5544   ASSERT_EQ(kMtuDiscoveryAttempts, mtu_discovery_packets.size());
5545   for (uint64_t i = 0; i < kMtuDiscoveryAttempts; i++) {
5546     // 2^0 + 2^1 + 2^2 + ... + 2^n = 2^(n + 1) - 1
5547     const QuicPacketCount packets_between_probes =
5548         packets_between_probes_base * ((1 << (i + 1)) - 1);
5549     EXPECT_EQ(QuicPacketNumber(packets_between_probes + (i + 1)),
5550               mtu_discovery_packets[i]);
5551   }
5552 
5553   EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5554   EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
5555   EXPECT_EQ(kMtuDiscoveryAttempts, connection_.mtu_probe_count());
5556 }
5557 
5558 // Probe 3 times, the first one succeeds, then fails, then succeeds again.
TEST_P(QuicConnectionTest,MtuDiscoverySecondProbeFailed)5559 TEST_P(QuicConnectionTest, MtuDiscoverySecondProbeFailed) {
5560   MtuDiscoveryTestInit();
5561 
5562   const QuicPacketCount packets_between_probes_base = 5;
5563   set_packets_between_probes_base(packets_between_probes_base);
5564 
5565   connection_.EnablePathMtuDiscovery(send_algorithm_);
5566 
5567   // Send enough packets so that the next one triggers path MTU discovery.
5568   QuicStreamOffset stream_offset = 0;
5569   for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5570     SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5571     ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5572   }
5573 
5574   // Trigger the probe.
5575   SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5576                        nullptr);
5577   ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5578   QuicByteCount probe_size;
5579   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5580       .WillOnce(SaveArg<3>(&probe_size));
5581   connection_.GetMtuDiscoveryAlarm()->Fire();
5582   EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5583                                   kMtuDiscoveryTargetPacketSizeHigh));
5584 
5585   const QuicPacketNumber probe_packet_number =
5586       FirstSendingPacketNumber() + packets_between_probes_base;
5587   ASSERT_EQ(probe_packet_number, creator_->packet_number());
5588 
5589   // Acknowledge all packets sent so far.
5590   QuicAckFrame first_ack = InitAckFrame(probe_packet_number);
5591   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
5592       .Times(AnyNumber());
5593   ProcessAckPacket(&first_ack);
5594   EXPECT_EQ(probe_size, connection_.max_packet_length());
5595   EXPECT_EQ(0u, connection_.GetBytesInFlight());
5596 
5597   EXPECT_EQ(1u, connection_.mtu_probe_count());
5598 
5599   // Send just enough packets without triggering the second probe.
5600   for (QuicPacketCount i = 0; i < (packets_between_probes_base << 1) - 1; ++i) {
5601     SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5602     ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5603   }
5604 
5605   // Trigger the second probe.
5606   SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5607   ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5608   QuicByteCount second_probe_size;
5609   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5610       .WillOnce(SaveArg<3>(&second_probe_size));
5611   connection_.GetMtuDiscoveryAlarm()->Fire();
5612   EXPECT_THAT(second_probe_size,
5613               InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5614   EXPECT_EQ(2u, connection_.mtu_probe_count());
5615 
5616   // Acknowledge all packets sent so far, except the second probe.
5617   QuicPacketNumber second_probe_packet_number = creator_->packet_number();
5618   QuicAckFrame second_ack = InitAckFrame(second_probe_packet_number - 1);
5619   ProcessAckPacket(&first_ack);
5620   EXPECT_EQ(probe_size, connection_.max_packet_length());
5621 
5622   // Send just enough packets without triggering the third probe.
5623   for (QuicPacketCount i = 0; i < (packets_between_probes_base << 2) - 1; ++i) {
5624     SendStreamDataToPeer(3, "@", stream_offset++, NO_FIN, nullptr);
5625     ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5626   }
5627 
5628   // Trigger the third probe.
5629   SendStreamDataToPeer(3, "#", stream_offset++, NO_FIN, nullptr);
5630   ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5631   QuicByteCount third_probe_size;
5632   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5633       .WillOnce(SaveArg<3>(&third_probe_size));
5634   connection_.GetMtuDiscoveryAlarm()->Fire();
5635   EXPECT_THAT(third_probe_size, InRange(probe_size, second_probe_size));
5636   EXPECT_EQ(3u, connection_.mtu_probe_count());
5637 
5638   // Acknowledge all packets sent so far, except the second probe.
5639   QuicAckFrame third_ack =
5640       ConstructAckFrame(creator_->packet_number(), second_probe_packet_number);
5641   ProcessAckPacket(&third_ack);
5642   EXPECT_EQ(third_probe_size, connection_.max_packet_length());
5643 
5644   SendStreamDataToPeer(3, "$", stream_offset++, NO_FIN, nullptr);
5645   EXPECT_TRUE(connection_.PathMtuReductionDetectionInProgress());
5646 
5647   if (connection_.PathDegradingDetectionInProgress() &&
5648       QuicConnectionPeer::GetPathDegradingDeadline(&connection_) <
5649           QuicConnectionPeer::GetPathMtuReductionDetectionDeadline(
5650               &connection_)) {
5651     // Fire path degrading alarm first.
5652     connection_.PathDegradingTimeout();
5653   }
5654 
5655   // Verify the max packet size has not reduced.
5656   EXPECT_EQ(third_probe_size, connection_.max_packet_length());
5657 
5658   // Fire alarm to get path mtu reduction callback called.
5659   EXPECT_TRUE(connection_.PathMtuReductionDetectionInProgress());
5660   connection_.GetBlackholeDetectorAlarm()->Fire();
5661 
5662   // Verify the max packet size has reduced to the previous value.
5663   EXPECT_EQ(probe_size, connection_.max_packet_length());
5664 }
5665 
5666 // Tests whether MTU discovery works when the writer has a limit on how large a
5667 // packet can be.
TEST_P(QuicConnectionTest,MtuDiscoveryWriterLimited)5668 TEST_P(QuicConnectionTest, MtuDiscoveryWriterLimited) {
5669   MtuDiscoveryTestInit();
5670 
5671   const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5672   writer_->set_max_packet_size(mtu_limit);
5673 
5674   const QuicPacketCount packets_between_probes_base = 5;
5675   set_packets_between_probes_base(packets_between_probes_base);
5676 
5677   connection_.EnablePathMtuDiscovery(send_algorithm_);
5678 
5679   // Send enough packets so that the next one triggers path MTU discovery.
5680   for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5681     SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5682     ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5683   }
5684 
5685   // Trigger the probe.
5686   SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5687                        nullptr);
5688   ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5689   QuicByteCount probe_size;
5690   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5691       .WillOnce(SaveArg<3>(&probe_size));
5692   connection_.GetMtuDiscoveryAlarm()->Fire();
5693 
5694   EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(), mtu_limit));
5695 
5696   const QuicPacketNumber probe_sequence_number =
5697       FirstSendingPacketNumber() + packets_between_probes_base;
5698   ASSERT_EQ(probe_sequence_number, creator_->packet_number());
5699 
5700   // Acknowledge all packets sent so far.
5701   {
5702     QuicAckFrame probe_ack = InitAckFrame(probe_sequence_number);
5703     EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
5704         .Times(AnyNumber());
5705     ProcessAckPacket(&probe_ack);
5706     EXPECT_EQ(probe_size, connection_.max_packet_length());
5707     EXPECT_EQ(0u, connection_.GetBytesInFlight());
5708   }
5709 
5710   EXPECT_EQ(1u, connection_.mtu_probe_count());
5711 
5712   QuicStreamOffset stream_offset = packets_between_probes_base;
5713   for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5714        ++num_probes) {
5715     // Send just enough packets without triggering the next probe.
5716     for (QuicPacketCount i = 0;
5717          i < (packets_between_probes_base << num_probes) - 1; ++i) {
5718       SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5719       ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5720     }
5721 
5722     // Trigger the next probe.
5723     SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5724     ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5725     QuicByteCount new_probe_size;
5726     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5727         .WillOnce(SaveArg<3>(&new_probe_size));
5728     connection_.GetMtuDiscoveryAlarm()->Fire();
5729     EXPECT_THAT(new_probe_size, InRange(probe_size, mtu_limit));
5730     EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5731 
5732     // Acknowledge all packets sent so far.
5733     QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5734     ProcessAckPacket(&probe_ack);
5735     EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5736     EXPECT_EQ(0u, connection_.GetBytesInFlight());
5737 
5738     probe_size = new_probe_size;
5739   }
5740 
5741   // The last probe size should be equal to the target.
5742   EXPECT_EQ(probe_size, mtu_limit);
5743 }
5744 
5745 // Tests whether MTU discovery works when the writer returns an error despite
5746 // advertising higher packet length.
TEST_P(QuicConnectionTest,MtuDiscoveryWriterFailed)5747 TEST_P(QuicConnectionTest, MtuDiscoveryWriterFailed) {
5748   MtuDiscoveryTestInit();
5749 
5750   const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5751   const QuicByteCount initial_mtu = connection_.max_packet_length();
5752   EXPECT_LT(initial_mtu, mtu_limit);
5753   writer_->set_max_packet_size(mtu_limit);
5754 
5755   const QuicPacketCount packets_between_probes_base = 5;
5756   set_packets_between_probes_base(packets_between_probes_base);
5757 
5758   connection_.EnablePathMtuDiscovery(send_algorithm_);
5759 
5760   // Send enough packets so that the next one triggers path MTU discovery.
5761   for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5762     SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5763     ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5764   }
5765 
5766   // Trigger the probe.
5767   SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5768                        nullptr);
5769   ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5770   writer_->SimulateNextPacketTooLarge();
5771   connection_.GetMtuDiscoveryAlarm()->Fire();
5772   ASSERT_TRUE(connection_.connected());
5773 
5774   // Send more data.
5775   QuicPacketNumber probe_number = creator_->packet_number();
5776   QuicPacketCount extra_packets = packets_between_probes_base * 3;
5777   for (QuicPacketCount i = 0; i < extra_packets; i++) {
5778     connection_.EnsureWritableAndSendStreamData5();
5779     ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5780   }
5781 
5782   // Acknowledge all packets sent so far, except for the lost probe.
5783   QuicAckFrame probe_ack =
5784       ConstructAckFrame(creator_->packet_number(), probe_number);
5785   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
5786   ProcessAckPacket(&probe_ack);
5787   EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5788 
5789   // Send more packets, and ensure that none of them sets the alarm.
5790   for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
5791     connection_.EnsureWritableAndSendStreamData5();
5792     ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5793   }
5794 
5795   EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5796   EXPECT_EQ(1u, connection_.mtu_probe_count());
5797 }
5798 
TEST_P(QuicConnectionTest,NoMtuDiscoveryAfterConnectionClosed)5799 TEST_P(QuicConnectionTest, NoMtuDiscoveryAfterConnectionClosed) {
5800   MtuDiscoveryTestInit();
5801 
5802   const QuicPacketCount packets_between_probes_base = 10;
5803   set_packets_between_probes_base(packets_between_probes_base);
5804 
5805   connection_.EnablePathMtuDiscovery(send_algorithm_);
5806 
5807   // Send enough packets so that the next one triggers path MTU discovery.
5808   for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5809     SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5810     ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5811   }
5812 
5813   SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5814                        nullptr);
5815   EXPECT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5816 
5817   EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
5818   connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
5819                               ConnectionCloseBehavior::SILENT_CLOSE);
5820   EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5821 }
5822 
TEST_P(QuicConnectionTest,TimeoutAfterSendDuringHandshake)5823 TEST_P(QuicConnectionTest, TimeoutAfterSendDuringHandshake) {
5824   EXPECT_TRUE(connection_.connected());
5825   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5826   QuicConfig config;
5827   connection_.SetFromConfig(config);
5828 
5829   const QuicTime::Delta initial_idle_timeout =
5830       QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5831   const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5832   QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5833 
5834   // When we send a packet, the timeout will change to 5ms +
5835   // kInitialIdleTimeoutSecs.
5836   clock_.AdvanceTime(five_ms);
5837   SendStreamDataToPeer(
5838       GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5839       0, FIN, nullptr);
5840   EXPECT_EQ(default_timeout + five_ms,
5841             connection_.GetTimeoutAlarm()->deadline());
5842 
5843   // Now send more data. This will not move the timeout because
5844   // no data has been received since the previous write.
5845   clock_.AdvanceTime(five_ms);
5846   SendStreamDataToPeer(
5847       GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5848       3, FIN, nullptr);
5849   EXPECT_EQ(default_timeout + five_ms,
5850             connection_.GetTimeoutAlarm()->deadline());
5851 
5852   // The original alarm will fire.  We should not time out because we had a
5853   // network event at t=5ms.  The alarm will reregister.
5854   clock_.AdvanceTime(initial_idle_timeout - five_ms - five_ms);
5855   EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5856   EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5857   EXPECT_TRUE(connection_.connected());
5858   EXPECT_EQ(default_timeout + five_ms,
5859             connection_.GetTimeoutAlarm()->deadline());
5860 
5861   // This time, we should time out.
5862   EXPECT_CALL(visitor_,
5863               OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5864   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
5865   clock_.AdvanceTime(five_ms);
5866   EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5867   connection_.GetTimeoutAlarm()->Fire();
5868   EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5869   EXPECT_FALSE(connection_.connected());
5870   TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
5871 }
5872 
TEST_P(QuicConnectionTest,TimeoutAfterSendAfterHandshake)5873 TEST_P(QuicConnectionTest, TimeoutAfterSendAfterHandshake) {
5874   // When the idle timeout fires, verify that by default we do not send any
5875   // connection close packets.
5876   EXPECT_TRUE(connection_.connected());
5877   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5878   QuicConfig config;
5879 
5880   // Create a handshake message that also enables silent close.
5881   CryptoHandshakeMessage msg;
5882   std::string error_details;
5883   QuicConfig client_config;
5884   client_config.SetInitialStreamFlowControlWindowToSend(
5885       kInitialStreamFlowControlWindowForTest);
5886   client_config.SetInitialSessionFlowControlWindowToSend(
5887       kInitialSessionFlowControlWindowForTest);
5888   client_config.SetIdleNetworkTimeout(
5889       QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
5890   client_config.ToHandshakeMessage(&msg, connection_.transport_version());
5891   const QuicErrorCode error =
5892       config.ProcessPeerHello(msg, CLIENT, &error_details);
5893   EXPECT_THAT(error, IsQuicNoError());
5894 
5895   if (connection_.version().UsesTls()) {
5896     QuicConfigPeer::SetReceivedOriginalConnectionId(
5897         &config, connection_.connection_id());
5898     QuicConfigPeer::SetReceivedInitialSourceConnectionId(
5899         &config, connection_.connection_id());
5900   }
5901   connection_.SetFromConfig(config);
5902 
5903   const QuicTime::Delta default_idle_timeout =
5904       QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
5905   const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5906   QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5907 
5908   // When we send a packet, the timeout will change to 5ms +
5909   // kInitialIdleTimeoutSecs.
5910   clock_.AdvanceTime(five_ms);
5911   SendStreamDataToPeer(
5912       GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5913       0, FIN, nullptr);
5914   EXPECT_EQ(default_timeout + five_ms,
5915             connection_.GetTimeoutAlarm()->deadline());
5916 
5917   // Now send more data. This will not move the timeout because
5918   // no data has been received since the previous write.
5919   clock_.AdvanceTime(five_ms);
5920   SendStreamDataToPeer(
5921       GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5922       3, FIN, nullptr);
5923   EXPECT_EQ(default_timeout + five_ms,
5924             connection_.GetTimeoutAlarm()->deadline());
5925 
5926   // The original alarm will fire.  We should not time out because we had a
5927   // network event at t=5ms.  The alarm will reregister.
5928   clock_.AdvanceTime(default_idle_timeout - five_ms - five_ms);
5929   EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5930   EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5931   EXPECT_TRUE(connection_.connected());
5932   EXPECT_EQ(default_timeout + five_ms,
5933             connection_.GetTimeoutAlarm()->deadline());
5934 
5935   // This time, we should time out.
5936   // This results in a SILENT_CLOSE, so the writer will not be invoked
5937   // and will not save the frame. Grab the frame from OnConnectionClosed
5938   // directly.
5939   EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
5940       .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5941 
5942   clock_.AdvanceTime(five_ms);
5943   EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5944   connection_.GetTimeoutAlarm()->Fire();
5945   EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5946   EXPECT_FALSE(connection_.connected());
5947   EXPECT_EQ(1, connection_close_frame_count_);
5948   EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5949               IsError(QUIC_NETWORK_IDLE_TIMEOUT));
5950 }
5951 
TEST_P(QuicConnectionTest,TimeoutAfterSendSilentCloseWithOpenStreams)5952 TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseWithOpenStreams) {
5953   // Same test as above, but having open streams causes a connection close
5954   // to be sent.
5955   EXPECT_TRUE(connection_.connected());
5956   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5957   QuicConfig config;
5958 
5959   // Create a handshake message that also enables silent close.
5960   CryptoHandshakeMessage msg;
5961   std::string error_details;
5962   QuicConfig client_config;
5963   client_config.SetInitialStreamFlowControlWindowToSend(
5964       kInitialStreamFlowControlWindowForTest);
5965   client_config.SetInitialSessionFlowControlWindowToSend(
5966       kInitialSessionFlowControlWindowForTest);
5967   client_config.SetIdleNetworkTimeout(
5968       QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
5969   client_config.ToHandshakeMessage(&msg, connection_.transport_version());
5970   const QuicErrorCode error =
5971       config.ProcessPeerHello(msg, CLIENT, &error_details);
5972   EXPECT_THAT(error, IsQuicNoError());
5973 
5974   if (connection_.version().UsesTls()) {
5975     QuicConfigPeer::SetReceivedOriginalConnectionId(
5976         &config, connection_.connection_id());
5977     QuicConfigPeer::SetReceivedInitialSourceConnectionId(
5978         &config, connection_.connection_id());
5979   }
5980   connection_.SetFromConfig(config);
5981 
5982   const QuicTime::Delta default_idle_timeout =
5983       QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
5984   const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5985   QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5986 
5987   // When we send a packet, the timeout will change to 5ms +
5988   // kInitialIdleTimeoutSecs.
5989   clock_.AdvanceTime(five_ms);
5990   SendStreamDataToPeer(
5991       GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5992       0, FIN, nullptr);
5993   EXPECT_EQ(default_timeout + five_ms,
5994             connection_.GetTimeoutAlarm()->deadline());
5995 
5996   // Indicate streams are still open.
5997   EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5998       .WillRepeatedly(Return(true));
5999   if (GetQuicReloadableFlag(quic_add_stream_info_to_idle_close_detail)) {
6000     EXPECT_CALL(visitor_, GetStreamsInfoForLogging()).WillOnce(Return(""));
6001   }
6002 
6003   // This time, we should time out and send a connection close due to the TLP.
6004   EXPECT_CALL(visitor_,
6005               OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
6006   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
6007   clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
6008                      clock_.ApproximateNow() + five_ms);
6009   connection_.GetTimeoutAlarm()->Fire();
6010   EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
6011   EXPECT_FALSE(connection_.connected());
6012   TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
6013 }
6014 
TEST_P(QuicConnectionTest,TimeoutAfterReceive)6015 TEST_P(QuicConnectionTest, TimeoutAfterReceive) {
6016   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6017   EXPECT_TRUE(connection_.connected());
6018   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6019   QuicConfig config;
6020   connection_.SetFromConfig(config);
6021 
6022   const QuicTime::Delta initial_idle_timeout =
6023       QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
6024   const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
6025   QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
6026 
6027   connection_.SendStreamDataWithString(
6028       GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6029       0, NO_FIN);
6030   connection_.SendStreamDataWithString(
6031       GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6032       3, NO_FIN);
6033 
6034   EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
6035   clock_.AdvanceTime(five_ms);
6036 
6037   // When we receive a packet, the timeout will change to 5ms +
6038   // kInitialIdleTimeoutSecs.
6039   QuicAckFrame ack = InitAckFrame(2);
6040   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
6041   ProcessAckPacket(&ack);
6042 
6043   // The original alarm will fire.  We should not time out because we had a
6044   // network event at t=5ms.  The alarm will reregister.
6045   clock_.AdvanceTime(initial_idle_timeout - five_ms);
6046   EXPECT_EQ(default_timeout, clock_.ApproximateNow());
6047   EXPECT_TRUE(connection_.connected());
6048   EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
6049   EXPECT_EQ(default_timeout + five_ms,
6050             connection_.GetTimeoutAlarm()->deadline());
6051 
6052   // This time, we should time out.
6053   EXPECT_CALL(visitor_,
6054               OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
6055   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
6056   clock_.AdvanceTime(five_ms);
6057   EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
6058   connection_.GetTimeoutAlarm()->Fire();
6059   EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
6060   EXPECT_FALSE(connection_.connected());
6061   TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
6062 }
6063 
TEST_P(QuicConnectionTest,TimeoutAfterReceiveNotSendWhenUnacked)6064 TEST_P(QuicConnectionTest, TimeoutAfterReceiveNotSendWhenUnacked) {
6065   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6066   EXPECT_TRUE(connection_.connected());
6067   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6068   QuicConfig config;
6069   connection_.SetFromConfig(config);
6070 
6071   const QuicTime::Delta initial_idle_timeout =
6072       QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
6073   connection_.SetNetworkTimeouts(
6074       QuicTime::Delta::Infinite(),
6075       initial_idle_timeout + QuicTime::Delta::FromSeconds(1));
6076   const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
6077   QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
6078 
6079   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6080   connection_.SendStreamDataWithString(
6081       GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6082       0, NO_FIN);
6083   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6084   connection_.SendStreamDataWithString(
6085       GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6086       3, NO_FIN);
6087 
6088   EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
6089 
6090   clock_.AdvanceTime(five_ms);
6091 
6092   // When we receive a packet, the timeout will change to 5ms +
6093   // kInitialIdleTimeoutSecs.
6094   QuicAckFrame ack = InitAckFrame(2);
6095   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
6096   ProcessAckPacket(&ack);
6097 
6098   // The original alarm will fire.  We should not time out because we had a
6099   // network event at t=5ms.  The alarm will reregister.
6100   clock_.AdvanceTime(initial_idle_timeout - five_ms);
6101   EXPECT_EQ(default_timeout, clock_.ApproximateNow());
6102   EXPECT_TRUE(connection_.connected());
6103   EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
6104   EXPECT_EQ(default_timeout + five_ms,
6105             connection_.GetTimeoutAlarm()->deadline());
6106 
6107   // Now, send packets while advancing the time and verify that the connection
6108   // eventually times out.
6109   EXPECT_CALL(visitor_,
6110               OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
6111   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
6112   for (int i = 0; i < 100 && connection_.connected(); ++i) {
6113     QUIC_LOG(INFO) << "sending data packet";
6114     connection_.SendStreamDataWithString(
6115         GetNthClientInitiatedStreamId(1, connection_.transport_version()),
6116         "foo", 0, NO_FIN);
6117     connection_.GetTimeoutAlarm()->Fire();
6118     clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6119   }
6120   EXPECT_FALSE(connection_.connected());
6121   EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
6122   TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
6123 }
6124 
TEST_P(QuicConnectionTest,SendScheduler)6125 TEST_P(QuicConnectionTest, SendScheduler) {
6126   // Test that if we send a packet without delay, it is not queued.
6127   QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
6128   std::unique_ptr<QuicPacket> packet =
6129       ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
6130   QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6131   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6132   connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
6133                          HAS_RETRANSMITTABLE_DATA, false, false);
6134   EXPECT_EQ(0u, connection_.NumQueuedPackets());
6135 }
6136 
TEST_P(QuicConnectionTest,FailToSendFirstPacket)6137 TEST_P(QuicConnectionTest, FailToSendFirstPacket) {
6138   // Test that the connection does not crash when it fails to send the first
6139   // packet at which point self_address_ might be uninitialized.
6140   QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
6141   EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
6142   std::unique_ptr<QuicPacket> packet =
6143       ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
6144   QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6145   writer_->SetShouldWriteFail();
6146   connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
6147                          HAS_RETRANSMITTABLE_DATA, false, false);
6148 }
6149 
TEST_P(QuicConnectionTest,SendSchedulerEAGAIN)6150 TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
6151   QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
6152   std::unique_ptr<QuicPacket> packet =
6153       ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
6154   QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6155   BlockOnNextWrite();
6156   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _))
6157       .Times(0);
6158   connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
6159                          HAS_RETRANSMITTABLE_DATA, false, false);
6160   EXPECT_EQ(1u, connection_.NumQueuedPackets());
6161 }
6162 
TEST_P(QuicConnectionTest,TestQueueLimitsOnSendStreamData)6163 TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
6164   // Queue the first packet.
6165   size_t payload_length = connection_.max_packet_length();
6166   EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(testing::Return(false));
6167   const std::string payload(payload_length, 'a');
6168   QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
6169       connection_.version().transport_version, Perspective::IS_CLIENT));
6170   EXPECT_EQ(0u, connection_
6171                     .SendStreamDataWithString(first_bidi_stream_id, payload, 0,
6172                                               NO_FIN)
6173                     .bytes_consumed);
6174   EXPECT_EQ(0u, connection_.NumQueuedPackets());
6175 }
6176 
TEST_P(QuicConnectionTest,SendingThreePackets)6177 TEST_P(QuicConnectionTest, SendingThreePackets) {
6178   // Make the payload twice the size of the packet, so 3 packets are written.
6179   size_t total_payload_length = 2 * connection_.max_packet_length();
6180   const std::string payload(total_payload_length, 'a');
6181   QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
6182       connection_.version().transport_version, Perspective::IS_CLIENT));
6183   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
6184   EXPECT_EQ(payload.size(), connection_
6185                                 .SendStreamDataWithString(first_bidi_stream_id,
6186                                                           payload, 0, NO_FIN)
6187                                 .bytes_consumed);
6188 }
6189 
TEST_P(QuicConnectionTest,LoopThroughSendingPacketsWithTruncation)6190 TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
6191   set_perspective(Perspective::IS_SERVER);
6192   // Set up a larger payload than will fit in one packet.
6193   const std::string payload(connection_.max_packet_length(), 'a');
6194   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
6195 
6196   // Now send some packets with no truncation.
6197   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6198   EXPECT_EQ(payload.size(),
6199             connection_.SendStreamDataWithString(3, payload, 0, NO_FIN)
6200                 .bytes_consumed);
6201   // Track the size of the second packet here.  The overhead will be the largest
6202   // we see in this test, due to the non-truncated connection id.
6203   size_t non_truncated_packet_size = writer_->last_packet_size();
6204 
6205   // Change to a 0 byte connection id.
6206   QuicConfig config;
6207   QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
6208   connection_.SetFromConfig(config);
6209   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6210   EXPECT_EQ(payload.size(),
6211             connection_.SendStreamDataWithString(3, payload, 1350, NO_FIN)
6212                 .bytes_consumed);
6213   // Short header packets sent from server omit connection ID already, and
6214   // stream offset size increases from 0 to 2.
6215   EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() - 2);
6216 }
6217 
TEST_P(QuicConnectionTest,SendDelayedAck)6218 TEST_P(QuicConnectionTest, SendDelayedAck) {
6219   QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6220   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6221   EXPECT_FALSE(connection_.HasPendingAcks());
6222   SetDecrypter(ENCRYPTION_ZERO_RTT,
6223                std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
6224   peer_framer_.SetEncrypter(
6225       ENCRYPTION_ZERO_RTT,
6226       std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
6227   // Process a packet from the non-crypto stream.
6228   frame1_.stream_id = 3;
6229 
6230   // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6231   // instead of ENCRYPTION_INITIAL.
6232   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6233   ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6234 
6235   // Check if delayed ack timer is running for the expected interval.
6236   EXPECT_TRUE(connection_.HasPendingAcks());
6237   EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6238   // Simulate delayed ack alarm firing.
6239   clock_.AdvanceTime(DefaultDelayedAckTime());
6240   connection_.GetAckAlarm()->Fire();
6241   // Check that ack is sent and that delayed ack alarm is reset.
6242   size_t padding_frame_count = writer_->padding_frames().size();
6243   EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6244   EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6245   EXPECT_FALSE(writer_->ack_frames().empty());
6246   EXPECT_FALSE(connection_.HasPendingAcks());
6247 }
6248 
TEST_P(QuicConnectionTest,SendDelayedAckDecimation)6249 TEST_P(QuicConnectionTest, SendDelayedAckDecimation) {
6250   EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6251 
6252   const size_t kMinRttMs = 40;
6253   RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6254   rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6255                        QuicTime::Delta::Zero(), QuicTime::Zero());
6256   // The ack time should be based on min_rtt/4, since it's less than the
6257   // default delayed ack time.
6258   QuicTime ack_time = clock_.ApproximateNow() +
6259                       QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6260   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6261   EXPECT_FALSE(connection_.HasPendingAcks());
6262   SetDecrypter(ENCRYPTION_ZERO_RTT,
6263                std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
6264   peer_framer_.SetEncrypter(
6265       ENCRYPTION_ZERO_RTT,
6266       std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
6267   // Process a packet from the non-crypto stream.
6268   frame1_.stream_id = 3;
6269 
6270   // Process all the initial packets in order so there aren't missing packets.
6271   uint64_t kFirstDecimatedPacket = 101;
6272   for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6273     EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6274     ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6275   }
6276   EXPECT_FALSE(connection_.HasPendingAcks());
6277   // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6278   // instead of ENCRYPTION_INITIAL.
6279   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6280   ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6281                            ENCRYPTION_ZERO_RTT);
6282 
6283   // Check if delayed ack timer is running for the expected interval.
6284   EXPECT_TRUE(connection_.HasPendingAcks());
6285   EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6286 
6287   // The 10th received packet causes an ack to be sent.
6288   for (int i = 0; i < 9; ++i) {
6289     EXPECT_TRUE(connection_.HasPendingAcks());
6290     EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6291     ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6292                              ENCRYPTION_ZERO_RTT);
6293   }
6294   // Check that ack is sent and that delayed ack alarm is reset.
6295   size_t padding_frame_count = writer_->padding_frames().size();
6296   EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6297   EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6298   EXPECT_FALSE(writer_->ack_frames().empty());
6299   EXPECT_FALSE(connection_.HasPendingAcks());
6300 }
6301 
TEST_P(QuicConnectionTest,SendDelayedAckDecimationUnlimitedAggregation)6302 TEST_P(QuicConnectionTest, SendDelayedAckDecimationUnlimitedAggregation) {
6303   EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6304   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6305   QuicConfig config;
6306   QuicTagVector connection_options;
6307   // No limit on the number of packets received before sending an ack.
6308   connection_options.push_back(kAKDU);
6309   config.SetConnectionOptionsToSend(connection_options);
6310   connection_.SetFromConfig(config);
6311 
6312   const size_t kMinRttMs = 40;
6313   RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6314   rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6315                        QuicTime::Delta::Zero(), QuicTime::Zero());
6316   // The ack time should be based on min_rtt/4, since it's less than the
6317   // default delayed ack time.
6318   QuicTime ack_time = clock_.ApproximateNow() +
6319                       QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6320   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6321   EXPECT_FALSE(connection_.HasPendingAcks());
6322   SetDecrypter(ENCRYPTION_ZERO_RTT,
6323                std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
6324   peer_framer_.SetEncrypter(
6325       ENCRYPTION_ZERO_RTT,
6326       std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
6327   // Process a packet from the non-crypto stream.
6328   frame1_.stream_id = 3;
6329 
6330   // Process all the initial packets in order so there aren't missing packets.
6331   uint64_t kFirstDecimatedPacket = 101;
6332   for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6333     EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6334     ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6335   }
6336   EXPECT_FALSE(connection_.HasPendingAcks());
6337   // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6338   // instead of ENCRYPTION_INITIAL.
6339   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6340   ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6341                            ENCRYPTION_ZERO_RTT);
6342 
6343   // Check if delayed ack timer is running for the expected interval.
6344   EXPECT_TRUE(connection_.HasPendingAcks());
6345   EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6346 
6347   // 18 packets will not cause an ack to be sent.  19 will because when
6348   // stop waiting frames are in use, we ack every 20 packets no matter what.
6349   for (int i = 0; i < 18; ++i) {
6350     EXPECT_TRUE(connection_.HasPendingAcks());
6351     EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6352     ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6353                              ENCRYPTION_ZERO_RTT);
6354   }
6355   // The delayed ack timer should still be set to the expected deadline.
6356   EXPECT_TRUE(connection_.HasPendingAcks());
6357   EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6358 }
6359 
TEST_P(QuicConnectionTest,SendDelayedAckDecimationEighthRtt)6360 TEST_P(QuicConnectionTest, SendDelayedAckDecimationEighthRtt) {
6361   EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6362   QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6363 
6364   const size_t kMinRttMs = 40;
6365   RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6366   rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6367                        QuicTime::Delta::Zero(), QuicTime::Zero());
6368   // The ack time should be based on min_rtt/8, since it's less than the
6369   // default delayed ack time.
6370   QuicTime ack_time = clock_.ApproximateNow() +
6371                       QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6372   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6373   EXPECT_FALSE(connection_.HasPendingAcks());
6374   SetDecrypter(ENCRYPTION_ZERO_RTT,
6375                std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
6376   peer_framer_.SetEncrypter(
6377       ENCRYPTION_ZERO_RTT,
6378       std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
6379   // Process a packet from the non-crypto stream.
6380   frame1_.stream_id = 3;
6381 
6382   // Process all the initial packets in order so there aren't missing packets.
6383   uint64_t kFirstDecimatedPacket = 101;
6384   for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6385     EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6386     ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6387   }
6388   EXPECT_FALSE(connection_.HasPendingAcks());
6389   // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6390   // instead of ENCRYPTION_INITIAL.
6391   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6392   ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6393                            ENCRYPTION_ZERO_RTT);
6394 
6395   // Check if delayed ack timer is running for the expected interval.
6396   EXPECT_TRUE(connection_.HasPendingAcks());
6397   EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6398 
6399   // The 10th received packet causes an ack to be sent.
6400   for (int i = 0; i < 9; ++i) {
6401     EXPECT_TRUE(connection_.HasPendingAcks());
6402     EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6403     ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6404                              ENCRYPTION_ZERO_RTT);
6405   }
6406   // Check that ack is sent and that delayed ack alarm is reset.
6407   size_t padding_frame_count = writer_->padding_frames().size();
6408   EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6409   EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6410   EXPECT_FALSE(writer_->ack_frames().empty());
6411   EXPECT_FALSE(connection_.HasPendingAcks());
6412 }
6413 
TEST_P(QuicConnectionTest,SendDelayedAckOnHandshakeConfirmed)6414 TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
6415   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6416   ProcessPacket(1);
6417   // Check that ack is sent and that delayed ack alarm is set.
6418   EXPECT_TRUE(connection_.HasPendingAcks());
6419   QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6420   EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6421 
6422   // Completing the handshake as the server does nothing.
6423   QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
6424   connection_.OnHandshakeComplete();
6425   EXPECT_TRUE(connection_.HasPendingAcks());
6426   EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6427 
6428   // Complete the handshake as the client decreases the delayed ack time to 0ms.
6429   QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
6430   connection_.OnHandshakeComplete();
6431   EXPECT_TRUE(connection_.HasPendingAcks());
6432   if (connection_.SupportsMultiplePacketNumberSpaces()) {
6433     EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(),
6434               connection_.GetAckAlarm()->deadline());
6435   } else {
6436     EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
6437   }
6438 }
6439 
TEST_P(QuicConnectionTest,SendDelayedAckOnSecondPacket)6440 TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
6441   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6442   ProcessPacket(1);
6443   ProcessPacket(2);
6444   // Check that ack is sent and that delayed ack alarm is reset.
6445   size_t padding_frame_count = writer_->padding_frames().size();
6446   EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6447   EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6448   EXPECT_FALSE(writer_->ack_frames().empty());
6449   EXPECT_FALSE(connection_.HasPendingAcks());
6450 }
6451 
TEST_P(QuicConnectionTest,NoAckOnOldNacks)6452 TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
6453   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6454   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6455   ProcessPacket(2);
6456   size_t frames_per_ack = 1;
6457 
6458   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6459   ProcessPacket(3);
6460   size_t padding_frame_count = writer_->padding_frames().size();
6461   EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
6462   EXPECT_FALSE(writer_->ack_frames().empty());
6463   writer_->Reset();
6464 
6465   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6466   ProcessPacket(4);
6467   EXPECT_EQ(0u, writer_->frame_count());
6468 
6469   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6470   ProcessPacket(5);
6471   padding_frame_count = writer_->padding_frames().size();
6472   EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
6473   EXPECT_FALSE(writer_->ack_frames().empty());
6474   writer_->Reset();
6475 
6476   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6477   // Now only set the timer on the 6th packet, instead of sending another ack.
6478   ProcessPacket(6);
6479   padding_frame_count = writer_->padding_frames().size();
6480   EXPECT_EQ(padding_frame_count, writer_->frame_count());
6481   EXPECT_TRUE(connection_.HasPendingAcks());
6482 }
6483 
TEST_P(QuicConnectionTest,SendDelayedAckOnOutgoingPacket)6484 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
6485   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6486   EXPECT_CALL(visitor_, OnStreamFrame(_));
6487   peer_framer_.SetEncrypter(
6488       ENCRYPTION_FORWARD_SECURE,
6489       std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
6490   SetDecrypter(
6491       ENCRYPTION_FORWARD_SECURE,
6492       std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
6493   ProcessDataPacket(1);
6494   connection_.SendStreamDataWithString(
6495       GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6496       0, NO_FIN);
6497   // Check that ack is bundled with outgoing data and that delayed ack
6498   // alarm is reset.
6499   EXPECT_EQ(2u, writer_->frame_count());
6500   EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6501   EXPECT_FALSE(writer_->ack_frames().empty());
6502   EXPECT_FALSE(connection_.HasPendingAcks());
6503 }
6504 
TEST_P(QuicConnectionTest,SendDelayedAckOnOutgoingCryptoPacket)6505 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
6506   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6507   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6508     EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6509   } else {
6510     EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6511   }
6512   ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
6513   connection_.SendCryptoDataWithString("foo", 0);
6514   // Check that ack is bundled with outgoing crypto data.
6515   EXPECT_EQ(3u, writer_->frame_count());
6516   EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6517   EXPECT_FALSE(connection_.HasPendingAcks());
6518 }
6519 
TEST_P(QuicConnectionTest,BlockAndBufferOnFirstCHLOPacketOfTwo)6520 TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
6521   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6522   ProcessPacket(1);
6523   BlockOnNextWrite();
6524   writer_->set_is_write_blocked_data_buffered(true);
6525   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6526     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6527   } else {
6528     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6529   }
6530   connection_.SendCryptoDataWithString("foo", 0);
6531   EXPECT_TRUE(writer_->IsWriteBlocked());
6532   EXPECT_FALSE(connection_.HasQueuedData());
6533   connection_.SendCryptoDataWithString("bar", 3);
6534   EXPECT_TRUE(writer_->IsWriteBlocked());
6535   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6536     // CRYPTO frames are not flushed when writer is blocked.
6537     EXPECT_FALSE(connection_.HasQueuedData());
6538   } else {
6539     EXPECT_TRUE(connection_.HasQueuedData());
6540   }
6541 }
6542 
TEST_P(QuicConnectionTest,BundleAckForSecondCHLO)6543 TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
6544   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6545   EXPECT_FALSE(connection_.HasPendingAcks());
6546   EXPECT_CALL(visitor_, OnCanWrite())
6547       .WillOnce(IgnoreResult(InvokeWithoutArgs(
6548           &connection_, &TestConnection::SendCryptoStreamData)));
6549   // Process a packet from the crypto stream, which is frame1_'s default.
6550   // Receiving the CHLO as packet 2 first will cause the connection to
6551   // immediately send an ack, due to the packet gap.
6552   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6553     EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6554   } else {
6555     EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6556   }
6557   ForceWillingAndAbleToWriteOnceForDeferSending();
6558   ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
6559   // Check that ack is sent and that delayed ack alarm is reset.
6560   EXPECT_EQ(3u, writer_->frame_count());
6561   EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6562   if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6563     EXPECT_EQ(1u, writer_->stream_frames().size());
6564   } else {
6565     EXPECT_EQ(1u, writer_->crypto_frames().size());
6566   }
6567   EXPECT_EQ(1u, writer_->padding_frames().size());
6568   ASSERT_FALSE(writer_->ack_frames().empty());
6569   EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
6570   EXPECT_FALSE(connection_.HasPendingAcks());
6571 }
6572 
TEST_P(QuicConnectionTest,BundleAckForSecondCHLOTwoPacketReject)6573 TEST_P(QuicConnectionTest, BundleAckForSecondCHLOTwoPacketReject) {
6574   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6575   EXPECT_FALSE(connection_.HasPendingAcks());
6576 
6577   // Process two packets from the crypto stream, which is frame1_'s default,
6578   // simulating a 2 packet reject.
6579   {
6580     if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6581       EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6582     } else {
6583       EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6584     }
6585     ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
6586     // Send the new CHLO when the REJ is processed.
6587     if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6588       EXPECT_CALL(visitor_, OnCryptoFrame(_))
6589           .WillOnce(IgnoreResult(InvokeWithoutArgs(
6590               &connection_, &TestConnection::SendCryptoStreamData)));
6591     } else {
6592       EXPECT_CALL(visitor_, OnStreamFrame(_))
6593           .WillOnce(IgnoreResult(InvokeWithoutArgs(
6594               &connection_, &TestConnection::SendCryptoStreamData)));
6595     }
6596     ForceWillingAndAbleToWriteOnceForDeferSending();
6597     ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
6598   }
6599   // Check that ack is sent and that delayed ack alarm is reset.
6600   EXPECT_EQ(3u, writer_->frame_count());
6601   EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6602   if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6603     EXPECT_EQ(1u, writer_->stream_frames().size());
6604   } else {
6605     EXPECT_EQ(1u, writer_->crypto_frames().size());
6606   }
6607   EXPECT_EQ(1u, writer_->padding_frames().size());
6608   ASSERT_FALSE(writer_->ack_frames().empty());
6609   EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
6610   EXPECT_FALSE(connection_.HasPendingAcks());
6611 }
6612 
TEST_P(QuicConnectionTest,BundleAckWithDataOnIncomingAck)6613 TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
6614   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6615   connection_.SendStreamDataWithString(
6616       GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6617       0, NO_FIN);
6618   connection_.SendStreamDataWithString(
6619       GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6620       3, NO_FIN);
6621   // Ack the second packet, which will retransmit the first packet.
6622   QuicAckFrame ack = ConstructAckFrame(2, 1);
6623   LostPacketVector lost_packets;
6624   lost_packets.push_back(
6625       LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
6626   EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
6627       .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
6628                       Return(LossDetectionInterface::DetectionStats())));
6629   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
6630   ProcessAckPacket(&ack);
6631   size_t padding_frame_count = writer_->padding_frames().size();
6632   EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6633   EXPECT_EQ(1u, writer_->stream_frames().size());
6634   writer_->Reset();
6635 
6636   // Now ack the retransmission, which will both raise the high water mark
6637   // and see if there is more data to send.
6638   ack = ConstructAckFrame(3, 1);
6639   EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
6640   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
6641   ProcessAckPacket(&ack);
6642 
6643   // Check that no packet is sent and the ack alarm isn't set.
6644   EXPECT_EQ(0u, writer_->frame_count());
6645   EXPECT_FALSE(connection_.HasPendingAcks());
6646   writer_->Reset();
6647 
6648   // Send the same ack, but send both data and an ack together.
6649   ack = ConstructAckFrame(3, 1);
6650   EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
6651   EXPECT_CALL(visitor_, OnCanWrite())
6652       .WillOnce(IgnoreResult(InvokeWithoutArgs(
6653           &connection_, &TestConnection::EnsureWritableAndSendStreamData5)));
6654   ForceWillingAndAbleToWriteOnceForDeferSending();
6655   ProcessAckPacket(&ack);
6656 
6657   // Check that ack is bundled with outgoing data and the delayed ack
6658   // alarm is reset.
6659   // Do not ACK acks.
6660   EXPECT_EQ(1u, writer_->frame_count());
6661   EXPECT_TRUE(writer_->ack_frames().empty());
6662   EXPECT_EQ(1u, writer_->stream_frames().size());
6663   EXPECT_FALSE(connection_.HasPendingAcks());
6664 }
6665 
TEST_P(QuicConnectionTest,NoAckSentForClose)6666 TEST_P(QuicConnectionTest, NoAckSentForClose) {
6667   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6668   ProcessPacket(1);
6669   EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6670       .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6671   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6672   ProcessClosePacket(2);
6673   EXPECT_EQ(1, connection_close_frame_count_);
6674   EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6675               IsError(QUIC_PEER_GOING_AWAY));
6676 }
6677 
TEST_P(QuicConnectionTest,SendWhenDisconnected)6678 TEST_P(QuicConnectionTest, SendWhenDisconnected) {
6679   EXPECT_TRUE(connection_.connected());
6680   EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6681       .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6682   connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
6683                               ConnectionCloseBehavior::SILENT_CLOSE);
6684   EXPECT_FALSE(connection_.connected());
6685   EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
6686   EXPECT_EQ(DISCARD, connection_.GetSerializedPacketFate(
6687                          /*is_mtu_discovery=*/false, ENCRYPTION_INITIAL));
6688 }
6689 
TEST_P(QuicConnectionTest,SendConnectivityProbingWhenDisconnected)6690 TEST_P(QuicConnectionTest, SendConnectivityProbingWhenDisconnected) {
6691   // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
6692   if (!IsDefaultTestConfiguration()) {
6693     return;
6694   }
6695 
6696   EXPECT_TRUE(connection_.connected());
6697   EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6698       .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6699   connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
6700                               ConnectionCloseBehavior::SILENT_CLOSE);
6701   EXPECT_FALSE(connection_.connected());
6702   EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
6703 
6704   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6705       .Times(0);
6706 
6707   EXPECT_QUIC_BUG(connection_.SendConnectivityProbingPacket(
6708                       writer_.get(), connection_.peer_address()),
6709                   "Not sending connectivity probing packet as connection is "
6710                   "disconnected.");
6711   EXPECT_EQ(1, connection_close_frame_count_);
6712   EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6713               IsError(QUIC_PEER_GOING_AWAY));
6714 }
6715 
TEST_P(QuicConnectionTest,WriteBlockedAfterClientSendsConnectivityProbe)6716 TEST_P(QuicConnectionTest, WriteBlockedAfterClientSendsConnectivityProbe) {
6717   PathProbeTestInit(Perspective::IS_CLIENT);
6718   TestPacketWriter probing_writer(version(), &clock_, Perspective::IS_CLIENT);
6719   // Block next write so that sending connectivity probe will encounter a
6720   // blocked write when send a connectivity probe to the peer.
6721   probing_writer.BlockOnNextWrite();
6722   // Connection will not be marked as write blocked as connectivity probe only
6723   // affects the probing_writer which is not the default.
6724   EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
6725 
6726   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6727       .Times(1);
6728   connection_.SendConnectivityProbingPacket(&probing_writer,
6729                                             connection_.peer_address());
6730 }
6731 
TEST_P(QuicConnectionTest,WriterBlockedAfterServerSendsConnectivityProbe)6732 TEST_P(QuicConnectionTest, WriterBlockedAfterServerSendsConnectivityProbe) {
6733   PathProbeTestInit(Perspective::IS_SERVER);
6734   if (version().SupportsAntiAmplificationLimit()) {
6735     QuicConnectionPeer::SetAddressValidated(&connection_);
6736   }
6737 
6738   // Block next write so that sending connectivity probe will encounter a
6739   // blocked write when send a connectivity probe to the peer.
6740   writer_->BlockOnNextWrite();
6741   // Connection will be marked as write blocked as server uses the default
6742   // writer to send connectivity probes.
6743   EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
6744 
6745   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6746       .Times(1);
6747   if (VersionHasIetfQuicFrames(GetParam().version.transport_version)) {
6748     QuicPathFrameBuffer payload{
6749         {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
6750     QuicConnection::ScopedPacketFlusher flusher(&connection_);
6751     connection_.SendPathChallenge(
6752         payload, connection_.self_address(), connection_.peer_address(),
6753         connection_.effective_peer_address(), writer_.get());
6754   } else {
6755     connection_.SendConnectivityProbingPacket(writer_.get(),
6756                                               connection_.peer_address());
6757   }
6758 }
6759 
TEST_P(QuicConnectionTest,WriterErrorWhenClientSendsConnectivityProbe)6760 TEST_P(QuicConnectionTest, WriterErrorWhenClientSendsConnectivityProbe) {
6761   PathProbeTestInit(Perspective::IS_CLIENT);
6762   TestPacketWriter probing_writer(version(), &clock_, Perspective::IS_CLIENT);
6763   probing_writer.SetShouldWriteFail();
6764 
6765   // Connection should not be closed if a connectivity probe is failed to be
6766   // sent.
6767   EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
6768 
6769   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6770       .Times(0);
6771   connection_.SendConnectivityProbingPacket(&probing_writer,
6772                                             connection_.peer_address());
6773 }
6774 
TEST_P(QuicConnectionTest,WriterErrorWhenServerSendsConnectivityProbe)6775 TEST_P(QuicConnectionTest, WriterErrorWhenServerSendsConnectivityProbe) {
6776   PathProbeTestInit(Perspective::IS_SERVER);
6777 
6778   writer_->SetShouldWriteFail();
6779   // Connection should not be closed if a connectivity probe is failed to be
6780   // sent.
6781   EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
6782 
6783   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6784       .Times(0);
6785   connection_.SendConnectivityProbingPacket(writer_.get(),
6786                                             connection_.peer_address());
6787 }
6788 
TEST_P(QuicConnectionTest,IetfStatelessReset)6789 TEST_P(QuicConnectionTest, IetfStatelessReset) {
6790   QuicConfig config;
6791   QuicConfigPeer::SetReceivedStatelessResetToken(&config,
6792                                                  kTestStatelessResetToken);
6793   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6794   connection_.SetFromConfig(config);
6795   std::unique_ptr<QuicEncryptedPacket> packet(
6796       QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
6797                                                 /*received_packet_length=*/100,
6798                                                 kTestStatelessResetToken));
6799   std::unique_ptr<QuicReceivedPacket> received(
6800       ConstructReceivedPacket(*packet, QuicTime::Zero()));
6801   EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6802       .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6803   connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6804   EXPECT_EQ(1, connection_close_frame_count_);
6805   EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6806               IsError(QUIC_PUBLIC_RESET));
6807 }
6808 
TEST_P(QuicConnectionTest,GoAway)6809 TEST_P(QuicConnectionTest, GoAway) {
6810   if (VersionHasIetfQuicFrames(GetParam().version.transport_version)) {
6811     // GoAway is not available in version 99.
6812     return;
6813   }
6814 
6815   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6816 
6817   QuicGoAwayFrame* goaway = new QuicGoAwayFrame();
6818   goaway->last_good_stream_id = 1;
6819   goaway->error_code = QUIC_PEER_GOING_AWAY;
6820   goaway->reason_phrase = "Going away.";
6821   EXPECT_CALL(visitor_, OnGoAway(_));
6822   ProcessGoAwayPacket(goaway);
6823 }
6824 
TEST_P(QuicConnectionTest,WindowUpdate)6825 TEST_P(QuicConnectionTest, WindowUpdate) {
6826   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6827 
6828   QuicWindowUpdateFrame window_update;
6829   window_update.stream_id = 3;
6830   window_update.max_data = 1234;
6831   EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
6832   ProcessFramePacket(QuicFrame(window_update));
6833 }
6834 
TEST_P(QuicConnectionTest,Blocked)6835 TEST_P(QuicConnectionTest, Blocked) {
6836   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6837 
6838   QuicBlockedFrame blocked;
6839   blocked.stream_id = 3;
6840   EXPECT_CALL(visitor_, OnBlockedFrame(_));
6841   ProcessFramePacket(QuicFrame(blocked));
6842   EXPECT_EQ(1u, connection_.GetStats().blocked_frames_received);
6843   EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
6844 }
6845 
TEST_P(QuicConnectionTest,ZeroBytePacket)6846 TEST_P(QuicConnectionTest, ZeroBytePacket) {
6847   // Don't close the connection for zero byte packets.
6848   EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
6849   QuicReceivedPacket encrypted(nullptr, 0, QuicTime::Zero());
6850   connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, encrypted);
6851 }
6852 
TEST_P(QuicConnectionTest,ClientHandlesVersionNegotiation)6853 TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
6854   // All supported versions except the one the connection supports.
6855   ParsedQuicVersionVector versions;
6856   for (auto version : AllSupportedVersions()) {
6857     if (version != connection_.version()) {
6858       versions.push_back(version);
6859     }
6860   }
6861 
6862   // Send a version negotiation packet.
6863   std::unique_ptr<QuicEncryptedPacket> encrypted(
6864       QuicFramer::BuildVersionNegotiationPacket(
6865           connection_id_, EmptyQuicConnectionId(), /*ietf_quic=*/true,
6866           connection_.version().HasLengthPrefixedConnectionIds(), versions));
6867   std::unique_ptr<QuicReceivedPacket> received(
6868       ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
6869   EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6870       .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6871   // Verify no connection close packet gets sent.
6872   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6873   connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6874   EXPECT_FALSE(connection_.connected());
6875   EXPECT_EQ(1, connection_close_frame_count_);
6876   EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6877               IsError(QUIC_INVALID_VERSION));
6878 }
6879 
TEST_P(QuicConnectionTest,ClientHandlesVersionNegotiationWithConnectionClose)6880 TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiationWithConnectionClose) {
6881   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6882   QuicConfig config;
6883   QuicTagVector connection_options;
6884   connection_options.push_back(kINVC);
6885   config.SetClientConnectionOptions(connection_options);
6886   connection_.SetFromConfig(config);
6887 
6888   // All supported versions except the one the connection supports.
6889   ParsedQuicVersionVector versions;
6890   for (auto version : AllSupportedVersions()) {
6891     if (version != connection_.version()) {
6892       versions.push_back(version);
6893     }
6894   }
6895 
6896   // Send a version negotiation packet.
6897   std::unique_ptr<QuicEncryptedPacket> encrypted(
6898       QuicFramer::BuildVersionNegotiationPacket(
6899           connection_id_, EmptyQuicConnectionId(), /*ietf_quic=*/true,
6900           connection_.version().HasLengthPrefixedConnectionIds(), versions));
6901   std::unique_ptr<QuicReceivedPacket> received(
6902       ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
6903   EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6904       .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6905   // Verify connection close packet gets sent.
6906   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1u));
6907   connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6908   EXPECT_FALSE(connection_.connected());
6909   EXPECT_EQ(1, connection_close_frame_count_);
6910   EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6911               IsError(QUIC_INVALID_VERSION));
6912 }
6913 
TEST_P(QuicConnectionTest,BadVersionNegotiation)6914 TEST_P(QuicConnectionTest, BadVersionNegotiation) {
6915   // Send a version negotiation packet with the version the client started with.
6916   // It should be rejected.
6917   EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6918       .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6919   std::unique_ptr<QuicEncryptedPacket> encrypted(
6920       QuicFramer::BuildVersionNegotiationPacket(
6921           connection_id_, EmptyQuicConnectionId(), /*ietf_quic=*/true,
6922           connection_.version().HasLengthPrefixedConnectionIds(),
6923           AllSupportedVersions()));
6924   std::unique_ptr<QuicReceivedPacket> received(
6925       ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
6926   connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6927   EXPECT_EQ(1, connection_close_frame_count_);
6928   EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6929               IsError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET));
6930 }
6931 
TEST_P(QuicConnectionTest,ProcessFramesIfPacketClosedConnection)6932 TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
6933   // Construct a packet with stream frame and connection close frame.
6934   QuicPacketHeader header;
6935   if (peer_framer_.perspective() == Perspective::IS_SERVER) {
6936     header.source_connection_id = connection_id_;
6937     header.destination_connection_id_included = CONNECTION_ID_ABSENT;
6938   } else {
6939     header.destination_connection_id = connection_id_;
6940     header.destination_connection_id_included = CONNECTION_ID_ABSENT;
6941   }
6942   header.packet_number = QuicPacketNumber(1);
6943   header.version_flag = false;
6944 
6945   QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
6946   // This QuicConnectionCloseFrame will default to being for a Google QUIC
6947   // close. If doing IETF QUIC then set fields appropriately for CC/T or CC/A,
6948   // depending on the mapping.
6949   QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
6950                                 kQuicErrorCode, NO_IETF_QUIC_ERROR, "",
6951                                 /*transport_close_frame_type=*/0);
6952   QuicFrames frames;
6953   frames.push_back(QuicFrame(frame1_));
6954   frames.push_back(QuicFrame(&qccf));
6955   std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
6956   EXPECT_TRUE(nullptr != packet);
6957   char buffer[kMaxOutgoingPacketSize];
6958   size_t encrypted_length = peer_framer_.EncryptPayload(
6959       ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
6960       kMaxOutgoingPacketSize);
6961 
6962   EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6963       .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6964   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6965   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6966 
6967   connection_.ProcessUdpPacket(
6968       kSelfAddress, kPeerAddress,
6969       QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
6970   EXPECT_EQ(1, connection_close_frame_count_);
6971   EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6972               IsError(QUIC_PEER_GOING_AWAY));
6973 }
6974 
TEST_P(QuicConnectionTest,SelectMutualVersion)6975 TEST_P(QuicConnectionTest, SelectMutualVersion) {
6976   connection_.SetSupportedVersions(AllSupportedVersions());
6977   // Set the connection to speak the lowest quic version.
6978   connection_.set_version(QuicVersionMin());
6979   EXPECT_EQ(QuicVersionMin(), connection_.version());
6980 
6981   // Pass in available versions which includes a higher mutually supported
6982   // version.  The higher mutually supported version should be selected.
6983   ParsedQuicVersionVector supported_versions = AllSupportedVersions();
6984   EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
6985   EXPECT_EQ(QuicVersionMax(), connection_.version());
6986 
6987   // Expect that the lowest version is selected.
6988   // Ensure the lowest supported version is less than the max, unless they're
6989   // the same.
6990   ParsedQuicVersionVector lowest_version_vector;
6991   lowest_version_vector.push_back(QuicVersionMin());
6992   EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
6993   EXPECT_EQ(QuicVersionMin(), connection_.version());
6994 
6995   // Shouldn't be able to find a mutually supported version.
6996   ParsedQuicVersionVector unsupported_version;
6997   unsupported_version.push_back(UnsupportedQuicVersion());
6998   EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
6999 }
7000 
TEST_P(QuicConnectionTest,ConnectionCloseWhenWritable)7001 TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
7002   EXPECT_FALSE(writer_->IsWriteBlocked());
7003 
7004   // Send a packet.
7005   connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7006   EXPECT_EQ(0u, connection_.NumQueuedPackets());
7007   EXPECT_EQ(1u, writer_->packets_write_attempts());
7008 
7009   TriggerConnectionClose();
7010   EXPECT_LE(2u, writer_->packets_write_attempts());
7011 }
7012 
TEST_P(QuicConnectionTest,ConnectionCloseGettingWriteBlocked)7013 TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
7014   BlockOnNextWrite();
7015   TriggerConnectionClose();
7016   EXPECT_EQ(1u, writer_->packets_write_attempts());
7017   EXPECT_TRUE(writer_->IsWriteBlocked());
7018 }
7019 
TEST_P(QuicConnectionTest,ConnectionCloseWhenWriteBlocked)7020 TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
7021   BlockOnNextWrite();
7022   connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7023   EXPECT_EQ(1u, connection_.NumQueuedPackets());
7024   EXPECT_EQ(1u, writer_->packets_write_attempts());
7025   EXPECT_TRUE(writer_->IsWriteBlocked());
7026   TriggerConnectionClose();
7027   EXPECT_EQ(1u, writer_->packets_write_attempts());
7028 }
7029 
TEST_P(QuicConnectionTest,OnPacketSentDebugVisitor)7030 TEST_P(QuicConnectionTest, OnPacketSentDebugVisitor) {
7031   PathProbeTestInit(Perspective::IS_CLIENT);
7032   MockQuicConnectionDebugVisitor debug_visitor;
7033   connection_.set_debug_visitor(&debug_visitor);
7034 
7035   EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(1);
7036   connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7037 
7038   EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(1);
7039   connection_.SendConnectivityProbingPacket(writer_.get(),
7040                                             connection_.peer_address());
7041 }
7042 
TEST_P(QuicConnectionTest,OnPacketHeaderDebugVisitor)7043 TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
7044   QuicPacketHeader header;
7045   header.packet_number = QuicPacketNumber(1);
7046   header.form = IETF_QUIC_LONG_HEADER_PACKET;
7047 
7048   MockQuicConnectionDebugVisitor debug_visitor;
7049   connection_.set_debug_visitor(&debug_visitor);
7050   EXPECT_CALL(debug_visitor, OnPacketHeader(Ref(header), _, _)).Times(1);
7051   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(1);
7052   EXPECT_CALL(debug_visitor, OnSuccessfulVersionNegotiation(_)).Times(1);
7053   connection_.OnPacketHeader(header);
7054 }
7055 
TEST_P(QuicConnectionTest,Pacing)7056 TEST_P(QuicConnectionTest, Pacing) {
7057   TestConnection server(connection_id_, kPeerAddress, kSelfAddress,
7058                         helper_.get(), alarm_factory_.get(), writer_.get(),
7059                         Perspective::IS_SERVER, version(),
7060                         connection_id_generator_);
7061   TestConnection client(connection_id_, kSelfAddress, kPeerAddress,
7062                         helper_.get(), alarm_factory_.get(), writer_.get(),
7063                         Perspective::IS_CLIENT, version(),
7064                         connection_id_generator_);
7065   EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7066       static_cast<const QuicSentPacketManager*>(
7067           &client.sent_packet_manager())));
7068   EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7069       static_cast<const QuicSentPacketManager*>(
7070           &server.sent_packet_manager())));
7071 }
7072 
TEST_P(QuicConnectionTest,WindowUpdateInstigateAcks)7073 TEST_P(QuicConnectionTest, WindowUpdateInstigateAcks) {
7074   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7075 
7076   // Send a WINDOW_UPDATE frame.
7077   QuicWindowUpdateFrame window_update;
7078   window_update.stream_id = 3;
7079   window_update.max_data = 1234;
7080   EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
7081   ProcessFramePacket(QuicFrame(window_update));
7082 
7083   // Ensure that this has caused the ACK alarm to be set.
7084   EXPECT_TRUE(connection_.HasPendingAcks());
7085 }
7086 
TEST_P(QuicConnectionTest,BlockedFrameInstigateAcks)7087 TEST_P(QuicConnectionTest, BlockedFrameInstigateAcks) {
7088   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7089 
7090   // Send a BLOCKED frame.
7091   QuicBlockedFrame blocked;
7092   blocked.stream_id = 3;
7093   EXPECT_CALL(visitor_, OnBlockedFrame(_));
7094   ProcessFramePacket(QuicFrame(blocked));
7095 
7096   // Ensure that this has caused the ACK alarm to be set.
7097   EXPECT_TRUE(connection_.HasPendingAcks());
7098 }
7099 
TEST_P(QuicConnectionTest,ReevaluateTimeUntilSendOnAck)7100 TEST_P(QuicConnectionTest, ReevaluateTimeUntilSendOnAck) {
7101   // Enable pacing.
7102   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7103   QuicConfig config;
7104   connection_.SetFromConfig(config);
7105 
7106   // Send two packets.  One packet is not sufficient because if it gets acked,
7107   // there will be no packets in flight after that and the pacer will always
7108   // allow the next packet in that situation.
7109   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7110   EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7111   connection_.SendStreamDataWithString(
7112       GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7113       0, NO_FIN);
7114   connection_.SendStreamDataWithString(
7115       GetNthClientInitiatedStreamId(1, connection_.transport_version()), "bar",
7116       3, NO_FIN);
7117   connection_.OnCanWrite();
7118 
7119   // Schedule the next packet for a few milliseconds in future.
7120   QuicSentPacketManagerPeer::DisablePacerBursts(manager_);
7121   QuicTime scheduled_pacing_time =
7122       clock_.Now() + QuicTime::Delta::FromMilliseconds(5);
7123   QuicSentPacketManagerPeer::SetNextPacedPacketTime(manager_,
7124                                                     scheduled_pacing_time);
7125 
7126   // Send a packet and have it be blocked by congestion control.
7127   EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false));
7128   connection_.SendStreamDataWithString(
7129       GetNthClientInitiatedStreamId(1, connection_.transport_version()), "baz",
7130       6, NO_FIN);
7131   EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
7132 
7133   // Process an ack and the send alarm will be set to the new 5ms delay.
7134   QuicAckFrame ack = InitAckFrame(1);
7135   EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7136   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
7137   EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7138   ProcessAckPacket(&ack);
7139   size_t padding_frame_count = writer_->padding_frames().size();
7140   EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
7141   EXPECT_EQ(1u, writer_->stream_frames().size());
7142   EXPECT_TRUE(connection_.GetSendAlarm()->IsSet());
7143   EXPECT_EQ(scheduled_pacing_time, connection_.GetSendAlarm()->deadline());
7144   writer_->Reset();
7145 }
7146 
TEST_P(QuicConnectionTest,SendAcksImmediately)7147 TEST_P(QuicConnectionTest, SendAcksImmediately) {
7148   if (connection_.SupportsMultiplePacketNumberSpaces()) {
7149     return;
7150   }
7151   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7152   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7153   ProcessDataPacket(1);
7154   CongestionBlockWrites();
7155   SendAckPacketToPeer();
7156 }
7157 
TEST_P(QuicConnectionTest,SendPingImmediately)7158 TEST_P(QuicConnectionTest, SendPingImmediately) {
7159   MockQuicConnectionDebugVisitor debug_visitor;
7160   connection_.set_debug_visitor(&debug_visitor);
7161 
7162   CongestionBlockWrites();
7163   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
7164   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7165   EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(1);
7166   EXPECT_CALL(debug_visitor, OnPingSent()).Times(1);
7167   connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7168   EXPECT_FALSE(connection_.HasQueuedData());
7169 }
7170 
TEST_P(QuicConnectionTest,SendBlockedImmediately)7171 TEST_P(QuicConnectionTest, SendBlockedImmediately) {
7172   MockQuicConnectionDebugVisitor debug_visitor;
7173   connection_.set_debug_visitor(&debug_visitor);
7174 
7175   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
7176   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7177   EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(1);
7178   EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7179   connection_.SendControlFrame(QuicFrame(QuicBlockedFrame(1, 3, 0)));
7180   EXPECT_EQ(1u, connection_.GetStats().blocked_frames_sent);
7181   EXPECT_FALSE(connection_.HasQueuedData());
7182 }
7183 
TEST_P(QuicConnectionTest,FailedToSendBlockedFrames)7184 TEST_P(QuicConnectionTest, FailedToSendBlockedFrames) {
7185   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
7186     return;
7187   }
7188   MockQuicConnectionDebugVisitor debug_visitor;
7189   connection_.set_debug_visitor(&debug_visitor);
7190   QuicBlockedFrame blocked(1, 3, 0);
7191 
7192   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7193   EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(0);
7194   EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7195   connection_.SendControlFrame(QuicFrame(blocked));
7196   EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7197   EXPECT_FALSE(connection_.HasQueuedData());
7198 }
7199 
TEST_P(QuicConnectionTest,SendingUnencryptedStreamDataFails)7200 TEST_P(QuicConnectionTest, SendingUnencryptedStreamDataFails) {
7201   // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
7202   if (!IsDefaultTestConfiguration()) {
7203     return;
7204   }
7205 
7206   EXPECT_QUIC_BUG(
7207       {
7208         EXPECT_CALL(visitor_,
7209                     OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7210             .WillOnce(
7211                 Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
7212         connection_.SaveAndSendStreamData(3, {}, 0, FIN);
7213         EXPECT_FALSE(connection_.connected());
7214         EXPECT_EQ(1, connection_close_frame_count_);
7215         EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7216                     IsError(QUIC_ATTEMPT_TO_SEND_UNENCRYPTED_STREAM_DATA));
7217       },
7218       "Cannot send stream data with level: ENCRYPTION_INITIAL");
7219 }
7220 
TEST_P(QuicConnectionTest,SetRetransmissionAlarmForCryptoPacket)7221 TEST_P(QuicConnectionTest, SetRetransmissionAlarmForCryptoPacket) {
7222   EXPECT_TRUE(connection_.connected());
7223   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
7224 
7225   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7226   connection_.SendCryptoStreamData();
7227 
7228   // Verify retransmission timer is correctly set after crypto packet has been
7229   // sent.
7230   EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
7231   QuicTime retransmission_time =
7232       QuicConnectionPeer::GetSentPacketManager(&connection_)
7233           ->GetRetransmissionTime();
7234   EXPECT_NE(retransmission_time, clock_.ApproximateNow());
7235   EXPECT_EQ(retransmission_time,
7236             connection_.GetRetransmissionAlarm()->deadline());
7237 
7238   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7239   connection_.GetRetransmissionAlarm()->Fire();
7240 }
7241 
7242 // Includes regression test for b/69979024.
TEST_P(QuicConnectionTest,PathDegradingDetectionForNonCryptoPackets)7243 TEST_P(QuicConnectionTest, PathDegradingDetectionForNonCryptoPackets) {
7244   EXPECT_TRUE(connection_.connected());
7245   EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7246   EXPECT_FALSE(connection_.IsPathDegrading());
7247   EXPECT_CALL(visitor_, GetHandshakeState())
7248       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
7249   connection_.OnHandshakeComplete();
7250 
7251   const char data[] = "data";
7252   size_t data_size = strlen(data);
7253   QuicStreamOffset offset = 0;
7254 
7255   for (int i = 0; i < 2; ++i) {
7256     // Send a packet. Now there's a retransmittable packet on the wire, so the
7257     // path degrading detection should be set.
7258     connection_.SendStreamDataWithString(
7259         GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7260         offset, NO_FIN);
7261     offset += data_size;
7262     EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7263     // Check the deadline of the path degrading detection.
7264     QuicTime::Delta delay =
7265         QuicConnectionPeer::GetSentPacketManager(&connection_)
7266             ->GetPathDegradingDelay();
7267     EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7268                          clock_.ApproximateNow());
7269 
7270     // Send a second packet. The path degrading detection's deadline should
7271     // remain the same.
7272     // Regression test for b/69979024.
7273     clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7274     QuicTime prev_deadline =
7275         connection_.GetBlackholeDetectorAlarm()->deadline();
7276     connection_.SendStreamDataWithString(
7277         GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7278         offset, NO_FIN);
7279     offset += data_size;
7280     EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7281     EXPECT_EQ(prev_deadline,
7282               connection_.GetBlackholeDetectorAlarm()->deadline());
7283 
7284     // Now receive an ACK of the first packet. This should advance the path
7285     // degrading detection's deadline since forward progress has been made.
7286     clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7287     if (i == 0) {
7288       EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7289     }
7290     EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
7291     QuicAckFrame frame = InitAckFrame(
7292         {{QuicPacketNumber(1u + 2u * i), QuicPacketNumber(2u + 2u * i)}});
7293     ProcessAckPacket(&frame);
7294     EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7295     // Check the deadline of the path degrading detection.
7296     delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7297                 ->GetPathDegradingDelay();
7298     EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7299                          clock_.ApproximateNow());
7300 
7301     if (i == 0) {
7302       // Now receive an ACK of the second packet. Since there are no more
7303       // retransmittable packets on the wire, this should cancel the path
7304       // degrading detection.
7305       clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7306       EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
7307       frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7308       ProcessAckPacket(&frame);
7309       EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7310     } else {
7311       // Advance time to the path degrading alarm's deadline and simulate
7312       // firing the alarm.
7313       clock_.AdvanceTime(delay);
7314       EXPECT_CALL(visitor_, OnPathDegrading());
7315       connection_.PathDegradingTimeout();
7316       EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7317     }
7318   }
7319   EXPECT_TRUE(connection_.IsPathDegrading());
7320 }
7321 
TEST_P(QuicConnectionTest,RetransmittableOnWireSetsPingAlarm)7322 TEST_P(QuicConnectionTest, RetransmittableOnWireSetsPingAlarm) {
7323   const QuicTime::Delta retransmittable_on_wire_timeout =
7324       QuicTime::Delta::FromMilliseconds(50);
7325   connection_.set_initial_retransmittable_on_wire_timeout(
7326       retransmittable_on_wire_timeout);
7327 
7328   EXPECT_TRUE(connection_.connected());
7329   EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7330       .WillRepeatedly(Return(true));
7331 
7332   EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7333   EXPECT_FALSE(connection_.IsPathDegrading());
7334   EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7335   EXPECT_CALL(visitor_, GetHandshakeState())
7336       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
7337   connection_.OnHandshakeComplete();
7338 
7339   const char data[] = "data";
7340   size_t data_size = strlen(data);
7341   QuicStreamOffset offset = 0;
7342 
7343   // Send a packet.
7344   connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7345   offset += data_size;
7346   // Now there's a retransmittable packet on the wire, so the path degrading
7347   // alarm should be set.
7348   // The retransmittable-on-wire alarm should not be set.
7349   EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7350   QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7351                               ->GetPathDegradingDelay();
7352   EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7353                        clock_.ApproximateNow());
7354   ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7355   // The ping alarm is set for the ping timeout, not the shorter
7356   // retransmittable_on_wire_timeout.
7357   EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7358   QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
7359   EXPECT_EQ(ping_delay,
7360             connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7361 
7362   // Now receive an ACK of the packet.
7363   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7364   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7365   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
7366   QuicAckFrame frame =
7367       InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7368   ProcessAckPacket(&frame);
7369   // No more retransmittable packets on the wire, so the path degrading alarm
7370   // should be cancelled, and the ping alarm should be set to the
7371   // retransmittable_on_wire_timeout.
7372   EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7373   EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7374   EXPECT_EQ(retransmittable_on_wire_timeout,
7375             connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7376 
7377   // Simulate firing the ping alarm and sending a PING.
7378   clock_.AdvanceTime(retransmittable_on_wire_timeout);
7379   connection_.GetPingAlarm()->Fire();
7380 
7381   // Now there's a retransmittable packet (PING) on the wire, so the path
7382   // degrading alarm should be set.
7383   ASSERT_TRUE(connection_.PathDegradingDetectionInProgress());
7384   delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7385               ->GetPathDegradingDelay();
7386   EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7387                        clock_.ApproximateNow());
7388 }
7389 
TEST_P(QuicConnectionTest,ServerRetransmittableOnWire)7390 TEST_P(QuicConnectionTest, ServerRetransmittableOnWire) {
7391   set_perspective(Perspective::IS_SERVER);
7392   QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7393   SetQuicReloadableFlag(quic_enable_server_on_wire_ping, true);
7394 
7395   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7396   QuicConfig config;
7397   QuicTagVector connection_options;
7398   connection_options.push_back(kSRWP);
7399   config.SetInitialReceivedConnectionOptions(connection_options);
7400   connection_.SetFromConfig(config);
7401 
7402   EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7403       .WillRepeatedly(Return(true));
7404 
7405   ProcessPacket(1);
7406 
7407   ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7408   QuicTime::Delta ping_delay = QuicTime::Delta::FromMilliseconds(200);
7409   EXPECT_EQ(ping_delay,
7410             connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7411 
7412   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
7413   connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
7414   // Verify PING alarm gets cancelled.
7415   EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7416 
7417   // Now receive an ACK of the packet.
7418   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100));
7419   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
7420   QuicAckFrame frame =
7421       InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7422   ProcessAckPacket(2, &frame);
7423   // Verify PING alarm gets scheduled.
7424   ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7425   EXPECT_EQ(ping_delay,
7426             connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7427 }
7428 
TEST_P(QuicConnectionTest,RetransmittableOnWireSendFirstPacket)7429 TEST_P(QuicConnectionTest, RetransmittableOnWireSendFirstPacket) {
7430   if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
7431     return;
7432   }
7433   EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7434       .WillRepeatedly(Return(true));
7435   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7436 
7437   const QuicTime::Delta kRetransmittableOnWireTimeout =
7438       QuicTime::Delta::FromMilliseconds(200);
7439   const QuicTime::Delta kTestRtt = QuicTime::Delta::FromMilliseconds(100);
7440 
7441   connection_.set_initial_retransmittable_on_wire_timeout(
7442       kRetransmittableOnWireTimeout);
7443 
7444   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7445   QuicConfig config;
7446   QuicTagVector connection_options;
7447   connection_options.push_back(kROWF);
7448   config.SetClientConnectionOptions(connection_options);
7449   connection_.SetFromConfig(config);
7450 
7451   // Send a request.
7452   connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7453   // Receive an ACK after 1-RTT.
7454   clock_.AdvanceTime(kTestRtt);
7455   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
7456   QuicAckFrame frame =
7457       InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7458   ProcessAckPacket(&frame);
7459   ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7460   EXPECT_EQ(kRetransmittableOnWireTimeout,
7461             connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7462   EXPECT_EQ(1u, writer_->packets_write_attempts());
7463 
7464   // Fire retransmittable-on-wire alarm.
7465   clock_.AdvanceTime(kRetransmittableOnWireTimeout);
7466   connection_.GetPingAlarm()->Fire();
7467   EXPECT_EQ(2u, writer_->packets_write_attempts());
7468   // Verify alarm is set in keep-alive mode.
7469   ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7470   EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
7471             connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7472 }
7473 
TEST_P(QuicConnectionTest,RetransmittableOnWireSendRandomBytes)7474 TEST_P(QuicConnectionTest, RetransmittableOnWireSendRandomBytes) {
7475   if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
7476     return;
7477   }
7478   EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7479       .WillRepeatedly(Return(true));
7480   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7481 
7482   const QuicTime::Delta kRetransmittableOnWireTimeout =
7483       QuicTime::Delta::FromMilliseconds(200);
7484   const QuicTime::Delta kTestRtt = QuicTime::Delta::FromMilliseconds(100);
7485 
7486   connection_.set_initial_retransmittable_on_wire_timeout(
7487       kRetransmittableOnWireTimeout);
7488 
7489   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7490   QuicConfig config;
7491   QuicTagVector connection_options;
7492   connection_options.push_back(kROWR);
7493   config.SetClientConnectionOptions(connection_options);
7494   connection_.SetFromConfig(config);
7495 
7496   // Send a request.
7497   connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7498   // Receive an ACK after 1-RTT.
7499   clock_.AdvanceTime(kTestRtt);
7500   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
7501   QuicAckFrame frame =
7502       InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7503   ProcessAckPacket(&frame);
7504   ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7505   EXPECT_EQ(kRetransmittableOnWireTimeout,
7506             connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7507   EXPECT_EQ(1u, writer_->packets_write_attempts());
7508 
7509   // Fire retransmittable-on-wire alarm.
7510   clock_.AdvanceTime(kRetransmittableOnWireTimeout);
7511   // Next packet is not processable by the framer in the test writer.
7512   ExpectNextPacketUnprocessable();
7513   connection_.GetPingAlarm()->Fire();
7514   EXPECT_EQ(2u, writer_->packets_write_attempts());
7515   // Verify alarm is set in keep-alive mode.
7516   ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7517   EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
7518             connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7519 }
7520 
TEST_P(QuicConnectionTest,RetransmittableOnWireSendRandomBytesWithWriterBlocked)7521 TEST_P(QuicConnectionTest,
7522        RetransmittableOnWireSendRandomBytesWithWriterBlocked) {
7523   if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
7524     return;
7525   }
7526   EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7527       .WillRepeatedly(Return(true));
7528   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7529   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7530 
7531   const QuicTime::Delta kRetransmittableOnWireTimeout =
7532       QuicTime::Delta::FromMilliseconds(200);
7533   const QuicTime::Delta kTestRtt = QuicTime::Delta::FromMilliseconds(100);
7534 
7535   connection_.set_initial_retransmittable_on_wire_timeout(
7536       kRetransmittableOnWireTimeout);
7537 
7538   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7539   QuicConfig config;
7540   QuicTagVector connection_options;
7541   connection_options.push_back(kROWR);
7542   config.SetClientConnectionOptions(connection_options);
7543   connection_.SetFromConfig(config);
7544 
7545   // Send a request.
7546   connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7547   // Receive an ACK after 1-RTT.
7548   clock_.AdvanceTime(kTestRtt);
7549   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
7550   QuicAckFrame frame =
7551       InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7552   ProcessAckPacket(&frame);
7553   ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7554   EXPECT_EQ(kRetransmittableOnWireTimeout,
7555             connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7556   EXPECT_EQ(1u, writer_->packets_write_attempts());
7557   // Receive an out of order data packet and block the ACK packet.
7558   BlockOnNextWrite();
7559   ProcessDataPacket(3);
7560   EXPECT_EQ(2u, writer_->packets_write_attempts());
7561   EXPECT_EQ(1u, connection_.NumQueuedPackets());
7562 
7563   // Fire retransmittable-on-wire alarm.
7564   clock_.AdvanceTime(kRetransmittableOnWireTimeout);
7565   connection_.GetPingAlarm()->Fire();
7566   // Verify the random bytes packet gets queued.
7567   EXPECT_EQ(2u, connection_.NumQueuedPackets());
7568 }
7569 
7570 // This test verifies that the connection marks path as degrading and does not
7571 // spin timer to detect path degrading when a new packet is sent on the
7572 // degraded path.
TEST_P(QuicConnectionTest,NoPathDegradingDetectionIfPathIsDegrading)7573 TEST_P(QuicConnectionTest, NoPathDegradingDetectionIfPathIsDegrading) {
7574   EXPECT_TRUE(connection_.connected());
7575   EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7576   EXPECT_FALSE(connection_.IsPathDegrading());
7577   EXPECT_CALL(visitor_, GetHandshakeState())
7578       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
7579   connection_.OnHandshakeComplete();
7580 
7581   const char data[] = "data";
7582   size_t data_size = strlen(data);
7583   QuicStreamOffset offset = 0;
7584 
7585   // Send the first packet. Now there's a retransmittable packet on the wire, so
7586   // the path degrading alarm should be set.
7587   connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7588   offset += data_size;
7589   EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7590   // Check the deadline of the path degrading detection.
7591   QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7592                               ->GetPathDegradingDelay();
7593   EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7594                        clock_.ApproximateNow());
7595 
7596   // Send a second packet. The path degrading detection's deadline should remain
7597   // the same.
7598   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7599   QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
7600   connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7601   offset += data_size;
7602   EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7603   EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline());
7604 
7605   // Now receive an ACK of the first packet. This should advance the path
7606   // degrading detection's deadline since forward progress has been made.
7607   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7608   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7609   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
7610   QuicAckFrame frame =
7611       InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7612   ProcessAckPacket(&frame);
7613   EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7614   // Check the deadline of the path degrading alarm.
7615   delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7616               ->GetPathDegradingDelay();
7617   EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7618                        clock_.ApproximateNow());
7619 
7620   // Advance time to the path degrading detection's deadline and simulate
7621   // firing the path degrading detection. This path will be considered as
7622   // degrading.
7623   clock_.AdvanceTime(delay);
7624   EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7625   connection_.PathDegradingTimeout();
7626   EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7627   EXPECT_TRUE(connection_.IsPathDegrading());
7628 
7629   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7630   EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7631   // Send a third packet. The path degrading detection is no longer set but path
7632   // should still be marked as degrading.
7633   connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7634   offset += data_size;
7635   EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7636   EXPECT_TRUE(connection_.IsPathDegrading());
7637 }
7638 
TEST_P(QuicConnectionTest,NoPathDegradingDetectionBeforeHandshakeConfirmed)7639 TEST_P(QuicConnectionTest, NoPathDegradingDetectionBeforeHandshakeConfirmed) {
7640   EXPECT_TRUE(connection_.connected());
7641   EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7642   EXPECT_FALSE(connection_.IsPathDegrading());
7643   EXPECT_CALL(visitor_, GetHandshakeState())
7644       .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
7645 
7646   connection_.SendStreamDataWithString(1, "data", 0, NO_FIN);
7647   if (GetQuicReloadableFlag(
7648           quic_no_path_degrading_before_handshake_confirmed) &&
7649       connection_.SupportsMultiplePacketNumberSpaces()) {
7650     EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7651   } else {
7652     EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7653   }
7654 }
7655 
7656 // This test verifies that the connection unmarks path as degrarding and spins
7657 // the timer to detect future path degrading when forward progress is made
7658 // after path has been marked degrading.
TEST_P(QuicConnectionTest,UnmarkPathDegradingOnForwardProgress)7659 TEST_P(QuicConnectionTest, UnmarkPathDegradingOnForwardProgress) {
7660   EXPECT_TRUE(connection_.connected());
7661   EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7662   EXPECT_FALSE(connection_.IsPathDegrading());
7663   EXPECT_CALL(visitor_, GetHandshakeState())
7664       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
7665   connection_.OnHandshakeComplete();
7666 
7667   const char data[] = "data";
7668   size_t data_size = strlen(data);
7669   QuicStreamOffset offset = 0;
7670 
7671   // Send the first packet. Now there's a retransmittable packet on the wire, so
7672   // the path degrading alarm should be set.
7673   connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7674   offset += data_size;
7675   EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7676   // Check the deadline of the path degrading alarm.
7677   QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7678                               ->GetPathDegradingDelay();
7679   EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7680                        clock_.ApproximateNow());
7681 
7682   // Send a second packet. The path degrading alarm's deadline should remain
7683   // the same.
7684   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7685   QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
7686   connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7687   offset += data_size;
7688   EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7689   EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline());
7690 
7691   // Now receive an ACK of the first packet. This should advance the path
7692   // degrading alarm's deadline since forward progress has been made.
7693   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7694   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7695   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
7696   QuicAckFrame frame =
7697       InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7698   ProcessAckPacket(&frame);
7699   EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7700   // Check the deadline of the path degrading alarm.
7701   delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7702               ->GetPathDegradingDelay();
7703   EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7704                        clock_.ApproximateNow());
7705 
7706   // Advance time to the path degrading alarm's deadline and simulate
7707   // firing the alarm.
7708   clock_.AdvanceTime(delay);
7709   EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7710   connection_.PathDegradingTimeout();
7711   EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7712   EXPECT_TRUE(connection_.IsPathDegrading());
7713 
7714   // Send a third packet. The path degrading alarm is no longer set but path
7715   // should still be marked as degrading.
7716   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7717   EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7718   connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7719   offset += data_size;
7720   EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7721   EXPECT_TRUE(connection_.IsPathDegrading());
7722 
7723   // Now receive an ACK of the second packet. This should unmark the path as
7724   // degrading. And will set a timer to detect new path degrading.
7725   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7726   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
7727   EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(1);
7728   frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7729   ProcessAckPacket(&frame);
7730   EXPECT_EQ(1,
7731             connection_.GetStats().num_forward_progress_after_path_degrading);
7732   EXPECT_FALSE(connection_.IsPathDegrading());
7733   EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7734 }
7735 
TEST_P(QuicConnectionTest,NoPathDegradingOnServer)7736 TEST_P(QuicConnectionTest, NoPathDegradingOnServer) {
7737   if (connection_.SupportsMultiplePacketNumberSpaces()) {
7738     return;
7739   }
7740   set_perspective(Perspective::IS_SERVER);
7741   QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7742 
7743   EXPECT_FALSE(connection_.IsPathDegrading());
7744   EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7745 
7746   // Send data.
7747   const char data[] = "data";
7748   connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
7749   EXPECT_FALSE(connection_.IsPathDegrading());
7750   EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7751 
7752   // Ack data.
7753   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7754   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
7755   QuicAckFrame frame =
7756       InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7757   ProcessAckPacket(&frame);
7758   EXPECT_FALSE(connection_.IsPathDegrading());
7759   EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7760 }
7761 
TEST_P(QuicConnectionTest,NoPathDegradingAfterSendingAck)7762 TEST_P(QuicConnectionTest, NoPathDegradingAfterSendingAck) {
7763   if (connection_.SupportsMultiplePacketNumberSpaces()) {
7764     return;
7765   }
7766   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7767   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7768   ProcessDataPacket(1);
7769   SendAckPacketToPeer();
7770   EXPECT_FALSE(connection_.sent_packet_manager().unacked_packets().empty());
7771   EXPECT_FALSE(connection_.sent_packet_manager().HasInFlightPackets());
7772   EXPECT_FALSE(connection_.IsPathDegrading());
7773   EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7774 }
7775 
TEST_P(QuicConnectionTest,MultipleCallsToCloseConnection)7776 TEST_P(QuicConnectionTest, MultipleCallsToCloseConnection) {
7777   // Verifies that multiple calls to CloseConnection do not
7778   // result in multiple attempts to close the connection - it will be marked as
7779   // disconnected after the first call.
7780   EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
7781   connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7782                               ConnectionCloseBehavior::SILENT_CLOSE);
7783   connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7784                               ConnectionCloseBehavior::SILENT_CLOSE);
7785 }
7786 
TEST_P(QuicConnectionTest,ServerReceivesChloOnNonCryptoStream)7787 TEST_P(QuicConnectionTest, ServerReceivesChloOnNonCryptoStream) {
7788   set_perspective(Perspective::IS_SERVER);
7789   QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7790   QuicConnectionPeer::SetAddressValidated(&connection_);
7791 
7792   CryptoHandshakeMessage message;
7793   CryptoFramer framer;
7794   message.set_tag(kCHLO);
7795   std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
7796   frame1_.stream_id = 10;
7797   frame1_.data_buffer = data->data();
7798   frame1_.data_length = data->length();
7799 
7800   if (version().handshake_protocol == PROTOCOL_TLS1_3) {
7801     EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
7802   }
7803   EXPECT_CALL(visitor_,
7804               OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
7805   ForceProcessFramePacket(QuicFrame(frame1_));
7806   if (VersionHasIetfQuicFrames(version().transport_version)) {
7807     // INITIAL packet should not contain STREAM frame.
7808     TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
7809   } else {
7810     TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
7811   }
7812 }
7813 
TEST_P(QuicConnectionTest,ClientReceivesRejOnNonCryptoStream)7814 TEST_P(QuicConnectionTest, ClientReceivesRejOnNonCryptoStream) {
7815   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7816 
7817   CryptoHandshakeMessage message;
7818   CryptoFramer framer;
7819   message.set_tag(kREJ);
7820   std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
7821   frame1_.stream_id = 10;
7822   frame1_.data_buffer = data->data();
7823   frame1_.data_length = data->length();
7824 
7825   EXPECT_CALL(visitor_,
7826               OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
7827   ForceProcessFramePacket(QuicFrame(frame1_));
7828   if (VersionHasIetfQuicFrames(version().transport_version)) {
7829     // INITIAL packet should not contain STREAM frame.
7830     TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
7831   } else {
7832     TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
7833   }
7834 }
7835 
TEST_P(QuicConnectionTest,CloseConnectionOnPacketTooLarge)7836 TEST_P(QuicConnectionTest, CloseConnectionOnPacketTooLarge) {
7837   SimulateNextPacketTooLarge();
7838   // A connection close packet is sent
7839   EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7840       .Times(1);
7841   connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7842   TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7843 }
7844 
TEST_P(QuicConnectionTest,AlwaysGetPacketTooLarge)7845 TEST_P(QuicConnectionTest, AlwaysGetPacketTooLarge) {
7846   // Test even we always get packet too large, we do not infinitely try to send
7847   // close packet.
7848   AlwaysGetPacketTooLarge();
7849   EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7850       .Times(1);
7851   connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7852   TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7853 }
7854 
TEST_P(QuicConnectionTest,CloseConnectionOnQueuedWriteError)7855 TEST_P(QuicConnectionTest, CloseConnectionOnQueuedWriteError) {
7856   // Regression test for crbug.com/979507.
7857   //
7858   // If we get a write error when writing queued packets, we should attempt to
7859   // send a connection close packet, but if sending that fails, it shouldn't get
7860   // queued.
7861 
7862   // Queue a packet to write.
7863   BlockOnNextWrite();
7864   connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7865   EXPECT_EQ(1u, connection_.NumQueuedPackets());
7866 
7867   // Configure writer to always fail.
7868   AlwaysGetPacketTooLarge();
7869 
7870   // Expect that we attempt to close the connection exactly once.
7871   EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7872       .Times(1);
7873 
7874   // Unblock the writes and actually send.
7875   writer_->SetWritable();
7876   connection_.OnCanWrite();
7877   EXPECT_EQ(0u, connection_.NumQueuedPackets());
7878 
7879   TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7880 }
7881 
7882 // Verify that if connection has no outstanding data, it notifies the send
7883 // algorithm after the write.
TEST_P(QuicConnectionTest,SendDataAndBecomeApplicationLimited)7884 TEST_P(QuicConnectionTest, SendDataAndBecomeApplicationLimited) {
7885   EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7886   {
7887     InSequence seq;
7888     EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7889     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7890     EXPECT_CALL(visitor_, WillingAndAbleToWrite())
7891         .WillRepeatedly(Return(false));
7892   }
7893 
7894   connection_.SendStreamData3();
7895 }
7896 
7897 // Verify that the connection does not become app-limited if there is
7898 // outstanding data to send after the write.
TEST_P(QuicConnectionTest,NotBecomeApplicationLimitedIfMoreDataAvailable)7899 TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedIfMoreDataAvailable) {
7900   EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7901   {
7902     InSequence seq;
7903     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7904     EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7905   }
7906 
7907   connection_.SendStreamData3();
7908 }
7909 
7910 // Verify that the connection does not become app-limited after blocked write
7911 // even if there is outstanding data to send after the write.
TEST_P(QuicConnectionTest,NotBecomeApplicationLimitedDueToWriteBlock)7912 TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedDueToWriteBlock) {
7913   EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7914   EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7915   BlockOnNextWrite();
7916 
7917   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7918   connection_.SendStreamData3();
7919 
7920   // Now unblock the writer, become congestion control blocked,
7921   // and ensure we become app-limited after writing.
7922   writer_->SetWritable();
7923   CongestionBlockWrites();
7924   EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
7925   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7926   EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7927   connection_.OnCanWrite();
7928 }
7929 
TEST_P(QuicConnectionTest,DoNotForceSendingAckOnPacketTooLarge)7930 TEST_P(QuicConnectionTest, DoNotForceSendingAckOnPacketTooLarge) {
7931   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7932   // Send an ack by simulating delayed ack alarm firing.
7933   ProcessPacket(1);
7934   EXPECT_TRUE(connection_.HasPendingAcks());
7935   connection_.GetAckAlarm()->Fire();
7936   // Simulate data packet causes write error.
7937   EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
7938   SimulateNextPacketTooLarge();
7939   connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7940   EXPECT_EQ(1u, writer_->connection_close_frames().size());
7941   // Ack frame is not bundled in connection close packet.
7942   EXPECT_TRUE(writer_->ack_frames().empty());
7943   if (writer_->padding_frames().empty()) {
7944     EXPECT_EQ(1u, writer_->frame_count());
7945   } else {
7946     EXPECT_EQ(2u, writer_->frame_count());
7947   }
7948 
7949   TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7950 }
7951 
TEST_P(QuicConnectionTest,CloseConnectionAllLevels)7952 TEST_P(QuicConnectionTest, CloseConnectionAllLevels) {
7953   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
7954     return;
7955   }
7956 
7957   EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
7958   const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
7959   connection_.CloseConnection(
7960       kQuicErrorCode, "Some random error message",
7961       ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
7962 
7963   EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
7964 
7965   TestConnectionCloseQuicErrorCode(kQuicErrorCode);
7966   EXPECT_EQ(1u, writer_->connection_close_frames().size());
7967 
7968   if (!connection_.version().CanSendCoalescedPackets()) {
7969     // Each connection close packet should be sent in distinct UDP packets.
7970     EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
7971               writer_->connection_close_packets());
7972     EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
7973               writer_->packets_write_attempts());
7974     return;
7975   }
7976 
7977   // A single UDP packet should be sent with multiple connection close packets
7978   // coalesced together.
7979   EXPECT_EQ(1u, writer_->packets_write_attempts());
7980 
7981   // Only the first packet has been processed yet.
7982   EXPECT_EQ(1u, writer_->connection_close_packets());
7983 
7984   // ProcessPacket resets the visitor and frees the coalesced packet.
7985   ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
7986   auto packet = writer_->coalesced_packet()->Clone();
7987   writer_->framer()->ProcessPacket(*packet);
7988   EXPECT_EQ(1u, writer_->connection_close_packets());
7989   ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
7990 }
7991 
TEST_P(QuicConnectionTest,CloseConnectionOneLevel)7992 TEST_P(QuicConnectionTest, CloseConnectionOneLevel) {
7993   if (connection_.SupportsMultiplePacketNumberSpaces()) {
7994     return;
7995   }
7996 
7997   EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
7998   const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
7999   connection_.CloseConnection(
8000       kQuicErrorCode, "Some random error message",
8001       ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8002 
8003   EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8004 
8005   TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8006   EXPECT_EQ(1u, writer_->connection_close_frames().size());
8007   EXPECT_EQ(1u, writer_->connection_close_packets());
8008   EXPECT_EQ(1u, writer_->packets_write_attempts());
8009   ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
8010 }
8011 
TEST_P(QuicConnectionTest,DoNotPadServerInitialConnectionClose)8012 TEST_P(QuicConnectionTest, DoNotPadServerInitialConnectionClose) {
8013   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8014     return;
8015   }
8016   set_perspective(Perspective::IS_SERVER);
8017   // Receives packet 1000 in initial data.
8018   EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
8019   ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
8020 
8021   if (version().handshake_protocol == PROTOCOL_TLS1_3) {
8022     EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
8023   }
8024   EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8025   const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
8026   connection_.CloseConnection(
8027       kQuicErrorCode, "Some random error message",
8028       ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8029 
8030   EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8031 
8032   TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8033   EXPECT_EQ(1u, writer_->connection_close_frames().size());
8034   EXPECT_TRUE(writer_->padding_frames().empty());
8035   EXPECT_EQ(ENCRYPTION_INITIAL, writer_->framer()->last_decrypted_level());
8036 }
8037 
8038 // Regression test for b/63620844.
TEST_P(QuicConnectionTest,FailedToWriteHandshakePacket)8039 TEST_P(QuicConnectionTest, FailedToWriteHandshakePacket) {
8040   SimulateNextPacketTooLarge();
8041   EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
8042       .Times(1);
8043 
8044   connection_.SendCryptoStreamData();
8045   TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
8046 }
8047 
TEST_P(QuicConnectionTest,MaxPacingRate)8048 TEST_P(QuicConnectionTest, MaxPacingRate) {
8049   EXPECT_EQ(0, connection_.MaxPacingRate().ToBytesPerSecond());
8050   connection_.SetMaxPacingRate(QuicBandwidth::FromBytesPerSecond(100));
8051   EXPECT_EQ(100, connection_.MaxPacingRate().ToBytesPerSecond());
8052 }
8053 
TEST_P(QuicConnectionTest,ClientAlwaysSendConnectionId)8054 TEST_P(QuicConnectionTest, ClientAlwaysSendConnectionId) {
8055   EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
8056   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8057   connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
8058   EXPECT_EQ(CONNECTION_ID_PRESENT,
8059             writer_->last_packet_header().destination_connection_id_included);
8060 
8061   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8062   QuicConfig config;
8063   QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
8064   connection_.SetFromConfig(config);
8065 
8066   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8067   connection_.SendStreamDataWithString(3, "bar", 3, NO_FIN);
8068   // Verify connection id is still sent in the packet.
8069   EXPECT_EQ(CONNECTION_ID_PRESENT,
8070             writer_->last_packet_header().destination_connection_id_included);
8071 }
8072 
TEST_P(QuicConnectionTest,PingAfterLastRetransmittablePacketAcked)8073 TEST_P(QuicConnectionTest, PingAfterLastRetransmittablePacketAcked) {
8074   const QuicTime::Delta retransmittable_on_wire_timeout =
8075       QuicTime::Delta::FromMilliseconds(50);
8076   connection_.set_initial_retransmittable_on_wire_timeout(
8077       retransmittable_on_wire_timeout);
8078 
8079   EXPECT_TRUE(connection_.connected());
8080   EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8081       .WillRepeatedly(Return(true));
8082 
8083   const char data[] = "data";
8084   size_t data_size = strlen(data);
8085   QuicStreamOffset offset = 0;
8086 
8087   // Advance 5ms, send a retransmittable packet to the peer.
8088   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8089   EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8090   connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8091   offset += data_size;
8092   EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8093   // The ping alarm is set for the ping timeout, not the shorter
8094   // retransmittable_on_wire_timeout.
8095   EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8096   QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
8097   EXPECT_EQ(ping_delay,
8098             connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8099 
8100   // Advance 5ms, send a second retransmittable packet to the peer.
8101   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8102   EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8103   connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8104   offset += data_size;
8105   EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8106 
8107   // Now receive an ACK of the first packet. This should not set the
8108   // retransmittable-on-wire alarm since packet 2 is still on the wire.
8109   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8110   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8111   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
8112   QuicAckFrame frame =
8113       InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8114   ProcessAckPacket(&frame);
8115   EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8116   // The ping alarm is set for the ping timeout, not the shorter
8117   // retransmittable_on_wire_timeout.
8118   EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8119   // The ping alarm has a 1 second granularity, and the clock has been advanced
8120   // 10ms since it was originally set.
8121   EXPECT_EQ(ping_delay - QuicTime::Delta::FromMilliseconds(10),
8122             connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8123 
8124   // Now receive an ACK of the second packet. This should set the
8125   // retransmittable-on-wire alarm now that no retransmittable packets are on
8126   // the wire.
8127   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8128   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
8129   frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8130   ProcessAckPacket(&frame);
8131   EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8132   EXPECT_EQ(retransmittable_on_wire_timeout,
8133             connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8134 
8135   // Now receive a duplicate ACK of the second packet. This should not update
8136   // the ping alarm.
8137   QuicTime prev_deadline = connection_.GetPingAlarm()->deadline();
8138   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8139   frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8140   ProcessAckPacket(&frame);
8141   EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8142   EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8143 
8144   // Now receive a non-ACK packet.  This should not update the ping alarm.
8145   prev_deadline = connection_.GetPingAlarm()->deadline();
8146   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8147   ProcessPacket(4);
8148   EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8149   EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8150 
8151   // Simulate the alarm firing and check that a PING is sent.
8152   connection_.GetPingAlarm()->Fire();
8153   size_t padding_frame_count = writer_->padding_frames().size();
8154   EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
8155   ASSERT_EQ(1u, writer_->ping_frames().size());
8156 }
8157 
TEST_P(QuicConnectionTest,NoPingIfRetransmittablePacketSent)8158 TEST_P(QuicConnectionTest, NoPingIfRetransmittablePacketSent) {
8159   const QuicTime::Delta retransmittable_on_wire_timeout =
8160       QuicTime::Delta::FromMilliseconds(50);
8161   connection_.set_initial_retransmittable_on_wire_timeout(
8162       retransmittable_on_wire_timeout);
8163 
8164   EXPECT_TRUE(connection_.connected());
8165   EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8166       .WillRepeatedly(Return(true));
8167 
8168   const char data[] = "data";
8169   size_t data_size = strlen(data);
8170   QuicStreamOffset offset = 0;
8171 
8172   // Advance 5ms, send a retransmittable packet to the peer.
8173   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8174   EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8175   connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8176   offset += data_size;
8177   EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8178   // The ping alarm is set for the ping timeout, not the shorter
8179   // retransmittable_on_wire_timeout.
8180   EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8181   QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
8182   EXPECT_EQ(ping_delay,
8183             connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8184 
8185   // Now receive an ACK of the first packet. This should set the
8186   // retransmittable-on-wire alarm now that no retransmittable packets are on
8187   // the wire.
8188   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8189   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8190   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
8191   QuicAckFrame frame =
8192       InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8193   ProcessAckPacket(&frame);
8194   EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8195   EXPECT_EQ(retransmittable_on_wire_timeout,
8196             connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8197 
8198   // Before the alarm fires, send another retransmittable packet. This should
8199   // cancel the retransmittable-on-wire alarm since now there's a
8200   // retransmittable packet on the wire.
8201   connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8202   offset += data_size;
8203   EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8204 
8205   // Now receive an ACK of the second packet. This should set the
8206   // retransmittable-on-wire alarm now that no retransmittable packets are on
8207   // the wire.
8208   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8209   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
8210   frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8211   ProcessAckPacket(&frame);
8212   EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8213   EXPECT_EQ(retransmittable_on_wire_timeout,
8214             connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8215 
8216   // Simulate the alarm firing and check that a PING is sent.
8217   writer_->Reset();
8218   connection_.GetPingAlarm()->Fire();
8219   size_t padding_frame_count = writer_->padding_frames().size();
8220   // Do not ACK acks.
8221   EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
8222   ASSERT_EQ(1u, writer_->ping_frames().size());
8223 }
8224 
8225 // When there is no stream data received but are open streams, send the
8226 // first few consecutive pings with aggressive retransmittable-on-wire
8227 // timeout. Exponentially back off the retransmittable-on-wire ping timeout
8228 // afterwards until it exceeds the default ping timeout.
TEST_P(QuicConnectionTest,BackOffRetransmittableOnWireTimeout)8229 TEST_P(QuicConnectionTest, BackOffRetransmittableOnWireTimeout) {
8230   int max_aggressive_retransmittable_on_wire_ping_count = 5;
8231   SetQuicFlag(quic_max_aggressive_retransmittable_on_wire_ping_count,
8232               max_aggressive_retransmittable_on_wire_ping_count);
8233   const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8234       QuicTime::Delta::FromMilliseconds(200);
8235   connection_.set_initial_retransmittable_on_wire_timeout(
8236       initial_retransmittable_on_wire_timeout);
8237 
8238   EXPECT_TRUE(connection_.connected());
8239   EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8240       .WillRepeatedly(Return(true));
8241 
8242   const char data[] = "data";
8243   // Advance 5ms, send a retransmittable data packet to the peer.
8244   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8245   EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8246   connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8247   EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8248   // The ping alarm is set for the ping timeout, not the shorter
8249   // retransmittable_on_wire_timeout.
8250   EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8251   EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
8252             connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8253 
8254   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8255   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
8256       .Times(AnyNumber());
8257 
8258   // Verify that the first few consecutive retransmittable on wire pings are
8259   // sent with aggressive timeout.
8260   for (int i = 0; i <= max_aggressive_retransmittable_on_wire_ping_count; i++) {
8261     // Receive an ACK of the previous packet. This should set the ping alarm
8262     // with the initial retransmittable-on-wire timeout.
8263     clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8264     QuicPacketNumber ack_num = creator_->packet_number();
8265     QuicAckFrame frame = InitAckFrame(
8266         {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8267     ProcessAckPacket(&frame);
8268     EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8269     EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8270               connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8271     // Simulate the alarm firing and check that a PING is sent.
8272     writer_->Reset();
8273     clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8274     connection_.GetPingAlarm()->Fire();
8275   }
8276 
8277   QuicTime::Delta retransmittable_on_wire_timeout =
8278       initial_retransmittable_on_wire_timeout;
8279 
8280   // Verify subsequent pings are sent with timeout that is exponentially backed
8281   // off.
8282   while (retransmittable_on_wire_timeout * 2 <
8283          QuicTime::Delta::FromSeconds(kPingTimeoutSecs)) {
8284     // Receive an ACK for the previous PING. This should set the
8285     // ping alarm with backed off retransmittable-on-wire timeout.
8286     retransmittable_on_wire_timeout = retransmittable_on_wire_timeout * 2;
8287     clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8288     QuicPacketNumber ack_num = creator_->packet_number();
8289     QuicAckFrame frame = InitAckFrame(
8290         {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8291     ProcessAckPacket(&frame);
8292     EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8293     EXPECT_EQ(retransmittable_on_wire_timeout,
8294               connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8295 
8296     // Simulate the alarm firing and check that a PING is sent.
8297     writer_->Reset();
8298     clock_.AdvanceTime(retransmittable_on_wire_timeout);
8299     connection_.GetPingAlarm()->Fire();
8300   }
8301 
8302   // The ping alarm is set with default ping timeout.
8303   EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8304   EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
8305             connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8306 
8307   // Receive an ACK for the previous PING. The ping alarm is set with an
8308   // earlier deadline.
8309   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8310   QuicPacketNumber ack_num = creator_->packet_number();
8311   QuicAckFrame frame = InitAckFrame(
8312       {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8313   ProcessAckPacket(&frame);
8314   EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8315   EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs) -
8316                 QuicTime::Delta::FromMilliseconds(5),
8317             connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8318 }
8319 
8320 // This test verify that the count of consecutive aggressive pings is reset
8321 // when new data is received. And it also verifies the connection resets
8322 // the exponential back-off of the retransmittable-on-wire ping timeout
8323 // after receiving new stream data.
TEST_P(QuicConnectionTest,ResetBackOffRetransmitableOnWireTimeout)8324 TEST_P(QuicConnectionTest, ResetBackOffRetransmitableOnWireTimeout) {
8325   int max_aggressive_retransmittable_on_wire_ping_count = 3;
8326   SetQuicFlag(quic_max_aggressive_retransmittable_on_wire_ping_count, 3);
8327   const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8328       QuicTime::Delta::FromMilliseconds(200);
8329   connection_.set_initial_retransmittable_on_wire_timeout(
8330       initial_retransmittable_on_wire_timeout);
8331 
8332   EXPECT_TRUE(connection_.connected());
8333   EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8334       .WillRepeatedly(Return(true));
8335   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8336   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
8337       .Times(AnyNumber());
8338 
8339   const char data[] = "data";
8340   // Advance 5ms, send a retransmittable data packet to the peer.
8341   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8342   EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8343   connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8344   EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8345   // The ping alarm is set for the ping timeout, not the shorter
8346   // retransmittable_on_wire_timeout.
8347   EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8348   EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
8349             connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8350 
8351   // Receive an ACK of the first packet. This should set the ping alarm with
8352   // initial retransmittable-on-wire timeout since there is no retransmittable
8353   // packet on the wire.
8354   {
8355     clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8356     QuicAckFrame frame =
8357         InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8358     ProcessAckPacket(&frame);
8359     EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8360     EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8361               connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8362   }
8363 
8364   // Simulate the alarm firing and check that a PING is sent.
8365   writer_->Reset();
8366   clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8367   connection_.GetPingAlarm()->Fire();
8368 
8369   // Receive an ACK for the previous PING. Ping alarm will be set with
8370   // aggressive timeout.
8371   {
8372     clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8373     QuicPacketNumber ack_num = creator_->packet_number();
8374     QuicAckFrame frame = InitAckFrame(
8375         {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8376     ProcessAckPacket(&frame);
8377     EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8378     EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8379               connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8380   }
8381 
8382   // Process a data packet.
8383   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8384   ProcessDataPacket(peer_creator_.packet_number() + 1);
8385   QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
8386                                          peer_creator_.packet_number() + 1);
8387   EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8388             connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8389   clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8390   connection_.GetPingAlarm()->Fire();
8391 
8392   // Verify the count of consecutive aggressive pings is reset.
8393   for (int i = 0; i < max_aggressive_retransmittable_on_wire_ping_count; i++) {
8394     // Receive an ACK of the previous packet. This should set the ping alarm
8395     // with the initial retransmittable-on-wire timeout.
8396     const QuicPacketNumber ack_num = creator_->packet_number();
8397     QuicAckFrame frame = InitAckFrame(
8398         {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8399     ProcessAckPacket(&frame);
8400     EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8401     EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8402               connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8403     // Simulate the alarm firing and check that a PING is sent.
8404     writer_->Reset();
8405     clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8406     connection_.GetPingAlarm()->Fire();
8407     // Advance 5ms to receive next packet.
8408     clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8409   }
8410 
8411   // Receive another ACK for the previous PING. This should set the
8412   // ping alarm with backed off retransmittable-on-wire timeout.
8413   {
8414     const QuicPacketNumber ack_num = creator_->packet_number();
8415     QuicAckFrame frame = InitAckFrame(
8416         {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8417     ProcessAckPacket(&frame);
8418     EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8419     EXPECT_EQ(initial_retransmittable_on_wire_timeout * 2,
8420               connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8421   }
8422 
8423   writer_->Reset();
8424   clock_.AdvanceTime(2 * initial_retransmittable_on_wire_timeout);
8425   connection_.GetPingAlarm()->Fire();
8426 
8427   // Process another data packet and a new ACK packet. The ping alarm is set
8428   // with aggressive ping timeout again.
8429   {
8430     EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8431     clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8432     ProcessDataPacket(peer_creator_.packet_number() + 1);
8433     QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
8434                                            peer_creator_.packet_number() + 1);
8435     const QuicPacketNumber ack_num = creator_->packet_number();
8436     QuicAckFrame frame = InitAckFrame(
8437         {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8438     ProcessAckPacket(&frame);
8439     EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8440     EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8441               connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8442   }
8443 }
8444 
8445 // Make sure that we never send more retransmissible on the wire pings than
8446 // the limit in FLAGS_quic_max_retransmittable_on_wire_ping_count.
TEST_P(QuicConnectionTest,RetransmittableOnWirePingLimit)8447 TEST_P(QuicConnectionTest, RetransmittableOnWirePingLimit) {
8448   static constexpr int kMaxRetransmittableOnWirePingCount = 3;
8449   SetQuicFlag(quic_max_retransmittable_on_wire_ping_count,
8450               kMaxRetransmittableOnWirePingCount);
8451   static constexpr QuicTime::Delta initial_retransmittable_on_wire_timeout =
8452       QuicTime::Delta::FromMilliseconds(200);
8453   static constexpr QuicTime::Delta short_delay =
8454       QuicTime::Delta::FromMilliseconds(5);
8455   ASSERT_LT(short_delay * 10, initial_retransmittable_on_wire_timeout);
8456   connection_.set_initial_retransmittable_on_wire_timeout(
8457       initial_retransmittable_on_wire_timeout);
8458 
8459   EXPECT_TRUE(connection_.connected());
8460   EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8461       .WillRepeatedly(Return(true));
8462 
8463   const char data[] = "data";
8464   // Advance 5ms, send a retransmittable data packet to the peer.
8465   clock_.AdvanceTime(short_delay);
8466   EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8467   connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8468   EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8469   // The ping alarm is set for the ping timeout, not the shorter
8470   // retransmittable_on_wire_timeout.
8471   EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8472   EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
8473             connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8474 
8475   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8476   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
8477       .Times(AnyNumber());
8478 
8479   // Verify that the first few consecutive retransmittable on wire pings are
8480   // sent with aggressive timeout.
8481   for (int i = 0; i <= kMaxRetransmittableOnWirePingCount; i++) {
8482     // Receive an ACK of the previous packet. This should set the ping alarm
8483     // with the initial retransmittable-on-wire timeout.
8484     clock_.AdvanceTime(short_delay);
8485     QuicPacketNumber ack_num = creator_->packet_number();
8486     QuicAckFrame frame = InitAckFrame(
8487         {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8488     ProcessAckPacket(&frame);
8489     EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8490     EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8491               connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8492     // Simulate the alarm firing and check that a PING is sent.
8493     writer_->Reset();
8494     clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8495     connection_.GetPingAlarm()->Fire();
8496   }
8497 
8498   // Receive an ACK of the previous packet. This should set the ping alarm
8499   // but this time with the default ping timeout.
8500   QuicPacketNumber ack_num = creator_->packet_number();
8501   QuicAckFrame frame = InitAckFrame(
8502       {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8503   ProcessAckPacket(&frame);
8504   EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8505   EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
8506             connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8507 }
8508 
TEST_P(QuicConnectionTest,ValidStatelessResetToken)8509 TEST_P(QuicConnectionTest, ValidStatelessResetToken) {
8510   const StatelessResetToken kTestToken{0, 1, 0, 1, 0, 1, 0, 1,
8511                                        0, 1, 0, 1, 0, 1, 0, 1};
8512   const StatelessResetToken kWrongTestToken{0, 1, 0, 1, 0, 1, 0, 1,
8513                                             0, 1, 0, 1, 0, 1, 0, 2};
8514   QuicConfig config;
8515   // No token has been received.
8516   EXPECT_FALSE(connection_.IsValidStatelessResetToken(kTestToken));
8517 
8518   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(2);
8519   // Token is different from received token.
8520   QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8521   connection_.SetFromConfig(config);
8522   EXPECT_FALSE(connection_.IsValidStatelessResetToken(kWrongTestToken));
8523 
8524   QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8525   connection_.SetFromConfig(config);
8526   EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestToken));
8527 }
8528 
TEST_P(QuicConnectionTest,WriteBlockedWithInvalidAck)8529 TEST_P(QuicConnectionTest, WriteBlockedWithInvalidAck) {
8530   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8531   EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
8532   BlockOnNextWrite();
8533   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8534   connection_.SendStreamDataWithString(5, "foo", 0, FIN);
8535   // This causes connection to be closed because packet 1 has not been sent yet.
8536   QuicAckFrame frame = InitAckFrame(1);
8537   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
8538   ProcessAckPacket(1, &frame);
8539   EXPECT_EQ(0, connection_close_frame_count_);
8540 }
8541 
TEST_P(QuicConnectionTest,SendMessage)8542 TEST_P(QuicConnectionTest, SendMessage) {
8543   if (connection_.version().UsesTls()) {
8544     QuicConfig config;
8545     QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
8546         &config, kMaxAcceptedDatagramFrameSize);
8547     EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8548     connection_.SetFromConfig(config);
8549   }
8550   std::string message(connection_.GetCurrentLargestMessagePayload() * 2, 'a');
8551   quiche::QuicheMemSlice slice;
8552   {
8553     QuicConnection::ScopedPacketFlusher flusher(&connection_);
8554     connection_.SendStreamData3();
8555     // Send a message which cannot fit into current open packet, and 2 packets
8556     // get sent, one contains stream frame, and the other only contains the
8557     // message frame.
8558     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8559     slice = MemSliceFromString(absl::string_view(
8560         message.data(), connection_.GetCurrentLargestMessagePayload()));
8561     EXPECT_EQ(MESSAGE_STATUS_SUCCESS,
8562               connection_.SendMessage(1, absl::MakeSpan(&slice, 1), false));
8563   }
8564   // Fail to send a message if connection is congestion control blocked.
8565   EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
8566   slice = MemSliceFromString("message");
8567   EXPECT_EQ(MESSAGE_STATUS_BLOCKED,
8568             connection_.SendMessage(2, absl::MakeSpan(&slice, 1), false));
8569 
8570   // Always fail to send a message which cannot fit into one packet.
8571   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8572   slice = MemSliceFromString(absl::string_view(
8573       message.data(), connection_.GetCurrentLargestMessagePayload() + 1));
8574   EXPECT_EQ(MESSAGE_STATUS_TOO_LARGE,
8575             connection_.SendMessage(3, absl::MakeSpan(&slice, 1), false));
8576 }
8577 
TEST_P(QuicConnectionTest,GetCurrentLargestMessagePayload)8578 TEST_P(QuicConnectionTest, GetCurrentLargestMessagePayload) {
8579   QuicPacketLength expected_largest_payload = 1215;
8580   if (connection_.version().SendsVariableLengthPacketNumberInLongHeader()) {
8581     expected_largest_payload += 3;
8582   }
8583   if (connection_.version().HasLongHeaderLengths()) {
8584     expected_largest_payload -= 2;
8585   }
8586   if (connection_.version().HasLengthPrefixedConnectionIds()) {
8587     expected_largest_payload -= 1;
8588   }
8589   if (connection_.version().UsesTls()) {
8590     // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
8591     EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
8592     QuicConfig config;
8593     QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
8594         &config, kMaxAcceptedDatagramFrameSize);
8595     EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8596     connection_.SetFromConfig(config);
8597     // Verify the value post-handshake.
8598     EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
8599               expected_largest_payload);
8600   } else {
8601     EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
8602               expected_largest_payload);
8603   }
8604 }
8605 
TEST_P(QuicConnectionTest,GetGuaranteedLargestMessagePayload)8606 TEST_P(QuicConnectionTest, GetGuaranteedLargestMessagePayload) {
8607   QuicPacketLength expected_largest_payload = 1215;
8608   if (connection_.version().HasLongHeaderLengths()) {
8609     expected_largest_payload -= 2;
8610   }
8611   if (connection_.version().HasLengthPrefixedConnectionIds()) {
8612     expected_largest_payload -= 1;
8613   }
8614   if (connection_.version().UsesTls()) {
8615     // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
8616     EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
8617     QuicConfig config;
8618     QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
8619         &config, kMaxAcceptedDatagramFrameSize);
8620     EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8621     connection_.SetFromConfig(config);
8622     // Verify the value post-handshake.
8623     EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
8624               expected_largest_payload);
8625   } else {
8626     EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
8627               expected_largest_payload);
8628   }
8629 }
8630 
TEST_P(QuicConnectionTest,LimitedLargestMessagePayload)8631 TEST_P(QuicConnectionTest, LimitedLargestMessagePayload) {
8632   if (!connection_.version().UsesTls()) {
8633     return;
8634   }
8635   constexpr QuicPacketLength kFrameSizeLimit = 1000;
8636   constexpr QuicPacketLength kPayloadSizeLimit =
8637       kFrameSizeLimit - kQuicFrameTypeSize;
8638   // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
8639   EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
8640   EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
8641   QuicConfig config;
8642   QuicConfigPeer::SetReceivedMaxDatagramFrameSize(&config, kFrameSizeLimit);
8643   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8644   connection_.SetFromConfig(config);
8645   // Verify the value post-handshake.
8646   EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), kPayloadSizeLimit);
8647   EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
8648             kPayloadSizeLimit);
8649 }
8650 
8651 // Test to check that the path challenge/path response logic works
8652 // correctly. This test is only for version-99
TEST_P(QuicConnectionTest,ServerResponseToPathChallenge)8653 TEST_P(QuicConnectionTest, ServerResponseToPathChallenge) {
8654   if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
8655     return;
8656   }
8657   PathProbeTestInit(Perspective::IS_SERVER);
8658   QuicConnectionPeer::SetAddressValidated(&connection_);
8659   // First check if the server can send probing packet.
8660   QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8661 
8662   // Create and send the probe request (PATH_CHALLENGE frame).
8663   // SendConnectivityProbingPacket ends up calling
8664   // TestPacketWriter::WritePacket() which in turns receives and parses the
8665   // packet by calling framer_.ProcessPacket() -- which in turn calls
8666   // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
8667   // the packet in writer_->path_challenge_frames()
8668   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8669   connection_.SendConnectivityProbingPacket(writer_.get(),
8670                                             connection_.peer_address());
8671   // Save the random contents of the challenge for later comparison to the
8672   // response.
8673   ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
8674   QuicPathFrameBuffer challenge_data =
8675       writer_->path_challenge_frames().front().data_buffer;
8676 
8677   // Normally, QuicConnection::OnPathChallengeFrame and OnPaddingFrame would be
8678   // called and it will perform actions to ensure that the rest of the protocol
8679   // is performed.
8680   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8681   EXPECT_TRUE(connection_.OnPathChallengeFrame(
8682       writer_->path_challenge_frames().front()));
8683   EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
8684   creator_->FlushCurrentPacket();
8685 
8686   // The final check is to ensure that the random data in the response matches
8687   // the random data from the challenge.
8688   EXPECT_EQ(1u, writer_->path_response_frames().size());
8689   EXPECT_EQ(0, memcmp(&challenge_data,
8690                       &(writer_->path_response_frames().front().data_buffer),
8691                       sizeof(challenge_data)));
8692 }
8693 
TEST_P(QuicConnectionTest,ClientResponseToPathChallengeOnDefaulSocket)8694 TEST_P(QuicConnectionTest, ClientResponseToPathChallengeOnDefaulSocket) {
8695   if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
8696     return;
8697   }
8698   PathProbeTestInit(Perspective::IS_CLIENT);
8699   // First check if the client can send probing packet.
8700   QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8701 
8702   // Create and send the probe request (PATH_CHALLENGE frame).
8703   // SendConnectivityProbingPacket ends up calling
8704   // TestPacketWriter::WritePacket() which in turns receives and parses the
8705   // packet by calling framer_.ProcessPacket() -- which in turn calls
8706   // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
8707   // the packet in writer_->path_challenge_frames()
8708   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8709   connection_.SendConnectivityProbingPacket(writer_.get(),
8710                                             connection_.peer_address());
8711   // Save the random contents of the challenge for later validation against the
8712   // response.
8713   ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
8714   QuicPathFrameBuffer challenge_data =
8715       writer_->path_challenge_frames().front().data_buffer;
8716 
8717   // Normally, QuicConnection::OnPathChallengeFrame would be
8718   // called and it will perform actions to ensure that the rest of the protocol
8719   // is performed.
8720   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8721   EXPECT_TRUE(connection_.OnPathChallengeFrame(
8722       writer_->path_challenge_frames().front()));
8723   EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
8724   creator_->FlushCurrentPacket();
8725 
8726   // The final check is to ensure that the random data in the response matches
8727   // the random data from the challenge.
8728   EXPECT_EQ(1u, writer_->path_response_frames().size());
8729   EXPECT_EQ(0, memcmp(&challenge_data,
8730                       &(writer_->path_response_frames().front().data_buffer),
8731                       sizeof(challenge_data)));
8732 }
8733 
TEST_P(QuicConnectionTest,ClientResponseToPathChallengeOnAlternativeSocket)8734 TEST_P(QuicConnectionTest, ClientResponseToPathChallengeOnAlternativeSocket) {
8735   if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
8736     return;
8737   }
8738   PathProbeTestInit(Perspective::IS_CLIENT);
8739   QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8740 
8741   QuicSocketAddress kNewSelfAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
8742   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
8743   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
8744       .Times(AtLeast(1u))
8745       .WillOnce(Invoke([&]() {
8746         EXPECT_EQ(1u, new_writer.packets_write_attempts());
8747         EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
8748         EXPECT_EQ(1u, new_writer.padding_frames().size());
8749         EXPECT_EQ(kNewSelfAddress.host(),
8750                   new_writer.last_write_source_address());
8751       }));
8752   bool success = false;
8753   connection_.ValidatePath(
8754       std::make_unique<TestQuicPathValidationContext>(
8755           kNewSelfAddress, connection_.peer_address(), &new_writer),
8756       std::make_unique<TestValidationResultDelegate>(
8757           &connection_, kNewSelfAddress, connection_.peer_address(), &success),
8758       PathValidationReason::kReasonUnknown);
8759 
8760   // Receiving a PATH_CHALLENGE on the alternative path. Response to this
8761   // PATH_CHALLENGE should be sent via the alternative writer.
8762   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
8763       .Times(AtLeast(1u))
8764       .WillOnce(Invoke([&]() {
8765         EXPECT_EQ(2u, new_writer.packets_write_attempts());
8766         EXPECT_EQ(1u, new_writer.path_response_frames().size());
8767         EXPECT_EQ(1u, new_writer.padding_frames().size());
8768         EXPECT_EQ(kNewSelfAddress.host(),
8769                   new_writer.last_write_source_address());
8770       }));
8771   std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
8772   std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
8773       QuicEncryptedPacket(probing_packet->encrypted_buffer,
8774                           probing_packet->encrypted_length),
8775       clock_.Now()));
8776   ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
8777 
8778   QuicSocketAddress kNewerSelfAddress(QuicIpAddress::Loopback6(),
8779                                       /*port=*/34567);
8780   // Receiving a PATH_CHALLENGE on an unknown socket should be ignored.
8781   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
8782   ProcessReceivedPacket(kNewerSelfAddress, kPeerAddress, *received);
8783 }
8784 
TEST_P(QuicConnectionTest,RestartPathDegradingDetectionAfterMigrationWithProbe)8785 TEST_P(QuicConnectionTest,
8786        RestartPathDegradingDetectionAfterMigrationWithProbe) {
8787   if (!version().HasIetfQuicFrames() &&
8788       GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
8789     return;
8790   }
8791   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8792   PathProbeTestInit(Perspective::IS_CLIENT);
8793 
8794   // Send data and verify the path degrading detection is set.
8795   const char data[] = "data";
8796   size_t data_size = strlen(data);
8797   QuicStreamOffset offset = 0;
8798   connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8799   offset += data_size;
8800 
8801   // Verify the path degrading detection is in progress.
8802   EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
8803   EXPECT_FALSE(connection_.IsPathDegrading());
8804   QuicTime ddl = connection_.GetBlackholeDetectorAlarm()->deadline();
8805 
8806   // Simulate the firing of path degrading.
8807   clock_.AdvanceTime(ddl - clock_.ApproximateNow());
8808   EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
8809   connection_.PathDegradingTimeout();
8810   EXPECT_TRUE(connection_.IsPathDegrading());
8811   EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
8812 
8813   if (!GetParam().version.HasIetfQuicFrames()) {
8814     // Simulate path degrading handling by sending a probe on an alternet path.
8815     clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8816     TestPacketWriter probing_writer(version(), &clock_, Perspective::IS_CLIENT);
8817     connection_.SendConnectivityProbingPacket(&probing_writer,
8818                                               connection_.peer_address());
8819     // Verify that path degrading detection is not reset.
8820     EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
8821 
8822     // Simulate successful path degrading handling by receiving probe response.
8823     clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
8824 
8825     EXPECT_CALL(visitor_,
8826                 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
8827         .Times(1);
8828     const QuicSocketAddress kNewSelfAddress =
8829         QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
8830 
8831     std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
8832     std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
8833         QuicEncryptedPacket(probing_packet->encrypted_buffer,
8834                             probing_packet->encrypted_length),
8835         clock_.Now()));
8836     uint64_t num_probing_received =
8837         connection_.GetStats().num_connectivity_probing_received;
8838     ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
8839 
8840     EXPECT_EQ(num_probing_received +
8841                   (GetQuicReloadableFlag(quic_ignore_gquic_probing) ? 0u : 1u),
8842               connection_.GetStats().num_connectivity_probing_received);
8843     EXPECT_EQ(kPeerAddress, connection_.peer_address());
8844     EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
8845     EXPECT_TRUE(connection_.IsPathDegrading());
8846   }
8847 
8848   // Verify new path degrading detection is activated.
8849   EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(1);
8850   connection_.OnSuccessfulMigration(/*is_port_change*/ true);
8851   EXPECT_FALSE(connection_.IsPathDegrading());
8852   EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
8853 }
8854 
TEST_P(QuicConnectionTest,ClientsResetCwndAfterConnectionMigration)8855 TEST_P(QuicConnectionTest, ClientsResetCwndAfterConnectionMigration) {
8856   if (!GetParam().version.HasIetfQuicFrames()) {
8857     return;
8858   }
8859   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8860   PathProbeTestInit(Perspective::IS_CLIENT);
8861   EXPECT_EQ(kSelfAddress, connection_.self_address());
8862 
8863   RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
8864   QuicTime::Delta default_init_rtt = rtt_stats->initial_rtt();
8865   rtt_stats->set_initial_rtt(default_init_rtt * 2);
8866   EXPECT_EQ(2 * default_init_rtt, rtt_stats->initial_rtt());
8867 
8868   QuicSentPacketManagerPeer::SetConsecutivePtoCount(manager_, 1);
8869   EXPECT_EQ(1u, manager_->GetConsecutivePtoCount());
8870   const SendAlgorithmInterface* send_algorithm = manager_->GetSendAlgorithm();
8871 
8872   // Migrate to a new address with different IP.
8873   const QuicSocketAddress kNewSelfAddress =
8874       QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
8875   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
8876   connection_.MigratePath(kNewSelfAddress, connection_.peer_address(),
8877                           &new_writer, false);
8878   EXPECT_EQ(default_init_rtt, manager_->GetRttStats()->initial_rtt());
8879   EXPECT_EQ(0u, manager_->GetConsecutivePtoCount());
8880   EXPECT_NE(send_algorithm, manager_->GetSendAlgorithm());
8881 }
8882 
8883 // Regression test for b/110259444
TEST_P(QuicConnectionTest,DoNotScheduleSpuriousAckAlarm)8884 TEST_P(QuicConnectionTest, DoNotScheduleSpuriousAckAlarm) {
8885   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8886   EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
8887   writer_->SetWriteBlocked();
8888 
8889   ProcessPacket(1);
8890   // Verify ack alarm is set.
8891   EXPECT_TRUE(connection_.HasPendingAcks());
8892   // Fire the ack alarm, verify no packet is sent because the writer is blocked.
8893   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8894   connection_.GetAckAlarm()->Fire();
8895 
8896   writer_->SetWritable();
8897   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8898   ProcessPacket(2);
8899   // Verify ack alarm is not set.
8900   EXPECT_FALSE(connection_.HasPendingAcks());
8901 }
8902 
TEST_P(QuicConnectionTest,DisablePacingOffloadConnectionOptions)8903 TEST_P(QuicConnectionTest, DisablePacingOffloadConnectionOptions) {
8904   EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8905   writer_->set_supports_release_time(true);
8906   QuicConfig config;
8907   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8908   connection_.SetFromConfig(config);
8909   EXPECT_TRUE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8910 
8911   QuicTagVector connection_options;
8912   connection_options.push_back(kNPCO);
8913   config.SetConnectionOptionsToSend(connection_options);
8914   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8915   connection_.SetFromConfig(config);
8916   // Verify pacing offload is disabled.
8917   EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8918 }
8919 
8920 // Regression test for b/110259444
8921 // Get a path response without having issued a path challenge...
TEST_P(QuicConnectionTest,OrphanPathResponse)8922 TEST_P(QuicConnectionTest, OrphanPathResponse) {
8923   QuicPathFrameBuffer data = {{0, 1, 2, 3, 4, 5, 6, 7}};
8924 
8925   QuicPathResponseFrame frame(99, data);
8926   EXPECT_TRUE(connection_.OnPathResponseFrame(frame));
8927   // If PATH_RESPONSE was accepted (payload matches the payload saved
8928   // in QuicConnection::transmitted_connectivity_probe_payload_) then
8929   // current_packet_content_ would be set to FIRST_FRAME_IS_PING.
8930   // Since this PATH_RESPONSE does not match, current_packet_content_
8931   // must not be FIRST_FRAME_IS_PING.
8932   EXPECT_NE(QuicConnection::FIRST_FRAME_IS_PING,
8933             QuicConnectionPeer::GetCurrentPacketContent(&connection_));
8934 }
8935 
TEST_P(QuicConnectionTest,AcceptPacketNumberZero)8936 TEST_P(QuicConnectionTest, AcceptPacketNumberZero) {
8937   if (!VersionHasIetfQuicFrames(version().transport_version)) {
8938     return;
8939   }
8940   // Set first_sending_packet_number to be 0 to allow successfully processing
8941   // acks which ack packet number 0.
8942   QuicFramerPeer::SetFirstSendingPacketNumber(writer_->framer()->framer(), 0);
8943   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8944 
8945   ProcessPacket(0);
8946   EXPECT_EQ(QuicPacketNumber(0), LargestAcked(connection_.ack_frame()));
8947   EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
8948 
8949   ProcessPacket(1);
8950   EXPECT_EQ(QuicPacketNumber(1), LargestAcked(connection_.ack_frame()));
8951   EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
8952 
8953   ProcessPacket(2);
8954   EXPECT_EQ(QuicPacketNumber(2), LargestAcked(connection_.ack_frame()));
8955   EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
8956 }
8957 
TEST_P(QuicConnectionTest,MultiplePacketNumberSpacesBasicSending)8958 TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicSending) {
8959   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8960     return;
8961   }
8962   connection_.SendCryptoStreamData();
8963   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8964   EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8965   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
8966   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8967   QuicAckFrame frame1 = InitAckFrame(1);
8968   // Received ACK for packet 1.
8969   ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
8970 
8971   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
8972   connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8973                                          NO_FIN);
8974   connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
8975                                          NO_FIN);
8976   connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
8977                                          8, NO_FIN);
8978   connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
8979                                          12, FIN);
8980   // Received ACK for packets 2, 4, 5.
8981   EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8982   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
8983   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8984   QuicAckFrame frame2 =
8985       InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
8986                     {QuicPacketNumber(4), QuicPacketNumber(6)}});
8987   // Make sure although the same packet number is used, but they are in
8988   // different packet number spaces.
8989   ProcessFramePacketAtLevel(30, QuicFrame(&frame2), ENCRYPTION_FORWARD_SECURE);
8990 }
8991 
TEST_P(QuicConnectionTest,PeerAcksPacketsInWrongPacketNumberSpace)8992 TEST_P(QuicConnectionTest, PeerAcksPacketsInWrongPacketNumberSpace) {
8993   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8994     return;
8995   }
8996   connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
8997                            std::make_unique<TaggingEncrypter>(0x01));
8998 
8999   connection_.SendCryptoStreamData();
9000   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9001   EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9002   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
9003   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9004   QuicAckFrame frame1 = InitAckFrame(1);
9005   // Received ACK for packet 1.
9006   ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9007 
9008   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9009   connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9010                                          NO_FIN);
9011   connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
9012                                          NO_FIN);
9013 
9014   // Received ACK for packets 2 and 3 in wrong packet number space.
9015   QuicAckFrame invalid_ack =
9016       InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(4)}});
9017   EXPECT_CALL(visitor_,
9018               OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9019   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
9020   ProcessFramePacketAtLevel(300, QuicFrame(&invalid_ack), ENCRYPTION_INITIAL);
9021   TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
9022 }
9023 
TEST_P(QuicConnectionTest,MultiplePacketNumberSpacesBasicReceiving)9024 TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicReceiving) {
9025   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9026     return;
9027   }
9028   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9029   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9030     EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9031   }
9032   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9033   // Receives packet 1000 in initial data.
9034   ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
9035   EXPECT_TRUE(connection_.HasPendingAcks());
9036   peer_framer_.SetEncrypter(
9037       ENCRYPTION_FORWARD_SECURE,
9038       std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
9039   SetDecrypter(
9040       ENCRYPTION_FORWARD_SECURE,
9041       std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
9042   // Receives packet 1000 in application data.
9043   ProcessDataPacketAtLevel(1000, false, ENCRYPTION_FORWARD_SECURE);
9044   EXPECT_TRUE(connection_.HasPendingAcks());
9045   connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
9046                                          0, NO_FIN);
9047   // Verify application data ACK gets bundled with outgoing data.
9048   EXPECT_EQ(2u, writer_->frame_count());
9049   // Make sure ACK alarm is still set because initial data is not ACKed.
9050   EXPECT_TRUE(connection_.HasPendingAcks());
9051   // Receive packet 1001 in application data.
9052   ProcessDataPacketAtLevel(1001, false, ENCRYPTION_FORWARD_SECURE);
9053   clock_.AdvanceTime(DefaultRetransmissionTime());
9054   // Simulates ACK alarm fires and verify two ACKs are flushed.
9055   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9056   connection_.SetEncrypter(
9057       ENCRYPTION_FORWARD_SECURE,
9058       std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
9059   connection_.GetAckAlarm()->Fire();
9060   EXPECT_FALSE(connection_.HasPendingAcks());
9061   // Receives more packets in application data.
9062   ProcessDataPacketAtLevel(1002, false, ENCRYPTION_FORWARD_SECURE);
9063   EXPECT_TRUE(connection_.HasPendingAcks());
9064 
9065   // Verify zero rtt and forward secure packets get acked in the same packet.
9066   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9067   ProcessDataPacket(1003);
9068   EXPECT_FALSE(connection_.HasPendingAcks());
9069 }
9070 
TEST_P(QuicConnectionTest,CancelAckAlarmOnWriteBlocked)9071 TEST_P(QuicConnectionTest, CancelAckAlarmOnWriteBlocked) {
9072   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9073     return;
9074   }
9075   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9076   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9077     EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9078   }
9079   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9080   // Receives packet 1000 in initial data.
9081   ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
9082   EXPECT_TRUE(connection_.HasPendingAcks());
9083   peer_framer_.SetEncrypter(
9084       ENCRYPTION_ZERO_RTT,
9085       std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
9086   SetDecrypter(ENCRYPTION_ZERO_RTT,
9087                std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
9088   // Receives packet 1000 in application data.
9089   ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
9090   EXPECT_TRUE(connection_.HasPendingAcks());
9091 
9092   writer_->SetWriteBlocked();
9093   EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber());
9094   // Simulates ACK alarm fires and verify no ACK is flushed because of write
9095   // blocked.
9096   clock_.AdvanceTime(DefaultDelayedAckTime());
9097   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9098   connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
9099                            std::make_unique<TaggingEncrypter>(0x02));
9100   connection_.GetAckAlarm()->Fire();
9101   // Verify ACK alarm is not set.
9102   EXPECT_FALSE(connection_.HasPendingAcks());
9103 
9104   writer_->SetWritable();
9105   // Verify 2 ACKs are sent when connection gets unblocked.
9106   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9107   connection_.OnCanWrite();
9108   EXPECT_FALSE(connection_.HasPendingAcks());
9109 }
9110 
9111 // Make sure a packet received with the right client connection ID is processed.
TEST_P(QuicConnectionTest,ValidClientConnectionId)9112 TEST_P(QuicConnectionTest, ValidClientConnectionId) {
9113   if (!framer_.version().SupportsClientConnectionIds()) {
9114     return;
9115   }
9116   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9117   SetClientConnectionId(TestConnectionId(0x33));
9118   QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9119   header.destination_connection_id = TestConnectionId(0x33);
9120   header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9121   header.source_connection_id_included = CONNECTION_ID_ABSENT;
9122   QuicFrames frames;
9123   QuicPingFrame ping_frame;
9124   QuicPaddingFrame padding_frame;
9125   frames.push_back(QuicFrame(ping_frame));
9126   frames.push_back(QuicFrame(padding_frame));
9127   std::unique_ptr<QuicPacket> packet =
9128       BuildUnsizedDataPacket(&peer_framer_, header, frames);
9129   char buffer[kMaxOutgoingPacketSize];
9130   size_t encrypted_length = peer_framer_.EncryptPayload(
9131       ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9132       kMaxOutgoingPacketSize);
9133   QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9134                                      false);
9135   EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9136   ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9137   EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9138 }
9139 
9140 // Make sure a packet received with a different client connection ID is dropped.
TEST_P(QuicConnectionTest,InvalidClientConnectionId)9141 TEST_P(QuicConnectionTest, InvalidClientConnectionId) {
9142   if (!framer_.version().SupportsClientConnectionIds()) {
9143     return;
9144   }
9145   SetClientConnectionId(TestConnectionId(0x33));
9146   QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9147   header.destination_connection_id = TestConnectionId(0xbad);
9148   header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9149   header.source_connection_id_included = CONNECTION_ID_ABSENT;
9150   QuicFrames frames;
9151   QuicPingFrame ping_frame;
9152   QuicPaddingFrame padding_frame;
9153   frames.push_back(QuicFrame(ping_frame));
9154   frames.push_back(QuicFrame(padding_frame));
9155   std::unique_ptr<QuicPacket> packet =
9156       BuildUnsizedDataPacket(&peer_framer_, header, frames);
9157   char buffer[kMaxOutgoingPacketSize];
9158   size_t encrypted_length = peer_framer_.EncryptPayload(
9159       ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9160       kMaxOutgoingPacketSize);
9161   QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9162                                      false);
9163   EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9164   ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9165   EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
9166 }
9167 
9168 // Make sure the first packet received with a different client connection ID on
9169 // the server is processed and it changes the client connection ID.
TEST_P(QuicConnectionTest,UpdateClientConnectionIdFromFirstPacket)9170 TEST_P(QuicConnectionTest, UpdateClientConnectionIdFromFirstPacket) {
9171   if (!framer_.version().SupportsClientConnectionIds()) {
9172     return;
9173   }
9174   set_perspective(Perspective::IS_SERVER);
9175   QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL);
9176   header.source_connection_id = TestConnectionId(0x33);
9177   header.source_connection_id_included = CONNECTION_ID_PRESENT;
9178   QuicFrames frames;
9179   QuicPingFrame ping_frame;
9180   QuicPaddingFrame padding_frame;
9181   frames.push_back(QuicFrame(ping_frame));
9182   frames.push_back(QuicFrame(padding_frame));
9183   std::unique_ptr<QuicPacket> packet =
9184       BuildUnsizedDataPacket(&peer_framer_, header, frames);
9185   char buffer[kMaxOutgoingPacketSize];
9186   size_t encrypted_length =
9187       peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1),
9188                                   *packet, buffer, kMaxOutgoingPacketSize);
9189   QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9190                                      false);
9191   EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9192   ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9193   EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9194   EXPECT_EQ(TestConnectionId(0x33), connection_.client_connection_id());
9195 }
TestReplaceConnectionIdFromInitial()9196 void QuicConnectionTest::TestReplaceConnectionIdFromInitial() {
9197   if (!framer_.version().AllowsVariableLengthConnectionIds()) {
9198     return;
9199   }
9200   // We start with a known connection ID.
9201   EXPECT_TRUE(connection_.connected());
9202   EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9203   EXPECT_NE(TestConnectionId(0x33), connection_.connection_id());
9204   // Receiving an initial can replace the connection ID once.
9205   {
9206     QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL);
9207     header.source_connection_id = TestConnectionId(0x33);
9208     header.source_connection_id_included = CONNECTION_ID_PRESENT;
9209     QuicFrames frames;
9210     QuicPingFrame ping_frame;
9211     QuicPaddingFrame padding_frame;
9212     frames.push_back(QuicFrame(ping_frame));
9213     frames.push_back(QuicFrame(padding_frame));
9214     std::unique_ptr<QuicPacket> packet =
9215         BuildUnsizedDataPacket(&peer_framer_, header, frames);
9216     char buffer[kMaxOutgoingPacketSize];
9217     size_t encrypted_length =
9218         peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1),
9219                                     *packet, buffer, kMaxOutgoingPacketSize);
9220     QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9221                                        false);
9222     ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9223   }
9224   EXPECT_TRUE(connection_.connected());
9225   EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9226   EXPECT_EQ(TestConnectionId(0x33), connection_.connection_id());
9227   // Trying to replace the connection ID a second time drops the packet.
9228   {
9229     QuicPacketHeader header = ConstructPacketHeader(2, ENCRYPTION_INITIAL);
9230     header.source_connection_id = TestConnectionId(0x66);
9231     header.source_connection_id_included = CONNECTION_ID_PRESENT;
9232     QuicFrames frames;
9233     QuicPingFrame ping_frame;
9234     QuicPaddingFrame padding_frame;
9235     frames.push_back(QuicFrame(ping_frame));
9236     frames.push_back(QuicFrame(padding_frame));
9237     std::unique_ptr<QuicPacket> packet =
9238         BuildUnsizedDataPacket(&peer_framer_, header, frames);
9239     char buffer[kMaxOutgoingPacketSize];
9240     size_t encrypted_length =
9241         peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(2),
9242                                     *packet, buffer, kMaxOutgoingPacketSize);
9243     QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9244                                        false);
9245     ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9246   }
9247   EXPECT_TRUE(connection_.connected());
9248   EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
9249   EXPECT_EQ(TestConnectionId(0x33), connection_.connection_id());
9250 }
9251 
TEST_P(QuicConnectionTest,ReplaceServerConnectionIdFromInitial)9252 TEST_P(QuicConnectionTest, ReplaceServerConnectionIdFromInitial) {
9253   TestReplaceConnectionIdFromInitial();
9254 }
9255 
TEST_P(QuicConnectionTest,ReplaceServerConnectionIdFromRetryAndInitial)9256 TEST_P(QuicConnectionTest, ReplaceServerConnectionIdFromRetryAndInitial) {
9257   // First make the connection process a RETRY and replace the server connection
9258   // ID a first time.
9259   TestClientRetryHandling(/*invalid_retry_tag=*/false,
9260                           /*missing_original_id_in_config=*/false,
9261                           /*wrong_original_id_in_config=*/false,
9262                           /*missing_retry_id_in_config=*/false,
9263                           /*wrong_retry_id_in_config=*/false);
9264   // Reset the test framer to use the right connection ID.
9265   peer_framer_.SetInitialObfuscators(connection_.connection_id());
9266   // Now process an INITIAL and replace the server connection ID a second time.
9267   TestReplaceConnectionIdFromInitial();
9268 }
9269 
9270 // Regression test for b/134416344.
TEST_P(QuicConnectionTest,CheckConnectedBeforeFlush)9271 TEST_P(QuicConnectionTest, CheckConnectedBeforeFlush) {
9272   // This test mimics a scenario where a connection processes 2 packets and the
9273   // 2nd packet contains connection close frame. When the 2nd flusher goes out
9274   // of scope, a delayed ACK is pending, and ACK alarm should not be scheduled
9275   // because connection is disconnected.
9276   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9277   EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
9278   EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
9279   const QuicErrorCode kErrorCode = QUIC_INTERNAL_ERROR;
9280   std::unique_ptr<QuicConnectionCloseFrame> connection_close_frame(
9281       new QuicConnectionCloseFrame(connection_.transport_version(), kErrorCode,
9282                                    NO_IETF_QUIC_ERROR, "",
9283                                    /*transport_close_frame_type=*/0));
9284 
9285   // Received 2 packets.
9286   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9287     EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9288   } else {
9289     EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9290   }
9291   ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
9292                                   ENCRYPTION_INITIAL);
9293   EXPECT_TRUE(connection_.HasPendingAcks());
9294   ProcessFramePacketWithAddresses(QuicFrame(connection_close_frame.release()),
9295                                   kSelfAddress, kPeerAddress,
9296                                   ENCRYPTION_INITIAL);
9297   // Verify ack alarm is not set.
9298   EXPECT_FALSE(connection_.HasPendingAcks());
9299 }
9300 
9301 // Verify that a packet containing three coalesced packets is parsed correctly.
TEST_P(QuicConnectionTest,CoalescedPacket)9302 TEST_P(QuicConnectionTest, CoalescedPacket) {
9303   if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9304     // Coalesced packets can only be encoded using long header lengths.
9305     return;
9306   }
9307   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9308   EXPECT_TRUE(connection_.connected());
9309   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9310     EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
9311   } else {
9312     EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
9313   }
9314 
9315   uint64_t packet_numbers[3] = {1, 2, 3};
9316   EncryptionLevel encryption_levels[3] = {
9317       ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9318   char buffer[kMaxOutgoingPacketSize] = {};
9319   size_t total_encrypted_length = 0;
9320   for (int i = 0; i < 3; i++) {
9321     QuicPacketHeader header =
9322         ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9323     QuicFrames frames;
9324     if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9325       frames.push_back(QuicFrame(&crypto_frame_));
9326     } else {
9327       frames.push_back(QuicFrame(frame1_));
9328     }
9329     std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9330     peer_creator_.set_encryption_level(encryption_levels[i]);
9331     size_t encrypted_length = peer_framer_.EncryptPayload(
9332         encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9333         buffer + total_encrypted_length,
9334         sizeof(buffer) - total_encrypted_length);
9335     EXPECT_GT(encrypted_length, 0u);
9336     total_encrypted_length += encrypted_length;
9337   }
9338   connection_.ProcessUdpPacket(
9339       kSelfAddress, kPeerAddress,
9340       QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9341   if (connection_.GetSendAlarm()->IsSet()) {
9342     connection_.GetSendAlarm()->Fire();
9343   }
9344 
9345   EXPECT_TRUE(connection_.connected());
9346 }
9347 
9348 // Regression test for crbug.com/992831.
TEST_P(QuicConnectionTest,CoalescedPacketThatSavesFrames)9349 TEST_P(QuicConnectionTest, CoalescedPacketThatSavesFrames) {
9350   if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9351     // Coalesced packets can only be encoded using long header lengths.
9352     return;
9353   }
9354   if (connection_.SupportsMultiplePacketNumberSpaces()) {
9355     // TODO(b/129151114) Enable this test with multiple packet number spaces.
9356     return;
9357   }
9358   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9359   EXPECT_TRUE(connection_.connected());
9360   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9361     EXPECT_CALL(visitor_, OnCryptoFrame(_))
9362         .Times(3)
9363         .WillRepeatedly([this](const QuicCryptoFrame& /*frame*/) {
9364           // QuicFrame takes ownership of the QuicBlockedFrame.
9365           connection_.SendControlFrame(QuicFrame(QuicBlockedFrame(1, 3, 0)));
9366         });
9367   } else {
9368     EXPECT_CALL(visitor_, OnStreamFrame(_))
9369         .Times(3)
9370         .WillRepeatedly([this](const QuicStreamFrame& /*frame*/) {
9371           // QuicFrame takes ownership of the QuicBlockedFrame.
9372           connection_.SendControlFrame(QuicFrame(QuicBlockedFrame(1, 3, 0)));
9373         });
9374   }
9375 
9376   uint64_t packet_numbers[3] = {1, 2, 3};
9377   EncryptionLevel encryption_levels[3] = {
9378       ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9379   char buffer[kMaxOutgoingPacketSize] = {};
9380   size_t total_encrypted_length = 0;
9381   for (int i = 0; i < 3; i++) {
9382     QuicPacketHeader header =
9383         ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9384     QuicFrames frames;
9385     if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9386       frames.push_back(QuicFrame(&crypto_frame_));
9387     } else {
9388       frames.push_back(QuicFrame(frame1_));
9389     }
9390     std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9391     peer_creator_.set_encryption_level(encryption_levels[i]);
9392     size_t encrypted_length = peer_framer_.EncryptPayload(
9393         encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9394         buffer + total_encrypted_length,
9395         sizeof(buffer) - total_encrypted_length);
9396     EXPECT_GT(encrypted_length, 0u);
9397     total_encrypted_length += encrypted_length;
9398   }
9399   connection_.ProcessUdpPacket(
9400       kSelfAddress, kPeerAddress,
9401       QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9402   if (connection_.GetSendAlarm()->IsSet()) {
9403     connection_.GetSendAlarm()->Fire();
9404   }
9405 
9406   EXPECT_TRUE(connection_.connected());
9407 
9408   SendAckPacketToPeer();
9409 }
9410 
9411 // Regresstion test for b/138962304.
TEST_P(QuicConnectionTest,RtoAndWriteBlocked)9412 TEST_P(QuicConnectionTest, RtoAndWriteBlocked) {
9413   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9414 
9415   QuicStreamId stream_id = 2;
9416   QuicPacketNumber last_data_packet;
9417   SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9418   EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9419 
9420   // Writer gets blocked.
9421   writer_->SetWriteBlocked();
9422 
9423   // Cancel the stream.
9424   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9425   EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9426   EXPECT_CALL(visitor_, WillingAndAbleToWrite())
9427       .WillRepeatedly(
9428           Invoke(&notifier_, &SimpleSessionNotifier::WillingToWrite));
9429   SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9430 
9431   // Retransmission timer fires in RTO mode.
9432   connection_.GetRetransmissionAlarm()->Fire();
9433   // Verify no packets get flushed when writer is blocked.
9434   EXPECT_EQ(0u, connection_.NumQueuedPackets());
9435 }
9436 
9437 // Regresstion test for b/138962304.
TEST_P(QuicConnectionTest,PtoAndWriteBlocked)9438 TEST_P(QuicConnectionTest, PtoAndWriteBlocked) {
9439   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9440 
9441   QuicStreamId stream_id = 2;
9442   QuicPacketNumber last_data_packet;
9443   SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9444   SendStreamDataToPeer(4, "foo", 0, NO_FIN, &last_data_packet);
9445   EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9446 
9447   // Writer gets blocked.
9448   writer_->SetWriteBlocked();
9449 
9450   // Cancel stream 2.
9451   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9452   EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9453   SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9454 
9455   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9456   // Retransmission timer fires in TLP mode.
9457   connection_.GetRetransmissionAlarm()->Fire();
9458   // Verify one packets is forced flushed when writer is blocked.
9459   EXPECT_EQ(1u, connection_.NumQueuedPackets());
9460 }
9461 
TEST_P(QuicConnectionTest,ProbeTimeout)9462 TEST_P(QuicConnectionTest, ProbeTimeout) {
9463   QuicConfig config;
9464   QuicTagVector connection_options;
9465   connection_options.push_back(k2PTO);
9466   config.SetConnectionOptionsToSend(connection_options);
9467   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9468   connection_.SetFromConfig(config);
9469   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9470 
9471   QuicStreamId stream_id = 2;
9472   QuicPacketNumber last_packet;
9473   SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
9474   SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
9475   EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9476 
9477   // Reset stream.
9478   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9479   SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9480 
9481   // Fire the PTO and verify only the RST_STREAM is resent, not stream data.
9482   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9483   connection_.GetRetransmissionAlarm()->Fire();
9484   EXPECT_EQ(0u, writer_->stream_frames().size());
9485   EXPECT_EQ(1u, writer_->rst_stream_frames().size());
9486   EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9487 }
9488 
TEST_P(QuicConnectionTest,CloseConnectionAfter6ClientPTOs)9489 TEST_P(QuicConnectionTest, CloseConnectionAfter6ClientPTOs) {
9490   QuicConfig config;
9491   QuicTagVector connection_options;
9492   connection_options.push_back(k1PTO);
9493   connection_options.push_back(k6PTO);
9494   config.SetConnectionOptionsToSend(connection_options);
9495   QuicConfigPeer::SetNegotiated(&config, true);
9496   if (connection_.version().UsesTls()) {
9497     QuicConfigPeer::SetReceivedOriginalConnectionId(
9498         &config, connection_.connection_id());
9499     QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9500         &config, connection_.connection_id());
9501   }
9502   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9503   connection_.SetFromConfig(config);
9504   if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
9505       GetQuicReloadableFlag(
9506           quic_no_path_degrading_before_handshake_confirmed)) {
9507     EXPECT_CALL(visitor_, GetHandshakeState())
9508         .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
9509   }
9510   connection_.OnHandshakeComplete();
9511   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9512 
9513   // Send stream data.
9514   SendStreamDataToPeer(
9515       GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9516       0, FIN, nullptr);
9517 
9518   // Fire the retransmission alarm 5 times.
9519   for (int i = 0; i < 5; ++i) {
9520     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9521     connection_.GetRetransmissionAlarm()->Fire();
9522     EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9523     EXPECT_TRUE(connection_.connected());
9524   }
9525   EXPECT_CALL(visitor_, OnPathDegrading());
9526   connection_.PathDegradingTimeout();
9527 
9528   EXPECT_EQ(5u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9529   // Closes connection on 6th PTO.
9530   // May send multiple connecction close packets with multiple PN spaces.
9531   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
9532   EXPECT_CALL(visitor_,
9533               OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9534   ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9535   connection_.GetBlackholeDetectorAlarm()->Fire();
9536   EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9537   EXPECT_FALSE(connection_.connected());
9538   TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9539 }
9540 
TEST_P(QuicConnectionTest,CloseConnectionAfter7ClientPTOs)9541 TEST_P(QuicConnectionTest, CloseConnectionAfter7ClientPTOs) {
9542   QuicConfig config;
9543   QuicTagVector connection_options;
9544   connection_options.push_back(k2PTO);
9545   connection_options.push_back(k7PTO);
9546   config.SetConnectionOptionsToSend(connection_options);
9547   QuicConfigPeer::SetNegotiated(&config, true);
9548   if (connection_.version().UsesTls()) {
9549     QuicConfigPeer::SetReceivedOriginalConnectionId(
9550         &config, connection_.connection_id());
9551     QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9552         &config, connection_.connection_id());
9553   }
9554   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9555   connection_.SetFromConfig(config);
9556   if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
9557       GetQuicReloadableFlag(
9558           quic_no_path_degrading_before_handshake_confirmed)) {
9559     EXPECT_CALL(visitor_, GetHandshakeState())
9560         .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
9561   }
9562   connection_.OnHandshakeComplete();
9563   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9564 
9565   // Send stream data.
9566   SendStreamDataToPeer(
9567       GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9568       0, FIN, nullptr);
9569 
9570   // Fire the retransmission alarm 6 times.
9571   for (int i = 0; i < 6; ++i) {
9572     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9573     connection_.GetRetransmissionAlarm()->Fire();
9574     EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9575     EXPECT_TRUE(connection_.connected());
9576   }
9577   EXPECT_CALL(visitor_, OnPathDegrading());
9578   connection_.PathDegradingTimeout();
9579 
9580   EXPECT_EQ(6u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9581   // Closes connection on 7th PTO.
9582   EXPECT_CALL(visitor_,
9583               OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9584   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
9585   ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9586   connection_.GetBlackholeDetectorAlarm()->Fire();
9587   EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9588   EXPECT_FALSE(connection_.connected());
9589   TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9590 }
9591 
TEST_P(QuicConnectionTest,CloseConnectionAfter8ClientPTOs)9592 TEST_P(QuicConnectionTest, CloseConnectionAfter8ClientPTOs) {
9593   QuicConfig config;
9594   QuicTagVector connection_options;
9595   connection_options.push_back(k2PTO);
9596   connection_options.push_back(k8PTO);
9597   QuicConfigPeer::SetNegotiated(&config, true);
9598   if (connection_.version().UsesTls()) {
9599     QuicConfigPeer::SetReceivedOriginalConnectionId(
9600         &config, connection_.connection_id());
9601     QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9602         &config, connection_.connection_id());
9603   }
9604   config.SetConnectionOptionsToSend(connection_options);
9605   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9606   connection_.SetFromConfig(config);
9607   if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
9608       GetQuicReloadableFlag(
9609           quic_no_path_degrading_before_handshake_confirmed)) {
9610     EXPECT_CALL(visitor_, GetHandshakeState())
9611         .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
9612   }
9613   connection_.OnHandshakeComplete();
9614   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9615 
9616   // Send stream data.
9617   SendStreamDataToPeer(
9618       GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9619       0, FIN, nullptr);
9620 
9621   // Fire the retransmission alarm 7 times.
9622   for (int i = 0; i < 7; ++i) {
9623     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9624     connection_.GetRetransmissionAlarm()->Fire();
9625     EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9626     EXPECT_TRUE(connection_.connected());
9627   }
9628   EXPECT_CALL(visitor_, OnPathDegrading());
9629   connection_.PathDegradingTimeout();
9630 
9631   EXPECT_EQ(7u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9632   // Closes connection on 8th PTO.
9633   EXPECT_CALL(visitor_,
9634               OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9635   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
9636   ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9637   connection_.GetBlackholeDetectorAlarm()->Fire();
9638   EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9639   EXPECT_FALSE(connection_.connected());
9640   TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9641 }
9642 
TEST_P(QuicConnectionTest,DeprecateHandshakeMode)9643 TEST_P(QuicConnectionTest, DeprecateHandshakeMode) {
9644   if (!connection_.version().SupportsAntiAmplificationLimit()) {
9645     return;
9646   }
9647   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9648   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9649 
9650   // Send CHLO.
9651   connection_.SendCryptoStreamData();
9652   EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9653 
9654   EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9655   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
9656   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9657   QuicAckFrame frame1 = InitAckFrame(1);
9658   // Received ACK for packet 1.
9659   ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9660 
9661   // Verify retransmission alarm is still set because handshake is not
9662   // confirmed although there is nothing in flight.
9663   EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9664   EXPECT_EQ(0u, connection_.GetStats().pto_count);
9665   EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
9666 
9667   // PTO fires, verify a PING packet gets sent because there is no data to send.
9668   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
9669   connection_.GetRetransmissionAlarm()->Fire();
9670   EXPECT_EQ(1u, connection_.GetStats().pto_count);
9671   EXPECT_EQ(1u, connection_.GetStats().crypto_retransmit_count);
9672   EXPECT_EQ(1u, writer_->ping_frames().size());
9673 }
9674 
TEST_P(QuicConnectionTest,AntiAmplificationLimit)9675 TEST_P(QuicConnectionTest, AntiAmplificationLimit) {
9676   if (!connection_.version().SupportsAntiAmplificationLimit() ||
9677       GetQuicFlag(quic_enforce_strict_amplification_factor)) {
9678     return;
9679   }
9680   EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9681 
9682   set_perspective(Perspective::IS_SERVER);
9683   // Verify no data can be sent at the beginning because bytes received is 0.
9684   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9685   connection_.SendCryptoDataWithString("foo", 0);
9686   EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
9687   EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
9688   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9689 
9690   // Receives packet 1.
9691   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9692   ForceWillingAndAbleToWriteOnceForDeferSending();
9693   ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9694 
9695   const size_t anti_amplification_factor =
9696       GetQuicFlag(quic_anti_amplification_factor);
9697   // Verify now packets can be sent.
9698   for (size_t i = 1; i < anti_amplification_factor; ++i) {
9699     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9700     connection_.SendCryptoDataWithString("foo", i * 3);
9701     // Verify retransmission alarm is not set if throttled by anti-amplification
9702     // limit.
9703     EXPECT_EQ(i != anti_amplification_factor - 1,
9704               connection_.GetRetransmissionAlarm()->IsSet());
9705   }
9706   // Verify server is throttled by anti-amplification limit.
9707   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9708   connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
9709 
9710   // Receives packet 2.
9711   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9712   ForceWillingAndAbleToWriteOnceForDeferSending();
9713   ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9714   // Verify more packets can be sent.
9715   for (size_t i = anti_amplification_factor + 1;
9716        i < anti_amplification_factor * 2; ++i) {
9717     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9718     connection_.SendCryptoDataWithString("foo", i * 3);
9719   }
9720   // Verify server is throttled by anti-amplification limit.
9721   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9722   connection_.SendCryptoDataWithString("foo",
9723                                        2 * anti_amplification_factor * 3);
9724 
9725   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9726   ForceWillingAndAbleToWriteOnceForDeferSending();
9727   ProcessPacket(3);
9728   // Verify anti-amplification limit is gone after address validation.
9729   for (size_t i = 0; i < 100; ++i) {
9730     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9731     connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
9732   }
9733 }
9734 
9735 TEST_P(QuicConnectionTest, 3AntiAmplificationLimit) {
9736   if (!connection_.version().SupportsAntiAmplificationLimit() ||
9737       GetQuicFlag(quic_enforce_strict_amplification_factor)) {
9738     return;
9739   }
9740   EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9741 
9742   set_perspective(Perspective::IS_SERVER);
9743   QuicConfig config;
9744   QuicTagVector connection_options;
9745   connection_options.push_back(k3AFF);
9746   config.SetInitialReceivedConnectionOptions(connection_options);
9747   if (connection_.version().UsesTls()) {
9748     QuicConfigPeer::SetReceivedOriginalConnectionId(
9749         &config, connection_.connection_id());
9750     QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
9751                                                          QuicConnectionId());
9752   }
9753   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9754   connection_.SetFromConfig(config);
9755 
9756   // Verify no data can be sent at the beginning because bytes received is 0.
9757   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9758   connection_.SendCryptoDataWithString("foo", 0);
9759   EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
9760   EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
9761   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9762 
9763   // Receives packet 1.
9764   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9765   ForceWillingAndAbleToWriteOnceForDeferSending();
9766   ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9767 
9768   const size_t anti_amplification_factor = 3;
9769   // Verify now packets can be sent.
9770   for (size_t i = 1; i < anti_amplification_factor; ++i) {
9771     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9772     connection_.SendCryptoDataWithString("foo", i * 3);
9773     // Verify retransmission alarm is not set if throttled by anti-amplification
9774     // limit.
9775     EXPECT_EQ(i != anti_amplification_factor - 1,
9776               connection_.GetRetransmissionAlarm()->IsSet());
9777   }
9778   // Verify server is throttled by anti-amplification limit.
9779   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9780   connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
9781 
9782   // Receives packet 2.
9783   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9784   ForceWillingAndAbleToWriteOnceForDeferSending();
9785   ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9786   // Verify more packets can be sent.
9787   for (size_t i = anti_amplification_factor + 1;
9788        i < anti_amplification_factor * 2; ++i) {
9789     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9790     connection_.SendCryptoDataWithString("foo", i * 3);
9791   }
9792   // Verify server is throttled by anti-amplification limit.
9793   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9794   connection_.SendCryptoDataWithString("foo",
9795                                        2 * anti_amplification_factor * 3);
9796 
9797   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9798   ForceWillingAndAbleToWriteOnceForDeferSending();
9799   ProcessPacket(3);
9800   // Verify anti-amplification limit is gone after address validation.
9801   for (size_t i = 0; i < 100; ++i) {
9802     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9803     connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
9804   }
9805 }
9806 
9807 TEST_P(QuicConnectionTest, 10AntiAmplificationLimit) {
9808   if (!connection_.version().SupportsAntiAmplificationLimit() ||
9809       GetQuicFlag(quic_enforce_strict_amplification_factor)) {
9810     return;
9811   }
9812   EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9813 
9814   set_perspective(Perspective::IS_SERVER);
9815   QuicConfig config;
9816   QuicTagVector connection_options;
9817   connection_options.push_back(k10AF);
9818   config.SetInitialReceivedConnectionOptions(connection_options);
9819   if (connection_.version().UsesTls()) {
9820     QuicConfigPeer::SetReceivedOriginalConnectionId(
9821         &config, connection_.connection_id());
9822     QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
9823                                                          QuicConnectionId());
9824   }
9825   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9826   connection_.SetFromConfig(config);
9827 
9828   // Verify no data can be sent at the beginning because bytes received is 0.
9829   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9830   connection_.SendCryptoDataWithString("foo", 0);
9831   EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
9832   EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
9833   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9834 
9835   // Receives packet 1.
9836   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9837   ForceWillingAndAbleToWriteOnceForDeferSending();
9838   ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9839 
9840   const size_t anti_amplification_factor = 10;
9841   // Verify now packets can be sent.
9842   for (size_t i = 1; i < anti_amplification_factor; ++i) {
9843     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9844     connection_.SendCryptoDataWithString("foo", i * 3);
9845     // Verify retransmission alarm is not set if throttled by anti-amplification
9846     // limit.
9847     EXPECT_EQ(i != anti_amplification_factor - 1,
9848               connection_.GetRetransmissionAlarm()->IsSet());
9849   }
9850   // Verify server is throttled by anti-amplification limit.
9851   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9852   connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
9853 
9854   // Receives packet 2.
9855   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9856   ForceWillingAndAbleToWriteOnceForDeferSending();
9857   ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9858   // Verify more packets can be sent.
9859   for (size_t i = anti_amplification_factor + 1;
9860        i < anti_amplification_factor * 2; ++i) {
9861     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9862     connection_.SendCryptoDataWithString("foo", i * 3);
9863   }
9864   // Verify server is throttled by anti-amplification limit.
9865   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9866   connection_.SendCryptoDataWithString("foo",
9867                                        2 * anti_amplification_factor * 3);
9868 
9869   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9870   ForceWillingAndAbleToWriteOnceForDeferSending();
9871   ProcessPacket(3);
9872   // Verify anti-amplification limit is gone after address validation.
9873   for (size_t i = 0; i < 100; ++i) {
9874     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9875     connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
9876   }
9877 }
9878 
TEST_P(QuicConnectionTest,AckPendingWithAmplificationLimited)9879 TEST_P(QuicConnectionTest, AckPendingWithAmplificationLimited) {
9880   if (!connection_.version().SupportsAntiAmplificationLimit()) {
9881     return;
9882   }
9883   EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9884   EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
9885   set_perspective(Perspective::IS_SERVER);
9886   connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
9887   // Receives packet 1.
9888   ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9889   connection_.SetEncrypter(
9890       ENCRYPTION_HANDSHAKE,
9891       std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
9892   connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
9893   EXPECT_TRUE(connection_.HasPendingAcks());
9894   // Send response in different encryption level and cause amplification factor
9895   // throttled.
9896   size_t i = 0;
9897   while (connection_.CanWrite(HAS_RETRANSMITTABLE_DATA)) {
9898     connection_.SendCryptoDataWithString(std::string(1024, 'a'), i * 1024,
9899                                          ENCRYPTION_HANDSHAKE);
9900     ++i;
9901   }
9902   // Verify ACK is still pending.
9903   EXPECT_TRUE(connection_.HasPendingAcks());
9904 
9905   // Fire ACK alarm and verify ACK cannot be sent due to amplification factor.
9906   clock_.AdvanceTime(connection_.GetAckAlarm()->deadline() - clock_.Now());
9907   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9908   connection_.GetAckAlarm()->Fire();
9909   // Verify ACK alarm is cancelled.
9910   EXPECT_FALSE(connection_.HasPendingAcks());
9911 
9912   // Receives packet 2 and verify ACK gets flushed.
9913   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9914   ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9915   EXPECT_FALSE(writer_->ack_frames().empty());
9916 }
9917 
TEST_P(QuicConnectionTest,ConnectionCloseFrameType)9918 TEST_P(QuicConnectionTest, ConnectionCloseFrameType) {
9919   if (!VersionHasIetfQuicFrames(version().transport_version)) {
9920     // Test relevent only for IETF QUIC.
9921     return;
9922   }
9923   const QuicErrorCode kQuicErrorCode = IETF_QUIC_PROTOCOL_VIOLATION;
9924   // Use the (unknown) frame type of 9999 to avoid triggering any logic
9925   // which might be associated with the processing of a known frame type.
9926   const uint64_t kTransportCloseFrameType = 9999u;
9927   QuicFramerPeer::set_current_received_frame_type(
9928       QuicConnectionPeer::GetFramer(&connection_), kTransportCloseFrameType);
9929   // Do a transport connection close
9930   EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
9931   connection_.CloseConnection(
9932       kQuicErrorCode, "Some random error message",
9933       ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
9934   const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
9935       writer_->connection_close_frames();
9936   ASSERT_EQ(1u, connection_close_frames.size());
9937   EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
9938             connection_close_frames[0].close_type);
9939   EXPECT_EQ(kQuicErrorCode, connection_close_frames[0].quic_error_code);
9940   EXPECT_EQ(kTransportCloseFrameType,
9941             connection_close_frames[0].transport_close_frame_type);
9942 }
9943 
TEST_P(QuicConnectionTest,PtoSkipsPacketNumber)9944 TEST_P(QuicConnectionTest, PtoSkipsPacketNumber) {
9945   QuicConfig config;
9946   QuicTagVector connection_options;
9947   connection_options.push_back(k1PTO);
9948   connection_options.push_back(kPTOS);
9949   config.SetConnectionOptionsToSend(connection_options);
9950   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9951   connection_.SetFromConfig(config);
9952   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9953 
9954   QuicStreamId stream_id = 2;
9955   QuicPacketNumber last_packet;
9956   SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
9957   SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
9958   EXPECT_EQ(QuicPacketNumber(2), last_packet);
9959   EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9960 
9961   // Fire PTO and verify the PTO retransmission skips one packet number.
9962   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9963   connection_.GetRetransmissionAlarm()->Fire();
9964   EXPECT_EQ(1u, writer_->stream_frames().size());
9965   EXPECT_EQ(QuicPacketNumber(4), writer_->last_packet_header().packet_number);
9966   EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9967 }
9968 
TEST_P(QuicConnectionTest,SendCoalescedPackets)9969 TEST_P(QuicConnectionTest, SendCoalescedPackets) {
9970   if (!connection_.version().CanSendCoalescedPackets()) {
9971     return;
9972   }
9973   MockQuicConnectionDebugVisitor debug_visitor;
9974   connection_.set_debug_visitor(&debug_visitor);
9975   EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(3);
9976   EXPECT_CALL(debug_visitor, OnCoalescedPacketSent(_, _)).Times(1);
9977   EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
9978   {
9979     QuicConnection::ScopedPacketFlusher flusher(&connection_);
9980     connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
9981     connection_.SendCryptoDataWithString("foo", 0);
9982     // Verify this packet is on hold.
9983     EXPECT_EQ(0u, writer_->packets_write_attempts());
9984 
9985     connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
9986                              std::make_unique<TaggingEncrypter>(0x02));
9987     connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
9988     connection_.SendCryptoDataWithString("bar", 3);
9989     EXPECT_EQ(0u, writer_->packets_write_attempts());
9990 
9991     connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
9992                              std::make_unique<TaggingEncrypter>(0x03));
9993     connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
9994     SendStreamDataToPeer(2, "baz", 3, NO_FIN, nullptr);
9995   }
9996   // Verify all 3 packets are coalesced in the same UDP datagram.
9997   EXPECT_EQ(1u, writer_->packets_write_attempts());
9998   EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
9999   // Verify the packet is padded to full.
10000   EXPECT_EQ(connection_.max_packet_length(), writer_->last_packet_size());
10001 
10002   // Verify packet process.
10003   EXPECT_EQ(1u, writer_->crypto_frames().size());
10004   EXPECT_EQ(0u, writer_->stream_frames().size());
10005   // Verify there is coalesced packet.
10006   EXPECT_NE(nullptr, writer_->coalesced_packet());
10007 }
10008 
TEST_P(QuicConnectionTest,FailToCoalescePacket)10009 TEST_P(QuicConnectionTest, FailToCoalescePacket) {
10010   // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
10011   if (!IsDefaultTestConfiguration() ||
10012       !connection_.version().CanSendCoalescedPackets() ||
10013       GetQuicFlag(quic_enforce_strict_amplification_factor)) {
10014     return;
10015   }
10016 
10017   set_perspective(Perspective::IS_SERVER);
10018 
10019   auto test_body = [&] {
10020     EXPECT_CALL(visitor_,
10021                 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10022         .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
10023 
10024     ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
10025 
10026     {
10027       QuicConnection::ScopedPacketFlusher flusher(&connection_);
10028       connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10029       connection_.SendCryptoDataWithString("foo", 0);
10030       // Verify this packet is on hold.
10031       EXPECT_EQ(0u, writer_->packets_write_attempts());
10032 
10033       connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10034                                std::make_unique<TaggingEncrypter>(0x02));
10035       connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10036       connection_.SendCryptoDataWithString("bar", 3);
10037       EXPECT_EQ(0u, writer_->packets_write_attempts());
10038 
10039       connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10040                                std::make_unique<TaggingEncrypter>(0x03));
10041       connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10042       SendStreamDataToPeer(2, "baz", 3, NO_FIN, nullptr);
10043 
10044       creator_->Flush();
10045 
10046       auto& coalesced_packet =
10047           QuicConnectionPeer::GetCoalescedPacket(&connection_);
10048       QuicPacketLength coalesced_packet_max_length =
10049           coalesced_packet.max_packet_length();
10050       QuicCoalescedPacketPeer::SetMaxPacketLength(coalesced_packet,
10051                                                   coalesced_packet.length());
10052 
10053       // Make the coalescer's FORWARD_SECURE packet longer.
10054       *QuicCoalescedPacketPeer::GetMutableEncryptedBuffer(
10055           coalesced_packet, ENCRYPTION_FORWARD_SECURE) += "!!! TEST !!!";
10056 
10057       QUIC_LOG(INFO) << "Reduced coalesced_packet_max_length from "
10058                      << coalesced_packet_max_length << " to "
10059                      << coalesced_packet.max_packet_length()
10060                      << ", coalesced_packet.length:"
10061                      << coalesced_packet.length()
10062                      << ", coalesced_packet.packet_lengths:"
10063                      << absl::StrJoin(coalesced_packet.packet_lengths(), ":");
10064     }
10065 
10066     EXPECT_FALSE(connection_.connected());
10067     EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
10068                 IsError(QUIC_FAILED_TO_SERIALIZE_PACKET));
10069     EXPECT_EQ(saved_connection_close_frame_.error_details,
10070               "Failed to serialize coalesced packet.");
10071   };
10072 
10073   EXPECT_QUIC_BUG(test_body(), "SerializeCoalescedPacket failed.");
10074 }
10075 
TEST_P(QuicConnectionTest,ClientReceivedHandshakeDone)10076 TEST_P(QuicConnectionTest, ClientReceivedHandshakeDone) {
10077   if (!connection_.version().UsesTls()) {
10078     return;
10079   }
10080   EXPECT_CALL(visitor_, OnHandshakeDoneReceived());
10081   QuicFrames frames;
10082   frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
10083   frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10084   ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10085 }
10086 
TEST_P(QuicConnectionTest,ServerReceivedHandshakeDone)10087 TEST_P(QuicConnectionTest, ServerReceivedHandshakeDone) {
10088   if (!connection_.version().UsesTls()) {
10089     return;
10090   }
10091   set_perspective(Perspective::IS_SERVER);
10092   EXPECT_CALL(visitor_, OnHandshakeDoneReceived()).Times(0);
10093   if (version().handshake_protocol == PROTOCOL_TLS1_3) {
10094     EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
10095   }
10096   EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10097       .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
10098   QuicFrames frames;
10099   frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
10100   frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10101   ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10102   EXPECT_EQ(1, connection_close_frame_count_);
10103   EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
10104               IsError(IETF_QUIC_PROTOCOL_VIOLATION));
10105 }
10106 
TEST_P(QuicConnectionTest,MultiplePacketNumberSpacePto)10107 TEST_P(QuicConnectionTest, MultiplePacketNumberSpacePto) {
10108   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10109     return;
10110   }
10111   // Send handshake packet.
10112   connection_.SetEncrypter(
10113       ENCRYPTION_HANDSHAKE,
10114       std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
10115   connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10116   EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10117   connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10118   EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
10119 
10120   // Send application data.
10121   connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
10122                                          0, NO_FIN);
10123   EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
10124   QuicTime retransmission_time =
10125       connection_.GetRetransmissionAlarm()->deadline();
10126   EXPECT_NE(QuicTime::Zero(), retransmission_time);
10127 
10128   // Retransmit handshake data.
10129   clock_.AdvanceTime(retransmission_time - clock_.Now());
10130   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _));
10131   connection_.GetRetransmissionAlarm()->Fire();
10132   // Verify 1-RTT packet gets coalesced with handshake retransmission.
10133   EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
10134 
10135   // Send application data.
10136   connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
10137                                          4, NO_FIN);
10138   EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
10139   retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
10140   EXPECT_NE(QuicTime::Zero(), retransmission_time);
10141 
10142   // Retransmit handshake data again.
10143   clock_.AdvanceTime(retransmission_time - clock_.Now());
10144   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(9), _, _));
10145   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(8), _, _));
10146   connection_.GetRetransmissionAlarm()->Fire();
10147   // Verify 1-RTT packet gets coalesced with handshake retransmission.
10148   EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
10149 
10150   // Discard handshake key.
10151   connection_.OnHandshakeComplete();
10152   retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
10153   EXPECT_NE(QuicTime::Zero(), retransmission_time);
10154 
10155   // Retransmit application data.
10156   clock_.AdvanceTime(retransmission_time - clock_.Now());
10157   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(11), _, _));
10158   connection_.GetRetransmissionAlarm()->Fire();
10159   EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
10160 }
10161 
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)10162 void QuicConnectionTest::TestClientRetryHandling(
10163     bool invalid_retry_tag, bool missing_original_id_in_config,
10164     bool wrong_original_id_in_config, bool missing_retry_id_in_config,
10165     bool wrong_retry_id_in_config) {
10166   if (invalid_retry_tag) {
10167     ASSERT_FALSE(missing_original_id_in_config);
10168     ASSERT_FALSE(wrong_original_id_in_config);
10169     ASSERT_FALSE(missing_retry_id_in_config);
10170     ASSERT_FALSE(wrong_retry_id_in_config);
10171   } else {
10172     ASSERT_FALSE(missing_original_id_in_config && wrong_original_id_in_config);
10173     ASSERT_FALSE(missing_retry_id_in_config && wrong_retry_id_in_config);
10174   }
10175   if (!version().UsesTls()) {
10176     return;
10177   }
10178 
10179   // These values come from draft-ietf-quic-v2 Appendix A.4.
10180   uint8_t retry_packet_rfcv2[] = {
10181       0xcf, 0x6b, 0x33, 0x43, 0xcf, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10182       0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xc8, 0x64, 0x6c, 0xe8,
10183       0xbf, 0xe3, 0x39, 0x52, 0xd9, 0x55, 0x54, 0x36, 0x65, 0xdc, 0xc7, 0xb6};
10184   // These values come from RFC9001 Appendix A.4.
10185   uint8_t retry_packet_rfcv1[] = {
10186       0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10187       0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x04, 0xa2, 0x65, 0xba,
10188       0x2e, 0xff, 0x4d, 0x82, 0x90, 0x58, 0xfb, 0x3f, 0x0f, 0x24, 0x96, 0xba};
10189   uint8_t retry_packet29[] = {
10190       0xff, 0xff, 0x00, 0x00, 0x1d, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10191       0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xd1, 0x69, 0x26, 0xd8,
10192       0x1f, 0x6f, 0x9c, 0xa2, 0x95, 0x3a, 0x8a, 0xa4, 0x57, 0x5e, 0x1e, 0x49};
10193 
10194   uint8_t* retry_packet;
10195   size_t retry_packet_length;
10196   if (version() == ParsedQuicVersion::RFCv2()) {
10197     retry_packet = retry_packet_rfcv2;
10198     retry_packet_length = ABSL_ARRAYSIZE(retry_packet_rfcv2);
10199   } else if (version() == ParsedQuicVersion::RFCv1()) {
10200     retry_packet = retry_packet_rfcv1;
10201     retry_packet_length = ABSL_ARRAYSIZE(retry_packet_rfcv1);
10202   } else if (version() == ParsedQuicVersion::Draft29()) {
10203     retry_packet = retry_packet29;
10204     retry_packet_length = ABSL_ARRAYSIZE(retry_packet29);
10205   } else {
10206     // TODO(dschinazi) generate retry packets for all versions once we have
10207     // server-side support for generating these programmatically.
10208     return;
10209   }
10210 
10211   uint8_t original_connection_id_bytes[] = {0x83, 0x94, 0xc8, 0xf0,
10212                                             0x3e, 0x51, 0x57, 0x08};
10213   uint8_t new_connection_id_bytes[] = {0xf0, 0x67, 0xa5, 0x50,
10214                                        0x2a, 0x42, 0x62, 0xb5};
10215   uint8_t retry_token_bytes[] = {0x74, 0x6f, 0x6b, 0x65, 0x6e};
10216 
10217   QuicConnectionId original_connection_id(
10218       reinterpret_cast<char*>(original_connection_id_bytes),
10219       ABSL_ARRAYSIZE(original_connection_id_bytes));
10220   QuicConnectionId new_connection_id(
10221       reinterpret_cast<char*>(new_connection_id_bytes),
10222       ABSL_ARRAYSIZE(new_connection_id_bytes));
10223 
10224   std::string retry_token(reinterpret_cast<char*>(retry_token_bytes),
10225                           ABSL_ARRAYSIZE(retry_token_bytes));
10226 
10227   if (invalid_retry_tag) {
10228     // Flip the last bit of the retry packet to prevent the integrity tag
10229     // from validating correctly.
10230     retry_packet[retry_packet_length - 1] ^= 1;
10231   }
10232 
10233   QuicConnectionId config_original_connection_id = original_connection_id;
10234   if (wrong_original_id_in_config) {
10235     // Flip the first bit of the connection ID.
10236     ASSERT_FALSE(config_original_connection_id.IsEmpty());
10237     config_original_connection_id.mutable_data()[0] ^= 0x80;
10238   }
10239   QuicConnectionId config_retry_source_connection_id = new_connection_id;
10240   if (wrong_retry_id_in_config) {
10241     // Flip the first bit of the connection ID.
10242     ASSERT_FALSE(config_retry_source_connection_id.IsEmpty());
10243     config_retry_source_connection_id.mutable_data()[0] ^= 0x80;
10244   }
10245 
10246   // Make sure the connection uses the connection ID from the test vectors,
10247   QuicConnectionPeer::SetServerConnectionId(&connection_,
10248                                             original_connection_id);
10249   // Make sure our fake framer has the new post-retry INITIAL keys so that any
10250   // retransmission triggered by retry can be decrypted.
10251   writer_->framer()->framer()->SetInitialObfuscators(new_connection_id);
10252 
10253   // Process the RETRY packet.
10254   connection_.ProcessUdpPacket(
10255       kSelfAddress, kPeerAddress,
10256       QuicReceivedPacket(reinterpret_cast<char*>(retry_packet),
10257                          retry_packet_length, clock_.Now()));
10258 
10259   if (invalid_retry_tag) {
10260     // Make sure we refuse to process a RETRY with invalid tag.
10261     EXPECT_FALSE(connection_.GetStats().retry_packet_processed);
10262     EXPECT_EQ(connection_.connection_id(), original_connection_id);
10263     EXPECT_TRUE(QuicPacketCreatorPeer::GetRetryToken(
10264                     QuicConnectionPeer::GetPacketCreator(&connection_))
10265                     .empty());
10266     return;
10267   }
10268 
10269   // Make sure we correctly parsed the RETRY.
10270   EXPECT_TRUE(connection_.GetStats().retry_packet_processed);
10271   EXPECT_EQ(connection_.connection_id(), new_connection_id);
10272   EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
10273                 QuicConnectionPeer::GetPacketCreator(&connection_)),
10274             retry_token);
10275 
10276   // Test validating the original_connection_id from the config.
10277   QuicConfig received_config;
10278   QuicConfigPeer::SetNegotiated(&received_config, true);
10279   if (connection_.version().UsesTls()) {
10280     QuicConfigPeer::SetReceivedInitialSourceConnectionId(
10281         &received_config, connection_.connection_id());
10282     if (!missing_retry_id_in_config) {
10283       QuicConfigPeer::SetReceivedRetrySourceConnectionId(
10284           &received_config, config_retry_source_connection_id);
10285     }
10286   }
10287   if (!missing_original_id_in_config) {
10288     QuicConfigPeer::SetReceivedOriginalConnectionId(
10289         &received_config, config_original_connection_id);
10290   }
10291 
10292   if (missing_original_id_in_config || wrong_original_id_in_config ||
10293       missing_retry_id_in_config || wrong_retry_id_in_config) {
10294     EXPECT_CALL(visitor_,
10295                 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10296         .Times(1);
10297   } else {
10298     EXPECT_CALL(visitor_,
10299                 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10300         .Times(0);
10301   }
10302   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10303   connection_.SetFromConfig(received_config);
10304   if (missing_original_id_in_config || wrong_original_id_in_config ||
10305       missing_retry_id_in_config || wrong_retry_id_in_config) {
10306     ASSERT_FALSE(connection_.connected());
10307     TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10308   } else {
10309     EXPECT_TRUE(connection_.connected());
10310   }
10311 }
10312 
TEST_P(QuicConnectionTest,ClientParsesRetry)10313 TEST_P(QuicConnectionTest, ClientParsesRetry) {
10314   TestClientRetryHandling(/*invalid_retry_tag=*/false,
10315                           /*missing_original_id_in_config=*/false,
10316                           /*wrong_original_id_in_config=*/false,
10317                           /*missing_retry_id_in_config=*/false,
10318                           /*wrong_retry_id_in_config=*/false);
10319 }
10320 
TEST_P(QuicConnectionTest,ClientParsesRetryInvalidTag)10321 TEST_P(QuicConnectionTest, ClientParsesRetryInvalidTag) {
10322   TestClientRetryHandling(/*invalid_retry_tag=*/true,
10323                           /*missing_original_id_in_config=*/false,
10324                           /*wrong_original_id_in_config=*/false,
10325                           /*missing_retry_id_in_config=*/false,
10326                           /*wrong_retry_id_in_config=*/false);
10327 }
10328 
TEST_P(QuicConnectionTest,ClientParsesRetryMissingOriginalId)10329 TEST_P(QuicConnectionTest, ClientParsesRetryMissingOriginalId) {
10330   TestClientRetryHandling(/*invalid_retry_tag=*/false,
10331                           /*missing_original_id_in_config=*/true,
10332                           /*wrong_original_id_in_config=*/false,
10333                           /*missing_retry_id_in_config=*/false,
10334                           /*wrong_retry_id_in_config=*/false);
10335 }
10336 
TEST_P(QuicConnectionTest,ClientParsesRetryWrongOriginalId)10337 TEST_P(QuicConnectionTest, ClientParsesRetryWrongOriginalId) {
10338   TestClientRetryHandling(/*invalid_retry_tag=*/false,
10339                           /*missing_original_id_in_config=*/false,
10340                           /*wrong_original_id_in_config=*/true,
10341                           /*missing_retry_id_in_config=*/false,
10342                           /*wrong_retry_id_in_config=*/false);
10343 }
10344 
TEST_P(QuicConnectionTest,ClientParsesRetryMissingRetryId)10345 TEST_P(QuicConnectionTest, ClientParsesRetryMissingRetryId) {
10346   if (!connection_.version().UsesTls()) {
10347     // Versions that do not authenticate connection IDs never send the
10348     // retry_source_connection_id transport parameter.
10349     return;
10350   }
10351   TestClientRetryHandling(/*invalid_retry_tag=*/false,
10352                           /*missing_original_id_in_config=*/false,
10353                           /*wrong_original_id_in_config=*/false,
10354                           /*missing_retry_id_in_config=*/true,
10355                           /*wrong_retry_id_in_config=*/false);
10356 }
10357 
TEST_P(QuicConnectionTest,ClientParsesRetryWrongRetryId)10358 TEST_P(QuicConnectionTest, ClientParsesRetryWrongRetryId) {
10359   if (!connection_.version().UsesTls()) {
10360     // Versions that do not authenticate connection IDs never send the
10361     // retry_source_connection_id transport parameter.
10362     return;
10363   }
10364   TestClientRetryHandling(/*invalid_retry_tag=*/false,
10365                           /*missing_original_id_in_config=*/false,
10366                           /*wrong_original_id_in_config=*/false,
10367                           /*missing_retry_id_in_config=*/false,
10368                           /*wrong_retry_id_in_config=*/true);
10369 }
10370 
TEST_P(QuicConnectionTest,ClientRetransmitsInitialPacketsOnRetry)10371 TEST_P(QuicConnectionTest, ClientRetransmitsInitialPacketsOnRetry) {
10372   if (!connection_.version().HasIetfQuicFrames()) {
10373     // TestClientRetryHandling() currently only supports IETF draft versions.
10374     return;
10375   }
10376   connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10377 
10378   connection_.SendCryptoStreamData();
10379 
10380   EXPECT_EQ(1u, writer_->packets_write_attempts());
10381   TestClientRetryHandling(/*invalid_retry_tag=*/false,
10382                           /*missing_original_id_in_config=*/false,
10383                           /*wrong_original_id_in_config=*/false,
10384                           /*missing_retry_id_in_config=*/false,
10385                           /*wrong_retry_id_in_config=*/false);
10386 
10387   // Verify that initial data is retransmitted immediately after receiving
10388   // RETRY.
10389   if (GetParam().ack_response == AckResponse::kImmediate) {
10390     EXPECT_EQ(2u, writer_->packets_write_attempts());
10391     EXPECT_EQ(1u, writer_->framer()->crypto_frames().size());
10392   }
10393 }
10394 
TEST_P(QuicConnectionTest,NoInitialPacketsRetransmissionOnInvalidRetry)10395 TEST_P(QuicConnectionTest, NoInitialPacketsRetransmissionOnInvalidRetry) {
10396   if (!connection_.version().HasIetfQuicFrames()) {
10397     return;
10398   }
10399   connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10400 
10401   connection_.SendCryptoStreamData();
10402 
10403   EXPECT_EQ(1u, writer_->packets_write_attempts());
10404   TestClientRetryHandling(/*invalid_retry_tag=*/true,
10405                           /*missing_original_id_in_config=*/false,
10406                           /*wrong_original_id_in_config=*/false,
10407                           /*missing_retry_id_in_config=*/false,
10408                           /*wrong_retry_id_in_config=*/false);
10409 
10410   EXPECT_EQ(1u, writer_->packets_write_attempts());
10411 }
10412 
TEST_P(QuicConnectionTest,ClientReceivesOriginalConnectionIdWithoutRetry)10413 TEST_P(QuicConnectionTest, ClientReceivesOriginalConnectionIdWithoutRetry) {
10414   if (!connection_.version().UsesTls()) {
10415     // QUIC+TLS is required to transmit connection ID transport parameters.
10416     return;
10417   }
10418   if (connection_.version().UsesTls()) {
10419     // Versions that authenticate connection IDs always send the
10420     // original_destination_connection_id transport parameter.
10421     return;
10422   }
10423   // Make sure that receiving the original_destination_connection_id transport
10424   // parameter fails the handshake when no RETRY packet was received before it.
10425   QuicConfig received_config;
10426   QuicConfigPeer::SetNegotiated(&received_config, true);
10427   QuicConfigPeer::SetReceivedOriginalConnectionId(&received_config,
10428                                                   TestConnectionId(0x12345));
10429   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10430   EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10431       .Times(1);
10432   connection_.SetFromConfig(received_config);
10433   EXPECT_FALSE(connection_.connected());
10434   TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10435 }
10436 
TEST_P(QuicConnectionTest,ClientReceivesRetrySourceConnectionIdWithoutRetry)10437 TEST_P(QuicConnectionTest, ClientReceivesRetrySourceConnectionIdWithoutRetry) {
10438   if (!connection_.version().UsesTls()) {
10439     // Versions that do not authenticate connection IDs never send the
10440     // retry_source_connection_id transport parameter.
10441     return;
10442   }
10443   // Make sure that receiving the retry_source_connection_id transport parameter
10444   // fails the handshake when no RETRY packet was received before it.
10445   QuicConfig received_config;
10446   QuicConfigPeer::SetNegotiated(&received_config, true);
10447   QuicConfigPeer::SetReceivedRetrySourceConnectionId(&received_config,
10448                                                      TestConnectionId(0x12345));
10449   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10450   EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10451       .Times(1);
10452   connection_.SetFromConfig(received_config);
10453   EXPECT_FALSE(connection_.connected());
10454   TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10455 }
10456 
10457 // Regression test for http://crbug/1047977
TEST_P(QuicConnectionTest,MaxStreamsFrameCausesConnectionClose)10458 TEST_P(QuicConnectionTest, MaxStreamsFrameCausesConnectionClose) {
10459   if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10460     return;
10461   }
10462   // Received frame causes connection close.
10463   EXPECT_CALL(visitor_, OnMaxStreamsFrame(_))
10464       .WillOnce(InvokeWithoutArgs([this]() {
10465         EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10466         connection_.CloseConnection(
10467             QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10468             ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10469         return true;
10470       }));
10471   QuicFrames frames;
10472   frames.push_back(QuicFrame(QuicMaxStreamsFrame()));
10473   frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10474   ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10475 }
10476 
TEST_P(QuicConnectionTest,StreamsBlockedFrameCausesConnectionClose)10477 TEST_P(QuicConnectionTest, StreamsBlockedFrameCausesConnectionClose) {
10478   if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10479     return;
10480   }
10481   // Received frame causes connection close.
10482   EXPECT_CALL(visitor_, OnStreamsBlockedFrame(_))
10483       .WillOnce(InvokeWithoutArgs([this]() {
10484         EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10485         connection_.CloseConnection(
10486             QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10487             ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10488         return true;
10489       }));
10490   QuicFrames frames;
10491   frames.push_back(
10492       QuicFrame(QuicStreamsBlockedFrame(kInvalidControlFrameId, 10, false)));
10493   frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10494   ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10495 }
10496 
TEST_P(QuicConnectionTest,BundleAckWithConnectionCloseMultiplePacketNumberSpace)10497 TEST_P(QuicConnectionTest,
10498        BundleAckWithConnectionCloseMultiplePacketNumberSpace) {
10499   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10500     return;
10501   }
10502   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10503   EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10504   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10505   // Receives packet 1000 in initial data.
10506   ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10507   // Receives packet 2000 in application data.
10508   ProcessDataPacketAtLevel(2000, false, ENCRYPTION_FORWARD_SECURE);
10509   EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10510   const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
10511   connection_.CloseConnection(
10512       kQuicErrorCode, "Some random error message",
10513       ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10514 
10515   EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
10516 
10517   TestConnectionCloseQuicErrorCode(kQuicErrorCode);
10518   EXPECT_EQ(1u, writer_->connection_close_frames().size());
10519   // Verify ack is bundled.
10520   EXPECT_EQ(1u, writer_->ack_frames().size());
10521 
10522   if (!connection_.version().CanSendCoalescedPackets()) {
10523     // Each connection close packet should be sent in distinct UDP packets.
10524     EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10525               writer_->connection_close_packets());
10526     EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10527               writer_->packets_write_attempts());
10528     return;
10529   }
10530 
10531   // A single UDP packet should be sent with multiple connection close packets
10532   // coalesced together.
10533   EXPECT_EQ(1u, writer_->packets_write_attempts());
10534 
10535   // Only the first packet has been processed yet.
10536   EXPECT_EQ(1u, writer_->connection_close_packets());
10537 
10538   // ProcessPacket resets the visitor and frees the coalesced packet.
10539   ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
10540   auto packet = writer_->coalesced_packet()->Clone();
10541   writer_->framer()->ProcessPacket(*packet);
10542   EXPECT_EQ(1u, writer_->connection_close_packets());
10543   EXPECT_EQ(1u, writer_->connection_close_frames().size());
10544   // Verify ack is bundled.
10545   EXPECT_EQ(1u, writer_->ack_frames().size());
10546   ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
10547 }
10548 
10549 // Regression test for b/151220135.
TEST_P(QuicConnectionTest,SendPingWhenSkipPacketNumberForPto)10550 TEST_P(QuicConnectionTest, SendPingWhenSkipPacketNumberForPto) {
10551   QuicConfig config;
10552   QuicTagVector connection_options;
10553   connection_options.push_back(kPTOS);
10554   connection_options.push_back(k1PTO);
10555   config.SetConnectionOptionsToSend(connection_options);
10556   if (connection_.version().UsesTls()) {
10557     QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
10558         &config, kMaxAcceptedDatagramFrameSize);
10559   }
10560   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10561   connection_.SetFromConfig(config);
10562   connection_.OnHandshakeComplete();
10563   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10564 
10565   EXPECT_EQ(MESSAGE_STATUS_SUCCESS, SendMessage("message"));
10566   EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10567 
10568   // PTO fires, verify a PING packet gets sent because there is no data to
10569   // send.
10570   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
10571   connection_.GetRetransmissionAlarm()->Fire();
10572   EXPECT_EQ(1u, connection_.GetStats().pto_count);
10573   EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
10574   EXPECT_EQ(1u, writer_->ping_frames().size());
10575 }
10576 
10577 // Regression test for b/155757133
TEST_P(QuicConnectionTest,DonotChangeQueuedAcks)10578 TEST_P(QuicConnectionTest, DonotChangeQueuedAcks) {
10579   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10580     return;
10581   }
10582   const size_t kMinRttMs = 40;
10583   RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
10584   rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
10585                        QuicTime::Delta::Zero(), QuicTime::Zero());
10586   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10587   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
10588   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10589   // Discard INITIAL key.
10590   connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
10591   connection_.NeuterUnencryptedPackets();
10592   EXPECT_CALL(visitor_, GetHandshakeState())
10593       .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10594 
10595   ProcessPacket(2);
10596   ProcessPacket(3);
10597   ProcessPacket(4);
10598   // Process a packet containing stream frame followed by ACK of packets 1.
10599   QuicFrames frames;
10600   frames.push_back(QuicFrame(QuicStreamFrame(
10601       QuicUtils::GetFirstBidirectionalStreamId(
10602           connection_.version().transport_version, Perspective::IS_CLIENT),
10603       false, 0u, absl::string_view())));
10604   QuicAckFrame ack_frame = InitAckFrame(1);
10605   frames.push_back(QuicFrame(&ack_frame));
10606   // Receiving stream frame causes something to send.
10607   EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() {
10608     connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
10609     // Verify now the queued ACK contains packet number 2.
10610     EXPECT_TRUE(QuicPacketCreatorPeer::QueuedFrames(
10611                     QuicConnectionPeer::GetPacketCreator(&connection_))[0]
10612                     .ack_frame->packets.Contains(QuicPacketNumber(2)));
10613   }));
10614   ProcessFramesPacketAtLevel(9, frames, ENCRYPTION_FORWARD_SECURE);
10615   EXPECT_TRUE(writer_->ack_frames()[0].packets.Contains(QuicPacketNumber(2)));
10616 }
10617 
TEST_P(QuicConnectionTest,DoNotExtendIdleTimeOnUndecryptablePackets)10618 TEST_P(QuicConnectionTest, DoNotExtendIdleTimeOnUndecryptablePackets) {
10619   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10620   QuicConfig config;
10621   connection_.SetFromConfig(config);
10622   // Subtract a second from the idle timeout on the client side.
10623   QuicTime initial_deadline =
10624       clock_.ApproximateNow() +
10625       QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
10626   EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10627 
10628   // Received an undecryptable packet.
10629   clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
10630   peer_framer_.SetEncrypter(
10631       ENCRYPTION_FORWARD_SECURE,
10632       std::make_unique<quic::NullEncrypter>(Perspective::IS_CLIENT));
10633   ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
10634   // Verify deadline does not get extended.
10635   EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10636   EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
10637   QuicTime::Delta delay = initial_deadline - clock_.ApproximateNow();
10638   clock_.AdvanceTime(delay);
10639   connection_.GetTimeoutAlarm()->Fire();
10640   // Verify connection gets closed.
10641   EXPECT_FALSE(connection_.connected());
10642 }
10643 
TEST_P(QuicConnectionTest,BundleAckWithImmediateResponse)10644 TEST_P(QuicConnectionTest, BundleAckWithImmediateResponse) {
10645   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10646   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10647 
10648   EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() {
10649     notifier_.WriteOrBufferWindowUpate(0, 0);
10650   }));
10651   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10652   ProcessDataPacket(1);
10653   // Verify ACK is bundled with WINDOW_UPDATE.
10654   EXPECT_FALSE(writer_->ack_frames().empty());
10655   EXPECT_FALSE(connection_.HasPendingAcks());
10656 }
10657 
TEST_P(QuicConnectionTest,AckAlarmFiresEarly)10658 TEST_P(QuicConnectionTest, AckAlarmFiresEarly) {
10659   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10660     return;
10661   }
10662   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10663   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10664     EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10665   }
10666   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10667   // Receives packet 1000 in initial data.
10668   ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10669   EXPECT_TRUE(connection_.HasPendingAcks());
10670 
10671   peer_framer_.SetEncrypter(
10672       ENCRYPTION_ZERO_RTT,
10673       std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
10674   SetDecrypter(ENCRYPTION_ZERO_RTT,
10675                std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
10676   // Receives packet 1000 in application data.
10677   ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
10678   EXPECT_TRUE(connection_.HasPendingAcks());
10679   // Verify ACK deadline does not change.
10680   EXPECT_EQ(clock_.ApproximateNow() + kAlarmGranularity,
10681             connection_.GetAckAlarm()->deadline());
10682 
10683   // Ack alarm fires early.
10684   // Verify the earliest ACK is flushed.
10685   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10686   connection_.GetAckAlarm()->Fire();
10687   EXPECT_TRUE(connection_.HasPendingAcks());
10688   EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(),
10689             connection_.GetAckAlarm()->deadline());
10690 }
10691 
TEST_P(QuicConnectionTest,ClientOnlyBlackholeDetectionClient)10692 TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionClient) {
10693   if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
10694     return;
10695   }
10696   QuicConfig config;
10697   QuicTagVector connection_options;
10698   connection_options.push_back(kCBHD);
10699   config.SetConnectionOptionsToSend(connection_options);
10700   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10701   connection_.SetFromConfig(config);
10702   EXPECT_CALL(visitor_, GetHandshakeState())
10703       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
10704   connection_.OnHandshakeComplete();
10705   EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10706   // Send stream data.
10707   SendStreamDataToPeer(
10708       GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10709       0, FIN, nullptr);
10710   // Verify blackhole detection is in progress.
10711   EXPECT_TRUE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10712 }
10713 
TEST_P(QuicConnectionTest,ClientOnlyBlackholeDetectionServer)10714 TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionServer) {
10715   if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
10716     return;
10717   }
10718   set_perspective(Perspective::IS_SERVER);
10719   QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
10720   if (version().SupportsAntiAmplificationLimit()) {
10721     QuicConnectionPeer::SetAddressValidated(&connection_);
10722   }
10723   QuicConfig config;
10724   QuicTagVector connection_options;
10725   connection_options.push_back(kCBHD);
10726   config.SetInitialReceivedConnectionOptions(connection_options);
10727   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10728   connection_.SetFromConfig(config);
10729   EXPECT_CALL(visitor_, GetHandshakeState())
10730       .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10731   EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10732   // Send stream data.
10733   SendStreamDataToPeer(
10734       GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10735       0, FIN, nullptr);
10736   // Verify blackhole detection is disabled.
10737   EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10738 }
10739 
10740 // Regresstion test for b/158491591.
TEST_P(QuicConnectionTest,MadeForwardProgressOnDiscardingKeys)10741 TEST_P(QuicConnectionTest, MadeForwardProgressOnDiscardingKeys) {
10742   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10743     return;
10744   }
10745   // Send handshake packet.
10746   connection_.SetEncrypter(
10747       ENCRYPTION_HANDSHAKE,
10748       std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
10749   connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10750   EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10751   QuicConfig config;
10752   QuicTagVector connection_options;
10753   connection_options.push_back(k5RTO);
10754   config.SetConnectionOptionsToSend(connection_options);
10755   QuicConfigPeer::SetNegotiated(&config, true);
10756   if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
10757       GetQuicReloadableFlag(
10758           quic_no_path_degrading_before_handshake_confirmed)) {
10759     EXPECT_CALL(visitor_, GetHandshakeState())
10760         .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10761   }
10762   if (connection_.version().UsesTls()) {
10763     QuicConfigPeer::SetReceivedOriginalConnectionId(
10764         &config, connection_.connection_id());
10765     QuicConfigPeer::SetReceivedInitialSourceConnectionId(
10766         &config, connection_.connection_id());
10767   }
10768   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10769   connection_.SetFromConfig(config);
10770 
10771   connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10772   if (GetQuicReloadableFlag(
10773           quic_no_path_degrading_before_handshake_confirmed)) {
10774     // No blackhole detection before handshake confirmed.
10775     EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
10776   } else {
10777     EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
10778   }
10779   // Discard handshake keys.
10780   EXPECT_CALL(visitor_, GetHandshakeState())
10781       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
10782   connection_.OnHandshakeComplete();
10783   if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
10784       GetQuicReloadableFlag(
10785           quic_no_path_degrading_before_handshake_confirmed)) {
10786     // Verify blackhole detection stops.
10787     EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
10788   } else {
10789     // Problematic: although there is nothing in flight, blackhole detection is
10790     // still in progress.
10791     EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
10792   }
10793 }
10794 
TEST_P(QuicConnectionTest,ProcessUndecryptablePacketsBasedOnEncryptionLevel)10795 TEST_P(QuicConnectionTest, ProcessUndecryptablePacketsBasedOnEncryptionLevel) {
10796   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10797     return;
10798   }
10799   // SetFromConfig is always called after construction from InitializeSession.
10800   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10801   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10802   EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
10803   QuicConfig config;
10804   connection_.SetFromConfig(config);
10805   connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10806   connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
10807 
10808   peer_framer_.SetEncrypter(
10809       ENCRYPTION_HANDSHAKE,
10810       std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
10811   peer_framer_.SetEncrypter(
10812       ENCRYPTION_FORWARD_SECURE,
10813       std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
10814 
10815   for (uint64_t i = 1; i <= 3; ++i) {
10816     ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
10817   }
10818   ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
10819   for (uint64_t j = 5; j <= 7; ++j) {
10820     ProcessDataPacketAtLevel(j, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
10821   }
10822   EXPECT_EQ(7u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
10823   EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
10824   SetDecrypter(ENCRYPTION_HANDSHAKE,
10825                std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
10826   EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
10827   connection_.SetEncrypter(
10828       ENCRYPTION_HANDSHAKE,
10829       std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
10830   connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10831   // Verify all ENCRYPTION_HANDSHAKE packets get processed.
10832   if (!VersionHasIetfQuicFrames(version().transport_version)) {
10833     EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(6);
10834   }
10835   connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
10836   EXPECT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
10837 
10838   SetDecrypter(
10839       ENCRYPTION_FORWARD_SECURE,
10840       std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
10841   EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
10842   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10843   connection_.SetEncrypter(
10844       ENCRYPTION_FORWARD_SECURE,
10845       std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
10846   // Verify the 1-RTT packet gets processed.
10847   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
10848   connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
10849   EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
10850 }
10851 
TEST_P(QuicConnectionTest,ServerBundlesInitialDataWithInitialAck)10852 TEST_P(QuicConnectionTest, ServerBundlesInitialDataWithInitialAck) {
10853   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10854     return;
10855   }
10856   set_perspective(Perspective::IS_SERVER);
10857   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10858     EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10859   }
10860   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10861   // Receives packet 1000 in initial data.
10862   ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10863   EXPECT_TRUE(connection_.HasPendingAcks());
10864 
10865   connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10866   connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
10867   QuicTime expected_pto_time =
10868       connection_.sent_packet_manager().GetRetransmissionTime();
10869 
10870   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
10871   connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10872                            std::make_unique<TaggingEncrypter>(0x02));
10873   connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10874   EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10875   connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10876   // Verify PTO time does not change.
10877   EXPECT_EQ(expected_pto_time,
10878             connection_.sent_packet_manager().GetRetransmissionTime());
10879 
10880   // Receives packet 1001 in initial data.
10881   ProcessCryptoPacketAtLevel(1001, ENCRYPTION_INITIAL);
10882   EXPECT_TRUE(connection_.HasPendingAcks());
10883   // Receives packet 1002 in initial data.
10884   ProcessCryptoPacketAtLevel(1002, ENCRYPTION_INITIAL);
10885   EXPECT_FALSE(writer_->ack_frames().empty());
10886   // Verify CRYPTO frame is bundled with INITIAL ACK.
10887   EXPECT_FALSE(writer_->crypto_frames().empty());
10888   // Verify PTO time changes.
10889   EXPECT_NE(expected_pto_time,
10890             connection_.sent_packet_manager().GetRetransmissionTime());
10891 }
10892 
TEST_P(QuicConnectionTest,ClientBundlesHandshakeDataWithHandshakeAck)10893 TEST_P(QuicConnectionTest, ClientBundlesHandshakeDataWithHandshakeAck) {
10894   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10895     return;
10896   }
10897   EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
10898   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10899     EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10900   }
10901   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10902   connection_.SetEncrypter(
10903       ENCRYPTION_HANDSHAKE,
10904       std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
10905   connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10906   SetDecrypter(ENCRYPTION_HANDSHAKE,
10907                std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
10908   peer_framer_.SetEncrypter(
10909       ENCRYPTION_HANDSHAKE,
10910       std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
10911   // Receives packet 1000 in handshake data.
10912   ProcessCryptoPacketAtLevel(1000, ENCRYPTION_HANDSHAKE);
10913   EXPECT_TRUE(connection_.HasPendingAcks());
10914   EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10915   connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10916 
10917   // Receives packet 1001 in handshake data.
10918   ProcessCryptoPacketAtLevel(1001, ENCRYPTION_HANDSHAKE);
10919   EXPECT_TRUE(connection_.HasPendingAcks());
10920   // Receives packet 1002 in handshake data.
10921   ProcessCryptoPacketAtLevel(1002, ENCRYPTION_HANDSHAKE);
10922   EXPECT_FALSE(writer_->ack_frames().empty());
10923   // Verify CRYPTO frame is bundled with HANDSHAKE ACK.
10924   EXPECT_FALSE(writer_->crypto_frames().empty());
10925 }
10926 
10927 // Regresstion test for b/156232673.
TEST_P(QuicConnectionTest,CoalescePacketOfLowerEncryptionLevel)10928 TEST_P(QuicConnectionTest, CoalescePacketOfLowerEncryptionLevel) {
10929   if (!connection_.version().CanSendCoalescedPackets()) {
10930     return;
10931   }
10932   EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10933   {
10934     QuicConnection::ScopedPacketFlusher flusher(&connection_);
10935     connection_.SetEncrypter(
10936         ENCRYPTION_HANDSHAKE,
10937         std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
10938     connection_.SetEncrypter(
10939         ENCRYPTION_FORWARD_SECURE,
10940         std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
10941     connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10942     SendStreamDataToPeer(2, std::string(1286, 'a'), 0, NO_FIN, nullptr);
10943     connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10944     // Try to coalesce a HANDSHAKE packet after 1-RTT packet.
10945     // Verify soft max packet length gets resumed and handshake packet gets
10946     // successfully sent.
10947     connection_.SendCryptoDataWithString("a", 0, ENCRYPTION_HANDSHAKE);
10948   }
10949 }
10950 
10951 // Regression test for b/160790422.
TEST_P(QuicConnectionTest,ServerRetransmitsHandshakeDataEarly)10952 TEST_P(QuicConnectionTest, ServerRetransmitsHandshakeDataEarly) {
10953   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10954     return;
10955   }
10956   set_perspective(Perspective::IS_SERVER);
10957   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10958     EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10959   }
10960   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10961   // Receives packet 1000 in initial data.
10962   ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10963   EXPECT_TRUE(connection_.HasPendingAcks());
10964 
10965   connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10966   // Send INITIAL 1.
10967   connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
10968   QuicTime expected_pto_time =
10969       connection_.sent_packet_manager().GetRetransmissionTime();
10970 
10971   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
10972   connection_.SetEncrypter(
10973       ENCRYPTION_HANDSHAKE,
10974       std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
10975   connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10976   EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10977   // Send HANDSHAKE 2 and 3.
10978   connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10979   connection_.SendCryptoDataWithString("bar", 3, ENCRYPTION_HANDSHAKE);
10980   // Verify PTO time does not change.
10981   EXPECT_EQ(expected_pto_time,
10982             connection_.sent_packet_manager().GetRetransmissionTime());
10983 
10984   // Receives ACK for HANDSHAKE 2.
10985   QuicFrames frames;
10986   auto ack_frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
10987   frames.push_back(QuicFrame(&ack_frame));
10988   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
10989   ProcessFramesPacketAtLevel(30, frames, ENCRYPTION_HANDSHAKE);
10990   // Discard INITIAL key.
10991   connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
10992   connection_.NeuterUnencryptedPackets();
10993   // Receives PING from peer.
10994   frames.clear();
10995   frames.push_back(QuicFrame(QuicPingFrame()));
10996   frames.push_back(QuicFrame(QuicPaddingFrame(3)));
10997   ProcessFramesPacketAtLevel(31, frames, ENCRYPTION_HANDSHAKE);
10998   EXPECT_EQ(clock_.Now() + kAlarmGranularity,
10999             connection_.GetAckAlarm()->deadline());
11000   // Fire ACK alarm.
11001   clock_.AdvanceTime(kAlarmGranularity);
11002   connection_.GetAckAlarm()->Fire();
11003   EXPECT_FALSE(writer_->ack_frames().empty());
11004   // Verify handshake data gets retransmitted early.
11005   EXPECT_FALSE(writer_->crypto_frames().empty());
11006 }
11007 
11008 // Regression test for b/161228202
TEST_P(QuicConnectionTest,InflatedRttSample)11009 TEST_P(QuicConnectionTest, InflatedRttSample) {
11010   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11011     return;
11012   }
11013   // 30ms RTT.
11014   const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
11015   set_perspective(Perspective::IS_SERVER);
11016   RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11017   // Receives packet 1000 in initial data.
11018   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11019     EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11020   }
11021   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
11022   ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
11023   EXPECT_TRUE(connection_.HasPendingAcks());
11024 
11025   connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11026   // Send INITIAL 1.
11027   std::string initial_crypto_data(512, 'a');
11028   connection_.SendCryptoDataWithString(initial_crypto_data, 0,
11029                                        ENCRYPTION_INITIAL);
11030   ASSERT_TRUE(connection_.sent_packet_manager()
11031                   .GetRetransmissionTime()
11032                   .IsInitialized());
11033   QuicTime::Delta pto_timeout =
11034       connection_.sent_packet_manager().GetRetransmissionTime() - clock_.Now();
11035   // Send Handshake 2.
11036   connection_.SetEncrypter(
11037       ENCRYPTION_HANDSHAKE,
11038       std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
11039   connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11040   EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11041   std::string handshake_crypto_data(1024, 'a');
11042   connection_.SendCryptoDataWithString(handshake_crypto_data, 0,
11043                                        ENCRYPTION_HANDSHAKE);
11044 
11045   // INITIAL 1 gets lost and PTO fires.
11046   clock_.AdvanceTime(pto_timeout);
11047   connection_.GetRetransmissionAlarm()->Fire();
11048 
11049   clock_.AdvanceTime(kTestRTT);
11050   // Assume retransmitted INITIAL gets received.
11051   QuicFrames frames;
11052   auto ack_frame = InitAckFrame({{QuicPacketNumber(4), QuicPacketNumber(5)}});
11053   frames.push_back(QuicFrame(&ack_frame));
11054   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
11055       .Times(AnyNumber());
11056   ProcessFramesPacketAtLevel(1001, frames, ENCRYPTION_INITIAL);
11057   EXPECT_EQ(kTestRTT, rtt_stats->latest_rtt());
11058   // Because retransmitted INITIAL gets received so HANDSHAKE 2 gets processed.
11059   frames.clear();
11060   // HANDSHAKE 5 is also processed.
11061   QuicAckFrame ack_frame2 =
11062       InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
11063                     {QuicPacketNumber(5), QuicPacketNumber(6)}});
11064   ack_frame2.ack_delay_time = QuicTime::Delta::Zero();
11065   frames.push_back(QuicFrame(&ack_frame2));
11066   ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_HANDSHAKE);
11067   // Verify RTT inflation gets mitigated.
11068   EXPECT_EQ(rtt_stats->latest_rtt(), kTestRTT);
11069 }
11070 
11071 // Regression test for b/161228202
TEST_P(QuicConnectionTest,CoalescingPacketCausesInfiniteLoop)11072 TEST_P(QuicConnectionTest, CoalescingPacketCausesInfiniteLoop) {
11073   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11074     return;
11075   }
11076   set_perspective(Perspective::IS_SERVER);
11077   // Receives packet 1000 in initial data.
11078   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11079     EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11080   }
11081   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
11082 
11083   // Set anti amplification factor to 2, such that RetransmitDataOfSpaceIfAny
11084   // makes no forward progress and causes infinite loop.
11085   SetQuicFlag(quic_anti_amplification_factor, 2);
11086 
11087   ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
11088   EXPECT_TRUE(connection_.HasPendingAcks());
11089 
11090   connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11091   // Send INITIAL 1.
11092   std::string initial_crypto_data(512, 'a');
11093   connection_.SendCryptoDataWithString(initial_crypto_data, 0,
11094                                        ENCRYPTION_INITIAL);
11095   ASSERT_TRUE(connection_.sent_packet_manager()
11096                   .GetRetransmissionTime()
11097                   .IsInitialized());
11098   QuicTime::Delta pto_timeout =
11099       connection_.sent_packet_manager().GetRetransmissionTime() - clock_.Now();
11100   // Send Handshake 2.
11101   connection_.SetEncrypter(
11102       ENCRYPTION_HANDSHAKE,
11103       std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
11104   connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11105   // Verify HANDSHAKE packet is coalesced with INITIAL retransmission.
11106   EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11107   std::string handshake_crypto_data(1024, 'a');
11108   connection_.SendCryptoDataWithString(handshake_crypto_data, 0,
11109                                        ENCRYPTION_HANDSHAKE);
11110 
11111   // INITIAL 1 gets lost and PTO fires.
11112   clock_.AdvanceTime(pto_timeout);
11113   connection_.GetRetransmissionAlarm()->Fire();
11114 }
11115 
TEST_P(QuicConnectionTest,ClientAckDelayForAsyncPacketProcessing)11116 TEST_P(QuicConnectionTest, ClientAckDelayForAsyncPacketProcessing) {
11117   if (!version().HasIetfQuicFrames()) {
11118     return;
11119   }
11120   // SetFromConfig is always called after construction from InitializeSession.
11121   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
11122   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11123   EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
11124     connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
11125     connection_.NeuterUnencryptedPackets();
11126   }));
11127   QuicConfig config;
11128   connection_.SetFromConfig(config);
11129   connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11130   peer_framer_.SetEncrypter(
11131       ENCRYPTION_HANDSHAKE,
11132       std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
11133   EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
11134 
11135   // Received undecryptable HANDSHAKE 2.
11136   ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
11137   ASSERT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
11138   // Received INITIAL 4 (which is retransmission of INITIAL 1) after 100ms.
11139   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100));
11140   ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_INITIAL);
11141   // Generate HANDSHAKE key.
11142   SetDecrypter(ENCRYPTION_HANDSHAKE,
11143                std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
11144   EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
11145   connection_.SetEncrypter(
11146       ENCRYPTION_HANDSHAKE,
11147       std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
11148   connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11149   // Verify HANDSHAKE packet gets processed.
11150   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
11151   connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
11152   // Verify immediate ACK has been sent out when flush went out of scope.
11153   ASSERT_FALSE(connection_.HasPendingAcks());
11154   ASSERT_FALSE(writer_->ack_frames().empty());
11155   // Verify the ack_delay_time in the sent HANDSHAKE ACK frame is 100ms.
11156   EXPECT_EQ(QuicTime::Delta::FromMilliseconds(100),
11157             writer_->ack_frames()[0].ack_delay_time);
11158   ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
11159 }
11160 
TEST_P(QuicConnectionTest,TestingLiveness)11161 TEST_P(QuicConnectionTest, TestingLiveness) {
11162   const size_t kMinRttMs = 40;
11163   RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11164   rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11165                        QuicTime::Delta::Zero(), QuicTime::Zero());
11166   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11167   QuicConfig config;
11168 
11169   CryptoHandshakeMessage msg;
11170   std::string error_details;
11171   QuicConfig client_config;
11172   client_config.SetInitialStreamFlowControlWindowToSend(
11173       kInitialStreamFlowControlWindowForTest);
11174   client_config.SetInitialSessionFlowControlWindowToSend(
11175       kInitialSessionFlowControlWindowForTest);
11176   client_config.SetIdleNetworkTimeout(QuicTime::Delta::FromSeconds(30));
11177   client_config.ToHandshakeMessage(&msg, connection_.transport_version());
11178   const QuicErrorCode error =
11179       config.ProcessPeerHello(msg, CLIENT, &error_details);
11180   EXPECT_THAT(error, IsQuicNoError());
11181 
11182   if (connection_.version().UsesTls()) {
11183     QuicConfigPeer::SetReceivedOriginalConnectionId(
11184         &config, connection_.connection_id());
11185     QuicConfigPeer::SetReceivedInitialSourceConnectionId(
11186         &config, connection_.connection_id());
11187   }
11188 
11189   connection_.SetFromConfig(config);
11190   connection_.OnHandshakeComplete();
11191   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11192   ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11193   EXPECT_FALSE(connection_.MaybeTestLiveness());
11194 
11195   QuicTime deadline = QuicConnectionPeer::GetIdleNetworkDeadline(&connection_);
11196   QuicTime::Delta timeout = deadline - clock_.ApproximateNow();
11197   // Advance time to near the idle timeout.
11198   clock_.AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(1));
11199   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
11200   EXPECT_TRUE(connection_.MaybeTestLiveness());
11201   // Verify idle deadline does not change.
11202   EXPECT_EQ(deadline, QuicConnectionPeer::GetIdleNetworkDeadline(&connection_));
11203 }
11204 
TEST_P(QuicConnectionTest,DisableLivenessTesting)11205 TEST_P(QuicConnectionTest, DisableLivenessTesting) {
11206   const size_t kMinRttMs = 40;
11207   RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11208   rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11209                        QuicTime::Delta::Zero(), QuicTime::Zero());
11210   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11211   QuicConfig config;
11212 
11213   CryptoHandshakeMessage msg;
11214   std::string error_details;
11215   QuicConfig client_config;
11216   client_config.SetInitialStreamFlowControlWindowToSend(
11217       kInitialStreamFlowControlWindowForTest);
11218   client_config.SetInitialSessionFlowControlWindowToSend(
11219       kInitialSessionFlowControlWindowForTest);
11220   client_config.SetIdleNetworkTimeout(QuicTime::Delta::FromSeconds(30));
11221   client_config.ToHandshakeMessage(&msg, connection_.transport_version());
11222   const QuicErrorCode error =
11223       config.ProcessPeerHello(msg, CLIENT, &error_details);
11224   EXPECT_THAT(error, IsQuicNoError());
11225 
11226   if (connection_.version().UsesTls()) {
11227     QuicConfigPeer::SetReceivedOriginalConnectionId(
11228         &config, connection_.connection_id());
11229     QuicConfigPeer::SetReceivedInitialSourceConnectionId(
11230         &config, connection_.connection_id());
11231   }
11232 
11233   connection_.SetFromConfig(config);
11234   connection_.OnHandshakeComplete();
11235   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11236   connection_.DisableLivenessTesting();
11237   ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11238   EXPECT_FALSE(connection_.MaybeTestLiveness());
11239 
11240   QuicTime deadline = QuicConnectionPeer::GetIdleNetworkDeadline(&connection_);
11241   QuicTime::Delta timeout = deadline - clock_.ApproximateNow();
11242   // Advance time to near the idle timeout.
11243   clock_.AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(1));
11244   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
11245   EXPECT_FALSE(connection_.MaybeTestLiveness());
11246 }
11247 
TEST_P(QuicConnectionTest,SilentIdleTimeout)11248 TEST_P(QuicConnectionTest, SilentIdleTimeout) {
11249   set_perspective(Perspective::IS_SERVER);
11250   QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
11251   if (version().SupportsAntiAmplificationLimit()) {
11252     QuicConnectionPeer::SetAddressValidated(&connection_);
11253   }
11254 
11255   QuicConfig config;
11256   QuicConfigPeer::SetNegotiated(&config, true);
11257   if (connection_.version().UsesTls()) {
11258     QuicConfigPeer::SetReceivedOriginalConnectionId(
11259         &config, connection_.connection_id());
11260     QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
11261                                                          QuicConnectionId());
11262   }
11263   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11264   connection_.SetFromConfig(config);
11265 
11266   EXPECT_TRUE(connection_.connected());
11267   EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11268 
11269   if (version().handshake_protocol == PROTOCOL_TLS1_3) {
11270     EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
11271   }
11272   EXPECT_CALL(visitor_,
11273               OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
11274   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
11275   connection_.GetTimeoutAlarm()->Fire();
11276   // Verify the connection close packets get serialized and added to
11277   // termination packets list.
11278   EXPECT_NE(nullptr,
11279             QuicConnectionPeer::GetConnectionClosePacket(&connection_));
11280 }
11281 
TEST_P(QuicConnectionTest,DoNotSendPing)11282 TEST_P(QuicConnectionTest, DoNotSendPing) {
11283   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11284   connection_.OnHandshakeComplete();
11285   EXPECT_TRUE(connection_.connected());
11286   EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
11287       .WillRepeatedly(Return(true));
11288   EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
11289   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
11290 
11291   SendStreamDataToPeer(
11292       GetNthClientInitiatedStreamId(0, connection_.transport_version()),
11293       "GET /", 0, FIN, nullptr);
11294   EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
11295   EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
11296   EXPECT_EQ(QuicTime::Delta::FromSeconds(15),
11297             connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
11298 
11299   // Now recevie an ACK and response of the previous packet, which will move the
11300   // ping alarm forward.
11301   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
11302   QuicFrames frames;
11303   QuicAckFrame ack_frame = InitAckFrame(1);
11304   frames.push_back(QuicFrame(&ack_frame));
11305   frames.push_back(QuicFrame(QuicStreamFrame(
11306       GetNthClientInitiatedStreamId(0, connection_.transport_version()), true,
11307       0u, absl::string_view())));
11308   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
11309   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
11310   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
11311   ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
11312   EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
11313   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
11314   // The ping timer is set slightly less than 15 seconds in the future, because
11315   // of the 1s ping timer alarm granularity.
11316   EXPECT_EQ(
11317       QuicTime::Delta::FromSeconds(15) - QuicTime::Delta::FromMilliseconds(5),
11318       connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
11319 
11320   clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
11321   // Suppose now ShouldKeepConnectionAlive returns false.
11322   EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
11323       .WillRepeatedly(Return(false));
11324   // Verify PING does not get sent.
11325   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
11326   connection_.GetPingAlarm()->Fire();
11327 }
11328 
11329 // Regression test for b/159698337
TEST_P(QuicConnectionTest,DuplicateAckCausesLostPackets)11330 TEST_P(QuicConnectionTest, DuplicateAckCausesLostPackets) {
11331   if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
11332     return;
11333   }
11334   // Finish handshake.
11335   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11336   notifier_.NeuterUnencryptedData();
11337   connection_.NeuterUnencryptedPackets();
11338   connection_.OnHandshakeComplete();
11339   EXPECT_CALL(visitor_, GetHandshakeState())
11340       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
11341 
11342   std::string data(1200, 'a');
11343   // Send data packets 1 - 5.
11344   for (size_t i = 0; i < 5; ++i) {
11345     SendStreamDataToPeer(
11346         GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
11347         i * 1200, i == 4 ? FIN : NO_FIN, nullptr);
11348   }
11349   ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
11350 
11351   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
11352       .Times(3);
11353 
11354   // ACK packet 5 and 1 and 2 are detected lost.
11355   QuicAckFrame frame =
11356       InitAckFrame({{QuicPacketNumber(5), QuicPacketNumber(6)}});
11357   LostPacketVector lost_packets;
11358   lost_packets.push_back(
11359       LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
11360   lost_packets.push_back(
11361       LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
11362   EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
11363       .Times(AnyNumber())
11364       .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
11365                       Return(LossDetectionInterface::DetectionStats())));
11366   ProcessAckPacket(1, &frame);
11367   EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
11368   QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
11369   EXPECT_TRUE(retransmission_alarm->IsSet());
11370 
11371   // ACK packet 1 - 5 and 7.
11372   QuicAckFrame frame2 =
11373       InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(6)},
11374                     {QuicPacketNumber(7), QuicPacketNumber(8)}});
11375   ProcessAckPacket(2, &frame2);
11376   EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
11377 
11378   // ACK packet 7 again and assume packet 6 is detected lost.
11379   QuicAckFrame frame3 =
11380       InitAckFrame({{QuicPacketNumber(7), QuicPacketNumber(8)}});
11381   lost_packets.clear();
11382   lost_packets.push_back(
11383       LostPacket(QuicPacketNumber(6), kMaxOutgoingPacketSize));
11384   EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
11385       .Times(AnyNumber())
11386       .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
11387                       Return(LossDetectionInterface::DetectionStats())));
11388   ProcessAckPacket(3, &frame3);
11389   // Make sure loss detection is cancelled even there is no new acked packets.
11390   EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
11391 }
11392 
TEST_P(QuicConnectionTest,ShorterIdleTimeoutOnSentPackets)11393 TEST_P(QuicConnectionTest, ShorterIdleTimeoutOnSentPackets) {
11394   EXPECT_TRUE(connection_.connected());
11395   RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11396   rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(100),
11397                        QuicTime::Delta::Zero(), QuicTime::Zero());
11398 
11399   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11400   QuicConfig config;
11401   config.SetClientConnectionOptions(QuicTagVector{kFIDT});
11402   QuicConfigPeer::SetNegotiated(&config, true);
11403   if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
11404     EXPECT_CALL(visitor_, GetHandshakeState())
11405         .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11406   }
11407   if (connection_.version().UsesTls()) {
11408     QuicConfigPeer::SetReceivedOriginalConnectionId(
11409         &config, connection_.connection_id());
11410     QuicConfigPeer::SetReceivedInitialSourceConnectionId(
11411         &config, connection_.connection_id());
11412   }
11413   connection_.SetFromConfig(config);
11414 
11415   ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11416   // Send a packet close to timeout.
11417   QuicTime::Delta timeout =
11418       connection_.GetTimeoutAlarm()->deadline() - clock_.Now();
11419   clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(1));
11420   // Send stream data.
11421   SendStreamDataToPeer(
11422       GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11423       0, FIN, nullptr);
11424   // Verify this sent packet does not extend idle timeout since 1s is > PTO
11425   // delay.
11426   ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11427   EXPECT_EQ(QuicTime::Delta::FromSeconds(1),
11428             connection_.GetTimeoutAlarm()->deadline() - clock_.Now());
11429 
11430   // Received an ACK 100ms later.
11431   clock_.AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(100));
11432   QuicAckFrame ack = InitAckFrame(1);
11433   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
11434   ProcessAckPacket(1, &ack);
11435   // Verify idle timeout gets extended.
11436   EXPECT_EQ(clock_.Now() + timeout, connection_.GetTimeoutAlarm()->deadline());
11437 }
11438 
11439 // Regression test for b/166255274
TEST_P(QuicConnectionTest,ReserializeInitialPacketInCoalescerAfterDiscardingInitialKey)11440 TEST_P(QuicConnectionTest,
11441        ReserializeInitialPacketInCoalescerAfterDiscardingInitialKey) {
11442   if (!connection_.version().CanSendCoalescedPackets()) {
11443     return;
11444   }
11445   connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11446   EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
11447   ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
11448   EXPECT_TRUE(connection_.HasPendingAcks());
11449   connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11450                            std::make_unique<TaggingEncrypter>(0x02));
11451   connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11452   EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
11453     connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
11454     connection_.NeuterUnencryptedPackets();
11455   }));
11456   {
11457     QuicConnection::ScopedPacketFlusher flusher(&connection_);
11458     connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
11459     // Verify the packet is on hold.
11460     EXPECT_EQ(0u, writer_->packets_write_attempts());
11461     // Flush pending ACKs.
11462     connection_.GetAckAlarm()->Fire();
11463   }
11464   EXPECT_FALSE(connection_.packet_creator().HasPendingFrames());
11465   // The ACK frame is deleted along with initial_packet_ in coalescer. Sending
11466   // connection close would cause this (released) ACK frame be serialized (and
11467   // crashes).
11468   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
11469   ProcessDataPacketAtLevel(1000, false, ENCRYPTION_FORWARD_SECURE);
11470   EXPECT_TRUE(connection_.connected());
11471 }
11472 
TEST_P(QuicConnectionTest,PathValidationOnNewSocketSuccess)11473 TEST_P(QuicConnectionTest, PathValidationOnNewSocketSuccess) {
11474   if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11475     return;
11476   }
11477   PathProbeTestInit(Perspective::IS_CLIENT);
11478   const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11479   EXPECT_NE(kNewSelfAddress, connection_.self_address());
11480   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11481   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11482       .Times(AtLeast(1u))
11483       .WillOnce(Invoke([&]() {
11484         EXPECT_EQ(1u, new_writer.packets_write_attempts());
11485         EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11486         EXPECT_EQ(1u, new_writer.padding_frames().size());
11487         EXPECT_EQ(kNewSelfAddress.host(),
11488                   new_writer.last_write_source_address());
11489       }));
11490   bool success = false;
11491   connection_.ValidatePath(
11492       std::make_unique<TestQuicPathValidationContext>(
11493           kNewSelfAddress, connection_.peer_address(), &new_writer),
11494       std::make_unique<TestValidationResultDelegate>(
11495           &connection_, kNewSelfAddress, connection_.peer_address(), &success),
11496       PathValidationReason::kReasonUnknown);
11497   EXPECT_EQ(0u, writer_->packets_write_attempts());
11498 
11499   QuicFrames frames;
11500   frames.push_back(QuicFrame(QuicPathResponseFrame(
11501       99, new_writer.path_challenge_frames().front().data_buffer)));
11502   ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
11503                                    ENCRYPTION_FORWARD_SECURE);
11504   EXPECT_TRUE(success);
11505 }
11506 
TEST_P(QuicConnectionTest,PathValidationOnNewSocketWriteBlocked)11507 TEST_P(QuicConnectionTest, PathValidationOnNewSocketWriteBlocked) {
11508   if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11509     return;
11510   }
11511   PathProbeTestInit(Perspective::IS_CLIENT);
11512   const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11513   EXPECT_NE(kNewSelfAddress, connection_.self_address());
11514   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11515   new_writer.SetWriteBlocked();
11516   bool success = false;
11517   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
11518   connection_.ValidatePath(
11519       std::make_unique<TestQuicPathValidationContext>(
11520           kNewSelfAddress, connection_.peer_address(), &new_writer),
11521       std::make_unique<TestValidationResultDelegate>(
11522           &connection_, kNewSelfAddress, connection_.peer_address(), &success),
11523       PathValidationReason::kReasonUnknown);
11524   EXPECT_EQ(0u, new_writer.packets_write_attempts());
11525   EXPECT_TRUE(connection_.HasPendingPathValidation());
11526 
11527   new_writer.SetWritable();
11528   // Retry after time out.
11529   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
11530   static_cast<test::MockRandom*>(helper_->GetRandomGenerator())->ChangeValue();
11531   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11532       .WillOnce(Invoke([&]() {
11533         EXPECT_EQ(1u, new_writer.packets_write_attempts());
11534         EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11535         EXPECT_EQ(1u, new_writer.padding_frames().size());
11536         EXPECT_EQ(kNewSelfAddress.host(),
11537                   new_writer.last_write_source_address());
11538       }));
11539   static_cast<TestAlarmFactory::TestAlarm*>(
11540       QuicPathValidatorPeer::retry_timer(
11541           QuicConnectionPeer::path_validator(&connection_)))
11542       ->Fire();
11543   EXPECT_EQ(1u, new_writer.packets_write_attempts());
11544 
11545   QuicFrames frames;
11546   QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
11547   frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
11548   new_writer.SetWriteBlocked();
11549   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11550       .WillRepeatedly(Invoke([&] {
11551         // Packets other than PATH_RESPONSE may be sent over the default writer.
11552         EXPECT_EQ(1u, new_writer.packets_write_attempts());
11553         EXPECT_TRUE(new_writer.path_response_frames().empty());
11554         EXPECT_EQ(1u, writer_->packets_write_attempts());
11555       }));
11556   ProcessFramesPacketWithAddresses(frames, kNewSelfAddress,
11557                                    connection_.peer_address(),
11558                                    ENCRYPTION_FORWARD_SECURE);
11559   EXPECT_EQ(1u, new_writer.packets_write_attempts());
11560 }
11561 
TEST_P(QuicConnectionTest,NewPathValidationCancelsPreviousOne)11562 TEST_P(QuicConnectionTest, NewPathValidationCancelsPreviousOne) {
11563   if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11564     return;
11565   }
11566   PathProbeTestInit(Perspective::IS_CLIENT);
11567   const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11568   EXPECT_NE(kNewSelfAddress, connection_.self_address());
11569   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11570   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11571       .Times(AtLeast(1u))
11572       .WillOnce(Invoke([&]() {
11573         EXPECT_EQ(1u, new_writer.packets_write_attempts());
11574         EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11575         EXPECT_EQ(1u, new_writer.padding_frames().size());
11576         EXPECT_EQ(kNewSelfAddress.host(),
11577                   new_writer.last_write_source_address());
11578       }));
11579   bool success = true;
11580   connection_.ValidatePath(
11581       std::make_unique<TestQuicPathValidationContext>(
11582           kNewSelfAddress, connection_.peer_address(), &new_writer),
11583       std::make_unique<TestValidationResultDelegate>(
11584           &connection_, kNewSelfAddress, connection_.peer_address(), &success),
11585       PathValidationReason::kReasonUnknown);
11586   EXPECT_EQ(0u, writer_->packets_write_attempts());
11587 
11588   // Start another path validation request.
11589   const QuicSocketAddress kNewSelfAddress2(QuicIpAddress::Any4(), 12346);
11590   EXPECT_NE(kNewSelfAddress2, connection_.self_address());
11591   TestPacketWriter new_writer2(version(), &clock_, Perspective::IS_CLIENT);
11592   bool success2 = false;
11593   connection_.ValidatePath(
11594       std::make_unique<TestQuicPathValidationContext>(
11595           kNewSelfAddress2, connection_.peer_address(), &new_writer2),
11596       std::make_unique<TestValidationResultDelegate>(
11597           &connection_, kNewSelfAddress2, connection_.peer_address(),
11598           &success2),
11599       PathValidationReason::kReasonUnknown);
11600   EXPECT_FALSE(success);
11601   // There is no pening path validation as there is no available connection ID.
11602   EXPECT_FALSE(connection_.HasPendingPathValidation());
11603 }
11604 
11605 // Regression test for b/182571515.
TEST_P(QuicConnectionTest,PathValidationRetry)11606 TEST_P(QuicConnectionTest, PathValidationRetry) {
11607   if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11608     return;
11609   }
11610   PathProbeTestInit(Perspective::IS_CLIENT);
11611 
11612   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11613       .Times(2u)
11614       .WillRepeatedly(Invoke([&]() {
11615         EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11616         EXPECT_EQ(1u, writer_->padding_frames().size());
11617       }));
11618   bool success = true;
11619   connection_.ValidatePath(std::make_unique<TestQuicPathValidationContext>(
11620                                connection_.self_address(),
11621                                connection_.peer_address(), writer_.get()),
11622                            std::make_unique<TestValidationResultDelegate>(
11623                                &connection_, connection_.self_address(),
11624                                connection_.peer_address(), &success),
11625                            PathValidationReason::kReasonUnknown);
11626   EXPECT_EQ(1u, writer_->packets_write_attempts());
11627   EXPECT_TRUE(connection_.HasPendingPathValidation());
11628 
11629   // Retry after time out.
11630   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
11631   static_cast<test::MockRandom*>(helper_->GetRandomGenerator())->ChangeValue();
11632   static_cast<TestAlarmFactory::TestAlarm*>(
11633       QuicPathValidatorPeer::retry_timer(
11634           QuicConnectionPeer::path_validator(&connection_)))
11635       ->Fire();
11636   EXPECT_EQ(2u, writer_->packets_write_attempts());
11637 }
11638 
TEST_P(QuicConnectionTest,PathValidationReceivesStatelessReset)11639 TEST_P(QuicConnectionTest, PathValidationReceivesStatelessReset) {
11640   if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11641     return;
11642   }
11643   PathProbeTestInit(Perspective::IS_CLIENT);
11644   QuicConfig config;
11645   QuicConfigPeer::SetReceivedStatelessResetToken(&config,
11646                                                  kTestStatelessResetToken);
11647   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11648   connection_.SetFromConfig(config);
11649   const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11650   EXPECT_NE(kNewSelfAddress, connection_.self_address());
11651   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11652   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11653       .Times(AtLeast(1u))
11654       .WillOnce(Invoke([&]() {
11655         EXPECT_EQ(1u, new_writer.packets_write_attempts());
11656         EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11657         EXPECT_EQ(1u, new_writer.padding_frames().size());
11658         EXPECT_EQ(kNewSelfAddress.host(),
11659                   new_writer.last_write_source_address());
11660       }));
11661   bool success = true;
11662   connection_.ValidatePath(
11663       std::make_unique<TestQuicPathValidationContext>(
11664           kNewSelfAddress, connection_.peer_address(), &new_writer),
11665       std::make_unique<TestValidationResultDelegate>(
11666           &connection_, kNewSelfAddress, connection_.peer_address(), &success),
11667       PathValidationReason::kReasonUnknown);
11668   EXPECT_EQ(0u, writer_->packets_write_attempts());
11669   EXPECT_TRUE(connection_.HasPendingPathValidation());
11670 
11671   std::unique_ptr<QuicEncryptedPacket> packet(
11672       QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
11673                                                 /*received_packet_length=*/100,
11674                                                 kTestStatelessResetToken));
11675   std::unique_ptr<QuicReceivedPacket> received(
11676       ConstructReceivedPacket(*packet, QuicTime::Zero()));
11677   EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
11678   connection_.ProcessUdpPacket(kNewSelfAddress, kPeerAddress, *received);
11679   EXPECT_FALSE(connection_.HasPendingPathValidation());
11680   EXPECT_FALSE(success);
11681 }
11682 
11683 // Tests that PATH_CHALLENGE is dropped if it is sent via a blocked alternative
11684 // writer.
TEST_P(QuicConnectionTest,SendPathChallengeUsingBlockedNewSocket)11685 TEST_P(QuicConnectionTest, SendPathChallengeUsingBlockedNewSocket) {
11686   if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11687     return;
11688   }
11689   PathProbeTestInit(Perspective::IS_CLIENT);
11690   const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11691   EXPECT_NE(kNewSelfAddress, connection_.self_address());
11692   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11693   new_writer.BlockOnNextWrite();
11694   EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
11695   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11696       .Times(AtLeast(1))
11697       .WillOnce(Invoke([&]() {
11698         // Even though the socket is blocked, the PATH_CHALLENGE should still be
11699         // treated as sent.
11700         EXPECT_EQ(1u, new_writer.packets_write_attempts());
11701         EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11702         EXPECT_EQ(1u, new_writer.padding_frames().size());
11703         EXPECT_EQ(kNewSelfAddress.host(),
11704                   new_writer.last_write_source_address());
11705       }));
11706   bool success = false;
11707   connection_.ValidatePath(
11708       std::make_unique<TestQuicPathValidationContext>(
11709           kNewSelfAddress, connection_.peer_address(), &new_writer),
11710       std::make_unique<TestValidationResultDelegate>(
11711           &connection_, kNewSelfAddress, connection_.peer_address(), &success),
11712       PathValidationReason::kReasonUnknown);
11713   EXPECT_EQ(0u, writer_->packets_write_attempts());
11714 
11715   new_writer.SetWritable();
11716   // Write event on the default socket shouldn't make any difference.
11717   connection_.OnCanWrite();
11718   // A NEW_CONNECTION_ID frame is received in PathProbeTestInit and OnCanWrite
11719   // will write a acking packet.
11720   EXPECT_EQ(1u, writer_->packets_write_attempts());
11721   EXPECT_EQ(1u, new_writer.packets_write_attempts());
11722 }
11723 
11724 //  Tests that PATH_CHALLENGE is dropped if it is sent via the default writer
11725 //  and the writer is blocked.
TEST_P(QuicConnectionTest,SendPathChallengeUsingBlockedDefaultSocket)11726 TEST_P(QuicConnectionTest, SendPathChallengeUsingBlockedDefaultSocket) {
11727   if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11728     return;
11729   }
11730   PathProbeTestInit(Perspective::IS_SERVER);
11731   const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Any4(), 12345);
11732   writer_->BlockOnNextWrite();
11733   // 1st time is after writer returns WRITE_STATUS_BLOCKED. 2nd time is in
11734   // ShouldGeneratePacket().
11735   EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(2));
11736   QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
11737   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11738       .Times(AtLeast(1u))
11739       .WillOnce(Invoke([&]() {
11740         // This packet isn't sent actually, instead it is buffered in the
11741         // connection.
11742         EXPECT_EQ(1u, writer_->packets_write_attempts());
11743         EXPECT_EQ(1u, writer_->path_response_frames().size());
11744         EXPECT_EQ(0,
11745                   memcmp(&path_challenge_payload,
11746                          &writer_->path_response_frames().front().data_buffer,
11747                          sizeof(path_challenge_payload)));
11748         EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11749         EXPECT_EQ(1u, writer_->padding_frames().size());
11750         EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11751       }))
11752       .WillRepeatedly(Invoke([&]() {
11753         // Only one PATH_CHALLENGE should be sent out.
11754         EXPECT_EQ(0u, writer_->path_challenge_frames().size());
11755       }));
11756   // Receiving a PATH_CHALLENGE from the new peer address should trigger address
11757   // validation.
11758   QuicFrames frames;
11759   frames.push_back(
11760       QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
11761   ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
11762                                    ENCRYPTION_FORWARD_SECURE);
11763   EXPECT_EQ(1u, writer_->packets_write_attempts());
11764 
11765   // Try again with the new socket blocked from the beginning. The 2nd
11766   // PATH_CHALLENGE shouldn't be serialized, but be dropped.
11767   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
11768   static_cast<test::MockRandom*>(helper_->GetRandomGenerator())->ChangeValue();
11769   static_cast<TestAlarmFactory::TestAlarm*>(
11770       QuicPathValidatorPeer::retry_timer(
11771           QuicConnectionPeer::path_validator(&connection_)))
11772       ->Fire();
11773 
11774   // No more write attempt should be made.
11775   EXPECT_EQ(1u, writer_->packets_write_attempts());
11776 
11777   writer_->SetWritable();
11778   // OnCanWrite() should actually write out the 1st PATH_CHALLENGE packet
11779   // buffered earlier, thus incrementing the write counter. It may also send
11780   // ACKs to previously received packets.
11781   connection_.OnCanWrite();
11782   EXPECT_LE(2u, writer_->packets_write_attempts());
11783 }
11784 
11785 // Tests that write error on the alternate socket should be ignored.
TEST_P(QuicConnectionTest,SendPathChallengeFailOnNewSocket)11786 TEST_P(QuicConnectionTest, SendPathChallengeFailOnNewSocket) {
11787   if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11788     return;
11789   }
11790   PathProbeTestInit(Perspective::IS_CLIENT);
11791   const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11792   EXPECT_NE(kNewSelfAddress, connection_.self_address());
11793   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11794   new_writer.SetShouldWriteFail();
11795   EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
11796       .Times(0);
11797   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
11798 
11799   bool success = false;
11800   connection_.ValidatePath(
11801       std::make_unique<TestQuicPathValidationContext>(
11802           kNewSelfAddress, connection_.peer_address(), &new_writer),
11803       std::make_unique<TestValidationResultDelegate>(
11804           &connection_, kNewSelfAddress, connection_.peer_address(), &success),
11805       PathValidationReason::kReasonUnknown);
11806   EXPECT_EQ(1u, new_writer.packets_write_attempts());
11807   EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11808   EXPECT_EQ(1u, new_writer.padding_frames().size());
11809   EXPECT_EQ(kNewSelfAddress.host(), new_writer.last_write_source_address());
11810 
11811   EXPECT_EQ(0u, writer_->packets_write_attempts());
11812   //  Regardless of the write error, the connection should still be connected.
11813   EXPECT_TRUE(connection_.connected());
11814 }
11815 
11816 // Tests that write error while sending PATH_CHALLANGE from the default socket
11817 // should close the connection.
TEST_P(QuicConnectionTest,SendPathChallengeFailOnDefaultPath)11818 TEST_P(QuicConnectionTest, SendPathChallengeFailOnDefaultPath) {
11819   if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11820     return;
11821   }
11822   PathProbeTestInit(Perspective::IS_CLIENT);
11823 
11824   writer_->SetShouldWriteFail();
11825   EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
11826       .WillOnce(
11827           Invoke([](QuicConnectionCloseFrame frame, ConnectionCloseSource) {
11828             EXPECT_EQ(QUIC_PACKET_WRITE_ERROR, frame.quic_error_code);
11829           }));
11830   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
11831   {
11832     // Add a flusher to force flush, otherwise the frames will remain in the
11833     // packet creator.
11834     bool success = false;
11835     QuicConnection::ScopedPacketFlusher flusher(&connection_);
11836     connection_.ValidatePath(std::make_unique<TestQuicPathValidationContext>(
11837                                  connection_.self_address(),
11838                                  connection_.peer_address(), writer_.get()),
11839                              std::make_unique<TestValidationResultDelegate>(
11840                                  &connection_, connection_.self_address(),
11841                                  connection_.peer_address(), &success),
11842                              PathValidationReason::kReasonUnknown);
11843   }
11844   EXPECT_EQ(1u, writer_->packets_write_attempts());
11845   EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11846   EXPECT_EQ(1u, writer_->padding_frames().size());
11847   EXPECT_EQ(connection_.peer_address(), writer_->last_write_peer_address());
11848   EXPECT_FALSE(connection_.connected());
11849   // Closing connection should abandon ongoing path validation.
11850   EXPECT_FALSE(connection_.HasPendingPathValidation());
11851 }
11852 
TEST_P(QuicConnectionTest,SendPathChallengeFailOnAlternativePeerAddress)11853 TEST_P(QuicConnectionTest, SendPathChallengeFailOnAlternativePeerAddress) {
11854   if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11855     return;
11856   }
11857   PathProbeTestInit(Perspective::IS_CLIENT);
11858 
11859   writer_->SetShouldWriteFail();
11860   const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Any4(), 12345);
11861   EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
11862       .WillOnce(
11863           Invoke([](QuicConnectionCloseFrame frame, ConnectionCloseSource) {
11864             EXPECT_EQ(QUIC_PACKET_WRITE_ERROR, frame.quic_error_code);
11865           }));
11866   // Sending PATH_CHALLENGE to trigger a flush write which will fail and close
11867   // the connection.
11868   bool success = false;
11869   connection_.ValidatePath(
11870       std::make_unique<TestQuicPathValidationContext>(
11871           connection_.self_address(), kNewPeerAddress, writer_.get()),
11872       std::make_unique<TestValidationResultDelegate>(
11873           &connection_, connection_.self_address(), kNewPeerAddress, &success),
11874       PathValidationReason::kReasonUnknown);
11875 
11876   EXPECT_EQ(1u, writer_->packets_write_attempts());
11877   EXPECT_FALSE(connection_.HasPendingPathValidation());
11878   EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11879   EXPECT_EQ(1u, writer_->padding_frames().size());
11880   EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11881   EXPECT_FALSE(connection_.connected());
11882 }
11883 
TEST_P(QuicConnectionTest,SendPathChallengeFailPacketTooBigOnAlternativePeerAddress)11884 TEST_P(QuicConnectionTest,
11885        SendPathChallengeFailPacketTooBigOnAlternativePeerAddress) {
11886   if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11887     return;
11888   }
11889   PathProbeTestInit(Perspective::IS_CLIENT);
11890   // Make sure there is no outstanding ACK_FRAME to write.
11891   connection_.OnCanWrite();
11892   uint32_t num_packets_write_attempts = writer_->packets_write_attempts();
11893 
11894   writer_->SetShouldWriteFail();
11895   writer_->SetWriteError(*writer_->MessageTooBigErrorCode());
11896   const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Any4(), 12345);
11897   EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
11898       .Times(0u);
11899   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
11900   // Sending PATH_CHALLENGE to trigger a flush write which will fail with
11901   // MSG_TOO_BIG.
11902   bool success = false;
11903   connection_.ValidatePath(
11904       std::make_unique<TestQuicPathValidationContext>(
11905           connection_.self_address(), kNewPeerAddress, writer_.get()),
11906       std::make_unique<TestValidationResultDelegate>(
11907           &connection_, connection_.self_address(), kNewPeerAddress, &success),
11908       PathValidationReason::kReasonUnknown);
11909   EXPECT_TRUE(connection_.HasPendingPathValidation());
11910   // Connection shouldn't be closed.
11911   EXPECT_TRUE(connection_.connected());
11912   EXPECT_EQ(++num_packets_write_attempts, writer_->packets_write_attempts());
11913   EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11914   EXPECT_EQ(1u, writer_->padding_frames().size());
11915   EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11916 }
11917 
11918 // Check that if there are two PATH_CHALLENGE frames in the packet, the latter
11919 // one is ignored.
TEST_P(QuicConnectionTest,ReceiveMultiplePathChallenge)11920 TEST_P(QuicConnectionTest, ReceiveMultiplePathChallenge) {
11921   if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11922     return;
11923   }
11924   PathProbeTestInit(Perspective::IS_SERVER);
11925 
11926   QuicPathFrameBuffer path_frame_buffer1{0, 1, 2, 3, 4, 5, 6, 7};
11927   QuicPathFrameBuffer path_frame_buffer2{8, 9, 10, 11, 12, 13, 14, 15};
11928   QuicFrames frames;
11929   frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer1)));
11930   frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer2)));
11931   const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(),
11932                                           /*port=*/23456);
11933 
11934   EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
11935 
11936   // Expect 2 packets to be sent: the first are padded PATH_RESPONSE(s) to the
11937   // alternative peer address. The 2nd is a ACK-only packet to the original
11938   // peer address.
11939   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11940       .Times(2)
11941       .WillOnce(Invoke([=]() {
11942         EXPECT_EQ(1u, writer_->path_response_frames().size());
11943         // The final check is to ensure that the random data in the response
11944         // matches the random data from the challenge.
11945         EXPECT_EQ(0,
11946                   memcmp(path_frame_buffer1.data(),
11947                          &(writer_->path_response_frames().front().data_buffer),
11948                          sizeof(path_frame_buffer1)));
11949         EXPECT_EQ(1u, writer_->padding_frames().size());
11950         EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11951       }))
11952       .WillOnce(Invoke([=]() {
11953         // The last write of ACK-only packet should still use the old peer
11954         // address.
11955         EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
11956       }));
11957   ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
11958                                    ENCRYPTION_FORWARD_SECURE);
11959 }
11960 
TEST_P(QuicConnectionTest,ReceiveStreamFrameBeforePathChallenge)11961 TEST_P(QuicConnectionTest, ReceiveStreamFrameBeforePathChallenge) {
11962   if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11963     return;
11964   }
11965   PathProbeTestInit(Perspective::IS_SERVER);
11966 
11967   QuicFrames frames;
11968   frames.push_back(QuicFrame(frame1_));
11969   QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
11970   frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
11971   frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
11972   const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
11973                                           /*port=*/23456);
11974 
11975   EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE));
11976   EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(0u);
11977   EXPECT_CALL(visitor_, OnStreamFrame(_))
11978       .WillOnce(Invoke([=](const QuicStreamFrame& frame) {
11979         // Send some data on the stream. The STREAM_FRAME should be built into
11980         // one packet together with the latter PATH_RESPONSE and PATH_CHALLENGE.
11981         const std::string data{"response body"};
11982         connection_.producer()->SaveStreamData(frame.stream_id, data);
11983         return notifier_.WriteOrBufferData(frame.stream_id, data.length(),
11984                                            NO_FIN);
11985       }));
11986   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
11987   ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
11988                                    ENCRYPTION_FORWARD_SECURE);
11989 
11990   // Verify that this packet contains a STREAM_FRAME and a
11991   // PATH_RESPONSE_FRAME.
11992   EXPECT_EQ(1u, writer_->stream_frames().size());
11993   EXPECT_EQ(1u, writer_->path_response_frames().size());
11994   EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11995   // The final check is to ensure that the random data in the response
11996   // matches the random data from the challenge.
11997   EXPECT_EQ(0, memcmp(path_frame_buffer.data(),
11998                       &(writer_->path_response_frames().front().data_buffer),
11999                       sizeof(path_frame_buffer)));
12000   EXPECT_EQ(1u, writer_->path_challenge_frames().size());
12001   EXPECT_EQ(1u, writer_->padding_frames().size());
12002   EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
12003   EXPECT_TRUE(connection_.HasPendingPathValidation());
12004 }
12005 
TEST_P(QuicConnectionTest,ReceiveStreamFrameFollowingPathChallenge)12006 TEST_P(QuicConnectionTest, ReceiveStreamFrameFollowingPathChallenge) {
12007   if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
12008     return;
12009   }
12010   PathProbeTestInit(Perspective::IS_SERVER);
12011 
12012   QuicFrames frames;
12013   QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
12014   frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
12015   // PATH_RESPONSE should be flushed out before the rest packet is parsed.
12016   frames.push_back(QuicFrame(frame1_));
12017   const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
12018                                           /*port=*/23456);
12019   QuicByteCount received_packet_size;
12020   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
12021       .Times(AtLeast(1u))
12022       .WillOnce(Invoke([=, &received_packet_size]() {
12023         // Verify that this packet contains a PATH_RESPONSE_FRAME.
12024         EXPECT_EQ(0u, writer_->stream_frames().size());
12025         EXPECT_EQ(1u, writer_->path_response_frames().size());
12026         // The final check is to ensure that the random data in the response
12027         // matches the random data from the challenge.
12028         EXPECT_EQ(0,
12029                   memcmp(path_frame_buffer.data(),
12030                          &(writer_->path_response_frames().front().data_buffer),
12031                          sizeof(path_frame_buffer)));
12032         EXPECT_EQ(1u, writer_->path_challenge_frames().size());
12033         EXPECT_EQ(1u, writer_->padding_frames().size());
12034         EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
12035         received_packet_size =
12036             QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_);
12037       }));
12038   EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE));
12039   EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(0u);
12040   EXPECT_CALL(visitor_, OnStreamFrame(_))
12041       .WillOnce(Invoke([=](const QuicStreamFrame& frame) {
12042         // Send some data on the stream. The STREAM_FRAME should be built into a
12043         // new packet but throttled by anti-amplifciation limit.
12044         const std::string data{"response body"};
12045         connection_.producer()->SaveStreamData(frame.stream_id, data);
12046         return notifier_.WriteOrBufferData(frame.stream_id, data.length(),
12047                                            NO_FIN);
12048       }));
12049 
12050   ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
12051                                    ENCRYPTION_FORWARD_SECURE);
12052   EXPECT_TRUE(connection_.HasPendingPathValidation());
12053   EXPECT_EQ(0u,
12054             QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
12055   EXPECT_EQ(
12056       received_packet_size,
12057       QuicConnectionPeer::BytesReceivedBeforeAddressValidation(&connection_));
12058 }
12059 
12060 // Tests that a PATH_CHALLENGE is received in between other frames in an out of
12061 // order packet.
TEST_P(QuicConnectionTest,PathChallengeWithDataInOutOfOrderPacket)12062 TEST_P(QuicConnectionTest, PathChallengeWithDataInOutOfOrderPacket) {
12063   if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
12064     return;
12065   }
12066   PathProbeTestInit(Perspective::IS_SERVER);
12067 
12068   QuicFrames frames;
12069   frames.push_back(QuicFrame(frame1_));
12070   QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
12071   frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
12072   frames.push_back(QuicFrame(frame2_));
12073   const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(),
12074                                           /*port=*/23456);
12075 
12076   EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0u);
12077   EXPECT_CALL(visitor_, OnStreamFrame(_))
12078       .Times(2)
12079       .WillRepeatedly(Invoke([=](const QuicStreamFrame& frame) {
12080         // Send some data on the stream. The STREAM_FRAME should be built into
12081         // one packet together with the latter PATH_RESPONSE.
12082         const std::string data{"response body"};
12083         connection_.producer()->SaveStreamData(frame.stream_id, data);
12084         return notifier_.WriteOrBufferData(frame.stream_id, data.length(),
12085                                            NO_FIN);
12086       }));
12087   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
12088       .WillOnce(Invoke([=]() {
12089         // Verify that this packet contains a STREAM_FRAME and is sent to the
12090         // original peer address.
12091         EXPECT_EQ(1u, writer_->stream_frames().size());
12092         // No connection migration should happen because the packet is received
12093         // out of order.
12094         EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
12095       }))
12096       .WillOnce(Invoke([=]() {
12097         EXPECT_EQ(1u, writer_->path_response_frames().size());
12098         // The final check is to ensure that the random data in the response
12099         // matches the random data from the challenge.
12100         EXPECT_EQ(0,
12101                   memcmp(path_frame_buffer.data(),
12102                          &(writer_->path_response_frames().front().data_buffer),
12103                          sizeof(path_frame_buffer)));
12104         EXPECT_EQ(1u, writer_->padding_frames().size());
12105         // PATH_RESPONSE should be sent in another packet to a different peer
12106         // address.
12107         EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
12108       }))
12109       .WillOnce(Invoke([=]() {
12110         // Verify that this packet contains a STREAM_FRAME and is sent to the
12111         // original peer address.
12112         EXPECT_EQ(1u, writer_->stream_frames().size());
12113         // No connection migration should happen because the packet is received
12114         // out of order.
12115         EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
12116       }));
12117   // Lower the packet number so that receiving this packet shouldn't trigger
12118   // peer migration.
12119   QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
12120   ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
12121                                    ENCRYPTION_FORWARD_SECURE);
12122 }
12123 
12124 // Tests that a PATH_CHALLENGE is cached if its PATH_RESPONSE can't be sent.
TEST_P(QuicConnectionTest,FailToWritePathResponseAtServer)12125 TEST_P(QuicConnectionTest, FailToWritePathResponseAtServer) {
12126   if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
12127     return;
12128   }
12129   PathProbeTestInit(Perspective::IS_SERVER);
12130 
12131   QuicFrames frames;
12132   QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
12133   frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
12134   const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(),
12135                                           /*port=*/23456);
12136 
12137   EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0u);
12138   // Lower the packet number so that receiving this packet shouldn't trigger
12139   // peer migration.
12140   QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
12141   EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
12142   writer_->SetWriteBlocked();
12143   ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
12144                                    ENCRYPTION_FORWARD_SECURE);
12145 }
12146 
12147 // Regression test for b/168101557.
TEST_P(QuicConnectionTest,HandshakeDataDoesNotGetPtoed)12148 TEST_P(QuicConnectionTest, HandshakeDataDoesNotGetPtoed) {
12149   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
12150     return;
12151   }
12152   set_perspective(Perspective::IS_SERVER);
12153   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
12154     EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
12155   }
12156   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
12157   ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
12158   EXPECT_TRUE(connection_.HasPendingAcks());
12159 
12160   connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
12161   // Send INITIAL 1.
12162   connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
12163 
12164   connection_.SetEncrypter(
12165       ENCRYPTION_HANDSHAKE,
12166       std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
12167   connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12168   SetDecrypter(ENCRYPTION_HANDSHAKE,
12169                std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
12170   // Send HANDSHAKE packets.
12171   EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
12172   connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
12173 
12174   connection_.SetEncrypter(
12175       ENCRYPTION_FORWARD_SECURE,
12176       std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
12177   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12178   // Send half RTT packet.
12179   connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
12180 
12181   // Receives HANDSHAKE 1.
12182   peer_framer_.SetEncrypter(
12183       ENCRYPTION_HANDSHAKE,
12184       std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
12185   ProcessCryptoPacketAtLevel(1, ENCRYPTION_HANDSHAKE);
12186   // Discard INITIAL key.
12187   connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12188   connection_.NeuterUnencryptedPackets();
12189   // Verify there is pending ACK.
12190   ASSERT_TRUE(connection_.HasPendingAcks());
12191   // Set the send alarm.
12192   connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
12193 
12194   // Fire ACK alarm.
12195   connection_.GetAckAlarm()->Fire();
12196   // Verify 1-RTT packet is coalesced with handshake packet.
12197   EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
12198   connection_.GetSendAlarm()->Fire();
12199 
12200   ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
12201   connection_.GetRetransmissionAlarm()->Fire();
12202   // Verify a handshake packet gets PTOed and 1-RTT packet gets coalesced.
12203   EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
12204 }
12205 
12206 // Regression test for b/168294218.
TEST_P(QuicConnectionTest,CoalescerHandlesInitialKeyDiscard)12207 TEST_P(QuicConnectionTest, CoalescerHandlesInitialKeyDiscard) {
12208   if (!connection_.version().CanSendCoalescedPackets()) {
12209     return;
12210   }
12211   SetQuicReloadableFlag(quic_discard_initial_packet_with_key_dropped, true);
12212   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
12213   EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
12214     connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12215     connection_.NeuterUnencryptedPackets();
12216   }));
12217   EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
12218 
12219   EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
12220   {
12221     QuicConnection::ScopedPacketFlusher flusher(&connection_);
12222     ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
12223     clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
12224     connection_.SetEncrypter(
12225         ENCRYPTION_HANDSHAKE,
12226         std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
12227     connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12228     connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0);
12229     // Verify this packet is on hold.
12230     EXPECT_EQ(0u, writer_->packets_write_attempts());
12231   }
12232   EXPECT_TRUE(connection_.connected());
12233 }
12234 
12235 // Regresstion test for b/168294218
TEST_P(QuicConnectionTest,ZeroRttRejectionAndMissingInitialKeys)12236 TEST_P(QuicConnectionTest, ZeroRttRejectionAndMissingInitialKeys) {
12237   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
12238     return;
12239   }
12240   // Not defer send in response to packet.
12241   connection_.set_defer_send_in_response_to_packets(false);
12242   EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
12243     connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12244     connection_.NeuterUnencryptedPackets();
12245   }));
12246   EXPECT_CALL(visitor_, OnCryptoFrame(_))
12247       .WillRepeatedly(Invoke([=](const QuicCryptoFrame& frame) {
12248         if (frame.level == ENCRYPTION_HANDSHAKE) {
12249           // 0-RTT gets rejected.
12250           connection_.MarkZeroRttPacketsForRetransmission(0);
12251           // Send Crypto data.
12252           connection_.SetEncrypter(
12253               ENCRYPTION_HANDSHAKE,
12254               std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
12255           connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12256           connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
12257           connection_.SetEncrypter(
12258               ENCRYPTION_FORWARD_SECURE,
12259               std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
12260           connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12261           // Advance INITIAL ack delay to trigger initial ACK to be sent AFTER
12262           // the retransmission of rejected 0-RTT packets while the HANDSHAKE
12263           // packet is still in the coalescer, such that the INITIAL key gets
12264           // dropped between SendAllPendingAcks and actually send the ack frame,
12265           // bummer.
12266           clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
12267         }
12268       }));
12269   connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
12270   // Send 0-RTT packet.
12271   connection_.SetEncrypter(
12272       ENCRYPTION_ZERO_RTT,
12273       std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
12274   connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
12275   connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
12276 
12277   QuicAckFrame frame1 = InitAckFrame(1);
12278   // Received ACK for packet 1.
12279   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
12280   ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
12281   EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
12282 
12283   // Fire retransmission alarm.
12284   connection_.GetRetransmissionAlarm()->Fire();
12285 
12286   QuicFrames frames1;
12287   frames1.push_back(QuicFrame(&crypto_frame_));
12288   QuicFrames frames2;
12289   QuicCryptoFrame crypto_frame(ENCRYPTION_HANDSHAKE, 0,
12290                                absl::string_view(data1));
12291   frames2.push_back(QuicFrame(&crypto_frame));
12292   ProcessCoalescedPacket(
12293       {{2, frames1, ENCRYPTION_INITIAL}, {3, frames2, ENCRYPTION_HANDSHAKE}});
12294 }
12295 
TEST_P(QuicConnectionTest,OnZeroRttPacketAcked)12296 TEST_P(QuicConnectionTest, OnZeroRttPacketAcked) {
12297   if (!connection_.version().UsesTls()) {
12298     return;
12299   }
12300   MockQuicConnectionDebugVisitor debug_visitor;
12301   connection_.set_debug_visitor(&debug_visitor);
12302   connection_.SendCryptoStreamData();
12303   // Send 0-RTT packet.
12304   connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
12305                            std::make_unique<TaggingEncrypter>(0x02));
12306   connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
12307   connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
12308   connection_.SendStreamDataWithString(4, "bar", 0, NO_FIN);
12309   // Received ACK for packet 1, HANDSHAKE packet and 1-RTT ACK.
12310   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
12311       .Times(AnyNumber());
12312   QuicFrames frames1;
12313   QuicAckFrame ack_frame1 = InitAckFrame(1);
12314   frames1.push_back(QuicFrame(&ack_frame1));
12315 
12316   QuicFrames frames2;
12317   QuicCryptoFrame crypto_frame(ENCRYPTION_HANDSHAKE, 0,
12318                                absl::string_view(data1));
12319   frames2.push_back(QuicFrame(&crypto_frame));
12320   EXPECT_CALL(debug_visitor, OnZeroRttPacketAcked()).Times(0);
12321   EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
12322   ProcessCoalescedPacket(
12323       {{1, frames1, ENCRYPTION_INITIAL}, {2, frames2, ENCRYPTION_HANDSHAKE}});
12324 
12325   QuicFrames frames3;
12326   QuicAckFrame ack_frame2 =
12327       InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
12328   frames3.push_back(QuicFrame(&ack_frame2));
12329   EXPECT_CALL(debug_visitor, OnZeroRttPacketAcked()).Times(1);
12330   ProcessCoalescedPacket({{3, frames3, ENCRYPTION_FORWARD_SECURE}});
12331 
12332   QuicFrames frames4;
12333   QuicAckFrame ack_frame3 =
12334       InitAckFrame({{QuicPacketNumber(3), QuicPacketNumber(4)}});
12335   frames4.push_back(QuicFrame(&ack_frame3));
12336   EXPECT_CALL(debug_visitor, OnZeroRttPacketAcked()).Times(0);
12337   ProcessCoalescedPacket({{4, frames4, ENCRYPTION_FORWARD_SECURE}});
12338 }
12339 
TEST_P(QuicConnectionTest,InitiateKeyUpdate)12340 TEST_P(QuicConnectionTest, InitiateKeyUpdate) {
12341   if (!connection_.version().UsesTls()) {
12342     return;
12343   }
12344 
12345   TransportParameters params;
12346   QuicConfig config;
12347   std::string error_details;
12348   EXPECT_THAT(config.ProcessTransportParameters(
12349                   params, /* is_resumption = */ false, &error_details),
12350               IsQuicNoError());
12351   QuicConfigPeer::SetNegotiated(&config, true);
12352   if (connection_.version().UsesTls()) {
12353     QuicConfigPeer::SetReceivedOriginalConnectionId(
12354         &config, connection_.connection_id());
12355     QuicConfigPeer::SetReceivedInitialSourceConnectionId(
12356         &config, connection_.connection_id());
12357   }
12358   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12359   connection_.SetFromConfig(config);
12360 
12361   EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12362 
12363   MockFramerVisitor peer_framer_visitor_;
12364   peer_framer_.set_visitor(&peer_framer_visitor_);
12365 
12366   uint8_t correct_tag = ENCRYPTION_FORWARD_SECURE;
12367   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12368   connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12369                            std::make_unique<TaggingEncrypter>(correct_tag));
12370   SetDecrypter(ENCRYPTION_FORWARD_SECURE,
12371                std::make_unique<StrictTaggingDecrypter>(correct_tag));
12372   EXPECT_CALL(visitor_, GetHandshakeState())
12373       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12374   connection_.OnHandshakeComplete();
12375 
12376   peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12377                             std::make_unique<TaggingEncrypter>(correct_tag));
12378 
12379   // Key update should still not be allowed, since no packet has been acked
12380   // from the current key phase.
12381   EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12382   EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12383 
12384   // Send packet 1.
12385   QuicPacketNumber last_packet;
12386   SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
12387   EXPECT_EQ(QuicPacketNumber(1u), last_packet);
12388 
12389   // Key update should still not be allowed, even though a packet was sent in
12390   // the current key phase it hasn't been acked yet.
12391   EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12392   EXPECT_TRUE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12393 
12394   EXPECT_FALSE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12395   // Receive ack for packet 1.
12396   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
12397   QuicAckFrame frame1 = InitAckFrame(1);
12398   ProcessAckPacket(&frame1);
12399 
12400   // OnDecryptedFirstPacketInKeyPhase is called even on the first key phase,
12401   // so discard_previous_keys_alarm_ should be set now.
12402   EXPECT_TRUE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12403   EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12404 
12405   correct_tag++;
12406   // Key update should now be allowed.
12407   EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
12408       .WillOnce([&correct_tag]() {
12409         return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12410       });
12411   EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter())
12412       .WillOnce([&correct_tag]() {
12413         return std::make_unique<TaggingEncrypter>(correct_tag);
12414       });
12415   EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
12416   EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
12417   // discard_previous_keys_alarm_ should not be set until a packet from the new
12418   // key phase has been received. (The alarm that was set above should be
12419   // cleared if it hasn't fired before the next key update happened.)
12420   EXPECT_FALSE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12421   EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12422 
12423   // Pretend that peer accepts the key update.
12424   EXPECT_CALL(peer_framer_visitor_,
12425               AdvanceKeysAndCreateCurrentOneRttDecrypter())
12426       .WillOnce([&correct_tag]() {
12427         return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12428       });
12429   EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
12430       .WillOnce([&correct_tag]() {
12431         return std::make_unique<TaggingEncrypter>(correct_tag);
12432       });
12433   peer_framer_.SetKeyUpdateSupportForConnection(true);
12434   peer_framer_.DoKeyUpdate(KeyUpdateReason::kRemote);
12435 
12436   // Another key update should not be allowed yet.
12437   EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12438 
12439   // Send packet 2.
12440   SendStreamDataToPeer(2, "bar", 0, NO_FIN, &last_packet);
12441   EXPECT_EQ(QuicPacketNumber(2u), last_packet);
12442   EXPECT_TRUE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12443   // Receive ack for packet 2.
12444   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
12445   QuicAckFrame frame2 = InitAckFrame(2);
12446   ProcessAckPacket(&frame2);
12447   EXPECT_TRUE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12448   EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12449 
12450   correct_tag++;
12451   // Key update should be allowed again now that a packet has been acked from
12452   // the current key phase.
12453   EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
12454       .WillOnce([&correct_tag]() {
12455         return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12456       });
12457   EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter())
12458       .WillOnce([&correct_tag]() {
12459         return std::make_unique<TaggingEncrypter>(correct_tag);
12460       });
12461   EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
12462   EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
12463 
12464   // Pretend that peer accepts the key update.
12465   EXPECT_CALL(peer_framer_visitor_,
12466               AdvanceKeysAndCreateCurrentOneRttDecrypter())
12467       .WillOnce([&correct_tag]() {
12468         return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12469       });
12470   EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
12471       .WillOnce([&correct_tag]() {
12472         return std::make_unique<TaggingEncrypter>(correct_tag);
12473       });
12474   peer_framer_.DoKeyUpdate(KeyUpdateReason::kRemote);
12475 
12476   // Another key update should not be allowed yet.
12477   EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12478 
12479   // Send packet 3.
12480   SendStreamDataToPeer(3, "baz", 0, NO_FIN, &last_packet);
12481   EXPECT_EQ(QuicPacketNumber(3u), last_packet);
12482 
12483   // Another key update should not be allowed yet.
12484   EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12485   EXPECT_TRUE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12486 
12487   // Receive ack for packet 3.
12488   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
12489   QuicAckFrame frame3 = InitAckFrame(3);
12490   ProcessAckPacket(&frame3);
12491   EXPECT_TRUE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12492   EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12493 
12494   correct_tag++;
12495   // Key update should be allowed now.
12496   EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
12497       .WillOnce([&correct_tag]() {
12498         return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12499       });
12500   EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter())
12501       .WillOnce([&correct_tag]() {
12502         return std::make_unique<TaggingEncrypter>(correct_tag);
12503       });
12504   EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
12505   EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
12506   EXPECT_FALSE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12507   EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12508 }
12509 
TEST_P(QuicConnectionTest,InitiateKeyUpdateApproachingConfidentialityLimit)12510 TEST_P(QuicConnectionTest, InitiateKeyUpdateApproachingConfidentialityLimit) {
12511   if (!connection_.version().UsesTls()) {
12512     return;
12513   }
12514 
12515   SetQuicFlag(quic_key_update_confidentiality_limit, 3U);
12516 
12517   std::string error_details;
12518   TransportParameters params;
12519   // Key update is enabled.
12520   QuicConfig config;
12521   EXPECT_THAT(config.ProcessTransportParameters(
12522                   params, /* is_resumption = */ false, &error_details),
12523               IsQuicNoError());
12524   QuicConfigPeer::SetNegotiated(&config, true);
12525   if (connection_.version().UsesTls()) {
12526     QuicConfigPeer::SetReceivedOriginalConnectionId(
12527         &config, connection_.connection_id());
12528     QuicConfigPeer::SetReceivedInitialSourceConnectionId(
12529         &config, connection_.connection_id());
12530   }
12531   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12532   connection_.SetFromConfig(config);
12533 
12534   MockFramerVisitor peer_framer_visitor_;
12535   peer_framer_.set_visitor(&peer_framer_visitor_);
12536 
12537   uint8_t current_tag = ENCRYPTION_FORWARD_SECURE;
12538 
12539   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12540   connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12541                            std::make_unique<TaggingEncrypter>(current_tag));
12542   SetDecrypter(ENCRYPTION_FORWARD_SECURE,
12543                std::make_unique<StrictTaggingDecrypter>(current_tag));
12544   EXPECT_CALL(visitor_, GetHandshakeState())
12545       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12546   connection_.OnHandshakeComplete();
12547 
12548   peer_framer_.SetKeyUpdateSupportForConnection(true);
12549   peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12550                             std::make_unique<TaggingEncrypter>(current_tag));
12551 
12552   const QuicConnectionStats& stats = connection_.GetStats();
12553 
12554   for (int packet_num = 1; packet_num <= 8; ++packet_num) {
12555     if (packet_num == 3 || packet_num == 6) {
12556       current_tag++;
12557       EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
12558           .WillOnce([current_tag]() {
12559             return std::make_unique<StrictTaggingDecrypter>(current_tag);
12560           });
12561       EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter())
12562           .WillOnce([current_tag]() {
12563             return std::make_unique<TaggingEncrypter>(current_tag);
12564           });
12565       EXPECT_CALL(visitor_,
12566                   OnKeyUpdate(KeyUpdateReason::kLocalKeyUpdateLimitOverride));
12567     }
12568     // Send packet.
12569     QuicPacketNumber last_packet;
12570     SendStreamDataToPeer(packet_num, "foo", 0, NO_FIN, &last_packet);
12571     EXPECT_EQ(QuicPacketNumber(packet_num), last_packet);
12572     if (packet_num >= 6) {
12573       EXPECT_EQ(2U, stats.key_update_count);
12574     } else if (packet_num >= 3) {
12575       EXPECT_EQ(1U, stats.key_update_count);
12576     } else {
12577       EXPECT_EQ(0U, stats.key_update_count);
12578     }
12579 
12580     if (packet_num == 4 || packet_num == 7) {
12581       // Pretend that peer accepts the key update.
12582       EXPECT_CALL(peer_framer_visitor_,
12583                   AdvanceKeysAndCreateCurrentOneRttDecrypter())
12584           .WillOnce([current_tag]() {
12585             return std::make_unique<StrictTaggingDecrypter>(current_tag);
12586           });
12587       EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
12588           .WillOnce([current_tag]() {
12589             return std::make_unique<TaggingEncrypter>(current_tag);
12590           });
12591       peer_framer_.DoKeyUpdate(KeyUpdateReason::kRemote);
12592     }
12593     // Receive ack for packet.
12594     EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
12595     QuicAckFrame frame1 = InitAckFrame(packet_num);
12596     ProcessAckPacket(&frame1);
12597   }
12598 }
12599 
TEST_P(QuicConnectionTest,CloseConnectionOnConfidentialityLimitKeyUpdateNotAllowed)12600 TEST_P(QuicConnectionTest,
12601        CloseConnectionOnConfidentialityLimitKeyUpdateNotAllowed) {
12602   if (!connection_.version().UsesTls()) {
12603     return;
12604   }
12605 
12606   // Set key update confidentiality limit to 1 packet.
12607   SetQuicFlag(quic_key_update_confidentiality_limit, 1U);
12608   // Use confidentiality limit for connection close of 3 packets.
12609   constexpr size_t kConfidentialityLimit = 3U;
12610 
12611   std::string error_details;
12612   TransportParameters params;
12613   // Key update is enabled.
12614   QuicConfig config;
12615   EXPECT_THAT(config.ProcessTransportParameters(
12616                   params, /* is_resumption = */ false, &error_details),
12617               IsQuicNoError());
12618   QuicConfigPeer::SetNegotiated(&config, true);
12619   if (connection_.version().UsesTls()) {
12620     QuicConfigPeer::SetReceivedOriginalConnectionId(
12621         &config, connection_.connection_id());
12622     QuicConfigPeer::SetReceivedInitialSourceConnectionId(
12623         &config, connection_.connection_id());
12624   }
12625   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12626   connection_.SetFromConfig(config);
12627 
12628   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12629   connection_.SetEncrypter(
12630       ENCRYPTION_FORWARD_SECURE,
12631       std::make_unique<TaggingEncrypterWithConfidentialityLimit>(
12632           ENCRYPTION_FORWARD_SECURE, kConfidentialityLimit));
12633   EXPECT_CALL(visitor_, GetHandshakeState())
12634       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12635   connection_.OnHandshakeComplete();
12636 
12637   QuicPacketNumber last_packet;
12638   // Send 3 packets without receiving acks for any of them. Key update will not
12639   // be allowed, so the confidentiality limit should be reached, forcing the
12640   // connection to be closed.
12641   SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
12642   EXPECT_TRUE(connection_.connected());
12643   SendStreamDataToPeer(2, "foo", 0, NO_FIN, &last_packet);
12644   EXPECT_TRUE(connection_.connected());
12645   EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12646   SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet);
12647   EXPECT_FALSE(connection_.connected());
12648   const QuicConnectionStats& stats = connection_.GetStats();
12649   EXPECT_EQ(0U, stats.key_update_count);
12650   TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12651 }
12652 
TEST_P(QuicConnectionTest,CloseConnectionOnIntegrityLimitDuringHandshake)12653 TEST_P(QuicConnectionTest, CloseConnectionOnIntegrityLimitDuringHandshake) {
12654   if (!connection_.version().UsesTls()) {
12655     return;
12656   }
12657 
12658   constexpr uint8_t correct_tag = ENCRYPTION_HANDSHAKE;
12659   constexpr uint8_t wrong_tag = 0xFE;
12660   constexpr QuicPacketCount kIntegrityLimit = 3;
12661 
12662   SetDecrypter(ENCRYPTION_HANDSHAKE,
12663                std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12664                    correct_tag, kIntegrityLimit));
12665   connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12666                            std::make_unique<TaggingEncrypter>(correct_tag));
12667   connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12668   peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12669                             std::make_unique<TaggingEncrypter>(wrong_tag));
12670   for (uint64_t i = 1; i <= kIntegrityLimit; ++i) {
12671     EXPECT_TRUE(connection_.connected());
12672     if (i == kIntegrityLimit) {
12673       EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12674       EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
12675     }
12676     ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
12677     EXPECT_EQ(
12678         i, connection_.GetStats().num_failed_authentication_packets_received);
12679   }
12680   EXPECT_FALSE(connection_.connected());
12681   TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12682 }
12683 
TEST_P(QuicConnectionTest,CloseConnectionOnIntegrityLimitAfterHandshake)12684 TEST_P(QuicConnectionTest, CloseConnectionOnIntegrityLimitAfterHandshake) {
12685   if (!connection_.version().UsesTls()) {
12686     return;
12687   }
12688 
12689   constexpr uint8_t correct_tag = ENCRYPTION_FORWARD_SECURE;
12690   constexpr uint8_t wrong_tag = 0xFE;
12691   constexpr QuicPacketCount kIntegrityLimit = 3;
12692 
12693   SetDecrypter(ENCRYPTION_FORWARD_SECURE,
12694                std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12695                    correct_tag, kIntegrityLimit));
12696   connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12697                            std::make_unique<TaggingEncrypter>(correct_tag));
12698   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12699   EXPECT_CALL(visitor_, GetHandshakeState())
12700       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12701   connection_.OnHandshakeComplete();
12702   connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12703   peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12704                             std::make_unique<TaggingEncrypter>(wrong_tag));
12705   for (uint64_t i = 1; i <= kIntegrityLimit; ++i) {
12706     EXPECT_TRUE(connection_.connected());
12707     if (i == kIntegrityLimit) {
12708       EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12709     }
12710     ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12711     EXPECT_EQ(
12712         i, connection_.GetStats().num_failed_authentication_packets_received);
12713   }
12714   EXPECT_FALSE(connection_.connected());
12715   TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12716 }
12717 
TEST_P(QuicConnectionTest,CloseConnectionOnIntegrityLimitAcrossEncryptionLevels)12718 TEST_P(QuicConnectionTest,
12719        CloseConnectionOnIntegrityLimitAcrossEncryptionLevels) {
12720   if (!connection_.version().UsesTls()) {
12721     return;
12722   }
12723 
12724   uint8_t correct_tag = ENCRYPTION_HANDSHAKE;
12725   constexpr uint8_t wrong_tag = 0xFE;
12726   constexpr QuicPacketCount kIntegrityLimit = 4;
12727 
12728   SetDecrypter(ENCRYPTION_HANDSHAKE,
12729                std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12730                    correct_tag, kIntegrityLimit));
12731   connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12732                            std::make_unique<TaggingEncrypter>(correct_tag));
12733   connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12734   peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12735                             std::make_unique<TaggingEncrypter>(wrong_tag));
12736   for (uint64_t i = 1; i <= 2; ++i) {
12737     EXPECT_TRUE(connection_.connected());
12738     ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
12739     EXPECT_EQ(
12740         i, connection_.GetStats().num_failed_authentication_packets_received);
12741   }
12742 
12743   correct_tag = ENCRYPTION_FORWARD_SECURE;
12744   SetDecrypter(ENCRYPTION_FORWARD_SECURE,
12745                std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12746                    correct_tag, kIntegrityLimit));
12747   connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12748                            std::make_unique<TaggingEncrypter>(correct_tag));
12749   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12750   EXPECT_CALL(visitor_, GetHandshakeState())
12751       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12752   connection_.OnHandshakeComplete();
12753   connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12754   connection_.RemoveEncrypter(ENCRYPTION_HANDSHAKE);
12755   peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12756                             std::make_unique<TaggingEncrypter>(wrong_tag));
12757   for (uint64_t i = 3; i <= kIntegrityLimit; ++i) {
12758     EXPECT_TRUE(connection_.connected());
12759     if (i == kIntegrityLimit) {
12760       EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12761     }
12762     ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12763     EXPECT_EQ(
12764         i, connection_.GetStats().num_failed_authentication_packets_received);
12765   }
12766   EXPECT_FALSE(connection_.connected());
12767   TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12768 }
12769 
TEST_P(QuicConnectionTest,IntegrityLimitDoesNotApplyWithoutDecryptionKey)12770 TEST_P(QuicConnectionTest, IntegrityLimitDoesNotApplyWithoutDecryptionKey) {
12771   if (!connection_.version().UsesTls()) {
12772     return;
12773   }
12774 
12775   constexpr uint8_t correct_tag = ENCRYPTION_HANDSHAKE;
12776   constexpr uint8_t wrong_tag = 0xFE;
12777   constexpr QuicPacketCount kIntegrityLimit = 3;
12778 
12779   SetDecrypter(ENCRYPTION_HANDSHAKE,
12780                std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12781                    correct_tag, kIntegrityLimit));
12782   connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12783                            std::make_unique<TaggingEncrypter>(correct_tag));
12784   connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12785   connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
12786 
12787   peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12788                             std::make_unique<TaggingEncrypter>(wrong_tag));
12789   for (uint64_t i = 1; i <= kIntegrityLimit * 2; ++i) {
12790     EXPECT_TRUE(connection_.connected());
12791     ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12792     EXPECT_EQ(
12793         0u, connection_.GetStats().num_failed_authentication_packets_received);
12794   }
12795   EXPECT_TRUE(connection_.connected());
12796 }
12797 
TEST_P(QuicConnectionTest,CloseConnectionOnIntegrityLimitAcrossKeyPhases)12798 TEST_P(QuicConnectionTest, CloseConnectionOnIntegrityLimitAcrossKeyPhases) {
12799   if (!connection_.version().UsesTls()) {
12800     return;
12801   }
12802 
12803   constexpr QuicPacketCount kIntegrityLimit = 4;
12804 
12805   TransportParameters params;
12806   QuicConfig config;
12807   std::string error_details;
12808   EXPECT_THAT(config.ProcessTransportParameters(
12809                   params, /* is_resumption = */ false, &error_details),
12810               IsQuicNoError());
12811   QuicConfigPeer::SetNegotiated(&config, true);
12812   if (connection_.version().UsesTls()) {
12813     QuicConfigPeer::SetReceivedOriginalConnectionId(
12814         &config, connection_.connection_id());
12815     QuicConfigPeer::SetReceivedInitialSourceConnectionId(
12816         &config, connection_.connection_id());
12817   }
12818   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12819   connection_.SetFromConfig(config);
12820 
12821   MockFramerVisitor peer_framer_visitor_;
12822   peer_framer_.set_visitor(&peer_framer_visitor_);
12823 
12824   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12825   connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12826                            std::make_unique<TaggingEncrypter>(0x01));
12827   SetDecrypter(ENCRYPTION_FORWARD_SECURE,
12828                std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12829                    ENCRYPTION_FORWARD_SECURE, kIntegrityLimit));
12830   EXPECT_CALL(visitor_, GetHandshakeState())
12831       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12832   connection_.OnHandshakeComplete();
12833   connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12834 
12835   peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12836                             std::make_unique<TaggingEncrypter>(0xFF));
12837   for (uint64_t i = 1; i <= 2; ++i) {
12838     EXPECT_TRUE(connection_.connected());
12839     ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12840     EXPECT_EQ(
12841         i, connection_.GetStats().num_failed_authentication_packets_received);
12842   }
12843 
12844   peer_framer_.SetEncrypter(
12845       ENCRYPTION_FORWARD_SECURE,
12846       std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
12847   // Send packet 1.
12848   QuicPacketNumber last_packet;
12849   SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
12850   EXPECT_EQ(QuicPacketNumber(1u), last_packet);
12851   // Receive ack for packet 1.
12852   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
12853   QuicAckFrame frame1 = InitAckFrame(1);
12854   ProcessAckPacket(&frame1);
12855   // Key update should now be allowed, initiate it.
12856   EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
12857       .WillOnce([kIntegrityLimit]() {
12858         return std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12859             0x02, kIntegrityLimit);
12860       });
12861   EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter()).WillOnce([]() {
12862     return std::make_unique<TaggingEncrypter>(0x02);
12863   });
12864   EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
12865   EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
12866 
12867   // Pretend that peer accepts the key update.
12868   EXPECT_CALL(peer_framer_visitor_,
12869               AdvanceKeysAndCreateCurrentOneRttDecrypter())
12870       .WillOnce(
12871           []() { return std::make_unique<StrictTaggingDecrypter>(0x02); });
12872   EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
12873       .WillOnce([]() { return std::make_unique<TaggingEncrypter>(0x02); });
12874   peer_framer_.SetKeyUpdateSupportForConnection(true);
12875   peer_framer_.DoKeyUpdate(KeyUpdateReason::kLocalForTests);
12876 
12877   // Send packet 2.
12878   SendStreamDataToPeer(2, "bar", 0, NO_FIN, &last_packet);
12879   EXPECT_EQ(QuicPacketNumber(2u), last_packet);
12880   // Receive ack for packet 2.
12881   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
12882   QuicAckFrame frame2 = InitAckFrame(2);
12883   ProcessAckPacket(&frame2);
12884 
12885   EXPECT_EQ(2u,
12886             connection_.GetStats().num_failed_authentication_packets_received);
12887 
12888   // Do two more undecryptable packets. Integrity limit should be reached.
12889   peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12890                             std::make_unique<TaggingEncrypter>(0xFF));
12891   for (uint64_t i = 3; i <= kIntegrityLimit; ++i) {
12892     EXPECT_TRUE(connection_.connected());
12893     if (i == kIntegrityLimit) {
12894       EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12895     }
12896     ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12897     EXPECT_EQ(
12898         i, connection_.GetStats().num_failed_authentication_packets_received);
12899   }
12900   EXPECT_FALSE(connection_.connected());
12901   TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12902 }
12903 
TEST_P(QuicConnectionTest,SendAckFrequencyFrame)12904 TEST_P(QuicConnectionTest, SendAckFrequencyFrame) {
12905   if (!version().HasIetfQuicFrames()) {
12906     return;
12907   }
12908   SetQuicReloadableFlag(quic_can_send_ack_frequency, true);
12909   set_perspective(Perspective::IS_SERVER);
12910   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
12911       .Times(AnyNumber());
12912   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
12913 
12914   QuicConfig config;
12915   QuicConfigPeer::SetReceivedMinAckDelayMs(&config, /*min_ack_delay_ms=*/1);
12916   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12917   connection_.SetFromConfig(config);
12918   QuicConnectionPeer::SetAddressValidated(&connection_);
12919   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12920   peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
12921 
12922   connection_.OnHandshakeComplete();
12923 
12924   writer_->SetWritable();
12925   QuicPacketCreatorPeer::SetPacketNumber(creator_, 99);
12926   // Send packet 100
12927   SendStreamDataToPeer(/*id=*/1, "foo", /*offset=*/0, NO_FIN, nullptr);
12928 
12929   QuicAckFrequencyFrame captured_frame;
12930   EXPECT_CALL(visitor_, SendAckFrequency(_))
12931       .WillOnce(Invoke([&captured_frame](const QuicAckFrequencyFrame& frame) {
12932         captured_frame = frame;
12933       }));
12934   // Send packet 101.
12935   SendStreamDataToPeer(/*id=*/1, "bar", /*offset=*/3, NO_FIN, nullptr);
12936 
12937   EXPECT_EQ(captured_frame.packet_tolerance, 10u);
12938   EXPECT_EQ(captured_frame.max_ack_delay,
12939             QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs));
12940 
12941   // Sending packet 102 does not trigger sending another AckFrequencyFrame.
12942   SendStreamDataToPeer(/*id=*/1, "baz", /*offset=*/6, NO_FIN, nullptr);
12943 }
12944 
TEST_P(QuicConnectionTest,SendAckFrequencyFrameUponHandshakeCompletion)12945 TEST_P(QuicConnectionTest, SendAckFrequencyFrameUponHandshakeCompletion) {
12946   if (!version().HasIetfQuicFrames()) {
12947     return;
12948   }
12949   SetQuicReloadableFlag(quic_can_send_ack_frequency, true);
12950   set_perspective(Perspective::IS_SERVER);
12951   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
12952       .Times(AnyNumber());
12953   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
12954 
12955   QuicConfig config;
12956   QuicConfigPeer::SetReceivedMinAckDelayMs(&config, /*min_ack_delay_ms=*/1);
12957   QuicTagVector quic_tag_vector;
12958   // Enable sending AckFrequency upon handshake completion.
12959   quic_tag_vector.push_back(kAFF2);
12960   QuicConfigPeer::SetReceivedConnectionOptions(&config, quic_tag_vector);
12961   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12962   connection_.SetFromConfig(config);
12963   QuicConnectionPeer::SetAddressValidated(&connection_);
12964   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12965   peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
12966 
12967   QuicAckFrequencyFrame captured_frame;
12968   EXPECT_CALL(visitor_, SendAckFrequency(_))
12969       .WillOnce(Invoke([&captured_frame](const QuicAckFrequencyFrame& frame) {
12970         captured_frame = frame;
12971       }));
12972 
12973   connection_.OnHandshakeComplete();
12974 
12975   EXPECT_EQ(captured_frame.packet_tolerance, 2u);
12976   EXPECT_EQ(captured_frame.max_ack_delay,
12977             QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs));
12978 }
12979 
TEST_P(QuicConnectionTest,FastRecoveryOfLostServerHello)12980 TEST_P(QuicConnectionTest, FastRecoveryOfLostServerHello) {
12981   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
12982     return;
12983   }
12984   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12985   QuicConfig config;
12986   connection_.SetFromConfig(config);
12987 
12988   connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
12989   connection_.SendCryptoStreamData();
12990   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
12991 
12992   // Assume ServerHello gets lost.
12993   peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12994                             std::make_unique<TaggingEncrypter>(0x02));
12995   ProcessCryptoPacketAtLevel(2, ENCRYPTION_HANDSHAKE);
12996   ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
12997   // Shorten PTO for fast recovery from lost ServerHello.
12998   EXPECT_EQ(clock_.ApproximateNow() + kAlarmGranularity,
12999             connection_.GetRetransmissionAlarm()->deadline());
13000 }
13001 
TEST_P(QuicConnectionTest,ServerHelloGetsReordered)13002 TEST_P(QuicConnectionTest, ServerHelloGetsReordered) {
13003   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
13004     return;
13005   }
13006   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13007   QuicConfig config;
13008   connection_.SetFromConfig(config);
13009   EXPECT_CALL(visitor_, OnCryptoFrame(_))
13010       .WillRepeatedly(Invoke([=](const QuicCryptoFrame& frame) {
13011         if (frame.level == ENCRYPTION_INITIAL) {
13012           // Install handshake read keys.
13013           SetDecrypter(
13014               ENCRYPTION_HANDSHAKE,
13015               std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
13016           connection_.SetEncrypter(
13017               ENCRYPTION_HANDSHAKE,
13018               std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
13019           connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
13020         }
13021       }));
13022 
13023   connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
13024   connection_.SendCryptoStreamData();
13025   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
13026 
13027   // Assume ServerHello gets reordered.
13028   peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
13029                             std::make_unique<TaggingEncrypter>(0x02));
13030   ProcessCryptoPacketAtLevel(2, ENCRYPTION_HANDSHAKE);
13031   ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
13032   // Verify fast recovery is not enabled.
13033   EXPECT_EQ(connection_.sent_packet_manager().GetRetransmissionTime(),
13034             connection_.GetRetransmissionAlarm()->deadline());
13035 }
13036 
TEST_P(QuicConnectionTest,MigratePath)13037 TEST_P(QuicConnectionTest, MigratePath) {
13038   connection_.CreateConnectionIdManager();
13039   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13040   connection_.OnHandshakeComplete();
13041   EXPECT_CALL(visitor_, GetHandshakeState())
13042       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
13043   EXPECT_CALL(visitor_, OnPathDegrading());
13044   connection_.OnPathDegradingDetected();
13045   const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
13046   EXPECT_NE(kNewSelfAddress, connection_.self_address());
13047 
13048   // Buffer a packet.
13049   EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
13050   writer_->SetWriteBlocked();
13051   connection_.SendMtuDiscoveryPacket(kMaxOutgoingPacketSize);
13052   EXPECT_EQ(1u, connection_.NumQueuedPackets());
13053 
13054   if (version().HasIetfQuicFrames()) {
13055     QuicNewConnectionIdFrame frame;
13056     frame.connection_id = TestConnectionId(1234);
13057     ASSERT_NE(frame.connection_id, connection_.connection_id());
13058     frame.stateless_reset_token =
13059         QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13060     frame.retire_prior_to = 0u;
13061     frame.sequence_number = 1u;
13062     connection_.OnNewConnectionIdFrame(frame);
13063   }
13064 
13065   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13066   EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading());
13067   EXPECT_TRUE(connection_.MigratePath(kNewSelfAddress,
13068                                       connection_.peer_address(), &new_writer,
13069                                       /*owns_writer=*/false));
13070 
13071   EXPECT_EQ(kNewSelfAddress, connection_.self_address());
13072   EXPECT_EQ(&new_writer, QuicConnectionPeer::GetWriter(&connection_));
13073   EXPECT_FALSE(connection_.IsPathDegrading());
13074   // Buffered packet on the old path should be discarded.
13075   if (version().HasIetfQuicFrames()) {
13076     EXPECT_EQ(0u, connection_.NumQueuedPackets());
13077   } else {
13078     EXPECT_EQ(1u, connection_.NumQueuedPackets());
13079   }
13080 }
13081 
TEST_P(QuicConnectionTest,MigrateToNewPathDuringProbing)13082 TEST_P(QuicConnectionTest, MigrateToNewPathDuringProbing) {
13083   if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
13084     return;
13085   }
13086   PathProbeTestInit(Perspective::IS_CLIENT);
13087   const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
13088   EXPECT_NE(kNewSelfAddress, connection_.self_address());
13089   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13090   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
13091   bool success = false;
13092   connection_.ValidatePath(
13093       std::make_unique<TestQuicPathValidationContext>(
13094           kNewSelfAddress, connection_.peer_address(), &new_writer),
13095       std::make_unique<TestValidationResultDelegate>(
13096           &connection_, kNewSelfAddress, connection_.peer_address(), &success),
13097       PathValidationReason::kReasonUnknown);
13098   EXPECT_TRUE(connection_.HasPendingPathValidation());
13099   EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13100       &connection_, kNewSelfAddress, connection_.peer_address()));
13101 
13102   connection_.MigratePath(kNewSelfAddress, connection_.peer_address(),
13103                           &new_writer, /*owns_writer=*/false);
13104   EXPECT_EQ(kNewSelfAddress, connection_.self_address());
13105   EXPECT_TRUE(connection_.HasPendingPathValidation());
13106   EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
13107       &connection_, kNewSelfAddress, connection_.peer_address()));
13108 }
13109 
TEST_P(QuicConnectionTest,MultiPortConnection)13110 TEST_P(QuicConnectionTest, MultiPortConnection) {
13111   set_perspective(Perspective::IS_CLIENT);
13112   QuicConfig config;
13113   config.SetClientConnectionOptions(QuicTagVector{kMPQC});
13114   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13115   connection_.SetFromConfig(config);
13116   if (!version().HasIetfQuicFrames()) {
13117     return;
13118   }
13119   connection_.CreateConnectionIdManager();
13120   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13121   connection_.OnHandshakeComplete();
13122 
13123   EXPECT_CALL(visitor_, OnPathDegrading());
13124   connection_.OnPathDegradingDetected();
13125 
13126   auto self_address = connection_.self_address();
13127   const QuicSocketAddress kNewSelfAddress(self_address.host(),
13128                                           self_address.port() + 1);
13129   EXPECT_NE(kNewSelfAddress, self_address);
13130   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13131 
13132   EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()).WillOnce(Return(false));
13133   QuicNewConnectionIdFrame frame;
13134   frame.connection_id = TestConnectionId(1234);
13135   ASSERT_NE(frame.connection_id, connection_.connection_id());
13136   frame.stateless_reset_token =
13137       QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13138   frame.retire_prior_to = 0u;
13139   frame.sequence_number = 1u;
13140   EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
13141       .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) {
13142         observer->OnMultiPortPathContextAvailable(
13143             std::move(std::make_unique<TestQuicPathValidationContext>(
13144                 kNewSelfAddress, connection_.peer_address(), &new_writer)));
13145       }));
13146   connection_.OnNewConnectionIdFrame(frame);
13147   EXPECT_TRUE(connection_.HasPendingPathValidation());
13148   EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13149       &connection_, kNewSelfAddress, connection_.peer_address()));
13150   auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13151   EXPECT_FALSE(alt_path->validated);
13152   EXPECT_EQ(PathValidationReason::kMultiPort,
13153             QuicConnectionPeer::path_validator(&connection_)
13154                 ->GetPathValidationReason());
13155 
13156   // Suppose the server retransmits the NEW_CID frame, the client will receive
13157   // the same frame again. It should be ignored.
13158   // Regression test of crbug.com/1406762
13159   connection_.OnNewConnectionIdFrame(frame);
13160 
13161   // 30ms RTT.
13162   const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
13163   // Fake a response delay.
13164   clock_.AdvanceTime(kTestRTT);
13165 
13166   QuicFrames frames;
13167   frames.push_back(QuicFrame(QuicPathResponseFrame(
13168       99, new_writer.path_challenge_frames().back().data_buffer)));
13169   ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
13170                                    ENCRYPTION_FORWARD_SECURE);
13171   // No migration should happen and the alternative path should still be alive.
13172   EXPECT_FALSE(connection_.HasPendingPathValidation());
13173   EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13174       &connection_, kNewSelfAddress, connection_.peer_address()));
13175   EXPECT_TRUE(alt_path->validated);
13176   auto stats = connection_.multi_port_stats();
13177   EXPECT_EQ(1, connection_.GetStats().num_path_degrading);
13178   EXPECT_EQ(1, stats->num_successful_probes);
13179   EXPECT_EQ(1, stats->num_client_probing_attempts);
13180   EXPECT_EQ(0, stats->num_multi_port_probe_failures_when_path_degrading);
13181   EXPECT_EQ(kTestRTT, stats->rtt_stats.latest_rtt());
13182   EXPECT_EQ(kTestRTT,
13183             stats->rtt_stats_when_default_path_degrading.latest_rtt());
13184 
13185   // Receiving the retransmitted NEW_CID frame now should still have no effect.
13186   EXPECT_CALL(visitor_, CreateContextForMultiPortPath).Times(0);
13187   connection_.OnNewConnectionIdFrame(frame);
13188 
13189   // When there's no active request, the probing shouldn't happen. But the
13190   // probing context should be saved.
13191   EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()).WillOnce(Return(false));
13192   connection_.GetMultiPortProbingAlarm()->Fire();
13193   EXPECT_FALSE(connection_.HasPendingPathValidation());
13194   EXPECT_FALSE(connection_.GetMultiPortProbingAlarm()->IsSet());
13195 
13196   // Simulate the situation where a new request stream is created.
13197   EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
13198       .WillRepeatedly(Return(true));
13199   random_generator_.ChangeValue();
13200   connection_.MaybeProbeMultiPortPath();
13201   EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13202       &connection_, kNewSelfAddress, connection_.peer_address()));
13203   EXPECT_TRUE(alt_path->validated);
13204   // Fake a response delay.
13205   clock_.AdvanceTime(kTestRTT);
13206   QuicFrames frames2;
13207   frames2.push_back(QuicFrame(QuicPathResponseFrame(
13208       99, new_writer.path_challenge_frames().back().data_buffer)));
13209   ProcessFramesPacketWithAddresses(frames2, kNewSelfAddress, kPeerAddress,
13210                                    ENCRYPTION_FORWARD_SECURE);
13211   // No migration should happen and the alternative path should still be alive.
13212   EXPECT_FALSE(connection_.HasPendingPathValidation());
13213   EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13214       &connection_, kNewSelfAddress, connection_.peer_address()));
13215   EXPECT_TRUE(alt_path->validated);
13216   EXPECT_EQ(1, connection_.GetStats().num_path_degrading);
13217   EXPECT_EQ(0, stats->num_multi_port_probe_failures_when_path_degrading);
13218   EXPECT_EQ(kTestRTT, stats->rtt_stats.latest_rtt());
13219   EXPECT_EQ(kTestRTT,
13220             stats->rtt_stats_when_default_path_degrading.latest_rtt());
13221 
13222   EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading());
13223   QuicConnectionPeer::OnForwardProgressMade(&connection_);
13224 
13225   EXPECT_TRUE(connection_.GetMultiPortProbingAlarm()->IsSet());
13226   // Since there's already a scheduled probing alarm, manual calls won't have
13227   // any effect.
13228   connection_.MaybeProbeMultiPortPath();
13229   EXPECT_FALSE(connection_.HasPendingPathValidation());
13230 
13231   // Since kMPQM is not set, migration shouldn't happen
13232   EXPECT_CALL(visitor_, OnPathDegrading());
13233   EXPECT_CALL(visitor_, MigrateToMultiPortPath(_)).Times(0);
13234   connection_.OnPathDegradingDetected();
13235   EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13236       &connection_, kNewSelfAddress, connection_.peer_address()));
13237 
13238   // Simulate the case where the path validation fails after retries.
13239   connection_.GetMultiPortProbingAlarm()->Fire();
13240   EXPECT_TRUE(connection_.HasPendingPathValidation());
13241   EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13242       &connection_, kNewSelfAddress, connection_.peer_address()));
13243   for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes + 1; ++i) {
13244     clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
13245     static_cast<TestAlarmFactory::TestAlarm*>(
13246         QuicPathValidatorPeer::retry_timer(
13247             QuicConnectionPeer::path_validator(&connection_)))
13248         ->Fire();
13249   }
13250 
13251   EXPECT_FALSE(connection_.HasPendingPathValidation());
13252   EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
13253       &connection_, kNewSelfAddress, connection_.peer_address()));
13254   EXPECT_EQ(2, connection_.GetStats().num_path_degrading);
13255   EXPECT_EQ(1, stats->num_multi_port_probe_failures_when_path_degrading);
13256   EXPECT_EQ(0, stats->num_multi_port_probe_failures_when_path_not_degrading);
13257 }
13258 
TEST_P(QuicConnectionTest,TooManyMultiPortPathCreations)13259 TEST_P(QuicConnectionTest, TooManyMultiPortPathCreations) {
13260   set_perspective(Perspective::IS_CLIENT);
13261   QuicConfig config;
13262   config.SetClientConnectionOptions(QuicTagVector{kMPQC});
13263   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13264   connection_.SetFromConfig(config);
13265   if (!version().HasIetfQuicFrames()) {
13266     return;
13267   }
13268   connection_.CreateConnectionIdManager();
13269   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13270   connection_.OnHandshakeComplete();
13271 
13272   EXPECT_CALL(visitor_, OnPathDegrading());
13273   connection_.OnPathDegradingDetected();
13274 
13275   auto self_address = connection_.self_address();
13276   const QuicSocketAddress kNewSelfAddress(self_address.host(),
13277                                           self_address.port() + 1);
13278   EXPECT_NE(kNewSelfAddress, self_address);
13279   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13280 
13281   EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
13282       .WillRepeatedly(Return(true));
13283 
13284   {
13285     QuicNewConnectionIdFrame frame;
13286     frame.connection_id = TestConnectionId(1234);
13287     ASSERT_NE(frame.connection_id, connection_.connection_id());
13288     frame.stateless_reset_token =
13289         QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13290     frame.retire_prior_to = 0u;
13291     frame.sequence_number = 1u;
13292     EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
13293         .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) {
13294           observer->OnMultiPortPathContextAvailable(
13295               std::move(std::make_unique<TestQuicPathValidationContext>(
13296                   kNewSelfAddress, connection_.peer_address(), &new_writer)));
13297         }));
13298     EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
13299   }
13300   EXPECT_TRUE(connection_.HasPendingPathValidation());
13301   EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13302       &connection_, kNewSelfAddress, connection_.peer_address()));
13303   auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13304   EXPECT_FALSE(alt_path->validated);
13305 
13306   EXPECT_TRUE(connection_.HasPendingPathValidation());
13307   EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13308       &connection_, kNewSelfAddress, connection_.peer_address()));
13309   for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes + 1; ++i) {
13310     clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
13311     static_cast<TestAlarmFactory::TestAlarm*>(
13312         QuicPathValidatorPeer::retry_timer(
13313             QuicConnectionPeer::path_validator(&connection_)))
13314         ->Fire();
13315   }
13316 
13317   auto stats = connection_.multi_port_stats();
13318   EXPECT_FALSE(connection_.HasPendingPathValidation());
13319   EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
13320       &connection_, kNewSelfAddress, connection_.peer_address()));
13321   EXPECT_EQ(1, connection_.GetStats().num_path_degrading);
13322   EXPECT_EQ(1, stats->num_multi_port_probe_failures_when_path_degrading);
13323 
13324   uint64_t connection_id = 1235;
13325   for (size_t i = 0; i < kMaxNumMultiPortPaths - 1; ++i) {
13326     QuicNewConnectionIdFrame frame;
13327     frame.connection_id = TestConnectionId(connection_id + i);
13328     ASSERT_NE(frame.connection_id, connection_.connection_id());
13329     frame.stateless_reset_token =
13330         QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13331     frame.retire_prior_to = 0u;
13332     frame.sequence_number = i + 2;
13333     EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
13334         .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) {
13335           observer->OnMultiPortPathContextAvailable(
13336               std::move(std::make_unique<TestQuicPathValidationContext>(
13337                   kNewSelfAddress, connection_.peer_address(), &new_writer)));
13338         }));
13339     EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
13340     EXPECT_TRUE(connection_.HasPendingPathValidation());
13341     EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13342         &connection_, kNewSelfAddress, connection_.peer_address()));
13343     EXPECT_FALSE(alt_path->validated);
13344 
13345     for (size_t j = 0; j < QuicPathValidator::kMaxRetryTimes + 1; ++j) {
13346       clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
13347       static_cast<TestAlarmFactory::TestAlarm*>(
13348           QuicPathValidatorPeer::retry_timer(
13349               QuicConnectionPeer::path_validator(&connection_)))
13350           ->Fire();
13351     }
13352 
13353     EXPECT_FALSE(connection_.HasPendingPathValidation());
13354     EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
13355         &connection_, kNewSelfAddress, connection_.peer_address()));
13356     EXPECT_EQ(1, connection_.GetStats().num_path_degrading);
13357     EXPECT_EQ(i + 2, stats->num_multi_port_probe_failures_when_path_degrading);
13358   }
13359 
13360   // The 6th attemp should fail.
13361   QuicNewConnectionIdFrame frame2;
13362   frame2.connection_id = TestConnectionId(1239);
13363   ASSERT_NE(frame2.connection_id, connection_.connection_id());
13364   frame2.stateless_reset_token =
13365       QuicUtils::GenerateStatelessResetToken(frame2.connection_id);
13366   frame2.retire_prior_to = 0u;
13367   frame2.sequence_number = 6u;
13368   EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame2));
13369   EXPECT_FALSE(connection_.HasPendingPathValidation());
13370   EXPECT_EQ(kMaxNumMultiPortPaths,
13371             stats->num_multi_port_probe_failures_when_path_degrading);
13372 }
13373 
TEST_P(QuicConnectionTest,MultiPortPathReceivesStatelessReset)13374 TEST_P(QuicConnectionTest, MultiPortPathReceivesStatelessReset) {
13375   set_perspective(Perspective::IS_CLIENT);
13376   QuicConfig config;
13377   QuicConfigPeer::SetReceivedStatelessResetToken(&config,
13378                                                  kTestStatelessResetToken);
13379   config.SetClientConnectionOptions(QuicTagVector{kMPQC});
13380   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13381   connection_.SetFromConfig(config);
13382   if (!version().HasIetfQuicFrames()) {
13383     return;
13384   }
13385   connection_.CreateConnectionIdManager();
13386   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13387   connection_.OnHandshakeComplete();
13388 
13389   EXPECT_CALL(visitor_, OnPathDegrading());
13390   connection_.OnPathDegradingDetected();
13391 
13392   auto self_address = connection_.self_address();
13393   const QuicSocketAddress kNewSelfAddress(self_address.host(),
13394                                           self_address.port() + 1);
13395   EXPECT_NE(kNewSelfAddress, self_address);
13396   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13397 
13398   QuicNewConnectionIdFrame frame;
13399   frame.connection_id = TestConnectionId(1234);
13400   ASSERT_NE(frame.connection_id, connection_.connection_id());
13401   frame.stateless_reset_token =
13402       QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13403   frame.retire_prior_to = 0u;
13404   frame.sequence_number = 1u;
13405   EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
13406       .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) {
13407         observer->OnMultiPortPathContextAvailable(
13408             std::move(std::make_unique<TestQuicPathValidationContext>(
13409                 kNewSelfAddress, connection_.peer_address(), &new_writer)));
13410       }));
13411   connection_.OnNewConnectionIdFrame(frame);
13412   EXPECT_TRUE(connection_.HasPendingPathValidation());
13413   EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13414       &connection_, kNewSelfAddress, connection_.peer_address()));
13415   auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13416   EXPECT_FALSE(alt_path->validated);
13417   EXPECT_EQ(PathValidationReason::kMultiPort,
13418             QuicConnectionPeer::path_validator(&connection_)
13419                 ->GetPathValidationReason());
13420 
13421   std::unique_ptr<QuicEncryptedPacket> packet(
13422       QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
13423                                                 /*received_packet_length=*/100,
13424                                                 kTestStatelessResetToken));
13425   std::unique_ptr<QuicReceivedPacket> received(
13426       ConstructReceivedPacket(*packet, QuicTime::Zero()));
13427   EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
13428       .Times(0);
13429   connection_.ProcessUdpPacket(kNewSelfAddress, kPeerAddress, *received);
13430 }
13431 
13432 // Test that if the client's active migration is disabled, multi-port will not
13433 // be attempted.
TEST_P(QuicConnectionTest,MultiPortPathRespectsActiveMigrationConfig)13434 TEST_P(QuicConnectionTest, MultiPortPathRespectsActiveMigrationConfig) {
13435   if (!version().HasIetfQuicFrames()) {
13436     return;
13437   }
13438   set_perspective(Perspective::IS_CLIENT);
13439   QuicConfig config;
13440   QuicConfigPeer::SetReceivedStatelessResetToken(&config,
13441                                                  kTestStatelessResetToken);
13442   QuicConfigPeer::SetReceivedDisableConnectionMigration(&config);
13443   config.SetClientConnectionOptions(QuicTagVector{kMPQC});
13444   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13445   connection_.SetFromConfig(config);
13446   connection_.CreateConnectionIdManager();
13447   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13448   connection_.OnHandshakeComplete();
13449 
13450   EXPECT_CALL(visitor_, OnPathDegrading());
13451   connection_.OnPathDegradingDetected();
13452 
13453   QuicNewConnectionIdFrame frame;
13454   frame.connection_id = TestConnectionId(1234);
13455   ASSERT_NE(frame.connection_id, connection_.connection_id());
13456   frame.stateless_reset_token =
13457       QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13458   frame.retire_prior_to = 0u;
13459   frame.sequence_number = 1u;
13460   EXPECT_CALL(visitor_, CreateContextForMultiPortPath).Times(0);
13461   connection_.OnNewConnectionIdFrame(frame);
13462   EXPECT_FALSE(connection_.HasPendingPathValidation());
13463 }
13464 
13465 // Verify that when multi-port is enabled and path degrading is triggered, if
13466 // the alt-path is not ready, nothing happens.
TEST_P(QuicConnectionTest,PathDegradingWhenAltPathIsNotReady)13467 TEST_P(QuicConnectionTest, PathDegradingWhenAltPathIsNotReady) {
13468   set_perspective(Perspective::IS_CLIENT);
13469   QuicConfig config;
13470   config.SetClientConnectionOptions(QuicTagVector{kMPQC});
13471   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13472   connection_.SetFromConfig(config);
13473   if (!version().HasIetfQuicFrames()) {
13474     return;
13475   }
13476   connection_.CreateConnectionIdManager();
13477   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13478   connection_.OnHandshakeComplete();
13479 
13480   auto self_address = connection_.self_address();
13481   const QuicSocketAddress kNewSelfAddress(self_address.host(),
13482                                           self_address.port() + 1);
13483   EXPECT_NE(kNewSelfAddress, self_address);
13484   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13485 
13486   EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
13487       .WillRepeatedly(Return(true));
13488 
13489   QuicNewConnectionIdFrame frame;
13490   frame.connection_id = TestConnectionId(1234);
13491   ASSERT_NE(frame.connection_id, connection_.connection_id());
13492   frame.stateless_reset_token =
13493       QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13494   frame.retire_prior_to = 0u;
13495   frame.sequence_number = 1u;
13496   EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
13497       .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) {
13498         observer->OnMultiPortPathContextAvailable(
13499             std::move(std::make_unique<TestQuicPathValidationContext>(
13500                 kNewSelfAddress, connection_.peer_address(), &new_writer)));
13501       }));
13502   EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
13503   EXPECT_TRUE(connection_.HasPendingPathValidation());
13504   EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13505       &connection_, kNewSelfAddress, connection_.peer_address()));
13506   auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13507   EXPECT_FALSE(alt_path->validated);
13508 
13509   // The alt path is not ready, path degrading doesn't do anything.
13510   EXPECT_CALL(visitor_, OnPathDegrading());
13511   EXPECT_CALL(visitor_, MigrateToMultiPortPath(_)).Times(0);
13512   connection_.OnPathDegradingDetected();
13513 
13514   // 30ms RTT.
13515   const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
13516   // Fake a response delay.
13517   clock_.AdvanceTime(kTestRTT);
13518 
13519   // Even if the alt path is validated after path degrading, nothing should
13520   // happen.
13521   QuicFrames frames;
13522   frames.push_back(QuicFrame(QuicPathResponseFrame(
13523       99, new_writer.path_challenge_frames().back().data_buffer)));
13524   ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
13525                                    ENCRYPTION_FORWARD_SECURE);
13526   // No migration should happen and the alternative path should still be alive.
13527   EXPECT_FALSE(connection_.HasPendingPathValidation());
13528   EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13529       &connection_, kNewSelfAddress, connection_.peer_address()));
13530   EXPECT_TRUE(alt_path->validated);
13531 }
13532 
13533 // Verify that when multi-port is enabled and path degrading is triggered, if
13534 // the alt-path is ready and not probing, it should be migrated.
TEST_P(QuicConnectionTest,PathDegradingWhenAltPathIsReadyAndNotProbing)13535 TEST_P(QuicConnectionTest, PathDegradingWhenAltPathIsReadyAndNotProbing) {
13536   EXPECT_CALL(visitor_, GetHandshakeState())
13537       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
13538   set_perspective(Perspective::IS_CLIENT);
13539   QuicConfig config;
13540   config.SetClientConnectionOptions(QuicTagVector{kMPQC, kMPQM});
13541   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13542   connection_.SetFromConfig(config);
13543   if (!version().HasIetfQuicFrames()) {
13544     return;
13545   }
13546   connection_.CreateConnectionIdManager();
13547   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13548   connection_.OnHandshakeComplete();
13549 
13550   auto self_address = connection_.self_address();
13551   const QuicSocketAddress kNewSelfAddress(self_address.host(),
13552                                           self_address.port() + 1);
13553   EXPECT_NE(kNewSelfAddress, self_address);
13554   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13555 
13556   EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
13557       .WillRepeatedly(Return(true));
13558 
13559   QuicNewConnectionIdFrame frame;
13560   frame.connection_id = TestConnectionId(1234);
13561   ASSERT_NE(frame.connection_id, connection_.connection_id());
13562   frame.stateless_reset_token =
13563       QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13564   frame.retire_prior_to = 0u;
13565   frame.sequence_number = 1u;
13566   EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
13567       .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) {
13568         observer->OnMultiPortPathContextAvailable(
13569             std::move(std::make_unique<TestQuicPathValidationContext>(
13570                 kNewSelfAddress, connection_.peer_address(), &new_writer)));
13571       }));
13572   EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
13573   EXPECT_TRUE(connection_.HasPendingPathValidation());
13574   EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13575       &connection_, kNewSelfAddress, connection_.peer_address()));
13576   auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13577   EXPECT_FALSE(alt_path->validated);
13578 
13579   // 30ms RTT.
13580   const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
13581   // Fake a response delay.
13582   clock_.AdvanceTime(kTestRTT);
13583 
13584   // Even if the alt path is validated after path degrading, nothing should
13585   // happen.
13586   QuicFrames frames;
13587   frames.push_back(QuicFrame(QuicPathResponseFrame(
13588       99, new_writer.path_challenge_frames().back().data_buffer)));
13589   ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
13590                                    ENCRYPTION_FORWARD_SECURE);
13591   // No migration should happen and the alternative path should still be alive.
13592   EXPECT_FALSE(connection_.HasPendingPathValidation());
13593   EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13594       &connection_, kNewSelfAddress, connection_.peer_address()));
13595   EXPECT_TRUE(alt_path->validated);
13596 
13597   // Trigger path degrading and the connection should attempt to migrate.
13598   EXPECT_CALL(visitor_, OnPathDegrading());
13599   EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(0);
13600   EXPECT_CALL(visitor_, MigrateToMultiPortPath(_))
13601       .WillOnce(Invoke([&](std::unique_ptr<QuicPathValidationContext> context) {
13602         EXPECT_EQ(context->self_address(), kNewSelfAddress);
13603         connection_.MigratePath(context->self_address(),
13604                                 context->peer_address(), context->WriterToUse(),
13605                                 /*owns_writer=*/false);
13606       }));
13607   connection_.OnPathDegradingDetected();
13608 }
13609 
13610 // Verify that when multi-port is enabled and path degrading is triggered, if
13611 // the alt-path is probing, the probing should be cancelled and the path should
13612 // be migrated.
TEST_P(QuicConnectionTest,PathDegradingWhenAltPathIsReadyAndProbing)13613 TEST_P(QuicConnectionTest, PathDegradingWhenAltPathIsReadyAndProbing) {
13614   EXPECT_CALL(visitor_, GetHandshakeState())
13615       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
13616   set_perspective(Perspective::IS_CLIENT);
13617   QuicConfig config;
13618   config.SetClientConnectionOptions(QuicTagVector{kMPQC, kMPQM});
13619   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13620   connection_.SetFromConfig(config);
13621   if (!version().HasIetfQuicFrames()) {
13622     return;
13623   }
13624   connection_.CreateConnectionIdManager();
13625   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13626   connection_.OnHandshakeComplete();
13627 
13628   auto self_address = connection_.self_address();
13629   const QuicSocketAddress kNewSelfAddress(self_address.host(),
13630                                           self_address.port() + 1);
13631   EXPECT_NE(kNewSelfAddress, self_address);
13632   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13633 
13634   EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
13635       .WillRepeatedly(Return(true));
13636 
13637   QuicNewConnectionIdFrame frame;
13638   frame.connection_id = TestConnectionId(1234);
13639   ASSERT_NE(frame.connection_id, connection_.connection_id());
13640   frame.stateless_reset_token =
13641       QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13642   frame.retire_prior_to = 0u;
13643   frame.sequence_number = 1u;
13644   EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
13645       .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) {
13646         observer->OnMultiPortPathContextAvailable(
13647             std::move(std::make_unique<TestQuicPathValidationContext>(
13648                 kNewSelfAddress, connection_.peer_address(), &new_writer)));
13649       }));
13650   EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
13651   EXPECT_TRUE(connection_.HasPendingPathValidation());
13652   EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13653       &connection_, kNewSelfAddress, connection_.peer_address()));
13654   auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13655   EXPECT_FALSE(alt_path->validated);
13656 
13657   // 30ms RTT.
13658   const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
13659   // Fake a response delay.
13660   clock_.AdvanceTime(kTestRTT);
13661 
13662   // Even if the alt path is validated after path degrading, nothing should
13663   // happen.
13664   QuicFrames frames;
13665   frames.push_back(QuicFrame(QuicPathResponseFrame(
13666       99, new_writer.path_challenge_frames().back().data_buffer)));
13667   ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
13668                                    ENCRYPTION_FORWARD_SECURE);
13669   // No migration should happen and the alternative path should still be alive.
13670   EXPECT_FALSE(connection_.HasPendingPathValidation());
13671   EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13672       &connection_, kNewSelfAddress, connection_.peer_address()));
13673   EXPECT_TRUE(alt_path->validated);
13674 
13675   random_generator_.ChangeValue();
13676   connection_.GetMultiPortProbingAlarm()->Fire();
13677   EXPECT_TRUE(connection_.HasPendingPathValidation());
13678   EXPECT_FALSE(connection_.GetMultiPortProbingAlarm()->IsSet());
13679 
13680   // Trigger path degrading and the connection should attempt to migrate.
13681   EXPECT_CALL(visitor_, OnPathDegrading());
13682   EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(0);
13683   EXPECT_CALL(visitor_, MigrateToMultiPortPath(_))
13684       .WillOnce(Invoke([&](std::unique_ptr<QuicPathValidationContext> context) {
13685         EXPECT_EQ(context->self_address(), kNewSelfAddress);
13686         connection_.MigratePath(context->self_address(),
13687                                 context->peer_address(), context->WriterToUse(),
13688                                 /*owns_writer=*/false);
13689       }));
13690   connection_.OnPathDegradingDetected();
13691   EXPECT_FALSE(connection_.HasPendingPathValidation());
13692   auto* path_validator = QuicConnectionPeer::path_validator(&connection_);
13693   EXPECT_FALSE(QuicPathValidatorPeer::retry_timer(path_validator)->IsSet());
13694 }
13695 
TEST_P(QuicConnectionTest,SingleAckInPacket)13696 TEST_P(QuicConnectionTest, SingleAckInPacket) {
13697   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
13698   EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
13699   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13700   connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
13701   connection_.NeuterUnencryptedPackets();
13702   connection_.OnHandshakeComplete();
13703   EXPECT_CALL(visitor_, GetHandshakeState())
13704       .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
13705 
13706   EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=]() {
13707     connection_.SendStreamData3();
13708     connection_.CloseConnection(
13709         QUIC_INTERNAL_ERROR, "error",
13710         ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
13711   }));
13712   QuicFrames frames;
13713   frames.push_back(QuicFrame(frame1_));
13714   ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
13715                                    ENCRYPTION_FORWARD_SECURE);
13716   ASSERT_FALSE(writer_->ack_frames().empty());
13717   EXPECT_EQ(1u, writer_->ack_frames().size());
13718 }
13719 
TEST_P(QuicConnectionTest,ServerReceivedZeroRttPacketAfterOneRttPacketWithRetainedKey)13720 TEST_P(QuicConnectionTest,
13721        ServerReceivedZeroRttPacketAfterOneRttPacketWithRetainedKey) {
13722   if (!connection_.version().UsesTls()) {
13723     return;
13724   }
13725 
13726   set_perspective(Perspective::IS_SERVER);
13727   SetDecrypter(ENCRYPTION_ZERO_RTT,
13728                std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
13729 
13730   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13731   ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13732 
13733   // Finish handshake.
13734   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13735   notifier_.NeuterUnencryptedData();
13736   connection_.NeuterUnencryptedPackets();
13737   connection_.OnHandshakeComplete();
13738   EXPECT_CALL(visitor_, GetHandshakeState())
13739       .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
13740 
13741   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13742   ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13743   EXPECT_TRUE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
13744 
13745   // 0-RTT packet received out of order should be decoded since the decrypter
13746   // is temporarily retained.
13747   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13748   ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13749   EXPECT_EQ(
13750       0u,
13751       connection_.GetStats()
13752           .num_tls_server_zero_rtt_packets_received_after_discarding_decrypter);
13753 
13754   // Simulate the timeout for discarding 0-RTT keys passing.
13755   connection_.GetDiscardZeroRttDecryptionKeysAlarm()->Fire();
13756 
13757   // Another 0-RTT packet received now should not be decoded.
13758   EXPECT_FALSE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
13759   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(0);
13760   ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13761   EXPECT_EQ(
13762       1u,
13763       connection_.GetStats()
13764           .num_tls_server_zero_rtt_packets_received_after_discarding_decrypter);
13765 
13766   // The |discard_zero_rtt_decryption_keys_alarm_| should only be set on the
13767   // first 1-RTT packet received.
13768   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13769   ProcessDataPacketAtLevel(5, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13770   EXPECT_FALSE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
13771 }
13772 
TEST_P(QuicConnectionTest,NewTokenFrameInstigateAcks)13773 TEST_P(QuicConnectionTest, NewTokenFrameInstigateAcks) {
13774   if (!version().HasIetfQuicFrames()) {
13775     return;
13776   }
13777   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
13778 
13779   QuicNewTokenFrame* new_token = new QuicNewTokenFrame();
13780   EXPECT_CALL(visitor_, OnNewTokenReceived(_));
13781   ProcessFramePacket(QuicFrame(new_token));
13782 
13783   // Ensure that this has caused the ACK alarm to be set.
13784   EXPECT_TRUE(connection_.HasPendingAcks());
13785 }
13786 
TEST_P(QuicConnectionTest,ServerClosesConnectionOnNewTokenFrame)13787 TEST_P(QuicConnectionTest, ServerClosesConnectionOnNewTokenFrame) {
13788   if (!version().HasIetfQuicFrames()) {
13789     return;
13790   }
13791   set_perspective(Perspective::IS_SERVER);
13792   QuicNewTokenFrame* new_token = new QuicNewTokenFrame();
13793   EXPECT_CALL(visitor_, OnNewTokenReceived(_)).Times(0);
13794   EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
13795   EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
13796   ProcessFramePacket(QuicFrame(new_token));
13797   EXPECT_FALSE(connection_.connected());
13798 }
13799 
TEST_P(QuicConnectionTest,OverrideRetryTokenWithRetryPacket)13800 TEST_P(QuicConnectionTest, OverrideRetryTokenWithRetryPacket) {
13801   if (!version().HasIetfQuicFrames()) {
13802     return;
13803   }
13804   std::string address_token = "TestAddressToken";
13805   connection_.SetSourceAddressTokenToSend(address_token);
13806   EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
13807                 QuicConnectionPeer::GetPacketCreator(&connection_)),
13808             address_token);
13809   // Passes valid retry and verify token gets overridden.
13810   TestClientRetryHandling(/*invalid_retry_tag=*/false,
13811                           /*missing_original_id_in_config=*/false,
13812                           /*wrong_original_id_in_config=*/false,
13813                           /*missing_retry_id_in_config=*/false,
13814                           /*wrong_retry_id_in_config=*/false);
13815 }
13816 
TEST_P(QuicConnectionTest,DonotOverrideRetryTokenWithAddressToken)13817 TEST_P(QuicConnectionTest, DonotOverrideRetryTokenWithAddressToken) {
13818   if (!version().HasIetfQuicFrames()) {
13819     return;
13820   }
13821   // Passes valid retry and verify token gets overridden.
13822   TestClientRetryHandling(/*invalid_retry_tag=*/false,
13823                           /*missing_original_id_in_config=*/false,
13824                           /*wrong_original_id_in_config=*/false,
13825                           /*missing_retry_id_in_config=*/false,
13826                           /*wrong_retry_id_in_config=*/false);
13827   std::string retry_token = QuicPacketCreatorPeer::GetRetryToken(
13828       QuicConnectionPeer::GetPacketCreator(&connection_));
13829 
13830   std::string address_token = "TestAddressToken";
13831   connection_.SetSourceAddressTokenToSend(address_token);
13832   EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
13833                 QuicConnectionPeer::GetPacketCreator(&connection_)),
13834             retry_token);
13835 }
13836 
TEST_P(QuicConnectionTest,ServerReceivedZeroRttWithHigherPacketNumberThanOneRtt)13837 TEST_P(QuicConnectionTest,
13838        ServerReceivedZeroRttWithHigherPacketNumberThanOneRtt) {
13839   if (!connection_.version().UsesTls()) {
13840     return;
13841   }
13842 
13843   // The code that checks for this error piggybacks on some book-keeping state
13844   // kept for key update, so enable key update for the test.
13845   std::string error_details;
13846   TransportParameters params;
13847   QuicConfig config;
13848   EXPECT_THAT(config.ProcessTransportParameters(
13849                   params, /* is_resumption = */ false, &error_details),
13850               IsQuicNoError());
13851   QuicConfigPeer::SetNegotiated(&config, true);
13852   QuicConfigPeer::SetReceivedOriginalConnectionId(&config,
13853                                                   connection_.connection_id());
13854   QuicConfigPeer::SetReceivedInitialSourceConnectionId(
13855       &config, connection_.connection_id());
13856   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13857   connection_.SetFromConfig(config);
13858 
13859   set_perspective(Perspective::IS_SERVER);
13860   SetDecrypter(ENCRYPTION_ZERO_RTT,
13861                std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
13862 
13863   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13864   ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13865 
13866   // Finish handshake.
13867   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13868   notifier_.NeuterUnencryptedData();
13869   connection_.NeuterUnencryptedPackets();
13870   connection_.OnHandshakeComplete();
13871   EXPECT_CALL(visitor_, GetHandshakeState())
13872       .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
13873 
13874   // Decrypt a 1-RTT packet.
13875   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13876   ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13877   EXPECT_TRUE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
13878 
13879   // 0-RTT packet with higher packet number than a 1-RTT packet is invalid and
13880   // should cause the connection to be closed.
13881   EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
13882   EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
13883   ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13884   EXPECT_FALSE(connection_.connected());
13885   TestConnectionCloseQuicErrorCode(
13886       QUIC_INVALID_0RTT_PACKET_NUMBER_OUT_OF_ORDER);
13887 }
13888 
13889 // Regression test for b/177312785
TEST_P(QuicConnectionTest,PeerMigrateBeforeHandshakeConfirm)13890 TEST_P(QuicConnectionTest, PeerMigrateBeforeHandshakeConfirm) {
13891   if (!VersionHasIetfQuicFrames(version().transport_version)) {
13892     return;
13893   }
13894   set_perspective(Perspective::IS_SERVER);
13895   QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
13896   EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
13897   EXPECT_CALL(visitor_, GetHandshakeState())
13898       .WillRepeatedly(Return(HANDSHAKE_START));
13899 
13900   // Clear direct_peer_address.
13901   QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
13902   // Clear effective_peer_address, it is the same as direct_peer_address for
13903   // this test.
13904   QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
13905                                               QuicSocketAddress());
13906   EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
13907 
13908   const QuicSocketAddress kNewPeerAddress =
13909       QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
13910   EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
13911   ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
13912                                   ENCRYPTION_INITIAL);
13913   EXPECT_EQ(kPeerAddress, connection_.peer_address());
13914   EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
13915 
13916   // Process another packet with a different peer address on server side will
13917   // close connection.
13918   QuicAckFrame frame = InitAckFrame(1);
13919   EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
13920   EXPECT_CALL(visitor_,
13921               OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
13922   EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0u);
13923 
13924   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
13925       .Times(0);
13926   ProcessFramePacketWithAddresses(QuicFrame(&frame), kSelfAddress,
13927                                   kNewPeerAddress, ENCRYPTION_INITIAL);
13928   EXPECT_FALSE(connection_.connected());
13929 }
13930 
13931 // Regresstion test for b/175685916
TEST_P(QuicConnectionTest,TryToFlushAckWithAckQueued)13932 TEST_P(QuicConnectionTest, TryToFlushAckWithAckQueued) {
13933   if (!version().HasIetfQuicFrames()) {
13934     return;
13935   }
13936   SetQuicReloadableFlag(quic_can_send_ack_frequency, true);
13937   set_perspective(Perspective::IS_SERVER);
13938 
13939   QuicConfig config;
13940   QuicConfigPeer::SetReceivedMinAckDelayMs(&config, /*min_ack_delay_ms=*/1);
13941   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13942   connection_.SetFromConfig(config);
13943   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13944   connection_.OnHandshakeComplete();
13945   QuicPacketCreatorPeer::SetPacketNumber(creator_, 200);
13946 
13947   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13948   ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13949   // Sending ACK_FREQUENCY bundles ACK. QuicConnectionPeer::SendPing
13950   // will try to bundle ACK but there is no pending ACK.
13951   EXPECT_CALL(visitor_, SendAckFrequency(_))
13952       .WillOnce(Invoke(&notifier_,
13953                        &SimpleSessionNotifier::WriteOrBufferAckFrequency));
13954   QuicConnectionPeer::SendPing(&connection_);
13955 }
13956 
TEST_P(QuicConnectionTest,PathChallengeBeforePeerIpAddressChangeAtServer)13957 TEST_P(QuicConnectionTest, PathChallengeBeforePeerIpAddressChangeAtServer) {
13958   set_perspective(Perspective::IS_SERVER);
13959   if (!version().HasIetfQuicFrames()) {
13960     return;
13961   }
13962   PathProbeTestInit(Perspective::IS_SERVER);
13963   SetClientConnectionId(TestConnectionId(1));
13964   connection_.CreateConnectionIdManager();
13965 
13966   QuicConnectionId server_cid0 = connection_.connection_id();
13967   QuicConnectionId client_cid0 = connection_.client_connection_id();
13968   QuicConnectionId client_cid1 = TestConnectionId(2);
13969   QuicConnectionId server_cid1;
13970   // Sends new server CID to client.
13971   if (!connection_.connection_id().IsEmpty()) {
13972     EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
13973         .WillOnce(Return(TestConnectionId(456)));
13974   }
13975   EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
13976       .WillOnce(Invoke([&](const QuicConnectionId& cid) {
13977         server_cid1 = cid;
13978         return true;
13979       }));
13980   EXPECT_CALL(visitor_, SendNewConnectionId(_));
13981   connection_.MaybeSendConnectionIdToClient();
13982   // Receives new client CID from client.
13983   QuicNewConnectionIdFrame new_cid_frame;
13984   new_cid_frame.connection_id = client_cid1;
13985   new_cid_frame.sequence_number = 1u;
13986   new_cid_frame.retire_prior_to = 0u;
13987   connection_.OnNewConnectionIdFrame(new_cid_frame);
13988   auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
13989   ASSERT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
13990   ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
13991 
13992   peer_creator_.SetServerConnectionId(server_cid1);
13993   const QuicSocketAddress kNewPeerAddress =
13994       QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
13995   QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
13996   QuicFrames frames1;
13997   frames1.push_back(
13998       QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
13999   QuicPathFrameBuffer payload;
14000   EXPECT_CALL(*send_algorithm_,
14001               OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
14002       .Times(AtLeast(1))
14003       .WillOnce(Invoke([&]() {
14004         EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
14005         EXPECT_EQ(kPeerAddress, connection_.peer_address());
14006         EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14007         EXPECT_FALSE(writer_->path_response_frames().empty());
14008         EXPECT_FALSE(writer_->path_challenge_frames().empty());
14009         payload = writer_->path_challenge_frames().front().data_buffer;
14010       }));
14011   ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewPeerAddress,
14012                                    ENCRYPTION_FORWARD_SECURE);
14013   EXPECT_EQ(kPeerAddress, connection_.peer_address());
14014   EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14015   EXPECT_TRUE(connection_.HasPendingPathValidation());
14016   const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14017   const auto* alternative_path =
14018       QuicConnectionPeer::GetAlternativePath(&connection_);
14019   EXPECT_EQ(default_path->client_connection_id, client_cid0);
14020   EXPECT_EQ(default_path->server_connection_id, server_cid0);
14021   EXPECT_EQ(alternative_path->client_connection_id, client_cid1);
14022   EXPECT_EQ(alternative_path->server_connection_id, server_cid1);
14023   EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
14024   EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
14025 
14026   // Process another packet with a different peer address on server side will
14027   // start connection migration.
14028   EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
14029   EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=]() {
14030     EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
14031   }));
14032   // IETF QUIC send algorithm should be changed to a different object, so no
14033   // OnPacketSent() called on the old send algorithm.
14034   EXPECT_CALL(*send_algorithm_,
14035               OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
14036       .Times(0);
14037   QuicFrames frames2;
14038   frames2.push_back(QuicFrame(frame2_));
14039   ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
14040                                    ENCRYPTION_FORWARD_SECURE);
14041   EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
14042   EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
14043   EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
14044             connection_.active_effective_peer_migration_type());
14045   EXPECT_TRUE(writer_->path_challenge_frames().empty());
14046   EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
14047             send_algorithm_);
14048   // Switch to use the mock send algorithm.
14049   send_algorithm_ = new StrictMock<MockSendAlgorithm>();
14050   EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
14051   EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
14052       .WillRepeatedly(Return(kDefaultTCPMSS));
14053   EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
14054   EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
14055       .Times(AnyNumber())
14056       .WillRepeatedly(Return(QuicBandwidth::Zero()));
14057   EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
14058   EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
14059   EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
14060   connection_.SetSendAlgorithm(send_algorithm_);
14061   EXPECT_EQ(default_path->client_connection_id, client_cid1);
14062   EXPECT_EQ(default_path->server_connection_id, server_cid1);
14063   // The previous default path is kept as alternative path before reverse path
14064   // validation finishes.
14065   EXPECT_EQ(alternative_path->client_connection_id, client_cid0);
14066   EXPECT_EQ(alternative_path->server_connection_id, server_cid0);
14067   EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid1);
14068   EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid1);
14069 
14070   EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
14071   EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
14072   EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
14073             connection_.active_effective_peer_migration_type());
14074   EXPECT_EQ(1u, connection_.GetStats()
14075                     .num_peer_migration_to_proactively_validated_address);
14076 
14077   // The PATH_CHALLENGE and PATH_RESPONSE is expanded upto the max packet size
14078   // which may exceeds the anti-amplification limit. Verify server is throttled
14079   // by anti-amplification limit.
14080   connection_.SendCryptoDataWithString("foo", 0);
14081   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
14082 
14083   // Receiving PATH_RESPONSE should lift the anti-amplification limit.
14084   QuicFrames frames3;
14085   frames3.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
14086   EXPECT_CALL(visitor_, MaybeSendAddressToken());
14087   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
14088       .Times(testing::AtLeast(1u));
14089   ProcessFramesPacketWithAddresses(frames3, kSelfAddress, kNewPeerAddress,
14090                                    ENCRYPTION_FORWARD_SECURE);
14091   EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
14092   // Verify that alternative_path_ is cleared and the peer CID is retired.
14093   EXPECT_TRUE(alternative_path->client_connection_id.IsEmpty());
14094   EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
14095   EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
14096   auto* retire_peer_issued_cid_alarm =
14097       connection_.GetRetirePeerIssuedConnectionIdAlarm();
14098   ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14099   EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14100   retire_peer_issued_cid_alarm->Fire();
14101 
14102   // Verify the anti-amplification limit is lifted by sending a packet larger
14103   // than the anti-amplification limit.
14104   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
14105   EXPECT_CALL(*send_algorithm_, PacingRate(_))
14106       .WillRepeatedly(Return(QuicBandwidth::Zero()));
14107   connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0);
14108   EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
14109   EXPECT_EQ(1u, connection_.num_unlinkable_client_migration());
14110 }
14111 
TEST_P(QuicConnectionTest,PathValidationSucceedsBeforePeerIpAddressChangeAtServer)14112 TEST_P(QuicConnectionTest,
14113        PathValidationSucceedsBeforePeerIpAddressChangeAtServer) {
14114   set_perspective(Perspective::IS_SERVER);
14115   if (!version().HasIetfQuicFrames()) {
14116     return;
14117   }
14118   PathProbeTestInit(Perspective::IS_SERVER);
14119   connection_.CreateConnectionIdManager();
14120 
14121   QuicConnectionId server_cid0 = connection_.connection_id();
14122   QuicConnectionId server_cid1;
14123   // Sends new server CID to client.
14124   if (!connection_.connection_id().IsEmpty()) {
14125     EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14126         .WillOnce(Return(TestConnectionId(456)));
14127   }
14128   EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
14129       .WillOnce(Invoke([&](const QuicConnectionId& cid) {
14130         server_cid1 = cid;
14131         return true;
14132       }));
14133   EXPECT_CALL(visitor_, SendNewConnectionId(_));
14134   connection_.MaybeSendConnectionIdToClient();
14135   auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
14136   ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
14137 
14138   // Receive probing packet with new peer address.
14139   peer_creator_.SetServerConnectionId(server_cid1);
14140   const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
14141                                           /*port=*/23456);
14142   QuicPathFrameBuffer payload;
14143   EXPECT_CALL(*send_algorithm_,
14144               OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
14145       .WillOnce(Invoke([&]() {
14146         EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
14147         EXPECT_EQ(kPeerAddress, connection_.peer_address());
14148         EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14149         EXPECT_FALSE(writer_->path_response_frames().empty());
14150         EXPECT_FALSE(writer_->path_challenge_frames().empty());
14151         payload = writer_->path_challenge_frames().front().data_buffer;
14152       }))
14153       .WillRepeatedly(Invoke([&]() {
14154         // Only start reverse path validation once.
14155         EXPECT_TRUE(writer_->path_challenge_frames().empty());
14156       }));
14157   QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
14158   QuicFrames frames1;
14159   frames1.push_back(
14160       QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
14161   ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewPeerAddress,
14162                                    ENCRYPTION_FORWARD_SECURE);
14163   EXPECT_TRUE(connection_.HasPendingPathValidation());
14164   const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14165   const auto* alternative_path =
14166       QuicConnectionPeer::GetAlternativePath(&connection_);
14167   EXPECT_EQ(default_path->server_connection_id, server_cid0);
14168   EXPECT_EQ(alternative_path->server_connection_id, server_cid1);
14169   EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
14170 
14171   // Receive PATH_RESPONSE should mark the new peer address validated.
14172   QuicFrames frames3;
14173   frames3.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
14174   ProcessFramesPacketWithAddresses(frames3, kSelfAddress, kNewPeerAddress,
14175                                    ENCRYPTION_FORWARD_SECURE);
14176 
14177   // Process another packet with a newer peer address with the same port will
14178   // start connection migration.
14179   EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
14180   // IETF QUIC send algorithm should be changed to a different object, so no
14181   // OnPacketSent() called on the old send algorithm.
14182   EXPECT_CALL(*send_algorithm_,
14183               OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
14184       .Times(0);
14185   const QuicSocketAddress kNewerPeerAddress(QuicIpAddress::Loopback4(),
14186                                             /*port=*/34567);
14187   EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=]() {
14188     EXPECT_EQ(kNewerPeerAddress, connection_.peer_address());
14189   }));
14190   EXPECT_CALL(visitor_, MaybeSendAddressToken());
14191   QuicFrames frames2;
14192   frames2.push_back(QuicFrame(frame2_));
14193   ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewerPeerAddress,
14194                                    ENCRYPTION_FORWARD_SECURE);
14195   EXPECT_EQ(kNewerPeerAddress, connection_.peer_address());
14196   EXPECT_EQ(kNewerPeerAddress, connection_.effective_peer_address());
14197   // Since the newer address has the same IP as the previously validated probing
14198   // address. The peer migration becomes validated immediately.
14199   EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
14200   EXPECT_EQ(kNewerPeerAddress, writer_->last_write_peer_address());
14201   EXPECT_EQ(1u, connection_.GetStats()
14202                     .num_peer_migration_to_proactively_validated_address);
14203   EXPECT_FALSE(connection_.HasPendingPathValidation());
14204   EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
14205             send_algorithm_);
14206 
14207   EXPECT_EQ(default_path->server_connection_id, server_cid1);
14208   EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid1);
14209   // Verify that alternative_path_ is cleared.
14210   EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
14211   EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
14212 
14213   // Switch to use the mock send algorithm.
14214   send_algorithm_ = new StrictMock<MockSendAlgorithm>();
14215   EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
14216   EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
14217       .WillRepeatedly(Return(kDefaultTCPMSS));
14218   EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
14219   EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
14220       .Times(AnyNumber())
14221       .WillRepeatedly(Return(QuicBandwidth::Zero()));
14222   EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
14223   EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
14224   EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
14225   connection_.SetSendAlgorithm(send_algorithm_);
14226 
14227   // Verify the server is not throttled by the anti-amplification limit by
14228   // sending a packet larger than the anti-amplification limit.
14229   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
14230   connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0);
14231   EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
14232 }
14233 
14234 // Regression test of b/228645208.
TEST_P(QuicConnectionTest,NoNonProbingFrameOnAlternativePath)14235 TEST_P(QuicConnectionTest, NoNonProbingFrameOnAlternativePath) {
14236   if (!version().HasIetfQuicFrames()) {
14237     return;
14238   }
14239 
14240   PathProbeTestInit(Perspective::IS_SERVER);
14241   SetClientConnectionId(TestConnectionId(1));
14242   connection_.CreateConnectionIdManager();
14243 
14244   QuicConnectionId server_cid0 = connection_.connection_id();
14245   QuicConnectionId client_cid0 = connection_.client_connection_id();
14246   QuicConnectionId client_cid1 = TestConnectionId(2);
14247   QuicConnectionId server_cid1;
14248   // Sends new server CID to client.
14249   if (!connection_.connection_id().IsEmpty()) {
14250     EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14251         .WillOnce(Return(TestConnectionId(456)));
14252   }
14253   EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
14254       .WillOnce(Invoke([&](const QuicConnectionId& cid) {
14255         server_cid1 = cid;
14256         return true;
14257       }));
14258   EXPECT_CALL(visitor_, SendNewConnectionId(_));
14259   connection_.MaybeSendConnectionIdToClient();
14260   // Receives new client CID from client.
14261   QuicNewConnectionIdFrame new_cid_frame;
14262   new_cid_frame.connection_id = client_cid1;
14263   new_cid_frame.sequence_number = 1u;
14264   new_cid_frame.retire_prior_to = 0u;
14265   connection_.OnNewConnectionIdFrame(new_cid_frame);
14266   auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
14267   ASSERT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
14268   ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
14269 
14270   peer_creator_.SetServerConnectionId(server_cid1);
14271   const QuicSocketAddress kNewPeerAddress =
14272       QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
14273   QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
14274   QuicFrames frames1;
14275   frames1.push_back(
14276       QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
14277   QuicPathFrameBuffer payload;
14278   EXPECT_CALL(*send_algorithm_,
14279               OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
14280       .Times(AtLeast(1))
14281       .WillOnce(Invoke([&]() {
14282         EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
14283         EXPECT_EQ(kPeerAddress, connection_.peer_address());
14284         EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14285         EXPECT_FALSE(writer_->path_response_frames().empty());
14286         EXPECT_FALSE(writer_->path_challenge_frames().empty());
14287         payload = writer_->path_challenge_frames().front().data_buffer;
14288       }));
14289   ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewPeerAddress,
14290                                    ENCRYPTION_FORWARD_SECURE);
14291   EXPECT_EQ(kPeerAddress, connection_.peer_address());
14292   EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14293   EXPECT_TRUE(connection_.HasPendingPathValidation());
14294   const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14295   const auto* alternative_path =
14296       QuicConnectionPeer::GetAlternativePath(&connection_);
14297   EXPECT_EQ(default_path->client_connection_id, client_cid0);
14298   EXPECT_EQ(default_path->server_connection_id, server_cid0);
14299   EXPECT_EQ(alternative_path->client_connection_id, client_cid1);
14300   EXPECT_EQ(alternative_path->server_connection_id, server_cid1);
14301   EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
14302   EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
14303 
14304   // Process non-probing packets on the default path.
14305   peer_creator_.SetServerConnectionId(server_cid0);
14306   EXPECT_CALL(visitor_, OnStreamFrame(_)).WillRepeatedly(Invoke([=]() {
14307     EXPECT_EQ(kPeerAddress, connection_.peer_address());
14308   }));
14309   // Receives packets 3 - 39 to send 19 ACK-only packets, which will force the
14310   // connection to reach |kMaxConsecutiveNonRetransmittablePackets| while
14311   // sending the next ACK.
14312   for (size_t i = 3; i <= 39; ++i) {
14313     ProcessDataPacket(i);
14314   }
14315   EXPECT_EQ(kPeerAddress, connection_.peer_address());
14316   EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14317 
14318   EXPECT_TRUE(connection_.HasPendingAcks());
14319   QuicTime ack_time = connection_.GetAckAlarm()->deadline();
14320   QuicTime path_validation_retry_time =
14321       connection_.GetRetryTimeout(kNewPeerAddress, writer_.get());
14322   // Advance time to simultaneously fire path validation retry and ACK alarms.
14323   clock_.AdvanceTime(std::max(ack_time, path_validation_retry_time) -
14324                      clock_.ApproximateNow());
14325 
14326   // The 20th ACK should bundle with a WINDOW_UPDATE frame.
14327   EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
14328       .WillOnce(Invoke([this]() {
14329         connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
14330       }));
14331   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
14332       .WillOnce(Invoke([&]() {
14333         EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
14334         EXPECT_FALSE(writer_->path_challenge_frames().empty());
14335         // Retry path validation shouldn't bundle ACK.
14336         EXPECT_TRUE(writer_->ack_frames().empty());
14337       }))
14338       .WillOnce(Invoke([&]() {
14339         EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
14340         EXPECT_FALSE(writer_->ack_frames().empty());
14341         EXPECT_FALSE(writer_->window_update_frames().empty());
14342       }));
14343   static_cast<TestAlarmFactory::TestAlarm*>(
14344       QuicPathValidatorPeer::retry_timer(
14345           QuicConnectionPeer::path_validator(&connection_)))
14346       ->Fire();
14347 }
14348 
TEST_P(QuicConnectionTest,DoNotIssueNewCidIfVisitorSaysNo)14349 TEST_P(QuicConnectionTest, DoNotIssueNewCidIfVisitorSaysNo) {
14350   set_perspective(Perspective::IS_SERVER);
14351   if (!version().HasIetfQuicFrames()) {
14352     return;
14353   }
14354 
14355   connection_.CreateConnectionIdManager();
14356 
14357   QuicConnectionId server_cid0 = connection_.connection_id();
14358   QuicConnectionId client_cid1 = TestConnectionId(2);
14359   QuicConnectionId server_cid1;
14360   // Sends new server CID to client.
14361   if (!connection_.connection_id().IsEmpty()) {
14362     EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14363         .WillOnce(Return(TestConnectionId(456)));
14364   }
14365   EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(false));
14366   EXPECT_CALL(visitor_, SendNewConnectionId(_)).Times(0);
14367   connection_.MaybeSendConnectionIdToClient();
14368 }
14369 
TEST_P(QuicConnectionTest,ProbedOnAnotherPathAfterPeerIpAddressChangeAtServer)14370 TEST_P(QuicConnectionTest,
14371        ProbedOnAnotherPathAfterPeerIpAddressChangeAtServer) {
14372   PathProbeTestInit(Perspective::IS_SERVER);
14373   if (!version().HasIetfQuicFrames()) {
14374     return;
14375   }
14376 
14377   const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
14378                                           /*port=*/23456);
14379 
14380   // Process a packet with a new peer address will start connection migration.
14381   EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
14382   // IETF QUIC send algorithm should be changed to a different object, so no
14383   // OnPacketSent() called on the old send algorithm.
14384   EXPECT_CALL(*send_algorithm_,
14385               OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
14386       .Times(0);
14387   EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=]() {
14388     EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
14389   }));
14390   QuicFrames frames2;
14391   frames2.push_back(QuicFrame(frame2_));
14392   ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
14393                                    ENCRYPTION_FORWARD_SECURE);
14394   EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_));
14395   EXPECT_TRUE(connection_.HasPendingPathValidation());
14396 
14397   // Switch to use the mock send algorithm.
14398   send_algorithm_ = new StrictMock<MockSendAlgorithm>();
14399   EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
14400   EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
14401       .WillRepeatedly(Return(kDefaultTCPMSS));
14402   EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
14403   EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
14404       .Times(AnyNumber())
14405       .WillRepeatedly(Return(QuicBandwidth::Zero()));
14406   EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
14407   EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
14408   EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
14409   connection_.SetSendAlgorithm(send_algorithm_);
14410 
14411   // Receive probing packet with a newer peer address shouldn't override the
14412   // on-going path validation.
14413   const QuicSocketAddress kNewerPeerAddress(QuicIpAddress::Loopback4(),
14414                                             /*port=*/34567);
14415   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
14416       .WillOnce(Invoke([&]() {
14417         EXPECT_EQ(kNewerPeerAddress, writer_->last_write_peer_address());
14418         EXPECT_FALSE(writer_->path_response_frames().empty());
14419         EXPECT_TRUE(writer_->path_challenge_frames().empty());
14420       }));
14421   QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
14422   QuicFrames frames1;
14423   frames1.push_back(
14424       QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
14425   ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewerPeerAddress,
14426                                    ENCRYPTION_FORWARD_SECURE);
14427   EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
14428   EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
14429   EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_));
14430   EXPECT_TRUE(connection_.HasPendingPathValidation());
14431 }
14432 
TEST_P(QuicConnectionTest,PathValidationFailedOnClientDueToLackOfServerConnectionId)14433 TEST_P(QuicConnectionTest,
14434        PathValidationFailedOnClientDueToLackOfServerConnectionId) {
14435   if (!version().HasIetfQuicFrames()) {
14436     return;
14437   }
14438   PathProbeTestInit(Perspective::IS_CLIENT,
14439                     /*receive_new_server_connection_id=*/false);
14440 
14441   const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Loopback4(),
14442                                           /*port=*/34567);
14443 
14444   bool success;
14445   connection_.ValidatePath(
14446       std::make_unique<TestQuicPathValidationContext>(
14447           kNewSelfAddress, connection_.peer_address(), writer_.get()),
14448       std::make_unique<TestValidationResultDelegate>(
14449           &connection_, kNewSelfAddress, connection_.peer_address(), &success),
14450       PathValidationReason::kReasonUnknown);
14451 
14452   EXPECT_FALSE(success);
14453 }
14454 
TEST_P(QuicConnectionTest,PathValidationFailedOnClientDueToLackOfClientConnectionIdTheSecondTime)14455 TEST_P(QuicConnectionTest,
14456        PathValidationFailedOnClientDueToLackOfClientConnectionIdTheSecondTime) {
14457   if (!version().HasIetfQuicFrames()) {
14458     return;
14459   }
14460   PathProbeTestInit(Perspective::IS_CLIENT,
14461                     /*receive_new_server_connection_id=*/false);
14462   SetClientConnectionId(TestConnectionId(1));
14463 
14464   // Make sure server connection ID is available for the 1st validation.
14465   QuicConnectionId server_cid0 = connection_.connection_id();
14466   QuicConnectionId server_cid1 = TestConnectionId(2);
14467   QuicConnectionId server_cid2 = TestConnectionId(4);
14468   QuicConnectionId client_cid1;
14469   QuicNewConnectionIdFrame frame1;
14470   frame1.connection_id = server_cid1;
14471   frame1.sequence_number = 1u;
14472   frame1.retire_prior_to = 0u;
14473   frame1.stateless_reset_token =
14474       QuicUtils::GenerateStatelessResetToken(frame1.connection_id);
14475   connection_.OnNewConnectionIdFrame(frame1);
14476   const auto* packet_creator =
14477       QuicConnectionPeer::GetPacketCreator(&connection_);
14478   ASSERT_EQ(packet_creator->GetDestinationConnectionId(), server_cid0);
14479 
14480   // Client will issue a new client connection ID to server.
14481   EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14482       .WillOnce(Return(TestConnectionId(456)));
14483   EXPECT_CALL(visitor_, SendNewConnectionId(_))
14484       .WillOnce(Invoke([&](const QuicNewConnectionIdFrame& frame) {
14485         client_cid1 = frame.connection_id;
14486       }));
14487 
14488   const QuicSocketAddress kSelfAddress1(QuicIpAddress::Any4(), 12345);
14489   ASSERT_NE(kSelfAddress1, connection_.self_address());
14490   bool success1;
14491   connection_.ValidatePath(
14492       std::make_unique<TestQuicPathValidationContext>(
14493           kSelfAddress1, connection_.peer_address(), writer_.get()),
14494       std::make_unique<TestValidationResultDelegate>(
14495           &connection_, kSelfAddress1, connection_.peer_address(), &success1),
14496       PathValidationReason::kReasonUnknown);
14497 
14498   // Migrate upon 1st validation success.
14499   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
14500   ASSERT_TRUE(connection_.MigratePath(kSelfAddress1, connection_.peer_address(),
14501                                       &new_writer, /*owns_writer=*/false));
14502   QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_);
14503   const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14504   EXPECT_EQ(default_path->client_connection_id, client_cid1);
14505   EXPECT_EQ(default_path->server_connection_id, server_cid1);
14506   EXPECT_EQ(default_path->stateless_reset_token, frame1.stateless_reset_token);
14507   const auto* alternative_path =
14508       QuicConnectionPeer::GetAlternativePath(&connection_);
14509   EXPECT_TRUE(alternative_path->client_connection_id.IsEmpty());
14510   EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
14511   EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
14512   ASSERT_EQ(packet_creator->GetDestinationConnectionId(), server_cid1);
14513 
14514   // Client will retire server connection ID on old default_path.
14515   auto* retire_peer_issued_cid_alarm =
14516       connection_.GetRetirePeerIssuedConnectionIdAlarm();
14517   ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14518   EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14519   retire_peer_issued_cid_alarm->Fire();
14520 
14521   // Another server connection ID is available to client.
14522   QuicNewConnectionIdFrame frame2;
14523   frame2.connection_id = server_cid2;
14524   frame2.sequence_number = 2u;
14525   frame2.retire_prior_to = 1u;
14526   frame2.stateless_reset_token =
14527       QuicUtils::GenerateStatelessResetToken(frame2.connection_id);
14528   connection_.OnNewConnectionIdFrame(frame2);
14529 
14530   const QuicSocketAddress kSelfAddress2(QuicIpAddress::Loopback4(),
14531                                         /*port=*/45678);
14532   bool success2;
14533   connection_.ValidatePath(
14534       std::make_unique<TestQuicPathValidationContext>(
14535           kSelfAddress2, connection_.peer_address(), writer_.get()),
14536       std::make_unique<TestValidationResultDelegate>(
14537           &connection_, kSelfAddress2, connection_.peer_address(), &success2),
14538       PathValidationReason::kReasonUnknown);
14539   // Since server does not retire any client connection ID yet, 2nd validation
14540   // would fail due to lack of client connection ID.
14541   EXPECT_FALSE(success2);
14542 }
14543 
TEST_P(QuicConnectionTest,ServerConnectionIdRetiredUponPathValidationFailure)14544 TEST_P(QuicConnectionTest, ServerConnectionIdRetiredUponPathValidationFailure) {
14545   if (!version().HasIetfQuicFrames()) {
14546     return;
14547   }
14548   PathProbeTestInit(Perspective::IS_CLIENT);
14549 
14550   // Make sure server connection ID is available for validation.
14551   QuicNewConnectionIdFrame frame;
14552   frame.connection_id = TestConnectionId(2);
14553   frame.sequence_number = 1u;
14554   frame.retire_prior_to = 0u;
14555   frame.stateless_reset_token =
14556       QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14557   connection_.OnNewConnectionIdFrame(frame);
14558 
14559   const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Loopback4(),
14560                                           /*port=*/34567);
14561   bool success;
14562   connection_.ValidatePath(
14563       std::make_unique<TestQuicPathValidationContext>(
14564           kNewSelfAddress, connection_.peer_address(), writer_.get()),
14565       std::make_unique<TestValidationResultDelegate>(
14566           &connection_, kNewSelfAddress, connection_.peer_address(), &success),
14567       PathValidationReason::kReasonUnknown);
14568 
14569   auto* path_validator = QuicConnectionPeer::path_validator(&connection_);
14570   path_validator->CancelPathValidation();
14571   QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_);
14572   EXPECT_FALSE(success);
14573   const auto* alternative_path =
14574       QuicConnectionPeer::GetAlternativePath(&connection_);
14575   EXPECT_TRUE(alternative_path->client_connection_id.IsEmpty());
14576   EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
14577   EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
14578 
14579   // Client will retire server connection ID on alternative_path.
14580   auto* retire_peer_issued_cid_alarm =
14581       connection_.GetRetirePeerIssuedConnectionIdAlarm();
14582   ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14583   EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/1u));
14584   retire_peer_issued_cid_alarm->Fire();
14585 }
14586 
TEST_P(QuicConnectionTest,MigratePathDirectlyFailedDueToLackOfServerConnectionId)14587 TEST_P(QuicConnectionTest,
14588        MigratePathDirectlyFailedDueToLackOfServerConnectionId) {
14589   if (!version().HasIetfQuicFrames()) {
14590     return;
14591   }
14592   PathProbeTestInit(Perspective::IS_CLIENT,
14593                     /*receive_new_server_connection_id=*/false);
14594   const QuicSocketAddress kSelfAddress1(QuicIpAddress::Any4(), 12345);
14595   ASSERT_NE(kSelfAddress1, connection_.self_address());
14596 
14597   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
14598   ASSERT_FALSE(connection_.MigratePath(kSelfAddress1,
14599                                        connection_.peer_address(), &new_writer,
14600                                        /*owns_writer=*/false));
14601 }
14602 
TEST_P(QuicConnectionTest,MigratePathDirectlyFailedDueToLackOfClientConnectionIdTheSecondTime)14603 TEST_P(QuicConnectionTest,
14604        MigratePathDirectlyFailedDueToLackOfClientConnectionIdTheSecondTime) {
14605   if (!version().HasIetfQuicFrames()) {
14606     return;
14607   }
14608   PathProbeTestInit(Perspective::IS_CLIENT,
14609                     /*receive_new_server_connection_id=*/false);
14610   SetClientConnectionId(TestConnectionId(1));
14611 
14612   // Make sure server connection ID is available for the 1st migration.
14613   QuicNewConnectionIdFrame frame1;
14614   frame1.connection_id = TestConnectionId(2);
14615   frame1.sequence_number = 1u;
14616   frame1.retire_prior_to = 0u;
14617   frame1.stateless_reset_token =
14618       QuicUtils::GenerateStatelessResetToken(frame1.connection_id);
14619   connection_.OnNewConnectionIdFrame(frame1);
14620 
14621   // Client will issue a new client connection ID to server.
14622   QuicConnectionId new_client_connection_id;
14623   EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14624       .WillOnce(Return(TestConnectionId(456)));
14625   EXPECT_CALL(visitor_, SendNewConnectionId(_))
14626       .WillOnce(Invoke([&](const QuicNewConnectionIdFrame& frame) {
14627         new_client_connection_id = frame.connection_id;
14628       }));
14629 
14630   // 1st migration is successful.
14631   const QuicSocketAddress kSelfAddress1(QuicIpAddress::Any4(), 12345);
14632   ASSERT_NE(kSelfAddress1, connection_.self_address());
14633   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
14634   ASSERT_TRUE(connection_.MigratePath(kSelfAddress1, connection_.peer_address(),
14635                                       &new_writer,
14636                                       /*owns_writer=*/false));
14637   QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_);
14638   const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14639   EXPECT_EQ(default_path->client_connection_id, new_client_connection_id);
14640   EXPECT_EQ(default_path->server_connection_id, frame1.connection_id);
14641   EXPECT_EQ(default_path->stateless_reset_token, frame1.stateless_reset_token);
14642 
14643   // Client will retire server connection ID on old default_path.
14644   auto* retire_peer_issued_cid_alarm =
14645       connection_.GetRetirePeerIssuedConnectionIdAlarm();
14646   ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14647   EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14648   retire_peer_issued_cid_alarm->Fire();
14649 
14650   // Another server connection ID is available to client.
14651   QuicNewConnectionIdFrame frame2;
14652   frame2.connection_id = TestConnectionId(4);
14653   frame2.sequence_number = 2u;
14654   frame2.retire_prior_to = 1u;
14655   frame2.stateless_reset_token =
14656       QuicUtils::GenerateStatelessResetToken(frame2.connection_id);
14657   connection_.OnNewConnectionIdFrame(frame2);
14658 
14659   // Since server does not retire any client connection ID yet, 2nd migration
14660   // would fail due to lack of client connection ID.
14661   const QuicSocketAddress kSelfAddress2(QuicIpAddress::Loopback4(),
14662                                         /*port=*/45678);
14663   auto new_writer2 = std::make_unique<TestPacketWriter>(version(), &clock_,
14664                                                         Perspective::IS_CLIENT);
14665   ASSERT_FALSE(connection_.MigratePath(
14666       kSelfAddress2, connection_.peer_address(), new_writer2.release(),
14667       /*owns_writer=*/true));
14668 }
14669 
TEST_P(QuicConnectionTest,CloseConnectionAfterReceiveNewConnectionIdFromPeerUsingEmptyCID)14670 TEST_P(QuicConnectionTest,
14671        CloseConnectionAfterReceiveNewConnectionIdFromPeerUsingEmptyCID) {
14672   if (!version().HasIetfQuicFrames()) {
14673     return;
14674   }
14675   set_perspective(Perspective::IS_SERVER);
14676   ASSERT_TRUE(connection_.client_connection_id().IsEmpty());
14677 
14678   EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
14679   EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
14680       .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
14681   QuicNewConnectionIdFrame frame;
14682   frame.sequence_number = 1u;
14683   frame.connection_id = TestConnectionId(1);
14684   frame.stateless_reset_token =
14685       QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14686   frame.retire_prior_to = 0u;
14687 
14688   EXPECT_FALSE(connection_.OnNewConnectionIdFrame(frame));
14689 
14690   EXPECT_FALSE(connection_.connected());
14691   EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
14692               IsError(IETF_QUIC_PROTOCOL_VIOLATION));
14693 }
14694 
TEST_P(QuicConnectionTest,NewConnectionIdFrameResultsInError)14695 TEST_P(QuicConnectionTest, NewConnectionIdFrameResultsInError) {
14696   if (!version().HasIetfQuicFrames()) {
14697     return;
14698   }
14699   connection_.CreateConnectionIdManager();
14700   ASSERT_FALSE(connection_.connection_id().IsEmpty());
14701 
14702   EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
14703       .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
14704   QuicNewConnectionIdFrame frame;
14705   frame.sequence_number = 1u;
14706   frame.connection_id = connection_id_;  // Reuses connection ID casuing error.
14707   frame.stateless_reset_token =
14708       QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14709   frame.retire_prior_to = 0u;
14710 
14711   EXPECT_FALSE(connection_.OnNewConnectionIdFrame(frame));
14712 
14713   EXPECT_FALSE(connection_.connected());
14714   EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
14715               IsError(IETF_QUIC_PROTOCOL_VIOLATION));
14716 }
14717 
TEST_P(QuicConnectionTest,ClientRetirePeerIssuedConnectionIdTriggeredByNewConnectionIdFrame)14718 TEST_P(QuicConnectionTest,
14719        ClientRetirePeerIssuedConnectionIdTriggeredByNewConnectionIdFrame) {
14720   if (!version().HasIetfQuicFrames()) {
14721     return;
14722   }
14723   connection_.CreateConnectionIdManager();
14724 
14725   QuicNewConnectionIdFrame frame;
14726   frame.sequence_number = 1u;
14727   frame.connection_id = TestConnectionId(1);
14728   frame.stateless_reset_token =
14729       QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14730   frame.retire_prior_to = 0u;
14731 
14732   EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14733   auto* retire_peer_issued_cid_alarm =
14734       connection_.GetRetirePeerIssuedConnectionIdAlarm();
14735   ASSERT_FALSE(retire_peer_issued_cid_alarm->IsSet());
14736 
14737   frame.sequence_number = 2u;
14738   frame.connection_id = TestConnectionId(2);
14739   frame.stateless_reset_token =
14740       QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14741   frame.retire_prior_to = 1u;  // CID associated with #1 will be retired.
14742 
14743   EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14744   ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14745   EXPECT_EQ(connection_.connection_id(), connection_id_);
14746 
14747   EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14748   retire_peer_issued_cid_alarm->Fire();
14749   EXPECT_EQ(connection_.connection_id(), TestConnectionId(2));
14750   EXPECT_EQ(connection_.packet_creator().GetDestinationConnectionId(),
14751             TestConnectionId(2));
14752 }
14753 
TEST_P(QuicConnectionTest,ServerRetirePeerIssuedConnectionIdTriggeredByNewConnectionIdFrame)14754 TEST_P(QuicConnectionTest,
14755        ServerRetirePeerIssuedConnectionIdTriggeredByNewConnectionIdFrame) {
14756   if (!version().HasIetfQuicFrames()) {
14757     return;
14758   }
14759   set_perspective(Perspective::IS_SERVER);
14760   SetClientConnectionId(TestConnectionId(0));
14761 
14762   QuicNewConnectionIdFrame frame;
14763   frame.sequence_number = 1u;
14764   frame.connection_id = TestConnectionId(1);
14765   frame.stateless_reset_token =
14766       QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14767   frame.retire_prior_to = 0u;
14768 
14769   EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14770   auto* retire_peer_issued_cid_alarm =
14771       connection_.GetRetirePeerIssuedConnectionIdAlarm();
14772   ASSERT_FALSE(retire_peer_issued_cid_alarm->IsSet());
14773 
14774   frame.sequence_number = 2u;
14775   frame.connection_id = TestConnectionId(2);
14776   frame.stateless_reset_token =
14777       QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14778   frame.retire_prior_to = 1u;  // CID associated with #1 will be retired.
14779 
14780   EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14781   ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14782   EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(0));
14783 
14784   EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14785   retire_peer_issued_cid_alarm->Fire();
14786   EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(2));
14787   EXPECT_EQ(connection_.packet_creator().GetDestinationConnectionId(),
14788             TestConnectionId(2));
14789 }
14790 
TEST_P(QuicConnectionTest,ReplacePeerIssuedConnectionIdOnBothPathsTriggeredByNewConnectionIdFrame)14791 TEST_P(
14792     QuicConnectionTest,
14793     ReplacePeerIssuedConnectionIdOnBothPathsTriggeredByNewConnectionIdFrame) {
14794   if (!version().HasIetfQuicFrames()) {
14795     return;
14796   }
14797   PathProbeTestInit(Perspective::IS_SERVER);
14798   SetClientConnectionId(TestConnectionId(0));
14799 
14800   // Populate alternative_path_ with probing packet.
14801   std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
14802 
14803   std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
14804       QuicEncryptedPacket(probing_packet->encrypted_buffer,
14805                           probing_packet->encrypted_length),
14806       clock_.Now()));
14807   QuicIpAddress new_host;
14808   new_host.FromString("1.1.1.1");
14809   ProcessReceivedPacket(kSelfAddress,
14810                         QuicSocketAddress(new_host, /*port=*/23456), *received);
14811 
14812   EXPECT_EQ(
14813       TestConnectionId(0),
14814       QuicConnectionPeer::GetClientConnectionIdOnAlternativePath(&connection_));
14815 
14816   QuicNewConnectionIdFrame frame;
14817   frame.sequence_number = 1u;
14818   frame.connection_id = TestConnectionId(1);
14819   frame.stateless_reset_token =
14820       QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14821   frame.retire_prior_to = 0u;
14822 
14823   EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14824   auto* retire_peer_issued_cid_alarm =
14825       connection_.GetRetirePeerIssuedConnectionIdAlarm();
14826   ASSERT_FALSE(retire_peer_issued_cid_alarm->IsSet());
14827 
14828   frame.sequence_number = 2u;
14829   frame.connection_id = TestConnectionId(2);
14830   frame.stateless_reset_token =
14831       QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14832   frame.retire_prior_to = 1u;  // CID associated with #1 will be retired.
14833 
14834   EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14835   ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14836   EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(0));
14837 
14838   EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14839   retire_peer_issued_cid_alarm->Fire();
14840   EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(2));
14841   EXPECT_EQ(connection_.packet_creator().GetDestinationConnectionId(),
14842             TestConnectionId(2));
14843   // Clean up alternative path connection ID.
14844   EXPECT_EQ(
14845       TestConnectionId(2),
14846       QuicConnectionPeer::GetClientConnectionIdOnAlternativePath(&connection_));
14847 }
14848 
TEST_P(QuicConnectionTest,CloseConnectionAfterReceiveRetireConnectionIdWhenNoCIDIssued)14849 TEST_P(QuicConnectionTest,
14850        CloseConnectionAfterReceiveRetireConnectionIdWhenNoCIDIssued) {
14851   if (!version().HasIetfQuicFrames()) {
14852     return;
14853   }
14854   set_perspective(Perspective::IS_SERVER);
14855 
14856   EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
14857   EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
14858       .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
14859   QuicRetireConnectionIdFrame frame;
14860   frame.sequence_number = 1u;
14861 
14862   EXPECT_FALSE(connection_.OnRetireConnectionIdFrame(frame));
14863 
14864   EXPECT_FALSE(connection_.connected());
14865   EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
14866               IsError(IETF_QUIC_PROTOCOL_VIOLATION));
14867 }
14868 
TEST_P(QuicConnectionTest,RetireConnectionIdFrameResultsInError)14869 TEST_P(QuicConnectionTest, RetireConnectionIdFrameResultsInError) {
14870   if (!version().HasIetfQuicFrames()) {
14871     return;
14872   }
14873   set_perspective(Perspective::IS_SERVER);
14874   connection_.CreateConnectionIdManager();
14875 
14876   if (!connection_.connection_id().IsEmpty()) {
14877     EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14878         .WillOnce(Return(TestConnectionId(456)));
14879   }
14880   EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(true));
14881   EXPECT_CALL(visitor_, SendNewConnectionId(_));
14882   connection_.MaybeSendConnectionIdToClient();
14883 
14884   EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
14885   EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
14886       .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
14887   QuicRetireConnectionIdFrame frame;
14888   frame.sequence_number = 2u;  // The corresponding ID is never issued.
14889 
14890   EXPECT_FALSE(connection_.OnRetireConnectionIdFrame(frame));
14891 
14892   EXPECT_FALSE(connection_.connected());
14893   EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
14894               IsError(IETF_QUIC_PROTOCOL_VIOLATION));
14895 }
14896 
TEST_P(QuicConnectionTest,ServerRetireSelfIssuedConnectionIdWithoutSendingNewConnectionIdBefore)14897 TEST_P(QuicConnectionTest,
14898        ServerRetireSelfIssuedConnectionIdWithoutSendingNewConnectionIdBefore) {
14899   if (!version().HasIetfQuicFrames()) {
14900     return;
14901   }
14902   set_perspective(Perspective::IS_SERVER);
14903   connection_.CreateConnectionIdManager();
14904 
14905   auto* retire_self_issued_cid_alarm =
14906       connection_.GetRetireSelfIssuedConnectionIdAlarm();
14907   ASSERT_FALSE(retire_self_issued_cid_alarm->IsSet());
14908 
14909   QuicConnectionId cid0 = connection_id_;
14910   QuicRetireConnectionIdFrame frame;
14911   frame.sequence_number = 0u;
14912 
14913   if (!connection_.connection_id().IsEmpty()) {
14914     EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(cid0))
14915         .WillOnce(Return(TestConnectionId(456)));
14916     EXPECT_CALL(connection_id_generator_,
14917                 GenerateNextConnectionId(TestConnectionId(456)))
14918         .WillOnce(Return(TestConnectionId(789)));
14919   }
14920   EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
14921       .Times(2)
14922       .WillRepeatedly(Return(true));
14923   EXPECT_CALL(visitor_, SendNewConnectionId(_)).Times(2);
14924   EXPECT_TRUE(connection_.OnRetireConnectionIdFrame(frame));
14925 }
14926 
TEST_P(QuicConnectionTest,ServerRetireSelfIssuedConnectionId)14927 TEST_P(QuicConnectionTest, ServerRetireSelfIssuedConnectionId) {
14928   if (!version().HasIetfQuicFrames()) {
14929     return;
14930   }
14931   set_perspective(Perspective::IS_SERVER);
14932   connection_.CreateConnectionIdManager();
14933   QuicConnectionId recorded_cid;
14934   auto cid_recorder = [&recorded_cid](const QuicConnectionId& cid) -> bool {
14935     recorded_cid = cid;
14936     return true;
14937   };
14938   QuicConnectionId cid0 = connection_id_;
14939   QuicConnectionId cid1;
14940   QuicConnectionId cid2;
14941   EXPECT_EQ(connection_.connection_id(), cid0);
14942   EXPECT_EQ(connection_.GetOneActiveServerConnectionId(), cid0);
14943 
14944   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
14945   if (!connection_.connection_id().IsEmpty()) {
14946     EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14947         .WillOnce(Return(TestConnectionId(456)));
14948   }
14949   EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
14950       .WillOnce(Invoke(cid_recorder));
14951   EXPECT_CALL(visitor_, SendNewConnectionId(_));
14952   connection_.MaybeSendConnectionIdToClient();
14953   cid1 = recorded_cid;
14954 
14955   auto* retire_self_issued_cid_alarm =
14956       connection_.GetRetireSelfIssuedConnectionIdAlarm();
14957   ASSERT_FALSE(retire_self_issued_cid_alarm->IsSet());
14958 
14959   // Generate three packets with different connection IDs that will arrive out
14960   // of order (2, 1, 3) later.
14961   char buffers[3][kMaxOutgoingPacketSize];
14962   // Destination connection ID of packet1 is cid0.
14963   auto packet1 =
14964       ConstructPacket({QuicFrame(QuicPingFrame())}, ENCRYPTION_FORWARD_SECURE,
14965                       buffers[0], kMaxOutgoingPacketSize);
14966   peer_creator_.SetServerConnectionId(cid1);
14967   auto retire_cid_frame = std::make_unique<QuicRetireConnectionIdFrame>();
14968   retire_cid_frame->sequence_number = 0u;
14969   // Destination connection ID of packet2 is cid1.
14970   auto packet2 = ConstructPacket({QuicFrame(retire_cid_frame.release())},
14971                                  ENCRYPTION_FORWARD_SECURE, buffers[1],
14972                                  kMaxOutgoingPacketSize);
14973   // Destination connection ID of packet3 is cid1.
14974   auto packet3 =
14975       ConstructPacket({QuicFrame(QuicPingFrame())}, ENCRYPTION_FORWARD_SECURE,
14976                       buffers[2], kMaxOutgoingPacketSize);
14977 
14978   // Packet2 with RetireConnectionId frame trigers sending NewConnectionId
14979   // immediately.
14980   if (!connection_.connection_id().IsEmpty()) {
14981     EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14982         .WillOnce(Return(TestConnectionId(456)));
14983   }
14984   EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
14985       .WillOnce(Invoke(cid_recorder));
14986   EXPECT_CALL(visitor_, SendNewConnectionId(_));
14987   peer_creator_.SetServerConnectionId(cid1);
14988   connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *packet2);
14989   cid2 = recorded_cid;
14990   // cid0 is not retired immediately.
14991   EXPECT_THAT(connection_.GetActiveServerConnectionIds(),
14992               ElementsAre(cid0, cid1, cid2));
14993   ASSERT_TRUE(retire_self_issued_cid_alarm->IsSet());
14994   EXPECT_EQ(connection_.connection_id(), cid1);
14995   EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid0 ||
14996               connection_.GetOneActiveServerConnectionId() == cid1 ||
14997               connection_.GetOneActiveServerConnectionId() == cid2);
14998 
14999   // Packet1 updates the connection ID on the default path but not the active
15000   // connection ID.
15001   connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *packet1);
15002   EXPECT_EQ(connection_.connection_id(), cid0);
15003   EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid0 ||
15004               connection_.GetOneActiveServerConnectionId() == cid1 ||
15005               connection_.GetOneActiveServerConnectionId() == cid2);
15006 
15007   // cid0 is retired when the retire CID alarm fires.
15008   EXPECT_CALL(visitor_, OnServerConnectionIdRetired(cid0));
15009   retire_self_issued_cid_alarm->Fire();
15010   EXPECT_THAT(connection_.GetActiveServerConnectionIds(),
15011               ElementsAre(cid1, cid2));
15012   EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid1 ||
15013               connection_.GetOneActiveServerConnectionId() == cid2);
15014 
15015   // Packet3 updates the connection ID on the default path.
15016   connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *packet3);
15017   EXPECT_EQ(connection_.connection_id(), cid1);
15018   EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid1 ||
15019               connection_.GetOneActiveServerConnectionId() == cid2);
15020 }
15021 
TEST_P(QuicConnectionTest,PatchMissingClientConnectionIdOntoAlternativePath)15022 TEST_P(QuicConnectionTest, PatchMissingClientConnectionIdOntoAlternativePath) {
15023   if (!version().HasIetfQuicFrames()) {
15024     return;
15025   }
15026   set_perspective(Perspective::IS_SERVER);
15027   connection_.CreateConnectionIdManager();
15028   connection_.set_client_connection_id(TestConnectionId(1));
15029 
15030   // Set up the state after path probing.
15031   const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
15032   auto* alternative_path = QuicConnectionPeer::GetAlternativePath(&connection_);
15033   QuicIpAddress new_host;
15034   new_host.FromString("12.12.12.12");
15035   alternative_path->self_address = default_path->self_address;
15036   alternative_path->peer_address = QuicSocketAddress(new_host, 12345);
15037   alternative_path->server_connection_id = TestConnectionId(3);
15038   ASSERT_TRUE(alternative_path->client_connection_id.IsEmpty());
15039   ASSERT_FALSE(alternative_path->stateless_reset_token.has_value());
15040 
15041   QuicNewConnectionIdFrame frame;
15042   frame.sequence_number = 1u;
15043   frame.connection_id = TestConnectionId(5);
15044   frame.stateless_reset_token =
15045       QuicUtils::GenerateStatelessResetToken(frame.connection_id);
15046   frame.retire_prior_to = 0u;
15047   // New ID is patched onto the alternative path when the needed
15048   // NEW_CONNECTION_ID frame is received after PATH_CHALLENGE frame.
15049   connection_.OnNewConnectionIdFrame(frame);
15050 
15051   ASSERT_EQ(alternative_path->client_connection_id, frame.connection_id);
15052   ASSERT_EQ(alternative_path->stateless_reset_token,
15053             frame.stateless_reset_token);
15054 }
15055 
TEST_P(QuicConnectionTest,PatchMissingClientConnectionIdOntoDefaultPath)15056 TEST_P(QuicConnectionTest, PatchMissingClientConnectionIdOntoDefaultPath) {
15057   if (!version().HasIetfQuicFrames()) {
15058     return;
15059   }
15060   set_perspective(Perspective::IS_SERVER);
15061   connection_.CreateConnectionIdManager();
15062   connection_.set_client_connection_id(TestConnectionId(1));
15063 
15064   // Set up the state after peer migration without probing.
15065   auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
15066   auto* alternative_path = QuicConnectionPeer::GetAlternativePath(&connection_);
15067   auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
15068   *alternative_path = std::move(*default_path);
15069   QuicIpAddress new_host;
15070   new_host.FromString("12.12.12.12");
15071   default_path->self_address = default_path->self_address;
15072   default_path->peer_address = QuicSocketAddress(new_host, 12345);
15073   default_path->server_connection_id = TestConnectionId(3);
15074   packet_creator->SetDefaultPeerAddress(default_path->peer_address);
15075   packet_creator->SetServerConnectionId(default_path->server_connection_id);
15076   packet_creator->SetClientConnectionId(default_path->client_connection_id);
15077 
15078   ASSERT_FALSE(default_path->validated);
15079   ASSERT_TRUE(default_path->client_connection_id.IsEmpty());
15080   ASSERT_FALSE(default_path->stateless_reset_token.has_value());
15081 
15082   QuicNewConnectionIdFrame frame;
15083   frame.sequence_number = 1u;
15084   frame.connection_id = TestConnectionId(5);
15085   frame.stateless_reset_token =
15086       QuicUtils::GenerateStatelessResetToken(frame.connection_id);
15087   frame.retire_prior_to = 0u;
15088   // New ID is patched onto the default path when the needed
15089   // NEW_CONNECTION_ID frame is received after PATH_CHALLENGE frame.
15090   connection_.OnNewConnectionIdFrame(frame);
15091 
15092   ASSERT_EQ(default_path->client_connection_id, frame.connection_id);
15093   ASSERT_EQ(default_path->stateless_reset_token, frame.stateless_reset_token);
15094   ASSERT_EQ(packet_creator->GetDestinationConnectionId(), frame.connection_id);
15095 }
15096 
TEST_P(QuicConnectionTest,ShouldGeneratePacketBlockedByMissingConnectionId)15097 TEST_P(QuicConnectionTest, ShouldGeneratePacketBlockedByMissingConnectionId) {
15098   if (!version().HasIetfQuicFrames()) {
15099     return;
15100   }
15101   set_perspective(Perspective::IS_SERVER);
15102   connection_.set_client_connection_id(TestConnectionId(1));
15103   connection_.CreateConnectionIdManager();
15104   if (version().SupportsAntiAmplificationLimit()) {
15105     QuicConnectionPeer::SetAddressValidated(&connection_);
15106   }
15107 
15108   ASSERT_TRUE(
15109       connection_.ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, NOT_HANDSHAKE));
15110 
15111   QuicPacketCreator* packet_creator =
15112       QuicConnectionPeer::GetPacketCreator(&connection_);
15113   QuicIpAddress peer_host1;
15114   peer_host1.FromString("12.12.12.12");
15115   QuicSocketAddress peer_address1(peer_host1, 1235);
15116 
15117   {
15118     // No connection ID is available as context is created without any.
15119     QuicPacketCreator::ScopedPeerAddressContext context(
15120         packet_creator, peer_address1, EmptyQuicConnectionId(),
15121         EmptyQuicConnectionId());
15122     ASSERT_FALSE(connection_.ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA,
15123                                                   NOT_HANDSHAKE));
15124   }
15125   ASSERT_TRUE(
15126       connection_.ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, NOT_HANDSHAKE));
15127 }
15128 
15129 // Regression test for b/182571515
TEST_P(QuicConnectionTest,LostDataThenGetAcknowledged)15130 TEST_P(QuicConnectionTest, LostDataThenGetAcknowledged) {
15131   set_perspective(Perspective::IS_SERVER);
15132   if (!version().SupportsAntiAmplificationLimit() ||
15133       GetQuicFlag(quic_enforce_strict_amplification_factor)) {
15134     return;
15135   }
15136 
15137   QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
15138   if (version().SupportsAntiAmplificationLimit()) {
15139     QuicConnectionPeer::SetAddressValidated(&connection_);
15140   }
15141   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15142   // Discard INITIAL key.
15143   connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
15144   connection_.NeuterUnencryptedPackets();
15145   EXPECT_CALL(visitor_, GetHandshakeState())
15146       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
15147 
15148   QuicPacketNumber last_packet;
15149   // Send packets 1 to 4.
15150   SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet);  // Packet 1
15151   SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet);  // Packet 2
15152   SendStreamDataToPeer(3, "foo", 6, NO_FIN, &last_packet);  // Packet 3
15153   SendStreamDataToPeer(3, "foo", 9, NO_FIN, &last_packet);  // Packet 4
15154 
15155   // Process a PING packet to set peer address.
15156   ProcessFramePacket(QuicFrame(QuicPingFrame()));
15157 
15158   // Process a packet containing a STREAM_FRAME and an ACK with changed peer
15159   // address.
15160   QuicFrames frames;
15161   frames.push_back(QuicFrame(frame1_));
15162   QuicAckFrame ack = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)}});
15163   frames.push_back(QuicFrame(&ack));
15164 
15165   // Invoke OnCanWrite.
15166   QuicIpAddress ip_address;
15167   ASSERT_TRUE(ip_address.FromString("127.0.52.223"));
15168   EXPECT_QUIC_BUG(
15169       {
15170         EXPECT_CALL(visitor_, OnConnectionMigration(_)).Times(1);
15171         EXPECT_CALL(visitor_, OnStreamFrame(_))
15172             .WillOnce(InvokeWithoutArgs(&notifier_,
15173                                         &SimpleSessionNotifier::OnCanWrite));
15174         ProcessFramesPacketWithAddresses(frames, kSelfAddress,
15175                                          QuicSocketAddress(ip_address, 1000),
15176                                          ENCRYPTION_FORWARD_SECURE);
15177         EXPECT_EQ(1u, writer_->path_challenge_frames().size());
15178 
15179         // Verify stream frame will not be retransmitted.
15180         EXPECT_TRUE(writer_->stream_frames().empty());
15181       },
15182       "Try to write mid packet processing");
15183 }
15184 
TEST_P(QuicConnectionTest,PtoSendStreamData)15185 TEST_P(QuicConnectionTest, PtoSendStreamData) {
15186   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
15187     return;
15188   }
15189   set_perspective(Perspective::IS_SERVER);
15190   if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
15191     EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15192   }
15193   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
15194   ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15195   EXPECT_TRUE(connection_.HasPendingAcks());
15196 
15197   connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15198   // Send INITIAL 1.
15199   connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15200 
15201   connection_.SetEncrypter(
15202       ENCRYPTION_HANDSHAKE,
15203       std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
15204   connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15205   SetDecrypter(ENCRYPTION_HANDSHAKE,
15206                std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
15207   // Send HANDSHAKE packets.
15208   EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15209   connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
15210 
15211   connection_.SetEncrypter(
15212       ENCRYPTION_FORWARD_SECURE,
15213       std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
15214   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15215 
15216   // Send half RTT packet with congestion control blocked.
15217   EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false));
15218   connection_.SendStreamDataWithString(2, std::string(1500, 'a'), 0, NO_FIN);
15219 
15220   ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15221   connection_.GetRetransmissionAlarm()->Fire();
15222   // Verify INITIAL and HANDSHAKE get retransmitted.
15223   EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
15224 }
15225 
TEST_P(QuicConnectionTest,SendingZeroRttPacketsDoesNotPostponePTO)15226 TEST_P(QuicConnectionTest, SendingZeroRttPacketsDoesNotPostponePTO) {
15227   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
15228     return;
15229   }
15230   connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15231   // Send CHLO.
15232   connection_.SendCryptoStreamData();
15233   ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15234   // Install 0-RTT keys.
15235   connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
15236                            std::make_unique<TaggingEncrypter>(0x02));
15237   connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15238 
15239   // CHLO gets acknowledged after 10ms.
15240   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
15241   QuicAckFrame frame1 = InitAckFrame(1);
15242   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
15243   ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
15244   // Verify PTO is still armed since address validation is not finished yet.
15245   ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15246   QuicTime pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
15247 
15248   // Send 0-RTT packet.
15249   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
15250   connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
15251                            std::make_unique<TaggingEncrypter>(0x02));
15252   connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15253   connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
15254   ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15255   // PTO deadline should be unchanged.
15256   EXPECT_EQ(pto_deadline, connection_.GetRetransmissionAlarm()->deadline());
15257 }
15258 
TEST_P(QuicConnectionTest,QueueingUndecryptablePacketsDoesntPostponePTO)15259 TEST_P(QuicConnectionTest, QueueingUndecryptablePacketsDoesntPostponePTO) {
15260   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
15261     return;
15262   }
15263   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
15264   QuicConfig config;
15265   config.set_max_undecryptable_packets(3);
15266   connection_.SetFromConfig(config);
15267   connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15268   connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
15269   // Send CHLO.
15270   connection_.SendCryptoStreamData();
15271 
15272   // Send 0-RTT packet.
15273   connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
15274                            std::make_unique<TaggingEncrypter>(0x02));
15275   connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15276   connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
15277 
15278   // CHLO gets acknowledged after 10ms.
15279   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
15280   QuicAckFrame frame1 = InitAckFrame(1);
15281   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
15282   ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
15283   // Verify PTO is still armed since address validation is not finished yet.
15284   ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15285   QuicTime pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
15286 
15287   // Receive an undecryptable packets.
15288   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
15289   peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
15290                             std::make_unique<TaggingEncrypter>(0xFF));
15291   ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
15292   // Verify PTO deadline is sooner.
15293   EXPECT_GT(pto_deadline, connection_.GetRetransmissionAlarm()->deadline());
15294   pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
15295 
15296   // PTO fires.
15297   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
15298   clock_.AdvanceTime(pto_deadline - clock_.ApproximateNow());
15299   connection_.GetRetransmissionAlarm()->Fire();
15300   // Verify PTO is still armed since address validation is not finished yet.
15301   ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15302   pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
15303 
15304   // Verify PTO deadline does not change.
15305   ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
15306   EXPECT_EQ(pto_deadline, connection_.GetRetransmissionAlarm()->deadline());
15307 }
15308 
TEST_P(QuicConnectionTest,QueueUndecryptableHandshakePackets)15309 TEST_P(QuicConnectionTest, QueueUndecryptableHandshakePackets) {
15310   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
15311     return;
15312   }
15313   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
15314   QuicConfig config;
15315   config.set_max_undecryptable_packets(3);
15316   connection_.SetFromConfig(config);
15317   connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15318   connection_.RemoveDecrypter(ENCRYPTION_HANDSHAKE);
15319   // Send CHLO.
15320   connection_.SendCryptoStreamData();
15321 
15322   // Send 0-RTT packet.
15323   connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
15324                            std::make_unique<TaggingEncrypter>(0x02));
15325   connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15326   connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
15327   EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15328 
15329   // Receive an undecryptable handshake packet.
15330   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
15331   peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
15332                             std::make_unique<TaggingEncrypter>(0xFF));
15333   ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
15334   // Verify this handshake packet gets queued.
15335   EXPECT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15336 }
15337 
TEST_P(QuicConnectionTest,PingNotSentAt0RTTLevelWhenInitialAvailable)15338 TEST_P(QuicConnectionTest, PingNotSentAt0RTTLevelWhenInitialAvailable) {
15339   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
15340     return;
15341   }
15342   connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15343   // Send CHLO.
15344   connection_.SendCryptoStreamData();
15345   // Send 0-RTT packet.
15346   connection_.SetEncrypter(
15347       ENCRYPTION_ZERO_RTT,
15348       std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
15349   connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15350   connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
15351 
15352   // CHLO gets acknowledged after 10ms.
15353   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
15354   QuicAckFrame frame1 = InitAckFrame(1);
15355   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
15356   ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
15357   // Verify PTO is still armed since address validation is not finished yet.
15358   ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15359   QuicTime pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
15360 
15361   // PTO fires.
15362   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
15363   clock_.AdvanceTime(pto_deadline - clock_.ApproximateNow());
15364   connection_.GetRetransmissionAlarm()->Fire();
15365   // Verify the PING gets sent in ENCRYPTION_INITIAL.
15366   EXPECT_NE(0x02020202u, writer_->final_bytes_of_last_packet());
15367 }
15368 
TEST_P(QuicConnectionTest,AckElicitingFrames)15369 TEST_P(QuicConnectionTest, AckElicitingFrames) {
15370   if (!version().HasIetfQuicFrames()) {
15371     return;
15372   }
15373   EXPECT_CALL(connection_id_generator_,
15374               GenerateNextConnectionId(TestConnectionId(12)))
15375       .WillOnce(Return(TestConnectionId(456)));
15376   EXPECT_CALL(connection_id_generator_,
15377               GenerateNextConnectionId(TestConnectionId(456)))
15378       .WillOnce(Return(TestConnectionId(789)));
15379   EXPECT_CALL(visitor_, SendNewConnectionId(_)).Times(2);
15380   EXPECT_CALL(visitor_, OnRstStream(_));
15381   EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
15382   EXPECT_CALL(visitor_, OnBlockedFrame(_));
15383   EXPECT_CALL(visitor_, OnHandshakeDoneReceived());
15384   EXPECT_CALL(visitor_, OnStreamFrame(_));
15385   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
15386   EXPECT_CALL(visitor_, OnMaxStreamsFrame(_));
15387   EXPECT_CALL(visitor_, OnStreamsBlockedFrame(_));
15388   EXPECT_CALL(visitor_, OnStopSendingFrame(_));
15389   EXPECT_CALL(visitor_, OnMessageReceived(""));
15390   EXPECT_CALL(visitor_, OnNewTokenReceived(""));
15391 
15392   SetClientConnectionId(TestConnectionId(12));
15393   connection_.CreateConnectionIdManager();
15394   QuicConnectionPeer::GetSelfIssuedConnectionIdManager(&connection_)
15395       ->MaybeSendNewConnectionIds();
15396   connection_.set_can_receive_ack_frequency_frame();
15397 
15398   QuicAckFrame ack_frame = InitAckFrame(1);
15399   QuicRstStreamFrame rst_stream_frame;
15400   QuicWindowUpdateFrame window_update_frame;
15401   QuicPathChallengeFrame path_challenge_frame;
15402   QuicNewConnectionIdFrame new_connection_id_frame;
15403   new_connection_id_frame.sequence_number = 1u;
15404   QuicRetireConnectionIdFrame retire_connection_id_frame;
15405   retire_connection_id_frame.sequence_number = 1u;
15406   QuicStopSendingFrame stop_sending_frame;
15407   QuicPathResponseFrame path_response_frame;
15408   QuicMessageFrame message_frame;
15409   QuicNewTokenFrame new_token_frame;
15410   QuicAckFrequencyFrame ack_frequency_frame;
15411   QuicResetStreamAtFrame reset_stream_at_frame;
15412   QuicBlockedFrame blocked_frame;
15413   size_t packet_number = 1;
15414 
15415   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15416   QuicFramer* framer = const_cast<QuicFramer*>(&connection_.framer());
15417   framer->set_process_reset_stream_at(true);
15418   peer_framer_.set_process_reset_stream_at(true);
15419 
15420   for (uint8_t i = 0; i < NUM_FRAME_TYPES; ++i) {
15421     QuicFrameType frame_type = static_cast<QuicFrameType>(i);
15422     bool skipped = false;
15423     QuicFrame frame;
15424     QuicFrames frames;
15425     // Add some padding to fullfill the min size requirement of header
15426     // protection.
15427     frames.push_back(QuicFrame(QuicPaddingFrame(10)));
15428     switch (frame_type) {
15429       case PADDING_FRAME:
15430         frame = QuicFrame(QuicPaddingFrame(10));
15431         break;
15432       case MTU_DISCOVERY_FRAME:
15433         frame = QuicFrame(QuicMtuDiscoveryFrame());
15434         break;
15435       case PING_FRAME:
15436         frame = QuicFrame(QuicPingFrame());
15437         break;
15438       case MAX_STREAMS_FRAME:
15439         frame = QuicFrame(QuicMaxStreamsFrame());
15440         break;
15441       case STOP_WAITING_FRAME:
15442         // Not supported.
15443         skipped = true;
15444         break;
15445       case STREAMS_BLOCKED_FRAME:
15446         frame = QuicFrame(QuicStreamsBlockedFrame());
15447         break;
15448       case STREAM_FRAME:
15449         frame = QuicFrame(QuicStreamFrame());
15450         break;
15451       case HANDSHAKE_DONE_FRAME:
15452         frame = QuicFrame(QuicHandshakeDoneFrame());
15453         break;
15454       case ACK_FRAME:
15455         frame = QuicFrame(&ack_frame);
15456         break;
15457       case RST_STREAM_FRAME:
15458         frame = QuicFrame(&rst_stream_frame);
15459         break;
15460       case CONNECTION_CLOSE_FRAME:
15461         // Do not test connection close.
15462         skipped = true;
15463         break;
15464       case GOAWAY_FRAME:
15465         // Does not exist in IETF QUIC.
15466         skipped = true;
15467         break;
15468       case BLOCKED_FRAME:
15469         frame = QuicFrame(blocked_frame);
15470         break;
15471       case WINDOW_UPDATE_FRAME:
15472         frame = QuicFrame(window_update_frame);
15473         break;
15474       case PATH_CHALLENGE_FRAME:
15475         frame = QuicFrame(path_challenge_frame);
15476         break;
15477       case STOP_SENDING_FRAME:
15478         frame = QuicFrame(stop_sending_frame);
15479         break;
15480       case NEW_CONNECTION_ID_FRAME:
15481         frame = QuicFrame(&new_connection_id_frame);
15482         break;
15483       case RETIRE_CONNECTION_ID_FRAME:
15484         frame = QuicFrame(&retire_connection_id_frame);
15485         break;
15486       case PATH_RESPONSE_FRAME:
15487         frame = QuicFrame(path_response_frame);
15488         break;
15489       case MESSAGE_FRAME:
15490         frame = QuicFrame(&message_frame);
15491         break;
15492       case CRYPTO_FRAME:
15493         // CRYPTO_FRAME is ack eliciting is covered by other tests.
15494         skipped = true;
15495         break;
15496       case NEW_TOKEN_FRAME:
15497         frame = QuicFrame(&new_token_frame);
15498         break;
15499       case ACK_FREQUENCY_FRAME:
15500         frame = QuicFrame(&ack_frequency_frame);
15501         break;
15502       case RESET_STREAM_AT_FRAME:
15503         frame = QuicFrame(&reset_stream_at_frame);
15504         break;
15505       case NUM_FRAME_TYPES:
15506         skipped = true;
15507         break;
15508     }
15509     if (skipped) {
15510       continue;
15511     }
15512     ASSERT_EQ(frame_type, frame.type);
15513     frames.push_back(frame);
15514     EXPECT_FALSE(connection_.HasPendingAcks());
15515     // Process frame.
15516     ProcessFramesPacketAtLevel(packet_number++, frames,
15517                                ENCRYPTION_FORWARD_SECURE);
15518     if (QuicUtils::IsAckElicitingFrame(frame_type)) {
15519       ASSERT_TRUE(connection_.HasPendingAcks()) << frame;
15520       // Flush ACK.
15521       clock_.AdvanceTime(DefaultDelayedAckTime());
15522       connection_.GetAckAlarm()->Fire();
15523     }
15524     EXPECT_FALSE(connection_.HasPendingAcks());
15525     ASSERT_TRUE(connection_.connected());
15526   }
15527 }
15528 
TEST_P(QuicConnectionTest,ReceivedChloAndAck)15529 TEST_P(QuicConnectionTest, ReceivedChloAndAck) {
15530   if (!version().HasIetfQuicFrames()) {
15531     return;
15532   }
15533   set_perspective(Perspective::IS_SERVER);
15534   QuicFrames frames;
15535   QuicAckFrame ack_frame = InitAckFrame(1);
15536   frames.push_back(MakeCryptoFrame());
15537   frames.push_back(QuicFrame(&ack_frame));
15538 
15539   EXPECT_CALL(visitor_, OnCryptoFrame(_))
15540       .WillOnce(IgnoreResult(InvokeWithoutArgs(
15541           &connection_, &TestConnection::SendCryptoStreamData)));
15542   EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
15543   EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
15544   ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
15545                                    ENCRYPTION_INITIAL);
15546 }
15547 
15548 // Regression test for b/201643321.
TEST_P(QuicConnectionTest,FailedToRetransmitShlo)15549 TEST_P(QuicConnectionTest, FailedToRetransmitShlo) {
15550   if (!version().SupportsAntiAmplificationLimit() ||
15551       GetQuicFlag(quic_enforce_strict_amplification_factor)) {
15552     return;
15553   }
15554   set_perspective(Perspective::IS_SERVER);
15555   EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15556   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
15557   // Received INITIAL 1.
15558   ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15559   EXPECT_TRUE(connection_.HasPendingAcks());
15560 
15561   peer_framer_.SetEncrypter(
15562       ENCRYPTION_ZERO_RTT,
15563       std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
15564 
15565   connection_.SetEncrypter(
15566       ENCRYPTION_HANDSHAKE,
15567       std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
15568   SetDecrypter(ENCRYPTION_HANDSHAKE,
15569                std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
15570   SetDecrypter(ENCRYPTION_ZERO_RTT,
15571                std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
15572   connection_.SetEncrypter(
15573       ENCRYPTION_FORWARD_SECURE,
15574       std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
15575   // Received ENCRYPTION_ZERO_RTT 1.
15576   ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
15577   {
15578     QuicConnection::ScopedPacketFlusher flusher(&connection_);
15579     // Send INITIAL 1.
15580     connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15581     connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15582     // Send HANDSHAKE 2.
15583     EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15584     connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15585     connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
15586     connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15587     // Send half RTT data to exhaust amplification credit.
15588     connection_.SendStreamDataWithString(0, std::string(100 * 1024, 'a'), 0,
15589                                          NO_FIN);
15590   }
15591   // Received INITIAL 2.
15592   ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
15593   ASSERT_TRUE(connection_.HasPendingAcks());
15594   // Verify ACK delay is 1ms.
15595   EXPECT_EQ(clock_.Now() + kAlarmGranularity,
15596             connection_.GetAckAlarm()->deadline());
15597   // ACK is not throttled by amplification limit, and SHLO is bundled. Also
15598   // HANDSHAKE + 1RTT packets get coalesced.
15599   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
15600   // ACK alarm fires.
15601   clock_.AdvanceTime(kAlarmGranularity);
15602   connection_.GetAckAlarm()->Fire();
15603   // Verify 1-RTT packet is coalesced.
15604   EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
15605   // Only the first packet in the coalesced packet has been processed,
15606   // verify SHLO is bundled with INITIAL ACK.
15607   EXPECT_EQ(1u, writer_->ack_frames().size());
15608   EXPECT_EQ(1u, writer_->crypto_frames().size());
15609   // Process the coalesced HANDSHAKE packet.
15610   ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
15611   auto packet = writer_->coalesced_packet()->Clone();
15612   writer_->framer()->ProcessPacket(*packet);
15613   EXPECT_EQ(0u, writer_->ack_frames().size());
15614   EXPECT_EQ(1u, writer_->crypto_frames().size());
15615   // Process the coalesced 1-RTT packet.
15616   ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
15617   packet = writer_->coalesced_packet()->Clone();
15618   writer_->framer()->ProcessPacket(*packet);
15619   EXPECT_EQ(0u, writer_->crypto_frames().size());
15620   EXPECT_EQ(1u, writer_->stream_frames().size());
15621 
15622   // Received INITIAL 3.
15623   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
15624   ProcessCryptoPacketAtLevel(3, ENCRYPTION_INITIAL);
15625   EXPECT_TRUE(connection_.HasPendingAcks());
15626 }
15627 
15628 // Regression test for b/216133388.
TEST_P(QuicConnectionTest,FailedToConsumeCryptoData)15629 TEST_P(QuicConnectionTest, FailedToConsumeCryptoData) {
15630   if (!version().HasIetfQuicFrames()) {
15631     return;
15632   }
15633   set_perspective(Perspective::IS_SERVER);
15634   EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15635   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
15636   // Received INITIAL 1.
15637   ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15638   EXPECT_TRUE(connection_.HasPendingAcks());
15639 
15640   peer_framer_.SetEncrypter(
15641       ENCRYPTION_ZERO_RTT,
15642       std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
15643   connection_.SetEncrypter(
15644       ENCRYPTION_HANDSHAKE,
15645       std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
15646   SetDecrypter(ENCRYPTION_HANDSHAKE,
15647                std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
15648   SetDecrypter(ENCRYPTION_ZERO_RTT,
15649                std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
15650   connection_.SetEncrypter(
15651       ENCRYPTION_FORWARD_SECURE,
15652       std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
15653   // Received ENCRYPTION_ZERO_RTT 1.
15654   ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
15655   {
15656     QuicConnection::ScopedPacketFlusher flusher(&connection_);
15657     // Send INITIAL 1.
15658     connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15659     connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15660     // Send HANDSHAKE 2.
15661     EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15662     connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15663     connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
15664                                          ENCRYPTION_HANDSHAKE);
15665     // Send 1-RTT 3.
15666     connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15667     connection_.SendStreamDataWithString(0, std::string(40, 'a'), 0, NO_FIN);
15668   }
15669   // Received HANDSHAKE Ping, hence discard INITIAL keys.
15670   peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
15671                             std::make_unique<TaggingEncrypter>(0x03));
15672   connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
15673   connection_.NeuterUnencryptedPackets();
15674   ProcessCryptoPacketAtLevel(1, ENCRYPTION_HANDSHAKE);
15675   clock_.AdvanceTime(kAlarmGranularity);
15676   {
15677     QuicConnection::ScopedPacketFlusher flusher(&connection_);
15678     // Sending this 1-RTT data would leave the coalescer only have space to
15679     // accommodate the HANDSHAKE ACK. The crypto data cannot be bundled with the
15680     // ACK.
15681     connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15682     connection_.SendStreamDataWithString(0, std::string(1395, 'a'), 40, NO_FIN);
15683   }
15684   // Verify retransmission alarm is armed.
15685   ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15686   const QuicTime retransmission_time =
15687       connection_.GetRetransmissionAlarm()->deadline();
15688   clock_.AdvanceTime(retransmission_time - clock_.Now());
15689   connection_.GetRetransmissionAlarm()->Fire();
15690 
15691   // Verify the retransmission is a coalesced packet with HANDSHAKE 2 and
15692   // 1-RTT 3.
15693   EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
15694   // Only the first packet in the coalesced packet has been processed.
15695   EXPECT_EQ(1u, writer_->crypto_frames().size());
15696   // Process the coalesced 1-RTT packet.
15697   ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
15698   auto packet = writer_->coalesced_packet()->Clone();
15699   writer_->framer()->ProcessPacket(*packet);
15700   EXPECT_EQ(1u, writer_->stream_frames().size());
15701   ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
15702   // Verify retransmission alarm is still armed.
15703   ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15704 }
15705 
TEST_P(QuicConnectionTest,RTTSampleDoesNotIncludeQueuingDelayWithPostponedAckProcessing)15706 TEST_P(QuicConnectionTest,
15707        RTTSampleDoesNotIncludeQueuingDelayWithPostponedAckProcessing) {
15708   // An endpoint might postpone the processing of ACK when the corresponding
15709   // decryption key is not available. This test makes sure the RTT sample does
15710   // not include the queuing delay.
15711   if (!version().HasIetfQuicFrames()) {
15712     return;
15713   }
15714   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
15715   QuicConfig config;
15716   config.set_max_undecryptable_packets(3);
15717   connection_.SetFromConfig(config);
15718 
15719   // 30ms RTT.
15720   const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
15721   RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
15722   rtt_stats->UpdateRtt(kTestRTT, QuicTime::Delta::Zero(), QuicTime::Zero());
15723 
15724   // Send 0-RTT packet.
15725   connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
15726   connection_.SetEncrypter(
15727       ENCRYPTION_ZERO_RTT,
15728       std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
15729   connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15730   connection_.SendStreamDataWithString(0, std::string(10, 'a'), 0, FIN);
15731 
15732   // Receives 1-RTT ACK for 0-RTT packet after RTT + ack_delay.
15733   clock_.AdvanceTime(
15734       kTestRTT + QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs));
15735   EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15736   peer_framer_.SetEncrypter(
15737       ENCRYPTION_FORWARD_SECURE,
15738       std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
15739   QuicAckFrame ack_frame = InitAckFrame(1);
15740   // Peer reported ACK delay.
15741   ack_frame.ack_delay_time =
15742       QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs);
15743   QuicFrames frames;
15744   frames.push_back(QuicFrame(&ack_frame));
15745   QuicPacketHeader header =
15746       ConstructPacketHeader(30, ENCRYPTION_FORWARD_SECURE);
15747   std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
15748 
15749   char buffer[kMaxOutgoingPacketSize];
15750   size_t encrypted_length = peer_framer_.EncryptPayload(
15751       ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(30), *packet, buffer,
15752       kMaxOutgoingPacketSize);
15753   connection_.ProcessUdpPacket(
15754       kSelfAddress, kPeerAddress,
15755       QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
15756   if (connection_.GetSendAlarm()->IsSet()) {
15757     connection_.GetSendAlarm()->Fire();
15758   }
15759   ASSERT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15760 
15761   // Assume 1-RTT decrypter is available after 10ms.
15762   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
15763   EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
15764   SetDecrypter(
15765       ENCRYPTION_FORWARD_SECURE,
15766       std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
15767   ASSERT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
15768 
15769   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
15770   connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
15771   // Verify RTT sample does not include queueing delay.
15772   EXPECT_EQ(rtt_stats->latest_rtt(), kTestRTT);
15773 }
15774 
15775 // Regression test for b/112480134.
TEST_P(QuicConnectionTest,NoExtraPaddingInReserializedInitial)15776 TEST_P(QuicConnectionTest, NoExtraPaddingInReserializedInitial) {
15777   // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
15778   if (!IsDefaultTestConfiguration() ||
15779       !connection_.version().CanSendCoalescedPackets()) {
15780     return;
15781   }
15782 
15783   set_perspective(Perspective::IS_SERVER);
15784   MockQuicConnectionDebugVisitor debug_visitor;
15785   connection_.set_debug_visitor(&debug_visitor);
15786 
15787   uint64_t debug_visitor_sent_count = 0;
15788   EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _))
15789       .WillRepeatedly([&]() { debug_visitor_sent_count++; });
15790 
15791   EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15792   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
15793 
15794   // Received INITIAL 1.
15795   ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15796 
15797   peer_framer_.SetEncrypter(
15798       ENCRYPTION_ZERO_RTT,
15799       std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
15800   connection_.SetEncrypter(
15801       ENCRYPTION_HANDSHAKE,
15802       std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
15803   SetDecrypter(ENCRYPTION_HANDSHAKE,
15804                std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
15805   SetDecrypter(ENCRYPTION_ZERO_RTT,
15806                std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
15807   connection_.SetEncrypter(
15808       ENCRYPTION_FORWARD_SECURE,
15809       std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
15810 
15811   // Received ENCRYPTION_ZERO_RTT 2.
15812   ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
15813 
15814   {
15815     QuicConnection::ScopedPacketFlusher flusher(&connection_);
15816     // Send INITIAL 1.
15817     connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15818     connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15819     // Send HANDSHAKE 2.
15820     EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15821     connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15822     connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
15823                                          ENCRYPTION_HANDSHAKE);
15824     // Send 1-RTT 3.
15825     connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15826     connection_.SendStreamDataWithString(0, std::string(400, 'b'), 0, NO_FIN);
15827   }
15828 
15829   // Arrange the stream data to be sent in response to ENCRYPTION_INITIAL 3.
15830   const std::string data4(1000, '4');  // Data to send in stream id 4
15831   const std::string data8(3000, '8');  // Data to send in stream id 8
15832   EXPECT_CALL(visitor_, OnCanWrite()).WillOnce([&]() {
15833     connection_.producer()->SaveStreamData(4, data4);
15834     connection_.producer()->SaveStreamData(8, data8);
15835 
15836     notifier_.WriteOrBufferData(4, data4.size(), FIN_AND_PADDING);
15837 
15838     // This should trigger FlushCoalescedPacket.
15839     notifier_.WriteOrBufferData(8, data8.size(), FIN);
15840   });
15841 
15842   QuicByteCount pending_padding_after_serialize_2nd_1rtt_packet = 0;
15843   QuicPacketCount num_1rtt_packets_serialized = 0;
15844   EXPECT_CALL(connection_, OnSerializedPacket(_))
15845       .WillRepeatedly([&](SerializedPacket packet) {
15846         if (packet.encryption_level == ENCRYPTION_FORWARD_SECURE) {
15847           num_1rtt_packets_serialized++;
15848           if (num_1rtt_packets_serialized == 2) {
15849             pending_padding_after_serialize_2nd_1rtt_packet =
15850                 connection_.packet_creator().pending_padding_bytes();
15851           }
15852         }
15853         connection_.QuicConnection::OnSerializedPacket(std::move(packet));
15854       });
15855 
15856   // Server receives INITIAL 3, this will serialzie FS 7 (stream 4, stream 8),
15857   // which will trigger a flush of a coalesced packet consists of INITIAL 4,
15858   // HS 5 and FS 6 (stream 4).
15859 
15860   // Expect no QUIC_BUG.
15861   ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_INITIAL);
15862   EXPECT_EQ(
15863       debug_visitor_sent_count,
15864       connection_.sent_packet_manager().GetLargestSentPacket().ToUint64());
15865 
15866   // The error only happens if after serializing the second 1RTT packet(pkt #7),
15867   // the pending padding bytes is non zero.
15868   EXPECT_GT(pending_padding_after_serialize_2nd_1rtt_packet, 0u);
15869   EXPECT_TRUE(connection_.connected());
15870 }
15871 
TEST_P(QuicConnectionTest,ReportedAckDelayIncludesQueuingDelay)15872 TEST_P(QuicConnectionTest, ReportedAckDelayIncludesQueuingDelay) {
15873   if (!version().HasIetfQuicFrames()) {
15874     return;
15875   }
15876   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
15877   QuicConfig config;
15878   config.set_max_undecryptable_packets(3);
15879   connection_.SetFromConfig(config);
15880 
15881   // Receive 1-RTT ack-eliciting packet while keys are not available.
15882   connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
15883   peer_framer_.SetEncrypter(
15884       ENCRYPTION_FORWARD_SECURE,
15885       std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
15886   QuicFrames frames;
15887   frames.push_back(QuicFrame(QuicPingFrame()));
15888   frames.push_back(QuicFrame(QuicPaddingFrame(100)));
15889   QuicPacketHeader header =
15890       ConstructPacketHeader(30, ENCRYPTION_FORWARD_SECURE);
15891   std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
15892 
15893   char buffer[kMaxOutgoingPacketSize];
15894   size_t encrypted_length = peer_framer_.EncryptPayload(
15895       ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(30), *packet, buffer,
15896       kMaxOutgoingPacketSize);
15897   EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15898   const QuicTime packet_receipt_time = clock_.Now();
15899   connection_.ProcessUdpPacket(
15900       kSelfAddress, kPeerAddress,
15901       QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
15902   if (connection_.GetSendAlarm()->IsSet()) {
15903     connection_.GetSendAlarm()->Fire();
15904   }
15905   ASSERT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15906   // 1-RTT keys become available after 10ms.
15907   const QuicTime::Delta kQueuingDelay = QuicTime::Delta::FromMilliseconds(10);
15908   clock_.AdvanceTime(kQueuingDelay);
15909   EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
15910   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15911   SetDecrypter(
15912       ENCRYPTION_FORWARD_SECURE,
15913       std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
15914   ASSERT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
15915 
15916   connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
15917   ASSERT_TRUE(connection_.HasPendingAcks());
15918   EXPECT_EQ(packet_receipt_time + DefaultDelayedAckTime(),
15919             connection_.GetAckAlarm()->deadline());
15920   clock_.AdvanceTime(packet_receipt_time + DefaultDelayedAckTime() -
15921                      clock_.Now());
15922   // Fire ACK alarm.
15923   connection_.GetAckAlarm()->Fire();
15924   ASSERT_EQ(1u, writer_->ack_frames().size());
15925   // Verify ACK delay time does not include queuing delay.
15926   EXPECT_EQ(DefaultDelayedAckTime(), writer_->ack_frames()[0].ack_delay_time);
15927 }
15928 
TEST_P(QuicConnectionTest,CoalesceOneRTTPacketWithInitialAndHandshakePackets)15929 TEST_P(QuicConnectionTest, CoalesceOneRTTPacketWithInitialAndHandshakePackets) {
15930   if (!version().HasIetfQuicFrames()) {
15931     return;
15932   }
15933   set_perspective(Perspective::IS_SERVER);
15934   EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15935   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
15936 
15937   // Received INITIAL 1.
15938   ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15939 
15940   peer_framer_.SetEncrypter(
15941       ENCRYPTION_ZERO_RTT,
15942       std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
15943 
15944   connection_.SetEncrypter(
15945       ENCRYPTION_HANDSHAKE,
15946       std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
15947   SetDecrypter(ENCRYPTION_HANDSHAKE,
15948                std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
15949   SetDecrypter(ENCRYPTION_ZERO_RTT,
15950                std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
15951   connection_.SetEncrypter(
15952       ENCRYPTION_FORWARD_SECURE,
15953       std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
15954 
15955   // Received ENCRYPTION_ZERO_RTT 2.
15956   ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
15957 
15958   {
15959     QuicConnection::ScopedPacketFlusher flusher(&connection_);
15960     // Send INITIAL 1.
15961     connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15962     connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15963     // Send HANDSHAKE 2.
15964     EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15965     connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15966     connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
15967                                          ENCRYPTION_HANDSHAKE);
15968     // Send 1-RTT data.
15969     connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15970     connection_.SendStreamDataWithString(0, std::string(2000, 'b'), 0, FIN);
15971   }
15972   // Verify coalesced packet [INITIAL 1 + HANDSHAKE 2 + part of 1-RTT data] +
15973   // rest of 1-RTT data get sent.
15974   EXPECT_EQ(2u, writer_->packets_write_attempts());
15975 
15976   // Received ENCRYPTION_INITIAL 3.
15977   ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_INITIAL);
15978 
15979   // Verify a coalesced packet gets sent.
15980   EXPECT_EQ(3u, writer_->packets_write_attempts());
15981 
15982   // Only the first INITIAL packet has been processed yet.
15983   EXPECT_EQ(1u, writer_->ack_frames().size());
15984   EXPECT_EQ(1u, writer_->crypto_frames().size());
15985 
15986   // Process HANDSHAKE packet.
15987   ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
15988   auto packet = writer_->coalesced_packet()->Clone();
15989   writer_->framer()->ProcessPacket(*packet);
15990   EXPECT_EQ(1u, writer_->crypto_frames().size());
15991   // Process 1-RTT packet.
15992   ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
15993   packet = writer_->coalesced_packet()->Clone();
15994   writer_->framer()->ProcessPacket(*packet);
15995   EXPECT_EQ(1u, writer_->stream_frames().size());
15996 }
15997 
15998 // Regression test for b/180103273
TEST_P(QuicConnectionTest,SendMultipleConnectionCloses)15999 TEST_P(QuicConnectionTest, SendMultipleConnectionCloses) {
16000   if (!version().HasIetfQuicFrames() ||
16001       !GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
16002     return;
16003   }
16004   set_perspective(Perspective::IS_SERVER);
16005   // Finish handshake.
16006   QuicConnectionPeer::SetAddressValidated(&connection_);
16007   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16008   notifier_.NeuterUnencryptedData();
16009   connection_.NeuterUnencryptedPackets();
16010   connection_.OnHandshakeComplete();
16011   connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
16012   connection_.RemoveEncrypter(ENCRYPTION_HANDSHAKE);
16013   EXPECT_CALL(visitor_, GetHandshakeState())
16014       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16015 
16016   SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
16017   ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
16018   // Verify that BeforeConnectionCloseSent() gets called twice,
16019   // while OnConnectionClosed() is called only once.
16020   EXPECT_CALL(visitor_, BeforeConnectionCloseSent()).Times(2);
16021   EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
16022   // Send connection close w/o closing connection.
16023   QuicConnectionPeer::SendConnectionClosePacket(
16024       &connection_, INTERNAL_ERROR, QUIC_INTERNAL_ERROR, "internal error");
16025   // Fire blackhole detection alarm.  This will invoke
16026   // SendConnectionClosePacket() a second time.
16027   connection_.GetBlackholeDetectorAlarm()->Fire();
16028 }
16029 
16030 // Regression test for b/157895910.
TEST_P(QuicConnectionTest,EarliestSentTimeNotInitializedWhenPtoFires)16031 TEST_P(QuicConnectionTest, EarliestSentTimeNotInitializedWhenPtoFires) {
16032   if (!connection_.SupportsMultiplePacketNumberSpaces()) {
16033     return;
16034   }
16035   set_perspective(Perspective::IS_SERVER);
16036   EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
16037   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
16038 
16039   // Received INITIAL 1.
16040   ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
16041   connection_.SetEncrypter(
16042       ENCRYPTION_HANDSHAKE,
16043       std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
16044   SetDecrypter(ENCRYPTION_HANDSHAKE,
16045                std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
16046   connection_.SetEncrypter(
16047       ENCRYPTION_FORWARD_SECURE,
16048       std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
16049   {
16050     QuicConnection::ScopedPacketFlusher flusher(&connection_);
16051     // Send INITIAL 1.
16052     connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
16053     connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
16054     // Send HANDSHAKE 2.
16055     EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
16056     connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
16057     connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
16058                                          ENCRYPTION_HANDSHAKE);
16059     // Send half RTT data.
16060     connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16061     connection_.SendStreamDataWithString(0, std::string(2000, 'b'), 0, FIN);
16062   }
16063 
16064   // Received ACKs for both INITIAL and HANDSHAKE packets.
16065   EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
16066       .Times(AnyNumber());
16067   QuicFrames frames1;
16068   QuicAckFrame ack_frame1 = InitAckFrame(1);
16069   frames1.push_back(QuicFrame(&ack_frame1));
16070 
16071   QuicFrames frames2;
16072   QuicAckFrame ack_frame2 =
16073       InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
16074   frames2.push_back(QuicFrame(&ack_frame2));
16075   ProcessCoalescedPacket(
16076       {{2, frames1, ENCRYPTION_INITIAL}, {3, frames2, ENCRYPTION_HANDSHAKE}});
16077   // Verify PTO is not armed given the only outstanding data is half RTT data.
16078   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
16079 }
16080 
TEST_P(QuicConnectionTest,CalculateNetworkBlackholeDelay)16081 TEST_P(QuicConnectionTest, CalculateNetworkBlackholeDelay) {
16082   if (!IsDefaultTestConfiguration()) {
16083     return;
16084   }
16085 
16086   const QuicTime::Delta kOneSec = QuicTime::Delta::FromSeconds(1);
16087   const QuicTime::Delta kTwoSec = QuicTime::Delta::FromSeconds(2);
16088   const QuicTime::Delta kFourSec = QuicTime::Delta::FromSeconds(4);
16089 
16090   // Normal case: blackhole_delay longer than path_degrading_delay +
16091   // 2*pto_delay.
16092   EXPECT_EQ(QuicConnection::CalculateNetworkBlackholeDelay(kFourSec, kOneSec,
16093                                                            kOneSec),
16094             kFourSec);
16095 
16096   EXPECT_EQ(QuicConnection::CalculateNetworkBlackholeDelay(kFourSec, kOneSec,
16097                                                            kTwoSec),
16098             QuicTime::Delta::FromSeconds(5));
16099 }
16100 
TEST_P(QuicConnectionTest,FixBytesAccountingForBufferedCoalescedPackets)16101 TEST_P(QuicConnectionTest, FixBytesAccountingForBufferedCoalescedPackets) {
16102   if (!connection_.version().CanSendCoalescedPackets()) {
16103     return;
16104   }
16105   // Write is blocked.
16106   EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber());
16107   writer_->SetWriteBlocked();
16108   connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
16109   QuicConnectionPeer::SendPing(&connection_);
16110   const QuicConnectionStats& stats = connection_.GetStats();
16111   // Verify padding is accounted.
16112   EXPECT_EQ(stats.bytes_sent, connection_.max_packet_length());
16113 }
16114 
TEST_P(QuicConnectionTest,StrictAntiAmplificationLimit)16115 TEST_P(QuicConnectionTest, StrictAntiAmplificationLimit) {
16116   if (!connection_.version().SupportsAntiAmplificationLimit()) {
16117     return;
16118   }
16119   EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
16120   set_perspective(Perspective::IS_SERVER);
16121   connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
16122   // Verify no data can be sent at the beginning because bytes received is 0.
16123   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
16124   connection_.SendCryptoDataWithString("foo", 0);
16125   EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
16126   EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
16127   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
16128 
16129   const size_t anti_amplification_factor =
16130       GetQuicFlag(quic_anti_amplification_factor);
16131   // Receives packet 1.
16132   EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
16133   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
16134       .Times(anti_amplification_factor);
16135   ForceWillingAndAbleToWriteOnceForDeferSending();
16136   ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
16137   connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
16138                            std::make_unique<TaggingEncrypter>(0x02));
16139   connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
16140                            std::make_unique<TaggingEncrypter>(0x03));
16141 
16142   for (size_t i = 1; i < anti_amplification_factor - 1; ++i) {
16143     connection_.SendCryptoDataWithString("foo", i * 3);
16144   }
16145   // Send an addtion packet with max_packet_size - 1.
16146   connection_.SetMaxPacketLength(connection_.max_packet_length() - 1);
16147   connection_.SendCryptoDataWithString("bar",
16148                                        (anti_amplification_factor - 1) * 3);
16149   EXPECT_LT(writer_->total_bytes_written(),
16150             anti_amplification_factor *
16151                 QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
16152   if (GetQuicFlag(quic_enforce_strict_amplification_factor)) {
16153     // 3 connection closes which will be buffered.
16154     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
16155     // Verify retransmission alarm is not set.
16156     EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
16157   } else {
16158     // Crypto + 3 connection closes.
16159     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
16160     EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
16161   }
16162   // Try to send another packet with max_packet_size.
16163   connection_.SetMaxPacketLength(connection_.max_packet_length() + 1);
16164   connection_.SendCryptoDataWithString("bar", anti_amplification_factor * 3);
16165   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
16166   // Close connection.
16167   EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
16168   EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
16169   connection_.CloseConnection(
16170       QUIC_INTERNAL_ERROR, "error",
16171       ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
16172   EXPECT_EQ(0u, connection_.NumQueuedPackets());
16173   if (GetQuicFlag(quic_enforce_strict_amplification_factor)) {
16174     EXPECT_LT(writer_->total_bytes_written(),
16175               anti_amplification_factor *
16176                   QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
16177   } else {
16178     EXPECT_LT(writer_->total_bytes_written(),
16179               (anti_amplification_factor + 2) *
16180                   QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
16181     EXPECT_GT(writer_->total_bytes_written(),
16182               (anti_amplification_factor + 1) *
16183                   QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
16184   }
16185 }
16186 
TEST_P(QuicConnectionTest,OriginalConnectionId)16187 TEST_P(QuicConnectionTest, OriginalConnectionId) {
16188   set_perspective(Perspective::IS_SERVER);
16189   EXPECT_FALSE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
16190   EXPECT_EQ(connection_.GetOriginalDestinationConnectionId(),
16191             connection_.connection_id());
16192   QuicConnectionId original({0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08});
16193   connection_.SetOriginalDestinationConnectionId(original);
16194   EXPECT_EQ(original, connection_.GetOriginalDestinationConnectionId());
16195   // Send a 1-RTT packet to start the DiscardZeroRttDecryptionKeys timer.
16196   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
16197   ProcessDataPacketAtLevel(1, false, ENCRYPTION_FORWARD_SECURE);
16198   if (connection_.version().UsesTls()) {
16199     EXPECT_TRUE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
16200     EXPECT_CALL(visitor_, OnServerConnectionIdRetired(original));
16201     connection_.GetDiscardZeroRttDecryptionKeysAlarm()->Fire();
16202     EXPECT_EQ(connection_.GetOriginalDestinationConnectionId(),
16203               connection_.connection_id());
16204   } else {
16205     EXPECT_EQ(connection_.GetOriginalDestinationConnectionId(), original);
16206   }
16207 }
16208 
ACTION_P2(InstallKeys,conn,level)16209 ACTION_P2(InstallKeys, conn, level) {
16210   uint8_t crypto_input = (level == ENCRYPTION_FORWARD_SECURE) ? 0x03 : 0x02;
16211   conn->SetEncrypter(level, std::make_unique<TaggingEncrypter>(crypto_input));
16212   conn->InstallDecrypter(
16213       level, std::make_unique<StrictTaggingDecrypter>(crypto_input));
16214   conn->SetDefaultEncryptionLevel(level);
16215 }
16216 
TEST_P(QuicConnectionTest,ServerConnectionIdChangeWithLateInitial)16217 TEST_P(QuicConnectionTest, ServerConnectionIdChangeWithLateInitial) {
16218   if (!connection_.version().HasIetfQuicFrames()) {
16219     return;
16220   }
16221   // Call SetFromConfig so that the undecrypted packet buffer size is
16222   // initialized above zero.
16223   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(1);
16224   QuicConfig config;
16225   connection_.SetFromConfig(config);
16226   connection_.RemoveEncrypter(ENCRYPTION_FORWARD_SECURE);
16227   connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
16228 
16229   // Send Client Initial.
16230   connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
16231   connection_.SendCryptoStreamData();
16232 
16233   EXPECT_EQ(1u, writer_->packets_write_attempts());
16234   // Server Handshake packet with new connection ID is buffered.
16235   QuicConnectionId old_id = connection_id_;
16236   connection_id_ = TestConnectionId(2);
16237   peer_creator_.SetEncrypter(ENCRYPTION_HANDSHAKE,
16238                              std::make_unique<TaggingEncrypter>(0x02));
16239   ProcessCryptoPacketAtLevel(0, ENCRYPTION_HANDSHAKE);
16240   EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 1u);
16241   EXPECT_EQ(connection_.connection_id(), old_id);
16242 
16243   // Server 1-RTT Packet is buffered.
16244   peer_creator_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
16245                              std::make_unique<TaggingEncrypter>(0x03));
16246   ProcessDataPacket(0);
16247   EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 2u);
16248 
16249   // Pretend the server Initial packet will yield the Handshake keys.
16250   EXPECT_CALL(visitor_, OnCryptoFrame(_))
16251       .Times(2)
16252       .WillOnce(InstallKeys(&connection_, ENCRYPTION_HANDSHAKE))
16253       .WillOnce(InstallKeys(&connection_, ENCRYPTION_FORWARD_SECURE));
16254   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
16255   ProcessCryptoPacketAtLevel(0, ENCRYPTION_INITIAL);
16256   // Two packets processed, connection ID changed.
16257   EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 0u);
16258   EXPECT_EQ(connection_.connection_id(), connection_id_);
16259 }
16260 
TEST_P(QuicConnectionTest,ServerConnectionIdChangeTwiceWithLateInitial)16261 TEST_P(QuicConnectionTest, ServerConnectionIdChangeTwiceWithLateInitial) {
16262   if (!connection_.version().HasIetfQuicFrames()) {
16263     return;
16264   }
16265   // Call SetFromConfig so that the undecrypted packet buffer size is
16266   // initialized above zero.
16267   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(1);
16268   QuicConfig config;
16269   connection_.SetFromConfig(config);
16270 
16271   // Send Client Initial.
16272   connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
16273   connection_.SendCryptoStreamData();
16274 
16275   EXPECT_EQ(1u, writer_->packets_write_attempts());
16276   // Server Handshake Packet Arrives with new connection ID.
16277   QuicConnectionId old_id = connection_id_;
16278   connection_id_ = TestConnectionId(2);
16279   peer_creator_.SetEncrypter(ENCRYPTION_HANDSHAKE,
16280                              std::make_unique<TaggingEncrypter>(0x02));
16281   ProcessCryptoPacketAtLevel(0, ENCRYPTION_HANDSHAKE);
16282   // Packet is buffered.
16283   EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 1u);
16284   EXPECT_EQ(connection_.connection_id(), old_id);
16285 
16286   // Pretend the server Initial packet will yield the Handshake keys.
16287   EXPECT_CALL(visitor_, OnCryptoFrame(_))
16288       .WillOnce(InstallKeys(&connection_, ENCRYPTION_HANDSHAKE));
16289   connection_id_ = TestConnectionId(1);
16290   ProcessCryptoPacketAtLevel(0, ENCRYPTION_INITIAL);
16291   // Handshake packet discarded because there's a different connection ID.
16292   EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 0u);
16293   EXPECT_EQ(connection_.connection_id(), connection_id_);
16294 }
16295 
TEST_P(QuicConnectionTest,ClientValidatedServerPreferredAddress)16296 TEST_P(QuicConnectionTest, ClientValidatedServerPreferredAddress) {
16297   // Test the scenario where the client validates server preferred address by
16298   // receiving PATH_RESPONSE from server preferred address.
16299   if (!connection_.version().HasIetfQuicFrames()) {
16300     return;
16301   }
16302   QuicConfig config;
16303   ServerPreferredAddressInit(config);
16304   const QuicSocketAddress kNewSelfAddress =
16305       QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16306   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
16307   const StatelessResetToken kNewStatelessResetToken =
16308       QuicUtils::GenerateStatelessResetToken(TestConnectionId(17));
16309   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16310   EXPECT_CALL(visitor_, GetHandshakeState())
16311       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16312   // Kick off path validation of server preferred address on handshake
16313   // confirmed.
16314   EXPECT_CALL(visitor_,
16315               OnServerPreferredAddressAvailable(kServerPreferredAddress))
16316       .WillOnce(Invoke([&]() {
16317         connection_.ValidatePath(
16318             std::make_unique<TestQuicPathValidationContext>(
16319                 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16320             std::make_unique<ServerPreferredAddressTestResultDelegate>(
16321                 &connection_),
16322             PathValidationReason::kReasonUnknown);
16323       }));
16324   connection_.OnHandshakeComplete();
16325   EXPECT_TRUE(connection_.HasPendingPathValidation());
16326   EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
16327       &connection_, kNewSelfAddress, kServerPreferredAddress));
16328   EXPECT_EQ(TestConnectionId(17),
16329             new_writer.last_packet_header().destination_connection_id);
16330   EXPECT_EQ(kServerPreferredAddress, new_writer.last_write_peer_address());
16331 
16332   ASSERT_FALSE(new_writer.path_challenge_frames().empty());
16333   QuicPathFrameBuffer payload =
16334       new_writer.path_challenge_frames().front().data_buffer;
16335   // Send data packet while path validation is pending.
16336   connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
16337   ASSERT_FALSE(writer_->stream_frames().empty());
16338   // While path validation is pending, packet is sent on default path.
16339   EXPECT_EQ(TestConnectionId(),
16340             writer_->last_packet_header().destination_connection_id);
16341   EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
16342   EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestStatelessResetToken));
16343   EXPECT_FALSE(connection_.IsValidStatelessResetToken(kNewStatelessResetToken));
16344 
16345   // Receive path response from server preferred address.
16346   QuicFrames frames;
16347   frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
16348   // Verify send_algorithm gets reset after migration (new sent packet is not
16349   // updated to exsting send_algorithm_).
16350   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
16351   ProcessFramesPacketWithAddresses(frames, kNewSelfAddress,
16352                                    kServerPreferredAddress,
16353                                    ENCRYPTION_FORWARD_SECURE);
16354   ASSERT_FALSE(connection_.HasPendingPathValidation());
16355   EXPECT_TRUE(QuicConnectionPeer::IsDefaultPath(&connection_, kNewSelfAddress,
16356                                                 kServerPreferredAddress));
16357   ASSERT_FALSE(new_writer.stream_frames().empty());
16358   // Verify stream data is retransmitted on new path.
16359   EXPECT_EQ(TestConnectionId(17),
16360             new_writer.last_packet_header().destination_connection_id);
16361   EXPECT_EQ(kServerPreferredAddress, new_writer.last_write_peer_address());
16362   // Verify stateless reset token gets changed.
16363   EXPECT_FALSE(
16364       connection_.IsValidStatelessResetToken(kTestStatelessResetToken));
16365   EXPECT_TRUE(connection_.IsValidStatelessResetToken(kNewStatelessResetToken));
16366 
16367   auto* retire_peer_issued_cid_alarm =
16368       connection_.GetRetirePeerIssuedConnectionIdAlarm();
16369   ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
16370   // Verify client retires connection ID with sequence number 0.
16371   EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
16372   retire_peer_issued_cid_alarm->Fire();
16373   EXPECT_TRUE(connection_.GetStats().server_preferred_address_validated);
16374   EXPECT_FALSE(
16375       connection_.GetStats().failed_to_validate_server_preferred_address);
16376 }
16377 
TEST_P(QuicConnectionTest,ClientValidatedServerPreferredAddress2)16378 TEST_P(QuicConnectionTest, ClientValidatedServerPreferredAddress2) {
16379   // Test the scenario where the client validates server preferred address by
16380   // receiving PATH_RESPONSE from original server address.
16381   if (!connection_.version().HasIetfQuicFrames()) {
16382     return;
16383   }
16384   QuicConfig config;
16385   ServerPreferredAddressInit(config);
16386   const QuicSocketAddress kNewSelfAddress =
16387       QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16388   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
16389   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16390   EXPECT_CALL(visitor_, GetHandshakeState())
16391       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16392   // Kick off path validation of server preferred address on handshake
16393   // confirmed.
16394   EXPECT_CALL(visitor_,
16395               OnServerPreferredAddressAvailable(kServerPreferredAddress))
16396       .WillOnce(Invoke([&]() {
16397         connection_.ValidatePath(
16398             std::make_unique<TestQuicPathValidationContext>(
16399                 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16400             std::make_unique<ServerPreferredAddressTestResultDelegate>(
16401                 &connection_),
16402             PathValidationReason::kReasonUnknown);
16403       }));
16404   connection_.OnHandshakeComplete();
16405   EXPECT_TRUE(connection_.HasPendingPathValidation());
16406   ASSERT_FALSE(new_writer.path_challenge_frames().empty());
16407   QuicPathFrameBuffer payload =
16408       new_writer.path_challenge_frames().front().data_buffer;
16409   // Send data packet while path validation is pending.
16410   connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
16411   ASSERT_FALSE(writer_->stream_frames().empty());
16412   EXPECT_EQ(TestConnectionId(),
16413             writer_->last_packet_header().destination_connection_id);
16414   EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
16415 
16416   // Receive path response from original server address.
16417   QuicFrames frames;
16418   frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
16419   ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
16420                                    ENCRYPTION_FORWARD_SECURE);
16421   ASSERT_FALSE(connection_.HasPendingPathValidation());
16422   ASSERT_FALSE(new_writer.stream_frames().empty());
16423   // Verify stream data is retransmitted on new path.
16424   EXPECT_EQ(TestConnectionId(17),
16425             new_writer.last_packet_header().destination_connection_id);
16426   EXPECT_EQ(kServerPreferredAddress, new_writer.last_write_peer_address());
16427 
16428   auto* retire_peer_issued_cid_alarm =
16429       connection_.GetRetirePeerIssuedConnectionIdAlarm();
16430   ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
16431   // Verify client retires connection ID with sequence number 0.
16432   EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
16433   retire_peer_issued_cid_alarm->Fire();
16434 
16435   // Verify another packet from original server address gets processed.
16436   EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
16437   frames.clear();
16438   frames.push_back(QuicFrame(frame1_));
16439   ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
16440                                    ENCRYPTION_FORWARD_SECURE);
16441   EXPECT_TRUE(connection_.GetStats().server_preferred_address_validated);
16442   EXPECT_FALSE(
16443       connection_.GetStats().failed_to_validate_server_preferred_address);
16444 }
16445 
TEST_P(QuicConnectionTest,ClientFailedToValidateServerPreferredAddress)16446 TEST_P(QuicConnectionTest, ClientFailedToValidateServerPreferredAddress) {
16447   // Test the scenario where the client fails to validate server preferred
16448   // address.
16449   if (!connection_.version().HasIetfQuicFrames()) {
16450     return;
16451   }
16452   QuicConfig config;
16453   ServerPreferredAddressInit(config);
16454   const QuicSocketAddress kNewSelfAddress =
16455       QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16456   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
16457   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16458   EXPECT_CALL(visitor_, GetHandshakeState())
16459       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16460   // Kick off path validation of server preferred address on handshake
16461   // confirmed.
16462   EXPECT_CALL(visitor_,
16463               OnServerPreferredAddressAvailable(kServerPreferredAddress))
16464       .WillOnce(Invoke([&]() {
16465         connection_.ValidatePath(
16466             std::make_unique<TestQuicPathValidationContext>(
16467                 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16468             std::make_unique<ServerPreferredAddressTestResultDelegate>(
16469                 &connection_),
16470             PathValidationReason::kReasonUnknown);
16471       }));
16472   connection_.OnHandshakeComplete();
16473   EXPECT_TRUE(connection_.IsValidatingServerPreferredAddress());
16474   EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
16475       &connection_, kNewSelfAddress, kServerPreferredAddress));
16476   ASSERT_FALSE(new_writer.path_challenge_frames().empty());
16477 
16478   // Receive mismatched path challenge from original server address.
16479   QuicFrames frames;
16480   frames.push_back(
16481       QuicFrame(QuicPathResponseFrame(99, {0, 1, 2, 3, 4, 5, 6, 7})));
16482   ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
16483                                    ENCRYPTION_FORWARD_SECURE);
16484   ASSERT_TRUE(connection_.HasPendingPathValidation());
16485   EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
16486       &connection_, kNewSelfAddress, kServerPreferredAddress));
16487 
16488   // Simluate path validation times out.
16489   for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes + 1; ++i) {
16490     clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
16491     static_cast<TestAlarmFactory::TestAlarm*>(
16492         QuicPathValidatorPeer::retry_timer(
16493             QuicConnectionPeer::path_validator(&connection_)))
16494         ->Fire();
16495   }
16496   EXPECT_FALSE(connection_.HasPendingPathValidation());
16497   EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
16498       &connection_, kNewSelfAddress, kServerPreferredAddress));
16499   // Verify stream data is sent on the default path.
16500   connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
16501   ASSERT_FALSE(writer_->stream_frames().empty());
16502   EXPECT_EQ(TestConnectionId(),
16503             writer_->last_packet_header().destination_connection_id);
16504   EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
16505 
16506   auto* retire_peer_issued_cid_alarm =
16507       connection_.GetRetirePeerIssuedConnectionIdAlarm();
16508   ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
16509   // Verify client retires connection ID with sequence number 1.
16510   EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/1u));
16511   retire_peer_issued_cid_alarm->Fire();
16512   EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestStatelessResetToken));
16513   EXPECT_FALSE(connection_.GetStats().server_preferred_address_validated);
16514   EXPECT_TRUE(
16515       connection_.GetStats().failed_to_validate_server_preferred_address);
16516 }
16517 
TEST_P(QuicConnectionTest,OptimizedServerPreferredAddress)16518 TEST_P(QuicConnectionTest, OptimizedServerPreferredAddress) {
16519   if (!connection_.version().HasIetfQuicFrames()) {
16520     return;
16521   }
16522   const QuicSocketAddress kNewSelfAddress =
16523       QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16524   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
16525   EXPECT_CALL(visitor_,
16526               OnServerPreferredAddressAvailable(kServerPreferredAddress))
16527       .WillOnce(Invoke([&]() {
16528         connection_.ValidatePath(
16529             std::make_unique<TestQuicPathValidationContext>(
16530                 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16531             std::make_unique<ServerPreferredAddressTestResultDelegate>(
16532                 &connection_),
16533             PathValidationReason::kReasonUnknown);
16534       }));
16535   QuicConfig config;
16536   config.SetClientConnectionOptions(QuicTagVector{kSPA2});
16537   ServerPreferredAddressInit(config);
16538   EXPECT_TRUE(connection_.HasPendingPathValidation());
16539   ASSERT_FALSE(new_writer.path_challenge_frames().empty());
16540 
16541   // Send data packet while path validation is pending.
16542   connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
16543   // Verify the packet is sent on both paths.
16544   EXPECT_FALSE(writer_->stream_frames().empty());
16545   EXPECT_FALSE(new_writer.stream_frames().empty());
16546 
16547   // Verify packet duplication stops on handshake confirmed.
16548   EXPECT_CALL(visitor_, GetHandshakeState())
16549       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16550   connection_.OnHandshakeComplete();
16551   SendPing();
16552   EXPECT_FALSE(writer_->ping_frames().empty());
16553   EXPECT_TRUE(new_writer.ping_frames().empty());
16554 }
16555 
TEST_P(QuicConnectionTest,OptimizedServerPreferredAddress2)16556 TEST_P(QuicConnectionTest, OptimizedServerPreferredAddress2) {
16557   if (!connection_.version().HasIetfQuicFrames()) {
16558     return;
16559   }
16560   const QuicSocketAddress kNewSelfAddress =
16561       QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16562   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
16563   EXPECT_CALL(visitor_,
16564               OnServerPreferredAddressAvailable(kServerPreferredAddress))
16565       .WillOnce(Invoke([&]() {
16566         connection_.ValidatePath(
16567             std::make_unique<TestQuicPathValidationContext>(
16568                 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16569             std::make_unique<ServerPreferredAddressTestResultDelegate>(
16570                 &connection_),
16571             PathValidationReason::kReasonUnknown);
16572       }));
16573   QuicConfig config;
16574   config.SetClientConnectionOptions(QuicTagVector{kSPA2});
16575   ServerPreferredAddressInit(config);
16576   EXPECT_TRUE(connection_.HasPendingPathValidation());
16577   ASSERT_FALSE(new_writer.path_challenge_frames().empty());
16578 
16579   // Send data packet while path validation is pending.
16580   connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
16581   // Verify the packet is sent on both paths.
16582   EXPECT_FALSE(writer_->stream_frames().empty());
16583   EXPECT_FALSE(new_writer.stream_frames().empty());
16584 
16585   // Simluate path validation times out.
16586   for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes + 1; ++i) {
16587     clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
16588     static_cast<TestAlarmFactory::TestAlarm*>(
16589         QuicPathValidatorPeer::retry_timer(
16590             QuicConnectionPeer::path_validator(&connection_)))
16591         ->Fire();
16592   }
16593   EXPECT_FALSE(connection_.HasPendingPathValidation());
16594   // Verify packet duplication stops if there is no pending validation.
16595   SendPing();
16596   EXPECT_FALSE(writer_->ping_frames().empty());
16597   EXPECT_TRUE(new_writer.ping_frames().empty());
16598 }
16599 
TEST_P(QuicConnectionTest,MaxDuplicatedPacketsSentToServerPreferredAddress)16600 TEST_P(QuicConnectionTest, MaxDuplicatedPacketsSentToServerPreferredAddress) {
16601   if (!connection_.version().HasIetfQuicFrames()) {
16602     return;
16603   }
16604   const QuicSocketAddress kNewSelfAddress =
16605       QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16606   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
16607   EXPECT_CALL(visitor_,
16608               OnServerPreferredAddressAvailable(kServerPreferredAddress))
16609       .WillOnce(Invoke([&]() {
16610         connection_.ValidatePath(
16611             std::make_unique<TestQuicPathValidationContext>(
16612                 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16613             std::make_unique<ServerPreferredAddressTestResultDelegate>(
16614                 &connection_),
16615             PathValidationReason::kReasonUnknown);
16616       }));
16617   QuicConfig config;
16618   config.SetClientConnectionOptions(QuicTagVector{kSPA2});
16619   ServerPreferredAddressInit(config);
16620   EXPECT_TRUE(connection_.HasPendingPathValidation());
16621   ASSERT_FALSE(new_writer.path_challenge_frames().empty());
16622 
16623   // Send data packet while path validation is pending.
16624   size_t write_limit = writer_->packets_write_attempts();
16625   size_t new_write_limit = new_writer.packets_write_attempts();
16626   for (size_t i = 0; i < kMaxDuplicatedPacketsSentToServerPreferredAddress;
16627        ++i) {
16628     connection_.SendStreamDataWithString(3, "foo", i * 3, NO_FIN);
16629     // Verify the packet is sent on both paths.
16630     ASSERT_EQ(write_limit + 1, writer_->packets_write_attempts());
16631     ASSERT_EQ(new_write_limit + 1, new_writer.packets_write_attempts());
16632     ++write_limit;
16633     ++new_write_limit;
16634     EXPECT_FALSE(writer_->stream_frames().empty());
16635     EXPECT_FALSE(new_writer.stream_frames().empty());
16636   }
16637 
16638   // Verify packet duplication stops if duplication limit is hit.
16639   SendPing();
16640   ASSERT_EQ(write_limit + 1, writer_->packets_write_attempts());
16641   ASSERT_EQ(new_write_limit, new_writer.packets_write_attempts());
16642   EXPECT_FALSE(writer_->ping_frames().empty());
16643   EXPECT_TRUE(new_writer.ping_frames().empty());
16644 }
16645 
TEST_P(QuicConnectionTest,MultiPortCreationAfterServerMigration)16646 TEST_P(QuicConnectionTest, MultiPortCreationAfterServerMigration) {
16647   if (!GetParam().version.HasIetfQuicFrames()) {
16648     return;
16649   }
16650   QuicConfig config;
16651   config.SetClientConnectionOptions(QuicTagVector{kMPQC});
16652   ServerPreferredAddressInit(config);
16653   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16654   QuicConnectionId cid_for_preferred_address = TestConnectionId(17);
16655   const QuicSocketAddress kNewSelfAddress =
16656       QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16657   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
16658   EXPECT_CALL(visitor_,
16659               OnServerPreferredAddressAvailable(kServerPreferredAddress))
16660       .WillOnce(Invoke([&]() {
16661         connection_.ValidatePath(
16662             std::make_unique<TestQuicPathValidationContext>(
16663                 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16664             std::make_unique<ServerPreferredAddressTestResultDelegate>(
16665                 &connection_),
16666             PathValidationReason::kReasonUnknown);
16667       }));
16668   // The connection should start probing the preferred address after handshake
16669   // confirmed.
16670   QuicPathFrameBuffer payload;
16671   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
16672       .Times(testing::AtLeast(1u))
16673       .WillOnce(Invoke([&]() {
16674         EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
16675         payload = new_writer.path_challenge_frames().front().data_buffer;
16676         EXPECT_EQ(kServerPreferredAddress,
16677                   new_writer.last_write_peer_address());
16678       }));
16679   EXPECT_CALL(visitor_, GetHandshakeState())
16680       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16681   connection_.OnHandshakeComplete();
16682   EXPECT_TRUE(connection_.IsValidatingServerPreferredAddress());
16683 
16684   // Receiving PATH_RESPONSE should cause the connection to migrate to the
16685   // preferred address.
16686   QuicFrames frames;
16687   frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
16688   ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
16689                                    ENCRYPTION_FORWARD_SECURE);
16690   EXPECT_FALSE(connection_.IsValidatingServerPreferredAddress());
16691   EXPECT_EQ(kServerPreferredAddress, connection_.effective_peer_address());
16692   EXPECT_EQ(kNewSelfAddress, connection_.self_address());
16693   EXPECT_EQ(connection_.connection_id(), cid_for_preferred_address);
16694 
16695   // As the default path changed, the server issued CID 1 should be retired.
16696   auto* retire_peer_issued_cid_alarm =
16697       connection_.GetRetirePeerIssuedConnectionIdAlarm();
16698   ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
16699   EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
16700   retire_peer_issued_cid_alarm->Fire();
16701 
16702   const QuicSocketAddress kNewSelfAddress2(kNewSelfAddress.host(),
16703                                            kNewSelfAddress.port() + 1);
16704   EXPECT_NE(kNewSelfAddress2, kNewSelfAddress);
16705   TestPacketWriter new_writer2(version(), &clock_, Perspective::IS_CLIENT);
16706   QuicNewConnectionIdFrame frame;
16707   frame.connection_id = TestConnectionId(789);
16708   ASSERT_NE(frame.connection_id, connection_.connection_id());
16709   frame.stateless_reset_token =
16710       QuicUtils::GenerateStatelessResetToken(frame.connection_id);
16711   frame.retire_prior_to = 0u;
16712   frame.sequence_number = 2u;
16713   EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
16714       .WillOnce(testing::WithArgs<0>([&](auto&& observer) {
16715         observer->OnMultiPortPathContextAvailable(
16716             std::move(std::make_unique<TestQuicPathValidationContext>(
16717                 kNewSelfAddress2, connection_.peer_address(), &new_writer2)));
16718       }));
16719   connection_.OnNewConnectionIdFrame(frame);
16720   EXPECT_TRUE(connection_.HasPendingPathValidation());
16721   EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
16722   payload = new_writer.path_challenge_frames().front().data_buffer;
16723   EXPECT_EQ(kServerPreferredAddress, new_writer.last_write_peer_address());
16724   EXPECT_EQ(kNewSelfAddress2.host(), new_writer.last_write_source_address());
16725   EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
16726       &connection_, kNewSelfAddress2, connection_.peer_address()));
16727   auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
16728   EXPECT_FALSE(alt_path->validated);
16729   QuicFrames frames2;
16730   frames2.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
16731   ProcessFramesPacketWithAddresses(frames2, kNewSelfAddress2, kPeerAddress,
16732                                    ENCRYPTION_FORWARD_SECURE);
16733   EXPECT_TRUE(alt_path->validated);
16734 }
16735 
16736 // Tests that after half-way server migration, the client should be able to
16737 // respond to any reverse path validation from the original server address.
TEST_P(QuicConnectionTest,ClientReceivePathChallengeAfterServerMigration)16738 TEST_P(QuicConnectionTest, ClientReceivePathChallengeAfterServerMigration) {
16739   if (!GetParam().version.HasIetfQuicFrames()) {
16740     return;
16741   }
16742   QuicConfig config;
16743   ServerPreferredAddressInit(config);
16744   QuicConnectionId cid_for_preferred_address = TestConnectionId(17);
16745   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16746   EXPECT_CALL(visitor_,
16747               OnServerPreferredAddressAvailable(kServerPreferredAddress))
16748       .WillOnce(Invoke([&]() {
16749         connection_.AddKnownServerAddress(kServerPreferredAddress);
16750       }));
16751   EXPECT_CALL(visitor_, GetHandshakeState())
16752       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16753   connection_.OnHandshakeComplete();
16754 
16755   const QuicSocketAddress kNewSelfAddress =
16756       QuicSocketAddress(QuicIpAddress::Loopback6(), kTestPort + 1);
16757   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
16758   auto context = std::make_unique<TestQuicPathValidationContext>(
16759       kNewSelfAddress, kServerPreferredAddress, &new_writer);
16760   // Pretend that the validation already succeeded. And start to use the server
16761   // preferred address.
16762   connection_.OnServerPreferredAddressValidated(*context, false);
16763   EXPECT_EQ(kServerPreferredAddress, connection_.effective_peer_address());
16764   EXPECT_EQ(kServerPreferredAddress, connection_.peer_address());
16765   EXPECT_EQ(kNewSelfAddress, connection_.self_address());
16766   EXPECT_EQ(connection_.connection_id(), cid_for_preferred_address);
16767   EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
16768             send_algorithm_);
16769   // Switch to use a mock send algorithm.
16770   send_algorithm_ = new StrictMock<MockSendAlgorithm>();
16771   EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
16772   EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
16773       .WillRepeatedly(Return(kDefaultTCPMSS));
16774   EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
16775   EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
16776       .Times(AnyNumber())
16777       .WillRepeatedly(Return(QuicBandwidth::Zero()));
16778   EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
16779   EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
16780   EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
16781   connection_.SetSendAlgorithm(send_algorithm_);
16782 
16783   // As the default path changed, the server issued CID 123 should be retired.
16784   QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_);
16785   auto* retire_peer_issued_cid_alarm =
16786       connection_.GetRetirePeerIssuedConnectionIdAlarm();
16787   ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
16788   EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
16789   retire_peer_issued_cid_alarm->Fire();
16790 
16791   // Receive PATH_CHALLENGE from the original server
16792   // address. The client connection responds it on the default path.
16793   QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
16794   QuicFrames frames1;
16795   frames1.push_back(
16796       QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
16797   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
16798       .Times(AtLeast(1))
16799       .WillOnce(Invoke([&]() {
16800         ASSERT_FALSE(new_writer.path_response_frames().empty());
16801         EXPECT_EQ(
16802             0, memcmp(&path_challenge_payload,
16803                       &(new_writer.path_response_frames().front().data_buffer),
16804                       sizeof(path_challenge_payload)));
16805         EXPECT_EQ(kServerPreferredAddress,
16806                   new_writer.last_write_peer_address());
16807         EXPECT_EQ(kNewSelfAddress.host(),
16808                   new_writer.last_write_source_address());
16809       }));
16810   ProcessFramesPacketWithAddresses(frames1, kNewSelfAddress, kPeerAddress,
16811                                    ENCRYPTION_FORWARD_SECURE);
16812 }
16813 
16814 // Tests that after half-way server migration, the client should be able to
16815 // probe with a different socket and respond to reverse path validation.
TEST_P(QuicConnectionTest,ClientProbesAfterServerMigration)16816 TEST_P(QuicConnectionTest, ClientProbesAfterServerMigration) {
16817   if (!GetParam().version.HasIetfQuicFrames()) {
16818     return;
16819   }
16820   QuicConfig config;
16821   ServerPreferredAddressInit(config);
16822   QuicConnectionId cid_for_preferred_address = TestConnectionId(17);
16823   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16824 
16825   // The connection should start probing the preferred address after handshake
16826   // confirmed.
16827   EXPECT_CALL(visitor_,
16828               OnServerPreferredAddressAvailable(kServerPreferredAddress))
16829       .WillOnce(Invoke([&]() {
16830         connection_.AddKnownServerAddress(kServerPreferredAddress);
16831       }));
16832   EXPECT_CALL(visitor_, GetHandshakeState())
16833       .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16834   connection_.OnHandshakeComplete();
16835 
16836   const QuicSocketAddress kNewSelfAddress =
16837       QuicSocketAddress(QuicIpAddress::Loopback6(), kTestPort + 1);
16838   TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
16839   auto context = std::make_unique<TestQuicPathValidationContext>(
16840       kNewSelfAddress, kServerPreferredAddress, &new_writer);
16841   // Pretend that the validation already succeeded.
16842   connection_.OnServerPreferredAddressValidated(*context, false);
16843   EXPECT_EQ(kServerPreferredAddress, connection_.effective_peer_address());
16844   EXPECT_EQ(kServerPreferredAddress, connection_.peer_address());
16845   EXPECT_EQ(kNewSelfAddress, connection_.self_address());
16846   EXPECT_EQ(connection_.connection_id(), cid_for_preferred_address);
16847   EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
16848             send_algorithm_);
16849   // Switch to use a mock send algorithm.
16850   send_algorithm_ = new StrictMock<MockSendAlgorithm>();
16851   EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
16852   EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
16853       .WillRepeatedly(Return(kDefaultTCPMSS));
16854   EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
16855   EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
16856       .Times(AnyNumber())
16857       .WillRepeatedly(Return(QuicBandwidth::Zero()));
16858   EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
16859   EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
16860   EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
16861   connection_.SetSendAlgorithm(send_algorithm_);
16862 
16863   // Receiving data from the original server address should not change the peer
16864   // address.
16865   EXPECT_CALL(visitor_, OnCryptoFrame(_));
16866   ProcessFramePacketWithAddresses(MakeCryptoFrame(), kNewSelfAddress,
16867                                   kPeerAddress, ENCRYPTION_FORWARD_SECURE);
16868   EXPECT_EQ(kServerPreferredAddress, connection_.effective_peer_address());
16869   EXPECT_EQ(kServerPreferredAddress, connection_.peer_address());
16870 
16871   // As the default path changed, the server issued CID 123 should be retired.
16872   auto* retire_peer_issued_cid_alarm =
16873       connection_.GetRetirePeerIssuedConnectionIdAlarm();
16874   ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
16875   EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
16876   retire_peer_issued_cid_alarm->Fire();
16877 
16878   // Receiving a new CID from the server.
16879   QuicNewConnectionIdFrame new_cid_frame1;
16880   new_cid_frame1.connection_id = TestConnectionId(456);
16881   ASSERT_NE(new_cid_frame1.connection_id, connection_.connection_id());
16882   new_cid_frame1.stateless_reset_token =
16883       QuicUtils::GenerateStatelessResetToken(new_cid_frame1.connection_id);
16884   new_cid_frame1.retire_prior_to = 0u;
16885   new_cid_frame1.sequence_number = 2u;
16886   connection_.OnNewConnectionIdFrame(new_cid_frame1);
16887 
16888   // Probe from a new socket.
16889   const QuicSocketAddress kNewSelfAddress2 =
16890       QuicSocketAddress(QuicIpAddress::Loopback4(), kTestPort + 2);
16891   TestPacketWriter new_writer2(version(), &clock_, Perspective::IS_CLIENT);
16892   bool success;
16893   QuicPathFrameBuffer payload;
16894   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
16895       .Times(testing::AtLeast(1u))
16896       .WillOnce(Invoke([&]() {
16897         EXPECT_EQ(1u, new_writer2.path_challenge_frames().size());
16898         payload = new_writer2.path_challenge_frames().front().data_buffer;
16899         EXPECT_EQ(kServerPreferredAddress,
16900                   new_writer2.last_write_peer_address());
16901         EXPECT_EQ(kNewSelfAddress2.host(),
16902                   new_writer2.last_write_source_address());
16903       }));
16904   connection_.ValidatePath(
16905       std::make_unique<TestQuicPathValidationContext>(
16906           kNewSelfAddress2, connection_.peer_address(), &new_writer2),
16907       std::make_unique<TestValidationResultDelegate>(
16908           &connection_, kNewSelfAddress2, connection_.peer_address(), &success),
16909       PathValidationReason::kServerPreferredAddressMigration);
16910   EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
16911       &connection_, kNewSelfAddress2, kServerPreferredAddress));
16912 
16913   // Our server implementation will send PATH_CHALLENGE from the original server
16914   // address. The client connection send PATH_RESPONSE to the default peer
16915   // address.
16916   QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
16917   QuicFrames frames;
16918   frames.push_back(
16919       QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
16920   frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
16921   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
16922       .Times(AtLeast(1))
16923       .WillOnce(Invoke([&]() {
16924         EXPECT_FALSE(new_writer2.path_response_frames().empty());
16925         EXPECT_EQ(
16926             0, memcmp(&path_challenge_payload,
16927                       &(new_writer2.path_response_frames().front().data_buffer),
16928                       sizeof(path_challenge_payload)));
16929         EXPECT_EQ(kServerPreferredAddress,
16930                   new_writer2.last_write_peer_address());
16931         EXPECT_EQ(kNewSelfAddress2.host(),
16932                   new_writer2.last_write_source_address());
16933       }));
16934   ProcessFramesPacketWithAddresses(frames, kNewSelfAddress2, kPeerAddress,
16935                                    ENCRYPTION_FORWARD_SECURE);
16936   EXPECT_TRUE(success);
16937 }
16938 
TEST_P(QuicConnectionTest,EcnMarksCorrectlyRecorded)16939 TEST_P(QuicConnectionTest, EcnMarksCorrectlyRecorded) {
16940   set_perspective(Perspective::IS_SERVER);
16941   QuicFrames frames;
16942   frames.push_back(QuicFrame(QuicPingFrame()));
16943   frames.push_back(QuicFrame(QuicPaddingFrame(7)));
16944   QuicAckFrame ack_frame =
16945       connection_.SupportsMultiplePacketNumberSpaces()
16946           ? connection_.received_packet_manager().GetAckFrame(APPLICATION_DATA)
16947           : connection_.received_packet_manager().ack_frame();
16948   EXPECT_FALSE(ack_frame.ecn_counters.has_value());
16949 
16950   ProcessFramesPacketAtLevelWithEcn(1, frames, ENCRYPTION_FORWARD_SECURE,
16951                                     ECN_ECT0);
16952   ack_frame =
16953       connection_.SupportsMultiplePacketNumberSpaces()
16954           ? connection_.received_packet_manager().GetAckFrame(APPLICATION_DATA)
16955           : connection_.received_packet_manager().ack_frame();
16956   // Send two PINGs so that the ACK goes too. The second packet should not
16957   // include an ACK, which checks that the packet state is cleared properly.
16958   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16959   if (connection_.version().HasIetfQuicFrames()) {
16960     QuicConnectionPeer::SendPing(&connection_);
16961     QuicConnectionPeer::SendPing(&connection_);
16962   }
16963   QuicConnectionStats stats = connection_.GetStats();
16964   ASSERT_TRUE(ack_frame.ecn_counters.has_value());
16965   EXPECT_EQ(ack_frame.ecn_counters->ect0, 1);
16966   EXPECT_EQ(stats.num_ack_frames_sent_with_ecn,
16967             connection_.version().HasIetfQuicFrames() ? 1 : 0);
16968   EXPECT_EQ(stats.num_ecn_marks_received.ect0, 1);
16969   EXPECT_EQ(stats.num_ecn_marks_received.ect1, 0);
16970   EXPECT_EQ(stats.num_ecn_marks_received.ce, 0);
16971 }
16972 
TEST_P(QuicConnectionTest,EcnMarksCoalescedPacket)16973 TEST_P(QuicConnectionTest, EcnMarksCoalescedPacket) {
16974   if (!connection_.version().CanSendCoalescedPackets()) {
16975     return;
16976   }
16977   QuicCryptoFrame crypto_frame1{ENCRYPTION_HANDSHAKE, 0, "foo"};
16978   QuicFrames frames1;
16979   frames1.push_back(QuicFrame(&crypto_frame1));
16980   QuicFrames frames2;
16981   QuicCryptoFrame crypto_frame2{ENCRYPTION_FORWARD_SECURE, 0, "bar"};
16982   frames2.push_back(QuicFrame(&crypto_frame2));
16983   std::vector<PacketInfo> packets = {{2, frames1, ENCRYPTION_HANDSHAKE},
16984                                      {3, frames2, ENCRYPTION_FORWARD_SECURE}};
16985   QuicAckFrame ack_frame =
16986       connection_.SupportsMultiplePacketNumberSpaces()
16987           ? connection_.received_packet_manager().GetAckFrame(APPLICATION_DATA)
16988           : connection_.received_packet_manager().ack_frame();
16989   EXPECT_FALSE(ack_frame.ecn_counters.has_value());
16990   ack_frame =
16991       connection_.SupportsMultiplePacketNumberSpaces()
16992           ? connection_.received_packet_manager().GetAckFrame(HANDSHAKE_DATA)
16993           : connection_.received_packet_manager().ack_frame();
16994   EXPECT_FALSE(ack_frame.ecn_counters.has_value());
16995   // Deliver packets.
16996   connection_.SetEncrypter(
16997       ENCRYPTION_HANDSHAKE,
16998       std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
16999   EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(2);
17000   ProcessCoalescedPacket(packets, ECN_ECT0);
17001   // Send two PINGs so that the ACKs go too.
17002   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
17003   if (connection_.version().HasIetfQuicFrames()) {
17004     EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
17005     connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
17006     QuicConnectionPeer::SendPing(&connection_);
17007     connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
17008     QuicConnectionPeer::SendPing(&connection_);
17009   }
17010   QuicConnectionStats stats = connection_.GetStats();
17011   ack_frame =
17012       connection_.SupportsMultiplePacketNumberSpaces()
17013           ? connection_.received_packet_manager().GetAckFrame(HANDSHAKE_DATA)
17014           : connection_.received_packet_manager().ack_frame();
17015   ASSERT_TRUE(ack_frame.ecn_counters.has_value());
17016   EXPECT_EQ(ack_frame.ecn_counters->ect0,
17017             connection_.SupportsMultiplePacketNumberSpaces() ? 1 : 2);
17018   if (connection_.SupportsMultiplePacketNumberSpaces()) {
17019     ack_frame = connection_.SupportsMultiplePacketNumberSpaces()
17020                     ? connection_.received_packet_manager().GetAckFrame(
17021                           APPLICATION_DATA)
17022                     : connection_.received_packet_manager().ack_frame();
17023     EXPECT_TRUE(ack_frame.ecn_counters.has_value());
17024     EXPECT_EQ(ack_frame.ecn_counters->ect0, 1);
17025   }
17026   EXPECT_EQ(stats.num_ecn_marks_received.ect0, 2);
17027   EXPECT_EQ(stats.num_ack_frames_sent_with_ecn,
17028             connection_.version().HasIetfQuicFrames() ? 2 : 0);
17029   EXPECT_EQ(stats.num_ecn_marks_received.ect1, 0);
17030   EXPECT_EQ(stats.num_ecn_marks_received.ce, 0);
17031 }
17032 
TEST_P(QuicConnectionTest,EcnMarksUndecryptableCoalescedPacket)17033 TEST_P(QuicConnectionTest, EcnMarksUndecryptableCoalescedPacket) {
17034   if (!connection_.version().CanSendCoalescedPackets()) {
17035     return;
17036   }
17037   // SetFromConfig is always called after construction from InitializeSession.
17038   EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
17039   QuicConfig config;
17040   config.set_max_undecryptable_packets(100);
17041   connection_.SetFromConfig(config);
17042   QuicCryptoFrame crypto_frame1{ENCRYPTION_HANDSHAKE, 0, "foo"};
17043   QuicFrames frames1;
17044   frames1.push_back(QuicFrame(&crypto_frame1));
17045   QuicFrames frames2;
17046   QuicCryptoFrame crypto_frame2{ENCRYPTION_FORWARD_SECURE, 0, "bar"};
17047   frames2.push_back(QuicFrame(&crypto_frame2));
17048   std::vector<PacketInfo> packets = {{2, frames1, ENCRYPTION_HANDSHAKE},
17049                                      {3, frames2, ENCRYPTION_FORWARD_SECURE}};
17050   char coalesced_buffer[kMaxOutgoingPacketSize];
17051   size_t coalesced_size = 0;
17052   for (const auto& packet : packets) {
17053     QuicPacketHeader header =
17054         ConstructPacketHeader(packet.packet_number, packet.level);
17055     // Set the correct encryption level and encrypter on peer_creator and
17056     // peer_framer, respectively.
17057     peer_creator_.set_encryption_level(packet.level);
17058     peer_framer_.SetEncrypter(packet.level,
17059                               std::make_unique<TaggingEncrypter>(packet.level));
17060     // Set the corresponding decrypter.
17061     if (packet.level == ENCRYPTION_HANDSHAKE) {
17062       connection_.SetEncrypter(
17063           packet.level, std::make_unique<TaggingEncrypter>(packet.level));
17064       connection_.SetDefaultEncryptionLevel(packet.level);
17065       SetDecrypter(packet.level,
17066                    std::make_unique<StrictTaggingDecrypter>(packet.level));
17067     }
17068     // Forward Secure packet is undecryptable.
17069     std::unique_ptr<QuicPacket> constructed_packet(
17070         ConstructPacket(header, packet.frames));
17071 
17072     char buffer[kMaxOutgoingPacketSize];
17073     size_t encrypted_length = peer_framer_.EncryptPayload(
17074         packet.level, QuicPacketNumber(packet.packet_number),
17075         *constructed_packet, buffer, kMaxOutgoingPacketSize);
17076     QUICHE_DCHECK_LE(coalesced_size + encrypted_length, kMaxOutgoingPacketSize);
17077     memcpy(coalesced_buffer + coalesced_size, buffer, encrypted_length);
17078     coalesced_size += encrypted_length;
17079   }
17080   QuicAckFrame ack_frame =
17081       connection_.SupportsMultiplePacketNumberSpaces()
17082           ? connection_.received_packet_manager().GetAckFrame(APPLICATION_DATA)
17083           : connection_.received_packet_manager().ack_frame();
17084   EXPECT_FALSE(ack_frame.ecn_counters.has_value());
17085   ack_frame =
17086       connection_.SupportsMultiplePacketNumberSpaces()
17087           ? connection_.received_packet_manager().GetAckFrame(HANDSHAKE_DATA)
17088           : connection_.received_packet_manager().ack_frame();
17089   EXPECT_FALSE(ack_frame.ecn_counters.has_value());
17090   // Deliver packets, but first remove the Forward Secure decrypter so that
17091   // packet has to be buffered.
17092   connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
17093   EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
17094   EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
17095   connection_.ProcessUdpPacket(
17096       kSelfAddress, kPeerAddress,
17097       QuicReceivedPacket(coalesced_buffer, coalesced_size, clock_.Now(), false,
17098                          0, true, nullptr, 0, true, ECN_ECT0));
17099   if (connection_.GetSendAlarm()->IsSet()) {
17100     connection_.GetSendAlarm()->Fire();
17101   }
17102   ack_frame =
17103       connection_.SupportsMultiplePacketNumberSpaces()
17104           ? connection_.received_packet_manager().GetAckFrame(HANDSHAKE_DATA)
17105           : connection_.received_packet_manager().ack_frame();
17106   ASSERT_TRUE(ack_frame.ecn_counters.has_value());
17107   EXPECT_EQ(ack_frame.ecn_counters->ect0, 1);
17108   if (connection_.SupportsMultiplePacketNumberSpaces()) {
17109     ack_frame = connection_.SupportsMultiplePacketNumberSpaces()
17110                     ? connection_.received_packet_manager().GetAckFrame(
17111                           APPLICATION_DATA)
17112                     : connection_.received_packet_manager().ack_frame();
17113     EXPECT_FALSE(ack_frame.ecn_counters.has_value());
17114   }
17115   // Send PING packet with ECN_CE, which will change the ECN codepoint in
17116   // last_received_packet_info_.
17117   ProcessFramePacketAtLevelWithEcn(4, QuicFrame(QuicPingFrame()),
17118                                    ENCRYPTION_HANDSHAKE, ECN_CE);
17119   ack_frame =
17120       connection_.SupportsMultiplePacketNumberSpaces()
17121           ? connection_.received_packet_manager().GetAckFrame(HANDSHAKE_DATA)
17122           : connection_.received_packet_manager().ack_frame();
17123   ASSERT_TRUE(ack_frame.ecn_counters.has_value());
17124   EXPECT_EQ(ack_frame.ecn_counters->ect0, 1);
17125   EXPECT_EQ(ack_frame.ecn_counters->ce, 1);
17126   if (connection_.SupportsMultiplePacketNumberSpaces()) {
17127     ack_frame = connection_.SupportsMultiplePacketNumberSpaces()
17128                     ? connection_.received_packet_manager().GetAckFrame(
17129                           APPLICATION_DATA)
17130                     : connection_.received_packet_manager().ack_frame();
17131     EXPECT_FALSE(ack_frame.ecn_counters.has_value());
17132   }
17133   // Install decrypter for ENCRYPTION_FORWARD_SECURE. Make sure the original
17134   // ECN codepoint is incremented.
17135   EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
17136   SetDecrypter(
17137       ENCRYPTION_FORWARD_SECURE,
17138       std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
17139   connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
17140   ack_frame =
17141       connection_.SupportsMultiplePacketNumberSpaces()
17142           ? connection_.received_packet_manager().GetAckFrame(APPLICATION_DATA)
17143           : connection_.received_packet_manager().ack_frame();
17144   ASSERT_TRUE(ack_frame.ecn_counters.has_value());
17145   // Should be recorded as ECT(0), not CE.
17146   EXPECT_EQ(ack_frame.ecn_counters->ect0,
17147             connection_.SupportsMultiplePacketNumberSpaces() ? 1 : 2);
17148   QuicConnectionStats stats = connection_.GetStats();
17149   EXPECT_EQ(stats.num_ecn_marks_received.ect0, 2);
17150   EXPECT_EQ(stats.num_ecn_marks_received.ect1, 0);
17151   EXPECT_EQ(stats.num_ecn_marks_received.ce, 1);
17152 }
17153 
TEST_P(QuicConnectionTest,ReceivedPacketInfoDefaults)17154 TEST_P(QuicConnectionTest, ReceivedPacketInfoDefaults) {
17155   EXPECT_TRUE(QuicConnectionPeer::TestLastReceivedPacketInfoDefaults());
17156 }
17157 
TEST_P(QuicConnectionTest,DetectMigrationToPreferredAddress)17158 TEST_P(QuicConnectionTest, DetectMigrationToPreferredAddress) {
17159   if (!GetParam().version.HasIetfQuicFrames()) {
17160     return;
17161   }
17162   ServerHandlePreferredAddressInit();
17163 
17164   // Issue a new server CID associated with the preferred address.
17165   QuicConnectionId server_issued_cid_for_preferred_address =
17166       TestConnectionId(17);
17167   EXPECT_CALL(connection_id_generator_,
17168               GenerateNextConnectionId(connection_id_))
17169       .WillOnce(Return(server_issued_cid_for_preferred_address));
17170   EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(true));
17171   std::optional<QuicNewConnectionIdFrame> frame =
17172       connection_.MaybeIssueNewConnectionIdForPreferredAddress();
17173   ASSERT_TRUE(frame.has_value());
17174 
17175   auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
17176   ASSERT_EQ(packet_creator->GetDestinationConnectionId(),
17177             connection_.client_connection_id());
17178   ASSERT_EQ(packet_creator->GetSourceConnectionId(), connection_id_);
17179 
17180   // Process a packet received at the preferred Address.
17181   peer_creator_.SetServerConnectionId(server_issued_cid_for_preferred_address);
17182   EXPECT_CALL(visitor_, OnCryptoFrame(_));
17183   ProcessFramePacketWithAddresses(MakeCryptoFrame(), kServerPreferredAddress,
17184                                   kPeerAddress, ENCRYPTION_FORWARD_SECURE);
17185   EXPECT_EQ(kPeerAddress, connection_.peer_address());
17186   // The server migrates half-way with the default path unchanged, and
17187   // continuing with the client issued CID 1.
17188   EXPECT_EQ(kSelfAddress.host(), writer_->last_write_source_address());
17189   EXPECT_EQ(kSelfAddress, connection_.self_address());
17190 
17191   // The peer retires CID 123.
17192   QuicRetireConnectionIdFrame retire_cid_frame;
17193   retire_cid_frame.sequence_number = 0u;
17194   EXPECT_CALL(connection_id_generator_,
17195               GenerateNextConnectionId(server_issued_cid_for_preferred_address))
17196       .WillOnce(Return(TestConnectionId(456)));
17197   EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(true));
17198   EXPECT_CALL(visitor_, SendNewConnectionId(_));
17199   EXPECT_TRUE(connection_.OnRetireConnectionIdFrame(retire_cid_frame));
17200 
17201   // Process another packet received at Preferred Address.
17202   EXPECT_CALL(visitor_, OnCryptoFrame(_));
17203   ProcessFramePacketWithAddresses(MakeCryptoFrame(), kServerPreferredAddress,
17204                                   kPeerAddress, ENCRYPTION_FORWARD_SECURE);
17205   EXPECT_EQ(kPeerAddress, connection_.peer_address());
17206   EXPECT_EQ(kSelfAddress.host(), writer_->last_write_source_address());
17207   EXPECT_EQ(kSelfAddress, connection_.self_address());
17208 }
17209 
TEST_P(QuicConnectionTest,DetectSimutanuousServerAndClientAddressChangeWithProbe)17210 TEST_P(QuicConnectionTest,
17211        DetectSimutanuousServerAndClientAddressChangeWithProbe) {
17212   if (!GetParam().version.HasIetfQuicFrames()) {
17213     return;
17214   }
17215   ServerHandlePreferredAddressInit();
17216 
17217   // Issue a new server CID associated with the preferred address.
17218   QuicConnectionId server_issued_cid_for_preferred_address =
17219       TestConnectionId(17);
17220   EXPECT_CALL(connection_id_generator_,
17221               GenerateNextConnectionId(connection_id_))
17222       .WillOnce(Return(server_issued_cid_for_preferred_address));
17223   EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(true));
17224   std::optional<QuicNewConnectionIdFrame> frame =
17225       connection_.MaybeIssueNewConnectionIdForPreferredAddress();
17226   ASSERT_TRUE(frame.has_value());
17227 
17228   auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
17229   ASSERT_EQ(packet_creator->GetSourceConnectionId(), connection_id_);
17230   ASSERT_EQ(packet_creator->GetDestinationConnectionId(),
17231             connection_.client_connection_id());
17232 
17233   // Receiving a probing packet from a new client address to the preferred
17234   // address.
17235   peer_creator_.SetServerConnectionId(server_issued_cid_for_preferred_address);
17236   const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
17237                                           /*port=*/34567);
17238   std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
17239   std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
17240       QuicEncryptedPacket(probing_packet->encrypted_buffer,
17241                           probing_packet->encrypted_length),
17242       clock_.Now()));
17243   uint64_t num_probing_received =
17244       connection_.GetStats().num_connectivity_probing_received;
17245   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
17246       .Times(AtLeast(1u))
17247       .WillOnce(Invoke([&]() {
17248         EXPECT_EQ(1u, writer_->path_response_frames().size());
17249         EXPECT_EQ(1u, writer_->path_challenge_frames().size());
17250         // The responses should be sent from preferred address given server
17251         // has not received packet on original address from the new client
17252         // address.
17253         EXPECT_EQ(kServerPreferredAddress.host(),
17254                   writer_->last_write_source_address());
17255         EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
17256       }));
17257   ProcessReceivedPacket(kServerPreferredAddress, kNewPeerAddress, *received);
17258   EXPECT_EQ(num_probing_received + 1,
17259             connection_.GetStats().num_connectivity_probing_received);
17260   EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(&connection_, kSelfAddress,
17261                                                     kNewPeerAddress));
17262   EXPECT_LT(0u, QuicConnectionPeer::BytesSentOnAlternativePath(&connection_));
17263   EXPECT_EQ(received->length(),
17264             QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
17265   EXPECT_EQ(kPeerAddress, connection_.peer_address());
17266   EXPECT_EQ(kSelfAddress, connection_.self_address());
17267 
17268   // Process a data packet received at the preferred Address from the new client
17269   // address.
17270   EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE));
17271   EXPECT_CALL(visitor_, OnCryptoFrame(_));
17272   ProcessFramePacketWithAddresses(MakeCryptoFrame(), kServerPreferredAddress,
17273                                   kNewPeerAddress, ENCRYPTION_FORWARD_SECURE);
17274   // The server migrates half-way with the new peer address but the same default
17275   // self address.
17276   EXPECT_EQ(kSelfAddress.host(), writer_->last_write_source_address());
17277   EXPECT_EQ(kSelfAddress, connection_.self_address());
17278   EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
17279   EXPECT_TRUE(connection_.HasPendingPathValidation());
17280   EXPECT_FALSE(QuicConnectionPeer::GetDefaultPath(&connection_)->validated);
17281   EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(&connection_, kSelfAddress,
17282                                                     kPeerAddress));
17283   EXPECT_EQ(packet_creator->GetSourceConnectionId(),
17284             server_issued_cid_for_preferred_address);
17285 
17286   // Process another packet received at the preferred Address.
17287   EXPECT_CALL(visitor_, OnCryptoFrame(_));
17288   ProcessFramePacketWithAddresses(MakeCryptoFrame(), kServerPreferredAddress,
17289                                   kNewPeerAddress, ENCRYPTION_FORWARD_SECURE);
17290   EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
17291   EXPECT_EQ(kServerPreferredAddress.host(),
17292             writer_->last_write_source_address());
17293   EXPECT_EQ(kSelfAddress, connection_.self_address());
17294 }
17295 
TEST_P(QuicConnectionTest,EcnCodepointsRejected)17296 TEST_P(QuicConnectionTest, EcnCodepointsRejected) {
17297   SetQuicRestartFlag(quic_support_ect1, true);
17298   for (QuicEcnCodepoint ecn : {ECN_NOT_ECT, ECN_ECT0, ECN_ECT1, ECN_CE}) {
17299     if (ecn == ECN_ECT0) {
17300       EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
17301     } else if (ecn == ECN_ECT1) {
17302       EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
17303     }
17304     if (ecn == ECN_NOT_ECT) {
17305       EXPECT_TRUE(connection_.set_ecn_codepoint(ecn));
17306     } else {
17307       EXPECT_FALSE(connection_.set_ecn_codepoint(ecn));
17308     }
17309     EXPECT_EQ(connection_.ecn_codepoint(), ECN_NOT_ECT);
17310     EXPECT_CALL(connection_, OnSerializedPacket(_));
17311     SendPing();
17312     EXPECT_EQ(writer_->last_ecn_sent(), ECN_NOT_ECT);
17313   }
17314 }
17315 
TEST_P(QuicConnectionTest,EcnCodepointsAccepted)17316 TEST_P(QuicConnectionTest, EcnCodepointsAccepted) {
17317   SetQuicRestartFlag(quic_support_ect1, true);
17318   for (QuicEcnCodepoint ecn : {ECN_NOT_ECT, ECN_ECT0, ECN_ECT1, ECN_CE}) {
17319     if (ecn == ECN_ECT0) {
17320       EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(true));
17321     } else if (ecn == ECN_ECT1) {
17322       EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
17323     }
17324     if (ecn == ECN_CE) {
17325       EXPECT_FALSE(connection_.set_ecn_codepoint(ecn));
17326     } else {
17327       EXPECT_TRUE(connection_.set_ecn_codepoint(ecn));
17328     }
17329     EXPECT_CALL(connection_, OnSerializedPacket(_));
17330     SendPing();
17331     QuicEcnCodepoint expected_codepoint = ecn;
17332     if (ecn == ECN_CE) {
17333       expected_codepoint = ECN_ECT1;
17334     }
17335     EXPECT_EQ(connection_.ecn_codepoint(), expected_codepoint);
17336     EXPECT_EQ(writer_->last_ecn_sent(), expected_codepoint);
17337   }
17338 }
17339 
TEST_P(QuicConnectionTest,EcnCodepointsRejectedIfFlagIsFalse)17340 TEST_P(QuicConnectionTest, EcnCodepointsRejectedIfFlagIsFalse) {
17341   SetQuicRestartFlag(quic_support_ect1, false);
17342   for (QuicEcnCodepoint ecn : {ECN_NOT_ECT, ECN_ECT0, ECN_ECT1, ECN_CE}) {
17343     EXPECT_FALSE(connection_.set_ecn_codepoint(ecn));
17344     EXPECT_CALL(connection_, OnSerializedPacket(_));
17345     SendPing();
17346     EXPECT_EQ(connection_.ecn_codepoint(), ECN_NOT_ECT);
17347     EXPECT_EQ(writer_->last_ecn_sent(), ECN_NOT_ECT);
17348   }
17349 }
17350 
TEST_P(QuicConnectionTest,EcnValidationDisabled)17351 TEST_P(QuicConnectionTest, EcnValidationDisabled) {
17352   SetQuicRestartFlag(quic_support_ect1, true);
17353   QuicConnectionPeer::DisableEcnCodepointValidation(&connection_);
17354   for (QuicEcnCodepoint ecn : {ECN_NOT_ECT, ECN_ECT0, ECN_ECT1, ECN_CE}) {
17355     EXPECT_TRUE(connection_.set_ecn_codepoint(ecn));
17356     EXPECT_CALL(connection_, OnSerializedPacket(_));
17357     SendPing();
17358     EXPECT_EQ(connection_.ecn_codepoint(), ecn);
17359     EXPECT_EQ(writer_->last_ecn_sent(), ecn);
17360   }
17361 }
17362 
TEST_P(QuicConnectionTest,RtoDisablesEcnMarking)17363 TEST_P(QuicConnectionTest, RtoDisablesEcnMarking) {
17364   SetQuicRestartFlag(quic_support_ect1, true);
17365   EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
17366   EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1));
17367   QuicPacketCreatorPeer::SetPacketNumber(
17368       QuicConnectionPeer::GetPacketCreator(&connection_), 1);
17369   SendPing();
17370   connection_.OnRetransmissionTimeout();
17371   EXPECT_EQ(writer_->last_ecn_sent(), ECN_NOT_ECT);
17372   EXPECT_EQ(connection_.ecn_codepoint(), ECN_ECT1);
17373   // On 2nd RTO, QUIC abandons ECN.
17374   connection_.OnRetransmissionTimeout();
17375   EXPECT_EQ(writer_->last_ecn_sent(), ECN_NOT_ECT);
17376   EXPECT_EQ(connection_.ecn_codepoint(), ECN_NOT_ECT);
17377 }
17378 
TEST_P(QuicConnectionTest,RtoDoesntDisableEcnMarkingIfEcnAcked)17379 TEST_P(QuicConnectionTest, RtoDoesntDisableEcnMarkingIfEcnAcked) {
17380   SetQuicRestartFlag(quic_support_ect1, true);
17381   EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
17382   EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1));
17383   QuicPacketCreatorPeer::SetPacketNumber(
17384       QuicConnectionPeer::GetPacketCreator(&connection_), 1);
17385   connection_.OnInFlightEcnPacketAcked();
17386   SendPing();
17387   // Because an ECN packet was acked, PTOs have no effect on ECN settings.
17388   connection_.OnRetransmissionTimeout();
17389   QuicEcnCodepoint expected_codepoint = ECN_ECT1;
17390   EXPECT_EQ(writer_->last_ecn_sent(), expected_codepoint);
17391   EXPECT_EQ(connection_.ecn_codepoint(), expected_codepoint);
17392   connection_.OnRetransmissionTimeout();
17393   EXPECT_EQ(writer_->last_ecn_sent(), expected_codepoint);
17394   EXPECT_EQ(connection_.ecn_codepoint(), expected_codepoint);
17395 }
17396 
TEST_P(QuicConnectionTest,InvalidFeedbackCancelsEcn)17397 TEST_P(QuicConnectionTest, InvalidFeedbackCancelsEcn) {
17398   SetQuicRestartFlag(quic_support_ect1, true);
17399   EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
17400   EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1));
17401   EXPECT_EQ(connection_.ecn_codepoint(), ECN_ECT1);
17402   connection_.OnInvalidEcnFeedback();
17403   EXPECT_EQ(connection_.ecn_codepoint(), ECN_NOT_ECT);
17404 }
17405 
TEST_P(QuicConnectionTest,StateMatchesSentEcn)17406 TEST_P(QuicConnectionTest, StateMatchesSentEcn) {
17407   SetQuicRestartFlag(quic_support_ect1, true);
17408   EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
17409   EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1));
17410   SendPing();
17411   QuicSentPacketManager* sent_packet_manager =
17412       QuicConnectionPeer::GetSentPacketManager(&connection_);
17413   EXPECT_EQ(writer_->last_ecn_sent(), ECN_ECT1);
17414   EXPECT_EQ(
17415       QuicSentPacketManagerPeer::GetEct1Sent(sent_packet_manager, INITIAL_DATA),
17416       1);
17417 }
17418 
TEST_P(QuicConnectionTest,CoalescedPacketSplitsEcn)17419 TEST_P(QuicConnectionTest, CoalescedPacketSplitsEcn) {
17420   if (!connection_.version().CanSendCoalescedPackets()) {
17421     return;
17422   }
17423   SetQuicRestartFlag(quic_support_ect1, true);
17424   EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
17425   EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1));
17426   // All these steps are necessary to send an INITIAL ping and save it to be
17427   // coalesced, instead of just calling SendPing() and sending it immediately.
17428   char buffer[1000];
17429   creator_->set_encryption_level(ENCRYPTION_INITIAL);
17430   QuicFrames frames;
17431   QuicPingFrame ping;
17432   frames.emplace_back(QuicFrame(ping));
17433   SerializedPacket packet1 = QuicPacketCreatorPeer::SerializeAllFrames(
17434       creator_, frames, buffer, sizeof(buffer));
17435   connection_.SendOrQueuePacket(std::move(packet1));
17436   creator_->set_encryption_level(ENCRYPTION_FORWARD_SECURE);
17437   EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(true));
17438   // If not for the line below, these packets would coalesce.
17439   EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT0));
17440   EXPECT_EQ(writer_->packets_write_attempts(), 0);
17441   SendPing();
17442   EXPECT_EQ(writer_->packets_write_attempts(), 2);
17443   EXPECT_EQ(writer_->last_ecn_sent(), ECN_ECT0);
17444 }
17445 
TEST_P(QuicConnectionTest,BufferedPacketRetainsOldEcn)17446 TEST_P(QuicConnectionTest, BufferedPacketRetainsOldEcn) {
17447   SetQuicRestartFlag(quic_support_ect1, true);
17448   EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
17449   EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1));
17450   writer_->SetWriteBlocked();
17451   EXPECT_CALL(visitor_, OnWriteBlocked()).Times(2);
17452   SendPing();
17453   EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(true));
17454   EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT0));
17455   writer_->SetWritable();
17456   connection_.OnCanWrite();
17457   EXPECT_EQ(writer_->last_ecn_sent(), ECN_ECT1);
17458 }
17459 
TEST_P(QuicConnectionTest,RejectEcnIfWriterDoesNotSupport)17460 TEST_P(QuicConnectionTest, RejectEcnIfWriterDoesNotSupport) {
17461   SetQuicRestartFlag(quic_support_ect1, true);
17462   MockPacketWriter mock_writer;
17463   QuicConnectionPeer::SetWriter(&connection_, &mock_writer, false);
17464   EXPECT_CALL(mock_writer, SupportsEcn()).WillOnce(Return(false));
17465   EXPECT_FALSE(connection_.set_ecn_codepoint(ECN_ECT1));
17466   EXPECT_EQ(connection_.ecn_codepoint(), ECN_NOT_ECT);
17467 }
17468 
17469 }  // namespace
17470 }  // namespace test
17471 }  // namespace quic
17472