blob: de7e4502c3bc5bb1cd91854ce2dd61d7fb90613b [file] [log] [blame]
QUICHE teama6ef0a62019-03-07 20:34:33 -05001// 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 "net/third_party/quiche/src/quic/core/quic_connection.h"
6
7#include <errno.h>
zhongyi546cc452019-04-12 15:27:49 -07008
QUICHE teama6ef0a62019-03-07 20:34:33 -05009#include <memory>
10#include <ostream>
zhongyi9e843642019-04-12 09:04:54 -070011#include <string>
zhongyi546cc452019-04-12 15:27:49 -070012#include <utility>
zhongyi9e843642019-04-12 09:04:54 -070013
QUICHE teama6ef0a62019-03-07 20:34:33 -050014#include "net/third_party/quiche/src/quic/core/congestion_control/loss_detection_interface.h"
15#include "net/third_party/quiche/src/quic/core/congestion_control/send_algorithm_interface.h"
zhongyi546cc452019-04-12 15:27:49 -070016#include "net/third_party/quiche/src/quic/core/crypto/null_decrypter.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050017#include "net/third_party/quiche/src/quic/core/crypto/null_encrypter.h"
18#include "net/third_party/quiche/src/quic/core/crypto/quic_decrypter.h"
19#include "net/third_party/quiche/src/quic/core/crypto/quic_encrypter.h"
20#include "net/third_party/quiche/src/quic/core/quic_connection_id.h"
wub50d4c712020-05-19 15:48:28 -070021#include "net/third_party/quiche/src/quic/core/quic_constants.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050022#include "net/third_party/quiche/src/quic/core/quic_packets.h"
23#include "net/third_party/quiche/src/quic/core/quic_simple_buffer_allocator.h"
24#include "net/third_party/quiche/src/quic/core/quic_types.h"
25#include "net/third_party/quiche/src/quic/core/quic_utils.h"
dschinazi278efae2020-01-28 17:03:09 -080026#include "net/third_party/quiche/src/quic/core/quic_versions.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050027#include "net/third_party/quiche/src/quic/platform/api/quic_error_code_wrappers.h"
28#include "net/third_party/quiche/src/quic/platform/api/quic_expect_bug.h"
29#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
30#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050031#include "net/third_party/quiche/src/quic/platform/api/quic_reference_counted.h"
renjietang5b245892020-05-18 11:57:26 -070032#include "net/third_party/quiche/src/quic/platform/api/quic_socket_address.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050033#include "net/third_party/quiche/src/quic/platform/api/quic_test.h"
34#include "net/third_party/quiche/src/quic/test_tools/mock_clock.h"
35#include "net/third_party/quiche/src/quic/test_tools/mock_random.h"
36#include "net/third_party/quiche/src/quic/test_tools/quic_config_peer.h"
37#include "net/third_party/quiche/src/quic/test_tools/quic_connection_peer.h"
38#include "net/third_party/quiche/src/quic/test_tools/quic_framer_peer.h"
39#include "net/third_party/quiche/src/quic/test_tools/quic_packet_creator_peer.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050040#include "net/third_party/quiche/src/quic/test_tools/quic_sent_packet_manager_peer.h"
41#include "net/third_party/quiche/src/quic/test_tools/quic_test_utils.h"
42#include "net/third_party/quiche/src/quic/test_tools/simple_data_producer.h"
43#include "net/third_party/quiche/src/quic/test_tools/simple_quic_framer.h"
44#include "net/third_party/quiche/src/quic/test_tools/simple_session_notifier.h"
dschinazi278efae2020-01-28 17:03:09 -080045#include "net/third_party/quiche/src/common/platform/api/quiche_arraysize.h"
dmcardlecf0bfcf2019-12-13 08:08:21 -080046#include "net/third_party/quiche/src/common/platform/api/quiche_str_cat.h"
47#include "net/third_party/quiche/src/common/platform/api/quiche_string_piece.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050048
49using testing::_;
50using testing::AnyNumber;
51using testing::AtLeast;
52using testing::DoAll;
QUICHE teama6ef0a62019-03-07 20:34:33 -050053using testing::Ge;
54using testing::IgnoreResult;
55using testing::InSequence;
56using testing::Invoke;
57using testing::InvokeWithoutArgs;
58using testing::Lt;
59using testing::Ref;
60using testing::Return;
61using testing::SaveArg;
62using testing::SetArgPointee;
63using testing::StrictMock;
64
65namespace quic {
66namespace test {
67namespace {
68
nharper55fa6132019-05-07 19:37:21 -070069const char data1[] = "foo data";
70const char data2[] = "bar data";
QUICHE teama6ef0a62019-03-07 20:34:33 -050071
72const bool kHasStopWaiting = true;
73
74const int kDefaultRetransmissionTimeMs = 500;
75
QUICHE team548d51b2019-03-14 10:06:54 -070076DiversificationNonce kTestDiversificationNonce = {
77 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a',
78 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
79 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
80};
81
QUICHE teama6ef0a62019-03-07 20:34:33 -050082const QuicSocketAddress kPeerAddress =
83 QuicSocketAddress(QuicIpAddress::Loopback6(),
84 /*port=*/12345);
85const QuicSocketAddress kSelfAddress =
86 QuicSocketAddress(QuicIpAddress::Loopback6(),
87 /*port=*/443);
88
QUICHE teama6ef0a62019-03-07 20:34:33 -050089QuicStreamId GetNthClientInitiatedStreamId(int n,
90 QuicTransportVersion version) {
dschinazi552accc2019-06-17 17:07:34 -070091 return QuicUtils::GetFirstBidirectionalStreamId(version,
92 Perspective::IS_CLIENT) +
93 n * 2;
QUICHE teama6ef0a62019-03-07 20:34:33 -050094}
95
QUICHE team8c1daa22019-03-13 08:33:41 -070096QuicLongHeaderType EncryptionlevelToLongHeaderType(EncryptionLevel level) {
97 switch (level) {
QUICHE team6987b4a2019-03-15 16:23:04 -070098 case ENCRYPTION_INITIAL:
QUICHE team8c1daa22019-03-13 08:33:41 -070099 return INITIAL;
QUICHE team88ea0082019-03-15 10:05:26 -0700100 case ENCRYPTION_HANDSHAKE:
101 return HANDSHAKE;
QUICHE team8c1daa22019-03-13 08:33:41 -0700102 case ENCRYPTION_ZERO_RTT:
103 return ZERO_RTT_PROTECTED;
104 case ENCRYPTION_FORWARD_SECURE:
105 DCHECK(false);
106 return INVALID_PACKET_TYPE;
107 default:
108 DCHECK(false);
109 return INVALID_PACKET_TYPE;
110 }
111}
112
QUICHE teama6ef0a62019-03-07 20:34:33 -0500113// TaggingEncrypter appends kTagSize bytes of |tag| to the end of each message.
114class TaggingEncrypter : public QuicEncrypter {
115 public:
116 explicit TaggingEncrypter(uint8_t tag) : tag_(tag) {}
117 TaggingEncrypter(const TaggingEncrypter&) = delete;
118 TaggingEncrypter& operator=(const TaggingEncrypter&) = delete;
119
120 ~TaggingEncrypter() override {}
121
122 // QuicEncrypter interface.
dmcardlecf0bfcf2019-12-13 08:08:21 -0800123 bool SetKey(quiche::QuicheStringPiece /*key*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500124
dmcardlecf0bfcf2019-12-13 08:08:21 -0800125 bool SetNoncePrefix(quiche::QuicheStringPiece /*nonce_prefix*/) override {
dschinazi17d42422019-06-18 16:35:07 -0700126 return true;
127 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500128
dmcardlecf0bfcf2019-12-13 08:08:21 -0800129 bool SetIV(quiche::QuicheStringPiece /*iv*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500130
dmcardlecf0bfcf2019-12-13 08:08:21 -0800131 bool SetHeaderProtectionKey(quiche::QuicheStringPiece /*key*/) override {
132 return true;
133 }
QUICHE team2d187972019-03-19 16:23:47 -0700134
dschinazi17d42422019-06-18 16:35:07 -0700135 bool EncryptPacket(uint64_t /*packet_number*/,
dmcardlecf0bfcf2019-12-13 08:08:21 -0800136 quiche::QuicheStringPiece /*associated_data*/,
137 quiche::QuicheStringPiece plaintext,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500138 char* output,
139 size_t* output_length,
140 size_t max_output_length) override {
141 const size_t len = plaintext.size() + kTagSize;
142 if (max_output_length < len) {
143 return false;
144 }
145 // Memmove is safe for inplace encryption.
146 memmove(output, plaintext.data(), plaintext.size());
147 output += plaintext.size();
148 memset(output, tag_, kTagSize);
149 *output_length = len;
150 return true;
151 }
152
dschinazi17d42422019-06-18 16:35:07 -0700153 std::string GenerateHeaderProtectionMask(
dmcardlecf0bfcf2019-12-13 08:08:21 -0800154 quiche::QuicheStringPiece /*sample*/) override {
QUICHE team2d187972019-03-19 16:23:47 -0700155 return std::string(5, 0);
156 }
157
QUICHE teama6ef0a62019-03-07 20:34:33 -0500158 size_t GetKeySize() const override { return 0; }
159 size_t GetNoncePrefixSize() const override { return 0; }
160 size_t GetIVSize() const override { return 0; }
161
162 size_t GetMaxPlaintextSize(size_t ciphertext_size) const override {
163 return ciphertext_size - kTagSize;
164 }
165
166 size_t GetCiphertextSize(size_t plaintext_size) const override {
167 return plaintext_size + kTagSize;
168 }
169
dmcardlecf0bfcf2019-12-13 08:08:21 -0800170 quiche::QuicheStringPiece GetKey() const override {
171 return quiche::QuicheStringPiece();
172 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500173
dmcardlecf0bfcf2019-12-13 08:08:21 -0800174 quiche::QuicheStringPiece GetNoncePrefix() const override {
175 return quiche::QuicheStringPiece();
176 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500177
178 private:
179 enum {
180 kTagSize = 12,
181 };
182
183 const uint8_t tag_;
184};
185
186// TaggingDecrypter ensures that the final kTagSize bytes of the message all
187// have the same value and then removes them.
188class TaggingDecrypter : public QuicDecrypter {
189 public:
190 ~TaggingDecrypter() override {}
191
192 // QuicDecrypter interface
dmcardlecf0bfcf2019-12-13 08:08:21 -0800193 bool SetKey(quiche::QuicheStringPiece /*key*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500194
dmcardlecf0bfcf2019-12-13 08:08:21 -0800195 bool SetNoncePrefix(quiche::QuicheStringPiece /*nonce_prefix*/) override {
dschinazi17d42422019-06-18 16:35:07 -0700196 return true;
197 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500198
dmcardlecf0bfcf2019-12-13 08:08:21 -0800199 bool SetIV(quiche::QuicheStringPiece /*iv*/) override { return true; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500200
dmcardlecf0bfcf2019-12-13 08:08:21 -0800201 bool SetHeaderProtectionKey(quiche::QuicheStringPiece /*key*/) override {
202 return true;
203 }
QUICHE team2d187972019-03-19 16:23:47 -0700204
dmcardlecf0bfcf2019-12-13 08:08:21 -0800205 bool SetPreliminaryKey(quiche::QuicheStringPiece /*key*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500206 QUIC_BUG << "should not be called";
207 return false;
208 }
209
dschinazi17d42422019-06-18 16:35:07 -0700210 bool SetDiversificationNonce(const DiversificationNonce& /*key*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500211 return true;
212 }
213
dschinazi17d42422019-06-18 16:35:07 -0700214 bool DecryptPacket(uint64_t /*packet_number*/,
dmcardlecf0bfcf2019-12-13 08:08:21 -0800215 quiche::QuicheStringPiece /*associated_data*/,
216 quiche::QuicheStringPiece ciphertext,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500217 char* output,
218 size_t* output_length,
dschinazi17d42422019-06-18 16:35:07 -0700219 size_t /*max_output_length*/) override {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500220 if (ciphertext.size() < kTagSize) {
221 return false;
222 }
223 if (!CheckTag(ciphertext, GetTag(ciphertext))) {
224 return false;
225 }
226 *output_length = ciphertext.size() - kTagSize;
227 memcpy(output, ciphertext.data(), *output_length);
228 return true;
229 }
230
QUICHE team2d187972019-03-19 16:23:47 -0700231 std::string GenerateHeaderProtectionMask(
dschinazi17d42422019-06-18 16:35:07 -0700232 QuicDataReader* /*sample_reader*/) override {
QUICHE team2d187972019-03-19 16:23:47 -0700233 return std::string(5, 0);
234 }
235
QUICHE teama6ef0a62019-03-07 20:34:33 -0500236 size_t GetKeySize() const override { return 0; }
nharper965e5922019-09-23 22:33:54 -0700237 size_t GetNoncePrefixSize() const override { return 0; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500238 size_t GetIVSize() const override { return 0; }
dmcardlecf0bfcf2019-12-13 08:08:21 -0800239 quiche::QuicheStringPiece GetKey() const override {
240 return quiche::QuicheStringPiece();
241 }
242 quiche::QuicheStringPiece GetNoncePrefix() const override {
243 return quiche::QuicheStringPiece();
244 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500245 // Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
246 uint32_t cipher_id() const override { return 0xFFFFFFF0; }
247
248 protected:
dmcardlecf0bfcf2019-12-13 08:08:21 -0800249 virtual uint8_t GetTag(quiche::QuicheStringPiece ciphertext) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500250 return ciphertext.data()[ciphertext.size() - 1];
251 }
252
253 private:
254 enum {
255 kTagSize = 12,
256 };
257
dmcardlecf0bfcf2019-12-13 08:08:21 -0800258 bool CheckTag(quiche::QuicheStringPiece ciphertext, uint8_t tag) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500259 for (size_t i = ciphertext.size() - kTagSize; i < ciphertext.size(); i++) {
260 if (ciphertext.data()[i] != tag) {
261 return false;
262 }
263 }
264
265 return true;
266 }
267};
268
269// StringTaggingDecrypter ensures that the final kTagSize bytes of the message
270// match the expected value.
271class StrictTaggingDecrypter : public TaggingDecrypter {
272 public:
273 explicit StrictTaggingDecrypter(uint8_t tag) : tag_(tag) {}
274 ~StrictTaggingDecrypter() override {}
275
276 // TaggingQuicDecrypter
dmcardlecf0bfcf2019-12-13 08:08:21 -0800277 uint8_t GetTag(quiche::QuicheStringPiece /*ciphertext*/) override {
278 return tag_;
279 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500280
281 // Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
282 uint32_t cipher_id() const override { return 0xFFFFFFF1; }
283
284 private:
285 const uint8_t tag_;
286};
287
288class TestConnectionHelper : public QuicConnectionHelperInterface {
289 public:
290 TestConnectionHelper(MockClock* clock, MockRandom* random_generator)
291 : clock_(clock), random_generator_(random_generator) {
292 clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
293 }
294 TestConnectionHelper(const TestConnectionHelper&) = delete;
295 TestConnectionHelper& operator=(const TestConnectionHelper&) = delete;
296
297 // QuicConnectionHelperInterface
298 const QuicClock* GetClock() const override { return clock_; }
299
300 QuicRandom* GetRandomGenerator() override { return random_generator_; }
301
302 QuicBufferAllocator* GetStreamSendBufferAllocator() override {
303 return &buffer_allocator_;
304 }
305
306 private:
307 MockClock* clock_;
308 MockRandom* random_generator_;
309 SimpleBufferAllocator buffer_allocator_;
310};
311
312class TestAlarmFactory : public QuicAlarmFactory {
313 public:
314 class TestAlarm : public QuicAlarm {
315 public:
316 explicit TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate> delegate)
317 : QuicAlarm(std::move(delegate)) {}
318
319 void SetImpl() override {}
320 void CancelImpl() override {}
321 using QuicAlarm::Fire;
322 };
323
324 TestAlarmFactory() {}
325 TestAlarmFactory(const TestAlarmFactory&) = delete;
326 TestAlarmFactory& operator=(const TestAlarmFactory&) = delete;
327
328 QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override {
329 return new TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate>(delegate));
330 }
331
332 QuicArenaScopedPtr<QuicAlarm> CreateAlarm(
333 QuicArenaScopedPtr<QuicAlarm::Delegate> delegate,
334 QuicConnectionArena* arena) override {
335 return arena->New<TestAlarm>(std::move(delegate));
336 }
337};
338
339class TestPacketWriter : public QuicPacketWriter {
wub50d4c712020-05-19 15:48:28 -0700340 struct PacketBuffer {
341 QUIC_CACHELINE_ALIGNED char buffer[1500];
342 bool in_use = false;
343 };
344
QUICHE teama6ef0a62019-03-07 20:34:33 -0500345 public:
346 TestPacketWriter(ParsedQuicVersion version, MockClock* clock)
347 : version_(version),
348 framer_(SupportedVersions(version_), Perspective::IS_SERVER),
wubb442b862020-01-31 08:16:21 -0800349 clock_(clock) {
dschinazib953d022019-08-01 18:05:58 -0700350 QuicFramerPeer::SetLastSerializedServerConnectionId(framer_.framer(),
351 TestConnectionId());
nharperc6b99512019-09-19 11:13:48 -0700352 framer_.framer()->SetInitialObfuscators(TestConnectionId());
wub50d4c712020-05-19 15:48:28 -0700353
354 for (int i = 0; i < 128; ++i) {
355 PacketBuffer* p = new PacketBuffer();
356 packet_buffer_pool_.push_back(p);
357 packet_buffer_pool_index_[p->buffer] = p;
358 packet_buffer_free_list_.push_back(p);
359 }
dschinazib953d022019-08-01 18:05:58 -0700360 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500361 TestPacketWriter(const TestPacketWriter&) = delete;
362 TestPacketWriter& operator=(const TestPacketWriter&) = delete;
363
wub50d4c712020-05-19 15:48:28 -0700364 ~TestPacketWriter() override {
365 EXPECT_EQ(packet_buffer_pool_.size(), packet_buffer_free_list_.size())
366 << packet_buffer_pool_.size() - packet_buffer_free_list_.size()
367 << " out of " << packet_buffer_pool_.size()
368 << " packet buffers have been leaked.";
369 for (auto p : packet_buffer_pool_) {
370 delete p;
371 }
372 }
373
QUICHE teama6ef0a62019-03-07 20:34:33 -0500374 // QuicPacketWriter interface
375 WriteResult WritePacket(const char* buffer,
376 size_t buf_len,
dschinazi17d42422019-06-18 16:35:07 -0700377 const QuicIpAddress& /*self_address*/,
378 const QuicSocketAddress& /*peer_address*/,
379 PerPacketOptions* /*options*/) override {
wub50d4c712020-05-19 15:48:28 -0700380 // If the buffer is allocated from the pool, return it back to the pool.
381 // Note the buffer content doesn't change.
382 if (packet_buffer_pool_index_.find(const_cast<char*>(buffer)) !=
383 packet_buffer_pool_index_.end()) {
384 FreePacketBuffer(buffer);
385 }
386
QUICHE teama6ef0a62019-03-07 20:34:33 -0500387 QuicEncryptedPacket packet(buffer, buf_len);
388 ++packets_write_attempts_;
389
390 if (packet.length() >= sizeof(final_bytes_of_last_packet_)) {
391 final_bytes_of_previous_packet_ = final_bytes_of_last_packet_;
392 memcpy(&final_bytes_of_last_packet_, packet.data() + packet.length() - 4,
393 sizeof(final_bytes_of_last_packet_));
394 }
395
396 if (use_tagging_decrypter_) {
zhongyi546cc452019-04-12 15:27:49 -0700397 if (framer_.framer()->version().KnowsWhichDecrypterToUse()) {
vasilvv0fc587f2019-09-06 13:33:08 -0700398 framer_.framer()->InstallDecrypter(
399 ENCRYPTION_INITIAL, std::make_unique<TaggingDecrypter>());
400 framer_.framer()->InstallDecrypter(
fayang18ff23b2020-01-28 09:19:00 -0800401 ENCRYPTION_HANDSHAKE, std::make_unique<TaggingDecrypter>());
402 framer_.framer()->InstallDecrypter(
vasilvv0fc587f2019-09-06 13:33:08 -0700403 ENCRYPTION_ZERO_RTT, std::make_unique<TaggingDecrypter>());
404 framer_.framer()->InstallDecrypter(
405 ENCRYPTION_FORWARD_SECURE, std::make_unique<TaggingDecrypter>());
zhongyi546cc452019-04-12 15:27:49 -0700406 } else {
407 framer_.framer()->SetDecrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -0700408 std::make_unique<TaggingDecrypter>());
zhongyi546cc452019-04-12 15:27:49 -0700409 }
410 } else if (framer_.framer()->version().KnowsWhichDecrypterToUse()) {
411 framer_.framer()->InstallDecrypter(
412 ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -0700413 std::make_unique<NullDecrypter>(Perspective::IS_SERVER));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500414 }
dschinazi39e5e552020-05-06 13:55:24 -0700415 EXPECT_TRUE(framer_.ProcessPacket(packet))
416 << framer_.framer()->detailed_error();
QUICHE teama6ef0a62019-03-07 20:34:33 -0500417 if (block_on_next_write_) {
418 write_blocked_ = true;
419 block_on_next_write_ = false;
420 }
421 if (next_packet_too_large_) {
422 next_packet_too_large_ = false;
423 return WriteResult(WRITE_STATUS_ERROR, QUIC_EMSGSIZE);
424 }
425 if (always_get_packet_too_large_) {
426 return WriteResult(WRITE_STATUS_ERROR, QUIC_EMSGSIZE);
427 }
428 if (IsWriteBlocked()) {
429 return WriteResult(is_write_blocked_data_buffered_
430 ? WRITE_STATUS_BLOCKED_DATA_BUFFERED
431 : WRITE_STATUS_BLOCKED,
432 0);
433 }
434
435 if (ShouldWriteFail()) {
436 return WriteResult(WRITE_STATUS_ERROR, 0);
437 }
438
439 last_packet_size_ = packet.length();
440 last_packet_header_ = framer_.header();
rchd672c6d2019-11-27 15:30:54 -0800441 if (!framer_.connection_close_frames().empty()) {
442 ++connection_close_packets_;
443 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500444 if (!write_pause_time_delta_.IsZero()) {
445 clock_->AdvanceTime(write_pause_time_delta_);
446 }
wubb442b862020-01-31 08:16:21 -0800447 if (is_batch_mode_) {
448 bytes_buffered_ += last_packet_size_;
449 return WriteResult(WRITE_STATUS_OK, 0);
450 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500451 return WriteResult(WRITE_STATUS_OK, last_packet_size_);
452 }
453
454 bool ShouldWriteFail() { return write_should_fail_; }
455
456 bool IsWriteBlocked() const override { return write_blocked_; }
457
458 void SetWriteBlocked() { write_blocked_ = true; }
459
460 void SetWritable() override { write_blocked_ = false; }
461
462 void SetShouldWriteFail() { write_should_fail_ = true; }
463
464 QuicByteCount GetMaxPacketSize(
465 const QuicSocketAddress& /*peer_address*/) const override {
466 return max_packet_size_;
467 }
468
dschinazi61eb6432019-06-14 16:27:16 -0700469 bool SupportsReleaseTime() const override { return supports_release_time_; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500470
471 bool IsBatchMode() const override { return is_batch_mode_; }
472
wub50d4c712020-05-19 15:48:28 -0700473 QuicPacketBuffer GetNextWriteLocation(
dschinazi17d42422019-06-18 16:35:07 -0700474 const QuicIpAddress& /*self_address*/,
475 const QuicSocketAddress& /*peer_address*/) override {
wub50d4c712020-05-19 15:48:28 -0700476 if (GetQuicReloadableFlag(quic_avoid_leak_writer_buffer)) {
477 return {AllocPacketBuffer(),
478 [this](const char* p) { FreePacketBuffer(p); }};
479 }
480 // Do not use writer buffer for serializing packets.
481 return {nullptr, nullptr};
QUICHE teama6ef0a62019-03-07 20:34:33 -0500482 }
483
484 WriteResult Flush() override {
wubb442b862020-01-31 08:16:21 -0800485 flush_attempts_++;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500486 if (block_on_next_flush_) {
487 block_on_next_flush_ = false;
488 SetWriteBlocked();
489 return WriteResult(WRITE_STATUS_BLOCKED, /*errno*/ -1);
490 }
wub748e20b2020-03-20 14:33:59 -0700491 if (write_should_fail_) {
492 return WriteResult(WRITE_STATUS_ERROR, /*errno*/ -1);
493 }
wubb442b862020-01-31 08:16:21 -0800494 int bytes_flushed = bytes_buffered_;
495 bytes_buffered_ = 0;
496 return WriteResult(WRITE_STATUS_OK, bytes_flushed);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500497 }
498
499 void BlockOnNextFlush() { block_on_next_flush_ = true; }
500
501 void BlockOnNextWrite() { block_on_next_write_ = true; }
502
503 void SimulateNextPacketTooLarge() { next_packet_too_large_ = true; }
504
505 void AlwaysGetPacketTooLarge() { always_get_packet_too_large_ = true; }
506
507 // Sets the amount of time that the writer should before the actual write.
508 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
509 write_pause_time_delta_ = delta;
510 }
511
512 void SetBatchMode(bool new_value) { is_batch_mode_ = new_value; }
513
514 const QuicPacketHeader& header() { return framer_.header(); }
515
516 size_t frame_count() const { return framer_.num_frames(); }
517
518 const std::vector<QuicAckFrame>& ack_frames() const {
519 return framer_.ack_frames();
520 }
521
522 const std::vector<QuicStopWaitingFrame>& stop_waiting_frames() const {
523 return framer_.stop_waiting_frames();
524 }
525
526 const std::vector<QuicConnectionCloseFrame>& connection_close_frames() const {
527 return framer_.connection_close_frames();
528 }
529
530 const std::vector<QuicRstStreamFrame>& rst_stream_frames() const {
531 return framer_.rst_stream_frames();
532 }
533
534 const std::vector<std::unique_ptr<QuicStreamFrame>>& stream_frames() const {
535 return framer_.stream_frames();
536 }
537
538 const std::vector<std::unique_ptr<QuicCryptoFrame>>& crypto_frames() const {
539 return framer_.crypto_frames();
540 }
541
542 const std::vector<QuicPingFrame>& ping_frames() const {
543 return framer_.ping_frames();
544 }
545
546 const std::vector<QuicMessageFrame>& message_frames() const {
547 return framer_.message_frames();
548 }
549
550 const std::vector<QuicWindowUpdateFrame>& window_update_frames() const {
551 return framer_.window_update_frames();
552 }
553
554 const std::vector<QuicPaddingFrame>& padding_frames() const {
555 return framer_.padding_frames();
556 }
557
558 const std::vector<QuicPathChallengeFrame>& path_challenge_frames() const {
559 return framer_.path_challenge_frames();
560 }
561
562 const std::vector<QuicPathResponseFrame>& path_response_frames() const {
563 return framer_.path_response_frames();
564 }
565
fayang58f71072019-11-05 08:47:02 -0800566 const QuicEncryptedPacket* coalesced_packet() const {
567 return framer_.coalesced_packet();
568 }
569
QUICHE teama6ef0a62019-03-07 20:34:33 -0500570 size_t last_packet_size() { return last_packet_size_; }
571
572 const QuicPacketHeader& last_packet_header() const {
573 return last_packet_header_;
574 }
575
576 const QuicVersionNegotiationPacket* version_negotiation_packet() {
577 return framer_.version_negotiation_packet();
578 }
579
580 void set_is_write_blocked_data_buffered(bool buffered) {
581 is_write_blocked_data_buffered_ = buffered;
582 }
583
584 void set_perspective(Perspective perspective) {
585 // We invert perspective here, because the framer needs to parse packets
586 // we send.
587 QuicFramerPeer::SetPerspective(framer_.framer(),
nharper4eba09b2019-06-26 20:17:25 -0700588 QuicUtils::InvertPerspective(perspective));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500589 }
590
591 // final_bytes_of_last_packet_ returns the last four bytes of the previous
592 // packet as a little-endian, uint32_t. This is intended to be used with a
593 // TaggingEncrypter so that tests can determine which encrypter was used for
594 // a given packet.
595 uint32_t final_bytes_of_last_packet() { return final_bytes_of_last_packet_; }
596
597 // Returns the final bytes of the second to last packet.
598 uint32_t final_bytes_of_previous_packet() {
599 return final_bytes_of_previous_packet_;
600 }
601
602 void use_tagging_decrypter() { use_tagging_decrypter_ = true; }
603
wubb442b862020-01-31 08:16:21 -0800604 uint32_t packets_write_attempts() const { return packets_write_attempts_; }
605
606 uint32_t flush_attempts() const { return flush_attempts_; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500607
rchd672c6d2019-11-27 15:30:54 -0800608 uint32_t connection_close_packets() const {
609 return connection_close_packets_;
610 }
611
QUICHE teama6ef0a62019-03-07 20:34:33 -0500612 void Reset() { framer_.Reset(); }
613
614 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
615 framer_.SetSupportedVersions(versions);
616 }
617
618 void set_max_packet_size(QuicByteCount max_packet_size) {
619 max_packet_size_ = max_packet_size;
620 }
621
622 void set_supports_release_time(bool supports_release_time) {
623 supports_release_time_ = supports_release_time;
624 }
625
626 SimpleQuicFramer* framer() { return &framer_; }
627
628 private:
wub50d4c712020-05-19 15:48:28 -0700629 char* AllocPacketBuffer() {
630 PacketBuffer* p = packet_buffer_free_list_.front();
631 EXPECT_FALSE(p->in_use);
632 p->in_use = true;
633 packet_buffer_free_list_.pop_front();
634 return p->buffer;
635 }
636
637 void FreePacketBuffer(const char* buffer) {
638 auto iter = packet_buffer_pool_index_.find(const_cast<char*>(buffer));
639 ASSERT_TRUE(iter != packet_buffer_pool_index_.end());
640 PacketBuffer* p = iter->second;
641 ASSERT_TRUE(p->in_use);
642 p->in_use = false;
643 packet_buffer_free_list_.push_back(p);
644 }
645
QUICHE teama6ef0a62019-03-07 20:34:33 -0500646 ParsedQuicVersion version_;
647 SimpleQuicFramer framer_;
wubb442b862020-01-31 08:16:21 -0800648 size_t last_packet_size_ = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500649 QuicPacketHeader last_packet_header_;
wubb442b862020-01-31 08:16:21 -0800650 bool write_blocked_ = false;
651 bool write_should_fail_ = false;
652 bool block_on_next_flush_ = false;
653 bool block_on_next_write_ = false;
654 bool next_packet_too_large_ = false;
655 bool always_get_packet_too_large_ = false;
656 bool is_write_blocked_data_buffered_ = false;
657 bool is_batch_mode_ = false;
658 // Number of times Flush() was called.
659 uint32_t flush_attempts_ = 0;
660 // (Batch mode only) Number of bytes buffered in writer. It is used as the
661 // return value of a successful Flush().
662 uint32_t bytes_buffered_ = 0;
663 uint32_t final_bytes_of_last_packet_ = 0;
664 uint32_t final_bytes_of_previous_packet_ = 0;
665 bool use_tagging_decrypter_ = false;
666 uint32_t packets_write_attempts_ = 0;
667 uint32_t connection_close_packets_ = 0;
668 MockClock* clock_ = nullptr;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500669 // If non-zero, the clock will pause during WritePacket for this amount of
670 // time.
wubb442b862020-01-31 08:16:21 -0800671 QuicTime::Delta write_pause_time_delta_ = QuicTime::Delta::Zero();
672 QuicByteCount max_packet_size_ = kMaxOutgoingPacketSize;
673 bool supports_release_time_ = false;
wub50d4c712020-05-19 15:48:28 -0700674 // Used to verify writer-allocated packet buffers are properly released.
675 std::vector<PacketBuffer*> packet_buffer_pool_;
676 // Buffer address => Address of the owning PacketBuffer.
677 QuicHashMap<char*, PacketBuffer*> packet_buffer_pool_index_;
678 // Indices in packet_buffer_pool_ that are not allocated.
679 std::list<PacketBuffer*> packet_buffer_free_list_;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500680};
681
682class TestConnection : public QuicConnection {
683 public:
684 TestConnection(QuicConnectionId connection_id,
685 QuicSocketAddress address,
686 TestConnectionHelper* helper,
687 TestAlarmFactory* alarm_factory,
688 TestPacketWriter* writer,
689 Perspective perspective,
690 ParsedQuicVersion version)
691 : QuicConnection(connection_id,
692 address,
693 helper,
694 alarm_factory,
695 writer,
696 /* owns_writer= */ false,
697 perspective,
698 SupportedVersions(version)),
699 notifier_(nullptr) {
700 writer->set_perspective(perspective);
701 SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -0700702 std::make_unique<NullEncrypter>(perspective));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500703 SetDataProducer(&producer_);
704 }
705 TestConnection(const TestConnection&) = delete;
706 TestConnection& operator=(const TestConnection&) = delete;
707
QUICHE teama6ef0a62019-03-07 20:34:33 -0500708 void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
709 QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
710 }
711
712 void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
713 QuicConnectionPeer::SetLossAlgorithm(this, loss_algorithm);
714 }
715
dschinazi17d42422019-06-18 16:35:07 -0700716 void SendPacket(EncryptionLevel /*level*/,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500717 uint64_t packet_number,
718 std::unique_ptr<QuicPacket> packet,
719 HasRetransmittableData retransmittable,
720 bool has_ack,
721 bool has_pending_frames) {
fayang58f71072019-11-05 08:47:02 -0800722 ScopedPacketFlusher flusher(this);
dschinazi66dea072019-04-09 11:41:06 -0700723 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -0500724 size_t encrypted_length =
725 QuicConnectionPeer::GetFramer(this)->EncryptPayload(
QUICHE team6987b4a2019-03-15 16:23:04 -0700726 ENCRYPTION_INITIAL, QuicPacketNumber(packet_number), *packet,
dschinazi66dea072019-04-09 11:41:06 -0700727 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500728 SerializedPacket serialized_packet(
729 QuicPacketNumber(packet_number), PACKET_4BYTE_PACKET_NUMBER, buffer,
730 encrypted_length, has_ack, has_pending_frames);
731 if (retransmittable == HAS_RETRANSMITTABLE_DATA) {
732 serialized_packet.retransmittable_frames.push_back(
fayang58f71072019-11-05 08:47:02 -0800733 QuicFrame(QuicPingFrame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500734 }
wub8a5dafa2020-05-13 12:30:17 -0700735 OnSerializedPacket(std::move(serialized_packet));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500736 }
737
738 QuicConsumedData SaveAndSendStreamData(QuicStreamId id,
739 const struct iovec* iov,
740 int iov_count,
741 size_t total_length,
742 QuicStreamOffset offset,
743 StreamSendingState state) {
fayanga4b37b22019-06-18 13:37:47 -0700744 ScopedPacketFlusher flusher(this);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500745 producer_.SaveStreamData(id, iov, iov_count, 0u, total_length);
746 if (notifier_ != nullptr) {
747 return notifier_->WriteOrBufferData(id, total_length, state);
748 }
749 return QuicConnection::SendStreamData(id, total_length, offset, state);
750 }
751
752 QuicConsumedData SendStreamDataWithString(QuicStreamId id,
dmcardlecf0bfcf2019-12-13 08:08:21 -0800753 quiche::QuicheStringPiece data,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500754 QuicStreamOffset offset,
755 StreamSendingState state) {
fayanga4b37b22019-06-18 13:37:47 -0700756 ScopedPacketFlusher flusher(this);
nharper46833c32019-05-15 21:33:05 -0700757 if (!QuicUtils::IsCryptoStreamId(transport_version(), id) &&
QUICHE team6987b4a2019-03-15 16:23:04 -0700758 this->encryption_level() == ENCRYPTION_INITIAL) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500759 this->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
fayangfa3b1d62019-11-18 08:02:13 -0800760 if (perspective() == Perspective::IS_CLIENT && !IsHandshakeComplete()) {
fayang5f135052019-08-22 17:59:40 -0700761 OnHandshakeComplete();
762 }
763 if (version().SupportsAntiAmplificationLimit()) {
764 QuicConnectionPeer::SetAddressValidated(this);
765 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500766 }
767 struct iovec iov;
768 MakeIOVector(data, &iov);
769 return SaveAndSendStreamData(id, &iov, 1, data.length(), offset, state);
770 }
771
QUICHE teamcd098022019-03-22 18:49:55 -0700772 QuicConsumedData SendApplicationDataAtLevel(EncryptionLevel encryption_level,
773 QuicStreamId id,
dmcardlecf0bfcf2019-12-13 08:08:21 -0800774 quiche::QuicheStringPiece data,
QUICHE teamcd098022019-03-22 18:49:55 -0700775 QuicStreamOffset offset,
776 StreamSendingState state) {
fayanga4b37b22019-06-18 13:37:47 -0700777 ScopedPacketFlusher flusher(this);
QUICHE teamcd098022019-03-22 18:49:55 -0700778 DCHECK(encryption_level >= ENCRYPTION_ZERO_RTT);
vasilvv0fc587f2019-09-06 13:33:08 -0700779 SetEncrypter(encryption_level, std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -0700780 SetDefaultEncryptionLevel(encryption_level);
781 struct iovec iov;
782 MakeIOVector(data, &iov);
783 return SaveAndSendStreamData(id, &iov, 1, data.length(), offset, state);
784 }
785
QUICHE teama6ef0a62019-03-07 20:34:33 -0500786 QuicConsumedData SendStreamData3() {
787 return SendStreamDataWithString(
788 GetNthClientInitiatedStreamId(1, transport_version()), "food", 0,
789 NO_FIN);
790 }
791
792 QuicConsumedData SendStreamData5() {
793 return SendStreamDataWithString(
794 GetNthClientInitiatedStreamId(2, transport_version()), "food2", 0,
795 NO_FIN);
796 }
797
798 // Ensures the connection can write stream data before writing.
799 QuicConsumedData EnsureWritableAndSendStreamData5() {
ianswettfc16a2b2020-05-18 16:05:49 -0700800 EXPECT_TRUE(CanWrite(HAS_RETRANSMITTABLE_DATA));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500801 return SendStreamData5();
802 }
803
804 // The crypto stream has special semantics so that it is not blocked by a
805 // congestion window limitation, and also so that it gets put into a separate
806 // packet (so that it is easier to reason about a crypto frame not being
807 // split needlessly across packet boundaries). As a result, we have separate
808 // tests for some cases for this stream.
809 QuicConsumedData SendCryptoStreamData() {
810 QuicStreamOffset offset = 0;
dmcardlecf0bfcf2019-12-13 08:08:21 -0800811 quiche::QuicheStringPiece data("chlo");
fayang2ce66082019-10-02 06:29:04 -0700812 if (!QuicVersionUsesCryptoFrames(transport_version())) {
813 return SendCryptoDataWithString(data, offset);
814 }
815 producer_.SaveCryptoData(ENCRYPTION_INITIAL, offset, data);
816 size_t bytes_written;
817 if (notifier_) {
818 bytes_written =
819 notifier_->WriteCryptoData(ENCRYPTION_INITIAL, data.length(), offset);
820 } else {
821 bytes_written = QuicConnection::SendCryptoData(ENCRYPTION_INITIAL,
822 data.length(), offset);
823 }
824 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
nharper46833c32019-05-15 21:33:05 -0700825 }
826
dmcardlecf0bfcf2019-12-13 08:08:21 -0800827 QuicConsumedData SendCryptoDataWithString(quiche::QuicheStringPiece data,
nharper46833c32019-05-15 21:33:05 -0700828 QuicStreamOffset offset) {
fayang18ff23b2020-01-28 09:19:00 -0800829 return SendCryptoDataWithString(data, offset, ENCRYPTION_INITIAL);
830 }
831
832 QuicConsumedData SendCryptoDataWithString(quiche::QuicheStringPiece data,
833 QuicStreamOffset offset,
834 EncryptionLevel encryption_level) {
QUICHE teamea740082019-03-11 17:58:43 -0700835 if (!QuicVersionUsesCryptoFrames(transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500836 return SendStreamDataWithString(
837 QuicUtils::GetCryptoStreamId(transport_version()), data, offset,
838 NO_FIN);
839 }
fayang18ff23b2020-01-28 09:19:00 -0800840 producer_.SaveCryptoData(encryption_level, offset, data);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500841 size_t bytes_written;
842 if (notifier_) {
843 bytes_written =
fayang18ff23b2020-01-28 09:19:00 -0800844 notifier_->WriteCryptoData(encryption_level, data.length(), offset);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500845 } else {
fayang18ff23b2020-01-28 09:19:00 -0800846 bytes_written = QuicConnection::SendCryptoData(encryption_level,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500847 data.length(), offset);
848 }
849 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
850 }
851
852 void set_version(ParsedQuicVersion version) {
853 QuicConnectionPeer::GetFramer(this)->set_version(version);
854 }
855
856 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
857 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500858 writer()->SetSupportedVersions(versions);
859 }
860
861 void set_perspective(Perspective perspective) {
862 writer()->set_perspective(perspective);
863 QuicConnectionPeer::SetPerspective(this, perspective);
864 }
865
866 // Enable path MTU discovery. Assumes that the test is performed from the
wub031d47c2019-11-21 08:04:07 -0800867 // server perspective and the higher value of MTU target is used.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500868 void EnablePathMtuDiscovery(MockSendAlgorithm* send_algorithm) {
wub031d47c2019-11-21 08:04:07 -0800869 ASSERT_EQ(Perspective::IS_SERVER, perspective());
QUICHE teama6ef0a62019-03-07 20:34:33 -0500870
871 QuicConfig config;
872 QuicTagVector connection_options;
873 connection_options.push_back(kMTUH);
wub031d47c2019-11-21 08:04:07 -0800874 config.SetInitialReceivedConnectionOptions(connection_options);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500875 EXPECT_CALL(*send_algorithm, SetFromConfig(_, _));
876 SetFromConfig(config);
877
878 // Normally, the pacing would be disabled in the test, but calling
879 // SetFromConfig enables it. Set nearly-infinite bandwidth to make the
880 // pacing algorithm work.
881 EXPECT_CALL(*send_algorithm, PacingRate(_))
882 .WillRepeatedly(Return(QuicBandwidth::Infinite()));
883 }
884
885 TestAlarmFactory::TestAlarm* GetAckAlarm() {
886 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
887 QuicConnectionPeer::GetAckAlarm(this));
888 }
889
890 TestAlarmFactory::TestAlarm* GetPingAlarm() {
891 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
892 QuicConnectionPeer::GetPingAlarm(this));
893 }
894
895 TestAlarmFactory::TestAlarm* GetRetransmissionAlarm() {
896 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
897 QuicConnectionPeer::GetRetransmissionAlarm(this));
898 }
899
900 TestAlarmFactory::TestAlarm* GetSendAlarm() {
901 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
902 QuicConnectionPeer::GetSendAlarm(this));
903 }
904
905 TestAlarmFactory::TestAlarm* GetTimeoutAlarm() {
906 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
fayang3a58dc42020-06-29 11:27:14 -0700907 QuicConnectionPeer::GetIdleNetworkDetectorAlarm(this));
QUICHE teama6ef0a62019-03-07 20:34:33 -0500908 }
909
910 TestAlarmFactory::TestAlarm* GetMtuDiscoveryAlarm() {
911 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
912 QuicConnectionPeer::GetMtuDiscoveryAlarm(this));
913 }
914
QUICHE teama6ef0a62019-03-07 20:34:33 -0500915 TestAlarmFactory::TestAlarm* GetProcessUndecryptablePacketsAlarm() {
916 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
917 QuicConnectionPeer::GetProcessUndecryptablePacketsAlarm(this));
918 }
919
fayangb59c6f12020-03-23 15:06:14 -0700920 TestAlarmFactory::TestAlarm* GetBlackholeDetectorAlarm() {
fayangb59c6f12020-03-23 15:06:14 -0700921 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
922 QuicConnectionPeer::GetBlackholeDetectorAlarm(this));
923 }
924
925 void PathDegradingTimeout() {
926 DCHECK(PathDegradingDetectionInProgress());
fayang2205d952020-05-12 13:45:56 -0700927 GetBlackholeDetectorAlarm()->Fire();
fayangb59c6f12020-03-23 15:06:14 -0700928 }
929
930 bool PathDegradingDetectionInProgress() {
fayang2205d952020-05-12 13:45:56 -0700931 return QuicConnectionPeer::GetPathDegradingDeadline(this).IsInitialized();
fayangb59c6f12020-03-23 15:06:14 -0700932 }
933
934 bool BlackholeDetectionInProgress() {
fayangb59c6f12020-03-23 15:06:14 -0700935 return QuicConnectionPeer::GetBlackholeDetectionDeadline(this)
936 .IsInitialized();
937 }
938
QUICHE teama6ef0a62019-03-07 20:34:33 -0500939 void SetMaxTailLossProbes(size_t max_tail_loss_probes) {
940 QuicSentPacketManagerPeer::SetMaxTailLossProbes(
941 QuicConnectionPeer::GetSentPacketManager(this), max_tail_loss_probes);
942 }
943
944 QuicByteCount GetBytesInFlight() {
ianswett9f459cb2019-04-21 06:39:59 -0700945 return QuicConnectionPeer::GetSentPacketManager(this)->GetBytesInFlight();
QUICHE teama6ef0a62019-03-07 20:34:33 -0500946 }
947
948 void set_notifier(SimpleSessionNotifier* notifier) { notifier_ = notifier; }
949
950 void ReturnEffectivePeerAddressForNextPacket(const QuicSocketAddress& addr) {
vasilvv0fc587f2019-09-06 13:33:08 -0700951 next_effective_peer_addr_ = std::make_unique<QuicSocketAddress>(addr);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500952 }
953
fayang5f135052019-08-22 17:59:40 -0700954 bool PtoEnabled() {
955 if (QuicConnectionPeer::GetSentPacketManager(this)->pto_enabled()) {
956 // PTO mode is default enabled for T099. And TLP/RTO related tests are
957 // stale.
fayang5d011982020-05-13 14:14:38 -0700958 DCHECK(PROTOCOL_TLS1_3 == version().handshake_protocol ||
959 GetQuicReloadableFlag(quic_default_on_pto));
fayang5f135052019-08-22 17:59:40 -0700960 return true;
961 }
962 return false;
963 }
964
nharper46833c32019-05-15 21:33:05 -0700965 SimpleDataProducer* producer() { return &producer_; }
966
QUICHE teama6ef0a62019-03-07 20:34:33 -0500967 using QuicConnection::active_effective_peer_migration_type;
968 using QuicConnection::IsCurrentPacketConnectivityProbing;
969 using QuicConnection::SelectMutualVersion;
970 using QuicConnection::SendProbingRetransmissions;
971 using QuicConnection::set_defer_send_in_response_to_packets;
972
973 protected:
974 QuicSocketAddress GetEffectivePeerAddressFromCurrentPacket() const override {
975 if (next_effective_peer_addr_) {
976 return *std::move(next_effective_peer_addr_);
977 }
978 return QuicConnection::GetEffectivePeerAddressFromCurrentPacket();
979 }
980
981 private:
982 TestPacketWriter* writer() {
983 return static_cast<TestPacketWriter*>(QuicConnection::writer());
984 }
985
986 SimpleDataProducer producer_;
987
988 SimpleSessionNotifier* notifier_;
989
990 std::unique_ptr<QuicSocketAddress> next_effective_peer_addr_;
991};
992
993enum class AckResponse { kDefer, kImmediate };
994
995// Run tests with combinations of {ParsedQuicVersion, AckResponse}.
996struct TestParams {
997 TestParams(ParsedQuicVersion version,
998 AckResponse ack_response,
999 bool no_stop_waiting)
1000 : version(version),
1001 ack_response(ack_response),
1002 no_stop_waiting(no_stop_waiting) {}
1003
QUICHE teama6ef0a62019-03-07 20:34:33 -05001004 ParsedQuicVersion version;
1005 AckResponse ack_response;
1006 bool no_stop_waiting;
1007};
1008
dschinazi142051a2019-09-18 18:17:29 -07001009// Used by ::testing::PrintToStringParamName().
1010std::string PrintToString(const TestParams& p) {
dmcardlecf0bfcf2019-12-13 08:08:21 -08001011 return quiche::QuicheStrCat(
dschinazi142051a2019-09-18 18:17:29 -07001012 ParsedQuicVersionToString(p.version), "_",
1013 (p.ack_response == AckResponse::kDefer ? "defer" : "immediate"), "_",
1014 (p.no_stop_waiting ? "No" : ""), "StopWaiting");
1015}
1016
QUICHE teama6ef0a62019-03-07 20:34:33 -05001017// Constructs various test permutations.
1018std::vector<TestParams> GetTestParams() {
1019 QuicFlagSaver flags;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001020 std::vector<TestParams> params;
1021 ParsedQuicVersionVector all_supported_versions = AllSupportedVersions();
1022 for (size_t i = 0; i < all_supported_versions.size(); ++i) {
1023 for (AckResponse ack_response :
1024 {AckResponse::kDefer, AckResponse::kImmediate}) {
dschinazi142051a2019-09-18 18:17:29 -07001025 params.push_back(
1026 TestParams(all_supported_versions[i], ack_response, true));
1027 if (!VersionHasIetfInvariantHeader(
1028 all_supported_versions[i].transport_version)) {
fayangd4291e42019-05-30 10:31:21 -07001029 params.push_back(
dschinazi142051a2019-09-18 18:17:29 -07001030 TestParams(all_supported_versions[i], ack_response, false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001031 }
1032 }
1033 }
1034 return params;
1035}
1036
1037class QuicConnectionTest : public QuicTestWithParam<TestParams> {
fkastenholz5d880a92019-06-21 09:01:56 -07001038 public:
1039 // For tests that do silent connection closes, no such packet is generated. In
1040 // order to verify the contents of the OnConnectionClosed upcall, EXPECTs
1041 // should invoke this method, saving the frame, and then the test can verify
1042 // the contents.
1043 void SaveConnectionCloseFrame(const QuicConnectionCloseFrame& frame,
1044 ConnectionCloseSource /*source*/) {
1045 saved_connection_close_frame_ = frame;
1046 connection_close_frame_count_++;
1047 }
1048
QUICHE teama6ef0a62019-03-07 20:34:33 -05001049 protected:
1050 QuicConnectionTest()
1051 : connection_id_(TestConnectionId()),
1052 framer_(SupportedVersions(version()),
1053 QuicTime::Zero(),
1054 Perspective::IS_CLIENT,
1055 connection_id_.length()),
1056 send_algorithm_(new StrictMock<MockSendAlgorithm>),
1057 loss_algorithm_(new MockLossAlgorithm()),
1058 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
1059 alarm_factory_(new TestAlarmFactory()),
1060 peer_framer_(SupportedVersions(version()),
1061 QuicTime::Zero(),
1062 Perspective::IS_SERVER,
1063 connection_id_.length()),
1064 peer_creator_(connection_id_,
1065 &peer_framer_,
1066 /*delegate=*/nullptr),
1067 writer_(new TestPacketWriter(version(), &clock_)),
1068 connection_(connection_id_,
1069 kPeerAddress,
1070 helper_.get(),
1071 alarm_factory_.get(),
1072 writer_.get(),
1073 Perspective::IS_CLIENT,
1074 version()),
1075 creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
QUICHE teama6ef0a62019-03-07 20:34:33 -05001076 manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
dmcardlecf0bfcf2019-12-13 08:08:21 -08001077 frame1_(0, false, 0, quiche::QuicheStringPiece(data1)),
1078 frame2_(0, false, 3, quiche::QuicheStringPiece(data2)),
1079 crypto_frame_(ENCRYPTION_INITIAL, 0, quiche::QuicheStringPiece(data1)),
QUICHE teama6ef0a62019-03-07 20:34:33 -05001080 packet_number_length_(PACKET_4BYTE_PACKET_NUMBER),
1081 connection_id_included_(CONNECTION_ID_PRESENT),
fkastenholz5d880a92019-06-21 09:01:56 -07001082 notifier_(&connection_),
1083 connection_close_frame_count_(0) {
dschinazi142051a2019-09-18 18:17:29 -07001084 QUIC_DVLOG(2) << "QuicConnectionTest(" << PrintToString(GetParam()) << ")";
QUICHE teama6ef0a62019-03-07 20:34:33 -05001085 connection_.set_defer_send_in_response_to_packets(GetParam().ack_response ==
1086 AckResponse::kDefer);
nharperc6b99512019-09-19 11:13:48 -07001087 framer_.SetInitialObfuscators(TestConnectionId());
1088 connection_.InstallInitialCrypters(TestConnectionId());
1089 CrypterPair crypters;
1090 CryptoUtils::CreateInitialObfuscators(Perspective::IS_SERVER, version(),
1091 TestConnectionId(), &crypters);
1092 peer_creator_.SetEncrypter(ENCRYPTION_INITIAL,
1093 std::move(crypters.encrypter));
1094 if (version().KnowsWhichDecrypterToUse()) {
1095 peer_framer_.InstallDecrypter(ENCRYPTION_INITIAL,
1096 std::move(crypters.decrypter));
1097 } else {
1098 peer_framer_.SetDecrypter(ENCRYPTION_INITIAL,
1099 std::move(crypters.decrypter));
1100 }
nharper2c9f02a2019-05-08 10:25:50 -07001101 for (EncryptionLevel level :
1102 {ENCRYPTION_ZERO_RTT, ENCRYPTION_FORWARD_SECURE}) {
1103 peer_creator_.SetEncrypter(
vasilvv0fc587f2019-09-06 13:33:08 -07001104 level, std::make_unique<NullEncrypter>(peer_framer_.perspective()));
nharper2c9f02a2019-05-08 10:25:50 -07001105 }
dschinazi7b9278c2019-05-20 07:36:21 -07001106 QuicFramerPeer::SetLastSerializedServerConnectionId(
QUICHE teama6ef0a62019-03-07 20:34:33 -05001107 QuicConnectionPeer::GetFramer(&connection_), connection_id_);
nharperc6b99512019-09-19 11:13:48 -07001108 QuicFramerPeer::SetLastWrittenPacketNumberLength(
1109 QuicConnectionPeer::GetFramer(&connection_), packet_number_length_);
fayangd4291e42019-05-30 10:31:21 -07001110 if (VersionHasIetfInvariantHeader(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001111 EXPECT_TRUE(QuicConnectionPeer::GetNoStopWaitingFrames(&connection_));
1112 } else {
1113 QuicConnectionPeer::SetNoStopWaitingFrames(&connection_,
1114 GetParam().no_stop_waiting);
1115 }
nharper46833c32019-05-15 21:33:05 -07001116 QuicStreamId stream_id;
1117 if (QuicVersionUsesCryptoFrames(version().transport_version)) {
1118 stream_id = QuicUtils::GetFirstBidirectionalStreamId(
1119 version().transport_version, Perspective::IS_CLIENT);
1120 } else {
1121 stream_id = QuicUtils::GetCryptoStreamId(version().transport_version);
1122 }
1123 frame1_.stream_id = stream_id;
1124 frame2_.stream_id = stream_id;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001125 connection_.set_visitor(&visitor_);
fayangcff885a2019-10-22 07:39:04 -07001126 connection_.SetSessionNotifier(&notifier_);
1127 connection_.set_notifier(&notifier_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001128 connection_.SetSendAlgorithm(send_algorithm_);
1129 connection_.SetLossAlgorithm(loss_algorithm_.get());
1130 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
1131 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1132 .Times(AnyNumber());
wubf4ab9652020-02-20 14:45:43 -08001133 EXPECT_CALL(*send_algorithm_, OnPacketNeutered(_)).Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001134 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
1135 .WillRepeatedly(Return(kDefaultTCPMSS));
1136 EXPECT_CALL(*send_algorithm_, PacingRate(_))
1137 .WillRepeatedly(Return(QuicBandwidth::Zero()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001138 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
1139 .Times(AnyNumber())
1140 .WillRepeatedly(Return(QuicBandwidth::Zero()));
wub5cd49592019-11-25 15:17:13 -08001141 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_))
1142 .Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001143 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
1144 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
1145 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
1146 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).Times(AnyNumber());
fayangd58736d2019-11-27 13:35:31 -08001147 EXPECT_CALL(visitor_, OnPacketDecrypted(_)).Times(AnyNumber());
fayangcff885a2019-10-22 07:39:04 -07001148 EXPECT_CALL(visitor_, OnCanWrite())
1149 .WillRepeatedly(Invoke(&notifier_, &SimpleSessionNotifier::OnCanWrite));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001150 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
1151 .WillRepeatedly(Return(false));
1152 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
zhongyi83161e42019-08-19 09:06:25 -07001153 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(AnyNumber());
wub256b2d62019-11-25 08:46:55 -08001154 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
fayang2f2915d2020-01-24 06:47:15 -08001155 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged())
1156 .Times(testing::AtMost(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001157 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
1158 .WillRepeatedly(Return(QuicTime::Zero()));
1159 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
1160 .Times(AnyNumber());
fayang5014e922020-01-22 12:28:11 -08001161 EXPECT_CALL(visitor_, GetHandshakeState())
1162 .WillRepeatedly(Return(HANDSHAKE_START));
zhongyi546cc452019-04-12 15:27:49 -07001163 if (connection_.version().KnowsWhichDecrypterToUse()) {
1164 connection_.InstallDecrypter(
1165 ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07001166 std::make_unique<NullDecrypter>(Perspective::IS_CLIENT));
zhongyi546cc452019-04-12 15:27:49 -07001167 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001168 }
1169
1170 QuicConnectionTest(const QuicConnectionTest&) = delete;
1171 QuicConnectionTest& operator=(const QuicConnectionTest&) = delete;
1172
1173 ParsedQuicVersion version() { return GetParam().version; }
1174
QUICHE teama6ef0a62019-03-07 20:34:33 -05001175 QuicStopWaitingFrame* stop_waiting() {
1176 QuicConnectionPeer::PopulateStopWaitingFrame(&connection_, &stop_waiting_);
1177 return &stop_waiting_;
1178 }
1179
1180 QuicPacketNumber least_unacked() {
1181 if (writer_->stop_waiting_frames().empty()) {
1182 return QuicPacketNumber();
1183 }
1184 return writer_->stop_waiting_frames()[0].least_unacked;
1185 }
1186
1187 void use_tagging_decrypter() { writer_->use_tagging_decrypter(); }
1188
zhongyi546cc452019-04-12 15:27:49 -07001189 void SetDecrypter(EncryptionLevel level,
1190 std::unique_ptr<QuicDecrypter> decrypter) {
1191 if (connection_.version().KnowsWhichDecrypterToUse()) {
1192 connection_.InstallDecrypter(level, std::move(decrypter));
1193 connection_.RemoveDecrypter(ENCRYPTION_INITIAL);
1194 } else {
1195 connection_.SetDecrypter(level, std::move(decrypter));
1196 }
1197 }
1198
QUICHE teama6ef0a62019-03-07 20:34:33 -05001199 void ProcessPacket(uint64_t number) {
1200 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
1201 ProcessDataPacket(number);
1202 if (connection_.GetSendAlarm()->IsSet()) {
1203 connection_.GetSendAlarm()->Fire();
1204 }
1205 }
1206
1207 void ProcessReceivedPacket(const QuicSocketAddress& self_address,
1208 const QuicSocketAddress& peer_address,
1209 const QuicReceivedPacket& packet) {
1210 connection_.ProcessUdpPacket(self_address, peer_address, packet);
1211 if (connection_.GetSendAlarm()->IsSet()) {
1212 connection_.GetSendAlarm()->Fire();
1213 }
1214 }
1215
wub8a5dafa2020-05-13 12:30:17 -07001216 QuicFrame MakeCryptoFrame() const {
1217 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1218 return QuicFrame(new QuicCryptoFrame(crypto_frame_));
1219 }
1220 return QuicFrame(QuicStreamFrame(
1221 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
1222 0u, quiche::QuicheStringPiece()));
1223 }
1224
QUICHE teama6ef0a62019-03-07 20:34:33 -05001225 void ProcessFramePacket(QuicFrame frame) {
1226 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress);
1227 }
1228
1229 void ProcessFramePacketWithAddresses(QuicFrame frame,
1230 QuicSocketAddress self_address,
1231 QuicSocketAddress peer_address) {
1232 QuicFrames frames;
1233 frames.push_back(QuicFrame(frame));
zhongyif06ca342020-02-24 14:11:13 -08001234 return ProcessFramesPacketWithAddresses(frames, self_address, peer_address);
1235 }
1236
1237 void ProcessFramesPacketWithAddresses(QuicFrames frames,
1238 QuicSocketAddress self_address,
1239 QuicSocketAddress peer_address) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001240 QuicPacketCreatorPeer::SetSendVersionInPacket(
wub031d47c2019-11-21 08:04:07 -08001241 &peer_creator_,
1242 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_) <
1243 ENCRYPTION_FORWARD_SECURE &&
1244 connection_.perspective() == Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001245
dschinazi66dea072019-04-09 11:41:06 -07001246 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001247 SerializedPacket serialized_packet =
dschinazi66dea072019-04-09 11:41:06 -07001248 QuicPacketCreatorPeer::SerializeAllFrames(
1249 &peer_creator_, frames, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001250 connection_.ProcessUdpPacket(
1251 self_address, peer_address,
1252 QuicReceivedPacket(serialized_packet.encrypted_buffer,
1253 serialized_packet.encrypted_length, clock_.Now()));
1254 if (connection_.GetSendAlarm()->IsSet()) {
1255 connection_.GetSendAlarm()->Fire();
1256 }
1257 }
1258
1259 // Bypassing the packet creator is unrealistic, but allows us to process
1260 // packets the QuicPacketCreator won't allow us to create.
1261 void ForceProcessFramePacket(QuicFrame frame) {
1262 QuicFrames frames;
1263 frames.push_back(QuicFrame(frame));
zhongyi546cc452019-04-12 15:27:49 -07001264 bool send_version = connection_.perspective() == Perspective::IS_SERVER;
1265 if (connection_.version().KnowsWhichDecrypterToUse()) {
1266 send_version = true;
1267 }
1268 QuicPacketCreatorPeer::SetSendVersionInPacket(&peer_creator_, send_version);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001269 QuicPacketHeader header;
1270 QuicPacketCreatorPeer::FillPacketHeader(&peer_creator_, &header);
dschinazi66dea072019-04-09 11:41:06 -07001271 char encrypted_buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05001272 size_t length = peer_framer_.BuildDataPacket(
dschinazi66dea072019-04-09 11:41:06 -07001273 header, frames, encrypted_buffer, kMaxOutgoingPacketSize,
1274 ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001275 DCHECK_GT(length, 0u);
1276
1277 const size_t encrypted_length = peer_framer_.EncryptInPlace(
QUICHE team6987b4a2019-03-15 16:23:04 -07001278 ENCRYPTION_INITIAL, header.packet_number,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001279 GetStartOfEncryptedData(peer_framer_.version().transport_version,
1280 header),
dschinazi66dea072019-04-09 11:41:06 -07001281 length, kMaxOutgoingPacketSize, encrypted_buffer);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001282 DCHECK_GT(encrypted_length, 0u);
1283
1284 connection_.ProcessUdpPacket(
1285 kSelfAddress, kPeerAddress,
1286 QuicReceivedPacket(encrypted_buffer, encrypted_length, clock_.Now()));
1287 }
1288
1289 size_t ProcessFramePacketAtLevel(uint64_t number,
1290 QuicFrame frame,
1291 EncryptionLevel level) {
fayang01062942020-01-22 07:23:23 -08001292 QuicFrames frames;
1293 frames.push_back(frame);
1294 return ProcessFramesPacketAtLevel(number, frames, level);
1295 }
1296
1297 size_t ProcessFramesPacketAtLevel(uint64_t number,
1298 const QuicFrames& frames,
1299 EncryptionLevel level) {
fayang5c2c7b52020-07-09 13:47:16 -04001300 QuicPacketHeader header = ConstructPacketHeader(number, level);
QUICHE teamcd098022019-03-22 18:49:55 -07001301 // Set the correct encryption level and encrypter on peer_creator and
1302 // peer_framer, respectively.
1303 peer_creator_.set_encryption_level(level);
1304 if (QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_) >
1305 ENCRYPTION_INITIAL) {
1306 peer_framer_.SetEncrypter(
1307 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -07001308 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07001309 // Set the corresponding decrypter.
zhongyi546cc452019-04-12 15:27:49 -07001310 if (connection_.version().KnowsWhichDecrypterToUse()) {
1311 connection_.InstallDecrypter(
1312 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -07001313 std::make_unique<StrictTaggingDecrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07001314 connection_.RemoveDecrypter(ENCRYPTION_INITIAL);
1315 } else {
1316 connection_.SetDecrypter(
1317 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
vasilvv0fc587f2019-09-06 13:33:08 -07001318 std::make_unique<StrictTaggingDecrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07001319 }
QUICHE teamcd098022019-03-22 18:49:55 -07001320 }
fayang5c2c7b52020-07-09 13:47:16 -04001321 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001322
dschinazi66dea072019-04-09 11:41:06 -07001323 char buffer[kMaxOutgoingPacketSize];
1324 size_t encrypted_length =
1325 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1326 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001327 connection_.ProcessUdpPacket(
1328 kSelfAddress, kPeerAddress,
QUICHE teamcd098022019-03-22 18:49:55 -07001329 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1330 if (connection_.GetSendAlarm()->IsSet()) {
1331 connection_.GetSendAlarm()->Fire();
1332 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001333 return encrypted_length;
1334 }
1335
1336 size_t ProcessDataPacket(uint64_t number) {
nharper2c9f02a2019-05-08 10:25:50 -07001337 return ProcessDataPacketAtLevel(number, false, ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001338 }
1339
1340 size_t ProcessDataPacket(QuicPacketNumber packet_number) {
nharper2c9f02a2019-05-08 10:25:50 -07001341 return ProcessDataPacketAtLevel(packet_number, false,
1342 ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001343 }
1344
1345 size_t ProcessDataPacketAtLevel(QuicPacketNumber packet_number,
1346 bool has_stop_waiting,
1347 EncryptionLevel level) {
1348 return ProcessDataPacketAtLevel(packet_number.ToUint64(), has_stop_waiting,
1349 level);
1350 }
1351
fayanga39d0362020-06-22 08:57:35 -07001352 size_t ProcessCryptoPacketAtLevel(uint64_t number, EncryptionLevel level) {
1353 QuicPacketHeader header = ConstructPacketHeader(number, level);
nharper46833c32019-05-15 21:33:05 -07001354 QuicFrames frames;
1355 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1356 frames.push_back(QuicFrame(&crypto_frame_));
1357 } else {
1358 frames.push_back(QuicFrame(frame1_));
1359 }
fayang5f135052019-08-22 17:59:40 -07001360 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
nharper46833c32019-05-15 21:33:05 -07001361 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
1362 char buffer[kMaxOutgoingPacketSize];
fayanga39d0362020-06-22 08:57:35 -07001363 peer_creator_.set_encryption_level(level);
1364 size_t encrypted_length =
1365 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1366 buffer, kMaxOutgoingPacketSize);
nharper46833c32019-05-15 21:33:05 -07001367 connection_.ProcessUdpPacket(
1368 kSelfAddress, kPeerAddress,
1369 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1370 if (connection_.GetSendAlarm()->IsSet()) {
1371 connection_.GetSendAlarm()->Fire();
1372 }
1373 return encrypted_length;
1374 }
1375
QUICHE teama6ef0a62019-03-07 20:34:33 -05001376 size_t ProcessDataPacketAtLevel(uint64_t number,
1377 bool has_stop_waiting,
1378 EncryptionLevel level) {
1379 std::unique_ptr<QuicPacket> packet(
QUICHE team8c1daa22019-03-13 08:33:41 -07001380 ConstructDataPacket(number, has_stop_waiting, level));
dschinazi66dea072019-04-09 11:41:06 -07001381 char buffer[kMaxOutgoingPacketSize];
QUICHE teamcd098022019-03-22 18:49:55 -07001382 peer_creator_.set_encryption_level(level);
dschinazi66dea072019-04-09 11:41:06 -07001383 size_t encrypted_length =
1384 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1385 buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001386 connection_.ProcessUdpPacket(
1387 kSelfAddress, kPeerAddress,
1388 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1389 if (connection_.GetSendAlarm()->IsSet()) {
1390 connection_.GetSendAlarm()->Fire();
1391 }
1392 return encrypted_length;
1393 }
1394
1395 void ProcessClosePacket(uint64_t number) {
1396 std::unique_ptr<QuicPacket> packet(ConstructClosePacket(number));
dschinazi66dea072019-04-09 11:41:06 -07001397 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07001398 size_t encrypted_length = peer_framer_.EncryptPayload(
nharperc6b99512019-09-19 11:13:48 -07001399 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(number), *packet, buffer,
dschinazi66dea072019-04-09 11:41:06 -07001400 kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001401 connection_.ProcessUdpPacket(
1402 kSelfAddress, kPeerAddress,
1403 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
1404 }
1405
1406 QuicByteCount SendStreamDataToPeer(QuicStreamId id,
dmcardlecf0bfcf2019-12-13 08:08:21 -08001407 quiche::QuicheStringPiece data,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001408 QuicStreamOffset offset,
1409 StreamSendingState state,
1410 QuicPacketNumber* last_packet) {
1411 QuicByteCount packet_size;
fayang0fcbf352019-08-30 11:15:58 -07001412 // Save the last packet's size.
QUICHE teama6ef0a62019-03-07 20:34:33 -05001413 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
fayang0fcbf352019-08-30 11:15:58 -07001414 .Times(AnyNumber())
1415 .WillRepeatedly(SaveArg<3>(&packet_size));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001416 connection_.SendStreamDataWithString(id, data, offset, state);
1417 if (last_packet != nullptr) {
1418 *last_packet = creator_->packet_number();
1419 }
1420 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1421 .Times(AnyNumber());
1422 return packet_size;
1423 }
1424
1425 void SendAckPacketToPeer() {
1426 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1427 {
fayanga4b37b22019-06-18 13:37:47 -07001428 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001429 connection_.SendAck();
1430 }
1431 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1432 .Times(AnyNumber());
1433 }
1434
1435 void SendRstStream(QuicStreamId id,
1436 QuicRstStreamErrorCode error,
1437 QuicStreamOffset bytes_written) {
fayangcff885a2019-10-22 07:39:04 -07001438 notifier_.WriteOrBufferRstStream(id, error, bytes_written);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001439 connection_.OnStreamReset(id, error);
1440 }
1441
fayangcff885a2019-10-22 07:39:04 -07001442 void SendPing() { notifier_.WriteOrBufferPing(); }
zhongyifbb25772019-04-10 16:54:08 -07001443
fayang61453cb2020-03-11 11:32:26 -07001444 MessageStatus SendMessage(quiche::QuicheStringPiece message) {
1445 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1446 QuicMemSliceStorage storage(nullptr, 0, nullptr, 0);
1447 return connection_.SendMessage(
1448 1,
1449 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(), message,
1450 &storage),
1451 false);
1452 }
1453
QUICHE teama6ef0a62019-03-07 20:34:33 -05001454 void ProcessAckPacket(uint64_t packet_number, QuicAckFrame* frame) {
1455 if (packet_number > 1) {
1456 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, packet_number - 1);
1457 } else {
1458 QuicPacketCreatorPeer::ClearPacketNumber(&peer_creator_);
1459 }
1460 ProcessFramePacket(QuicFrame(frame));
1461 }
1462
1463 void ProcessAckPacket(QuicAckFrame* frame) {
1464 ProcessFramePacket(QuicFrame(frame));
1465 }
1466
1467 void ProcessStopWaitingPacket(QuicStopWaitingFrame frame) {
1468 ProcessFramePacket(QuicFrame(frame));
1469 }
1470
1471 size_t ProcessStopWaitingPacketAtLevel(uint64_t number,
1472 QuicStopWaitingFrame frame,
dschinazi17d42422019-06-18 16:35:07 -07001473 EncryptionLevel /*level*/) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001474 return ProcessFramePacketAtLevel(number, QuicFrame(frame),
1475 ENCRYPTION_ZERO_RTT);
1476 }
1477
1478 void ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
1479 ProcessFramePacket(QuicFrame(frame));
1480 }
1481
1482 bool IsMissing(uint64_t number) {
fayangc31c9952019-06-05 13:54:48 -07001483 return IsAwaitingPacket(connection_.ack_frame(), QuicPacketNumber(number),
QUICHE teama6ef0a62019-03-07 20:34:33 -05001484 QuicPacketNumber());
1485 }
1486
1487 std::unique_ptr<QuicPacket> ConstructPacket(const QuicPacketHeader& header,
1488 const QuicFrames& frames) {
1489 auto packet = BuildUnsizedDataPacket(&peer_framer_, header, frames);
1490 EXPECT_NE(nullptr, packet.get());
1491 return packet;
1492 }
1493
nharper46833c32019-05-15 21:33:05 -07001494 QuicPacketHeader ConstructPacketHeader(uint64_t number,
1495 EncryptionLevel level) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001496 QuicPacketHeader header;
fayangd4291e42019-05-30 10:31:21 -07001497 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version()) &&
QUICHE team8c1daa22019-03-13 08:33:41 -07001498 level < ENCRYPTION_FORWARD_SECURE) {
1499 // Set long header type accordingly.
1500 header.version_flag = true;
nharperc6b99512019-09-19 11:13:48 -07001501 header.form = IETF_QUIC_LONG_HEADER_PACKET;
QUICHE team8c1daa22019-03-13 08:33:41 -07001502 header.long_packet_type = EncryptionlevelToLongHeaderType(level);
1503 if (QuicVersionHasLongHeaderLengths(
1504 peer_framer_.version().transport_version)) {
1505 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
1506 if (header.long_packet_type == INITIAL) {
1507 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
1508 }
1509 }
1510 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001511 // Set connection_id to peer's in memory representation as this data packet
1512 // is created by peer_framer.
dschinazi5e1a7b22019-07-31 12:23:21 -07001513 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04001514 header.source_connection_id = connection_id_;
1515 header.source_connection_id_included = connection_id_included_;
1516 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1517 } else {
1518 header.destination_connection_id = connection_id_;
1519 header.destination_connection_id_included = connection_id_included_;
1520 }
fayangd4291e42019-05-30 10:31:21 -07001521 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version()) &&
QUICHE teama6ef0a62019-03-07 20:34:33 -05001522 peer_framer_.perspective() == Perspective::IS_SERVER) {
1523 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
QUICHE team8c1daa22019-03-13 08:33:41 -07001524 if (header.version_flag) {
1525 header.source_connection_id = connection_id_;
1526 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1527 if (GetParam().version.handshake_protocol == PROTOCOL_QUIC_CRYPTO &&
1528 header.long_packet_type == ZERO_RTT_PROTECTED) {
QUICHE team548d51b2019-03-14 10:06:54 -07001529 header.nonce = &kTestDiversificationNonce;
QUICHE team8c1daa22019-03-13 08:33:41 -07001530 }
1531 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001532 }
QUICHE team2252b702019-05-14 23:55:14 -04001533 header.packet_number_length = packet_number_length_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001534 header.packet_number = QuicPacketNumber(number);
nharper46833c32019-05-15 21:33:05 -07001535 return header;
1536 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001537
nharper46833c32019-05-15 21:33:05 -07001538 std::unique_ptr<QuicPacket> ConstructDataPacket(uint64_t number,
1539 bool has_stop_waiting,
1540 EncryptionLevel level) {
1541 QuicPacketHeader header = ConstructPacketHeader(number, level);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001542 QuicFrames frames;
1543 frames.push_back(QuicFrame(frame1_));
1544 if (has_stop_waiting) {
1545 frames.push_back(QuicFrame(stop_waiting_));
1546 }
1547 return ConstructPacket(header, frames);
1548 }
1549
wub8a5dafa2020-05-13 12:30:17 -07001550 std::unique_ptr<SerializedPacket> ConstructProbingPacket() {
fkastenholz305e1732019-06-18 05:01:22 -07001551 if (VersionHasIetfQuicFrames(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001552 QuicPathFrameBuffer payload = {
1553 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
1554 return QuicPacketCreatorPeer::
1555 SerializePathChallengeConnectivityProbingPacket(&peer_creator_,
1556 &payload);
1557 }
1558 return QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
1559 &peer_creator_);
1560 }
1561
1562 std::unique_ptr<QuicPacket> ConstructClosePacket(uint64_t number) {
1563 QuicPacketHeader header;
1564 // Set connection_id to peer's in memory representation as this connection
1565 // close packet is created by peer_framer.
dschinazi5e1a7b22019-07-31 12:23:21 -07001566 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04001567 header.source_connection_id = connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001568 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
fayangd4291e42019-05-30 10:31:21 -07001569 if (!VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04001570 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1571 }
1572 } else {
1573 header.destination_connection_id = connection_id_;
fayangd4291e42019-05-30 10:31:21 -07001574 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04001575 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1576 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001577 }
1578
QUICHE team2252b702019-05-14 23:55:14 -04001579 header.packet_number = QuicPacketNumber(number);
1580
fkastenholz0d6554a2019-08-05 12:20:35 -07001581 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
fkastenholz591814c2019-09-06 12:11:46 -07001582 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
1583 kQuicErrorCode, "",
1584 /*transport_close_frame_type=*/0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001585 QuicFrames frames;
1586 frames.push_back(QuicFrame(&qccf));
1587 return ConstructPacket(header, frames);
1588 }
1589
1590 QuicTime::Delta DefaultRetransmissionTime() {
1591 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
1592 }
1593
1594 QuicTime::Delta DefaultDelayedAckTime() {
1595 return QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs);
1596 }
1597
1598 const QuicStopWaitingFrame InitStopWaitingFrame(uint64_t least_unacked) {
1599 QuicStopWaitingFrame frame;
1600 frame.least_unacked = QuicPacketNumber(least_unacked);
1601 return frame;
1602 }
1603
1604 // Construct a ack_frame that acks all packet numbers between 1 and
1605 // |largest_acked|, except |missing|.
1606 // REQUIRES: 1 <= |missing| < |largest_acked|
1607 QuicAckFrame ConstructAckFrame(uint64_t largest_acked, uint64_t missing) {
1608 return ConstructAckFrame(QuicPacketNumber(largest_acked),
1609 QuicPacketNumber(missing));
1610 }
1611
1612 QuicAckFrame ConstructAckFrame(QuicPacketNumber largest_acked,
1613 QuicPacketNumber missing) {
1614 if (missing == QuicPacketNumber(1)) {
1615 return InitAckFrame({{missing + 1, largest_acked + 1}});
1616 }
1617 return InitAckFrame(
1618 {{QuicPacketNumber(1), missing}, {missing + 1, largest_acked + 1}});
1619 }
1620
1621 // Undo nacking a packet within the frame.
1622 void AckPacket(QuicPacketNumber arrived, QuicAckFrame* frame) {
1623 EXPECT_FALSE(frame->packets.Contains(arrived));
1624 frame->packets.Add(arrived);
1625 }
1626
1627 void TriggerConnectionClose() {
1628 // Send an erroneous packet to close the connection.
fkastenholz5d880a92019-06-21 09:01:56 -07001629 EXPECT_CALL(visitor_,
1630 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
1631 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
1632
QUICHE teamcd098022019-03-22 18:49:55 -07001633 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1634 // Triggers a connection by receiving ACK of unsent packet.
1635 QuicAckFrame frame = InitAckFrame(10000);
1636 ProcessAckPacket(1, &frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001637 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1638 nullptr);
fkastenholz5d880a92019-06-21 09:01:56 -07001639 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08001640 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
1641 IsError(QUIC_INVALID_ACK_DATA));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001642 }
1643
1644 void BlockOnNextWrite() {
1645 writer_->BlockOnNextWrite();
1646 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
1647 }
1648
1649 void SimulateNextPacketTooLarge() { writer_->SimulateNextPacketTooLarge(); }
1650
1651 void AlwaysGetPacketTooLarge() { writer_->AlwaysGetPacketTooLarge(); }
1652
1653 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
1654 writer_->SetWritePauseTimeDelta(delta);
1655 }
1656
1657 void CongestionBlockWrites() {
1658 EXPECT_CALL(*send_algorithm_, CanSend(_))
1659 .WillRepeatedly(testing::Return(false));
1660 }
1661
1662 void CongestionUnblockWrites() {
1663 EXPECT_CALL(*send_algorithm_, CanSend(_))
1664 .WillRepeatedly(testing::Return(true));
1665 }
1666
1667 void set_perspective(Perspective perspective) {
1668 connection_.set_perspective(perspective);
1669 if (perspective == Perspective::IS_SERVER) {
1670 connection_.set_can_truncate_connection_ids(true);
wub256b2d62019-11-25 08:46:55 -08001671 QuicConnectionPeer::SetNegotiatedVersion(&connection_);
wubbea386e2020-01-27 09:04:51 -08001672 connection_.OnSuccessfulVersionNegotiation();
QUICHE teama6ef0a62019-03-07 20:34:33 -05001673 }
1674 QuicFramerPeer::SetPerspective(&peer_framer_,
nharper4eba09b2019-06-26 20:17:25 -07001675 QuicUtils::InvertPerspective(perspective));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001676 }
1677
1678 void set_packets_between_probes_base(
1679 const QuicPacketCount packets_between_probes_base) {
wub173916e2019-11-27 14:36:24 -08001680 QuicConnectionPeer::ReInitializeMtuDiscoverer(
1681 &connection_, packets_between_probes_base,
1682 QuicPacketNumber(packets_between_probes_base));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001683 }
1684
1685 bool IsDefaultTestConfiguration() {
1686 TestParams p = GetParam();
1687 return p.ack_response == AckResponse::kImmediate &&
1688 p.version == AllSupportedVersions()[0] && p.no_stop_waiting;
1689 }
1690
fkastenholz5d880a92019-06-21 09:01:56 -07001691 void TestConnectionCloseQuicErrorCode(QuicErrorCode expected_code) {
1692 // Not strictly needed for this test, but is commonly done.
1693 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1694 nullptr);
1695 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
1696 writer_->connection_close_frames();
1697 ASSERT_EQ(1u, connection_close_frames.size());
bnc77e77b82020-04-05 10:36:49 -07001698
dschinazi39e5e552020-05-06 13:55:24 -07001699 EXPECT_THAT(connection_close_frames[0].quic_error_code,
1700 IsError(expected_code));
bnc77e77b82020-04-05 10:36:49 -07001701
fkastenholz0d6554a2019-08-05 12:20:35 -07001702 if (!VersionHasIetfQuicFrames(version().transport_version)) {
dschinazi39e5e552020-05-06 13:55:24 -07001703 EXPECT_THAT(connection_close_frames[0].wire_error_code,
1704 IsError(expected_code));
fkastenholz0d6554a2019-08-05 12:20:35 -07001705 EXPECT_EQ(GOOGLE_QUIC_CONNECTION_CLOSE,
1706 connection_close_frames[0].close_type);
1707 return;
1708 }
1709
1710 QuicErrorCodeToIetfMapping mapping =
1711 QuicErrorCodeToTransportErrorCode(expected_code);
1712
bnc0054cc62020-04-09 18:22:57 -07001713 if (mapping.is_transport_close) {
fkastenholz0d6554a2019-08-05 12:20:35 -07001714 // This Google QUIC Error Code maps to a transport close,
1715 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
1716 connection_close_frames[0].close_type);
fkastenholz0d6554a2019-08-05 12:20:35 -07001717 } else {
1718 // This maps to an application close.
fkastenholz0d6554a2019-08-05 12:20:35 -07001719 EXPECT_EQ(IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
1720 connection_close_frames[0].close_type);
fkastenholz0d6554a2019-08-05 12:20:35 -07001721 }
bnc0054cc62020-04-09 18:22:57 -07001722 EXPECT_EQ(mapping.error_code, connection_close_frames[0].wire_error_code);
fkastenholz5d880a92019-06-21 09:01:56 -07001723 }
1724
wub031d47c2019-11-21 08:04:07 -08001725 void MtuDiscoveryTestInit() {
1726 set_perspective(Perspective::IS_SERVER);
wub031d47c2019-11-21 08:04:07 -08001727 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
fayang6a258412020-05-28 08:57:12 -07001728 if (version().SupportsAntiAmplificationLimit()) {
1729 QuicConnectionPeer::SetAddressValidated(&connection_);
1730 }
wub031d47c2019-11-21 08:04:07 -08001731 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1732 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1733 // QuicFramer::GetMaxPlaintextSize uses the smallest max plaintext size
1734 // across all encrypters. The initial encrypter used with IETF QUIC has a
1735 // 16-byte overhead, while the NullEncrypter used throughout this test has a
1736 // 12-byte overhead. This test tests behavior that relies on computing the
1737 // packet size correctly, so by unsetting the initial encrypter, we avoid
1738 // having a mismatch between the overheads for the encrypters used. In
1739 // non-test scenarios all encrypters used for a given connection have the
1740 // same overhead, either 12 bytes for ones using Google QUIC crypto, or 16
1741 // bytes for ones using TLS.
1742 connection_.SetEncrypter(ENCRYPTION_INITIAL, nullptr);
wubecb643f2020-03-19 08:58:46 -07001743 // Prevent packets from being coalesced.
1744 EXPECT_CALL(visitor_, GetHandshakeState())
1745 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
wub031d47c2019-11-21 08:04:07 -08001746 EXPECT_TRUE(connection_.connected());
1747 }
1748
dschinazi1c6e5922020-06-19 10:35:03 -07001749 void PathProbeTestInit(Perspective perspective) {
1750 set_perspective(perspective);
1751 EXPECT_EQ(connection_.perspective(), perspective);
1752 if (perspective == Perspective::IS_SERVER) {
1753 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1754 }
1755 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1756 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1757 }
1758
dschinazi39e5e552020-05-06 13:55:24 -07001759 void TestClientRetryHandling(bool invalid_retry_tag,
dschinazie7c38a52020-05-29 15:25:45 -07001760 bool missing_original_id_in_config,
1761 bool wrong_original_id_in_config,
1762 bool missing_retry_id_in_config,
1763 bool wrong_retry_id_in_config);
dschinazi39e5e552020-05-06 13:55:24 -07001764
QUICHE teama6ef0a62019-03-07 20:34:33 -05001765 QuicConnectionId connection_id_;
1766 QuicFramer framer_;
1767
1768 MockSendAlgorithm* send_algorithm_;
1769 std::unique_ptr<MockLossAlgorithm> loss_algorithm_;
1770 MockClock clock_;
1771 MockRandom random_generator_;
1772 SimpleBufferAllocator buffer_allocator_;
1773 std::unique_ptr<TestConnectionHelper> helper_;
1774 std::unique_ptr<TestAlarmFactory> alarm_factory_;
1775 QuicFramer peer_framer_;
1776 QuicPacketCreator peer_creator_;
1777 std::unique_ptr<TestPacketWriter> writer_;
1778 TestConnection connection_;
1779 QuicPacketCreator* creator_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001780 QuicSentPacketManager* manager_;
1781 StrictMock<MockQuicConnectionVisitor> visitor_;
1782
1783 QuicStreamFrame frame1_;
1784 QuicStreamFrame frame2_;
nharper46833c32019-05-15 21:33:05 -07001785 QuicCryptoFrame crypto_frame_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001786 QuicAckFrame ack_;
1787 QuicStopWaitingFrame stop_waiting_;
1788 QuicPacketNumberLength packet_number_length_;
1789 QuicConnectionIdIncluded connection_id_included_;
1790
1791 SimpleSessionNotifier notifier_;
fkastenholz5d880a92019-06-21 09:01:56 -07001792
1793 QuicConnectionCloseFrame saved_connection_close_frame_;
1794 int connection_close_frame_count_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001795};
1796
1797// Run all end to end tests with all supported versions.
dschinazi39e5e552020-05-06 13:55:24 -07001798INSTANTIATE_TEST_SUITE_P(QuicConnectionTests,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001799 QuicConnectionTest,
dschinazi142051a2019-09-18 18:17:29 -07001800 ::testing::ValuesIn(GetTestParams()),
1801 ::testing::PrintToStringParamName());
QUICHE teama6ef0a62019-03-07 20:34:33 -05001802
fkastenholz0d6554a2019-08-05 12:20:35 -07001803// These two tests ensure that the QuicErrorCode mapping works correctly.
1804// Both tests expect to see a Google QUIC close if not running IETF QUIC.
1805// If running IETF QUIC, the first will generate a transport connection
1806// close, the second an application connection close.
1807// The connection close codes for the two tests are manually chosen;
1808// they are expected to always map to transport- and application-
dschinazi39e5e552020-05-06 13:55:24 -07001809// closes, respectively. If that changes, new codes should be chosen.
fkastenholz0d6554a2019-08-05 12:20:35 -07001810TEST_P(QuicConnectionTest, CloseErrorCodeTestTransport) {
1811 EXPECT_TRUE(connection_.connected());
1812 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1813 connection_.CloseConnection(
1814 IETF_QUIC_PROTOCOL_VIOLATION, "Should be transport close",
1815 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1816 EXPECT_FALSE(connection_.connected());
1817 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
1818}
1819
1820// Test that the IETF QUIC Error code mapping function works
1821// properly for application connection close codes.
1822TEST_P(QuicConnectionTest, CloseErrorCodeTestApplication) {
1823 EXPECT_TRUE(connection_.connected());
1824 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1825 connection_.CloseConnection(
1826 QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE,
1827 "Should be application close",
1828 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1829 EXPECT_FALSE(connection_.connected());
1830 TestConnectionCloseQuicErrorCode(QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE);
1831}
1832
QUICHE teama6ef0a62019-03-07 20:34:33 -05001833TEST_P(QuicConnectionTest, SelfAddressChangeAtClient) {
1834 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1835
1836 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1837 EXPECT_TRUE(connection_.connected());
1838
nharper46833c32019-05-15 21:33:05 -07001839 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001840 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1841 } else {
nharper46833c32019-05-15 21:33:05 -07001842 EXPECT_CALL(visitor_, OnStreamFrame(_));
1843 }
wub8a5dafa2020-05-13 12:30:17 -07001844 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1845 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001846 // Cause change in self_address.
1847 QuicIpAddress host;
1848 host.FromString("1.1.1.1");
1849 QuicSocketAddress self_address(host, 123);
nharper46833c32019-05-15 21:33:05 -07001850 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1851 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1852 } else {
1853 EXPECT_CALL(visitor_, OnStreamFrame(_));
1854 }
wub8a5dafa2020-05-13 12:30:17 -07001855 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address,
1856 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001857 EXPECT_TRUE(connection_.connected());
1858}
1859
1860TEST_P(QuicConnectionTest, SelfAddressChangeAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001861 set_perspective(Perspective::IS_SERVER);
1862 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1863
1864 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1865 EXPECT_TRUE(connection_.connected());
1866
nharper46833c32019-05-15 21:33:05 -07001867 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001868 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1869 } else {
nharper46833c32019-05-15 21:33:05 -07001870 EXPECT_CALL(visitor_, OnStreamFrame(_));
1871 }
wub8a5dafa2020-05-13 12:30:17 -07001872 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1873 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001874 // Cause change in self_address.
1875 QuicIpAddress host;
1876 host.FromString("1.1.1.1");
1877 QuicSocketAddress self_address(host, 123);
1878 EXPECT_CALL(visitor_, AllowSelfAddressChange()).WillOnce(Return(false));
fkastenholz5d880a92019-06-21 09:01:56 -07001879 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
wub8a5dafa2020-05-13 12:30:17 -07001880 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address,
1881 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001882 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07001883 TestConnectionCloseQuicErrorCode(QUIC_ERROR_MIGRATING_ADDRESS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001884}
1885
1886TEST_P(QuicConnectionTest, AllowSelfAddressChangeToMappedIpv4AddressAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001887 set_perspective(Perspective::IS_SERVER);
1888 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1889
1890 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1891 EXPECT_TRUE(connection_.connected());
1892
nharper46833c32019-05-15 21:33:05 -07001893 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001894 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
1895 } else {
nharper46833c32019-05-15 21:33:05 -07001896 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
1897 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001898 QuicIpAddress host;
1899 host.FromString("1.1.1.1");
1900 QuicSocketAddress self_address1(host, 443);
wub8a5dafa2020-05-13 12:30:17 -07001901 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1,
1902 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001903 // Cause self_address change to mapped Ipv4 address.
1904 QuicIpAddress host2;
dmcardlecf0bfcf2019-12-13 08:08:21 -08001905 host2.FromString(quiche::QuicheStrCat(
1906 "::ffff:", connection_.self_address().host().ToString()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05001907 QuicSocketAddress self_address2(host2, connection_.self_address().port());
wub8a5dafa2020-05-13 12:30:17 -07001908 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address2,
1909 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001910 EXPECT_TRUE(connection_.connected());
1911 // self_address change back to Ipv4 address.
wub8a5dafa2020-05-13 12:30:17 -07001912 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1,
1913 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001914 EXPECT_TRUE(connection_.connected());
1915}
1916
1917TEST_P(QuicConnectionTest, ClientAddressChangeAndPacketReordered) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001918 set_perspective(Perspective::IS_SERVER);
1919 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1920
1921 // Clear direct_peer_address.
1922 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1923 // Clear effective_peer_address, it is the same as direct_peer_address for
1924 // this test.
1925 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1926 QuicSocketAddress());
1927
nharper46833c32019-05-15 21:33:05 -07001928 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001929 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1930 } else {
nharper46833c32019-05-15 21:33:05 -07001931 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1932 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001933 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001934 const QuicSocketAddress kNewPeerAddress =
1935 QuicSocketAddress(QuicIpAddress::Loopback6(),
1936 /*port=*/23456);
wub8a5dafa2020-05-13 12:30:17 -07001937 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1938 kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001939 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1940 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1941
1942 // Decrease packet number to simulate out-of-order packets.
1943 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
1944 // This is an old packet, do not migrate.
1945 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
wub8a5dafa2020-05-13 12:30:17 -07001946 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1947 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001948 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1949 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1950}
1951
1952TEST_P(QuicConnectionTest, PeerAddressChangeAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001953 set_perspective(Perspective::IS_SERVER);
1954 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1955 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1956
1957 // Clear direct_peer_address.
1958 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1959 // Clear effective_peer_address, it is the same as direct_peer_address for
1960 // this test.
1961 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1962 QuicSocketAddress());
1963 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1964
nharper46833c32019-05-15 21:33:05 -07001965 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07001966 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1967 } else {
nharper46833c32019-05-15 21:33:05 -07001968 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1969 }
wub8a5dafa2020-05-13 12:30:17 -07001970 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1971 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001972 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1973 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1974
1975 // Process another packet with a different peer address on server side will
1976 // start connection migration.
1977 const QuicSocketAddress kNewPeerAddress =
1978 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1979 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
wub8a5dafa2020-05-13 12:30:17 -07001980 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1981 kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001982 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1983 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1984}
1985
1986TEST_P(QuicConnectionTest, EffectivePeerAddressChangeAtServer) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001987 set_perspective(Perspective::IS_SERVER);
1988 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1989 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
fayang6a258412020-05-28 08:57:12 -07001990 if (version().SupportsAntiAmplificationLimit()) {
1991 QuicConnectionPeer::SetAddressValidated(&connection_);
1992 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001993
1994 // Clear direct_peer_address.
1995 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1996 // Clear effective_peer_address, it is different from direct_peer_address for
1997 // this test.
1998 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1999 QuicSocketAddress());
2000 const QuicSocketAddress kEffectivePeerAddress =
2001 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/43210);
2002 connection_.ReturnEffectivePeerAddressForNextPacket(kEffectivePeerAddress);
2003
nharper46833c32019-05-15 21:33:05 -07002004 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002005 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2006 } else {
nharper46833c32019-05-15 21:33:05 -07002007 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2008 }
wub8a5dafa2020-05-13 12:30:17 -07002009 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2010 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002011 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2012 EXPECT_EQ(kEffectivePeerAddress, connection_.effective_peer_address());
2013
2014 // Process another packet with the same direct peer address and different
2015 // effective peer address on server side will start connection migration.
2016 const QuicSocketAddress kNewEffectivePeerAddress =
2017 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/54321);
2018 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
2019 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
wub8a5dafa2020-05-13 12:30:17 -07002020 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2021 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002022 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2023 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
2024
2025 // Process another packet with a different direct peer address and the same
2026 // effective peer address on server side will not start connection migration.
2027 const QuicSocketAddress kNewPeerAddress =
2028 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2029 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
2030 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2031 // ack_frame is used to complete the migration started by the last packet, we
2032 // need to make sure a new migration does not start after the previous one is
2033 // completed.
2034 QuicAckFrame ack_frame = InitAckFrame(1);
2035 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
2036 ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress,
2037 kNewPeerAddress);
2038 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2039 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
2040
2041 // Process another packet with different direct peer address and different
2042 // effective peer address on server side will start connection migration.
2043 const QuicSocketAddress kNewerEffectivePeerAddress =
2044 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/65432);
2045 const QuicSocketAddress kFinalPeerAddress =
2046 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/34567);
2047 connection_.ReturnEffectivePeerAddressForNextPacket(
2048 kNewerEffectivePeerAddress);
2049 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
wub8a5dafa2020-05-13 12:30:17 -07002050 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2051 kFinalPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002052 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
2053 EXPECT_EQ(kNewerEffectivePeerAddress, connection_.effective_peer_address());
2054 EXPECT_EQ(PORT_CHANGE, connection_.active_effective_peer_migration_type());
2055
2056 // While the previous migration is ongoing, process another packet with the
2057 // same direct peer address and different effective peer address on server
2058 // side will start a new connection migration.
2059 const QuicSocketAddress kNewestEffectivePeerAddress =
2060 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/65430);
2061 connection_.ReturnEffectivePeerAddressForNextPacket(
2062 kNewestEffectivePeerAddress);
2063 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
2064 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(1);
wub8a5dafa2020-05-13 12:30:17 -07002065 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2066 kFinalPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002067 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
2068 EXPECT_EQ(kNewestEffectivePeerAddress, connection_.effective_peer_address());
2069 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
2070 connection_.active_effective_peer_migration_type());
2071}
2072
zhongyif06ca342020-02-24 14:11:13 -08002073TEST_P(QuicConnectionTest, ReceivePathProbeWithNoAddressChangeAtServer) {
dschinazi1c6e5922020-06-19 10:35:03 -07002074 PathProbeTestInit(Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002075
2076 // Clear direct_peer_address.
2077 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2078 // Clear effective_peer_address, it is the same as direct_peer_address for
2079 // this test.
2080 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2081 QuicSocketAddress());
2082 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2083
nharper46833c32019-05-15 21:33:05 -07002084 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002085 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2086 } else {
nharper46833c32019-05-15 21:33:05 -07002087 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2088 }
wub8a5dafa2020-05-13 12:30:17 -07002089 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2090 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002091 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2092 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2093
2094 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002095 EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002096
2097 // Process a padded PING or PATH CHALLENGE packet with no peer address change
2098 // on server side will be ignored.
wub8a5dafa2020-05-13 12:30:17 -07002099 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
zhongyif06ca342020-02-24 14:11:13 -08002100
QUICHE teama6ef0a62019-03-07 20:34:33 -05002101 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2102 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2103 probing_packet->encrypted_length),
2104 clock_.Now()));
2105
2106 uint64_t num_probing_received =
2107 connection_.GetStats().num_connectivity_probing_received;
2108 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2109
2110 EXPECT_EQ(num_probing_received,
2111 connection_.GetStats().num_connectivity_probing_received);
2112 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2113 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2114}
2115
wub54bd5bf2020-05-13 13:02:16 -07002116// Regression test for b/150161358.
2117TEST_P(QuicConnectionTest, BufferedMtuPacketTooBig) {
wub54bd5bf2020-05-13 13:02:16 -07002118 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
2119 writer_->SetWriteBlocked();
2120
2121 // Send a MTU packet while blocked. It should be buffered.
2122 connection_.SendMtuDiscoveryPacket(kMaxOutgoingPacketSize);
2123 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2124 EXPECT_TRUE(writer_->IsWriteBlocked());
2125
2126 writer_->AlwaysGetPacketTooLarge();
2127 writer_->SetWritable();
2128 connection_.OnCanWrite();
2129}
2130
QUICHE teama6ef0a62019-03-07 20:34:33 -05002131TEST_P(QuicConnectionTest, WriteOutOfOrderQueuedPackets) {
2132 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
fayangc31c9952019-06-05 13:54:48 -07002133 if (!IsDefaultTestConfiguration()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002134 return;
2135 }
2136
2137 set_perspective(Perspective::IS_CLIENT);
2138
2139 BlockOnNextWrite();
2140
2141 QuicStreamId stream_id = 2;
2142 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
2143
2144 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2145
2146 writer_->SetWritable();
2147 connection_.SendConnectivityProbingPacket(writer_.get(),
2148 connection_.peer_address());
fayange62e63c2019-12-04 07:16:25 -08002149 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
2150 connection_.OnCanWrite();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002151}
2152
2153TEST_P(QuicConnectionTest, DiscardQueuedPacketsAfterConnectionClose) {
2154 // Regression test for b/74073386.
2155 {
2156 InSequence seq;
rch39c88ab2019-10-16 19:24:40 -07002157 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2158 .Times(AtLeast(1));
2159 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002160 }
2161
2162 set_perspective(Perspective::IS_CLIENT);
2163
2164 writer_->SimulateNextPacketTooLarge();
2165
2166 // This packet write should fail, which should cause the connection to close
2167 // after sending a connection close packet, then the failed packet should be
2168 // queued.
2169 connection_.SendStreamDataWithString(/*id=*/2, "foo", 0, NO_FIN);
2170
2171 EXPECT_FALSE(connection_.connected());
fayange62e63c2019-12-04 07:16:25 -08002172 // No need to buffer packets.
2173 EXPECT_EQ(0u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002174
2175 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
2176 connection_.OnCanWrite();
fayang0f0c4e62019-07-16 08:55:54 -07002177 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002178}
2179
zhongyif06ca342020-02-24 14:11:13 -08002180// Receive a path probe request at the server side, i.e.,
2181// in non-IETF version: receive a padded PING packet with a peer addess change;
2182// in IETF version: receive a packet contains PATH CHALLENGE with peer address
2183// change.
2184TEST_P(QuicConnectionTest, ReceivePathProbingAtServer) {
dschinazi1c6e5922020-06-19 10:35:03 -07002185 PathProbeTestInit(Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002186
2187 // Clear direct_peer_address.
2188 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2189 // Clear effective_peer_address, it is the same as direct_peer_address for
2190 // this test.
2191 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2192 QuicSocketAddress());
2193 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2194
nharper46833c32019-05-15 21:33:05 -07002195 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002196 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2197 } else {
nharper46833c32019-05-15 21:33:05 -07002198 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2199 }
wub8a5dafa2020-05-13 12:30:17 -07002200 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2201 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002202 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2203 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2204
2205 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyif06ca342020-02-24 14:11:13 -08002206 if (!GetParam().version.HasIetfQuicFrames()) {
2207 EXPECT_CALL(visitor_,
2208 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2209 .Times(1);
2210 } else {
2211 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2212 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002213 // Process a padded PING packet from a new peer address on server side
2214 // is effectively receiving a connectivity probing.
2215 const QuicSocketAddress kNewPeerAddress =
2216 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2217
wub8a5dafa2020-05-13 12:30:17 -07002218 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002219 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2220 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2221 probing_packet->encrypted_length),
2222 clock_.Now()));
2223
2224 uint64_t num_probing_received =
2225 connection_.GetStats().num_connectivity_probing_received;
2226 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2227
2228 EXPECT_EQ(num_probing_received + 1,
2229 connection_.GetStats().num_connectivity_probing_received);
2230 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2231 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2232
2233 // Process another packet with the old peer address on server side will not
2234 // start peer migration.
2235 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
wub8a5dafa2020-05-13 12:30:17 -07002236 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2237 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002238 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2239 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2240}
2241
zhongyif06ca342020-02-24 14:11:13 -08002242// Receive a padded PING packet with a port change on server side.
2243TEST_P(QuicConnectionTest, ReceivePaddedPingWithPortChangeAtServer) {
2244 set_perspective(Perspective::IS_SERVER);
2245 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2246 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2247
2248 // Clear direct_peer_address.
2249 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2250 // Clear effective_peer_address, it is the same as direct_peer_address for
2251 // this test.
2252 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2253 QuicSocketAddress());
2254 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2255
zhongyif06ca342020-02-24 14:11:13 -08002256 if (GetParam().version.UsesCryptoFrames()) {
zhongyif06ca342020-02-24 14:11:13 -08002257 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2258 } else {
zhongyif06ca342020-02-24 14:11:13 -08002259 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2260 }
wub8a5dafa2020-05-13 12:30:17 -07002261 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2262 kPeerAddress);
zhongyif06ca342020-02-24 14:11:13 -08002263 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2264 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2265
2266 if (GetParam().version.HasIetfQuicFrames()) {
2267 // In IETF version, a padded PING packet with port change is not taken as
2268 // connectivity probe.
2269 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2270 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2271 } else {
2272 // In non-IETF version, process a padded PING packet from a new peer
2273 // address on server side is effectively receiving a connectivity probing.
2274 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2275 EXPECT_CALL(visitor_,
2276 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2277 .Times(1);
2278 }
2279 const QuicSocketAddress kNewPeerAddress =
2280 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2281
2282 QuicFrames frames;
2283 // Write a PING frame, which has no data payload.
2284 QuicPingFrame ping_frame;
2285 frames.push_back(QuicFrame(ping_frame));
2286
2287 // Add padding to the rest of the packet.
2288 QuicPaddingFrame padding_frame;
2289 frames.push_back(QuicFrame(padding_frame));
2290
2291 uint64_t num_probing_received =
2292 connection_.GetStats().num_connectivity_probing_received;
2293
2294 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress);
2295
2296 if (GetParam().version.HasIetfQuicFrames()) {
2297 // Padded PING with port changen is not considered as connectivity probe but
2298 // a PORT CHANGE.
2299 EXPECT_EQ(num_probing_received,
2300 connection_.GetStats().num_connectivity_probing_received);
2301 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2302 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2303 } else {
2304 EXPECT_EQ(num_probing_received + 1,
2305 connection_.GetStats().num_connectivity_probing_received);
2306 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2307 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2308 }
2309
2310 // Process another packet with the old peer address on server side.
2311 if (GetParam().version.HasIetfQuicFrames()) {
2312 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2313 } else {
2314 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2315 }
wub8a5dafa2020-05-13 12:30:17 -07002316 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2317 kPeerAddress);
zhongyif06ca342020-02-24 14:11:13 -08002318 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2319 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2320}
2321
2322TEST_P(QuicConnectionTest, ReceiveReorderedPathProbingAtServer) {
dschinazi1c6e5922020-06-19 10:35:03 -07002323 PathProbeTestInit(Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002324
2325 // Clear direct_peer_address.
2326 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2327 // Clear effective_peer_address, it is the same as direct_peer_address for
2328 // this test.
2329 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2330 QuicSocketAddress());
2331 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2332
nharper46833c32019-05-15 21:33:05 -07002333 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002334 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2335 } else {
nharper46833c32019-05-15 21:33:05 -07002336 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2337 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002338 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
wub8a5dafa2020-05-13 12:30:17 -07002339 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2340 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002341 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2342 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2343
2344 // Decrease packet number to simulate out-of-order packets.
2345 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
2346
2347 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyif06ca342020-02-24 14:11:13 -08002348 if (!GetParam().version.HasIetfQuicFrames()) {
2349 EXPECT_CALL(visitor_,
2350 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2351 .Times(1);
2352 } else {
2353 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2354 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002355
2356 // Process a padded PING packet from a new peer address on server side
2357 // is effectively receiving a connectivity probing, even if a newer packet has
2358 // been received before this one.
2359 const QuicSocketAddress kNewPeerAddress =
2360 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2361
wub8a5dafa2020-05-13 12:30:17 -07002362 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002363 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2364 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2365 probing_packet->encrypted_length),
2366 clock_.Now()));
2367
2368 uint64_t num_probing_received =
2369 connection_.GetStats().num_connectivity_probing_received;
2370 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2371
2372 EXPECT_EQ(num_probing_received + 1,
2373 connection_.GetStats().num_connectivity_probing_received);
2374 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2375 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2376}
2377
2378TEST_P(QuicConnectionTest, MigrateAfterProbingAtServer) {
dschinazi1c6e5922020-06-19 10:35:03 -07002379 PathProbeTestInit(Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002380
2381 // Clear direct_peer_address.
2382 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2383 // Clear effective_peer_address, it is the same as direct_peer_address for
2384 // this test.
2385 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2386 QuicSocketAddress());
2387 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2388
nharper46833c32019-05-15 21:33:05 -07002389 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002390 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2391 } else {
nharper46833c32019-05-15 21:33:05 -07002392 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2393 }
wub8a5dafa2020-05-13 12:30:17 -07002394 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2395 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002396 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2397 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2398
2399 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyif06ca342020-02-24 14:11:13 -08002400 if (!GetParam().version.HasIetfQuicFrames()) {
2401 EXPECT_CALL(visitor_,
2402 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2403 .Times(1);
2404 } else {
2405 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2406 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002407
2408 // Process a padded PING packet from a new peer address on server side
2409 // is effectively receiving a connectivity probing.
2410 const QuicSocketAddress kNewPeerAddress =
2411 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2412
wub8a5dafa2020-05-13 12:30:17 -07002413 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002414 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2415 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2416 probing_packet->encrypted_length),
2417 clock_.Now()));
2418 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2419 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2420 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2421
2422 // Process another non-probing packet with the new peer address on server
2423 // side will start peer migration.
2424 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2425
wub8a5dafa2020-05-13 12:30:17 -07002426 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2427 kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002428 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2429 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2430}
2431
2432TEST_P(QuicConnectionTest, ReceivePaddedPingAtClient) {
2433 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
dschinazi1c6e5922020-06-19 10:35:03 -07002434 PathProbeTestInit(Perspective::IS_CLIENT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002435
2436 // Clear direct_peer_address.
2437 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2438 // Clear effective_peer_address, it is the same as direct_peer_address for
2439 // this test.
2440 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2441 QuicSocketAddress());
2442 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2443
nharper46833c32019-05-15 21:33:05 -07002444 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002445 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2446 } else {
nharper46833c32019-05-15 21:33:05 -07002447 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2448 }
wub8a5dafa2020-05-13 12:30:17 -07002449 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2450 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002451 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2452 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2453
2454 // Client takes all padded PING packet as speculative connectivity
2455 // probing packet, and reports to visitor.
2456 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyi83161e42019-08-19 09:06:25 -07002457 EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002458
wub8a5dafa2020-05-13 12:30:17 -07002459 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002460 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2461 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2462 probing_packet->encrypted_length),
2463 clock_.Now()));
2464 uint64_t num_probing_received =
2465 connection_.GetStats().num_connectivity_probing_received;
2466 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2467
2468 EXPECT_EQ(num_probing_received,
2469 connection_.GetStats().num_connectivity_probing_received);
2470 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2471 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2472}
2473
zhongyif06ca342020-02-24 14:11:13 -08002474TEST_P(QuicConnectionTest, ReceiveConnectivityProbingResponseAtClient) {
2475 // TODO(b/150095484): add test coverage for IETF to verify that client takes
2476 // PATH RESPONSE with peer address change as correct validation on the new
2477 // path.
2478 if (GetParam().version.HasIetfQuicFrames()) {
2479 return;
2480 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002481 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
dschinazi1c6e5922020-06-19 10:35:03 -07002482 PathProbeTestInit(Perspective::IS_CLIENT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002483
2484 // Clear direct_peer_address.
2485 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2486 // Clear effective_peer_address, it is the same as direct_peer_address for
2487 // this test.
2488 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2489 QuicSocketAddress());
2490 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2491
nharper46833c32019-05-15 21:33:05 -07002492 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002493 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2494 } else {
nharper46833c32019-05-15 21:33:05 -07002495 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2496 }
wub8a5dafa2020-05-13 12:30:17 -07002497 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2498 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002499 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2500 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2501
2502 // Process a padded PING packet with a different self address on client side
2503 // is effectively receiving a connectivity probing.
2504 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
zhongyif06ca342020-02-24 14:11:13 -08002505 if (!GetParam().version.HasIetfQuicFrames()) {
2506 EXPECT_CALL(visitor_,
2507 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2508 .Times(1);
2509 } else {
2510 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2511 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002512
2513 const QuicSocketAddress kNewSelfAddress =
2514 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2515
wub8a5dafa2020-05-13 12:30:17 -07002516 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
QUICHE teama6ef0a62019-03-07 20:34:33 -05002517 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2518 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2519 probing_packet->encrypted_length),
2520 clock_.Now()));
2521 uint64_t num_probing_received =
2522 connection_.GetStats().num_connectivity_probing_received;
2523 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
2524
2525 EXPECT_EQ(num_probing_received + 1,
2526 connection_.GetStats().num_connectivity_probing_received);
2527 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2528 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2529}
2530
2531TEST_P(QuicConnectionTest, PeerAddressChangeAtClient) {
2532 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2533 set_perspective(Perspective::IS_CLIENT);
2534 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2535
2536 // Clear direct_peer_address.
2537 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2538 // Clear effective_peer_address, it is the same as direct_peer_address for
2539 // this test.
2540 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2541 QuicSocketAddress());
2542 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2543
nharper46833c32019-05-15 21:33:05 -07002544 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07002545 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2546 } else {
nharper46833c32019-05-15 21:33:05 -07002547 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2548 }
wub8a5dafa2020-05-13 12:30:17 -07002549 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2550 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002551 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2552 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2553
2554 // Process another packet with a different peer address on client side will
2555 // only update peer address.
2556 const QuicSocketAddress kNewPeerAddress =
2557 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2558 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
wub8a5dafa2020-05-13 12:30:17 -07002559 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2560 kNewPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002561 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2562 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2563}
2564
2565TEST_P(QuicConnectionTest, MaxPacketSize) {
2566 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2567 EXPECT_EQ(1350u, connection_.max_packet_length());
2568}
2569
dschinazi4ad1f462020-01-16 11:56:52 -08002570TEST_P(QuicConnectionTest, PeerLowersMaxPacketSize) {
2571 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2572
2573 // SetFromConfig is always called after construction from InitializeSession.
2574 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2575 constexpr uint32_t kTestMaxPacketSize = 1233u;
2576 QuicConfig config;
2577 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
2578 connection_.SetFromConfig(config);
2579
2580 EXPECT_EQ(kTestMaxPacketSize, connection_.max_packet_length());
2581}
2582
vasilvvebc5d0c2020-01-16 15:19:21 -08002583TEST_P(QuicConnectionTest, PeerCannotRaiseMaxPacketSize) {
2584 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2585
2586 // SetFromConfig is always called after construction from InitializeSession.
2587 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2588 constexpr uint32_t kTestMaxPacketSize = 1450u;
2589 QuicConfig config;
2590 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
2591 connection_.SetFromConfig(config);
2592
2593 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
2594}
2595
QUICHE teama6ef0a62019-03-07 20:34:33 -05002596TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
2597 TestConnection connection(TestConnectionId(), kPeerAddress, helper_.get(),
2598 alarm_factory_.get(), writer_.get(),
2599 Perspective::IS_SERVER, version());
2600 EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
2601 EXPECT_EQ(1000u, connection.max_packet_length());
2602}
2603
2604TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002605 set_perspective(Perspective::IS_SERVER);
2606 connection_.SetMaxPacketLength(1000);
2607
2608 QuicPacketHeader header;
2609 header.destination_connection_id = connection_id_;
2610 header.version_flag = true;
nharper21af28e2019-06-17 15:54:34 -07002611 header.packet_number = QuicPacketNumber(12);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002612
2613 if (QuicVersionHasLongHeaderLengths(
2614 peer_framer_.version().transport_version)) {
2615 header.long_packet_type = INITIAL;
2616 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2617 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2618 }
2619
2620 QuicFrames frames;
2621 QuicPaddingFrame padding;
nharper46833c32019-05-15 21:33:05 -07002622 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2623 frames.push_back(QuicFrame(&crypto_frame_));
2624 } else {
2625 frames.push_back(QuicFrame(frame1_));
2626 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002627 frames.push_back(QuicFrame(padding));
2628 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07002629 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002630 size_t encrypted_length =
2631 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07002632 *packet, buffer, kMaxOutgoingPacketSize);
2633 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002634
2635 framer_.set_version(version());
nharper46833c32019-05-15 21:33:05 -07002636 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2637 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2638 } else {
2639 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2640 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002641 connection_.ProcessUdpPacket(
2642 kSelfAddress, kPeerAddress,
2643 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2644
dschinazi66dea072019-04-09 11:41:06 -07002645 EXPECT_EQ(kMaxOutgoingPacketSize, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002646}
2647
2648TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSizeWhileWriterLimited) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05002649 const QuicByteCount lower_max_packet_size = 1240;
2650 writer_->set_max_packet_size(lower_max_packet_size);
2651 set_perspective(Perspective::IS_SERVER);
2652 connection_.SetMaxPacketLength(1000);
2653 EXPECT_EQ(1000u, connection_.max_packet_length());
2654
2655 QuicPacketHeader header;
2656 header.destination_connection_id = connection_id_;
2657 header.version_flag = true;
nharper21af28e2019-06-17 15:54:34 -07002658 header.packet_number = QuicPacketNumber(12);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002659
2660 if (QuicVersionHasLongHeaderLengths(
2661 peer_framer_.version().transport_version)) {
2662 header.long_packet_type = INITIAL;
2663 header.retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_1;
2664 header.length_length = VARIABLE_LENGTH_INTEGER_LENGTH_2;
2665 }
2666
2667 QuicFrames frames;
2668 QuicPaddingFrame padding;
nharper46833c32019-05-15 21:33:05 -07002669 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2670 frames.push_back(QuicFrame(&crypto_frame_));
2671 } else {
2672 frames.push_back(QuicFrame(frame1_));
2673 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002674 frames.push_back(QuicFrame(padding));
2675 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
dschinazi66dea072019-04-09 11:41:06 -07002676 char buffer[kMaxOutgoingPacketSize];
QUICHE team6987b4a2019-03-15 16:23:04 -07002677 size_t encrypted_length =
2678 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
dschinazi66dea072019-04-09 11:41:06 -07002679 *packet, buffer, kMaxOutgoingPacketSize);
2680 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002681
2682 framer_.set_version(version());
nharper46833c32019-05-15 21:33:05 -07002683 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2684 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2685 } else {
2686 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2687 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002688 connection_.ProcessUdpPacket(
2689 kSelfAddress, kPeerAddress,
2690 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
2691
2692 // Here, the limit imposed by the writer is lower than the size of the packet
2693 // received, so the writer max packet size is used.
2694 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2695}
2696
2697TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriter) {
2698 const QuicByteCount lower_max_packet_size = 1240;
2699 writer_->set_max_packet_size(lower_max_packet_size);
2700
2701 static_assert(lower_max_packet_size < kDefaultMaxPacketSize,
2702 "Default maximum packet size is too low");
2703 connection_.SetMaxPacketLength(kDefaultMaxPacketSize);
2704
2705 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
2706}
2707
2708TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriterForNewConnection) {
2709 const QuicConnectionId connection_id = TestConnectionId(17);
2710 const QuicByteCount lower_max_packet_size = 1240;
2711 writer_->set_max_packet_size(lower_max_packet_size);
2712 TestConnection connection(connection_id, kPeerAddress, helper_.get(),
2713 alarm_factory_.get(), writer_.get(),
2714 Perspective::IS_CLIENT, version());
2715 EXPECT_EQ(Perspective::IS_CLIENT, connection.perspective());
2716 EXPECT_EQ(lower_max_packet_size, connection.max_packet_length());
2717}
2718
2719TEST_P(QuicConnectionTest, PacketsInOrder) {
2720 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2721
2722 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07002723 EXPECT_EQ(QuicPacketNumber(1u), LargestAcked(connection_.ack_frame()));
2724 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002725
2726 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002727 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(connection_.ack_frame()));
2728 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002729
2730 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002731 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
2732 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002733}
2734
2735TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
2736 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2737
2738 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002739 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002740 EXPECT_TRUE(IsMissing(2));
2741 EXPECT_TRUE(IsMissing(1));
2742
2743 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002744 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002745 EXPECT_FALSE(IsMissing(2));
2746 EXPECT_TRUE(IsMissing(1));
2747
2748 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07002749 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002750 EXPECT_FALSE(IsMissing(2));
2751 EXPECT_FALSE(IsMissing(1));
2752}
2753
2754TEST_P(QuicConnectionTest, DuplicatePacket) {
2755 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2756
2757 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002758 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002759 EXPECT_TRUE(IsMissing(2));
2760 EXPECT_TRUE(IsMissing(1));
2761
2762 // Send packet 3 again, but do not set the expectation that
2763 // the visitor OnStreamFrame() will be called.
2764 ProcessDataPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002765 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002766 EXPECT_TRUE(IsMissing(2));
2767 EXPECT_TRUE(IsMissing(1));
2768}
2769
2770TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
QUICHE teamcd098022019-03-22 18:49:55 -07002771 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2772 return;
2773 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002774 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2775
2776 ProcessPacket(3);
fayangc31c9952019-06-05 13:54:48 -07002777 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002778 EXPECT_TRUE(IsMissing(2));
2779 EXPECT_TRUE(IsMissing(1));
2780
2781 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07002782 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002783 EXPECT_TRUE(IsMissing(1));
2784
2785 ProcessPacket(5);
fayangc31c9952019-06-05 13:54:48 -07002786 EXPECT_EQ(QuicPacketNumber(5u), LargestAcked(connection_.ack_frame()));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002787 EXPECT_TRUE(IsMissing(1));
2788 EXPECT_TRUE(IsMissing(4));
2789
2790 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
2791 // packet the peer will not retransmit. It indicates this by sending 'least
2792 // awaiting' is 4. The connection should then realize 1 will not be
2793 // retransmitted, and will remove it from the missing list.
2794 QuicAckFrame frame = InitAckFrame(1);
2795 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
2796 ProcessAckPacket(6, &frame);
2797
2798 // Force an ack to be sent.
2799 SendAckPacketToPeer();
2800 EXPECT_TRUE(IsMissing(4));
2801}
2802
QUICHE teama6ef0a62019-03-07 20:34:33 -05002803TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
2804 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
2805 if (!IsDefaultTestConfiguration()) {
2806 return;
2807 }
2808
2809 // Process an unencrypted packet from the non-crypto stream.
2810 frame1_.stream_id = 3;
2811 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fkastenholz5d880a92019-06-21 09:01:56 -07002812 EXPECT_CALL(visitor_,
2813 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
nharper2c9f02a2019-05-08 10:25:50 -07002814 EXPECT_QUIC_PEER_BUG(ProcessDataPacketAtLevel(1, false, ENCRYPTION_INITIAL),
2815 "");
fkastenholz5d880a92019-06-21 09:01:56 -07002816 TestConnectionCloseQuicErrorCode(QUIC_UNENCRYPTED_STREAM_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002817}
2818
2819TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
2820 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2821
2822 ProcessPacket(3);
fayang6dba4902019-06-17 10:04:23 -07002823 // Should not cause an ack.
2824 EXPECT_EQ(0u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002825
2826 ProcessPacket(2);
fayang6dba4902019-06-17 10:04:23 -07002827 // Should ack immediately, since this fills the last hole.
2828 EXPECT_EQ(1u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002829
2830 ProcessPacket(1);
2831 // Should ack immediately, since this fills the last hole.
fayang6dba4902019-06-17 10:04:23 -07002832 EXPECT_EQ(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002833
2834 ProcessPacket(4);
2835 // Should not cause an ack.
fayang6dba4902019-06-17 10:04:23 -07002836 EXPECT_EQ(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002837}
2838
2839TEST_P(QuicConnectionTest, OutOfOrderAckReceiptCausesNoAck) {
2840 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2841
2842 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2843 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
2844 EXPECT_EQ(2u, writer_->packets_write_attempts());
2845
2846 QuicAckFrame ack1 = InitAckFrame(1);
2847 QuicAckFrame ack2 = InitAckFrame(2);
2848 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
fayang2f2915d2020-01-24 06:47:15 -08002849 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2850 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(1);
2851 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002852 ProcessAckPacket(2, &ack2);
2853 // Should ack immediately since we have missing packets.
2854 EXPECT_EQ(2u, writer_->packets_write_attempts());
2855
fayang2f2915d2020-01-24 06:47:15 -08002856 if (connection_.SupportsMultiplePacketNumberSpaces()) {
2857 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(0);
2858 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002859 ProcessAckPacket(1, &ack1);
2860 // Should not ack an ack filling a missing packet.
2861 EXPECT_EQ(2u, writer_->packets_write_attempts());
2862}
2863
2864TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
2865 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2866 QuicPacketNumber original, second;
2867
2868 QuicByteCount packet_size =
2869 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
2870 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
2871
2872 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
2873 // First nack triggers early retransmit.
2874 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07002875 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002876 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07002877 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
2878 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05002879 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2880 QuicPacketNumber retransmission;
2881 // Packet 1 is short header for IETF QUIC because the encryption level
2882 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangd4291e42019-05-30 10:31:21 -07002883 EXPECT_CALL(*send_algorithm_,
2884 OnPacketSent(_, _, _,
2885 VersionHasIetfInvariantHeader(
2886 GetParam().version.transport_version)
2887 ? packet_size
2888 : packet_size - kQuicVersionSize,
2889 _))
QUICHE teama6ef0a62019-03-07 20:34:33 -05002890 .WillOnce(SaveArg<2>(&retransmission));
2891
2892 ProcessAckPacket(&frame);
2893
2894 QuicAckFrame frame2 = ConstructAckFrame(retransmission, original);
2895 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2896 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
2897 ProcessAckPacket(&frame2);
2898
2899 // Now if the peer sends an ack which still reports the retransmitted packet
2900 // as missing, that will bundle an ack with data after two acks in a row
2901 // indicate the high water mark needs to be raised.
2902 EXPECT_CALL(*send_algorithm_,
2903 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
2904 connection_.SendStreamDataWithString(3, "foo", 6, NO_FIN);
2905 // No ack sent.
nharper55fa6132019-05-07 19:37:21 -07002906 size_t padding_frame_count = writer_->padding_frames().size();
2907 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002908 EXPECT_EQ(1u, writer_->stream_frames().size());
2909
2910 // No more packet loss for the rest of the test.
2911 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
2912 .Times(AnyNumber());
2913 ProcessAckPacket(&frame2);
2914 EXPECT_CALL(*send_algorithm_,
2915 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
fayang03916692019-05-22 17:57:18 -07002916 connection_.SendStreamDataWithString(3, "foofoofoo", 9, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002917 // Ack bundled.
2918 if (GetParam().no_stop_waiting) {
fayang8a27b0f2019-11-04 11:27:40 -08002919 // Do not ACK acks.
2920 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05002921 } else {
2922 EXPECT_EQ(3u, writer_->frame_count());
2923 }
2924 EXPECT_EQ(1u, writer_->stream_frames().size());
fayang8a27b0f2019-11-04 11:27:40 -08002925 if (GetParam().no_stop_waiting) {
fayang03916692019-05-22 17:57:18 -07002926 EXPECT_TRUE(writer_->ack_frames().empty());
2927 } else {
2928 EXPECT_FALSE(writer_->ack_frames().empty());
2929 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05002930
2931 // But an ack with no missing packets will not send an ack.
2932 AckPacket(original, &frame2);
2933 ProcessAckPacket(&frame2);
2934 ProcessAckPacket(&frame2);
2935}
2936
2937TEST_P(QuicConnectionTest, AckSentEveryNthPacket) {
2938 connection_.set_ack_frequency_before_ack_decimation(3);
2939
2940 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2941 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(39);
2942
2943 // Expect 13 acks, every 3rd packet.
2944 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(13);
2945 // Receives packets 1 - 39.
2946 for (size_t i = 1; i <= 39; ++i) {
2947 ProcessDataPacket(i);
2948 }
2949}
2950
2951TEST_P(QuicConnectionTest, AckDecimationReducesAcks) {
2952 const size_t kMinRttMs = 40;
2953 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
2954 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
2955 QuicTime::Delta::Zero(), QuicTime::Zero());
2956 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
2957
2958 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
2959
2960 // Start ack decimation from 10th packet.
2961 connection_.set_min_received_before_ack_decimation(10);
2962
2963 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2964 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(30);
2965
2966 // Expect 6 acks: 5 acks between packets 1-10, and ack at 20.
2967 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6);
2968 // Receives packets 1 - 29.
2969 for (size_t i = 1; i <= 29; ++i) {
2970 ProcessDataPacket(i);
2971 }
2972
2973 // We now receive the 30th packet, and so we send an ack.
2974 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2975 ProcessDataPacket(30);
2976}
2977
2978TEST_P(QuicConnectionTest, AckNeedsRetransmittableFrames) {
ianswett68cf0042019-05-09 08:37:58 -07002979 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05002980 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2981 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(99);
2982
2983 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
2984 // Receives packets 1 - 39.
2985 for (size_t i = 1; i <= 39; ++i) {
2986 ProcessDataPacket(i);
2987 }
2988 // Receiving Packet 40 causes 20th ack to send. Session is informed and adds
2989 // WINDOW_UPDATE.
2990 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
2991 .WillOnce(Invoke([this]() {
2992 connection_.SendControlFrame(
2993 QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
2994 }));
2995 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2996 EXPECT_EQ(0u, writer_->window_update_frames().size());
2997 ProcessDataPacket(40);
2998 EXPECT_EQ(1u, writer_->window_update_frames().size());
2999
3000 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
3001 // Receives packets 41 - 59.
3002 for (size_t i = 41; i <= 59; ++i) {
3003 ProcessDataPacket(i);
3004 }
3005 // Send a packet containing stream frame.
QUICHE team8c1daa22019-03-13 08:33:41 -07003006 SendStreamDataToPeer(
nharper46833c32019-05-15 21:33:05 -07003007 QuicUtils::GetFirstBidirectionalStreamId(
3008 connection_.version().transport_version, Perspective::IS_CLIENT),
QUICHE team8c1daa22019-03-13 08:33:41 -07003009 "bar", 0, NO_FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003010
3011 // Session will not be informed until receiving another 20 packets.
3012 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
3013 for (size_t i = 60; i <= 98; ++i) {
3014 ProcessDataPacket(i);
3015 EXPECT_EQ(0u, writer_->window_update_frames().size());
3016 }
3017 // Session does not add a retransmittable frame.
3018 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3019 .WillOnce(Invoke([this]() {
3020 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
3021 }));
3022 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3023 EXPECT_EQ(0u, writer_->ping_frames().size());
3024 ProcessDataPacket(99);
3025 EXPECT_EQ(0u, writer_->window_update_frames().size());
3026 // A ping frame will be added.
3027 EXPECT_EQ(1u, writer_->ping_frames().size());
3028}
3029
ianswett6083a102020-02-09 12:04:04 -08003030TEST_P(QuicConnectionTest, AckNeedsRetransmittableFramesAfterPto) {
ianswett6083a102020-02-09 12:04:04 -08003031 // Disable TLP so the RTO fires immediately.
3032 connection_.SetMaxTailLossProbes(0);
3033 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3034 QuicConfig config;
3035 QuicTagVector connection_options;
3036 connection_options.push_back(kEACK);
3037 config.SetConnectionOptionsToSend(connection_options);
3038 connection_.SetFromConfig(config);
3039
3040 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3041 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3042 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(10);
3043
3044 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
3045 // Receive packets 1 - 9.
3046 for (size_t i = 1; i <= 9; ++i) {
3047 ProcessDataPacket(i);
3048 }
3049
3050 // Send a ping and fire the retransmission alarm.
3051 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3052 SendPing();
3053 QuicTime retransmission_time =
3054 connection_.GetRetransmissionAlarm()->deadline();
3055 clock_.AdvanceTime(retransmission_time - clock_.Now());
3056 connection_.GetRetransmissionAlarm()->Fire();
3057 ASSERT_TRUE(manager_->GetConsecutiveRtoCount() > 0 ||
3058 manager_->GetConsecutivePtoCount() > 0);
3059
3060 // Process a packet, which requests a retransmittable frame be bundled
3061 // with the ACK.
3062 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3063 .WillOnce(Invoke([this]() {
3064 connection_.SendControlFrame(
3065 QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
3066 }));
3067 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3068 ProcessDataPacket(11);
3069 EXPECT_EQ(1u, writer_->window_update_frames().size());
3070}
3071
QUICHE teama6ef0a62019-03-07 20:34:33 -05003072TEST_P(QuicConnectionTest, LeastUnackedLower) {
fayangc31c9952019-06-05 13:54:48 -07003073 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003074 return;
3075 }
3076 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3077
3078 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3079 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3080 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
3081
3082 // Start out saying the least unacked is 2.
3083 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
3084 ProcessStopWaitingPacket(InitStopWaitingFrame(2));
3085
3086 // Change it to 1, but lower the packet number to fake out-of-order packets.
3087 // This should be fine.
3088 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
3089 // The scheduler will not process out of order acks, but all packet processing
3090 // causes the connection to try to write.
3091 if (!GetParam().no_stop_waiting) {
3092 EXPECT_CALL(visitor_, OnCanWrite());
3093 }
3094 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
3095
3096 // Now claim it's one, but set the ordering so it was sent "after" the first
3097 // one. This should cause a connection error.
3098 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 7);
3099 if (!GetParam().no_stop_waiting) {
rch39c88ab2019-10-16 19:24:40 -07003100 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3101 .Times(AtLeast(1));
fkastenholz5d880a92019-06-21 09:01:56 -07003102 EXPECT_CALL(visitor_,
rch39c88ab2019-10-16 19:24:40 -07003103 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
3104 .Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003105 }
3106 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
fkastenholz5d880a92019-06-21 09:01:56 -07003107 if (!GetParam().no_stop_waiting) {
3108 TestConnectionCloseQuicErrorCode(QUIC_INVALID_STOP_WAITING_DATA);
3109 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003110}
3111
3112TEST_P(QuicConnectionTest, TooManySentPackets) {
3113 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3114
3115 QuicPacketCount max_tracked_packets = 50;
3116 QuicConnectionPeer::SetMaxTrackedPackets(&connection_, max_tracked_packets);
3117
3118 const int num_packets = max_tracked_packets + 5;
3119
3120 for (int i = 0; i < num_packets; ++i) {
3121 SendStreamDataToPeer(1, "foo", 3 * i, NO_FIN, nullptr);
3122 }
3123
3124 // Ack packet 1, which leaves more than the limit outstanding.
3125 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3126 EXPECT_CALL(visitor_,
fkastenholz5d880a92019-06-21 09:01:56 -07003127 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003128
3129 // Nack the first packet and ack the rest, leaving a huge gap.
3130 QuicAckFrame frame1 = ConstructAckFrame(num_packets, 1);
3131 ProcessAckPacket(&frame1);
fkastenholz5d880a92019-06-21 09:01:56 -07003132 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003133}
3134
3135TEST_P(QuicConnectionTest, LargestObservedLower) {
3136 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3137
3138 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3139 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3140 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
3141 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3142
3143 // Start out saying the largest observed is 2.
3144 QuicAckFrame frame1 = InitAckFrame(1);
3145 QuicAckFrame frame2 = InitAckFrame(2);
3146 ProcessAckPacket(&frame2);
3147
fayang745c93a2019-06-21 13:43:04 -07003148 EXPECT_CALL(visitor_, OnCanWrite());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003149 ProcessAckPacket(&frame1);
3150}
3151
3152TEST_P(QuicConnectionTest, AckUnsentData) {
3153 // Ack a packet which has not been sent.
fkastenholz5d880a92019-06-21 09:01:56 -07003154 EXPECT_CALL(visitor_,
3155 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003156 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
rch39c88ab2019-10-16 19:24:40 -07003157 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003158 QuicAckFrame frame = InitAckFrame(1);
3159 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
3160 ProcessAckPacket(&frame);
fkastenholz5d880a92019-06-21 09:01:56 -07003161 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003162}
3163
3164TEST_P(QuicConnectionTest, BasicSending) {
QUICHE teamcd098022019-03-22 18:49:55 -07003165 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3166 return;
3167 }
fayang643c7dd2020-05-18 07:11:27 -07003168 const QuicConnectionStats& stats = connection_.GetStats();
3169 EXPECT_FALSE(stats.first_decrypted_packet.IsInitialized());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003170 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3171 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3172 ProcessDataPacket(1);
fayang643c7dd2020-05-18 07:11:27 -07003173 EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003174 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3175 QuicPacketNumber last_packet;
3176 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3177 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
3178 SendAckPacketToPeer(); // Packet 2
3179
3180 if (GetParam().no_stop_waiting) {
3181 // Expect no stop waiting frame is sent.
3182 EXPECT_FALSE(least_unacked().IsInitialized());
3183 } else {
3184 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
3185 }
3186
3187 SendAckPacketToPeer(); // Packet 3
3188 if (GetParam().no_stop_waiting) {
3189 // Expect no stop waiting frame is sent.
3190 EXPECT_FALSE(least_unacked().IsInitialized());
3191 } else {
3192 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
3193 }
3194
3195 SendStreamDataToPeer(1, "bar", 3, NO_FIN, &last_packet); // Packet 4
3196 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
3197 SendAckPacketToPeer(); // Packet 5
3198 if (GetParam().no_stop_waiting) {
3199 // Expect no stop waiting frame is sent.
3200 EXPECT_FALSE(least_unacked().IsInitialized());
3201 } else {
3202 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
3203 }
3204
3205 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3206
3207 // Peer acks up to packet 3.
3208 QuicAckFrame frame = InitAckFrame(3);
3209 ProcessAckPacket(&frame);
3210 SendAckPacketToPeer(); // Packet 6
3211
3212 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
3213 // ack for 4.
3214 if (GetParam().no_stop_waiting) {
3215 // Expect no stop waiting frame is sent.
3216 EXPECT_FALSE(least_unacked().IsInitialized());
3217 } else {
3218 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
3219 }
3220
3221 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3222
3223 // Peer acks up to packet 4, the last packet.
3224 QuicAckFrame frame2 = InitAckFrame(6);
3225 ProcessAckPacket(&frame2); // Acks don't instigate acks.
3226
3227 // Verify that we did not send an ack.
3228 EXPECT_EQ(QuicPacketNumber(6u), writer_->header().packet_number);
3229
3230 // So the last ack has not changed.
3231 if (GetParam().no_stop_waiting) {
3232 // Expect no stop waiting frame is sent.
3233 EXPECT_FALSE(least_unacked().IsInitialized());
3234 } else {
3235 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
3236 }
3237
3238 // If we force an ack, we shouldn't change our retransmit state.
3239 SendAckPacketToPeer(); // Packet 7
3240 if (GetParam().no_stop_waiting) {
3241 // Expect no stop waiting frame is sent.
3242 EXPECT_FALSE(least_unacked().IsInitialized());
3243 } else {
3244 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
3245 }
3246
3247 // But if we send more data it should.
3248 SendStreamDataToPeer(1, "eep", 6, NO_FIN, &last_packet); // Packet 8
3249 EXPECT_EQ(QuicPacketNumber(8u), last_packet);
3250 SendAckPacketToPeer(); // Packet 9
3251 if (GetParam().no_stop_waiting) {
3252 // Expect no stop waiting frame is sent.
3253 EXPECT_FALSE(least_unacked().IsInitialized());
3254 } else {
3255 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
3256 }
fayang643c7dd2020-05-18 07:11:27 -07003257 EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003258}
3259
3260// QuicConnection should record the packet sent-time prior to sending the
3261// packet.
3262TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
3263 // We're using a MockClock for the tests, so we have complete control over the
3264 // time.
3265 // Our recorded timestamp for the last packet sent time will be passed in to
3266 // the send_algorithm. Make sure that it is set to the correct value.
3267 QuicTime actual_recorded_send_time = QuicTime::Zero();
3268 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3269 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3270
3271 // First send without any pause and check the result.
3272 QuicTime expected_recorded_send_time = clock_.Now();
3273 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3274 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3275 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3276 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3277
3278 // Now pause during the write, and check the results.
3279 actual_recorded_send_time = QuicTime::Zero();
3280 const QuicTime::Delta write_pause_time_delta =
3281 QuicTime::Delta::FromMilliseconds(5000);
3282 SetWritePauseTimeDelta(write_pause_time_delta);
3283 expected_recorded_send_time = clock_.Now();
3284
3285 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3286 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3287 connection_.SendStreamDataWithString(2, "baz", 0, NO_FIN);
3288 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3289 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3290 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3291}
3292
3293TEST_P(QuicConnectionTest, FramePacking) {
3294 // Send two stream frames in 1 packet by queueing them.
3295 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3296 {
fayanga4b37b22019-06-18 13:37:47 -07003297 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003298 connection_.SendStreamData3();
3299 connection_.SendStreamData5();
3300 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3301 }
3302 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3303 EXPECT_FALSE(connection_.HasQueuedData());
3304
3305 // Parse the last packet and ensure it's an ack and two stream frames from
3306 // two different streams.
3307 if (GetParam().no_stop_waiting) {
3308 EXPECT_EQ(2u, writer_->frame_count());
3309 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3310 } else {
3311 EXPECT_EQ(2u, writer_->frame_count());
3312 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3313 }
3314
3315 EXPECT_TRUE(writer_->ack_frames().empty());
3316
3317 ASSERT_EQ(2u, writer_->stream_frames().size());
3318 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3319 writer_->stream_frames()[0]->stream_id);
3320 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3321 writer_->stream_frames()[1]->stream_id);
3322}
3323
3324TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
3325 // Send two stream frames (one non-crypto, then one crypto) in 2 packets by
3326 // queueing them.
3327 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3328 {
3329 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
fayanga4b37b22019-06-18 13:37:47 -07003330 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003331 connection_.SendStreamData3();
fayang58f71072019-11-05 08:47:02 -08003332 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003333 connection_.SendCryptoStreamData();
fayang58f71072019-11-05 08:47:02 -08003334 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003335 }
3336 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3337 EXPECT_FALSE(connection_.HasQueuedData());
3338
3339 // Parse the last packet and ensure it's the crypto stream frame.
3340 EXPECT_EQ(2u, writer_->frame_count());
3341 ASSERT_EQ(1u, writer_->padding_frames().size());
QUICHE teamea740082019-03-11 17:58:43 -07003342 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05003343 ASSERT_EQ(1u, writer_->stream_frames().size());
3344 EXPECT_EQ(QuicUtils::GetCryptoStreamId(connection_.transport_version()),
3345 writer_->stream_frames()[0]->stream_id);
3346 } else {
3347 EXPECT_EQ(1u, writer_->crypto_frames().size());
3348 }
3349}
3350
3351TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
3352 // Send two stream frames (one crypto, then one non-crypto) in 2 packets by
3353 // queueing them.
3354 {
3355 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3356 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
fayanga4b37b22019-06-18 13:37:47 -07003357 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003358 connection_.SendCryptoStreamData();
3359 connection_.SendStreamData3();
3360 }
3361 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3362 EXPECT_FALSE(connection_.HasQueuedData());
3363
3364 // Parse the last packet and ensure it's the stream frame from stream 3.
nharper55fa6132019-05-07 19:37:21 -07003365 size_t padding_frame_count = writer_->padding_frames().size();
3366 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003367 ASSERT_EQ(1u, writer_->stream_frames().size());
3368 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3369 writer_->stream_frames()[0]->stream_id);
3370}
3371
3372TEST_P(QuicConnectionTest, FramePackingAckResponse) {
3373 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3374 // Process a data packet to queue up a pending ack.
fayang3451f6e2019-06-11 08:18:12 -07003375 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3376 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3377 } else {
3378 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3379 }
3380 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
3381
QUICHE teama6ef0a62019-03-07 20:34:33 -05003382 QuicPacketNumber last_packet;
nharper46833c32019-05-15 21:33:05 -07003383 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3384 connection_.SendCryptoDataWithString("foo", 0);
3385 } else {
3386 SendStreamDataToPeer(
3387 QuicUtils::GetCryptoStreamId(connection_.transport_version()), "foo", 0,
3388 NO_FIN, &last_packet);
3389 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003390 // Verify ack is bundled with outging packet.
3391 EXPECT_FALSE(writer_->ack_frames().empty());
3392
3393 EXPECT_CALL(visitor_, OnCanWrite())
3394 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3395 &connection_, &TestConnection::SendStreamData3)),
3396 IgnoreResult(InvokeWithoutArgs(
3397 &connection_, &TestConnection::SendStreamData5))));
3398
3399 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3400
3401 // Process a data packet to cause the visitor's OnCanWrite to be invoked.
3402 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07003403 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07003404 std::make_unique<TaggingEncrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07003405 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07003406 std::make_unique<StrictTaggingDecrypter>(0x01));
nharper2c9f02a2019-05-08 10:25:50 -07003407 ProcessDataPacket(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003408
3409 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3410 EXPECT_FALSE(connection_.HasQueuedData());
3411
3412 // Parse the last packet and ensure it's an ack and two stream frames from
3413 // two different streams.
3414 if (GetParam().no_stop_waiting) {
3415 EXPECT_EQ(3u, writer_->frame_count());
3416 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3417 } else {
3418 EXPECT_EQ(4u, writer_->frame_count());
3419 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3420 }
3421 EXPECT_FALSE(writer_->ack_frames().empty());
3422 ASSERT_EQ(2u, writer_->stream_frames().size());
3423 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3424 writer_->stream_frames()[0]->stream_id);
3425 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3426 writer_->stream_frames()[1]->stream_id);
3427}
3428
3429TEST_P(QuicConnectionTest, FramePackingSendv) {
nharper46833c32019-05-15 21:33:05 -07003430 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003431 // Send data in 1 packet by writing multiple blocks in a single iovector
3432 // using writev.
3433 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3434
3435 char data[] = "ABCDEF";
3436 struct iovec iov[2];
3437 iov[0].iov_base = data;
3438 iov[0].iov_len = 4;
3439 iov[1].iov_base = data + 4;
3440 iov[1].iov_len = 2;
nharper46833c32019-05-15 21:33:05 -07003441 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3442 connection_.transport_version(), Perspective::IS_CLIENT);
3443 connection_.SaveAndSendStreamData(stream_id, iov, 2, 6, 0, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003444
3445 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3446 EXPECT_FALSE(connection_.HasQueuedData());
3447
3448 // Parse the last packet and ensure multiple iovector blocks have
3449 // been packed into a single stream frame from one stream.
nharper46833c32019-05-15 21:33:05 -07003450 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003451 EXPECT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003452 EXPECT_EQ(0u, writer_->padding_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003453 QuicStreamFrame* frame = writer_->stream_frames()[0].get();
nharper46833c32019-05-15 21:33:05 -07003454 EXPECT_EQ(stream_id, frame->stream_id);
dmcardlecf0bfcf2019-12-13 08:08:21 -08003455 EXPECT_EQ("ABCDEF",
3456 quiche::QuicheStringPiece(frame->data_buffer, frame->data_length));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003457}
3458
3459TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
nharper46833c32019-05-15 21:33:05 -07003460 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003461 // Try to send two stream frames in 1 packet by using writev.
3462 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3463
3464 BlockOnNextWrite();
3465 char data[] = "ABCDEF";
3466 struct iovec iov[2];
3467 iov[0].iov_base = data;
3468 iov[0].iov_len = 4;
3469 iov[1].iov_base = data + 4;
3470 iov[1].iov_len = 2;
nharper46833c32019-05-15 21:33:05 -07003471 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3472 connection_.transport_version(), Perspective::IS_CLIENT);
3473 connection_.SaveAndSendStreamData(stream_id, iov, 2, 6, 0, NO_FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003474
3475 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3476 EXPECT_TRUE(connection_.HasQueuedData());
3477
3478 // Unblock the writes and actually send.
3479 writer_->SetWritable();
3480 connection_.OnCanWrite();
3481 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3482
3483 // Parse the last packet and ensure it's one stream frame from one stream.
nharper46833c32019-05-15 21:33:05 -07003484 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003485 EXPECT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003486 EXPECT_EQ(0u, writer_->padding_frames().size());
3487 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003488}
3489
3490TEST_P(QuicConnectionTest, SendingZeroBytes) {
3491 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3492 // Send a zero byte write with a fin using writev.
3493 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
nharper46833c32019-05-15 21:33:05 -07003494 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3495 connection_.transport_version(), Perspective::IS_CLIENT);
3496 connection_.SaveAndSendStreamData(stream_id, nullptr, 0, 0, 0, FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003497
3498 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3499 EXPECT_FALSE(connection_.HasQueuedData());
3500
nharper55fa6132019-05-07 19:37:21 -07003501 // Padding frames are added by v99 to ensure a minimum packet size.
3502 size_t extra_padding_frames = 0;
3503 if (GetParam().version.HasHeaderProtection()) {
3504 extra_padding_frames = 1;
3505 }
3506
QUICHE teama6ef0a62019-03-07 20:34:33 -05003507 // Parse the last packet and ensure it's one stream frame from one stream.
nharper55fa6132019-05-07 19:37:21 -07003508 EXPECT_EQ(1u + extra_padding_frames, writer_->frame_count());
3509 EXPECT_EQ(extra_padding_frames, writer_->padding_frames().size());
3510 ASSERT_EQ(1u, writer_->stream_frames().size());
nharper46833c32019-05-15 21:33:05 -07003511 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003512 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3513}
3514
3515TEST_P(QuicConnectionTest, LargeSendWithPendingAck) {
3516 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
fayang15042962020-07-01 12:14:29 -07003517 EXPECT_CALL(visitor_, GetHandshakeState())
3518 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003519 // Set the ack alarm by processing a ping frame.
3520 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3521
3522 // Processs a PING frame.
3523 ProcessFramePacket(QuicFrame(QuicPingFrame()));
3524 // Ensure that this has caused the ACK alarm to be set.
fayang9adfb532020-06-04 06:58:45 -07003525 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003526
3527 // Send data and ensure the ack is bundled.
3528 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(8);
3529 size_t len = 10000;
3530 std::unique_ptr<char[]> data_array(new char[len]);
3531 memset(data_array.get(), '?', len);
3532 struct iovec iov;
3533 iov.iov_base = data_array.get();
3534 iov.iov_len = len;
3535 QuicConsumedData consumed = connection_.SaveAndSendStreamData(
dschinazi552accc2019-06-17 17:07:34 -07003536 GetNthClientInitiatedStreamId(0, connection_.transport_version()), &iov,
3537 1, len, 0, FIN);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003538 EXPECT_EQ(len, consumed.bytes_consumed);
3539 EXPECT_TRUE(consumed.fin_consumed);
3540 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3541 EXPECT_FALSE(connection_.HasQueuedData());
3542
3543 // Parse the last packet and ensure it's one stream frame with a fin.
3544 EXPECT_EQ(1u, writer_->frame_count());
nharper55fa6132019-05-07 19:37:21 -07003545 ASSERT_EQ(1u, writer_->stream_frames().size());
dschinazi552accc2019-06-17 17:07:34 -07003546 EXPECT_EQ(GetNthClientInitiatedStreamId(0, connection_.transport_version()),
QUICHE teama6ef0a62019-03-07 20:34:33 -05003547 writer_->stream_frames()[0]->stream_id);
3548 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3549 // Ensure the ack alarm was cancelled when the ack was sent.
fayang9adfb532020-06-04 06:58:45 -07003550 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003551}
3552
3553TEST_P(QuicConnectionTest, OnCanWrite) {
3554 // Visitor's OnCanWrite will send data, but will have more pending writes.
3555 EXPECT_CALL(visitor_, OnCanWrite())
3556 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3557 &connection_, &TestConnection::SendStreamData3)),
3558 IgnoreResult(InvokeWithoutArgs(
3559 &connection_, &TestConnection::SendStreamData5))));
3560 {
3561 InSequence seq;
3562 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
3563 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
3564 .WillRepeatedly(Return(false));
3565 }
3566
3567 EXPECT_CALL(*send_algorithm_, CanSend(_))
3568 .WillRepeatedly(testing::Return(true));
3569
3570 connection_.OnCanWrite();
3571
3572 // Parse the last packet and ensure it's the two stream frames from
3573 // two different streams.
3574 EXPECT_EQ(2u, writer_->frame_count());
3575 EXPECT_EQ(2u, writer_->stream_frames().size());
3576 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3577 writer_->stream_frames()[0]->stream_id);
3578 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3579 writer_->stream_frames()[1]->stream_id);
3580}
3581
3582TEST_P(QuicConnectionTest, RetransmitOnNack) {
3583 QuicPacketNumber last_packet;
3584 QuicByteCount second_packet_size;
3585 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 1
3586 second_packet_size =
3587 SendStreamDataToPeer(3, "foos", 3, NO_FIN, &last_packet); // Packet 2
3588 SendStreamDataToPeer(3, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3589
3590 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3591
3592 // Don't lose a packet on an ack, and nothing is retransmitted.
3593 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3594 QuicAckFrame ack_one = InitAckFrame(1);
3595 ProcessAckPacket(&ack_one);
3596
3597 // Lose a packet and ensure it triggers retransmission.
3598 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3599 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003600 lost_packets.push_back(
3601 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003602 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003603 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3604 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003605 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3606 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3607 EXPECT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
3608 ProcessAckPacket(&nack_two);
3609}
3610
3611TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
3612 // Block the connection to queue the packet.
3613 BlockOnNextWrite();
3614
3615 QuicStreamId stream_id = 2;
3616 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3617
3618 // Now that there is a queued packet, reset the stream.
3619 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3620
3621 // Unblock the connection and verify that only the RST_STREAM is sent.
3622 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3623 writer_->SetWritable();
3624 connection_.OnCanWrite();
nharper55fa6132019-05-07 19:37:21 -07003625 size_t padding_frame_count = writer_->padding_frames().size();
3626 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003627 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3628}
3629
3630TEST_P(QuicConnectionTest, SendQueuedPacketForQuicRstStreamNoError) {
3631 // Block the connection to queue the packet.
3632 BlockOnNextWrite();
3633
3634 QuicStreamId stream_id = 2;
fayange62e63c2019-12-04 07:16:25 -08003635 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003636 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
3637
3638 // Now that there is a queued packet, reset the stream.
3639 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3640
3641 // Unblock the connection and verify that the RST_STREAM is sent and the data
3642 // packet is sent.
fayange62e63c2019-12-04 07:16:25 -08003643 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003644 writer_->SetWritable();
3645 connection_.OnCanWrite();
nharper55fa6132019-05-07 19:37:21 -07003646 size_t padding_frame_count = writer_->padding_frames().size();
3647 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003648 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3649}
3650
3651TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
3652 QuicStreamId stream_id = 2;
3653 QuicPacketNumber last_packet;
3654 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3655 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3656 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3657
3658 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3659 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3660
3661 // Lose a packet and ensure it does not trigger retransmission.
3662 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3663 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3664 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3665 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3666 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3667 ProcessAckPacket(&nack_two);
3668}
3669
3670TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnNack) {
3671 QuicStreamId stream_id = 2;
3672 QuicPacketNumber last_packet;
3673 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3674 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3675 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
3676
3677 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3678 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3679
3680 // Lose a packet, ensure it triggers retransmission.
3681 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
3682 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3683 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003684 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003685 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003686 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3687 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003688 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3689 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
3690 ProcessAckPacket(&nack_two);
3691}
3692
3693TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
3694 QuicStreamId stream_id = 2;
3695 QuicPacketNumber last_packet;
3696 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3697
3698 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3699 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3700
3701 // Fire the RTO and verify that the RST_STREAM is resent, not stream data.
3702 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3703 clock_.AdvanceTime(DefaultRetransmissionTime());
3704 connection_.GetRetransmissionAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07003705 size_t padding_frame_count = writer_->padding_frames().size();
3706 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003707 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3708 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3709}
3710
3711// Ensure that if the only data in flight is non-retransmittable, the
3712// retransmission alarm is not set.
3713TEST_P(QuicConnectionTest, CancelRetransmissionAlarmAfterResetStream) {
3714 QuicStreamId stream_id = 2;
3715 QuicPacketNumber last_data_packet;
3716 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
3717
3718 // Cancel the stream.
3719 const QuicPacketNumber rst_packet = last_data_packet + 1;
3720 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, rst_packet, _, _)).Times(1);
3721 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
3722
3723 // Ack the RST_STREAM frame (since it's retransmittable), but not the data
3724 // packet, which is no longer retransmittable since the stream was cancelled.
3725 QuicAckFrame nack_stream_data =
3726 ConstructAckFrame(rst_packet, last_data_packet);
3727 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3728 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3729 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3730 ProcessAckPacket(&nack_stream_data);
3731
3732 // Ensure that the data is still in flight, but the retransmission alarm is no
3733 // longer set.
ianswett9f459cb2019-04-21 06:39:59 -07003734 EXPECT_GT(manager_->GetBytesInFlight(), 0u);
fayangcff885a2019-10-22 07:39:04 -07003735 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003736}
3737
3738TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnRTO) {
3739 connection_.SetMaxTailLossProbes(0);
3740
3741 QuicStreamId stream_id = 2;
3742 QuicPacketNumber last_packet;
3743 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3744
3745 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3746 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
3747
3748 // Fire the RTO and verify that the RST_STREAM is resent, the stream data
3749 // is sent.
fayang1c2d1ab2020-03-11 12:08:41 -07003750 const size_t num_retransmissions =
3751 connection_.SupportsMultiplePacketNumberSpaces() ? 1 : 2;
3752 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3753 .Times(AtLeast(num_retransmissions));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003754 clock_.AdvanceTime(DefaultRetransmissionTime());
3755 connection_.GetRetransmissionAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07003756 size_t padding_frame_count = writer_->padding_frames().size();
3757 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
fayang1c2d1ab2020-03-11 12:08:41 -07003758 if (num_retransmissions == 2) {
3759 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
3760 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3761 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003762}
3763
3764TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
3765 QuicStreamId stream_id = 2;
3766 QuicPacketNumber last_packet;
3767 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3768 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3769 BlockOnNextWrite();
3770 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3771
3772 // Lose a packet which will trigger a pending retransmission.
3773 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3774 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3775 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3776 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3777 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3778 ProcessAckPacket(&ack);
3779
3780 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
3781
3782 // Unblock the connection and verify that the RST_STREAM is sent but not the
3783 // second data packet nor a retransmit.
3784 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3785 writer_->SetWritable();
3786 connection_.OnCanWrite();
nharper55fa6132019-05-07 19:37:21 -07003787 size_t padding_frame_count = writer_->padding_frames().size();
3788 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
zhongyi546cc452019-04-12 15:27:49 -07003789 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003790 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
3791}
3792
3793TEST_P(QuicConnectionTest, SendPendingRetransmissionForQuicRstStreamNoError) {
3794 QuicStreamId stream_id = 2;
3795 QuicPacketNumber last_packet;
3796 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
3797 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
3798 BlockOnNextWrite();
3799 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
3800
3801 // Lose a packet which will trigger a pending retransmission.
3802 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
3803 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3804 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003805 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003806 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003807 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3808 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003809 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3810 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3811 ProcessAckPacket(&ack);
3812
3813 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
3814
3815 // Unblock the connection and verify that the RST_STREAM is sent and the
3816 // second data packet or a retransmit is sent.
3817 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
3818 writer_->SetWritable();
3819 connection_.OnCanWrite();
3820 // The RST_STREAM_FRAME is sent after queued packets and pending
3821 // retransmission.
3822 connection_.SendControlFrame(QuicFrame(
3823 new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14)));
nharper55fa6132019-05-07 19:37:21 -07003824 size_t padding_frame_count = writer_->padding_frames().size();
3825 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003826 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
3827}
3828
3829TEST_P(QuicConnectionTest, RetransmitAckedPacket) {
3830 QuicPacketNumber last_packet;
3831 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3832 SendStreamDataToPeer(1, "foos", 3, NO_FIN, &last_packet); // Packet 2
3833 SendStreamDataToPeer(1, "fooos", 7, NO_FIN, &last_packet); // Packet 3
3834
3835 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3836
3837 // Instigate a loss with an ack.
3838 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3839 // The first nack should trigger a fast retransmission, but we'll be
3840 // write blocked, so the packet will be queued.
3841 BlockOnNextWrite();
3842
3843 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003844 lost_packets.push_back(
3845 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003846 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003847 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3848 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003849 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
fayange62e63c2019-12-04 07:16:25 -08003850 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
3851 .Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003852 ProcessAckPacket(&nack_two);
3853 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3854
3855 // Now, ack the previous transmission.
3856 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3857 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(false, _, _, _, _));
3858 QuicAckFrame ack_all = InitAckFrame(3);
3859 ProcessAckPacket(&ack_all);
3860
fayange62e63c2019-12-04 07:16:25 -08003861 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
3862 .Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003863
3864 writer_->SetWritable();
3865 connection_.OnCanWrite();
3866
3867 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3868 // We do not store retransmittable frames of this retransmission.
3869 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 4));
3870}
3871
3872TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
3873 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3874 QuicPacketNumber original, second;
3875
3876 QuicByteCount packet_size =
3877 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
3878 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
3879
3880 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
3881 // The first nack should retransmit the largest observed packet.
3882 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07003883 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003884 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07003885 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3886 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003887 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3888 // Packet 1 is short header for IETF QUIC because the encryption level
3889 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangd4291e42019-05-30 10:31:21 -07003890 EXPECT_CALL(*send_algorithm_,
3891 OnPacketSent(_, _, _,
3892 VersionHasIetfInvariantHeader(
3893 GetParam().version.transport_version)
3894 ? packet_size
3895 : packet_size - kQuicVersionSize,
3896 _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003897 ProcessAckPacket(&frame);
3898}
3899
3900TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) {
fayangcff885a2019-10-22 07:39:04 -07003901 if (connection_.PtoEnabled()) {
fayang5f135052019-08-22 17:59:40 -07003902 return;
3903 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05003904 connection_.SetMaxTailLossProbes(0);
3905
3906 for (int i = 0; i < 10; ++i) {
3907 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3908 connection_.SendStreamDataWithString(3, "foo", i * 3, NO_FIN);
3909 }
3910
3911 // Block the writer and ensure they're queued.
3912 BlockOnNextWrite();
3913 clock_.AdvanceTime(DefaultRetransmissionTime());
fayange62e63c2019-12-04 07:16:25 -08003914 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003915 connection_.GetRetransmissionAlarm()->Fire();
3916 EXPECT_TRUE(connection_.HasQueuedData());
3917
3918 // Unblock the writer.
3919 writer_->SetWritable();
3920 clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
3921 2 * DefaultRetransmissionTime().ToMicroseconds()));
fayange62e63c2019-12-04 07:16:25 -08003922 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003923 connection_.GetRetransmissionAlarm()->Fire();
3924 connection_.OnCanWrite();
3925}
3926
3927TEST_P(QuicConnectionTest, WriteBlockedBufferedThenSent) {
3928 BlockOnNextWrite();
3929 writer_->set_is_write_blocked_data_buffered(true);
3930 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3931 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3932 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3933
3934 writer_->SetWritable();
3935 connection_.OnCanWrite();
3936 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3937}
3938
3939TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
3940 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
3941 BlockOnNextWrite();
fayange62e63c2019-12-04 07:16:25 -08003942 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003943 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
fayange62e63c2019-12-04 07:16:25 -08003944 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003945 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3946
3947 // The second packet should also be queued, in order to ensure packets are
3948 // never sent out of order.
3949 writer_->SetWritable();
fayange62e63c2019-12-04 07:16:25 -08003950 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003951 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3952 EXPECT_EQ(2u, connection_.NumQueuedPackets());
3953
3954 // Now both are sent in order when we unblock.
fayange62e63c2019-12-04 07:16:25 -08003955 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05003956 connection_.OnCanWrite();
3957 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayang2ce66082019-10-02 06:29:04 -07003958 EXPECT_EQ(0u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05003959}
3960
3961TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
3962 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3963 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3964 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
3965
3966 BlockOnNextWrite();
3967 writer_->set_is_write_blocked_data_buffered(true);
3968 // Simulate the retransmission alarm firing.
3969 clock_.AdvanceTime(DefaultRetransmissionTime());
3970 connection_.GetRetransmissionAlarm()->Fire();
3971
3972 // Ack the sent packet before the callback returns, which happens in
3973 // rare circumstances with write blocked sockets.
3974 QuicAckFrame ack = InitAckFrame(1);
3975 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3976 ProcessAckPacket(&ack);
3977
3978 writer_->SetWritable();
3979 connection_.OnCanWrite();
fayangcff885a2019-10-22 07:39:04 -07003980 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayang5d011982020-05-13 14:14:38 -07003981 uint64_t retransmission = connection_.SupportsMultiplePacketNumberSpaces() &&
3982 !GetQuicReloadableFlag(quic_default_on_pto)
3983 ? 3
3984 : 2;
fayang1c2d1ab2020-03-11 12:08:41 -07003985 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_,
3986 retransmission));
QUICHE teama6ef0a62019-03-07 20:34:33 -05003987}
3988
3989TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
3990 // Block the connection.
3991 BlockOnNextWrite();
3992 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
3993 EXPECT_EQ(1u, writer_->packets_write_attempts());
3994 EXPECT_TRUE(writer_->IsWriteBlocked());
3995
3996 // Set the send alarm. Fire the alarm and ensure it doesn't attempt to write.
3997 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
3998 connection_.GetSendAlarm()->Fire();
3999 EXPECT_TRUE(writer_->IsWriteBlocked());
4000 EXPECT_EQ(1u, writer_->packets_write_attempts());
4001}
4002
4003TEST_P(QuicConnectionTest, NoSendAlarmAfterProcessPacketWhenWriteBlocked) {
4004 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4005
4006 // Block the connection.
4007 BlockOnNextWrite();
4008 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4009 EXPECT_TRUE(writer_->IsWriteBlocked());
4010 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4011 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4012
4013 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4014 // Process packet number 1. Can not call ProcessPacket or ProcessDataPacket
4015 // here, because they will fire the alarm after QuicConnection::ProcessPacket
4016 // is returned.
4017 const uint64_t received_packet_num = 1;
4018 const bool has_stop_waiting = false;
nharperc6b99512019-09-19 11:13:48 -07004019 const EncryptionLevel level = ENCRYPTION_FORWARD_SECURE;
4020 std::unique_ptr<QuicPacket> packet(
4021 ConstructDataPacket(received_packet_num, has_stop_waiting, level));
dschinazi66dea072019-04-09 11:41:06 -07004022 char buffer[kMaxOutgoingPacketSize];
QUICHE teama6ef0a62019-03-07 20:34:33 -05004023 size_t encrypted_length =
4024 peer_framer_.EncryptPayload(level, QuicPacketNumber(received_packet_num),
dschinazi66dea072019-04-09 11:41:06 -07004025 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004026 connection_.ProcessUdpPacket(
4027 kSelfAddress, kPeerAddress,
4028 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
4029
4030 EXPECT_TRUE(writer_->IsWriteBlocked());
4031 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4032}
4033
4034TEST_P(QuicConnectionTest, AddToWriteBlockedListIfWriterBlockedWhenProcessing) {
4035 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4036 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
4037
4038 // Simulate the case where a shared writer gets blocked by another connection.
4039 writer_->SetWriteBlocked();
4040
4041 // Process an ACK, make sure the connection calls visitor_->OnWriteBlocked().
4042 QuicAckFrame ack1 = InitAckFrame(1);
4043 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
4044 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
4045 ProcessAckPacket(1, &ack1);
4046}
4047
4048TEST_P(QuicConnectionTest, DoNotAddToWriteBlockedListAfterDisconnect) {
4049 writer_->SetBatchMode(true);
4050 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07004051 // Have to explicitly grab the OnConnectionClosed frame and check
4052 // its parameters because this is a silent connection close and the
4053 // frame is not also transmitted to the peer.
4054 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
4055 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004056
4057 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
4058
4059 {
fayanga4b37b22019-06-18 13:37:47 -07004060 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004061 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
4062 ConnectionCloseBehavior::SILENT_CLOSE);
4063
4064 EXPECT_FALSE(connection_.connected());
4065 writer_->SetWriteBlocked();
4066 }
fkastenholz5d880a92019-06-21 09:01:56 -07004067 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08004068 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
4069 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004070}
4071
4072TEST_P(QuicConnectionTest, AddToWriteBlockedListIfBlockedOnFlushPackets) {
4073 writer_->SetBatchMode(true);
4074 writer_->BlockOnNextFlush();
4075
4076 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
4077 {
fayanga4b37b22019-06-18 13:37:47 -07004078 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004079 // flusher's destructor will call connection_.FlushPackets, which should add
4080 // the connection to the write blocked list.
4081 }
4082}
4083
4084TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
4085 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4086 int offset = 0;
4087 // Send packets 1 to 15.
4088 for (int i = 0; i < 15; ++i) {
4089 SendStreamDataToPeer(1, "foo", offset, NO_FIN, nullptr);
4090 offset += 3;
4091 }
4092
4093 // Ack 15, nack 1-14.
4094
4095 QuicAckFrame nack =
4096 InitAckFrame({{QuicPacketNumber(15), QuicPacketNumber(16)}});
4097
4098 // 14 packets have been NACK'd and lost.
4099 LostPacketVector lost_packets;
4100 for (int i = 1; i < 15; ++i) {
dschinazi66dea072019-04-09 11:41:06 -07004101 lost_packets.push_back(
4102 LostPacket(QuicPacketNumber(i), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004103 }
4104 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07004105 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4106 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004107 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
fayangcff885a2019-10-22 07:39:04 -07004108 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004109 ProcessAckPacket(&nack);
4110}
4111
4112// Test sending multiple acks from the connection to the session.
4113TEST_P(QuicConnectionTest, MultipleAcks) {
QUICHE teamcd098022019-03-22 18:49:55 -07004114 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4115 return;
4116 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004117 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4118 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4119 ProcessDataPacket(1);
4120 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
4121 QuicPacketNumber last_packet;
4122 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
4123 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4124 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 2
4125 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4126 SendAckPacketToPeer(); // Packet 3
4127 SendStreamDataToPeer(5, "foo", 0, NO_FIN, &last_packet); // Packet 4
4128 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
4129 SendStreamDataToPeer(1, "foo", 3, NO_FIN, &last_packet); // Packet 5
4130 EXPECT_EQ(QuicPacketNumber(5u), last_packet);
4131 SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); // Packet 6
4132 EXPECT_EQ(QuicPacketNumber(6u), last_packet);
4133
4134 // Client will ack packets 1, 2, [!3], 4, 5.
4135 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4136 QuicAckFrame frame1 = ConstructAckFrame(5, 3);
4137 ProcessAckPacket(&frame1);
4138
4139 // Now the client implicitly acks 3, and explicitly acks 6.
4140 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4141 QuicAckFrame frame2 = InitAckFrame(6);
4142 ProcessAckPacket(&frame2);
4143}
4144
4145TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
QUICHE teamcd098022019-03-22 18:49:55 -07004146 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4147 return;
4148 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004149 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4150 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4151 ProcessDataPacket(1);
4152 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
4153 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr); // Packet 1;
4154 // From now on, we send acks, so the send algorithm won't mark them pending.
4155 SendAckPacketToPeer(); // Packet 2
4156
4157 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4158 QuicAckFrame frame = InitAckFrame(1);
4159 ProcessAckPacket(&frame);
4160
4161 // Verify that our internal state has least-unacked as 2, because we're still
4162 // waiting for a potential ack for 2.
4163
4164 EXPECT_EQ(QuicPacketNumber(2u), stop_waiting()->least_unacked);
4165
4166 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4167 frame = InitAckFrame(2);
4168 ProcessAckPacket(&frame);
4169 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
4170
4171 // When we send an ack, we make sure our least-unacked makes sense. In this
4172 // case since we're not waiting on an ack for 2 and all packets are acked, we
4173 // set it to 3.
4174 SendAckPacketToPeer(); // Packet 3
4175 // Least_unacked remains at 3 until another ack is received.
4176 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
4177 if (GetParam().no_stop_waiting) {
4178 // Expect no stop waiting frame is sent.
4179 EXPECT_FALSE(least_unacked().IsInitialized());
4180 } else {
4181 // Check that the outgoing ack had its packet number as least_unacked.
4182 EXPECT_EQ(QuicPacketNumber(3u), least_unacked());
4183 }
4184
4185 // Ack the ack, which updates the rtt and raises the least unacked.
4186 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4187 frame = InitAckFrame(3);
4188 ProcessAckPacket(&frame);
4189
4190 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr); // Packet 4
4191 EXPECT_EQ(QuicPacketNumber(4u), stop_waiting()->least_unacked);
4192 SendAckPacketToPeer(); // Packet 5
4193 if (GetParam().no_stop_waiting) {
4194 // Expect no stop waiting frame is sent.
4195 EXPECT_FALSE(least_unacked().IsInitialized());
4196 } else {
4197 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
4198 }
4199
4200 // Send two data packets at the end, and ensure if the last one is acked,
4201 // the least unacked is raised above the ack packets.
4202 SendStreamDataToPeer(1, "bar", 6, NO_FIN, nullptr); // Packet 6
4203 SendStreamDataToPeer(1, "bar", 9, NO_FIN, nullptr); // Packet 7
4204
4205 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4206 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)},
4207 {QuicPacketNumber(7), QuicPacketNumber(8)}});
4208 ProcessAckPacket(&frame);
4209
4210 EXPECT_EQ(QuicPacketNumber(6u), stop_waiting()->least_unacked);
4211}
4212
4213TEST_P(QuicConnectionTest, TLP) {
fayang5d011982020-05-13 14:14:38 -07004214 if (connection_.PtoEnabled()) {
4215 return;
4216 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004217 connection_.SetMaxTailLossProbes(1);
4218
4219 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4220 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4221 QuicTime retransmission_time =
4222 connection_.GetRetransmissionAlarm()->deadline();
4223 EXPECT_NE(QuicTime::Zero(), retransmission_time);
4224
4225 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4226 // Simulate the retransmission alarm firing and sending a tlp,
4227 // so send algorithm's OnRetransmissionTimeout is not called.
4228 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayang1c2d1ab2020-03-11 12:08:41 -07004229 const QuicPacketNumber retransmission(
4230 connection_.SupportsMultiplePacketNumberSpaces() ? 3 : 2);
4231 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, retransmission, _, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004232 connection_.GetRetransmissionAlarm()->Fire();
fayang1c2d1ab2020-03-11 12:08:41 -07004233 EXPECT_EQ(retransmission, writer_->header().packet_number);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004234 // We do not raise the high water mark yet.
4235 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4236}
4237
zhongyifbb25772019-04-10 16:54:08 -07004238TEST_P(QuicConnectionTest, TailLossProbeDelayForStreamDataInTLPR) {
fayangcff885a2019-10-22 07:39:04 -07004239 if (connection_.PtoEnabled()) {
zhongyi1b2f7832019-06-14 13:31:34 -07004240 return;
4241 }
4242
zhongyifbb25772019-04-10 16:54:08 -07004243 // Set TLPR from QuicConfig.
4244 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4245 QuicConfig config;
4246 QuicTagVector options;
4247 options.push_back(kTLPR);
4248 config.SetConnectionOptionsToSend(options);
4249 connection_.SetFromConfig(config);
4250 connection_.SetMaxTailLossProbes(1);
4251
4252 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4253 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4254
4255 QuicTime retransmission_time =
4256 connection_.GetRetransmissionAlarm()->deadline();
4257 EXPECT_NE(QuicTime::Zero(), retransmission_time);
4258 QuicTime::Delta expected_tlp_delay =
4259 0.5 * manager_->GetRttStats()->SmoothedOrInitialRtt();
4260 EXPECT_EQ(expected_tlp_delay, retransmission_time - clock_.Now());
4261
4262 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4263 // Simulate firing of the retransmission alarm and retransmit the packet.
4264 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
4265 clock_.AdvanceTime(retransmission_time - clock_.Now());
4266 connection_.GetRetransmissionAlarm()->Fire();
4267 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
4268
4269 // We do not raise the high water mark yet.
4270 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4271}
4272
4273TEST_P(QuicConnectionTest, TailLossProbeDelayForNonStreamDataInTLPR) {
fayangcff885a2019-10-22 07:39:04 -07004274 if (connection_.PtoEnabled()) {
zhongyi1b2f7832019-06-14 13:31:34 -07004275 return;
4276 }
4277
zhongyifbb25772019-04-10 16:54:08 -07004278 // Set TLPR from QuicConfig.
4279 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4280 QuicConfig config;
4281 QuicTagVector options;
4282 options.push_back(kTLPR);
4283 config.SetConnectionOptionsToSend(options);
dschinazif7c6a912020-05-05 11:39:53 -07004284 QuicConfigPeer::SetNegotiated(&config, true);
dschinazie7c38a52020-05-29 15:25:45 -07004285 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
4286 QuicConfigPeer::SetReceivedOriginalConnectionId(
4287 &config, connection_.connection_id());
4288 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
4289 &config, connection_.connection_id());
4290 }
zhongyifbb25772019-04-10 16:54:08 -07004291 connection_.SetFromConfig(config);
4292 connection_.SetMaxTailLossProbes(1);
4293
4294 // Sets retransmittable on wire.
4295 const QuicTime::Delta retransmittable_on_wire_timeout =
4296 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07004297 connection_.set_initial_retransmittable_on_wire_timeout(
zhongyifbb25772019-04-10 16:54:08 -07004298 retransmittable_on_wire_timeout);
4299
4300 EXPECT_TRUE(connection_.connected());
4301 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4302 .WillRepeatedly(Return(true));
fayangb59c6f12020-03-23 15:06:14 -07004303 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07004304 EXPECT_FALSE(connection_.IsPathDegrading());
4305 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4306
4307 const char data[] = "data";
4308 size_t data_size = strlen(data);
4309 QuicStreamOffset offset = 0;
4310
4311 // Send a data packet.
4312 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
4313 offset += data_size;
4314
4315 // Path degrading alarm should be set when there is a retransmittable packet
4316 // on the wire.
fayangb59c6f12020-03-23 15:06:14 -07004317 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07004318
4319 // Verify the path degrading delay.
4320 // First TLP with stream data.
4321 QuicTime::Delta srtt = manager_->GetRttStats()->SmoothedOrInitialRtt();
4322 QuicTime::Delta expected_delay = 0.5 * srtt;
4323 // Add 1st RTO.
4324 QuicTime::Delta retransmission_delay =
4325 QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
4326 expected_delay = expected_delay + retransmission_delay;
4327 // Add 2nd RTO.
4328 expected_delay = expected_delay + retransmission_delay * 2;
4329 EXPECT_EQ(expected_delay,
4330 QuicConnectionPeer::GetSentPacketManager(&connection_)
4331 ->GetPathDegradingDelay());
4332 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
4333
4334 // The ping alarm is set for the ping timeout, not the shorter
4335 // retransmittable_on_wire_timeout.
4336 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004337 EXPECT_EQ(connection_.ping_timeout(),
zhongyifbb25772019-04-10 16:54:08 -07004338 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4339
4340 // Receive an ACK for the data packet.
4341 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4342 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4343 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4344 QuicAckFrame frame =
4345 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
4346 ProcessAckPacket(&frame);
4347
4348 // Path degrading alarm should be cancelled as there is no more
4349 // reretransmittable packets on the wire.
fayangb59c6f12020-03-23 15:06:14 -07004350 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07004351 // The ping alarm should be set to the retransmittable_on_wire_timeout.
4352 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4353 EXPECT_EQ(retransmittable_on_wire_timeout,
4354 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4355
4356 // Simulate firing of the retransmittable on wire and send a PING.
4357 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
4358 clock_.AdvanceTime(retransmittable_on_wire_timeout);
4359 connection_.GetPingAlarm()->Fire();
4360
4361 // The retransmission alarm and the path degrading alarm should be set as
4362 // there is a retransmittable packet (PING) on the wire,
4363 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayangb59c6f12020-03-23 15:06:14 -07004364 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
zhongyifbb25772019-04-10 16:54:08 -07004365
4366 // Verify the retransmission delay.
4367 QuicTime::Delta min_rto_timeout =
4368 QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs);
4369 srtt = manager_->GetRttStats()->SmoothedOrInitialRtt();
zhongyi9fa2be32019-09-10 12:39:01 -07004370
4371 // First TLP without unacked stream data will no longer use TLPR.
4372 expected_delay = std::max(2 * srtt, 1.5 * srtt + 0.5 * min_rto_timeout);
zhongyifbb25772019-04-10 16:54:08 -07004373 EXPECT_EQ(expected_delay,
4374 connection_.GetRetransmissionAlarm()->deadline() - clock_.Now());
4375
zhongyi1b2f7832019-06-14 13:31:34 -07004376 // Verify the path degrading delay = TLP delay + 1st RTO + 2nd RTO.
zhongyifbb25772019-04-10 16:54:08 -07004377 // Add 1st RTO.
4378 retransmission_delay =
4379 std::max(manager_->GetRttStats()->smoothed_rtt() +
4380 4 * manager_->GetRttStats()->mean_deviation(),
4381 min_rto_timeout);
4382 expected_delay = expected_delay + retransmission_delay;
4383 // Add 2nd RTO.
4384 expected_delay = expected_delay + retransmission_delay * 2;
4385 EXPECT_EQ(expected_delay,
4386 QuicConnectionPeer::GetSentPacketManager(&connection_)
4387 ->GetPathDegradingDelay());
4388
4389 // The ping alarm is set for the ping timeout, not the shorter
4390 // retransmittable_on_wire_timeout.
4391 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004392 EXPECT_EQ(connection_.ping_timeout(),
zhongyifbb25772019-04-10 16:54:08 -07004393 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
zhongyi1b2f7832019-06-14 13:31:34 -07004394
4395 // Advance a small period of time: 5ms. And receive a retransmitted ACK.
4396 // This will update the retransmission alarm, verify the retransmission delay
4397 // is correct.
4398 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4399 QuicAckFrame ack = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
4400 ProcessAckPacket(&ack);
4401
4402 // Verify the retransmission delay.
zhongyi9fa2be32019-09-10 12:39:01 -07004403 // First TLP without unacked stream data will no longer use TLPR.
4404 expected_delay = std::max(2 * srtt, 1.5 * srtt + 0.5 * min_rto_timeout);
zhongyi1b2f7832019-06-14 13:31:34 -07004405 expected_delay = expected_delay - QuicTime::Delta::FromMilliseconds(5);
4406 EXPECT_EQ(expected_delay,
4407 connection_.GetRetransmissionAlarm()->deadline() - clock_.Now());
zhongyifbb25772019-04-10 16:54:08 -07004408}
4409
QUICHE teama6ef0a62019-03-07 20:34:33 -05004410TEST_P(QuicConnectionTest, RTO) {
fayang5f135052019-08-22 17:59:40 -07004411 if (connection_.PtoEnabled()) {
4412 return;
4413 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004414 connection_.SetMaxTailLossProbes(0);
4415
4416 QuicTime default_retransmission_time =
4417 clock_.ApproximateNow() + DefaultRetransmissionTime();
4418 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4419 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4420
4421 EXPECT_EQ(QuicPacketNumber(1u), writer_->header().packet_number);
4422 EXPECT_EQ(default_retransmission_time,
4423 connection_.GetRetransmissionAlarm()->deadline());
4424 // Simulate the retransmission alarm firing.
4425 clock_.AdvanceTime(DefaultRetransmissionTime());
4426 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
4427 connection_.GetRetransmissionAlarm()->Fire();
4428 EXPECT_EQ(QuicPacketNumber(2u), writer_->header().packet_number);
4429 // We do not raise the high water mark yet.
4430 EXPECT_EQ(QuicPacketNumber(1u), stop_waiting()->least_unacked);
4431}
4432
fayanga29eb242019-07-16 12:25:38 -07004433// Regression test of b/133771183.
4434TEST_P(QuicConnectionTest, RtoWithNoDataToRetransmit) {
fayangcff885a2019-10-22 07:39:04 -07004435 if (connection_.PtoEnabled()) {
fayanga29eb242019-07-16 12:25:38 -07004436 return;
4437 }
4438 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4439 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4440 connection_.SetMaxTailLossProbes(0);
4441
4442 SendStreamDataToPeer(3, "foo", 0, NO_FIN, nullptr);
4443 // Connection is cwnd limited.
4444 CongestionBlockWrites();
4445 // Stream gets reset.
4446 SendRstStream(3, QUIC_ERROR_PROCESSING_STREAM, 3);
4447 // Simulate the retransmission alarm firing.
4448 clock_.AdvanceTime(DefaultRetransmissionTime());
4449 // RTO fires, but there is no packet to be RTOed.
fayange861aee2019-10-16 13:40:39 -07004450 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayanga29eb242019-07-16 12:25:38 -07004451 connection_.GetRetransmissionAlarm()->Fire();
fayange861aee2019-10-16 13:40:39 -07004452 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
fayanga29eb242019-07-16 12:25:38 -07004453
4454 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(40);
4455 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(20);
fayange861aee2019-10-16 13:40:39 -07004456 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
4457 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(1);
fayanga29eb242019-07-16 12:25:38 -07004458 // Receives packets 1 - 40.
4459 for (size_t i = 1; i <= 40; ++i) {
4460 ProcessDataPacket(i);
4461 }
4462}
4463
QUICHE teama6ef0a62019-03-07 20:34:33 -05004464TEST_P(QuicConnectionTest, SendHandshakeMessages) {
4465 use_tagging_decrypter();
4466 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
4467 // the end of the packet. We can test this to check which encrypter was used.
QUICHE team6987b4a2019-03-15 16:23:04 -07004468 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004469 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004470
4471 // Attempt to send a handshake message and have the socket block.
4472 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
4473 BlockOnNextWrite();
nharper46833c32019-05-15 21:33:05 -07004474 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004475 // The packet should be serialized, but not queued.
4476 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4477
4478 // Switch to the new encrypter.
4479 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004480 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004481 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4482
4483 // Now become writeable and flush the packets.
4484 writer_->SetWritable();
4485 EXPECT_CALL(visitor_, OnCanWrite());
4486 connection_.OnCanWrite();
4487 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4488
4489 // Verify that the handshake packet went out at the null encryption.
4490 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
4491}
4492
4493TEST_P(QuicConnectionTest,
4494 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
4495 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07004496 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004497 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004498 connection_.SendCryptoStreamData();
4499
4500 // Simulate the retransmission alarm firing and the socket blocking.
4501 BlockOnNextWrite();
4502 clock_.AdvanceTime(DefaultRetransmissionTime());
fayange62e63c2019-12-04 07:16:25 -08004503 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004504 connection_.GetRetransmissionAlarm()->Fire();
fayang2ce66082019-10-02 06:29:04 -07004505 EXPECT_EQ(1u, connection_.NumQueuedPackets());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004506
4507 // Go forward secure.
4508 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07004509 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004510 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4511 notifier_.NeuterUnencryptedData();
4512 connection_.NeuterUnencryptedPackets();
fayang2ce66082019-10-02 06:29:04 -07004513 connection_.OnHandshakeComplete();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004514
4515 EXPECT_EQ(QuicTime::Zero(), connection_.GetRetransmissionAlarm()->deadline());
4516 // Unblock the socket and ensure that no packets are sent.
4517 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4518 writer_->SetWritable();
4519 connection_.OnCanWrite();
4520}
4521
4522TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
4523 use_tagging_decrypter();
QUICHE team6987b4a2019-03-15 16:23:04 -07004524 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07004525 std::make_unique<TaggingEncrypter>(0x01));
QUICHE team6987b4a2019-03-15 16:23:04 -07004526 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004527
nharper46833c32019-05-15 21:33:05 -07004528 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004529
4530 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004531 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004532 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4533
4534 SendStreamDataToPeer(2, "bar", 0, NO_FIN, nullptr);
renjietang37d4ae12020-06-18 11:18:31 -07004535 EXPECT_FALSE(notifier_.HasLostStreamData());
renjietangb2b8ff22020-07-07 16:18:54 -07004536 connection_.MarkZeroRttPacketsForRetransmission();
renjietang37d4ae12020-06-18 11:18:31 -07004537 EXPECT_TRUE(notifier_.HasLostStreamData());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004538}
4539
4540TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
QUICHE teamcd098022019-03-22 18:49:55 -07004541 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4542 return;
4543 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004544 // SetFromConfig is always called after construction from InitializeSession.
4545 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4546 QuicConfig config;
4547 connection_.SetFromConfig(config);
4548 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4549 use_tagging_decrypter();
4550
4551 const uint8_t tag = 0x07;
4552 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004553 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004554
4555 // Process an encrypted packet which can not yet be decrypted which should
4556 // result in the packet being buffered.
4557 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4558
4559 // Transition to the new encryption state and process another encrypted packet
4560 // which should result in the original packet being processed.
zhongyi546cc452019-04-12 15:27:49 -07004561 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004562 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004563 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4564 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004565 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004566 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
4567 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4568
4569 // Finally, process a third packet and note that we do not reprocess the
4570 // buffered packet.
4571 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4572 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4573}
4574
4575TEST_P(QuicConnectionTest, TestRetransmitOrder) {
fayang5f135052019-08-22 17:59:40 -07004576 if (connection_.PtoEnabled()) {
4577 return;
4578 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004579 connection_.SetMaxTailLossProbes(0);
4580
4581 QuicByteCount first_packet_size;
4582 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4583 .WillOnce(SaveArg<3>(&first_packet_size));
4584
4585 connection_.SendStreamDataWithString(3, "first_packet", 0, NO_FIN);
4586 QuicByteCount second_packet_size;
4587 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
4588 .WillOnce(SaveArg<3>(&second_packet_size));
4589 connection_.SendStreamDataWithString(3, "second_packet", 12, NO_FIN);
4590 EXPECT_NE(first_packet_size, second_packet_size);
4591 // Advance the clock by huge time to make sure packets will be retransmitted.
4592 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
4593 {
4594 InSequence s;
4595 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4596 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4597 }
4598 connection_.GetRetransmissionAlarm()->Fire();
4599
4600 // Advance again and expect the packets to be sent again in the same order.
4601 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20));
4602 {
4603 InSequence s;
4604 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, first_packet_size, _));
4605 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, second_packet_size, _));
4606 }
4607 connection_.GetRetransmissionAlarm()->Fire();
4608}
4609
4610TEST_P(QuicConnectionTest, Buffer100NonDecryptablePacketsThenKeyChange) {
QUICHE teamcd098022019-03-22 18:49:55 -07004611 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4612 return;
4613 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004614 // SetFromConfig is always called after construction from InitializeSession.
4615 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4616 QuicConfig config;
4617 config.set_max_undecryptable_packets(100);
4618 connection_.SetFromConfig(config);
4619 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4620 use_tagging_decrypter();
4621
4622 const uint8_t tag = 0x07;
4623 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004624 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004625
4626 // Process an encrypted packet which can not yet be decrypted which should
4627 // result in the packet being buffered.
4628 for (uint64_t i = 1; i <= 100; ++i) {
4629 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4630 }
4631
4632 // Transition to the new encryption state and process another encrypted packet
4633 // which should result in the original packets being processed.
4634 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
zhongyi546cc452019-04-12 15:27:49 -07004635 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004636 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004637 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4638 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4639 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07004640 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004641
4642 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(100);
4643 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
4644
4645 // Finally, process a third packet and note that we do not reprocess the
4646 // buffered packet.
4647 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4648 ProcessDataPacketAtLevel(102, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4649}
4650
4651TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
4652 BlockOnNextWrite();
fayange62e63c2019-12-04 07:16:25 -08004653 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004654 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
fayange62e63c2019-12-04 07:16:25 -08004655 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004656
4657 // Test that RTO is started once we write to the socket.
4658 writer_->SetWritable();
fayange62e63c2019-12-04 07:16:25 -08004659 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004660 connection_.OnCanWrite();
4661 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4662}
4663
4664TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) {
fayang5f135052019-08-22 17:59:40 -07004665 if (connection_.PtoEnabled()) {
4666 return;
4667 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004668 connection_.SetMaxTailLossProbes(0);
4669
4670 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4671 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
4672 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
4673 connection_.SendStreamDataWithString(3, "bar", 0, NO_FIN);
4674 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
4675 EXPECT_TRUE(retransmission_alarm->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004676 EXPECT_EQ(DefaultRetransmissionTime(),
4677 retransmission_alarm->deadline() - clock_.Now());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004678
4679 // Advance the time right before the RTO, then receive an ack for the first
4680 // packet to delay the RTO.
4681 clock_.AdvanceTime(DefaultRetransmissionTime());
4682 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4683 QuicAckFrame ack = InitAckFrame(1);
4684 ProcessAckPacket(&ack);
4685 // Now we have an RTT sample of DefaultRetransmissionTime(500ms),
4686 // so the RTO has increased to 2 * SRTT.
4687 EXPECT_TRUE(retransmission_alarm->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004688 EXPECT_EQ(retransmission_alarm->deadline() - clock_.Now(),
4689 2 * DefaultRetransmissionTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004690
4691 // Move forward past the original RTO and ensure the RTO is still pending.
4692 clock_.AdvanceTime(2 * DefaultRetransmissionTime());
4693
4694 // Ensure the second packet gets retransmitted when it finally fires.
4695 EXPECT_TRUE(retransmission_alarm->IsSet());
4696 EXPECT_EQ(retransmission_alarm->deadline(), clock_.ApproximateNow());
4697 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4698 // Manually cancel the alarm to simulate a real test.
4699 connection_.GetRetransmissionAlarm()->Fire();
4700
4701 // The new retransmitted packet number should set the RTO to a larger value
4702 // than previously.
4703 EXPECT_TRUE(retransmission_alarm->IsSet());
4704 QuicTime next_rto_time = retransmission_alarm->deadline();
4705 QuicTime expected_rto_time =
4706 connection_.sent_packet_manager().GetRetransmissionTime();
4707 EXPECT_EQ(next_rto_time, expected_rto_time);
4708}
4709
4710TEST_P(QuicConnectionTest, TestQueued) {
4711 connection_.SetMaxTailLossProbes(0);
4712
4713 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4714 BlockOnNextWrite();
4715 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4716 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4717
4718 // Unblock the writes and actually send.
4719 writer_->SetWritable();
4720 connection_.OnCanWrite();
4721 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4722}
4723
4724TEST_P(QuicConnectionTest, InitialTimeout) {
4725 EXPECT_TRUE(connection_.connected());
4726 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4727 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4728
4729 // SetFromConfig sets the initial timeouts before negotiation.
4730 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4731 QuicConfig config;
4732 connection_.SetFromConfig(config);
4733 // Subtract a second from the idle timeout on the client side.
4734 QuicTime default_timeout =
4735 clock_.ApproximateNow() +
4736 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4737 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
4738
fkastenholz5d880a92019-06-21 09:01:56 -07004739 EXPECT_CALL(visitor_,
4740 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004741 // Simulate the timeout alarm firing.
4742 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
4743 connection_.GetTimeoutAlarm()->Fire();
4744
4745 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4746 EXPECT_FALSE(connection_.connected());
4747
fayang9adfb532020-06-04 06:58:45 -07004748 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004749 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4750 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4751 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4752 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
renjietang11e4a3d2019-05-03 11:27:26 -07004753 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004754 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004755}
4756
4757TEST_P(QuicConnectionTest, IdleTimeoutAfterFirstSentPacket) {
4758 EXPECT_TRUE(connection_.connected());
4759 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4760 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4761
4762 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4763 QuicConfig config;
4764 connection_.SetFromConfig(config);
4765 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4766 QuicTime initial_ddl =
4767 clock_.ApproximateNow() +
4768 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4769 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4770 EXPECT_TRUE(connection_.connected());
4771
4772 // Advance the time and send the first packet to the peer.
fayangb9c88442020-03-26 07:03:57 -07004773 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004774 QuicPacketNumber last_packet;
4775 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4776 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4777 // This will be the updated deadline for the connection to idle time out.
4778 QuicTime new_ddl = clock_.ApproximateNow() +
4779 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4780
4781 // Simulate the timeout alarm firing, the connection should not be closed as
4782 // a new packet has been sent.
fkastenholz5d880a92019-06-21 09:01:56 -07004783 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004784 QuicTime::Delta delay = initial_ddl - clock_.ApproximateNow();
4785 clock_.AdvanceTime(delay);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004786 // Verify the timeout alarm deadline is updated.
4787 EXPECT_TRUE(connection_.connected());
4788 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4789 EXPECT_EQ(new_ddl, connection_.GetTimeoutAlarm()->deadline());
4790
4791 // Simulate the timeout alarm firing again, the connection now should be
4792 // closed.
fkastenholz5d880a92019-06-21 09:01:56 -07004793 EXPECT_CALL(visitor_,
4794 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004795 clock_.AdvanceTime(new_ddl - clock_.ApproximateNow());
4796 connection_.GetTimeoutAlarm()->Fire();
4797 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4798 EXPECT_FALSE(connection_.connected());
4799
fayang9adfb532020-06-04 06:58:45 -07004800 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004801 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4802 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4803 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4804 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004805 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004806}
4807
4808TEST_P(QuicConnectionTest, IdleTimeoutAfterSendTwoPackets) {
4809 EXPECT_TRUE(connection_.connected());
4810 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4811 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4812
4813 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4814 QuicConfig config;
4815 connection_.SetFromConfig(config);
4816 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4817 QuicTime initial_ddl =
4818 clock_.ApproximateNow() +
4819 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4820 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4821 EXPECT_TRUE(connection_.connected());
4822
4823 // Immediately send the first packet, this is a rare case but test code will
4824 // hit this issue often as MockClock used for tests doesn't move with code
4825 // execution until manually adjusted.
4826 QuicPacketNumber last_packet;
4827 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4828 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4829
4830 // Advance the time and send the second packet to the peer.
4831 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
4832 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4833 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4834
zhongyic1cab062019-06-19 12:02:24 -07004835 // Simulate the timeout alarm firing, the connection will be closed.
fkastenholz5d880a92019-06-21 09:01:56 -07004836 EXPECT_CALL(visitor_,
4837 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
zhongyic1cab062019-06-19 12:02:24 -07004838 clock_.AdvanceTime(initial_ddl - clock_.ApproximateNow());
4839 connection_.GetTimeoutAlarm()->Fire();
QUICHE teama6ef0a62019-03-07 20:34:33 -05004840
4841 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4842 EXPECT_FALSE(connection_.connected());
4843
fayang9adfb532020-06-04 06:58:45 -07004844 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004845 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4846 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4847 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4848 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004849 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004850}
4851
4852TEST_P(QuicConnectionTest, HandshakeTimeout) {
4853 // Use a shorter handshake timeout than idle timeout for this test.
4854 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
4855 connection_.SetNetworkTimeouts(timeout, timeout);
4856 EXPECT_TRUE(connection_.connected());
4857 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4858
4859 QuicTime handshake_timeout =
4860 clock_.ApproximateNow() + timeout - QuicTime::Delta::FromSeconds(1);
4861 EXPECT_EQ(handshake_timeout, connection_.GetTimeoutAlarm()->deadline());
4862 EXPECT_TRUE(connection_.connected());
4863
4864 // Send and ack new data 3 seconds later to lengthen the idle timeout.
4865 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004866 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4867 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004868 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
4869 QuicAckFrame frame = InitAckFrame(1);
4870 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4871 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4872 ProcessAckPacket(&frame);
4873
QUICHE teama6ef0a62019-03-07 20:34:33 -05004874 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4875 EXPECT_TRUE(connection_.connected());
4876
4877 clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(2));
4878
fkastenholz5d880a92019-06-21 09:01:56 -07004879 EXPECT_CALL(visitor_,
4880 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004881 // Simulate the timeout alarm firing.
4882 connection_.GetTimeoutAlarm()->Fire();
4883
4884 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4885 EXPECT_FALSE(connection_.connected());
4886
fayang9adfb532020-06-04 06:58:45 -07004887 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004888 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4889 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4890 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07004891 TestConnectionCloseQuicErrorCode(QUIC_HANDSHAKE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004892}
4893
4894TEST_P(QuicConnectionTest, PingAfterSend) {
QUICHE teamcd098022019-03-22 18:49:55 -07004895 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4896 return;
4897 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004898 EXPECT_TRUE(connection_.connected());
4899 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4900 .WillRepeatedly(Return(true));
4901 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4902
4903 // Advance to 5ms, and send a packet to the peer, which will set
4904 // the ping alarm.
4905 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4906 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4907 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004908 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4909 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004910 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004911 EXPECT_EQ(QuicTime::Delta::FromSeconds(15),
4912 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004913
4914 // Now recevie an ACK of the previous packet, which will move the
4915 // ping alarm forward.
4916 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4917 QuicAckFrame frame = InitAckFrame(1);
4918 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4919 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4920 ProcessAckPacket(&frame);
4921 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4922 // The ping timer is set slightly less than 15 seconds in the future, because
4923 // of the 1s ping timer alarm granularity.
zhongyieef848f2019-10-18 07:09:37 -07004924 EXPECT_EQ(
4925 QuicTime::Delta::FromSeconds(15) - QuicTime::Delta::FromMilliseconds(5),
4926 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004927
4928 writer_->Reset();
4929 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
zhongyifbb25772019-04-10 16:54:08 -07004930 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
QUICHE teama6ef0a62019-03-07 20:34:33 -05004931 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07004932 size_t padding_frame_count = writer_->padding_frames().size();
4933 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004934 ASSERT_EQ(1u, writer_->ping_frames().size());
4935 writer_->Reset();
4936
4937 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4938 .WillRepeatedly(Return(false));
4939 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4940 SendAckPacketToPeer();
4941
4942 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4943}
4944
4945TEST_P(QuicConnectionTest, ReducedPingTimeout) {
QUICHE teamcd098022019-03-22 18:49:55 -07004946 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4947 return;
4948 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05004949 EXPECT_TRUE(connection_.connected());
4950 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4951 .WillRepeatedly(Return(true));
4952 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4953
4954 // Use a reduced ping timeout for this connection.
4955 connection_.set_ping_timeout(QuicTime::Delta::FromSeconds(10));
4956
4957 // Advance to 5ms, and send a packet to the peer, which will set
4958 // the ping alarm.
4959 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4960 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4961 SendStreamDataToPeer(
dschinazi552accc2019-06-17 17:07:34 -07004962 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4963 "GET /", 0, FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05004964 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07004965 EXPECT_EQ(QuicTime::Delta::FromSeconds(10),
4966 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004967
4968 // Now recevie an ACK of the previous packet, which will move the
4969 // ping alarm forward.
4970 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4971 QuicAckFrame frame = InitAckFrame(1);
4972 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4973 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4974 ProcessAckPacket(&frame);
4975 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4976 // The ping timer is set slightly less than 10 seconds in the future, because
4977 // of the 1s ping timer alarm granularity.
zhongyieef848f2019-10-18 07:09:37 -07004978 EXPECT_EQ(
4979 QuicTime::Delta::FromSeconds(10) - QuicTime::Delta::FromMilliseconds(5),
4980 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004981
4982 writer_->Reset();
4983 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
4984 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
4985 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
4986 }));
4987 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07004988 size_t padding_frame_count = writer_->padding_frames().size();
4989 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05004990 ASSERT_EQ(1u, writer_->ping_frames().size());
4991 writer_->Reset();
4992
4993 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4994 .WillRepeatedly(Return(false));
4995 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4996 SendAckPacketToPeer();
4997
4998 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4999}
5000
5001// Tests whether sending an MTU discovery packet to peer successfully causes the
5002// maximum packet size to increase.
5003TEST_P(QuicConnectionTest, SendMtuDiscoveryPacket) {
wub031d47c2019-11-21 08:04:07 -08005004 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005005
5006 // Send an MTU probe.
5007 const size_t new_mtu = kDefaultMaxPacketSize + 100;
5008 QuicByteCount mtu_probe_size;
5009 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5010 .WillOnce(SaveArg<3>(&mtu_probe_size));
5011 connection_.SendMtuDiscoveryPacket(new_mtu);
5012 EXPECT_EQ(new_mtu, mtu_probe_size);
5013 EXPECT_EQ(QuicPacketNumber(1u), creator_->packet_number());
5014
5015 // Send more than MTU worth of data. No acknowledgement was received so far,
5016 // so the MTU should be at its old value.
vasilvvc48c8712019-03-11 13:38:16 -07005017 const std::string data(kDefaultMaxPacketSize + 1, '.');
QUICHE teama6ef0a62019-03-07 20:34:33 -05005018 QuicByteCount size_before_mtu_change;
5019 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5020 .Times(2)
5021 .WillOnce(SaveArg<3>(&size_before_mtu_change))
5022 .WillOnce(Return());
5023 connection_.SendStreamDataWithString(3, data, 0, FIN);
5024 EXPECT_EQ(QuicPacketNumber(3u), creator_->packet_number());
5025 EXPECT_EQ(kDefaultMaxPacketSize, size_before_mtu_change);
5026
5027 // Acknowledge all packets so far.
5028 QuicAckFrame probe_ack = InitAckFrame(3);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005029 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5030 ProcessAckPacket(&probe_ack);
5031 EXPECT_EQ(new_mtu, connection_.max_packet_length());
5032
5033 // Send the same data again. Check that it fits into a single packet now.
5034 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
5035 connection_.SendStreamDataWithString(3, data, 0, FIN);
5036 EXPECT_EQ(QuicPacketNumber(4u), creator_->packet_number());
5037}
5038
wubb442b862020-01-31 08:16:21 -08005039// Verifies that when a MTU probe packet is sent and buffered in a batch writer,
5040// the writer is flushed immediately.
5041TEST_P(QuicConnectionTest, BatchWriterFlushedAfterMtuDiscoveryPacket) {
5042 writer_->SetBatchMode(true);
5043 MtuDiscoveryTestInit();
5044
5045 // Send an MTU probe.
5046 const size_t target_mtu = kDefaultMaxPacketSize + 100;
5047 QuicByteCount mtu_probe_size;
5048 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5049 .WillOnce(SaveArg<3>(&mtu_probe_size));
5050 const uint32_t prior_flush_attempts = writer_->flush_attempts();
5051 connection_.SendMtuDiscoveryPacket(target_mtu);
5052 EXPECT_EQ(target_mtu, mtu_probe_size);
wub18f47342020-03-16 15:56:03 -07005053 EXPECT_EQ(writer_->flush_attempts(), prior_flush_attempts + 1);
wubb442b862020-01-31 08:16:21 -08005054}
5055
QUICHE teama6ef0a62019-03-07 20:34:33 -05005056// Tests whether MTU discovery does not happen when it is not explicitly enabled
5057// by the connection options.
5058TEST_P(QuicConnectionTest, MtuDiscoveryDisabled) {
wub031d47c2019-11-21 08:04:07 -08005059 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005060
5061 const QuicPacketCount packets_between_probes_base = 10;
5062 set_packets_between_probes_base(packets_between_probes_base);
5063
5064 const QuicPacketCount number_of_packets = packets_between_probes_base * 2;
5065 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5066 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5067 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5068 EXPECT_EQ(0u, connection_.mtu_probe_count());
5069 }
5070}
5071
wubf76cf2a2019-10-11 18:49:07 -07005072// Tests whether MTU discovery works when all probes are acknowledged on the
QUICHE teama6ef0a62019-03-07 20:34:33 -05005073// first try.
5074TEST_P(QuicConnectionTest, MtuDiscoveryEnabled) {
wub031d47c2019-11-21 08:04:07 -08005075 MtuDiscoveryTestInit();
nharperc6b99512019-09-19 11:13:48 -07005076
QUICHE teama6ef0a62019-03-07 20:34:33 -05005077 const QuicPacketCount packets_between_probes_base = 5;
5078 set_packets_between_probes_base(packets_between_probes_base);
5079
wubf76cf2a2019-10-11 18:49:07 -07005080 connection_.EnablePathMtuDiscovery(send_algorithm_);
5081
QUICHE teama6ef0a62019-03-07 20:34:33 -05005082 // Send enough packets so that the next one triggers path MTU discovery.
5083 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5084 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5085 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5086 }
5087
5088 // Trigger the probe.
5089 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5090 nullptr);
5091 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5092 QuicByteCount probe_size;
5093 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5094 .WillOnce(SaveArg<3>(&probe_size));
5095 connection_.GetMtuDiscoveryAlarm()->Fire();
wub173916e2019-11-27 14:36:24 -08005096
5097 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5098 kMtuDiscoveryTargetPacketSizeHigh));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005099
5100 const QuicPacketNumber probe_packet_number =
5101 FirstSendingPacketNumber() + packets_between_probes_base;
5102 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5103
5104 // Acknowledge all packets sent so far.
5105 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
wubf76cf2a2019-10-11 18:49:07 -07005106 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5107 .Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005108 ProcessAckPacket(&probe_ack);
wubf76cf2a2019-10-11 18:49:07 -07005109 EXPECT_EQ(probe_size, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005110 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5111
wubf76cf2a2019-10-11 18:49:07 -07005112 EXPECT_EQ(1u, connection_.mtu_probe_count());
5113
wubf76cf2a2019-10-11 18:49:07 -07005114 QuicStreamOffset stream_offset = packets_between_probes_base;
wubecb643f2020-03-19 08:58:46 -07005115 QuicByteCount last_probe_size = 0;
wubf76cf2a2019-10-11 18:49:07 -07005116 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5117 ++num_probes) {
5118 // Send just enough packets without triggering the next probe.
5119 for (QuicPacketCount i = 0;
5120 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5121 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5122 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5123 }
5124
5125 // Trigger the next probe.
5126 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5127 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5128 QuicByteCount new_probe_size;
5129 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5130 .WillOnce(SaveArg<3>(&new_probe_size));
5131 connection_.GetMtuDiscoveryAlarm()->Fire();
5132 EXPECT_THAT(new_probe_size,
5133 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5134 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5135
5136 // Acknowledge all packets sent so far.
5137 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5138 ProcessAckPacket(&probe_ack);
5139 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5140 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5141
wubecb643f2020-03-19 08:58:46 -07005142 last_probe_size = probe_size;
wubf76cf2a2019-10-11 18:49:07 -07005143 probe_size = new_probe_size;
5144 }
5145
5146 // The last probe size should be equal to the target.
5147 EXPECT_EQ(probe_size, kMtuDiscoveryTargetPacketSizeHigh);
wubecb643f2020-03-19 08:58:46 -07005148
wubae6581a2020-05-04 12:13:05 -07005149 writer_->SetShouldWriteFail();
wubecb643f2020-03-19 08:58:46 -07005150
wubae6581a2020-05-04 12:13:05 -07005151 // Ignore PACKET_WRITE_ERROR once.
5152 SendStreamDataToPeer(3, "(", stream_offset++, NO_FIN, nullptr);
5153 EXPECT_EQ(last_probe_size, connection_.max_packet_length());
5154 EXPECT_TRUE(connection_.connected());
wubecb643f2020-03-19 08:58:46 -07005155
wubae6581a2020-05-04 12:13:05 -07005156 // Close connection on another PACKET_WRITE_ERROR.
5157 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
5158 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5159 SendStreamDataToPeer(3, ")", stream_offset++, NO_FIN, nullptr);
5160 EXPECT_EQ(last_probe_size, connection_.max_packet_length());
5161 EXPECT_FALSE(connection_.connected());
5162 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5163 IsError(QUIC_PACKET_WRITE_ERROR));
wubf76cf2a2019-10-11 18:49:07 -07005164}
5165
wub748e20b2020-03-20 14:33:59 -07005166// After a successful MTU probe, one and only one write error should be ignored
5167// if it happened in QuicConnection::FlushPacket.
5168TEST_P(QuicConnectionTest,
5169 MtuDiscoveryIgnoreOneWriteErrorInFlushAfterSuccessfulProbes) {
5170 MtuDiscoveryTestInit();
5171 writer_->SetBatchMode(true);
5172
5173 const QuicPacketCount packets_between_probes_base = 5;
5174 set_packets_between_probes_base(packets_between_probes_base);
5175
5176 connection_.EnablePathMtuDiscovery(send_algorithm_);
5177
5178 const QuicByteCount original_max_packet_length =
5179 connection_.max_packet_length();
5180 // Send enough packets so that the next one triggers path MTU discovery.
5181 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5182 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5183 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5184 }
5185
5186 // Trigger the probe.
5187 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5188 nullptr);
5189 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5190 QuicByteCount probe_size;
5191 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5192 .WillOnce(SaveArg<3>(&probe_size));
5193 connection_.GetMtuDiscoveryAlarm()->Fire();
5194
5195 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5196 kMtuDiscoveryTargetPacketSizeHigh));
5197
5198 const QuicPacketNumber probe_packet_number =
5199 FirstSendingPacketNumber() + packets_between_probes_base;
5200 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5201
5202 // Acknowledge all packets sent so far.
5203 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
5204 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5205 .Times(AnyNumber());
5206 ProcessAckPacket(&probe_ack);
5207 EXPECT_EQ(probe_size, connection_.max_packet_length());
5208 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5209
5210 EXPECT_EQ(1u, connection_.mtu_probe_count());
5211
wubae6581a2020-05-04 12:13:05 -07005212 writer_->SetShouldWriteFail();
wub748e20b2020-03-20 14:33:59 -07005213
wubae6581a2020-05-04 12:13:05 -07005214 // Ignore PACKET_WRITE_ERROR once.
5215 {
5216 QuicConnection::ScopedPacketFlusher flusher(&connection_);
5217 // flusher's destructor will call connection_.FlushPackets, which should
5218 // get a WRITE_STATUS_ERROR from the writer and ignore it.
wub748e20b2020-03-20 14:33:59 -07005219 }
wubae6581a2020-05-04 12:13:05 -07005220 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5221 EXPECT_TRUE(connection_.connected());
5222
5223 // Close connection on another PACKET_WRITE_ERROR.
5224 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
5225 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5226 {
5227 QuicConnection::ScopedPacketFlusher flusher(&connection_);
5228 // flusher's destructor will call connection_.FlushPackets, which should
5229 // get a WRITE_STATUS_ERROR from the writer and ignore it.
5230 }
5231 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5232 EXPECT_FALSE(connection_.connected());
5233 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5234 IsError(QUIC_PACKET_WRITE_ERROR));
wub748e20b2020-03-20 14:33:59 -07005235}
5236
wubf76cf2a2019-10-11 18:49:07 -07005237// Simulate the case where the first attempt to send a probe is write blocked,
5238// and after unblock, the second attempt returns a MSG_TOO_BIG error.
5239TEST_P(QuicConnectionTest, MtuDiscoveryWriteBlocked) {
wub031d47c2019-11-21 08:04:07 -08005240 MtuDiscoveryTestInit();
wubf76cf2a2019-10-11 18:49:07 -07005241
5242 const QuicPacketCount packets_between_probes_base = 5;
5243 set_packets_between_probes_base(packets_between_probes_base);
5244
5245 connection_.EnablePathMtuDiscovery(send_algorithm_);
5246
5247 // Send enough packets so that the next one triggers path MTU discovery.
5248 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5249 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005250 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5251 }
5252
wubf76cf2a2019-10-11 18:49:07 -07005253 QuicByteCount original_max_packet_length = connection_.max_packet_length();
5254
5255 // Trigger the probe.
5256 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5257 nullptr);
5258 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
fayange62e63c2019-12-04 07:16:25 -08005259 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
wubf76cf2a2019-10-11 18:49:07 -07005260 BlockOnNextWrite();
5261 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5262 connection_.GetMtuDiscoveryAlarm()->Fire();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005263 EXPECT_EQ(1u, connection_.mtu_probe_count());
wubf76cf2a2019-10-11 18:49:07 -07005264 EXPECT_EQ(1u, connection_.NumQueuedPackets());
5265 ASSERT_TRUE(connection_.connected());
5266
5267 writer_->SetWritable();
5268 SimulateNextPacketTooLarge();
5269 connection_.OnCanWrite();
5270 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5271 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5272 EXPECT_TRUE(connection_.connected());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005273}
5274
5275// Tests whether MTU discovery works correctly when the probes never get
5276// acknowledged.
5277TEST_P(QuicConnectionTest, MtuDiscoveryFailed) {
wub031d47c2019-11-21 08:04:07 -08005278 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005279
QUICHE teama6ef0a62019-03-07 20:34:33 -05005280 // Lower the number of probes between packets in order to make the test go
5281 // much faster.
5282 const QuicPacketCount packets_between_probes_base = 5;
5283 set_packets_between_probes_base(packets_between_probes_base);
5284
wubf76cf2a2019-10-11 18:49:07 -07005285 connection_.EnablePathMtuDiscovery(send_algorithm_);
5286
5287 const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(100);
5288
5289 EXPECT_EQ(packets_between_probes_base,
5290 QuicConnectionPeer::GetPacketsBetweenMtuProbes(&connection_));
5291
QUICHE teama6ef0a62019-03-07 20:34:33 -05005292 // This tests sends more packets than strictly necessary to make sure that if
5293 // the connection was to send more discovery packets than needed, those would
5294 // get caught as well.
5295 const QuicPacketCount number_of_packets =
5296 packets_between_probes_base * (1 << (kMtuDiscoveryAttempts + 1));
5297 std::vector<QuicPacketNumber> mtu_discovery_packets;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005298 // Called on many acks.
5299 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5300 .Times(AnyNumber());
5301 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5302 SendStreamDataToPeer(3, "!", i, NO_FIN, nullptr);
5303 clock_.AdvanceTime(rtt);
5304
5305 // Receive an ACK, which marks all data packets as received, and all MTU
5306 // discovery packets as missing.
5307
5308 QuicAckFrame ack;
5309
5310 if (!mtu_discovery_packets.empty()) {
5311 QuicPacketNumber min_packet = *min_element(mtu_discovery_packets.begin(),
5312 mtu_discovery_packets.end());
5313 QuicPacketNumber max_packet = *max_element(mtu_discovery_packets.begin(),
5314 mtu_discovery_packets.end());
5315 ack.packets.AddRange(QuicPacketNumber(1), min_packet);
5316 ack.packets.AddRange(QuicPacketNumber(max_packet + 1),
5317 creator_->packet_number() + 1);
5318 ack.largest_acked = creator_->packet_number();
5319
5320 } else {
5321 ack.packets.AddRange(QuicPacketNumber(1), creator_->packet_number() + 1);
5322 ack.largest_acked = creator_->packet_number();
5323 }
5324
5325 ProcessAckPacket(&ack);
5326
5327 // Trigger MTU probe if it would be scheduled now.
5328 if (!connection_.GetMtuDiscoveryAlarm()->IsSet()) {
5329 continue;
5330 }
5331
5332 // Fire the alarm. The alarm should cause a packet to be sent.
5333 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5334 connection_.GetMtuDiscoveryAlarm()->Fire();
5335 // Record the packet number of the MTU discovery packet in order to
5336 // mark it as NACK'd.
5337 mtu_discovery_packets.push_back(creator_->packet_number());
5338 }
5339
5340 // Ensure the number of packets between probes grows exponentially by checking
5341 // it against the closed-form expression for the packet number.
5342 ASSERT_EQ(kMtuDiscoveryAttempts, mtu_discovery_packets.size());
5343 for (uint64_t i = 0; i < kMtuDiscoveryAttempts; i++) {
5344 // 2^0 + 2^1 + 2^2 + ... + 2^n = 2^(n + 1) - 1
5345 const QuicPacketCount packets_between_probes =
5346 packets_between_probes_base * ((1 << (i + 1)) - 1);
5347 EXPECT_EQ(QuicPacketNumber(packets_between_probes + (i + 1)),
5348 mtu_discovery_packets[i]);
5349 }
5350
5351 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5352 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
5353 EXPECT_EQ(kMtuDiscoveryAttempts, connection_.mtu_probe_count());
5354}
5355
wubf76cf2a2019-10-11 18:49:07 -07005356// Probe 3 times, the first one succeeds, then fails, then succeeds again.
5357TEST_P(QuicConnectionTest, MtuDiscoverySecondProbeFailed) {
wub031d47c2019-11-21 08:04:07 -08005358 MtuDiscoveryTestInit();
wubf76cf2a2019-10-11 18:49:07 -07005359
5360 const QuicPacketCount packets_between_probes_base = 5;
5361 set_packets_between_probes_base(packets_between_probes_base);
5362
5363 connection_.EnablePathMtuDiscovery(send_algorithm_);
5364
5365 // Send enough packets so that the next one triggers path MTU discovery.
5366 QuicStreamOffset stream_offset = 0;
5367 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5368 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5369 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5370 }
5371
5372 // Trigger the probe.
5373 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5374 nullptr);
5375 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5376 QuicByteCount probe_size;
5377 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5378 .WillOnce(SaveArg<3>(&probe_size));
5379 connection_.GetMtuDiscoveryAlarm()->Fire();
5380 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5381 kMtuDiscoveryTargetPacketSizeHigh));
5382
5383 const QuicPacketNumber probe_packet_number =
5384 FirstSendingPacketNumber() + packets_between_probes_base;
5385 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5386
5387 // Acknowledge all packets sent so far.
5388 QuicAckFrame first_ack = InitAckFrame(probe_packet_number);
wubf76cf2a2019-10-11 18:49:07 -07005389 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5390 .Times(AnyNumber());
5391 ProcessAckPacket(&first_ack);
5392 EXPECT_EQ(probe_size, connection_.max_packet_length());
5393 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5394
5395 EXPECT_EQ(1u, connection_.mtu_probe_count());
5396
5397 // Send just enough packets without triggering the second probe.
5398 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 1) - 1; ++i) {
5399 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5400 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5401 }
5402
5403 // Trigger the second probe.
5404 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5405 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5406 QuicByteCount second_probe_size;
5407 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5408 .WillOnce(SaveArg<3>(&second_probe_size));
5409 connection_.GetMtuDiscoveryAlarm()->Fire();
5410 EXPECT_THAT(second_probe_size,
5411 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5412 EXPECT_EQ(2u, connection_.mtu_probe_count());
5413
5414 // Acknowledge all packets sent so far, except the second probe.
5415 QuicPacketNumber second_probe_packet_number = creator_->packet_number();
5416 QuicAckFrame second_ack = InitAckFrame(second_probe_packet_number - 1);
5417 ProcessAckPacket(&first_ack);
5418 EXPECT_EQ(probe_size, connection_.max_packet_length());
5419
5420 // Send just enough packets without triggering the third probe.
5421 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 2) - 1; ++i) {
5422 SendStreamDataToPeer(3, "@", stream_offset++, NO_FIN, nullptr);
5423 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5424 }
5425
5426 // Trigger the third probe.
5427 SendStreamDataToPeer(3, "#", stream_offset++, NO_FIN, nullptr);
5428 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5429 QuicByteCount third_probe_size;
5430 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5431 .WillOnce(SaveArg<3>(&third_probe_size));
5432 connection_.GetMtuDiscoveryAlarm()->Fire();
5433 EXPECT_THAT(third_probe_size, InRange(probe_size, second_probe_size));
5434 EXPECT_EQ(3u, connection_.mtu_probe_count());
5435
5436 // Acknowledge all packets sent so far, except the second probe.
5437 QuicAckFrame third_ack =
5438 ConstructAckFrame(creator_->packet_number(), second_probe_packet_number);
5439 ProcessAckPacket(&third_ack);
5440 EXPECT_EQ(third_probe_size, connection_.max_packet_length());
5441}
5442
QUICHE teama6ef0a62019-03-07 20:34:33 -05005443// Tests whether MTU discovery works when the writer has a limit on how large a
5444// packet can be.
5445TEST_P(QuicConnectionTest, MtuDiscoveryWriterLimited) {
wub031d47c2019-11-21 08:04:07 -08005446 MtuDiscoveryTestInit();
nharperc6b99512019-09-19 11:13:48 -07005447
QUICHE teama6ef0a62019-03-07 20:34:33 -05005448 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5449 writer_->set_max_packet_size(mtu_limit);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005450
5451 const QuicPacketCount packets_between_probes_base = 5;
5452 set_packets_between_probes_base(packets_between_probes_base);
5453
wubf76cf2a2019-10-11 18:49:07 -07005454 connection_.EnablePathMtuDiscovery(send_algorithm_);
5455
QUICHE teama6ef0a62019-03-07 20:34:33 -05005456 // Send enough packets so that the next one triggers path MTU discovery.
5457 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5458 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5459 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5460 }
5461
5462 // Trigger the probe.
5463 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5464 nullptr);
5465 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5466 QuicByteCount probe_size;
5467 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5468 .WillOnce(SaveArg<3>(&probe_size));
5469 connection_.GetMtuDiscoveryAlarm()->Fire();
wub173916e2019-11-27 14:36:24 -08005470
5471 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(), mtu_limit));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005472
5473 const QuicPacketNumber probe_sequence_number =
5474 FirstSendingPacketNumber() + packets_between_probes_base;
5475 ASSERT_EQ(probe_sequence_number, creator_->packet_number());
5476
5477 // Acknowledge all packets sent so far.
5478 QuicAckFrame probe_ack = InitAckFrame(probe_sequence_number);
wubf76cf2a2019-10-11 18:49:07 -07005479 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5480 .Times(AnyNumber());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005481 ProcessAckPacket(&probe_ack);
wubf76cf2a2019-10-11 18:49:07 -07005482 EXPECT_EQ(probe_size, connection_.max_packet_length());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005483 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5484
wubf76cf2a2019-10-11 18:49:07 -07005485 EXPECT_EQ(1u, connection_.mtu_probe_count());
5486
wubf76cf2a2019-10-11 18:49:07 -07005487 QuicStreamOffset stream_offset = packets_between_probes_base;
5488 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5489 ++num_probes) {
5490 // Send just enough packets without triggering the next probe.
5491 for (QuicPacketCount i = 0;
5492 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5493 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5494 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5495 }
5496
5497 // Trigger the next probe.
5498 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5499 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5500 QuicByteCount new_probe_size;
5501 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5502 .WillOnce(SaveArg<3>(&new_probe_size));
5503 connection_.GetMtuDiscoveryAlarm()->Fire();
5504 EXPECT_THAT(new_probe_size, InRange(probe_size, mtu_limit));
5505 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5506
5507 // Acknowledge all packets sent so far.
5508 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5509 ProcessAckPacket(&probe_ack);
5510 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5511 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5512
5513 probe_size = new_probe_size;
5514 }
5515
5516 // The last probe size should be equal to the target.
5517 EXPECT_EQ(probe_size, mtu_limit);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005518}
5519
5520// Tests whether MTU discovery works when the writer returns an error despite
5521// advertising higher packet length.
5522TEST_P(QuicConnectionTest, MtuDiscoveryWriterFailed) {
wub031d47c2019-11-21 08:04:07 -08005523 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005524
5525 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5526 const QuicByteCount initial_mtu = connection_.max_packet_length();
5527 EXPECT_LT(initial_mtu, mtu_limit);
5528 writer_->set_max_packet_size(mtu_limit);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005529
5530 const QuicPacketCount packets_between_probes_base = 5;
5531 set_packets_between_probes_base(packets_between_probes_base);
5532
wubf76cf2a2019-10-11 18:49:07 -07005533 connection_.EnablePathMtuDiscovery(send_algorithm_);
5534
QUICHE teama6ef0a62019-03-07 20:34:33 -05005535 // Send enough packets so that the next one triggers path MTU discovery.
5536 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5537 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5538 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5539 }
5540
5541 // Trigger the probe.
5542 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5543 nullptr);
5544 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5545 writer_->SimulateNextPacketTooLarge();
5546 connection_.GetMtuDiscoveryAlarm()->Fire();
5547 ASSERT_TRUE(connection_.connected());
5548
5549 // Send more data.
5550 QuicPacketNumber probe_number = creator_->packet_number();
5551 QuicPacketCount extra_packets = packets_between_probes_base * 3;
5552 for (QuicPacketCount i = 0; i < extra_packets; i++) {
5553 connection_.EnsureWritableAndSendStreamData5();
5554 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5555 }
5556
5557 // Acknowledge all packets sent so far, except for the lost probe.
5558 QuicAckFrame probe_ack =
5559 ConstructAckFrame(creator_->packet_number(), probe_number);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005560 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5561 ProcessAckPacket(&probe_ack);
5562 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5563
5564 // Send more packets, and ensure that none of them sets the alarm.
5565 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
5566 connection_.EnsureWritableAndSendStreamData5();
5567 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5568 }
5569
5570 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5571 EXPECT_EQ(1u, connection_.mtu_probe_count());
5572}
5573
5574TEST_P(QuicConnectionTest, NoMtuDiscoveryAfterConnectionClosed) {
wub031d47c2019-11-21 08:04:07 -08005575 MtuDiscoveryTestInit();
QUICHE teama6ef0a62019-03-07 20:34:33 -05005576
QUICHE teama6ef0a62019-03-07 20:34:33 -05005577 const QuicPacketCount packets_between_probes_base = 10;
5578 set_packets_between_probes_base(packets_between_probes_base);
5579
wubf76cf2a2019-10-11 18:49:07 -07005580 connection_.EnablePathMtuDiscovery(send_algorithm_);
5581
QUICHE teama6ef0a62019-03-07 20:34:33 -05005582 // Send enough packets so that the next one triggers path MTU discovery.
5583 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5584 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5585 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5586 }
5587
5588 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5589 nullptr);
5590 EXPECT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5591
fkastenholz5d880a92019-06-21 09:01:56 -07005592 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005593 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
5594 ConnectionCloseBehavior::SILENT_CLOSE);
5595 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5596}
5597
dschinazi9a6194e2020-04-30 16:21:09 -07005598TEST_P(QuicConnectionTest, TimeoutAfterSendDuringHandshake) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05005599 EXPECT_TRUE(connection_.connected());
5600 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5601 QuicConfig config;
5602 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005603
5604 const QuicTime::Delta initial_idle_timeout =
5605 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5606 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5607 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5608
5609 // When we send a packet, the timeout will change to 5ms +
5610 // kInitialIdleTimeoutSecs.
5611 clock_.AdvanceTime(five_ms);
5612 SendStreamDataToPeer(
5613 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5614 0, FIN, nullptr);
fayang3a58dc42020-06-29 11:27:14 -07005615 EXPECT_EQ(default_timeout + five_ms,
5616 connection_.GetTimeoutAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005617
5618 // Now send more data. This will not move the timeout because
5619 // no data has been received since the previous write.
5620 clock_.AdvanceTime(five_ms);
5621 SendStreamDataToPeer(
5622 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5623 3, FIN, nullptr);
fayang3a58dc42020-06-29 11:27:14 -07005624 EXPECT_EQ(default_timeout + five_ms,
5625 connection_.GetTimeoutAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005626
5627 // The original alarm will fire. We should not time out because we had a
5628 // network event at t=5ms. The alarm will reregister.
5629 clock_.AdvanceTime(initial_idle_timeout - five_ms - five_ms);
5630 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005631 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5632 EXPECT_TRUE(connection_.connected());
5633 EXPECT_EQ(default_timeout + five_ms,
5634 connection_.GetTimeoutAlarm()->deadline());
5635
5636 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005637 EXPECT_CALL(visitor_,
5638 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005639 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005640 clock_.AdvanceTime(five_ms);
5641 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5642 connection_.GetTimeoutAlarm()->Fire();
5643 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5644 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005645 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005646}
5647
5648TEST_P(QuicConnectionTest, TimeoutAfterRetransmission) {
fayang5f135052019-08-22 17:59:40 -07005649 if (connection_.PtoEnabled()) {
5650 return;
5651 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005652 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5653 EXPECT_TRUE(connection_.connected());
5654 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5655 QuicConfig config;
5656 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005657
5658 const QuicTime start_time = clock_.Now();
5659 const QuicTime::Delta initial_idle_timeout =
5660 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5661 QuicTime default_timeout = clock_.Now() + initial_idle_timeout;
5662
5663 connection_.SetMaxTailLossProbes(0);
5664 const QuicTime default_retransmission_time =
5665 start_time + DefaultRetransmissionTime();
5666
5667 ASSERT_LT(default_retransmission_time, default_timeout);
5668
5669 // When we send a packet, the timeout will change to 5 ms +
5670 // kInitialIdleTimeoutSecs (but it will not reschedule the alarm).
5671 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5672 const QuicTime send_time = start_time + five_ms;
5673 clock_.AdvanceTime(five_ms);
5674 ASSERT_EQ(send_time, clock_.Now());
5675 SendStreamDataToPeer(
5676 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5677 0, FIN, nullptr);
fayang3a58dc42020-06-29 11:27:14 -07005678 EXPECT_EQ(default_timeout + five_ms,
5679 connection_.GetTimeoutAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005680
5681 // Move forward 5 ms and receive a packet, which will move the timeout
5682 // forward 5 ms more (but will not reschedule the alarm).
5683 const QuicTime receive_time = send_time + five_ms;
5684 clock_.AdvanceTime(receive_time - clock_.Now());
5685 ASSERT_EQ(receive_time, clock_.Now());
5686 ProcessPacket(1);
5687
5688 // Now move forward to the retransmission time and retransmit the
5689 // packet, which should move the timeout forward again (but will not
5690 // reschedule the alarm).
5691 EXPECT_EQ(default_retransmission_time + five_ms,
5692 connection_.GetRetransmissionAlarm()->deadline());
5693 // Simulate the retransmission alarm firing.
5694 const QuicTime rto_time = send_time + DefaultRetransmissionTime();
5695 const QuicTime final_timeout = rto_time + initial_idle_timeout;
5696 clock_.AdvanceTime(rto_time - clock_.Now());
5697 ASSERT_EQ(rto_time, clock_.Now());
5698 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
5699 connection_.GetRetransmissionAlarm()->Fire();
5700
5701 // Advance to the original timeout and fire the alarm. The connection should
5702 // timeout, and the alarm should be registered based on the time of the
5703 // retransmission.
5704 clock_.AdvanceTime(default_timeout - clock_.Now());
5705 ASSERT_EQ(default_timeout.ToDebuggingValue(),
5706 clock_.Now().ToDebuggingValue());
5707 EXPECT_EQ(default_timeout, clock_.Now());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005708 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5709 EXPECT_TRUE(connection_.connected());
5710 ASSERT_EQ(final_timeout.ToDebuggingValue(),
5711 connection_.GetTimeoutAlarm()->deadline().ToDebuggingValue());
5712
5713 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005714 EXPECT_CALL(visitor_,
5715 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005716 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005717 clock_.AdvanceTime(final_timeout - clock_.Now());
5718 EXPECT_EQ(connection_.GetTimeoutAlarm()->deadline(), clock_.Now());
5719 EXPECT_EQ(final_timeout, clock_.Now());
5720 connection_.GetTimeoutAlarm()->Fire();
5721 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5722 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005723 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005724}
5725
dschinazi9a6194e2020-04-30 16:21:09 -07005726TEST_P(QuicConnectionTest, TimeoutAfterSendAfterHandshake) {
5727 // When the idle timeout fires, verify that by default we do not send any
5728 // connection close packets.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005729 EXPECT_TRUE(connection_.connected());
5730 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5731 QuicConfig config;
5732
5733 // Create a handshake message that also enables silent close.
5734 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005735 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005736 QuicConfig client_config;
5737 client_config.SetInitialStreamFlowControlWindowToSend(
5738 kInitialStreamFlowControlWindowForTest);
5739 client_config.SetInitialSessionFlowControlWindowToSend(
5740 kInitialSessionFlowControlWindowForTest);
5741 client_config.SetIdleNetworkTimeout(
dschinazi027366e2020-05-01 14:31:19 -07005742 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005743 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005744 const QuicErrorCode error =
5745 config.ProcessPeerHello(msg, CLIENT, &error_details);
bncf54082a2019-11-27 10:19:47 -08005746 EXPECT_THAT(error, IsQuicNoError());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005747
dschinazie7c38a52020-05-29 15:25:45 -07005748 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
5749 QuicConfigPeer::SetReceivedOriginalConnectionId(
5750 &config, connection_.connection_id());
5751 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
5752 &config, connection_.connection_id());
5753 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005754 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005755
5756 const QuicTime::Delta default_idle_timeout =
dschinazi027366e2020-05-01 14:31:19 -07005757 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005758 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5759 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5760
5761 // When we send a packet, the timeout will change to 5ms +
5762 // kInitialIdleTimeoutSecs.
5763 clock_.AdvanceTime(five_ms);
5764 SendStreamDataToPeer(
5765 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5766 0, FIN, nullptr);
fayang3a58dc42020-06-29 11:27:14 -07005767 EXPECT_EQ(default_timeout + five_ms,
5768 connection_.GetTimeoutAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005769
5770 // Now send more data. This will not move the timeout because
5771 // no data has been received since the previous write.
5772 clock_.AdvanceTime(five_ms);
5773 SendStreamDataToPeer(
5774 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5775 3, FIN, nullptr);
fayang3a58dc42020-06-29 11:27:14 -07005776 EXPECT_EQ(default_timeout + five_ms,
5777 connection_.GetTimeoutAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005778
5779 // The original alarm will fire. We should not time out because we had a
5780 // network event at t=5ms. The alarm will reregister.
5781 clock_.AdvanceTime(default_idle_timeout - five_ms - five_ms);
5782 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005783 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5784 EXPECT_TRUE(connection_.connected());
5785 EXPECT_EQ(default_timeout + five_ms,
5786 connection_.GetTimeoutAlarm()->deadline());
5787
5788 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005789 // This results in a SILENT_CLOSE, so the writer will not be invoked
5790 // and will not save the frame. Grab the frame from OnConnectionClosed
5791 // directly.
5792 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
5793 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5794
QUICHE teama6ef0a62019-03-07 20:34:33 -05005795 clock_.AdvanceTime(five_ms);
5796 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5797 connection_.GetTimeoutAlarm()->Fire();
5798 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5799 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005800 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08005801 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5802 IsError(QUIC_NETWORK_IDLE_TIMEOUT));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005803}
5804
5805TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseAndTLP) {
fayang5f135052019-08-22 17:59:40 -07005806 if (connection_.PtoEnabled()) {
5807 return;
5808 }
dschinazi9a6194e2020-04-30 16:21:09 -07005809 // Same test as above, but sending TLPs causes a connection close to be sent.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005810 EXPECT_TRUE(connection_.connected());
5811 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5812 QuicConfig config;
5813
5814 // Create a handshake message that also enables silent close.
5815 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005816 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005817 QuicConfig client_config;
5818 client_config.SetInitialStreamFlowControlWindowToSend(
5819 kInitialStreamFlowControlWindowForTest);
5820 client_config.SetInitialSessionFlowControlWindowToSend(
5821 kInitialSessionFlowControlWindowForTest);
5822 client_config.SetIdleNetworkTimeout(
dschinazi027366e2020-05-01 14:31:19 -07005823 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005824 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005825 const QuicErrorCode error =
5826 config.ProcessPeerHello(msg, CLIENT, &error_details);
bncf54082a2019-11-27 10:19:47 -08005827 EXPECT_THAT(error, IsQuicNoError());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005828
5829 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005830
5831 const QuicTime::Delta default_idle_timeout =
dschinazi027366e2020-05-01 14:31:19 -07005832 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005833 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5834 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5835
5836 // When we send a packet, the timeout will change to 5ms +
5837 // kInitialIdleTimeoutSecs.
5838 clock_.AdvanceTime(five_ms);
5839 SendStreamDataToPeer(
5840 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5841 0, FIN, nullptr);
fayang3a58dc42020-06-29 11:27:14 -07005842 EXPECT_EQ(default_timeout + five_ms,
5843 connection_.GetTimeoutAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005844
5845 // Retransmit the packet via tail loss probe.
5846 clock_.AdvanceTime(connection_.GetRetransmissionAlarm()->deadline() -
5847 clock_.Now());
5848 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _));
5849 connection_.GetRetransmissionAlarm()->Fire();
5850
5851 // This time, we should time out and send a connection close due to the TLP.
fkastenholz5d880a92019-06-21 09:01:56 -07005852 EXPECT_CALL(visitor_,
5853 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005854 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005855 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5856 clock_.ApproximateNow() + five_ms);
5857 connection_.GetTimeoutAlarm()->Fire();
5858 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5859 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005860 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005861}
5862
5863TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseWithOpenStreams) {
dschinazi9a6194e2020-04-30 16:21:09 -07005864 // Same test as above, but having open streams causes a connection close
5865 // to be sent.
QUICHE teama6ef0a62019-03-07 20:34:33 -05005866 EXPECT_TRUE(connection_.connected());
5867 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5868 QuicConfig config;
5869
5870 // Create a handshake message that also enables silent close.
5871 CryptoHandshakeMessage msg;
vasilvvc48c8712019-03-11 13:38:16 -07005872 std::string error_details;
QUICHE teama6ef0a62019-03-07 20:34:33 -05005873 QuicConfig client_config;
5874 client_config.SetInitialStreamFlowControlWindowToSend(
5875 kInitialStreamFlowControlWindowForTest);
5876 client_config.SetInitialSessionFlowControlWindowToSend(
5877 kInitialSessionFlowControlWindowForTest);
5878 client_config.SetIdleNetworkTimeout(
dschinazi027366e2020-05-01 14:31:19 -07005879 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
fkastenholzd3a1de92019-05-15 07:00:07 -07005880 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005881 const QuicErrorCode error =
5882 config.ProcessPeerHello(msg, CLIENT, &error_details);
bncf54082a2019-11-27 10:19:47 -08005883 EXPECT_THAT(error, IsQuicNoError());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005884
dschinazie7c38a52020-05-29 15:25:45 -07005885 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
5886 QuicConfigPeer::SetReceivedOriginalConnectionId(
5887 &config, connection_.connection_id());
5888 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
5889 &config, connection_.connection_id());
5890 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05005891 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005892
5893 const QuicTime::Delta default_idle_timeout =
dschinazi027366e2020-05-01 14:31:19 -07005894 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005895 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5896 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5897
5898 // When we send a packet, the timeout will change to 5ms +
5899 // kInitialIdleTimeoutSecs.
5900 clock_.AdvanceTime(five_ms);
5901 SendStreamDataToPeer(
5902 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5903 0, FIN, nullptr);
fayang3a58dc42020-06-29 11:27:14 -07005904 EXPECT_EQ(default_timeout + five_ms,
5905 connection_.GetTimeoutAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005906
5907 // Indicate streams are still open.
5908 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5909 .WillRepeatedly(Return(true));
5910
5911 // This time, we should time out and send a connection close due to the TLP.
fkastenholz5d880a92019-06-21 09:01:56 -07005912 EXPECT_CALL(visitor_,
5913 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005914 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005915 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5916 clock_.ApproximateNow() + five_ms);
5917 connection_.GetTimeoutAlarm()->Fire();
5918 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5919 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005920 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005921}
5922
5923TEST_P(QuicConnectionTest, TimeoutAfterReceive) {
5924 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5925 EXPECT_TRUE(connection_.connected());
5926 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5927 QuicConfig config;
5928 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005929
5930 const QuicTime::Delta initial_idle_timeout =
5931 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5932 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5933 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5934
5935 connection_.SendStreamDataWithString(
5936 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5937 0, NO_FIN);
5938 connection_.SendStreamDataWithString(
5939 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5940 3, NO_FIN);
5941
5942 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5943 clock_.AdvanceTime(five_ms);
5944
5945 // When we receive a packet, the timeout will change to 5ms +
5946 // kInitialIdleTimeoutSecs.
5947 QuicAckFrame ack = InitAckFrame(2);
5948 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5949 ProcessAckPacket(&ack);
5950
5951 // The original alarm will fire. We should not time out because we had a
5952 // network event at t=5ms. The alarm will reregister.
5953 clock_.AdvanceTime(initial_idle_timeout - five_ms);
5954 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05005955 EXPECT_TRUE(connection_.connected());
5956 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5957 EXPECT_EQ(default_timeout + five_ms,
5958 connection_.GetTimeoutAlarm()->deadline());
5959
5960 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07005961 EXPECT_CALL(visitor_,
5962 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07005963 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teama6ef0a62019-03-07 20:34:33 -05005964 clock_.AdvanceTime(five_ms);
5965 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5966 connection_.GetTimeoutAlarm()->Fire();
5967 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5968 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07005969 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005970}
5971
5972TEST_P(QuicConnectionTest, TimeoutAfterReceiveNotSendWhenUnacked) {
5973 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5974 EXPECT_TRUE(connection_.connected());
5975 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5976 QuicConfig config;
5977 connection_.SetFromConfig(config);
QUICHE teama6ef0a62019-03-07 20:34:33 -05005978
5979 const QuicTime::Delta initial_idle_timeout =
5980 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5981 connection_.SetNetworkTimeouts(
5982 QuicTime::Delta::Infinite(),
5983 initial_idle_timeout + QuicTime::Delta::FromSeconds(1));
5984 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5985 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5986
5987 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5988 connection_.SendStreamDataWithString(
5989 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5990 0, NO_FIN);
5991 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5992 connection_.SendStreamDataWithString(
5993 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5994 3, NO_FIN);
5995
5996 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5997
5998 clock_.AdvanceTime(five_ms);
5999
6000 // When we receive a packet, the timeout will change to 5ms +
6001 // kInitialIdleTimeoutSecs.
6002 QuicAckFrame ack = InitAckFrame(2);
6003 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6004 ProcessAckPacket(&ack);
6005
6006 // The original alarm will fire. We should not time out because we had a
6007 // network event at t=5ms. The alarm will reregister.
6008 clock_.AdvanceTime(initial_idle_timeout - five_ms);
6009 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006010 EXPECT_TRUE(connection_.connected());
6011 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
6012 EXPECT_EQ(default_timeout + five_ms,
6013 connection_.GetTimeoutAlarm()->deadline());
6014
6015 // Now, send packets while advancing the time and verify that the connection
6016 // eventually times out.
fkastenholz5d880a92019-06-21 09:01:56 -07006017 EXPECT_CALL(visitor_,
6018 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006019 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
6020 for (int i = 0; i < 100 && connection_.connected(); ++i) {
6021 QUIC_LOG(INFO) << "sending data packet";
6022 connection_.SendStreamDataWithString(
6023 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
6024 "foo", 0, NO_FIN);
6025 connection_.GetTimeoutAlarm()->Fire();
6026 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6027 }
6028 EXPECT_FALSE(connection_.connected());
6029 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
fkastenholz5d880a92019-06-21 09:01:56 -07006030 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006031}
6032
6033TEST_P(QuicConnectionTest, TimeoutAfter5ClientRTOs) {
fayang5f135052019-08-22 17:59:40 -07006034 if (connection_.PtoEnabled()) {
6035 return;
6036 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006037 connection_.SetMaxTailLossProbes(2);
6038 EXPECT_TRUE(connection_.connected());
6039 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6040 QuicConfig config;
6041 QuicTagVector connection_options;
6042 connection_options.push_back(k5RTO);
6043 config.SetConnectionOptionsToSend(connection_options);
dschinazif7c6a912020-05-05 11:39:53 -07006044 QuicConfigPeer::SetNegotiated(&config, true);
fayang656cbb52020-06-09 13:29:35 -07006045 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -07006046 EXPECT_CALL(visitor_, GetHandshakeState())
6047 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
6048 }
dschinazie7c38a52020-05-29 15:25:45 -07006049 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
6050 QuicConfigPeer::SetReceivedOriginalConnectionId(
6051 &config, connection_.connection_id());
6052 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
6053 &config, connection_.connection_id());
6054 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006055 connection_.SetFromConfig(config);
6056
6057 // Send stream data.
6058 SendStreamDataToPeer(
6059 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6060 0, FIN, nullptr);
6061
6062 // Fire the retransmission alarm 6 times, twice for TLP and 4 times for RTO.
6063 for (int i = 0; i < 6; ++i) {
6064 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6065 connection_.GetRetransmissionAlarm()->Fire();
6066 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
6067 EXPECT_TRUE(connection_.connected());
6068 }
fayang2205d952020-05-12 13:45:56 -07006069 EXPECT_CALL(visitor_, OnPathDegrading());
6070 connection_.PathDegradingTimeout();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006071
6072 EXPECT_EQ(2u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
6073 EXPECT_EQ(4u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
6074 // This time, we should time out.
fkastenholz5d880a92019-06-21 09:01:56 -07006075 EXPECT_CALL(visitor_,
6076 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07006077 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayang2205d952020-05-12 13:45:56 -07006078 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
6079 connection_.GetBlackholeDetectorAlarm()->Fire();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006080 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
6081 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07006082 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006083}
6084
6085TEST_P(QuicConnectionTest, SendScheduler) {
6086 // Test that if we send a packet without delay, it is not queued.
6087 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07006088 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07006089 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006090 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6091 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
QUICHE team6987b4a2019-03-15 16:23:04 -07006092 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006093 HAS_RETRANSMITTABLE_DATA, false, false);
6094 EXPECT_EQ(0u, connection_.NumQueuedPackets());
6095}
6096
6097TEST_P(QuicConnectionTest, FailToSendFirstPacket) {
6098 // Test that the connection does not crash when it fails to send the first
6099 // packet at which point self_address_ might be uninitialized.
6100 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
fkastenholz5d880a92019-06-21 09:01:56 -07006101 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
QUICHE team8c1daa22019-03-13 08:33:41 -07006102 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07006103 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006104 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6105 writer_->SetShouldWriteFail();
QUICHE team6987b4a2019-03-15 16:23:04 -07006106 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006107 HAS_RETRANSMITTABLE_DATA, false, false);
6108}
6109
6110TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
6111 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
QUICHE team8c1daa22019-03-13 08:33:41 -07006112 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07006113 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006114 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6115 BlockOnNextWrite();
6116 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _))
6117 .Times(0);
QUICHE team6987b4a2019-03-15 16:23:04 -07006118 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05006119 HAS_RETRANSMITTABLE_DATA, false, false);
6120 EXPECT_EQ(1u, connection_.NumQueuedPackets());
6121}
6122
6123TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006124 // Queue the first packet.
ianswett3085da82019-04-04 07:24:24 -07006125 size_t payload_length = connection_.max_packet_length();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006126 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(testing::Return(false));
vasilvvc48c8712019-03-11 13:38:16 -07006127 const std::string payload(payload_length, 'a');
ianswett3085da82019-04-04 07:24:24 -07006128 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
6129 connection_.version().transport_version, Perspective::IS_CLIENT));
6130 EXPECT_EQ(0u, connection_
6131 .SendStreamDataWithString(first_bidi_stream_id, payload, 0,
6132 NO_FIN)
QUICHE teama6ef0a62019-03-07 20:34:33 -05006133 .bytes_consumed);
6134 EXPECT_EQ(0u, connection_.NumQueuedPackets());
6135}
6136
ianswett3085da82019-04-04 07:24:24 -07006137TEST_P(QuicConnectionTest, SendingThreePackets) {
ianswett3085da82019-04-04 07:24:24 -07006138 // Make the payload twice the size of the packet, so 3 packets are written.
6139 size_t total_payload_length = 2 * connection_.max_packet_length();
vasilvvc48c8712019-03-11 13:38:16 -07006140 const std::string payload(total_payload_length, 'a');
ianswett3085da82019-04-04 07:24:24 -07006141 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
6142 connection_.version().transport_version, Perspective::IS_CLIENT));
6143 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
6144 EXPECT_EQ(payload.size(), connection_
6145 .SendStreamDataWithString(first_bidi_stream_id,
6146 payload, 0, NO_FIN)
6147 .bytes_consumed);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006148}
6149
6150TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
6151 set_perspective(Perspective::IS_SERVER);
fayangd4291e42019-05-30 10:31:21 -07006152 if (!VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006153 // For IETF QUIC, encryption level will be switched to FORWARD_SECURE in
6154 // SendStreamDataWithString.
6155 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
6156 }
6157 // Set up a larger payload than will fit in one packet.
vasilvvc48c8712019-03-11 13:38:16 -07006158 const std::string payload(connection_.max_packet_length(), 'a');
QUICHE teama6ef0a62019-03-07 20:34:33 -05006159 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
6160
6161 // Now send some packets with no truncation.
6162 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6163 EXPECT_EQ(payload.size(),
6164 connection_.SendStreamDataWithString(3, payload, 0, NO_FIN)
6165 .bytes_consumed);
6166 // Track the size of the second packet here. The overhead will be the largest
6167 // we see in this test, due to the non-truncated connection id.
6168 size_t non_truncated_packet_size = writer_->last_packet_size();
6169
6170 // Change to a 0 byte connection id.
6171 QuicConfig config;
6172 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
6173 connection_.SetFromConfig(config);
6174 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6175 EXPECT_EQ(payload.size(),
6176 connection_.SendStreamDataWithString(3, payload, 1350, NO_FIN)
6177 .bytes_consumed);
fayangd4291e42019-05-30 10:31:21 -07006178 if (VersionHasIetfInvariantHeader(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05006179 // Short header packets sent from server omit connection ID already, and
6180 // stream offset size increases from 0 to 2.
6181 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() - 2);
6182 } else {
6183 // Just like above, we save 8 bytes on payload, and 8 on truncation. -2
6184 // because stream offset size is 2 instead of 0.
6185 EXPECT_EQ(non_truncated_packet_size,
6186 writer_->last_packet_size() + 8 * 2 - 2);
6187 }
6188}
6189
6190TEST_P(QuicConnectionTest, SendDelayedAck) {
6191 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6192 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006193 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006194 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006195 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006196 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006197 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006198 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006199 // Process a packet from the non-crypto stream.
6200 frame1_.stream_id = 3;
6201
6202 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006203 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006204 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6205 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6206
6207 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006208 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006209 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6210 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006211 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006212 connection_.GetAckAlarm()->Fire();
6213 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006214 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006215 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006216 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006217 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6218 } else {
nharper55fa6132019-05-07 19:37:21 -07006219 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006220 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6221 }
6222 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006223 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006224}
6225
6226TEST_P(QuicConnectionTest, SendDelayedAfterQuiescence) {
6227 QuicConnectionPeer::SetFastAckAfterQuiescence(&connection_, true);
6228
6229 // The beginning of the connection counts as quiescence.
ianswett8f90e512019-12-18 10:50:27 -08006230 QuicTime ack_time = clock_.ApproximateNow() + kAlarmGranularity;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006231 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006232 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006233 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006234 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006235 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006236 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006237 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006238 // Process a packet from the non-crypto stream.
6239 frame1_.stream_id = 3;
6240
6241 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006242 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006243 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6244 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6245
6246 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006247 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006248 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6249 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006250 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006251 connection_.GetAckAlarm()->Fire();
6252 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006253 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006254 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006255 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006256 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6257 } else {
nharper55fa6132019-05-07 19:37:21 -07006258 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006259 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6260 }
6261 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006262 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006263
6264 // Process another packet immedately after sending the ack and expect the
6265 // ack alarm to be set delayed ack time in the future.
6266 ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6267 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6268 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6269
6270 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006271 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006272 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6273 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006274 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006275 connection_.GetAckAlarm()->Fire();
6276 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006277 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006278 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006279 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006280 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6281 } else {
nharper55fa6132019-05-07 19:37:21 -07006282 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006283 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6284 }
6285 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006286 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006287
ianswett8f90e512019-12-18 10:50:27 -08006288 // Wait 1 second and ensure the ack alarm is set to 1ms in the future.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006289 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6290 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6291 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6292 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6293
6294 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006295 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006296 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6297}
6298
6299TEST_P(QuicConnectionTest, SendDelayedAckDecimation) {
6300 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6301 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
6302
6303 const size_t kMinRttMs = 40;
6304 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6305 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6306 QuicTime::Delta::Zero(), QuicTime::Zero());
6307 // The ack time should be based on min_rtt/4, since it's less than the
6308 // default delayed ack time.
6309 QuicTime ack_time = clock_.ApproximateNow() +
6310 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6311 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006312 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006313 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006314 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006315 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006316 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006317 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006318 // Process a packet from the non-crypto stream.
6319 frame1_.stream_id = 3;
6320
6321 // Process all the initial packets in order so there aren't missing packets.
6322 uint64_t kFirstDecimatedPacket = 101;
6323 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6324 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6325 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6326 }
fayang9adfb532020-06-04 06:58:45 -07006327 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006328 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006329 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006330 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6331 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6332 ENCRYPTION_ZERO_RTT);
6333
6334 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006335 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006336 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6337
6338 // The 10th received packet causes an ack to be sent.
6339 for (int i = 0; i < 9; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006340 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006341 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6342 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6343 ENCRYPTION_ZERO_RTT);
6344 }
6345 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006346 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006347 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006348 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006349 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6350 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006351 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006352 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6353 }
6354 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006355 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006356}
6357
6358TEST_P(QuicConnectionTest, SendDelayedAckAckDecimationAfterQuiescence) {
6359 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6360 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
6361 QuicConnectionPeer::SetFastAckAfterQuiescence(&connection_, true);
6362
6363 const size_t kMinRttMs = 40;
6364 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6365 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6366 QuicTime::Delta::Zero(), QuicTime::Zero());
6367
6368 // The beginning of the connection counts as quiescence.
6369 QuicTime ack_time =
6370 clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6371 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006372 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006373 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006374 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006375 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006376 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006377 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006378 // Process a packet from the non-crypto stream.
6379 frame1_.stream_id = 3;
6380
6381 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006382 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006383 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6384 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6385
6386 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006387 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006388 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6389 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006390 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006391 connection_.GetAckAlarm()->Fire();
6392 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006393 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006394 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006395 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006396 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6397 } else {
nharper55fa6132019-05-07 19:37:21 -07006398 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006399 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6400 }
6401 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006402 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006403
6404 // Process another packet immedately after sending the ack and expect the
6405 // ack alarm to be set delayed ack time in the future.
6406 ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6407 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6408 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6409
6410 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006411 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006412 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6413 // Simulate delayed ack alarm firing.
QUICHE team8c1daa22019-03-13 08:33:41 -07006414 clock_.AdvanceTime(DefaultDelayedAckTime());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006415 connection_.GetAckAlarm()->Fire();
6416 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006417 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006418 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006419 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006420 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6421 } else {
nharper55fa6132019-05-07 19:37:21 -07006422 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006423 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6424 }
6425 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006426 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006427
6428 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
6429 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6430 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6431 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6432 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6433
6434 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006435 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006436 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6437
6438 // Process enough packets to get into ack decimation behavior.
6439 // The ack time should be based on min_rtt/4, since it's less than the
6440 // default delayed ack time.
6441 ack_time = clock_.ApproximateNow() +
6442 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6443 uint64_t kFirstDecimatedPacket = 101;
6444 for (unsigned int i = 0; i < kFirstDecimatedPacket - 4; ++i) {
6445 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6446 ProcessDataPacketAtLevel(4 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6447 }
fayang9adfb532020-06-04 06:58:45 -07006448 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006449 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006450 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006451 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6452 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6453 ENCRYPTION_ZERO_RTT);
6454
6455 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006456 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006457 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6458
6459 // The 10th received packet causes an ack to be sent.
6460 for (int i = 0; i < 9; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006461 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006462 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6463 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6464 ENCRYPTION_ZERO_RTT);
6465 }
6466 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006467 padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006468 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006469 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006470 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6471 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006472 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006473 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6474 }
6475 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006476 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006477
6478 // Wait 1 second and enesure the ack alarm is set to 1ms in the future.
6479 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6480 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(1);
6481 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6482 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6483 ENCRYPTION_ZERO_RTT);
6484
6485 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006486 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006487 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6488}
6489
6490TEST_P(QuicConnectionTest, SendDelayedAckDecimationUnlimitedAggregation) {
6491 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6492 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6493 QuicConfig config;
6494 QuicTagVector connection_options;
6495 connection_options.push_back(kACKD);
6496 // No limit on the number of packets received before sending an ack.
6497 connection_options.push_back(kAKDU);
6498 config.SetConnectionOptionsToSend(connection_options);
6499 connection_.SetFromConfig(config);
6500
6501 const size_t kMinRttMs = 40;
6502 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6503 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6504 QuicTime::Delta::Zero(), QuicTime::Zero());
6505 // The ack time should be based on min_rtt/4, since it's less than the
6506 // default delayed ack time.
6507 QuicTime ack_time = clock_.ApproximateNow() +
6508 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6509 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006510 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006511 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006512 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006513 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006514 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006515 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006516 // Process a packet from the non-crypto stream.
6517 frame1_.stream_id = 3;
6518
6519 // Process all the initial packets in order so there aren't missing packets.
6520 uint64_t kFirstDecimatedPacket = 101;
6521 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6522 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6523 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6524 }
fayang9adfb532020-06-04 06:58:45 -07006525 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006526 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006527 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006528 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6529 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6530 ENCRYPTION_ZERO_RTT);
6531
6532 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006533 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006534 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6535
6536 // 18 packets will not cause an ack to be sent. 19 will because when
6537 // stop waiting frames are in use, we ack every 20 packets no matter what.
6538 for (int i = 0; i < 18; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006539 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006540 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6541 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6542 ENCRYPTION_ZERO_RTT);
6543 }
6544 // The delayed ack timer should still be set to the expected deadline.
fayang9adfb532020-06-04 06:58:45 -07006545 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006546 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6547}
6548
6549TEST_P(QuicConnectionTest, SendDelayedAckDecimationEighthRtt) {
6550 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6551 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION);
6552 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6553
6554 const size_t kMinRttMs = 40;
6555 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6556 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6557 QuicTime::Delta::Zero(), QuicTime::Zero());
6558 // The ack time should be based on min_rtt/8, since it's less than the
6559 // default delayed ack time.
6560 QuicTime ack_time = clock_.ApproximateNow() +
6561 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6562 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006563 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006564 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006565 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006566 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006567 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006568 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006569 // Process a packet from the non-crypto stream.
6570 frame1_.stream_id = 3;
6571
6572 // Process all the initial packets in order so there aren't missing packets.
6573 uint64_t kFirstDecimatedPacket = 101;
6574 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6575 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6576 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6577 }
fayang9adfb532020-06-04 06:58:45 -07006578 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006579 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006580 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006581 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6582 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6583 ENCRYPTION_ZERO_RTT);
6584
6585 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006586 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006587 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6588
6589 // The 10th received packet causes an ack to be sent.
6590 for (int i = 0; i < 9; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006591 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006592 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6593 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6594 ENCRYPTION_ZERO_RTT);
6595 }
6596 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006597 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006598 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006599 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006600 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6601 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006602 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006603 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6604 }
6605 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006606 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006607}
6608
6609TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithReordering) {
6610 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6611 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6612
6613 const size_t kMinRttMs = 40;
6614 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6615 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6616 QuicTime::Delta::Zero(), QuicTime::Zero());
6617 // The ack time should be based on min_rtt/4, since it's less than the
6618 // default delayed ack time.
6619 QuicTime ack_time = clock_.ApproximateNow() +
6620 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6621 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006622 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006623 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006624 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006625 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006626 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006627 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006628 // Process a packet from the non-crypto stream.
6629 frame1_.stream_id = 3;
6630
6631 // Process all the initial packets in order so there aren't missing packets.
6632 uint64_t kFirstDecimatedPacket = 101;
6633 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6634 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6635 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6636 }
fayang9adfb532020-06-04 06:58:45 -07006637 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006638
6639 // Receive one packet out of order and then the rest in order.
6640 // The loop leaves a one packet gap between acks sent to simulate some loss.
6641 for (int j = 0; j < 3; ++j) {
6642 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6643 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6644 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 9 + (j * 11),
6645 !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6646 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
fayang9adfb532020-06-04 06:58:45 -07006647 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006648 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6649
6650 // The 10th received packet causes an ack to be sent.
6651 writer_->Reset();
6652 for (int i = 0; i < 9; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006653 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006654 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6655 // The ACK shouldn't be sent until the 10th packet is processed.
6656 EXPECT_TRUE(writer_->ack_frames().empty());
6657 ProcessDataPacketAtLevel(kFirstDecimatedPacket + i + (j * 11),
6658 !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6659 }
6660 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006661 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006662 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006663 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006664 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6665 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006666 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006667 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6668 }
6669 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006670 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006671 }
6672}
6673
6674TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithLargeReordering) {
6675 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6676 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6677
6678 const size_t kMinRttMs = 40;
6679 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6680 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6681 QuicTime::Delta::Zero(), QuicTime::Zero());
6682 // The ack time should be based on min_rtt/4, since it's less than the
6683 // default delayed ack time.
6684 QuicTime ack_time = clock_.ApproximateNow() +
6685 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6686 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006687 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006688 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006689 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006690 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006691 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006692 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006693 // Process a packet from the non-crypto stream.
6694 frame1_.stream_id = 3;
6695
6696 // Process all the initial packets in order so there aren't missing packets.
6697 uint64_t kFirstDecimatedPacket = 101;
6698 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6699 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6700 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6701 }
fayang9adfb532020-06-04 06:58:45 -07006702 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006703 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006704 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006705 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6706 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6707 ENCRYPTION_ZERO_RTT);
6708
6709 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006710 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006711 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6712
6713 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6714 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6715 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 19, !kHasStopWaiting,
6716 ENCRYPTION_ZERO_RTT);
6717 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
fayang9adfb532020-06-04 06:58:45 -07006718 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006719 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6720
6721 // The 10th received packet causes an ack to be sent.
6722 for (int i = 0; i < 8; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006723 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006724 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6725 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6726 ENCRYPTION_ZERO_RTT);
6727 }
6728 // Check that ack is sent and that delayed ack alarm is reset.
6729 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006730 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006731 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6732 } else {
6733 EXPECT_EQ(2u, writer_->frame_count());
6734 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6735 }
6736 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006737 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006738
6739 // The next packet received in order will cause an immediate ack,
6740 // because it fills a hole.
fayang9adfb532020-06-04 06:58:45 -07006741 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006742 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6743 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6744 ENCRYPTION_ZERO_RTT);
6745 // Check that ack is sent and that delayed ack alarm is reset.
6746 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006747 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006748 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6749 } else {
6750 EXPECT_EQ(2u, writer_->frame_count());
6751 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6752 }
6753 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006754 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006755}
6756
6757TEST_P(QuicConnectionTest, SendDelayedAckDecimationWithReorderingEighthRtt) {
6758 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6759 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6760 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6761
6762 const size_t kMinRttMs = 40;
6763 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6764 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6765 QuicTime::Delta::Zero(), QuicTime::Zero());
6766 // The ack time should be based on min_rtt/8, since it's less than the
6767 // default delayed ack time.
6768 QuicTime ack_time = clock_.ApproximateNow() +
6769 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6770 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006771 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006772 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006773 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006774 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006775 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006776 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006777 // Process a packet from the non-crypto stream.
6778 frame1_.stream_id = 3;
6779
6780 // Process all the initial packets in order so there aren't missing packets.
6781 uint64_t kFirstDecimatedPacket = 101;
6782 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6783 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6784 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6785 }
fayang9adfb532020-06-04 06:58:45 -07006786 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006787 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006788 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006789 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6790 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6791 ENCRYPTION_ZERO_RTT);
6792
6793 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006794 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006795 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6796
6797 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6798 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6799 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 9, !kHasStopWaiting,
6800 ENCRYPTION_ZERO_RTT);
6801 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
fayang9adfb532020-06-04 06:58:45 -07006802 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006803 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6804
6805 // The 10th received packet causes an ack to be sent.
6806 for (int i = 0; i < 8; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006807 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006808 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6809 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6810 ENCRYPTION_ZERO_RTT);
6811 }
6812 // Check that ack is sent and that delayed ack alarm is reset.
nharperc32d8ab2019-10-09 11:09:06 -07006813 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006814 if (GetParam().no_stop_waiting) {
nharperc32d8ab2019-10-09 11:09:06 -07006815 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006816 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6817 } else {
nharperc32d8ab2019-10-09 11:09:06 -07006818 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006819 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6820 }
6821 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006822 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006823}
6824
6825TEST_P(QuicConnectionTest,
6826 SendDelayedAckDecimationWithLargeReorderingEighthRtt) {
6827 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6828 QuicConnectionPeer::SetAckMode(&connection_, ACK_DECIMATION_WITH_REORDERING);
6829 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6830
6831 const size_t kMinRttMs = 40;
6832 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6833 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6834 QuicTime::Delta::Zero(), QuicTime::Zero());
6835 // The ack time should be based on min_rtt/8, since it's less than the
6836 // default delayed ack time.
6837 QuicTime ack_time = clock_.ApproximateNow() +
6838 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6839 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07006840 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006841 const uint8_t tag = 0x07;
zhongyi546cc452019-04-12 15:27:49 -07006842 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006843 std::make_unique<StrictTaggingDecrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006844 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07006845 std::make_unique<TaggingEncrypter>(tag));
QUICHE teama6ef0a62019-03-07 20:34:33 -05006846 // Process a packet from the non-crypto stream.
6847 frame1_.stream_id = 3;
6848
6849 // Process all the initial packets in order so there aren't missing packets.
6850 uint64_t kFirstDecimatedPacket = 101;
6851 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6852 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6853 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6854 }
fayang9adfb532020-06-04 06:58:45 -07006855 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006856 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
QUICHE team6987b4a2019-03-15 16:23:04 -07006857 // instead of ENCRYPTION_INITIAL.
QUICHE teama6ef0a62019-03-07 20:34:33 -05006858 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6859 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6860 ENCRYPTION_ZERO_RTT);
6861
6862 // Check if delayed ack timer is running for the expected interval.
fayang9adfb532020-06-04 06:58:45 -07006863 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006864 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6865
6866 // Process packet 10 first and ensure the alarm is one eighth min_rtt.
6867 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6868 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 19, !kHasStopWaiting,
6869 ENCRYPTION_ZERO_RTT);
6870 ack_time = clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5);
fayang9adfb532020-06-04 06:58:45 -07006871 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006872 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6873
6874 // The 10th received packet causes an ack to be sent.
6875 for (int i = 0; i < 8; ++i) {
fayang9adfb532020-06-04 06:58:45 -07006876 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006877 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6878 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6879 ENCRYPTION_ZERO_RTT);
6880 }
6881 // Check that ack is sent and that delayed ack alarm is reset.
6882 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006883 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006884 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6885 } else {
6886 EXPECT_EQ(2u, writer_->frame_count());
6887 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6888 }
6889 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006890 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006891
6892 // The next packet received in order will cause an immediate ack,
6893 // because it fills a hole.
fayang9adfb532020-06-04 06:58:45 -07006894 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006895 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6896 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 10, !kHasStopWaiting,
6897 ENCRYPTION_ZERO_RTT);
6898 // Check that ack is sent and that delayed ack alarm is reset.
6899 if (GetParam().no_stop_waiting) {
fayang58f71072019-11-05 08:47:02 -08006900 EXPECT_EQ(writer_->padding_frames().size() + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006901 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6902 } else {
6903 EXPECT_EQ(2u, writer_->frame_count());
6904 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6905 }
6906 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006907 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006908}
6909
6910TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
6911 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6912 ProcessPacket(1);
6913 // Check that ack is sent and that delayed ack alarm is set.
fayang9adfb532020-06-04 06:58:45 -07006914 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006915 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6916 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6917
6918 // Completing the handshake as the server does nothing.
6919 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
6920 connection_.OnHandshakeComplete();
fayang9adfb532020-06-04 06:58:45 -07006921 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006922 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6923
6924 // Complete the handshake as the client decreases the delayed ack time to 0ms.
6925 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
6926 connection_.OnHandshakeComplete();
fayang9adfb532020-06-04 06:58:45 -07006927 EXPECT_TRUE(connection_.HasPendingAcks());
fayangb296fb82020-02-11 08:14:28 -08006928 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6929 EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(),
6930 connection_.GetAckAlarm()->deadline());
6931 } else {
6932 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
6933 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05006934}
6935
6936TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
6937 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6938 ProcessPacket(1);
6939 ProcessPacket(2);
6940 // Check that ack is sent and that delayed ack alarm is reset.
nharper55fa6132019-05-07 19:37:21 -07006941 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05006942 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07006943 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006944 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6945 } else {
nharper55fa6132019-05-07 19:37:21 -07006946 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006947 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6948 }
6949 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07006950 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006951}
6952
6953TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
6954 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang6dba4902019-06-17 10:04:23 -07006955 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006956 ProcessPacket(2);
6957 size_t frames_per_ack = GetParam().no_stop_waiting ? 1 : 2;
QUICHE teama6ef0a62019-03-07 20:34:33 -05006958
6959 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6960 ProcessPacket(3);
nharper55fa6132019-05-07 19:37:21 -07006961 size_t padding_frame_count = writer_->padding_frames().size();
6962 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006963 EXPECT_FALSE(writer_->ack_frames().empty());
6964 writer_->Reset();
6965
fayang6dba4902019-06-17 10:04:23 -07006966 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006967 ProcessPacket(4);
fayang6dba4902019-06-17 10:04:23 -07006968 EXPECT_EQ(0u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006969
6970 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6971 ProcessPacket(5);
nharper55fa6132019-05-07 19:37:21 -07006972 padding_frame_count = writer_->padding_frames().size();
6973 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006974 EXPECT_FALSE(writer_->ack_frames().empty());
6975 writer_->Reset();
6976
6977 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6978 // Now only set the timer on the 6th packet, instead of sending another ack.
6979 ProcessPacket(6);
nharper55fa6132019-05-07 19:37:21 -07006980 padding_frame_count = writer_->padding_frames().size();
6981 EXPECT_EQ(padding_frame_count, writer_->frame_count());
fayang9adfb532020-06-04 06:58:45 -07006982 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05006983}
6984
6985TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
6986 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
QUICHE team8c1daa22019-03-13 08:33:41 -07006987 EXPECT_CALL(visitor_, OnStreamFrame(_));
6988 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07006989 std::make_unique<TaggingEncrypter>(0x01));
zhongyi546cc452019-04-12 15:27:49 -07006990 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07006991 std::make_unique<StrictTaggingDecrypter>(0x01));
nharper2c9f02a2019-05-08 10:25:50 -07006992 ProcessDataPacket(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05006993 connection_.SendStreamDataWithString(
6994 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6995 0, NO_FIN);
6996 // Check that ack is bundled with outgoing data and that delayed ack
6997 // alarm is reset.
6998 if (GetParam().no_stop_waiting) {
6999 EXPECT_EQ(2u, writer_->frame_count());
7000 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7001 } else {
7002 EXPECT_EQ(3u, writer_->frame_count());
7003 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7004 }
7005 EXPECT_FALSE(writer_->ack_frames().empty());
fayang9adfb532020-06-04 06:58:45 -07007006 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007007}
7008
7009TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
7010 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayangc31c9952019-06-05 13:54:48 -07007011 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7012 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
7013 } else {
7014 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7015 }
7016 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
nharper46833c32019-05-15 21:33:05 -07007017 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007018 // Check that ack is bundled with outgoing crypto data.
7019 if (GetParam().no_stop_waiting) {
7020 EXPECT_EQ(3u, writer_->frame_count());
7021 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7022 } else {
7023 EXPECT_EQ(4u, writer_->frame_count());
7024 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7025 }
fayang9adfb532020-06-04 06:58:45 -07007026 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007027}
7028
7029TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
7030 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7031 ProcessPacket(1);
7032 BlockOnNextWrite();
7033 writer_->set_is_write_blocked_data_buffered(true);
fayang60d9c042020-07-06 08:42:40 -07007034 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
fayang6a258412020-05-28 08:57:12 -07007035 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7036 } else {
7037 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
7038 }
nharper46833c32019-05-15 21:33:05 -07007039 connection_.SendCryptoDataWithString("foo", 0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007040 EXPECT_TRUE(writer_->IsWriteBlocked());
7041 EXPECT_FALSE(connection_.HasQueuedData());
nharper46833c32019-05-15 21:33:05 -07007042 connection_.SendCryptoDataWithString("bar", 3);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007043 EXPECT_TRUE(writer_->IsWriteBlocked());
fayang60d9c042020-07-06 08:42:40 -07007044 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
fayang6a258412020-05-28 08:57:12 -07007045 // CRYPTO frames are not flushed when writer is blocked.
7046 EXPECT_FALSE(connection_.HasQueuedData());
7047 } else {
7048 EXPECT_TRUE(connection_.HasQueuedData());
7049 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007050}
7051
7052TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
7053 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07007054 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007055 EXPECT_CALL(visitor_, OnCanWrite())
7056 .WillOnce(IgnoreResult(InvokeWithoutArgs(
7057 &connection_, &TestConnection::SendCryptoStreamData)));
7058 // Process a packet from the crypto stream, which is frame1_'s default.
7059 // Receiving the CHLO as packet 2 first will cause the connection to
7060 // immediately send an ack, due to the packet gap.
fayangc31c9952019-06-05 13:54:48 -07007061 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7062 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
7063 } else {
7064 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7065 }
7066 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007067 // Check that ack is sent and that delayed ack alarm is reset.
7068 if (GetParam().no_stop_waiting) {
7069 EXPECT_EQ(3u, writer_->frame_count());
7070 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7071 } else {
7072 EXPECT_EQ(4u, writer_->frame_count());
7073 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7074 }
QUICHE teamea740082019-03-11 17:58:43 -07007075 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007076 EXPECT_EQ(1u, writer_->stream_frames().size());
7077 } else {
7078 EXPECT_EQ(1u, writer_->crypto_frames().size());
7079 }
7080 EXPECT_EQ(1u, writer_->padding_frames().size());
7081 ASSERT_FALSE(writer_->ack_frames().empty());
7082 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
fayang9adfb532020-06-04 06:58:45 -07007083 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007084}
7085
7086TEST_P(QuicConnectionTest, BundleAckForSecondCHLOTwoPacketReject) {
7087 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayang9adfb532020-06-04 06:58:45 -07007088 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007089
7090 // Process two packets from the crypto stream, which is frame1_'s default,
7091 // simulating a 2 packet reject.
7092 {
fayangc31c9952019-06-05 13:54:48 -07007093 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7094 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
7095 } else {
7096 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7097 }
7098 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007099 // Send the new CHLO when the REJ is processed.
fayangc31c9952019-06-05 13:54:48 -07007100 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
7101 EXPECT_CALL(visitor_, OnCryptoFrame(_))
7102 .WillOnce(IgnoreResult(InvokeWithoutArgs(
7103 &connection_, &TestConnection::SendCryptoStreamData)));
7104 } else {
7105 EXPECT_CALL(visitor_, OnStreamFrame(_))
7106 .WillOnce(IgnoreResult(InvokeWithoutArgs(
7107 &connection_, &TestConnection::SendCryptoStreamData)));
7108 }
7109 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007110 }
7111 // Check that ack is sent and that delayed ack alarm is reset.
7112 if (GetParam().no_stop_waiting) {
7113 EXPECT_EQ(3u, writer_->frame_count());
7114 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
7115 } else {
7116 EXPECT_EQ(4u, writer_->frame_count());
7117 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7118 }
QUICHE teamea740082019-03-11 17:58:43 -07007119 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007120 EXPECT_EQ(1u, writer_->stream_frames().size());
7121 } else {
7122 EXPECT_EQ(1u, writer_->crypto_frames().size());
7123 }
7124 EXPECT_EQ(1u, writer_->padding_frames().size());
7125 ASSERT_FALSE(writer_->ack_frames().empty());
7126 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
fayang9adfb532020-06-04 06:58:45 -07007127 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007128}
7129
7130TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
7131 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7132 connection_.SendStreamDataWithString(
7133 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7134 0, NO_FIN);
7135 connection_.SendStreamDataWithString(
7136 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7137 3, NO_FIN);
7138 // Ack the second packet, which will retransmit the first packet.
7139 QuicAckFrame ack = ConstructAckFrame(2, 1);
7140 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07007141 lost_packets.push_back(
7142 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007143 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07007144 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
7145 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007146 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7147 ProcessAckPacket(&ack);
nharper55fa6132019-05-07 19:37:21 -07007148 size_t padding_frame_count = writer_->padding_frames().size();
7149 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007150 EXPECT_EQ(1u, writer_->stream_frames().size());
7151 writer_->Reset();
7152
7153 // Now ack the retransmission, which will both raise the high water mark
7154 // and see if there is more data to send.
7155 ack = ConstructAckFrame(3, 1);
7156 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7157 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7158 ProcessAckPacket(&ack);
7159
7160 // Check that no packet is sent and the ack alarm isn't set.
7161 EXPECT_EQ(0u, writer_->frame_count());
fayang9adfb532020-06-04 06:58:45 -07007162 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007163 writer_->Reset();
7164
7165 // Send the same ack, but send both data and an ack together.
7166 ack = ConstructAckFrame(3, 1);
7167 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7168 EXPECT_CALL(visitor_, OnCanWrite())
7169 .WillOnce(IgnoreResult(InvokeWithoutArgs(
7170 &connection_, &TestConnection::EnsureWritableAndSendStreamData5)));
7171 ProcessAckPacket(&ack);
7172
7173 // Check that ack is bundled with outgoing data and the delayed ack
7174 // alarm is reset.
7175 if (GetParam().no_stop_waiting) {
fayang8a27b0f2019-11-04 11:27:40 -08007176 // Do not ACK acks.
7177 EXPECT_EQ(1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007178 } else {
7179 EXPECT_EQ(3u, writer_->frame_count());
7180 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
7181 }
fayang8a27b0f2019-11-04 11:27:40 -08007182 if (GetParam().no_stop_waiting) {
fayang03916692019-05-22 17:57:18 -07007183 EXPECT_TRUE(writer_->ack_frames().empty());
7184 } else {
7185 EXPECT_FALSE(writer_->ack_frames().empty());
7186 EXPECT_EQ(QuicPacketNumber(3u),
7187 LargestAcked(writer_->ack_frames().front()));
7188 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007189 EXPECT_EQ(1u, writer_->stream_frames().size());
fayang9adfb532020-06-04 06:58:45 -07007190 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007191}
7192
7193TEST_P(QuicConnectionTest, NoAckSentForClose) {
7194 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7195 ProcessPacket(1);
fkastenholz5d880a92019-06-21 09:01:56 -07007196 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7197 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007198 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7199 ProcessClosePacket(2);
fkastenholz5d880a92019-06-21 09:01:56 -07007200 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007201 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7202 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007203}
7204
7205TEST_P(QuicConnectionTest, SendWhenDisconnected) {
7206 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007207 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7208 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007209 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
7210 ConnectionCloseBehavior::SILENT_CLOSE);
7211 EXPECT_FALSE(connection_.connected());
ianswettfc16a2b2020-05-18 16:05:49 -07007212 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
fayang15042962020-07-01 12:14:29 -07007213 if (GetQuicReloadableFlag(quic_determine_serialized_packet_fate_early)) {
7214 EXPECT_EQ(DISCARD, connection_.GetSerializedPacketFate(
7215 /*is_mtu_discovery=*/false, ENCRYPTION_INITIAL));
7216 return;
7217 }
QUICHE team8c1daa22019-03-13 08:33:41 -07007218 std::unique_ptr<QuicPacket> packet =
QUICHE team6987b4a2019-03-15 16:23:04 -07007219 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007220 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7221 .Times(0);
QUICHE team6987b4a2019-03-15 16:23:04 -07007222 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
QUICHE teama6ef0a62019-03-07 20:34:33 -05007223 HAS_RETRANSMITTABLE_DATA, false, false);
fkastenholz5d880a92019-06-21 09:01:56 -07007224 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007225 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7226 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007227}
7228
7229TEST_P(QuicConnectionTest, SendConnectivityProbingWhenDisconnected) {
7230 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
fayangc31c9952019-06-05 13:54:48 -07007231 if (!IsDefaultTestConfiguration()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007232 return;
7233 }
7234
7235 EXPECT_TRUE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007236 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7237 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007238 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
7239 ConnectionCloseBehavior::SILENT_CLOSE);
7240 EXPECT_FALSE(connection_.connected());
ianswettfc16a2b2020-05-18 16:05:49 -07007241 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007242
7243 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7244 .Times(0);
7245
7246 EXPECT_QUIC_BUG(connection_.SendConnectivityProbingPacket(
7247 writer_.get(), connection_.peer_address()),
7248 "Not sending connectivity probing packet as connection is "
7249 "disconnected.");
fkastenholz5d880a92019-06-21 09:01:56 -07007250 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007251 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7252 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007253}
7254
7255TEST_P(QuicConnectionTest, WriteBlockedAfterClientSendsConnectivityProbe) {
dschinazi1c6e5922020-06-19 10:35:03 -07007256 PathProbeTestInit(Perspective::IS_CLIENT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007257 TestPacketWriter probing_writer(version(), &clock_);
7258 // Block next write so that sending connectivity probe will encounter a
7259 // blocked write when send a connectivity probe to the peer.
7260 probing_writer.BlockOnNextWrite();
7261 // Connection will not be marked as write blocked as connectivity probe only
7262 // affects the probing_writer which is not the default.
7263 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
7264
7265 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7266 .Times(1);
7267 connection_.SendConnectivityProbingPacket(&probing_writer,
7268 connection_.peer_address());
7269}
7270
7271TEST_P(QuicConnectionTest, WriterBlockedAfterServerSendsConnectivityProbe) {
dschinazi1c6e5922020-06-19 10:35:03 -07007272 PathProbeTestInit(Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007273
7274 // Block next write so that sending connectivity probe will encounter a
7275 // blocked write when send a connectivity probe to the peer.
7276 writer_->BlockOnNextWrite();
7277 // Connection will be marked as write blocked as server uses the default
7278 // writer to send connectivity probes.
7279 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
7280
7281 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7282 .Times(1);
7283 connection_.SendConnectivityProbingPacket(writer_.get(),
7284 connection_.peer_address());
7285}
7286
7287TEST_P(QuicConnectionTest, WriterErrorWhenClientSendsConnectivityProbe) {
dschinazi1c6e5922020-06-19 10:35:03 -07007288 PathProbeTestInit(Perspective::IS_CLIENT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007289 TestPacketWriter probing_writer(version(), &clock_);
7290 probing_writer.SetShouldWriteFail();
7291
7292 // Connection should not be closed if a connectivity probe is failed to be
7293 // sent.
fkastenholz5d880a92019-06-21 09:01:56 -07007294 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007295
7296 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7297 .Times(0);
7298 connection_.SendConnectivityProbingPacket(&probing_writer,
7299 connection_.peer_address());
7300}
7301
7302TEST_P(QuicConnectionTest, WriterErrorWhenServerSendsConnectivityProbe) {
dschinazi1c6e5922020-06-19 10:35:03 -07007303 PathProbeTestInit(Perspective::IS_SERVER);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007304
7305 writer_->SetShouldWriteFail();
7306 // Connection should not be closed if a connectivity probe is failed to be
7307 // sent.
fkastenholz5d880a92019-06-21 09:01:56 -07007308 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007309
7310 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
7311 .Times(0);
7312 connection_.SendConnectivityProbingPacket(writer_.get(),
7313 connection_.peer_address());
7314}
7315
7316TEST_P(QuicConnectionTest, PublicReset) {
fayangc31c9952019-06-05 13:54:48 -07007317 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007318 return;
7319 }
7320 QuicPublicResetPacket header;
7321 // Public reset packet in only built by server.
7322 header.connection_id = connection_id_;
7323 std::unique_ptr<QuicEncryptedPacket> packet(
7324 framer_.BuildPublicResetPacket(header));
7325 std::unique_ptr<QuicReceivedPacket> received(
7326 ConstructReceivedPacket(*packet, QuicTime::Zero()));
fkastenholz5d880a92019-06-21 09:01:56 -07007327 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7328 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007329 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07007330 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007331 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7332 IsError(QUIC_PUBLIC_RESET));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007333}
7334
7335TEST_P(QuicConnectionTest, IetfStatelessReset) {
fayangc31c9952019-06-05 13:54:48 -07007336 if (!VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007337 return;
7338 }
7339 const QuicUint128 kTestStatelessResetToken = 1010101;
7340 QuicConfig config;
7341 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
7342 kTestStatelessResetToken);
7343 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7344 connection_.SetFromConfig(config);
7345 std::unique_ptr<QuicEncryptedPacket> packet(
7346 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
7347 kTestStatelessResetToken));
7348 std::unique_ptr<QuicReceivedPacket> received(
7349 ConstructReceivedPacket(*packet, QuicTime::Zero()));
renjietang7f483b52020-05-20 14:30:47 -07007350 EXPECT_CALL(visitor_, ValidateStatelessReset(_, _)).WillOnce(Return(true));
fkastenholz5d880a92019-06-21 09:01:56 -07007351 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7352 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007353 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07007354 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007355 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7356 IsError(QUIC_PUBLIC_RESET));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007357}
7358
7359TEST_P(QuicConnectionTest, GoAway) {
fkastenholz305e1732019-06-18 05:01:22 -07007360 if (VersionHasIetfQuicFrames(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007361 // GoAway is not available in version 99.
7362 return;
7363 }
7364
7365 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7366
wub8a5dafa2020-05-13 12:30:17 -07007367 QuicGoAwayFrame* goaway = new QuicGoAwayFrame();
7368 goaway->last_good_stream_id = 1;
7369 goaway->error_code = QUIC_PEER_GOING_AWAY;
7370 goaway->reason_phrase = "Going away.";
QUICHE teama6ef0a62019-03-07 20:34:33 -05007371 EXPECT_CALL(visitor_, OnGoAway(_));
wub8a5dafa2020-05-13 12:30:17 -07007372 ProcessGoAwayPacket(goaway);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007373}
7374
7375TEST_P(QuicConnectionTest, WindowUpdate) {
7376 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7377
wub8a5dafa2020-05-13 12:30:17 -07007378 QuicWindowUpdateFrame* window_update = new QuicWindowUpdateFrame();
7379 window_update->stream_id = 3;
7380 window_update->max_data = 1234;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007381 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
wub8a5dafa2020-05-13 12:30:17 -07007382 ProcessFramePacket(QuicFrame(window_update));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007383}
7384
7385TEST_P(QuicConnectionTest, Blocked) {
7386 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7387
wub8a5dafa2020-05-13 12:30:17 -07007388 QuicBlockedFrame* blocked = new QuicBlockedFrame();
7389 blocked->stream_id = 3;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007390 EXPECT_CALL(visitor_, OnBlockedFrame(_));
wub8a5dafa2020-05-13 12:30:17 -07007391 ProcessFramePacket(QuicFrame(blocked));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007392 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_received);
7393 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7394}
7395
7396TEST_P(QuicConnectionTest, ZeroBytePacket) {
7397 // Don't close the connection for zero byte packets.
fkastenholz5d880a92019-06-21 09:01:56 -07007398 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007399 QuicReceivedPacket encrypted(nullptr, 0, QuicTime::Zero());
7400 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, encrypted);
7401}
7402
7403TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
fayangd4291e42019-05-30 10:31:21 -07007404 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007405 return;
7406 }
7407 // Set the packet number of the ack packet to be least unacked (4).
7408 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 3);
7409 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7410 ProcessStopWaitingPacket(InitStopWaitingFrame(4));
fayangc31c9952019-06-05 13:54:48 -07007411 EXPECT_FALSE(connection_.ack_frame().packets.Empty());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007412}
7413
QUICHE teama6ef0a62019-03-07 20:34:33 -05007414TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
dschinazi48ac9192019-07-31 00:07:26 -07007415 // All supported versions except the one the connection supports.
7416 ParsedQuicVersionVector versions;
7417 for (auto version : AllSupportedVersions()) {
7418 if (version != connection_.version()) {
7419 versions.push_back(version);
7420 }
7421 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007422
7423 // Send a version negotiation packet.
7424 std::unique_ptr<QuicEncryptedPacket> encrypted(
dschinazib417d602019-05-29 13:08:45 -07007425 QuicFramer::BuildVersionNegotiationPacket(
7426 connection_id_, EmptyQuicConnectionId(),
fayangd4291e42019-05-30 10:31:21 -07007427 VersionHasIetfInvariantHeader(connection_.transport_version()),
dschinazi48ac9192019-07-31 00:07:26 -07007428 connection_.version().HasLengthPrefixedConnectionIds(), versions));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007429 std::unique_ptr<QuicReceivedPacket> received(
7430 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
fkastenholz5d880a92019-06-21 09:01:56 -07007431 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7432 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
fayang95cef072019-10-10 12:44:14 -07007433 // Verify no connection close packet gets sent.
7434 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007435 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fayang9ed391a2019-06-20 11:16:59 -07007436 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007437 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007438 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7439 IsError(QUIC_INVALID_VERSION));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007440}
7441
7442TEST_P(QuicConnectionTest, BadVersionNegotiation) {
7443 // Send a version negotiation packet with the version the client started with.
7444 // It should be rejected.
fkastenholz5d880a92019-06-21 09:01:56 -07007445 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7446 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007447 std::unique_ptr<QuicEncryptedPacket> encrypted(
dschinazib417d602019-05-29 13:08:45 -07007448 QuicFramer::BuildVersionNegotiationPacket(
7449 connection_id_, EmptyQuicConnectionId(),
fayangd4291e42019-05-30 10:31:21 -07007450 VersionHasIetfInvariantHeader(connection_.transport_version()),
dschinazi48ac9192019-07-31 00:07:26 -07007451 connection_.version().HasLengthPrefixedConnectionIds(),
QUICHE teama6ef0a62019-03-07 20:34:33 -05007452 AllSupportedVersions()));
7453 std::unique_ptr<QuicReceivedPacket> received(
7454 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
7455 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
fkastenholz5d880a92019-06-21 09:01:56 -07007456 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007457 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7458 IsError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007459}
7460
7461TEST_P(QuicConnectionTest, CheckSendStats) {
fayang5f135052019-08-22 17:59:40 -07007462 if (connection_.PtoEnabled()) {
7463 return;
7464 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007465 connection_.SetMaxTailLossProbes(0);
7466
7467 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7468 connection_.SendStreamDataWithString(3, "first", 0, NO_FIN);
7469 size_t first_packet_size = writer_->last_packet_size();
7470
7471 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7472 connection_.SendStreamDataWithString(5, "second", 0, NO_FIN);
7473 size_t second_packet_size = writer_->last_packet_size();
7474
7475 // 2 retransmissions due to rto, 1 due to explicit nack.
7476 EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
7477 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
7478
7479 // Retransmit due to RTO.
7480 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
7481 connection_.GetRetransmissionAlarm()->Fire();
7482
7483 // Retransmit due to explicit nacks.
7484 QuicAckFrame nack_three =
7485 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
7486 {QuicPacketNumber(4), QuicPacketNumber(5)}});
7487
7488 LostPacketVector lost_packets;
dschinazi66dea072019-04-09 11:41:06 -07007489 lost_packets.push_back(
7490 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
7491 lost_packets.push_back(
7492 LostPacket(QuicPacketNumber(3), kMaxOutgoingPacketSize));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007493 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
wubaa51f0e2020-05-12 15:08:16 -07007494 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
7495 Return(LossDetectionInterface::DetectionStats())));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007496 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007497 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7498 ProcessAckPacket(&nack_three);
7499
7500 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
7501 .WillOnce(Return(QuicBandwidth::Zero()));
7502
7503 const QuicConnectionStats& stats = connection_.GetStats();
7504 // For IETF QUIC, version is not included as the encryption level switches to
7505 // FORWARD_SECURE in SendStreamDataWithString.
7506 size_t save_on_version =
fayangd4291e42019-05-30 10:31:21 -07007507 VersionHasIetfInvariantHeader(GetParam().version.transport_version)
7508 ? 0
7509 : kQuicVersionSize;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007510 EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - save_on_version,
7511 stats.bytes_sent);
7512 EXPECT_EQ(5u, stats.packets_sent);
7513 EXPECT_EQ(2 * first_packet_size + second_packet_size - save_on_version,
7514 stats.bytes_retransmitted);
7515 EXPECT_EQ(3u, stats.packets_retransmitted);
7516 EXPECT_EQ(1u, stats.rto_count);
7517 EXPECT_EQ(kDefaultMaxPacketSize, stats.max_packet_size);
7518}
7519
7520TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
7521 // Construct a packet with stream frame and connection close frame.
7522 QuicPacketHeader header;
dschinazi5e1a7b22019-07-31 12:23:21 -07007523 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
QUICHE team2252b702019-05-14 23:55:14 -04007524 header.source_connection_id = connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007525 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
fayangd4291e42019-05-30 10:31:21 -07007526 if (!VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04007527 header.source_connection_id_included = CONNECTION_ID_PRESENT;
7528 }
7529 } else {
7530 header.destination_connection_id = connection_id_;
fayangd4291e42019-05-30 10:31:21 -07007531 if (VersionHasIetfInvariantHeader(peer_framer_.transport_version())) {
QUICHE team2252b702019-05-14 23:55:14 -04007532 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
7533 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007534 }
7535 header.packet_number = QuicPacketNumber(1);
7536 header.version_flag = false;
7537
fkastenholz488a4622019-08-26 06:24:46 -07007538 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
7539 // This QuicConnectionCloseFrame will default to being for a Google QUIC
7540 // close. If doing IETF QUIC then set fields appropriately for CC/T or CC/A,
7541 // depending on the mapping.
fkastenholz591814c2019-09-06 12:11:46 -07007542 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
7543 kQuicErrorCode, "",
7544 /*transport_close_frame_type=*/0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007545 QuicFrames frames;
7546 frames.push_back(QuicFrame(frame1_));
7547 frames.push_back(QuicFrame(&qccf));
7548 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
7549 EXPECT_TRUE(nullptr != packet);
dschinazi66dea072019-04-09 11:41:06 -07007550 char buffer[kMaxOutgoingPacketSize];
nharperc6b99512019-09-19 11:13:48 -07007551 size_t encrypted_length = peer_framer_.EncryptPayload(
7552 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
7553 kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007554
fkastenholz5d880a92019-06-21 09:01:56 -07007555 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7556 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007557 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7558 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7559
7560 connection_.ProcessUdpPacket(
7561 kSelfAddress, kPeerAddress,
7562 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
fkastenholz5d880a92019-06-21 09:01:56 -07007563 EXPECT_EQ(1, connection_close_frame_count_);
bnc77e77b82020-04-05 10:36:49 -07007564 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
bncf54082a2019-11-27 10:19:47 -08007565 IsError(QUIC_PEER_GOING_AWAY));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007566}
7567
7568TEST_P(QuicConnectionTest, SelectMutualVersion) {
7569 connection_.SetSupportedVersions(AllSupportedVersions());
7570 // Set the connection to speak the lowest quic version.
7571 connection_.set_version(QuicVersionMin());
7572 EXPECT_EQ(QuicVersionMin(), connection_.version());
7573
7574 // Pass in available versions which includes a higher mutually supported
7575 // version. The higher mutually supported version should be selected.
7576 ParsedQuicVersionVector supported_versions = AllSupportedVersions();
7577 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
7578 EXPECT_EQ(QuicVersionMax(), connection_.version());
7579
7580 // Expect that the lowest version is selected.
7581 // Ensure the lowest supported version is less than the max, unless they're
7582 // the same.
7583 ParsedQuicVersionVector lowest_version_vector;
7584 lowest_version_vector.push_back(QuicVersionMin());
7585 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
7586 EXPECT_EQ(QuicVersionMin(), connection_.version());
7587
7588 // Shouldn't be able to find a mutually supported version.
7589 ParsedQuicVersionVector unsupported_version;
7590 unsupported_version.push_back(UnsupportedQuicVersion());
7591 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
7592}
7593
7594TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
7595 EXPECT_FALSE(writer_->IsWriteBlocked());
7596
7597 // Send a packet.
7598 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7599 EXPECT_EQ(0u, connection_.NumQueuedPackets());
7600 EXPECT_EQ(1u, writer_->packets_write_attempts());
7601
7602 TriggerConnectionClose();
rch39c88ab2019-10-16 19:24:40 -07007603 EXPECT_LE(2u, writer_->packets_write_attempts());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007604}
7605
7606TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
7607 BlockOnNextWrite();
7608 TriggerConnectionClose();
7609 EXPECT_EQ(1u, writer_->packets_write_attempts());
7610 EXPECT_TRUE(writer_->IsWriteBlocked());
7611}
7612
7613TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
7614 BlockOnNextWrite();
7615 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7616 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7617 EXPECT_EQ(1u, writer_->packets_write_attempts());
7618 EXPECT_TRUE(writer_->IsWriteBlocked());
7619 TriggerConnectionClose();
7620 EXPECT_EQ(1u, writer_->packets_write_attempts());
7621}
7622
7623TEST_P(QuicConnectionTest, OnPacketSentDebugVisitor) {
dschinazi1c6e5922020-06-19 10:35:03 -07007624 PathProbeTestInit(Perspective::IS_CLIENT);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007625 MockQuicConnectionDebugVisitor debug_visitor;
7626 connection_.set_debug_visitor(&debug_visitor);
7627
fayangcff885a2019-10-22 07:39:04 -07007628 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007629 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7630
fayangcff885a2019-10-22 07:39:04 -07007631 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007632 connection_.SendConnectivityProbingPacket(writer_.get(),
7633 connection_.peer_address());
7634}
7635
7636TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
7637 QuicPacketHeader header;
7638 header.packet_number = QuicPacketNumber(1);
fayangd4291e42019-05-30 10:31:21 -07007639 if (VersionHasIetfInvariantHeader(GetParam().version.transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007640 header.form = IETF_QUIC_LONG_HEADER_PACKET;
7641 }
7642
7643 MockQuicConnectionDebugVisitor debug_visitor;
7644 connection_.set_debug_visitor(&debug_visitor);
7645 EXPECT_CALL(debug_visitor, OnPacketHeader(Ref(header))).Times(1);
7646 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(1);
7647 EXPECT_CALL(debug_visitor, OnSuccessfulVersionNegotiation(_)).Times(1);
7648 connection_.OnPacketHeader(header);
7649}
7650
7651TEST_P(QuicConnectionTest, Pacing) {
7652 TestConnection server(connection_id_, kSelfAddress, helper_.get(),
7653 alarm_factory_.get(), writer_.get(),
7654 Perspective::IS_SERVER, version());
7655 TestConnection client(connection_id_, kPeerAddress, helper_.get(),
7656 alarm_factory_.get(), writer_.get(),
7657 Perspective::IS_CLIENT, version());
7658 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7659 static_cast<const QuicSentPacketManager*>(
7660 &client.sent_packet_manager())));
7661 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7662 static_cast<const QuicSentPacketManager*>(
7663 &server.sent_packet_manager())));
7664}
7665
7666TEST_P(QuicConnectionTest, WindowUpdateInstigateAcks) {
7667 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7668
7669 // Send a WINDOW_UPDATE frame.
wub8a5dafa2020-05-13 12:30:17 -07007670 QuicWindowUpdateFrame* window_update = new QuicWindowUpdateFrame();
7671 window_update->stream_id = 3;
7672 window_update->max_data = 1234;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007673 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
wub8a5dafa2020-05-13 12:30:17 -07007674 ProcessFramePacket(QuicFrame(window_update));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007675
7676 // Ensure that this has caused the ACK alarm to be set.
fayang9adfb532020-06-04 06:58:45 -07007677 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007678}
7679
7680TEST_P(QuicConnectionTest, BlockedFrameInstigateAcks) {
7681 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7682
7683 // Send a BLOCKED frame.
wub8a5dafa2020-05-13 12:30:17 -07007684 QuicBlockedFrame* blocked = new QuicBlockedFrame();
7685 blocked->stream_id = 3;
QUICHE teama6ef0a62019-03-07 20:34:33 -05007686 EXPECT_CALL(visitor_, OnBlockedFrame(_));
wub8a5dafa2020-05-13 12:30:17 -07007687 ProcessFramePacket(QuicFrame(blocked));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007688
7689 // Ensure that this has caused the ACK alarm to be set.
fayang9adfb532020-06-04 06:58:45 -07007690 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007691}
7692
7693TEST_P(QuicConnectionTest, ReevaluateTimeUntilSendOnAck) {
7694 // Enable pacing.
7695 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7696 QuicConfig config;
7697 connection_.SetFromConfig(config);
7698
7699 // Send two packets. One packet is not sufficient because if it gets acked,
7700 // there will be no packets in flight after that and the pacer will always
7701 // allow the next packet in that situation.
7702 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7703 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7704 connection_.SendStreamDataWithString(
7705 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7706 0, NO_FIN);
7707 connection_.SendStreamDataWithString(
7708 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "bar",
7709 3, NO_FIN);
7710 connection_.OnCanWrite();
7711
7712 // Schedule the next packet for a few milliseconds in future.
7713 QuicSentPacketManagerPeer::DisablePacerBursts(manager_);
7714 QuicTime scheduled_pacing_time =
7715 clock_.Now() + QuicTime::Delta::FromMilliseconds(5);
7716 QuicSentPacketManagerPeer::SetNextPacedPacketTime(manager_,
7717 scheduled_pacing_time);
7718
7719 // Send a packet and have it be blocked by congestion control.
7720 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false));
7721 connection_.SendStreamDataWithString(
7722 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "baz",
7723 6, NO_FIN);
7724 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
7725
7726 // Process an ack and the send alarm will be set to the new 5ms delay.
7727 QuicAckFrame ack = InitAckFrame(1);
7728 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7729 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7730 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7731 ProcessAckPacket(&ack);
nharper55fa6132019-05-07 19:37:21 -07007732 size_t padding_frame_count = writer_->padding_frames().size();
7733 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007734 EXPECT_EQ(1u, writer_->stream_frames().size());
7735 EXPECT_TRUE(connection_.GetSendAlarm()->IsSet());
7736 EXPECT_EQ(scheduled_pacing_time, connection_.GetSendAlarm()->deadline());
7737 writer_->Reset();
7738}
7739
7740TEST_P(QuicConnectionTest, SendAcksImmediately) {
QUICHE teamcd098022019-03-22 18:49:55 -07007741 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7742 return;
7743 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05007744 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7745 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7746 ProcessDataPacket(1);
7747 CongestionBlockWrites();
7748 SendAckPacketToPeer();
7749}
7750
7751TEST_P(QuicConnectionTest, SendPingImmediately) {
7752 MockQuicConnectionDebugVisitor debug_visitor;
7753 connection_.set_debug_visitor(&debug_visitor);
7754
7755 CongestionBlockWrites();
fayang93cc53a2019-08-22 12:47:30 -07007756 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007757 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayangcff885a2019-10-22 07:39:04 -07007758 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007759 EXPECT_CALL(debug_visitor, OnPingSent()).Times(1);
7760 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7761 EXPECT_FALSE(connection_.HasQueuedData());
7762}
7763
7764TEST_P(QuicConnectionTest, SendBlockedImmediately) {
7765 MockQuicConnectionDebugVisitor debug_visitor;
7766 connection_.set_debug_visitor(&debug_visitor);
7767
fayang93cc53a2019-08-22 12:47:30 -07007768 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007769 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayangcff885a2019-10-22 07:39:04 -07007770 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05007771 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7772 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
7773 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_sent);
7774 EXPECT_FALSE(connection_.HasQueuedData());
7775}
7776
fayang93cc53a2019-08-22 12:47:30 -07007777TEST_P(QuicConnectionTest, FailedToSendBlockedFrames) {
7778 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
7779 return;
7780 }
7781 MockQuicConnectionDebugVisitor debug_visitor;
7782 connection_.set_debug_visitor(&debug_visitor);
7783 QuicBlockedFrame blocked(1, 3);
7784
7785 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
fayangcff885a2019-10-22 07:39:04 -07007786 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(0);
fayang93cc53a2019-08-22 12:47:30 -07007787 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7788 connection_.SendControlFrame(QuicFrame(&blocked));
7789 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7790 EXPECT_FALSE(connection_.HasQueuedData());
7791}
7792
QUICHE teama6ef0a62019-03-07 20:34:33 -05007793TEST_P(QuicConnectionTest, SendingUnencryptedStreamDataFails) {
7794 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
7795 if (!IsDefaultTestConfiguration()) {
7796 return;
7797 }
7798
fkastenholz5d880a92019-06-21 09:01:56 -07007799 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7800 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007801 struct iovec iov;
7802 MakeIOVector("", &iov);
7803 EXPECT_QUIC_BUG(connection_.SaveAndSendStreamData(3, &iov, 1, 0, 0, FIN),
fayang49523232019-05-03 06:28:22 -07007804 "Cannot send stream data with level: ENCRYPTION_INITIAL");
QUICHE teama6ef0a62019-03-07 20:34:33 -05007805 EXPECT_FALSE(connection_.connected());
fkastenholz5d880a92019-06-21 09:01:56 -07007806 EXPECT_EQ(1, connection_close_frame_count_);
bncf54082a2019-11-27 10:19:47 -08007807 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7808 IsError(QUIC_ATTEMPT_TO_SEND_UNENCRYPTED_STREAM_DATA));
QUICHE teama6ef0a62019-03-07 20:34:33 -05007809}
7810
7811TEST_P(QuicConnectionTest, SetRetransmissionAlarmForCryptoPacket) {
7812 EXPECT_TRUE(connection_.connected());
7813 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
7814
7815 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7816 connection_.SendCryptoStreamData();
7817
7818 // Verify retransmission timer is correctly set after crypto packet has been
7819 // sent.
7820 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
7821 QuicTime retransmission_time =
7822 QuicConnectionPeer::GetSentPacketManager(&connection_)
7823 ->GetRetransmissionTime();
7824 EXPECT_NE(retransmission_time, clock_.ApproximateNow());
7825 EXPECT_EQ(retransmission_time,
7826 connection_.GetRetransmissionAlarm()->deadline());
7827
7828 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7829 connection_.GetRetransmissionAlarm()->Fire();
7830}
7831
vasilvv693d5b02019-04-09 21:58:56 -07007832// Includes regression test for b/69979024.
zhongyi3ae832d2020-06-15 13:03:31 -07007833TEST_P(QuicConnectionTest, PathDegradingDetectionForNonCryptoPackets) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007834 EXPECT_TRUE(connection_.connected());
fayangb59c6f12020-03-23 15:06:14 -07007835 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007836 EXPECT_FALSE(connection_.IsPathDegrading());
7837
7838 const char data[] = "data";
7839 size_t data_size = strlen(data);
7840 QuicStreamOffset offset = 0;
7841
7842 for (int i = 0; i < 2; ++i) {
7843 // Send a packet. Now there's a retransmittable packet on the wire, so the
zhongyi3ae832d2020-06-15 13:03:31 -07007844 // path degrading detection should be set.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007845 connection_.SendStreamDataWithString(
7846 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7847 offset, NO_FIN);
7848 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07007849 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
zhongyi3ae832d2020-06-15 13:03:31 -07007850 // Check the deadline of the path degrading detection.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007851 QuicTime::Delta delay =
7852 QuicConnectionPeer::GetSentPacketManager(&connection_)
7853 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07007854 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7855 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007856
zhongyi3ae832d2020-06-15 13:03:31 -07007857 // Send a second packet. The path degrading detection's deadline should
7858 // remain the same.
vasilvv693d5b02019-04-09 21:58:56 -07007859 // Regression test for b/69979024.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007860 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayang2205d952020-05-12 13:45:56 -07007861 QuicTime prev_deadline =
7862 connection_.GetBlackholeDetectorAlarm()->deadline();
QUICHE teama6ef0a62019-03-07 20:34:33 -05007863 connection_.SendStreamDataWithString(
7864 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7865 offset, NO_FIN);
7866 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07007867 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
fayang2205d952020-05-12 13:45:56 -07007868 EXPECT_EQ(prev_deadline,
7869 connection_.GetBlackholeDetectorAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007870
7871 // Now receive an ACK of the first packet. This should advance the path
zhongyi3ae832d2020-06-15 13:03:31 -07007872 // degrading detection's deadline since forward progress has been made.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007873 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7874 if (i == 0) {
7875 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7876 }
7877 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7878 QuicAckFrame frame = InitAckFrame(
7879 {{QuicPacketNumber(1u + 2u * i), QuicPacketNumber(2u + 2u * i)}});
7880 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07007881 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
zhongyi3ae832d2020-06-15 13:03:31 -07007882 // Check the deadline of the path degrading detection.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007883 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7884 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07007885 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7886 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007887
7888 if (i == 0) {
7889 // Now receive an ACK of the second packet. Since there are no more
7890 // retransmittable packets on the wire, this should cancel the path
zhongyi3ae832d2020-06-15 13:03:31 -07007891 // degrading detection.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007892 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7893 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7894 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7895 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07007896 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007897 } else {
7898 // Advance time to the path degrading alarm's deadline and simulate
7899 // firing the alarm.
7900 clock_.AdvanceTime(delay);
7901 EXPECT_CALL(visitor_, OnPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07007902 connection_.PathDegradingTimeout();
7903 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007904 }
7905 }
7906 EXPECT_TRUE(connection_.IsPathDegrading());
7907}
7908
7909TEST_P(QuicConnectionTest, RetransmittableOnWireSetsPingAlarm) {
7910 const QuicTime::Delta retransmittable_on_wire_timeout =
7911 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07007912 connection_.set_initial_retransmittable_on_wire_timeout(
QUICHE teama6ef0a62019-03-07 20:34:33 -05007913 retransmittable_on_wire_timeout);
7914
7915 EXPECT_TRUE(connection_.connected());
7916 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7917 .WillRepeatedly(Return(true));
7918
fayangb59c6f12020-03-23 15:06:14 -07007919 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007920 EXPECT_FALSE(connection_.IsPathDegrading());
7921 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7922
7923 const char data[] = "data";
7924 size_t data_size = strlen(data);
7925 QuicStreamOffset offset = 0;
7926
7927 // Send a packet.
7928 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7929 offset += data_size;
7930 // Now there's a retransmittable packet on the wire, so the path degrading
7931 // alarm should be set.
7932 // The retransmittable-on-wire alarm should not be set.
fayangb59c6f12020-03-23 15:06:14 -07007933 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007934 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7935 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07007936 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7937 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007938 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7939 // The ping alarm is set for the ping timeout, not the shorter
7940 // retransmittable_on_wire_timeout.
7941 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7942 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
zhongyieef848f2019-10-18 07:09:37 -07007943 EXPECT_EQ(ping_delay,
7944 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007945
7946 // Now receive an ACK of the packet.
7947 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7948 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7949 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7950 QuicAckFrame frame =
7951 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7952 ProcessAckPacket(&frame);
7953 // No more retransmittable packets on the wire, so the path degrading alarm
7954 // should be cancelled, and the ping alarm should be set to the
7955 // retransmittable_on_wire_timeout.
fayangb59c6f12020-03-23 15:06:14 -07007956 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007957 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07007958 EXPECT_EQ(retransmittable_on_wire_timeout,
7959 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007960
7961 // Simulate firing the ping alarm and sending a PING.
7962 clock_.AdvanceTime(retransmittable_on_wire_timeout);
7963 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
7964 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7965 }));
7966 connection_.GetPingAlarm()->Fire();
7967
7968 // Now there's a retransmittable packet (PING) on the wire, so the path
7969 // degrading alarm should be set.
fayangb59c6f12020-03-23 15:06:14 -07007970 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007971 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7972 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07007973 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7974 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007975}
7976
7977// This test verifies that the connection marks path as degrading and does not
7978// spin timer to detect path degrading when a new packet is sent on the
7979// degraded path.
zhongyi3ae832d2020-06-15 13:03:31 -07007980TEST_P(QuicConnectionTest, NoPathDegradingDetectionIfPathIsDegrading) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05007981 EXPECT_TRUE(connection_.connected());
fayangb59c6f12020-03-23 15:06:14 -07007982 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007983 EXPECT_FALSE(connection_.IsPathDegrading());
7984
7985 const char data[] = "data";
7986 size_t data_size = strlen(data);
7987 QuicStreamOffset offset = 0;
7988
7989 // Send the first packet. Now there's a retransmittable packet on the wire, so
7990 // the path degrading alarm should be set.
7991 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7992 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07007993 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
zhongyi3ae832d2020-06-15 13:03:31 -07007994 // Check the deadline of the path degrading detection.
QUICHE teama6ef0a62019-03-07 20:34:33 -05007995 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7996 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07007997 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7998 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05007999
zhongyi3ae832d2020-06-15 13:03:31 -07008000 // Send a second packet. The path degrading detection's deadline should remain
QUICHE teama6ef0a62019-03-07 20:34:33 -05008001 // the same.
8002 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayang2205d952020-05-12 13:45:56 -07008003 QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008004 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8005 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008006 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
fayang2205d952020-05-12 13:45:56 -07008007 EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008008
8009 // Now receive an ACK of the first packet. This should advance the path
zhongyi3ae832d2020-06-15 13:03:31 -07008010 // degrading detection's deadline since forward progress has been made.
QUICHE teama6ef0a62019-03-07 20:34:33 -05008011 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8012 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8013 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8014 QuicAckFrame frame =
8015 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
8016 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07008017 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008018 // Check the deadline of the path degrading alarm.
8019 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8020 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07008021 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8022 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008023
zhongyi3ae832d2020-06-15 13:03:31 -07008024 // Advance time to the path degrading detection's deadline and simulate
8025 // firing the path degrading detection. This path will be considered as
QUICHE teama6ef0a62019-03-07 20:34:33 -05008026 // degrading.
8027 clock_.AdvanceTime(delay);
8028 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
fayangb59c6f12020-03-23 15:06:14 -07008029 connection_.PathDegradingTimeout();
8030 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008031 EXPECT_TRUE(connection_.IsPathDegrading());
8032
8033 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayangb59c6f12020-03-23 15:06:14 -07008034 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
zhongyi3ae832d2020-06-15 13:03:31 -07008035 // Send a third packet. The path degrading detection is no longer set but path
QUICHE teama6ef0a62019-03-07 20:34:33 -05008036 // should still be marked as degrading.
8037 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8038 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008039 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008040 EXPECT_TRUE(connection_.IsPathDegrading());
8041}
8042
8043// This test verifies that the connection unmarks path as degrarding and spins
8044// the timer to detect future path degrading when forward progress is made
8045// after path has been marked degrading.
8046TEST_P(QuicConnectionTest, UnmarkPathDegradingOnForwardProgress) {
8047 EXPECT_TRUE(connection_.connected());
fayangb59c6f12020-03-23 15:06:14 -07008048 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008049 EXPECT_FALSE(connection_.IsPathDegrading());
8050
8051 const char data[] = "data";
8052 size_t data_size = strlen(data);
8053 QuicStreamOffset offset = 0;
8054
8055 // Send the first packet. Now there's a retransmittable packet on the wire, so
8056 // the path degrading alarm should be set.
8057 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8058 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008059 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008060 // Check the deadline of the path degrading alarm.
8061 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8062 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07008063 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8064 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008065
8066 // Send a second packet. The path degrading alarm's deadline should remain
8067 // the same.
8068 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayang2205d952020-05-12 13:45:56 -07008069 QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008070 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8071 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008072 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
fayang2205d952020-05-12 13:45:56 -07008073 EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008074
8075 // Now receive an ACK of the first packet. This should advance the path
8076 // degrading alarm's deadline since forward progress has been made.
8077 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8078 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8079 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8080 QuicAckFrame frame =
8081 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
8082 ProcessAckPacket(&frame);
fayangb59c6f12020-03-23 15:06:14 -07008083 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008084 // Check the deadline of the path degrading alarm.
8085 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
8086 ->GetPathDegradingDelay();
fayang2205d952020-05-12 13:45:56 -07008087 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
8088 clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008089
8090 // Advance time to the path degrading alarm's deadline and simulate
8091 // firing the alarm.
8092 clock_.AdvanceTime(delay);
8093 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
fayangb59c6f12020-03-23 15:06:14 -07008094 connection_.PathDegradingTimeout();
8095 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008096 EXPECT_TRUE(connection_.IsPathDegrading());
8097
8098 // Send a third packet. The path degrading alarm is no longer set but path
8099 // should still be marked as degrading.
8100 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
fayangb59c6f12020-03-23 15:06:14 -07008101 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008102 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8103 offset += data_size;
fayangb59c6f12020-03-23 15:06:14 -07008104 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008105 EXPECT_TRUE(connection_.IsPathDegrading());
8106
8107 // Now receive an ACK of the second packet. This should unmark the path as
8108 // degrading. And will set a timer to detect new path degrading.
8109 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8110 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
zhongyief1d6752020-06-11 16:19:28 -07008111 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008112 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8113 ProcessAckPacket(&frame);
8114 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07008115 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008116}
8117
8118TEST_P(QuicConnectionTest, NoPathDegradingOnServer) {
QUICHE teamcd098022019-03-22 18:49:55 -07008119 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8120 return;
8121 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008122 set_perspective(Perspective::IS_SERVER);
8123 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8124
8125 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07008126 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008127
8128 // Send data.
8129 const char data[] = "data";
8130 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8131 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07008132 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008133
8134 // Ack data.
8135 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008136 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8137 QuicAckFrame frame =
8138 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
8139 ProcessAckPacket(&frame);
8140 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07008141 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008142}
8143
8144TEST_P(QuicConnectionTest, NoPathDegradingAfterSendingAck) {
QUICHE teamcd098022019-03-22 18:49:55 -07008145 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8146 return;
8147 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008148 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8149 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8150 ProcessDataPacket(1);
8151 SendAckPacketToPeer();
8152 EXPECT_FALSE(connection_.sent_packet_manager().unacked_packets().empty());
8153 EXPECT_FALSE(connection_.sent_packet_manager().HasInFlightPackets());
8154 EXPECT_FALSE(connection_.IsPathDegrading());
fayangb59c6f12020-03-23 15:06:14 -07008155 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008156}
8157
8158TEST_P(QuicConnectionTest, MultipleCallsToCloseConnection) {
8159 // Verifies that multiple calls to CloseConnection do not
8160 // result in multiple attempts to close the connection - it will be marked as
8161 // disconnected after the first call.
fkastenholz5d880a92019-06-21 09:01:56 -07008162 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008163 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
8164 ConnectionCloseBehavior::SILENT_CLOSE);
8165 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
8166 ConnectionCloseBehavior::SILENT_CLOSE);
8167}
8168
8169TEST_P(QuicConnectionTest, ServerReceivesChloOnNonCryptoStream) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008170 set_perspective(Perspective::IS_SERVER);
8171 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8172
8173 CryptoHandshakeMessage message;
8174 CryptoFramer framer;
8175 message.set_tag(kCHLO);
QUICHE team3fe6a8b2019-03-14 09:10:38 -07008176 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008177 frame1_.stream_id = 10;
8178 frame1_.data_buffer = data->data();
8179 frame1_.data_length = data->length();
8180
fkastenholz5d880a92019-06-21 09:01:56 -07008181 EXPECT_CALL(visitor_,
8182 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008183 ForceProcessFramePacket(QuicFrame(frame1_));
fkastenholz5d880a92019-06-21 09:01:56 -07008184 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008185}
8186
8187TEST_P(QuicConnectionTest, ClientReceivesRejOnNonCryptoStream) {
8188 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8189
8190 CryptoHandshakeMessage message;
8191 CryptoFramer framer;
8192 message.set_tag(kREJ);
QUICHE team3fe6a8b2019-03-14 09:10:38 -07008193 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008194 frame1_.stream_id = 10;
8195 frame1_.data_buffer = data->data();
8196 frame1_.data_length = data->length();
8197
fkastenholz5d880a92019-06-21 09:01:56 -07008198 EXPECT_CALL(visitor_,
8199 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008200 ForceProcessFramePacket(QuicFrame(frame1_));
fkastenholz5d880a92019-06-21 09:01:56 -07008201 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008202}
8203
8204TEST_P(QuicConnectionTest, CloseConnectionOnPacketTooLarge) {
8205 SimulateNextPacketTooLarge();
8206 // A connection close packet is sent
fkastenholz5d880a92019-06-21 09:01:56 -07008207 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
QUICHE teama6ef0a62019-03-07 20:34:33 -05008208 .Times(1);
8209 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fkastenholz5d880a92019-06-21 09:01:56 -07008210 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008211}
8212
8213TEST_P(QuicConnectionTest, AlwaysGetPacketTooLarge) {
8214 // Test even we always get packet too large, we do not infinitely try to send
8215 // close packet.
8216 AlwaysGetPacketTooLarge();
fkastenholz5d880a92019-06-21 09:01:56 -07008217 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
QUICHE teama6ef0a62019-03-07 20:34:33 -05008218 .Times(1);
8219 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fkastenholz5d880a92019-06-21 09:01:56 -07008220 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008221}
8222
nharperef468962019-07-02 14:15:38 -07008223TEST_P(QuicConnectionTest, CloseConnectionOnQueuedWriteError) {
nharperef468962019-07-02 14:15:38 -07008224 // Regression test for crbug.com/979507.
8225 //
8226 // If we get a write error when writing queued packets, we should attempt to
8227 // send a connection close packet, but if sending that fails, it shouldn't get
8228 // queued.
8229
8230 // Queue a packet to write.
8231 BlockOnNextWrite();
8232 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
8233 EXPECT_EQ(1u, connection_.NumQueuedPackets());
8234
8235 // Configure writer to always fail.
8236 AlwaysGetPacketTooLarge();
8237
8238 // Expect that we attempt to close the connection exactly once.
8239 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
8240 .Times(1);
8241
8242 // Unblock the writes and actually send.
8243 writer_->SetWritable();
8244 connection_.OnCanWrite();
8245 EXPECT_EQ(0u, connection_.NumQueuedPackets());
8246
8247 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
8248}
8249
QUICHE teama6ef0a62019-03-07 20:34:33 -05008250// Verify that if connection has no outstanding data, it notifies the send
8251// algorithm after the write.
8252TEST_P(QuicConnectionTest, SendDataAndBecomeApplicationLimited) {
8253 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
8254 {
8255 InSequence seq;
8256 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
8257 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
8258 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
8259 .WillRepeatedly(Return(false));
8260 }
8261
8262 connection_.SendStreamData3();
8263}
8264
8265// Verify that the connection does not become app-limited if there is
8266// outstanding data to send after the write.
8267TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedIfMoreDataAvailable) {
8268 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
8269 {
8270 InSequence seq;
8271 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
8272 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
8273 }
8274
8275 connection_.SendStreamData3();
8276}
8277
8278// Verify that the connection does not become app-limited after blocked write
8279// even if there is outstanding data to send after the write.
8280TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedDueToWriteBlock) {
8281 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
8282 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
8283 BlockOnNextWrite();
8284
fayange62e63c2019-12-04 07:16:25 -08008285 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008286 connection_.SendStreamData3();
8287
8288 // Now unblock the writer, become congestion control blocked,
8289 // and ensure we become app-limited after writing.
8290 writer_->SetWritable();
8291 CongestionBlockWrites();
8292 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
fayange62e63c2019-12-04 07:16:25 -08008293 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
fayang2ce66082019-10-02 06:29:04 -07008294 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008295 connection_.OnCanWrite();
8296}
8297
8298// Test the mode in which the link is filled up with probing retransmissions if
8299// the connection becomes application-limited.
8300TEST_P(QuicConnectionTest, SendDataWhenApplicationLimited) {
8301 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8302 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
8303 .WillRepeatedly(Return(true));
8304 {
8305 InSequence seq;
8306 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
8307 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
8308 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
8309 .WillRepeatedly(Return(false));
8310 }
QUICHE teamb8343252019-04-29 13:58:01 -07008311 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
8312 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
8313 PROBING_RETRANSMISSION);
8314 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05008315 // Fix congestion window to be 20,000 bytes.
8316 EXPECT_CALL(*send_algorithm_, CanSend(Ge(20000u)))
8317 .WillRepeatedly(Return(false));
8318 EXPECT_CALL(*send_algorithm_, CanSend(Lt(20000u)))
8319 .WillRepeatedly(Return(true));
8320
8321 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
8322 ASSERT_EQ(0u, connection_.GetStats().packets_sent);
8323 connection_.set_fill_up_link_during_probing(true);
fayangedf9ad52020-03-05 13:49:18 -08008324 EXPECT_CALL(visitor_, GetHandshakeState())
fayang15042962020-07-01 12:14:29 -07008325 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008326 connection_.OnHandshakeComplete();
8327 connection_.SendStreamData3();
8328
8329 // We expect a lot of packets from a 20 kbyte window.
8330 EXPECT_GT(connection_.GetStats().packets_sent, 10u);
8331 // Ensure that the packets are padded.
8332 QuicByteCount average_packet_size =
8333 connection_.GetStats().bytes_sent / connection_.GetStats().packets_sent;
8334 EXPECT_GT(average_packet_size, 1000u);
8335
8336 // Acknowledge all packets sent, except for the last one.
8337 QuicAckFrame ack = InitAckFrame(
8338 connection_.sent_packet_manager().GetLargestSentPacket() - 1);
8339 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8340 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8341
8342 // Ensure that since we no longer have retransmittable bytes in flight, this
8343 // will not cause any responses to be sent.
8344 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8345 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
8346 ProcessAckPacket(&ack);
8347}
8348
rchd672c6d2019-11-27 15:30:54 -08008349TEST_P(QuicConnectionTest, DoNotForceSendingAckOnPacketTooLarge) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008350 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8351 // Send an ack by simulating delayed ack alarm firing.
8352 ProcessPacket(1);
fayang9adfb532020-06-04 06:58:45 -07008353 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008354 connection_.GetAckAlarm()->Fire();
8355 // Simulate data packet causes write error.
fkastenholz5d880a92019-06-21 09:01:56 -07008356 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008357 SimulateNextPacketTooLarge();
8358 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
rchd672c6d2019-11-27 15:30:54 -08008359 EXPECT_EQ(1u, writer_->connection_close_frames().size());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008360 // Ack frame is not bundled in connection close packet.
8361 EXPECT_TRUE(writer_->ack_frames().empty());
rchd672c6d2019-11-27 15:30:54 -08008362 if (writer_->padding_frames().empty()) {
8363 EXPECT_EQ(1u, writer_->frame_count());
8364 } else {
8365 EXPECT_EQ(2u, writer_->frame_count());
8366 }
8367
fkastenholz5d880a92019-06-21 09:01:56 -07008368 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008369}
8370
rchd672c6d2019-11-27 15:30:54 -08008371TEST_P(QuicConnectionTest, CloseConnectionAllLevels) {
fayangc303bfd2020-02-11 09:19:54 -08008372 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8373 return;
8374 }
rchd672c6d2019-11-27 15:30:54 -08008375
8376 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8377 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
8378 connection_.CloseConnection(
8379 kQuicErrorCode, "Some random error message",
8380 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8381
8382 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8383
8384 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8385 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8386
8387 if (!connection_.version().CanSendCoalescedPackets()) {
8388 // Each connection close packet should be sent in distinct UDP packets.
8389 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
8390 writer_->connection_close_packets());
8391 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
8392 writer_->packets_write_attempts());
8393 return;
8394 }
8395
8396 // A single UDP packet should be sent with multiple connection close packets
8397 // coalesced together.
8398 EXPECT_EQ(1u, writer_->packets_write_attempts());
8399
8400 // Only the first packet has been processed yet.
8401 EXPECT_EQ(1u, writer_->connection_close_packets());
8402
8403 // ProcessPacket resets the visitor and frees the coalesced packet.
8404 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
8405 auto packet = writer_->coalesced_packet()->Clone();
8406 writer_->framer()->ProcessPacket(*packet);
8407 EXPECT_EQ(1u, writer_->connection_close_packets());
8408 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
8409}
8410
8411TEST_P(QuicConnectionTest, CloseConnectionOneLevel) {
fayangc303bfd2020-02-11 09:19:54 -08008412 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8413 return;
8414 }
rchd672c6d2019-11-27 15:30:54 -08008415
8416 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8417 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
8418 connection_.CloseConnection(
8419 kQuicErrorCode, "Some random error message",
8420 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8421
8422 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8423
8424 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8425 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8426 EXPECT_EQ(1u, writer_->connection_close_packets());
8427 EXPECT_EQ(1u, writer_->packets_write_attempts());
8428 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
8429}
8430
fayang9abdfec2020-02-13 12:34:58 -08008431TEST_P(QuicConnectionTest, DoNotPadServerInitialConnectionClose) {
8432 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8433 return;
8434 }
8435 set_perspective(Perspective::IS_SERVER);
8436
8437 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8438 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
8439 connection_.CloseConnection(
8440 kQuicErrorCode, "Some random error message",
8441 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8442
8443 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8444
8445 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8446 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8447 EXPECT_TRUE(writer_->padding_frames().empty());
8448 EXPECT_EQ(ENCRYPTION_INITIAL, writer_->framer()->last_decrypted_level());
8449}
8450
QUICHE teama6ef0a62019-03-07 20:34:33 -05008451// Regression test for b/63620844.
8452TEST_P(QuicConnectionTest, FailedToWriteHandshakePacket) {
8453 SimulateNextPacketTooLarge();
fkastenholz5d880a92019-06-21 09:01:56 -07008454 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
QUICHE teama6ef0a62019-03-07 20:34:33 -05008455 .Times(1);
fkastenholz5d880a92019-06-21 09:01:56 -07008456
QUICHE teama6ef0a62019-03-07 20:34:33 -05008457 connection_.SendCryptoStreamData();
fkastenholz5d880a92019-06-21 09:01:56 -07008458 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008459}
8460
8461TEST_P(QuicConnectionTest, MaxPacingRate) {
8462 EXPECT_EQ(0, connection_.MaxPacingRate().ToBytesPerSecond());
8463 connection_.SetMaxPacingRate(QuicBandwidth::FromBytesPerSecond(100));
8464 EXPECT_EQ(100, connection_.MaxPacingRate().ToBytesPerSecond());
8465}
8466
8467TEST_P(QuicConnectionTest, ClientAlwaysSendConnectionId) {
8468 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
8469 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8470 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
8471 EXPECT_EQ(CONNECTION_ID_PRESENT,
8472 writer_->last_packet_header().destination_connection_id_included);
8473
8474 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8475 QuicConfig config;
8476 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
8477 connection_.SetFromConfig(config);
8478
8479 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8480 connection_.SendStreamDataWithString(3, "bar", 3, NO_FIN);
8481 // Verify connection id is still sent in the packet.
8482 EXPECT_EQ(CONNECTION_ID_PRESENT,
8483 writer_->last_packet_header().destination_connection_id_included);
8484}
8485
8486TEST_P(QuicConnectionTest, SendProbingRetransmissions) {
8487 MockQuicConnectionDebugVisitor debug_visitor;
8488 connection_.set_debug_visitor(&debug_visitor);
8489
8490 const QuicStreamId stream_id = 2;
8491 QuicPacketNumber last_packet;
8492 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
8493 SendStreamDataToPeer(stream_id, "bar", 3, NO_FIN, &last_packet);
8494 SendStreamDataToPeer(stream_id, "test", 6, NO_FIN, &last_packet);
8495
8496 const QuicByteCount old_bytes_in_flight =
8497 connection_.sent_packet_manager().GetBytesInFlight();
8498
8499 // Allow 9 probing retransmissions to be sent.
8500 {
8501 InSequence seq;
8502 EXPECT_CALL(*send_algorithm_, CanSend(_))
8503 .Times(9 * 2)
8504 .WillRepeatedly(Return(true));
8505 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
8506 }
8507 // Expect them retransmitted in cyclic order (foo, bar, test, foo, bar...).
8508 QuicPacketCount sent_count = 0;
fayangcff885a2019-10-22 07:39:04 -07008509 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _))
QUICHE teama6ef0a62019-03-07 20:34:33 -05008510 .WillRepeatedly(Invoke([this, &sent_count](const SerializedPacket&,
QUICHE teama6ef0a62019-03-07 20:34:33 -05008511 TransmissionType, QuicTime) {
8512 ASSERT_EQ(1u, writer_->stream_frames().size());
fayang58f71072019-11-05 08:47:02 -08008513 if (connection_.version().CanSendCoalescedPackets()) {
8514 // There is a delay of sending coalesced packet, so (6, 0, 3, 6,
8515 // 0...).
8516 EXPECT_EQ(3 * ((sent_count + 2) % 3),
8517 writer_->stream_frames()[0]->offset);
8518 } else {
8519 // Identify the frames by stream offset (0, 3, 6, 0, 3...).
8520 EXPECT_EQ(3 * (sent_count % 3), writer_->stream_frames()[0]->offset);
8521 }
QUICHE teama6ef0a62019-03-07 20:34:33 -05008522 sent_count++;
8523 }));
8524 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
8525 .WillRepeatedly(Return(true));
QUICHE teamb8343252019-04-29 13:58:01 -07008526 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
8527 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
8528 PROBING_RETRANSMISSION);
8529 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05008530
8531 connection_.SendProbingRetransmissions();
8532
8533 // Ensure that the in-flight has increased.
8534 const QuicByteCount new_bytes_in_flight =
8535 connection_.sent_packet_manager().GetBytesInFlight();
8536 EXPECT_GT(new_bytes_in_flight, old_bytes_in_flight);
8537}
8538
8539// Ensure that SendProbingRetransmissions() does not retransmit anything when
8540// there are no outstanding packets.
8541TEST_P(QuicConnectionTest,
8542 SendProbingRetransmissionsFailsWhenNothingToRetransmit) {
8543 ASSERT_TRUE(connection_.sent_packet_manager().unacked_packets().empty());
8544
8545 MockQuicConnectionDebugVisitor debug_visitor;
8546 connection_.set_debug_visitor(&debug_visitor);
fayangcff885a2019-10-22 07:39:04 -07008547 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008548 EXPECT_CALL(*send_algorithm_, ShouldSendProbingPacket())
8549 .WillRepeatedly(Return(true));
QUICHE teamb8343252019-04-29 13:58:01 -07008550 EXPECT_CALL(visitor_, SendProbingData()).WillRepeatedly([this] {
8551 return connection_.sent_packet_manager().MaybeRetransmitOldestPacket(
8552 PROBING_RETRANSMISSION);
8553 });
QUICHE teama6ef0a62019-03-07 20:34:33 -05008554
8555 connection_.SendProbingRetransmissions();
8556}
8557
8558TEST_P(QuicConnectionTest, PingAfterLastRetransmittablePacketAcked) {
8559 const QuicTime::Delta retransmittable_on_wire_timeout =
8560 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07008561 connection_.set_initial_retransmittable_on_wire_timeout(
QUICHE teama6ef0a62019-03-07 20:34:33 -05008562 retransmittable_on_wire_timeout);
8563
8564 EXPECT_TRUE(connection_.connected());
8565 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8566 .WillRepeatedly(Return(true));
8567
8568 const char data[] = "data";
8569 size_t data_size = strlen(data);
8570 QuicStreamOffset offset = 0;
8571
8572 // Advance 5ms, send a retransmittable packet to the peer.
8573 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8574 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8575 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8576 offset += data_size;
8577 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8578 // The ping alarm is set for the ping timeout, not the shorter
8579 // retransmittable_on_wire_timeout.
8580 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8581 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
zhongyieef848f2019-10-18 07:09:37 -07008582 EXPECT_EQ(ping_delay,
8583 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008584
8585 // Advance 5ms, send a second retransmittable packet to the peer.
8586 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8587 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8588 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8589 offset += data_size;
8590 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8591
8592 // Now receive an ACK of the first packet. This should not set the
8593 // retransmittable-on-wire alarm since packet 2 is still on the wire.
8594 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8595 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8596 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8597 QuicAckFrame frame =
8598 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8599 ProcessAckPacket(&frame);
8600 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8601 // The ping alarm is set for the ping timeout, not the shorter
8602 // retransmittable_on_wire_timeout.
8603 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8604 // The ping alarm has a 1 second granularity, and the clock has been advanced
8605 // 10ms since it was originally set.
zhongyieef848f2019-10-18 07:09:37 -07008606 EXPECT_EQ(ping_delay - QuicTime::Delta::FromMilliseconds(10),
8607 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008608
8609 // Now receive an ACK of the second packet. This should set the
8610 // retransmittable-on-wire alarm now that no retransmittable packets are on
8611 // the wire.
8612 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8613 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8614 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8615 ProcessAckPacket(&frame);
8616 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07008617 EXPECT_EQ(retransmittable_on_wire_timeout,
8618 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008619
8620 // Now receive a duplicate ACK of the second packet. This should not update
8621 // the ping alarm.
8622 QuicTime prev_deadline = connection_.GetPingAlarm()->deadline();
8623 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8624 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8625 ProcessAckPacket(&frame);
8626 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8627 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8628
8629 // Now receive a non-ACK packet. This should not update the ping alarm.
8630 prev_deadline = connection_.GetPingAlarm()->deadline();
8631 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8632 ProcessPacket(4);
8633 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8634 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8635
8636 // Simulate the alarm firing and check that a PING is sent.
8637 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8638 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
8639 }));
8640 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07008641 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008642 if (GetParam().no_stop_waiting) {
nharper55fa6132019-05-07 19:37:21 -07008643 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008644 } else {
nharper55fa6132019-05-07 19:37:21 -07008645 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008646 }
8647 ASSERT_EQ(1u, writer_->ping_frames().size());
8648}
8649
8650TEST_P(QuicConnectionTest, NoPingIfRetransmittablePacketSent) {
8651 const QuicTime::Delta retransmittable_on_wire_timeout =
8652 QuicTime::Delta::FromMilliseconds(50);
zhongyi79ace162019-10-21 15:57:09 -07008653 connection_.set_initial_retransmittable_on_wire_timeout(
QUICHE teama6ef0a62019-03-07 20:34:33 -05008654 retransmittable_on_wire_timeout);
8655
8656 EXPECT_TRUE(connection_.connected());
8657 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8658 .WillRepeatedly(Return(true));
8659
8660 const char data[] = "data";
8661 size_t data_size = strlen(data);
8662 QuicStreamOffset offset = 0;
8663
8664 // Advance 5ms, send a retransmittable packet to the peer.
8665 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8666 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8667 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8668 offset += data_size;
8669 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8670 // The ping alarm is set for the ping timeout, not the shorter
8671 // retransmittable_on_wire_timeout.
8672 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8673 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
zhongyieef848f2019-10-18 07:09:37 -07008674 EXPECT_EQ(ping_delay,
8675 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008676
8677 // Now receive an ACK of the first packet. This should set the
8678 // retransmittable-on-wire alarm now that no retransmittable packets are on
8679 // the wire.
8680 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8681 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8682 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8683 QuicAckFrame frame =
8684 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8685 ProcessAckPacket(&frame);
8686 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07008687 EXPECT_EQ(retransmittable_on_wire_timeout,
8688 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008689
8690 // Before the alarm fires, send another retransmittable packet. This should
8691 // cancel the retransmittable-on-wire alarm since now there's a
8692 // retransmittable packet on the wire.
8693 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8694 offset += data_size;
8695 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8696
8697 // Now receive an ACK of the second packet. This should set the
8698 // retransmittable-on-wire alarm now that no retransmittable packets are on
8699 // the wire.
8700 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8701 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8702 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8703 ProcessAckPacket(&frame);
8704 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
zhongyieef848f2019-10-18 07:09:37 -07008705 EXPECT_EQ(retransmittable_on_wire_timeout,
8706 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008707
8708 // Simulate the alarm firing and check that a PING is sent.
8709 writer_->Reset();
8710 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8711 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
8712 }));
8713 connection_.GetPingAlarm()->Fire();
nharper55fa6132019-05-07 19:37:21 -07008714 size_t padding_frame_count = writer_->padding_frames().size();
QUICHE teama6ef0a62019-03-07 20:34:33 -05008715 if (GetParam().no_stop_waiting) {
fayang8a27b0f2019-11-04 11:27:40 -08008716 // Do not ACK acks.
8717 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008718 } else {
nharper55fa6132019-05-07 19:37:21 -07008719 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
QUICHE teama6ef0a62019-03-07 20:34:33 -05008720 }
8721 ASSERT_EQ(1u, writer_->ping_frames().size());
8722}
8723
zhongyi79ace162019-10-21 15:57:09 -07008724// When there is no stream data received but are open streams, send the
8725// first few consecutive pings with aggressive retransmittable-on-wire
8726// timeout. Exponentially back off the retransmittable-on-wire ping timeout
8727// afterwards until it exceeds the default ping timeout.
8728TEST_P(QuicConnectionTest, BackOffRetransmittableOnWireTimeout) {
8729 int max_aggressive_retransmittable_on_wire_ping_count = 5;
8730 SetQuicFlag(FLAGS_quic_max_aggressive_retransmittable_on_wire_ping_count,
8731 max_aggressive_retransmittable_on_wire_ping_count);
8732 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8733 QuicTime::Delta::FromMilliseconds(200);
8734 connection_.set_initial_retransmittable_on_wire_timeout(
8735 initial_retransmittable_on_wire_timeout);
8736
8737 EXPECT_TRUE(connection_.connected());
8738 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8739 .WillRepeatedly(Return(true));
8740
8741 const char data[] = "data";
8742 // Advance 5ms, send a retransmittable data packet to the peer.
8743 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8744 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8745 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8746 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8747 // The ping alarm is set for the ping timeout, not the shorter
8748 // retransmittable_on_wire_timeout.
8749 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8750 EXPECT_EQ(connection_.ping_timeout(),
8751 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8752
8753 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8754 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
8755 .Times(AnyNumber());
8756
8757 // Verify that the first few consecutive retransmittable on wire pings are
8758 // sent with aggressive timeout.
8759 for (int i = 0; i <= max_aggressive_retransmittable_on_wire_ping_count; i++) {
8760 // Receive an ACK of the previous packet. This should set the ping alarm
8761 // with the initial retransmittable-on-wire timeout.
8762 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8763 QuicPacketNumber ack_num = creator_->packet_number();
8764 QuicAckFrame frame = InitAckFrame(
8765 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8766 ProcessAckPacket(&frame);
8767 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8768 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8769 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8770 // Simulate the alarm firing and check that a PING is sent.
8771 writer_->Reset();
8772 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8773 SendPing();
8774 }));
8775 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8776 connection_.GetPingAlarm()->Fire();
8777 }
8778
8779 QuicTime::Delta retransmittable_on_wire_timeout =
8780 initial_retransmittable_on_wire_timeout;
8781
8782 // Verify subsequent pings are sent with timeout that is exponentially backed
8783 // off.
8784 while (retransmittable_on_wire_timeout * 2 < connection_.ping_timeout()) {
8785 // Receive an ACK for the previous PING. This should set the
8786 // ping alarm with backed off retransmittable-on-wire timeout.
8787 retransmittable_on_wire_timeout = retransmittable_on_wire_timeout * 2;
8788 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8789 QuicPacketNumber ack_num = creator_->packet_number();
8790 QuicAckFrame frame = InitAckFrame(
8791 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8792 ProcessAckPacket(&frame);
8793 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8794 EXPECT_EQ(retransmittable_on_wire_timeout,
8795 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8796
8797 // Simulate the alarm firing and check that a PING is sent.
8798 writer_->Reset();
8799 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8800 SendPing();
8801 }));
8802 clock_.AdvanceTime(retransmittable_on_wire_timeout);
8803 connection_.GetPingAlarm()->Fire();
8804 }
8805
8806 // The ping alarm is set with default ping timeout.
8807 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8808 EXPECT_EQ(connection_.ping_timeout(),
8809 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8810
8811 // Receive an ACK for the previous PING. The ping alarm is set with an
8812 // earlier deadline.
8813 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8814 QuicPacketNumber ack_num = creator_->packet_number();
8815 QuicAckFrame frame = InitAckFrame(
8816 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8817 ProcessAckPacket(&frame);
8818 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8819 EXPECT_EQ(connection_.ping_timeout() - QuicTime::Delta::FromMilliseconds(5),
8820 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8821}
8822
8823// This test verify that the count of consecutive aggressive pings is reset
8824// when new data is received. And it also verifies the connection resets
8825// the exponential back-off of the retransmittable-on-wire ping timeout
8826// after receiving new stream data.
8827TEST_P(QuicConnectionTest, ResetBackOffRetransmitableOnWireTimeout) {
8828 int max_aggressive_retransmittable_on_wire_ping_count = 3;
8829 SetQuicFlag(FLAGS_quic_max_aggressive_retransmittable_on_wire_ping_count, 3);
8830 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8831 QuicTime::Delta::FromMilliseconds(200);
8832 connection_.set_initial_retransmittable_on_wire_timeout(
8833 initial_retransmittable_on_wire_timeout);
8834
8835 EXPECT_TRUE(connection_.connected());
8836 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8837 .WillRepeatedly(Return(true));
8838 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8839 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
8840 .Times(AnyNumber());
8841
8842 const char data[] = "data";
8843 // Advance 5ms, send a retransmittable data packet to the peer.
8844 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8845 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8846 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8847 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8848 // The ping alarm is set for the ping timeout, not the shorter
8849 // retransmittable_on_wire_timeout.
8850 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8851 EXPECT_EQ(connection_.ping_timeout(),
8852 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8853
8854 // Receive an ACK of the first packet. This should set the ping alarm with
8855 // initial retransmittable-on-wire timeout since there is no retransmittable
8856 // packet on the wire.
8857 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8858 QuicAckFrame frame =
8859 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8860 ProcessAckPacket(&frame);
8861 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8862 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8863 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8864
8865 // Simulate the alarm firing and check that a PING is sent.
8866 writer_->Reset();
8867 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
8868 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8869 connection_.GetPingAlarm()->Fire();
8870
8871 // Receive an ACK for the previous PING. Ping alarm will be set with
8872 // aggressive timeout.
8873 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8874 QuicPacketNumber ack_num = creator_->packet_number();
8875 frame = InitAckFrame(
8876 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8877 ProcessAckPacket(&frame);
8878 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8879 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8880 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8881
8882 // Process a data packet.
8883 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8884 ProcessDataPacket(peer_creator_.packet_number() + 1);
8885 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
8886 peer_creator_.packet_number() + 1);
8887 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8888 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8889
8890 // Verify the count of consecutive aggressive pings is reset.
8891 for (int i = 0; i < max_aggressive_retransmittable_on_wire_ping_count; i++) {
8892 // Receive an ACK of the previous packet. This should set the ping alarm
8893 // with the initial retransmittable-on-wire timeout.
8894 QuicPacketNumber ack_num = creator_->packet_number();
8895 QuicAckFrame frame = InitAckFrame(
8896 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8897 ProcessAckPacket(&frame);
8898 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8899 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8900 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8901 // Simulate the alarm firing and check that a PING is sent.
8902 writer_->Reset();
8903 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() {
8904 SendPing();
8905 }));
8906 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8907 connection_.GetPingAlarm()->Fire();
8908 // Advance 5ms to receive next packet.
8909 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8910 }
8911
8912 // Receive another ACK for the previous PING. This should set the
8913 // ping alarm with backed off retransmittable-on-wire timeout.
8914 ack_num = creator_->packet_number();
8915 frame = InitAckFrame(
8916 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8917 ProcessAckPacket(&frame);
8918 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8919 EXPECT_EQ(initial_retransmittable_on_wire_timeout * 2,
8920 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8921
8922 writer_->Reset();
8923 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
8924 clock_.AdvanceTime(2 * initial_retransmittable_on_wire_timeout);
8925 connection_.GetPingAlarm()->Fire();
8926
8927 // Process another data packet and a new ACK packet. The ping alarm is set
8928 // with aggressive ping timeout again.
8929 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8930 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8931 ProcessDataPacket(peer_creator_.packet_number() + 1);
8932 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
8933 peer_creator_.packet_number() + 1);
8934 ack_num = creator_->packet_number();
8935 frame = InitAckFrame(
8936 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8937 ProcessAckPacket(&frame);
8938 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8939 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8940 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8941}
8942
QUICHE teama6ef0a62019-03-07 20:34:33 -05008943TEST_P(QuicConnectionTest, ValidStatelessResetToken) {
8944 const QuicUint128 kTestToken = 1010101;
8945 const QuicUint128 kWrongTestToken = 1010100;
8946 QuicConfig config;
8947 // No token has been received.
8948 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kTestToken));
8949
8950 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(2);
8951 // Token is different from received token.
8952 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8953 connection_.SetFromConfig(config);
8954 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kWrongTestToken));
8955
8956 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8957 connection_.SetFromConfig(config);
8958 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestToken));
8959}
8960
8961TEST_P(QuicConnectionTest, WriteBlockedWithInvalidAck) {
8962 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fayange62e63c2019-12-04 07:16:25 -08008963 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008964 BlockOnNextWrite();
fayange62e63c2019-12-04 07:16:25 -08008965 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008966 connection_.SendStreamDataWithString(5, "foo", 0, FIN);
8967 // This causes connection to be closed because packet 1 has not been sent yet.
8968 QuicAckFrame frame = InitAckFrame(1);
fayange62e63c2019-12-04 07:16:25 -08008969 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
QUICHE teama6ef0a62019-03-07 20:34:33 -05008970 ProcessAckPacket(1, &frame);
fayange62e63c2019-12-04 07:16:25 -08008971 EXPECT_EQ(0, connection_close_frame_count_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008972}
8973
8974TEST_P(QuicConnectionTest, SendMessage) {
fayangc31c9952019-06-05 13:54:48 -07008975 if (!VersionSupportsMessageFrames(connection_.transport_version())) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05008976 return;
8977 }
dschinazied459c02020-05-07 16:12:23 -07008978 if (connection_.version().UsesTls()) {
8979 QuicConfig config;
8980 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
8981 &config, kMaxAcceptedDatagramFrameSize);
8982 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8983 connection_.SetFromConfig(config);
8984 }
ianswettb239f862019-04-05 09:15:06 -07008985 std::string message(connection_.GetCurrentLargestMessagePayload() * 2, 'a');
dmcardlecf0bfcf2019-12-13 08:08:21 -08008986 quiche::QuicheStringPiece message_data(message);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008987 QuicMemSliceStorage storage(nullptr, 0, nullptr, 0);
8988 {
fayanga4b37b22019-06-18 13:37:47 -07008989 QuicConnection::ScopedPacketFlusher flusher(&connection_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05008990 connection_.SendStreamData3();
8991 // Send a message which cannot fit into current open packet, and 2 packets
8992 // get sent, one contains stream frame, and the other only contains the
8993 // message frame.
8994 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
QUICHE team350e9e62019-11-19 13:16:24 -08008995 EXPECT_EQ(MESSAGE_STATUS_SUCCESS,
8996 connection_.SendMessage(
8997 1,
8998 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
dmcardlecf0bfcf2019-12-13 08:08:21 -08008999 quiche::QuicheStringPiece(
QUICHE team350e9e62019-11-19 13:16:24 -08009000 message_data.data(),
9001 connection_.GetCurrentLargestMessagePayload()),
9002 &storage),
9003 false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05009004 }
9005 // Fail to send a message if connection is congestion control blocked.
9006 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
QUICHE team350e9e62019-11-19 13:16:24 -08009007 EXPECT_EQ(MESSAGE_STATUS_BLOCKED,
9008 connection_.SendMessage(
9009 2,
9010 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
9011 "message", &storage),
9012 false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05009013
9014 // Always fail to send a message which cannot fit into one packet.
9015 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
QUICHE team350e9e62019-11-19 13:16:24 -08009016 EXPECT_EQ(MESSAGE_STATUS_TOO_LARGE,
9017 connection_.SendMessage(
9018 3,
9019 MakeSpan(connection_.helper()->GetStreamSendBufferAllocator(),
dmcardlecf0bfcf2019-12-13 08:08:21 -08009020 quiche::QuicheStringPiece(
QUICHE team350e9e62019-11-19 13:16:24 -08009021 message_data.data(),
9022 connection_.GetCurrentLargestMessagePayload() + 1),
9023 &storage),
9024 false));
QUICHE teama6ef0a62019-03-07 20:34:33 -05009025}
9026
dschinazied459c02020-05-07 16:12:23 -07009027TEST_P(QuicConnectionTest, GetCurrentLargestMessagePayload) {
9028 if (!connection_.version().SupportsMessageFrames()) {
9029 return;
9030 }
9031 // Force use of this encrypter to simplify test expectations by making sure
9032 // that the encryption overhead is constant across versions.
9033 connection_.SetEncrypter(ENCRYPTION_INITIAL,
9034 std::make_unique<TaggingEncrypter>(0x00));
9035 QuicPacketLength expected_largest_payload = 1319;
9036 if (connection_.version().SendsVariableLengthPacketNumberInLongHeader()) {
9037 expected_largest_payload += 3;
9038 }
9039 if (connection_.version().HasLongHeaderLengths()) {
9040 expected_largest_payload -= 2;
9041 }
9042 if (connection_.version().HasLengthPrefixedConnectionIds()) {
9043 expected_largest_payload -= 1;
9044 }
9045 if (connection_.version().UsesTls()) {
9046 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
9047 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
9048 QuicConfig config;
9049 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
9050 &config, kMaxAcceptedDatagramFrameSize);
9051 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9052 connection_.SetFromConfig(config);
9053 // Verify the value post-handshake.
9054 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
9055 expected_largest_payload);
9056 } else {
9057 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
9058 expected_largest_payload);
9059 }
9060}
9061
9062TEST_P(QuicConnectionTest, GetGuaranteedLargestMessagePayload) {
9063 if (!connection_.version().SupportsMessageFrames()) {
9064 return;
9065 }
9066 // Force use of this encrypter to simplify test expectations by making sure
9067 // that the encryption overhead is constant across versions.
9068 connection_.SetEncrypter(ENCRYPTION_INITIAL,
9069 std::make_unique<TaggingEncrypter>(0x00));
9070 QuicPacketLength expected_largest_payload = 1319;
9071 if (connection_.version().HasLongHeaderLengths()) {
9072 expected_largest_payload -= 2;
9073 }
9074 if (connection_.version().HasLengthPrefixedConnectionIds()) {
9075 expected_largest_payload -= 1;
9076 }
9077 if (connection_.version().UsesTls()) {
9078 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
9079 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
9080 QuicConfig config;
9081 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
9082 &config, kMaxAcceptedDatagramFrameSize);
9083 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9084 connection_.SetFromConfig(config);
9085 // Verify the value post-handshake.
9086 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
9087 expected_largest_payload);
9088 } else {
9089 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
9090 expected_largest_payload);
9091 }
9092}
9093
9094TEST_P(QuicConnectionTest, LimitedLargestMessagePayload) {
9095 if (!connection_.version().SupportsMessageFrames() ||
9096 !connection_.version().UsesTls()) {
9097 return;
9098 }
9099 constexpr QuicPacketLength kFrameSizeLimit = 1000;
9100 constexpr QuicPacketLength kPayloadSizeLimit =
9101 kFrameSizeLimit - kQuicFrameTypeSize;
9102 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
9103 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
9104 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
9105 QuicConfig config;
9106 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(&config, kFrameSizeLimit);
9107 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9108 connection_.SetFromConfig(config);
9109 // Verify the value post-handshake.
9110 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), kPayloadSizeLimit);
9111 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
9112 kPayloadSizeLimit);
9113}
9114
QUICHE teama6ef0a62019-03-07 20:34:33 -05009115// Test to check that the path challenge/path response logic works
9116// correctly. This test is only for version-99
9117TEST_P(QuicConnectionTest, PathChallengeResponse) {
fkastenholz305e1732019-06-18 05:01:22 -07009118 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009119 return;
9120 }
9121 // First check if we can probe from server to client and back
9122 set_perspective(Perspective::IS_SERVER);
9123 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
9124
9125 // Create and send the probe request (PATH_CHALLENGE frame).
9126 // SendConnectivityProbingPacket ends up calling
9127 // TestPacketWriter::WritePacket() which in turns receives and parses the
9128 // packet by calling framer_.ProcessPacket() -- which in turn calls
9129 // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
9130 // the packet in writer_->path_challenge_frames()
9131 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9132 connection_.SendConnectivityProbingPacket(writer_.get(),
9133 connection_.peer_address());
9134 // Save the random contents of the challenge for later comparison to the
9135 // response.
nharper55fa6132019-05-07 19:37:21 -07009136 ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009137 QuicPathFrameBuffer challenge_data =
9138 writer_->path_challenge_frames().front().data_buffer;
9139
9140 // Normally, QuicConnection::OnPathChallengeFrame and OnPaddingFrame would be
9141 // called and it will perform actions to ensure that the rest of the protocol
9142 // is performed (specifically, call UpdatePacketContent to say that this is a
9143 // path challenge so that when QuicConnection::OnPacketComplete is called
9144 // (again, out of the framer), the response is generated). Simulate those
9145 // calls so that the right internal state is set up for generating
9146 // the response.
9147 EXPECT_TRUE(connection_.OnPathChallengeFrame(
9148 writer_->path_challenge_frames().front()));
9149 EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
9150 // Cause the response to be created and sent. Result is that the response
9151 // should be stashed in writer's path_response_frames.
9152 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9153 connection_.SendConnectivityProbingResponsePacket(connection_.peer_address());
9154
9155 // The final check is to ensure that the random data in the response matches
9156 // the random data from the challenge.
9157 EXPECT_EQ(0, memcmp(&challenge_data,
9158 &(writer_->path_response_frames().front().data_buffer),
9159 sizeof(challenge_data)));
9160}
9161
zhongyi2da16be2020-06-17 11:05:23 -07009162TEST_P(QuicConnectionTest,
9163 RestartPathDegradingDetectionAfterMigrationWithProbe) {
9164 // TODO(b/150095484): add test coverage for IETF to verify that client takes
9165 // PATH RESPONSE with peer address change as correct validation on the new
9166 // path.
9167 if (GetParam().version.HasIetfQuicFrames()) {
9168 return;
9169 }
9170 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
dschinazi1c6e5922020-06-19 10:35:03 -07009171 PathProbeTestInit(Perspective::IS_CLIENT);
zhongyi2da16be2020-06-17 11:05:23 -07009172
9173 // Clear direct_peer_address and effective_peer_address.
9174 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
9175 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
9176 QuicSocketAddress());
9177 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
9178
9179 EXPECT_TRUE(connection_.connected());
9180 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
9181 .WillRepeatedly(Return(true));
9182 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
9183 EXPECT_FALSE(connection_.IsPathDegrading());
9184 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
9185
9186 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9187 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9188 } else {
9189 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9190 }
9191 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
9192 kPeerAddress);
9193 EXPECT_EQ(kPeerAddress, connection_.peer_address());
9194 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
9195
9196 // Send data and verify the path degrading detection is set.
9197 const char data[] = "data";
9198 size_t data_size = strlen(data);
9199 QuicStreamOffset offset = 0;
9200 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
9201 offset += data_size;
9202
9203 // Verify the path degrading detection is in progress.
9204 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
9205 EXPECT_FALSE(connection_.IsPathDegrading());
9206 QuicTime ddl = connection_.GetBlackholeDetectorAlarm()->deadline();
9207
9208 // Simulate the firing of path degrading.
9209 clock_.AdvanceTime(ddl - clock_.ApproximateNow());
9210 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
9211 connection_.PathDegradingTimeout();
9212 EXPECT_TRUE(connection_.IsPathDegrading());
9213 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
9214
9215 // Simulate path degrading handling by sending a probe on an alternet path.
9216 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
9217 TestPacketWriter probing_writer(version(), &clock_);
9218 connection_.SendConnectivityProbingPacket(&probing_writer,
9219 connection_.peer_address());
9220 // Verify that path degrading detection is not reset.
9221 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
9222
9223 // Simulate successful path degrading handling by receiving probe response.
9224 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
9225
9226 if (!GetParam().version.HasIetfQuicFrames()) {
9227 EXPECT_CALL(visitor_,
9228 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
9229 .Times(1);
9230 } else {
9231 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
9232 }
9233 const QuicSocketAddress kNewSelfAddress =
9234 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
9235
9236 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
9237 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
9238 QuicEncryptedPacket(probing_packet->encrypted_buffer,
9239 probing_packet->encrypted_length),
9240 clock_.Now()));
9241 uint64_t num_probing_received =
9242 connection_.GetStats().num_connectivity_probing_received;
9243 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
9244
9245 EXPECT_EQ(num_probing_received + 1,
9246 connection_.GetStats().num_connectivity_probing_received);
9247 EXPECT_EQ(kPeerAddress, connection_.peer_address());
9248 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
9249 EXPECT_TRUE(connection_.IsPathDegrading());
9250
9251 // Verify new path degrading detection is activated.
9252 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(1);
9253 connection_.OnSuccessfulMigrationAfterProbing();
9254 EXPECT_FALSE(connection_.IsPathDegrading());
9255 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
9256}
9257
QUICHE teama6ef0a62019-03-07 20:34:33 -05009258// Regression test for b/110259444
9259TEST_P(QuicConnectionTest, DoNotScheduleSpuriousAckAlarm) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009260 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9261 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9262 writer_->SetWriteBlocked();
9263
9264 ProcessPacket(1);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009265 // Verify ack alarm is set.
fayang9adfb532020-06-04 06:58:45 -07009266 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009267 // Fire the ack alarm, verify no packet is sent because the writer is blocked.
9268 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9269 connection_.GetAckAlarm()->Fire();
9270
9271 writer_->SetWritable();
9272 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9273 ProcessPacket(2);
9274 // Verify ack alarm is not set.
fayang9adfb532020-06-04 06:58:45 -07009275 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009276}
9277
9278TEST_P(QuicConnectionTest, DisablePacingOffloadConnectionOptions) {
9279 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
9280 writer_->set_supports_release_time(true);
9281 QuicConfig config;
9282 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9283 connection_.SetFromConfig(config);
9284 EXPECT_TRUE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
9285
9286 QuicTagVector connection_options;
9287 connection_options.push_back(kNPCO);
9288 config.SetConnectionOptionsToSend(connection_options);
9289 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9290 connection_.SetFromConfig(config);
9291 // Verify pacing offload is disabled.
9292 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
9293}
9294
9295// Regression test for b/110259444
9296// Get a path response without having issued a path challenge...
9297TEST_P(QuicConnectionTest, OrphanPathResponse) {
9298 QuicPathFrameBuffer data = {{0, 1, 2, 3, 4, 5, 6, 7}};
9299
9300 QuicPathResponseFrame frame(99, data);
9301 EXPECT_TRUE(connection_.OnPathResponseFrame(frame));
9302 // If PATH_RESPONSE was accepted (payload matches the payload saved
9303 // in QuicConnection::transmitted_connectivity_probe_payload_) then
9304 // current_packet_content_ would be set to FIRST_FRAME_IS_PING.
9305 // Since this PATH_RESPONSE does not match, current_packet_content_
9306 // must not be FIRST_FRAME_IS_PING.
9307 EXPECT_NE(QuicConnection::FIRST_FRAME_IS_PING,
9308 QuicConnectionPeer::GetCurrentPacketContent(&connection_));
9309}
9310
9311// Regression test for b/120791670
9312TEST_P(QuicConnectionTest, StopProcessingGQuicPacketInIetfQuicConnection) {
9313 // This test mimics a problematic scenario where an IETF QUIC connection
9314 // receives a Google QUIC packet and continue processing it using Google QUIC
9315 // wire format.
fayangd4291e42019-05-30 10:31:21 -07009316 if (!VersionHasIetfInvariantHeader(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009317 return;
9318 }
9319 set_perspective(Perspective::IS_SERVER);
nharper46833c32019-05-15 21:33:05 -07009320 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
nharper46833c32019-05-15 21:33:05 -07009321 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
9322 } else {
nharper46833c32019-05-15 21:33:05 -07009323 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
9324 }
wub8a5dafa2020-05-13 12:30:17 -07009325 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
9326 kPeerAddress);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009327
9328 // Let connection process a Google QUIC packet.
9329 peer_framer_.set_version_for_tests(
9330 ParsedQuicVersion(PROTOCOL_QUIC_CRYPTO, QUIC_VERSION_43));
QUICHE team8c1daa22019-03-13 08:33:41 -07009331 std::unique_ptr<QuicPacket> packet(
QUICHE team6987b4a2019-03-15 16:23:04 -07009332 ConstructDataPacket(2, !kHasStopWaiting, ENCRYPTION_INITIAL));
dschinazi66dea072019-04-09 11:41:06 -07009333 char buffer[kMaxOutgoingPacketSize];
9334 size_t encrypted_length =
9335 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(2),
9336 *packet, buffer, kMaxOutgoingPacketSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -05009337 // Make sure no stream frame is processed.
9338 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(0);
9339 connection_.ProcessUdpPacket(
9340 kSelfAddress, kPeerAddress,
9341 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
9342
9343 EXPECT_EQ(2u, connection_.GetStats().packets_received);
9344 EXPECT_EQ(1u, connection_.GetStats().packets_processed);
9345}
9346
9347TEST_P(QuicConnectionTest, AcceptPacketNumberZero) {
fkastenholz305e1732019-06-18 05:01:22 -07009348 if (!VersionHasIetfQuicFrames(version().transport_version)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -05009349 return;
9350 }
9351 // Set first_sending_packet_number to be 0 to allow successfully processing
9352 // acks which ack packet number 0.
9353 QuicFramerPeer::SetFirstSendingPacketNumber(writer_->framer()->framer(), 0);
9354 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9355
9356 ProcessPacket(0);
fayangc31c9952019-06-05 13:54:48 -07009357 EXPECT_EQ(QuicPacketNumber(0), LargestAcked(connection_.ack_frame()));
9358 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009359
9360 ProcessPacket(1);
fayangc31c9952019-06-05 13:54:48 -07009361 EXPECT_EQ(QuicPacketNumber(1), LargestAcked(connection_.ack_frame()));
9362 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009363
9364 ProcessPacket(2);
fayangc31c9952019-06-05 13:54:48 -07009365 EXPECT_EQ(QuicPacketNumber(2), LargestAcked(connection_.ack_frame()));
9366 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
QUICHE teama6ef0a62019-03-07 20:34:33 -05009367}
9368
QUICHE teamcd098022019-03-22 18:49:55 -07009369TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicSending) {
9370 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9371 return;
9372 }
9373 use_tagging_decrypter();
9374 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07009375 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07009376
9377 connection_.SendCryptoStreamData();
9378 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9379 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9380 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9381 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9382 QuicAckFrame frame1 = InitAckFrame(1);
9383 // Received ACK for packet 1.
9384 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9385
9386 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
9387 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9388 NO_FIN);
9389 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
9390 NO_FIN);
9391 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
9392 8, NO_FIN);
9393 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
9394 12, FIN);
9395 // Received ACK for packets 2, 4, 5.
9396 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9397 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9398 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9399 QuicAckFrame frame2 =
9400 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
9401 {QuicPacketNumber(4), QuicPacketNumber(6)}});
9402 // Make sure although the same packet number is used, but they are in
9403 // different packet number spaces.
9404 ProcessFramePacketAtLevel(30, QuicFrame(&frame2), ENCRYPTION_FORWARD_SECURE);
9405}
9406
9407TEST_P(QuicConnectionTest, PeerAcksPacketsInWrongPacketNumberSpace) {
9408 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9409 return;
9410 }
9411 use_tagging_decrypter();
9412 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07009413 std::make_unique<TaggingEncrypter>(0x01));
rch39c88ab2019-10-16 19:24:40 -07009414 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
9415 std::make_unique<TaggingEncrypter>(0x01));
QUICHE teamcd098022019-03-22 18:49:55 -07009416
9417 connection_.SendCryptoStreamData();
9418 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9419 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9420 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9421 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9422 QuicAckFrame frame1 = InitAckFrame(1);
9423 // Received ACK for packet 1.
9424 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9425
9426 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9427 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9428 NO_FIN);
9429 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
9430 NO_FIN);
9431
9432 // Received ACK for packets 2 and 3 in wrong packet number space.
9433 QuicAckFrame invalid_ack =
9434 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(4)}});
fkastenholz5d880a92019-06-21 09:01:56 -07009435 EXPECT_CALL(visitor_,
9436 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07009437 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
QUICHE teamcd098022019-03-22 18:49:55 -07009438 ProcessFramePacketAtLevel(300, QuicFrame(&invalid_ack), ENCRYPTION_INITIAL);
fkastenholz5d880a92019-06-21 09:01:56 -07009439 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
QUICHE teamcd098022019-03-22 18:49:55 -07009440}
9441
9442TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicReceiving) {
9443 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9444 return;
9445 }
9446 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07009447 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9448 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9449 }
QUICHE teamcd098022019-03-22 18:49:55 -07009450 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9451 use_tagging_decrypter();
9452 // Receives packet 1000 in initial data.
nharper46833c32019-05-15 21:33:05 -07009453 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
fayang9adfb532020-06-04 06:58:45 -07009454 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009455 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009456 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07009457 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009458 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009459 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07009460 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009461 // Receives packet 1000 in application data.
9462 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
fayang9adfb532020-06-04 06:58:45 -07009463 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009464 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9465 NO_FIN);
9466 // Verify application data ACK gets bundled with outgoing data.
9467 EXPECT_EQ(2u, writer_->frame_count());
9468 // Make sure ACK alarm is still set because initial data is not ACKed.
fayang9adfb532020-06-04 06:58:45 -07009469 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009470 // Receive packet 1001 in application data.
9471 ProcessDataPacketAtLevel(1001, false, ENCRYPTION_ZERO_RTT);
9472 clock_.AdvanceTime(DefaultRetransmissionTime());
9473 // Simulates ACK alarm fires and verify two ACKs are flushed.
9474 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9475 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009476 std::make_unique<TaggingEncrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009477 connection_.GetAckAlarm()->Fire();
fayang9adfb532020-06-04 06:58:45 -07009478 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009479 // Receives more packets in application data.
9480 ProcessDataPacketAtLevel(1002, false, ENCRYPTION_ZERO_RTT);
fayang9adfb532020-06-04 06:58:45 -07009481 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009482
9483 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009484 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07009485 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009486 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE teamcd098022019-03-22 18:49:55 -07009487 // Verify zero rtt and forward secure packets get acked in the same packet.
9488 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
nharper2c9f02a2019-05-08 10:25:50 -07009489 ProcessDataPacket(1003);
fayang9adfb532020-06-04 06:58:45 -07009490 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE teamcd098022019-03-22 18:49:55 -07009491}
9492
QUICHE team552f71f2019-03-23 15:37:59 -07009493TEST_P(QuicConnectionTest, CancelAckAlarmOnWriteBlocked) {
9494 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9495 return;
9496 }
9497 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
nharper46833c32019-05-15 21:33:05 -07009498 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9499 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9500 }
QUICHE team552f71f2019-03-23 15:37:59 -07009501 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9502 use_tagging_decrypter();
9503 // Receives packet 1000 in initial data.
nharper46833c32019-05-15 21:33:05 -07009504 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
fayang9adfb532020-06-04 06:58:45 -07009505 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE team552f71f2019-03-23 15:37:59 -07009506 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009507 std::make_unique<TaggingEncrypter>(0x02));
zhongyi546cc452019-04-12 15:27:49 -07009508 SetDecrypter(ENCRYPTION_ZERO_RTT,
vasilvv0fc587f2019-09-06 13:33:08 -07009509 std::make_unique<StrictTaggingDecrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07009510 connection_.SetEncrypter(ENCRYPTION_INITIAL,
vasilvv0fc587f2019-09-06 13:33:08 -07009511 std::make_unique<TaggingEncrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07009512 // Receives packet 1000 in application data.
9513 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
fayang9adfb532020-06-04 06:58:45 -07009514 EXPECT_TRUE(connection_.HasPendingAcks());
QUICHE team552f71f2019-03-23 15:37:59 -07009515
9516 writer_->SetWriteBlocked();
9517 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber());
9518 // Simulates ACK alarm fires and verify no ACK is flushed because of write
9519 // blocked.
9520 clock_.AdvanceTime(DefaultDelayedAckTime());
9521 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9522 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
vasilvv0fc587f2019-09-06 13:33:08 -07009523 std::make_unique<TaggingEncrypter>(0x02));
QUICHE team552f71f2019-03-23 15:37:59 -07009524 connection_.GetAckAlarm()->Fire();
9525 // Verify ACK alarm is not set.
fayang9adfb532020-06-04 06:58:45 -07009526 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE team552f71f2019-03-23 15:37:59 -07009527
9528 writer_->SetWritable();
9529 // Verify 2 ACKs are sent when connection gets unblocked.
9530 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9531 connection_.OnCanWrite();
fayang9adfb532020-06-04 06:58:45 -07009532 EXPECT_FALSE(connection_.HasPendingAcks());
QUICHE team552f71f2019-03-23 15:37:59 -07009533}
9534
dschinazi346b7ce2019-06-05 01:38:18 -07009535// Make sure a packet received with the right client connection ID is processed.
9536TEST_P(QuicConnectionTest, ValidClientConnectionId) {
dschinazi346b7ce2019-06-05 01:38:18 -07009537 if (!framer_.version().SupportsClientConnectionIds()) {
9538 return;
9539 }
9540 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9541 connection_.set_client_connection_id(TestConnectionId(0x33));
9542 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9543 header.destination_connection_id = TestConnectionId(0x33);
9544 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9545 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9546 QuicFrames frames;
9547 QuicPingFrame ping_frame;
9548 QuicPaddingFrame padding_frame;
9549 frames.push_back(QuicFrame(ping_frame));
9550 frames.push_back(QuicFrame(padding_frame));
9551 std::unique_ptr<QuicPacket> packet =
9552 BuildUnsizedDataPacket(&framer_, header, frames);
9553 char buffer[kMaxOutgoingPacketSize];
9554 size_t encrypted_length = peer_framer_.EncryptPayload(
9555 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9556 kMaxOutgoingPacketSize);
9557 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9558 false);
9559 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9560 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9561 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9562}
9563
9564// Make sure a packet received with a different client connection ID is dropped.
9565TEST_P(QuicConnectionTest, InvalidClientConnectionId) {
dschinazi346b7ce2019-06-05 01:38:18 -07009566 if (!framer_.version().SupportsClientConnectionIds()) {
9567 return;
9568 }
9569 connection_.set_client_connection_id(TestConnectionId(0x33));
9570 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9571 header.destination_connection_id = TestConnectionId(0xbad);
9572 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9573 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9574 QuicFrames frames;
9575 QuicPingFrame ping_frame;
9576 QuicPaddingFrame padding_frame;
9577 frames.push_back(QuicFrame(ping_frame));
9578 frames.push_back(QuicFrame(padding_frame));
9579 std::unique_ptr<QuicPacket> packet =
9580 BuildUnsizedDataPacket(&framer_, header, frames);
9581 char buffer[kMaxOutgoingPacketSize];
9582 size_t encrypted_length = peer_framer_.EncryptPayload(
9583 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9584 kMaxOutgoingPacketSize);
9585 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9586 false);
9587 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9588 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9589 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
9590}
9591
9592// Make sure the first packet received with a different client connection ID on
9593// the server is processed and it changes the client connection ID.
9594TEST_P(QuicConnectionTest, UpdateClientConnectionIdFromFirstPacket) {
dschinazi346b7ce2019-06-05 01:38:18 -07009595 if (!framer_.version().SupportsClientConnectionIds()) {
9596 return;
9597 }
dschinazi346b7ce2019-06-05 01:38:18 -07009598 set_perspective(Perspective::IS_SERVER);
9599 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL);
9600 header.source_connection_id = TestConnectionId(0x33);
9601 header.source_connection_id_included = CONNECTION_ID_PRESENT;
9602 QuicFrames frames;
9603 QuicPingFrame ping_frame;
9604 QuicPaddingFrame padding_frame;
9605 frames.push_back(QuicFrame(ping_frame));
9606 frames.push_back(QuicFrame(padding_frame));
9607 std::unique_ptr<QuicPacket> packet =
9608 BuildUnsizedDataPacket(&framer_, header, frames);
9609 char buffer[kMaxOutgoingPacketSize];
nharperc6b99512019-09-19 11:13:48 -07009610 size_t encrypted_length =
9611 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1),
9612 *packet, buffer, kMaxOutgoingPacketSize);
dschinazi346b7ce2019-06-05 01:38:18 -07009613 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9614 false);
9615 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9616 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9617 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9618 EXPECT_EQ(TestConnectionId(0x33), connection_.client_connection_id());
9619}
9620
fayang40ec3ac2019-06-05 09:07:54 -07009621// Regression test for b/134416344.
9622TEST_P(QuicConnectionTest, CheckConnectedBeforeFlush) {
9623 // This test mimics a scenario where a connection processes 2 packets and the
9624 // 2nd packet contains connection close frame. When the 2nd flusher goes out
9625 // of scope, a delayed ACK is pending, and ACK alarm should not be scheduled
9626 // because connection is disconnected.
9627 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
fkastenholz5d880a92019-06-21 09:01:56 -07009628 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
fayang40ec3ac2019-06-05 09:07:54 -07009629 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
fkastenholz88d08f42019-09-06 07:38:04 -07009630 const QuicErrorCode kErrorCode = QUIC_INTERNAL_ERROR;
fayang40ec3ac2019-06-05 09:07:54 -07009631 std::unique_ptr<QuicConnectionCloseFrame> connection_close_frame(
fkastenholz591814c2019-09-06 12:11:46 -07009632 new QuicConnectionCloseFrame(connection_.transport_version(), kErrorCode,
9633 "",
9634 /*transport_close_frame_type=*/0));
9635
fayang40ec3ac2019-06-05 09:07:54 -07009636 // Received 2 packets.
fayang40ec3ac2019-06-05 09:07:54 -07009637 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
fayang40ec3ac2019-06-05 09:07:54 -07009638 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9639 } else {
fayang40ec3ac2019-06-05 09:07:54 -07009640 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9641 }
wub8a5dafa2020-05-13 12:30:17 -07009642 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
9643 kPeerAddress);
fayang9adfb532020-06-04 06:58:45 -07009644 EXPECT_TRUE(connection_.HasPendingAcks());
wub8a5dafa2020-05-13 12:30:17 -07009645 ProcessFramePacketWithAddresses(QuicFrame(connection_close_frame.release()),
fayang40ec3ac2019-06-05 09:07:54 -07009646 kSelfAddress, kPeerAddress);
fayang0f0c4e62019-07-16 08:55:54 -07009647 // Verify ack alarm is not set.
fayang9adfb532020-06-04 06:58:45 -07009648 EXPECT_FALSE(connection_.HasPendingAcks());
fayang40ec3ac2019-06-05 09:07:54 -07009649}
9650
dschinazi8d551132019-08-02 19:17:16 -07009651// Verify that a packet containing three coalesced packets is parsed correctly.
9652TEST_P(QuicConnectionTest, CoalescedPacket) {
9653 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9654 // Coalesced packets can only be encoded using long header lengths.
9655 return;
9656 }
9657 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9658 EXPECT_TRUE(connection_.connected());
9659 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9660 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
9661 } else {
9662 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
9663 }
9664
9665 uint64_t packet_numbers[3] = {1, 2, 3};
9666 EncryptionLevel encryption_levels[3] = {
9667 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9668 char buffer[kMaxOutgoingPacketSize] = {};
9669 size_t total_encrypted_length = 0;
9670 for (int i = 0; i < 3; i++) {
9671 QuicPacketHeader header =
9672 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9673 QuicFrames frames;
9674 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9675 frames.push_back(QuicFrame(&crypto_frame_));
9676 } else {
9677 frames.push_back(QuicFrame(frame1_));
9678 }
9679 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9680 peer_creator_.set_encryption_level(encryption_levels[i]);
9681 size_t encrypted_length = peer_framer_.EncryptPayload(
9682 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9683 buffer + total_encrypted_length,
9684 sizeof(buffer) - total_encrypted_length);
9685 EXPECT_GT(encrypted_length, 0u);
9686 total_encrypted_length += encrypted_length;
9687 }
9688 connection_.ProcessUdpPacket(
9689 kSelfAddress, kPeerAddress,
9690 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9691 if (connection_.GetSendAlarm()->IsSet()) {
9692 connection_.GetSendAlarm()->Fire();
9693 }
9694
9695 EXPECT_TRUE(connection_.connected());
9696}
9697
dschinazi66fc0242019-08-16 10:00:25 -07009698// Regression test for crbug.com/992831.
9699TEST_P(QuicConnectionTest, CoalescedPacketThatSavesFrames) {
9700 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9701 // Coalesced packets can only be encoded using long header lengths.
9702 return;
9703 }
9704 if (connection_.SupportsMultiplePacketNumberSpaces()) {
9705 // TODO(b/129151114) Enable this test with multiple packet number spaces.
9706 return;
9707 }
9708 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9709 EXPECT_TRUE(connection_.connected());
9710 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9711 EXPECT_CALL(visitor_, OnCryptoFrame(_))
9712 .Times(3)
9713 .WillRepeatedly([this](const QuicCryptoFrame& /*frame*/) {
9714 // QuicFrame takes ownership of the QuicBlockedFrame.
9715 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
9716 });
9717 } else {
9718 EXPECT_CALL(visitor_, OnStreamFrame(_))
9719 .Times(3)
9720 .WillRepeatedly([this](const QuicStreamFrame& /*frame*/) {
9721 // QuicFrame takes ownership of the QuicBlockedFrame.
9722 connection_.SendControlFrame(QuicFrame(new QuicBlockedFrame(1, 3)));
9723 });
9724 }
9725
9726 uint64_t packet_numbers[3] = {1, 2, 3};
9727 EncryptionLevel encryption_levels[3] = {
9728 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9729 char buffer[kMaxOutgoingPacketSize] = {};
9730 size_t total_encrypted_length = 0;
9731 for (int i = 0; i < 3; i++) {
9732 QuicPacketHeader header =
9733 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9734 QuicFrames frames;
9735 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9736 frames.push_back(QuicFrame(&crypto_frame_));
9737 } else {
9738 frames.push_back(QuicFrame(frame1_));
9739 }
9740 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9741 peer_creator_.set_encryption_level(encryption_levels[i]);
9742 size_t encrypted_length = peer_framer_.EncryptPayload(
9743 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9744 buffer + total_encrypted_length,
9745 sizeof(buffer) - total_encrypted_length);
9746 EXPECT_GT(encrypted_length, 0u);
9747 total_encrypted_length += encrypted_length;
9748 }
9749 connection_.ProcessUdpPacket(
9750 kSelfAddress, kPeerAddress,
9751 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9752 if (connection_.GetSendAlarm()->IsSet()) {
9753 connection_.GetSendAlarm()->Fire();
9754 }
9755
9756 EXPECT_TRUE(connection_.connected());
9757
9758 SendAckPacketToPeer();
9759}
9760
fayangd3016832019-08-08 07:24:45 -07009761// Regresstion test for b/138962304.
9762TEST_P(QuicConnectionTest, RtoAndWriteBlocked) {
fayangd3016832019-08-08 07:24:45 -07009763 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9764
9765 QuicStreamId stream_id = 2;
9766 QuicPacketNumber last_data_packet;
9767 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9768 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9769
9770 // Writer gets blocked.
9771 writer_->SetWriteBlocked();
9772
9773 // Cancel the stream.
9774 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9775 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
fayang67f82272019-08-14 16:08:45 -07009776 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
9777 .WillRepeatedly(
9778 Invoke(&notifier_, &SimpleSessionNotifier::WillingToWrite));
fayangd3016832019-08-08 07:24:45 -07009779 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9780
9781 // Retransmission timer fires in RTO mode.
9782 connection_.GetRetransmissionAlarm()->Fire();
9783 // Verify no packets get flushed when writer is blocked.
9784 EXPECT_EQ(0u, connection_.NumQueuedPackets());
9785}
9786
9787// Regresstion test for b/138962304.
9788TEST_P(QuicConnectionTest, TlpAndWriteBlocked) {
fayangd3016832019-08-08 07:24:45 -07009789 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9790 connection_.SetMaxTailLossProbes(1);
9791
9792 QuicStreamId stream_id = 2;
9793 QuicPacketNumber last_data_packet;
9794 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9795 SendStreamDataToPeer(4, "foo", 0, NO_FIN, &last_data_packet);
9796 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9797
9798 // Writer gets blocked.
9799 writer_->SetWriteBlocked();
9800
9801 // Cancel stream 2.
9802 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9803 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9804 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9805
fayange62e63c2019-12-04 07:16:25 -08009806 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayangd3016832019-08-08 07:24:45 -07009807 // Retransmission timer fires in TLP mode.
9808 connection_.GetRetransmissionAlarm()->Fire();
9809 // Verify one packets is forced flushed when writer is blocked.
9810 EXPECT_EQ(1u, connection_.NumQueuedPackets());
9811}
9812
fayang67f82272019-08-14 16:08:45 -07009813// Regresstion test for b/139375344.
9814TEST_P(QuicConnectionTest, RtoForcesSendingPing) {
fayangcff885a2019-10-22 07:39:04 -07009815 if (connection_.PtoEnabled()) {
fayang67f82272019-08-14 16:08:45 -07009816 return;
9817 }
9818 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9819 connection_.SetMaxTailLossProbes(2);
9820 EXPECT_EQ(0u, connection_.GetStats().tlp_count);
9821 EXPECT_EQ(0u, connection_.GetStats().rto_count);
9822
9823 SendStreamDataToPeer(2, "foo", 0, NO_FIN, nullptr);
9824 QuicTime retransmission_time =
9825 connection_.GetRetransmissionAlarm()->deadline();
9826 EXPECT_NE(QuicTime::Zero(), retransmission_time);
9827 // TLP fires.
9828 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2), _, _));
9829 clock_.AdvanceTime(retransmission_time - clock_.Now());
9830 connection_.GetRetransmissionAlarm()->Fire();
9831 EXPECT_EQ(1u, connection_.GetStats().tlp_count);
9832 EXPECT_EQ(0u, connection_.GetStats().rto_count);
9833 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9834
9835 // Packet 1 gets acked.
9836 QuicAckFrame frame = InitAckFrame(1);
9837 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
9838 ProcessAckPacket(1, &frame);
9839 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9840 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
9841
9842 // RTO fires, verify a PING packet gets sent because there is no data to send.
9843 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
9844 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
9845 clock_.AdvanceTime(retransmission_time - clock_.Now());
9846 connection_.GetRetransmissionAlarm()->Fire();
9847 EXPECT_EQ(1u, connection_.GetStats().tlp_count);
9848 EXPECT_EQ(1u, connection_.GetStats().rto_count);
9849 EXPECT_EQ(1u, writer_->ping_frames().size());
9850}
9851
fayangce0a3162019-08-15 09:05:36 -07009852TEST_P(QuicConnectionTest, ProbeTimeout) {
fayangce0a3162019-08-15 09:05:36 -07009853 QuicConfig config;
9854 QuicTagVector connection_options;
9855 connection_options.push_back(k2PTO);
9856 config.SetConnectionOptionsToSend(connection_options);
9857 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9858 connection_.SetFromConfig(config);
9859 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9860
9861 QuicStreamId stream_id = 2;
9862 QuicPacketNumber last_packet;
9863 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
9864 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
9865 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9866
9867 // Reset stream.
9868 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9869 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9870
9871 // Fire the PTO and verify only the RST_STREAM is resent, not stream data.
9872 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9873 connection_.GetRetransmissionAlarm()->Fire();
9874 EXPECT_EQ(0u, writer_->stream_frames().size());
9875 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
9876 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9877}
9878
fayang97ce41e2019-10-07 08:37:29 -07009879TEST_P(QuicConnectionTest, CloseConnectionAfter6ClientPTOs) {
fayang97ce41e2019-10-07 08:37:29 -07009880 QuicConfig config;
9881 QuicTagVector connection_options;
9882 connection_options.push_back(k1PTO);
9883 connection_options.push_back(k6PTO);
9884 config.SetConnectionOptionsToSend(connection_options);
dschinazif7c6a912020-05-05 11:39:53 -07009885 QuicConfigPeer::SetNegotiated(&config, true);
dschinazie7c38a52020-05-29 15:25:45 -07009886 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
9887 QuicConfigPeer::SetReceivedOriginalConnectionId(
9888 &config, connection_.connection_id());
9889 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9890 &config, connection_.connection_id());
9891 }
fayang97ce41e2019-10-07 08:37:29 -07009892 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9893 connection_.SetFromConfig(config);
fayang656cbb52020-06-09 13:29:35 -07009894 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangaa4f3f22020-06-05 16:22:00 -07009895 EXPECT_CALL(visitor_, GetHandshakeState())
9896 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
9897 }
fayang97ce41e2019-10-07 08:37:29 -07009898 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9899
9900 // Send stream data.
9901 SendStreamDataToPeer(
9902 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9903 0, FIN, nullptr);
9904
fayang97ce41e2019-10-07 08:37:29 -07009905 // Fire the retransmission alarm 5 times.
9906 for (int i = 0; i < 5; ++i) {
ianswett825b48b2020-05-11 06:25:04 -07009907 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
fayang97ce41e2019-10-07 08:37:29 -07009908 connection_.GetRetransmissionAlarm()->Fire();
9909 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9910 EXPECT_TRUE(connection_.connected());
9911 }
fayang2205d952020-05-12 13:45:56 -07009912 EXPECT_CALL(visitor_, OnPathDegrading());
9913 connection_.PathDegradingTimeout();
fayang97ce41e2019-10-07 08:37:29 -07009914
9915 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
9916 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
9917 EXPECT_EQ(5u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9918 // Closes connection on 6th PTO.
ianswett825b48b2020-05-11 06:25:04 -07009919 // May send multiple connecction close packets with multiple PN spaces.
9920 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayang97ce41e2019-10-07 08:37:29 -07009921 EXPECT_CALL(visitor_,
9922 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
fayang2205d952020-05-12 13:45:56 -07009923 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9924 connection_.GetBlackholeDetectorAlarm()->Fire();
fayang97ce41e2019-10-07 08:37:29 -07009925 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9926 EXPECT_FALSE(connection_.connected());
9927 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9928}
9929
fayangce0a3162019-08-15 09:05:36 -07009930TEST_P(QuicConnectionTest, CloseConnectionAfter7ClientPTOs) {
fayangce0a3162019-08-15 09:05:36 -07009931 QuicConfig config;
9932 QuicTagVector connection_options;
9933 connection_options.push_back(k2PTO);
9934 connection_options.push_back(k7PTO);
9935 config.SetConnectionOptionsToSend(connection_options);
dschinazif7c6a912020-05-05 11:39:53 -07009936 QuicConfigPeer::SetNegotiated(&config, true);
dschinazie7c38a52020-05-29 15:25:45 -07009937 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
9938 QuicConfigPeer::SetReceivedOriginalConnectionId(
9939 &config, connection_.connection_id());
9940 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9941 &config, connection_.connection_id());
9942 }
fayangce0a3162019-08-15 09:05:36 -07009943 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9944 connection_.SetFromConfig(config);
fayang656cbb52020-06-09 13:29:35 -07009945 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangaa4f3f22020-06-05 16:22:00 -07009946 EXPECT_CALL(visitor_, GetHandshakeState())
9947 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
9948 }
fayangce0a3162019-08-15 09:05:36 -07009949 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9950
9951 // Send stream data.
9952 SendStreamDataToPeer(
9953 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9954 0, FIN, nullptr);
9955
9956 // Fire the retransmission alarm 6 times.
9957 for (int i = 0; i < 6; ++i) {
9958 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9959 connection_.GetRetransmissionAlarm()->Fire();
9960 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9961 EXPECT_TRUE(connection_.connected());
9962 }
fayang2205d952020-05-12 13:45:56 -07009963 EXPECT_CALL(visitor_, OnPathDegrading());
9964 connection_.PathDegradingTimeout();
fayangce0a3162019-08-15 09:05:36 -07009965
9966 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
9967 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
9968 EXPECT_EQ(6u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9969 // Closes connection on 7th PTO.
9970 EXPECT_CALL(visitor_,
9971 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -07009972 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayang2205d952020-05-12 13:45:56 -07009973 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9974 connection_.GetBlackholeDetectorAlarm()->Fire();
fayangce0a3162019-08-15 09:05:36 -07009975 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9976 EXPECT_FALSE(connection_.connected());
9977 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9978}
9979
9980TEST_P(QuicConnectionTest, CloseConnectionAfter8ClientPTOs) {
fayangce0a3162019-08-15 09:05:36 -07009981 QuicConfig config;
9982 QuicTagVector connection_options;
9983 connection_options.push_back(k2PTO);
9984 connection_options.push_back(k8PTO);
dschinazif7c6a912020-05-05 11:39:53 -07009985 QuicConfigPeer::SetNegotiated(&config, true);
dschinazie7c38a52020-05-29 15:25:45 -07009986 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
9987 QuicConfigPeer::SetReceivedOriginalConnectionId(
9988 &config, connection_.connection_id());
9989 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9990 &config, connection_.connection_id());
9991 }
fayangce0a3162019-08-15 09:05:36 -07009992 config.SetConnectionOptionsToSend(connection_options);
9993 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9994 connection_.SetFromConfig(config);
fayang656cbb52020-06-09 13:29:35 -07009995 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangaa4f3f22020-06-05 16:22:00 -07009996 EXPECT_CALL(visitor_, GetHandshakeState())
9997 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
9998 }
fayangce0a3162019-08-15 09:05:36 -07009999 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10000
10001 // Send stream data.
10002 SendStreamDataToPeer(
10003 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10004 0, FIN, nullptr);
10005
10006 // Fire the retransmission alarm 7 times.
10007 for (int i = 0; i < 7; ++i) {
10008 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
10009 connection_.GetRetransmissionAlarm()->Fire();
10010 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
10011 EXPECT_TRUE(connection_.connected());
10012 }
fayang2205d952020-05-12 13:45:56 -070010013 EXPECT_CALL(visitor_, OnPathDegrading());
10014 connection_.PathDegradingTimeout();
fayangce0a3162019-08-15 09:05:36 -070010015
10016 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveTlpCount());
10017 EXPECT_EQ(0u, connection_.sent_packet_manager().GetConsecutiveRtoCount());
10018 EXPECT_EQ(7u, connection_.sent_packet_manager().GetConsecutivePtoCount());
10019 // Closes connection on 8th PTO.
10020 EXPECT_CALL(visitor_,
10021 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
rch39c88ab2019-10-16 19:24:40 -070010022 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
fayang2205d952020-05-12 13:45:56 -070010023 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
10024 connection_.GetBlackholeDetectorAlarm()->Fire();
fayangce0a3162019-08-15 09:05:36 -070010025 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
10026 EXPECT_FALSE(connection_.connected());
10027 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
10028}
10029
fayang5f135052019-08-22 17:59:40 -070010030TEST_P(QuicConnectionTest, DeprecateHandshakeMode) {
10031 if (!connection_.version().SupportsAntiAmplificationLimit()) {
10032 return;
10033 }
10034 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10035 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10036
10037 // Send CHLO.
10038 connection_.SendCryptoStreamData();
10039 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10040
10041 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
10042 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
10043 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10044 QuicAckFrame frame1 = InitAckFrame(1);
10045 // Received ACK for packet 1.
10046 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
10047
10048 // Verify retransmission alarm is still set because handshake is not
10049 // confirmed although there is nothing in flight.
10050 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10051 EXPECT_EQ(0u, connection_.GetStats().pto_count);
10052 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
10053
10054 // PTO fires, verify a PING packet gets sent because there is no data to send.
fayang5d011982020-05-13 14:14:38 -070010055 EXPECT_CALL(*send_algorithm_,
10056 OnPacketSent(_, _,
10057 GetQuicReloadableFlag(quic_default_on_pto)
10058 ? QuicPacketNumber(2)
10059 : QuicPacketNumber(3),
10060 _, _));
fayang5f135052019-08-22 17:59:40 -070010061 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
10062 connection_.GetRetransmissionAlarm()->Fire();
10063 EXPECT_EQ(1u, connection_.GetStats().pto_count);
fayangaf9903b2020-05-14 14:34:28 -070010064 EXPECT_EQ(1u, connection_.GetStats().crypto_retransmit_count);
fayang5f135052019-08-22 17:59:40 -070010065 EXPECT_EQ(1u, writer_->ping_frames().size());
10066}
10067
10068TEST_P(QuicConnectionTest, AntiAmplificationLimit) {
10069 if (!connection_.version().SupportsAntiAmplificationLimit()) {
10070 return;
10071 }
fayang5f135052019-08-22 17:59:40 -070010072 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10073
10074 set_perspective(Perspective::IS_SERVER);
10075 // Verify no data can be sent at the beginning because bytes received is 0.
10076 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10077 connection_.SendCryptoDataWithString("foo", 0);
fayang60d9c042020-07-06 08:42:40 -070010078 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
10079 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
fayang5f135052019-08-22 17:59:40 -070010080 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10081
10082 // Receives packet 1.
10083 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
10084
10085 const size_t anti_amplification_factor =
fayang60d9c042020-07-06 08:42:40 -070010086 GetQuicFlag(FLAGS_quic_anti_amplification_factor);
fayang5f135052019-08-22 17:59:40 -070010087 // Verify now packets can be sent.
10088 for (size_t i = 0; i < anti_amplification_factor; ++i) {
10089 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10090 connection_.SendCryptoDataWithString("foo", i * 3);
10091 // Verify retransmission alarm is not set if throttled by anti-amplification
10092 // limit.
10093 EXPECT_EQ(i != anti_amplification_factor - 1,
10094 connection_.GetRetransmissionAlarm()->IsSet());
10095 }
10096 // Verify server is throttled by anti-amplification limit.
10097 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10098 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
10099
10100 // Receives packet 2.
10101 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
10102 // Verify more packets can be sent.
10103 for (size_t i = anti_amplification_factor; i < anti_amplification_factor * 2;
10104 ++i) {
10105 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10106 connection_.SendCryptoDataWithString("foo", i * 3);
10107 }
10108 // Verify server is throttled by anti-amplification limit.
10109 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10110 connection_.SendCryptoDataWithString("foo",
10111 2 * anti_amplification_factor * 3);
10112
10113 ProcessPacket(3);
10114 // Verify anti-amplification limit is gone after address validation.
10115 for (size_t i = 0; i < 100; ++i) {
10116 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10117 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
10118 }
10119}
10120
fayang6a258412020-05-28 08:57:12 -070010121TEST_P(QuicConnectionTest, AckPendingWithAmplificationLimited) {
fayang60d9c042020-07-06 08:42:40 -070010122 if (!connection_.version().SupportsAntiAmplificationLimit()) {
fayang6a258412020-05-28 08:57:12 -070010123 return;
10124 }
10125 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10126 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
10127 set_perspective(Perspective::IS_SERVER);
10128 use_tagging_decrypter();
10129 connection_.SetEncrypter(ENCRYPTION_INITIAL,
10130 std::make_unique<TaggingEncrypter>(0x01));
10131 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10132 // Receives packet 1.
10133 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
10134 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10135 std::make_unique<TaggingEncrypter>(0x02));
10136 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
fayang9adfb532020-06-04 06:58:45 -070010137 EXPECT_TRUE(connection_.HasPendingAcks());
fayang6a258412020-05-28 08:57:12 -070010138 // Send response in different encryption level and cause amplification factor
10139 // throttled.
10140 size_t i = 0;
10141 while (connection_.CanWrite(HAS_RETRANSMITTABLE_DATA)) {
10142 connection_.SendCryptoDataWithString(std::string(1024, 'a'), i * 1024,
10143 ENCRYPTION_HANDSHAKE);
10144 ++i;
10145 }
10146 // Verify ACK is still pending.
fayang9adfb532020-06-04 06:58:45 -070010147 EXPECT_TRUE(connection_.HasPendingAcks());
fayang6a258412020-05-28 08:57:12 -070010148
10149 // Fire ACK alarm and verify ACK cannot be sent due to amplification factor.
10150 clock_.AdvanceTime(connection_.GetAckAlarm()->deadline() - clock_.Now());
10151 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10152 connection_.GetAckAlarm()->Fire();
10153 // Verify ACK alarm is cancelled.
fayang9adfb532020-06-04 06:58:45 -070010154 EXPECT_FALSE(connection_.HasPendingAcks());
fayang6a258412020-05-28 08:57:12 -070010155
10156 // Receives packet 2 and verify ACK gets flushed.
10157 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10158 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
10159 EXPECT_FALSE(writer_->ack_frames().empty());
10160}
10161
fkastenholza3660102019-08-28 05:19:24 -070010162TEST_P(QuicConnectionTest, ConnectionCloseFrameType) {
10163 if (!VersionHasIetfQuicFrames(version().transport_version)) {
10164 // Test relevent only for IETF QUIC.
10165 return;
10166 }
10167 const QuicErrorCode kQuicErrorCode = IETF_QUIC_PROTOCOL_VIOLATION;
10168 // Use the (unknown) frame type of 9999 to avoid triggering any logic
10169 // which might be associated with the processing of a known frame type.
10170 const uint64_t kTransportCloseFrameType = 9999u;
10171 QuicFramerPeer::set_current_received_frame_type(
10172 QuicConnectionPeer::GetFramer(&connection_), kTransportCloseFrameType);
10173 // Do a transport connection close
10174 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10175 connection_.CloseConnection(
10176 kQuicErrorCode, "Some random error message",
10177 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10178 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
10179 writer_->connection_close_frames();
10180 ASSERT_EQ(1u, connection_close_frames.size());
10181 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
10182 connection_close_frames[0].close_type);
bnc77e77b82020-04-05 10:36:49 -070010183 EXPECT_EQ(kQuicErrorCode, connection_close_frames[0].quic_error_code);
fkastenholza3660102019-08-28 05:19:24 -070010184 EXPECT_EQ(kTransportCloseFrameType,
10185 connection_close_frames[0].transport_close_frame_type);
10186}
10187
fayang0fcbf352019-08-30 11:15:58 -070010188// Regression test for b/137401387 and b/138962304.
10189TEST_P(QuicConnectionTest, RtoPacketAsTwo) {
fayangcff885a2019-10-22 07:39:04 -070010190 if (connection_.PtoEnabled()) {
fayang0fcbf352019-08-30 11:15:58 -070010191 return;
10192 }
10193 connection_.SetMaxTailLossProbes(1);
10194 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10195 std::string stream_data(3000, 's');
10196 // Send packets 1 - 66 and exhaust cwnd.
10197 for (size_t i = 0; i < 22; ++i) {
10198 // 3 packets for each stream, the first 2 are guaranteed to be full packets.
10199 SendStreamDataToPeer(i + 2, stream_data, 0, FIN, nullptr);
10200 }
10201 CongestionBlockWrites();
10202
10203 // Fires TLP. Please note, this tail loss probe has 1 byte less stream data
10204 // compared to packet 1 because packet number length increases.
10205 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(67), _, _));
10206 connection_.GetRetransmissionAlarm()->Fire();
10207 // Fires RTO. Please note, although packets 2 and 3 *should* be RTOed, but
10208 // packet 2 gets RTOed to two packets because packet number length increases.
10209 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(68), _, _));
10210 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(69), _, _));
10211 connection_.GetRetransmissionAlarm()->Fire();
10212
10213 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10214 // Resets all streams except 2 and ack packets 1 and 2. Now, packet 3 is the
10215 // only one containing retransmittable frames.
10216 for (size_t i = 1; i < 22; ++i) {
10217 notifier_.OnStreamReset(i + 2, QUIC_STREAM_CANCELLED);
10218 }
10219 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
10220 QuicAckFrame frame =
10221 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(3)}});
10222 ProcessAckPacket(1, &frame);
10223 CongestionUnblockWrites();
10224
10225 // Fires TLP, verify a PING gets sent because packet 3 is marked
10226 // RTO_RETRANSMITTED.
10227 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(70), _, _));
10228 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
10229 connection_.GetRetransmissionAlarm()->Fire();
10230}
10231
fayang4c1c2362019-09-13 07:20:01 -070010232TEST_P(QuicConnectionTest, PtoSkipsPacketNumber) {
fayang4c1c2362019-09-13 07:20:01 -070010233 QuicConfig config;
10234 QuicTagVector connection_options;
10235 connection_options.push_back(k1PTO);
10236 connection_options.push_back(kPTOS);
10237 config.SetConnectionOptionsToSend(connection_options);
10238 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10239 connection_.SetFromConfig(config);
10240 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10241
10242 QuicStreamId stream_id = 2;
10243 QuicPacketNumber last_packet;
10244 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
10245 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
10246 EXPECT_EQ(QuicPacketNumber(2), last_packet);
10247 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10248
10249 // Fire PTO and verify the PTO retransmission skips one packet number.
10250 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10251 connection_.GetRetransmissionAlarm()->Fire();
10252 EXPECT_EQ(1u, writer_->stream_frames().size());
10253 EXPECT_EQ(QuicPacketNumber(4), writer_->last_packet_header().packet_number);
10254 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10255}
10256
fayang58f71072019-11-05 08:47:02 -080010257TEST_P(QuicConnectionTest, SendCoalescedPackets) {
10258 if (!connection_.version().CanSendCoalescedPackets()) {
10259 return;
10260 }
fayang6100ab72020-03-18 13:16:25 -070010261 MockQuicConnectionDebugVisitor debug_visitor;
10262 connection_.set_debug_visitor(&debug_visitor);
10263 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(3);
10264 EXPECT_CALL(debug_visitor, OnCoalescedPacketSent(_, _)).Times(1);
fayang44ae4e92020-04-28 13:09:42 -070010265 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang58f71072019-11-05 08:47:02 -080010266 {
10267 QuicConnection::ScopedPacketFlusher flusher(&connection_);
10268 use_tagging_decrypter();
10269 connection_.SetEncrypter(ENCRYPTION_INITIAL,
10270 std::make_unique<TaggingEncrypter>(0x01));
10271 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10272 connection_.SendCryptoDataWithString("foo", 0);
10273 // Verify this packet is on hold.
10274 EXPECT_EQ(0u, writer_->packets_write_attempts());
10275
10276 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10277 std::make_unique<TaggingEncrypter>(0x02));
10278 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10279 connection_.SendCryptoDataWithString("bar", 3);
10280 EXPECT_EQ(0u, writer_->packets_write_attempts());
10281
10282 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10283 std::make_unique<TaggingEncrypter>(0x03));
10284 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10285 SendStreamDataToPeer(2, "baz", 3, NO_FIN, nullptr);
10286 }
10287 // Verify all 3 packets are coalesced in the same UDP datagram.
10288 EXPECT_EQ(1u, writer_->packets_write_attempts());
10289 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
10290 // Verify the packet is padded to full.
10291 EXPECT_EQ(connection_.max_packet_length(), writer_->last_packet_size());
10292
10293 // Verify packet process.
10294 EXPECT_EQ(1u, writer_->crypto_frames().size());
10295 EXPECT_EQ(0u, writer_->stream_frames().size());
10296 // Verify there is coalesced packet.
10297 EXPECT_NE(nullptr, writer_->coalesced_packet());
10298}
10299
dschinazi6458eb32020-06-23 12:38:41 -070010300TEST_P(QuicConnectionTest, LegacyVersionEncapsulation) {
10301 connection_.EnableLegacyVersionEncapsulation("test.example.org");
10302
10303 MockQuicConnectionDebugVisitor debug_visitor;
10304 connection_.set_debug_visitor(&debug_visitor);
10305 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _)).Times(1);
10306
10307 // Our TestPacketWriter normally parses the sent packet using the version
10308 // from the connection, so here we need to tell it to use the encapsulation
10309 // version, and reset the initial decrypter for that version.
10310 writer_->framer()->SetSupportedVersions(
10311 SupportedVersions(LegacyVersionForEncapsulation()));
10312 writer_->framer()->framer()->SetInitialObfuscators(
10313 connection_.connection_id());
10314
10315 {
10316 QuicConnection::ScopedPacketFlusher flusher(&connection_);
10317 connection_.SendCryptoDataWithString("TEST_CRYPTO_DATA", /*offset=*/0);
10318 }
10319
10320 EXPECT_EQ(1u, writer_->packets_write_attempts());
10321 // Verify that the packet is fully padded.
10322 EXPECT_EQ(connection_.max_packet_length(), writer_->last_packet_size());
10323
10324 // Check that the connection stats show Legacy Version Encapsulation was used.
10325 EXPECT_GT(connection_.GetStats().sent_legacy_version_encapsulated_packets,
10326 0u);
10327
10328 // Verify that the sent packet was in fact encapsulated, and check header.
10329 const QuicPacketHeader& encapsulated_header = writer_->last_packet_header();
10330 EXPECT_TRUE(encapsulated_header.version_flag);
10331 EXPECT_EQ(encapsulated_header.version, LegacyVersionForEncapsulation());
10332 EXPECT_EQ(encapsulated_header.destination_connection_id,
10333 connection_.connection_id());
10334
10335 // Encapsulated packet should contain a stream frame for the crypto stream,
10336 // optionally padding, and nothing else.
10337 EXPECT_EQ(0u, writer_->crypto_frames().size());
10338 EXPECT_EQ(1u, writer_->stream_frames().size());
10339 EXPECT_EQ(writer_->frame_count(), writer_->framer()->padding_frames().size() +
10340 writer_->stream_frames().size());
10341}
10342
fayang01062942020-01-22 07:23:23 -080010343TEST_P(QuicConnectionTest, ClientReceivedHandshakeDone) {
10344 if (!connection_.version().HasHandshakeDone()) {
10345 return;
10346 }
10347 EXPECT_CALL(visitor_, OnHandshakeDoneReceived());
10348 QuicFrames frames;
10349 frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
10350 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10351 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10352}
10353
10354TEST_P(QuicConnectionTest, ServerReceivedHandshakeDone) {
10355 if (!connection_.version().HasHandshakeDone()) {
10356 return;
10357 }
10358 set_perspective(Perspective::IS_SERVER);
10359 EXPECT_CALL(visitor_, OnHandshakeDoneReceived()).Times(0);
10360 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10361 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
10362 QuicFrames frames;
10363 frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
10364 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10365 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10366 EXPECT_EQ(1, connection_close_frame_count_);
10367 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
10368 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
10369}
10370
fayang18ff23b2020-01-28 09:19:00 -080010371TEST_P(QuicConnectionTest, MultiplePacketNumberSpacePto) {
10372 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10373 return;
10374 }
10375 use_tagging_decrypter();
10376 // Send handshake packet.
10377 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10378 std::make_unique<TaggingEncrypter>(0x02));
10379 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
fayang44ae4e92020-04-28 13:09:42 -070010380 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang18ff23b2020-01-28 09:19:00 -080010381 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10382 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
10383
10384 // Send application data.
10385 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
10386 0, NO_FIN);
10387 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
10388 QuicTime retransmission_time =
10389 connection_.GetRetransmissionAlarm()->deadline();
10390 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10391
10392 // Retransmit handshake data.
10393 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayang5d011982020-05-13 14:14:38 -070010394 EXPECT_CALL(*send_algorithm_,
10395 OnPacketSent(_, _,
10396 GetQuicReloadableFlag(quic_default_on_pto)
10397 ? QuicPacketNumber(3)
10398 : QuicPacketNumber(4),
10399 _, _));
fayang44ae4e92020-04-28 13:09:42 -070010400 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang18ff23b2020-01-28 09:19:00 -080010401 connection_.GetRetransmissionAlarm()->Fire();
fayangfe963c52020-07-16 06:56:09 -070010402 if (GetQuicReloadableFlag(quic_coalesced_packet_of_higher_space)) {
10403 // Verify 1-RTT packet gets coalesced with handshake retransmission.
10404 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
10405 } else {
10406 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
10407 }
fayang18ff23b2020-01-28 09:19:00 -080010408
10409 // Send application data.
10410 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
10411 4, NO_FIN);
10412 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
10413 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
10414 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10415
10416 // Retransmit handshake data again.
10417 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayangfe963c52020-07-16 06:56:09 -070010418 QuicPacketNumber handshake_retransmission =
10419 GetQuicReloadableFlag(quic_default_on_pto) ? QuicPacketNumber(5)
10420 : QuicPacketNumber(7);
10421 if (GetQuicReloadableFlag(quic_coalesced_packet_of_higher_space)) {
10422 handshake_retransmission += 1;
10423 EXPECT_CALL(*send_algorithm_,
10424 OnPacketSent(_, _, handshake_retransmission + 1, _, _));
10425 }
fayang5d011982020-05-13 14:14:38 -070010426 EXPECT_CALL(*send_algorithm_,
fayangfe963c52020-07-16 06:56:09 -070010427 OnPacketSent(_, _, handshake_retransmission, _, _));
fayang44ae4e92020-04-28 13:09:42 -070010428 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang18ff23b2020-01-28 09:19:00 -080010429 connection_.GetRetransmissionAlarm()->Fire();
fayangfe963c52020-07-16 06:56:09 -070010430 if (GetQuicReloadableFlag(quic_coalesced_packet_of_higher_space)) {
10431 // Verify 1-RTT packet gets coalesced with handshake retransmission.
10432 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
10433 } else {
10434 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
10435 }
fayang18ff23b2020-01-28 09:19:00 -080010436
10437 // Discard handshake key.
10438 connection_.OnHandshakeComplete();
10439 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
10440 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10441
10442 // Retransmit application data.
10443 clock_.AdvanceTime(retransmission_time - clock_.Now());
fayangfe963c52020-07-16 06:56:09 -070010444 QuicPacketNumber application_retransmission =
10445 GetQuicReloadableFlag(quic_default_on_pto) ? QuicPacketNumber(6)
10446 : QuicPacketNumber(9);
10447 if (GetQuicReloadableFlag(quic_coalesced_packet_of_higher_space)) {
10448 application_retransmission += 2;
10449 }
fayang5d011982020-05-13 14:14:38 -070010450 EXPECT_CALL(*send_algorithm_,
fayangfe963c52020-07-16 06:56:09 -070010451 OnPacketSent(_, _, application_retransmission, _, _));
fayang18ff23b2020-01-28 09:19:00 -080010452 connection_.GetRetransmissionAlarm()->Fire();
10453 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
10454}
10455
dschinazie7c38a52020-05-29 15:25:45 -070010456void QuicConnectionTest::TestClientRetryHandling(
10457 bool invalid_retry_tag,
10458 bool missing_original_id_in_config,
10459 bool wrong_original_id_in_config,
10460 bool missing_retry_id_in_config,
10461 bool wrong_retry_id_in_config) {
dschinazi39e5e552020-05-06 13:55:24 -070010462 if (invalid_retry_tag) {
dschinazie7c38a52020-05-29 15:25:45 -070010463 ASSERT_FALSE(missing_original_id_in_config);
10464 ASSERT_FALSE(wrong_original_id_in_config);
10465 ASSERT_FALSE(missing_retry_id_in_config);
10466 ASSERT_FALSE(wrong_retry_id_in_config);
dschinazi39e5e552020-05-06 13:55:24 -070010467 } else {
dschinazie7c38a52020-05-29 15:25:45 -070010468 ASSERT_FALSE(missing_original_id_in_config && wrong_original_id_in_config);
10469 ASSERT_FALSE(missing_retry_id_in_config && wrong_retry_id_in_config);
dschinazi39e5e552020-05-06 13:55:24 -070010470 }
dschinazi278efae2020-01-28 17:03:09 -080010471 if (!version().HasRetryIntegrityTag()) {
10472 return;
10473 }
dschinazi39e5e552020-05-06 13:55:24 -070010474
10475 // These values come from draft-ietf-quic-tls Appendix A.4.
10476 char retry_packet25[] = {
10477 0xff, 0xff, 0x00, 0x00, 0x19, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10478 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x1e, 0x5e, 0xc5, 0xb0,
10479 0x14, 0xcb, 0xb1, 0xf0, 0xfd, 0x93, 0xdf, 0x40, 0x48, 0xc4, 0x46, 0xa6};
10480 char retry_packet27[] = {
10481 0xff, 0xff, 0x00, 0x00, 0x1b, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10482 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xa5, 0x23, 0xcb, 0x5b,
10483 0xa5, 0x24, 0x69, 0x5f, 0x65, 0x69, 0xf2, 0x93, 0xa1, 0x35, 0x9d, 0x8e};
dschinazib3fed9e2020-06-11 11:59:33 -070010484 char retry_packet29[] = {
10485 0xff, 0xff, 0x00, 0x00, 0x1d, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10486 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xd1, 0x69, 0x26, 0xd8,
10487 0x1f, 0x6f, 0x9c, 0xa2, 0x95, 0x3a, 0x8a, 0xa4, 0x57, 0x5e, 0x1e, 0x49};
dschinazi39e5e552020-05-06 13:55:24 -070010488
10489 char* retry_packet;
10490 size_t retry_packet_length;
dschinazib3fed9e2020-06-11 11:59:33 -070010491 if (version() == ParsedQuicVersion::Draft29()) {
10492 retry_packet = retry_packet29;
10493 retry_packet_length = QUICHE_ARRAYSIZE(retry_packet29);
dschinazib3fed9e2020-06-11 11:59:33 -070010494 } else if (version() == ParsedQuicVersion::Draft27()) {
dschinazi39e5e552020-05-06 13:55:24 -070010495 retry_packet = retry_packet27;
10496 retry_packet_length = QUICHE_ARRAYSIZE(retry_packet27);
dschinazib3fed9e2020-06-11 11:59:33 -070010497 } else if (version() == ParsedQuicVersion::Draft25()) {
dschinazi39e5e552020-05-06 13:55:24 -070010498 retry_packet = retry_packet25;
10499 retry_packet_length = QUICHE_ARRAYSIZE(retry_packet25);
10500 } else {
dschinazi278efae2020-01-28 17:03:09 -080010501 // TODO(dschinazi) generate retry packets for all versions once we have
10502 // server-side support for generating these programmatically.
10503 return;
10504 }
10505
dschinazi278efae2020-01-28 17:03:09 -080010506 char original_connection_id_bytes[] = {0x83, 0x94, 0xc8, 0xf0,
10507 0x3e, 0x51, 0x57, 0x08};
10508 char new_connection_id_bytes[] = {0xf0, 0x67, 0xa5, 0x50,
10509 0x2a, 0x42, 0x62, 0xb5};
10510 char retry_token_bytes[] = {0x74, 0x6f, 0x6b, 0x65, 0x6e};
10511
10512 QuicConnectionId original_connection_id(
10513 original_connection_id_bytes,
10514 QUICHE_ARRAYSIZE(original_connection_id_bytes));
10515 QuicConnectionId new_connection_id(new_connection_id_bytes,
10516 QUICHE_ARRAYSIZE(new_connection_id_bytes));
10517
10518 std::string retry_token(retry_token_bytes,
10519 QUICHE_ARRAYSIZE(retry_token_bytes));
10520
dschinazi39e5e552020-05-06 13:55:24 -070010521 if (invalid_retry_tag) {
10522 // Flip the last bit of the retry packet to prevent the integrity tag
10523 // from validating correctly.
10524 retry_packet[retry_packet_length - 1] ^= 1;
dschinazi278efae2020-01-28 17:03:09 -080010525 }
10526
dschinazi39e5e552020-05-06 13:55:24 -070010527 QuicConnectionId config_original_connection_id = original_connection_id;
dschinazie7c38a52020-05-29 15:25:45 -070010528 if (wrong_original_id_in_config) {
dschinazi39e5e552020-05-06 13:55:24 -070010529 // Flip the first bit of the connection ID.
10530 ASSERT_FALSE(config_original_connection_id.IsEmpty());
10531 config_original_connection_id.mutable_data()[0] ^= 0x80;
10532 }
dschinazie7c38a52020-05-29 15:25:45 -070010533 QuicConnectionId config_retry_source_connection_id = new_connection_id;
10534 if (wrong_retry_id_in_config) {
10535 // Flip the first bit of the connection ID.
10536 ASSERT_FALSE(config_retry_source_connection_id.IsEmpty());
10537 config_retry_source_connection_id.mutable_data()[0] ^= 0x80;
10538 }
dschinazi278efae2020-01-28 17:03:09 -080010539
dschinazi39e5e552020-05-06 13:55:24 -070010540 // Make sure the connection uses the connection ID from the test vectors,
10541 QuicConnectionPeer::SetServerConnectionId(&connection_,
10542 original_connection_id);
dschinazi278efae2020-01-28 17:03:09 -080010543
dschinazi39e5e552020-05-06 13:55:24 -070010544 // Process the RETRY packet.
10545 connection_.ProcessUdpPacket(
10546 kSelfAddress, kPeerAddress,
10547 QuicReceivedPacket(retry_packet, retry_packet_length, clock_.Now()));
10548
10549 if (invalid_retry_tag) {
10550 // Make sure we refuse to process a RETRY with invalid tag.
10551 EXPECT_FALSE(connection_.GetStats().retry_packet_processed);
10552 EXPECT_EQ(connection_.connection_id(), original_connection_id);
dschinazi278efae2020-01-28 17:03:09 -080010553 EXPECT_TRUE(QuicPacketCreatorPeer::GetRetryToken(
dschinazi39e5e552020-05-06 13:55:24 -070010554 QuicConnectionPeer::GetPacketCreator(&connection_))
dschinazi278efae2020-01-28 17:03:09 -080010555 .empty());
dschinazi39e5e552020-05-06 13:55:24 -070010556 return;
dschinazi278efae2020-01-28 17:03:09 -080010557 }
dschinazi39e5e552020-05-06 13:55:24 -070010558
10559 // Make sure we correctly parsed the RETRY.
10560 EXPECT_TRUE(connection_.GetStats().retry_packet_processed);
10561 EXPECT_EQ(connection_.connection_id(), new_connection_id);
10562 EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
10563 QuicConnectionPeer::GetPacketCreator(&connection_)),
10564 retry_token);
10565 // Make sure our fake framer has the new post-retry INITIAL keys.
10566 writer_->framer()->framer()->SetInitialObfuscators(new_connection_id);
10567
10568 // Test validating the original_connection_id from the config.
10569 QuicConfig received_config;
10570 QuicConfigPeer::SetNegotiated(&received_config, true);
dschinazie7c38a52020-05-29 15:25:45 -070010571 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
10572 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
10573 &received_config, connection_.connection_id());
10574 if (!missing_retry_id_in_config) {
10575 QuicConfigPeer::SetReceivedRetrySourceConnectionId(
10576 &received_config, config_retry_source_connection_id);
10577 }
10578 }
10579 if (!missing_original_id_in_config) {
dschinazi39e5e552020-05-06 13:55:24 -070010580 QuicConfigPeer::SetReceivedOriginalConnectionId(
10581 &received_config, config_original_connection_id);
10582 }
dschinazie7c38a52020-05-29 15:25:45 -070010583
10584 if (missing_original_id_in_config || wrong_original_id_in_config ||
10585 missing_retry_id_in_config || wrong_retry_id_in_config) {
dschinazi39e5e552020-05-06 13:55:24 -070010586 EXPECT_CALL(visitor_,
10587 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10588 .Times(1);
10589 } else {
10590 EXPECT_CALL(visitor_,
10591 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10592 .Times(0);
10593 }
10594 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10595 connection_.SetFromConfig(received_config);
dschinazie7c38a52020-05-29 15:25:45 -070010596 if (missing_original_id_in_config || wrong_original_id_in_config ||
10597 missing_retry_id_in_config || wrong_retry_id_in_config) {
10598 ASSERT_FALSE(connection_.connected());
dschinazi39e5e552020-05-06 13:55:24 -070010599 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10600 } else {
10601 EXPECT_TRUE(connection_.connected());
10602 }
10603}
10604
10605TEST_P(QuicConnectionTest, ClientParsesRetry) {
10606 TestClientRetryHandling(/*invalid_retry_tag=*/false,
dschinazie7c38a52020-05-29 15:25:45 -070010607 /*missing_original_id_in_config=*/false,
10608 /*wrong_original_id_in_config=*/false,
10609 /*missing_retry_id_in_config=*/false,
10610 /*wrong_retry_id_in_config=*/false);
dschinazi39e5e552020-05-06 13:55:24 -070010611}
10612
dschinazie7c38a52020-05-29 15:25:45 -070010613TEST_P(QuicConnectionTest, ClientParsesRetryInvalidTag) {
dschinazi39e5e552020-05-06 13:55:24 -070010614 TestClientRetryHandling(/*invalid_retry_tag=*/true,
dschinazie7c38a52020-05-29 15:25:45 -070010615 /*missing_original_id_in_config=*/false,
10616 /*wrong_original_id_in_config=*/false,
10617 /*missing_retry_id_in_config=*/false,
10618 /*wrong_retry_id_in_config=*/false);
dschinazi39e5e552020-05-06 13:55:24 -070010619}
10620
dschinazie7c38a52020-05-29 15:25:45 -070010621TEST_P(QuicConnectionTest, ClientParsesRetryMissingOriginalId) {
dschinazi39e5e552020-05-06 13:55:24 -070010622 TestClientRetryHandling(/*invalid_retry_tag=*/false,
dschinazie7c38a52020-05-29 15:25:45 -070010623 /*missing_original_id_in_config=*/true,
10624 /*wrong_original_id_in_config=*/false,
10625 /*missing_retry_id_in_config=*/false,
10626 /*wrong_retry_id_in_config=*/false);
dschinazi39e5e552020-05-06 13:55:24 -070010627}
10628
dschinazie7c38a52020-05-29 15:25:45 -070010629TEST_P(QuicConnectionTest, ClientParsesRetryWrongOriginalId) {
dschinazi39e5e552020-05-06 13:55:24 -070010630 TestClientRetryHandling(/*invalid_retry_tag=*/false,
dschinazie7c38a52020-05-29 15:25:45 -070010631 /*missing_original_id_in_config=*/false,
10632 /*wrong_original_id_in_config=*/true,
10633 /*missing_retry_id_in_config=*/false,
10634 /*wrong_retry_id_in_config=*/false);
10635}
10636
10637TEST_P(QuicConnectionTest, ClientParsesRetryMissingRetryId) {
10638 if (!connection_.version().AuthenticatesHandshakeConnectionIds()) {
10639 // Versions that do not authenticate connection IDs never send the
10640 // retry_source_connection_id transport parameter.
10641 return;
10642 }
10643 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10644 /*missing_original_id_in_config=*/false,
10645 /*wrong_original_id_in_config=*/false,
10646 /*missing_retry_id_in_config=*/true,
10647 /*wrong_retry_id_in_config=*/false);
10648}
10649
10650TEST_P(QuicConnectionTest, ClientParsesRetryWrongRetryId) {
10651 if (!connection_.version().AuthenticatesHandshakeConnectionIds()) {
10652 // Versions that do not authenticate connection IDs never send the
10653 // retry_source_connection_id transport parameter.
10654 return;
10655 }
10656 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10657 /*missing_original_id_in_config=*/false,
10658 /*wrong_original_id_in_config=*/false,
10659 /*missing_retry_id_in_config=*/false,
10660 /*wrong_retry_id_in_config=*/true);
dschinazi39e5e552020-05-06 13:55:24 -070010661}
10662
10663TEST_P(QuicConnectionTest, ClientReceivesOriginalConnectionIdWithoutRetry) {
dschinazie7c38a52020-05-29 15:25:45 -070010664 if (!connection_.version().UsesTls()) {
10665 // QUIC+TLS is required to transmit connection ID transport parameters.
10666 return;
10667 }
10668 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
10669 // Versions that authenticate connection IDs always send the
10670 // original_destination_connection_id transport parameter.
10671 return;
10672 }
10673 // Make sure that receiving the original_destination_connection_id transport
10674 // parameter fails the handshake when no RETRY packet was received before it.
dschinazi39e5e552020-05-06 13:55:24 -070010675 QuicConfig received_config;
10676 QuicConfigPeer::SetNegotiated(&received_config, true);
10677 QuicConfigPeer::SetReceivedOriginalConnectionId(&received_config,
10678 TestConnectionId(0x12345));
10679 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10680 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10681 .Times(1);
10682 connection_.SetFromConfig(received_config);
10683 EXPECT_FALSE(connection_.connected());
10684 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
dschinazi278efae2020-01-28 17:03:09 -080010685}
10686
dschinazie7c38a52020-05-29 15:25:45 -070010687TEST_P(QuicConnectionTest, ClientReceivesRetrySourceConnectionIdWithoutRetry) {
10688 if (!connection_.version().AuthenticatesHandshakeConnectionIds()) {
10689 // Versions that do not authenticate connection IDs never send the
10690 // retry_source_connection_id transport parameter.
10691 return;
10692 }
10693 // Make sure that receiving the retry_source_connection_id transport parameter
10694 // fails the handshake when no RETRY packet was received before it.
10695 QuicConfig received_config;
10696 QuicConfigPeer::SetNegotiated(&received_config, true);
10697 QuicConfigPeer::SetReceivedRetrySourceConnectionId(&received_config,
10698 TestConnectionId(0x12345));
10699 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10700 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10701 .Times(1);
10702 connection_.SetFromConfig(received_config);
10703 EXPECT_FALSE(connection_.connected());
10704 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10705}
10706
fayang0e3035e2020-02-03 13:30:36 -080010707// Regression test for http://crbug/1047977
10708TEST_P(QuicConnectionTest, MaxStreamsFrameCausesConnectionClose) {
10709 if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10710 return;
10711 }
10712 // Received frame causes connection close.
10713 EXPECT_CALL(visitor_, OnMaxStreamsFrame(_))
10714 .WillOnce(InvokeWithoutArgs([this]() {
10715 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10716 connection_.CloseConnection(
10717 QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10718 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10719 return true;
10720 }));
10721 QuicFrames frames;
10722 frames.push_back(QuicFrame(QuicMaxStreamsFrame()));
10723 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10724 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10725}
10726
10727TEST_P(QuicConnectionTest, StreamsBlockedFrameCausesConnectionClose) {
10728 if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10729 return;
10730 }
10731 // Received frame causes connection close.
10732 EXPECT_CALL(visitor_, OnStreamsBlockedFrame(_))
10733 .WillOnce(InvokeWithoutArgs([this]() {
10734 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10735 connection_.CloseConnection(
10736 QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10737 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10738 return true;
10739 }));
10740 QuicFrames frames;
10741 frames.push_back(
10742 QuicFrame(QuicStreamsBlockedFrame(kInvalidControlFrameId, 10, false)));
10743 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10744 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10745}
10746
fayang79400d52020-02-13 10:13:05 -080010747TEST_P(QuicConnectionTest,
10748 BundleAckWithConnectionCloseMultiplePacketNumberSpace) {
10749 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10750 return;
10751 }
10752 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10753 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10754 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10755 // Receives packet 1000 in initial data.
10756 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10757 // Receives packet 2000 in application data.
10758 ProcessDataPacketAtLevel(2000, false, ENCRYPTION_FORWARD_SECURE);
10759 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10760 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
10761 connection_.CloseConnection(
10762 kQuicErrorCode, "Some random error message",
10763 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10764
10765 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
10766
10767 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
10768 EXPECT_EQ(1u, writer_->connection_close_frames().size());
10769 // Verify ack is bundled.
10770 EXPECT_EQ(1u, writer_->ack_frames().size());
10771
10772 if (!connection_.version().CanSendCoalescedPackets()) {
10773 // Each connection close packet should be sent in distinct UDP packets.
10774 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10775 writer_->connection_close_packets());
10776 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10777 writer_->packets_write_attempts());
10778 return;
10779 }
10780
10781 // A single UDP packet should be sent with multiple connection close packets
10782 // coalesced together.
10783 EXPECT_EQ(1u, writer_->packets_write_attempts());
10784
10785 // Only the first packet has been processed yet.
10786 EXPECT_EQ(1u, writer_->connection_close_packets());
10787
10788 // ProcessPacket resets the visitor and frees the coalesced packet.
10789 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
10790 auto packet = writer_->coalesced_packet()->Clone();
10791 writer_->framer()->ProcessPacket(*packet);
10792 EXPECT_EQ(1u, writer_->connection_close_packets());
10793 EXPECT_EQ(1u, writer_->connection_close_frames().size());
10794 // Verify ack is bundled.
10795 EXPECT_EQ(1u, writer_->ack_frames().size());
10796 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
10797}
10798
fayang61453cb2020-03-11 11:32:26 -070010799// Regression test for b/151220135.
10800TEST_P(QuicConnectionTest, SendPingWhenSkipPacketNumberForPto) {
10801 if (!VersionSupportsMessageFrames(connection_.transport_version())) {
10802 return;
10803 }
10804 QuicConfig config;
10805 QuicTagVector connection_options;
10806 connection_options.push_back(kPTOS);
10807 connection_options.push_back(k1PTO);
10808 config.SetConnectionOptionsToSend(connection_options);
dschinazied459c02020-05-07 16:12:23 -070010809 if (connection_.version().UsesTls()) {
10810 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
10811 &config, kMaxAcceptedDatagramFrameSize);
10812 }
fayang61453cb2020-03-11 11:32:26 -070010813 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10814 connection_.SetFromConfig(config);
10815 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10816
10817 EXPECT_EQ(MESSAGE_STATUS_SUCCESS, SendMessage("message"));
10818 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10819
fayang80f9cc62020-04-22 08:08:20 -070010820 // PTO fires, verify a PING packet gets sent because there is no data to
10821 // send.
10822 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
10823 EXPECT_CALL(visitor_, SendPing()).WillOnce(Invoke([this]() { SendPing(); }));
fayang61453cb2020-03-11 11:32:26 -070010824 connection_.GetRetransmissionAlarm()->Fire();
fayang80f9cc62020-04-22 08:08:20 -070010825 EXPECT_EQ(1u, connection_.GetStats().pto_count);
10826 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
10827 EXPECT_EQ(1u, writer_->ping_frames().size());
fayang61453cb2020-03-11 11:32:26 -070010828}
10829
fayangcc210e72020-05-05 14:41:34 -070010830// Regression test for b/155757133
10831TEST_P(QuicConnectionTest, DonotChangeQueuedAcks) {
10832 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10833 return;
10834 }
10835 const size_t kMinRttMs = 40;
10836 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
10837 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
10838 QuicTime::Delta::Zero(), QuicTime::Zero());
10839 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10840 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
10841 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10842
10843 ProcessPacket(2);
10844 ProcessPacket(3);
10845 ProcessPacket(4);
10846 // Process a packet containing stream frame followed by ACK of packets 1.
10847 QuicFrames frames;
10848 frames.push_back(QuicFrame(QuicStreamFrame(
10849 QuicUtils::GetFirstBidirectionalStreamId(
10850 connection_.version().transport_version, Perspective::IS_CLIENT),
10851 false, 0u, quiche::QuicheStringPiece())));
10852 QuicAckFrame ack_frame = InitAckFrame(1);
10853 frames.push_back(QuicFrame(&ack_frame));
10854 // Receiving stream frame causes something to send.
10855 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() {
10856 connection_.SendControlFrame(QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
10857 // Verify now the queued ACK contains packet number 2.
10858 EXPECT_TRUE(QuicPacketCreatorPeer::QueuedFrames(
10859 QuicConnectionPeer::GetPacketCreator(&connection_))[0]
10860 .ack_frame->packets.Contains(QuicPacketNumber(2)));
10861 }));
10862 ProcessFramesPacketAtLevel(9, frames, ENCRYPTION_FORWARD_SECURE);
fayang97da12c2020-06-29 08:22:42 -070010863 EXPECT_TRUE(writer_->ack_frames()[0].packets.Contains(QuicPacketNumber(2)));
fayangcc210e72020-05-05 14:41:34 -070010864}
10865
fayange9304002020-05-07 11:57:48 -070010866TEST_P(QuicConnectionTest, DonotExtendIdleTimeOnUndecryptablePackets) {
10867 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10868 QuicConfig config;
10869 connection_.SetFromConfig(config);
10870 // Subtract a second from the idle timeout on the client side.
10871 QuicTime initial_deadline =
10872 clock_.ApproximateNow() +
10873 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
10874 EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10875
10876 // Received an undecryptable packet.
10877 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
10878 const uint8_t tag = 0x07;
10879 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10880 std::make_unique<TaggingEncrypter>(tag));
10881 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
fayang655bb412020-06-24 10:20:47 -070010882 // Verify deadline does not get extended.
10883 EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10884 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
fayange9304002020-05-07 11:57:48 -070010885 QuicTime::Delta delay = initial_deadline - clock_.ApproximateNow();
10886 clock_.AdvanceTime(delay);
fayang655bb412020-06-24 10:20:47 -070010887 connection_.GetTimeoutAlarm()->Fire();
10888 // Verify connection gets closed.
10889 EXPECT_FALSE(connection_.connected());
fayange9304002020-05-07 11:57:48 -070010890}
10891
fayang9f430a52020-05-08 07:28:33 -070010892TEST_P(QuicConnectionTest, BundleAckWithImmediateResponse) {
10893 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10894 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10895
10896 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() {
10897 connection_.SendControlFrame(QuicFrame(new QuicWindowUpdateFrame(1, 0, 0)));
10898 }));
10899 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10900 ProcessDataPacket(1);
fayangf0fa58f2020-06-24 09:13:11 -070010901 // Verify ACK is bundled with WINDOW_UPDATE.
10902 EXPECT_FALSE(writer_->ack_frames().empty());
10903 EXPECT_FALSE(connection_.HasPendingAcks());
fayang9f430a52020-05-08 07:28:33 -070010904}
10905
fayangf44a6672020-05-27 12:51:45 -070010906TEST_P(QuicConnectionTest, AckAlarmFiresEarly) {
10907 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10908 return;
10909 }
10910 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10911 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10912 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10913 }
10914 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10915 use_tagging_decrypter();
10916 // Receives packet 1000 in initial data.
10917 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
fayang9adfb532020-06-04 06:58:45 -070010918 EXPECT_TRUE(connection_.HasPendingAcks());
fayangf44a6672020-05-27 12:51:45 -070010919
10920 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
10921 std::make_unique<TaggingEncrypter>(0x02));
10922 SetDecrypter(ENCRYPTION_ZERO_RTT,
10923 std::make_unique<StrictTaggingDecrypter>(0x02));
10924 connection_.SetEncrypter(ENCRYPTION_INITIAL,
10925 std::make_unique<TaggingEncrypter>(0x02));
10926 // Receives packet 1000 in application data.
10927 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
fayang9adfb532020-06-04 06:58:45 -070010928 EXPECT_TRUE(connection_.HasPendingAcks());
fayangf44a6672020-05-27 12:51:45 -070010929 // Verify ACK deadline does not change.
10930 EXPECT_EQ(clock_.ApproximateNow() + kAlarmGranularity,
10931 connection_.GetAckAlarm()->deadline());
10932
10933 // Ack alarm fires early.
10934 if (GetQuicReloadableFlag(quic_always_send_earliest_ack)) {
10935 // Verify the earliest ACK is flushed.
10936 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10937 } else {
10938 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10939 }
10940 connection_.GetAckAlarm()->Fire();
fayang9adfb532020-06-04 06:58:45 -070010941 EXPECT_TRUE(connection_.HasPendingAcks());
fayangf44a6672020-05-27 12:51:45 -070010942 if (GetQuicReloadableFlag(quic_always_send_earliest_ack)) {
10943 EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(),
10944 connection_.GetAckAlarm()->deadline());
10945 } else {
10946 // No forward progress has been made.
10947 EXPECT_EQ(clock_.ApproximateNow() + kAlarmGranularity,
10948 connection_.GetAckAlarm()->deadline());
10949 }
10950}
10951
fayangf78b6932020-06-08 08:36:45 -070010952TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionClient) {
fayang656cbb52020-06-09 13:29:35 -070010953 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070010954 return;
10955 }
10956 QuicConfig config;
10957 QuicTagVector connection_options;
10958 connection_options.push_back(kCBHD);
10959 config.SetConnectionOptionsToSend(connection_options);
10960 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10961 connection_.SetFromConfig(config);
10962 EXPECT_CALL(visitor_, GetHandshakeState())
10963 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10964 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10965 // Send stream data.
10966 SendStreamDataToPeer(
10967 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10968 0, FIN, nullptr);
10969 // Verify blackhole detection is in progress.
10970 EXPECT_TRUE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10971}
10972
10973TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionServer) {
fayang656cbb52020-06-09 13:29:35 -070010974 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070010975 return;
10976 }
10977 set_perspective(Perspective::IS_SERVER);
10978 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
10979 if (version().SupportsAntiAmplificationLimit()) {
10980 QuicConnectionPeer::SetAddressValidated(&connection_);
10981 }
10982 QuicConfig config;
10983 QuicTagVector connection_options;
10984 connection_options.push_back(kCBHD);
10985 config.SetInitialReceivedConnectionOptions(connection_options);
10986 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10987 connection_.SetFromConfig(config);
10988 EXPECT_CALL(visitor_, GetHandshakeState())
10989 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10990 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10991 // Send stream data.
10992 SendStreamDataToPeer(
10993 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10994 0, FIN, nullptr);
10995 // Verify blackhole detection is disabled.
10996 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10997}
10998
10999TEST_P(QuicConnectionTest, 2RtoBlackholeDetection) {
fayang656cbb52020-06-09 13:29:35 -070011000 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070011001 return;
11002 }
11003 QuicConfig config;
11004 QuicTagVector connection_options;
11005 connection_options.push_back(k2RTO);
11006 config.SetConnectionOptionsToSend(connection_options);
11007 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11008 connection_.SetFromConfig(config);
11009 const size_t kMinRttMs = 40;
11010 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11011 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11012 QuicTime::Delta::Zero(), QuicTime::Zero());
11013 EXPECT_CALL(visitor_, GetHandshakeState())
11014 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11015 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11016 // Send stream data.
11017 SendStreamDataToPeer(
11018 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11019 0, FIN, nullptr);
11020 // Verify blackhole delay is expected.
11021 EXPECT_EQ(clock_.Now() +
11022 connection_.sent_packet_manager().GetNetworkBlackholeDelay(2),
11023 QuicConnectionPeer::GetBlackholeDetectionDeadline(&connection_));
11024}
11025
11026TEST_P(QuicConnectionTest, 3RtoBlackholeDetection) {
fayang656cbb52020-06-09 13:29:35 -070011027 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070011028 return;
11029 }
11030 QuicConfig config;
11031 QuicTagVector connection_options;
11032 connection_options.push_back(k3RTO);
11033 config.SetConnectionOptionsToSend(connection_options);
11034 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11035 connection_.SetFromConfig(config);
11036 const size_t kMinRttMs = 40;
11037 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11038 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11039 QuicTime::Delta::Zero(), QuicTime::Zero());
11040 EXPECT_CALL(visitor_, GetHandshakeState())
11041 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11042 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11043 // Send stream data.
11044 SendStreamDataToPeer(
11045 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11046 0, FIN, nullptr);
11047 // Verify blackhole delay is expected.
11048 EXPECT_EQ(clock_.Now() +
11049 connection_.sent_packet_manager().GetNetworkBlackholeDelay(3),
11050 QuicConnectionPeer::GetBlackholeDetectionDeadline(&connection_));
11051}
11052
11053TEST_P(QuicConnectionTest, 4RtoBlackholeDetection) {
fayang656cbb52020-06-09 13:29:35 -070011054 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070011055 return;
11056 }
11057 QuicConfig config;
11058 QuicTagVector connection_options;
11059 connection_options.push_back(k4RTO);
11060 config.SetConnectionOptionsToSend(connection_options);
11061 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11062 connection_.SetFromConfig(config);
11063 const size_t kMinRttMs = 40;
11064 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11065 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11066 QuicTime::Delta::Zero(), QuicTime::Zero());
11067 EXPECT_CALL(visitor_, GetHandshakeState())
11068 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11069 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11070 // Send stream data.
11071 SendStreamDataToPeer(
11072 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11073 0, FIN, nullptr);
11074 // Verify blackhole delay is expected.
11075 EXPECT_EQ(clock_.Now() +
11076 connection_.sent_packet_manager().GetNetworkBlackholeDelay(4),
11077 QuicConnectionPeer::GetBlackholeDetectionDeadline(&connection_));
11078}
11079
11080TEST_P(QuicConnectionTest, 6RtoBlackholeDetection) {
fayang656cbb52020-06-09 13:29:35 -070011081 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
fayangf78b6932020-06-08 08:36:45 -070011082 return;
11083 }
11084 QuicConfig config;
11085 QuicTagVector connection_options;
11086 connection_options.push_back(k6RTO);
11087 config.SetConnectionOptionsToSend(connection_options);
11088 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11089 connection_.SetFromConfig(config);
11090 const size_t kMinRttMs = 40;
11091 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11092 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11093 QuicTime::Delta::Zero(), QuicTime::Zero());
11094 EXPECT_CALL(visitor_, GetHandshakeState())
11095 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11096 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11097 // Send stream data.
11098 SendStreamDataToPeer(
11099 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11100 0, FIN, nullptr);
11101 // Verify blackhole delay is expected.
11102 EXPECT_EQ(clock_.Now() +
11103 connection_.sent_packet_manager().GetNetworkBlackholeDelay(6),
11104 QuicConnectionPeer::GetBlackholeDetectionDeadline(&connection_));
11105}
11106
fayang656cbb52020-06-09 13:29:35 -070011107// Regresstion test for b/158491591.
11108TEST_P(QuicConnectionTest, MadeForwardProgressOnDiscardingKeys) {
11109 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11110 return;
11111 }
11112 use_tagging_decrypter();
11113 // Send handshake packet.
11114 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11115 std::make_unique<TaggingEncrypter>(0x02));
11116 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11117 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11118 QuicConfig config;
11119 QuicTagVector connection_options;
11120 connection_options.push_back(k5RTO);
11121 config.SetConnectionOptionsToSend(connection_options);
11122 QuicConfigPeer::SetNegotiated(&config, true);
11123 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
11124 EXPECT_CALL(visitor_, GetHandshakeState())
11125 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11126 }
11127 if (connection_.version().AuthenticatesHandshakeConnectionIds()) {
11128 QuicConfigPeer::SetReceivedOriginalConnectionId(
11129 &config, connection_.connection_id());
11130 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
11131 &config, connection_.connection_id());
11132 }
11133 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11134 connection_.SetFromConfig(config);
11135
11136 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
11137 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
11138 // Discard handshake keys.
11139 connection_.OnHandshakeComplete();
11140 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
11141 // Verify blackhole detection stops.
11142 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
11143 } else {
11144 // Problematic: although there is nothing in flight, blackhole detection is
11145 // still in progress.
11146 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
11147 }
11148}
11149
fayang750b54f2020-06-18 06:26:54 -070011150TEST_P(QuicConnectionTest, ProcessUndecryptablePacketsBasedOnEncryptionLevel) {
11151 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11152 return;
11153 }
11154 // SetFromConfig is always called after construction from InitializeSession.
11155 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
11156 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11157 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
11158 QuicConfig config;
11159 connection_.SetFromConfig(config);
11160 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11161 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
11162 use_tagging_decrypter();
11163
11164 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11165 std::make_unique<TaggingEncrypter>(0x01));
11166 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
11167 std::make_unique<TaggingEncrypter>(0x02));
11168
11169 for (uint64_t i = 1; i <= 3; ++i) {
11170 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
11171 }
11172 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
11173 for (uint64_t j = 5; j <= 7; ++j) {
11174 ProcessDataPacketAtLevel(j, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
11175 }
11176 EXPECT_EQ(7u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
11177 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
11178 SetDecrypter(ENCRYPTION_HANDSHAKE,
11179 std::make_unique<StrictTaggingDecrypter>(0x01));
11180 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
11181 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11182 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11183 std::make_unique<TaggingEncrypter>(0x01));
11184 if (GetQuicReloadableFlag(quic_fix_undecryptable_packets)) {
11185 // Verify all ENCRYPTION_HANDSHAKE packets get processed.
11186 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(6);
11187 } else {
11188 // Verify packets before 4 get processed.
11189 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
11190 }
11191 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
11192 EXPECT_EQ(4u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
11193
11194 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
11195 std::make_unique<StrictTaggingDecrypter>(0x02));
11196 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
11197 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11198 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
11199 std::make_unique<TaggingEncrypter>(0x02));
11200 if (GetQuicReloadableFlag(quic_fix_undecryptable_packets)) {
11201 // Verify the 1-RTT packet gets processed.
11202 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
11203 } else {
11204 // Verify all packets get processed.
11205 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(4);
11206 }
11207 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
11208 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
11209}
11210
fayanga39d0362020-06-22 08:57:35 -070011211TEST_P(QuicConnectionTest, ServerBundlesInitialDataWithInitialAck) {
fayang7d4b0172020-06-18 14:05:45 -070011212 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11213 return;
11214 }
11215 set_perspective(Perspective::IS_SERVER);
11216 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11217 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11218 }
11219 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
11220 use_tagging_decrypter();
11221 // Receives packet 1000 in initial data.
11222 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
11223 EXPECT_TRUE(connection_.HasPendingAcks());
11224
11225 connection_.SetEncrypter(ENCRYPTION_INITIAL,
11226 std::make_unique<TaggingEncrypter>(0x01));
11227 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11228 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
11229 QuicTime expected_pto_time =
11230 connection_.sent_packet_manager().GetRetransmissionTime();
11231
11232 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
11233 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11234 std::make_unique<TaggingEncrypter>(0x02));
11235 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
fayangfe963c52020-07-16 06:56:09 -070011236 if (GetQuicReloadableFlag(quic_coalesced_packet_of_higher_space)) {
11237 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(2);
11238 } else {
11239 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11240 }
fayang7d4b0172020-06-18 14:05:45 -070011241 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
11242 // Verify PTO time does not change.
11243 EXPECT_EQ(expected_pto_time,
11244 connection_.sent_packet_manager().GetRetransmissionTime());
11245
11246 // Receives packet 1001 in initial data.
11247 ProcessCryptoPacketAtLevel(1001, ENCRYPTION_INITIAL);
11248 EXPECT_TRUE(connection_.HasPendingAcks());
11249 // Receives packet 1002 in initial data.
11250 ProcessCryptoPacketAtLevel(1002, ENCRYPTION_INITIAL);
11251 EXPECT_FALSE(writer_->ack_frames().empty());
fayangc6312d42020-07-06 08:15:28 -070011252 // Verify CRYPTO frame is bundled with INITIAL ACK.
11253 EXPECT_FALSE(writer_->crypto_frames().empty());
11254 // Verify PTO time changes.
11255 EXPECT_NE(expected_pto_time,
11256 connection_.sent_packet_manager().GetRetransmissionTime());
fayang7d4b0172020-06-18 14:05:45 -070011257}
11258
fayanga39d0362020-06-22 08:57:35 -070011259TEST_P(QuicConnectionTest, ClientBundlesHandshakeDataWithHandshakeAck) {
11260 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11261 return;
11262 }
11263 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
11264 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11265 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11266 }
11267 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
11268 use_tagging_decrypter();
11269 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11270 std::make_unique<TaggingEncrypter>(0x02));
11271 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11272 SetDecrypter(ENCRYPTION_HANDSHAKE,
11273 std::make_unique<StrictTaggingDecrypter>(0x02));
11274 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11275 std::make_unique<TaggingEncrypter>(0x02));
11276 // Receives packet 1000 in handshake data.
11277 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_HANDSHAKE);
11278 EXPECT_TRUE(connection_.HasPendingAcks());
11279
11280 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(2);
11281 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
11282
11283 // Receives packet 1001 in handshake data.
11284 ProcessCryptoPacketAtLevel(1001, ENCRYPTION_HANDSHAKE);
11285 EXPECT_TRUE(connection_.HasPendingAcks());
11286 // Receives packet 1002 in handshake data.
11287 ProcessCryptoPacketAtLevel(1002, ENCRYPTION_HANDSHAKE);
11288 EXPECT_FALSE(writer_->ack_frames().empty());
fayangc6312d42020-07-06 08:15:28 -070011289 // Verify CRYPTO frame is bundled with HANDSHAKE ACK.
11290 EXPECT_FALSE(writer_->crypto_frames().empty());
fayanga39d0362020-06-22 08:57:35 -070011291}
11292
fayang04bd30d2020-06-22 15:04:57 -070011293// Regresstion test for b/156232673.
11294TEST_P(QuicConnectionTest, CoalescePacketOfLowerEncryptionLevel) {
11295 if (!connection_.version().CanSendCoalescedPackets()) {
11296 return;
11297 }
fayangf627e012020-07-13 08:10:44 -070011298 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
fayang04bd30d2020-06-22 15:04:57 -070011299 {
11300 QuicConnection::ScopedPacketFlusher flusher(&connection_);
11301 use_tagging_decrypter();
11302 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11303 std::make_unique<TaggingEncrypter>(0x01));
11304 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
11305 std::make_unique<TaggingEncrypter>(0x02));
11306 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
fayangbd7ad682020-06-23 10:49:12 -070011307 SendStreamDataToPeer(2, std::string(1286, 'a'), 0, NO_FIN, nullptr);
fayang04bd30d2020-06-22 15:04:57 -070011308 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11309 // Try to coalesce a HANDSHAKE packet after 1-RTT packet.
fayangf627e012020-07-13 08:10:44 -070011310 // Verify soft max packet length gets resumed and handshake packet gets
11311 // successfully sent.
11312 connection_.SendCryptoDataWithString("a", 0, ENCRYPTION_HANDSHAKE);
fayang04bd30d2020-06-22 15:04:57 -070011313 }
11314}
11315
fayang5c2c7b52020-07-09 13:47:16 -040011316// Regression test for b/160790422.
11317TEST_P(QuicConnectionTest, ServerRetransmitsHandshakeDataEarly) {
11318 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11319 return;
11320 }
11321 set_perspective(Perspective::IS_SERVER);
11322 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11323 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11324 }
11325 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
11326 use_tagging_decrypter();
11327 // Receives packet 1000 in initial data.
11328 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
11329 EXPECT_TRUE(connection_.HasPendingAcks());
11330
11331 connection_.SetEncrypter(ENCRYPTION_INITIAL,
11332 std::make_unique<TaggingEncrypter>(0x01));
11333 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11334 // Send INITIAL 1.
11335 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
11336 QuicTime expected_pto_time =
11337 connection_.sent_packet_manager().GetRetransmissionTime();
11338
11339 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
11340 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11341 std::make_unique<TaggingEncrypter>(0x02));
11342 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11343 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(3);
11344 // Send HANDSHAKE 2 and 3.
11345 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
11346 connection_.SendCryptoDataWithString("bar", 3, ENCRYPTION_HANDSHAKE);
11347 // Verify PTO time does not change.
11348 EXPECT_EQ(expected_pto_time,
11349 connection_.sent_packet_manager().GetRetransmissionTime());
11350
11351 // Receives ACK for HANDSHAKE 2.
11352 QuicFrames frames;
11353 auto ack_frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
11354 frames.push_back(QuicFrame(&ack_frame));
11355 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
11356 ProcessFramesPacketAtLevel(30, frames, ENCRYPTION_HANDSHAKE);
11357 // Discard INITIAL key.
11358 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
11359 connection_.NeuterUnencryptedPackets();
11360 // Receives PING from peer.
11361 frames.clear();
11362 frames.push_back(QuicFrame(QuicPingFrame()));
11363 frames.push_back(QuicFrame(QuicPaddingFrame(3)));
11364 ProcessFramesPacketAtLevel(31, frames, ENCRYPTION_HANDSHAKE);
11365 EXPECT_EQ(clock_.Now() + kAlarmGranularity,
11366 connection_.GetAckAlarm()->deadline());
11367 // Fire ACK alarm.
11368 clock_.AdvanceTime(kAlarmGranularity);
11369 connection_.GetAckAlarm()->Fire();
11370 EXPECT_FALSE(writer_->ack_frames().empty());
11371 if (GetQuicReloadableFlag(quic_retransmit_handshake_data_early)) {
11372 // Verify handshake data gets retransmitted early.
11373 EXPECT_FALSE(writer_->crypto_frames().empty());
11374 } else {
11375 EXPECT_TRUE(writer_->crypto_frames().empty());
11376 }
11377}
11378
fayangfe963c52020-07-16 06:56:09 -070011379// Regression test for b/161228202
11380TEST_P(QuicConnectionTest, InflatedRttSample) {
11381 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11382 return;
11383 }
11384 // 30ms RTT.
11385 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
11386 set_perspective(Perspective::IS_SERVER);
11387 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11388 use_tagging_decrypter();
11389 // Receives packet 1000 in initial data.
11390 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11391 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11392 }
11393 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
11394 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
11395 EXPECT_TRUE(connection_.HasPendingAcks());
11396
11397 connection_.SetEncrypter(ENCRYPTION_INITIAL,
11398 std::make_unique<TaggingEncrypter>(0x01));
11399 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11400 // Send INITIAL 1.
11401 connection_.SendCryptoDataWithString(std::string(512, 'a'), 0,
11402 ENCRYPTION_INITIAL);
11403 ASSERT_TRUE(connection_.sent_packet_manager()
11404 .GetRetransmissionTime()
11405 .IsInitialized());
11406 QuicTime::Delta pto_timeout =
11407 connection_.sent_packet_manager().GetRetransmissionTime() - clock_.Now();
11408 // Send Handshake 2.
11409 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11410 std::make_unique<TaggingEncrypter>(0x02));
11411 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11412 if (GetQuicReloadableFlag(quic_coalesced_packet_of_higher_space)) {
11413 // Verify HANDSHAKE packet is coalesced with INITIAL retransmission.
11414 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(2);
11415 } else {
11416 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11417 }
11418 connection_.SendCryptoDataWithString(std::string(1024, 'a'), 0,
11419 ENCRYPTION_HANDSHAKE);
11420
11421 // INITIAL 1 gets lost and PTO fires.
11422 clock_.AdvanceTime(pto_timeout);
11423 connection_.GetRetransmissionAlarm()->Fire();
11424
11425 clock_.AdvanceTime(kTestRTT);
11426 // Assume retransmitted INITIAL gets received.
11427 QuicFrames frames;
11428 QuicPacketNumber initial_retransmission =
11429 GetQuicReloadableFlag(quic_default_on_pto) ? QuicPacketNumber(3)
11430 : QuicPacketNumber(4);
11431 auto ack_frame =
11432 InitAckFrame({{initial_retransmission, initial_retransmission + 1}});
11433 frames.push_back(QuicFrame(&ack_frame));
11434 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _))
11435 .Times(AnyNumber());
11436 ProcessFramesPacketAtLevel(1001, frames, ENCRYPTION_INITIAL);
11437 EXPECT_EQ(kTestRTT, rtt_stats->latest_rtt());
11438 // Because retransmitted INITIAL gets received so HANDSHAKE 2 gets processed.
11439 frames.clear();
11440 QuicAckFrame ack_frame2;
11441 if (GetQuicReloadableFlag(quic_coalesced_packet_of_higher_space)) {
11442 // HANDSHAKE 5 is also processed.
11443 ack_frame2 = InitAckFrame(
11444 {{QuicPacketNumber(2), QuicPacketNumber(3)},
11445 {initial_retransmission + 1, initial_retransmission + 2}});
11446 } else {
11447 ack_frame2 = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
11448 }
11449 ack_frame2.ack_delay_time = QuicTime::Delta::Zero();
11450 frames.push_back(QuicFrame(&ack_frame2));
11451 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_HANDSHAKE);
11452 if (GetQuicReloadableFlag(quic_coalesced_packet_of_higher_space)) {
11453 // Verify RTT inflation gets mitigated.
11454 EXPECT_EQ(rtt_stats->latest_rtt(), kTestRTT);
11455 } else {
11456 // Verify this RTT sample gets inflated as it includes the PTO timeout and
11457 // the actual RTT.
11458 EXPECT_GE(rtt_stats->latest_rtt(), pto_timeout + kTestRTT);
11459 }
11460}
11461
QUICHE teama6ef0a62019-03-07 20:34:33 -050011462} // namespace
11463} // namespace test
11464} // namespace quic